2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
21 package jalview.schemes;
23 import java.util.Locale;
25 import jalview.api.FeatureColourI;
26 import jalview.datamodel.SequenceFeature;
27 import jalview.datamodel.features.FeatureMatcher;
28 import jalview.util.ColorUtils;
29 import jalview.util.Format;
30 import jalview.util.MessageManager;
32 import java.awt.Color;
33 import java.util.StringTokenizer;
36 * A class that represents a colour scheme for a feature type. Options supported
39 * <li>a simple colour e.g. Red</li>
40 * <li>colour by label - a colour is generated from the feature description</li>
41 * <li>graduated colour by feature score</li>
43 * <li>minimum and maximum score range must be provided</li>
44 * <li>minimum and maximum value colours should be specified</li>
45 * <li>a colour for 'no value' may optionally be provided</li>
46 * <li>colours for intermediate scores are interpolated RGB values</li>
47 * <li>there is an optional threshold above/below which to colour values</li>
48 * <li>the range may be the full value range, or may be limited by the threshold
51 * <li>colour by (text) value of a named attribute</li> <li>graduated colour by
52 * (numeric) value of a named attribute</li> </ul>
54 public class FeatureColour implements FeatureColourI
56 private static final String I18N_LABEL = MessageManager
57 .getString("label.label");
59 private static final String I18N_SCORE = MessageManager
60 .getString("label.score");
62 private static final String ABSOLUTE = "abso";
64 private static final String ABOVE = "above";
66 private static final String BELOW = "below";
69 * constants used to read or write a Jalview Features file
71 private static final String LABEL = "label";
73 private static final String SCORE = "score";
75 private static final String ATTRIBUTE = "attribute";
77 private static final String NO_VALUE_MIN = "noValueMin";
79 private static final String NO_VALUE_MAX = "noValueMax";
81 private static final String NO_VALUE_NONE = "noValueNone";
83 static final Color DEFAULT_NO_COLOUR = null;
85 private static final String BAR = "|";
87 final private Color colour;
89 final private Color minColour;
91 final private Color maxColour;
94 * colour to use for colour by attribute when the
95 * attribute value is absent
97 final private Color noColour;
100 * if true, then colour has a gradient based on a numerical
101 * range (either feature score, or an attribute value)
103 private boolean graduatedColour;
106 * if true, colour values are generated from a text string,
107 * either feature description, or an attribute value
109 private boolean colourByLabel;
112 * if not null, the value of [attribute, [sub-attribute] ...]
113 * is used for colourByLabel or graduatedColour
115 private String[] attributeName;
117 private float threshold;
123 private boolean belowThreshold;
125 private boolean aboveThreshold;
127 private boolean isHighToLow;
129 private boolean autoScaled;
131 final private float minRed;
133 final private float minGreen;
135 final private float minBlue;
137 final private float deltaRed;
139 final private float deltaGreen;
141 final private float deltaBlue;
144 * Parses a Jalview features file format colour descriptor
147 * [label|score|[attribute|attributeName]|][mincolour|maxcolour|
148 * [absolute|]minvalue|maxvalue|[noValueOption|]thresholdtype|thresholdvalue]</code>
150 * 'Score' is optional (default) for a graduated colour. An attribute with
151 * sub-attribute should be written as (for example) CSQ:Consequence.
152 * noValueOption is one of <code>noValueMin, noValueMax, noValueNone</code>
153 * with default noValueMin.
159 * <li>25,125,213</li>
161 * <li>attribute|CSQ:PolyPhen</li>
162 * <li>label|||0.0|0.0|above|12.5</li>
163 * <li>label|||0.0|0.0|below|12.5</li>
164 * <li>red|green|12.0|26.0|none</li>
165 * <li>score|red|green|12.0|26.0|none</li>
166 * <li>attribute|AF|red|green|12.0|26.0|none</li>
167 * <li>attribute|AF|red|green|noValueNone|12.0|26.0|none</li>
168 * <li>a28bbb|3eb555|12.0|26.0|above|12.5</li>
169 * <li>a28bbb|3eb555|abso|12.0|26.0|below|12.5</li>
174 * @throws IllegalArgumentException
177 public static FeatureColourI parseJalviewFeatureColour(String descriptor)
179 StringTokenizer gcol = new StringTokenizer(descriptor, BAR, true);
180 float min = Float.MIN_VALUE;
181 float max = Float.MAX_VALUE;
182 boolean byLabel = false;
183 boolean byAttribute = false;
184 String attName = null;
185 String mincol = null;
186 String maxcol = null;
189 * first token should be 'label', or 'score', or an
190 * attribute name, or simple colour, or minimum colour
192 String nextToken = gcol.nextToken();
193 if (nextToken == BAR)
195 throw new IllegalArgumentException(
196 "Expected either 'label' or a colour specification in the line: "
199 if (nextToken.toLowerCase(Locale.ROOT).startsWith(LABEL))
202 // get the token after the next delimiter:
203 mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null);
204 mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null);
206 else if (nextToken.toLowerCase(Locale.ROOT).startsWith(SCORE))
208 mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null);
209 mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null);
211 else if (nextToken.toLowerCase(Locale.ROOT).startsWith(ATTRIBUTE))
214 attName = (gcol.hasMoreTokens() ? gcol.nextToken() : null);
215 attName = (gcol.hasMoreTokens() ? gcol.nextToken() : null);
216 mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null);
217 mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null);
225 * if only one token, it can validly be label, attributeName,
226 * or a plain colour value
228 if (!gcol.hasMoreTokens())
230 if (byLabel || byAttribute)
232 FeatureColourI fc = new FeatureColour();
233 fc.setColourByLabel(true);
237 FeatureMatcher.fromAttributeDisplayName(attName));
242 Color colour = ColorUtils.parseColourString(descriptor);
245 throw new IllegalArgumentException(
246 "Invalid colour descriptor: " + descriptor);
248 return new FeatureColour(colour);
252 * continue parsing for min/max/no colour (if graduated)
253 * and for threshold (colour by text or graduated)
257 * autoScaled == true: colours range over actual score range
258 * autoScaled == false ('abso'): colours range over min/max range
260 boolean autoScaled = true;
261 String tok = null, minval, maxval;
262 String noValueColour = NO_VALUE_MIN;
266 // at least four more tokens
267 if (mincol.equals(BAR))
273 gcol.nextToken(); // skip next '|'
275 maxcol = gcol.nextToken();
276 if (maxcol.equals(BAR))
282 gcol.nextToken(); // skip next '|'
284 tok = gcol.nextToken();
287 * check for specifier for colour for no attribute value
288 * (new in 2.11, defaults to minColour if not specified)
290 if (tok.equalsIgnoreCase(NO_VALUE_MIN))
292 tok = gcol.nextToken();
293 tok = gcol.nextToken();
295 else if (tok.equalsIgnoreCase(NO_VALUE_MAX))
297 noValueColour = NO_VALUE_MAX;
298 tok = gcol.nextToken();
299 tok = gcol.nextToken();
301 else if (tok.equalsIgnoreCase(NO_VALUE_NONE))
303 noValueColour = NO_VALUE_NONE;
304 tok = gcol.nextToken();
305 tok = gcol.nextToken();
308 gcol.nextToken(); // skip next '|'
309 if (tok.toLowerCase(Locale.ROOT).startsWith(ABSOLUTE))
311 minval = gcol.nextToken();
312 gcol.nextToken(); // skip next '|'
319 maxval = gcol.nextToken();
320 if (gcol.hasMoreTokens())
322 gcol.nextToken(); // skip next '|'
326 if (minval.length() > 0)
328 min = Float.valueOf(minval).floatValue();
330 } catch (Exception e)
332 throw new IllegalArgumentException(
333 "Couldn't parse the minimum value for graduated colour ('"
338 if (maxval.length() > 0)
340 max = Float.valueOf(maxval).floatValue();
342 } catch (Exception e)
344 throw new IllegalArgumentException(
345 "Couldn't parse the maximum value for graduated colour ("
352 * dummy min/max colours for colour by text
353 * (label or attribute value)
361 * construct the FeatureColour!
363 FeatureColour featureColour;
366 Color minColour = ColorUtils.parseColourString(mincol);
367 Color maxColour = ColorUtils.parseColourString(maxcol);
368 Color noColour = noValueColour.equals(NO_VALUE_MAX) ? maxColour
369 : (noValueColour.equals(NO_VALUE_NONE) ? null : minColour);
370 featureColour = new FeatureColour(maxColour, minColour, maxColour,
372 featureColour.setColourByLabel(minColour == null);
373 featureColour.setAutoScaled(autoScaled);
376 featureColour.setAttributeName(
377 FeatureMatcher.fromAttributeDisplayName(attName));
379 // add in any additional parameters
380 String ttype = null, tval = null;
381 if (gcol.hasMoreTokens())
383 // threshold type and possibly a threshold value
384 ttype = gcol.nextToken();
385 if (ttype.toLowerCase(Locale.ROOT).startsWith(BELOW))
387 featureColour.setBelowThreshold(true);
389 else if (ttype.toLowerCase(Locale.ROOT).startsWith(ABOVE))
391 featureColour.setAboveThreshold(true);
395 if (!ttype.toLowerCase(Locale.ROOT).startsWith("no"))
398 "Ignoring unrecognised threshold type : " + ttype);
402 if (featureColour.hasThreshold())
407 tval = gcol.nextToken();
408 featureColour.setThreshold(Float.valueOf(tval).floatValue());
409 } catch (Exception e)
411 System.err.println("Couldn't parse threshold value as a float: ("
415 if (gcol.hasMoreTokens())
418 "Ignoring additional tokens in parameters in graduated colour specification\n");
419 while (gcol.hasMoreTokens())
421 System.err.println(BAR + gcol.nextToken());
423 System.err.println("\n");
425 return featureColour;
426 } catch (Exception e)
428 throw new IllegalArgumentException(e.getMessage());
433 * Default constructor
435 public FeatureColour()
441 * Constructor given a simple colour. This also 'primes' a graduated colour
442 * range, where the maximum colour is the given simple colour, and the minimum
443 * colour a paler shade of it. This is for convenience when switching from a
444 * simple colour to a graduated colour scheme.
448 public FeatureColour(Color c)
451 * set max colour to the simple colour, min colour to a paler shade of it
453 this(c, c == null ? Color.white : ColorUtils.bleachColour(c, 0.9f),
454 c == null ? Color.black : c, DEFAULT_NO_COLOUR, 0, 0);
457 * but enforce simple colour for now!
459 setGraduatedColour(false);
467 public FeatureColour(FeatureColour fc)
469 graduatedColour = fc.graduatedColour;
471 minColour = fc.minColour;
472 maxColour = fc.maxColour;
473 noColour = fc.noColour;
475 minGreen = fc.minGreen;
476 minBlue = fc.minBlue;
477 deltaRed = fc.deltaRed;
478 deltaGreen = fc.deltaGreen;
479 deltaBlue = fc.deltaBlue;
482 isHighToLow = fc.isHighToLow;
483 attributeName = fc.attributeName;
484 setAboveThreshold(fc.isAboveThreshold());
485 setBelowThreshold(fc.isBelowThreshold());
486 setThreshold(fc.getThreshold());
487 setAutoScaled(fc.isAutoScaled());
488 setColourByLabel(fc.isColourByLabel());
492 * Constructor that sets both simple and graduated colour values. This allows
493 * alternative colour schemes to be 'preserved' while switching between them
494 * to explore their effects on the visualisation.
496 * This sets the colour scheme to 'graduated' by default. Override this if
497 * wanted by calling <code>setGraduatedColour(false)</code> for a simple
498 * colour, or <code>setColourByLabel(true)</code> for colour by label.
503 * @param noValueColour
507 public FeatureColour(Color myColour, Color low, Color high,
508 Color noValueColour, float min, float max)
521 setGraduatedColour(true);
522 noColour = noValueColour;
523 threshold = Float.NaN;
524 isHighToLow = min >= max;
525 minRed = low.getRed() / 255f;
526 minGreen = low.getGreen() / 255f;
527 minBlue = low.getBlue() / 255f;
528 deltaRed = (high.getRed() / 255f) - minRed;
529 deltaGreen = (high.getGreen() / 255f) - minGreen;
530 deltaBlue = (high.getBlue() / 255f) - minBlue;
544 public boolean isGraduatedColour()
546 return graduatedColour;
550 * Sets the 'graduated colour' flag. If true, also sets 'colour by label' to
553 public void setGraduatedColour(boolean b)
558 setColourByLabel(false);
563 public Color getColour()
569 public Color getMinColour()
575 public Color getMaxColour()
581 public Color getNoColour()
587 public boolean isColourByLabel()
589 return colourByLabel;
593 * Sets the 'colour by label' flag. If true, also sets 'graduated colour' to
597 public void setColourByLabel(boolean b)
602 setGraduatedColour(false);
607 public boolean isBelowThreshold()
609 return belowThreshold;
613 public void setBelowThreshold(boolean b)
618 setAboveThreshold(false);
623 public boolean isAboveThreshold()
625 return aboveThreshold;
629 public void setAboveThreshold(boolean b)
634 setBelowThreshold(false);
639 public float getThreshold()
645 public void setThreshold(float f)
651 public boolean isAutoScaled()
657 public void setAutoScaled(boolean b)
666 public void updateBounds(float min, float max)
683 * Returns the colour for the given instance of the feature. This may be a
684 * simple colour, a colour generated from the feature description or other
685 * attribute (if isColourByLabel()), or a colour derived from the feature
686 * score or other attribute (if isGraduatedColour()).
688 * Answers null if feature score (or attribute) value lies outside a
689 * configured threshold.
695 public Color getColor(SequenceFeature feature)
697 if (isColourByLabel())
699 String label = attributeName == null ? feature.getDescription()
700 : feature.getValueAsString(attributeName);
701 return label == null ? noColour : ColorUtils
702 .createColourFromName(label);
705 if (!isGraduatedColour())
711 * graduated colour case, optionally with threshold
712 * may be based on feature score on an attribute value
713 * Float.NaN, or no value, is assigned the 'no value' colour
715 float scr = feature.getScore();
716 if (attributeName != null)
720 String attVal = feature.getValueAsString(attributeName);
721 scr = Float.valueOf(attVal);
722 } catch (Throwable e)
727 if (Float.isNaN(scr))
732 if (isAboveThreshold() && scr <= threshold)
737 if (isBelowThreshold() && scr >= threshold)
743 return getMaxColour();
745 float scl = (scr - base) / range;
758 return new Color(minRed + scl * deltaRed, minGreen + scl * deltaGreen,
759 minBlue + scl * deltaBlue);
763 * Returns the maximum score of the graduated colour range
768 public float getMax()
770 // regenerate the original values passed in to the constructor
771 return (isHighToLow) ? base : (base + range);
775 * Returns the minimum score of the graduated colour range
780 public float getMin()
782 // regenerate the original value passed in to the constructor
783 return (isHighToLow) ? (base + range) : base;
787 public boolean isSimpleColour()
789 return (!isColourByLabel() && !isGraduatedColour());
793 public boolean hasThreshold()
795 return isAboveThreshold() || isBelowThreshold();
799 public String toJalviewFormat(String featureType)
801 String colourString = null;
802 if (isSimpleColour())
804 colourString = Format.getHexString(getColour());
808 StringBuilder sb = new StringBuilder(32);
809 if (isColourByAttribute())
811 sb.append(ATTRIBUTE).append(BAR);
813 FeatureMatcher.toAttributeDisplayName(getAttributeName()));
815 else if (isColourByLabel())
823 if (isGraduatedColour())
825 sb.append(BAR).append(Format.getHexString(getMinColour()))
827 sb.append(Format.getHexString(getMaxColour())).append(BAR);
830 * 'no value' colour should be null, min or max colour;
831 * if none of these, coerce to minColour
833 String noValue = NO_VALUE_MIN;
834 if (maxColour.equals(noColour))
836 noValue = NO_VALUE_MAX;
838 if (noColour == null)
840 noValue = NO_VALUE_NONE;
842 sb.append(noValue).append(BAR);
845 sb.append(ABSOLUTE).append(BAR);
851 * colour by text with score threshold: empty fields for
852 * minColour and maxColour (not used)
856 sb.append(BAR).append(BAR).append(BAR);
859 if (hasThreshold() || isGraduatedColour())
861 sb.append(getMin()).append(BAR);
862 sb.append(getMax()).append(BAR);
863 if (isBelowThreshold())
865 sb.append(BELOW).append(BAR).append(getThreshold());
867 else if (isAboveThreshold())
869 sb.append(ABOVE).append(BAR).append(getThreshold());
876 colourString = sb.toString();
878 return String.format("%s\t%s", featureType, colourString);
882 public boolean isColourByAttribute()
884 return attributeName != null;
888 public String[] getAttributeName()
890 return attributeName;
894 public void setAttributeName(String... name)
896 attributeName = name;
900 public boolean isOutwithThreshold(SequenceFeature feature)
902 if (!isGraduatedColour())
906 float scr = feature.getScore();
907 if (attributeName != null)
911 String attVal = feature.getValueAsString(attributeName);
912 scr = Float.valueOf(attVal);
913 } catch (Throwable e)
918 if (Float.isNaN(scr))
923 return ((isAboveThreshold() && scr <= threshold)
924 || (isBelowThreshold() && scr >= threshold));
928 public String getDescription()
930 if (isSimpleColour())
932 return "r=" + colour.getRed() + ",g=" + colour.getGreen() + ",b="
935 StringBuilder tt = new StringBuilder();
938 if (getAttributeName() != null)
940 by = FeatureMatcher.toAttributeDisplayName(getAttributeName());
942 else if (isColourByLabel())
950 tt.append(MessageManager.formatMessage("action.by_title_param", by));
953 * add threshold if any
955 if (isAboveThreshold() || isBelowThreshold())
958 if (isColourByLabel())
961 * Jalview features file supports the combination of
962 * colour by label or attribute text with score threshold
964 tt.append(I18N_SCORE).append(" ");
966 tt.append(isAboveThreshold() ? "> " : "< ");
967 tt.append(getThreshold()).append(")");
970 return tt.toString();