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