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