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