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