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