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