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