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