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