JAL-2816 exclude filtered / thresholded out features when finding
[jalview.git] / src / jalview / schemes / FeatureColour.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.api.FeatureColourI;
24 import jalview.datamodel.SequenceFeature;
25 import jalview.util.ColorUtils;
26 import jalview.util.Format;
27
28 import java.awt.Color;
29 import java.util.StringTokenizer;
30
31 /**
32  * A class that represents a colour scheme for a feature type. Options supported
33  * are currently
34  * <ul>
35  * <li>a simple colour e.g. Red</li>
36  * <li>colour by label - a colour is generated from the feature description</li>
37  * <li>graduated colour by feature score</li>
38  * <ul>
39  * <li>minimum and maximum score range must be provided</li>
40  * <li>minimum and maximum value colours should be specified</li>
41  * <li>a colour for 'no value' may optionally be provided</li>
42  * <li>colours for intermediate scores are interpolated RGB values</li>
43  * <li>there is an optional threshold above/below which to colour values</li>
44  * <li>the range may be the full value range, or may be limited by the threshold
45  * value</li>
46  * </ul>
47  * <li>colour by (text) value of a named attribute</li> <li>graduated colour by
48  * (numeric) value of a named attribute</li> </ul>
49  */
50 public class FeatureColour implements FeatureColourI
51 {
52   static final Color DEFAULT_NO_COLOUR = null;
53
54   private static final String BAR = "|";
55
56   final private Color colour;
57
58   final private Color minColour;
59
60   final private Color maxColour;
61
62   /*
63    * colour to use for colour by attribute when the 
64    * attribute value is absent
65    */
66   final private Color noColour;
67
68   /*
69    * if true, then colour has a gradient based on a numerical 
70    * range (either feature score, or an attribute value)
71    */
72   private boolean graduatedColour;
73
74   /*
75    * if true, colour values are generated from a text string,
76    * either feature description, or an attribute value
77    */
78   private boolean colourByLabel;
79
80   /*
81    * if not null, the value of [attribute, [sub-attribute] ...]
82    *  is used for colourByLabel or graduatedColour
83    */
84   private String[] attributeName;
85
86   private float threshold;
87
88   private float base;
89
90   private float range;
91
92   private boolean belowThreshold;
93
94   private boolean aboveThreshold;
95
96   private boolean thresholdIsMinOrMax;
97
98   private boolean isHighToLow;
99
100   private boolean autoScaled;
101
102   final private float minRed;
103
104   final private float minGreen;
105
106   final private float minBlue;
107
108   final private float deltaRed;
109
110   final private float deltaGreen;
111
112   final private float deltaBlue;
113
114   /**
115    * Parses a Jalview features file format colour descriptor
116    * [label|][mincolour|maxcolour
117    * |[absolute|]minvalue|maxvalue|thresholdtype|thresholdvalue] Examples:
118    * <ul>
119    * <li>red</li>
120    * <li>a28bbb</li>
121    * <li>25,125,213</li>
122    * <li>label</li>
123    * <li>label|||0.0|0.0|above|12.5</li>
124    * <li>label|||0.0|0.0|below|12.5</li>
125    * <li>red|green|12.0|26.0|none</li>
126    * <li>a28bbb|3eb555|12.0|26.0|above|12.5</li>
127    * <li>a28bbb|3eb555|abso|12.0|26.0|below|12.5</li>
128    * </ul>
129    * 
130    * @param descriptor
131    * @return
132    * @throws IllegalArgumentException
133    *           if not parseable
134    */
135   public static FeatureColour parseJalviewFeatureColour(String descriptor)
136   {
137     StringTokenizer gcol = new StringTokenizer(descriptor, "|", true);
138     float min = Float.MIN_VALUE;
139     float max = Float.MAX_VALUE;
140     boolean labelColour = false;
141
142     String mincol = gcol.nextToken();
143     if (mincol == "|")
144     {
145       throw new IllegalArgumentException(
146               "Expected either 'label' or a colour specification in the line: "
147                       + descriptor);
148     }
149     String maxcol = null;
150     if (mincol.toLowerCase().indexOf("label") == 0)
151     {
152       labelColour = true;
153       mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null);
154       // skip '|'
155       mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null);
156     }
157
158     if (!labelColour && !gcol.hasMoreTokens())
159     {
160       /*
161        * only a simple colour specification - parse it
162        */
163       Color colour = ColorUtils.parseColourString(descriptor);
164       if (colour == null)
165       {
166         throw new IllegalArgumentException(
167                 "Invalid colour descriptor: " + descriptor);
168       }
169       return new FeatureColour(colour);
170     }
171
172     /*
173      * autoScaled == true: colours range over actual score range
174      * autoScaled == false ('abso'): colours range over min/max range
175      */
176     boolean autoScaled = true;
177     String tok = null, minval, maxval;
178     if (mincol != null)
179     {
180       // at least four more tokens
181       if (mincol.equals("|"))
182       {
183         mincol = "";
184       }
185       else
186       {
187         gcol.nextToken(); // skip next '|'
188       }
189       maxcol = gcol.nextToken();
190       if (maxcol.equals("|"))
191       {
192         maxcol = "";
193       }
194       else
195       {
196         gcol.nextToken(); // skip next '|'
197       }
198       tok = gcol.nextToken();
199       gcol.nextToken(); // skip next '|'
200       if (tok.toLowerCase().startsWith("abso"))
201       {
202         minval = gcol.nextToken();
203         gcol.nextToken(); // skip next '|'
204         autoScaled = false;
205       }
206       else
207       {
208         minval = tok;
209       }
210       maxval = gcol.nextToken();
211       if (gcol.hasMoreTokens())
212       {
213         gcol.nextToken(); // skip next '|'
214       }
215       try
216       {
217         if (minval.length() > 0)
218         {
219           min = new Float(minval).floatValue();
220         }
221       } catch (Exception e)
222       {
223         throw new IllegalArgumentException(
224                 "Couldn't parse the minimum value for graduated colour ("
225                         + descriptor + ")");
226       }
227       try
228       {
229         if (maxval.length() > 0)
230         {
231           max = new Float(maxval).floatValue();
232         }
233       } catch (Exception e)
234       {
235         throw new IllegalArgumentException(
236                 "Couldn't parse the maximum value for graduated colour ("
237                         + descriptor + ")");
238       }
239     }
240     else
241     {
242       // add in some dummy min/max colours for the label-only
243       // colourscheme.
244       mincol = "FFFFFF";
245       maxcol = "000000";
246     }
247
248     /*
249      * construct the FeatureColour
250      */
251     FeatureColour featureColour;
252     try
253     {
254       Color minColour = ColorUtils.parseColourString(mincol);
255       Color maxColour = ColorUtils.parseColourString(maxcol);
256       featureColour = new FeatureColour(minColour, maxColour, min, max);
257       featureColour.setColourByLabel(labelColour);
258       featureColour.setAutoScaled(autoScaled);
259       // add in any additional parameters
260       String ttype = null, tval = null;
261       if (gcol.hasMoreTokens())
262       {
263         // threshold type and possibly a threshold value
264         ttype = gcol.nextToken();
265         if (ttype.toLowerCase().startsWith("below"))
266         {
267           featureColour.setBelowThreshold(true);
268         }
269         else if (ttype.toLowerCase().startsWith("above"))
270         {
271           featureColour.setAboveThreshold(true);
272         }
273         else
274         {
275           if (!ttype.toLowerCase().startsWith("no"))
276           {
277             System.err.println(
278                     "Ignoring unrecognised threshold type : " + ttype);
279           }
280         }
281       }
282       if (featureColour.hasThreshold())
283       {
284         try
285         {
286           gcol.nextToken();
287           tval = gcol.nextToken();
288           featureColour.setThreshold(new Float(tval).floatValue());
289         } catch (Exception e)
290         {
291           System.err.println("Couldn't parse threshold value as a float: ("
292                   + tval + ")");
293         }
294       }
295       if (gcol.hasMoreTokens())
296       {
297         System.err.println(
298                 "Ignoring additional tokens in parameters in graduated colour specification\n");
299         while (gcol.hasMoreTokens())
300         {
301           System.err.println("|" + gcol.nextToken());
302         }
303         System.err.println("\n");
304       }
305       return featureColour;
306     } catch (Exception e)
307     {
308       throw new IllegalArgumentException(e.getMessage());
309     }
310   }
311
312   /**
313    * Default constructor
314    */
315   public FeatureColour()
316   {
317     this((Color) null);
318   }
319
320   /**
321    * Constructor given a simple colour
322    * 
323    * @param c
324    */
325   public FeatureColour(Color c)
326   {
327     minColour = Color.WHITE;
328     maxColour = Color.BLACK;
329     noColour = DEFAULT_NO_COLOUR;
330     minRed = 0f;
331     minGreen = 0f;
332     minBlue = 0f;
333     deltaRed = 0f;
334     deltaGreen = 0f;
335     deltaBlue = 0f;
336     colour = c;
337   }
338
339   /**
340    * Constructor given a colour range and a score range, defaulting 'no value
341    * colour' to be the same as minimum colour
342    * 
343    * @param low
344    * @param high
345    * @param min
346    * @param max
347    */
348   public FeatureColour(Color low, Color high, float min, float max)
349   {
350     this(low, high, low, min, max);
351   }
352
353   /**
354    * Copy constructor
355    * 
356    * @param fc
357    */
358   public FeatureColour(FeatureColour fc)
359   {
360     graduatedColour = fc.graduatedColour;
361     colour = fc.colour;
362     minColour = fc.minColour;
363     maxColour = fc.maxColour;
364     noColour = fc.noColour;
365     minRed = fc.minRed;
366     minGreen = fc.minGreen;
367     minBlue = fc.minBlue;
368     deltaRed = fc.deltaRed;
369     deltaGreen = fc.deltaGreen;
370     deltaBlue = fc.deltaBlue;
371     base = fc.base;
372     range = fc.range;
373     isHighToLow = fc.isHighToLow;
374     attributeName = fc.attributeName;
375     setAboveThreshold(fc.isAboveThreshold());
376     setBelowThreshold(fc.isBelowThreshold());
377     setThreshold(fc.getThreshold());
378     setAutoScaled(fc.isAutoScaled());
379     setColourByLabel(fc.isColourByLabel());
380   }
381
382   /**
383    * Copy constructor with new min/max ranges
384    * 
385    * @param fc
386    * @param min
387    * @param max
388    */
389   public FeatureColour(FeatureColour fc, float min, float max)
390   {
391     this(fc);
392     updateBounds(min, max);
393   }
394
395   public FeatureColour(Color low, Color high, Color noValueColour,
396           float min, float max)
397   {
398     if (low == null)
399     {
400       low = Color.white;
401     }
402     if (high == null)
403     {
404       high = Color.black;
405     }
406     graduatedColour = true;
407     colour = null;
408     minColour = low;
409     maxColour = high;
410     noColour = noValueColour;
411     threshold = Float.NaN;
412     isHighToLow = min >= max;
413     minRed = low.getRed() / 255f;
414     minGreen = low.getGreen() / 255f;
415     minBlue = low.getBlue() / 255f;
416     deltaRed = (high.getRed() / 255f) - minRed;
417     deltaGreen = (high.getGreen() / 255f) - minGreen;
418     deltaBlue = (high.getBlue() / 255f) - minBlue;
419     if (isHighToLow)
420     {
421       base = max;
422       range = min - max;
423     }
424     else
425     {
426       base = min;
427       range = max - min;
428     }
429   }
430
431   @Override
432   public boolean isGraduatedColour()
433   {
434     return graduatedColour;
435   }
436
437   /**
438    * Sets the 'graduated colour' flag. If true, also sets 'colour by label' to
439    * false.
440    */
441   void setGraduatedColour(boolean b)
442   {
443     graduatedColour = b;
444     if (b)
445     {
446       setColourByLabel(false);
447     }
448   }
449
450   @Override
451   public Color getColour()
452   {
453     return colour;
454   }
455
456   @Override
457   public Color getMinColour()
458   {
459     return minColour;
460   }
461
462   @Override
463   public Color getMaxColour()
464   {
465     return maxColour;
466   }
467
468   @Override
469   public Color getNoColour()
470   {
471     return noColour;
472   }
473
474   @Override
475   public boolean isColourByLabel()
476   {
477     return colourByLabel;
478   }
479
480   /**
481    * Sets the 'colour by label' flag. If true, also sets 'graduated colour' to
482    * false.
483    */
484   @Override
485   public void setColourByLabel(boolean b)
486   {
487     colourByLabel = b;
488     if (b)
489     {
490       setGraduatedColour(false);
491     }
492   }
493
494   @Override
495   public boolean isBelowThreshold()
496   {
497     return belowThreshold;
498   }
499
500   @Override
501   public void setBelowThreshold(boolean b)
502   {
503     belowThreshold = b;
504     if (b)
505     {
506       setAboveThreshold(false);
507     }
508   }
509
510   @Override
511   public boolean isAboveThreshold()
512   {
513     return aboveThreshold;
514   }
515
516   @Override
517   public void setAboveThreshold(boolean b)
518   {
519     aboveThreshold = b;
520     if (b)
521     {
522       setBelowThreshold(false);
523     }
524   }
525
526   @Override
527   public boolean isThresholdMinMax()
528   {
529     return thresholdIsMinOrMax;
530   }
531
532   @Override
533   public void setThresholdMinMax(boolean b)
534   {
535     thresholdIsMinOrMax = b;
536   }
537
538   @Override
539   public float getThreshold()
540   {
541     return threshold;
542   }
543
544   @Override
545   public void setThreshold(float f)
546   {
547     threshold = f;
548   }
549
550   @Override
551   public boolean isAutoScaled()
552   {
553     return autoScaled;
554   }
555
556   @Override
557   public void setAutoScaled(boolean b)
558   {
559     this.autoScaled = b;
560   }
561
562   /**
563    * {@inheritDoc}
564    */
565   @Override
566   public void updateBounds(float min, float max)
567   {
568     if (max < min)
569     {
570       base = max;
571       range = min - max;
572       isHighToLow = true;
573     }
574     else
575     {
576       base = min;
577       range = max - min;
578       isHighToLow = false;
579     }
580   }
581
582   /**
583    * Returns the colour for the given instance of the feature. This may be a
584    * simple colour, a colour generated from the feature description (if
585    * isColourByLabel()), or a colour derived from the feature score (if
586    * isGraduatedColour()).
587    * 
588    * @param feature
589    * @return
590    */
591   @Override
592   public Color getColor(SequenceFeature feature)
593   {
594     if (isColourByLabel())
595     {
596       String label = attributeName == null ? feature.getDescription()
597               : feature.getValueAsString(attributeName);
598       return label == null ? noColour : ColorUtils
599               .createColourFromName(label);
600     }
601
602     if (!isGraduatedColour())
603     {
604       return getColour();
605     }
606
607     /*
608      * graduated colour case, optionally with threshold
609      * may be based on feature score on an attribute value
610      * Float.NaN, or no value, is assigned the 'no value' colour
611      */
612     float scr = feature.getScore();
613     if (attributeName != null)
614     {
615       try
616       {
617         String attVal = feature.getValueAsString(attributeName);
618         scr = Float.valueOf(attVal);
619       } catch (Throwable e)
620       {
621         scr = Float.NaN;
622       }
623     }
624     if (Float.isNaN(scr))
625     {
626       return noColour;
627     }
628
629     if (isAboveThreshold() && scr <= threshold)
630     {
631       return null;
632     }
633
634     if (isBelowThreshold() && scr >= threshold)
635     {
636       return null;
637     }
638     if (range == 0.0)
639     {
640       return getMaxColour();
641     }
642     float scl = (scr - base) / range;
643     if (isHighToLow)
644     {
645       scl = -scl;
646     }
647     if (scl < 0f)
648     {
649       scl = 0f;
650     }
651     if (scl > 1f)
652     {
653       scl = 1f;
654     }
655     return new Color(minRed + scl * deltaRed, minGreen + scl * deltaGreen,
656             minBlue + scl * deltaBlue);
657   }
658
659   /**
660    * Returns the maximum score of the graduated colour range
661    * 
662    * @return
663    */
664   @Override
665   public float getMax()
666   {
667     // regenerate the original values passed in to the constructor
668     return (isHighToLow) ? base : (base + range);
669   }
670
671   /**
672    * Returns the minimum score of the graduated colour range
673    * 
674    * @return
675    */
676   @Override
677   public float getMin()
678   {
679     // regenerate the original value passed in to the constructor
680     return (isHighToLow) ? (base + range) : base;
681   }
682
683   @Override
684   public boolean isSimpleColour()
685   {
686     return (!isColourByLabel() && !isGraduatedColour());
687   }
688
689   @Override
690   public boolean hasThreshold()
691   {
692     return isAboveThreshold() || isBelowThreshold();
693   }
694
695   @Override
696   public String toJalviewFormat(String featureType)
697   {
698     String colourString = null;
699     if (isSimpleColour())
700     {
701       colourString = Format.getHexString(getColour());
702     }
703     else
704     {
705       StringBuilder sb = new StringBuilder(32);
706       if (isColourByLabel())
707       {
708         sb.append("label");
709         if (hasThreshold())
710         {
711           sb.append(BAR).append(BAR).append(BAR);
712         }
713       }
714       if (isGraduatedColour())
715       {
716         sb.append(Format.getHexString(getMinColour())).append(BAR);
717         sb.append(Format.getHexString(getMaxColour())).append(BAR);
718         if (!isAutoScaled())
719         {
720           sb.append("abso").append(BAR);
721         }
722       }
723       if (hasThreshold() || isGraduatedColour())
724       {
725         sb.append(getMin()).append(BAR);
726         sb.append(getMax()).append(BAR);
727         if (isBelowThreshold())
728         {
729           sb.append("below").append(BAR).append(getThreshold());
730         }
731         else if (isAboveThreshold())
732         {
733           sb.append("above").append(BAR).append(getThreshold());
734         }
735         else
736         {
737           sb.append("none");
738         }
739       }
740       colourString = sb.toString();
741     }
742     return String.format("%s\t%s", featureType, colourString);
743   }
744
745   @Override
746   public boolean isColourByAttribute()
747   {
748     return attributeName != null;
749   }
750
751   @Override
752   public String[] getAttributeName()
753   {
754     return attributeName;
755   }
756
757   @Override
758   public void setAttributeName(String... name)
759   {
760     attributeName = name;
761   }
762
763 }