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.datamodel.AlignmentAnnotation;
24 import jalview.datamodel.Annotation;
25 import jalview.datamodel.ResidueCount;
26 import jalview.datamodel.ResidueCount.SymbolCounts;
27 import jalview.datamodel.Sequence;
28 import jalview.datamodel.SequenceI;
29 import jalview.schemes.ResidueProperties;
30 import jalview.util.Comparison;
32 import java.awt.Color;
33 import java.util.List;
35 import java.util.Map.Entry;
36 import java.util.TreeMap;
37 import java.util.Vector;
40 * Calculates conservation values for a given set of sequences
42 public class Conservation
45 * need to have a minimum of 3% of sequences with a residue
46 * for it to be included in the conservation calculation
48 private static final int THRESHOLD_PERCENT = 3;
50 private static final int TOUPPERCASE = 'a' - 'A';
52 SequenceI[] sequences;
58 Vector<int[]> seqNums; // vector of int vectors where first is sequence
61 int maxLength = 0; // used by quality calcs
63 boolean seqNumsChanged = false; // updated after any change via calcSeqNum;
66 * a map per column with {property, conservation} where conservation value is
67 * 1 (property is conserved), 0 (absence of property is conserved) or -1
68 * (property is not conserved i.e. column has residues with and without it)
70 Map<String, Integer>[] total;
72 boolean canonicaliseAa = true; // if true then conservation calculation will
74 // map all symbols to canonical aa numbering
75 // rather than consider conservation of that
78 /** Stores calculated quality values */
79 private Vector<Double> quality;
81 /** Stores maximum and minimum values of quality values */
82 private double[] qualityRange = new double[2];
84 private Sequence consSequence;
87 * percentage of residues in a column to qualify for counting conservation
89 private int threshold;
91 private String name = "";
93 private int[][] cons2;
95 private String[] consSymbs;
98 * Constructor using default threshold of 3%
101 * Name of conservation
103 * sequences to be used in calculation
105 * start residue position
107 * end residue position
109 public Conservation(String name, List<SequenceI> sequences, int start,
112 this(name, THRESHOLD_PERCENT, sequences, start, end);
119 * Name of conservation
121 * percentage of sequences at or below which property conservation is
124 * sequences to be used in calculation
126 * start column position
128 * end column position
130 public Conservation(String name, int threshold,
131 List<SequenceI> sequences, int start, int end)
134 this.threshold = threshold;
138 maxLength = end - start + 1; // default width includes bounds of
141 int s, sSize = sequences.size();
142 SequenceI[] sarray = new SequenceI[sSize];
143 this.sequences = sarray;
146 for (s = 0; s < sSize; s++)
148 sarray[s] = sequences.get(s);
149 if (sarray[s].getLength() > maxLength)
151 maxLength = sarray[s].getLength();
154 } catch (ArrayIndexOutOfBoundsException ex)
156 // bail - another thread has modified the sequence array, so the current
157 // calculation is probably invalid.
158 this.sequences = new SequenceI[0];
164 * Translate sequence i into a numerical representation and store it in the
165 * i'th position of the seqNums array.
169 private void calcSeqNum(int i)
171 String sq = null; // for dumb jbuilder not-inited exception warning
174 int sSize = sequences.length;
176 if ((i > -1) && (i < sSize))
178 sq = sequences[i].getSequenceAsString();
180 if (seqNums.size() <= i)
182 seqNums.addElement(new int[sq.length() + 1]);
185 if (sq.hashCode() != seqNums.elementAt(i)[0])
189 seqNumsChanged = true;
197 sqnum = new int[len + 1]; // better to always make a new array -
198 // sequence can change its length
199 sqnum[0] = sq.hashCode();
201 for (j = 1; j <= len; j++)
203 sqnum[j] = jalview.schemes.ResidueProperties.aaIndex[sq
207 seqNums.setElementAt(sqnum, i);
211 System.out.println("SEQUENCE HAS BEEN DELETED!!!");
216 // JBPNote INFO level debug
218 .println("ERROR: calcSeqNum called with out of range sequence index for Alignment\n");
223 * Calculates the conservation values for given set of sequences
225 public void calculate()
227 int height = sequences.length;
229 total = new Map[maxLength];
231 for (int column = start; column <= end; column++)
233 ResidueCount values = countResidues(column);
236 * percentage count at or below which we ignore residues
238 int thresh = (threshold * height) / 100;
241 * check observed residues in column and record whether each
242 * physico-chemical property is conserved (+1), absence conserved (0),
243 * or not conserved (-1)
244 * Using TreeMap means properties are displayed in alphabetical order
246 Map<String, Integer> resultHash = new TreeMap<String, Integer>();
247 SymbolCounts symbolCounts = values.getSymbolCounts();
248 char[] symbols = symbolCounts.symbols;
249 int[] counts = symbolCounts.values;
250 for (int j = 0; j < symbols.length; j++)
253 if (counts[j] > thresh)
255 recordConservation(resultHash, String.valueOf(c));
258 if (values.getGapCount() > thresh)
260 recordConservation(resultHash, "-");
263 if (total.length > 0)
265 total[column - start] = resultHash;
271 * Updates the conservation results for an observed residue
274 * a map of {property, conservation} where conservation value is +1
275 * (all residues have the property), 0 (no residue has the property)
276 * or -1 (some do, some don't)
279 protected static void recordConservation(Map<String, Integer> resultMap,
282 res = res.toUpperCase();
283 for (Entry<String, Map<String, Integer>> property : ResidueProperties.propHash
286 String propertyName = property.getKey();
287 Integer residuePropertyValue = property.getValue().get(res);
289 if (!resultMap.containsKey(propertyName))
292 * first time we've seen this residue - note whether it has this property
294 if (residuePropertyValue != null)
296 resultMap.put(propertyName, residuePropertyValue);
301 * unrecognised residue - use default value for property
303 resultMap.put(propertyName, property.getValue().get("-"));
308 Integer currentResult = resultMap.get(propertyName);
309 if (currentResult.intValue() != -1
310 && !currentResult.equals(residuePropertyValue))
313 * property is unconserved - residues seen both with and without it
315 resultMap.put(propertyName, Integer.valueOf(-1));
322 * Counts residues (upper-cased) and gaps in the given column
327 protected ResidueCount countResidues(int column)
329 ResidueCount values = new ResidueCount(false);
331 for (int row = 0; row < sequences.length; row++)
333 if (sequences[row].getLength() > column)
335 char c = sequences[row].getCharAt(column);
338 int index = ResidueProperties.aaIndex[c];
339 c = index > 20 ? '-' : ResidueProperties.aa[index].charAt(0);
345 if (Comparison.isGap(c))
363 * Counts conservation and gaps for a column of the alignment
365 * @return { 1 if fully conserved, else 0, gap count }
367 public int[] countConservationAndGaps(int column)
370 boolean fullyConserved = true;
371 int iSize = sequences.length;
375 return new int[] { 0, 0 };
379 for (int i = 0; i < iSize; i++)
381 if (column >= sequences[i].getLength())
387 char c = sequences[i].getCharAt(column); // gaps do not have upper/lower case
389 if (Comparison.isGap((c)))
402 fullyConserved = false;
407 int[] r = new int[] { fullyConserved ? 1 : 0, gapCount };
412 * Returns the upper-cased character if between 'a' and 'z', else the
418 char toUpperCase(char c)
420 if ('a' <= c && c <= 'z')
428 * Calculates the conservation sequence
430 * @param positiveOnly
431 * if true, calculate positive conservation; else calculate both
432 * positive and negative conservation
433 * @param maxPercentageGaps
434 * the percentage of gaps in a column, at or above which no
435 * conservation is asserted
437 public void verdict(boolean positiveOnly, float maxPercentageGaps)
439 // TODO call this at the end of calculate(), should not be a public method
441 StringBuilder consString = new StringBuilder(end);
443 // NOTE THIS SHOULD CHECK IF THE CONSEQUENCE ALREADY
444 // EXISTS AND NOT OVERWRITE WITH '-', BUT THIS CASE
445 // DOES NOT EXIST IN JALVIEW 2.1.2
446 for (int i = 0; i < start; i++)
448 consString.append('-');
450 consSymbs = new String[end - start + 1];
451 for (int i = start; i <= end; i++)
453 int[] gapcons = countConservationAndGaps(i);
454 boolean fullyConserved = gapcons[0] == 1;
455 int totGaps = gapcons[1];
456 float pgaps = (totGaps * 100f) / sequences.length;
458 if (maxPercentageGaps > pgaps)
460 Map<String, Integer> resultHash = total[i - start];
462 StringBuilder positives = new StringBuilder(64);
463 StringBuilder negatives = new StringBuilder(32);
464 for (String type : resultHash.keySet())
466 int result = resultHash.get(type).intValue();
470 * not conserved (present or absent)
478 * positively conserved property (all residues have it)
480 positives.append(positives.length() == 0 ? "" : " ");
481 positives.append(type);
483 if (result == 0 && !positiveOnly)
486 * absense of property is conserved (all residues lack it)
488 negatives.append(negatives.length() == 0 ? "" : " ");
489 negatives.append("!").append(type);
492 if (negatives.length() > 0)
494 positives.append(" ").append(negatives);
496 consSymbs[i - start] = positives.toString();
500 consString.append(count); // Conserved props!=Identity
504 consString.append(fullyConserved ? "*" : "+");
509 consString.append('-');
513 consSequence = new Sequence(name, consString.toString(), start, end);
519 * @return Conservation sequence
521 public Sequence getConsSequence()
526 // From Alignment.java in jalview118
527 public void findQuality()
529 findQuality(0, maxLength - 1);
535 private void percentIdentity2()
537 seqNums = new Vector<int[]>();
539 int i = 0, iSize = sequences.length;
540 // Do we need to calculate this again?
541 for (i = 0; i < iSize; i++)
546 if ((cons2 == null) || seqNumsChanged)
548 cons2 = new int[maxLength][24];
550 // Initialize the array
551 for (int j = 0; j < 24; j++)
553 for (i = 0; i < maxLength; i++)
562 while (j < sequences.length)
564 sqnum = seqNums.elementAt(j);
566 for (i = 1; i < sqnum.length; i++)
568 cons2[i - 1][sqnum[i]]++;
571 for (i = sqnum.length - 1; i < maxLength; i++)
573 cons2[i][23]++; // gap count
582 * for (int i=start; i <= end; i++) { int max = -1000; int maxi = -1; int
585 * for (int j=0;j<24;j++) { if (cons2[i][j] > max) { max = cons2[i][j];
586 * maxi = i; maxj = j; } } }
592 * Calculates the quality of the set of sequences
599 public void findQuality(int startRes, int endRes)
601 quality = new Vector<Double>();
604 int[][] BLOSUM62 = ResidueProperties.getBLOSUM62();
606 // Loop over columns // JBPNote Profiling info
607 // long ts = System.currentTimeMillis();
608 // long te = System.currentTimeMillis();
611 int size = seqNums.size();
612 int[] lengths = new int[size];
613 double tot, bigtot, sr, tmp;
615 int l, j, i, ii, i2, k, seqNum;
617 for (l = 0; l < size; l++)
619 lengths[l] = seqNums.elementAt(l).length - 1;
622 for (j = startRes; j <= endRes; j++)
626 // First Xr = depends on column only
629 for (ii = 0; ii < 24; ii++)
633 for (i2 = 0; i2 < 24; i2++)
635 x[ii] += (((double) cons2[j][i2] * BLOSUM62[ii][i2]) + 4);
641 // Now calculate D for each position and sum
642 for (k = 0; k < size; k++)
646 seqNum = (j < lengths[k]) ? seqNums.elementAt(k)[j + 1] : 23; // Sequence,
651 // This is a loop over r
652 for (i = 0; i < 23; i++)
656 sr = (double) BLOSUM62[i][seqNum] + 4;
658 // Calculate X with another loop over residues
659 // System.out.println("Xi " + i + " " + x[i] + " " + sr);
662 tot += (xx[i] * xx[i]);
665 bigtot += Math.sqrt(tot);
668 // This is the quality for one column
674 // bigtot = bigtot * (size-cons2[j][23])/size;
675 quality.addElement(new Double(bigtot));
677 // Need to normalize by gaps
680 double newmax = -10000;
682 for (j = startRes; j <= endRes; j++)
684 tmp = quality.elementAt(j).doubleValue();
685 tmp = ((max - tmp) * (size - cons2[j][23])) / size;
687 // System.out.println(tmp+ " " + j);
688 quality.setElementAt(new Double(tmp), j);
696 // System.out.println("Quality " + s);
697 qualityRange[0] = 0D;
698 qualityRange[1] = newmax;
702 * Complete the given consensus and quuality annotation rows. Note: currently
703 * this method will enlarge the given annotation row if it is too small,
704 * otherwise will leave its length unchanged.
706 * @param conservation
707 * conservation annotation row
709 * (optional - may be null)
711 * first column for conservation
713 * extent of conservation
715 public void completeAnnotations(AlignmentAnnotation conservation,
716 AlignmentAnnotation quality2, int istart, int alWidth)
718 char[] sequence = getConsSequence().getSequence();
730 maxB = 0f - minB; // scalable range for colouring both Conservation and
740 if (conservation != null && conservation.annotations != null
741 && conservation.annotations.length < alWidth)
743 conservation.annotations = new Annotation[alWidth];
746 if (quality2 != null)
748 quality2.graphMax = (float) qualityRange[1];
749 if (quality2.annotations != null
750 && quality2.annotations.length < alWidth)
752 quality2.annotations = new Annotation[alWidth];
754 qmin = (float) qualityRange[0];
755 qmax = (float) qualityRange[1];
758 for (int i = istart; i < alWidth; i++)
764 if (Character.isDigit(c))
777 if (conservation != null)
779 float vprop = value - min;
781 int consp = i - start;
782 String conssym = (value > 0 && consp > -1 && consp < consSymbs.length) ? consSymbs[consp]
784 conservation.annotations[i] = new Annotation(String.valueOf(c),
785 conssym, ' ', value, new Color(minR + (maxR * vprop), minG
786 + (maxG * vprop), minB + (maxB * vprop)));
790 if (quality2 != null)
792 value = quality.elementAt(i).floatValue();
793 float vprop = value - qmin;
795 quality2.annotations[i] = new Annotation(" ",
796 String.valueOf(value), ' ', value, new Color(minR
797 + (maxR * vprop), minG + (maxG * vprop), minB
804 * construct and call the calculation methods on a new Conservation object
807 * - name of conservation
810 * first column in calculation window
812 * last column in calculation window
813 * @param positiveOnly
814 * calculate positive (true) or positive and negative (false)
816 * @param maxPercentGaps
817 * percentage of gaps tolerated in column
819 * flag indicating if alignment quality should be calculated
820 * @return Conservation object ready for use in visualization
822 public static Conservation calculateConservation(String name,
823 List<SequenceI> seqs, int start, int end, boolean positiveOnly,
824 int maxPercentGaps, boolean calcQuality)
826 Conservation cons = new Conservation(name, seqs, start, end);
828 cons.verdict(positiveOnly, maxPercentGaps);
839 * Returns the computed tooltip (annotation description) for a given column.
840 * The tip is empty if the conservation score is zero, otherwise holds the
841 * conserved properties (and, optionally, properties whose absence is
847 String getTooltip(int column)
849 char[] sequence = getConsSequence().getSequence();
850 char val = column < sequence.length ? sequence[column] : '-';
851 boolean hasConservation = val != '-' && val != '0';
852 int consp = column - start;
853 String tip = (hasConservation && consp > -1 && consp < consSymbs.length) ? consSymbs[consp]