checks for negative start column in restrict
[jalview.git] / src / jalview / datamodel / AlignmentAnnotation.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 import java.util.Enumeration;
22 import java.util.Hashtable;
23
24 /**
25  * DOCUMENT ME!
26  *
27  * @author $author$
28  * @version $Revision$
29  */
30 public class AlignmentAnnotation
31 {
32   /** If true, this annotations is calculated every edit,
33    * eg consensus, quality or conservation graphs */
34   public boolean autoCalculated = false;
35
36   public String annotationId;
37
38   public SequenceI sequenceRef;
39
40   /** DOCUMENT ME!! */
41   public String label;
42
43   /** DOCUMENT ME!! */
44   public String description;
45
46   /** DOCUMENT ME!! */
47   public Annotation[] annotations;
48
49   public java.util.Hashtable sequenceMapping;
50
51   /** DOCUMENT ME!! */
52   public float graphMin;
53
54   /** DOCUMENT ME!! */
55   public float graphMax;
56
57   /**
58    * Score associated with label and description.
59    */
60   public double score= Double.NaN;
61   /**
62    * flag indicating if annotation has a score.
63    */
64   public boolean hasScore=false;
65
66   public GraphLine threshold;
67
68   // Graphical hints and tips
69
70   /** DOCUMENT ME!! */
71   public boolean editable = false;
72
73   /** DOCUMENT ME!! */
74   public boolean hasIcons; //
75
76   /** DOCUMENT ME!! */
77   public boolean hasText;
78
79   /** DOCUMENT ME!! */
80   public boolean visible = true;
81
82   public int graphGroup = -1;
83
84   /** DOCUMENT ME!! */
85   public int height = 0;
86
87   public int graph = 0;
88
89   public int graphHeight = 40;
90
91   public boolean padGaps = false;
92
93   public static final int NO_GRAPH = 0;
94
95   public static final int BAR_GRAPH = 1;
96
97   public static final int LINE_GRAPH = 2;
98
99   public boolean belowAlignment = true;
100
101
102   public static int getGraphValueFromString(String string)
103   {
104     if (string.equalsIgnoreCase("BAR_GRAPH"))
105     {
106       return BAR_GRAPH;
107     }
108     else if (string.equalsIgnoreCase("LINE_GRAPH"))
109     {
110       return LINE_GRAPH;
111     }
112     else
113     {
114       return NO_GRAPH;
115     }
116   }
117
118   /**
119    * Creates a new AlignmentAnnotation object.
120    *
121    * @param label DOCUMENT ME!
122    * @param description DOCUMENT ME!
123    * @param annotations DOCUMENT ME!about:blank
124 Loading...
125    */
126   public AlignmentAnnotation(String label, String description,
127                              Annotation[] annotations)
128   {
129     // always editable?
130     editable = true;
131     this.label = label;
132     this.description = description;
133     this.annotations = annotations;
134
135      validateRangeAndDisplay();
136   }
137
138   void areLabelsSecondaryStructure()
139   {
140     boolean nonSSLabel = false;
141     for (int i = 0; i < annotations.length; i++)
142     {
143       if (annotations[i] == null)
144       {
145         continue;
146       }
147       if (annotations[i].secondaryStructure == 'H' ||
148           annotations[i].secondaryStructure == 'E')
149       {
150           hasIcons = true;
151       }
152
153       if(annotations[i].displayCharacter==null)
154       {
155         continue;
156       }
157
158       if (annotations[i].displayCharacter.length() == 1
159           && !annotations[i].displayCharacter.equals("H")
160           && !annotations[i].displayCharacter.equals("E")
161           && !annotations[i].displayCharacter.equals("-")
162           && !annotations[i].displayCharacter.equals("."))
163         {
164           if (jalview.schemes.ResidueProperties.aaIndex
165                   [annotations[i].displayCharacter.charAt(0)] < 23)
166           {
167             nonSSLabel = true;
168           }
169         }
170
171         if (annotations[i].displayCharacter.length() > 0)
172         {
173           hasText = true;
174         }
175       }
176
177     if (nonSSLabel)
178     {
179       hasIcons = false;
180       for (int j = 0; j < annotations.length; j++)
181       {
182         if (annotations[j] != null && annotations[j].secondaryStructure != ' ')
183         {
184           annotations[j].displayCharacter
185               = String.valueOf(annotations[j].secondaryStructure);
186           annotations[j].secondaryStructure = ' ';
187         }
188
189       }
190     }
191
192     annotationId = this.hashCode() + "";
193   }
194   /**
195    * Creates a new AlignmentAnnotation object.
196    *
197    * @param label DOCUMENT ME!
198    * @param description DOCUMENT ME!
199    * @param annotations DOCUMENT ME!
200    * @param min DOCUMENT ME!
201    * @param max DOCUMENT ME!
202    * @param winLength DOCUMENT ME!
203    */
204   public AlignmentAnnotation(String label, String description,
205                              Annotation[] annotations, float min, float max,
206                              int graphType)
207   {
208     // graphs are not editable
209     editable = graphType==0;
210
211     this.label = label;
212     this.description = description;
213     this.annotations = annotations;
214     graph = graphType;
215     graphMin = min;
216     graphMax = max;
217     validateRangeAndDisplay();
218   }
219   /**
220    * checks graphMin and graphMax,
221    * secondary structure symbols,
222    * sets graphType appropriately,
223    * sets null labels to the empty string
224    * if appropriate.
225    */
226   private void validateRangeAndDisplay() {
227
228     if (annotations==null)
229     {
230       visible=false; // try to prevent renderer from displaying.
231       return; // this is a non-annotation row annotation - ie a sequence score.
232     }
233
234     int graphType = graph;
235     float min = graphMin;
236     float max = graphMax;
237     boolean drawValues = true;
238
239     if (min == max)
240     {
241       min = 999999999;
242       for (int i = 0; i < annotations.length; i++)
243       {
244         if (annotations[i] == null)
245         {
246           continue;
247         }
248
249         if (drawValues
250             && annotations[i].displayCharacter!=null
251             && annotations[i].displayCharacter.length() > 1)
252         {
253           drawValues = false;
254         }
255
256         if (annotations[i].value > max)
257         {
258           max = annotations[i].value;
259         }
260
261         if (annotations[i].value < min)
262         {
263           min = annotations[i].value;
264         }
265       }
266     }
267
268     graphMin = min;
269     graphMax = max;
270
271     areLabelsSecondaryStructure();
272
273     if (!drawValues && graphType != NO_GRAPH)
274     {
275       for (int i = 0; i < annotations.length; i++)
276       {
277         if (annotations[i] != null)
278         {
279           annotations[i].displayCharacter = "";
280         }
281       }
282     }
283   }
284
285   /**
286    * Copy constructor
287    * creates a new independent annotation row with the same associated sequenceRef
288    * @param annotation
289    */
290   public AlignmentAnnotation(AlignmentAnnotation annotation)
291   {
292     this.label = new String(annotation.label);
293     if (annotation.description != null)
294       this.description = new String(annotation.description);
295     this.graphMin = annotation.graphMin;
296     this.graphMax = annotation.graphMax;
297     this.graph = annotation.graph;
298     this.graphHeight = annotation.graphHeight;
299     this.graphGroup = annotation.graphGroup;
300     this.editable = annotation.editable;
301     this.autoCalculated = annotation.autoCalculated;
302     this.hasIcons = annotation.hasIcons;
303     this.hasText = annotation.hasText;
304     this.height = annotation.height;
305     this.label = annotation.label;
306     this.padGaps = annotation.padGaps;
307     this.visible = annotation.visible;
308     if (this.hasScore = annotation.hasScore)
309     {
310       this.score = annotation.score;
311     }
312     if (threshold!=null) {
313       threshold = new GraphLine(annotation.threshold);
314     }
315     if (annotation.annotations!=null) {
316       Annotation[] ann = annotation.annotations;
317       this.annotations = new Annotation[ann.length];
318       for (int i=0; i<ann.length; i++) {
319         annotations[i] = new Annotation(ann[i]);
320       };
321       if (annotation.sequenceRef!=null) {
322         this.sequenceRef = annotation.sequenceRef;
323         if (annotation.sequenceMapping!=null)
324         {
325           Integer p=null;
326           sequenceMapping = new Hashtable();
327           Enumeration pos=annotation.sequenceMapping.keys();
328           while (pos.hasMoreElements()) {
329             // could optimise this!
330             p = (Integer) pos.nextElement();
331             Annotation a = (Annotation) annotation.sequenceMapping.get(p);
332             if (a==null)
333             {
334               continue;
335             }
336             for (int i=0; i<ann.length; i++)
337             {
338               if (ann[i]==a)
339               {
340                 sequenceMapping.put(p, annotations[i]);
341               }
342             }
343           }
344         } else {
345           this.sequenceMapping = null;
346         }
347       }
348     }
349     validateRangeAndDisplay(); // construct hashcodes, etc.
350   }
351
352   /**
353    * clip the annotation to the columns given by startRes and endRes (inclusive)
354    * and prune any existing sequenceMapping to just those columns.
355    * @param startRes
356    * @param endRes
357    */
358   public void restrict(int startRes, int endRes)
359   {
360     if (startRes<0)
361       startRes=0;
362     if (startRes>=annotations.length)
363       startRes = annotations.length-1;
364     if (endRes>=annotations.length)
365       endRes = annotations.length-1;
366     if (annotations==null)
367       return;
368     Annotation[] temp = new Annotation[endRes-startRes+1];
369     if (startRes<annotations.length)
370     {
371       System.arraycopy(annotations, startRes, temp, 0, endRes-startRes+1);
372     }
373     if (sequenceRef!=null) {
374       // Clip the mapping, if it exists.
375       int spos = sequenceRef.findPosition(startRes);
376       int epos = sequenceRef.findPosition(endRes);
377       if (sequenceMapping!=null)
378       {
379         Hashtable newmapping = new Hashtable();
380         Enumeration e = sequenceMapping.keys();
381         while (e.hasMoreElements())
382         {
383           Integer pos = (Integer) e.nextElement();
384           if (pos.intValue()>=spos && pos.intValue()<=epos)
385           {
386             newmapping.put(pos, sequenceMapping.get(pos));
387           }
388         }
389         sequenceMapping.clear();
390         sequenceMapping = newmapping;
391       }
392     }
393     annotations=temp;
394   }
395   /**
396    * set the annotation row to be at least length Annotations
397    * @param length minimum number of columns required in the annotation row
398    * @return false if the annotation row is greater than length
399    */
400   public boolean padAnnotation(int length) {
401     if (annotations==null)
402     {
403       return true; // annotation row is correct - null == not visible and undefined length
404     }
405     if (annotations.length<length)
406     {
407       Annotation[] na = new Annotation[length];
408       System.arraycopy(annotations, 0, na, 0, annotations.length);
409       annotations = na;
410       return true;
411     }
412     return annotations.length>length;
413
414   }
415
416   /**
417    * DOCUMENT ME!
418    *
419    * @return DOCUMENT ME!
420    */
421   public String toString()
422   {
423     StringBuffer buffer = new StringBuffer();
424
425     for (int i = 0; i < annotations.length; i++)
426     {
427       if (annotations[i] != null)
428       {
429         if (graph != 0)
430         {
431           buffer.append(annotations[i].value);
432         }
433         else if (hasIcons)
434         {
435           buffer.append(annotations[i].secondaryStructure);
436         }
437         else
438         {
439           buffer.append(annotations[i].displayCharacter);
440         }
441       }
442
443       buffer.append(", ");
444     }
445
446     if (label.equals("Consensus"))
447     {
448       buffer.append("\n");
449
450       for (int i = 0; i < annotations.length; i++)
451       {
452         if (annotations[i] != null)
453         {
454           buffer.append(annotations[i].description);
455         }
456
457         buffer.append(", ");
458       }
459     }
460
461     return buffer.toString();
462   }
463
464   public void setThreshold(GraphLine line)
465   {
466     threshold = line;
467   }
468
469   public GraphLine getThreshold()
470   {
471     return threshold;
472   }
473
474   /**
475    * Attach the annotation to seqRef, starting from startRes position. If alreadyMapped is true then the indices of the annotation[] array are sequence positions rather than alignment column positions.
476    * @param seqRef
477    * @param startRes
478    * @param alreadyMapped
479    */
480   public void createSequenceMapping(SequenceI seqRef,
481                                     int startRes,
482                                     boolean alreadyMapped)
483   {
484
485     if (seqRef == null)
486     {
487       return;
488     }
489     sequenceRef=seqRef;
490     if (annotations==null)
491     {
492       return;
493     }
494     sequenceMapping = new java.util.Hashtable();
495
496     int seqPos;
497
498     for (int i = 0; i < annotations.length; i++)
499     {
500       if (annotations[i] != null)
501       {
502         if (alreadyMapped)
503         {
504           seqPos = seqRef.findPosition(i);
505         }
506         else
507         {
508           seqPos = i + startRes;
509         }
510
511         sequenceMapping.put(new Integer(seqPos), annotations[i]);
512       }
513     }
514
515   }
516
517   public void adjustForAlignment()
518   {
519     if (sequenceRef==null)
520       return;
521
522     if (annotations==null)
523     {
524       return;
525     }
526
527     int a = 0, aSize = sequenceRef.getLength();
528
529     if (aSize == 0)
530     {
531       //Its been deleted
532       return;
533     }
534
535     int position;
536     Annotation[] temp = new Annotation[aSize];
537     Integer index;
538
539     for (a = sequenceRef.getStart(); a <= sequenceRef.getEnd(); a++)
540     {
541       index = new Integer(a);
542       if (sequenceMapping.containsKey(index))
543       {
544         position = sequenceRef.findIndex(a) - 1;
545
546         temp[position] = (Annotation) sequenceMapping.get(index);
547       }
548     }
549
550     annotations = temp;
551   }
552   /**
553    * remove any null entries in annotation row and return the
554    * number of non-null annotation elements.
555    * @return
556    */
557   private int compactAnnotationArray() {
558     int j=0;
559     for (int i=0;i<annotations.length; i++) {
560       if (annotations[i]!=null && j!=i) {
561         annotations[j++] = annotations[i];
562       }
563     }
564     Annotation[] ann = annotations;
565     annotations = new Annotation[j];
566     System.arraycopy(ann, 0, annotations, 0, j);
567     ann = null;
568     return j;
569   }
570
571   /**
572    * Associate this annotion with the aligned residues of a particular sequence.
573    * sequenceMapping will be updated in the following way:
574    *   null sequenceI - existing mapping will be discarded but annotations left in mapped positions.
575    *   valid sequenceI not equal to current sequenceRef: mapping is discarded and rebuilt assuming 1:1 correspondence
576    *   TODO: overload with parameter to specify correspondence between current and new sequenceRef
577    * @param sequenceI
578    */
579   public void setSequenceRef(SequenceI sequenceI)
580   {
581     if (sequenceI != null)
582     {
583       if (sequenceRef != null)
584       {
585         if (sequenceRef != sequenceI && !sequenceRef.equals(sequenceI) && sequenceRef.getDatasetSequence()!=sequenceI.getDatasetSequence())
586         {
587           // if sequenceRef isn't intersecting with sequenceI
588           // throw away old mapping and reconstruct.
589           sequenceRef = null;
590           if (sequenceMapping != null)
591           {
592             sequenceMapping = null;
593             // compactAnnotationArray();
594           }
595           createSequenceMapping(sequenceI, 1, true);
596           adjustForAlignment();
597         }
598         else
599         {
600           // Mapping carried over
601           sequenceRef = sequenceI;
602         }
603       }
604       else
605       {
606         // No mapping exists
607         createSequenceMapping(sequenceI, 1, true);
608         adjustForAlignment();
609       }
610     }
611     else
612     {
613       // throw away the mapping without compacting.
614       sequenceMapping = null;
615       sequenceRef = null;
616     }
617   }
618
619   /**
620    * @return the score
621    */
622   public double getScore()
623   {
624     return score;
625   }
626
627   /**
628    * @param score the score to set
629    */
630   public void setScore(double score)
631   {
632     hasScore=true;
633     this.score = score;
634   }
635   /**
636    *
637    * @return true if annotation has an associated score
638    */
639   public boolean hasScore()
640   {
641     return hasScore || !Double.isNaN(score);
642   }
643   /**
644    * Score only annotation
645    * @param label
646    * @param description
647    * @param score
648    */
649   public AlignmentAnnotation(String label, String description, double score)
650   {
651     this(label, description, null);
652     setScore(score);
653   }
654
655   public void setPadGaps(boolean padgaps, char gapchar)
656   {
657     this.padGaps = padgaps;
658     if(padgaps)
659     {
660       hasText = true;
661       for(int i=0; i<annotations.length; i++)
662       {
663         if(annotations[i]==null)
664           annotations[i] = new Annotation(String.valueOf(gapchar),null,' ',0f);
665         else if(annotations[i].displayCharacter==null ||annotations[i].displayCharacter.equals(" "))
666           annotations[i].displayCharacter=String.valueOf(gapchar);
667       }
668     }
669   }
670 }