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