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,
147 List<SequenceI> sequences, int start, int end)
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 .println("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<String, Integer>();
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 case
419 if (Comparison.isGap((c)))
432 fullyConserved = false;
437 int[] r = new int[] { fullyConserved ? 1 : 0, gapCount };
442 * Returns the upper-cased character if between 'a' and 'z', else the
448 char toUpperCase(char c)
450 if ('a' <= c && c <= 'z')
458 * Calculates the conservation sequence
460 * @param positiveOnly
461 * if true, calculate positive conservation; else calculate both
462 * positive and negative conservation
463 * @param maxPercentageGaps
464 * the percentage of gaps in a column, at or above which no
465 * conservation is asserted
467 public void verdict(boolean positiveOnly, float maxPercentageGaps)
469 // TODO call this at the end of calculate(), should not be a public method
471 StringBuilder consString = new StringBuilder(end);
473 // NOTE THIS SHOULD CHECK IF THE CONSEQUENCE ALREADY
474 // EXISTS AND NOT OVERWRITE WITH '-', BUT THIS CASE
475 // DOES NOT EXIST IN JALVIEW 2.1.2
476 for (int i = 0; i < start; i++)
478 consString.append('-');
480 consSymbs = new String[end - start + 1];
481 for (int i = start; i <= end; i++)
483 int[] gapcons = countConservationAndGaps(i);
484 boolean fullyConserved = gapcons[0] == 1;
485 int totGaps = gapcons[1];
486 float pgaps = (totGaps * 100f) / sequences.length;
488 if (maxPercentageGaps > pgaps)
490 Map<String, Integer> resultHash = total[i - start];
492 StringBuilder positives = new StringBuilder(64);
493 StringBuilder negatives = new StringBuilder(32);
494 for (String type : resultHash.keySet())
496 int result = resultHash.get(type).intValue();
500 * not conserved (present or absent)
508 * positively conserved property (all residues have it)
510 positives.append(positives.length() == 0 ? "" : " ");
511 positives.append(type);
513 if (result == 0 && !positiveOnly)
516 * absense of property is conserved (all residues lack it)
518 negatives.append(negatives.length() == 0 ? "" : " ");
519 negatives.append("!").append(type);
522 if (negatives.length() > 0)
524 positives.append(" ").append(negatives);
526 consSymbs[i - start] = positives.toString();
530 consString.append(count); // Conserved props!=Identity
534 consString.append(fullyConserved ? "*" : "+");
539 consString.append('-');
543 consSequence = new Sequence(name, consString.toString(), start, end);
549 * @return Conservation sequence
551 public SequenceI getConsSequence()
556 // From Alignment.java in jalview118
557 public void findQuality()
559 findQuality(0, maxLength - 1, ScoreModels.getInstance().getBlosum62());
567 private void percentIdentity(ScoreMatrix sm)
569 seqNums = new Vector<int[]>();
570 int i = 0, iSize = sequences.length;
571 // Do we need to calculate this again?
572 for (i = 0; i < iSize; i++)
577 if ((cons2 == null) || seqNumsChanged)
579 // FIXME remove magic number 24 without changing calc
580 // sm.getSize() returns 25 so doesn't quite do it...
581 cons2 = new int[maxLength][24];
582 cons2GapCounts = new int[maxLength];
586 while (j < sequences.length)
588 int[] sqnum = seqNums.elementAt(j);
590 for (i = 1; i < sqnum.length; i++)
592 int index = sqnum[i];
593 if (index == GAP_INDEX)
595 cons2GapCounts[i - 1]++;
599 cons2[i - 1][index]++;
603 // TODO should this start from sqnum.length?
604 for (i = sqnum.length - 1; i < maxLength; i++)
614 * Calculates the quality of the set of sequences over the given inclusive
615 * column range, using the specified substitution score matrix
621 protected void findQuality(int startCol, int endCol, ScoreMatrix scoreMatrix)
623 quality = new Vector<Double>();
625 double max = -Double.MAX_VALUE;
626 float[][] scores = scoreMatrix.getMatrix();
628 percentIdentity(scoreMatrix);
630 int size = seqNums.size();
631 int[] lengths = new int[size];
633 for (int l = 0; l < size; l++)
635 lengths[l] = seqNums.elementAt(l).length - 1;
638 final int symbolCount = scoreMatrix.getSize();
640 for (int j = startCol; j <= endCol; j++)
644 // First Xr = depends on column only
645 double[] x = new double[symbolCount];
647 for (int ii = 0; ii < symbolCount; ii++)
652 * todo JAL-728 currently assuming last symbol in matrix is * for gap
653 * (which we ignore as counted separately); true for BLOSUM62 but may
654 * not be once alternative matrices are supported
656 for (int i2 = 0; i2 < symbolCount - 1; i2++)
658 x[ii] += (((double) cons2[j][i2] * scores[ii][i2]) + 4D);
660 x[ii] += 4D + cons2GapCounts[j] * scoreMatrix.getMinimumScore();
665 // Now calculate D for each position and sum
666 for (int k = 0; k < size; k++)
669 double[] xx = new double[symbolCount];
670 // sequence character index, or implied gap if sequence too short
671 int seqNum = (j < lengths[k]) ? seqNums.elementAt(k)[j + 1]
674 for (int i = 0; i < symbolCount - 1; i++)
677 if (seqNum == GAP_INDEX)
679 sr += scoreMatrix.getMinimumScore();
683 sr += scores[i][seqNum];
688 tot += (xx[i] * xx[i]);
691 bigtot += Math.sqrt(tot);
694 max = Math.max(max, bigtot);
696 quality.addElement(new Double(bigtot));
699 double newmax = -Double.MAX_VALUE;
701 for (int j = startCol; j <= endCol; j++)
703 double tmp = quality.elementAt(j).doubleValue();
704 // tmp = ((max - tmp) * (size - cons2[j][23])) / size;
705 tmp = ((max - tmp) * (size - cons2GapCounts[j])) / size;
707 // System.out.println(tmp+ " " + j);
708 quality.setElementAt(new Double(tmp), j);
717 qualityMaximum = newmax;
721 * Complete the given consensus and quuality annotation rows. Note: currently
722 * this method will enlarge the given annotation row if it is too small,
723 * otherwise will leave its length unchanged.
725 * @param conservation
726 * conservation annotation row
728 * (optional - may be null)
730 * first column for conservation
732 * extent of conservation
734 public void completeAnnotations(AlignmentAnnotation conservation,
735 AlignmentAnnotation quality2, int istart, int alWidth)
737 SequenceI cons = getConsSequence();
740 * colour scale for Conservation and Quality;
745 float maxR = 1.0f - minR;
746 float maxG = 0.9f - minG;
747 float maxB = 0f - minB;
754 if (conservation != null && conservation.annotations != null
755 && conservation.annotations.length < alWidth)
757 conservation.annotations = new Annotation[alWidth];
760 if (quality2 != null)
762 quality2.graphMax = (float) qualityMaximum;
763 if (quality2.annotations != null
764 && quality2.annotations.length < alWidth)
766 quality2.annotations = new Annotation[alWidth];
768 qmin = (float) qualityMinimum;
769 qmax = (float) qualityMaximum;
772 for (int i = istart; i < alWidth; i++)
776 char c = cons.getCharAt(i);
778 if (Character.isDigit(c))
791 if (conservation != null)
793 float vprop = value - min;
795 int consp = i - start;
796 String conssym = (value > 0 && consp > -1 && consp < consSymbs.length) ? consSymbs[consp]
798 conservation.annotations[i] = new Annotation(String.valueOf(c),
799 conssym, ' ', value, new Color(minR + (maxR * vprop), minG
800 + (maxG * vprop), minB + (maxB * vprop)));
804 if (quality2 != null)
806 value = quality.elementAt(i).floatValue();
807 float vprop = value - qmin;
809 quality2.annotations[i] = new Annotation(" ",
810 String.valueOf(value), ' ', value, new Color(minR
811 + (maxR * vprop), minG + (maxG * vprop), minB
818 * construct and call the calculation methods on a new Conservation object
821 * - name of conservation
824 * first column in calculation window
826 * last column in calculation window
827 * @param positiveOnly
828 * calculate positive (true) or positive and negative (false)
830 * @param maxPercentGaps
831 * percentage of gaps tolerated in column
833 * flag indicating if alignment quality should be calculated
834 * @return Conservation object ready for use in visualization
836 public static Conservation calculateConservation(String name,
837 List<SequenceI> seqs, int start, int end, boolean positiveOnly,
838 int maxPercentGaps, boolean calcQuality)
840 Conservation cons = new Conservation(name, seqs, start, end);
842 cons.verdict(positiveOnly, maxPercentGaps);
853 * Returns the computed tooltip (annotation description) for a given column.
854 * The tip is empty if the conservation score is zero, otherwise holds the
855 * conserved properties (and, optionally, properties whose absence is
861 String getTooltip(int column)
863 SequenceI cons = getConsSequence();
864 char val = column < cons.getLength() ? cons.getCharAt(column) : '-';
865 boolean hasConservation = val != '-' && val != '0';
866 int consp = column - start;
867 String tip = (hasConservation && consp > -1 && consp < consSymbs.length) ? consSymbs[consp]