JAL-1950 update colour gradient variables to new, more verbose names
[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       if (rna)
251       {
252         ColourSchemeProperty.initRnaHelicesShading(1 + (int) aamax);
253       }
254     }
255   }
256
257   /**
258    * positional annotation max/min
259    */
260   double aamin = 0.0, aamax = 0.0;
261
262   /**
263    * per line score max/min
264    */
265   double plmin = Double.NaN, plmax = Double.NaN;
266
267   public AlignmentAnnotation getAnnotation()
268   {
269     return annotation;
270   }
271
272   public int getAboveThreshold()
273   {
274     return aboveAnnotationThreshold;
275   }
276
277   public float getAnnotationThreshold()
278   {
279     if (annotationThreshold == null)
280     {
281       return 0;
282     }
283     else
284     {
285       return annotationThreshold.value;
286     }
287   }
288
289   public Color getMinColour()
290   {
291     return new Color(redMin, greenMin, blueMin);
292   }
293
294   public Color getMaxColour()
295   {
296     return new Color(redMin + redRange, greenMin + greenRange,
297             blueMin + blueRange);
298   }
299
300   /**
301    * DOCUMENT ME!
302    * 
303    * @param n
304    *          DOCUMENT ME!
305    * 
306    * @return DOCUMENT ME!
307    */
308   @Override
309   public Color findColour(char c)
310   {
311     return Color.red;
312   }
313
314   /**
315    * Returns the colour for a given character and position in a sequence
316    * 
317    * @param c
318    *          the residue character
319    * @param j
320    *          the aligned position
321    * @param seq
322    *          the sequence
323    * @return
324    */
325   @Override
326   public Color findColour(char c, int j, SequenceI seq)
327   {
328     /*
329      * locate the annotation we are configured to colour by
330      */
331     AlignmentAnnotation ann = (seqAssociated && seqannot != null
332             ? seqannot.get(seq)
333             : this.annotation);
334
335     /*
336      * if gap or no annotation at position, no colour (White)
337      */
338     if (ann == null || ann.annotations == null
339             || j >= ann.annotations.length || ann.annotations[j] == null
340             || Comparison.isGap(c))
341     {
342       return Color.white;
343     }
344
345     Annotation aj = ann.annotations[j];
346     // 'use original colours' => colourScheme != null
347     // -> look up colour to be used
348     // predefined colours => preconfigured shading
349     // -> only use original colours reference if thresholding enabled &
350     // minmax exists
351     // annotation.hasIcons => null or black colours replaced with glyph
352     // colours
353     // -> reuse original colours if present
354     // -> if thresholding enabled then return colour on non-whitespace glyph
355
356     /*
357      * if threshold applies, and annotation fails the test - no colour (white)
358      */
359     if (annotationThreshold != null)
360     {
361       if ((aboveAnnotationThreshold == ABOVE_THRESHOLD
362               && aj.value < annotationThreshold.value)
363               || (aboveAnnotationThreshold == BELOW_THRESHOLD
364                       && aj.value > annotationThreshold.value))
365       {
366         return Color.white;
367       }
368     }
369
370     /*
371      * If 'use original colours' then return the colour of the annotation
372      * at the aligned position - computed using the background colour scheme
373      */
374     if (predefinedColours && aj.colour != null
375             && !aj.colour.equals(Color.black))
376     {
377       return aj.colour;
378     }
379
380     Color result = Color.white;
381     if (ann.hasIcons && ann.graph == AlignmentAnnotation.NO_GRAPH)
382     {
383       /*
384        * secondary structure symbol colouring
385        */
386       if (aj.secondaryStructure > ' ' && aj.secondaryStructure != '.'
387               && aj.secondaryStructure != '-')
388       {
389         if (getColourScheme() != null)
390         {
391           result = getColourScheme().findColour(c, j, seq, null, 0f);
392         }
393         else
394         {
395           if (ann.isRNA())
396           {
397             result = ColourSchemeProperty.rnaHelices[(int) aj.value];
398           }
399           else
400           {
401             result = ann.annotations[j].secondaryStructure == 'H'
402                     ? AnnotationRenderer.HELIX_COLOUR
403                     : ann.annotations[j].secondaryStructure == 'E'
404                             ? AnnotationRenderer.SHEET_COLOUR
405                             : AnnotationRenderer.STEM_COLOUR;
406           }
407         }
408       }
409       else
410       {
411         return Color.white;
412       }
413     }
414     else if (noGradient)
415     {
416       if (getColourScheme() != null)
417       {
418         result = getColourScheme().findColour(c, j, seq, null, 0f);
419       }
420       else
421       {
422         if (aj.colour != null)
423         {
424           result = aj.colour;
425         }
426       }
427     }
428     else
429     {
430       result = shadeCalculation(ann, j);
431     }
432
433     return result;
434   }
435
436   /**
437    * Returns a graduated colour for the annotation at the given column. If there
438    * is a threshold value, and it is used as the top/bottom of the colour range,
439    * and the value satisfies the threshold condition, then a colour
440    * proportionate to the range from the threshold is calculated. For all other
441    * cases, a colour proportionate to the annotation's min-max range is
442    * calulated. Note that thresholding is _not_ done here (a colour is computed
443    * even if threshold is not passed).
444    * 
445    * @param ann
446    * @param col
447    * @return
448    */
449   Color shadeCalculation(AlignmentAnnotation ann, int col)
450   {
451     float range = 1f;
452     float value = ann.annotations[col].value;
453     if (thresholdIsMinMax && ann.threshold != null
454             && aboveAnnotationThreshold == ABOVE_THRESHOLD
455             && value >= ann.threshold.value)
456     {
457       range = (value - ann.threshold.value)
458               / (ann.graphMax - ann.threshold.value);
459     }
460     else if (thresholdIsMinMax && ann.threshold != null
461             && aboveAnnotationThreshold == BELOW_THRESHOLD
462             && value <= ann.threshold.value)
463     {
464       range = (value - ann.graphMin) / (ann.threshold.value - ann.graphMin);
465     }
466     else
467     {
468       if (ann.graphMax != ann.graphMin)
469       {
470         range = (value - ann.graphMin) / (ann.graphMax - ann.graphMin);
471       }
472       else
473       {
474         range = 0f;
475       }
476     }
477
478     // midtr sets the ceiling for bleaching out the shading
479     int trans = 0, midtr = 239;
480     if (perLineScore)
481     {
482       trans = (int) ((1f - range) * midtr);
483       range = (float) ((annotation.score - plmin) / (plmax - aamin));
484     }
485     int dr = (int) (redRange * range + redMin),
486             dg = (int) (greenRange * range + greenMin),
487             db = (int) (blueRange * range + blueMin);
488     if (annotation.score == annotation.score && positionToTransparency)
489     {
490       return new Color(Math.min(dr + trans, midtr), Math.min(dg
491               + trans, midtr), Math.min(db + trans, midtr));
492     }
493     else
494     {
495       return new Color(dr, dg, db);
496     }
497   }
498
499   public boolean isPredefinedColours()
500   {
501     return predefinedColours;
502   }
503
504   public void setPredefinedColours(boolean predefinedColours)
505   {
506     this.predefinedColours = predefinedColours;
507   }
508
509   public boolean isSeqAssociated()
510   {
511     return seqAssociated;
512   }
513
514   public void setSeqAssociated(boolean sassoc)
515   {
516     seqAssociated = sassoc;
517   }
518
519   public boolean isThresholdIsMinMax()
520   {
521     return thresholdIsMinMax;
522   }
523
524   public void setThresholdIsMinMax(boolean minMax)
525   {
526     this.thresholdIsMinMax = minMax;
527   }
528
529   @Override
530   public String getSchemeName()
531   {
532     return "Annotation";
533   }
534
535   @Override
536   public boolean isSimple()
537   {
538     return false;
539   }
540 }