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.analysis;
23 import jalview.analysis.scoremodels.ScoreMatrix;
24 import jalview.analysis.scoremodels.ScoreModels;
25 import jalview.datamodel.AlignmentAnnotation;
26 import jalview.datamodel.Annotation;
27 import jalview.datamodel.ResidueCount;
28 import jalview.datamodel.ResidueCount.SymbolCounts;
29 import jalview.datamodel.Sequence;
30 import jalview.datamodel.SequenceI;
31 import jalview.schemes.ResidueProperties;
32 import jalview.util.Comparison;
34 import java.awt.Color;
35 import java.util.List;
37 import java.util.Map.Entry;
38 import java.util.SortedMap;
39 import java.util.TreeMap;
40 import java.util.Vector;
43 * Calculates conservation values for a given set of sequences
45 public class Conservation
48 * need to have a minimum of 3% of sequences with a residue
49 * for it to be included in the conservation calculation
51 private static final int THRESHOLD_PERCENT = 3;
53 private static final int TOUPPERCASE = 'a' - 'A';
55 private static final int GAP_INDEX = -1;
57 SequenceI[] sequences;
64 * a list whose i'th element is an array whose first entry is the checksum
65 * of the i'th sequence, followed by residues encoded to score matrix index
67 Vector<int[]> seqNums;
69 int maxLength = 0; // used by quality calcs
71 boolean seqNumsChanged = false; // updated after any change via calcSeqNum;
74 * a map per column with {property, conservation} where conservation value is
75 * 1 (property is conserved), 0 (absence of property is conserved) or -1
76 * (property is not conserved i.e. column has residues with and without it)
78 Map<String, Integer>[] total;
81 * if true then conservation calculation will map all symbols to canonical aa
82 * numbering rather than consider conservation of that symbol
84 boolean canonicaliseAa = true;
86 private Vector<Double> quality;
88 private double qualityMinimum;
90 private double qualityMaximum;
92 private Sequence consSequence;
95 * percentage of residues in a column to qualify for counting conservation
97 private int threshold;
99 private String name = "";
102 * an array, for each column, of counts of symbols (by score matrix index)
104 private int[][] cons2;
107 * gap counts for each column
109 private int[] cons2GapCounts;
111 private String[] consSymbs;
114 * Constructor using default threshold of 3%
117 * Name of conservation
119 * sequences to be used in calculation
121 * start residue position
123 * end residue position
125 public Conservation(String name, List<SequenceI> sequences, int start,
128 this(name, THRESHOLD_PERCENT, sequences, start, end);
135 * Name of conservation
137 * percentage of sequences at or below which property conservation is
140 * sequences to be used in calculation
142 * start column position
144 * end column position
146 public Conservation(String name, int threshold, List<SequenceI> sequences,
150 this.threshold = threshold;
154 maxLength = end - start + 1; // default width includes bounds of
157 int s, sSize = sequences.size();
158 SequenceI[] sarray = new SequenceI[sSize];
159 this.sequences = sarray;
162 for (s = 0; s < sSize; s++)
164 sarray[s] = sequences.get(s);
165 if (sarray[s].getLength() > maxLength)
167 maxLength = sarray[s].getLength();
170 } catch (ArrayIndexOutOfBoundsException ex)
172 // bail - another thread has modified the sequence array, so the current
173 // calculation is probably invalid.
174 this.sequences = new SequenceI[0];
180 * Translate sequence i into score matrix indices and store it in the i'th
181 * position of the seqNums array.
186 private void calcSeqNum(int i, ScoreMatrix sm)
188 int sSize = sequences.length;
190 if ((i > -1) && (i < sSize))
192 String sq = sequences[i].getSequenceAsString();
194 if (seqNums.size() <= i)
196 seqNums.addElement(new int[sq.length() + 1]);
200 * the first entry in the array is the sequence's hashcode,
201 * following entries are matrix indices of sequence characters
203 if (sq.hashCode() != seqNums.elementAt(i)[0])
207 seqNumsChanged = true;
215 int[] sqnum = new int[len + 1]; // better to always make a new array -
216 // sequence can change its length
217 sqnum[0] = sq.hashCode();
219 for (j = 1; j <= len; j++)
221 // sqnum[j] = ResidueProperties.aaIndex[sq.charAt(j - 1)];
222 char residue = sq.charAt(j - 1);
223 if (Comparison.isGap(residue))
225 sqnum[j] = GAP_INDEX;
229 sqnum[j] = sm.getMatrixIndex(residue);
232 sqnum[j] = GAP_INDEX;
237 seqNums.setElementAt(sqnum, i);
241 System.out.println("SEQUENCE HAS BEEN DELETED!!!");
246 // JBPNote INFO level debug
248 "ERROR: calcSeqNum called with out of range sequence index for Alignment\n");
253 * Calculates the conservation values for given set of sequences
255 public void calculate()
257 int height = sequences.length;
259 total = new Map[maxLength];
261 for (int column = start; column <= end; column++)
263 ResidueCount values = countResidues(column);
266 * percentage count at or below which we ignore residues
268 int thresh = (threshold * height) / 100;
271 * check observed residues in column and record whether each
272 * physico-chemical property is conserved (+1), absence conserved (0),
273 * or not conserved (-1)
274 * Using TreeMap means properties are displayed in alphabetical order
276 SortedMap<String, Integer> resultHash = new TreeMap<>();
277 SymbolCounts symbolCounts = values.getSymbolCounts();
278 char[] symbols = symbolCounts.symbols;
279 int[] counts = symbolCounts.values;
280 for (int j = 0; j < symbols.length; j++)
283 if (counts[j] > thresh)
285 recordConservation(resultHash, String.valueOf(c));
288 if (values.getGapCount() > thresh)
290 recordConservation(resultHash, "-");
293 if (total.length > 0)
295 total[column - start] = resultHash;
301 * Updates the conservation results for an observed residue
304 * a map of {property, conservation} where conservation value is +1
305 * (all residues have the property), 0 (no residue has the property)
306 * or -1 (some do, some don't)
309 protected static void recordConservation(Map<String, Integer> resultMap,
312 res = res.toUpperCase();
313 for (Entry<String, Map<String, Integer>> property : ResidueProperties.propHash
316 String propertyName = property.getKey();
317 Integer residuePropertyValue = property.getValue().get(res);
319 if (!resultMap.containsKey(propertyName))
322 * first time we've seen this residue - note whether it has this property
324 if (residuePropertyValue != null)
326 resultMap.put(propertyName, residuePropertyValue);
331 * unrecognised residue - use default value for property
333 resultMap.put(propertyName, property.getValue().get("-"));
338 Integer currentResult = resultMap.get(propertyName);
339 if (currentResult.intValue() != -1
340 && !currentResult.equals(residuePropertyValue))
343 * property is unconserved - residues seen both with and without it
345 resultMap.put(propertyName, Integer.valueOf(-1));
352 * Counts residues (upper-cased) and gaps in the given column
357 protected ResidueCount countResidues(int column)
359 ResidueCount values = new ResidueCount(false);
361 for (int row = 0; row < sequences.length; row++)
363 if (sequences[row].getLength() > column)
365 char c = sequences[row].getCharAt(column);
368 int index = ResidueProperties.aaIndex[c];
369 c = index > 20 ? '-' : ResidueProperties.aa[index].charAt(0);
375 if (Comparison.isGap(c))
393 * Counts conservation and gaps for a column of the alignment
395 * @return { 1 if fully conserved, else 0, gap count }
397 public int[] countConservationAndGaps(int column)
400 boolean fullyConserved = true;
401 int iSize = sequences.length;
405 return new int[] { 0, 0 };
409 for (int i = 0; i < iSize; i++)
411 if (column >= sequences[i].getLength())
417 char c = sequences[i].getCharAt(column); // gaps do not have upper/lower
420 if (Comparison.isGap((c)))
433 fullyConserved = false;
438 int[] r = new int[] { fullyConserved ? 1 : 0, gapCount };
443 * Returns the upper-cased character if between 'a' and 'z', else the
449 char toUpperCase(char c)
451 if ('a' <= c && c <= 'z')
459 * Calculates the conservation sequence
461 * @param positiveOnly
462 * if true, calculate positive conservation; else calculate both
463 * positive and negative conservation
464 * @param maxPercentageGaps
465 * the percentage of gaps in a column, at or above which no
466 * conservation is asserted
468 public void verdict(boolean positiveOnly, float maxPercentageGaps)
470 // TODO call this at the end of calculate(), should not be a public method
472 StringBuilder consString = new StringBuilder(end);
474 // NOTE THIS SHOULD CHECK IF THE CONSEQUENCE ALREADY
475 // EXISTS AND NOT OVERWRITE WITH '-', BUT THIS CASE
476 // DOES NOT EXIST IN JALVIEW 2.1.2
477 for (int i = 0; i < start; i++)
479 consString.append('-');
481 consSymbs = new String[end - start + 1];
482 for (int i = start; i <= end; i++)
484 int[] gapcons = countConservationAndGaps(i);
485 boolean fullyConserved = gapcons[0] == 1;
486 int totGaps = gapcons[1];
487 float pgaps = (totGaps * 100f) / sequences.length;
489 if (maxPercentageGaps > pgaps)
491 Map<String, Integer> resultHash = total[i - start];
493 StringBuilder positives = new StringBuilder(64);
494 StringBuilder negatives = new StringBuilder(32);
495 for (String type : resultHash.keySet())
497 int result = resultHash.get(type).intValue();
501 * not conserved (present or absent)
509 * positively conserved property (all residues have it)
511 positives.append(positives.length() == 0 ? "" : " ");
512 positives.append(type);
514 if (result == 0 && !positiveOnly)
517 * absense of property is conserved (all residues lack it)
519 negatives.append(negatives.length() == 0 ? "" : " ");
520 negatives.append("!").append(type);
523 if (negatives.length() > 0)
525 positives.append(" ").append(negatives);
527 consSymbs[i - start] = positives.toString();
531 consString.append(count); // Conserved props!=Identity
535 consString.append(fullyConserved ? "*" : "+");
540 consString.append('-');
544 consSequence = new Sequence(name, consString.toString(), start, end);
550 * @return Conservation sequence
552 public SequenceI getConsSequence()
557 // From Alignment.java in jalview118
558 public void findQuality()
560 findQuality(0, maxLength - 1, ScoreModels.getInstance().getBlosum62());
568 private void percentIdentity(ScoreMatrix sm)
570 seqNums = new Vector<>();
571 int i = 0, iSize = sequences.length;
572 // Do we need to calculate this again?
573 for (i = 0; i < iSize; i++)
578 if ((cons2 == null) || seqNumsChanged)
580 // FIXME remove magic number 24 without changing calc
581 // sm.getSize() returns 25 so doesn't quite do it...
582 cons2 = new int[maxLength][24];
583 cons2GapCounts = new int[maxLength];
587 while (j < sequences.length)
589 int[] sqnum = seqNums.elementAt(j);
591 for (i = 1; i < sqnum.length; i++)
593 int index = sqnum[i];
594 if (index == GAP_INDEX)
596 cons2GapCounts[i - 1]++;
600 cons2[i - 1][index]++;
604 // TODO should this start from sqnum.length?
605 for (i = sqnum.length - 1; i < maxLength; i++)
615 * Calculates the quality of the set of sequences over the given inclusive
616 * column range, using the specified substitution score matrix
622 protected void findQuality(int startCol, int endCol,
623 ScoreMatrix scoreMatrix)
625 quality = new Vector<>();
627 double max = -Double.MAX_VALUE;
628 float[][] scores = scoreMatrix.getMatrix();
630 percentIdentity(scoreMatrix);
632 int size = seqNums.size();
633 int[] lengths = new int[size];
635 for (int l = 0; l < size; l++)
637 lengths[l] = seqNums.elementAt(l).length - 1;
640 final int symbolCount = scoreMatrix.getSize();
642 for (int j = startCol; j <= endCol; j++)
646 // First Xr = depends on column only
647 double[] x = new double[symbolCount];
649 for (int ii = 0; ii < symbolCount; ii++)
654 * todo JAL-728 currently assuming last symbol in matrix is * for gap
655 * (which we ignore as counted separately); true for BLOSUM62 but may
656 * not be once alternative matrices are supported
658 for (int i2 = 0; i2 < symbolCount - 1; i2++)
660 x[ii] += (((double) cons2[j][i2] * scores[ii][i2]) + 4D);
662 x[ii] += 4D + cons2GapCounts[j] * scoreMatrix.getMinimumScore();
667 // Now calculate D for each position and sum
668 for (int k = 0; k < size; k++)
671 double[] xx = new double[symbolCount];
672 // sequence character index, or implied gap if sequence too short
673 int seqNum = (j < lengths[k]) ? seqNums.elementAt(k)[j + 1]
676 for (int i = 0; i < symbolCount - 1; i++)
679 if (seqNum == GAP_INDEX)
681 sr += scoreMatrix.getMinimumScore();
685 sr += scores[i][seqNum];
690 tot += (xx[i] * xx[i]);
693 bigtot += Math.sqrt(tot);
696 max = Math.max(max, bigtot);
698 quality.addElement(new Double(bigtot));
701 double newmax = -Double.MAX_VALUE;
703 for (int j = startCol; j <= endCol; j++)
705 double tmp = quality.elementAt(j).doubleValue();
706 // tmp = ((max - tmp) * (size - cons2[j][23])) / size;
707 tmp = ((max - tmp) * (size - cons2GapCounts[j])) / size;
709 // System.out.println(tmp+ " " + j);
710 quality.setElementAt(new Double(tmp), j);
719 qualityMaximum = newmax;
723 * Complete the given consensus and quuality annotation rows. Note: currently
724 * this method will reallocate the given annotation row if it is different to
725 * the calculated width, otherwise will leave its length unchanged.
727 * @param conservation
728 * conservation annotation row
730 * (optional - may be null)
732 * first column for conservation
734 * extent of conservation
736 public void completeAnnotations(AlignmentAnnotation conservation,
737 AlignmentAnnotation quality2, int istart, int alWidth)
739 SequenceI cons = getConsSequence();
742 * colour scale for Conservation and Quality;
747 float maxR = 1.0f - minR;
748 float maxG = 0.9f - minG;
749 float maxB = 0f - minB;
756 if (conservation != null && conservation.annotations != null
757 && conservation.annotations.length != alWidth)
759 conservation.annotations = new Annotation[alWidth];
762 if (quality2 != null)
764 quality2.graphMax = (float) qualityMaximum;
765 if (quality2.annotations != null
766 && quality2.annotations.length != alWidth)
768 quality2.annotations = new Annotation[alWidth];
770 qmin = (float) qualityMinimum;
771 qmax = (float) qualityMaximum;
774 for (int i = istart; i < alWidth; i++)
778 char c = cons.getCharAt(i);
780 if (Character.isDigit(c))
793 if (conservation != null)
795 float vprop = value - min;
797 int consp = i - start;
798 String conssym = (value > 0 && consp > -1
799 && consp < consSymbs.length) ? consSymbs[consp] : "";
800 conservation.annotations[i] = new Annotation(String.valueOf(c),
801 conssym, ' ', value, new Color(minR + (maxR * vprop),
802 minG + (maxG * vprop), minB + (maxB * vprop)));
806 if (quality2 != null)
808 value = quality.elementAt(i).floatValue();
809 float vprop = value - qmin;
811 quality2.annotations[i] = new Annotation(" ", String.valueOf(value),
812 ' ', value, new Color(minR + (maxR * vprop),
813 minG + (maxG * vprop), minB + (maxB * vprop)));
819 * construct and call the calculation methods on a new Conservation object
822 * - name of conservation
825 * first column in calculation window
827 * last column in calculation window
828 * @param positiveOnly
829 * calculate positive (true) or positive and negative (false)
831 * @param maxPercentGaps
832 * percentage of gaps tolerated in column
834 * flag indicating if alignment quality should be calculated
835 * @return Conservation object ready for use in visualization
837 public static Conservation calculateConservation(String name,
838 List<SequenceI> seqs, int start, int end, boolean positiveOnly,
839 int maxPercentGaps, boolean calcQuality)
841 Conservation cons = new Conservation(name, seqs, start, end);
843 cons.verdict(positiveOnly, maxPercentGaps);
854 * Returns the computed tooltip (annotation description) for a given column.
855 * The tip is empty if the conservation score is zero, otherwise holds the
856 * conserved properties (and, optionally, properties whose absence is
862 String getTooltip(int column)
864 SequenceI cons = getConsSequence();
865 char val = column < cons.getLength() ? cons.getCharAt(column) : '-';
866 boolean hasConservation = val != '-' && val != '0';
867 int consp = column - start;
868 String tip = (hasConservation && consp > -1 && consp < consSymbs.length)