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