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