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