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.datamodel.AlignmentAnnotation;
25 import jalview.datamodel.Annotation;
26 import jalview.datamodel.ResidueCount;
27 import jalview.datamodel.ResidueCount.SymbolCounts;
28 import jalview.datamodel.Sequence;
29 import jalview.datamodel.SequenceI;
30 import jalview.schemes.ResidueProperties;
31 import jalview.util.Comparison;
33 import java.awt.Color;
34 import java.util.List;
36 import java.util.Map.Entry;
37 import java.util.SortedMap;
38 import java.util.TreeMap;
39 import java.util.Vector;
42 * Calculates conservation values for a given set of sequences
44 public class Conservation
47 * need to have a minimum of 3% of sequences with a residue
48 * for it to be included in the conservation calculation
50 private static final int THRESHOLD_PERCENT = 3;
52 private static final int TOUPPERCASE = 'a' - 'A';
54 private static final int GAP_INDEX = -1;
56 SequenceI[] sequences;
63 * a list whose i'th element is an array whose first entry is the checksum
64 * of the i'th sequence, followed by residues encoded to score matrix index
66 Vector<int[]> seqNums;
68 int maxLength = 0; // used by quality calcs
70 boolean seqNumsChanged = false; // updated after any change via calcSeqNum;
73 * a map per column with {property, conservation} where conservation value is
74 * 1 (property is conserved), 0 (absence of property is conserved) or -1
75 * (property is not conserved i.e. column has residues with and without it)
77 Map<String, Integer>[] total;
80 * if true then conservation calculation will map all symbols to canonical aa
81 * numbering rather than consider conservation of that symbol
83 boolean canonicaliseAa = true;
85 private Vector<Double> quality;
87 private double qualityMinimum;
89 private double qualityMaximum;
91 private Sequence consSequence;
94 * percentage of residues in a column to qualify for counting conservation
96 private int threshold;
98 private String name = "";
101 * an array, for each column, of counts of symbols (by score matrix index)
103 private int[][] cons2;
106 * gap counts for each column
108 private int[] cons2GapCounts;
110 private String[] consSymbs;
113 * Constructor using default threshold of 3%
116 * Name of conservation
118 * sequences to be used in calculation
120 * start residue position
122 * end residue position
124 public Conservation(String name, List<SequenceI> sequences, int start,
127 this(name, THRESHOLD_PERCENT, sequences, start, end);
134 * Name of conservation
136 * percentage of sequences at or below which property conservation is
139 * sequences to be used in calculation
141 * start column position
143 * end column position
145 public Conservation(String name, int threshold,
146 List<SequenceI> sequences, int start, int end)
149 this.threshold = threshold;
153 maxLength = end - start + 1; // default width includes bounds of
156 int s, sSize = sequences.size();
157 SequenceI[] sarray = new SequenceI[sSize];
158 this.sequences = sarray;
161 for (s = 0; s < sSize; s++)
163 sarray[s] = sequences.get(s);
164 if (sarray[s].getLength() > maxLength)
166 maxLength = sarray[s].getLength();
169 } catch (ArrayIndexOutOfBoundsException ex)
171 // bail - another thread has modified the sequence array, so the current
172 // calculation is probably invalid.
173 this.sequences = new SequenceI[0];
179 * Translate sequence i into score matrix indices and store it in the i'th
180 * position of the seqNums array.
185 private void calcSeqNum(int i, ScoreMatrix sm)
187 int sSize = sequences.length;
189 if ((i > -1) && (i < sSize))
191 String sq = sequences[i].getSequenceAsString();
193 if (seqNums.size() <= i)
195 seqNums.addElement(new int[sq.length() + 1]);
199 * the first entry in the array is the sequence's hashcode,
200 * following entries are matrix indices of sequence characters
202 if (sq.hashCode() != seqNums.elementAt(i)[0])
206 seqNumsChanged = true;
214 int[] sqnum = new int[len + 1]; // better to always make a new array -
215 // sequence can change its length
216 sqnum[0] = sq.hashCode();
218 for (j = 1; j <= len; j++)
220 // sqnum[j] = ResidueProperties.aaIndex[sq.charAt(j - 1)];
221 char residue = sq.charAt(j - 1);
222 if (Comparison.isGap(residue))
224 sqnum[j] = GAP_INDEX;
228 sqnum[j] = sm.getMatrixIndex(residue);
231 sqnum[j] = GAP_INDEX;
236 seqNums.setElementAt(sqnum, i);
240 System.out.println("SEQUENCE HAS BEEN DELETED!!!");
245 // JBPNote INFO level debug
247 .println("ERROR: calcSeqNum called with out of range sequence index for Alignment\n");
252 * Calculates the conservation values for given set of sequences
254 public void calculate()
256 int height = sequences.length;
258 total = new Map[maxLength];
260 for (int column = start; column <= end; column++)
262 ResidueCount values = countResidues(column);
265 * percentage count at or below which we ignore residues
267 int thresh = (threshold * height) / 100;
270 * check observed residues in column and record whether each
271 * physico-chemical property is conserved (+1), absence conserved (0),
272 * or not conserved (-1)
273 * Using TreeMap means properties are displayed in alphabetical order
275 SortedMap<String, Integer> resultHash = new TreeMap<String, Integer>();
276 SymbolCounts symbolCounts = values.getSymbolCounts();
277 char[] symbols = symbolCounts.symbols;
278 int[] counts = symbolCounts.values;
279 for (int j = 0; j < symbols.length; j++)
282 if (counts[j] > thresh)
284 recordConservation(resultHash, String.valueOf(c));
287 if (values.getGapCount() > thresh)
289 recordConservation(resultHash, "-");
292 if (total.length > 0)
294 total[column - start] = resultHash;
300 * Updates the conservation results for an observed residue
303 * a map of {property, conservation} where conservation value is +1
304 * (all residues have the property), 0 (no residue has the property)
305 * or -1 (some do, some don't)
308 protected static void recordConservation(Map<String, Integer> resultMap,
311 res = res.toUpperCase();
312 for (Entry<String, Map<String, Integer>> property : ResidueProperties.propHash
315 String propertyName = property.getKey();
316 Integer residuePropertyValue = property.getValue().get(res);
318 if (!resultMap.containsKey(propertyName))
321 * first time we've seen this residue - note whether it has this property
323 if (residuePropertyValue != null)
325 resultMap.put(propertyName, residuePropertyValue);
330 * unrecognised residue - use default value for property
332 resultMap.put(propertyName, property.getValue().get("-"));
337 Integer currentResult = resultMap.get(propertyName);
338 if (currentResult.intValue() != -1
339 && !currentResult.equals(residuePropertyValue))
342 * property is unconserved - residues seen both with and without it
344 resultMap.put(propertyName, Integer.valueOf(-1));
351 * Counts residues (upper-cased) and gaps in the given column
356 protected ResidueCount countResidues(int column)
358 ResidueCount values = new ResidueCount(false);
360 for (int row = 0; row < sequences.length; row++)
362 if (sequences[row].getLength() > column)
364 char c = sequences[row].getCharAt(column);
367 int index = ResidueProperties.aaIndex[c];
368 c = index > 20 ? '-' : ResidueProperties.aa[index].charAt(0);
374 if (Comparison.isGap(c))
392 * Counts conservation and gaps for a column of the alignment
394 * @return { 1 if fully conserved, else 0, gap count }
396 public int[] countConservationAndGaps(int column)
399 boolean fullyConserved = true;
400 int iSize = sequences.length;
404 return new int[] { 0, 0 };
408 for (int i = 0; i < iSize; i++)
410 if (column >= sequences[i].getLength())
416 char c = sequences[i].getCharAt(column); // gaps do not have upper/lower case
418 if (Comparison.isGap((c)))
431 fullyConserved = false;
436 int[] r = new int[] { fullyConserved ? 1 : 0, gapCount };
441 * Returns the upper-cased character if between 'a' and 'z', else the
447 char toUpperCase(char c)
449 if ('a' <= c && c <= 'z')
457 * Calculates the conservation sequence
459 * @param positiveOnly
460 * if true, calculate positive conservation; else calculate both
461 * positive and negative conservation
462 * @param maxPercentageGaps
463 * the percentage of gaps in a column, at or above which no
464 * conservation is asserted
466 public void verdict(boolean positiveOnly, float maxPercentageGaps)
468 // TODO call this at the end of calculate(), should not be a public method
470 StringBuilder consString = new StringBuilder(end);
472 // NOTE THIS SHOULD CHECK IF THE CONSEQUENCE ALREADY
473 // EXISTS AND NOT OVERWRITE WITH '-', BUT THIS CASE
474 // DOES NOT EXIST IN JALVIEW 2.1.2
475 for (int i = 0; i < start; i++)
477 consString.append('-');
479 consSymbs = new String[end - start + 1];
480 for (int i = start; i <= end; i++)
482 int[] gapcons = countConservationAndGaps(i);
483 boolean fullyConserved = gapcons[0] == 1;
484 int totGaps = gapcons[1];
485 float pgaps = (totGaps * 100f) / sequences.length;
487 if (maxPercentageGaps > pgaps)
489 Map<String, Integer> resultHash = total[i - start];
491 StringBuilder positives = new StringBuilder(64);
492 StringBuilder negatives = new StringBuilder(32);
493 for (String type : resultHash.keySet())
495 int result = resultHash.get(type).intValue();
499 * not conserved (present or absent)
507 * positively conserved property (all residues have it)
509 positives.append(positives.length() == 0 ? "" : " ");
510 positives.append(type);
512 if (result == 0 && !positiveOnly)
515 * absense of property is conserved (all residues lack it)
517 negatives.append(negatives.length() == 0 ? "" : " ");
518 negatives.append("!").append(type);
521 if (negatives.length() > 0)
523 positives.append(" ").append(negatives);
525 consSymbs[i - start] = positives.toString();
529 consString.append(count); // Conserved props!=Identity
533 consString.append(fullyConserved ? "*" : "+");
538 consString.append('-');
542 consSequence = new Sequence(name, consString.toString(), start, end);
548 * @return Conservation sequence
550 public SequenceI getConsSequence()
555 // From Alignment.java in jalview118
556 public void findQuality(ScoreMatrix scoreModel)
558 findQuality(0, maxLength - 1, scoreModel);
566 private void percentIdentity(ScoreMatrix sm)
568 seqNums = new Vector<int[]>();
569 int i = 0, iSize = sequences.length;
570 // Do we need to calculate this again?
571 for (i = 0; i < iSize; i++)
576 if ((cons2 == null) || seqNumsChanged)
578 // FIXME remove magic number 24 without changing calc
579 // sm.getSize() returns 25 so doesn't quite do it...
580 cons2 = new int[maxLength][24];
581 cons2GapCounts = new int[maxLength];
585 while (j < sequences.length)
587 int[] sqnum = seqNums.elementAt(j);
589 for (i = 1; i < sqnum.length; i++)
591 int index = sqnum[i];
592 if (index == GAP_INDEX)
594 cons2GapCounts[i - 1]++;
598 cons2[i - 1][index]++;
602 // TODO should this start from sqnum.length?
603 for (i = sqnum.length - 1; i < maxLength; i++)
613 * Calculates the quality of the set of sequences over the given inclusive
614 * column range, using the specified substitution score matrix
620 protected void findQuality(int startCol, int endCol, ScoreMatrix scoreMatrix)
622 quality = new Vector<Double>();
624 double max = -Double.MAX_VALUE;
625 float[][] scores = scoreMatrix.getMatrix();
627 percentIdentity(scoreMatrix);
629 int size = seqNums.size();
630 int[] lengths = new int[size];
632 for (int l = 0; l < size; l++)
634 lengths[l] = seqNums.elementAt(l).length - 1;
637 final int symbolCount = scoreMatrix.getSize();
639 for (int j = startCol; j <= endCol; j++)
643 // First Xr = depends on column only
644 double[] x = new double[symbolCount];
646 for (int ii = 0; ii < symbolCount; ii++)
651 * todo JAL-728 currently assuming last symbol in matrix is * for gap
652 * (which we ignore as counted separately); true for BLOSUM62 but may
653 * not be once alternative matrices are supported
655 for (int i2 = 0; i2 < symbolCount - 1; i2++)
657 x[ii] += (((double) cons2[j][i2] * scores[ii][i2]) + 4D);
659 x[ii] += 4D + cons2GapCounts[j] * scoreMatrix.getMinimumScore();
664 // Now calculate D for each position and sum
665 for (int k = 0; k < size; k++)
668 double[] xx = new double[symbolCount];
669 // sequence character index, or implied gap if sequence too short
670 int seqNum = (j < lengths[k]) ? seqNums.elementAt(k)[j + 1]
673 for (int i = 0; i < symbolCount - 1; i++)
676 if (seqNum == GAP_INDEX)
678 sr += scoreMatrix.getMinimumScore();
682 sr += scores[i][seqNum];
687 tot += (xx[i] * xx[i]);
690 bigtot += Math.sqrt(tot);
693 max = Math.max(max, bigtot);
695 quality.addElement(new Double(bigtot));
698 double newmax = -Double.MAX_VALUE;
700 for (int j = startCol; j <= endCol; j++)
702 double tmp = quality.elementAt(j).doubleValue();
703 // tmp = ((max - tmp) * (size - cons2[j][23])) / size;
704 tmp = ((max - tmp) * (size - cons2GapCounts[j])) / size;
706 // System.out.println(tmp+ " " + j);
707 quality.setElementAt(new Double(tmp), j);
716 qualityMaximum = newmax;
720 * Complete the given consensus and quuality annotation rows. Note: currently
721 * this method will enlarge the given annotation row if it is too small,
722 * otherwise will leave its length unchanged.
724 * @param conservation
725 * conservation annotation row
727 * (optional - may be null)
729 * first column for conservation
731 * extent of conservation
733 public void completeAnnotations(AlignmentAnnotation conservation,
734 AlignmentAnnotation quality2, int istart, int alWidth)
736 char[] sequence = getConsSequence().getSequence();
748 maxB = 0f - minB; // scalable range for colouring both Conservation and
758 if (conservation != null && conservation.annotations != null
759 && conservation.annotations.length < alWidth)
761 conservation.annotations = new Annotation[alWidth];
764 if (quality2 != null)
766 quality2.graphMax = (float) qualityMaximum;
767 if (quality2.annotations != null
768 && quality2.annotations.length < alWidth)
770 quality2.annotations = new Annotation[alWidth];
772 qmin = (float) qualityMinimum;
773 qmax = (float) qualityMaximum;
776 for (int i = istart; i < alWidth; i++)
782 if (Character.isDigit(c))
795 if (conservation != null)
797 float vprop = value - min;
799 int consp = i - start;
800 String conssym = (value > 0 && consp > -1 && consp < consSymbs.length) ? consSymbs[consp]
802 conservation.annotations[i] = new Annotation(String.valueOf(c),
803 conssym, ' ', value, new Color(minR + (maxR * vprop), minG
804 + (maxG * vprop), minB + (maxB * vprop)));
808 if (quality2 != null)
810 value = quality.elementAt(i).floatValue();
811 float vprop = value - qmin;
813 quality2.annotations[i] = new Annotation(" ",
814 String.valueOf(value), ' ', value, new Color(minR
815 + (maxR * vprop), minG + (maxG * vprop), minB
822 * construct and call the calculation methods on a new Conservation object
825 * - name of conservation
828 * first column in calculation window
830 * last column in calculation window
831 * @param positiveOnly
832 * calculate positive (true) or positive and negative (false)
834 * @param maxPercentGaps
835 * percentage of gaps tolerated in column
837 * flag indicating if alignment quality should be calculated
838 * @return Conservation object ready for use in visualization
840 public static Conservation calculateConservation(String name,
841 List<SequenceI> seqs, int start, int end, boolean positiveOnly,
842 int maxPercentGaps, boolean calcQuality, ScoreMatrix scoreModel)
844 Conservation cons = new Conservation(name, seqs, start, end);
846 cons.verdict(positiveOnly, maxPercentGaps);
850 cons.findQuality(scoreModel);
857 * Returns the computed tooltip (annotation description) for a given column.
858 * The tip is empty if the conservation score is zero, otherwise holds the
859 * conserved properties (and, optionally, properties whose absence is
865 String getTooltip(int column)
867 char[] sequence = getConsSequence().getSequence();
868 char val = column < sequence.length ? sequence[column] : '-';
869 boolean hasConservation = val != '-' && val != '0';
870 int consp = column - start;
871 String tip = (hasConservation && consp > -1 && consp < consSymbs.length) ? consSymbs[consp]