JAL-653 allow a dummy sequence to take on attributes from a fully instantiated sequen...
[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 java.util.ArrayList;
24 import java.util.Enumeration;
25 import java.util.List;
26 import java.util.Vector;
27
28 import fr.orsay.lri.varna.models.rna.RNA;
29
30 import jalview.analysis.AlignSeq;
31 import jalview.util.StringUtils;
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.getPDBId() != null)
263     {
264       Vector ids = seq.getPDBId();
265       Enumeration e = ids.elements();
266       while (e.hasMoreElements())
267       {
268         this.addPDBId(new PDBEntry((PDBEntry) e.nextElement()));
269       }
270     }
271   }
272
273   /**
274    * DOCUMENT ME!
275    * 
276    * @param v
277    *          DOCUMENT ME!
278    */
279   public void setSequenceFeatures(SequenceFeature[] features)
280   {
281     sequenceFeatures = features;
282   }
283
284   public synchronized void addSequenceFeature(SequenceFeature sf)
285   {
286     if (sequenceFeatures == null)
287     {
288       sequenceFeatures = new SequenceFeature[0];
289     }
290
291     for (int i = 0; i < sequenceFeatures.length; i++)
292     {
293       if (sequenceFeatures[i].equals(sf))
294       {
295         return;
296       }
297     }
298
299     SequenceFeature[] temp = new SequenceFeature[sequenceFeatures.length + 1];
300     System.arraycopy(sequenceFeatures, 0, temp, 0, sequenceFeatures.length);
301     temp[sequenceFeatures.length] = sf;
302
303     sequenceFeatures = temp;
304   }
305
306   public void deleteFeature(SequenceFeature sf)
307   {
308     if (sequenceFeatures == null)
309     {
310       return;
311     }
312
313     int index = 0;
314     for (index = 0; index < sequenceFeatures.length; index++)
315     {
316       if (sequenceFeatures[index].equals(sf))
317       {
318         break;
319       }
320     }
321
322     if (index == sequenceFeatures.length)
323     {
324       return;
325     }
326
327     int sfLength = sequenceFeatures.length;
328     if (sfLength < 2)
329     {
330       sequenceFeatures = null;
331     }
332     else
333     {
334       SequenceFeature[] temp = new SequenceFeature[sfLength - 1];
335       System.arraycopy(sequenceFeatures, 0, temp, 0, index);
336
337       if (index < sfLength)
338       {
339         System.arraycopy(sequenceFeatures, index + 1, temp, index,
340                 sequenceFeatures.length - index - 1);
341       }
342
343       sequenceFeatures = temp;
344     }
345   }
346
347   /**
348    * Returns the sequence features (if any), looking first on the sequence, then
349    * on its dataset sequence, and so on until a non-null value is found (or
350    * none). This supports retrieval of sequence features stored on the sequence
351    * (as in the applet) or on the dataset sequence (as in the Desktop version).
352    * 
353    * @return
354    */
355   public SequenceFeature[] getSequenceFeatures()
356   {
357     SequenceFeature[] features = sequenceFeatures;
358
359     SequenceI seq = this;
360     int count = 0; // failsafe against loop in sequence.datasetsequence...
361     while (features == null && seq.getDatasetSequence() != null
362             && count++ < 10)
363     {
364       seq = seq.getDatasetSequence();
365       features = ((Sequence) seq).sequenceFeatures;
366     }
367     return features;
368   }
369
370   public void addPDBId(PDBEntry entry)
371   {
372     if (pdbIds == null)
373     {
374       pdbIds = new Vector<PDBEntry>();
375     }
376     if (pdbIds.contains(entry))
377     {
378       updatePDBEntry(pdbIds.get(pdbIds.indexOf(entry)), entry);
379     }
380     else
381     {
382       pdbIds.addElement(entry);
383     }
384   }
385
386   private static void updatePDBEntry(PDBEntry oldEntry, PDBEntry newEntry)
387   {
388     if (newEntry.getFile() != null)
389     {
390       oldEntry.setFile(newEntry.getFile());
391     }
392   }
393
394   /**
395    * DOCUMENT ME!
396    * 
397    * @param id
398    *          DOCUMENT ME!
399    */
400   @Override
401   public void setPDBId(Vector<PDBEntry> id)
402   {
403     pdbIds = id;
404   }
405
406   /**
407    * DOCUMENT ME!
408    * 
409    * @return DOCUMENT ME!
410    */
411   @Override
412   public Vector<PDBEntry> getPDBId()
413   {
414     return pdbIds;
415   }
416
417   /**
418    * DOCUMENT ME!
419    * 
420    * @return DOCUMENT ME!
421    */
422   public String getDisplayId(boolean jvsuffix)
423   {
424     StringBuffer result = new StringBuffer(name);
425     if (jvsuffix)
426     {
427       result.append("/" + start + "-" + end);
428     }
429
430     return result.toString();
431   }
432
433   /**
434    * DOCUMENT ME!
435    * 
436    * @param name
437    *          DOCUMENT ME!
438    */
439   public void setName(String name)
440   {
441     this.name = name;
442     this.parseId();
443   }
444
445   /**
446    * DOCUMENT ME!
447    * 
448    * @return DOCUMENT ME!
449    */
450   public String getName()
451   {
452     return this.name;
453   }
454
455   /**
456    * DOCUMENT ME!
457    * 
458    * @param start
459    *          DOCUMENT ME!
460    */
461   public void setStart(int start)
462   {
463     this.start = start;
464   }
465
466   /**
467    * DOCUMENT ME!
468    * 
469    * @return DOCUMENT ME!
470    */
471   public int getStart()
472   {
473     return this.start;
474   }
475
476   /**
477    * DOCUMENT ME!
478    * 
479    * @param end
480    *          DOCUMENT ME!
481    */
482   public void setEnd(int end)
483   {
484     this.end = end;
485   }
486
487   /**
488    * DOCUMENT ME!
489    * 
490    * @return DOCUMENT ME!
491    */
492   public int getEnd()
493   {
494     return this.end;
495   }
496
497   /**
498    * DOCUMENT ME!
499    * 
500    * @return DOCUMENT ME!
501    */
502   public int getLength()
503   {
504     return this.sequence.length;
505   }
506
507   /**
508    * DOCUMENT ME!
509    * 
510    * @param seq
511    *          DOCUMENT ME!
512    */
513   public void setSequence(String seq)
514   {
515     this.sequence = seq.toCharArray();
516     checkValidRange();
517   }
518
519   public String getSequenceAsString()
520   {
521     return new String(sequence);
522   }
523
524   public String getSequenceAsString(int start, int end)
525   {
526     return new String(getSequence(start, end));
527   }
528
529   public char[] getSequence()
530   {
531     return sequence;
532   }
533
534   /*
535    * (non-Javadoc)
536    * 
537    * @see jalview.datamodel.SequenceI#getSequence(int, int)
538    */
539   public char[] getSequence(int start, int end)
540   {
541     if (start < 0)
542     {
543       start = 0;
544     }
545     // JBPNote - left to user to pad the result here (TODO:Decide on this
546     // policy)
547     if (start >= sequence.length)
548     {
549       return new char[0];
550     }
551
552     if (end >= sequence.length)
553     {
554       end = sequence.length;
555     }
556
557     char[] reply = new char[end - start];
558     System.arraycopy(sequence, start, reply, 0, end - start);
559
560     return reply;
561   }
562
563   @Override
564   public SequenceI getSubSequence(int start, int end)
565   {
566     if (start < 0)
567     {
568       start = 0;
569     }
570     char[] seq = getSequence(start, end);
571     if (seq.length == 0)
572     {
573       return null;
574     }
575     int nstart = findPosition(start);
576     int nend = findPosition(end) - 1;
577     // JBPNote - this is an incomplete copy.
578     SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
579     nseq.setDescription(description);
580     if (datasetSequence != null)
581     {
582       nseq.setDatasetSequence(datasetSequence);
583     }
584     else
585     {
586       nseq.setDatasetSequence(this);
587     }
588     return nseq;
589   }
590
591   /**
592    * DOCUMENT ME!
593    * 
594    * @param i
595    *          DOCUMENT ME!
596    * 
597    * @return DOCUMENT ME!
598    */
599   public char getCharAt(int i)
600   {
601     if (i < sequence.length)
602     {
603       return sequence[i];
604     }
605     else
606     {
607       return ' ';
608     }
609   }
610
611   /**
612    * DOCUMENT ME!
613    * 
614    * @param desc
615    *          DOCUMENT ME!
616    */
617   public void setDescription(String desc)
618   {
619     this.description = desc;
620   }
621
622   /**
623    * DOCUMENT ME!
624    * 
625    * @return DOCUMENT ME!
626    */
627   public String getDescription()
628   {
629     return this.description;
630   }
631
632   /*
633    * (non-Javadoc)
634    * 
635    * @see jalview.datamodel.SequenceI#findIndex(int)
636    */
637   public int findIndex(int pos)
638   {
639     // returns the alignment position for a residue
640     int j = start;
641     int i = 0;
642     // Rely on end being at least as long as the length of the sequence.
643     while ((i < sequence.length) && (j <= end) && (j <= pos))
644     {
645       if (!jalview.util.Comparison.isGap(sequence[i]))
646       {
647         j++;
648       }
649
650       i++;
651     }
652
653     if ((j == end) && (j < pos))
654     {
655       return end + 1;
656     }
657     else
658     {
659       return i;
660     }
661   }
662
663   @Override
664   public int findPosition(int i)
665   {
666     int j = 0;
667     int pos = start;
668     int seqlen = sequence.length;
669     while ((j < i) && (j < seqlen))
670     {
671       if (!jalview.util.Comparison.isGap(sequence[j]))
672       {
673         pos++;
674       }
675
676       j++;
677     }
678
679     return pos;
680   }
681
682   /**
683    * Returns an int array where indices correspond to each residue in the
684    * sequence and the element value gives its position in the alignment
685    * 
686    * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
687    *         residues in SequenceI object
688    */
689   public int[] gapMap()
690   {
691     String seq = jalview.analysis.AlignSeq.extractGaps(
692             jalview.util.Comparison.GapChars, new String(sequence));
693     int[] map = new int[seq.length()];
694     int j = 0;
695     int p = 0;
696
697     while (j < sequence.length)
698     {
699       if (!jalview.util.Comparison.isGap(sequence[j]))
700       {
701         map[p++] = j;
702       }
703
704       j++;
705     }
706
707     return map;
708   }
709
710   @Override
711   public int[] findPositionMap()
712   {
713     int map[] = new int[sequence.length];
714     int j = 0;
715     int pos = start;
716     int seqlen = sequence.length;
717     while ((j < seqlen))
718     {
719       map[j] = pos;
720       if (!jalview.util.Comparison.isGap(sequence[j]))
721       {
722         pos++;
723       }
724
725       j++;
726     }
727     return map;
728   }
729
730   @Override
731   public List<int[]> getInsertions()
732   {
733     ArrayList<int[]> map = new ArrayList<int[]>();
734     int lastj = -1, j = 0;
735     int pos = start;
736     int seqlen = sequence.length;
737     while ((j < seqlen))
738     {
739       if (jalview.util.Comparison.isGap(sequence[j]))
740       {
741         if (lastj == -1)
742         {
743           lastj = j;
744         }
745       }
746       else
747       {
748         if (lastj != -1)
749         {
750           map.add(new int[]
751           { lastj, j - 1 });
752           lastj = -1;
753         }
754       }
755       j++;
756     }
757     if (lastj != -1)
758     {
759       map.add(new int[]
760       { lastj, j - 1 });
761       lastj = -1;
762     }
763     return map;
764   }
765
766   @Override
767   public void deleteChars(int i, int j)
768   {
769     int newstart = start, newend = end;
770     if (i >= sequence.length)
771     {
772       return;
773     }
774
775     char[] tmp = StringUtils.deleteChars(sequence, i, j);
776     boolean createNewDs = false;
777     // TODO: take a (second look) at the dataset creation validation method for
778     // the very large sequence case
779     int eindex = -1, sindex = -1;
780     boolean ecalc = false, scalc = false;
781     for (int s = i; s < j; s++)
782     {
783       if (jalview.schemes.ResidueProperties.aaIndex[sequence[s]] != 23)
784       {
785         if (createNewDs)
786         {
787           newend--;
788         }
789         else
790         {
791           if (!scalc)
792           {
793             sindex = findIndex(start) - 1;
794             scalc = true;
795           }
796           if (sindex == s)
797           {
798             // delete characters including start of sequence
799             newstart = findPosition(j);
800             break; // don't need to search for any more residue characters.
801           }
802           else
803           {
804             // delete characters after start.
805             if (!ecalc)
806             {
807               eindex = findIndex(end) - 1;
808               ecalc = true;
809             }
810             if (eindex < j)
811             {
812               // delete characters at end of sequence
813               newend = findPosition(i - 1);
814               break; // don't need to search for any more residue characters.
815             }
816             else
817             {
818               createNewDs = true;
819               newend--; // decrease end position by one for the deleted residue
820               // and search further
821             }
822           }
823         }
824       }
825     }
826     // deletion occured in the middle of the sequence
827     if (createNewDs && this.datasetSequence != null)
828     {
829       // construct a new sequence
830       Sequence ds = new Sequence(datasetSequence);
831       // TODO: remove any non-inheritable properties ?
832       // TODO: create a sequence mapping (since there is a relation here ?)
833       ds.deleteChars(i, j);
834       datasetSequence = ds;
835     }
836     start = newstart;
837     end = newend;
838     sequence = tmp;
839   }
840
841   @Override
842   public void insertCharAt(int i, int length, char c)
843   {
844     char[] tmp = new char[sequence.length + length];
845
846     if (i >= sequence.length)
847     {
848       System.arraycopy(sequence, 0, tmp, 0, sequence.length);
849       i = sequence.length;
850     }
851     else
852     {
853       System.arraycopy(sequence, 0, tmp, 0, i);
854     }
855
856     int index = i;
857     while (length > 0)
858     {
859       tmp[index++] = c;
860       length--;
861     }
862
863     if (i < sequence.length)
864     {
865       System.arraycopy(sequence, i, tmp, index, sequence.length - i);
866     }
867
868     sequence = tmp;
869   }
870
871   @Override
872   public void insertCharAt(int i, char c)
873   {
874     insertCharAt(i, 1, c);
875   }
876
877   @Override
878   public String getVamsasId()
879   {
880     return vamsasId;
881   }
882
883   @Override
884   public void setVamsasId(String id)
885   {
886     vamsasId = id;
887   }
888
889   @Override
890   public void setDBRef(DBRefEntry[] dbref)
891   {
892     dbrefs = dbref;
893   }
894
895   @Override
896   public DBRefEntry[] getDBRef()
897   {
898     if (dbrefs == null && datasetSequence != null
899             && this != datasetSequence)
900     {
901       return datasetSequence.getDBRef();
902     }
903     return dbrefs;
904   }
905
906   @Override
907   public void addDBRef(DBRefEntry entry)
908   {
909     if (dbrefs == null)
910     {
911       dbrefs = new DBRefEntry[0];
912     }
913
914     int i, iSize = dbrefs.length;
915
916     for (i = 0; i < iSize; i++)
917     {
918       if (dbrefs[i].equalRef(entry))
919       {
920         if (entry.getMap() != null)
921         {
922           if (dbrefs[i].getMap() == null)
923           {
924             // overwrite with 'superior' entry that contains a mapping.
925             dbrefs[i] = entry;
926           }
927         }
928         return;
929       }
930     }
931
932     DBRefEntry[] temp = new DBRefEntry[iSize + 1];
933     System.arraycopy(dbrefs, 0, temp, 0, iSize);
934     temp[temp.length - 1] = entry;
935
936     dbrefs = temp;
937   }
938
939   @Override
940   public void setDatasetSequence(SequenceI seq)
941   {
942     datasetSequence = seq;
943   }
944
945   @Override
946   public SequenceI getDatasetSequence()
947   {
948     return datasetSequence;
949   }
950
951   @Override
952   public AlignmentAnnotation[] getAnnotation()
953   {
954     return annotation == null ? null : annotation
955             .toArray(new AlignmentAnnotation[annotation.size()]);
956   }
957
958
959   @Override
960   public boolean hasAnnotation(AlignmentAnnotation ann)
961   {
962     return annotation == null ? false : annotation.contains(ann);
963   }
964
965   @Override
966   public void addAlignmentAnnotation(AlignmentAnnotation annotation)
967   {
968     if (this.annotation == null)
969     {
970       this.annotation = new Vector<AlignmentAnnotation>();
971     }
972     if (!this.annotation.contains(annotation))
973     {
974       this.annotation.addElement(annotation);
975     }
976     annotation.setSequenceRef(this);
977   }
978
979   public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
980   {
981     if (this.annotation != null)
982     {
983       this.annotation.removeElement(annotation);
984       if (this.annotation.size() == 0)
985       {
986         this.annotation = null;
987       }
988     }
989   }
990
991   /**
992    * test if this is a valid candidate for another sequence's dataset sequence.
993    * 
994    */
995   private boolean isValidDatasetSequence()
996   {
997     if (datasetSequence != null)
998     {
999       return false;
1000     }
1001     for (int i = 0; i < sequence.length; i++)
1002     {
1003       if (jalview.util.Comparison.isGap(sequence[i]))
1004       {
1005         return false;
1006       }
1007     }
1008     return true;
1009   }
1010
1011   @Override
1012   public SequenceI deriveSequence()
1013   {
1014     SequenceI seq = new Sequence(this);
1015     if (datasetSequence != null)
1016     {
1017       // duplicate current sequence with same dataset
1018       seq.setDatasetSequence(datasetSequence);
1019     }
1020     else
1021     {
1022       if (isValidDatasetSequence())
1023       {
1024         // Use this as dataset sequence
1025         seq.setDatasetSequence(this);
1026       }
1027       else
1028       {
1029         // Create a new, valid dataset sequence
1030         SequenceI ds = seq;
1031         ds.setSequence(AlignSeq.extractGaps(
1032                 jalview.util.Comparison.GapChars, new String(sequence)));
1033         setDatasetSequence(ds);
1034         ds.setSequenceFeatures(getSequenceFeatures());
1035         seq = this; // and return this sequence as the derived sequence.
1036       }
1037     }
1038     return seq;
1039   }
1040
1041   /*
1042    * (non-Javadoc)
1043    * 
1044    * @see jalview.datamodel.SequenceI#createDatasetSequence()
1045    */
1046   public SequenceI createDatasetSequence()
1047   {
1048     if (datasetSequence == null)
1049     {
1050       datasetSequence = new Sequence(getName(), AlignSeq.extractGaps(
1051               jalview.util.Comparison.GapChars, getSequenceAsString()),
1052               getStart(), getEnd());
1053       datasetSequence.setSequenceFeatures(getSequenceFeatures());
1054       datasetSequence.setDescription(getDescription());
1055       setSequenceFeatures(null);
1056       // move database references onto dataset sequence
1057       datasetSequence.setDBRef(getDBRef());
1058       setDBRef(null);
1059       datasetSequence.setPDBId(getPDBId());
1060       setPDBId(null);
1061       datasetSequence.updatePDBIds();
1062       if (annotation != null)
1063       {
1064         for (AlignmentAnnotation aa : annotation)
1065         {
1066           AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1067           _aa.sequenceRef = datasetSequence;
1068           _aa.adjustForAlignment(); // uses annotation's own record of
1069                                     // sequence-column mapping
1070           datasetSequence.addAlignmentAnnotation(_aa);
1071         }
1072       }
1073     }
1074     return datasetSequence;
1075   }
1076
1077   /*
1078    * (non-Javadoc)
1079    * 
1080    * @see
1081    * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1082    * annotations)
1083    */
1084   public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1085   {
1086     if (annotation != null)
1087     {
1088       annotation.removeAllElements();
1089     }
1090     if (annotations != null)
1091     {
1092       for (int i = 0; i < annotations.length; i++)
1093       {
1094         if (annotations[i] != null)
1095         {
1096           addAlignmentAnnotation(annotations[i]);
1097         }
1098       }
1099     }
1100   }
1101
1102   @Override
1103   public AlignmentAnnotation[] getAnnotation(String label)
1104   {
1105     if (annotation == null || annotation.size() == 0)
1106     {
1107       return null;
1108     }
1109
1110     Vector subset = new Vector();
1111     Enumeration e = annotation.elements();
1112     while (e.hasMoreElements())
1113     {
1114       AlignmentAnnotation ann = (AlignmentAnnotation) e.nextElement();
1115       if (ann.label != null && ann.label.equals(label))
1116       {
1117         subset.addElement(ann);
1118       }
1119     }
1120     if (subset.size() == 0)
1121     {
1122       return null;
1123     }
1124     AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1125     int i = 0;
1126     e = subset.elements();
1127     while (e.hasMoreElements())
1128     {
1129       anns[i++] = (AlignmentAnnotation) e.nextElement();
1130     }
1131     subset.removeAllElements();
1132     return anns;
1133   }
1134
1135   @Override
1136   public boolean updatePDBIds()
1137   {
1138     if (datasetSequence != null)
1139     {
1140       // TODO: could merge DBRefs
1141       return datasetSequence.updatePDBIds();
1142     }
1143     if (dbrefs == null || dbrefs.length == 0)
1144     {
1145       return false;
1146     }
1147     Vector newpdb = new Vector();
1148     for (int i = 0; i < dbrefs.length; i++)
1149     {
1150       if (DBRefSource.PDB.equals(dbrefs[i].getSource()))
1151       {
1152         PDBEntry pdbe = new PDBEntry();
1153         pdbe.setId(dbrefs[i].getAccessionId());
1154         if (pdbIds == null || pdbIds.size() == 0)
1155         {
1156           newpdb.addElement(pdbe);
1157         }
1158         else
1159         {
1160           Enumeration en = pdbIds.elements();
1161           boolean matched = false;
1162           while (!matched && en.hasMoreElements())
1163           {
1164             PDBEntry anentry = (PDBEntry) en.nextElement();
1165             if (anentry.getId().equals(pdbe.getId()))
1166             {
1167               matched = true;
1168             }
1169           }
1170           if (!matched)
1171           {
1172             newpdb.addElement(pdbe);
1173           }
1174         }
1175       }
1176     }
1177     if (newpdb.size() > 0)
1178     {
1179       Enumeration en = newpdb.elements();
1180       while (en.hasMoreElements())
1181       {
1182         addPDBId((PDBEntry) en.nextElement());
1183       }
1184       return true;
1185     }
1186     return false;
1187   }
1188
1189   @Override
1190   public void transferAnnotation(SequenceI entry, Mapping mp)
1191   {
1192     if (datasetSequence != null)
1193     {
1194       datasetSequence.transferAnnotation(entry, mp);
1195       return;
1196     }
1197     if (entry.getDatasetSequence() != null)
1198     {
1199       transferAnnotation(entry.getDatasetSequence(), mp);
1200       return;
1201     }
1202     // transfer any new features from entry onto sequence
1203     if (entry.getSequenceFeatures() != null)
1204     {
1205
1206       SequenceFeature[] sfs = entry.getSequenceFeatures();
1207       for (int si = 0; si < sfs.length; si++)
1208       {
1209         SequenceFeature sf[] = (mp != null) ? mp.locateFeature(sfs[si])
1210                 : new SequenceFeature[]
1211                 { new SequenceFeature(sfs[si]) };
1212         if (sf != null && sf.length > 0)
1213         {
1214           for (int sfi = 0; sfi < sf.length; sfi++)
1215           {
1216             addSequenceFeature(sf[sfi]);
1217           }
1218         }
1219       }
1220     }
1221
1222     // transfer PDB entries
1223     if (entry.getPDBId() != null)
1224     {
1225       Enumeration e = entry.getPDBId().elements();
1226       while (e.hasMoreElements())
1227       {
1228         PDBEntry pdb = (PDBEntry) e.nextElement();
1229         addPDBId(pdb);
1230       }
1231     }
1232     // transfer database references
1233     DBRefEntry[] entryRefs = entry.getDBRef();
1234     if (entryRefs != null)
1235     {
1236       for (int r = 0; r < entryRefs.length; r++)
1237       {
1238         DBRefEntry newref = new DBRefEntry(entryRefs[r]);
1239         if (newref.getMap() != null && mp != null)
1240         {
1241           // remap ref using our local mapping
1242         }
1243         // we also assume all version string setting is done by dbSourceProxy
1244         /*
1245          * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1246          * newref.setSource(dbSource); }
1247          */
1248         addDBRef(newref);
1249       }
1250     }
1251   }
1252
1253   /**
1254    * @return The index (zero-based) on this sequence in the MSA. It returns
1255    *         {@code -1} if this information is not available.
1256    */
1257   public int getIndex()
1258   {
1259     return index;
1260   }
1261
1262   /**
1263    * Defines the position of this sequence in the MSA. Use the value {@code -1}
1264    * if this information is undefined.
1265    * 
1266    * @param The
1267    *          position for this sequence. This value is zero-based (zero for
1268    *          this first sequence)
1269    */
1270   public void setIndex(int value)
1271   {
1272     index = value;
1273   }
1274
1275   public void setRNA(RNA r)
1276   {
1277     rna = r;
1278   }
1279
1280   public RNA getRNA()
1281   {
1282     return rna;
1283   }
1284
1285   @Override
1286   public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1287           String label)
1288   {
1289     List<AlignmentAnnotation> result = new ArrayList<AlignmentAnnotation>();
1290     if (this.annotation != null)
1291     {
1292       for (AlignmentAnnotation ann : annotation)
1293       {
1294         if (ann.calcId != null && ann.calcId.equals(calcId)
1295                 && ann.label != null && ann.label.equals(label))
1296         {
1297           result.add(ann);
1298         }
1299       }
1300     }
1301     return result;
1302   }
1303
1304 }