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