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