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