JAL-3253-applet JAL-3383 Overview
[jalview.git] / src / jalview / renderer / ResidueShader.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.renderer;
22
23 import jalview.analysis.Conservation;
24 import jalview.api.ViewStyleI;
25 import jalview.datamodel.AnnotatedCollectionI;
26 import jalview.datamodel.ProfileI;
27 import jalview.datamodel.ProfilesI;
28 import jalview.datamodel.SequenceCollectionI;
29 import jalview.datamodel.SequenceI;
30 import jalview.schemes.ColourSchemeI;
31 import jalview.util.ColorUtils;
32 import jalview.util.Comparison;
33
34 import java.awt.Color;
35 import java.util.Map;
36
37 /**
38  * A class that computes the colouring of an alignment (or subgroup). Currently
39  * the factors that may influence residue colouring are
40  * <ul>
41  * <li>the colour scheme that provides a colour for each aligned residue</li>
42  * <li>any threshold for colour, based on percentage identity with
43  * consensus</li>
44  * <li>any graduation based on conservation of physico-chemical properties</li>
45  * </ul>
46  * 
47  * @author gmcarstairs
48  *
49  */
50 public class ResidueShader implements ResidueShaderI
51 {
52   private static final int INITIAL_CONSERVATION = 30;
53
54   /*
55    * the colour scheme that gives the colour of each residue
56    * before applying any conservation or PID shading
57    */
58   private ColourSchemeI colourScheme;
59
60   /*
61    * the consensus data for each column
62    */
63   private ProfilesI consensus;
64
65   /*
66    * if true, apply shading of colour by conservation
67    */
68   private boolean conservationColouring;
69
70   /*
71    * the physico-chemical property conservation scores for columns, with values
72    * 0-9, '+' (all properties conserved), '*' (residue fully conserved) or '-' (gap)
73    * (may be null if colour by conservation is not selected)
74    */
75   private char[] conservation;
76
77   /*
78    * minimum percentage identity for colour to be applied;
79    * if above zero, residue must match consensus (or joint consensus)
80    * and column have >= pidThreshold identity with the residue
81    */
82   private int pidThreshold;
83
84   /*
85    * if true, ignore gaps in percentage identity calculation
86    */
87   private boolean ignoreGaps;
88
89   /*
90    * setting of the By Conservation slider
91    */
92   private int conservationIncrement = INITIAL_CONSERVATION;
93
94   public ResidueShader(ColourSchemeI cs)
95   {
96     colourScheme = cs;
97   }
98
99   /**
100    * Default constructor
101    */
102   public ResidueShader()
103   {
104   }
105
106   /**
107    * Constructor given view style settings
108    * 
109    * @param viewStyle
110    */
111   public ResidueShader(ViewStyleI viewStyle)
112   {
113     // TODO remove duplicated storing of conservation / pid thresholds?
114     this();
115     setConservationApplied(viewStyle.isConservationColourSelected());
116     // setThreshold(viewStyle.getThreshold());
117   }
118
119   /**
120    * Copy constructor
121    */
122   public ResidueShader(ResidueShader rs)
123   {
124     this.colourScheme = rs.colourScheme;
125     this.consensus = rs.consensus;
126     this.conservation = rs.conservation;
127     this.conservationColouring = rs.conservationColouring;
128     this.conservationIncrement = rs.conservationIncrement;
129     this.ignoreGaps = rs.ignoreGaps;
130     this.pidThreshold = rs.pidThreshold;
131   }
132
133   /**
134    * @see jalview.renderer.ResidueShaderI#setConsensus(jalview.datamodel.ProfilesI)
135    */
136   @Override
137   public void setConsensus(ProfilesI cons)
138   {
139     consensus = cons;
140   }
141
142   /**
143    * @see jalview.renderer.ResidueShaderI#conservationApplied()
144    */
145   @Override
146   public boolean conservationApplied()
147   {
148     return conservationColouring;
149   }
150
151   /**
152    * @see jalview.renderer.ResidueShaderI#setConservationApplied(boolean)
153    */
154   @Override
155   public void setConservationApplied(boolean conservationApplied)
156   {
157     conservationColouring = conservationApplied;
158   }
159
160   /**
161    * @see jalview.renderer.ResidueShaderI#setConservation(jalview.analysis.Conservation)
162    */
163   @Override
164   public void setConservation(Conservation cons)
165   {
166     if (cons == null)
167     {
168       conservationColouring = false;
169       conservation = null;
170     }
171     else
172     {
173       conservationColouring = true;
174       conservation = cons.getConsSequence().getSequenceAsString()
175               .toCharArray();
176     }
177
178   }
179
180   /**
181    * @see jalview.renderer.ResidueShaderI#alignmentChanged(jalview.datamodel.AnnotatedCollectionI,
182    *      java.util.Map)
183    */
184   @Override
185   public void alignmentChanged(AnnotatedCollectionI alignment,
186           Map<SequenceI, SequenceCollectionI> hiddenReps)
187   {
188     if (colourScheme != null)
189     {
190       colourScheme.alignmentChanged(alignment, hiddenReps);
191     }
192   }
193
194   /**
195    * @see jalview.renderer.ResidueShaderI#setThreshold(int, boolean)
196    */
197   @Override
198   public void setThreshold(int consensusThreshold, boolean ignoreGaps)
199   {
200     pidThreshold = consensusThreshold;
201     this.ignoreGaps = ignoreGaps;
202   }
203
204   /**
205    * @see jalview.renderer.ResidueShaderI#setConservationInc(int)
206    */
207   @Override
208   public void setConservationInc(int i)
209   {
210     conservationIncrement = i;
211   }
212
213   /**
214    * @see jalview.renderer.ResidueShaderI#getConservationInc()
215    */
216   @Override
217   public int getConservationInc()
218   {
219     return conservationIncrement;
220   }
221
222   /**
223    * @see jalview.renderer.ResidueShaderI#getThreshold()
224    */
225   @Override
226   public int getThreshold()
227   {
228     return pidThreshold;
229   }
230
231   /**
232    * @see jalview.renderer.ResidueShaderI#findColour(char, int,
233    *      jalview.datamodel.SequenceI)
234    */
235   @Override
236   public Color findColour(char symbol, int position, SequenceI seq)
237   {
238     if (colourScheme == null)
239     {
240       return Color.white; // Colour is 'None'
241     }
242
243     /*
244      * get 'base' colour
245      */
246     ProfileI profile = consensus == null ? null : consensus.get(position);
247     String modalResidue = profile == null ? null
248             : profile.getModalResidue();
249     float pid = profile == null ? 0f
250             : profile.getPercentageIdentity(ignoreGaps);
251     Color colour = colourScheme.findColour(symbol, position, seq,
252             modalResidue, pid);
253
254     /*
255      * apply PID threshold and consensus fading if in force
256      */
257     if (!Comparison.isGap(symbol))
258     {
259       colour = adjustColour(symbol, position, colour);
260     }
261
262     return colour;
263   }
264
265   @Override
266   public int findColourInt(char symbol, int position, SequenceI seq)
267   {
268     if (colourScheme == null)
269     {
270       return -1;// Color.white; // Colour is 'None'
271     }
272
273     /*
274      * get 'base' colour
275      */
276     ProfileI profile = consensus == null ? null : consensus.get(position);
277     String modalResidue = profile == null ? null
278             : profile.getModalResidue();
279     float pid = profile == null ? 0f
280             : profile.getPercentageIdentity(ignoreGaps);
281     int colour = colourScheme
282             .findColour(symbol, position, seq, modalResidue, pid).getRGB();
283
284     /*
285      * apply PID threshold and consensus fading if in force
286      */
287     if (!Comparison.isGap(symbol))
288     {
289       colour = adjustColourInt(symbol, position, colour);
290     }
291
292     return colour;
293   }
294
295   /**
296    * Adjusts colour by applying thresholding or conservation shading, if in
297    * force. That is
298    * <ul>
299    * <li>if there is a threshold set for colouring, and the residue doesn't
300    * match the consensus (or a joint consensus) residue, or the consensus score
301    * is not above the threshold, then the colour is set to white</li>
302    * <li>if conservation colouring is selected, the colour is faded by an amount
303    * depending on the conservation score for the column, and the conservation
304    * colour threshold</li>
305    * </ul>
306    * 
307    * @param symbol
308    * @param column
309    * @param colour
310    * @return
311    */
312   protected Color adjustColour(char symbol, int column, Color colour)
313   {
314     if (!aboveThreshold(symbol, column))
315     {
316       colour = Color.white;
317     }
318
319     if (conservationColouring)
320     {
321       colour = applyConservation(colour, column);
322     }
323     return colour;
324   }
325
326   protected int adjustColourInt(char symbol, int column, int colour)
327   {
328     if (!aboveThreshold(symbol, column))
329     {
330       colour = -1;// Color.white;
331     }
332
333     if (conservationColouring)
334     {
335       colour = applyConservationInt(colour, column);
336     }
337     return colour;
338   }
339
340   /**
341    * Answers true if there is a consensus profile for the specified column, and
342    * the given residue matches the consensus (or joint consensus) residue for
343    * the column, and the percentage identity for the profile is equal to or
344    * greater than the current threshold; else answers false. The percentage
345    * calculation depends on whether or not we are ignoring gapped sequences.
346    * 
347    * @param residue
348    * @param column
349    *          (index into consensus profiles)
350    * 
351    * @return
352    * @see #setThreshold(int, boolean)
353    */
354   protected boolean aboveThreshold(char residue, int column)
355   {
356     if (pidThreshold == 0)
357     {
358       return true;
359     }
360     if ('a' <= residue && residue <= 'z')
361     {
362       // TO UPPERCASE !!!
363       // Faster than toUpperCase
364       residue -= ('a' - 'A');
365     }
366
367     if (consensus == null)
368     {
369       return false;
370     }
371
372     ProfileI profile = consensus.get(column);
373
374     /*
375      * test whether this is the consensus (or joint consensus) residue
376      */
377     if (profile != null
378             && profile.getModalResidue().contains(String.valueOf(residue)))
379     {
380       if (profile.getPercentageIdentity(ignoreGaps) >= pidThreshold)
381       {
382         return true;
383       }
384     }
385
386     return false;
387   }
388
389   /**
390    * Applies a combination of column conservation score, and conservation
391    * percentage slider, to 'bleach' out the residue colours towards white.
392    * <p>
393    * If a column is fully conserved (identical residues, conservation score 11,
394    * shown as *), or all 10 physico-chemical properties are conserved
395    * (conservation score 10, shown as +), then the colour is left unchanged.
396    * <p>
397    * Otherwise a 'bleaching' factor is computed and applied to the colour. This
398    * is designed to fade colours for scores of 0-9 completely to white at slider
399    * positions ranging from 18% - 100% respectively.
400    * 
401    * @param currentColour
402    * @param column
403    * 
404    * @return bleached (or unmodified) colour
405    */
406   protected Color applyConservation(Color currentColour, int column)
407   {
408     if (conservation == null || conservation.length <= column)
409     {
410       return currentColour;
411     }
412     char conservationScore = conservation[column];
413
414     /*
415      * if residues are fully conserved (* or 11), or all properties
416      * are conserved (+ or 10), leave colour unchanged
417      */
418     if (conservationScore == '*' || conservationScore == '+'
419             || conservationScore == (char) 10
420             || conservationScore == (char) 11)
421     {
422       return currentColour;
423     }
424
425     if (Comparison.isGap(conservationScore))
426     {
427       return Color.white;
428     }
429
430     /*
431      * convert score 0-9 to a bleaching factor 1.1 - 0.2
432      */
433     float bleachFactor = (11 - (conservationScore - '0')) / 10f;
434
435     /*
436      * scale this up by 0-5 (percentage slider / 20)
437      * as a result, scores of:         0  1  2  3  4  5  6  7  8  9
438      * fade to white at slider value: 18 20 22 25 29 33 40 50 67 100%
439      */
440     bleachFactor *= (conservationIncrement / 20f);
441
442     return ColorUtils.bleachColour(currentColour, bleachFactor);
443   }
444
445   protected int applyConservationInt(int currentColour, int column)
446   {
447     if (conservation == null || conservation.length <= column)
448     {
449       return currentColour;
450     }
451     char conservationScore = conservation[column];
452
453     /*
454      * if residues are fully conserved (* or 11), or all properties
455      * are conserved (+ or 10), leave colour unchanged
456      */
457     if (conservationScore == '*' || conservationScore == '+'
458             || conservationScore == (char) 10
459             || conservationScore == (char) 11)
460     {
461       return currentColour;
462     }
463
464     if (Comparison.isGap(conservationScore))
465     {
466       return -1;// Color.white;
467     }
468
469     /*
470      * convert score 0-9 to a bleaching factor 1.1 - 0.2
471      */
472     float bleachFactor = (11 - (conservationScore - '0')) / 10f;
473
474     /*
475      * scale this up by 0-5 (percentage slider / 20)
476      * as a result, scores of:         0  1  2  3  4  5  6  7  8  9
477      * fade to white at slider value: 18 20 22 25 29 33 40 50 67 100%
478      */
479     bleachFactor *= (conservationIncrement / 20f);
480
481     return ColorUtils.bleachColourInt(currentColour, bleachFactor);
482   }
483
484   /**
485    * @see jalview.renderer.ResidueShaderI#getColourScheme()
486    */
487   @Override
488   public ColourSchemeI getColourScheme()
489   {
490     return this.colourScheme;
491   }
492
493   /**
494    * @see jalview.renderer.ResidueShaderI#setColourScheme(jalview.schemes.ColourSchemeI)
495    */
496   @Override
497   public void setColourScheme(ColourSchemeI cs)
498   {
499     colourScheme = cs;
500   }
501 }