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