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