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