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