correct construction of new dataset sequence when residues are deleted
[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   /* (non-Javadoc)
619    * @see jalview.datamodel.SequenceI#deleteChars(int, int)
620    */
621   public void deleteChars(int i, int j)
622   {
623     int newstart=start,newend=end;
624     if (i >= sequence.length)
625     {
626       return;
627     }
628
629     char [] tmp;
630
631     if (j >= sequence.length)
632     {
633       tmp = new char[i];
634       System.arraycopy(sequence,0,tmp,0,i);
635     }
636     else
637     {
638       tmp = new char[sequence.length-j+i];
639       System.arraycopy(sequence,0,tmp,0,i);
640       System.arraycopy(sequence,j,tmp,i,sequence.length-j);
641     }
642     boolean createNewDs=false;
643     for (int s = i; s < j; s++)
644     {
645       if (jalview.schemes.ResidueProperties.aaIndex[sequence[s]] != 23)
646       {
647         if (createNewDs)
648         {
649           newend--;
650         } else {
651           int sindex = findIndex(start)-1;
652           if (sindex==s)
653         {
654           // delete characters including start of sequence
655           newstart = findPosition(j);
656           break; // don't need to search for any more residue characters.
657         } else {
658           // delete characters after start.
659           int eindex = findIndex(end)-1;
660           if (eindex<j)
661           {
662             // delete characters at end of sequence
663             newend = findPosition(i-1);
664             break; // don't need to search for any more residue characters.
665           } else {
666             createNewDs=true;
667             newend--; // decrease end position by one for the deleted residue and search further
668           }
669         }
670         }
671       }
672     }
673     // deletion occured in the middle of the sequence
674     if (createNewDs && this.datasetSequence != null)
675     {
676       // construct a new sequence
677       Sequence ds = new Sequence(datasetSequence);
678       // TODO: remove any non-inheritable properties ?
679       // TODO: create a sequence mapping (since there is a relation here ?)
680       ds.deleteChars(i, j);
681       datasetSequence = ds;
682     }
683     start = newstart;
684     end = newend;
685     sequence = tmp;
686   }
687
688
689   /**
690    * DOCUMENT ME!
691    *
692    * @param i DOCUMENT ME!
693    * @param c DOCUMENT ME!
694    * @param chop DOCUMENT ME!
695    */
696   public void insertCharAt(int i, int length, char c)
697   {
698     char [] tmp = new char[sequence.length+length];
699
700     if (i >= sequence.length)
701     {
702       System.arraycopy(sequence, 0, tmp, 0, sequence.length);
703       i = sequence.length;
704     }
705     else
706    {
707       System.arraycopy(sequence, 0, tmp, 0, i);
708    }
709
710
711     int index = i;
712     while (length > 0)
713     {
714       tmp[ index++ ] = c;
715       length--;
716     }
717
718     if (i < sequence.length)
719     {
720       System.arraycopy(sequence, i, tmp, index, sequence.length-i );
721     }
722
723     sequence = tmp;
724   }
725
726   public void insertCharAt(int i, char c)
727   {
728     insertCharAt(i, 1, c);
729   }
730
731   public String getVamsasId()
732   {
733     return vamsasId;
734   }
735
736   public void setVamsasId(String id)
737   {
738     vamsasId = id;
739   }
740
741   public void setDBRef(DBRefEntry[] dbref)
742   {
743     dbrefs = dbref;
744   }
745
746   public DBRefEntry[] getDBRef()
747   {
748     return dbrefs;
749   }
750
751   public void addDBRef(DBRefEntry entry)
752   {
753     if (dbrefs == null)
754     {
755       dbrefs = new DBRefEntry[0];
756     }
757
758     int i, iSize = dbrefs.length;
759
760     for(i=0; i<iSize; i++)
761     {
762       if(dbrefs[i].equals(entry))
763       {
764         return;
765       }
766     }
767
768     DBRefEntry[] temp = new DBRefEntry[iSize + 1];
769     System.arraycopy(dbrefs, 0, temp, 0, iSize);
770     temp[temp.length - 1] = entry;
771
772     dbrefs = temp;
773   }
774
775   public void setDatasetSequence(SequenceI seq)
776   {
777     datasetSequence = seq;
778   }
779
780   public SequenceI getDatasetSequence()
781   {
782     return datasetSequence;
783   }
784
785   public AlignmentAnnotation[] getAnnotation()
786   {
787     if (annotation == null)
788     {
789       return null;
790     }
791
792     AlignmentAnnotation[] ret = new AlignmentAnnotation[annotation.size()];
793     for (int r = 0; r < ret.length; r++)
794     {
795       ret[r] = (AlignmentAnnotation) annotation.elementAt(r);
796     }
797
798     return ret;
799   }
800
801   public void addAlignmentAnnotation(AlignmentAnnotation annotation)
802   {
803     if (this.annotation == null)
804     {
805       this.annotation = new Vector();
806     }
807
808     this.annotation.addElement(annotation);
809     annotation.setSequenceRef(this);
810   }
811
812   public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
813   {
814     if(this.annotation!=null)
815     {
816       this.annotation.removeElement(annotation);
817       if(this.annotation.size()==0)
818         this.annotation = null;
819     }
820   }
821
822
823   /**
824    * test if this is a valid candidate for another
825    * sequence's dataset sequence.
826    *
827    */
828   private boolean isValidDatasetSequence()
829   {
830     if (datasetSequence!=null)
831     {
832           return false;
833     }
834       for (int i=0;i<sequence.length; i++)
835     {
836           if (jalview.util.Comparison.isGap(sequence[i]))
837       {
838               return false;
839       }
840     }
841       return true;
842   }
843   /* (non-Javadoc)
844    * @see jalview.datamodel.SequenceI#deriveSequence()
845    */
846   public SequenceI deriveSequence()
847   {
848     SequenceI seq=new Sequence(this);
849     if (datasetSequence != null)
850     {
851       // duplicate current sequence with same dataset
852       seq.setDatasetSequence(datasetSequence);
853     }
854     else
855     {
856       if (isValidDatasetSequence())
857       {
858         // Use this as dataset sequence
859         seq.setDatasetSequence(this);
860       } else {
861         // Create a new, valid dataset sequence
862         SequenceI ds = seq;
863         ds.setSequence(AlignSeq.extractGaps(jalview.util.Comparison.GapChars, new String(sequence)));
864         setDatasetSequence(ds);
865         ds.setSequenceFeatures(getSequenceFeatures());
866         seq = this; // and return this sequence as the derived sequence.
867       }
868     }
869     return seq;
870   }
871   /* (non-Javadoc)
872    * @see jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[] annotations)
873    */
874   public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
875   {
876     if (annotation!=null) {
877       annotation.removeAllElements();
878     }
879     if (annotations!=null) {
880       for (int i=0; i<annotations.length; i++)
881       {
882         if (annotations[i]!=null)
883           addAlignmentAnnotation(annotations[i]);
884       }
885     }
886   }
887
888   /* (non-Javadoc)
889    * @see jalview.datamodel.SequenceI#getAnnotation(java.lang.String)
890    */
891   public AlignmentAnnotation[] getAnnotation(String label)
892   {
893     if (annotation==null || annotation.size()==0)
894     {
895       return null;
896     }
897     
898     Vector subset = new Vector();
899     Enumeration e = annotation.elements();
900     while (e.hasMoreElements())
901     {
902       AlignmentAnnotation ann = (AlignmentAnnotation) e.nextElement();
903       if (ann.label!=null && ann.label.equals(label))
904       {
905         subset.addElement(ann);
906       }
907     }
908     if (subset.size()==0)
909     {
910       return null;
911     }
912     AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
913     int i=0;
914     e = subset.elements();
915     while (e.hasMoreElements())
916     {
917       anns[i++] = (AlignmentAnnotation) e.nextElement();
918     }
919     subset.removeAllElements();
920     return anns;
921   }
922
923 }
924
925