JAL-2446 add call to SequenceFeatures.delete(); use varargs for type
[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.util.Comparison;
27 import jalview.util.DBRefUtils;
28 import jalview.util.MapList;
29 import jalview.util.StringUtils;
30
31 import java.util.ArrayList;
32 import java.util.Arrays;
33 import java.util.Collections;
34 import java.util.Enumeration;
35 import java.util.List;
36 import java.util.Vector;
37
38 import fr.orsay.lri.varna.models.rna.RNA;
39
40 /**
41  * 
42  * Implements the SequenceI interface for a char[] based sequence object.
43  * 
44  * @author $author$
45  * @version $Revision$
46  */
47 public class Sequence extends ASequence implements SequenceI
48 {
49   SequenceI datasetSequence;
50
51   String name;
52
53   private char[] sequence;
54
55   String description;
56
57   int start;
58
59   int end;
60
61   Vector<PDBEntry> pdbIds;
62
63   String vamsasId;
64
65   DBRefEntry[] dbrefs;
66
67   RNA rna;
68
69   /**
70    * This annotation is displayed below the alignment but the positions are tied
71    * to the residues of this sequence
72    *
73    * TODO: change to List<>
74    */
75   Vector<AlignmentAnnotation> annotation;
76
77   /**
78    * The index of the sequence in a MSA
79    */
80   int index = -1;
81
82   /** array of sequence features - may not be null for a valid sequence object */
83   public SequenceFeature[] sequenceFeatures;
84
85   private SequenceFeatures sequenceFeatureStore;
86
87   /**
88    * Creates a new Sequence object.
89    * 
90    * @param name
91    *          display name string
92    * @param sequence
93    *          string to form a possibly gapped sequence out of
94    * @param start
95    *          first position of non-gap residue in the sequence
96    * @param end
97    *          last position of ungapped residues (nearly always only used for
98    *          display purposes)
99    */
100   public Sequence(String name, String sequence, int start, int end)
101   {
102     initSeqAndName(name, sequence.toCharArray(), start, end);
103   }
104
105   public Sequence(String name, char[] sequence, int start, int end)
106   {
107     initSeqAndName(name, sequence, start, end);
108   }
109
110   /**
111    * Stage 1 constructor - assign name, sequence, and set start and end fields.
112    * start and end are updated values from name2 if it ends with /start-end
113    * 
114    * @param name2
115    * @param sequence2
116    * @param start2
117    * @param end2
118    */
119   protected void initSeqAndName(String name2, char[] sequence2, int start2,
120           int end2)
121   {
122     this.name = name2;
123     this.sequence = sequence2;
124     this.start = start2;
125     this.end = end2;
126     sequenceFeatureStore = new SequenceFeatures();
127     parseId();
128     checkValidRange();
129   }
130
131   com.stevesoft.pat.Regex limitrx = new com.stevesoft.pat.Regex(
132           "[/][0-9]{1,}[-][0-9]{1,}$");
133
134   com.stevesoft.pat.Regex endrx = new com.stevesoft.pat.Regex("[0-9]{1,}$");
135
136   void parseId()
137   {
138     if (name == null)
139     {
140       System.err
141               .println("POSSIBLE IMPLEMENTATION ERROR: null sequence name passed to constructor.");
142       name = "";
143     }
144     // Does sequence have the /start-end signature?
145     if (limitrx.search(name))
146     {
147       name = limitrx.left();
148       endrx.search(limitrx.stringMatched());
149       setStart(Integer.parseInt(limitrx.stringMatched().substring(1,
150               endrx.matchedFrom() - 1)));
151       setEnd(Integer.parseInt(endrx.stringMatched()));
152     }
153   }
154
155   void checkValidRange()
156   {
157     // Note: JAL-774 :
158     // http://issues.jalview.org/browse/JAL-774?focusedCommentId=11239&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-11239
159     {
160       int endRes = 0;
161       for (int j = 0; j < sequence.length; j++)
162       {
163         if (!jalview.util.Comparison.isGap(sequence[j]))
164         {
165           endRes++;
166         }
167       }
168       if (endRes > 0)
169       {
170         endRes += start - 1;
171       }
172
173       if (end < endRes)
174       {
175         end = endRes;
176       }
177     }
178
179   }
180
181   /**
182    * Creates a new Sequence object.
183    * 
184    * @param name
185    *          DOCUMENT ME!
186    * @param sequence
187    *          DOCUMENT ME!
188    */
189   public Sequence(String name, String sequence)
190   {
191     this(name, sequence, 1, -1);
192   }
193
194   /**
195    * Creates a new Sequence object with new AlignmentAnnotations but inherits
196    * any existing dataset sequence reference. If non exists, everything is
197    * copied.
198    * 
199    * @param seq
200    *          if seq is a dataset sequence, behaves like a plain old copy
201    *          constructor
202    */
203   public Sequence(SequenceI seq)
204   {
205     this(seq, seq.getAnnotation());
206   }
207
208   /**
209    * Create a new sequence object with new features, DBRefEntries, and PDBIds
210    * but inherits any existing dataset sequence reference, and duplicate of any
211    * annotation that is present in the given annotation array.
212    * 
213    * @param seq
214    *          the sequence to be copied
215    * @param alAnnotation
216    *          an array of annotation including some associated with seq
217    */
218   public Sequence(SequenceI seq, AlignmentAnnotation[] alAnnotation)
219   {
220     initSeqFrom(seq, alAnnotation);
221
222   }
223
224   /**
225    * does the heavy lifting when cloning a dataset sequence, or coping data from
226    * dataset to a new derived sequence.
227    * 
228    * @param seq
229    *          - source of attributes.
230    * @param alAnnotation
231    *          - alignment annotation present on seq that should be copied onto
232    *          this sequence
233    */
234   protected void initSeqFrom(SequenceI seq,
235           AlignmentAnnotation[] alAnnotation)
236   {
237     {
238       char[] oseq = seq.getSequence();
239       initSeqAndName(seq.getName(), Arrays.copyOf(oseq, oseq.length),
240               seq.getStart(), seq.getEnd());
241     }
242     description = seq.getDescription();
243     if (seq != datasetSequence)
244     {
245       setDatasetSequence(seq.getDatasetSequence());
246     }
247     if (datasetSequence == null && seq.getDBRefs() != null)
248     {
249       // only copy DBRefs and seqfeatures if we really are a dataset sequence
250       DBRefEntry[] dbr = seq.getDBRefs();
251       for (int i = 0; i < dbr.length; i++)
252       {
253         addDBRef(new DBRefEntry(dbr[i]));
254       }
255       if (seq.getSequenceFeatures() != null)
256       {
257         SequenceFeature[] sf = seq.getSequenceFeatures();
258         for (int i = 0; i < sf.length; i++)
259         {
260           addSequenceFeature(new SequenceFeature(sf[i]));
261         }
262       }
263     }
264     if (seq.getAnnotation() != null)
265     {
266       AlignmentAnnotation[] sqann = seq.getAnnotation();
267       for (int i = 0; i < sqann.length; i++)
268       {
269         if (sqann[i] == null)
270         {
271           continue;
272         }
273         boolean found = (alAnnotation == null);
274         if (!found)
275         {
276           for (int apos = 0; !found && apos < alAnnotation.length; apos++)
277           {
278             found = (alAnnotation[apos] == sqann[i]);
279           }
280         }
281         if (found)
282         {
283           // only copy the given annotation
284           AlignmentAnnotation newann = new AlignmentAnnotation(sqann[i]);
285           addAlignmentAnnotation(newann);
286         }
287       }
288     }
289     if (seq.getAllPDBEntries() != null)
290     {
291       Vector<PDBEntry> ids = seq.getAllPDBEntries();
292       for (PDBEntry pdb : ids)
293       {
294         this.addPDBId(new PDBEntry(pdb));
295       }
296     }
297   }
298
299   @Override
300   public void setSequenceFeatures(SequenceFeature[] features)
301   {
302     if (datasetSequence == null)
303     {
304       sequenceFeatures = features;
305     }
306     else
307     {
308       if (datasetSequence.getSequenceFeatures() != features
309               && datasetSequence.getSequenceFeatures() != null
310               && datasetSequence.getSequenceFeatures().length > 0)
311       {
312         new Exception(
313                 "Warning: JAL-2046 side effect ? Possible implementation error: overwriting dataset sequence features by setting sequence features on alignment")
314                 .printStackTrace();
315       }
316       datasetSequence.setSequenceFeatures(features);
317     }
318   }
319
320   @Override
321   public synchronized boolean addSequenceFeature(SequenceFeature sf)
322   {
323     if (sequenceFeatures == null && datasetSequence != null)
324     {
325       return datasetSequence.addSequenceFeature(sf);
326     }
327     if (sequenceFeatures == null)
328     {
329       sequenceFeatures = new SequenceFeature[0];
330     }
331
332     for (int i = 0; i < sequenceFeatures.length; i++)
333     {
334       if (sequenceFeatures[i].equals(sf))
335       {
336         return false;
337       }
338     }
339
340     SequenceFeature[] temp = new SequenceFeature[sequenceFeatures.length + 1];
341     System.arraycopy(sequenceFeatures, 0, temp, 0, sequenceFeatures.length);
342     temp[sequenceFeatures.length] = sf;
343
344     sequenceFeatures = temp;
345
346     sequenceFeatureStore.add(sf);
347     return true;
348   }
349
350   @Override
351   public void deleteFeature(SequenceFeature sf)
352   {
353     if (sequenceFeatures == null)
354     {
355       if (datasetSequence != null)
356       {
357         datasetSequence.deleteFeature(sf);
358       }
359       return;
360     }
361
362     /*
363      * new way
364      */
365     sequenceFeatureStore.delete(sf);
366
367     /*
368      * old way - to be removed
369      */
370     int index = 0;
371     for (index = 0; index < sequenceFeatures.length; index++)
372     {
373       if (sequenceFeatures[index].equals(sf))
374       {
375         break;
376       }
377     }
378
379     if (index == sequenceFeatures.length)
380     {
381       return;
382     }
383
384     int sfLength = sequenceFeatures.length;
385     if (sfLength < 2)
386     {
387       sequenceFeatures = null;
388     }
389     else
390     {
391       SequenceFeature[] temp = new SequenceFeature[sfLength - 1];
392       System.arraycopy(sequenceFeatures, 0, temp, 0, index);
393
394       if (index < sfLength)
395       {
396         System.arraycopy(sequenceFeatures, index + 1, temp, index,
397                 sequenceFeatures.length - index - 1);
398       }
399
400       sequenceFeatures = temp;
401     }
402   }
403
404   /**
405    * Returns the sequence features (if any), looking first on the sequence, then
406    * on its dataset sequence, and so on until a non-null value is found (or
407    * none). This supports retrieval of sequence features stored on the sequence
408    * (as in the applet) or on the dataset sequence (as in the Desktop version).
409    * 
410    * @return
411    */
412   @Override
413   public SequenceFeature[] getSequenceFeatures()
414   {
415     SequenceFeature[] features = sequenceFeatures;
416
417     SequenceI seq = this;
418     int count = 0; // failsafe against loop in sequence.datasetsequence...
419     while (features == null && seq.getDatasetSequence() != null
420             && count++ < 10)
421     {
422       seq = seq.getDatasetSequence();
423       features = ((Sequence) seq).sequenceFeatures;
424     }
425     return features;
426   }
427
428   @Override
429   public boolean addPDBId(PDBEntry entry)
430   {
431     if (pdbIds == null)
432     {
433       pdbIds = new Vector<PDBEntry>();
434       pdbIds.add(entry);
435       return true;
436     }
437
438     for (PDBEntry pdbe : pdbIds)
439     {
440       if (pdbe.updateFrom(entry))
441       {
442         return false;
443       }
444     }
445     pdbIds.addElement(entry);
446     return true;
447   }
448
449   /**
450    * DOCUMENT ME!
451    * 
452    * @param id
453    *          DOCUMENT ME!
454    */
455   @Override
456   public void setPDBId(Vector<PDBEntry> id)
457   {
458     pdbIds = id;
459   }
460
461   /**
462    * DOCUMENT ME!
463    * 
464    * @return DOCUMENT ME!
465    */
466   @Override
467   public Vector<PDBEntry> getAllPDBEntries()
468   {
469     return pdbIds == null ? new Vector<PDBEntry>() : pdbIds;
470   }
471
472   /**
473    * DOCUMENT ME!
474    * 
475    * @return DOCUMENT ME!
476    */
477   @Override
478   public String getDisplayId(boolean jvsuffix)
479   {
480     StringBuffer result = new StringBuffer(name);
481     if (jvsuffix)
482     {
483       result.append("/" + start + "-" + end);
484     }
485
486     return result.toString();
487   }
488
489   /**
490    * DOCUMENT ME!
491    * 
492    * @param name
493    *          DOCUMENT ME!
494    */
495   @Override
496   public void setName(String name)
497   {
498     this.name = name;
499     this.parseId();
500   }
501
502   /**
503    * DOCUMENT ME!
504    * 
505    * @return DOCUMENT ME!
506    */
507   @Override
508   public String getName()
509   {
510     return this.name;
511   }
512
513   /**
514    * DOCUMENT ME!
515    * 
516    * @param start
517    *          DOCUMENT ME!
518    */
519   @Override
520   public void setStart(int start)
521   {
522     this.start = start;
523   }
524
525   /**
526    * DOCUMENT ME!
527    * 
528    * @return DOCUMENT ME!
529    */
530   @Override
531   public int getStart()
532   {
533     return this.start;
534   }
535
536   /**
537    * DOCUMENT ME!
538    * 
539    * @param end
540    *          DOCUMENT ME!
541    */
542   @Override
543   public void setEnd(int end)
544   {
545     this.end = end;
546   }
547
548   /**
549    * DOCUMENT ME!
550    * 
551    * @return DOCUMENT ME!
552    */
553   @Override
554   public int getEnd()
555   {
556     return this.end;
557   }
558
559   /**
560    * DOCUMENT ME!
561    * 
562    * @return DOCUMENT ME!
563    */
564   @Override
565   public int getLength()
566   {
567     return this.sequence.length;
568   }
569
570   /**
571    * DOCUMENT ME!
572    * 
573    * @param seq
574    *          DOCUMENT ME!
575    */
576   @Override
577   public void setSequence(String seq)
578   {
579     this.sequence = seq.toCharArray();
580     checkValidRange();
581   }
582
583   @Override
584   public String getSequenceAsString()
585   {
586     return new String(sequence);
587   }
588
589   @Override
590   public String getSequenceAsString(int start, int end)
591   {
592     return new String(getSequence(start, end));
593   }
594
595   @Override
596   public char[] getSequence()
597   {
598     return sequence;
599   }
600
601   /*
602    * (non-Javadoc)
603    * 
604    * @see jalview.datamodel.SequenceI#getSequence(int, int)
605    */
606   @Override
607   public char[] getSequence(int start, int end)
608   {
609     if (start < 0)
610     {
611       start = 0;
612     }
613     // JBPNote - left to user to pad the result here (TODO:Decide on this
614     // policy)
615     if (start >= sequence.length)
616     {
617       return new char[0];
618     }
619
620     if (end >= sequence.length)
621     {
622       end = sequence.length;
623     }
624
625     char[] reply = new char[end - start];
626     System.arraycopy(sequence, start, reply, 0, end - start);
627
628     return reply;
629   }
630
631   @Override
632   public SequenceI getSubSequence(int start, int end)
633   {
634     if (start < 0)
635     {
636       start = 0;
637     }
638     char[] seq = getSequence(start, end);
639     if (seq.length == 0)
640     {
641       return null;
642     }
643     int nstart = findPosition(start);
644     int nend = findPosition(end) - 1;
645     // JBPNote - this is an incomplete copy.
646     SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
647     nseq.setDescription(description);
648     if (datasetSequence != null)
649     {
650       nseq.setDatasetSequence(datasetSequence);
651     }
652     else
653     {
654       nseq.setDatasetSequence(this);
655     }
656     return nseq;
657   }
658
659   /**
660    * Returns the character of the aligned sequence at the given position (base
661    * zero), or space if the position is not within the sequence's bounds
662    * 
663    * @return
664    */
665   @Override
666   public char getCharAt(int i)
667   {
668     if (i >= 0 && i < sequence.length)
669     {
670       return sequence[i];
671     }
672     else
673     {
674       return ' ';
675     }
676   }
677
678   /**
679    * DOCUMENT ME!
680    * 
681    * @param desc
682    *          DOCUMENT ME!
683    */
684   @Override
685   public void setDescription(String desc)
686   {
687     this.description = desc;
688   }
689
690   /**
691    * DOCUMENT ME!
692    * 
693    * @return DOCUMENT ME!
694    */
695   @Override
696   public String getDescription()
697   {
698     return this.description;
699   }
700
701   /*
702    * (non-Javadoc)
703    * 
704    * @see jalview.datamodel.SequenceI#findIndex(int)
705    */
706   @Override
707   public int findIndex(int pos)
708   {
709     // returns the alignment position for a residue
710     int j = start;
711     int i = 0;
712     // Rely on end being at least as long as the length of the sequence.
713     while ((i < sequence.length) && (j <= end) && (j <= pos))
714     {
715       if (!jalview.util.Comparison.isGap(sequence[i]))
716       {
717         j++;
718       }
719
720       i++;
721     }
722
723     if ((j == end) && (j < pos))
724     {
725       return end + 1;
726     }
727     else
728     {
729       return i;
730     }
731   }
732
733   @Override
734   public int findPosition(int i)
735   {
736     int j = 0;
737     int pos = start;
738     int seqlen = sequence.length;
739     while ((j < i) && (j < seqlen))
740     {
741       if (!jalview.util.Comparison.isGap(sequence[j]))
742       {
743         pos++;
744       }
745
746       j++;
747     }
748
749     return pos;
750   }
751
752   /**
753    * Returns an int array where indices correspond to each residue in the
754    * sequence and the element value gives its position in the alignment
755    * 
756    * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
757    *         residues in SequenceI object
758    */
759   @Override
760   public int[] gapMap()
761   {
762     String seq = jalview.analysis.AlignSeq.extractGaps(
763             jalview.util.Comparison.GapChars, new String(sequence));
764     int[] map = new int[seq.length()];
765     int j = 0;
766     int p = 0;
767
768     while (j < sequence.length)
769     {
770       if (!jalview.util.Comparison.isGap(sequence[j]))
771       {
772         map[p++] = j;
773       }
774
775       j++;
776     }
777
778     return map;
779   }
780
781   @Override
782   public int[] findPositionMap()
783   {
784     int map[] = new int[sequence.length];
785     int j = 0;
786     int pos = start;
787     int seqlen = sequence.length;
788     while ((j < seqlen))
789     {
790       map[j] = pos;
791       if (!jalview.util.Comparison.isGap(sequence[j]))
792       {
793         pos++;
794       }
795
796       j++;
797     }
798     return map;
799   }
800
801   @Override
802   public List<int[]> getInsertions()
803   {
804     ArrayList<int[]> map = new ArrayList<int[]>();
805     int lastj = -1, j = 0;
806     int pos = start;
807     int seqlen = sequence.length;
808     while ((j < seqlen))
809     {
810       if (jalview.util.Comparison.isGap(sequence[j]))
811       {
812         if (lastj == -1)
813         {
814           lastj = j;
815         }
816       }
817       else
818       {
819         if (lastj != -1)
820         {
821           map.add(new int[] { lastj, j - 1 });
822           lastj = -1;
823         }
824       }
825       j++;
826     }
827     if (lastj != -1)
828     {
829       map.add(new int[] { lastj, j - 1 });
830       lastj = -1;
831     }
832     return map;
833   }
834
835   @Override
836   public void deleteChars(int i, int j)
837   {
838     int newstart = start, newend = end;
839     if (i >= sequence.length || i < 0)
840     {
841       return;
842     }
843
844     char[] tmp = StringUtils.deleteChars(sequence, i, j);
845     boolean createNewDs = false;
846     // TODO: take a (second look) at the dataset creation validation method for
847     // the very large sequence case
848     int eindex = -1, sindex = -1;
849     boolean ecalc = false, scalc = false;
850     for (int s = i; s < j; s++)
851     {
852       if (jalview.schemes.ResidueProperties.aaIndex[sequence[s]] != 23)
853       {
854         if (createNewDs)
855         {
856           newend--;
857         }
858         else
859         {
860           if (!scalc)
861           {
862             sindex = findIndex(start) - 1;
863             scalc = true;
864           }
865           if (sindex == s)
866           {
867             // delete characters including start of sequence
868             newstart = findPosition(j);
869             break; // don't need to search for any more residue characters.
870           }
871           else
872           {
873             // delete characters after start.
874             if (!ecalc)
875             {
876               eindex = findIndex(end) - 1;
877               ecalc = true;
878             }
879             if (eindex < j)
880             {
881               // delete characters at end of sequence
882               newend = findPosition(i - 1);
883               break; // don't need to search for any more residue characters.
884             }
885             else
886             {
887               createNewDs = true;
888               newend--; // decrease end position by one for the deleted residue
889               // and search further
890             }
891           }
892         }
893       }
894     }
895     // deletion occured in the middle of the sequence
896     if (createNewDs && this.datasetSequence != null)
897     {
898       // construct a new sequence
899       Sequence ds = new Sequence(datasetSequence);
900       // TODO: remove any non-inheritable properties ?
901       // TODO: create a sequence mapping (since there is a relation here ?)
902       ds.deleteChars(i, j);
903       datasetSequence = ds;
904     }
905     start = newstart;
906     end = newend;
907     sequence = tmp;
908   }
909
910   @Override
911   public void insertCharAt(int i, int length, char c)
912   {
913     char[] tmp = new char[sequence.length + length];
914
915     if (i >= sequence.length)
916     {
917       System.arraycopy(sequence, 0, tmp, 0, sequence.length);
918       i = sequence.length;
919     }
920     else
921     {
922       System.arraycopy(sequence, 0, tmp, 0, i);
923     }
924
925     int index = i;
926     while (length > 0)
927     {
928       tmp[index++] = c;
929       length--;
930     }
931
932     if (i < sequence.length)
933     {
934       System.arraycopy(sequence, i, tmp, index, sequence.length - i);
935     }
936
937     sequence = tmp;
938   }
939
940   @Override
941   public void insertCharAt(int i, char c)
942   {
943     insertCharAt(i, 1, c);
944   }
945
946   @Override
947   public String getVamsasId()
948   {
949     return vamsasId;
950   }
951
952   @Override
953   public void setVamsasId(String id)
954   {
955     vamsasId = id;
956   }
957
958   @Override
959   public void setDBRefs(DBRefEntry[] dbref)
960   {
961     if (dbrefs == null && datasetSequence != null
962             && this != datasetSequence)
963     {
964       datasetSequence.setDBRefs(dbref);
965       return;
966     }
967     dbrefs = dbref;
968     if (dbrefs != null)
969     {
970       DBRefUtils.ensurePrimaries(this);
971     }
972   }
973
974   @Override
975   public DBRefEntry[] getDBRefs()
976   {
977     if (dbrefs == null && datasetSequence != null
978             && this != datasetSequence)
979     {
980       return datasetSequence.getDBRefs();
981     }
982     return dbrefs;
983   }
984
985   @Override
986   public void addDBRef(DBRefEntry entry)
987   {
988     if (datasetSequence != null)
989     {
990       datasetSequence.addDBRef(entry);
991       return;
992     }
993
994     if (dbrefs == null)
995     {
996       dbrefs = new DBRefEntry[0];
997     }
998
999     for (DBRefEntryI dbr : dbrefs)
1000     {
1001       if (dbr.updateFrom(entry))
1002       {
1003         /*
1004          * found a dbref that either matched, or could be
1005          * updated from, the new entry - no need to add it
1006          */
1007         return;
1008       }
1009     }
1010
1011     /*
1012      * extend the array to make room for one more
1013      */
1014     // TODO use an ArrayList instead
1015     int j = dbrefs.length;
1016     DBRefEntry[] temp = new DBRefEntry[j + 1];
1017     System.arraycopy(dbrefs, 0, temp, 0, j);
1018     temp[temp.length - 1] = entry;
1019
1020     dbrefs = temp;
1021
1022     DBRefUtils.ensurePrimaries(this);
1023   }
1024
1025   @Override
1026   public void setDatasetSequence(SequenceI seq)
1027   {
1028     if (seq == this)
1029     {
1030       throw new IllegalArgumentException(
1031               "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1032     }
1033     if (seq != null && seq.getDatasetSequence() != null)
1034     {
1035       throw new IllegalArgumentException(
1036               "Implementation error: cascading dataset sequences are not allowed.");
1037     }
1038     datasetSequence = seq;
1039   }
1040
1041   @Override
1042   public SequenceI getDatasetSequence()
1043   {
1044     return datasetSequence;
1045   }
1046
1047   @Override
1048   public AlignmentAnnotation[] getAnnotation()
1049   {
1050     return annotation == null ? null : annotation
1051             .toArray(new AlignmentAnnotation[annotation.size()]);
1052   }
1053
1054   @Override
1055   public boolean hasAnnotation(AlignmentAnnotation ann)
1056   {
1057     return annotation == null ? false : annotation.contains(ann);
1058   }
1059
1060   @Override
1061   public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1062   {
1063     if (this.annotation == null)
1064     {
1065       this.annotation = new Vector<AlignmentAnnotation>();
1066     }
1067     if (!this.annotation.contains(annotation))
1068     {
1069       this.annotation.addElement(annotation);
1070     }
1071     annotation.setSequenceRef(this);
1072   }
1073
1074   @Override
1075   public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1076   {
1077     if (this.annotation != null)
1078     {
1079       this.annotation.removeElement(annotation);
1080       if (this.annotation.size() == 0)
1081       {
1082         this.annotation = null;
1083       }
1084     }
1085   }
1086
1087   /**
1088    * test if this is a valid candidate for another sequence's dataset sequence.
1089    * 
1090    */
1091   private boolean isValidDatasetSequence()
1092   {
1093     if (datasetSequence != null)
1094     {
1095       return false;
1096     }
1097     for (int i = 0; i < sequence.length; i++)
1098     {
1099       if (jalview.util.Comparison.isGap(sequence[i]))
1100       {
1101         return false;
1102       }
1103     }
1104     return true;
1105   }
1106
1107   @Override
1108   public SequenceI deriveSequence()
1109   {
1110     Sequence seq = null;
1111     if (datasetSequence == null)
1112     {
1113       if (isValidDatasetSequence())
1114       {
1115         // Use this as dataset sequence
1116         seq = new Sequence(getName(), "", 1, -1);
1117         seq.setDatasetSequence(this);
1118         seq.initSeqFrom(this, getAnnotation());
1119         return seq;
1120       }
1121       else
1122       {
1123         // Create a new, valid dataset sequence
1124         createDatasetSequence();
1125       }
1126     }
1127     return new Sequence(this);
1128   }
1129
1130   private boolean _isNa;
1131
1132   private long _seqhash = 0;
1133
1134   /**
1135    * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1136    * true
1137    */
1138   @Override
1139   public boolean isProtein()
1140   {
1141     if (datasetSequence != null)
1142     {
1143       return datasetSequence.isProtein();
1144     }
1145     if (_seqhash != sequence.hashCode())
1146     {
1147       _seqhash = sequence.hashCode();
1148       _isNa = Comparison.isNucleotide(this);
1149     }
1150     return !_isNa;
1151   };
1152
1153   /*
1154    * (non-Javadoc)
1155    * 
1156    * @see jalview.datamodel.SequenceI#createDatasetSequence()
1157    */
1158   @Override
1159   public SequenceI createDatasetSequence()
1160   {
1161     if (datasetSequence == null)
1162     {
1163       Sequence dsseq = new Sequence(getName(), AlignSeq.extractGaps(
1164               jalview.util.Comparison.GapChars, getSequenceAsString()),
1165               getStart(), getEnd());
1166
1167       datasetSequence = dsseq;
1168
1169       dsseq.setDescription(description);
1170       // move features and database references onto dataset sequence
1171       dsseq.sequenceFeatures = sequenceFeatures;
1172       sequenceFeatures = null;
1173       dsseq.dbrefs = dbrefs;
1174       dbrefs = null;
1175       // TODO: search and replace any references to this sequence with
1176       // references to the dataset sequence in Mappings on dbref
1177       dsseq.pdbIds = pdbIds;
1178       pdbIds = null;
1179       datasetSequence.updatePDBIds();
1180       if (annotation != null)
1181       {
1182         // annotation is cloned rather than moved, to preserve what's currently
1183         // on the alignment
1184         for (AlignmentAnnotation aa : annotation)
1185         {
1186           AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1187           _aa.sequenceRef = datasetSequence;
1188           _aa.adjustForAlignment(); // uses annotation's own record of
1189                                     // sequence-column mapping
1190           datasetSequence.addAlignmentAnnotation(_aa);
1191         }
1192       }
1193     }
1194     return datasetSequence;
1195   }
1196
1197   /*
1198    * (non-Javadoc)
1199    * 
1200    * @see
1201    * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1202    * annotations)
1203    */
1204   @Override
1205   public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1206   {
1207     if (annotation != null)
1208     {
1209       annotation.removeAllElements();
1210     }
1211     if (annotations != null)
1212     {
1213       for (int i = 0; i < annotations.length; i++)
1214       {
1215         if (annotations[i] != null)
1216         {
1217           addAlignmentAnnotation(annotations[i]);
1218         }
1219       }
1220     }
1221   }
1222
1223   @Override
1224   public AlignmentAnnotation[] getAnnotation(String label)
1225   {
1226     if (annotation == null || annotation.size() == 0)
1227     {
1228       return null;
1229     }
1230
1231     Vector subset = new Vector();
1232     Enumeration e = annotation.elements();
1233     while (e.hasMoreElements())
1234     {
1235       AlignmentAnnotation ann = (AlignmentAnnotation) e.nextElement();
1236       if (ann.label != null && ann.label.equals(label))
1237       {
1238         subset.addElement(ann);
1239       }
1240     }
1241     if (subset.size() == 0)
1242     {
1243       return null;
1244     }
1245     AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1246     int i = 0;
1247     e = subset.elements();
1248     while (e.hasMoreElements())
1249     {
1250       anns[i++] = (AlignmentAnnotation) e.nextElement();
1251     }
1252     subset.removeAllElements();
1253     return anns;
1254   }
1255
1256   @Override
1257   public boolean updatePDBIds()
1258   {
1259     if (datasetSequence != null)
1260     {
1261       // TODO: could merge DBRefs
1262       return datasetSequence.updatePDBIds();
1263     }
1264     if (dbrefs == null || dbrefs.length == 0)
1265     {
1266       return false;
1267     }
1268     boolean added = false;
1269     for (DBRefEntry dbr : dbrefs)
1270     {
1271       if (DBRefSource.PDB.equals(dbr.getSource()))
1272       {
1273         /*
1274          * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1275          * PDB id is not already present in a 'matching' PDBEntry
1276          * Constructor parses out a chain code if appended to the accession id
1277          * (a fudge used to 'store' the chain code in the DBRef)
1278          */
1279         PDBEntry pdbe = new PDBEntry(dbr);
1280         added |= addPDBId(pdbe);
1281       }
1282     }
1283     return added;
1284   }
1285
1286   @Override
1287   public void transferAnnotation(SequenceI entry, Mapping mp)
1288   {
1289     if (datasetSequence != null)
1290     {
1291       datasetSequence.transferAnnotation(entry, mp);
1292       return;
1293     }
1294     if (entry.getDatasetSequence() != null)
1295     {
1296       transferAnnotation(entry.getDatasetSequence(), mp);
1297       return;
1298     }
1299     // transfer any new features from entry onto sequence
1300     if (entry.getSequenceFeatures() != null)
1301     {
1302
1303       SequenceFeature[] sfs = entry.getSequenceFeatures();
1304       for (int si = 0; si < sfs.length; si++)
1305       {
1306         SequenceFeature sf[] = (mp != null) ? mp.locateFeature(sfs[si])
1307                 : new SequenceFeature[] { new SequenceFeature(sfs[si]) };
1308         if (sf != null && sf.length > 0)
1309         {
1310           for (int sfi = 0; sfi < sf.length; sfi++)
1311           {
1312             addSequenceFeature(sf[sfi]);
1313           }
1314         }
1315       }
1316     }
1317
1318     // transfer PDB entries
1319     if (entry.getAllPDBEntries() != null)
1320     {
1321       Enumeration e = entry.getAllPDBEntries().elements();
1322       while (e.hasMoreElements())
1323       {
1324         PDBEntry pdb = (PDBEntry) e.nextElement();
1325         addPDBId(pdb);
1326       }
1327     }
1328     // transfer database references
1329     DBRefEntry[] entryRefs = entry.getDBRefs();
1330     if (entryRefs != null)
1331     {
1332       for (int r = 0; r < entryRefs.length; r++)
1333       {
1334         DBRefEntry newref = new DBRefEntry(entryRefs[r]);
1335         if (newref.getMap() != null && mp != null)
1336         {
1337           // remap ref using our local mapping
1338         }
1339         // we also assume all version string setting is done by dbSourceProxy
1340         /*
1341          * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1342          * newref.setSource(dbSource); }
1343          */
1344         addDBRef(newref);
1345       }
1346     }
1347   }
1348
1349   /**
1350    * @return The index (zero-based) on this sequence in the MSA. It returns
1351    *         {@code -1} if this information is not available.
1352    */
1353   @Override
1354   public int getIndex()
1355   {
1356     return index;
1357   }
1358
1359   /**
1360    * Defines the position of this sequence in the MSA. Use the value {@code -1}
1361    * if this information is undefined.
1362    * 
1363    * @param The
1364    *          position for this sequence. This value is zero-based (zero for
1365    *          this first sequence)
1366    */
1367   @Override
1368   public void setIndex(int value)
1369   {
1370     index = value;
1371   }
1372
1373   @Override
1374   public void setRNA(RNA r)
1375   {
1376     rna = r;
1377   }
1378
1379   @Override
1380   public RNA getRNA()
1381   {
1382     return rna;
1383   }
1384
1385   @Override
1386   public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1387           String label)
1388   {
1389     List<AlignmentAnnotation> result = new ArrayList<AlignmentAnnotation>();
1390     if (this.annotation != null)
1391     {
1392       for (AlignmentAnnotation ann : annotation)
1393       {
1394         if (ann.calcId != null && ann.calcId.equals(calcId)
1395                 && ann.label != null && ann.label.equals(label))
1396         {
1397           result.add(ann);
1398         }
1399       }
1400     }
1401     return result;
1402   }
1403
1404   @Override
1405   public String toString()
1406   {
1407     return getDisplayId(false);
1408   }
1409
1410   @Override
1411   public PDBEntry getPDBEntry(String pdbIdStr)
1412   {
1413     if (getDatasetSequence() != null)
1414     {
1415       return getDatasetSequence().getPDBEntry(pdbIdStr);
1416     }
1417     if (pdbIds == null)
1418     {
1419       return null;
1420     }
1421     List<PDBEntry> entries = getAllPDBEntries();
1422     for (PDBEntry entry : entries)
1423     {
1424       if (entry.getId().equalsIgnoreCase(pdbIdStr))
1425       {
1426         return entry;
1427       }
1428     }
1429     return null;
1430   }
1431
1432   @Override
1433   public List<DBRefEntry> getPrimaryDBRefs()
1434   {
1435     if (datasetSequence != null)
1436     {
1437       return datasetSequence.getPrimaryDBRefs();
1438     }
1439     if (dbrefs == null || dbrefs.length == 0)
1440     {
1441       return Collections.emptyList();
1442     }
1443     synchronized (dbrefs)
1444     {
1445       List<DBRefEntry> primaries = new ArrayList<DBRefEntry>();
1446       DBRefEntry[] tmp = new DBRefEntry[1];
1447       for (DBRefEntry ref : dbrefs)
1448       {
1449         if (!ref.isPrimaryCandidate())
1450         {
1451           continue;
1452         }
1453         if (ref.hasMap())
1454         {
1455           MapList mp = ref.getMap().getMap();
1456           if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1457           {
1458             // map only involves a subsequence, so cannot be primary
1459             continue;
1460           }
1461         }
1462         // whilst it looks like it is a primary ref, we also sanity check type
1463         if (DBRefUtils.getCanonicalName(DBRefSource.PDB).equals(
1464                 DBRefUtils.getCanonicalName(ref.getSource())))
1465         {
1466           // PDB dbrefs imply there should be a PDBEntry associated
1467           // TODO: tighten PDB dbrefs
1468           // formally imply Jalview has actually downloaded and
1469           // parsed the pdb file. That means there should be a cached file
1470           // handle on the PDBEntry, and a real mapping between sequence and
1471           // extracted sequence from PDB file
1472           PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1473           if (pdbentry != null && pdbentry.getFile() != null)
1474           {
1475             primaries.add(ref);
1476           }
1477           continue;
1478         }
1479         // check standard protein or dna sources
1480         tmp[0] = ref;
1481         DBRefEntry[] res = DBRefUtils.selectDbRefs(!isProtein(), tmp);
1482         if (res != null && res[0] == tmp[0])
1483         {
1484           primaries.add(ref);
1485           continue;
1486         }
1487       }
1488       return primaries;
1489     }
1490   }
1491
1492   @Override
1493   public List<SequenceFeature> findFeatures(String type, int from, int to)
1494   {
1495     if (datasetSequence != null)
1496     {
1497       return datasetSequence.findFeatures(type, from, to);
1498     }
1499     return sequenceFeatureStore.findFeatures(from, to, type);
1500   }
1501 }