bugfix on copy only referenced annotation in copy constructor
[jalview.git] / src / jalview / datamodel / Sequence.java
1 /*
2 * Jalview - A Sequence Alignment Editor and Viewer
3  * Copyright (C) 2007 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
4 *
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
18 */
19 package jalview.datamodel;
20
21
22 import java.util.*;
23
24 import jalview.analysis.*;
25
26 /**
27  * DOCUMENT ME!
28  *
29  * @author $author$
30  * @version $Revision$
31  */
32 public class Sequence
33     implements SequenceI
34 {
35   SequenceI datasetSequence;
36   String name;
37   private char [] sequence;
38   String description;
39   int start;
40   int end;
41   Vector pdbIds;
42   String vamsasId;
43   DBRefEntry[] dbrefs;
44
45   /** This annotation is displayed below the alignment but the
46    * positions are tied to the residues of this sequence */
47   Vector annotation;
48
49   /** DOCUMENT ME!! */
50   public SequenceFeature[] sequenceFeatures;
51
52
53   /**
54    * Creates a new Sequence object.
55    *
56    * @param name DOCUMENT ME!
57    * @param sequence DOCUMENT ME!
58    * @param start DOCUMENT ME!
59    * @param end DOCUMENT ME!
60    */
61   public Sequence(String name, String sequence, int start, int end)
62   {
63     this.name = name;
64     this.sequence = sequence.toCharArray();
65     this.start = start;
66     this.end = end;
67     parseId();
68     checkValidRange();
69   }
70
71   public Sequence(String name, char [] sequence, int start, int end)
72   {
73     this.name = name;
74     this.sequence = sequence;
75     this.start = start;
76     this.end = end;
77     parseId();
78     checkValidRange();
79   }
80
81   com.stevesoft.pat.Regex limitrx = new com.stevesoft.pat.Regex(
82       "[/][0-9]{1,}[-][0-9]{1,}$");
83   com.stevesoft.pat.Regex endrx = new com.stevesoft.pat.Regex(
84       "[0-9]{1,}$");
85
86   void parseId()
87   {
88     // Does sequence have the /start-end signiature?
89     if (limitrx.search(name))
90     {
91       name = limitrx.left();
92       endrx.search(limitrx.stringMatched());
93       setStart(Integer.parseInt(limitrx.stringMatched().substring(1,
94           endrx.matchedFrom() - 1)));
95       setEnd(Integer.parseInt(endrx.stringMatched()));
96     }
97   }
98
99   void checkValidRange()
100   {
101     if (end < 1)
102     {
103       int endRes = 0;
104       for (int j = 0; j < sequence.length; j++)
105       {
106         if (!jalview.util.Comparison.isGap( sequence[j] ))
107         {
108           endRes++;
109         }
110       }
111       if (endRes > 0)
112       {
113         endRes += start - 1;
114       }
115
116       this.end = endRes;
117     }
118
119   }
120
121   /**
122    * Creates a new Sequence object.
123    *
124    * @param name DOCUMENT ME!
125    * @param sequence DOCUMENT ME!
126    */
127   public Sequence(String name, String sequence)
128   {
129     this(name, sequence, 1, -1);
130   }
131
132   /**
133    * Creates a new Sequence object with new features, DBRefEntries, AlignmentAnnotations, and PDBIds
134    * but inherits any existing dataset sequence reference.
135    * @param seq DOCUMENT ME!
136    */
137   public Sequence(SequenceI seq)
138   {
139     this(seq, seq.getAnnotation());
140   }
141   /**
142    * Create a new sequence object with new features, DBRefEntries, and PDBIds
143    * but inherits any existing dataset sequence reference, and duplicate of
144    * any annotation that is present in the given annotation array.
145    * @param seq the sequence to be copied
146    * @param alAnnotation an array of annotation including some associated with seq 
147    */
148   public Sequence(SequenceI seq, AlignmentAnnotation[] alAnnotation)
149   {
150     this(seq.getName(),
151             seq.getSequence(),
152             seq.getStart(),
153             seq.getEnd());
154     description = seq.getDescription();
155     if (seq.getSequenceFeatures()!=null) {
156       SequenceFeature[] sf = seq.getSequenceFeatures();
157       for (int i=0; i<sf.length; i++) {
158         addSequenceFeature(new SequenceFeature(sf[i]));
159       }
160     }
161     if (seq.getDBRef()!=null) {
162       DBRefEntry[] dbr = seq.getDBRef();
163       for (int i=0; i<dbr.length; i++) {
164         addDBRef(new DBRefEntry(dbr[i]));
165       }
166     }
167     setDatasetSequence(seq.getDatasetSequence());
168     if (seq.getAnnotation()!=null) {
169       AlignmentAnnotation[] sqann = seq.getAnnotation();
170       for (int i=0;i<sqann.length; i++)
171       {
172         if (sqann[i]==null)
173         {
174           continue;
175         }
176         boolean found = (alAnnotation==null);
177         if (!found)
178         {
179           for (int apos = 0; !found && apos<alAnnotation.length; apos++)
180           {
181             found = (alAnnotation[apos] == sqann[i]);
182           }
183         }
184         if (found)
185         {
186           // only copy the given annotation
187           AlignmentAnnotation newann = new AlignmentAnnotation(sqann[i]);
188           addAlignmentAnnotation(newann);
189         }
190       }
191     }
192     if (seq.getPDBId()!=null) {
193       Vector ids = seq.getPDBId();
194       Enumeration e = ids.elements();
195       while (e.hasMoreElements()) {
196         this.addPDBId(new PDBEntry((PDBEntry) e.nextElement()));
197       }
198     }
199   }
200
201   /**
202    * DOCUMENT ME!
203    *
204    * @param v DOCUMENT ME!
205    */
206   public void setSequenceFeatures(SequenceFeature[] features)
207   {
208     sequenceFeatures = features;
209   }
210
211   public synchronized void addSequenceFeature(SequenceFeature sf)
212   {
213     if (sequenceFeatures == null)
214     {
215       sequenceFeatures = new SequenceFeature[0];
216     }
217
218     for (int i = 0; i < sequenceFeatures.length; i++)
219     {
220       if (sequenceFeatures[i].equals(sf))
221       {
222         return;
223       }
224     }
225
226     SequenceFeature[] temp = new SequenceFeature[sequenceFeatures.length + 1];
227     System.arraycopy(sequenceFeatures, 0, temp, 0, sequenceFeatures.length);
228     temp[sequenceFeatures.length] = sf;
229
230     sequenceFeatures = temp;
231   }
232
233   public void deleteFeature(SequenceFeature sf)
234   {
235     if(sequenceFeatures==null)
236     {
237       return;
238     }
239
240     int index=0;
241     for (index = 0; index < sequenceFeatures.length; index++)
242     {
243       if (sequenceFeatures[index].equals(sf))
244       {
245         break;
246       }
247     }
248
249
250     if(index==sequenceFeatures.length)
251     {
252       return;
253     }
254
255     int sfLength = sequenceFeatures.length;
256     if(sfLength<2)
257     {
258       sequenceFeatures = null;
259     }
260     else
261     {
262       SequenceFeature[] temp = new SequenceFeature[sfLength-1];
263       System.arraycopy(sequenceFeatures, 0, temp, 0, index);
264
265       if(index<sfLength)
266       {
267         System.arraycopy(sequenceFeatures,
268                          index + 1,
269                          temp,
270                          index, sequenceFeatures.length - index -1);
271       }
272
273       sequenceFeatures = temp;
274     }
275   }
276
277   /**
278    * DOCUMENT ME!
279    *
280    * @return DOCUMENT ME!
281    */
282   public SequenceFeature[] getSequenceFeatures()
283   {
284     return sequenceFeatures;
285   }
286
287   public void addPDBId(PDBEntry entry)
288   {
289     if (pdbIds == null)
290     {
291       pdbIds = new Vector();
292     }
293
294     pdbIds.addElement(entry);
295   }
296
297   /**
298    * DOCUMENT ME!
299    *
300    * @param id DOCUMENT ME!
301    */
302   public void setPDBId(Vector id)
303   {
304     pdbIds = id;
305   }
306
307   /**
308    * DOCUMENT ME!
309    *
310    * @return DOCUMENT ME!
311    */
312   public Vector getPDBId()
313   {
314     return pdbIds;
315   }
316
317   /**
318    * DOCUMENT ME!
319    *
320    * @return DOCUMENT ME!
321    */
322   public String getDisplayId(boolean jvsuffix)
323   {
324     StringBuffer result = new StringBuffer(name);
325     if (jvsuffix)
326     {
327       result.append("/" + start + "-" + end);
328     }
329
330     return result.toString();
331   }
332
333   /**
334    * DOCUMENT ME!
335    *
336    * @param name DOCUMENT ME!
337    */
338   public void setName(String name)
339   {
340     this.name = name;
341     this.parseId();
342   }
343
344   /**
345    * DOCUMENT ME!
346    *
347    * @return DOCUMENT ME!
348    */
349   public String getName()
350   {
351     return this.name;
352   }
353
354   /**
355    * DOCUMENT ME!
356    *
357    * @param start DOCUMENT ME!
358    */
359   public void setStart(int start)
360   {
361     this.start = start;
362   }
363
364   /**
365    * DOCUMENT ME!
366    *
367    * @return DOCUMENT ME!
368    */
369   public int getStart()
370   {
371     return this.start;
372   }
373
374   /**
375    * DOCUMENT ME!
376    *
377    * @param end DOCUMENT ME!
378    */
379   public void setEnd(int end)
380   {
381     this.end = end;
382   }
383
384   /**
385    * DOCUMENT ME!
386    *
387    * @return DOCUMENT ME!
388    */
389   public int getEnd()
390   {
391     return this.end;
392   }
393
394   /**
395    * DOCUMENT ME!
396    *
397    * @return DOCUMENT ME!
398    */
399   public int getLength()
400   {
401     return this.sequence.length;
402   }
403
404   /**
405    * DOCUMENT ME!
406    *
407    * @param seq DOCUMENT ME!
408    */
409   public void setSequence(String seq)
410   {
411     this.sequence = seq.toCharArray();
412     checkValidRange();
413   }
414
415
416   public String getSequenceAsString()
417   {
418     return new String(sequence);
419   }
420
421   public String getSequenceAsString(int start, int end)
422   {
423     return new String(getSequence(start, end));
424   }
425
426
427   public char [] getSequence()
428   {
429     return sequence;
430   }
431
432   /**
433    * DOCUMENT ME!
434    *
435    * @param start DOCUMENT ME!
436    * @param end DOCUMENT ME!
437    *
438    * @return DOCUMENT ME!
439    */
440   public char [] getSequence(int start, int end)
441   {
442     if (start<0)
443       start=0;
444     // JBPNote - left to user to pad the result here (TODO:Decide on this policy)
445     if (start >= sequence.length)
446     {
447       return new char[0];
448     }
449
450     if (end >= sequence.length)
451     {
452       end = sequence.length;
453     }
454
455     char [] reply = new char[end-start];
456     System.arraycopy(sequence, start, reply, 0, end-start);
457
458     return reply;
459   }
460
461
462   /**
463    * make a new Sequence object from start to end (including gaps) over this seqeunce
464    * @param start int
465    * @param end int
466    * @return SequenceI
467    */
468   public SequenceI getSubSequence(int start, int end)
469   {
470     if (start < 0)
471     {
472       start = 0;
473     }
474     char [] seq = getSequence(start, end);
475     if (seq.length == 0)
476     {
477       return null;
478     }
479     int nstart = findPosition(start);
480     int nend = findPosition(end) - 1;
481     // JBPNote - this is an incomplete copy.
482     SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
483     nseq.setDescription(description);
484     if (datasetSequence!=null)
485     {
486         nseq.setDatasetSequence(datasetSequence);
487     }
488     else
489     {
490         nseq.setDatasetSequence(this);
491     }
492     return nseq;
493   }
494
495   /**
496    * DOCUMENT ME!
497    *
498    * @param i DOCUMENT ME!
499    *
500    * @return DOCUMENT ME!
501    */
502   public char getCharAt(int i)
503   {
504     if (i < sequence.length)
505     {
506       return sequence[i];
507     }
508     else
509     {
510       return ' ';
511     }
512   }
513
514   /**
515    * DOCUMENT ME!
516    *
517    * @param desc DOCUMENT ME!
518    */
519   public void setDescription(String desc)
520   {
521     this.description = desc;
522   }
523
524   /**
525    * DOCUMENT ME!
526    *
527    * @return DOCUMENT ME!
528    */
529   public String getDescription()
530   {
531     return this.description;
532   }
533
534   /**
535    * Return the alignment position for a sequence position
536    *
537    * @param pos lying from start to end
538    *
539    * @return aligned position of residue pos
540    */
541   public int findIndex(int pos)
542   {
543     // returns the alignment position for a residue
544     int j = start;
545     int i = 0;
546
547     while ( (i < sequence.length) && (j <= end) && (j <= pos))
548     {
549       if (!jalview.util.Comparison.isGap(sequence[i]))
550       {
551         j++;
552       }
553
554       i++;
555     }
556
557     if ( (j == end) && (j < pos))
558     {
559       return end + 1;
560     }
561     else
562     {
563       return i;
564     }
565   }
566
567   /**
568    * Returns the sequence position for an alignment position
569    *
570    * @param i column index in alignment (from 1)
571    *
572    * @return residue number for residue (left of and) nearest ith column
573    */
574   public int findPosition(int i)
575   {
576     int j = 0;
577     int pos = start;
578     int seqlen = sequence.length;
579     while ( (j < i) && (j < seqlen))
580     {
581       if (!jalview.util.Comparison.isGap( sequence[j] ))
582       {
583         pos++;
584       }
585
586       j++;
587     }
588
589     return pos;
590   }
591
592   /**
593    * Returns an int array where indices correspond to each residue in the sequence and the element value gives its position in the alignment
594    *
595    * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no residues in SequenceI object
596    */
597   public int[] gapMap()
598   {
599     String seq = jalview.analysis.AlignSeq.extractGaps(jalview.util.Comparison.
600         GapChars, new String(sequence));
601     int[] map = new int[seq.length()];
602     int j = 0;
603     int p = 0;
604
605     while (j < sequence.length)
606     {
607       if (!jalview.util.Comparison.isGap(sequence[j]))
608       {
609         map[p++] = j;
610       }
611
612       j++;
613     }
614
615     return map;
616   }
617
618   /**
619    * DOCUMENT ME!
620    *
621    * @param i DOCUMENT ME!
622    * @param j DOCUMENT ME!
623    */
624   public void deleteChars(int i, int j)
625   {
626     if (i >= sequence.length)
627     {
628       return;
629     }
630
631     char [] tmp;
632
633     if (j >= sequence.length)
634     {
635       tmp = new char[i];
636       System.arraycopy(sequence,0,tmp,0,i);
637     }
638     else
639     {
640       tmp = new char[sequence.length-j+i];
641       System.arraycopy(sequence,0,tmp,0,i);
642       System.arraycopy(sequence,j,tmp,i,sequence.length-j);
643     }
644
645     if (this.datasetSequence != null)
646     {
647       for (int s = i; s < j; s++)
648       {
649         if (jalview.schemes.ResidueProperties.aaIndex[sequence[s]] != 23)
650         {
651
652           Sequence ds = new Sequence(name,
653                                      AlignSeq.extractGaps(
654                                          jalview.util.Comparison.GapChars,
655                                          this.getSequenceAsString()
656                                      ),
657                                      start,
658                                      end);
659           ds.setDescription(description);
660         }
661         break;
662       }
663     }
664
665     sequence = tmp;
666
667   }
668
669
670   /**
671    * DOCUMENT ME!
672    *
673    * @param i DOCUMENT ME!
674    * @param c DOCUMENT ME!
675    * @param chop DOCUMENT ME!
676    */
677   public void insertCharAt(int i, int length, char c)
678   {
679     char [] tmp = new char[sequence.length+length];
680
681     if (i >= sequence.length)
682     {
683       System.arraycopy(sequence, 0, tmp, 0, sequence.length);
684       i = sequence.length;
685     }
686     else
687    {
688       System.arraycopy(sequence, 0, tmp, 0, i);
689    }
690
691
692     int index = i;
693     while (length > 0)
694     {
695       tmp[ index++ ] = c;
696       length--;
697     }
698
699     if (i < sequence.length)
700     {
701       System.arraycopy(sequence, i, tmp, index, sequence.length-i );
702     }
703
704     sequence = tmp;
705   }
706
707   public void insertCharAt(int i, char c)
708   {
709     insertCharAt(i, 1, c);
710   }
711
712   public String getVamsasId()
713   {
714     return vamsasId;
715   }
716
717   public void setVamsasId(String id)
718   {
719     vamsasId = id;
720   }
721
722   public void setDBRef(DBRefEntry[] dbref)
723   {
724     dbrefs = dbref;
725   }
726
727   public DBRefEntry[] getDBRef()
728   {
729     return dbrefs;
730   }
731
732   public void addDBRef(DBRefEntry entry)
733   {
734     if (dbrefs == null)
735     {
736       dbrefs = new DBRefEntry[0];
737     }
738
739     int i, iSize = dbrefs.length;
740
741     for(i=0; i<iSize; i++)
742     {
743       if(dbrefs[i].equals(entry))
744       {
745         return;
746       }
747     }
748
749     DBRefEntry[] temp = new DBRefEntry[iSize + 1];
750     System.arraycopy(dbrefs, 0, temp, 0, iSize);
751     temp[temp.length - 1] = entry;
752
753     dbrefs = temp;
754   }
755
756   public void setDatasetSequence(SequenceI seq)
757   {
758     datasetSequence = seq;
759   }
760
761   public SequenceI getDatasetSequence()
762   {
763     return datasetSequence;
764   }
765
766   public AlignmentAnnotation[] getAnnotation()
767   {
768     if (annotation == null)
769     {
770       return null;
771     }
772
773     AlignmentAnnotation[] ret = new AlignmentAnnotation[annotation.size()];
774     for (int r = 0; r < ret.length; r++)
775     {
776       ret[r] = (AlignmentAnnotation) annotation.elementAt(r);
777     }
778
779     return ret;
780   }
781
782   public void addAlignmentAnnotation(AlignmentAnnotation annotation)
783   {
784     if (this.annotation == null)
785     {
786       this.annotation = new Vector();
787     }
788
789     this.annotation.addElement(annotation);
790     annotation.setSequenceRef(this);
791   }
792
793   public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
794   {
795     if(this.annotation!=null)
796     {
797       this.annotation.removeElement(annotation);
798       if(this.annotation.size()==0)
799         this.annotation = null;
800     }
801   }
802
803
804   /**
805    * test if this is a valid candidate for another
806    * sequence's dataset sequence.
807    *
808    */
809   private boolean isValidDatasetSequence()
810   {
811     if (datasetSequence!=null)
812     {
813           return false;
814     }
815       for (int i=0;i<sequence.length; i++)
816     {
817           if (jalview.util.Comparison.isGap(sequence[i]))
818       {
819               return false;
820       }
821     }
822       return true;
823   }
824   /* (non-Javadoc)
825    * @see jalview.datamodel.SequenceI#deriveSequence()
826    */
827   public SequenceI deriveSequence()
828   {
829     SequenceI seq=new Sequence(this);
830     if (datasetSequence != null)
831     {
832       // duplicate current sequence with same dataset
833       seq.setDatasetSequence(datasetSequence);
834     }
835     else
836     {
837       if (isValidDatasetSequence())
838       {
839         // Use this as dataset sequence
840         seq.setDatasetSequence(this);
841       } else {
842         // Create a new, valid dataset sequence
843         SequenceI ds = seq;
844         ds.setSequence(AlignSeq.extractGaps(jalview.util.Comparison.GapChars, new String(sequence)));
845         setDatasetSequence(ds);
846         seq = this; // and return this sequence as the derived sequence.
847       }
848     }
849     return seq;
850   }
851   /* (non-Javadoc)
852    * @see jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[] annotations)
853    */
854   public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
855   {
856     if (annotation!=null) {
857       annotation.removeAllElements();
858     }
859     if (annotations!=null) {
860       for (int i=0; i<annotations.length; i++)
861       {
862         if (annotations[i]!=null)
863           addAlignmentAnnotation(annotations[i]);
864       }
865     }
866   }
867
868   /* (non-Javadoc)
869    * @see jalview.datamodel.SequenceI#getAnnotation(java.lang.String)
870    */
871   public AlignmentAnnotation[] getAnnotation(String label)
872   {
873     if (annotation==null || annotation.size()==0)
874     {
875       return null;
876     }
877     
878     Vector subset = new Vector();
879     Enumeration e = annotation.elements();
880     while (e.hasMoreElements())
881     {
882       AlignmentAnnotation ann = (AlignmentAnnotation) e.nextElement();
883       if (ann.label!=null && ann.label.equals(label))
884       {
885         subset.addElement(ann);
886       }
887     }
888     if (subset.size()==0)
889     {
890       return null;
891     }
892     AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
893     int i=0;
894     e = subset.elements();
895     while (e.hasMoreElements())
896     {
897       anns[i++] = (AlignmentAnnotation) e.nextElement();
898     }
899     subset.removeAllElements();
900     return anns;
901   }
902
903 }
904
905