7133f130fdb2a53f6db8e49bfd0c38d96013fee5
[jalview.git] / src / jalview / schemes / AnnotationColourGradient.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.schemes;
22
23 import jalview.datamodel.AlignmentAnnotation;
24 import jalview.datamodel.AlignmentI;
25 import jalview.datamodel.AnnotatedCollectionI;
26 import jalview.datamodel.Annotation;
27 import jalview.datamodel.GraphLine;
28 import jalview.datamodel.SequenceCollectionI;
29 import jalview.datamodel.SequenceI;
30 import jalview.renderer.AnnotationRenderer;
31 import jalview.util.Comparison;
32
33 import java.awt.Color;
34 import java.util.IdentityHashMap;
35 import java.util.Map;
36
37 public class AnnotationColourGradient extends FollowerColourScheme
38 {
39   /**
40    * map positional scores to transparency rather than colour
41    */
42   boolean positionToTransparency = true;
43
44   /**
45    * compute shade based on annotation row score
46    */
47   boolean perLineScore = true;
48
49   public static final int NO_THRESHOLD = -1;
50
51   public static final int BELOW_THRESHOLD = 0;
52
53   public static final int ABOVE_THRESHOLD = 1;
54
55   private final AlignmentAnnotation annotation;
56
57   private final int aboveAnnotationThreshold;
58
59   public boolean thresholdIsMinMax = false;
60
61   private GraphLine annotationThreshold;
62
63   private int redMin;
64
65   private int greenMin;
66
67   private int blueMin;
68
69   private int redRange;
70
71   private int greenRange;
72
73   private int blueRange;
74
75   private boolean predefinedColours = false;
76
77   private boolean seqAssociated = false;
78
79   /**
80    * false if the scheme was constructed without a minColour and maxColour used
81    * to decide if existing colours should be taken from annotation elements when
82    * they exist
83    */
84   private boolean noGradient = false;
85
86   private IdentityHashMap<SequenceI, AlignmentAnnotation> seqannot = null;
87
88   @Override
89   public ColourSchemeI getInstance(AnnotatedCollectionI sg,
90           Map<SequenceI, SequenceCollectionI> hiddenRepSequences)
91   {
92     AnnotationColourGradient acg = new AnnotationColourGradient(annotation,
93             getColourScheme(), aboveAnnotationThreshold);
94     acg.thresholdIsMinMax = thresholdIsMinMax;
95     acg.annotationThreshold = (annotationThreshold == null) ? null
96             : new GraphLine(annotationThreshold);
97     acg.redMin = redMin;
98     acg.greenMin = greenMin;
99     acg.blueMin = blueMin;
100     acg.redRange = redRange;
101     acg.greenRange = greenRange;
102     acg.blueRange = blueRange;
103     acg.predefinedColours = predefinedColours;
104     acg.seqAssociated = seqAssociated;
105     acg.noGradient = noGradient;
106     acg.positionToTransparency = positionToTransparency;
107     acg.perLineScore = perLineScore;
108     return acg;
109   }
110
111   /**
112    * Creates a new AnnotationColourGradient object.
113    */
114   public AnnotationColourGradient(AlignmentAnnotation annotation,
115           ColourSchemeI originalColour, int aboveThreshold)
116   {
117     if (originalColour instanceof AnnotationColourGradient)
118     {
119       setColourScheme(((AnnotationColourGradient) originalColour)
120               .getColourScheme());
121     }
122     else
123     {
124       setColourScheme(originalColour);
125     }
126
127     this.annotation = annotation;
128
129     aboveAnnotationThreshold = aboveThreshold;
130
131     if (aboveThreshold != NO_THRESHOLD && annotation.threshold != null)
132     {
133       annotationThreshold = annotation.threshold;
134     }
135     // clear values so we don't get weird black bands...
136     redMin = 254;
137     greenMin = 254;
138     blueMin = 254;
139     redRange = 0;
140     greenRange = 0;
141     blueRange = 0;
142
143     noGradient = true;
144     checkLimits();
145   }
146
147   /**
148    * Creates a new AnnotationColourGradient object.
149    */
150   public AnnotationColourGradient(AlignmentAnnotation annotation,
151           Color minColour, Color maxColour, int aboveThreshold)
152   {
153     this.annotation = annotation;
154
155     aboveAnnotationThreshold = aboveThreshold;
156
157     if (aboveThreshold != NO_THRESHOLD && annotation.threshold != null)
158     {
159       annotationThreshold = annotation.threshold;
160     }
161
162     redMin = minColour.getRed();
163     greenMin = minColour.getGreen();
164     blueMin = minColour.getBlue();
165
166     redRange = maxColour.getRed() - redMin;
167     greenRange = maxColour.getGreen() - greenMin;
168     blueRange = maxColour.getBlue() - blueMin;
169
170     noGradient = false;
171     checkLimits();
172   }
173
174   private void checkLimits()
175   {
176     aamax = annotation.graphMax;
177     aamin = annotation.graphMin;
178     if (annotation.isRNA())
179     {
180       // reset colour palette
181       ColourSchemeProperty.resetRnaHelicesShading();
182       ColourSchemeProperty.initRnaHelicesShading(1 + (int) aamax);
183     }
184   }
185
186   @Override
187   public void alignmentChanged(AnnotatedCollectionI alignment,
188           Map<SequenceI, SequenceCollectionI> hiddenReps)
189   {
190     super.alignmentChanged(alignment, hiddenReps);
191
192     if (seqAssociated && annotation.getCalcId() != null)
193     {
194       if (seqannot != null)
195       {
196         seqannot.clear();
197       }
198       else
199       {
200         seqannot = new IdentityHashMap<>();
201       }
202       // resolve the context containing all the annotation for the sequence
203       AnnotatedCollectionI alcontext = alignment instanceof AlignmentI
204               ? alignment
205               : alignment.getContext();
206       boolean f = true, sf = true, rna = false;
207       long plcount = 0, ancount = 0;
208       for (AlignmentAnnotation alan : alcontext.findAnnotation(annotation
209               .getCalcId()))
210       {
211         if (alan.sequenceRef != null
212                 && (alan.label != null && annotation != null
213                         && alan.label.equals(annotation.label)))
214         {
215           ancount++;
216           if (!rna && alan.isRNA())
217           {
218             rna = true;
219           }
220           seqannot.put(alan.sequenceRef, alan);
221           if (f || alan.graphMax > aamax)
222           {
223             aamax = alan.graphMax;
224           }
225           if (f || alan.graphMin < aamin)
226           {
227             aamin = alan.graphMin;
228           }
229           f = false;
230           if (alan.score == alan.score)
231           {
232             if (sf || alan.score < plmin)
233             {
234               plmin = alan.score;
235             }
236             if (sf || alan.score > plmax)
237             {
238               plmax = alan.score;
239             }
240             sf = false;
241             plcount++;
242           }
243         }
244       }
245       if (plcount > 0 && plcount == ancount)
246       {
247         perLineScore = plcount == ancount;
248         aamax=plmax;
249       }
250       else
251       {
252         perLineScore = false;
253       }
254       if (rna)
255       {
256         ColourSchemeProperty.initRnaHelicesShading(1 + (int) aamax);
257       }
258     }
259   }
260
261   /**
262    * positional annotation max/min
263    */
264   double aamin = 0.0, aamax = 0.0;
265
266   /**
267    * per line score max/min
268    */
269   double plmin = Double.NaN, plmax = Double.NaN;
270
271   public AlignmentAnnotation getAnnotation()
272   {
273     return annotation;
274   }
275
276   public int getAboveThreshold()
277   {
278     return aboveAnnotationThreshold;
279   }
280
281   public float getAnnotationThreshold()
282   {
283     if (annotationThreshold == null)
284     {
285       return 0;
286     }
287     else
288     {
289       return annotationThreshold.value;
290     }
291   }
292
293   public Color getMinColour()
294   {
295     return new Color(redMin, greenMin, blueMin);
296   }
297
298   public Color getMaxColour()
299   {
300     return new Color(redMin + redRange, greenMin + greenRange,
301             blueMin + blueRange);
302   }
303
304   /**
305    * DOCUMENT ME!
306    * 
307    * @param n
308    *          DOCUMENT ME!
309    * 
310    * @return DOCUMENT ME!
311    */
312   @Override
313   public Color findColour(char c)
314   {
315     return Color.red;
316   }
317
318   /**
319    * Returns the colour for a given character and position in a sequence
320    * 
321    * @param c
322    *          the residue character
323    * @param j
324    *          the aligned position
325    * @param seq
326    *          the sequence
327    * @return
328    */
329   @Override
330   public Color findColour(char c, int j, SequenceI seq)
331   {
332     /*
333      * locate the annotation we are configured to colour by
334      */
335     AlignmentAnnotation ann = (seqAssociated && seqannot != null
336             ? seqannot.get(seq)
337             : this.annotation);
338
339     /*
340      * if gap or no annotation at position, no colour (White)
341      */
342     if (ann == null || ann.annotations == null
343             || j >= ann.annotations.length || ann.annotations[j] == null
344             || Comparison.isGap(c))
345     {
346       return Color.white;
347     }
348
349     Annotation aj = ann.annotations[j];
350     // 'use original colours' => colourScheme != null
351     // -> look up colour to be used
352     // predefined colours => preconfigured shading
353     // -> only use original colours reference if thresholding enabled &
354     // minmax exists
355     // annotation.hasIcons => null or black colours replaced with glyph
356     // colours
357     // -> reuse original colours if present
358     // -> if thresholding enabled then return colour on non-whitespace glyph
359
360     /*
361      * if threshold applies, and annotation fails the test - no colour (white)
362      */
363     if (annotationThreshold != null)
364     {
365       if ((aboveAnnotationThreshold == ABOVE_THRESHOLD
366               && aj.value < annotationThreshold.value)
367               || (aboveAnnotationThreshold == BELOW_THRESHOLD
368                       && aj.value > annotationThreshold.value))
369       {
370         return Color.white;
371       }
372     }
373
374     /*
375      * If 'use original colours' then return the colour of the annotation
376      * at the aligned position - computed using the background colour scheme
377      */
378     if (predefinedColours && aj.colour != null
379             && !aj.colour.equals(Color.black))
380     {
381       return aj.colour;
382     }
383
384     Color result = Color.white;
385     if (ann.hasIcons && ann.graph == AlignmentAnnotation.NO_GRAPH)
386     {
387       /*
388        * secondary structure symbol colouring
389        */
390       if (aj.secondaryStructure > ' ' && aj.secondaryStructure != '.'
391               && aj.secondaryStructure != '-')
392       {
393         if (getColourScheme() != null)
394         {
395           result = getColourScheme().findColour(c, j, seq, null, 0f);
396         }
397         else
398         {
399           if (ann.isRNA())
400           {
401             result = ColourSchemeProperty.rnaHelices[(int) aj.value];
402           }
403           else
404           {
405             result = ann.annotations[j].secondaryStructure == 'H'
406                     ? AnnotationRenderer.HELIX_COLOUR
407                     : ann.annotations[j].secondaryStructure == 'E'
408                             ? AnnotationRenderer.SHEET_COLOUR
409                             : AnnotationRenderer.STEM_COLOUR;
410           }
411         }
412       }
413       else
414       {
415         return Color.white;
416       }
417     }
418     else if (noGradient)
419     {
420       if (getColourScheme() != null)
421       {
422         result = getColourScheme().findColour(c, j, seq, null, 0f);
423       }
424       else
425       {
426         if (aj.colour != null)
427         {
428           result = aj.colour;
429         }
430       }
431     }
432     else
433     {
434       result = shadeCalculation(ann, j);
435     }
436
437     return result;
438   }
439
440   /**
441    * Returns a graduated colour for the annotation at the given column. If there
442    * is a threshold value, and it is used as the top/bottom of the colour range,
443    * and the value satisfies the threshold condition, then a colour
444    * proportionate to the range from the threshold is calculated. For all other
445    * cases, a colour proportionate to the annotation's min-max range is
446    * calulated. Note that thresholding is _not_ done here (a colour is computed
447    * even if threshold is not passed).
448    * 
449    * @param ann
450    * @param col
451    * @return
452    */
453   Color shadeCalculation(AlignmentAnnotation ann, int col)
454   {
455     float range = 1f;
456     float value = ann.annotations[col].value;
457     if (thresholdIsMinMax && ann.threshold != null
458             && aboveAnnotationThreshold == ABOVE_THRESHOLD
459             && value >= ann.threshold.value)
460     {
461       range = (value - ann.threshold.value)
462               / (ann.graphMax - ann.threshold.value);
463     }
464     else if (thresholdIsMinMax && ann.threshold != null
465             && aboveAnnotationThreshold == BELOW_THRESHOLD
466             && value <= ann.threshold.value)
467     {
468       range = (value - ann.graphMin) / (ann.threshold.value - ann.graphMin);
469     }
470     else
471     {
472       if (ann.graphMax != ann.graphMin)
473       {
474         range = (value - ann.graphMin) / (ann.graphMax - ann.graphMin);
475       }
476       else
477       {
478         range = 0f;
479       }
480     }
481
482     // midtr sets the ceiling for bleaching out the shading
483     int trans = 0, midtr = 239;
484     if (perLineScore)
485     {
486       trans = (int) ((1f - range) * midtr);
487       range = (float) ((ann.score - plmin) / (plmax - aamin));
488     }
489     int dr = (int) (redRange * range + redMin),
490             dg = (int) (greenRange * range + greenMin),
491             db = (int) (blueRange * range + blueMin);
492     if (ann.score == ann.score && positionToTransparency)
493     {
494       return new Color(Math.min(dr + trans, midtr), Math.min(dg
495               + trans, midtr), Math.min(db + trans, midtr));
496     }
497     else
498     {
499       return new Color(dr, dg, db);
500     }
501   }
502
503   public boolean isPredefinedColours()
504   {
505     return predefinedColours;
506   }
507
508   public void setPredefinedColours(boolean predefinedColours)
509   {
510     this.predefinedColours = predefinedColours;
511   }
512
513   public boolean isSeqAssociated()
514   {
515     return seqAssociated;
516   }
517
518   public void setSeqAssociated(boolean sassoc)
519   {
520     seqAssociated = sassoc;
521   }
522
523   public boolean isThresholdIsMinMax()
524   {
525     return thresholdIsMinMax;
526   }
527
528   public void setThresholdIsMinMax(boolean minMax)
529   {
530     this.thresholdIsMinMax = minMax;
531   }
532
533   @Override
534   public String getSchemeName()
535   {
536     return "Annotation";
537   }
538
539   @Override
540   public boolean isSimple()
541   {
542     return false;
543   }
544 }