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