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