d64e133777ce29d50430e6b889888dd5e16b3569
[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 && alAnnotation!=null) {
169       AlignmentAnnotation[] sqann = seq.getAnnotation();
170       for (int i=0;i<sqann.length; i++)
171       {
172         boolean found = sqann == alAnnotation;
173         if (!found)
174         {
175           for (int apos = 0; !found && apos<alAnnotation.length; apos++)
176           {
177             found = (alAnnotation[apos] == sqann[i]);
178           }
179         }
180         AlignmentAnnotation newann = new AlignmentAnnotation(sqann[i]);
181         addAlignmentAnnotation(newann);
182       }
183     }
184     if (seq.getPDBId()!=null) {
185       Vector ids = seq.getPDBId();
186       Enumeration e = ids.elements();
187       while (e.hasMoreElements()) {
188         this.addPDBId(new PDBEntry((PDBEntry) e.nextElement()));
189       }
190     }
191   }
192
193   /**
194    * DOCUMENT ME!
195    *
196    * @param v DOCUMENT ME!
197    */
198   public void setSequenceFeatures(SequenceFeature[] features)
199   {
200     sequenceFeatures = features;
201   }
202
203   public synchronized void addSequenceFeature(SequenceFeature sf)
204   {
205     if (sequenceFeatures == null)
206     {
207       sequenceFeatures = new SequenceFeature[0];
208     }
209
210     for (int i = 0; i < sequenceFeatures.length; i++)
211     {
212       if (sequenceFeatures[i].equals(sf))
213       {
214         return;
215       }
216     }
217
218     SequenceFeature[] temp = new SequenceFeature[sequenceFeatures.length + 1];
219     System.arraycopy(sequenceFeatures, 0, temp, 0, sequenceFeatures.length);
220     temp[sequenceFeatures.length] = sf;
221
222     sequenceFeatures = temp;
223   }
224
225   public void deleteFeature(SequenceFeature sf)
226   {
227     if(sequenceFeatures==null)
228     {
229       return;
230     }
231
232     int index=0;
233     for (index = 0; index < sequenceFeatures.length; index++)
234     {
235       if (sequenceFeatures[index].equals(sf))
236       {
237         break;
238       }
239     }
240
241
242     if(index==sequenceFeatures.length)
243     {
244       return;
245     }
246
247     int sfLength = sequenceFeatures.length;
248     if(sfLength<2)
249     {
250       sequenceFeatures = null;
251     }
252     else
253     {
254       SequenceFeature[] temp = new SequenceFeature[sfLength-1];
255       System.arraycopy(sequenceFeatures, 0, temp, 0, index);
256
257       if(index<sfLength)
258       {
259         System.arraycopy(sequenceFeatures,
260                          index + 1,
261                          temp,
262                          index, sequenceFeatures.length - index -1);
263       }
264
265       sequenceFeatures = temp;
266     }
267   }
268
269   /**
270    * DOCUMENT ME!
271    *
272    * @return DOCUMENT ME!
273    */
274   public SequenceFeature[] getSequenceFeatures()
275   {
276     return sequenceFeatures;
277   }
278
279   public void addPDBId(PDBEntry entry)
280   {
281     if (pdbIds == null)
282     {
283       pdbIds = new Vector();
284     }
285
286     pdbIds.addElement(entry);
287   }
288
289   /**
290    * DOCUMENT ME!
291    *
292    * @param id DOCUMENT ME!
293    */
294   public void setPDBId(Vector id)
295   {
296     pdbIds = id;
297   }
298
299   /**
300    * DOCUMENT ME!
301    *
302    * @return DOCUMENT ME!
303    */
304   public Vector getPDBId()
305   {
306     return pdbIds;
307   }
308
309   /**
310    * DOCUMENT ME!
311    *
312    * @return DOCUMENT ME!
313    */
314   public String getDisplayId(boolean jvsuffix)
315   {
316     StringBuffer result = new StringBuffer(name);
317     if (jvsuffix)
318     {
319       result.append("/" + start + "-" + end);
320     }
321
322     return result.toString();
323   }
324
325   /**
326    * DOCUMENT ME!
327    *
328    * @param name DOCUMENT ME!
329    */
330   public void setName(String name)
331   {
332     this.name = name;
333     this.parseId();
334   }
335
336   /**
337    * DOCUMENT ME!
338    *
339    * @return DOCUMENT ME!
340    */
341   public String getName()
342   {
343     return this.name;
344   }
345
346   /**
347    * DOCUMENT ME!
348    *
349    * @param start DOCUMENT ME!
350    */
351   public void setStart(int start)
352   {
353     this.start = start;
354   }
355
356   /**
357    * DOCUMENT ME!
358    *
359    * @return DOCUMENT ME!
360    */
361   public int getStart()
362   {
363     return this.start;
364   }
365
366   /**
367    * DOCUMENT ME!
368    *
369    * @param end DOCUMENT ME!
370    */
371   public void setEnd(int end)
372   {
373     this.end = end;
374   }
375
376   /**
377    * DOCUMENT ME!
378    *
379    * @return DOCUMENT ME!
380    */
381   public int getEnd()
382   {
383     return this.end;
384   }
385
386   /**
387    * DOCUMENT ME!
388    *
389    * @return DOCUMENT ME!
390    */
391   public int getLength()
392   {
393     return this.sequence.length;
394   }
395
396   /**
397    * DOCUMENT ME!
398    *
399    * @param seq DOCUMENT ME!
400    */
401   public void setSequence(String seq)
402   {
403     this.sequence = seq.toCharArray();
404     checkValidRange();
405   }
406
407
408   public String getSequenceAsString()
409   {
410     return new String(sequence);
411   }
412
413   public String getSequenceAsString(int start, int end)
414   {
415     return new String(getSequence(start, end));
416   }
417
418
419   public char [] getSequence()
420   {
421     return sequence;
422   }
423
424   /**
425    * DOCUMENT ME!
426    *
427    * @param start DOCUMENT ME!
428    * @param end DOCUMENT ME!
429    *
430    * @return DOCUMENT ME!
431    */
432   public char [] getSequence(int start, int end)
433   {
434     if (start<0)
435       start=0;
436     // JBPNote - left to user to pad the result here (TODO:Decide on this policy)
437     if (start >= sequence.length)
438     {
439       return new char[0];
440     }
441
442     if (end >= sequence.length)
443     {
444       end = sequence.length;
445     }
446
447     char [] reply = new char[end-start];
448     System.arraycopy(sequence, start, reply, 0, end-start);
449
450     return reply;
451   }
452
453
454   /**
455    * make a new Sequence object from start to end (including gaps) over this seqeunce
456    * @param start int
457    * @param end int
458    * @return SequenceI
459    */
460   public SequenceI getSubSequence(int start, int end)
461   {
462     if (start < 0)
463     {
464       start = 0;
465     }
466     char [] seq = getSequence(start, end);
467     if (seq.length == 0)
468     {
469       return null;
470     }
471     int nstart = findPosition(start);
472     int nend = findPosition(end) - 1;
473     // JBPNote - this is an incomplete copy.
474     SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
475     nseq.setDescription(description);
476     if (datasetSequence!=null)
477     {
478         nseq.setDatasetSequence(datasetSequence);
479     }
480     else
481     {
482         nseq.setDatasetSequence(this);
483     }
484     return nseq;
485   }
486
487   /**
488    * DOCUMENT ME!
489    *
490    * @param i DOCUMENT ME!
491    *
492    * @return DOCUMENT ME!
493    */
494   public char getCharAt(int i)
495   {
496     if (i < sequence.length)
497     {
498       return sequence[i];
499     }
500     else
501     {
502       return ' ';
503     }
504   }
505
506   /**
507    * DOCUMENT ME!
508    *
509    * @param desc DOCUMENT ME!
510    */
511   public void setDescription(String desc)
512   {
513     this.description = desc;
514   }
515
516   /**
517    * DOCUMENT ME!
518    *
519    * @return DOCUMENT ME!
520    */
521   public String getDescription()
522   {
523     return this.description;
524   }
525
526   /**
527    * Return the alignment position for a sequence position
528    *
529    * @param pos lying from start to end
530    *
531    * @return aligned position of residue pos
532    */
533   public int findIndex(int pos)
534   {
535     // returns the alignment position for a residue
536     int j = start;
537     int i = 0;
538
539     while ( (i < sequence.length) && (j <= end) && (j <= pos))
540     {
541       if (!jalview.util.Comparison.isGap(sequence[i]))
542       {
543         j++;
544       }
545
546       i++;
547     }
548
549     if ( (j == end) && (j < pos))
550     {
551       return end + 1;
552     }
553     else
554     {
555       return i;
556     }
557   }
558
559   /**
560    * Returns the sequence position for an alignment position
561    *
562    * @param i column index in alignment (from 1)
563    *
564    * @return residue number for residue (left of and) nearest ith column
565    */
566   public int findPosition(int i)
567   {
568     int j = 0;
569     int pos = start;
570     int seqlen = sequence.length;
571     while ( (j < i) && (j < seqlen))
572     {
573       if (!jalview.util.Comparison.isGap( sequence[j] ))
574       {
575         pos++;
576       }
577
578       j++;
579     }
580
581     return pos;
582   }
583
584   /**
585    * Returns an int array where indices correspond to each residue in the sequence and the element value gives its position in the alignment
586    *
587    * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no residues in SequenceI object
588    */
589   public int[] gapMap()
590   {
591     String seq = jalview.analysis.AlignSeq.extractGaps(jalview.util.Comparison.
592         GapChars, new String(sequence));
593     int[] map = new int[seq.length()];
594     int j = 0;
595     int p = 0;
596
597     while (j < sequence.length)
598     {
599       if (!jalview.util.Comparison.isGap(sequence[j]))
600       {
601         map[p++] = j;
602       }
603
604       j++;
605     }
606
607     return map;
608   }
609
610   /**
611    * DOCUMENT ME!
612    *
613    * @param i DOCUMENT ME!
614    * @param j DOCUMENT ME!
615    */
616   public void deleteChars(int i, int j)
617   {
618     if (i >= sequence.length)
619     {
620       return;
621     }
622
623     char [] tmp;
624
625     if (j >= sequence.length)
626     {
627       tmp = new char[i];
628       System.arraycopy(sequence,0,tmp,0,i);
629     }
630     else
631     {
632       tmp = new char[sequence.length-j+i];
633       System.arraycopy(sequence,0,tmp,0,i);
634       System.arraycopy(sequence,j,tmp,i,sequence.length-j);
635     }
636
637     if (this.datasetSequence != null)
638     {
639       for (int s = i; s < j; s++)
640       {
641         if (jalview.schemes.ResidueProperties.aaIndex[sequence[s]] != 23)
642         {
643
644           Sequence ds = new Sequence(name,
645                                      AlignSeq.extractGaps(
646                                          jalview.util.Comparison.GapChars,
647                                          this.getSequenceAsString()
648                                      ),
649                                      start,
650                                      end);
651           ds.setDescription(description);
652         }
653         break;
654       }
655     }
656
657     sequence = tmp;
658
659   }
660
661
662   /**
663    * DOCUMENT ME!
664    *
665    * @param i DOCUMENT ME!
666    * @param c DOCUMENT ME!
667    * @param chop DOCUMENT ME!
668    */
669   public void insertCharAt(int i, int length, char c)
670   {
671     char [] tmp = new char[sequence.length+length];
672
673     if (i >= sequence.length)
674     {
675       System.arraycopy(sequence, 0, tmp, 0, sequence.length);
676       i = sequence.length;
677     }
678     else
679    {
680       System.arraycopy(sequence, 0, tmp, 0, i);
681    }
682
683
684     int index = i;
685     while (length > 0)
686     {
687       tmp[ index++ ] = c;
688       length--;
689     }
690
691     if (i < sequence.length)
692     {
693       System.arraycopy(sequence, i, tmp, index, sequence.length-i );
694     }
695
696     sequence = tmp;
697   }
698
699   public void insertCharAt(int i, char c)
700   {
701     insertCharAt(i, 1, c);
702   }
703
704   public String getVamsasId()
705   {
706     return vamsasId;
707   }
708
709   public void setVamsasId(String id)
710   {
711     vamsasId = id;
712   }
713
714   public void setDBRef(DBRefEntry[] dbref)
715   {
716     dbrefs = dbref;
717   }
718
719   public DBRefEntry[] getDBRef()
720   {
721     return dbrefs;
722   }
723
724   public void addDBRef(DBRefEntry entry)
725   {
726     if (dbrefs == null)
727     {
728       dbrefs = new DBRefEntry[0];
729     }
730
731     int i, iSize = dbrefs.length;
732
733     for(i=0; i<iSize; i++)
734     {
735       if(dbrefs[i].equals(entry))
736       {
737         return;
738       }
739     }
740
741     DBRefEntry[] temp = new DBRefEntry[iSize + 1];
742     System.arraycopy(dbrefs, 0, temp, 0, iSize);
743     temp[temp.length - 1] = entry;
744
745     dbrefs = temp;
746   }
747
748   public void setDatasetSequence(SequenceI seq)
749   {
750     datasetSequence = seq;
751   }
752
753   public SequenceI getDatasetSequence()
754   {
755     return datasetSequence;
756   }
757
758   public AlignmentAnnotation[] getAnnotation()
759   {
760     if (annotation == null)
761     {
762       return null;
763     }
764
765     AlignmentAnnotation[] ret = new AlignmentAnnotation[annotation.size()];
766     for (int r = 0; r < ret.length; r++)
767     {
768       ret[r] = (AlignmentAnnotation) annotation.elementAt(r);
769     }
770
771     return ret;
772   }
773
774   public void addAlignmentAnnotation(AlignmentAnnotation annotation)
775   {
776     if (this.annotation == null)
777     {
778       this.annotation = new Vector();
779     }
780
781     this.annotation.addElement(annotation);
782     annotation.setSequenceRef(this);
783   }
784
785   public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
786   {
787     if(this.annotation!=null)
788     {
789       this.annotation.removeElement(annotation);
790       if(this.annotation.size()==0)
791         this.annotation = null;
792     }
793   }
794
795
796   /**
797    * test if this is a valid candidate for another
798    * sequence's dataset sequence.
799    *
800    */
801   private boolean isValidDatasetSequence()
802   {
803     if (datasetSequence!=null)
804     {
805           return false;
806     }
807       for (int i=0;i<sequence.length; i++)
808     {
809           if (jalview.util.Comparison.isGap(sequence[i]))
810       {
811               return false;
812       }
813     }
814       return true;
815   }
816   /* (non-Javadoc)
817    * @see jalview.datamodel.SequenceI#deriveSequence()
818    */
819   public SequenceI deriveSequence()
820   {
821     SequenceI seq=new Sequence(this);
822     if (datasetSequence != null)
823     {
824       // duplicate current sequence with same dataset
825       seq.setDatasetSequence(datasetSequence);
826     }
827     else
828     {
829       if (isValidDatasetSequence())
830       {
831         // Use this as dataset sequence
832         seq.setDatasetSequence(this);
833       } else {
834         // Create a new, valid dataset sequence
835         SequenceI ds = seq;
836         ds.setSequence(AlignSeq.extractGaps(jalview.util.Comparison.GapChars, new String(sequence)));
837         setDatasetSequence(ds);
838         seq = this; // and return this sequence as the derived sequence.
839       }
840     }
841     return seq;
842   }
843   /* (non-Javadoc)
844    * @see jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[] annotations)
845    */
846   public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
847   {
848     if (annotation!=null) {
849       annotation.removeAllElements();
850     }
851     if (annotations!=null) {
852       for (int i=0; i<annotations.length; i++)
853       {
854         if (annotations[i]!=null)
855           addAlignmentAnnotation(annotations[i]);
856       }
857     }
858   }
859
860   /* (non-Javadoc)
861    * @see jalview.datamodel.SequenceI#getAnnotation(java.lang.String)
862    */
863   public AlignmentAnnotation[] getAnnotation(String label)
864   {
865     if (annotation==null || annotation.size()==0)
866     {
867       return null;
868     }
869     
870     Vector subset = new Vector();
871     Enumeration e = annotation.elements();
872     while (e.hasMoreElements())
873     {
874       AlignmentAnnotation ann = (AlignmentAnnotation) e.nextElement();
875       if (ann.label!=null && ann.label.equals(label))
876       {
877         subset.addElement(ann);
878       }
879     }
880     if (subset.size()==0)
881     {
882       return null;
883     }
884     AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
885     int i=0;
886     e = subset.elements();
887     while (e.hasMoreElements())
888     {
889       anns[i++] = (AlignmentAnnotation) e.nextElement();
890     }
891     subset.removeAllElements();
892     return anns;
893   }
894
895 }
896
897