JAL-3980 JAL-3979 TODOs
[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     // TODO JAL-3980 maintain as sorted list
1419     if (datasetSequence != null)
1420     {
1421       datasetSequence.addDBRef(entry);
1422       return;
1423     }
1424
1425     if (dbrefs == null)
1426     {
1427       dbrefs = new DBModList<>();
1428     }
1429     // TODO JAL-3979 LOOK UP RATHER THAN SWEEP FOR EFFICIENCY
1430
1431     for (int ib = 0, nb = dbrefs.size(); ib < nb; ib++)
1432     {
1433       if (dbrefs.get(ib).updateFrom(entry))
1434       {
1435         /*
1436          * found a dbref that either matched, or could be
1437          * updated from, the new entry - no need to add it
1438          */
1439         return;
1440       }
1441     }
1442
1443     // /// BH OUCH!
1444     // /*
1445     // * extend the array to make room for one more
1446     // */
1447     // // TODO use an ArrayList instead
1448     // int j = dbrefs.length;
1449     // List<DBRefEntry> temp = new DBRefEntry[j + 1];
1450     // System.arraycopy(dbrefs, 0, temp, 0, j);
1451     // temp[temp.length - 1] = entry;
1452     //
1453     // dbrefs = temp;
1454
1455     dbrefs.add(entry);
1456   }
1457
1458   @Override
1459   public void setDatasetSequence(SequenceI seq)
1460   {
1461     if (seq == this)
1462     {
1463       throw new IllegalArgumentException(
1464               "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1465     }
1466     if (seq != null && seq.getDatasetSequence() != null)
1467     {
1468       throw new IllegalArgumentException(
1469               "Implementation error: cascading dataset sequences are not allowed.");
1470     }
1471     datasetSequence = seq;
1472   }
1473
1474   @Override
1475   public SequenceI getDatasetSequence()
1476   {
1477     return datasetSequence;
1478   }
1479
1480   @Override
1481   public AlignmentAnnotation[] getAnnotation()
1482   {
1483     return annotation == null ? null
1484             : annotation
1485                     .toArray(new AlignmentAnnotation[annotation.size()]);
1486   }
1487
1488   @Override
1489   public boolean hasAnnotation(AlignmentAnnotation ann)
1490   {
1491     return annotation == null ? false : annotation.contains(ann);
1492   }
1493
1494   @Override
1495   public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1496   {
1497     if (this.annotation == null)
1498     {
1499       this.annotation = new Vector<>();
1500     }
1501     if (!this.annotation.contains(annotation))
1502     {
1503       this.annotation.addElement(annotation);
1504     }
1505     annotation.setSequenceRef(this);
1506   }
1507
1508   @Override
1509   public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1510   {
1511     if (this.annotation != null)
1512     {
1513       this.annotation.removeElement(annotation);
1514       if (this.annotation.size() == 0)
1515       {
1516         this.annotation = null;
1517       }
1518     }
1519   }
1520
1521   /**
1522    * test if this is a valid candidate for another sequence's dataset sequence.
1523    * 
1524    */
1525   private boolean isValidDatasetSequence()
1526   {
1527     if (datasetSequence != null)
1528     {
1529       return false;
1530     }
1531     for (int i = 0; i < sequence.length; i++)
1532     {
1533       if (jalview.util.Comparison.isGap(sequence[i]))
1534       {
1535         return false;
1536       }
1537     }
1538     return true;
1539   }
1540
1541   @Override
1542   public SequenceI deriveSequence()
1543   {
1544     Sequence seq = null;
1545     if (datasetSequence == null)
1546     {
1547       if (isValidDatasetSequence())
1548       {
1549         // Use this as dataset sequence
1550         seq = new Sequence(getName(), "", 1, -1);
1551         seq.setDatasetSequence(this);
1552         seq.initSeqFrom(this, getAnnotation());
1553         return seq;
1554       }
1555       else
1556       {
1557         // Create a new, valid dataset sequence
1558         createDatasetSequence();
1559       }
1560     }
1561     return new Sequence(this);
1562   }
1563
1564   private boolean _isNa;
1565
1566   private int _seqhash = 0;
1567
1568   private List<DBRefEntry> primaryRefs;
1569
1570   /**
1571    * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1572    * true
1573    */
1574   @Override
1575   public boolean isProtein()
1576   {
1577     if (datasetSequence != null)
1578     {
1579       return datasetSequence.isProtein();
1580     }
1581     if (_seqhash != sequence.hashCode())
1582     {
1583       _seqhash = sequence.hashCode();
1584       _isNa = Comparison.isNucleotide(this);
1585     }
1586     return !_isNa;
1587   }
1588
1589   /*
1590    * (non-Javadoc)
1591    * 
1592    * @see jalview.datamodel.SequenceI#createDatasetSequence()
1593    */
1594   @Override
1595   public SequenceI createDatasetSequence()
1596   {
1597     if (datasetSequence == null)
1598     {
1599       Sequence dsseq = new Sequence(getName(),
1600               AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
1601                       getSequenceAsString()),
1602               getStart(), getEnd());
1603
1604       datasetSequence = dsseq;
1605
1606       dsseq.setDescription(description);
1607       // move features and database references onto dataset sequence
1608       dsseq.sequenceFeatureStore = sequenceFeatureStore;
1609       sequenceFeatureStore = null;
1610       dsseq.dbrefs = dbrefs;
1611       dbrefs = null;
1612       // TODO: search and replace any references to this sequence with
1613       // references to the dataset sequence in Mappings on dbref
1614       dsseq.pdbIds = pdbIds;
1615       pdbIds = null;
1616       datasetSequence.updatePDBIds();
1617       if (annotation != null)
1618       {
1619         // annotation is cloned rather than moved, to preserve what's currently
1620         // on the alignment
1621         for (AlignmentAnnotation aa : annotation)
1622         {
1623           AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1624           _aa.sequenceRef = datasetSequence;
1625           _aa.adjustForAlignment(); // uses annotation's own record of
1626                                     // sequence-column mapping
1627           datasetSequence.addAlignmentAnnotation(_aa);
1628         }
1629       }
1630     }
1631     return datasetSequence;
1632   }
1633
1634   /*
1635    * (non-Javadoc)
1636    * 
1637    * @see
1638    * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1639    * annotations)
1640    */
1641   @Override
1642   public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1643   {
1644     if (annotation != null)
1645     {
1646       annotation.removeAllElements();
1647     }
1648     if (annotations != null)
1649     {
1650       for (int i = 0; i < annotations.length; i++)
1651       {
1652         if (annotations[i] != null)
1653         {
1654           addAlignmentAnnotation(annotations[i]);
1655         }
1656       }
1657     }
1658   }
1659
1660   @Override
1661   public AlignmentAnnotation[] getAnnotation(String label)
1662   {
1663     if (annotation == null || annotation.size() == 0)
1664     {
1665       return null;
1666     }
1667
1668     Vector<AlignmentAnnotation> subset = new Vector<>();
1669     Enumeration<AlignmentAnnotation> e = annotation.elements();
1670     while (e.hasMoreElements())
1671     {
1672       AlignmentAnnotation ann = e.nextElement();
1673       if (ann.label != null && ann.label.equals(label))
1674       {
1675         subset.addElement(ann);
1676       }
1677     }
1678     if (subset.size() == 0)
1679     {
1680       return null;
1681     }
1682     AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1683     int i = 0;
1684     e = subset.elements();
1685     while (e.hasMoreElements())
1686     {
1687       anns[i++] = e.nextElement();
1688     }
1689     subset.removeAllElements();
1690     return anns;
1691   }
1692
1693   @Override
1694   public boolean updatePDBIds()
1695   {
1696     if (datasetSequence != null)
1697     {
1698       // TODO: could merge DBRefs
1699       return datasetSequence.updatePDBIds();
1700     }
1701     if (dbrefs == null || dbrefs.size() == 0)
1702     {
1703       return false;
1704     }
1705     boolean added = false;
1706     for (int ib = 0, nb = dbrefs.size(); ib < nb; ib++)
1707     {
1708       DBRefEntry dbr = dbrefs.get(ib);
1709       if (DBRefSource.PDB.equals(dbr.getSource()))
1710       {
1711         /*
1712          * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1713          * PDB id is not already present in a 'matching' PDBEntry
1714          * Constructor parses out a chain code if appended to the accession id
1715          * (a fudge used to 'store' the chain code in the DBRef)
1716          */
1717         PDBEntry pdbe = new PDBEntry(dbr);
1718         added |= addPDBId(pdbe);
1719       }
1720     }
1721     return added;
1722   }
1723
1724   @Override
1725   public void transferAnnotation(SequenceI entry, Mapping mp)
1726   {
1727     if (datasetSequence != null)
1728     {
1729       datasetSequence.transferAnnotation(entry, mp);
1730       return;
1731     }
1732     if (entry.getDatasetSequence() != null)
1733     {
1734       transferAnnotation(entry.getDatasetSequence(), mp);
1735       return;
1736     }
1737     // transfer any new features from entry onto sequence
1738     if (entry.getSequenceFeatures() != null)
1739     {
1740
1741       List<SequenceFeature> sfs = entry.getSequenceFeatures();
1742       for (SequenceFeature feature : sfs)
1743       {
1744         SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1745                 : new SequenceFeature[]
1746                 { new SequenceFeature(feature) };
1747         if (sf != null)
1748         {
1749           for (int sfi = 0; sfi < sf.length; sfi++)
1750           {
1751             addSequenceFeature(sf[sfi]);
1752           }
1753         }
1754       }
1755     }
1756
1757     // transfer PDB entries
1758     if (entry.getAllPDBEntries() != null)
1759     {
1760       Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1761       while (e.hasMoreElements())
1762       {
1763         PDBEntry pdb = e.nextElement();
1764         addPDBId(pdb);
1765       }
1766     }
1767     // transfer database references
1768     List<DBRefEntry> entryRefs = entry.getDBRefs();
1769     if (entryRefs != null)
1770     {
1771       for (int r = 0, n = entryRefs.size(); r < n; r++)
1772       {
1773         DBRefEntry newref = new DBRefEntry(entryRefs.get(r));
1774         if (newref.getMap() != null && mp != null)
1775         {
1776           // remap ref using our local mapping
1777         }
1778         // we also assume all version string setting is done by dbSourceProxy
1779         /*
1780          * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1781          * newref.setSource(dbSource); }
1782          */
1783         addDBRef(newref);
1784       }
1785     }
1786   }
1787
1788   @Override
1789   public void setRNA(RNA r)
1790   {
1791     rna = r;
1792   }
1793
1794   @Override
1795   public RNA getRNA()
1796   {
1797     return rna;
1798   }
1799
1800   @Override
1801   public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1802           String label)
1803   {
1804     return getAlignmentAnnotations(calcId, label, null, true);
1805   }
1806
1807   @Override
1808   public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1809           String label, String description)
1810   {
1811     return getAlignmentAnnotations(calcId, label, description, false);
1812   }
1813
1814   private List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1815           String label, String description, boolean ignoreDescription)
1816   {
1817     List<AlignmentAnnotation> result = new ArrayList<>();
1818     if (this.annotation != null)
1819     {
1820       for (AlignmentAnnotation ann : annotation)
1821       {
1822         if ((ann.calcId != null && ann.calcId.equals(calcId))
1823                 && (ann.label != null && ann.label.equals(label))
1824                 && ((ignoreDescription && description == null)
1825                         || (ann.description != null
1826                                 && ann.description.equals(description))))
1827
1828         {
1829           result.add(ann);
1830         }
1831       }
1832     }
1833     return result;
1834   }
1835
1836   @Override
1837   public String toString()
1838   {
1839     return getDisplayId(false);
1840   }
1841
1842   @Override
1843   public PDBEntry getPDBEntry(String pdbIdStr)
1844   {
1845     if (getDatasetSequence() != null)
1846     {
1847       return getDatasetSequence().getPDBEntry(pdbIdStr);
1848     }
1849     if (pdbIds == null)
1850     {
1851       return null;
1852     }
1853     List<PDBEntry> entries = getAllPDBEntries();
1854     for (PDBEntry entry : entries)
1855     {
1856       if (entry.getId().equalsIgnoreCase(pdbIdStr))
1857       {
1858         return entry;
1859       }
1860     }
1861     return null;
1862   }
1863
1864   private List<DBRefEntry> tmpList;
1865
1866   @Override
1867   public List<DBRefEntry> getPrimaryDBRefs()
1868   {
1869     if (datasetSequence != null)
1870     {
1871       return datasetSequence.getPrimaryDBRefs();
1872     }
1873     if (dbrefs == null || dbrefs.size() == 0)
1874     {
1875       return Collections.emptyList();
1876     }
1877     synchronized (dbrefs)
1878     {
1879       if (refModCount == dbrefs.getModCount() && primaryRefs != null)
1880       {
1881         return primaryRefs; // no changes
1882       }
1883       refModCount = dbrefs.getModCount();
1884       List<DBRefEntry> primaries = (primaryRefs == null
1885               ? (primaryRefs = new ArrayList<>())
1886               : primaryRefs);
1887       primaries.clear();
1888       if (tmpList == null)
1889       {
1890         tmpList = new ArrayList<>();
1891         tmpList.add(null); // for replacement
1892       }
1893       for (int i = 0, n = dbrefs.size(); i < n; i++)
1894       {
1895         DBRefEntry ref = dbrefs.get(i);
1896         if (!ref.isPrimaryCandidate())
1897         {
1898           continue;
1899         }
1900         if (ref.hasMap())
1901         {
1902           MapList mp = ref.getMap().getMap();
1903           if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1904           {
1905             // map only involves a subsequence, so cannot be primary
1906             continue;
1907           }
1908         }
1909         // whilst it looks like it is a primary ref, we also sanity check type
1910         if (DBRefSource.PDB_CANONICAL_NAME
1911                 .equals(ref.getCanonicalSourceName()))
1912         {
1913           // PDB dbrefs imply there should be a PDBEntry associated
1914           // TODO: tighten PDB dbrefs
1915           // formally imply Jalview has actually downloaded and
1916           // parsed the pdb file. That means there should be a cached file
1917           // handle on the PDBEntry, and a real mapping between sequence and
1918           // extracted sequence from PDB file
1919           PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1920           if (pdbentry == null || pdbentry.getFile() == null)
1921           {
1922             continue;
1923           }
1924         }
1925         else
1926         {
1927           // check standard protein or dna sources
1928           tmpList.set(0, ref);
1929           List<DBRefEntry> res = DBRefUtils.selectDbRefs(!isProtein(),
1930                   tmpList);
1931           if (res == null || res.get(0) != tmpList.get(0))
1932           {
1933             continue;
1934           }
1935         }
1936         primaries.add(ref);
1937       }
1938
1939       // version must be not null, as otherwise it will not be a candidate,
1940       // above
1941       DBRefUtils.ensurePrimaries(this, primaries);
1942       return primaries;
1943     }
1944   }
1945
1946   /**
1947    * {@inheritDoc}
1948    */
1949   @Override
1950   public List<SequenceFeature> findFeatures(int fromColumn, int toColumn,
1951           String... types)
1952   {
1953     int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
1954     int endPos = fromColumn == toColumn ? startPos
1955             : findPosition(toColumn - 1);
1956
1957     List<SequenceFeature> result = getFeatures().findFeatures(startPos,
1958             endPos, types);
1959
1960     /*
1961      * if end column is gapped, endPos may be to the right, 
1962      * and we may have included adjacent or enclosing features;
1963      * remove any that are not enclosing, non-contact features
1964      */
1965     boolean endColumnIsGapped = toColumn > 0 && toColumn <= sequence.length
1966             && Comparison.isGap(sequence[toColumn - 1]);
1967     if (endPos > this.end || endColumnIsGapped)
1968     {
1969       ListIterator<SequenceFeature> it = result.listIterator();
1970       while (it.hasNext())
1971       {
1972         SequenceFeature sf = it.next();
1973         int sfBegin = sf.getBegin();
1974         int sfEnd = sf.getEnd();
1975         int featureStartColumn = findIndex(sfBegin);
1976         if (featureStartColumn > toColumn)
1977         {
1978           it.remove();
1979         }
1980         else if (featureStartColumn < fromColumn)
1981         {
1982           int featureEndColumn = sfEnd == sfBegin ? featureStartColumn
1983                   : findIndex(sfEnd);
1984           if (featureEndColumn < fromColumn)
1985           {
1986             it.remove();
1987           }
1988           else if (featureEndColumn > toColumn && sf.isContactFeature())
1989           {
1990             /*
1991              * remove an enclosing feature if it is a contact feature
1992              */
1993             it.remove();
1994           }
1995         }
1996       }
1997     }
1998
1999     return result;
2000   }
2001
2002   /**
2003    * Invalidates any stale cursors (forcing recalculation) by incrementing the
2004    * token that has to match the one presented by the cursor
2005    */
2006   @Override
2007   public void sequenceChanged()
2008   {
2009     changeCount++;
2010   }
2011
2012   /**
2013    * {@inheritDoc}
2014    */
2015   @Override
2016   public int replace(char c1, char c2)
2017   {
2018     if (c1 == c2)
2019     {
2020       return 0;
2021     }
2022     int count = 0;
2023     synchronized (sequence)
2024     {
2025       for (int c = 0; c < sequence.length; c++)
2026       {
2027         if (sequence[c] == c1)
2028         {
2029           sequence[c] = c2;
2030           count++;
2031         }
2032       }
2033     }
2034     if (count > 0)
2035     {
2036       sequenceChanged();
2037     }
2038
2039     return count;
2040   }
2041
2042   @Override
2043   public String getSequenceStringFromIterator(Iterator<int[]> it)
2044   {
2045     StringBuilder newSequence = new StringBuilder();
2046     while (it.hasNext())
2047     {
2048       int[] block = it.next();
2049       if (it.hasNext())
2050       {
2051         newSequence.append(getSequence(block[0], block[1] + 1));
2052       }
2053       else
2054       {
2055         newSequence.append(getSequence(block[0], block[1]));
2056       }
2057     }
2058
2059     return newSequence.toString();
2060   }
2061
2062   @Override
2063   public int firstResidueOutsideIterator(Iterator<int[]> regions)
2064   {
2065     int start = 0;
2066
2067     if (!regions.hasNext())
2068     {
2069       return findIndex(getStart()) - 1;
2070     }
2071
2072     // Simply walk along the sequence whilst watching for region
2073     // boundaries
2074     int hideStart = getLength();
2075     int hideEnd = -1;
2076     boolean foundStart = false;
2077
2078     // step through the non-gapped positions of the sequence
2079     for (int i = getStart(); i <= getEnd() && (!foundStart); i++)
2080     {
2081       // get alignment position of this residue in the sequence
2082       int p = findIndex(i) - 1;
2083
2084       // update region start/end
2085       while (hideEnd < p && regions.hasNext())
2086       {
2087         int[] region = regions.next();
2088         hideStart = region[0];
2089         hideEnd = region[1];
2090       }
2091       if (hideEnd < p)
2092       {
2093         hideStart = getLength();
2094       }
2095       // update boundary for sequence
2096       if (p < hideStart)
2097       {
2098         start = p;
2099         foundStart = true;
2100       }
2101     }
2102
2103     if (foundStart)
2104     {
2105       return start;
2106     }
2107     // otherwise, sequence was completely hidden
2108     return 0;
2109   }
2110 }