JAL-2490 findFeaturesAtRes with performant feature lookup
[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 datasetSequence != null ? datasetSequence.getFeatures()
433             : sequenceFeatureStore;
434   }
435
436   @Override
437   public boolean addPDBId(PDBEntry entry)
438   {
439     if (pdbIds == null)
440     {
441       pdbIds = new Vector<PDBEntry>();
442       pdbIds.add(entry);
443       return true;
444     }
445
446     for (PDBEntry pdbe : pdbIds)
447     {
448       if (pdbe.updateFrom(entry))
449       {
450         return false;
451       }
452     }
453     pdbIds.addElement(entry);
454     return true;
455   }
456
457   /**
458    * DOCUMENT ME!
459    * 
460    * @param id
461    *          DOCUMENT ME!
462    */
463   @Override
464   public void setPDBId(Vector<PDBEntry> id)
465   {
466     pdbIds = id;
467   }
468
469   /**
470    * DOCUMENT ME!
471    * 
472    * @return DOCUMENT ME!
473    */
474   @Override
475   public Vector<PDBEntry> getAllPDBEntries()
476   {
477     return pdbIds == null ? new Vector<PDBEntry>() : pdbIds;
478   }
479
480   /**
481    * DOCUMENT ME!
482    * 
483    * @return DOCUMENT ME!
484    */
485   @Override
486   public String getDisplayId(boolean jvsuffix)
487   {
488     StringBuffer result = new StringBuffer(name);
489     if (jvsuffix)
490     {
491       result.append("/" + start + "-" + end);
492     }
493
494     return result.toString();
495   }
496
497   /**
498    * DOCUMENT ME!
499    * 
500    * @param name
501    *          DOCUMENT ME!
502    */
503   @Override
504   public void setName(String name)
505   {
506     this.name = name;
507     this.parseId();
508   }
509
510   /**
511    * DOCUMENT ME!
512    * 
513    * @return DOCUMENT ME!
514    */
515   @Override
516   public String getName()
517   {
518     return this.name;
519   }
520
521   /**
522    * DOCUMENT ME!
523    * 
524    * @param start
525    *          DOCUMENT ME!
526    */
527   @Override
528   public void setStart(int start)
529   {
530     this.start = start;
531   }
532
533   /**
534    * DOCUMENT ME!
535    * 
536    * @return DOCUMENT ME!
537    */
538   @Override
539   public int getStart()
540   {
541     return this.start;
542   }
543
544   /**
545    * DOCUMENT ME!
546    * 
547    * @param end
548    *          DOCUMENT ME!
549    */
550   @Override
551   public void setEnd(int end)
552   {
553     this.end = end;
554   }
555
556   /**
557    * DOCUMENT ME!
558    * 
559    * @return DOCUMENT ME!
560    */
561   @Override
562   public int getEnd()
563   {
564     return this.end;
565   }
566
567   /**
568    * DOCUMENT ME!
569    * 
570    * @return DOCUMENT ME!
571    */
572   @Override
573   public int getLength()
574   {
575     return this.sequence.length;
576   }
577
578   /**
579    * DOCUMENT ME!
580    * 
581    * @param seq
582    *          DOCUMENT ME!
583    */
584   @Override
585   public void setSequence(String seq)
586   {
587     this.sequence = seq.toCharArray();
588     checkValidRange();
589   }
590
591   @Override
592   public String getSequenceAsString()
593   {
594     return new String(sequence);
595   }
596
597   @Override
598   public String getSequenceAsString(int start, int end)
599   {
600     return new String(getSequence(start, end));
601   }
602
603   @Override
604   public char[] getSequence()
605   {
606     return sequence;
607   }
608
609   /*
610    * (non-Javadoc)
611    * 
612    * @see jalview.datamodel.SequenceI#getSequence(int, int)
613    */
614   @Override
615   public char[] getSequence(int start, int end)
616   {
617     if (start < 0)
618     {
619       start = 0;
620     }
621     // JBPNote - left to user to pad the result here (TODO:Decide on this
622     // policy)
623     if (start >= sequence.length)
624     {
625       return new char[0];
626     }
627
628     if (end >= sequence.length)
629     {
630       end = sequence.length;
631     }
632
633     char[] reply = new char[end - start];
634     System.arraycopy(sequence, start, reply, 0, end - start);
635
636     return reply;
637   }
638
639   @Override
640   public SequenceI getSubSequence(int start, int end)
641   {
642     if (start < 0)
643     {
644       start = 0;
645     }
646     char[] seq = getSequence(start, end);
647     if (seq.length == 0)
648     {
649       return null;
650     }
651     int nstart = findPosition(start);
652     int nend = findPosition(end) - 1;
653     // JBPNote - this is an incomplete copy.
654     SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
655     nseq.setDescription(description);
656     if (datasetSequence != null)
657     {
658       nseq.setDatasetSequence(datasetSequence);
659     }
660     else
661     {
662       nseq.setDatasetSequence(this);
663     }
664     return nseq;
665   }
666
667   /**
668    * Returns the character of the aligned sequence at the given position (base
669    * zero), or space if the position is not within the sequence's bounds
670    * 
671    * @return
672    */
673   @Override
674   public char getCharAt(int i)
675   {
676     if (i >= 0 && i < sequence.length)
677     {
678       return sequence[i];
679     }
680     else
681     {
682       return ' ';
683     }
684   }
685
686   /**
687    * DOCUMENT ME!
688    * 
689    * @param desc
690    *          DOCUMENT ME!
691    */
692   @Override
693   public void setDescription(String desc)
694   {
695     this.description = desc;
696   }
697
698   /**
699    * DOCUMENT ME!
700    * 
701    * @return DOCUMENT ME!
702    */
703   @Override
704   public String getDescription()
705   {
706     return this.description;
707   }
708
709   /*
710    * (non-Javadoc)
711    * 
712    * @see jalview.datamodel.SequenceI#findIndex(int)
713    */
714   @Override
715   public int findIndex(int pos)
716   {
717     // returns the alignment position for a residue
718     int j = start;
719     int i = 0;
720     // Rely on end being at least as long as the length of the sequence.
721     while ((i < sequence.length) && (j <= end) && (j <= pos))
722     {
723       if (!jalview.util.Comparison.isGap(sequence[i]))
724       {
725         j++;
726       }
727
728       i++;
729     }
730
731     if ((j == end) && (j < pos))
732     {
733       return end + 1;
734     }
735     else
736     {
737       return i;
738     }
739   }
740
741   @Override
742   public int findPosition(int i)
743   {
744     int j = 0;
745     int pos = start;
746     int seqlen = sequence.length;
747     while ((j < i) && (j < seqlen))
748     {
749       if (!jalview.util.Comparison.isGap(sequence[j]))
750       {
751         pos++;
752       }
753
754       j++;
755     }
756
757     return pos;
758   }
759
760   /**
761    * Returns an int array where indices correspond to each residue in the
762    * sequence and the element value gives its position in the alignment
763    * 
764    * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
765    *         residues in SequenceI object
766    */
767   @Override
768   public int[] gapMap()
769   {
770     String seq = jalview.analysis.AlignSeq.extractGaps(
771             jalview.util.Comparison.GapChars, new String(sequence));
772     int[] map = new int[seq.length()];
773     int j = 0;
774     int p = 0;
775
776     while (j < sequence.length)
777     {
778       if (!jalview.util.Comparison.isGap(sequence[j]))
779       {
780         map[p++] = j;
781       }
782
783       j++;
784     }
785
786     return map;
787   }
788
789   @Override
790   public int[] findPositionMap()
791   {
792     int map[] = new int[sequence.length];
793     int j = 0;
794     int pos = start;
795     int seqlen = sequence.length;
796     while ((j < seqlen))
797     {
798       map[j] = pos;
799       if (!jalview.util.Comparison.isGap(sequence[j]))
800       {
801         pos++;
802       }
803
804       j++;
805     }
806     return map;
807   }
808
809   @Override
810   public List<int[]> getInsertions()
811   {
812     ArrayList<int[]> map = new ArrayList<int[]>();
813     int lastj = -1, j = 0;
814     int pos = start;
815     int seqlen = sequence.length;
816     while ((j < seqlen))
817     {
818       if (jalview.util.Comparison.isGap(sequence[j]))
819       {
820         if (lastj == -1)
821         {
822           lastj = j;
823         }
824       }
825       else
826       {
827         if (lastj != -1)
828         {
829           map.add(new int[] { lastj, j - 1 });
830           lastj = -1;
831         }
832       }
833       j++;
834     }
835     if (lastj != -1)
836     {
837       map.add(new int[] { lastj, j - 1 });
838       lastj = -1;
839     }
840     return map;
841   }
842
843   @Override
844   public void deleteChars(int i, int j)
845   {
846     int newstart = start, newend = end;
847     if (i >= sequence.length || i < 0)
848     {
849       return;
850     }
851
852     char[] tmp = StringUtils.deleteChars(sequence, i, j);
853     boolean createNewDs = false;
854     // TODO: take a (second look) at the dataset creation validation method for
855     // the very large sequence case
856     int eindex = -1, sindex = -1;
857     boolean ecalc = false, scalc = false;
858     for (int s = i; s < j; s++)
859     {
860       if (jalview.schemes.ResidueProperties.aaIndex[sequence[s]] != 23)
861       {
862         if (createNewDs)
863         {
864           newend--;
865         }
866         else
867         {
868           if (!scalc)
869           {
870             sindex = findIndex(start) - 1;
871             scalc = true;
872           }
873           if (sindex == s)
874           {
875             // delete characters including start of sequence
876             newstart = findPosition(j);
877             break; // don't need to search for any more residue characters.
878           }
879           else
880           {
881             // delete characters after start.
882             if (!ecalc)
883             {
884               eindex = findIndex(end) - 1;
885               ecalc = true;
886             }
887             if (eindex < j)
888             {
889               // delete characters at end of sequence
890               newend = findPosition(i - 1);
891               break; // don't need to search for any more residue characters.
892             }
893             else
894             {
895               createNewDs = true;
896               newend--; // decrease end position by one for the deleted residue
897               // and search further
898             }
899           }
900         }
901       }
902     }
903     // deletion occured in the middle of the sequence
904     if (createNewDs && this.datasetSequence != null)
905     {
906       // construct a new sequence
907       Sequence ds = new Sequence(datasetSequence);
908       // TODO: remove any non-inheritable properties ?
909       // TODO: create a sequence mapping (since there is a relation here ?)
910       ds.deleteChars(i, j);
911       datasetSequence = ds;
912     }
913     start = newstart;
914     end = newend;
915     sequence = tmp;
916   }
917
918   @Override
919   public void insertCharAt(int i, int length, char c)
920   {
921     char[] tmp = new char[sequence.length + length];
922
923     if (i >= sequence.length)
924     {
925       System.arraycopy(sequence, 0, tmp, 0, sequence.length);
926       i = sequence.length;
927     }
928     else
929     {
930       System.arraycopy(sequence, 0, tmp, 0, i);
931     }
932
933     int index = i;
934     while (length > 0)
935     {
936       tmp[index++] = c;
937       length--;
938     }
939
940     if (i < sequence.length)
941     {
942       System.arraycopy(sequence, i, tmp, index, sequence.length - i);
943     }
944
945     sequence = tmp;
946   }
947
948   @Override
949   public void insertCharAt(int i, char c)
950   {
951     insertCharAt(i, 1, c);
952   }
953
954   @Override
955   public String getVamsasId()
956   {
957     return vamsasId;
958   }
959
960   @Override
961   public void setVamsasId(String id)
962   {
963     vamsasId = id;
964   }
965
966   @Override
967   public void setDBRefs(DBRefEntry[] dbref)
968   {
969     if (dbrefs == null && datasetSequence != null
970             && this != datasetSequence)
971     {
972       datasetSequence.setDBRefs(dbref);
973       return;
974     }
975     dbrefs = dbref;
976     if (dbrefs != null)
977     {
978       DBRefUtils.ensurePrimaries(this);
979     }
980   }
981
982   @Override
983   public DBRefEntry[] getDBRefs()
984   {
985     if (dbrefs == null && datasetSequence != null
986             && this != datasetSequence)
987     {
988       return datasetSequence.getDBRefs();
989     }
990     return dbrefs;
991   }
992
993   @Override
994   public void addDBRef(DBRefEntry entry)
995   {
996     if (datasetSequence != null)
997     {
998       datasetSequence.addDBRef(entry);
999       return;
1000     }
1001
1002     if (dbrefs == null)
1003     {
1004       dbrefs = new DBRefEntry[0];
1005     }
1006
1007     for (DBRefEntryI dbr : dbrefs)
1008     {
1009       if (dbr.updateFrom(entry))
1010       {
1011         /*
1012          * found a dbref that either matched, or could be
1013          * updated from, the new entry - no need to add it
1014          */
1015         return;
1016       }
1017     }
1018
1019     /*
1020      * extend the array to make room for one more
1021      */
1022     // TODO use an ArrayList instead
1023     int j = dbrefs.length;
1024     DBRefEntry[] temp = new DBRefEntry[j + 1];
1025     System.arraycopy(dbrefs, 0, temp, 0, j);
1026     temp[temp.length - 1] = entry;
1027
1028     dbrefs = temp;
1029
1030     DBRefUtils.ensurePrimaries(this);
1031   }
1032
1033   @Override
1034   public void setDatasetSequence(SequenceI seq)
1035   {
1036     if (seq == this)
1037     {
1038       throw new IllegalArgumentException(
1039               "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1040     }
1041     if (seq != null && seq.getDatasetSequence() != null)
1042     {
1043       throw new IllegalArgumentException(
1044               "Implementation error: cascading dataset sequences are not allowed.");
1045     }
1046     datasetSequence = seq;
1047   }
1048
1049   @Override
1050   public SequenceI getDatasetSequence()
1051   {
1052     return datasetSequence;
1053   }
1054
1055   @Override
1056   public AlignmentAnnotation[] getAnnotation()
1057   {
1058     return annotation == null ? null : annotation
1059             .toArray(new AlignmentAnnotation[annotation.size()]);
1060   }
1061
1062   @Override
1063   public boolean hasAnnotation(AlignmentAnnotation ann)
1064   {
1065     return annotation == null ? false : annotation.contains(ann);
1066   }
1067
1068   @Override
1069   public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1070   {
1071     if (this.annotation == null)
1072     {
1073       this.annotation = new Vector<AlignmentAnnotation>();
1074     }
1075     if (!this.annotation.contains(annotation))
1076     {
1077       this.annotation.addElement(annotation);
1078     }
1079     annotation.setSequenceRef(this);
1080   }
1081
1082   @Override
1083   public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1084   {
1085     if (this.annotation != null)
1086     {
1087       this.annotation.removeElement(annotation);
1088       if (this.annotation.size() == 0)
1089       {
1090         this.annotation = null;
1091       }
1092     }
1093   }
1094
1095   /**
1096    * test if this is a valid candidate for another sequence's dataset sequence.
1097    * 
1098    */
1099   private boolean isValidDatasetSequence()
1100   {
1101     if (datasetSequence != null)
1102     {
1103       return false;
1104     }
1105     for (int i = 0; i < sequence.length; i++)
1106     {
1107       if (jalview.util.Comparison.isGap(sequence[i]))
1108       {
1109         return false;
1110       }
1111     }
1112     return true;
1113   }
1114
1115   @Override
1116   public SequenceI deriveSequence()
1117   {
1118     Sequence seq = null;
1119     if (datasetSequence == null)
1120     {
1121       if (isValidDatasetSequence())
1122       {
1123         // Use this as dataset sequence
1124         seq = new Sequence(getName(), "", 1, -1);
1125         seq.setDatasetSequence(this);
1126         seq.initSeqFrom(this, getAnnotation());
1127         return seq;
1128       }
1129       else
1130       {
1131         // Create a new, valid dataset sequence
1132         createDatasetSequence();
1133       }
1134     }
1135     return new Sequence(this);
1136   }
1137
1138   private boolean _isNa;
1139
1140   private long _seqhash = 0;
1141
1142   /**
1143    * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1144    * true
1145    */
1146   @Override
1147   public boolean isProtein()
1148   {
1149     if (datasetSequence != null)
1150     {
1151       return datasetSequence.isProtein();
1152     }
1153     if (_seqhash != sequence.hashCode())
1154     {
1155       _seqhash = sequence.hashCode();
1156       _isNa = Comparison.isNucleotide(this);
1157     }
1158     return !_isNa;
1159   };
1160
1161   /*
1162    * (non-Javadoc)
1163    * 
1164    * @see jalview.datamodel.SequenceI#createDatasetSequence()
1165    */
1166   @Override
1167   public SequenceI createDatasetSequence()
1168   {
1169     if (datasetSequence == null)
1170     {
1171       Sequence dsseq = new Sequence(getName(), AlignSeq.extractGaps(
1172               jalview.util.Comparison.GapChars, getSequenceAsString()),
1173               getStart(), getEnd());
1174
1175       datasetSequence = dsseq;
1176
1177       dsseq.setDescription(description);
1178       // move features and database references onto dataset sequence
1179       dsseq.sequenceFeatures = sequenceFeatures;
1180       sequenceFeatures = null;
1181       dsseq.dbrefs = dbrefs;
1182       dbrefs = null;
1183       // TODO: search and replace any references to this sequence with
1184       // references to the dataset sequence in Mappings on dbref
1185       dsseq.pdbIds = pdbIds;
1186       pdbIds = null;
1187       datasetSequence.updatePDBIds();
1188       if (annotation != null)
1189       {
1190         // annotation is cloned rather than moved, to preserve what's currently
1191         // on the alignment
1192         for (AlignmentAnnotation aa : annotation)
1193         {
1194           AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1195           _aa.sequenceRef = datasetSequence;
1196           _aa.adjustForAlignment(); // uses annotation's own record of
1197                                     // sequence-column mapping
1198           datasetSequence.addAlignmentAnnotation(_aa);
1199         }
1200       }
1201     }
1202     return datasetSequence;
1203   }
1204
1205   /*
1206    * (non-Javadoc)
1207    * 
1208    * @see
1209    * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1210    * annotations)
1211    */
1212   @Override
1213   public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1214   {
1215     if (annotation != null)
1216     {
1217       annotation.removeAllElements();
1218     }
1219     if (annotations != null)
1220     {
1221       for (int i = 0; i < annotations.length; i++)
1222       {
1223         if (annotations[i] != null)
1224         {
1225           addAlignmentAnnotation(annotations[i]);
1226         }
1227       }
1228     }
1229   }
1230
1231   @Override
1232   public AlignmentAnnotation[] getAnnotation(String label)
1233   {
1234     if (annotation == null || annotation.size() == 0)
1235     {
1236       return null;
1237     }
1238
1239     Vector subset = new Vector();
1240     Enumeration e = annotation.elements();
1241     while (e.hasMoreElements())
1242     {
1243       AlignmentAnnotation ann = (AlignmentAnnotation) e.nextElement();
1244       if (ann.label != null && ann.label.equals(label))
1245       {
1246         subset.addElement(ann);
1247       }
1248     }
1249     if (subset.size() == 0)
1250     {
1251       return null;
1252     }
1253     AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1254     int i = 0;
1255     e = subset.elements();
1256     while (e.hasMoreElements())
1257     {
1258       anns[i++] = (AlignmentAnnotation) e.nextElement();
1259     }
1260     subset.removeAllElements();
1261     return anns;
1262   }
1263
1264   @Override
1265   public boolean updatePDBIds()
1266   {
1267     if (datasetSequence != null)
1268     {
1269       // TODO: could merge DBRefs
1270       return datasetSequence.updatePDBIds();
1271     }
1272     if (dbrefs == null || dbrefs.length == 0)
1273     {
1274       return false;
1275     }
1276     boolean added = false;
1277     for (DBRefEntry dbr : dbrefs)
1278     {
1279       if (DBRefSource.PDB.equals(dbr.getSource()))
1280       {
1281         /*
1282          * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1283          * PDB id is not already present in a 'matching' PDBEntry
1284          * Constructor parses out a chain code if appended to the accession id
1285          * (a fudge used to 'store' the chain code in the DBRef)
1286          */
1287         PDBEntry pdbe = new PDBEntry(dbr);
1288         added |= addPDBId(pdbe);
1289       }
1290     }
1291     return added;
1292   }
1293
1294   @Override
1295   public void transferAnnotation(SequenceI entry, Mapping mp)
1296   {
1297     if (datasetSequence != null)
1298     {
1299       datasetSequence.transferAnnotation(entry, mp);
1300       return;
1301     }
1302     if (entry.getDatasetSequence() != null)
1303     {
1304       transferAnnotation(entry.getDatasetSequence(), mp);
1305       return;
1306     }
1307     // transfer any new features from entry onto sequence
1308     if (entry.getSequenceFeatures() != null)
1309     {
1310
1311       SequenceFeature[] sfs = entry.getSequenceFeatures();
1312       for (int si = 0; si < sfs.length; si++)
1313       {
1314         SequenceFeature sf[] = (mp != null) ? mp.locateFeature(sfs[si])
1315                 : new SequenceFeature[] { new SequenceFeature(sfs[si]) };
1316         if (sf != null && sf.length > 0)
1317         {
1318           for (int sfi = 0; sfi < sf.length; sfi++)
1319           {
1320             addSequenceFeature(sf[sfi]);
1321           }
1322         }
1323       }
1324     }
1325
1326     // transfer PDB entries
1327     if (entry.getAllPDBEntries() != null)
1328     {
1329       Enumeration e = entry.getAllPDBEntries().elements();
1330       while (e.hasMoreElements())
1331       {
1332         PDBEntry pdb = (PDBEntry) e.nextElement();
1333         addPDBId(pdb);
1334       }
1335     }
1336     // transfer database references
1337     DBRefEntry[] entryRefs = entry.getDBRefs();
1338     if (entryRefs != null)
1339     {
1340       for (int r = 0; r < entryRefs.length; r++)
1341       {
1342         DBRefEntry newref = new DBRefEntry(entryRefs[r]);
1343         if (newref.getMap() != null && mp != null)
1344         {
1345           // remap ref using our local mapping
1346         }
1347         // we also assume all version string setting is done by dbSourceProxy
1348         /*
1349          * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1350          * newref.setSource(dbSource); }
1351          */
1352         addDBRef(newref);
1353       }
1354     }
1355   }
1356
1357   /**
1358    * @return The index (zero-based) on this sequence in the MSA. It returns
1359    *         {@code -1} if this information is not available.
1360    */
1361   @Override
1362   public int getIndex()
1363   {
1364     return index;
1365   }
1366
1367   /**
1368    * Defines the position of this sequence in the MSA. Use the value {@code -1}
1369    * if this information is undefined.
1370    * 
1371    * @param The
1372    *          position for this sequence. This value is zero-based (zero for
1373    *          this first sequence)
1374    */
1375   @Override
1376   public void setIndex(int value)
1377   {
1378     index = value;
1379   }
1380
1381   @Override
1382   public void setRNA(RNA r)
1383   {
1384     rna = r;
1385   }
1386
1387   @Override
1388   public RNA getRNA()
1389   {
1390     return rna;
1391   }
1392
1393   @Override
1394   public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1395           String label)
1396   {
1397     List<AlignmentAnnotation> result = new ArrayList<AlignmentAnnotation>();
1398     if (this.annotation != null)
1399     {
1400       for (AlignmentAnnotation ann : annotation)
1401       {
1402         if (ann.calcId != null && ann.calcId.equals(calcId)
1403                 && ann.label != null && ann.label.equals(label))
1404         {
1405           result.add(ann);
1406         }
1407       }
1408     }
1409     return result;
1410   }
1411
1412   @Override
1413   public String toString()
1414   {
1415     return getDisplayId(false);
1416   }
1417
1418   @Override
1419   public PDBEntry getPDBEntry(String pdbIdStr)
1420   {
1421     if (getDatasetSequence() != null)
1422     {
1423       return getDatasetSequence().getPDBEntry(pdbIdStr);
1424     }
1425     if (pdbIds == null)
1426     {
1427       return null;
1428     }
1429     List<PDBEntry> entries = getAllPDBEntries();
1430     for (PDBEntry entry : entries)
1431     {
1432       if (entry.getId().equalsIgnoreCase(pdbIdStr))
1433       {
1434         return entry;
1435       }
1436     }
1437     return null;
1438   }
1439
1440   @Override
1441   public List<DBRefEntry> getPrimaryDBRefs()
1442   {
1443     if (datasetSequence != null)
1444     {
1445       return datasetSequence.getPrimaryDBRefs();
1446     }
1447     if (dbrefs == null || dbrefs.length == 0)
1448     {
1449       return Collections.emptyList();
1450     }
1451     synchronized (dbrefs)
1452     {
1453       List<DBRefEntry> primaries = new ArrayList<DBRefEntry>();
1454       DBRefEntry[] tmp = new DBRefEntry[1];
1455       for (DBRefEntry ref : dbrefs)
1456       {
1457         if (!ref.isPrimaryCandidate())
1458         {
1459           continue;
1460         }
1461         if (ref.hasMap())
1462         {
1463           MapList mp = ref.getMap().getMap();
1464           if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1465           {
1466             // map only involves a subsequence, so cannot be primary
1467             continue;
1468           }
1469         }
1470         // whilst it looks like it is a primary ref, we also sanity check type
1471         if (DBRefUtils.getCanonicalName(DBRefSource.PDB).equals(
1472                 DBRefUtils.getCanonicalName(ref.getSource())))
1473         {
1474           // PDB dbrefs imply there should be a PDBEntry associated
1475           // TODO: tighten PDB dbrefs
1476           // formally imply Jalview has actually downloaded and
1477           // parsed the pdb file. That means there should be a cached file
1478           // handle on the PDBEntry, and a real mapping between sequence and
1479           // extracted sequence from PDB file
1480           PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1481           if (pdbentry != null && pdbentry.getFile() != null)
1482           {
1483             primaries.add(ref);
1484           }
1485           continue;
1486         }
1487         // check standard protein or dna sources
1488         tmp[0] = ref;
1489         DBRefEntry[] res = DBRefUtils.selectDbRefs(!isProtein(), tmp);
1490         if (res != null && res[0] == tmp[0])
1491         {
1492           primaries.add(ref);
1493           continue;
1494         }
1495       }
1496       return primaries;
1497     }
1498   }
1499
1500   /**
1501    * {@inheritDoc}
1502    */
1503   @Override
1504   public List<SequenceFeature> findFeatures(int from, int to,
1505           String... types)
1506   {
1507     if (datasetSequence != null)
1508     {
1509       return datasetSequence.findFeatures(from, to, types);
1510     }
1511     return sequenceFeatureStore.findFeatures(from, to, types);
1512   }
1513 }