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