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