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.ResidueCount.SymbolCounts;
24 import jalview.datamodel.AlignmentAnnotation;
25 import jalview.datamodel.Annotation;
26 import jalview.datamodel.Sequence;
27 import jalview.datamodel.SequenceI;
28 import jalview.schemes.ResidueProperties;
29 import jalview.util.Comparison;
31 import java.awt.Color;
32 import java.util.List;
34 import java.util.Map.Entry;
35 import java.util.TreeMap;
36 import java.util.Vector;
39 * Calculates conservation values for a given set of sequences
44 public class Conservation
46 private static final int TOUPPERCASE = 'a' - 'A';
48 SequenceI[] sequences;
54 Vector<int[]> seqNums; // vector of int vectors where first is sequence
57 int maxLength = 0; // used by quality calcs
59 boolean seqNumsChanged = false; // updated after any change via calcSeqNum;
62 * a map per column with {property, conservation} where conservation value is
63 * 1 (property is conserved), 0 (property is negatively conserved) or -1
64 * (property is not conserved i.e. column has residues with and without it)
66 Map<String, Integer>[] total;
68 boolean canonicaliseAa = true; // if true then conservation calculation will
70 // map all symbols to canonical aa numbering
71 // rather than consider conservation of that
74 /** Stores calculated quality values */
75 private Vector<Double> quality;
77 /** Stores maximum and minimum values of quality values */
78 private double[] qualityRange = new double[2];
80 private Sequence consSequence;
83 * percentage of residues in a column to qualify for counting conservation
85 private int threshold;
87 private String name = "";
89 private int[][] cons2;
91 private String[] consSymbs;
94 * Creates a new Conservation object.
97 * Name of conservation
99 * to count the residues in residueHash(). commonly used value is 3
101 * sequences to be used in calculation
103 * start residue position
105 * end residue position
107 public Conservation(String name, int threshold,
108 List<SequenceI> sequences, int start, int end)
111 this.threshold = threshold;
115 maxLength = end - start + 1; // default width includes bounds of
118 int s, sSize = sequences.size();
119 SequenceI[] sarray = new SequenceI[sSize];
120 this.sequences = sarray;
123 for (s = 0; s < sSize; s++)
125 sarray[s] = sequences.get(s);
126 if (sarray[s].getLength() > maxLength)
128 maxLength = sarray[s].getLength();
131 } catch (ArrayIndexOutOfBoundsException ex)
133 // bail - another thread has modified the sequence array, so the current
134 // calculation is probably invalid.
135 this.sequences = new SequenceI[0];
141 * Translate sequence i into a numerical representation and store it in the
142 * i'th position of the seqNums array.
146 private void calcSeqNum(int i)
148 String sq = null; // for dumb jbuilder not-inited exception warning
151 int sSize = sequences.length;
153 if ((i > -1) && (i < sSize))
155 sq = sequences[i].getSequenceAsString();
157 if (seqNums.size() <= i)
159 seqNums.addElement(new int[sq.length() + 1]);
162 if (sq.hashCode() != seqNums.elementAt(i)[0])
166 seqNumsChanged = true;
174 sqnum = new int[len + 1]; // better to always make a new array -
175 // sequence can change its length
176 sqnum[0] = sq.hashCode();
178 for (j = 1; j <= len; j++)
180 sqnum[j] = jalview.schemes.ResidueProperties.aaIndex[sq
184 seqNums.setElementAt(sqnum, i);
188 System.out.println("SEQUENCE HAS BEEN DELETED!!!");
193 // JBPNote INFO level debug
195 .println("ERROR: calcSeqNum called with out of range sequence index for Alignment\n");
200 * Calculates the conservation values for given set of sequences
202 public void calculate()
204 int height = sequences.length;
206 total = new Map[maxLength];
208 for (int column = start; column <= end; column++)
210 ResidueCount values = countResidues(column);
212 // TODO is threshold a percentage or count value?
213 int thresh = (threshold * height) / 100;
216 * check observed residues in column and record whether each
217 * physico-chemical property is conserved (+1), negatively conserved (0),
218 * or not conserved (-1)
219 * Using TreeMap means properties are displayed in alphabetical order
221 Map<String, Integer> resultHash = new TreeMap<String, Integer>();
222 SymbolCounts symbolCounts = values.getSymbolCounts();
223 char[] symbols = symbolCounts.symbols;
224 int[] counts = symbolCounts.values;
225 for (int j = 0; j < symbols.length; j++)
228 if (counts[j] > thresh)
230 recordConservation(resultHash, String.valueOf(c));
233 if (values.getGapCount() > thresh)
235 recordConservation(resultHash, "-");
238 if (total.length > 0)
240 total[column - start] = resultHash;
246 * Updates the conservation results for an observed residue
249 * a map of {property, conservation} where conservation value is +1
250 * (all residues have the property), 0 (no residue has the property)
251 * or -1 (some do, some don't)
254 protected static void recordConservation(Map<String, Integer> resultMap,
257 res = res.toUpperCase();
258 for (Entry<String, Map<String, Integer>> property : ResidueProperties.propHash
261 String propertyName = property.getKey();
262 Integer residuePropertyValue = property.getValue().get(res);
264 if (!resultMap.containsKey(propertyName))
267 * first time we've seen this residue - note whether it has this property
269 if (residuePropertyValue != null)
271 resultMap.put(propertyName, residuePropertyValue);
276 * unrecognised residue - use default value for property
278 resultMap.put(propertyName, property.getValue().get("-"));
283 Integer currentResult = resultMap.get(propertyName);
284 if (currentResult.intValue() != -1
285 && !currentResult.equals(residuePropertyValue))
288 * property is unconserved - residues seen both with and without it
290 resultMap.put(propertyName, Integer.valueOf(-1));
297 * Counts residues (upper-cased) and gaps in the given column
302 protected ResidueCount countResidues(int column)
304 ResidueCount values = new ResidueCount(false);
306 for (int row = 0; row < sequences.length; row++)
308 if (sequences[row].getLength() > column)
310 char c = sequences[row].getCharAt(column);
313 int index = ResidueProperties.aaIndex[c];
314 c = index > 20 ? '-' : ResidueProperties.aa[index].charAt(0);
320 if (Comparison.isGap(c))
338 * Counts conservation and gaps for a column of the alignment
340 * @return { 1 if fully conserved, else 0, gap count }
342 public int[] countConservationAndGaps(int column)
345 boolean fullyConserved = true;
346 int iSize = sequences.length;
350 return new int[] { 0, 0 };
354 for (int i = 0; i < iSize; i++)
356 if (column >= sequences[i].getLength())
362 char c = sequences[i].getCharAt(column); // gaps do not have upper/lower case
364 if (Comparison.isGap((c)))
377 fullyConserved = false;
382 int[] r = new int[] { fullyConserved ? 1 : 0, gapCount };
387 * Returns the upper-cased character if between 'a' and 'z', else the
393 char toUpperCase(char c)
395 if ('a' <= c && c <= 'z')
403 * Calculates the conservation sequence
405 * @param positiveOnly
406 * if true, calculate positive conservation; else calculate both
407 * positive and negative conservation
408 * @param maxPercentageGaps
409 * the percentage of gaps in a column, at or above which no
410 * conservation is asserted
412 public void verdict(boolean positiveOnly, float maxPercentageGaps)
414 // TODO call this at the end of calculate(), should not be a public method
416 StringBuilder consString = new StringBuilder(end);
418 // NOTE THIS SHOULD CHECK IF THE CONSEQUENCE ALREADY
419 // EXISTS AND NOT OVERWRITE WITH '-', BUT THIS CASE
420 // DOES NOT EXIST IN JALVIEW 2.1.2
421 for (int i = 0; i < start; i++)
423 consString.append('-');
425 consSymbs = new String[end - start + 1];
426 for (int i = start; i <= end; i++)
428 int[] gapcons = countConservationAndGaps(i);
429 boolean fullyConserved = gapcons[0] == 1;
430 int totGaps = gapcons[1];
431 float pgaps = (totGaps * 100f) / sequences.length;
433 if (maxPercentageGaps > pgaps)
435 Map<String, Integer> resultHash = total[i - start];
437 StringBuilder positives = new StringBuilder(64);
438 StringBuilder negatives = new StringBuilder(32);
439 for (String type : resultHash.keySet())
441 int result = resultHash.get(type).intValue();
445 * not conserved either positively or negatively
453 * positively conserved property (all residues have it)
455 positives.append(positives.length() == 0 ? "" : " ");
456 positives.append(type);
458 if (result == 0 && !positiveOnly)
461 * negatively conserved property (all residues lack it)
463 negatives.append(negatives.length() == 0 ? "" : " ");
464 negatives.append("!").append(type);
467 if (negatives.length() > 0)
469 positives.append(" ").append(negatives);
471 consSymbs[i - start] = positives.toString();
475 consString.append(count); // Conserved props!=Identity
479 consString.append(fullyConserved ? "*" : "+");
484 consString.append('-');
488 consSequence = new Sequence(name, consString.toString(), start, end);
494 * @return Conservation sequence
496 public Sequence getConsSequence()
501 // From Alignment.java in jalview118
502 public void findQuality()
504 findQuality(0, maxLength - 1);
510 private void percentIdentity2()
512 seqNums = new Vector<int[]>();
514 int i = 0, iSize = sequences.length;
515 // Do we need to calculate this again?
516 for (i = 0; i < iSize; i++)
521 if ((cons2 == null) || seqNumsChanged)
523 cons2 = new int[maxLength][24];
525 // Initialize the array
526 for (int j = 0; j < 24; j++)
528 for (i = 0; i < maxLength; i++)
537 while (j < sequences.length)
539 sqnum = seqNums.elementAt(j);
541 for (i = 1; i < sqnum.length; i++)
543 cons2[i - 1][sqnum[i]]++;
546 for (i = sqnum.length - 1; i < maxLength; i++)
548 cons2[i][23]++; // gap count
557 * for (int i=start; i <= end; i++) { int max = -1000; int maxi = -1; int
560 * for (int j=0;j<24;j++) { if (cons2[i][j] > max) { max = cons2[i][j];
561 * maxi = i; maxj = j; } } }
567 * Calculates the quality of the set of sequences
574 public void findQuality(int startRes, int endRes)
576 quality = new Vector<Double>();
579 int[][] BLOSUM62 = ResidueProperties.getBLOSUM62();
581 // Loop over columns // JBPNote Profiling info
582 // long ts = System.currentTimeMillis();
583 // long te = System.currentTimeMillis();
586 int size = seqNums.size();
587 int[] lengths = new int[size];
588 double tot, bigtot, sr, tmp;
590 int l, j, i, ii, i2, k, seqNum;
592 for (l = 0; l < size; l++)
594 lengths[l] = seqNums.elementAt(l).length - 1;
597 for (j = startRes; j <= endRes; j++)
601 // First Xr = depends on column only
604 for (ii = 0; ii < 24; ii++)
608 for (i2 = 0; i2 < 24; i2++)
610 x[ii] += (((double) cons2[j][i2] * BLOSUM62[ii][i2]) + 4);
616 // Now calculate D for each position and sum
617 for (k = 0; k < size; k++)
621 seqNum = (j < lengths[k]) ? seqNums.elementAt(k)[j + 1] : 23; // Sequence,
626 // This is a loop over r
627 for (i = 0; i < 23; i++)
631 sr = (double) BLOSUM62[i][seqNum] + 4;
633 // Calculate X with another loop over residues
634 // System.out.println("Xi " + i + " " + x[i] + " " + sr);
637 tot += (xx[i] * xx[i]);
640 bigtot += Math.sqrt(tot);
643 // This is the quality for one column
649 // bigtot = bigtot * (size-cons2[j][23])/size;
650 quality.addElement(new Double(bigtot));
652 // Need to normalize by gaps
655 double newmax = -10000;
657 for (j = startRes; j <= endRes; j++)
659 tmp = quality.elementAt(j).doubleValue();
660 tmp = ((max - tmp) * (size - cons2[j][23])) / size;
662 // System.out.println(tmp+ " " + j);
663 quality.setElementAt(new Double(tmp), j);
671 // System.out.println("Quality " + s);
672 qualityRange[0] = 0D;
673 qualityRange[1] = newmax;
677 * Complete the given consensus and quuality annotation rows. Note: currently
678 * this method will enlarge the given annotation row if it is too small,
679 * otherwise will leave its length unchanged.
681 * @param conservation
682 * conservation annotation row
684 * (optional - may be null)
686 * first column for conservation
688 * extent of conservation
690 public void completeAnnotations(AlignmentAnnotation conservation,
691 AlignmentAnnotation quality2, int istart, int alWidth)
693 char[] sequence = getConsSequence().getSequence();
705 maxB = 0f - minB; // scalable range for colouring both Conservation and
715 if (conservation != null && conservation.annotations != null
716 && conservation.annotations.length < alWidth)
718 conservation.annotations = new Annotation[alWidth];
721 if (quality2 != null)
723 quality2.graphMax = (float) qualityRange[1];
724 if (quality2.annotations != null
725 && quality2.annotations.length < alWidth)
727 quality2.annotations = new Annotation[alWidth];
729 qmin = (float) qualityRange[0];
730 qmax = (float) qualityRange[1];
733 for (int i = istart; i < alWidth; i++)
739 if (Character.isDigit(c))
752 if (conservation != null)
754 float vprop = value - min;
756 int consp = i - start;
757 String conssym = (value > 0 && consp > -1 && consp < consSymbs.length) ? consSymbs[consp]
759 conservation.annotations[i] = new Annotation(String.valueOf(c),
760 conssym, ' ', value, new Color(minR + (maxR * vprop), minG
761 + (maxG * vprop), minB + (maxB * vprop)));
765 if (quality2 != null)
767 value = quality.elementAt(i).floatValue();
768 float vprop = value - qmin;
770 quality2.annotations[i] = new Annotation(" ",
771 String.valueOf(value), ' ', value, new Color(minR
772 + (maxR * vprop), minG + (maxG * vprop), minB
779 * construct and call the calculation methods on a new Conservation object
782 * - name of conservation
784 * - minimum number of conserved residues needed to indicate
785 * conservation (typically 3)
788 * first column in calculation window
790 * last column in calculation window
791 * @param positiveOnly
792 * calculate positive (true) or positive and negative (false)
794 * @param maxPercentGaps
795 * percentage of gaps tolerated in column
797 * flag indicating if alignment quality should be calculated
798 * @return Conservation object ready for use in visualization
800 public static Conservation calculateConservation(String name,
801 int threshold, List<SequenceI> seqs, int start, int end,
802 boolean positiveOnly, int maxPercentGaps, boolean calcQuality)
804 Conservation cons = new Conservation(name, threshold, seqs, start, end);
806 cons.verdict(positiveOnly, maxPercentGaps);
817 * Returns the computed tooltip (annotation description) for a given column.
818 * The tip is empty if the conservation score is zero, otherwise holds the
819 * positively (and, optionally, negatively) conserved properties.
824 String getTooltip(int column)
826 char[] sequence = getConsSequence().getSequence();
827 char val = column < sequence.length ? sequence[column] : '-';
828 boolean hasConservation = val != '-' && val != '0';
829 int consp = column - start;
830 String tip = (hasConservation && consp > -1 && consp < consSymbs.length) ? consSymbs[consp]