JAL-2754 Sequence.findFeatures(fromCol, toCol)
[jalview.git] / src / jalview / datamodel / Sequence.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.datamodel;
22
23 import jalview.analysis.AlignSeq;
24 import jalview.api.DBRefEntryI;
25 import jalview.datamodel.features.SequenceFeatures;
26 import jalview.datamodel.features.SequenceFeaturesI;
27 import jalview.util.Comparison;
28 import jalview.util.DBRefUtils;
29 import jalview.util.MapList;
30 import jalview.util.StringUtils;
31
32 import java.util.ArrayList;
33 import java.util.Arrays;
34 import java.util.Collections;
35 import java.util.Enumeration;
36 import java.util.List;
37 import java.util.ListIterator;
38 import java.util.Vector;
39
40 import com.stevesoft.pat.Regex;
41
42 import fr.orsay.lri.varna.models.rna.RNA;
43
44 /**
45  * 
46  * Implements the SequenceI interface for a char[] based sequence object.
47  * 
48  * @author $author$
49  * @version $Revision$
50  */
51 public class Sequence extends ASequence implements SequenceI
52 {
53   private static final Regex limitrx = new Regex(
54           "[/][0-9]{1,}[-][0-9]{1,}$");
55
56   private static final Regex endrx = new Regex("[0-9]{1,}$");
57
58   SequenceI datasetSequence;
59
60   String name;
61
62   private char[] sequence;
63
64   String description;
65
66   int start;
67
68   int end;
69
70   Vector<PDBEntry> pdbIds;
71
72   String vamsasId;
73
74   DBRefEntry[] dbrefs;
75
76   RNA rna;
77
78   /**
79    * This annotation is displayed below the alignment but the positions are tied
80    * to the residues of this sequence
81    *
82    * TODO: change to List<>
83    */
84   Vector<AlignmentAnnotation> annotation;
85
86   /**
87    * The index of the sequence in a MSA
88    */
89   int index = -1;
90
91   private SequenceFeatures sequenceFeatureStore;
92
93   /**
94    * Creates a new Sequence object.
95    * 
96    * @param name
97    *          display name string
98    * @param sequence
99    *          string to form a possibly gapped sequence out of
100    * @param start
101    *          first position of non-gap residue in the sequence
102    * @param end
103    *          last position of ungapped residues (nearly always only used for
104    *          display purposes)
105    */
106   public Sequence(String name, String sequence, int start, int end)
107   {
108     this();
109     initSeqAndName(name, sequence.toCharArray(), start, end);
110   }
111
112   public Sequence(String name, char[] sequence, int start, int end)
113   {
114     this();
115     initSeqAndName(name, sequence, start, end);
116   }
117
118   /**
119    * Stage 1 constructor - assign name, sequence, and set start and end fields.
120    * start and end are updated values from name2 if it ends with /start-end
121    * 
122    * @param name2
123    * @param sequence2
124    * @param start2
125    * @param end2
126    */
127   protected void initSeqAndName(String name2, char[] sequence2, int start2,
128           int end2)
129   {
130     this.name = name2;
131     this.sequence = sequence2;
132     this.start = start2;
133     this.end = end2;
134     parseId();
135     checkValidRange();
136   }
137
138   void parseId()
139   {
140     if (name == null)
141     {
142       System.err
143               .println("POSSIBLE IMPLEMENTATION ERROR: null sequence name passed to constructor.");
144       name = "";
145     }
146     // Does sequence have the /start-end signature?
147     if (limitrx.search(name))
148     {
149       name = limitrx.left();
150       endrx.search(limitrx.stringMatched());
151       setStart(Integer.parseInt(limitrx.stringMatched().substring(1,
152               endrx.matchedFrom() - 1)));
153       setEnd(Integer.parseInt(endrx.stringMatched()));
154     }
155   }
156
157   void checkValidRange()
158   {
159     // Note: JAL-774 :
160     // http://issues.jalview.org/browse/JAL-774?focusedCommentId=11239&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-11239
161     {
162       int endRes = 0;
163       for (int j = 0; j < sequence.length; j++)
164       {
165         if (!jalview.util.Comparison.isGap(sequence[j]))
166         {
167           endRes++;
168         }
169       }
170       if (endRes > 0)
171       {
172         endRes += start - 1;
173       }
174
175       if (end < endRes)
176       {
177         end = endRes;
178       }
179     }
180
181   }
182
183   /**
184    * default constructor
185    */
186   private Sequence()
187   {
188     sequenceFeatureStore = new SequenceFeatures();
189   }
190
191   /**
192    * Creates a new Sequence object.
193    * 
194    * @param name
195    *          DOCUMENT ME!
196    * @param sequence
197    *          DOCUMENT ME!
198    */
199   public Sequence(String name, String sequence)
200   {
201     this(name, sequence, 1, -1);
202   }
203
204   /**
205    * Creates a new Sequence object with new AlignmentAnnotations but inherits
206    * any existing dataset sequence reference. If non exists, everything is
207    * copied.
208    * 
209    * @param seq
210    *          if seq is a dataset sequence, behaves like a plain old copy
211    *          constructor
212    */
213   public Sequence(SequenceI seq)
214   {
215     this(seq, seq.getAnnotation());
216   }
217
218   /**
219    * Create a new sequence object with new features, DBRefEntries, and PDBIds
220    * but inherits any existing dataset sequence reference, and duplicate of any
221    * annotation that is present in the given annotation array.
222    * 
223    * @param seq
224    *          the sequence to be copied
225    * @param alAnnotation
226    *          an array of annotation including some associated with seq
227    */
228   public Sequence(SequenceI seq, AlignmentAnnotation[] alAnnotation)
229   {
230     this();
231     initSeqFrom(seq, alAnnotation);
232   }
233
234   /**
235    * does the heavy lifting when cloning a dataset sequence, or coping data from
236    * dataset to a new derived sequence.
237    * 
238    * @param seq
239    *          - source of attributes.
240    * @param alAnnotation
241    *          - alignment annotation present on seq that should be copied onto
242    *          this sequence
243    */
244   protected void initSeqFrom(SequenceI seq,
245           AlignmentAnnotation[] alAnnotation)
246   {
247     char[] oseq = seq.getSequence();
248     initSeqAndName(seq.getName(), Arrays.copyOf(oseq, oseq.length),
249             seq.getStart(), seq.getEnd());
250
251     description = seq.getDescription();
252     if (seq != datasetSequence)
253     {
254       setDatasetSequence(seq.getDatasetSequence());
255     }
256     
257     /*
258      * only copy DBRefs and seqfeatures if we really are a dataset sequence
259      */
260     if (datasetSequence == null)
261     {
262       if (seq.getDBRefs() != null)
263       {
264         DBRefEntry[] dbr = seq.getDBRefs();
265         for (int i = 0; i < dbr.length; i++)
266         {
267           addDBRef(new DBRefEntry(dbr[i]));
268         }
269       }
270
271       /*
272        * make copies of any sequence features
273        */
274       for (SequenceFeature sf : seq.getSequenceFeatures())
275       {
276         addSequenceFeature(new SequenceFeature(sf));
277       }
278     }
279
280     if (seq.getAnnotation() != null)
281     {
282       AlignmentAnnotation[] sqann = seq.getAnnotation();
283       for (int i = 0; i < sqann.length; i++)
284       {
285         if (sqann[i] == null)
286         {
287           continue;
288         }
289         boolean found = (alAnnotation == null);
290         if (!found)
291         {
292           for (int apos = 0; !found && apos < alAnnotation.length; apos++)
293           {
294             found = (alAnnotation[apos] == sqann[i]);
295           }
296         }
297         if (found)
298         {
299           // only copy the given annotation
300           AlignmentAnnotation newann = new AlignmentAnnotation(sqann[i]);
301           addAlignmentAnnotation(newann);
302         }
303       }
304     }
305     if (seq.getAllPDBEntries() != null)
306     {
307       Vector<PDBEntry> ids = seq.getAllPDBEntries();
308       for (PDBEntry pdb : ids)
309       {
310         this.addPDBId(new PDBEntry(pdb));
311       }
312     }
313   }
314
315   @Override
316   public void setSequenceFeatures(List<SequenceFeature> features)
317   {
318     if (datasetSequence != null)
319     {
320       datasetSequence.setSequenceFeatures(features);
321       return;
322     }
323     sequenceFeatureStore = new SequenceFeatures(features);
324   }
325
326   @Override
327   public synchronized boolean addSequenceFeature(SequenceFeature sf)
328   {
329     if (sf.getType() == null)
330     {
331       System.err.println("SequenceFeature type may not be null: "
332               + sf.toString());
333       return false;
334     }
335
336     if (datasetSequence != null)
337     {
338       return datasetSequence.addSequenceFeature(sf);
339     }
340
341     return sequenceFeatureStore.add(sf);
342   }
343
344   @Override
345   public void deleteFeature(SequenceFeature sf)
346   {
347     if (datasetSequence != null)
348     {
349       datasetSequence.deleteFeature(sf);
350     }
351     else
352     {
353       sequenceFeatureStore.delete(sf);
354     }
355   }
356
357   /**
358    * {@inheritDoc}
359    * 
360    * @return
361    */
362   @Override
363   public List<SequenceFeature> getSequenceFeatures()
364   {
365     if (datasetSequence != null)
366     {
367       return datasetSequence.getSequenceFeatures();
368     }
369     return sequenceFeatureStore.getAllFeatures();
370   }
371
372   @Override
373   public SequenceFeaturesI getFeatures()
374   {
375     return datasetSequence != null ? datasetSequence.getFeatures()
376             : sequenceFeatureStore;
377   }
378
379   @Override
380   public boolean addPDBId(PDBEntry entry)
381   {
382     if (pdbIds == null)
383     {
384       pdbIds = new Vector<PDBEntry>();
385       pdbIds.add(entry);
386       return true;
387     }
388
389     for (PDBEntry pdbe : pdbIds)
390     {
391       if (pdbe.updateFrom(entry))
392       {
393         return false;
394       }
395     }
396     pdbIds.addElement(entry);
397     return true;
398   }
399
400   /**
401    * DOCUMENT ME!
402    * 
403    * @param id
404    *          DOCUMENT ME!
405    */
406   @Override
407   public void setPDBId(Vector<PDBEntry> id)
408   {
409     pdbIds = id;
410   }
411
412   /**
413    * DOCUMENT ME!
414    * 
415    * @return DOCUMENT ME!
416    */
417   @Override
418   public Vector<PDBEntry> getAllPDBEntries()
419   {
420     return pdbIds == null ? new Vector<PDBEntry>() : pdbIds;
421   }
422
423   /**
424    * DOCUMENT ME!
425    * 
426    * @return DOCUMENT ME!
427    */
428   @Override
429   public String getDisplayId(boolean jvsuffix)
430   {
431     StringBuffer result = new StringBuffer(name);
432     if (jvsuffix)
433     {
434       result.append("/" + start + "-" + end);
435     }
436
437     return result.toString();
438   }
439
440   /**
441    * DOCUMENT ME!
442    * 
443    * @param name
444    *          DOCUMENT ME!
445    */
446   @Override
447   public void setName(String name)
448   {
449     this.name = name;
450     this.parseId();
451   }
452
453   /**
454    * DOCUMENT ME!
455    * 
456    * @return DOCUMENT ME!
457    */
458   @Override
459   public String getName()
460   {
461     return this.name;
462   }
463
464   /**
465    * DOCUMENT ME!
466    * 
467    * @param start
468    *          DOCUMENT ME!
469    */
470   @Override
471   public void setStart(int start)
472   {
473     this.start = start;
474   }
475
476   /**
477    * DOCUMENT ME!
478    * 
479    * @return DOCUMENT ME!
480    */
481   @Override
482   public int getStart()
483   {
484     return this.start;
485   }
486
487   /**
488    * DOCUMENT ME!
489    * 
490    * @param end
491    *          DOCUMENT ME!
492    */
493   @Override
494   public void setEnd(int end)
495   {
496     this.end = end;
497   }
498
499   /**
500    * DOCUMENT ME!
501    * 
502    * @return DOCUMENT ME!
503    */
504   @Override
505   public int getEnd()
506   {
507     return this.end;
508   }
509
510   /**
511    * DOCUMENT ME!
512    * 
513    * @return DOCUMENT ME!
514    */
515   @Override
516   public int getLength()
517   {
518     return this.sequence.length;
519   }
520
521   /**
522    * DOCUMENT ME!
523    * 
524    * @param seq
525    *          DOCUMENT ME!
526    */
527   @Override
528   public void setSequence(String seq)
529   {
530     this.sequence = seq.toCharArray();
531     checkValidRange();
532   }
533
534   @Override
535   public String getSequenceAsString()
536   {
537     return new String(sequence);
538   }
539
540   @Override
541   public String getSequenceAsString(int start, int end)
542   {
543     return new String(getSequence(start, end));
544   }
545
546   @Override
547   public char[] getSequence()
548   {
549     return sequence;
550   }
551
552   /*
553    * (non-Javadoc)
554    * 
555    * @see jalview.datamodel.SequenceI#getSequence(int, int)
556    */
557   @Override
558   public char[] getSequence(int start, int end)
559   {
560     if (start < 0)
561     {
562       start = 0;
563     }
564     // JBPNote - left to user to pad the result here (TODO:Decide on this
565     // policy)
566     if (start >= sequence.length)
567     {
568       return new char[0];
569     }
570
571     if (end >= sequence.length)
572     {
573       end = sequence.length;
574     }
575
576     char[] reply = new char[end - start];
577     System.arraycopy(sequence, start, reply, 0, end - start);
578
579     return reply;
580   }
581
582   @Override
583   public SequenceI getSubSequence(int start, int end)
584   {
585     if (start < 0)
586     {
587       start = 0;
588     }
589     char[] seq = getSequence(start, end);
590     if (seq.length == 0)
591     {
592       return null;
593     }
594     int nstart = findPosition(start);
595     int nend = findPosition(end) - 1;
596     // JBPNote - this is an incomplete copy.
597     SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
598     nseq.setDescription(description);
599     if (datasetSequence != null)
600     {
601       nseq.setDatasetSequence(datasetSequence);
602     }
603     else
604     {
605       nseq.setDatasetSequence(this);
606     }
607     return nseq;
608   }
609
610   /**
611    * Returns the character of the aligned sequence at the given position (base
612    * zero), or space if the position is not within the sequence's bounds
613    * 
614    * @return
615    */
616   @Override
617   public char getCharAt(int i)
618   {
619     if (i >= 0 && i < sequence.length)
620     {
621       return sequence[i];
622     }
623     else
624     {
625       return ' ';
626     }
627   }
628
629   /**
630    * DOCUMENT ME!
631    * 
632    * @param desc
633    *          DOCUMENT ME!
634    */
635   @Override
636   public void setDescription(String desc)
637   {
638     this.description = desc;
639   }
640
641   /**
642    * DOCUMENT ME!
643    * 
644    * @return DOCUMENT ME!
645    */
646   @Override
647   public String getDescription()
648   {
649     return this.description;
650   }
651
652   /*
653    * (non-Javadoc)
654    * 
655    * @see jalview.datamodel.SequenceI#findIndex(int)
656    */
657   @Override
658   public int findIndex(int pos)
659   {
660     // returns the alignment position for a residue
661     int j = start;
662     int i = 0;
663     // Rely on end being at least as long as the length of the sequence.
664     while ((i < sequence.length) && (j <= end) && (j <= pos))
665     {
666       if (!Comparison.isGap(sequence[i]))
667       {
668         j++;
669       }
670
671       i++;
672     }
673
674     if ((j == end) && (j < pos))
675     {
676       return end + 1;
677     }
678     else
679     {
680       return i;
681     }
682   }
683
684   @Override
685   public int findPosition(int i)
686   {
687     int j = 0;
688     int pos = start;
689     int seqlen = sequence.length;
690     while ((j < i) && (j < seqlen))
691     {
692       if (!Comparison.isGap(sequence[j]))
693       {
694         pos++;
695       }
696
697       j++;
698     }
699
700     return pos;
701   }
702
703   /**
704    * Returns an int array where indices correspond to each residue in the
705    * sequence and the element value gives its position in the alignment
706    * 
707    * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
708    *         residues in SequenceI object
709    */
710   @Override
711   public int[] gapMap()
712   {
713     String seq = jalview.analysis.AlignSeq.extractGaps(
714             jalview.util.Comparison.GapChars, new String(sequence));
715     int[] map = new int[seq.length()];
716     int j = 0;
717     int p = 0;
718
719     while (j < sequence.length)
720     {
721       if (!jalview.util.Comparison.isGap(sequence[j]))
722       {
723         map[p++] = j;
724       }
725
726       j++;
727     }
728
729     return map;
730   }
731
732   @Override
733   public int[] findPositionMap()
734   {
735     int map[] = new int[sequence.length];
736     int j = 0;
737     int pos = start;
738     int seqlen = sequence.length;
739     while ((j < seqlen))
740     {
741       map[j] = pos;
742       if (!jalview.util.Comparison.isGap(sequence[j]))
743       {
744         pos++;
745       }
746
747       j++;
748     }
749     return map;
750   }
751
752   @Override
753   public List<int[]> getInsertions()
754   {
755     ArrayList<int[]> map = new ArrayList<int[]>();
756     int lastj = -1, j = 0;
757     int pos = start;
758     int seqlen = sequence.length;
759     while ((j < seqlen))
760     {
761       if (jalview.util.Comparison.isGap(sequence[j]))
762       {
763         if (lastj == -1)
764         {
765           lastj = j;
766         }
767       }
768       else
769       {
770         if (lastj != -1)
771         {
772           map.add(new int[] { lastj, j - 1 });
773           lastj = -1;
774         }
775       }
776       j++;
777     }
778     if (lastj != -1)
779     {
780       map.add(new int[] { lastj, j - 1 });
781       lastj = -1;
782     }
783     return map;
784   }
785
786   @Override
787   public void deleteChars(int i, int j)
788   {
789     int newstart = start, newend = end;
790     if (i >= sequence.length || i < 0)
791     {
792       return;
793     }
794
795     char[] tmp = StringUtils.deleteChars(sequence, i, j);
796     boolean createNewDs = false;
797     // TODO: take a (second look) at the dataset creation validation method for
798     // the very large sequence case
799     int eindex = -1, sindex = -1;
800     boolean ecalc = false, scalc = false;
801     for (int s = i; s < j; s++)
802     {
803       if (jalview.schemes.ResidueProperties.aaIndex[sequence[s]] != 23)
804       {
805         if (createNewDs)
806         {
807           newend--;
808         }
809         else
810         {
811           if (!scalc)
812           {
813             sindex = findIndex(start) - 1;
814             scalc = true;
815           }
816           if (sindex == s)
817           {
818             // delete characters including start of sequence
819             newstart = findPosition(j);
820             break; // don't need to search for any more residue characters.
821           }
822           else
823           {
824             // delete characters after start.
825             if (!ecalc)
826             {
827               eindex = findIndex(end) - 1;
828               ecalc = true;
829             }
830             if (eindex < j)
831             {
832               // delete characters at end of sequence
833               newend = findPosition(i - 1);
834               break; // don't need to search for any more residue characters.
835             }
836             else
837             {
838               createNewDs = true;
839               newend--; // decrease end position by one for the deleted residue
840               // and search further
841             }
842           }
843         }
844       }
845     }
846     // deletion occured in the middle of the sequence
847     if (createNewDs && this.datasetSequence != null)
848     {
849       // construct a new sequence
850       Sequence ds = new Sequence(datasetSequence);
851       // TODO: remove any non-inheritable properties ?
852       // TODO: create a sequence mapping (since there is a relation here ?)
853       ds.deleteChars(i, j);
854       datasetSequence = ds;
855     }
856     start = newstart;
857     end = newend;
858     sequence = tmp;
859   }
860
861   @Override
862   public void insertCharAt(int i, int length, char c)
863   {
864     char[] tmp = new char[sequence.length + length];
865
866     if (i >= sequence.length)
867     {
868       System.arraycopy(sequence, 0, tmp, 0, sequence.length);
869       i = sequence.length;
870     }
871     else
872     {
873       System.arraycopy(sequence, 0, tmp, 0, i);
874     }
875
876     int index = i;
877     while (length > 0)
878     {
879       tmp[index++] = c;
880       length--;
881     }
882
883     if (i < sequence.length)
884     {
885       System.arraycopy(sequence, i, tmp, index, sequence.length - i);
886     }
887
888     sequence = tmp;
889   }
890
891   @Override
892   public void insertCharAt(int i, char c)
893   {
894     insertCharAt(i, 1, c);
895   }
896
897   @Override
898   public String getVamsasId()
899   {
900     return vamsasId;
901   }
902
903   @Override
904   public void setVamsasId(String id)
905   {
906     vamsasId = id;
907   }
908
909   @Override
910   public void setDBRefs(DBRefEntry[] dbref)
911   {
912     if (dbrefs == null && datasetSequence != null
913             && this != datasetSequence)
914     {
915       datasetSequence.setDBRefs(dbref);
916       return;
917     }
918     dbrefs = dbref;
919     if (dbrefs != null)
920     {
921       DBRefUtils.ensurePrimaries(this);
922     }
923   }
924
925   @Override
926   public DBRefEntry[] getDBRefs()
927   {
928     if (dbrefs == null && datasetSequence != null
929             && this != datasetSequence)
930     {
931       return datasetSequence.getDBRefs();
932     }
933     return dbrefs;
934   }
935
936   @Override
937   public void addDBRef(DBRefEntry entry)
938   {
939     if (datasetSequence != null)
940     {
941       datasetSequence.addDBRef(entry);
942       return;
943     }
944
945     if (dbrefs == null)
946     {
947       dbrefs = new DBRefEntry[0];
948     }
949
950     for (DBRefEntryI dbr : dbrefs)
951     {
952       if (dbr.updateFrom(entry))
953       {
954         /*
955          * found a dbref that either matched, or could be
956          * updated from, the new entry - no need to add it
957          */
958         return;
959       }
960     }
961
962     /*
963      * extend the array to make room for one more
964      */
965     // TODO use an ArrayList instead
966     int j = dbrefs.length;
967     DBRefEntry[] temp = new DBRefEntry[j + 1];
968     System.arraycopy(dbrefs, 0, temp, 0, j);
969     temp[temp.length - 1] = entry;
970
971     dbrefs = temp;
972
973     DBRefUtils.ensurePrimaries(this);
974   }
975
976   @Override
977   public void setDatasetSequence(SequenceI seq)
978   {
979     if (seq == this)
980     {
981       throw new IllegalArgumentException(
982               "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
983     }
984     if (seq != null && seq.getDatasetSequence() != null)
985     {
986       throw new IllegalArgumentException(
987               "Implementation error: cascading dataset sequences are not allowed.");
988     }
989     datasetSequence = seq;
990   }
991
992   @Override
993   public SequenceI getDatasetSequence()
994   {
995     return datasetSequence;
996   }
997
998   @Override
999   public AlignmentAnnotation[] getAnnotation()
1000   {
1001     return annotation == null ? null : annotation
1002             .toArray(new AlignmentAnnotation[annotation.size()]);
1003   }
1004
1005   @Override
1006   public boolean hasAnnotation(AlignmentAnnotation ann)
1007   {
1008     return annotation == null ? false : annotation.contains(ann);
1009   }
1010
1011   @Override
1012   public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1013   {
1014     if (this.annotation == null)
1015     {
1016       this.annotation = new Vector<AlignmentAnnotation>();
1017     }
1018     if (!this.annotation.contains(annotation))
1019     {
1020       this.annotation.addElement(annotation);
1021     }
1022     annotation.setSequenceRef(this);
1023   }
1024
1025   @Override
1026   public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1027   {
1028     if (this.annotation != null)
1029     {
1030       this.annotation.removeElement(annotation);
1031       if (this.annotation.size() == 0)
1032       {
1033         this.annotation = null;
1034       }
1035     }
1036   }
1037
1038   /**
1039    * test if this is a valid candidate for another sequence's dataset sequence.
1040    * 
1041    */
1042   private boolean isValidDatasetSequence()
1043   {
1044     if (datasetSequence != null)
1045     {
1046       return false;
1047     }
1048     for (int i = 0; i < sequence.length; i++)
1049     {
1050       if (jalview.util.Comparison.isGap(sequence[i]))
1051       {
1052         return false;
1053       }
1054     }
1055     return true;
1056   }
1057
1058   @Override
1059   public SequenceI deriveSequence()
1060   {
1061     Sequence seq = null;
1062     if (datasetSequence == null)
1063     {
1064       if (isValidDatasetSequence())
1065       {
1066         // Use this as dataset sequence
1067         seq = new Sequence(getName(), "", 1, -1);
1068         seq.setDatasetSequence(this);
1069         seq.initSeqFrom(this, getAnnotation());
1070         return seq;
1071       }
1072       else
1073       {
1074         // Create a new, valid dataset sequence
1075         createDatasetSequence();
1076       }
1077     }
1078     return new Sequence(this);
1079   }
1080
1081   private boolean _isNa;
1082
1083   private long _seqhash = 0;
1084
1085   /**
1086    * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1087    * true
1088    */
1089   @Override
1090   public boolean isProtein()
1091   {
1092     if (datasetSequence != null)
1093     {
1094       return datasetSequence.isProtein();
1095     }
1096     if (_seqhash != sequence.hashCode())
1097     {
1098       _seqhash = sequence.hashCode();
1099       _isNa = Comparison.isNucleotide(this);
1100     }
1101     return !_isNa;
1102   };
1103
1104   /*
1105    * (non-Javadoc)
1106    * 
1107    * @see jalview.datamodel.SequenceI#createDatasetSequence()
1108    */
1109   @Override
1110   public SequenceI createDatasetSequence()
1111   {
1112     if (datasetSequence == null)
1113     {
1114       Sequence dsseq = new Sequence(getName(), AlignSeq.extractGaps(
1115               jalview.util.Comparison.GapChars, getSequenceAsString()),
1116               getStart(), getEnd());
1117
1118       datasetSequence = dsseq;
1119
1120       dsseq.setDescription(description);
1121       // move features and database references onto dataset sequence
1122       dsseq.sequenceFeatureStore = sequenceFeatureStore;
1123       sequenceFeatureStore = null;
1124       dsseq.dbrefs = dbrefs;
1125       dbrefs = null;
1126       // TODO: search and replace any references to this sequence with
1127       // references to the dataset sequence in Mappings on dbref
1128       dsseq.pdbIds = pdbIds;
1129       pdbIds = null;
1130       datasetSequence.updatePDBIds();
1131       if (annotation != null)
1132       {
1133         // annotation is cloned rather than moved, to preserve what's currently
1134         // on the alignment
1135         for (AlignmentAnnotation aa : annotation)
1136         {
1137           AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1138           _aa.sequenceRef = datasetSequence;
1139           _aa.adjustForAlignment(); // uses annotation's own record of
1140                                     // sequence-column mapping
1141           datasetSequence.addAlignmentAnnotation(_aa);
1142         }
1143       }
1144     }
1145     return datasetSequence;
1146   }
1147
1148   /*
1149    * (non-Javadoc)
1150    * 
1151    * @see
1152    * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1153    * annotations)
1154    */
1155   @Override
1156   public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1157   {
1158     if (annotation != null)
1159     {
1160       annotation.removeAllElements();
1161     }
1162     if (annotations != null)
1163     {
1164       for (int i = 0; i < annotations.length; i++)
1165       {
1166         if (annotations[i] != null)
1167         {
1168           addAlignmentAnnotation(annotations[i]);
1169         }
1170       }
1171     }
1172   }
1173
1174   @Override
1175   public AlignmentAnnotation[] getAnnotation(String label)
1176   {
1177     if (annotation == null || annotation.size() == 0)
1178     {
1179       return null;
1180     }
1181
1182     Vector<AlignmentAnnotation> subset = new Vector<AlignmentAnnotation>();
1183     Enumeration<AlignmentAnnotation> e = annotation.elements();
1184     while (e.hasMoreElements())
1185     {
1186       AlignmentAnnotation ann = e.nextElement();
1187       if (ann.label != null && ann.label.equals(label))
1188       {
1189         subset.addElement(ann);
1190       }
1191     }
1192     if (subset.size() == 0)
1193     {
1194       return null;
1195     }
1196     AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1197     int i = 0;
1198     e = subset.elements();
1199     while (e.hasMoreElements())
1200     {
1201       anns[i++] = e.nextElement();
1202     }
1203     subset.removeAllElements();
1204     return anns;
1205   }
1206
1207   @Override
1208   public boolean updatePDBIds()
1209   {
1210     if (datasetSequence != null)
1211     {
1212       // TODO: could merge DBRefs
1213       return datasetSequence.updatePDBIds();
1214     }
1215     if (dbrefs == null || dbrefs.length == 0)
1216     {
1217       return false;
1218     }
1219     boolean added = false;
1220     for (DBRefEntry dbr : dbrefs)
1221     {
1222       if (DBRefSource.PDB.equals(dbr.getSource()))
1223       {
1224         /*
1225          * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1226          * PDB id is not already present in a 'matching' PDBEntry
1227          * Constructor parses out a chain code if appended to the accession id
1228          * (a fudge used to 'store' the chain code in the DBRef)
1229          */
1230         PDBEntry pdbe = new PDBEntry(dbr);
1231         added |= addPDBId(pdbe);
1232       }
1233     }
1234     return added;
1235   }
1236
1237   @Override
1238   public void transferAnnotation(SequenceI entry, Mapping mp)
1239   {
1240     if (datasetSequence != null)
1241     {
1242       datasetSequence.transferAnnotation(entry, mp);
1243       return;
1244     }
1245     if (entry.getDatasetSequence() != null)
1246     {
1247       transferAnnotation(entry.getDatasetSequence(), mp);
1248       return;
1249     }
1250     // transfer any new features from entry onto sequence
1251     if (entry.getSequenceFeatures() != null)
1252     {
1253
1254       List<SequenceFeature> sfs = entry.getSequenceFeatures();
1255       for (SequenceFeature feature : sfs)
1256       {
1257         SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1258                 : new SequenceFeature[] { new SequenceFeature(feature) };
1259         if (sf != null)
1260         {
1261           for (int sfi = 0; sfi < sf.length; sfi++)
1262           {
1263             addSequenceFeature(sf[sfi]);
1264           }
1265         }
1266       }
1267     }
1268
1269     // transfer PDB entries
1270     if (entry.getAllPDBEntries() != null)
1271     {
1272       Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1273       while (e.hasMoreElements())
1274       {
1275         PDBEntry pdb = e.nextElement();
1276         addPDBId(pdb);
1277       }
1278     }
1279     // transfer database references
1280     DBRefEntry[] entryRefs = entry.getDBRefs();
1281     if (entryRefs != null)
1282     {
1283       for (int r = 0; r < entryRefs.length; r++)
1284       {
1285         DBRefEntry newref = new DBRefEntry(entryRefs[r]);
1286         if (newref.getMap() != null && mp != null)
1287         {
1288           // remap ref using our local mapping
1289         }
1290         // we also assume all version string setting is done by dbSourceProxy
1291         /*
1292          * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1293          * newref.setSource(dbSource); }
1294          */
1295         addDBRef(newref);
1296       }
1297     }
1298   }
1299
1300   /**
1301    * @return The index (zero-based) on this sequence in the MSA. It returns
1302    *         {@code -1} if this information is not available.
1303    */
1304   @Override
1305   public int getIndex()
1306   {
1307     return index;
1308   }
1309
1310   /**
1311    * Defines the position of this sequence in the MSA. Use the value {@code -1}
1312    * if this information is undefined.
1313    * 
1314    * @param The
1315    *          position for this sequence. This value is zero-based (zero for
1316    *          this first sequence)
1317    */
1318   @Override
1319   public void setIndex(int value)
1320   {
1321     index = value;
1322   }
1323
1324   @Override
1325   public void setRNA(RNA r)
1326   {
1327     rna = r;
1328   }
1329
1330   @Override
1331   public RNA getRNA()
1332   {
1333     return rna;
1334   }
1335
1336   @Override
1337   public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1338           String label)
1339   {
1340     List<AlignmentAnnotation> result = new ArrayList<AlignmentAnnotation>();
1341     if (this.annotation != null)
1342     {
1343       for (AlignmentAnnotation ann : annotation)
1344       {
1345         if (ann.calcId != null && ann.calcId.equals(calcId)
1346                 && ann.label != null && ann.label.equals(label))
1347         {
1348           result.add(ann);
1349         }
1350       }
1351     }
1352     return result;
1353   }
1354
1355   @Override
1356   public String toString()
1357   {
1358     return getDisplayId(false);
1359   }
1360
1361   @Override
1362   public PDBEntry getPDBEntry(String pdbIdStr)
1363   {
1364     if (getDatasetSequence() != null)
1365     {
1366       return getDatasetSequence().getPDBEntry(pdbIdStr);
1367     }
1368     if (pdbIds == null)
1369     {
1370       return null;
1371     }
1372     List<PDBEntry> entries = getAllPDBEntries();
1373     for (PDBEntry entry : entries)
1374     {
1375       if (entry.getId().equalsIgnoreCase(pdbIdStr))
1376       {
1377         return entry;
1378       }
1379     }
1380     return null;
1381   }
1382
1383   @Override
1384   public List<DBRefEntry> getPrimaryDBRefs()
1385   {
1386     if (datasetSequence != null)
1387     {
1388       return datasetSequence.getPrimaryDBRefs();
1389     }
1390     if (dbrefs == null || dbrefs.length == 0)
1391     {
1392       return Collections.emptyList();
1393     }
1394     synchronized (dbrefs)
1395     {
1396       List<DBRefEntry> primaries = new ArrayList<DBRefEntry>();
1397       DBRefEntry[] tmp = new DBRefEntry[1];
1398       for (DBRefEntry ref : dbrefs)
1399       {
1400         if (!ref.isPrimaryCandidate())
1401         {
1402           continue;
1403         }
1404         if (ref.hasMap())
1405         {
1406           MapList mp = ref.getMap().getMap();
1407           if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1408           {
1409             // map only involves a subsequence, so cannot be primary
1410             continue;
1411           }
1412         }
1413         // whilst it looks like it is a primary ref, we also sanity check type
1414         if (DBRefUtils.getCanonicalName(DBRefSource.PDB).equals(
1415                 DBRefUtils.getCanonicalName(ref.getSource())))
1416         {
1417           // PDB dbrefs imply there should be a PDBEntry associated
1418           // TODO: tighten PDB dbrefs
1419           // formally imply Jalview has actually downloaded and
1420           // parsed the pdb file. That means there should be a cached file
1421           // handle on the PDBEntry, and a real mapping between sequence and
1422           // extracted sequence from PDB file
1423           PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1424           if (pdbentry != null && pdbentry.getFile() != null)
1425           {
1426             primaries.add(ref);
1427           }
1428           continue;
1429         }
1430         // check standard protein or dna sources
1431         tmp[0] = ref;
1432         DBRefEntry[] res = DBRefUtils.selectDbRefs(!isProtein(), tmp);
1433         if (res != null && res[0] == tmp[0])
1434         {
1435           primaries.add(ref);
1436           continue;
1437         }
1438       }
1439       return primaries;
1440     }
1441   }
1442
1443   /**
1444    * {@inheritDoc}
1445    */
1446   @Override
1447   public List<SequenceFeature> findFeatures(int fromColumn, int toColumn,
1448           String... types)
1449   {
1450     int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
1451     int endPos = findPosition(toColumn - 1);
1452
1453     List<SequenceFeature> result = new ArrayList<>();
1454     if (datasetSequence != null)
1455     {
1456       result = datasetSequence.getFeatures().findFeatures(startPos, endPos,
1457               types);
1458     }
1459     else
1460     {
1461       result = sequenceFeatureStore.findFeatures(startPos, endPos, types);
1462     }
1463
1464     /*
1465      * if the start or end column is gapped, startPos or endPos may be to the 
1466      * left or right, and we may have included adjacent or enclosing features;
1467      * remove any that are not enclosing, non-contact features
1468      */
1469     if (endPos > this.end || Comparison.isGap(sequence[fromColumn - 1])
1470             || Comparison.isGap(sequence[toColumn - 1]))
1471     {
1472       ListIterator<SequenceFeature> it = result.listIterator();
1473       while (it.hasNext())
1474       {
1475         SequenceFeature sf = it.next();
1476         int featureStartColumn = findIndex(sf.getBegin());
1477         int featureEndColumn = findIndex(sf.getEnd());
1478         boolean noOverlap = featureStartColumn > toColumn
1479                         || featureEndColumn < fromColumn;
1480
1481         /*
1482          * reject an 'enclosing' feature if it is actually a contact feature
1483          */
1484         if (sf.isContactFeature() && featureStartColumn < fromColumn
1485                 && featureEndColumn > toColumn)
1486         {
1487           noOverlap = true;
1488         }
1489         if (noOverlap)
1490         {
1491           it.remove();
1492         }
1493       }
1494     }
1495
1496     return result;
1497   }
1498 }