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