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