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