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