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.ScoreModels;
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 SequenceI[] sequences;
60 Vector<int[]> seqNums; // vector of int vectors where first is sequence
63 int maxLength = 0; // used by quality calcs
65 boolean seqNumsChanged = false; // updated after any change via calcSeqNum;
68 * a map per column with {property, conservation} where conservation value is
69 * 1 (property is conserved), 0 (absence of property is conserved) or -1
70 * (property is not conserved i.e. column has residues with and without it)
72 Map<String, Integer>[] total;
74 boolean canonicaliseAa = true; // if true then conservation calculation will
76 // map all symbols to canonical aa numbering
77 // rather than consider conservation of that
80 /** Stores calculated quality values */
81 private Vector<Double> quality;
83 /** Stores maximum and minimum values of quality values */
84 private double[] qualityRange = new double[2];
86 private Sequence consSequence;
89 * percentage of residues in a column to qualify for counting conservation
91 private int threshold;
93 private String name = "";
95 private int[][] cons2;
97 private String[] consSymbs;
100 * Constructor using default threshold of 3%
103 * Name of conservation
105 * sequences to be used in calculation
107 * start residue position
109 * end residue position
111 public Conservation(String name, List<SequenceI> sequences, int start,
114 this(name, THRESHOLD_PERCENT, sequences, start, end);
121 * Name of conservation
123 * percentage of sequences at or below which property conservation is
126 * sequences to be used in calculation
128 * start column position
130 * end column position
132 public Conservation(String name, int threshold,
133 List<SequenceI> sequences, int start, int end)
136 this.threshold = threshold;
140 maxLength = end - start + 1; // default width includes bounds of
143 int s, sSize = sequences.size();
144 SequenceI[] sarray = new SequenceI[sSize];
145 this.sequences = sarray;
148 for (s = 0; s < sSize; s++)
150 sarray[s] = sequences.get(s);
151 if (sarray[s].getLength() > maxLength)
153 maxLength = sarray[s].getLength();
156 } catch (ArrayIndexOutOfBoundsException ex)
158 // bail - another thread has modified the sequence array, so the current
159 // calculation is probably invalid.
160 this.sequences = new SequenceI[0];
166 * Translate sequence i into a numerical representation and store it in the
167 * i'th position of the seqNums array.
171 private void calcSeqNum(int i)
173 String sq = null; // for dumb jbuilder not-inited exception warning
176 int sSize = sequences.length;
178 if ((i > -1) && (i < sSize))
180 sq = sequences[i].getSequenceAsString();
182 if (seqNums.size() <= i)
184 seqNums.addElement(new int[sq.length() + 1]);
187 if (sq.hashCode() != seqNums.elementAt(i)[0])
191 seqNumsChanged = true;
199 sqnum = new int[len + 1]; // better to always make a new array -
200 // sequence can change its length
201 sqnum[0] = sq.hashCode();
203 for (j = 1; j <= len; j++)
205 sqnum[j] = jalview.schemes.ResidueProperties.aaIndex[sq
209 seqNums.setElementAt(sqnum, i);
213 System.out.println("SEQUENCE HAS BEEN DELETED!!!");
218 // JBPNote INFO level debug
220 .println("ERROR: calcSeqNum called with out of range sequence index for Alignment\n");
225 * Calculates the conservation values for given set of sequences
227 public void calculate()
229 int height = sequences.length;
231 total = new Map[maxLength];
233 for (int column = start; column <= end; column++)
235 ResidueCount values = countResidues(column);
238 * percentage count at or below which we ignore residues
240 int thresh = (threshold * height) / 100;
243 * check observed residues in column and record whether each
244 * physico-chemical property is conserved (+1), absence conserved (0),
245 * or not conserved (-1)
246 * Using TreeMap means properties are displayed in alphabetical order
248 SortedMap<String, Integer> resultHash = new TreeMap<String, Integer>();
249 SymbolCounts symbolCounts = values.getSymbolCounts();
250 char[] symbols = symbolCounts.symbols;
251 int[] counts = symbolCounts.values;
252 for (int j = 0; j < symbols.length; j++)
255 if (counts[j] > thresh)
257 recordConservation(resultHash, String.valueOf(c));
260 if (values.getGapCount() > thresh)
262 recordConservation(resultHash, "-");
265 if (total.length > 0)
267 total[column - start] = resultHash;
273 * Updates the conservation results for an observed residue
276 * a map of {property, conservation} where conservation value is +1
277 * (all residues have the property), 0 (no residue has the property)
278 * or -1 (some do, some don't)
281 protected static void recordConservation(Map<String, Integer> resultMap,
284 res = res.toUpperCase();
285 for (Entry<String, Map<String, Integer>> property : ResidueProperties.propHash
288 String propertyName = property.getKey();
289 Integer residuePropertyValue = property.getValue().get(res);
291 if (!resultMap.containsKey(propertyName))
294 * first time we've seen this residue - note whether it has this property
296 if (residuePropertyValue != null)
298 resultMap.put(propertyName, residuePropertyValue);
303 * unrecognised residue - use default value for property
305 resultMap.put(propertyName, property.getValue().get("-"));
310 Integer currentResult = resultMap.get(propertyName);
311 if (currentResult.intValue() != -1
312 && !currentResult.equals(residuePropertyValue))
315 * property is unconserved - residues seen both with and without it
317 resultMap.put(propertyName, Integer.valueOf(-1));
324 * Counts residues (upper-cased) and gaps in the given column
329 protected ResidueCount countResidues(int column)
331 ResidueCount values = new ResidueCount(false);
333 for (int row = 0; row < sequences.length; row++)
335 if (sequences[row].getLength() > column)
337 char c = sequences[row].getCharAt(column);
340 int index = ResidueProperties.aaIndex[c];
341 c = index > 20 ? '-' : ResidueProperties.aa[index].charAt(0);
347 if (Comparison.isGap(c))
365 * Counts conservation and gaps for a column of the alignment
367 * @return { 1 if fully conserved, else 0, gap count }
369 public int[] countConservationAndGaps(int column)
372 boolean fullyConserved = true;
373 int iSize = sequences.length;
377 return new int[] { 0, 0 };
381 for (int i = 0; i < iSize; i++)
383 if (column >= sequences[i].getLength())
389 char c = sequences[i].getCharAt(column); // gaps do not have upper/lower case
391 if (Comparison.isGap((c)))
404 fullyConserved = false;
409 int[] r = new int[] { fullyConserved ? 1 : 0, gapCount };
414 * Returns the upper-cased character if between 'a' and 'z', else the
420 char toUpperCase(char c)
422 if ('a' <= c && c <= 'z')
430 * Calculates the conservation sequence
432 * @param positiveOnly
433 * if true, calculate positive conservation; else calculate both
434 * positive and negative conservation
435 * @param maxPercentageGaps
436 * the percentage of gaps in a column, at or above which no
437 * conservation is asserted
439 public void verdict(boolean positiveOnly, float maxPercentageGaps)
441 // TODO call this at the end of calculate(), should not be a public method
443 StringBuilder consString = new StringBuilder(end);
445 // NOTE THIS SHOULD CHECK IF THE CONSEQUENCE ALREADY
446 // EXISTS AND NOT OVERWRITE WITH '-', BUT THIS CASE
447 // DOES NOT EXIST IN JALVIEW 2.1.2
448 for (int i = 0; i < start; i++)
450 consString.append('-');
452 consSymbs = new String[end - start + 1];
453 for (int i = start; i <= end; i++)
455 int[] gapcons = countConservationAndGaps(i);
456 boolean fullyConserved = gapcons[0] == 1;
457 int totGaps = gapcons[1];
458 float pgaps = (totGaps * 100f) / sequences.length;
460 if (maxPercentageGaps > pgaps)
462 Map<String, Integer> resultHash = total[i - start];
464 StringBuilder positives = new StringBuilder(64);
465 StringBuilder negatives = new StringBuilder(32);
466 for (String type : resultHash.keySet())
468 int result = resultHash.get(type).intValue();
472 * not conserved (present or absent)
480 * positively conserved property (all residues have it)
482 positives.append(positives.length() == 0 ? "" : " ");
483 positives.append(type);
485 if (result == 0 && !positiveOnly)
488 * absense of property is conserved (all residues lack it)
490 negatives.append(negatives.length() == 0 ? "" : " ");
491 negatives.append("!").append(type);
494 if (negatives.length() > 0)
496 positives.append(" ").append(negatives);
498 consSymbs[i - start] = positives.toString();
502 consString.append(count); // Conserved props!=Identity
506 consString.append(fullyConserved ? "*" : "+");
511 consString.append('-');
515 consSequence = new Sequence(name, consString.toString(), start, end);
521 * @return Conservation sequence
523 public SequenceI getConsSequence()
528 // From Alignment.java in jalview118
529 public void findQuality()
531 findQuality(0, maxLength - 1);
537 private void percentIdentity2()
539 seqNums = new Vector<int[]>();
541 int i = 0, iSize = sequences.length;
542 // Do we need to calculate this again?
543 for (i = 0; i < iSize; i++)
548 if ((cons2 == null) || seqNumsChanged)
550 cons2 = new int[maxLength][24];
552 // Initialize the array
553 for (int j = 0; j < 24; j++)
555 for (i = 0; i < maxLength; i++)
564 while (j < sequences.length)
566 sqnum = seqNums.elementAt(j);
568 for (i = 1; i < sqnum.length; i++)
570 cons2[i - 1][sqnum[i]]++;
573 for (i = sqnum.length - 1; i < maxLength; i++)
575 cons2[i][23]++; // gap count
584 * for (int i=start; i <= end; i++) { int max = -1000; int maxi = -1; int
587 * for (int j=0;j<24;j++) { if (cons2[i][j] > max) { max = cons2[i][j];
588 * maxi = i; maxj = j; } } }
594 * Calculates the quality of the set of sequences
601 public void findQuality(int startRes, int endRes)
603 quality = new Vector<Double>();
606 float[][] BLOSUM62 = ScoreModels.getInstance().getBlosum62()
609 // Loop over columns // JBPNote Profiling info
610 // long ts = System.currentTimeMillis();
611 // long te = System.currentTimeMillis();
614 int size = seqNums.size();
615 int[] lengths = new int[size];
616 double tot, bigtot, sr, tmp;
618 int l, j, i, ii, i2, k, seqNum;
620 for (l = 0; l < size; l++)
622 lengths[l] = seqNums.elementAt(l).length - 1;
625 for (j = startRes; j <= endRes; j++)
629 // First Xr = depends on column only
632 for (ii = 0; ii < 24; ii++)
636 for (i2 = 0; i2 < 24; i2++)
638 x[ii] += (((double) cons2[j][i2] * BLOSUM62[ii][i2]) + 4);
644 // Now calculate D for each position and sum
645 for (k = 0; k < size; k++)
649 seqNum = (j < lengths[k]) ? seqNums.elementAt(k)[j + 1] : 23; // Sequence,
654 // This is a loop over r
655 for (i = 0; i < 23; i++)
659 sr = (double) BLOSUM62[i][seqNum] + 4;
661 // Calculate X with another loop over residues
662 // System.out.println("Xi " + i + " " + x[i] + " " + sr);
665 tot += (xx[i] * xx[i]);
668 bigtot += Math.sqrt(tot);
671 // This is the quality for one column
677 // bigtot = bigtot * (size-cons2[j][23])/size;
678 quality.addElement(new Double(bigtot));
680 // Need to normalize by gaps
683 double newmax = -10000;
685 for (j = startRes; j <= endRes; j++)
687 tmp = quality.elementAt(j).doubleValue();
688 tmp = ((max - tmp) * (size - cons2[j][23])) / size;
690 // System.out.println(tmp+ " " + j);
691 quality.setElementAt(new Double(tmp), j);
699 // System.out.println("Quality " + s);
700 qualityRange[0] = 0D;
701 qualityRange[1] = newmax;
705 * Complete the given consensus and quuality annotation rows. Note: currently
706 * this method will enlarge the given annotation row if it is too small,
707 * otherwise will leave its length unchanged.
709 * @param conservation
710 * conservation annotation row
712 * (optional - may be null)
714 * first column for conservation
716 * extent of conservation
718 public void completeAnnotations(AlignmentAnnotation conservation,
719 AlignmentAnnotation quality2, int istart, int alWidth)
721 char[] sequence = getConsSequence().getSequence();
733 maxB = 0f - minB; // scalable range for colouring both Conservation and
743 if (conservation != null && conservation.annotations != null
744 && conservation.annotations.length < alWidth)
746 conservation.annotations = new Annotation[alWidth];
749 if (quality2 != null)
751 quality2.graphMax = (float) qualityRange[1];
752 if (quality2.annotations != null
753 && quality2.annotations.length < alWidth)
755 quality2.annotations = new Annotation[alWidth];
757 qmin = (float) qualityRange[0];
758 qmax = (float) qualityRange[1];
761 for (int i = istart; i < alWidth; i++)
767 if (Character.isDigit(c))
780 if (conservation != null)
782 float vprop = value - min;
784 int consp = i - start;
785 String conssym = (value > 0 && consp > -1 && consp < consSymbs.length) ? consSymbs[consp]
787 conservation.annotations[i] = new Annotation(String.valueOf(c),
788 conssym, ' ', value, new Color(minR + (maxR * vprop), minG
789 + (maxG * vprop), minB + (maxB * vprop)));
793 if (quality2 != null)
795 value = quality.elementAt(i).floatValue();
796 float vprop = value - qmin;
798 quality2.annotations[i] = new Annotation(" ",
799 String.valueOf(value), ' ', value, new Color(minR
800 + (maxR * vprop), minG + (maxG * vprop), minB
807 * construct and call the calculation methods on a new Conservation object
810 * - name of conservation
813 * first column in calculation window
815 * last column in calculation window
816 * @param positiveOnly
817 * calculate positive (true) or positive and negative (false)
819 * @param maxPercentGaps
820 * percentage of gaps tolerated in column
822 * flag indicating if alignment quality should be calculated
823 * @return Conservation object ready for use in visualization
825 public static Conservation calculateConservation(String name,
826 List<SequenceI> seqs, int start, int end, boolean positiveOnly,
827 int maxPercentGaps, boolean calcQuality)
829 Conservation cons = new Conservation(name, seqs, start, end);
831 cons.verdict(positiveOnly, maxPercentGaps);
842 * Returns the computed tooltip (annotation description) for a given column.
843 * The tip is empty if the conservation score is zero, otherwise holds the
844 * conserved properties (and, optionally, properties whose absence is
850 String getTooltip(int column)
852 char[] sequence = getConsSequence().getSequence();
853 char val = column < sequence.length ? sequence[column] : '-';
854 boolean hasConservation = val != '-' && val != '0';
855 int consp = column - start;
856 String tip = (hasConservation && consp > -1 && consp < consSymbs.length) ? consSymbs[consp]