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