JAL-1619 refactoring / tests to support 'align linked dna as protein'
[jalview.git] / src / jalview / datamodel / Sequence.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3  * Copyright (C) 2014 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 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 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     this.name = name;
94     this.sequence = sequence.toCharArray();
95     this.start = start;
96     this.end = end;
97     parseId();
98     checkValidRange();
99   }
100
101   public Sequence(String name, char[] sequence, int start, int end)
102   {
103     this.name = name;
104     this.sequence = sequence;
105     this.start = start;
106     this.end = end;
107     parseId();
108     checkValidRange();
109   }
110
111   com.stevesoft.pat.Regex limitrx = new com.stevesoft.pat.Regex(
112           "[/][0-9]{1,}[-][0-9]{1,}$");
113
114   com.stevesoft.pat.Regex endrx = new com.stevesoft.pat.Regex("[0-9]{1,}$");
115
116   void parseId()
117   {
118     if (name == null)
119     {
120       System.err
121               .println("POSSIBLE IMPLEMENTATION ERROR: null sequence name passed to constructor.");
122       name = "";
123     }
124     // Does sequence have the /start-end signiature?
125     if (limitrx.search(name))
126     {
127       name = limitrx.left();
128       endrx.search(limitrx.stringMatched());
129       setStart(Integer.parseInt(limitrx.stringMatched().substring(1,
130               endrx.matchedFrom() - 1)));
131       setEnd(Integer.parseInt(endrx.stringMatched()));
132     }
133   }
134
135   void checkValidRange()
136   {
137     // Note: JAL-774 :
138     // http://issues.jalview.org/browse/JAL-774?focusedCommentId=11239&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-11239
139     {
140       int endRes = 0;
141       for (int j = 0; j < sequence.length; j++)
142       {
143         if (!jalview.util.Comparison.isGap(sequence[j]))
144         {
145           endRes++;
146         }
147       }
148       if (endRes > 0)
149       {
150         endRes += start - 1;
151       }
152
153       if (end < endRes)
154       {
155         end = endRes;
156       }
157     }
158
159   }
160
161   /**
162    * Creates a new Sequence object.
163    * 
164    * @param name
165    *          DOCUMENT ME!
166    * @param sequence
167    *          DOCUMENT ME!
168    */
169   public Sequence(String name, String sequence)
170   {
171     this(name, sequence, 1, -1);
172   }
173
174   /**
175    * Creates a new Sequence object with new features, DBRefEntries,
176    * AlignmentAnnotations, and PDBIds but inherits any existing dataset sequence
177    * reference.
178    * 
179    * @param seq
180    *          DOCUMENT ME!
181    */
182   public Sequence(SequenceI seq)
183   {
184     this(seq, seq.getAnnotation());
185   }
186
187   /**
188    * Create a new sequence object with new features, DBRefEntries, and PDBIds
189    * but inherits any existing dataset sequence reference, and duplicate of any
190    * annotation that is present in the given annotation array.
191    * 
192    * @param seq
193    *          the sequence to be copied
194    * @param alAnnotation
195    *          an array of annotation including some associated with seq
196    */
197   public Sequence(SequenceI seq, AlignmentAnnotation[] alAnnotation)
198   {
199     this(seq.getName(), seq.getSequence(), seq.getStart(), seq.getEnd());
200     description = seq.getDescription();
201     if (seq.getSequenceFeatures() != null)
202     {
203       SequenceFeature[] sf = seq.getSequenceFeatures();
204       for (int i = 0; i < sf.length; i++)
205       {
206         addSequenceFeature(new SequenceFeature(sf[i]));
207       }
208     }
209     setDatasetSequence(seq.getDatasetSequence());
210     if (datasetSequence == null && seq.getDBRef() != null)
211     {
212       // only copy DBRefs if we really are a dataset sequence
213       DBRefEntry[] dbr = seq.getDBRef();
214       for (int i = 0; i < dbr.length; i++)
215       {
216         addDBRef(new DBRefEntry(dbr[i]));
217       }
218     }
219     if (seq.getAnnotation() != null)
220     {
221       AlignmentAnnotation[] sqann = seq.getAnnotation();
222       for (int i = 0; i < sqann.length; i++)
223       {
224         if (sqann[i] == null)
225         {
226           continue;
227         }
228         boolean found = (alAnnotation == null);
229         if (!found)
230         {
231           for (int apos = 0; !found && apos < alAnnotation.length; apos++)
232           {
233             found = (alAnnotation[apos] == sqann[i]);
234           }
235         }
236         if (found)
237         {
238           // only copy the given annotation
239           AlignmentAnnotation newann = new AlignmentAnnotation(sqann[i]);
240           addAlignmentAnnotation(newann);
241         }
242       }
243     }
244     if (seq.getPDBId() != null)
245     {
246       Vector ids = seq.getPDBId();
247       Enumeration e = ids.elements();
248       while (e.hasMoreElements())
249       {
250         this.addPDBId(new PDBEntry((PDBEntry) e.nextElement()));
251       }
252     }
253   }
254
255   /**
256    * DOCUMENT ME!
257    * 
258    * @param v
259    *          DOCUMENT ME!
260    */
261   public void setSequenceFeatures(SequenceFeature[] features)
262   {
263     sequenceFeatures = features;
264   }
265
266   public synchronized void addSequenceFeature(SequenceFeature sf)
267   {
268     if (sequenceFeatures == null)
269     {
270       sequenceFeatures = new SequenceFeature[0];
271     }
272
273     for (int i = 0; i < sequenceFeatures.length; i++)
274     {
275       if (sequenceFeatures[i].equals(sf))
276       {
277         return;
278       }
279     }
280
281     SequenceFeature[] temp = new SequenceFeature[sequenceFeatures.length + 1];
282     System.arraycopy(sequenceFeatures, 0, temp, 0, sequenceFeatures.length);
283     temp[sequenceFeatures.length] = sf;
284
285     sequenceFeatures = temp;
286   }
287
288   public void deleteFeature(SequenceFeature sf)
289   {
290     if (sequenceFeatures == null)
291     {
292       return;
293     }
294
295     int index = 0;
296     for (index = 0; index < sequenceFeatures.length; index++)
297     {
298       if (sequenceFeatures[index].equals(sf))
299       {
300         break;
301       }
302     }
303
304     if (index == sequenceFeatures.length)
305     {
306       return;
307     }
308
309     int sfLength = sequenceFeatures.length;
310     if (sfLength < 2)
311     {
312       sequenceFeatures = null;
313     }
314     else
315     {
316       SequenceFeature[] temp = new SequenceFeature[sfLength - 1];
317       System.arraycopy(sequenceFeatures, 0, temp, 0, index);
318
319       if (index < sfLength)
320       {
321         System.arraycopy(sequenceFeatures, index + 1, temp, index,
322                 sequenceFeatures.length - index - 1);
323       }
324
325       sequenceFeatures = temp;
326     }
327   }
328
329   /**
330    * DOCUMENT ME!
331    * 
332    * @return DOCUMENT ME!
333    */
334   public SequenceFeature[] getSequenceFeatures()
335   {
336     return sequenceFeatures;
337   }
338
339   public void addPDBId(PDBEntry entry)
340   {
341     if (pdbIds == null)
342     {
343       pdbIds = new Vector();
344     }
345     if (!pdbIds.contains(entry))
346     {
347       pdbIds.addElement(entry);
348     }
349   }
350
351   /**
352    * DOCUMENT ME!
353    * 
354    * @param id
355    *          DOCUMENT ME!
356    */
357   public void setPDBId(Vector id)
358   {
359     pdbIds = id;
360   }
361
362   /**
363    * DOCUMENT ME!
364    * 
365    * @return DOCUMENT ME!
366    */
367   public Vector getPDBId()
368   {
369     return pdbIds;
370   }
371
372   /**
373    * DOCUMENT ME!
374    * 
375    * @return DOCUMENT ME!
376    */
377   public String getDisplayId(boolean jvsuffix)
378   {
379     StringBuffer result = new StringBuffer(name);
380     if (jvsuffix)
381     {
382       result.append("/" + start + "-" + end);
383     }
384
385     return result.toString();
386   }
387
388   /**
389    * DOCUMENT ME!
390    * 
391    * @param name
392    *          DOCUMENT ME!
393    */
394   public void setName(String name)
395   {
396     this.name = name;
397     this.parseId();
398   }
399
400   /**
401    * DOCUMENT ME!
402    * 
403    * @return DOCUMENT ME!
404    */
405   public String getName()
406   {
407     return this.name;
408   }
409
410   /**
411    * DOCUMENT ME!
412    * 
413    * @param start
414    *          DOCUMENT ME!
415    */
416   public void setStart(int start)
417   {
418     this.start = start;
419   }
420
421   /**
422    * DOCUMENT ME!
423    * 
424    * @return DOCUMENT ME!
425    */
426   public int getStart()
427   {
428     return this.start;
429   }
430
431   /**
432    * DOCUMENT ME!
433    * 
434    * @param end
435    *          DOCUMENT ME!
436    */
437   public void setEnd(int end)
438   {
439     this.end = end;
440   }
441
442   /**
443    * DOCUMENT ME!
444    * 
445    * @return DOCUMENT ME!
446    */
447   public int getEnd()
448   {
449     return this.end;
450   }
451
452   /**
453    * DOCUMENT ME!
454    * 
455    * @return DOCUMENT ME!
456    */
457   public int getLength()
458   {
459     return this.sequence.length;
460   }
461
462   /**
463    * DOCUMENT ME!
464    * 
465    * @param seq
466    *          DOCUMENT ME!
467    */
468   public void setSequence(String seq)
469   {
470     this.sequence = seq.toCharArray();
471     checkValidRange();
472   }
473
474   public String getSequenceAsString()
475   {
476     return new String(sequence);
477   }
478
479   public String getSequenceAsString(int start, int end)
480   {
481     return new String(getSequence(start, end));
482   }
483
484   public char[] getSequence()
485   {
486     return sequence;
487   }
488
489   /*
490    * (non-Javadoc)
491    * 
492    * @see jalview.datamodel.SequenceI#getSequence(int, int)
493    */
494   public char[] getSequence(int start, int end)
495   {
496     if (start < 0)
497     {
498       start = 0;
499     }
500     // JBPNote - left to user to pad the result here (TODO:Decide on this
501     // policy)
502     if (start >= sequence.length)
503     {
504       return new char[0];
505     }
506
507     if (end >= sequence.length)
508     {
509       end = sequence.length;
510     }
511
512     char[] reply = new char[end - start];
513     System.arraycopy(sequence, start, reply, 0, end - start);
514
515     return reply;
516   }
517
518   @Override
519   public SequenceI getSubSequence(int start, int end)
520   {
521     if (start < 0)
522     {
523       start = 0;
524     }
525     char[] seq = getSequence(start, end);
526     if (seq.length == 0)
527     {
528       return null;
529     }
530     int nstart = findPosition(start);
531     int nend = findPosition(end) - 1;
532     // JBPNote - this is an incomplete copy.
533     SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
534     nseq.setDescription(description);
535     if (datasetSequence != null)
536     {
537       nseq.setDatasetSequence(datasetSequence);
538     }
539     else
540     {
541       nseq.setDatasetSequence(this);
542     }
543     return nseq;
544   }
545
546   /**
547    * DOCUMENT ME!
548    * 
549    * @param i
550    *          DOCUMENT ME!
551    * 
552    * @return DOCUMENT ME!
553    */
554   public char getCharAt(int i)
555   {
556     if (i < sequence.length)
557     {
558       return sequence[i];
559     }
560     else
561     {
562       return ' ';
563     }
564   }
565
566   /**
567    * DOCUMENT ME!
568    * 
569    * @param desc
570    *          DOCUMENT ME!
571    */
572   public void setDescription(String desc)
573   {
574     this.description = desc;
575   }
576
577   /**
578    * DOCUMENT ME!
579    * 
580    * @return DOCUMENT ME!
581    */
582   public String getDescription()
583   {
584     return this.description;
585   }
586
587   /*
588    * (non-Javadoc)
589    * 
590    * @see jalview.datamodel.SequenceI#findIndex(int)
591    */
592   public int findIndex(int pos)
593   {
594     // returns the alignment position for a residue
595     int j = start;
596     int i = 0;
597     // Rely on end being at least as long as the length of the sequence.
598     while ((i < sequence.length) && (j <= end) && (j <= pos))
599     {
600       if (!jalview.util.Comparison.isGap(sequence[i]))
601       {
602         j++;
603       }
604
605       i++;
606     }
607
608     if ((j == end) && (j < pos))
609     {
610       return end + 1;
611     }
612     else
613     {
614       return i;
615     }
616   }
617
618   /**
619    * Returns the (1-based) residue position for a (0-based) alignment position
620    * 
621    * @param i
622    *          column index in alignment (from 0..<length)
623    * 
624    * @return residue number for residue (left of and) nearest ith column
625    */
626   @Override
627   public int findPosition(int i)
628   {
629     int j = 0;
630     int pos = start;
631     int seqlen = sequence.length;
632     while ((j < i) && (j < seqlen))
633     {
634       if (!jalview.util.Comparison.isGap(sequence[j]))
635       {
636         pos++;
637       }
638
639       j++;
640     }
641
642     return pos;
643   }
644
645   /**
646    * Returns an int array where indices correspond to each residue in the
647    * sequence and the element value gives its position in the alignment
648    * 
649    * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
650    *         residues in SequenceI object
651    */
652   public int[] gapMap()
653   {
654     String seq = jalview.analysis.AlignSeq.extractGaps(
655             jalview.util.Comparison.GapChars, new String(sequence));
656     int[] map = new int[seq.length()];
657     int j = 0;
658     int p = 0;
659
660     while (j < sequence.length)
661     {
662       if (!jalview.util.Comparison.isGap(sequence[j]))
663       {
664         map[p++] = j;
665       }
666
667       j++;
668     }
669
670     return map;
671   }
672
673   /*
674    * (non-Javadoc)
675    * 
676    * @see jalview.datamodel.SequenceI#findPositionMap()
677    */
678   public int[] findPositionMap()
679   {
680     int map[] = new int[sequence.length];
681     int j = 0;
682     int pos = start;
683     int seqlen = sequence.length;
684     while ((j < seqlen))
685     {
686       map[j] = pos;
687       if (!jalview.util.Comparison.isGap(sequence[j]))
688       {
689         pos++;
690       }
691
692       j++;
693     }
694     return map;
695   }
696
697   /**
698    * Delete sequence characters from position 'from' (inclusive) to 'to'
699    * (exclusive). The end range is limited to the length of the sequence. If the
700    * start position is out of range, do nothing.
701    * 
702    * @see jalview.datamodel.SequenceI#deleteChars(int, int)
703    */
704   @Override
705   public void deleteChars(int from, int to)
706   {
707     if (from >= sequence.length)
708     {
709       return;
710     }
711     if (to > sequence.length)
712     {
713       to = sequence.length;
714     }
715     char[] tmp = StringUtils.deleteChars(sequence, from, to);
716
717     recreateDatasetAfterDeletions(from, to);
718     sequence = tmp;
719   }
720
721   /**
722    * Reconstruct the dataset sequence, if necessary, after deletion of columns
723    * in the aligned sequence.
724    * 
725    * @param from
726    *          start column of deletions (zero-based, inclusive)
727    * @param to
728    *          end column of deletions (exclusive)
729    */
730   protected boolean recreateDatasetAfterDeletions(int from, int to)
731   {
732     boolean created = false;
733     boolean createNewDs = false;
734     int newstart = start, newend = end;
735     // TODO: take a look at the new dataset creation validation method below -
736     // this could become time consuming for large sequences - consider making it
737     // more efficient
738     for (int s = from; s < to; s++)
739     {
740       if (jalview.schemes.ResidueProperties.aaIndex[sequence[s]] != 23)
741       {
742         if (createNewDs)
743         {
744           newend--;
745         }
746         else
747         {
748           int sindex = findIndex(start) - 1;
749           if (sindex == s)
750           {
751             // delete characters including start of sequence
752             newstart = findPosition(to);
753             break; // don't need to search for any more residue characters.
754           }
755           else
756           {
757             // delete characters after start.
758             int eindex = findIndex(end) - 1;
759             if (eindex < to)
760             {
761               // delete characters at end of sequence
762               newend = findPosition(from - 1);
763               break; // don't need to search for any more residue characters.
764             }
765             else
766             {
767               createNewDs = true;
768               newend--; // decrease end position by one for the deleted residue
769               // and search further
770             }
771           }
772         }
773       }
774     }
775     // deletion occured in the middle of the sequence
776     if (createNewDs && this.datasetSequence != null)
777     {
778       // construct a new sequence
779       Sequence ds = new Sequence(datasetSequence);
780       // TODO: remove any non-inheritable properties ?
781       // TODO: create a sequence mapping (since there is a relation here ?)
782       ds.deleteChars(from, to);
783       datasetSequence = ds;
784       created = true;
785     }
786     start = newstart;
787     end = newend;
788     return created;
789   }
790
791   @Override
792   public void insertCharAt(int i, char c)
793   {
794     insertCharAt(i, 1, c);
795   }
796
797   @Override
798   public void insertCharAt(int pos, int count, char c)
799   {
800     sequence = StringUtils.insertCharAt(sequence, pos, count, c);
801   }
802
803   public String getVamsasId()
804   {
805     return vamsasId;
806   }
807
808   public void setVamsasId(String id)
809   {
810     vamsasId = id;
811   }
812
813   public void setDBRef(DBRefEntry[] dbref)
814   {
815     dbrefs = dbref;
816   }
817
818   public DBRefEntry[] getDBRef()
819   {
820     if (dbrefs == null && datasetSequence != null
821             && this != datasetSequence)
822     {
823       return datasetSequence.getDBRef();
824     }
825     return dbrefs;
826   }
827
828   public void addDBRef(DBRefEntry entry)
829   {
830     if (dbrefs == null)
831     {
832       dbrefs = new DBRefEntry[0];
833     }
834
835     int i, iSize = dbrefs.length;
836
837     for (i = 0; i < iSize; i++)
838     {
839       if (dbrefs[i].equalRef(entry))
840       {
841         if (entry.getMap() != null)
842         {
843           if (dbrefs[i].getMap() == null)
844           {
845             // overwrite with 'superior' entry that contains a mapping.
846             dbrefs[i] = entry;
847           }
848         }
849         return;
850       }
851     }
852
853     DBRefEntry[] temp = new DBRefEntry[iSize + 1];
854     System.arraycopy(dbrefs, 0, temp, 0, iSize);
855     temp[temp.length - 1] = entry;
856
857     dbrefs = temp;
858   }
859
860   public void setDatasetSequence(SequenceI seq)
861   {
862     datasetSequence = seq;
863   }
864
865   public SequenceI getDatasetSequence()
866   {
867     return datasetSequence;
868   }
869
870   /**
871    * Returns a new array containing this sequence's annotations, or null.
872    */
873   public AlignmentAnnotation[] getAnnotation()
874   {
875     return annotation == null ? null : annotation
876             .toArray(new AlignmentAnnotation[annotation.size()]);
877   }
878
879   /**
880    * Returns true if this sequence has the given annotation (by object
881    * identity).
882    */
883   @Override
884   public boolean hasAnnotation(AlignmentAnnotation ann)
885   {
886     return annotation == null ? false : annotation.contains(ann);
887   }
888
889   /**
890    * Add the given annotation, if not already added, and set its sequence ref to
891    * be this sequence. Does nothing if this sequence's annotations already
892    * include this annotation (by identical object reference).
893    */
894   public void addAlignmentAnnotation(AlignmentAnnotation annotation)
895   {
896     if (this.annotation == null)
897     {
898       this.annotation = new Vector();
899     }
900     if (!this.annotation.contains(annotation))
901     {
902       this.annotation.addElement(annotation);
903     }
904     annotation.setSequenceRef(this);
905   }
906
907   public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
908   {
909     if (this.annotation != null)
910     {
911       this.annotation.removeElement(annotation);
912       if (this.annotation.size() == 0)
913       {
914         this.annotation = null;
915       }
916     }
917   }
918
919   /**
920    * test if this is a valid candidate for another sequence's dataset sequence.
921    * 
922    */
923   private boolean isValidDatasetSequence()
924   {
925     if (datasetSequence != null)
926     {
927       return false;
928     }
929     for (int i = 0; i < sequence.length; i++)
930     {
931       if (jalview.util.Comparison.isGap(sequence[i]))
932       {
933         return false;
934       }
935     }
936     return true;
937   }
938
939   /*
940    * (non-Javadoc)
941    * 
942    * @see jalview.datamodel.SequenceI#deriveSequence()
943    */
944   public SequenceI deriveSequence()
945   {
946     SequenceI seq = new Sequence(this);
947     if (datasetSequence != null)
948     {
949       // duplicate current sequence with same dataset
950       seq.setDatasetSequence(datasetSequence);
951     }
952     else
953     {
954       if (isValidDatasetSequence())
955       {
956         // Use this as dataset sequence
957         seq.setDatasetSequence(this);
958       }
959       else
960       {
961         // Create a new, valid dataset sequence
962         SequenceI ds = seq;
963         ds.setSequence(AlignSeq.extractGaps(
964                 jalview.util.Comparison.GapChars, new String(sequence)));
965         setDatasetSequence(ds);
966         ds.setSequenceFeatures(getSequenceFeatures());
967         seq = this; // and return this sequence as the derived sequence.
968       }
969     }
970     return seq;
971   }
972
973   /*
974    * (non-Javadoc)
975    * 
976    * @see jalview.datamodel.SequenceI#createDatasetSequence()
977    */
978   public SequenceI createDatasetSequence()
979   {
980     if (datasetSequence == null)
981     {
982       datasetSequence = new Sequence(getName(), AlignSeq.extractGaps(
983               jalview.util.Comparison.GapChars, getSequenceAsString()),
984               getStart(), getEnd());
985       datasetSequence.setSequenceFeatures(getSequenceFeatures());
986       datasetSequence.setDescription(getDescription());
987       setSequenceFeatures(null);
988       // move database references onto dataset sequence
989       datasetSequence.setDBRef(getDBRef());
990       setDBRef(null);
991       datasetSequence.setPDBId(getPDBId());
992       setPDBId(null);
993       datasetSequence.updatePDBIds();
994       if (annotation != null)
995       {
996         for (AlignmentAnnotation aa : annotation)
997         {
998           AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
999           _aa.sequenceRef = datasetSequence;
1000           _aa.adjustForAlignment(); // uses annotation's own record of
1001                                     // sequence-column mapping
1002           datasetSequence.addAlignmentAnnotation(_aa);
1003         }
1004       }
1005     }
1006     return datasetSequence;
1007   }
1008
1009   /*
1010    * (non-Javadoc)
1011    * 
1012    * @see
1013    * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1014    * annotations)
1015    */
1016   public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1017   {
1018     if (annotation != null)
1019     {
1020       annotation.removeAllElements();
1021     }
1022     if (annotations != null)
1023     {
1024       for (int i = 0; i < annotations.length; i++)
1025       {
1026         if (annotations[i] != null)
1027         {
1028           addAlignmentAnnotation(annotations[i]);
1029         }
1030       }
1031     }
1032   }
1033
1034   /*
1035    * (non-Javadoc)
1036    * 
1037    * @see jalview.datamodel.SequenceI#getAnnotation(java.lang.String)
1038    */
1039   public AlignmentAnnotation[] getAnnotation(String label)
1040   {
1041     if (annotation == null || annotation.size() == 0)
1042     {
1043       return null;
1044     }
1045
1046     Vector subset = new Vector();
1047     Enumeration e = annotation.elements();
1048     while (e.hasMoreElements())
1049     {
1050       AlignmentAnnotation ann = (AlignmentAnnotation) e.nextElement();
1051       if (ann.label != null && ann.label.equals(label))
1052       {
1053         subset.addElement(ann);
1054       }
1055     }
1056     if (subset.size() == 0)
1057     {
1058       return null;
1059     }
1060     AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1061     int i = 0;
1062     e = subset.elements();
1063     while (e.hasMoreElements())
1064     {
1065       anns[i++] = (AlignmentAnnotation) e.nextElement();
1066     }
1067     subset.removeAllElements();
1068     return anns;
1069   }
1070
1071   public boolean updatePDBIds()
1072   {
1073     if (datasetSequence != null)
1074     {
1075       // TODO: could merge DBRefs
1076       return datasetSequence.updatePDBIds();
1077     }
1078     if (dbrefs == null || dbrefs.length == 0)
1079     {
1080       return false;
1081     }
1082     Vector newpdb = new Vector();
1083     for (int i = 0; i < dbrefs.length; i++)
1084     {
1085       if (DBRefSource.PDB.equals(dbrefs[i].getSource()))
1086       {
1087         PDBEntry pdbe = new PDBEntry();
1088         pdbe.setId(dbrefs[i].getAccessionId());
1089         if (pdbIds == null || pdbIds.size() == 0)
1090         {
1091           newpdb.addElement(pdbe);
1092         }
1093         else
1094         {
1095           Enumeration en = pdbIds.elements();
1096           boolean matched = false;
1097           while (!matched && en.hasMoreElements())
1098           {
1099             PDBEntry anentry = (PDBEntry) en.nextElement();
1100             if (anentry.getId().equals(pdbe.getId()))
1101             {
1102               matched = true;
1103             }
1104           }
1105           if (!matched)
1106           {
1107             newpdb.addElement(pdbe);
1108           }
1109         }
1110       }
1111     }
1112     if (newpdb.size() > 0)
1113     {
1114       Enumeration en = newpdb.elements();
1115       while (en.hasMoreElements())
1116       {
1117         addPDBId((PDBEntry) en.nextElement());
1118       }
1119       return true;
1120     }
1121     return false;
1122   }
1123
1124   /*
1125    * (non-Javadoc)
1126    * 
1127    * @see
1128    * jalview.datamodel.SequenceI#transferAnnotation(jalview.datamodel.SequenceI,
1129    * jalview.datamodel.Mapping)
1130    */
1131   public void transferAnnotation(SequenceI entry, Mapping mp)
1132   {
1133     if (datasetSequence != null)
1134     {
1135       datasetSequence.transferAnnotation(entry, mp);
1136       return;
1137     }
1138     if (entry.getDatasetSequence() != null)
1139     {
1140       transferAnnotation(entry.getDatasetSequence(), mp);
1141       return;
1142     }
1143     // transfer any new features from entry onto sequence
1144     if (entry.getSequenceFeatures() != null)
1145     {
1146
1147       SequenceFeature[] sfs = entry.getSequenceFeatures();
1148       for (int si = 0; si < sfs.length; si++)
1149       {
1150         SequenceFeature sf[] = (mp != null) ? mp.locateFeature(sfs[si])
1151                 : new SequenceFeature[]
1152                 { new SequenceFeature(sfs[si]) };
1153         if (sf != null && sf.length > 0)
1154         {
1155           for (int sfi = 0; sfi < sf.length; sfi++)
1156           {
1157             addSequenceFeature(sf[sfi]);
1158           }
1159         }
1160       }
1161     }
1162
1163     // transfer PDB entries
1164     if (entry.getPDBId() != null)
1165     {
1166       Enumeration e = entry.getPDBId().elements();
1167       while (e.hasMoreElements())
1168       {
1169         PDBEntry pdb = (PDBEntry) e.nextElement();
1170         addPDBId(pdb);
1171       }
1172     }
1173     // transfer database references
1174     DBRefEntry[] entryRefs = entry.getDBRef();
1175     if (entryRefs != null)
1176     {
1177       for (int r = 0; r < entryRefs.length; r++)
1178       {
1179         DBRefEntry newref = new DBRefEntry(entryRefs[r]);
1180         if (newref.getMap() != null && mp != null)
1181         {
1182           // remap ref using our local mapping
1183         }
1184         // we also assume all version string setting is done by dbSourceProxy
1185         /*
1186          * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1187          * newref.setSource(dbSource); }
1188          */
1189         addDBRef(newref);
1190       }
1191     }
1192   }
1193
1194   /**
1195    * @return The index (zero-based) on this sequence in the MSA. It returns
1196    *         {@code -1} if this information is not available.
1197    */
1198   public int getIndex()
1199   {
1200     return index;
1201   }
1202
1203   /**
1204    * Defines the position of this sequence in the MSA. Use the value {@code -1}
1205    * if this information is undefined.
1206    * 
1207    * @param The
1208    *          position for this sequence. This value is zero-based (zero for
1209    *          this first sequence)
1210    */
1211   public void setIndex(int value)
1212   {
1213     index = value;
1214   }
1215
1216   public void setRNA(RNA r)
1217   {
1218     rna = r;
1219   }
1220
1221   public RNA getRNA()
1222   {
1223     return rna;
1224   }
1225
1226   /**
1227    * Returns a (possibly empty) list of any annotations that match on given
1228    * calcId (source) and label (type). Null values do not match.
1229    * 
1230    * @param calcId
1231    * @param label
1232    */
1233   @Override
1234   public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1235           String label)
1236   {
1237     List<AlignmentAnnotation> result = new ArrayList<AlignmentAnnotation>();
1238     if (this.annotation != null)
1239     {
1240       for (AlignmentAnnotation ann : annotation)
1241       {
1242         if (ann.calcId != null && ann.calcId.equals(calcId)
1243                 && ann.label != null && ann.label.equals(label))
1244         {
1245           result.add(ann);
1246         }
1247       }
1248     }
1249     return result;
1250   }
1251
1252 }