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