JAL-1421 use generics JAL-1551 @Override annotations added
[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.util.StringUtils;
25
26 import java.util.ArrayList;
27 import java.util.Enumeration;
28 import java.util.List;
29 import java.util.Vector;
30
31 import fr.orsay.lri.varna.models.rna.RNA;
32
33 /**
34  * 
35  * Implements the SequenceI interface for a char[] based sequence object.
36  * 
37  * @author $author$
38  * @version $Revision$
39  */
40 public class Sequence extends ASequence implements SequenceI
41 {
42   SequenceI datasetSequence;
43
44   String name;
45
46   private char[] sequence;
47
48   String description;
49
50   int start;
51
52   int end;
53
54   Vector<PDBEntry> pdbIds;
55
56   String vamsasId;
57
58   DBRefEntry[] dbrefs;
59
60   RNA rna;
61
62   /**
63    * This annotation is displayed below the alignment but the positions are tied
64    * to the residues of this sequence
65    *
66    * TODO: change to List<>
67    */
68   Vector<AlignmentAnnotation> annotation;
69
70   /**
71    * The index of the sequence in a MSA
72    */
73   int index = -1;
74
75   /** array of sequence features - may not be null for a valid sequence object */
76   public SequenceFeature[] sequenceFeatures;
77
78   /**
79    * Creates a new Sequence object.
80    * 
81    * @param name
82    *          display name string
83    * @param sequence
84    *          string to form a possibly gapped sequence out of
85    * @param start
86    *          first position of non-gap residue in the sequence
87    * @param end
88    *          last position of ungapped residues (nearly always only used for
89    *          display purposes)
90    */
91   public Sequence(String name, String sequence, int start, int end)
92   {
93     initSeqAndName(name, sequence.toCharArray(), start, end);
94   }
95
96   public Sequence(String name, char[] sequence, int start, int end)
97   {
98     initSeqAndName(name, sequence, start, end);
99   }
100
101   /**
102    * Stage 1 constructor - assign name, sequence, and set start and end fields.
103    * start and end are updated values from name2 if it ends with /start-end
104    * 
105    * @param name2
106    * @param sequence2
107    * @param start2
108    * @param end2
109    */
110   protected void initSeqAndName(String name2, char[] sequence2, int start2,
111           int end2)
112   {
113     this.name = name2;
114     this.sequence = sequence2;
115     this.start = start2;
116     this.end = end2;
117     parseId();
118     checkValidRange();
119   }
120
121   com.stevesoft.pat.Regex limitrx = new com.stevesoft.pat.Regex(
122           "[/][0-9]{1,}[-][0-9]{1,}$");
123
124   com.stevesoft.pat.Regex endrx = new com.stevesoft.pat.Regex("[0-9]{1,}$");
125
126   void parseId()
127   {
128     if (name == null)
129     {
130       System.err
131               .println("POSSIBLE IMPLEMENTATION ERROR: null sequence name passed to constructor.");
132       name = "";
133     }
134     // Does sequence have the /start-end signature?
135     if (limitrx.search(name))
136     {
137       name = limitrx.left();
138       endrx.search(limitrx.stringMatched());
139       setStart(Integer.parseInt(limitrx.stringMatched().substring(1,
140               endrx.matchedFrom() - 1)));
141       setEnd(Integer.parseInt(endrx.stringMatched()));
142     }
143   }
144
145   void checkValidRange()
146   {
147     // Note: JAL-774 :
148     // http://issues.jalview.org/browse/JAL-774?focusedCommentId=11239&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-11239
149     {
150       int endRes = 0;
151       for (int j = 0; j < sequence.length; j++)
152       {
153         if (!jalview.util.Comparison.isGap(sequence[j]))
154         {
155           endRes++;
156         }
157       }
158       if (endRes > 0)
159       {
160         endRes += start - 1;
161       }
162
163       if (end < endRes)
164       {
165         end = endRes;
166       }
167     }
168
169   }
170
171   /**
172    * Creates a new Sequence object.
173    * 
174    * @param name
175    *          DOCUMENT ME!
176    * @param sequence
177    *          DOCUMENT ME!
178    */
179   public Sequence(String name, String sequence)
180   {
181     this(name, sequence, 1, -1);
182   }
183
184   /**
185    * Creates a new Sequence object with new features, DBRefEntries,
186    * AlignmentAnnotations, and PDBIds but inherits any existing dataset sequence
187    * reference.
188    * 
189    * @param seq
190    *          DOCUMENT ME!
191    */
192   public Sequence(SequenceI seq)
193   {
194     this(seq, seq.getAnnotation());
195   }
196
197   /**
198    * Create a new sequence object with new features, DBRefEntries, and PDBIds
199    * but inherits any existing dataset sequence reference, and duplicate of any
200    * annotation that is present in the given annotation array.
201    * 
202    * @param seq
203    *          the sequence to be copied
204    * @param alAnnotation
205    *          an array of annotation including some associated with seq
206    */
207   public Sequence(SequenceI seq, AlignmentAnnotation[] alAnnotation)
208   {
209     initSeqFrom(seq, alAnnotation);
210
211   }
212
213   protected void initSeqFrom(SequenceI seq,
214           AlignmentAnnotation[] alAnnotation)
215   {
216     initSeqAndName(seq.getName(), seq.getSequence(), seq.getStart(),
217             seq.getEnd());
218     description = seq.getDescription();
219     if (seq.getSequenceFeatures() != null)
220     {
221       SequenceFeature[] sf = seq.getSequenceFeatures();
222       for (int i = 0; i < sf.length; i++)
223       {
224         addSequenceFeature(new SequenceFeature(sf[i]));
225       }
226     }
227     setDatasetSequence(seq.getDatasetSequence());
228     if (datasetSequence == null && seq.getDBRef() != null)
229     {
230       // only copy DBRefs if we really are a dataset sequence
231       DBRefEntry[] dbr = seq.getDBRef();
232       for (int i = 0; i < dbr.length; i++)
233       {
234         addDBRef(new DBRefEntry(dbr[i]));
235       }
236     }
237     if (seq.getAnnotation() != null)
238     {
239       AlignmentAnnotation[] sqann = seq.getAnnotation();
240       for (int i = 0; i < sqann.length; i++)
241       {
242         if (sqann[i] == null)
243         {
244           continue;
245         }
246         boolean found = (alAnnotation == null);
247         if (!found)
248         {
249           for (int apos = 0; !found && apos < alAnnotation.length; apos++)
250           {
251             found = (alAnnotation[apos] == sqann[i]);
252           }
253         }
254         if (found)
255         {
256           // only copy the given annotation
257           AlignmentAnnotation newann = new AlignmentAnnotation(sqann[i]);
258           addAlignmentAnnotation(newann);
259         }
260       }
261     }
262     if (seq.getAllPDBEntries() != null)
263     {
264       Vector<PDBEntry> ids = seq.getAllPDBEntries();
265       for (PDBEntry pdb : ids)
266       {
267         this.addPDBId(new PDBEntry(pdb));
268       }
269     }
270   }
271
272   /**
273    * DOCUMENT ME!
274    * 
275    * @param v
276    *          DOCUMENT ME!
277    */
278   @Override
279   public void setSequenceFeatures(SequenceFeature[] features)
280   {
281     sequenceFeatures = features;
282   }
283
284   @Override
285   public synchronized void addSequenceFeature(SequenceFeature sf)
286   {
287     if (sequenceFeatures == null)
288     {
289       sequenceFeatures = new SequenceFeature[0];
290     }
291
292     for (int i = 0; i < sequenceFeatures.length; i++)
293     {
294       if (sequenceFeatures[i].equals(sf))
295       {
296         return;
297       }
298     }
299
300     SequenceFeature[] temp = new SequenceFeature[sequenceFeatures.length + 1];
301     System.arraycopy(sequenceFeatures, 0, temp, 0, sequenceFeatures.length);
302     temp[sequenceFeatures.length] = sf;
303
304     sequenceFeatures = temp;
305   }
306
307   @Override
308   public void deleteFeature(SequenceFeature sf)
309   {
310     if (sequenceFeatures == null)
311     {
312       return;
313     }
314
315     int index = 0;
316     for (index = 0; index < sequenceFeatures.length; index++)
317     {
318       if (sequenceFeatures[index].equals(sf))
319       {
320         break;
321       }
322     }
323
324     if (index == sequenceFeatures.length)
325     {
326       return;
327     }
328
329     int sfLength = sequenceFeatures.length;
330     if (sfLength < 2)
331     {
332       sequenceFeatures = null;
333     }
334     else
335     {
336       SequenceFeature[] temp = new SequenceFeature[sfLength - 1];
337       System.arraycopy(sequenceFeatures, 0, temp, 0, index);
338
339       if (index < sfLength)
340       {
341         System.arraycopy(sequenceFeatures, index + 1, temp, index,
342                 sequenceFeatures.length - index - 1);
343       }
344
345       sequenceFeatures = temp;
346     }
347   }
348
349   /**
350    * Returns the sequence features (if any), looking first on the sequence, then
351    * on its dataset sequence, and so on until a non-null value is found (or
352    * none). This supports retrieval of sequence features stored on the sequence
353    * (as in the applet) or on the dataset sequence (as in the Desktop version).
354    * 
355    * @return
356    */
357   @Override
358   public SequenceFeature[] getSequenceFeatures()
359   {
360     SequenceFeature[] features = sequenceFeatures;
361
362     SequenceI seq = this;
363     int count = 0; // failsafe against loop in sequence.datasetsequence...
364     while (features == null && seq.getDatasetSequence() != null
365             && count++ < 10)
366     {
367       seq = seq.getDatasetSequence();
368       features = ((Sequence) seq).sequenceFeatures;
369     }
370     return features;
371   }
372
373   @Override
374   public void addPDBId(PDBEntry entry)
375   {
376     if (pdbIds == null)
377     {
378       pdbIds = new Vector<PDBEntry>();
379     }
380     if (pdbIds.contains(entry))
381     {
382       updatePDBEntry(pdbIds.get(pdbIds.indexOf(entry)), entry);
383     }
384     else
385     {
386       pdbIds.addElement(entry);
387     }
388   }
389
390   private static void updatePDBEntry(PDBEntry oldEntry, PDBEntry newEntry)
391   {
392     if (newEntry.getFile() != null)
393     {
394       oldEntry.setFile(newEntry.getFile());
395     }
396   }
397
398   /**
399    * DOCUMENT ME!
400    * 
401    * @param id
402    *          DOCUMENT ME!
403    */
404   @Override
405   public void setPDBId(Vector<PDBEntry> id)
406   {
407     pdbIds = id;
408   }
409
410   /**
411    * DOCUMENT ME!
412    * 
413    * @return DOCUMENT ME!
414    */
415   @Override
416   public Vector<PDBEntry> getAllPDBEntries()
417   {
418     return pdbIds;
419   }
420
421   /**
422    * DOCUMENT ME!
423    * 
424    * @return DOCUMENT ME!
425    */
426   @Override
427   public String getDisplayId(boolean jvsuffix)
428   {
429     StringBuffer result = new StringBuffer(name);
430     if (jvsuffix)
431     {
432       result.append("/" + start + "-" + end);
433     }
434
435     return result.toString();
436   }
437
438   /**
439    * DOCUMENT ME!
440    * 
441    * @param name
442    *          DOCUMENT ME!
443    */
444   @Override
445   public void setName(String name)
446   {
447     this.name = name;
448     this.parseId();
449   }
450
451   /**
452    * DOCUMENT ME!
453    * 
454    * @return DOCUMENT ME!
455    */
456   @Override
457   public String getName()
458   {
459     return this.name;
460   }
461
462   /**
463    * DOCUMENT ME!
464    * 
465    * @param start
466    *          DOCUMENT ME!
467    */
468   @Override
469   public void setStart(int start)
470   {
471     this.start = start;
472   }
473
474   /**
475    * DOCUMENT ME!
476    * 
477    * @return DOCUMENT ME!
478    */
479   @Override
480   public int getStart()
481   {
482     return this.start;
483   }
484
485   /**
486    * DOCUMENT ME!
487    * 
488    * @param end
489    *          DOCUMENT ME!
490    */
491   @Override
492   public void setEnd(int end)
493   {
494     this.end = end;
495   }
496
497   /**
498    * DOCUMENT ME!
499    * 
500    * @return DOCUMENT ME!
501    */
502   @Override
503   public int getEnd()
504   {
505     return this.end;
506   }
507
508   /**
509    * DOCUMENT ME!
510    * 
511    * @return DOCUMENT ME!
512    */
513   @Override
514   public int getLength()
515   {
516     return this.sequence.length;
517   }
518
519   /**
520    * DOCUMENT ME!
521    * 
522    * @param seq
523    *          DOCUMENT ME!
524    */
525   @Override
526   public void setSequence(String seq)
527   {
528     this.sequence = seq.toCharArray();
529     checkValidRange();
530   }
531
532   @Override
533   public String getSequenceAsString()
534   {
535     return new String(sequence);
536   }
537
538   @Override
539   public String getSequenceAsString(int start, int end)
540   {
541     return new String(getSequence(start, end));
542   }
543
544   @Override
545   public char[] getSequence()
546   {
547     return sequence;
548   }
549
550   /*
551    * (non-Javadoc)
552    * 
553    * @see jalview.datamodel.SequenceI#getSequence(int, int)
554    */
555   @Override
556   public char[] getSequence(int start, int end)
557   {
558     if (start < 0)
559     {
560       start = 0;
561     }
562     // JBPNote - left to user to pad the result here (TODO:Decide on this
563     // policy)
564     if (start >= sequence.length)
565     {
566       return new char[0];
567     }
568
569     if (end >= sequence.length)
570     {
571       end = sequence.length;
572     }
573
574     char[] reply = new char[end - start];
575     System.arraycopy(sequence, start, reply, 0, end - start);
576
577     return reply;
578   }
579
580   @Override
581   public SequenceI getSubSequence(int start, int end)
582   {
583     if (start < 0)
584     {
585       start = 0;
586     }
587     char[] seq = getSequence(start, end);
588     if (seq.length == 0)
589     {
590       return null;
591     }
592     int nstart = findPosition(start);
593     int nend = findPosition(end) - 1;
594     // JBPNote - this is an incomplete copy.
595     SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
596     nseq.setDescription(description);
597     if (datasetSequence != null)
598     {
599       nseq.setDatasetSequence(datasetSequence);
600     }
601     else
602     {
603       nseq.setDatasetSequence(this);
604     }
605     return nseq;
606   }
607
608   /**
609    * DOCUMENT ME!
610    * 
611    * @param i
612    *          DOCUMENT ME!
613    * 
614    * @return DOCUMENT ME!
615    */
616   @Override
617   public char getCharAt(int i)
618   {
619     if (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 (!jalview.util.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 (!jalview.util.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 setDBRef(DBRefEntry[] dbref)
911   {
912     dbrefs = dbref;
913   }
914
915   @Override
916   public DBRefEntry[] getDBRef()
917   {
918     if (dbrefs == null && datasetSequence != null
919             && this != datasetSequence)
920     {
921       return datasetSequence.getDBRef();
922     }
923     return dbrefs;
924   }
925
926   @Override
927   public void addDBRef(DBRefEntry entry)
928   {
929     if (dbrefs == null)
930     {
931       dbrefs = new DBRefEntry[0];
932     }
933
934     int i, iSize = dbrefs.length;
935
936     for (i = 0; i < iSize; i++)
937     {
938       if (dbrefs[i].equalRef(entry))
939       {
940         if (entry.getMap() != null)
941         {
942           if (dbrefs[i].getMap() == null)
943           {
944             // overwrite with 'superior' entry that contains a mapping.
945             dbrefs[i] = entry;
946           }
947         }
948         return;
949       }
950     }
951
952     DBRefEntry[] temp = new DBRefEntry[iSize + 1];
953     System.arraycopy(dbrefs, 0, temp, 0, iSize);
954     temp[temp.length - 1] = entry;
955
956     dbrefs = temp;
957   }
958
959   @Override
960   public void setDatasetSequence(SequenceI seq)
961   {
962     // TODO check for circular reference before setting?
963     datasetSequence = seq;
964   }
965
966   @Override
967   public SequenceI getDatasetSequence()
968   {
969     return datasetSequence;
970   }
971
972   @Override
973   public AlignmentAnnotation[] getAnnotation()
974   {
975     return annotation == null ? null : annotation
976             .toArray(new AlignmentAnnotation[annotation.size()]);
977   }
978
979   @Override
980   public boolean hasAnnotation(AlignmentAnnotation ann)
981   {
982     return annotation == null ? false : annotation.contains(ann);
983   }
984
985   @Override
986   public void addAlignmentAnnotation(AlignmentAnnotation annotation)
987   {
988     if (this.annotation == null)
989     {
990       this.annotation = new Vector<AlignmentAnnotation>();
991     }
992     if (!this.annotation.contains(annotation))
993     {
994       this.annotation.addElement(annotation);
995     }
996     annotation.setSequenceRef(this);
997   }
998
999   @Override
1000   public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1001   {
1002     if (this.annotation != null)
1003     {
1004       this.annotation.removeElement(annotation);
1005       if (this.annotation.size() == 0)
1006       {
1007         this.annotation = null;
1008       }
1009     }
1010   }
1011
1012   /**
1013    * test if this is a valid candidate for another sequence's dataset sequence.
1014    * 
1015    */
1016   private boolean isValidDatasetSequence()
1017   {
1018     if (datasetSequence != null)
1019     {
1020       return false;
1021     }
1022     for (int i = 0; i < sequence.length; i++)
1023     {
1024       if (jalview.util.Comparison.isGap(sequence[i]))
1025       {
1026         return false;
1027       }
1028     }
1029     return true;
1030   }
1031
1032   @Override
1033   public SequenceI deriveSequence()
1034   {
1035     SequenceI seq = new Sequence(this);
1036     if (datasetSequence != null)
1037     {
1038       // duplicate current sequence with same dataset
1039       seq.setDatasetSequence(datasetSequence);
1040     }
1041     else
1042     {
1043       if (isValidDatasetSequence())
1044       {
1045         // Use this as dataset sequence
1046         seq.setDatasetSequence(this);
1047       }
1048       else
1049       {
1050         // Create a new, valid dataset sequence
1051         SequenceI ds = seq;
1052         ds.setSequence(AlignSeq.extractGaps(
1053                 jalview.util.Comparison.GapChars, new String(sequence)));
1054         setDatasetSequence(ds);
1055         ds.setSequenceFeatures(getSequenceFeatures());
1056         seq = this; // and return this sequence as the derived sequence.
1057       }
1058     }
1059     return seq;
1060   }
1061
1062   /*
1063    * (non-Javadoc)
1064    * 
1065    * @see jalview.datamodel.SequenceI#createDatasetSequence()
1066    */
1067   @Override
1068   public SequenceI createDatasetSequence()
1069   {
1070     if (datasetSequence == null)
1071     {
1072       datasetSequence = new Sequence(getName(), AlignSeq.extractGaps(
1073               jalview.util.Comparison.GapChars, getSequenceAsString()),
1074               getStart(), getEnd());
1075       datasetSequence.setSequenceFeatures(getSequenceFeatures());
1076       datasetSequence.setDescription(getDescription());
1077       setSequenceFeatures(null);
1078       // move database references onto dataset sequence
1079       datasetSequence.setDBRef(getDBRef());
1080       setDBRef(null);
1081       datasetSequence.setPDBId(getAllPDBEntries());
1082       setPDBId(null);
1083       datasetSequence.updatePDBIds();
1084       if (annotation != null)
1085       {
1086         for (AlignmentAnnotation aa : annotation)
1087         {
1088           AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1089           _aa.sequenceRef = datasetSequence;
1090           _aa.adjustForAlignment(); // uses annotation's own record of
1091                                     // sequence-column mapping
1092           datasetSequence.addAlignmentAnnotation(_aa);
1093         }
1094       }
1095     }
1096     return datasetSequence;
1097   }
1098
1099   /*
1100    * (non-Javadoc)
1101    * 
1102    * @see
1103    * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1104    * annotations)
1105    */
1106   @Override
1107   public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1108   {
1109     if (annotation != null)
1110     {
1111       annotation.removeAllElements();
1112     }
1113     if (annotations != null)
1114     {
1115       for (int i = 0; i < annotations.length; i++)
1116       {
1117         if (annotations[i] != null)
1118         {
1119           addAlignmentAnnotation(annotations[i]);
1120         }
1121       }
1122     }
1123   }
1124
1125   @Override
1126   public AlignmentAnnotation[] getAnnotation(String label)
1127   {
1128     if (annotation == null || annotation.size() == 0)
1129     {
1130       return null;
1131     }
1132
1133     Vector subset = new Vector();
1134     Enumeration e = annotation.elements();
1135     while (e.hasMoreElements())
1136     {
1137       AlignmentAnnotation ann = (AlignmentAnnotation) e.nextElement();
1138       if (ann.label != null && ann.label.equals(label))
1139       {
1140         subset.addElement(ann);
1141       }
1142     }
1143     if (subset.size() == 0)
1144     {
1145       return null;
1146     }
1147     AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1148     int i = 0;
1149     e = subset.elements();
1150     while (e.hasMoreElements())
1151     {
1152       anns[i++] = (AlignmentAnnotation) e.nextElement();
1153     }
1154     subset.removeAllElements();
1155     return anns;
1156   }
1157
1158   @Override
1159   public boolean updatePDBIds()
1160   {
1161     if (datasetSequence != null)
1162     {
1163       // TODO: could merge DBRefs
1164       return datasetSequence.updatePDBIds();
1165     }
1166     if (dbrefs == null || dbrefs.length == 0)
1167     {
1168       return false;
1169     }
1170     Vector newpdb = new Vector();
1171     for (int i = 0; i < dbrefs.length; i++)
1172     {
1173       if (DBRefSource.PDB.equals(dbrefs[i].getSource()))
1174       {
1175         PDBEntry pdbe = new PDBEntry();
1176         pdbe.setId(dbrefs[i].getAccessionId());
1177         if (pdbIds == null || pdbIds.size() == 0)
1178         {
1179           newpdb.addElement(pdbe);
1180         }
1181         else
1182         {
1183           Enumeration en = pdbIds.elements();
1184           boolean matched = false;
1185           while (!matched && en.hasMoreElements())
1186           {
1187             PDBEntry anentry = (PDBEntry) en.nextElement();
1188             if (anentry.getId().equals(pdbe.getId()))
1189             {
1190               matched = true;
1191             }
1192           }
1193           if (!matched)
1194           {
1195             newpdb.addElement(pdbe);
1196           }
1197         }
1198       }
1199     }
1200     if (newpdb.size() > 0)
1201     {
1202       Enumeration en = newpdb.elements();
1203       while (en.hasMoreElements())
1204       {
1205         addPDBId((PDBEntry) en.nextElement());
1206       }
1207       return true;
1208     }
1209     return false;
1210   }
1211
1212   @Override
1213   public void transferAnnotation(SequenceI entry, Mapping mp)
1214   {
1215     if (datasetSequence != null)
1216     {
1217       datasetSequence.transferAnnotation(entry, mp);
1218       return;
1219     }
1220     if (entry.getDatasetSequence() != null)
1221     {
1222       transferAnnotation(entry.getDatasetSequence(), mp);
1223       return;
1224     }
1225     // transfer any new features from entry onto sequence
1226     if (entry.getSequenceFeatures() != null)
1227     {
1228
1229       SequenceFeature[] sfs = entry.getSequenceFeatures();
1230       for (int si = 0; si < sfs.length; si++)
1231       {
1232         SequenceFeature sf[] = (mp != null) ? mp.locateFeature(sfs[si])
1233                 : new SequenceFeature[] { new SequenceFeature(sfs[si]) };
1234         if (sf != null && sf.length > 0)
1235         {
1236           for (int sfi = 0; sfi < sf.length; sfi++)
1237           {
1238             addSequenceFeature(sf[sfi]);
1239           }
1240         }
1241       }
1242     }
1243
1244     // transfer PDB entries
1245     if (entry.getAllPDBEntries() != null)
1246     {
1247       Enumeration e = entry.getAllPDBEntries().elements();
1248       while (e.hasMoreElements())
1249       {
1250         PDBEntry pdb = (PDBEntry) e.nextElement();
1251         addPDBId(pdb);
1252       }
1253     }
1254     // transfer database references
1255     DBRefEntry[] entryRefs = entry.getDBRef();
1256     if (entryRefs != null)
1257     {
1258       for (int r = 0; r < entryRefs.length; r++)
1259       {
1260         DBRefEntry newref = new DBRefEntry(entryRefs[r]);
1261         if (newref.getMap() != null && mp != null)
1262         {
1263           // remap ref using our local mapping
1264         }
1265         // we also assume all version string setting is done by dbSourceProxy
1266         /*
1267          * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1268          * newref.setSource(dbSource); }
1269          */
1270         addDBRef(newref);
1271       }
1272     }
1273   }
1274
1275   /**
1276    * @return The index (zero-based) on this sequence in the MSA. It returns
1277    *         {@code -1} if this information is not available.
1278    */
1279   @Override
1280   public int getIndex()
1281   {
1282     return index;
1283   }
1284
1285   /**
1286    * Defines the position of this sequence in the MSA. Use the value {@code -1}
1287    * if this information is undefined.
1288    * 
1289    * @param The
1290    *          position for this sequence. This value is zero-based (zero for
1291    *          this first sequence)
1292    */
1293   @Override
1294   public void setIndex(int value)
1295   {
1296     index = value;
1297   }
1298
1299   @Override
1300   public void setRNA(RNA r)
1301   {
1302     rna = r;
1303   }
1304
1305   @Override
1306   public RNA getRNA()
1307   {
1308     return rna;
1309   }
1310
1311   @Override
1312   public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1313           String label)
1314   {
1315     List<AlignmentAnnotation> result = new ArrayList<AlignmentAnnotation>();
1316     if (this.annotation != null)
1317     {
1318       for (AlignmentAnnotation ann : annotation)
1319       {
1320         if (ann.calcId != null && ann.calcId.equals(calcId)
1321                 && ann.label != null && ann.label.equals(label))
1322         {
1323           result.add(ann);
1324         }
1325       }
1326     }
1327     return result;
1328   }
1329
1330   @Override
1331   public String toString()
1332   {
1333     return getDisplayId(false);
1334   }
1335
1336   @Override
1337   public PDBEntry getPDBEntry(String pdbIdStr)
1338   {
1339     if (getDatasetSequence() == null
1340             || getDatasetSequence().getAllPDBEntries() == null)
1341     {
1342       return null;
1343     }
1344     List<PDBEntry> entries = getDatasetSequence().getAllPDBEntries();
1345     for (PDBEntry entry : entries)
1346     {
1347       if (entry.getId().equalsIgnoreCase(pdbIdStr))
1348       {
1349         return entry;
1350       }
1351     }
1352     return null;
1353   }
1354
1355 }