d1f13c18e9d7c3ab9b57e0d1942943a7e71486c7
[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 import jalview.workers.InformationThread;
32
33 import java.util.ArrayList;
34 import java.util.Arrays;
35 import java.util.BitSet;
36 import java.util.Collections;
37 import java.util.Enumeration;
38 import java.util.Iterator;
39 import java.util.List;
40 import java.util.ListIterator;
41 import java.util.Vector;
42
43 import fr.orsay.lri.varna.models.rna.RNA;
44
45 /**
46  * 
47  * Implements the SequenceI interface for a char[] based sequence object
48  */
49 public class Sequence extends ASequence implements SequenceI
50 {
51   SequenceI datasetSequence;
52
53   String name;
54
55   private char[] sequence;
56
57   String description;
58
59   int start;
60
61   int end;
62
63   HiddenMarkovModel hmm;
64
65   boolean isHMMConsensusSequence = false;
66
67   Vector<PDBEntry> pdbIds;
68
69   String vamsasId;
70
71   DBRefEntry[] dbrefs;
72
73   RNA rna;
74
75   /**
76    * This annotation is displayed below the alignment but the positions are tied
77    * to the residues of this sequence
78    *
79    * TODO: change to List<>
80    */
81   Vector<AlignmentAnnotation> annotation;
82
83   private SequenceFeaturesI sequenceFeatureStore;
84
85   /*
86    * A cursor holding the approximate current view position to the sequence,
87    * as determined by findIndex or findPosition or findPositions.
88    * Using a cursor as a hint allows these methods to be more performant for
89    * large sequences.
90    */
91   private SequenceCursor cursor;
92
93   /*
94    * A number that should be incremented whenever the sequence is edited.
95    * If the value matches the cursor token, then we can trust the cursor,
96    * if not then it should be recomputed. 
97    */
98   private int changeCount;
99
100   /**
101    * Creates a new Sequence object.
102    * 
103    * @param name
104    *          display name string
105    * @param sequence
106    *          string to form a possibly gapped sequence out of
107    * @param start
108    *          first position of non-gap residue in the sequence
109    * @param end
110    *          last position of ungapped residues (nearly always only used for
111    *          display purposes)
112    */
113   public Sequence(String name, String sequence, int start, int end)
114   {
115     this();
116     initSeqAndName(name, sequence.toCharArray(), start, end);
117   }
118
119   public Sequence(String name, char[] sequence, int start, int end)
120   {
121     this();
122     initSeqAndName(name, sequence, start, end);
123   }
124
125   /**
126    * Stage 1 constructor - assign name, sequence, and set start and end fields.
127    * start and end are updated values from name2 if it ends with /start-end
128    * 
129    * @param name2
130    * @param sequence2
131    * @param start2
132    * @param end2
133    */
134   protected void initSeqAndName(String name2, char[] sequence2, int start2,
135           int end2)
136   {
137     this.name = name2;
138     this.sequence = sequence2;
139     this.start = start2;
140     this.end = end2;
141     parseId();
142     checkValidRange();
143   }
144
145   /**
146    * If 'name' ends in /i-j, where i >= j > 0 are integers, extracts i and j as
147    * start and end respectively and removes the suffix from the name
148    */
149   void parseId()
150   {
151     if (name == null)
152     {
153       System.err.println(
154               "POSSIBLE IMPLEMENTATION ERROR: null sequence name passed to constructor.");
155       name = "";
156     }
157     int slashPos = name.lastIndexOf('/');
158     if (slashPos > -1 && slashPos < name.length() - 1)
159     {
160       String suffix = name.substring(slashPos + 1);
161       String[] range = suffix.split("-");
162       if (range.length == 2)
163       {
164         try
165         {
166           int from = Integer.valueOf(range[0]);
167           int to = Integer.valueOf(range[1]);
168           if (from > 0 && to >= from)
169           {
170             name = name.substring(0, slashPos);
171             setStart(from);
172             setEnd(to);
173             checkValidRange();
174           }
175         } catch (NumberFormatException e)
176         {
177           // leave name unchanged if suffix is invalid
178         }
179       }
180     }
181   }
182
183   /**
184    * Ensures that 'end' is not before the end of the sequence, that is,
185    * (end-start+1) is at least as long as the count of ungapped positions. Note
186    * that end is permitted to be beyond the end of the sequence data.
187    */
188   void checkValidRange()
189   {
190     // Note: JAL-774 :
191     // http://issues.jalview.org/browse/JAL-774?focusedCommentId=11239&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-11239
192     {
193       int endRes = 0;
194       for (int j = 0; j < sequence.length; j++)
195       {
196         if (!Comparison.isGap(sequence[j]))
197         {
198           endRes++;
199         }
200       }
201       if (endRes > 0)
202       {
203         endRes += start - 1;
204       }
205
206       if (end < endRes)
207       {
208         end = endRes;
209       }
210     }
211
212   }
213
214   /**
215    * default constructor
216    */
217   private Sequence()
218   {
219     sequenceFeatureStore = new SequenceFeatures();
220   }
221
222   /**
223    * Creates a new Sequence object.
224    * 
225    * @param name
226    *          DOCUMENT ME!
227    * @param sequence
228    *          DOCUMENT ME!
229    */
230   public Sequence(String name, String sequence)
231   {
232     this(name, sequence, 1, -1);
233   }
234
235   /**
236    * Creates a new Sequence object with new AlignmentAnnotations but inherits
237    * any existing dataset sequence reference. If non exists, everything is
238    * copied.
239    * 
240    * @param seq
241    *          if seq is a dataset sequence, behaves like a plain old copy
242    *          constructor
243    */
244   public Sequence(SequenceI seq)
245   {
246     this(seq, seq.getAnnotation());
247   }
248
249   /**
250    * Create a new sequence object with new features, DBRefEntries, and PDBIds
251    * but inherits any existing dataset sequence reference, and duplicate of any
252    * annotation that is present in the given annotation array.
253    * 
254    * @param seq
255    *          the sequence to be copied
256    * @param alAnnotation
257    *          an array of annotation including some associated with seq
258    */
259   public Sequence(SequenceI seq, AlignmentAnnotation[] alAnnotation)
260   {
261     this();
262     initSeqFrom(seq, alAnnotation);
263   }
264
265   /**
266    * does the heavy lifting when cloning a dataset sequence, or coping data from
267    * dataset to a new derived sequence.
268    * 
269    * @param seq
270    *          - source of attributes.
271    * @param alAnnotation
272    *          - alignment annotation present on seq that should be copied onto
273    *          this sequence
274    */
275   protected void initSeqFrom(SequenceI seq,
276           AlignmentAnnotation[] alAnnotation)
277   {
278     char[] oseq = seq.getSequence(); // returns a copy of the array
279     initSeqAndName(seq.getName(), oseq, seq.getStart(), seq.getEnd());
280
281     description = seq.getDescription();
282     if (seq != datasetSequence)
283     {
284       setDatasetSequence(seq.getDatasetSequence());
285     }
286     
287     /*
288      * only copy DBRefs and seqfeatures if we really are a dataset sequence
289      */
290     if (datasetSequence == null)
291     {
292       if (seq.getDBRefs() != null)
293       {
294         DBRefEntry[] dbr = seq.getDBRefs();
295         for (int i = 0; i < dbr.length; i++)
296         {
297           addDBRef(new DBRefEntry(dbr[i]));
298         }
299       }
300
301       /*
302        * make copies of any sequence features
303        */
304       for (SequenceFeature sf : seq.getSequenceFeatures())
305       {
306         addSequenceFeature(new SequenceFeature(sf));
307       }
308     }
309
310     if (seq.getAnnotation() != null)
311     {
312       AlignmentAnnotation[] sqann = seq.getAnnotation();
313       for (int i = 0; i < sqann.length; i++)
314       {
315         if (sqann[i] == null)
316         {
317           continue;
318         }
319         boolean found = (alAnnotation == null);
320         if (!found)
321         {
322           for (int apos = 0; !found && apos < alAnnotation.length; apos++)
323           {
324             found = (alAnnotation[apos] == sqann[i]);
325           }
326         }
327         if (found)
328         {
329           // only copy the given annotation
330           AlignmentAnnotation newann = new AlignmentAnnotation(sqann[i]);
331           addAlignmentAnnotation(newann);
332         }
333       }
334     }
335     if (seq.getAllPDBEntries() != null)
336     {
337       Vector<PDBEntry> ids = seq.getAllPDBEntries();
338       for (PDBEntry pdb : ids)
339       {
340         this.addPDBId(new PDBEntry(pdb));
341       }
342     }
343     if (seq.getHMM() != null)
344     {
345       this.hmm = new HiddenMarkovModel(seq.getHMM(), this);
346     }
347
348   }
349
350   @Override
351   public void setSequenceFeatures(List<SequenceFeature> features)
352   {
353     if (datasetSequence != null)
354     {
355       datasetSequence.setSequenceFeatures(features);
356       return;
357     }
358     sequenceFeatureStore = new SequenceFeatures(features);
359   }
360
361   @Override
362   public synchronized boolean addSequenceFeature(SequenceFeature sf)
363   {
364     if (sf.getType() == null)
365     {
366       System.err.println("SequenceFeature type may not be null: "
367               + sf.toString());
368       return false;
369     }
370
371     if (datasetSequence != null)
372     {
373       return datasetSequence.addSequenceFeature(sf);
374     }
375
376     return sequenceFeatureStore.add(sf);
377   }
378
379   @Override
380   public void deleteFeature(SequenceFeature sf)
381   {
382     if (datasetSequence != null)
383     {
384       datasetSequence.deleteFeature(sf);
385     }
386     else
387     {
388       sequenceFeatureStore.delete(sf);
389     }
390   }
391
392   /**
393    * {@inheritDoc}
394    * 
395    * @return
396    */
397   @Override
398   public List<SequenceFeature> getSequenceFeatures()
399   {
400     if (datasetSequence != null)
401     {
402       return datasetSequence.getSequenceFeatures();
403     }
404     return sequenceFeatureStore.getAllFeatures();
405   }
406
407   @Override
408   public SequenceFeaturesI getFeatures()
409   {
410     return datasetSequence != null ? datasetSequence.getFeatures()
411             : sequenceFeatureStore;
412   }
413
414   @Override
415   public boolean addPDBId(PDBEntry entry)
416   {
417     if (pdbIds == null)
418     {
419       pdbIds = new Vector<>();
420       pdbIds.add(entry);
421       return true;
422     }
423
424     for (PDBEntry pdbe : pdbIds)
425     {
426       if (pdbe.updateFrom(entry))
427       {
428         return false;
429       }
430     }
431     pdbIds.addElement(entry);
432     return true;
433   }
434
435   /**
436    * DOCUMENT ME!
437    * 
438    * @param id
439    *          DOCUMENT ME!
440    */
441   @Override
442   public void setPDBId(Vector<PDBEntry> id)
443   {
444     pdbIds = id;
445   }
446
447   /**
448    * DOCUMENT ME!
449    * 
450    * @return DOCUMENT ME!
451    */
452   @Override
453   public Vector<PDBEntry> getAllPDBEntries()
454   {
455     return pdbIds == null ? new Vector<>() : pdbIds;
456   }
457
458   /**
459    * Answers the sequence name, with '/start-end' appended if jvsuffix is true
460    * 
461    * @return
462    */
463   @Override
464   public String getDisplayId(boolean jvsuffix)
465   {
466     if (!jvsuffix)
467     {
468       return name;
469     }
470     StringBuilder result = new StringBuilder(name);
471     result.append("/").append(start).append("-").append(end);
472
473     return result.toString();
474   }
475
476   /**
477    * Sets the sequence name. If the name ends in /start-end, then the start-end
478    * values are parsed out and set, and the suffix is removed from the name.
479    * 
480    * @param theName
481    */
482   @Override
483   public void setName(String theName)
484   {
485     this.name = theName;
486     this.parseId();
487   }
488
489   /**
490    * DOCUMENT ME!
491    * 
492    * @return DOCUMENT ME!
493    */
494   @Override
495   public String getName()
496   {
497     return this.name;
498   }
499
500   /**
501    * DOCUMENT ME!
502    * 
503    * @param start
504    *          DOCUMENT ME!
505    */
506   @Override
507   public void setStart(int start)
508   {
509     this.start = start;
510     sequenceChanged();
511   }
512
513   /**
514    * DOCUMENT ME!
515    * 
516    * @return DOCUMENT ME!
517    */
518   @Override
519   public int getStart()
520   {
521     return this.start;
522   }
523
524   /**
525    * DOCUMENT ME!
526    * 
527    * @param end
528    *          DOCUMENT ME!
529    */
530   @Override
531   public void setEnd(int end)
532   {
533     this.end = end;
534   }
535
536   /**
537    * DOCUMENT ME!
538    * 
539    * @return DOCUMENT ME!
540    */
541   @Override
542   public int getEnd()
543   {
544     return this.end;
545   }
546
547   /**
548    * DOCUMENT ME!
549    * 
550    * @return DOCUMENT ME!
551    */
552   @Override
553   public int getLength()
554   {
555     return this.sequence.length;
556   }
557
558   /**
559    * DOCUMENT ME!
560    * 
561    * @param seq
562    *          DOCUMENT ME!
563    */
564   @Override
565   public void setSequence(String seq)
566   {
567     this.sequence = seq.toCharArray();
568     checkValidRange();
569     sequenceChanged();
570   }
571
572   @Override
573   public String getSequenceAsString()
574   {
575     return new String(sequence);
576   }
577
578   @Override
579   public String getSequenceAsString(int start, int end)
580   {
581     return new String(getSequence(start, end));
582   }
583
584   @Override
585   public char[] getSequence()
586   {
587     // return sequence;
588     return sequence == null ? null : Arrays.copyOf(sequence,
589             sequence.length);
590   }
591
592   /*
593    * (non-Javadoc)
594    * 
595    * @see jalview.datamodel.SequenceI#getSequence(int, int)
596    */
597   @Override
598   public char[] getSequence(int start, int end)
599   {
600     if (start < 0)
601     {
602       start = 0;
603     }
604     // JBPNote - left to user to pad the result here (TODO:Decide on this
605     // policy)
606     if (start >= sequence.length)
607     {
608       return new char[0];
609     }
610
611     if (end >= sequence.length)
612     {
613       end = sequence.length;
614     }
615
616     char[] reply = new char[end - start];
617     System.arraycopy(sequence, start, reply, 0, end - start);
618
619     return reply;
620   }
621
622   @Override
623   public SequenceI getSubSequence(int start, int end)
624   {
625     if (start < 0)
626     {
627       start = 0;
628     }
629     char[] seq = getSequence(start, end);
630     if (seq.length == 0)
631     {
632       return null;
633     }
634     int nstart = findPosition(start);
635     int nend = findPosition(end) - 1;
636     // JBPNote - this is an incomplete copy.
637     SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
638     nseq.setDescription(description);
639     if (datasetSequence != null)
640     {
641       nseq.setDatasetSequence(datasetSequence);
642     }
643     else
644     {
645       nseq.setDatasetSequence(this);
646     }
647     return nseq;
648   }
649
650   /**
651    * Returns the character of the aligned sequence at the given position (base
652    * zero), or space if the position is not within the sequence's bounds
653    * 
654    * @return
655    */
656   @Override
657   public char getCharAt(int i)
658   {
659     if (i >= 0 && i < sequence.length)
660     {
661       return sequence[i];
662     }
663     else
664     {
665       return ' ';
666     }
667   }
668
669   /**
670    * Sets the sequence description, and also parses out any special formats of
671    * interest
672    * 
673    * @param desc
674    */
675   @Override
676   public void setDescription(String desc)
677   {
678     this.description = desc;
679   }
680
681   @Override
682   public void setGeneLoci(String speciesId, String assemblyId,
683           String chromosomeId, MapList map)
684   {
685     addDBRef(new GeneLocus(speciesId, assemblyId, chromosomeId,
686             new Mapping(map)));
687   }
688
689   /**
690    * Returns the gene loci mapping for the sequence (may be null)
691    * 
692    * @return
693    */
694   @Override
695   public GeneLociI getGeneLoci()
696   {
697     DBRefEntry[] refs = getDBRefs();
698     if (refs != null)
699     {
700       for (final DBRefEntry ref : refs)
701       {
702         if (ref instanceof GeneLociI)
703         {
704           return (GeneLociI) ref;
705         }
706       }
707     }
708     return null;
709   }
710
711   /**
712    * Answers the description
713    * 
714    * @return
715    */
716   @Override
717   public String getDescription()
718   {
719     return this.description;
720   }
721
722   /**
723    * {@inheritDoc}
724    */
725   @Override
726   public int findIndex(int pos)
727   {
728     /*
729      * use a valid, hopefully nearby, cursor if available
730      */
731     if (isValidCursor(cursor))
732     {
733       return findIndex(pos, cursor);
734     }
735
736     int j = start;
737     int i = 0;
738     int startColumn = 0;
739
740     /*
741      * traverse sequence from the start counting gaps; make a note of
742      * the column of the first residue to save in the cursor
743      */
744     while ((i < sequence.length) && (j <= end) && (j <= pos))
745     {
746       if (!Comparison.isGap(sequence[i]))
747       {
748         if (j == start)
749         {
750           startColumn = i;
751         }
752         j++;
753       }
754       i++;
755     }
756
757     if (j == end && j < pos)
758     {
759       return end + 1;
760     }
761
762     updateCursor(pos, i, startColumn);
763     return i;
764   }
765
766   /**
767    * Updates the cursor to the latest found residue and column position
768    * 
769    * @param residuePos
770    *          (start..)
771    * @param column
772    *          (1..)
773    * @param startColumn
774    *          column position of the first sequence residue
775    */
776   protected void updateCursor(int residuePos, int column, int startColumn)
777   {
778     /*
779      * preserve end residue column provided cursor was valid
780      */
781     int endColumn = isValidCursor(cursor) ? cursor.lastColumnPosition : 0;
782
783     if (residuePos == this.end)
784     {
785       endColumn = column;
786     }
787
788     cursor = new SequenceCursor(this, residuePos, column, startColumn,
789             endColumn, this.changeCount);
790   }
791
792   /**
793    * Answers the aligned column position (1..) for the given residue position
794    * (start..) given a 'hint' of a residue/column location in the neighbourhood.
795    * The hint may be left of, at, or to the right of the required position.
796    * 
797    * @param pos
798    * @param curs
799    * @return
800    */
801   protected int findIndex(final int pos, SequenceCursor curs)
802   {
803     if (!isValidCursor(curs))
804     {
805       /*
806        * wrong or invalidated cursor, compute de novo
807        */
808       return findIndex(pos);
809     }
810
811     if (curs.residuePosition == pos)
812     {
813       return curs.columnPosition;
814     }
815
816     /*
817      * move left or right to find pos from hint.position
818      */
819     int col = curs.columnPosition - 1; // convert from base 1 to base 0
820     int newPos = curs.residuePosition;
821     int delta = newPos > pos ? -1 : 1;
822
823     while (newPos != pos)
824     {
825       col += delta; // shift one column left or right
826       if (col < 0)
827       {
828         break;
829       }
830       if (col == sequence.length)
831       {
832         col--; // return last column if we failed to reach pos
833         break;
834       }
835       if (!Comparison.isGap(sequence[col]))
836       {
837         newPos += delta;
838       }
839     }
840
841     col++; // convert back to base 1
842
843     /*
844      * only update cursor if we found the target position
845      */
846     if (newPos == pos)
847     {
848       updateCursor(pos, col, curs.firstColumnPosition);
849     }
850
851     return col;
852   }
853
854   /**
855    * {@inheritDoc}
856    */
857   @Override
858   public int findPosition(final int column)
859   {
860     /*
861      * use a valid, hopefully nearby, cursor if available
862      */
863     if (isValidCursor(cursor))
864     {
865       return findPosition(column + 1, cursor);
866     }
867     
868     // TODO recode this more naturally i.e. count residues only
869     // as they are found, not 'in anticipation'
870
871     /*
872      * traverse the sequence counting gaps; note the column position
873      * of the first residue, to save in the cursor
874      */
875     int firstResidueColumn = 0;
876     int lastPosFound = 0;
877     int lastPosFoundColumn = 0;
878     int seqlen = sequence.length;
879
880     if (seqlen > 0 && !Comparison.isGap(sequence[0]))
881     {
882       lastPosFound = start;
883       lastPosFoundColumn = 0;
884     }
885
886     int j = 0;
887     int pos = start;
888
889     while (j < column && j < seqlen)
890     {
891       if (!Comparison.isGap(sequence[j]))
892       {
893         lastPosFound = pos;
894         lastPosFoundColumn = j;
895         if (pos == this.start)
896         {
897           firstResidueColumn = j;
898         }
899         pos++;
900       }
901       j++;
902     }
903     if (j < seqlen && !Comparison.isGap(sequence[j]))
904     {
905       lastPosFound = pos;
906       lastPosFoundColumn = j;
907       if (pos == this.start)
908       {
909         firstResidueColumn = j;
910       }
911     }
912
913     /*
914      * update the cursor to the last residue position found (if any)
915      * (converting column position to base 1)
916      */
917     if (lastPosFound != 0)
918     {
919       updateCursor(lastPosFound, lastPosFoundColumn + 1,
920               firstResidueColumn + 1);
921     }
922
923     return pos;
924   }
925
926   /**
927    * Answers true if the given cursor is not null, is for this sequence object,
928    * and has a token value that matches this object's changeCount, else false.
929    * This allows us to ignore a cursor as 'stale' if the sequence has been
930    * modified since the cursor was created.
931    * 
932    * @param curs
933    * @return
934    */
935   protected boolean isValidCursor(SequenceCursor curs)
936   {
937     if (curs == null || curs.sequence != this || curs.token != changeCount)
938     {
939       return false;
940     }
941     /*
942      * sanity check against range
943      */
944     if (curs.columnPosition < 0 || curs.columnPosition > sequence.length)
945     {
946       return false;
947     }
948     if (curs.residuePosition < start || curs.residuePosition > end)
949     {
950       return false;
951     }
952     return true;
953   }
954
955   /**
956    * Answers the sequence position (start..) for the given aligned column
957    * position (1..), given a hint of a cursor in the neighbourhood. The cursor
958    * may lie left of, at, or to the right of the column position.
959    * 
960    * @param col
961    * @param curs
962    * @return
963    */
964   protected int findPosition(final int col, SequenceCursor curs)
965   {
966     if (!isValidCursor(curs))
967     {
968       /*
969        * wrong or invalidated cursor, compute de novo
970        */
971       return findPosition(col - 1);// ugh back to base 0
972     }
973
974     if (curs.columnPosition == col)
975     {
976       cursor = curs; // in case this method becomes public
977       return curs.residuePosition; // easy case :-)
978     }
979
980     if (curs.lastColumnPosition > 0 && curs.lastColumnPosition < col)
981     {
982       /*
983        * sequence lies entirely to the left of col
984        * - return last residue + 1
985        */
986       return end + 1;
987     }
988
989     if (curs.firstColumnPosition > 0 && curs.firstColumnPosition > col)
990     {
991       /*
992        * sequence lies entirely to the right of col
993        * - return first residue
994        */
995       return start;
996     }
997
998     // todo could choose closest to col out of column,
999     // firstColumnPosition, lastColumnPosition as a start point
1000
1001     /*
1002      * move left or right to find pos from cursor position
1003      */
1004     int firstResidueColumn = curs.firstColumnPosition;
1005     int column = curs.columnPosition - 1; // to base 0
1006     int newPos = curs.residuePosition;
1007     int delta = curs.columnPosition > col ? -1 : 1;
1008     boolean gapped = false;
1009     int lastFoundPosition = curs.residuePosition;
1010     int lastFoundPositionColumn = curs.columnPosition;
1011
1012     while (column != col - 1)
1013     {
1014       column += delta; // shift one column left or right
1015       if (column < 0 || column == sequence.length)
1016       {
1017         break;
1018       }
1019       gapped = Comparison.isGap(sequence[column]);
1020       if (!gapped)
1021       {
1022         newPos += delta;
1023         lastFoundPosition = newPos;
1024         lastFoundPositionColumn = column + 1;
1025         if (lastFoundPosition == this.start)
1026         {
1027           firstResidueColumn = column + 1;
1028         }
1029       }
1030     }
1031
1032     if (cursor == null || lastFoundPosition != cursor.residuePosition)
1033     {
1034       updateCursor(lastFoundPosition, lastFoundPositionColumn,
1035               firstResidueColumn);
1036     }
1037
1038     /*
1039      * hack to give position to the right if on a gap
1040      * or beyond the length of the sequence (see JAL-2562)
1041      */
1042     if (delta > 0 && (gapped || column >= sequence.length))
1043     {
1044       newPos++;
1045     }
1046
1047     return newPos;
1048   }
1049
1050   /**
1051    * {@inheritDoc}
1052    */
1053   @Override
1054   public ContiguousI findPositions(int fromColumn, int toColumn)
1055   {
1056     fromColumn = Math.max(fromColumn, 1);
1057     if (toColumn < fromColumn)
1058     {
1059       return null;
1060     }
1061
1062     /*
1063      * find the first non-gapped position, if any
1064      */
1065     int firstPosition = 0;
1066     int col = fromColumn - 1;
1067     int length = sequence.length;
1068     while (col < length && col < toColumn)
1069     {
1070       if (!Comparison.isGap(sequence[col]))
1071       {
1072         firstPosition = findPosition(col++);
1073         break;
1074       }
1075       col++;
1076     }
1077
1078     if (firstPosition == 0)
1079     {
1080       return null;
1081     }
1082
1083     /*
1084      * find the last non-gapped position
1085      */
1086     int lastPosition = firstPosition;
1087     while (col < length && col < toColumn)
1088     {
1089       if (!Comparison.isGap(sequence[col++]))
1090       {
1091         lastPosition++;
1092       }
1093     }
1094
1095     return new Range(firstPosition, lastPosition);
1096   }
1097
1098   /**
1099    * Returns an int array where indices correspond to each residue in the
1100    * sequence and the element value gives its position in the alignment
1101    * 
1102    * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
1103    *         residues in SequenceI object
1104    */
1105   @Override
1106   public int[] gapMap()
1107   {
1108     String seq = jalview.analysis.AlignSeq.extractGaps(
1109             jalview.util.Comparison.GapChars, new String(sequence));
1110     int[] map = new int[seq.length()];
1111     int j = 0;
1112     int p = 0;
1113
1114     while (j < sequence.length)
1115     {
1116       if (!jalview.util.Comparison.isGap(sequence[j]))
1117       {
1118         map[p++] = j;
1119       }
1120
1121       j++;
1122     }
1123
1124     return map;
1125   }
1126
1127   /**
1128    * Build a bitset corresponding to sequence gaps
1129    * 
1130    * @return a BitSet where set values correspond to gaps in the sequence
1131    */
1132   @Override
1133   public BitSet gapBitset()
1134   {
1135     BitSet gaps = new BitSet(sequence.length);
1136     int j = 0;
1137     while (j < sequence.length)
1138     {
1139       if (jalview.util.Comparison.isGap(sequence[j]))
1140       {
1141         gaps.set(j);
1142       }
1143       j++;
1144     }
1145     return gaps;
1146   }
1147
1148   @Override
1149   public int[] findPositionMap()
1150   {
1151     int map[] = new int[sequence.length];
1152     int j = 0;
1153     int pos = start;
1154     int seqlen = sequence.length;
1155     while ((j < seqlen))
1156     {
1157       map[j] = pos;
1158       if (!jalview.util.Comparison.isGap(sequence[j]))
1159       {
1160         pos++;
1161       }
1162
1163       j++;
1164     }
1165     return map;
1166   }
1167
1168   @Override
1169   public List<int[]> getInsertions()
1170   {
1171     ArrayList<int[]> map = new ArrayList<>();
1172     int lastj = -1, j = 0;
1173     int pos = start;
1174     int seqlen = sequence.length;
1175     while ((j < seqlen))
1176     {
1177       if (jalview.util.Comparison.isGap(sequence[j]))
1178       {
1179         if (lastj == -1)
1180         {
1181           lastj = j;
1182         }
1183       }
1184       else
1185       {
1186         if (lastj != -1)
1187         {
1188           map.add(new int[] { lastj, j - 1 });
1189           lastj = -1;
1190         }
1191       }
1192       j++;
1193     }
1194     if (lastj != -1)
1195     {
1196       map.add(new int[] { lastj, j - 1 });
1197       lastj = -1;
1198     }
1199     return map;
1200   }
1201
1202   @Override
1203   public BitSet getInsertionsAsBits()
1204   {
1205     BitSet map = new BitSet();
1206     int lastj = -1, j = 0;
1207     int pos = start;
1208     int seqlen = sequence.length;
1209     while ((j < seqlen))
1210     {
1211       if (jalview.util.Comparison.isGap(sequence[j]))
1212       {
1213         if (lastj == -1)
1214         {
1215           lastj = j;
1216         }
1217       }
1218       else
1219       {
1220         if (lastj != -1)
1221         {
1222           map.set(lastj, j);
1223           lastj = -1;
1224         }
1225       }
1226       j++;
1227     }
1228     if (lastj != -1)
1229     {
1230       map.set(lastj, j);
1231       lastj = -1;
1232     }
1233     return map;
1234   }
1235
1236   @Override
1237   public void deleteChars(final int i, final int j)
1238   {
1239     int newstart = start, newend = end;
1240     if (i >= sequence.length || i < 0)
1241     {
1242       return;
1243     }
1244
1245     char[] tmp = StringUtils.deleteChars(sequence, i, j);
1246     boolean createNewDs = false;
1247     // TODO: take a (second look) at the dataset creation validation method for
1248     // the very large sequence case
1249
1250     int startIndex = findIndex(start) - 1;
1251     int endIndex = findIndex(end) - 1;
1252     int startDeleteColumn = -1; // for dataset sequence deletions
1253     int deleteCount = 0;
1254
1255     for (int s = i; s < j && s < sequence.length; s++)
1256     {
1257       if (Comparison.isGap(sequence[s]))
1258       {
1259         continue;
1260       }
1261       deleteCount++;
1262       if (startDeleteColumn == -1)
1263       {
1264         startDeleteColumn = findPosition(s) - start;
1265       }
1266       if (createNewDs)
1267       {
1268         newend--;
1269       }
1270       else
1271       {
1272         if (startIndex == s)
1273         {
1274           /*
1275            * deleting characters from start of sequence; new start is the
1276            * sequence position of the next column (position to the right
1277            * if the column position is gapped)
1278            */
1279           newstart = findPosition(j);
1280           break;
1281         }
1282         else
1283         {
1284           if (endIndex < j)
1285           {
1286             /*
1287              * deleting characters at end of sequence; new end is the sequence
1288              * position of the column before the deletion; subtract 1 if this is
1289              * gapped since findPosition returns the next sequence position
1290              */
1291             newend = findPosition(i - 1);
1292             if (Comparison.isGap(sequence[i - 1]))
1293             {
1294               newend--;
1295             }
1296             break;
1297           }
1298           else
1299           {
1300             createNewDs = true;
1301             newend--;
1302           }
1303         }
1304       }
1305     }
1306
1307     if (createNewDs && this.datasetSequence != null)
1308     {
1309       /*
1310        * if deletion occured in the middle of the sequence,
1311        * construct a new dataset sequence and delete the residues
1312        * that were deleted from the aligned sequence
1313        */
1314       Sequence ds = new Sequence(datasetSequence);
1315       ds.deleteChars(startDeleteColumn, startDeleteColumn + deleteCount);
1316       datasetSequence = ds;
1317       // TODO: remove any non-inheritable properties ?
1318       // TODO: create a sequence mapping (since there is a relation here ?)
1319     }
1320     start = newstart;
1321     end = newend;
1322     sequence = tmp;
1323     sequenceChanged();
1324   }
1325
1326   @Override
1327   public void insertCharAt(int i, int length, char c)
1328   {
1329     char[] tmp = new char[sequence.length + length];
1330
1331     if (i >= sequence.length)
1332     {
1333       System.arraycopy(sequence, 0, tmp, 0, sequence.length);
1334       i = sequence.length;
1335     }
1336     else
1337     {
1338       System.arraycopy(sequence, 0, tmp, 0, i);
1339     }
1340
1341     int index = i;
1342     while (length > 0)
1343     {
1344       tmp[index++] = c;
1345       length--;
1346     }
1347
1348     if (i < sequence.length)
1349     {
1350       System.arraycopy(sequence, i, tmp, index, sequence.length - i);
1351     }
1352
1353     sequence = tmp;
1354     sequenceChanged();
1355   }
1356
1357   @Override
1358   public void insertCharAt(int i, char c)
1359   {
1360     insertCharAt(i, 1, c);
1361   }
1362
1363   @Override
1364   public String getVamsasId()
1365   {
1366     return vamsasId;
1367   }
1368
1369   @Override
1370   public void setVamsasId(String id)
1371   {
1372     vamsasId = id;
1373   }
1374
1375   @Override
1376   public void setDBRefs(DBRefEntry[] dbref)
1377   {
1378     if (dbrefs == null && datasetSequence != null
1379             && this != datasetSequence)
1380     {
1381       datasetSequence.setDBRefs(dbref);
1382       return;
1383     }
1384     dbrefs = dbref;
1385     if (dbrefs != null)
1386     {
1387       DBRefUtils.ensurePrimaries(this);
1388     }
1389   }
1390
1391   @Override
1392   public DBRefEntry[] getDBRefs()
1393   {
1394     if (dbrefs == null && datasetSequence != null
1395             && this != datasetSequence)
1396     {
1397       return datasetSequence.getDBRefs();
1398     }
1399     return dbrefs;
1400   }
1401
1402   @Override
1403   public void addDBRef(DBRefEntry entry)
1404   {
1405     if (datasetSequence != null)
1406     {
1407       datasetSequence.addDBRef(entry);
1408       return;
1409     }
1410
1411     if (dbrefs == null)
1412     {
1413       dbrefs = new DBRefEntry[0];
1414     }
1415
1416     for (DBRefEntryI dbr : dbrefs)
1417     {
1418       if (dbr.updateFrom(entry))
1419       {
1420         /*
1421          * found a dbref that either matched, or could be
1422          * updated from, the new entry - no need to add it
1423          */
1424         return;
1425       }
1426     }
1427
1428     /*
1429      * extend the array to make room for one more
1430      */
1431     // TODO use an ArrayList instead
1432     int j = dbrefs.length;
1433     DBRefEntry[] temp = new DBRefEntry[j + 1];
1434     System.arraycopy(dbrefs, 0, temp, 0, j);
1435     temp[temp.length - 1] = entry;
1436
1437     dbrefs = temp;
1438
1439     DBRefUtils.ensurePrimaries(this);
1440   }
1441
1442   @Override
1443   public void setDatasetSequence(SequenceI seq)
1444   {
1445     if (seq == this)
1446     {
1447       throw new IllegalArgumentException(
1448               "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1449     }
1450     if (seq != null && seq.getDatasetSequence() != null)
1451     {
1452       throw new IllegalArgumentException(
1453               "Implementation error: cascading dataset sequences are not allowed.");
1454     }
1455     datasetSequence = seq;
1456   }
1457
1458   @Override
1459   public SequenceI getDatasetSequence()
1460   {
1461     return datasetSequence;
1462   }
1463
1464   @Override
1465   public AlignmentAnnotation[] getAnnotation()
1466   {
1467     return annotation == null ? null
1468             : annotation
1469                     .toArray(new AlignmentAnnotation[annotation.size()]);
1470   }
1471
1472   @Override
1473   public boolean hasAnnotation(AlignmentAnnotation ann)
1474   {
1475     return annotation == null ? false : annotation.contains(ann);
1476   }
1477
1478   @Override
1479   public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1480   {
1481     if (this.annotation == null)
1482     {
1483       this.annotation = new Vector<>();
1484     }
1485     if (!this.annotation.contains(annotation))
1486     {
1487       this.annotation.addElement(annotation);
1488     }
1489     annotation.setSequenceRef(this);
1490   }
1491
1492   @Override
1493   public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1494   {
1495     if (this.annotation != null)
1496     {
1497       this.annotation.removeElement(annotation);
1498       if (this.annotation.size() == 0)
1499       {
1500         this.annotation = null;
1501       }
1502     }
1503   }
1504
1505   /**
1506    * test if this is a valid candidate for another sequence's dataset sequence.
1507    * 
1508    */
1509   private boolean isValidDatasetSequence()
1510   {
1511     if (datasetSequence != null)
1512     {
1513       return false;
1514     }
1515     for (int i = 0; i < sequence.length; i++)
1516     {
1517       if (jalview.util.Comparison.isGap(sequence[i]))
1518       {
1519         return false;
1520       }
1521     }
1522     return true;
1523   }
1524
1525   @Override
1526   public SequenceI deriveSequence()
1527   {
1528     Sequence seq = null;
1529     if (datasetSequence == null)
1530     {
1531       if (isValidDatasetSequence())
1532       {
1533         // Use this as dataset sequence
1534         seq = new Sequence(getName(), "", 1, -1);
1535         seq.setDatasetSequence(this);
1536         seq.initSeqFrom(this, getAnnotation());
1537         return seq;
1538       }
1539       else
1540       {
1541         // Create a new, valid dataset sequence
1542         createDatasetSequence();
1543       }
1544     }
1545     return new Sequence(this);
1546   }
1547
1548   private boolean _isNa;
1549
1550   private int _seqhash = 0;
1551
1552   /**
1553    * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1554    * true
1555    */
1556   @Override
1557   public boolean isProtein()
1558   {
1559     if (datasetSequence != null)
1560     {
1561       return datasetSequence.isProtein();
1562     }
1563     if (_seqhash != sequence.hashCode())
1564     {
1565       _seqhash = sequence.hashCode();
1566       _isNa = Comparison.isNucleotide(this);
1567     }
1568     return !_isNa;
1569   };
1570
1571   /*
1572    * (non-Javadoc)
1573    * 
1574    * @see jalview.datamodel.SequenceI#createDatasetSequence()
1575    */
1576   @Override
1577   public SequenceI createDatasetSequence()
1578   {
1579     if (datasetSequence == null)
1580     {
1581       Sequence dsseq = new Sequence(getName(),
1582               AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
1583                       getSequenceAsString()),
1584               getStart(), getEnd());
1585
1586       datasetSequence = dsseq;
1587
1588       dsseq.setDescription(description);
1589       // move features and database references onto dataset sequence
1590       dsseq.sequenceFeatureStore = sequenceFeatureStore;
1591       sequenceFeatureStore = null;
1592       dsseq.dbrefs = dbrefs;
1593       dbrefs = null;
1594       // TODO: search and replace any references to this sequence with
1595       // references to the dataset sequence in Mappings on dbref
1596       dsseq.pdbIds = pdbIds;
1597       pdbIds = null;
1598       datasetSequence.updatePDBIds();
1599       if (annotation != null)
1600       {
1601         // annotation is cloned rather than moved, to preserve what's currently
1602         // on the alignment
1603         for (AlignmentAnnotation aa : annotation)
1604         {
1605           AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1606           _aa.sequenceRef = datasetSequence;
1607           _aa.adjustForAlignment(); // uses annotation's own record of
1608                                     // sequence-column mapping
1609           datasetSequence.addAlignmentAnnotation(_aa);
1610         }
1611       }
1612       datasetSequence.setHMM(hmm);
1613       hmm=null;
1614     }
1615     return datasetSequence;
1616   }
1617
1618   /*
1619    * (non-Javadoc)
1620    * 
1621    * @see
1622    * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1623    * annotations)
1624    */
1625   @Override
1626   public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1627   {
1628     if (annotation != null)
1629     {
1630       annotation.removeAllElements();
1631     }
1632     if (annotations != null)
1633     {
1634       for (int i = 0; i < annotations.length; i++)
1635       {
1636         if (annotations[i] != null)
1637         {
1638           addAlignmentAnnotation(annotations[i]);
1639         }
1640       }
1641     }
1642   }
1643
1644   @Override
1645   public AlignmentAnnotation[] getAnnotation(String label)
1646   {
1647     if (annotation == null || annotation.size() == 0)
1648     {
1649       return null;
1650     }
1651
1652     Vector<AlignmentAnnotation> subset = new Vector<>();
1653     Enumeration<AlignmentAnnotation> e = annotation.elements();
1654     while (e.hasMoreElements())
1655     {
1656       AlignmentAnnotation ann = e.nextElement();
1657       if (ann.label != null && ann.label.equals(label))
1658       {
1659         subset.addElement(ann);
1660       }
1661     }
1662     if (subset.size() == 0)
1663     {
1664       return null;
1665     }
1666     AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1667     int i = 0;
1668     e = subset.elements();
1669     while (e.hasMoreElements())
1670     {
1671       anns[i++] = e.nextElement();
1672     }
1673     subset.removeAllElements();
1674     return anns;
1675   }
1676
1677   @Override
1678   public boolean updatePDBIds()
1679   {
1680     if (datasetSequence != null)
1681     {
1682       // TODO: could merge DBRefs
1683       return datasetSequence.updatePDBIds();
1684     }
1685     if (dbrefs == null || dbrefs.length == 0)
1686     {
1687       return false;
1688     }
1689     boolean added = false;
1690     for (DBRefEntry dbr : dbrefs)
1691     {
1692       if (DBRefSource.PDB.equals(dbr.getSource()))
1693       {
1694         /*
1695          * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1696          * PDB id is not already present in a 'matching' PDBEntry
1697          * Constructor parses out a chain code if appended to the accession id
1698          * (a fudge used to 'store' the chain code in the DBRef)
1699          */
1700         PDBEntry pdbe = new PDBEntry(dbr);
1701         added |= addPDBId(pdbe);
1702       }
1703     }
1704     return added;
1705   }
1706
1707   @Override
1708   public void transferAnnotation(SequenceI entry, Mapping mp)
1709   {
1710     if (datasetSequence != null)
1711     {
1712       datasetSequence.transferAnnotation(entry, mp);
1713       return;
1714     }
1715     if (entry.getDatasetSequence() != null)
1716     {
1717       transferAnnotation(entry.getDatasetSequence(), mp);
1718       return;
1719     }
1720     // transfer any new features from entry onto sequence
1721     if (entry.getSequenceFeatures() != null)
1722     {
1723
1724       List<SequenceFeature> sfs = entry.getSequenceFeatures();
1725       for (SequenceFeature feature : sfs)
1726       {
1727        SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1728                 : new SequenceFeature[] { new SequenceFeature(feature) };
1729         if (sf != null)
1730         {
1731           for (int sfi = 0; sfi < sf.length; sfi++)
1732           {
1733             addSequenceFeature(sf[sfi]);
1734           }
1735         }
1736       }
1737     }
1738
1739     // transfer PDB entries
1740     if (entry.getAllPDBEntries() != null)
1741     {
1742       Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1743       while (e.hasMoreElements())
1744       {
1745         PDBEntry pdb = e.nextElement();
1746         addPDBId(pdb);
1747       }
1748     }
1749     // transfer database references
1750     DBRefEntry[] entryRefs = entry.getDBRefs();
1751     if (entryRefs != null)
1752     {
1753       for (int r = 0; r < entryRefs.length; r++)
1754       {
1755         DBRefEntry newref = new DBRefEntry(entryRefs[r]);
1756         if (newref.getMap() != null && mp != null)
1757         {
1758           // remap ref using our local mapping
1759         }
1760         // we also assume all version string setting is done by dbSourceProxy
1761         /*
1762          * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1763          * newref.setSource(dbSource); }
1764          */
1765         addDBRef(newref);
1766       }
1767     }
1768   }
1769
1770   @Override
1771   public void setRNA(RNA r)
1772   {
1773     rna = r;
1774   }
1775
1776   @Override
1777   public RNA getRNA()
1778   {
1779     return rna;
1780   }
1781
1782   @Override
1783   public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1784           String label)
1785   {
1786     List<AlignmentAnnotation> result = new ArrayList<>();
1787     if (this.annotation != null)
1788     {
1789       for (AlignmentAnnotation ann : annotation)
1790       {
1791         String id = ann.getCalcId();
1792         if (id != null && id.equals(calcId)
1793                 && ann.label != null && ann.label.equals(label))
1794         {
1795           result.add(ann);
1796         }
1797       }
1798     }
1799     return result;
1800   }
1801
1802   @Override
1803   public String toString()
1804   {
1805     return getDisplayId(false);
1806   }
1807
1808   @Override
1809   public PDBEntry getPDBEntry(String pdbIdStr)
1810   {
1811     if (getDatasetSequence() != null)
1812     {
1813       return getDatasetSequence().getPDBEntry(pdbIdStr);
1814     }
1815     if (pdbIds == null)
1816     {
1817       return null;
1818     }
1819     List<PDBEntry> entries = getAllPDBEntries();
1820     for (PDBEntry entry : entries)
1821     {
1822       if (entry.getId().equalsIgnoreCase(pdbIdStr))
1823       {
1824         return entry;
1825       }
1826     }
1827     return null;
1828   }
1829
1830   @Override
1831   public List<DBRefEntry> getPrimaryDBRefs()
1832   {
1833     if (datasetSequence != null)
1834     {
1835       return datasetSequence.getPrimaryDBRefs();
1836     }
1837     if (dbrefs == null || dbrefs.length == 0)
1838     {
1839       return Collections.emptyList();
1840     }
1841     synchronized (dbrefs)
1842     {
1843       List<DBRefEntry> primaries = new ArrayList<>();
1844       DBRefEntry[] tmp = new DBRefEntry[1];
1845       for (DBRefEntry ref : dbrefs)
1846       {
1847         if (!ref.isPrimaryCandidate())
1848         {
1849           continue;
1850         }
1851         if (ref.hasMap())
1852         {
1853           MapList mp = ref.getMap().getMap();
1854           if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1855           {
1856             // map only involves a subsequence, so cannot be primary
1857             continue;
1858           }
1859         }
1860         // whilst it looks like it is a primary ref, we also sanity check type
1861         if (DBRefUtils.getCanonicalName(DBRefSource.PDB)
1862                 .equals(DBRefUtils.getCanonicalName(ref.getSource())))
1863         {
1864           // PDB dbrefs imply there should be a PDBEntry associated
1865           // TODO: tighten PDB dbrefs
1866           // formally imply Jalview has actually downloaded and
1867           // parsed the pdb file. That means there should be a cached file
1868           // handle on the PDBEntry, and a real mapping between sequence and
1869           // extracted sequence from PDB file
1870           PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1871           if (pdbentry != null && pdbentry.getFile() != null)
1872           {
1873             primaries.add(ref);
1874           }
1875           continue;
1876         }
1877         // check standard protein or dna sources
1878         tmp[0] = ref;
1879         DBRefEntry[] res = DBRefUtils.selectDbRefs(!isProtein(), tmp);
1880         if (res != null && res[0] == tmp[0])
1881         {
1882           primaries.add(ref);
1883           continue;
1884         }
1885       }
1886       return primaries;
1887     }
1888   }
1889
1890   @Override
1891   public HiddenMarkovModel getHMM()
1892   {
1893     if (datasetSequence!=null)
1894     {
1895       return datasetSequence.getHMM();
1896     }
1897     return hmm;
1898   }
1899
1900   @Override
1901   public void setHMM(HiddenMarkovModel hmm)
1902   {
1903     if (datasetSequence!=null)
1904     {
1905       datasetSequence.setHMM(hmm);
1906     } else {
1907       this.hmm=hmm;
1908     }
1909     
1910   }
1911
1912   @Override
1913   public boolean hasHMMAnnotation()
1914   {
1915     if (this.annotation == null) {
1916       return false;
1917     }
1918     for (AlignmentAnnotation ann : annotation)
1919     {
1920       if (InformationThread.HMM_CALC_ID.equals(ann.getCalcId()))
1921       {
1922         return true;
1923       }
1924     }
1925     return false;
1926   }
1927
1928   /**
1929    * {@inheritDoc}
1930    */
1931   @Override
1932   public List<SequenceFeature> findFeatures(int fromColumn, int toColumn,
1933           String... types)
1934   {
1935     int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
1936     int endPos = fromColumn == toColumn ? startPos
1937             : findPosition(toColumn - 1);
1938
1939     List<SequenceFeature> result = getFeatures().findFeatures(startPos,
1940             endPos, types);
1941
1942     /*
1943      * if end column is gapped, endPos may be to the right, 
1944      * and we may have included adjacent or enclosing features;
1945      * remove any that are not enclosing, non-contact features
1946      */
1947     boolean endColumnIsGapped = toColumn > 0 && toColumn <= sequence.length
1948             && Comparison.isGap(sequence[toColumn - 1]);
1949     if (endPos > this.end || endColumnIsGapped)
1950     {
1951       ListIterator<SequenceFeature> it = result.listIterator();
1952       while (it.hasNext())
1953       {
1954         SequenceFeature sf = it.next();
1955         int sfBegin = sf.getBegin();
1956         int sfEnd = sf.getEnd();
1957         int featureStartColumn = findIndex(sfBegin);
1958         if (featureStartColumn > toColumn)
1959         {
1960           it.remove();
1961         }
1962         else if (featureStartColumn < fromColumn)
1963         {
1964           int featureEndColumn = sfEnd == sfBegin ? featureStartColumn
1965                   : findIndex(sfEnd);
1966           if (featureEndColumn < fromColumn)
1967           {
1968             it.remove();
1969           }
1970           else if (featureEndColumn > toColumn && sf.isContactFeature())
1971           {
1972             /*
1973              * remove an enclosing feature if it is a contact feature
1974              */
1975             it.remove();
1976           }
1977         }
1978       }
1979     }
1980
1981     return result;
1982   }
1983
1984   /**
1985    * Invalidates any stale cursors (forcing recalculation) by incrementing the
1986    * token that has to match the one presented by the cursor
1987    */
1988   @Override
1989   public void sequenceChanged()
1990   {
1991     changeCount++;
1992   }
1993
1994   /**
1995    * {@inheritDoc}
1996    */
1997   @Override
1998   public int replace(char c1, char c2)
1999   {
2000     if (c1 == c2)
2001     {
2002       return 0;
2003     }
2004     int count = 0;
2005     synchronized (sequence)
2006     {
2007       for (int c = 0; c < sequence.length; c++)
2008       {
2009         if (sequence[c] == c1)
2010         {
2011           sequence[c] = c2;
2012           count++;
2013         }
2014       }
2015     }
2016     if (count > 0)
2017     {
2018       sequenceChanged();
2019     }
2020
2021     return count;
2022   }
2023
2024   @Override
2025   public String getSequenceStringFromIterator(Iterator<int[]> it)
2026   {
2027     StringBuilder newSequence = new StringBuilder();
2028     while (it.hasNext())
2029     {
2030       int[] block = it.next();
2031       if (it.hasNext())
2032       {
2033         newSequence.append(getSequence(block[0], block[1] + 1));
2034       }
2035       else
2036       {
2037         newSequence.append(getSequence(block[0], block[1]));
2038       }
2039     }
2040
2041     return newSequence.toString();
2042   }
2043
2044   @Override
2045   public int firstResidueOutsideIterator(Iterator<int[]> regions)
2046   {
2047     int start = 0;
2048
2049     if (!regions.hasNext())
2050     {
2051       return findIndex(getStart()) - 1;
2052     }
2053
2054     // Simply walk along the sequence whilst watching for region
2055     // boundaries
2056     int hideStart = getLength();
2057     int hideEnd = -1;
2058     boolean foundStart = false;
2059
2060     // step through the non-gapped positions of the sequence
2061     for (int i = getStart(); i <= getEnd() && (!foundStart); i++)
2062     {
2063       // get alignment position of this residue in the sequence
2064       int p = findIndex(i) - 1;
2065
2066       // update region start/end
2067       while (hideEnd < p && regions.hasNext())
2068       {
2069         int[] region = regions.next();
2070         hideStart = region[0];
2071         hideEnd = region[1];
2072       }
2073       if (hideEnd < p)
2074       {
2075         hideStart = getLength();
2076       }
2077       // update boundary for sequence
2078       if (p < hideStart)
2079       {
2080         start = p;
2081         foundStart = true;
2082       }
2083     }
2084
2085     if (foundStart)
2086     {
2087       return start;
2088     }
2089     // otherwise, sequence was completely hidden
2090     return 0;
2091   }
2092
2093   @Override
2094   public boolean hasHMMProfile()
2095   {
2096     return hmm != null || (datasetSequence!=null && datasetSequence.hasHMMProfile());
2097   }
2098 }