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