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