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;
33 import jalview.util.Format;
35 import java.awt.Color;
36 import java.util.List;
38 import java.util.Map.Entry;
39 import java.util.SortedMap;
40 import java.util.TreeMap;
41 import java.util.Vector;
44 * Calculates conservation values for a given set of sequences
46 public class Conservation
49 * need to have a minimum of 3% of sequences with a residue
50 * for it to be included in the conservation calculation
52 private static final int THRESHOLD_PERCENT = 3;
54 private static final int TOUPPERCASE = 'a' - 'A';
56 private static final int GAP_INDEX = -1;
58 private static final Format FORMAT_3DP = new Format("%2.5f");
60 SequenceI[] sequences;
67 * a list whose i'th element is an array whose first entry is the checksum
68 * of the i'th sequence, followed by residues encoded to score matrix index
70 Vector<int[]> seqNums;
72 int maxLength = 0; // used by quality calcs
74 boolean seqNumsChanged = false; // updated after any change via calcSeqNum;
77 * a map per column with {property, conservation} where conservation value is
78 * 1 (property is conserved), 0 (absence of property is conserved) or -1
79 * (property is not conserved i.e. column has residues with and without it)
81 Map<String, Integer>[] total;
84 * if true then conservation calculation will map all symbols to canonical aa
85 * numbering rather than consider conservation of that symbol
87 boolean canonicaliseAa = true;
89 private Vector<Double> quality;
91 private double qualityMinimum;
93 private double qualityMaximum;
95 private Sequence consSequence;
98 * percentage of residues in a column to qualify for counting conservation
100 private int threshold;
102 private String name = "";
105 * an array, for each column, of counts of symbols (by score matrix index)
107 private int[][] cons2;
110 * gap counts for each column
112 private int[] cons2GapCounts;
114 private String[] consSymbs;
117 * Constructor using default threshold of 3%
120 * Name of conservation
122 * sequences to be used in calculation
124 * start residue position
126 * end residue position
128 public Conservation(String name, List<SequenceI> sequences, int start,
131 this(name, THRESHOLD_PERCENT, sequences, start, end);
138 * Name of conservation
140 * percentage of sequences at or below which property conservation is
143 * sequences to be used in calculation
145 * start column position
147 * end column position
149 public Conservation(String name, int threshold, List<SequenceI> sequences,
153 this.threshold = threshold;
157 maxLength = end - start + 1; // default width includes bounds of
160 int s, sSize = sequences.size();
161 SequenceI[] sarray = new SequenceI[sSize];
162 this.sequences = sarray;
165 for (s = 0; s < sSize; s++)
167 sarray[s] = sequences.get(s);
168 if (sarray[s].getLength() > maxLength)
170 maxLength = sarray[s].getLength();
173 } catch (ArrayIndexOutOfBoundsException ex)
175 // bail - another thread has modified the sequence array, so the current
176 // calculation is probably invalid.
177 this.sequences = new SequenceI[0];
183 * Translate sequence i into score matrix indices and store it in the i'th
184 * position of the seqNums array.
189 private void calcSeqNum(int i, ScoreMatrix sm)
191 int sSize = sequences.length;
193 if ((i > -1) && (i < sSize))
195 String sq = sequences[i].getSequenceAsString();
197 if (seqNums.size() <= i)
199 seqNums.addElement(new int[sq.length() + 1]);
203 * the first entry in the array is the sequence's hashcode,
204 * following entries are matrix indices of sequence characters
206 if (sq.hashCode() != seqNums.elementAt(i)[0])
210 seqNumsChanged = true;
218 int[] sqnum = new int[len + 1]; // better to always make a new array -
219 // sequence can change its length
220 sqnum[0] = sq.hashCode();
222 for (j = 1; j <= len; j++)
224 // sqnum[j] = ResidueProperties.aaIndex[sq.charAt(j - 1)];
225 char residue = sq.charAt(j - 1);
226 if (Comparison.isGap(residue))
228 sqnum[j] = GAP_INDEX;
232 sqnum[j] = sm.getMatrixIndex(residue);
235 sqnum[j] = GAP_INDEX;
240 seqNums.setElementAt(sqnum, i);
244 System.out.println("SEQUENCE HAS BEEN DELETED!!!");
249 // JBPNote INFO level debug
251 "ERROR: calcSeqNum called with out of range sequence index for Alignment\n");
256 * Calculates the conservation values for given set of sequences
258 public void calculate()
260 int height = sequences.length;
262 total = new Map[maxLength];
264 for (int column = start; column <= end; column++)
266 ResidueCount values = countResidues(column);
269 * percentage count at or below which we ignore residues
271 int thresh = (threshold * height) / 100;
274 * check observed residues in column and record whether each
275 * physico-chemical property is conserved (+1), absence conserved (0),
276 * or not conserved (-1)
277 * Using TreeMap means properties are displayed in alphabetical order
279 SortedMap<String, Integer> resultHash = new TreeMap<>();
280 SymbolCounts symbolCounts = values.getSymbolCounts();
281 char[] symbols = symbolCounts.symbols;
282 int[] counts = symbolCounts.values;
283 for (int j = 0; j < symbols.length; j++)
286 if (counts[j] > thresh)
288 recordConservation(resultHash, String.valueOf(c));
291 if (values.getGapCount() > thresh)
293 recordConservation(resultHash, "-");
296 if (total.length > 0)
298 total[column - start] = resultHash;
304 * Updates the conservation results for an observed residue
307 * a map of {property, conservation} where conservation value is +1
308 * (all residues have the property), 0 (no residue has the property)
309 * or -1 (some do, some don't)
312 protected static void recordConservation(Map<String, Integer> resultMap,
315 res = res.toUpperCase();
316 for (Entry<String, Map<String, Integer>> property : ResidueProperties.propHash
319 String propertyName = property.getKey();
320 Integer residuePropertyValue = property.getValue().get(res);
322 if (!resultMap.containsKey(propertyName))
325 * first time we've seen this residue - note whether it has this property
327 if (residuePropertyValue != null)
329 resultMap.put(propertyName, residuePropertyValue);
334 * unrecognised residue - use default value for property
336 resultMap.put(propertyName, property.getValue().get("-"));
341 Integer currentResult = resultMap.get(propertyName);
342 if (currentResult.intValue() != -1
343 && !currentResult.equals(residuePropertyValue))
346 * property is unconserved - residues seen both with and without it
348 resultMap.put(propertyName, Integer.valueOf(-1));
355 * Counts residues (upper-cased) and gaps in the given column
360 protected ResidueCount countResidues(int column)
362 ResidueCount values = new ResidueCount(false);
364 for (int row = 0; row < sequences.length; row++)
366 if (sequences[row].getLength() > column)
368 char c = sequences[row].getCharAt(column);
371 int index = ResidueProperties.aaIndex[c];
372 c = index > 20 ? '-' : ResidueProperties.aa[index].charAt(0);
378 if (Comparison.isGap(c))
396 * Counts conservation and gaps for a column of the alignment
398 * @return { 1 if fully conserved, else 0, gap count }
400 public int[] countConservationAndGaps(int column)
403 boolean fullyConserved = true;
404 int iSize = sequences.length;
408 return new int[] { 0, 0 };
412 for (int i = 0; i < iSize; i++)
414 if (column >= sequences[i].getLength())
420 char c = sequences[i].getCharAt(column); // gaps do not have upper/lower
423 if (Comparison.isGap((c)))
436 fullyConserved = false;
441 int[] r = new int[] { fullyConserved ? 1 : 0, gapCount };
446 * Returns the upper-cased character if between 'a' and 'z', else the
452 char toUpperCase(char c)
454 if ('a' <= c && c <= 'z')
462 * Calculates the conservation sequence
464 * @param positiveOnly
465 * if true, calculate positive conservation; else calculate both
466 * positive and negative conservation
467 * @param maxPercentageGaps
468 * the percentage of gaps in a column, at or above which no
469 * conservation is asserted
471 public void verdict(boolean positiveOnly, float maxPercentageGaps)
473 // TODO call this at the end of calculate(), should not be a public method
475 StringBuilder consString = new StringBuilder(end);
477 // NOTE THIS SHOULD CHECK IF THE CONSEQUENCE ALREADY
478 // EXISTS AND NOT OVERWRITE WITH '-', BUT THIS CASE
479 // DOES NOT EXIST IN JALVIEW 2.1.2
480 for (int i = 0; i < start; i++)
482 consString.append('-');
484 consSymbs = new String[end - start + 1];
485 for (int i = start; i <= end; i++)
487 int[] gapcons = countConservationAndGaps(i);
488 boolean fullyConserved = gapcons[0] == 1;
489 int totGaps = gapcons[1];
490 float pgaps = (totGaps * 100f) / sequences.length;
492 if (maxPercentageGaps > pgaps)
494 Map<String, Integer> resultHash = total[i - start];
496 StringBuilder positives = new StringBuilder(64);
497 StringBuilder negatives = new StringBuilder(32);
498 for (String type : resultHash.keySet())
500 int result = resultHash.get(type).intValue();
504 * not conserved (present or absent)
512 * positively conserved property (all residues have it)
514 positives.append(positives.length() == 0 ? "" : " ");
515 positives.append(type);
517 if (result == 0 && !positiveOnly)
520 * absense of property is conserved (all residues lack it)
522 negatives.append(negatives.length() == 0 ? "" : " ");
523 negatives.append("!").append(type);
526 if (negatives.length() > 0)
528 positives.append(" ").append(negatives);
530 consSymbs[i - start] = positives.toString();
534 consString.append(count); // Conserved props!=Identity
538 consString.append(fullyConserved ? "*" : "+");
543 consString.append('-');
547 consSequence = new Sequence(name, consString.toString(), start, end);
553 * @return Conservation sequence
555 public SequenceI getConsSequence()
560 // From Alignment.java in jalview118
561 public void findQuality()
563 findQuality(0, maxLength - 1, ScoreModels.getInstance().getBlosum62());
571 private void percentIdentity(ScoreMatrix sm)
573 seqNums = new Vector<>();
574 int i = 0, iSize = sequences.length;
575 // Do we need to calculate this again?
576 for (i = 0; i < iSize; i++)
581 if ((cons2 == null) || seqNumsChanged)
583 // FIXME remove magic number 24 without changing calc
584 // sm.getSize() returns 25 so doesn't quite do it...
585 cons2 = new int[maxLength][24];
586 cons2GapCounts = new int[maxLength];
590 while (j < sequences.length)
592 int[] sqnum = seqNums.elementAt(j);
594 for (i = 1; i < sqnum.length; i++)
596 int index = sqnum[i];
597 if (index == GAP_INDEX)
599 cons2GapCounts[i - 1]++;
603 cons2[i - 1][index]++;
607 // TODO should this start from sqnum.length?
608 for (i = sqnum.length - 1; i < maxLength; i++)
618 * Calculates the quality of the set of sequences over the given inclusive
619 * column range, using the specified substitution score matrix
625 protected void findQuality(int startCol, int endCol,
626 ScoreMatrix scoreMatrix)
628 quality = new Vector<>();
630 double max = -Double.MAX_VALUE;
631 float[][] scores = scoreMatrix.getMatrix();
633 percentIdentity(scoreMatrix);
635 int size = seqNums.size();
636 int[] lengths = new int[size];
638 for (int l = 0; l < size; l++)
640 lengths[l] = seqNums.elementAt(l).length - 1;
643 final int symbolCount = scoreMatrix.getSize();
645 for (int j = startCol; j <= endCol; j++)
649 // First Xr = depends on column only
650 double[] x = new double[symbolCount];
652 for (int ii = 0; ii < symbolCount; ii++)
657 * todo JAL-728 currently assuming last symbol in matrix is * for gap
658 * (which we ignore as counted separately); true for BLOSUM62 but may
659 * not be once alternative matrices are supported
661 for (int i2 = 0; i2 < symbolCount - 1; i2++)
663 x[ii] += (((double) cons2[j][i2] * scores[ii][i2]) + 4D);
665 x[ii] += 4D + cons2GapCounts[j] * scoreMatrix.getMinimumScore();
670 // Now calculate D for each position and sum
671 for (int k = 0; k < size; k++)
674 double[] xx = new double[symbolCount];
675 // sequence character index, or implied gap if sequence too short
676 int seqNum = (j < lengths[k]) ? seqNums.elementAt(k)[j + 1]
679 for (int i = 0; i < symbolCount - 1; i++)
682 if (seqNum == GAP_INDEX)
684 sr += scoreMatrix.getMinimumScore();
688 sr += scores[i][seqNum];
693 tot += (xx[i] * xx[i]);
696 bigtot += Math.sqrt(tot);
699 max = Math.max(max, bigtot);
701 quality.addElement(new Double(bigtot));
704 double newmax = -Double.MAX_VALUE;
706 for (int j = startCol; j <= endCol; j++)
708 double tmp = quality.elementAt(j).doubleValue();
709 // tmp = ((max - tmp) * (size - cons2[j][23])) / size;
710 tmp = ((max - tmp) * (size - cons2GapCounts[j])) / size;
712 // System.out.println(tmp+ " " + j);
713 quality.setElementAt(new Double(tmp), j);
722 qualityMaximum = newmax;
726 * Complete the given consensus and quuality annotation rows. Note: currently
727 * this method will reallocate the given annotation row if it is different to
728 * the calculated width, otherwise will leave its length unchanged.
730 * @param conservation
731 * conservation annotation row
733 * (optional - may be null)
735 * first column for conservation
737 * extent of conservation
739 public void completeAnnotations(AlignmentAnnotation conservation,
740 AlignmentAnnotation quality2, int istart, int alWidth)
742 SequenceI cons = getConsSequence();
745 * colour scale for Conservation and Quality;
750 float maxR = 1.0f - minR;
751 float maxG = 0.9f - minG;
752 float maxB = 0f - minB;
759 if (conservation != null && conservation.annotations != null
760 && conservation.annotations.length != alWidth)
762 conservation.annotations = new Annotation[alWidth];
765 if (quality2 != null)
767 quality2.graphMax = (float) qualityMaximum;
768 if (quality2.annotations != null
769 && quality2.annotations.length != alWidth)
771 quality2.annotations = new Annotation[alWidth];
773 qmin = (float) qualityMinimum;
774 qmax = (float) qualityMaximum;
777 for (int i = istart; i < alWidth; i++)
781 char c = cons.getCharAt(i);
783 if (Character.isDigit(c))
796 if (conservation != null)
798 float vprop = value - min;
800 int consp = i - start;
801 String conssym = (value > 0 && consp > -1
802 && consp < consSymbs.length) ? consSymbs[consp] : "";
803 conservation.annotations[i] = new Annotation(String.valueOf(c),
804 conssym, ' ', value, new Color(minR + (maxR * vprop),
805 minG + (maxG * vprop), minB + (maxB * vprop)));
809 if (quality2 != null)
811 value = quality.elementAt(i).floatValue();
812 float vprop = value - qmin;
814 String description = FORMAT_3DP.form(value);
815 quality2.annotations[i] = new Annotation(" ", description,
816 ' ', value, new Color(minR + (maxR * vprop),
817 minG + (maxG * vprop), minB + (maxB * vprop)));
823 * construct and call the calculation methods on a new Conservation object
826 * - name of conservation
829 * first column in calculation window
831 * last column in calculation window
832 * @param positiveOnly
833 * calculate positive (true) or positive and negative (false)
835 * @param maxPercentGaps
836 * percentage of gaps tolerated in column
838 * flag indicating if alignment quality should be calculated
839 * @return Conservation object ready for use in visualization
841 public static Conservation calculateConservation(String name,
842 List<SequenceI> seqs, int start, int end, boolean positiveOnly,
843 int maxPercentGaps, boolean calcQuality)
845 Conservation cons = new Conservation(name, seqs, start, end);
847 cons.verdict(positiveOnly, maxPercentGaps);
858 * Returns the computed tooltip (annotation description) for a given column.
859 * The tip is empty if the conservation score is zero, otherwise holds the
860 * conserved properties (and, optionally, properties whose absence is
866 String getTooltip(int column)
868 SequenceI cons = getConsSequence();
869 char val = column < cons.getLength() ? cons.getCharAt(column) : '-';
870 boolean hasConservation = val != '-' && val != '0';
871 int consp = column - start;
872 String tip = (hasConservation && consp > -1 && consp < consSymbs.length)