Merge branch 'develop' into features/JAL-2446NCList
[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 (!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 (!Comparison.isGap(sequence[j]))
692       {
693         pos++;
694       }
695
696       j++;
697     }
698
699     return pos;
700   }
701
702   /**
703    * {@inheritDoc}
704    */
705   @Override
706   public Range findPositions(int fromCol, int toCol)
707   {
708     /*
709      * count residues before fromCol
710      */
711     int j = 0;
712     int count = 0;
713     int seqlen = sequence.length;
714     while (j < fromCol && j < seqlen)
715     {
716       if (!Comparison.isGap(sequence[j]))
717       {
718         count++;
719       }
720       j++;
721     }
722
723     /*
724      * find first and last residues between fromCol and toCol
725      */
726     int firstPos = 0;
727     int lastPos = 0;
728     int firstPosCol = 0;
729     boolean foundFirst = false;
730     
731     while (j <= toCol && j < seqlen)
732     {
733       if (!Comparison.isGap(sequence[j]))
734       {
735         count++;
736         if (!foundFirst)
737         {
738           firstPos = count;
739           firstPosCol = j;
740           foundFirst = true;
741         }
742         lastPos = count;
743       }
744       j++;
745     }
746
747     if (firstPos == 0)
748     {
749       /*
750        * no residues in this range
751        */
752       return null;
753     }
754
755     /*
756      * adjust for sequence start coordinate
757      */
758     firstPos += start - 1;
759     lastPos += start - 1;
760
761     return new Range(firstPos, lastPos);
762   }
763
764   /**
765    * Returns an int array where indices correspond to each residue in the
766    * sequence and the element value gives its position in the alignment
767    * 
768    * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
769    *         residues in SequenceI object
770    */
771   @Override
772   public int[] gapMap()
773   {
774     String seq = jalview.analysis.AlignSeq.extractGaps(
775             jalview.util.Comparison.GapChars, new String(sequence));
776     int[] map = new int[seq.length()];
777     int j = 0;
778     int p = 0;
779
780     while (j < sequence.length)
781     {
782       if (!jalview.util.Comparison.isGap(sequence[j]))
783       {
784         map[p++] = j;
785       }
786
787       j++;
788     }
789
790     return map;
791   }
792
793   @Override
794   public int[] findPositionMap()
795   {
796     int map[] = new int[sequence.length];
797     int j = 0;
798     int pos = start;
799     int seqlen = sequence.length;
800     while ((j < seqlen))
801     {
802       map[j] = pos;
803       if (!jalview.util.Comparison.isGap(sequence[j]))
804       {
805         pos++;
806       }
807
808       j++;
809     }
810     return map;
811   }
812
813   @Override
814   public List<int[]> getInsertions()
815   {
816     ArrayList<int[]> map = new ArrayList<int[]>();
817     int lastj = -1, j = 0;
818     int pos = start;
819     int seqlen = sequence.length;
820     while ((j < seqlen))
821     {
822       if (jalview.util.Comparison.isGap(sequence[j]))
823       {
824         if (lastj == -1)
825         {
826           lastj = j;
827         }
828       }
829       else
830       {
831         if (lastj != -1)
832         {
833           map.add(new int[] { lastj, j - 1 });
834           lastj = -1;
835         }
836       }
837       j++;
838     }
839     if (lastj != -1)
840     {
841       map.add(new int[] { lastj, j - 1 });
842       lastj = -1;
843     }
844     return map;
845   }
846
847   @Override
848   public void deleteChars(int i, int j)
849   {
850     int newstart = start, newend = end;
851     if (i >= sequence.length || i < 0)
852     {
853       return;
854     }
855
856     char[] tmp = StringUtils.deleteChars(sequence, i, j);
857     boolean createNewDs = false;
858     // TODO: take a (second look) at the dataset creation validation method for
859     // the very large sequence case
860     int eindex = -1, sindex = -1;
861     boolean ecalc = false, scalc = false;
862     for (int s = i; s < j; s++)
863     {
864       if (jalview.schemes.ResidueProperties.aaIndex[sequence[s]] != 23)
865       {
866         if (createNewDs)
867         {
868           newend--;
869         }
870         else
871         {
872           if (!scalc)
873           {
874             sindex = findIndex(start) - 1;
875             scalc = true;
876           }
877           if (sindex == s)
878           {
879             // delete characters including start of sequence
880             newstart = findPosition(j);
881             break; // don't need to search for any more residue characters.
882           }
883           else
884           {
885             // delete characters after start.
886             if (!ecalc)
887             {
888               eindex = findIndex(end) - 1;
889               ecalc = true;
890             }
891             if (eindex < j)
892             {
893               // delete characters at end of sequence
894               newend = findPosition(i - 1);
895               break; // don't need to search for any more residue characters.
896             }
897             else
898             {
899               createNewDs = true;
900               newend--; // decrease end position by one for the deleted residue
901               // and search further
902             }
903           }
904         }
905       }
906     }
907     // deletion occured in the middle of the sequence
908     if (createNewDs && this.datasetSequence != null)
909     {
910       // construct a new sequence
911       Sequence ds = new Sequence(datasetSequence);
912       // TODO: remove any non-inheritable properties ?
913       // TODO: create a sequence mapping (since there is a relation here ?)
914       ds.deleteChars(i, j);
915       datasetSequence = ds;
916     }
917     start = newstart;
918     end = newend;
919     sequence = tmp;
920   }
921
922   @Override
923   public void insertCharAt(int i, int length, char c)
924   {
925     char[] tmp = new char[sequence.length + length];
926
927     if (i >= sequence.length)
928     {
929       System.arraycopy(sequence, 0, tmp, 0, sequence.length);
930       i = sequence.length;
931     }
932     else
933     {
934       System.arraycopy(sequence, 0, tmp, 0, i);
935     }
936
937     int index = i;
938     while (length > 0)
939     {
940       tmp[index++] = c;
941       length--;
942     }
943
944     if (i < sequence.length)
945     {
946       System.arraycopy(sequence, i, tmp, index, sequence.length - i);
947     }
948
949     sequence = tmp;
950   }
951
952   @Override
953   public void insertCharAt(int i, char c)
954   {
955     insertCharAt(i, 1, c);
956   }
957
958   @Override
959   public String getVamsasId()
960   {
961     return vamsasId;
962   }
963
964   @Override
965   public void setVamsasId(String id)
966   {
967     vamsasId = id;
968   }
969
970   @Override
971   public void setDBRefs(DBRefEntry[] dbref)
972   {
973     if (dbrefs == null && datasetSequence != null
974             && this != datasetSequence)
975     {
976       datasetSequence.setDBRefs(dbref);
977       return;
978     }
979     dbrefs = dbref;
980     if (dbrefs != null)
981     {
982       DBRefUtils.ensurePrimaries(this);
983     }
984   }
985
986   @Override
987   public DBRefEntry[] getDBRefs()
988   {
989     if (dbrefs == null && datasetSequence != null
990             && this != datasetSequence)
991     {
992       return datasetSequence.getDBRefs();
993     }
994     return dbrefs;
995   }
996
997   @Override
998   public void addDBRef(DBRefEntry entry)
999   {
1000     if (datasetSequence != null)
1001     {
1002       datasetSequence.addDBRef(entry);
1003       return;
1004     }
1005
1006     if (dbrefs == null)
1007     {
1008       dbrefs = new DBRefEntry[0];
1009     }
1010
1011     for (DBRefEntryI dbr : dbrefs)
1012     {
1013       if (dbr.updateFrom(entry))
1014       {
1015         /*
1016          * found a dbref that either matched, or could be
1017          * updated from, the new entry - no need to add it
1018          */
1019         return;
1020       }
1021     }
1022
1023     /*
1024      * extend the array to make room for one more
1025      */
1026     // TODO use an ArrayList instead
1027     int j = dbrefs.length;
1028     DBRefEntry[] temp = new DBRefEntry[j + 1];
1029     System.arraycopy(dbrefs, 0, temp, 0, j);
1030     temp[temp.length - 1] = entry;
1031
1032     dbrefs = temp;
1033
1034     DBRefUtils.ensurePrimaries(this);
1035   }
1036
1037   @Override
1038   public void setDatasetSequence(SequenceI seq)
1039   {
1040     if (seq == this)
1041     {
1042       throw new IllegalArgumentException(
1043               "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1044     }
1045     if (seq != null && seq.getDatasetSequence() != null)
1046     {
1047       throw new IllegalArgumentException(
1048               "Implementation error: cascading dataset sequences are not allowed.");
1049     }
1050     datasetSequence = seq;
1051   }
1052
1053   @Override
1054   public SequenceI getDatasetSequence()
1055   {
1056     return datasetSequence;
1057   }
1058
1059   @Override
1060   public AlignmentAnnotation[] getAnnotation()
1061   {
1062     return annotation == null ? null : annotation
1063             .toArray(new AlignmentAnnotation[annotation.size()]);
1064   }
1065
1066   @Override
1067   public boolean hasAnnotation(AlignmentAnnotation ann)
1068   {
1069     return annotation == null ? false : annotation.contains(ann);
1070   }
1071
1072   @Override
1073   public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1074   {
1075     if (this.annotation == null)
1076     {
1077       this.annotation = new Vector<AlignmentAnnotation>();
1078     }
1079     if (!this.annotation.contains(annotation))
1080     {
1081       this.annotation.addElement(annotation);
1082     }
1083     annotation.setSequenceRef(this);
1084   }
1085
1086   @Override
1087   public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1088   {
1089     if (this.annotation != null)
1090     {
1091       this.annotation.removeElement(annotation);
1092       if (this.annotation.size() == 0)
1093       {
1094         this.annotation = null;
1095       }
1096     }
1097   }
1098
1099   /**
1100    * test if this is a valid candidate for another sequence's dataset sequence.
1101    * 
1102    */
1103   private boolean isValidDatasetSequence()
1104   {
1105     if (datasetSequence != null)
1106     {
1107       return false;
1108     }
1109     for (int i = 0; i < sequence.length; i++)
1110     {
1111       if (jalview.util.Comparison.isGap(sequence[i]))
1112       {
1113         return false;
1114       }
1115     }
1116     return true;
1117   }
1118
1119   @Override
1120   public SequenceI deriveSequence()
1121   {
1122     Sequence seq = null;
1123     if (datasetSequence == null)
1124     {
1125       if (isValidDatasetSequence())
1126       {
1127         // Use this as dataset sequence
1128         seq = new Sequence(getName(), "", 1, -1);
1129         seq.setDatasetSequence(this);
1130         seq.initSeqFrom(this, getAnnotation());
1131         return seq;
1132       }
1133       else
1134       {
1135         // Create a new, valid dataset sequence
1136         createDatasetSequence();
1137       }
1138     }
1139     return new Sequence(this);
1140   }
1141
1142   private boolean _isNa;
1143
1144   private long _seqhash = 0;
1145
1146   /**
1147    * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1148    * true
1149    */
1150   @Override
1151   public boolean isProtein()
1152   {
1153     if (datasetSequence != null)
1154     {
1155       return datasetSequence.isProtein();
1156     }
1157     if (_seqhash != sequence.hashCode())
1158     {
1159       _seqhash = sequence.hashCode();
1160       _isNa = Comparison.isNucleotide(this);
1161     }
1162     return !_isNa;
1163   };
1164
1165   /*
1166    * (non-Javadoc)
1167    * 
1168    * @see jalview.datamodel.SequenceI#createDatasetSequence()
1169    */
1170   @Override
1171   public SequenceI createDatasetSequence()
1172   {
1173     if (datasetSequence == null)
1174     {
1175       Sequence dsseq = new Sequence(getName(), AlignSeq.extractGaps(
1176               jalview.util.Comparison.GapChars, getSequenceAsString()),
1177               getStart(), getEnd());
1178
1179       datasetSequence = dsseq;
1180
1181       dsseq.setDescription(description);
1182       // move features and database references onto dataset sequence
1183       dsseq.sequenceFeatureStore = sequenceFeatureStore;
1184       sequenceFeatureStore = null;
1185       dsseq.dbrefs = dbrefs;
1186       dbrefs = null;
1187       // TODO: search and replace any references to this sequence with
1188       // references to the dataset sequence in Mappings on dbref
1189       dsseq.pdbIds = pdbIds;
1190       pdbIds = null;
1191       datasetSequence.updatePDBIds();
1192       if (annotation != null)
1193       {
1194         // annotation is cloned rather than moved, to preserve what's currently
1195         // on the alignment
1196         for (AlignmentAnnotation aa : annotation)
1197         {
1198           AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1199           _aa.sequenceRef = datasetSequence;
1200           _aa.adjustForAlignment(); // uses annotation's own record of
1201                                     // sequence-column mapping
1202           datasetSequence.addAlignmentAnnotation(_aa);
1203         }
1204       }
1205     }
1206     return datasetSequence;
1207   }
1208
1209   /*
1210    * (non-Javadoc)
1211    * 
1212    * @see
1213    * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1214    * annotations)
1215    */
1216   @Override
1217   public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1218   {
1219     if (annotation != null)
1220     {
1221       annotation.removeAllElements();
1222     }
1223     if (annotations != null)
1224     {
1225       for (int i = 0; i < annotations.length; i++)
1226       {
1227         if (annotations[i] != null)
1228         {
1229           addAlignmentAnnotation(annotations[i]);
1230         }
1231       }
1232     }
1233   }
1234
1235   @Override
1236   public AlignmentAnnotation[] getAnnotation(String label)
1237   {
1238     if (annotation == null || annotation.size() == 0)
1239     {
1240       return null;
1241     }
1242
1243     Vector<AlignmentAnnotation> subset = new Vector<AlignmentAnnotation>();
1244     Enumeration<AlignmentAnnotation> e = annotation.elements();
1245     while (e.hasMoreElements())
1246     {
1247       AlignmentAnnotation ann = e.nextElement();
1248       if (ann.label != null && ann.label.equals(label))
1249       {
1250         subset.addElement(ann);
1251       }
1252     }
1253     if (subset.size() == 0)
1254     {
1255       return null;
1256     }
1257     AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1258     int i = 0;
1259     e = subset.elements();
1260     while (e.hasMoreElements())
1261     {
1262       anns[i++] = e.nextElement();
1263     }
1264     subset.removeAllElements();
1265     return anns;
1266   }
1267
1268   @Override
1269   public boolean updatePDBIds()
1270   {
1271     if (datasetSequence != null)
1272     {
1273       // TODO: could merge DBRefs
1274       return datasetSequence.updatePDBIds();
1275     }
1276     if (dbrefs == null || dbrefs.length == 0)
1277     {
1278       return false;
1279     }
1280     boolean added = false;
1281     for (DBRefEntry dbr : dbrefs)
1282     {
1283       if (DBRefSource.PDB.equals(dbr.getSource()))
1284       {
1285         /*
1286          * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1287          * PDB id is not already present in a 'matching' PDBEntry
1288          * Constructor parses out a chain code if appended to the accession id
1289          * (a fudge used to 'store' the chain code in the DBRef)
1290          */
1291         PDBEntry pdbe = new PDBEntry(dbr);
1292         added |= addPDBId(pdbe);
1293       }
1294     }
1295     return added;
1296   }
1297
1298   @Override
1299   public void transferAnnotation(SequenceI entry, Mapping mp)
1300   {
1301     if (datasetSequence != null)
1302     {
1303       datasetSequence.transferAnnotation(entry, mp);
1304       return;
1305     }
1306     if (entry.getDatasetSequence() != null)
1307     {
1308       transferAnnotation(entry.getDatasetSequence(), mp);
1309       return;
1310     }
1311     // transfer any new features from entry onto sequence
1312     if (entry.getSequenceFeatures() != null)
1313     {
1314
1315       List<SequenceFeature> sfs = entry.getSequenceFeatures();
1316       for (SequenceFeature feature : sfs)
1317       {
1318         SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1319                 : new SequenceFeature[] { new SequenceFeature(feature) };
1320         if (sf != null)
1321         {
1322           for (int sfi = 0; sfi < sf.length; sfi++)
1323           {
1324             addSequenceFeature(sf[sfi]);
1325           }
1326         }
1327       }
1328     }
1329
1330     // transfer PDB entries
1331     if (entry.getAllPDBEntries() != null)
1332     {
1333       Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1334       while (e.hasMoreElements())
1335       {
1336         PDBEntry pdb = e.nextElement();
1337         addPDBId(pdb);
1338       }
1339     }
1340     // transfer database references
1341     DBRefEntry[] entryRefs = entry.getDBRefs();
1342     if (entryRefs != null)
1343     {
1344       for (int r = 0; r < entryRefs.length; r++)
1345       {
1346         DBRefEntry newref = new DBRefEntry(entryRefs[r]);
1347         if (newref.getMap() != null && mp != null)
1348         {
1349           // remap ref using our local mapping
1350         }
1351         // we also assume all version string setting is done by dbSourceProxy
1352         /*
1353          * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1354          * newref.setSource(dbSource); }
1355          */
1356         addDBRef(newref);
1357       }
1358     }
1359   }
1360
1361   /**
1362    * @return The index (zero-based) on this sequence in the MSA. It returns
1363    *         {@code -1} if this information is not available.
1364    */
1365   @Override
1366   public int getIndex()
1367   {
1368     return index;
1369   }
1370
1371   /**
1372    * Defines the position of this sequence in the MSA. Use the value {@code -1}
1373    * if this information is undefined.
1374    * 
1375    * @param The
1376    *          position for this sequence. This value is zero-based (zero for
1377    *          this first sequence)
1378    */
1379   @Override
1380   public void setIndex(int value)
1381   {
1382     index = value;
1383   }
1384
1385   @Override
1386   public void setRNA(RNA r)
1387   {
1388     rna = r;
1389   }
1390
1391   @Override
1392   public RNA getRNA()
1393   {
1394     return rna;
1395   }
1396
1397   @Override
1398   public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1399           String label)
1400   {
1401     List<AlignmentAnnotation> result = new ArrayList<AlignmentAnnotation>();
1402     if (this.annotation != null)
1403     {
1404       for (AlignmentAnnotation ann : annotation)
1405       {
1406         if (ann.calcId != null && ann.calcId.equals(calcId)
1407                 && ann.label != null && ann.label.equals(label))
1408         {
1409           result.add(ann);
1410         }
1411       }
1412     }
1413     return result;
1414   }
1415
1416   @Override
1417   public String toString()
1418   {
1419     return getDisplayId(false);
1420   }
1421
1422   @Override
1423   public PDBEntry getPDBEntry(String pdbIdStr)
1424   {
1425     if (getDatasetSequence() != null)
1426     {
1427       return getDatasetSequence().getPDBEntry(pdbIdStr);
1428     }
1429     if (pdbIds == null)
1430     {
1431       return null;
1432     }
1433     List<PDBEntry> entries = getAllPDBEntries();
1434     for (PDBEntry entry : entries)
1435     {
1436       if (entry.getId().equalsIgnoreCase(pdbIdStr))
1437       {
1438         return entry;
1439       }
1440     }
1441     return null;
1442   }
1443
1444   @Override
1445   public List<DBRefEntry> getPrimaryDBRefs()
1446   {
1447     if (datasetSequence != null)
1448     {
1449       return datasetSequence.getPrimaryDBRefs();
1450     }
1451     if (dbrefs == null || dbrefs.length == 0)
1452     {
1453       return Collections.emptyList();
1454     }
1455     synchronized (dbrefs)
1456     {
1457       List<DBRefEntry> primaries = new ArrayList<DBRefEntry>();
1458       DBRefEntry[] tmp = new DBRefEntry[1];
1459       for (DBRefEntry ref : dbrefs)
1460       {
1461         if (!ref.isPrimaryCandidate())
1462         {
1463           continue;
1464         }
1465         if (ref.hasMap())
1466         {
1467           MapList mp = ref.getMap().getMap();
1468           if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1469           {
1470             // map only involves a subsequence, so cannot be primary
1471             continue;
1472           }
1473         }
1474         // whilst it looks like it is a primary ref, we also sanity check type
1475         if (DBRefUtils.getCanonicalName(DBRefSource.PDB).equals(
1476                 DBRefUtils.getCanonicalName(ref.getSource())))
1477         {
1478           // PDB dbrefs imply there should be a PDBEntry associated
1479           // TODO: tighten PDB dbrefs
1480           // formally imply Jalview has actually downloaded and
1481           // parsed the pdb file. That means there should be a cached file
1482           // handle on the PDBEntry, and a real mapping between sequence and
1483           // extracted sequence from PDB file
1484           PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1485           if (pdbentry != null && pdbentry.getFile() != null)
1486           {
1487             primaries.add(ref);
1488           }
1489           continue;
1490         }
1491         // check standard protein or dna sources
1492         tmp[0] = ref;
1493         DBRefEntry[] res = DBRefUtils.selectDbRefs(!isProtein(), tmp);
1494         if (res != null && res[0] == tmp[0])
1495         {
1496           primaries.add(ref);
1497           continue;
1498         }
1499       }
1500       return primaries;
1501     }
1502   }
1503
1504   /**
1505    * {@inheritDoc}
1506    */
1507   @Override
1508   public List<SequenceFeature> findFeatures(int from, int to,
1509           String... types)
1510   {
1511     if (datasetSequence != null)
1512     {
1513       return datasetSequence.findFeatures(from, to, types);
1514     }
1515     return sequenceFeatureStore.findFeatures(from, to, types);
1516   }
1517 }