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