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 java.util.Locale;
25 import jalview.analysis.scoremodels.ScoreMatrix;
26 import jalview.analysis.scoremodels.ScoreModels;
27 import jalview.datamodel.AlignmentAnnotation;
28 import jalview.datamodel.Annotation;
29 import jalview.datamodel.ResidueCount;
30 import jalview.datamodel.ResidueCount.SymbolCounts;
31 import jalview.datamodel.Sequence;
32 import jalview.datamodel.SequenceI;
33 import jalview.schemes.ResidueProperties;
34 import jalview.util.Comparison;
35 import jalview.util.Format;
37 import java.awt.Color;
38 import java.util.List;
40 import java.util.Map.Entry;
41 import java.util.SortedMap;
42 import java.util.TreeMap;
43 import java.util.Vector;
46 * Calculates conservation values for a given set of sequences
48 public class Conservation
51 * need to have a minimum of 3% of sequences with a residue
52 * for it to be included in the conservation calculation
54 private static final int THRESHOLD_PERCENT = 3;
56 private static final int TOUPPERCASE = 'a' - 'A';
58 private static final int GAP_INDEX = -1;
60 private static final Format FORMAT_3DP = new Format("%2.5f");
62 SequenceI[] sequences;
69 * a list whose i'th element is an array whose first entry is the checksum
70 * of the i'th sequence, followed by residues encoded to score matrix index
72 Vector<int[]> seqNums;
74 int maxLength = 0; // used by quality calcs
76 boolean seqNumsChanged = false; // updated after any change via calcSeqNum;
79 * a map per column with {property, conservation} where conservation value is
80 * 1 (property is conserved), 0 (absence of property is conserved) or -1
81 * (property is not conserved i.e. column has residues with and without it)
83 Map<String, Integer>[] total;
86 * if true then conservation calculation will map all symbols to canonical aa
87 * numbering rather than consider conservation of that symbol
89 boolean canonicaliseAa = true;
91 private Vector<Double> quality;
93 private double qualityMinimum;
95 private double qualityMaximum;
97 private Sequence consSequence;
100 * percentage of residues in a column to qualify for counting conservation
102 private int threshold;
104 private String name = "";
107 * an array, for each column, of counts of symbols (by score matrix index)
109 private int[][] cons2;
112 * gap counts for each column
114 private int[] cons2GapCounts;
116 private String[] consSymbs;
119 * Constructor using default threshold of 3%
122 * Name of conservation
124 * sequences to be used in calculation
126 * start residue position
128 * end residue position
130 public Conservation(String name, List<SequenceI> sequences, int start,
133 this(name, THRESHOLD_PERCENT, sequences, start, end);
140 * Name of conservation
142 * percentage of sequences at or below which property conservation is
145 * sequences to be used in calculation
147 * start column position
149 * end column position
151 public Conservation(String name, int threshold, List<SequenceI> sequences,
155 this.threshold = threshold;
159 maxLength = end - start + 1; // default width includes bounds of
162 int s, sSize = sequences.size();
163 SequenceI[] sarray = new SequenceI[sSize];
164 this.sequences = sarray;
167 for (s = 0; s < sSize; s++)
169 sarray[s] = sequences.get(s);
170 if (sarray[s].getLength() > maxLength)
172 maxLength = sarray[s].getLength();
175 } catch (ArrayIndexOutOfBoundsException ex)
177 // bail - another thread has modified the sequence array, so the current
178 // calculation is probably invalid.
179 this.sequences = new SequenceI[0];
185 * Translate sequence i into score matrix indices and store it in the i'th
186 * position of the seqNums array.
191 private void calcSeqNum(int i, ScoreMatrix sm)
193 int sSize = sequences.length;
195 if ((i > -1) && (i < sSize))
197 String sq = sequences[i].getSequenceAsString();
199 if (seqNums.size() <= i)
201 seqNums.addElement(new int[sq.length() + 1]);
205 * the first entry in the array is the sequence's hashcode,
206 * following entries are matrix indices of sequence characters
208 if (sq.hashCode() != seqNums.elementAt(i)[0])
212 seqNumsChanged = true;
220 int[] sqnum = new int[len + 1]; // better to always make a new array -
221 // sequence can change its length
222 sqnum[0] = sq.hashCode();
224 for (j = 1; j <= len; j++)
226 // sqnum[j] = ResidueProperties.aaIndex[sq.charAt(j - 1)];
227 char residue = sq.charAt(j - 1);
228 if (Comparison.isGap(residue))
230 sqnum[j] = GAP_INDEX;
234 sqnum[j] = sm.getMatrixIndex(residue);
237 sqnum[j] = GAP_INDEX;
242 seqNums.setElementAt(sqnum, i);
246 System.out.println("SEQUENCE HAS BEEN DELETED!!!");
251 // JBPNote INFO level debug
253 "ERROR: calcSeqNum called with out of range sequence index for Alignment\n");
258 * Calculates the conservation values for given set of sequences
260 public void calculate()
262 int height = sequences.length;
264 total = new Map[maxLength];
266 for (int column = start; column <= end; column++)
268 ResidueCount values = countResidues(column);
271 * percentage count at or below which we ignore residues
273 int thresh = (threshold * height) / 100;
276 * check observed residues in column and record whether each
277 * physico-chemical property is conserved (+1), absence conserved (0),
278 * or not conserved (-1)
279 * Using TreeMap means properties are displayed in alphabetical order
281 SortedMap<String, Integer> resultHash = new TreeMap<>();
282 SymbolCounts symbolCounts = values.getSymbolCounts();
283 char[] symbols = symbolCounts.symbols;
284 int[] counts = symbolCounts.values;
285 for (int j = 0; j < symbols.length; j++)
288 if (counts[j] > thresh)
290 recordConservation(resultHash, String.valueOf(c));
293 if (values.getGapCount() > thresh)
295 recordConservation(resultHash, "-");
298 if (total.length > 0)
300 total[column - start] = resultHash;
306 * Updates the conservation results for an observed residue
309 * a map of {property, conservation} where conservation value is +1
310 * (all residues have the property), 0 (no residue has the property)
311 * or -1 (some do, some don't)
314 protected static void recordConservation(Map<String, Integer> resultMap,
317 res = res.toUpperCase(Locale.ROOT);
318 for (Entry<String, Map<String, Integer>> property : ResidueProperties.propHash
321 String propertyName = property.getKey();
322 Integer residuePropertyValue = property.getValue().get(res);
324 if (!resultMap.containsKey(propertyName))
327 * first time we've seen this residue - note whether it has this property
329 if (residuePropertyValue != null)
331 resultMap.put(propertyName, residuePropertyValue);
336 * unrecognised residue - use default value for property
338 resultMap.put(propertyName, property.getValue().get("-"));
343 Integer currentResult = resultMap.get(propertyName);
344 if (currentResult.intValue() != -1
345 && !currentResult.equals(residuePropertyValue))
348 * property is unconserved - residues seen both with and without it
350 resultMap.put(propertyName, Integer.valueOf(-1));
357 * Counts residues (upper-cased) and gaps in the given column
362 protected ResidueCount countResidues(int column)
364 ResidueCount values = new ResidueCount(false);
366 for (int row = 0; row < sequences.length; row++)
368 if (sequences[row].getLength() > column)
370 char c = sequences[row].getCharAt(column);
373 int index = ResidueProperties.aaIndex[c];
374 c = index > 20 ? '-' : ResidueProperties.aa[index].charAt(0);
380 if (Comparison.isGap(c))
398 * Counts conservation and gaps for a column of the alignment
400 * @return { 1 if fully conserved, else 0, gap count }
402 public int[] countConservationAndGaps(int column)
405 boolean fullyConserved = true;
406 int iSize = sequences.length;
410 return new int[] { 0, 0 };
414 for (int i = 0; i < iSize; i++)
416 if (column >= sequences[i].getLength())
422 char c = sequences[i].getCharAt(column); // gaps do not have upper/lower
425 if (Comparison.isGap((c)))
438 fullyConserved = false;
443 int[] r = new int[] { fullyConserved ? 1 : 0, gapCount };
448 * Returns the upper-cased character if between 'a' and 'z', else the
454 char toUpperCase(char c)
456 if ('a' <= c && c <= 'z')
464 * Calculates the conservation sequence
466 * @param positiveOnly
467 * if true, calculate positive conservation; else calculate both
468 * positive and negative conservation
469 * @param maxPercentageGaps
470 * the percentage of gaps in a column, at or above which no
471 * conservation is asserted
473 public void verdict(boolean positiveOnly, float maxPercentageGaps)
475 // TODO call this at the end of calculate(), should not be a public method
477 StringBuilder consString = new StringBuilder(end);
479 // NOTE THIS SHOULD CHECK IF THE CONSEQUENCE ALREADY
480 // EXISTS AND NOT OVERWRITE WITH '-', BUT THIS CASE
481 // DOES NOT EXIST IN JALVIEW 2.1.2
482 for (int i = 0; i < start; i++)
484 consString.append('-');
486 consSymbs = new String[end - start + 1];
487 for (int i = start; i <= end; i++)
489 int[] gapcons = countConservationAndGaps(i);
490 boolean fullyConserved = gapcons[0] == 1;
491 int totGaps = gapcons[1];
492 float pgaps = (totGaps * 100f) / sequences.length;
494 if (maxPercentageGaps > pgaps)
496 Map<String, Integer> resultHash = total[i - start];
498 StringBuilder positives = new StringBuilder(64);
499 StringBuilder negatives = new StringBuilder(32);
500 for (String type : resultHash.keySet())
502 int result = resultHash.get(type).intValue();
506 * not conserved (present or absent)
514 * positively conserved property (all residues have it)
516 positives.append(positives.length() == 0 ? "" : " ");
517 positives.append(type);
519 if (result == 0 && !positiveOnly)
522 * absense of property is conserved (all residues lack it)
524 negatives.append(negatives.length() == 0 ? "" : " ");
525 negatives.append("!").append(type);
528 if (negatives.length() > 0)
530 positives.append(" ").append(negatives);
532 consSymbs[i - start] = positives.toString();
536 consString.append(count); // Conserved props!=Identity
540 consString.append(fullyConserved ? "*" : "+");
545 consString.append('-');
549 consSequence = new Sequence(name, consString.toString(), start, end);
555 * @return Conservation sequence
557 public SequenceI getConsSequence()
562 // From Alignment.java in jalview118
563 public void findQuality()
565 findQuality(0, maxLength - 1, ScoreModels.getInstance().getBlosum62());
573 private void percentIdentity(ScoreMatrix sm)
575 seqNums = new Vector<>();
576 int i = 0, iSize = sequences.length;
577 // Do we need to calculate this again?
578 for (i = 0; i < iSize; i++)
583 if ((cons2 == null) || seqNumsChanged)
585 // FIXME remove magic number 24 without changing calc
586 // sm.getSize() returns 25 so doesn't quite do it...
587 cons2 = new int[maxLength][24];
588 cons2GapCounts = new int[maxLength];
592 while (j < sequences.length)
594 int[] sqnum = seqNums.elementAt(j);
596 for (i = 1; i < sqnum.length; i++)
598 int index = sqnum[i];
599 if (index == GAP_INDEX)
601 cons2GapCounts[i - 1]++;
605 cons2[i - 1][index]++;
609 // TODO should this start from sqnum.length?
610 for (i = sqnum.length - 1; i < maxLength; i++)
620 * Calculates the quality of the set of sequences over the given inclusive
621 * column range, using the specified substitution score matrix
627 protected void findQuality(int startCol, int endCol,
628 ScoreMatrix scoreMatrix)
630 quality = new Vector<>();
632 double max = -Double.MAX_VALUE;
633 float[][] scores = scoreMatrix.getMatrix();
635 percentIdentity(scoreMatrix);
637 int size = seqNums.size();
638 int[] lengths = new int[size];
640 for (int l = 0; l < size; l++)
642 lengths[l] = seqNums.elementAt(l).length - 1;
645 final int symbolCount = scoreMatrix.getSize();
647 for (int j = startCol; j <= endCol; j++)
651 // First Xr = depends on column only
652 double[] x = new double[symbolCount];
654 for (int ii = 0; ii < symbolCount; ii++)
659 * todo JAL-728 currently assuming last symbol in matrix is * for gap
660 * (which we ignore as counted separately); true for BLOSUM62 but may
661 * not be once alternative matrices are supported
663 for (int i2 = 0; i2 < symbolCount - 1; i2++)
665 x[ii] += (((double) cons2[j][i2] * scores[ii][i2]) + 4D);
667 x[ii] += 4D + cons2GapCounts[j] * scoreMatrix.getMinimumScore();
672 // Now calculate D for each position and sum
673 for (int k = 0; k < size; k++)
676 double[] xx = new double[symbolCount];
677 // sequence character index, or implied gap if sequence too short
678 int seqNum = (j < lengths[k]) ? seqNums.elementAt(k)[j + 1]
681 for (int i = 0; i < symbolCount - 1; i++)
684 if (seqNum == GAP_INDEX)
686 sr += scoreMatrix.getMinimumScore();
690 sr += scores[i][seqNum];
695 tot += (xx[i] * xx[i]);
698 bigtot += Math.sqrt(tot);
701 max = Math.max(max, bigtot);
703 quality.addElement(Double.valueOf(bigtot));
706 double newmax = -Double.MAX_VALUE;
708 for (int j = startCol; j <= endCol; j++)
710 double tmp = quality.elementAt(j).doubleValue();
711 // tmp = ((max - tmp) * (size - cons2[j][23])) / size;
712 tmp = ((max - tmp) * (size - cons2GapCounts[j])) / size;
714 // System.out.println(tmp+ " " + j);
715 quality.setElementAt(Double.valueOf(tmp), j);
724 qualityMaximum = newmax;
728 * Complete the given consensus and quuality annotation rows. Note: currently
729 * this method will reallocate the given annotation row if it is different to
730 * the calculated width, otherwise will leave its length unchanged.
732 * @param conservation
733 * conservation annotation row
735 * (optional - may be null)
737 * first column for conservation
739 * extent of conservation
741 public void completeAnnotations(AlignmentAnnotation conservation,
742 AlignmentAnnotation quality2, int istart, int alWidth)
744 SequenceI cons = getConsSequence();
747 * colour scale for Conservation and Quality;
752 float maxR = 1.0f - minR;
753 float maxG = 0.9f - minG;
754 float maxB = 0f - minB;
761 if (conservation != null && conservation.annotations != null
762 && conservation.annotations.length != alWidth)
764 conservation.annotations = new Annotation[alWidth];
767 if (quality2 != null)
769 quality2.graphMax = (float) qualityMaximum;
770 if (quality2.annotations != null
771 && quality2.annotations.length != alWidth)
773 quality2.annotations = new Annotation[alWidth];
775 qmin = (float) qualityMinimum;
776 qmax = (float) qualityMaximum;
779 for (int i = istart; i < alWidth; i++)
783 char c = cons.getCharAt(i);
785 if (Character.isDigit(c))
798 if (conservation != null)
800 float vprop = value - min;
802 int consp = i - start;
803 String conssym = (value > 0 && consp > -1
804 && consp < consSymbs.length) ? consSymbs[consp] : "";
805 conservation.annotations[i] = new Annotation(String.valueOf(c),
806 conssym, ' ', value, new Color(minR + (maxR * vprop),
807 minG + (maxG * vprop), minB + (maxB * vprop)));
811 if (quality2 != null)
813 value = quality.elementAt(i).floatValue();
814 float vprop = value - qmin;
816 String description = FORMAT_3DP.form(value);
817 quality2.annotations[i] = new Annotation(" ", description, ' ',
818 value, new Color(minR + (maxR * vprop),
819 minG + (maxG * vprop), minB + (maxB * vprop)));
825 * construct and call the calculation methods on a new Conservation object
828 * - name of conservation
831 * first column in calculation window
833 * last column in calculation window
834 * @param positiveOnly
835 * calculate positive (true) or positive and negative (false)
837 * @param maxPercentGaps
838 * percentage of gaps tolerated in column
840 * flag indicating if alignment quality should be calculated
841 * @return Conservation object ready for use in visualization
843 public static Conservation calculateConservation(String name,
844 List<SequenceI> seqs, int start, int end, boolean positiveOnly,
845 int maxPercentGaps, boolean calcQuality)
847 Conservation cons = new Conservation(name, seqs, start, end);
849 cons.verdict(positiveOnly, maxPercentGaps);
860 * Returns the computed tooltip (annotation description) for a given column.
861 * The tip is empty if the conservation score is zero, otherwise holds the
862 * conserved properties (and, optionally, properties whose absence is
868 String getTooltip(int column)
870 SequenceI cons = getConsSequence();
871 char val = column < cons.getLength() ? cons.getCharAt(column) : '-';
872 boolean hasConservation = val != '-' && val != '0';
873 int consp = column - start;
874 String tip = (hasConservation && consp > -1 && consp < consSymbs.length)