JAL-2829 fixes and unit tests
[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    * DOCUMENT ME!
666    * 
667    * @param desc
668    *          DOCUMENT ME!
669    */
670   @Override
671   public void setDescription(String desc)
672   {
673     this.description = desc;
674   }
675
676   /**
677    * DOCUMENT ME!
678    * 
679    * @return DOCUMENT ME!
680    */
681   @Override
682   public String getDescription()
683   {
684     return this.description;
685   }
686
687   /**
688    * {@inheritDoc}
689    */
690   @Override
691   public int findIndex(int pos)
692   {
693     /*
694      * use a valid, hopefully nearby, cursor if available
695      */
696     if (isValidCursor(cursor))
697     {
698       return findIndex(pos, cursor);
699     }
700
701     int j = start;
702     int i = 0;
703     int startColumn = 0;
704
705     /*
706      * traverse sequence from the start counting gaps; make a note of
707      * the column of the first residue to save in the cursor
708      */
709     while ((i < sequence.length) && (j <= end) && (j <= pos))
710     {
711       if (!Comparison.isGap(sequence[i]))
712       {
713         if (j == start)
714         {
715           startColumn = i;
716         }
717         j++;
718       }
719       i++;
720     }
721
722     if (j == end && j < pos)
723     {
724       return end + 1;
725     }
726
727     updateCursor(pos, i, startColumn);
728     return i;
729   }
730
731   /**
732    * Updates the cursor to the latest found residue and column position
733    * 
734    * @param residuePos
735    *          (start..)
736    * @param column
737    *          (1..)
738    * @param startColumn
739    *          column position of the first sequence residue
740    */
741   protected void updateCursor(int residuePos, int column, int startColumn)
742   {
743     /*
744      * preserve end residue column provided cursor was valid
745      */
746     int endColumn = isValidCursor(cursor) ? cursor.lastColumnPosition : 0;
747     if (residuePos == this.end)
748     {
749       endColumn = column;
750     }
751
752     cursor = new SequenceCursor(this, residuePos, column, startColumn,
753             endColumn, this.changeCount);
754   }
755
756   /**
757    * Answers the aligned column position (1..) for the given residue position
758    * (start..) given a 'hint' of a residue/column location in the neighbourhood.
759    * The hint may be left of, at, or to the right of the required position.
760    * 
761    * @param pos
762    * @param curs
763    * @return
764    */
765   protected int findIndex(int pos, SequenceCursor curs)
766   {
767     if (!isValidCursor(curs))
768     {
769       /*
770        * wrong or invalidated cursor, compute de novo
771        */
772       return findIndex(pos);
773     }
774
775     if (curs.residuePosition == pos)
776     {
777       return curs.columnPosition;
778     }
779
780     /*
781      * move left or right to find pos from hint.position
782      */
783     int col = curs.columnPosition - 1; // convert from base 1 to 0-based array
784                                        // index
785     int newPos = curs.residuePosition;
786     int delta = newPos > pos ? -1 : 1;
787
788     while (newPos != pos)
789     {
790       col += delta; // shift one column left or right
791       if (col < 0 || col == sequence.length)
792       {
793         break;
794       }
795       if (!Comparison.isGap(sequence[col]))
796       {
797         newPos += delta;
798       }
799     }
800
801     col++; // convert back to base 1
802     updateCursor(pos, col, curs.firstColumnPosition);
803
804     return col;
805   }
806
807   /**
808    * {@inheritDoc}
809    */
810   @Override
811   public int findPosition(final int column)
812   {
813     /*
814      * use a valid, hopefully nearby, cursor if available
815      */
816     if (isValidCursor(cursor))
817     {
818       return findPosition(column + 1, cursor);
819     }
820     
821     // TODO recode this more naturally i.e. count residues only
822     // as they are found, not 'in anticipation'
823
824     /*
825      * traverse the sequence counting gaps; note the column position
826      * of the first residue, to save in the cursor
827      */
828     int firstResidueColumn = 0;
829     int lastPosFound = 0;
830     int lastPosFoundColumn = 0;
831     int seqlen = sequence.length;
832
833     if (seqlen > 0 && !Comparison.isGap(sequence[0]))
834     {
835       lastPosFound = start;
836       lastPosFoundColumn = 0;
837     }
838
839     int j = 0;
840     int pos = start;
841
842     while (j < column && j < seqlen)
843     {
844       if (!Comparison.isGap(sequence[j]))
845       {
846         lastPosFound = pos;
847         lastPosFoundColumn = j;
848         if (pos == this.start)
849         {
850           firstResidueColumn = j;
851         }
852         pos++;
853       }
854       j++;
855     }
856     if (j < seqlen && !Comparison.isGap(sequence[j]))
857     {
858       lastPosFound = pos;
859       lastPosFoundColumn = j;
860       if (pos == this.start)
861       {
862         firstResidueColumn = j;
863       }
864     }
865
866     /*
867      * update the cursor to the last residue position found (if any)
868      * (converting column position to base 1)
869      */
870     if (lastPosFound != 0)
871     {
872       updateCursor(lastPosFound, lastPosFoundColumn + 1,
873               firstResidueColumn + 1);
874     }
875
876     return pos;
877   }
878
879   /**
880    * Answers true if the given cursor is not null, is for this sequence object,
881    * and has a token value that matches this object's changeCount, else false.
882    * This allows us to ignore a cursor as 'stale' if the sequence has been
883    * modified since the cursor was created.
884    * 
885    * @param curs
886    * @return
887    */
888   protected boolean isValidCursor(SequenceCursor curs)
889   {
890     if (curs == null || curs.sequence != this || curs.token != changeCount)
891     {
892       return false;
893     }
894     /*
895      * sanity check against range
896      */
897     if (curs.columnPosition < 0 || curs.columnPosition > sequence.length)
898     {
899       return false;
900     }
901     if (curs.residuePosition < start || curs.residuePosition > end)
902     {
903       return false;
904     }
905     return true;
906   }
907
908   /**
909    * Answers the sequence position (start..) for the given aligned column
910    * position (1..), given a hint of a cursor in the neighbourhood. The cursor
911    * may lie left of, at, or to the right of the column position.
912    * 
913    * @param col
914    * @param curs
915    * @return
916    */
917   protected int findPosition(final int col, SequenceCursor curs)
918   {
919     if (!isValidCursor(curs))
920     {
921       /*
922        * wrong or invalidated cursor, compute de novo
923        */
924       return findPosition(col - 1);// ugh back to base 0
925     }
926
927     if (curs.columnPosition == col)
928     {
929       cursor = curs; // in case this method becomes public
930       return curs.residuePosition; // easy case :-)
931     }
932
933     if (curs.lastColumnPosition > 0 && curs.lastColumnPosition < col)
934     {
935       /*
936        * sequence lies entirely to the left of col
937        * - return last residue + 1
938        */
939       return end + 1;
940     }
941
942     if (curs.firstColumnPosition > 0 && curs.firstColumnPosition > col)
943     {
944       /*
945        * sequence lies entirely to the right of col
946        * - return first residue
947        */
948       return start;
949     }
950
951     // todo could choose closest to col out of column,
952     // firstColumnPosition, lastColumnPosition as a start point
953
954     /*
955      * move left or right to find pos from cursor position
956      */
957     int firstResidueColumn = curs.firstColumnPosition;
958     int column = curs.columnPosition - 1; // to base 0
959     int newPos = curs.residuePosition;
960     int delta = curs.columnPosition > col ? -1 : 1;
961     boolean gapped = false;
962     int lastFoundPosition = curs.residuePosition;
963     int lastFoundPositionColumn = curs.columnPosition;
964
965     while (column != col - 1)
966     {
967       column += delta; // shift one column left or right
968       if (column < 0 || column == sequence.length)
969       {
970         break;
971       }
972       gapped = Comparison.isGap(sequence[column]);
973       if (!gapped)
974       {
975         newPos += delta;
976         lastFoundPosition = newPos;
977         lastFoundPositionColumn = column + 1;
978         if (lastFoundPosition == this.start)
979         {
980           firstResidueColumn = column + 1;
981         }
982       }
983     }
984
985     if (cursor == null || lastFoundPosition != cursor.residuePosition)
986     {
987       updateCursor(lastFoundPosition, lastFoundPositionColumn,
988               firstResidueColumn);
989     }
990
991     /*
992      * hack to give position to the right if on a gap
993      * or beyond the length of the sequence (see JAL-2562)
994      */
995     if (delta > 0 && (gapped || column >= sequence.length))
996     {
997       newPos++;
998     }
999
1000     return newPos;
1001   }
1002
1003   /**
1004    * {@inheritDoc}
1005    */
1006   @Override
1007   public Range findPositions(int fromColumn, int toColumn)
1008   {
1009     if (toColumn < fromColumn || fromColumn < 1)
1010     {
1011       return null;
1012     }
1013
1014     /*
1015      * find the first non-gapped position, if any
1016      */
1017     int firstPosition = 0;
1018     int col = fromColumn - 1;
1019     int length = sequence.length;
1020     while (col < length && col < toColumn)
1021     {
1022       if (!Comparison.isGap(sequence[col]))
1023       {
1024         firstPosition = findPosition(col++);
1025         break;
1026       }
1027       col++;
1028     }
1029
1030     if (firstPosition == 0)
1031     {
1032       return null;
1033     }
1034
1035     /*
1036      * find the last non-gapped position
1037      */
1038     int lastPosition = firstPosition;
1039     while (col < length && col < toColumn)
1040     {
1041       if (!Comparison.isGap(sequence[col++]))
1042       {
1043         lastPosition++;
1044       }
1045     }
1046
1047     return new Range(firstPosition, lastPosition);
1048   }
1049
1050   /**
1051    * Returns an int array where indices correspond to each residue in the
1052    * sequence and the element value gives its position in the alignment
1053    * 
1054    * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
1055    *         residues in SequenceI object
1056    */
1057   @Override
1058   public int[] gapMap()
1059   {
1060     String seq = jalview.analysis.AlignSeq.extractGaps(
1061             jalview.util.Comparison.GapChars, new String(sequence));
1062     int[] map = new int[seq.length()];
1063     int j = 0;
1064     int p = 0;
1065
1066     while (j < sequence.length)
1067     {
1068       if (!jalview.util.Comparison.isGap(sequence[j]))
1069       {
1070         map[p++] = j;
1071       }
1072
1073       j++;
1074     }
1075
1076     return map;
1077   }
1078
1079   @Override
1080   public int[] findPositionMap()
1081   {
1082     int map[] = new int[sequence.length];
1083     int j = 0;
1084     int pos = start;
1085     int seqlen = sequence.length;
1086     while ((j < seqlen))
1087     {
1088       map[j] = pos;
1089       if (!jalview.util.Comparison.isGap(sequence[j]))
1090       {
1091         pos++;
1092       }
1093
1094       j++;
1095     }
1096     return map;
1097   }
1098
1099   @Override
1100   public List<int[]> getInsertions()
1101   {
1102     ArrayList<int[]> map = new ArrayList<int[]>();
1103     int lastj = -1, j = 0;
1104     int pos = start;
1105     int seqlen = sequence.length;
1106     while ((j < seqlen))
1107     {
1108       if (jalview.util.Comparison.isGap(sequence[j]))
1109       {
1110         if (lastj == -1)
1111         {
1112           lastj = j;
1113         }
1114       }
1115       else
1116       {
1117         if (lastj != -1)
1118         {
1119           map.add(new int[] { lastj, j - 1 });
1120           lastj = -1;
1121         }
1122       }
1123       j++;
1124     }
1125     if (lastj != -1)
1126     {
1127       map.add(new int[] { lastj, j - 1 });
1128       lastj = -1;
1129     }
1130     return map;
1131   }
1132
1133   @Override
1134   public BitSet getInsertionsAsBits()
1135   {
1136     BitSet map = new BitSet();
1137     int lastj = -1, j = 0;
1138     int pos = start;
1139     int seqlen = sequence.length;
1140     while ((j < seqlen))
1141     {
1142       if (jalview.util.Comparison.isGap(sequence[j]))
1143       {
1144         if (lastj == -1)
1145         {
1146           lastj = j;
1147         }
1148       }
1149       else
1150       {
1151         if (lastj != -1)
1152         {
1153           map.set(lastj, j);
1154           lastj = -1;
1155         }
1156       }
1157       j++;
1158     }
1159     if (lastj != -1)
1160     {
1161       map.set(lastj, j);
1162       lastj = -1;
1163     }
1164     return map;
1165   }
1166
1167   @Override
1168   public void deleteChars(final int i, final int j)
1169   {
1170     int newstart = start, newend = end;
1171     if (i >= sequence.length || i < 0)
1172     {
1173       return;
1174     }
1175
1176     char[] tmp = StringUtils.deleteChars(sequence, i, j);
1177     boolean createNewDs = false;
1178     // TODO: take a (second look) at the dataset creation validation method for
1179     // the very large sequence case
1180     int startIndex = findIndex(start) - 1;
1181     int endIndex = findIndex(end) - 1;
1182     int startDeleteColumn = -1; // for dataset sequence deletions
1183     int deleteCount = 0;
1184
1185     for (int s = i; s < j; s++)
1186     {
1187       if (Comparison.isGap(sequence[s]))
1188       {
1189         continue;
1190       }
1191       deleteCount++;
1192       if (startDeleteColumn == -1)
1193       {
1194         startDeleteColumn = findPosition(s) - start;
1195       }
1196       if (createNewDs)
1197       {
1198         newend--;
1199       }
1200       else
1201       {
1202         if (startIndex == s)
1203         {
1204           /*
1205            * deleting characters from start of sequence; new start is the
1206            * sequence position of the next column (position to the right
1207            * if the column position is gapped)
1208            */
1209           newstart = findPosition(j);
1210           break;
1211         }
1212         else
1213         {
1214           if (endIndex < j)
1215           {
1216             /*
1217              * deleting characters at end of sequence; new end is the sequence
1218              * position of the column before the deletion; subtract 1 if this is
1219              * gapped since findPosition returns the next sequence position
1220              */
1221             newend = findPosition(i - 1);
1222             if (Comparison.isGap(sequence[i - 1]))
1223             {
1224               newend--;
1225             }
1226             break;
1227           }
1228           else
1229           {
1230             createNewDs = true;
1231             newend--;
1232           }
1233         }
1234       }
1235     }
1236
1237     if (createNewDs && this.datasetSequence != null)
1238     {
1239       /*
1240        * if deletion occured in the middle of the sequence,
1241        * construct a new dataset sequence and delete the residues
1242        * that were deleted from the aligned sequence
1243        */
1244       Sequence ds = new Sequence(datasetSequence);
1245       ds.deleteChars(startDeleteColumn, startDeleteColumn + deleteCount);
1246       datasetSequence = ds;
1247       // TODO: remove any non-inheritable properties ?
1248       // TODO: create a sequence mapping (since there is a relation here ?)
1249     }
1250     start = newstart;
1251     end = newend;
1252     sequence = tmp;
1253     sequenceChanged();
1254   }
1255
1256   @Override
1257   public void insertCharAt(int i, int length, char c)
1258   {
1259     char[] tmp = new char[sequence.length + length];
1260
1261     if (i >= sequence.length)
1262     {
1263       System.arraycopy(sequence, 0, tmp, 0, sequence.length);
1264       i = sequence.length;
1265     }
1266     else
1267     {
1268       System.arraycopy(sequence, 0, tmp, 0, i);
1269     }
1270
1271     int index = i;
1272     while (length > 0)
1273     {
1274       tmp[index++] = c;
1275       length--;
1276     }
1277
1278     if (i < sequence.length)
1279     {
1280       System.arraycopy(sequence, i, tmp, index, sequence.length - i);
1281     }
1282
1283     sequence = tmp;
1284     sequenceChanged();
1285   }
1286
1287   @Override
1288   public void insertCharAt(int i, char c)
1289   {
1290     insertCharAt(i, 1, c);
1291   }
1292
1293   @Override
1294   public String getVamsasId()
1295   {
1296     return vamsasId;
1297   }
1298
1299   @Override
1300   public void setVamsasId(String id)
1301   {
1302     vamsasId = id;
1303   }
1304
1305   @Override
1306   public void setDBRefs(DBRefEntry[] dbref)
1307   {
1308     if (dbrefs == null && datasetSequence != null
1309             && this != datasetSequence)
1310     {
1311       datasetSequence.setDBRefs(dbref);
1312       return;
1313     }
1314     dbrefs = dbref;
1315     if (dbrefs != null)
1316     {
1317       DBRefUtils.ensurePrimaries(this);
1318     }
1319   }
1320
1321   @Override
1322   public DBRefEntry[] getDBRefs()
1323   {
1324     if (dbrefs == null && datasetSequence != null
1325             && this != datasetSequence)
1326     {
1327       return datasetSequence.getDBRefs();
1328     }
1329     return dbrefs;
1330   }
1331
1332   @Override
1333   public void addDBRef(DBRefEntry entry)
1334   {
1335     if (datasetSequence != null)
1336     {
1337       datasetSequence.addDBRef(entry);
1338       return;
1339     }
1340
1341     if (dbrefs == null)
1342     {
1343       dbrefs = new DBRefEntry[0];
1344     }
1345
1346     for (DBRefEntryI dbr : dbrefs)
1347     {
1348       if (dbr.updateFrom(entry))
1349       {
1350         /*
1351          * found a dbref that either matched, or could be
1352          * updated from, the new entry - no need to add it
1353          */
1354         return;
1355       }
1356     }
1357
1358     /*
1359      * extend the array to make room for one more
1360      */
1361     // TODO use an ArrayList instead
1362     int j = dbrefs.length;
1363     DBRefEntry[] temp = new DBRefEntry[j + 1];
1364     System.arraycopy(dbrefs, 0, temp, 0, j);
1365     temp[temp.length - 1] = entry;
1366
1367     dbrefs = temp;
1368
1369     DBRefUtils.ensurePrimaries(this);
1370   }
1371
1372   @Override
1373   public void setDatasetSequence(SequenceI seq)
1374   {
1375     if (seq == this)
1376     {
1377       throw new IllegalArgumentException(
1378               "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1379     }
1380     if (seq != null && seq.getDatasetSequence() != null)
1381     {
1382       throw new IllegalArgumentException(
1383               "Implementation error: cascading dataset sequences are not allowed.");
1384     }
1385     datasetSequence = seq;
1386   }
1387
1388   @Override
1389   public SequenceI getDatasetSequence()
1390   {
1391     return datasetSequence;
1392   }
1393
1394   @Override
1395   public AlignmentAnnotation[] getAnnotation()
1396   {
1397     return annotation == null ? null
1398             : annotation
1399                     .toArray(new AlignmentAnnotation[annotation.size()]);
1400   }
1401
1402   @Override
1403   public boolean hasAnnotation(AlignmentAnnotation ann)
1404   {
1405     return annotation == null ? false : annotation.contains(ann);
1406   }
1407
1408   @Override
1409   public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1410   {
1411     if (this.annotation == null)
1412     {
1413       this.annotation = new Vector<AlignmentAnnotation>();
1414     }
1415     if (!this.annotation.contains(annotation))
1416     {
1417       this.annotation.addElement(annotation);
1418     }
1419     annotation.setSequenceRef(this);
1420   }
1421
1422   @Override
1423   public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1424   {
1425     if (this.annotation != null)
1426     {
1427       this.annotation.removeElement(annotation);
1428       if (this.annotation.size() == 0)
1429       {
1430         this.annotation = null;
1431       }
1432     }
1433   }
1434
1435   /**
1436    * test if this is a valid candidate for another sequence's dataset sequence.
1437    * 
1438    */
1439   private boolean isValidDatasetSequence()
1440   {
1441     if (datasetSequence != null)
1442     {
1443       return false;
1444     }
1445     for (int i = 0; i < sequence.length; i++)
1446     {
1447       if (jalview.util.Comparison.isGap(sequence[i]))
1448       {
1449         return false;
1450       }
1451     }
1452     return true;
1453   }
1454
1455   @Override
1456   public SequenceI deriveSequence()
1457   {
1458     Sequence seq = null;
1459     if (datasetSequence == null)
1460     {
1461       if (isValidDatasetSequence())
1462       {
1463         // Use this as dataset sequence
1464         seq = new Sequence(getName(), "", 1, -1);
1465         seq.setDatasetSequence(this);
1466         seq.initSeqFrom(this, getAnnotation());
1467         return seq;
1468       }
1469       else
1470       {
1471         // Create a new, valid dataset sequence
1472         createDatasetSequence();
1473       }
1474     }
1475     return new Sequence(this);
1476   }
1477
1478   private boolean _isNa;
1479
1480   private int _seqhash = 0;
1481
1482   /**
1483    * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1484    * true
1485    */
1486   @Override
1487   public boolean isProtein()
1488   {
1489     if (datasetSequence != null)
1490     {
1491       return datasetSequence.isProtein();
1492     }
1493     if (_seqhash != sequence.hashCode())
1494     {
1495       _seqhash = sequence.hashCode();
1496       _isNa = Comparison.isNucleotide(this);
1497     }
1498     return !_isNa;
1499   };
1500
1501   /*
1502    * (non-Javadoc)
1503    * 
1504    * @see jalview.datamodel.SequenceI#createDatasetSequence()
1505    */
1506   @Override
1507   public SequenceI createDatasetSequence()
1508   {
1509     if (datasetSequence == null)
1510     {
1511       Sequence dsseq = new Sequence(getName(),
1512               AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
1513                       getSequenceAsString()),
1514               getStart(), getEnd());
1515
1516       datasetSequence = dsseq;
1517
1518       dsseq.setDescription(description);
1519       // move features and database references onto dataset sequence
1520       dsseq.sequenceFeatureStore = sequenceFeatureStore;
1521       sequenceFeatureStore = null;
1522       dsseq.dbrefs = dbrefs;
1523       dbrefs = null;
1524       // TODO: search and replace any references to this sequence with
1525       // references to the dataset sequence in Mappings on dbref
1526       dsseq.pdbIds = pdbIds;
1527       pdbIds = null;
1528       datasetSequence.updatePDBIds();
1529       if (annotation != null)
1530       {
1531         // annotation is cloned rather than moved, to preserve what's currently
1532         // on the alignment
1533         for (AlignmentAnnotation aa : annotation)
1534         {
1535           AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1536           _aa.sequenceRef = datasetSequence;
1537           _aa.adjustForAlignment(); // uses annotation's own record of
1538                                     // sequence-column mapping
1539           datasetSequence.addAlignmentAnnotation(_aa);
1540         }
1541       }
1542     }
1543     return datasetSequence;
1544   }
1545
1546   /*
1547    * (non-Javadoc)
1548    * 
1549    * @see
1550    * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1551    * annotations)
1552    */
1553   @Override
1554   public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1555   {
1556     if (annotation != null)
1557     {
1558       annotation.removeAllElements();
1559     }
1560     if (annotations != null)
1561     {
1562       for (int i = 0; i < annotations.length; i++)
1563       {
1564         if (annotations[i] != null)
1565         {
1566           addAlignmentAnnotation(annotations[i]);
1567         }
1568       }
1569     }
1570   }
1571
1572   @Override
1573   public AlignmentAnnotation[] getAnnotation(String label)
1574   {
1575     if (annotation == null || annotation.size() == 0)
1576     {
1577       return null;
1578     }
1579
1580     Vector<AlignmentAnnotation> subset = new Vector<AlignmentAnnotation>();
1581     Enumeration<AlignmentAnnotation> e = annotation.elements();
1582     while (e.hasMoreElements())
1583     {
1584       AlignmentAnnotation ann = e.nextElement();
1585       if (ann.label != null && ann.label.equals(label))
1586       {
1587         subset.addElement(ann);
1588       }
1589     }
1590     if (subset.size() == 0)
1591     {
1592       return null;
1593     }
1594     AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1595     int i = 0;
1596     e = subset.elements();
1597     while (e.hasMoreElements())
1598     {
1599       anns[i++] = e.nextElement();
1600     }
1601     subset.removeAllElements();
1602     return anns;
1603   }
1604
1605   @Override
1606   public boolean updatePDBIds()
1607   {
1608     if (datasetSequence != null)
1609     {
1610       // TODO: could merge DBRefs
1611       return datasetSequence.updatePDBIds();
1612     }
1613     if (dbrefs == null || dbrefs.length == 0)
1614     {
1615       return false;
1616     }
1617     boolean added = false;
1618     for (DBRefEntry dbr : dbrefs)
1619     {
1620       if (DBRefSource.PDB.equals(dbr.getSource()))
1621       {
1622         /*
1623          * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1624          * PDB id is not already present in a 'matching' PDBEntry
1625          * Constructor parses out a chain code if appended to the accession id
1626          * (a fudge used to 'store' the chain code in the DBRef)
1627          */
1628         PDBEntry pdbe = new PDBEntry(dbr);
1629         added |= addPDBId(pdbe);
1630       }
1631     }
1632     return added;
1633   }
1634
1635   @Override
1636   public void transferAnnotation(SequenceI entry, Mapping mp)
1637   {
1638     if (datasetSequence != null)
1639     {
1640       datasetSequence.transferAnnotation(entry, mp);
1641       return;
1642     }
1643     if (entry.getDatasetSequence() != null)
1644     {
1645       transferAnnotation(entry.getDatasetSequence(), mp);
1646       return;
1647     }
1648     // transfer any new features from entry onto sequence
1649     if (entry.getSequenceFeatures() != null)
1650     {
1651
1652       List<SequenceFeature> sfs = entry.getSequenceFeatures();
1653       for (SequenceFeature feature : sfs)
1654       {
1655        SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1656                 : new SequenceFeature[] { new SequenceFeature(feature) };
1657         if (sf != null)
1658         {
1659           for (int sfi = 0; sfi < sf.length; sfi++)
1660           {
1661             addSequenceFeature(sf[sfi]);
1662           }
1663         }
1664       }
1665     }
1666
1667     // transfer PDB entries
1668     if (entry.getAllPDBEntries() != null)
1669     {
1670       Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1671       while (e.hasMoreElements())
1672       {
1673         PDBEntry pdb = e.nextElement();
1674         addPDBId(pdb);
1675       }
1676     }
1677     // transfer database references
1678     DBRefEntry[] entryRefs = entry.getDBRefs();
1679     if (entryRefs != null)
1680     {
1681       for (int r = 0; r < entryRefs.length; r++)
1682       {
1683         DBRefEntry newref = new DBRefEntry(entryRefs[r]);
1684         if (newref.getMap() != null && mp != null)
1685         {
1686           // remap ref using our local mapping
1687         }
1688         // we also assume all version string setting is done by dbSourceProxy
1689         /*
1690          * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1691          * newref.setSource(dbSource); }
1692          */
1693         addDBRef(newref);
1694       }
1695     }
1696   }
1697
1698   /**
1699    * @return The index (zero-based) on this sequence in the MSA. It returns
1700    *         {@code -1} if this information is not available.
1701    */
1702   @Override
1703   public int getIndex()
1704   {
1705     return index;
1706   }
1707
1708   /**
1709    * Defines the position of this sequence in the MSA. Use the value {@code -1}
1710    * if this information is undefined.
1711    * 
1712    * @param The
1713    *          position for this sequence. This value is zero-based (zero for
1714    *          this first sequence)
1715    */
1716   @Override
1717   public void setIndex(int value)
1718   {
1719     index = value;
1720   }
1721
1722   @Override
1723   public void setRNA(RNA r)
1724   {
1725     rna = r;
1726   }
1727
1728   @Override
1729   public RNA getRNA()
1730   {
1731     return rna;
1732   }
1733
1734   @Override
1735   public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1736           String label)
1737   {
1738     List<AlignmentAnnotation> result = new ArrayList<AlignmentAnnotation>();
1739     if (this.annotation != null)
1740     {
1741       for (AlignmentAnnotation ann : annotation)
1742       {
1743         if (ann.calcId != null && ann.calcId.equals(calcId)
1744                 && ann.label != null && ann.label.equals(label))
1745         {
1746           result.add(ann);
1747         }
1748       }
1749     }
1750     return result;
1751   }
1752
1753   @Override
1754   public String toString()
1755   {
1756     return getDisplayId(false);
1757   }
1758
1759   @Override
1760   public PDBEntry getPDBEntry(String pdbIdStr)
1761   {
1762     if (getDatasetSequence() != null)
1763     {
1764       return getDatasetSequence().getPDBEntry(pdbIdStr);
1765     }
1766     if (pdbIds == null)
1767     {
1768       return null;
1769     }
1770     List<PDBEntry> entries = getAllPDBEntries();
1771     for (PDBEntry entry : entries)
1772     {
1773       if (entry.getId().equalsIgnoreCase(pdbIdStr))
1774       {
1775         return entry;
1776       }
1777     }
1778     return null;
1779   }
1780
1781   @Override
1782   public List<DBRefEntry> getPrimaryDBRefs()
1783   {
1784     if (datasetSequence != null)
1785     {
1786       return datasetSequence.getPrimaryDBRefs();
1787     }
1788     if (dbrefs == null || dbrefs.length == 0)
1789     {
1790       return Collections.emptyList();
1791     }
1792     synchronized (dbrefs)
1793     {
1794       List<DBRefEntry> primaries = new ArrayList<DBRefEntry>();
1795       DBRefEntry[] tmp = new DBRefEntry[1];
1796       for (DBRefEntry ref : dbrefs)
1797       {
1798         if (!ref.isPrimaryCandidate())
1799         {
1800           continue;
1801         }
1802         if (ref.hasMap())
1803         {
1804           MapList mp = ref.getMap().getMap();
1805           if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1806           {
1807             // map only involves a subsequence, so cannot be primary
1808             continue;
1809           }
1810         }
1811         // whilst it looks like it is a primary ref, we also sanity check type
1812         if (DBRefUtils.getCanonicalName(DBRefSource.PDB)
1813                 .equals(DBRefUtils.getCanonicalName(ref.getSource())))
1814         {
1815           // PDB dbrefs imply there should be a PDBEntry associated
1816           // TODO: tighten PDB dbrefs
1817           // formally imply Jalview has actually downloaded and
1818           // parsed the pdb file. That means there should be a cached file
1819           // handle on the PDBEntry, and a real mapping between sequence and
1820           // extracted sequence from PDB file
1821           PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1822           if (pdbentry != null && pdbentry.getFile() != null)
1823           {
1824             primaries.add(ref);
1825           }
1826           continue;
1827         }
1828         // check standard protein or dna sources
1829         tmp[0] = ref;
1830         DBRefEntry[] res = DBRefUtils.selectDbRefs(!isProtein(), tmp);
1831         if (res != null && res[0] == tmp[0])
1832         {
1833           primaries.add(ref);
1834           continue;
1835         }
1836       }
1837       return primaries;
1838     }
1839   }
1840
1841   /**
1842    * {@inheritDoc}
1843    */
1844   @Override
1845   public List<SequenceFeature> findFeatures(int fromColumn, int toColumn,
1846           String... types)
1847   {
1848     int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
1849     int endPos = fromColumn == toColumn ? startPos
1850             : findPosition(toColumn - 1);
1851
1852     List<SequenceFeature> result = getFeatures().findFeatures(startPos,
1853             endPos, types);
1854
1855     /*
1856      * if end column is gapped, endPos may be to the right, 
1857      * and we may have included adjacent or enclosing features;
1858      * remove any that are not enclosing, non-contact features
1859      */
1860     boolean endColumnIsGapped = toColumn > 0 && toColumn <= sequence.length
1861             && Comparison.isGap(sequence[toColumn - 1]);
1862     if (endPos > this.end || endColumnIsGapped)
1863     {
1864       ListIterator<SequenceFeature> it = result.listIterator();
1865       while (it.hasNext())
1866       {
1867         SequenceFeature sf = it.next();
1868         int sfBegin = sf.getBegin();
1869         int sfEnd = sf.getEnd();
1870         int featureStartColumn = findIndex(sfBegin);
1871         if (featureStartColumn > toColumn)
1872         {
1873           it.remove();
1874         }
1875         else if (featureStartColumn < fromColumn)
1876         {
1877           int featureEndColumn = sfEnd == sfBegin ? featureStartColumn
1878                   : findIndex(sfEnd);
1879           if (featureEndColumn < fromColumn)
1880           {
1881             it.remove();
1882           }
1883           else if (featureEndColumn > toColumn && sf.isContactFeature())
1884           {
1885             /*
1886              * remove an enclosing feature if it is a contact feature
1887              */
1888             it.remove();
1889           }
1890         }
1891       }
1892     }
1893
1894     return result;
1895   }
1896
1897   /**
1898    * Invalidates any stale cursors (forcing recalculation) by incrementing the
1899    * token that has to match the one presented by the cursor
1900    */
1901   @Override
1902   public void sequenceChanged()
1903   {
1904     changeCount++;
1905   }
1906
1907   /**
1908    * {@inheritDoc}
1909    */
1910   @Override
1911   public int replace(char c1, char c2)
1912   {
1913     if (c1 == c2)
1914     {
1915       return 0;
1916     }
1917     int count = 0;
1918     synchronized (sequence)
1919     {
1920       for (int c = 0; c < sequence.length; c++)
1921       {
1922         if (sequence[c] == c1)
1923         {
1924           sequence[c] = c2;
1925           count++;
1926         }
1927       }
1928     }
1929     if (count > 0)
1930     {
1931       sequenceChanged();
1932     }
1933
1934     return count;
1935   }
1936 }