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