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