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.SortedMap;
37 import java.util.TreeMap;
38 import java.util.Vector;
41 * Calculates conservation values for a given set of sequences
43 public class Conservation
46 * need to have a minimum of 3% of sequences with a residue
47 * for it to be included in the conservation calculation
49 private static final int THRESHOLD_PERCENT = 3;
51 private static final int TOUPPERCASE = 'a' - 'A';
53 SequenceI[] sequences;
59 Vector<int[]> seqNums; // vector of int vectors where first is sequence
62 int maxLength = 0; // used by quality calcs
64 boolean seqNumsChanged = false; // updated after any change via calcSeqNum;
67 * a map per column with {property, conservation} where conservation value is
68 * 1 (property is conserved), 0 (absence of property is conserved) or -1
69 * (property is not conserved i.e. column has residues with and without it)
71 Map<String, Integer>[] total;
73 boolean canonicaliseAa = true; // if true then conservation calculation will
75 // map all symbols to canonical aa numbering
76 // rather than consider conservation of that
79 /** Stores calculated quality values */
80 private Vector<Double> quality;
82 /** Stores maximum and minimum values of quality values */
83 private double[] qualityRange = new double[2];
85 private Sequence consSequence;
88 * percentage of residues in a column to qualify for counting conservation
90 private int threshold;
92 private String name = "";
94 private int[][] cons2;
96 private String[] consSymbs;
99 * Constructor using default threshold of 3%
102 * Name of conservation
104 * sequences to be used in calculation
106 * start residue position
108 * end residue position
110 public Conservation(String name, List<SequenceI> sequences, int start,
113 this(name, THRESHOLD_PERCENT, sequences, start, end);
120 * Name of conservation
122 * percentage of sequences at or below which property conservation is
125 * sequences to be used in calculation
127 * start column position
129 * end column position
131 public Conservation(String name, int threshold,
132 List<SequenceI> sequences, int start, int end)
135 this.threshold = threshold;
139 maxLength = end - start + 1; // default width includes bounds of
142 int s, sSize = sequences.size();
143 SequenceI[] sarray = new SequenceI[sSize];
144 this.sequences = sarray;
147 for (s = 0; s < sSize; s++)
149 sarray[s] = sequences.get(s);
150 if (sarray[s].getLength() > maxLength)
152 maxLength = sarray[s].getLength();
155 } catch (ArrayIndexOutOfBoundsException ex)
157 // bail - another thread has modified the sequence array, so the current
158 // calculation is probably invalid.
159 this.sequences = new SequenceI[0];
165 * Translate sequence i into a numerical representation and store it in the
166 * i'th position of the seqNums array.
170 private void calcSeqNum(int i)
172 String sq = null; // for dumb jbuilder not-inited exception warning
175 int sSize = sequences.length;
177 if ((i > -1) && (i < sSize))
179 sq = sequences[i].getSequenceAsString();
181 if (seqNums.size() <= i)
183 seqNums.addElement(new int[sq.length() + 1]);
186 if (sq.hashCode() != seqNums.elementAt(i)[0])
190 seqNumsChanged = true;
198 sqnum = new int[len + 1]; // better to always make a new array -
199 // sequence can change its length
200 sqnum[0] = sq.hashCode();
202 for (j = 1; j <= len; j++)
204 sqnum[j] = jalview.schemes.ResidueProperties.aaIndex[sq
208 seqNums.setElementAt(sqnum, i);
212 System.out.println("SEQUENCE HAS BEEN DELETED!!!");
217 // JBPNote INFO level debug
219 .println("ERROR: calcSeqNum called with out of range sequence index for Alignment\n");
224 * Calculates the conservation values for given set of sequences
226 public void calculate()
228 int height = sequences.length;
230 total = new Map[maxLength];
232 for (int column = start; column <= end; column++)
234 ResidueCount values = countResidues(column);
237 * percentage count at or below which we ignore residues
239 int thresh = (threshold * height) / 100;
242 * check observed residues in column and record whether each
243 * physico-chemical property is conserved (+1), absence conserved (0),
244 * or not conserved (-1)
245 * Using TreeMap means properties are displayed in alphabetical order
247 SortedMap<String, Integer> resultHash = new TreeMap<String, Integer>();
248 SymbolCounts symbolCounts = values.getSymbolCounts();
249 char[] symbols = symbolCounts.symbols;
250 int[] counts = symbolCounts.values;
251 for (int j = 0; j < symbols.length; j++)
254 if (counts[j] > thresh)
256 recordConservation(resultHash, String.valueOf(c));
259 if (values.getGapCount() > thresh)
261 recordConservation(resultHash, "-");
264 if (total.length > 0)
266 total[column - start] = resultHash;
272 * Updates the conservation results for an observed residue
275 * a map of {property, conservation} where conservation value is +1
276 * (all residues have the property), 0 (no residue has the property)
277 * or -1 (some do, some don't)
280 protected static void recordConservation(Map<String, Integer> resultMap,
283 res = res.toUpperCase();
284 for (Entry<String, Map<String, Integer>> property : ResidueProperties.propHash
287 String propertyName = property.getKey();
288 Integer residuePropertyValue = property.getValue().get(res);
290 if (!resultMap.containsKey(propertyName))
293 * first time we've seen this residue - note whether it has this property
295 if (residuePropertyValue != null)
297 resultMap.put(propertyName, residuePropertyValue);
302 * unrecognised residue - use default value for property
304 resultMap.put(propertyName, property.getValue().get("-"));
309 Integer currentResult = resultMap.get(propertyName);
310 if (currentResult.intValue() != -1
311 && !currentResult.equals(residuePropertyValue))
314 * property is unconserved - residues seen both with and without it
316 resultMap.put(propertyName, Integer.valueOf(-1));
323 * Counts residues (upper-cased) and gaps in the given column
328 protected ResidueCount countResidues(int column)
330 ResidueCount values = new ResidueCount(false);
332 for (int row = 0; row < sequences.length; row++)
334 if (sequences[row].getLength() > column)
336 char c = sequences[row].getCharAt(column);
339 int index = ResidueProperties.aaIndex[c];
340 c = index > 20 ? '-' : ResidueProperties.aa[index].charAt(0);
346 if (Comparison.isGap(c))
364 * Counts conservation and gaps for a column of the alignment
366 * @return { 1 if fully conserved, else 0, gap count }
368 public int[] countConservationAndGaps(int column)
371 boolean fullyConserved = true;
372 int iSize = sequences.length;
376 return new int[] { 0, 0 };
380 for (int i = 0; i < iSize; i++)
382 if (column >= sequences[i].getLength())
388 char c = sequences[i].getCharAt(column); // gaps do not have upper/lower case
390 if (Comparison.isGap((c)))
403 fullyConserved = false;
408 int[] r = new int[] { fullyConserved ? 1 : 0, gapCount };
413 * Returns the upper-cased character if between 'a' and 'z', else the
419 char toUpperCase(char c)
421 if ('a' <= c && c <= 'z')
429 * Calculates the conservation sequence
431 * @param positiveOnly
432 * if true, calculate positive conservation; else calculate both
433 * positive and negative conservation
434 * @param maxPercentageGaps
435 * the percentage of gaps in a column, at or above which no
436 * conservation is asserted
438 public void verdict(boolean positiveOnly, float maxPercentageGaps)
440 // TODO call this at the end of calculate(), should not be a public method
442 StringBuilder consString = new StringBuilder(end);
444 // NOTE THIS SHOULD CHECK IF THE CONSEQUENCE ALREADY
445 // EXISTS AND NOT OVERWRITE WITH '-', BUT THIS CASE
446 // DOES NOT EXIST IN JALVIEW 2.1.2
447 for (int i = 0; i < start; i++)
449 consString.append('-');
451 consSymbs = new String[end - start + 1];
452 for (int i = start; i <= end; i++)
454 int[] gapcons = countConservationAndGaps(i);
455 boolean fullyConserved = gapcons[0] == 1;
456 int totGaps = gapcons[1];
457 float pgaps = (totGaps * 100f) / sequences.length;
459 if (maxPercentageGaps > pgaps)
461 Map<String, Integer> resultHash = total[i - start];
463 StringBuilder positives = new StringBuilder(64);
464 StringBuilder negatives = new StringBuilder(32);
465 for (String type : resultHash.keySet())
467 int result = resultHash.get(type).intValue();
471 * not conserved (present or absent)
479 * positively conserved property (all residues have it)
481 positives.append(positives.length() == 0 ? "" : " ");
482 positives.append(type);
484 if (result == 0 && !positiveOnly)
487 * absense of property is conserved (all residues lack it)
489 negatives.append(negatives.length() == 0 ? "" : " ");
490 negatives.append("!").append(type);
493 if (negatives.length() > 0)
495 positives.append(" ").append(negatives);
497 consSymbs[i - start] = positives.toString();
501 consString.append(count); // Conserved props!=Identity
505 consString.append(fullyConserved ? "*" : "+");
510 consString.append('-');
514 consSequence = new Sequence(name, consString.toString(), start, end);
520 * @return Conservation sequence
522 public SequenceI getConsSequence()
527 // From Alignment.java in jalview118
528 public void findQuality()
530 findQuality(0, maxLength - 1);
536 private void percentIdentity2()
538 seqNums = new Vector<int[]>();
540 int i = 0, iSize = sequences.length;
541 // Do we need to calculate this again?
542 for (i = 0; i < iSize; i++)
547 if ((cons2 == null) || seqNumsChanged)
549 cons2 = new int[maxLength][24];
551 // Initialize the array
552 for (int j = 0; j < 24; j++)
554 for (i = 0; i < maxLength; i++)
563 while (j < sequences.length)
565 sqnum = seqNums.elementAt(j);
567 for (i = 1; i < sqnum.length; i++)
569 cons2[i - 1][sqnum[i]]++;
572 for (i = sqnum.length - 1; i < maxLength; i++)
574 cons2[i][23]++; // gap count
583 * for (int i=start; i <= end; i++) { int max = -1000; int maxi = -1; int
586 * for (int j=0;j<24;j++) { if (cons2[i][j] > max) { max = cons2[i][j];
587 * maxi = i; maxj = j; } } }
593 * Calculates the quality of the set of sequences
600 public void findQuality(int startRes, int endRes)
602 quality = new Vector<Double>();
605 int[][] BLOSUM62 = ResidueProperties.getBLOSUM62();
607 // Loop over columns // JBPNote Profiling info
608 // long ts = System.currentTimeMillis();
609 // long te = System.currentTimeMillis();
612 int size = seqNums.size();
613 int[] lengths = new int[size];
614 double tot, bigtot, sr, tmp;
616 int l, j, i, ii, i2, k, seqNum;
618 for (l = 0; l < size; l++)
620 lengths[l] = seqNums.elementAt(l).length - 1;
623 for (j = startRes; j <= endRes; j++)
627 // First Xr = depends on column only
630 for (ii = 0; ii < 24; ii++)
634 for (i2 = 0; i2 < 24; i2++)
636 x[ii] += (((double) cons2[j][i2] * BLOSUM62[ii][i2]) + 4);
642 // Now calculate D for each position and sum
643 for (k = 0; k < size; k++)
647 seqNum = (j < lengths[k]) ? seqNums.elementAt(k)[j + 1] : 23; // Sequence,
652 // This is a loop over r
653 for (i = 0; i < 23; i++)
657 sr = (double) BLOSUM62[i][seqNum] + 4;
659 // Calculate X with another loop over residues
660 // System.out.println("Xi " + i + " " + x[i] + " " + sr);
663 tot += (xx[i] * xx[i]);
666 bigtot += Math.sqrt(tot);
669 // This is the quality for one column
675 // bigtot = bigtot * (size-cons2[j][23])/size;
676 quality.addElement(new Double(bigtot));
678 // Need to normalize by gaps
681 double newmax = -10000;
683 for (j = startRes; j <= endRes; j++)
685 tmp = quality.elementAt(j).doubleValue();
686 tmp = ((max - tmp) * (size - cons2[j][23])) / size;
688 // System.out.println(tmp+ " " + j);
689 quality.setElementAt(new Double(tmp), j);
697 // System.out.println("Quality " + s);
698 qualityRange[0] = 0D;
699 qualityRange[1] = newmax;
703 * Complete the given consensus and quuality annotation rows. Note: currently
704 * this method will enlarge the given annotation row if it is too small,
705 * otherwise will leave its length unchanged.
707 * @param conservation
708 * conservation annotation row
710 * (optional - may be null)
712 * first column for conservation
714 * extent of conservation
716 public void completeAnnotations(AlignmentAnnotation conservation,
717 AlignmentAnnotation quality2, int istart, int alWidth)
719 char[] sequence = getConsSequence().getSequence();
731 maxB = 0f - minB; // scalable range for colouring both Conservation and
741 if (conservation != null && conservation.annotations != null
742 && conservation.annotations.length < alWidth)
744 conservation.annotations = new Annotation[alWidth];
747 if (quality2 != null)
749 quality2.graphMax = (float) qualityRange[1];
750 if (quality2.annotations != null
751 && quality2.annotations.length < alWidth)
753 quality2.annotations = new Annotation[alWidth];
755 qmin = (float) qualityRange[0];
756 qmax = (float) qualityRange[1];
759 for (int i = istart; i < alWidth; i++)
765 if (Character.isDigit(c))
778 if (conservation != null)
780 float vprop = value - min;
782 int consp = i - start;
783 String conssym = (value > 0 && consp > -1 && consp < consSymbs.length) ? consSymbs[consp]
785 conservation.annotations[i] = new Annotation(String.valueOf(c),
786 conssym, ' ', value, new Color(minR + (maxR * vprop), minG
787 + (maxG * vprop), minB + (maxB * vprop)));
791 if (quality2 != null)
793 value = quality.elementAt(i).floatValue();
794 float vprop = value - qmin;
796 quality2.annotations[i] = new Annotation(" ",
797 String.valueOf(value), ' ', value, new Color(minR
798 + (maxR * vprop), minG + (maxG * vprop), minB
805 * construct and call the calculation methods on a new Conservation object
808 * - name of conservation
811 * first column in calculation window
813 * last column in calculation window
814 * @param positiveOnly
815 * calculate positive (true) or positive and negative (false)
817 * @param maxPercentGaps
818 * percentage of gaps tolerated in column
820 * flag indicating if alignment quality should be calculated
821 * @return Conservation object ready for use in visualization
823 public static Conservation calculateConservation(String name,
824 List<SequenceI> seqs, int start, int end, boolean positiveOnly,
825 int maxPercentGaps, boolean calcQuality)
827 Conservation cons = new Conservation(name, seqs, start, end);
829 cons.verdict(positiveOnly, maxPercentGaps);
840 * Returns the computed tooltip (annotation description) for a given column.
841 * The tip is empty if the conservation score is zero, otherwise holds the
842 * conserved properties (and, optionally, properties whose absence is
848 String getTooltip(int column)
850 char[] sequence = getConsSequence().getSequence();
851 char val = column < sequence.length ? sequence[column] : '-';
852 boolean hasConservation = val != '-' && val != '0';
853 int consp = column - start;
854 String tip = (hasConservation && consp > -1 && consp < consSymbs.length) ? consSymbs[consp]