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