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