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