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.Sequence;
26 import jalview.datamodel.SequenceI;
27 import jalview.schemes.ResidueProperties;
29 import java.awt.Color;
30 import java.util.Hashtable;
31 import java.util.List;
33 import java.util.Vector;
36 * Calculates conservation values for a given set of sequences
41 public class Conservation
43 SequenceI[] sequences;
49 Vector<int[]> seqNums; // vector of int vectors where first is sequence
52 int maxLength = 0; // used by quality calcs
54 boolean seqNumsChanged = false; // updated after any change via calcSeqNum;
56 Map<String, Integer>[] total;
58 boolean canonicaliseAa = true; // if true then conservation calculation will
60 // map all symbols to canonical aa numbering
61 // rather than consider conservation of that
64 /** Stores calculated quality values */
65 private Vector<Double> quality;
67 /** Stores maximum and minimum values of quality values */
68 private double[] qualityRange = new double[2];
70 private Sequence consSequence;
72 private int threshold;
74 private String name = "";
76 private int[][] cons2;
78 private String[] consSymbs;
81 * Creates a new Conservation object.
84 * Name of conservation
86 * to count the residues in residueHash(). commonly used value is 3
88 * sequences to be used in calculation
90 * start residue position
92 * end residue position
94 public Conservation(String name, int threshold,
95 List<SequenceI> sequences, int start, int end)
98 this.threshold = threshold;
102 maxLength = end - start + 1; // default width includes bounds of
105 int s, sSize = sequences.size();
106 SequenceI[] sarray = new SequenceI[sSize];
107 this.sequences = sarray;
110 for (s = 0; s < sSize; s++)
112 sarray[s] = sequences.get(s);
113 if (sarray[s].getLength() > maxLength)
115 maxLength = sarray[s].getLength();
118 } catch (ArrayIndexOutOfBoundsException ex)
120 // bail - another thread has modified the sequence array, so the current
121 // calculation is probably invalid.
122 this.sequences = new SequenceI[0];
128 * Translate sequence i into a numerical representation and store it in the
129 * i'th position of the seqNums array.
133 private void calcSeqNum(int i)
135 String sq = null; // for dumb jbuilder not-inited exception warning
138 int sSize = sequences.length;
140 if ((i > -1) && (i < sSize))
142 sq = sequences[i].getSequenceAsString();
144 if (seqNums.size() <= i)
146 seqNums.addElement(new int[sq.length() + 1]);
149 if (sq.hashCode() != seqNums.elementAt(i)[0])
153 seqNumsChanged = true;
161 sqnum = new int[len + 1]; // better to always make a new array -
162 // sequence can change its length
163 sqnum[0] = sq.hashCode();
165 for (j = 1; j <= len; j++)
167 sqnum[j] = jalview.schemes.ResidueProperties.aaIndex[sq
171 seqNums.setElementAt(sqnum, i);
175 System.out.println("SEQUENCE HAS BEEN DELETED!!!");
180 // JBPNote INFO level debug
182 .println("ERROR: calcSeqNum called with out of range sequence index for Alignment\n");
187 * Calculates the conservation values for given set of sequences
189 public void calculate()
191 int thresh, j, jSize = sequences.length;
192 int[] values; // Replaces residueHash
195 total = new Hashtable[maxLength];
197 for (int i = start; i <= end; i++)
199 values = new int[255];
201 for (j = 0; j < jSize; j++)
203 if (sequences[j].getLength() > i)
205 c = sequences[j].getCharAt(i);
208 { // lookup the base aa code symbol
209 c = (char) ResidueProperties.aaIndex[sequences[j].getCharAt(i)];
216 // recover canonical aa symbol
217 c = ResidueProperties.aa[c].charAt(0);
222 // original behaviour - operate on ascii symbols directly
223 // No need to check if its a '-'
224 if (c == '.' || c == ' ')
239 // What is the count threshold to count the residues in residueHash()
240 thresh = (threshold * (jSize)) / 100;
242 // loop over all the found residues
243 Hashtable<String, Integer> resultHash = new Hashtable<String, Integer>();
244 for (char v = '-'; v < 'Z'; v++)
247 if (values[v] > thresh)
249 String res = String.valueOf(v);
251 // Now loop over the properties
252 for (String type : ResidueProperties.propHash.keySet())
254 Hashtable<String, Integer> ht = (Hashtable<String, Integer>) ResidueProperties.propHash
257 // Have we ticked this before?
258 if (!resultHash.containsKey(type))
260 if (ht.containsKey(res))
262 resultHash.put(type, ht.get(res));
266 resultHash.put(type, ht.get("-"));
269 else if (!resultHash.get(type).equals(ht.get(res)))
271 resultHash.put(type, new Integer(-1));
277 if (total.length > 0)
279 total[i - start] = resultHash;
284 /*****************************************************************************
285 * count conservation for the j'th column of the alignment
287 * @return { gap count, conserved residue count}
289 public int[] countConsNGaps(int j)
294 int[] r = new int[2];
296 int i, iSize = sequences.length;
299 for (i = 0; i < iSize; i++)
301 if (j >= sequences[i].getLength())
307 c = sequences[i].getCharAt(j); // gaps do not have upper/lower case
309 if (jalview.util.Comparison.isGap((c)))
330 r[0] = (nres == cons) ? 1 : 0;
337 * Returns the upper-cased character if between 'a' and 'z', else the
343 char toUpperCase(char c)
345 if ('a' <= c && c <= 'z')
347 c -= (32); // 32 = 'a' - 'A'
353 * Calculates the conservation sequence
356 * if true, positive conservation; false calculates negative
358 * @param percentageGaps
359 * commonly used value is 25
361 public void verdict(boolean consflag, float percentageGaps)
363 StringBuffer consString = new StringBuffer();
365 // NOTE THIS SHOULD CHECK IF THE CONSEQUENCE ALREADY
366 // EXISTS AND NOT OVERWRITE WITH '-', BUT THIS CASE
367 // DOES NOT EXIST IN JALVIEW 2.1.2
368 for (int i = 0; i < start; i++)
370 consString.append('-');
372 consSymbs = new String[end - start + 1];
373 for (int i = start; i <= end; i++)
375 int[] gapcons = countConsNGaps(i);
376 int totGaps = gapcons[1];
377 float pgaps = ((float) totGaps * 100) / sequences.length;
378 consSymbs[i - start] = new String();
380 if (percentageGaps > pgaps)
382 Map<String, Integer> resultHash = total[i - start];
383 // Now find the verdict
385 for (String type : resultHash.keySet())
387 int result = resultHash.get(type).intValue();
388 // Do we want to count +ve conservation or +ve and -ve cons.?
393 consSymbs[i - start] = type + " " + consSymbs[i - start];
403 consSymbs[i - start] = consSymbs[i - start] + " !" + type;
407 consSymbs[i - start] = type + " " + consSymbs[i - start];
416 consString.append(count); // Conserved props!=Identity
420 consString.append((gapcons[0] == 1) ? "*" : "+");
425 consString.append('-');
429 consSequence = new Sequence(name, consString.toString(), start, end);
435 * @return Conservation sequence
437 public Sequence getConsSequence()
442 // From Alignment.java in jalview118
443 public void findQuality()
445 findQuality(0, maxLength - 1);
451 private void percentIdentity2()
453 seqNums = new Vector<int[]>();
455 int i = 0, iSize = sequences.length;
456 // Do we need to calculate this again?
457 for (i = 0; i < iSize; i++)
462 if ((cons2 == null) || seqNumsChanged)
464 cons2 = new int[maxLength][24];
466 // Initialize the array
467 for (int j = 0; j < 24; j++)
469 for (i = 0; i < maxLength; i++)
478 while (j < sequences.length)
480 sqnum = seqNums.elementAt(j);
482 for (i = 1; i < sqnum.length; i++)
484 cons2[i - 1][sqnum[i]]++;
487 for (i = sqnum.length - 1; i < maxLength; i++)
489 cons2[i][23]++; // gap count
498 * for (int i=start; i <= end; i++) { int max = -1000; int maxi = -1; int
501 * for (int j=0;j<24;j++) { if (cons2[i][j] > max) { max = cons2[i][j];
502 * maxi = i; maxj = j; } } }
508 * Calculates the quality of the set of sequences
515 public void findQuality(int startRes, int endRes)
517 quality = new Vector<Double>();
520 int[][] BLOSUM62 = ResidueProperties.getBLOSUM62();
522 // Loop over columns // JBPNote Profiling info
523 // long ts = System.currentTimeMillis();
524 // long te = System.currentTimeMillis();
527 int size = seqNums.size();
528 int[] lengths = new int[size];
529 double tot, bigtot, sr, tmp;
531 int l, j, i, ii, i2, k, seqNum;
533 for (l = 0; l < size; l++)
535 lengths[l] = seqNums.elementAt(l).length - 1;
538 for (j = startRes; j <= endRes; j++)
542 // First Xr = depends on column only
545 for (ii = 0; ii < 24; ii++)
549 for (i2 = 0; i2 < 24; i2++)
551 x[ii] += (((double) cons2[j][i2] * BLOSUM62[ii][i2]) + 4);
557 // Now calculate D for each position and sum
558 for (k = 0; k < size; k++)
562 seqNum = (j < lengths[k]) ? seqNums.elementAt(k)[j + 1]
563 : 23; // Sequence, or gap at the end
565 // This is a loop over r
566 for (i = 0; i < 23; i++)
570 sr = (double) BLOSUM62[i][seqNum] + 4;
572 // Calculate X with another loop over residues
573 // System.out.println("Xi " + i + " " + x[i] + " " + sr);
576 tot += (xx[i] * xx[i]);
579 bigtot += Math.sqrt(tot);
582 // This is the quality for one column
588 // bigtot = bigtot * (size-cons2[j][23])/size;
589 quality.addElement(new Double(bigtot));
591 // Need to normalize by gaps
594 double newmax = -10000;
596 for (j = startRes; j <= endRes; j++)
598 tmp = quality.elementAt(j).doubleValue();
599 tmp = ((max - tmp) * (size - cons2[j][23])) / size;
601 // System.out.println(tmp+ " " + j);
602 quality.setElementAt(new Double(tmp), j);
610 // System.out.println("Quality " + s);
611 qualityRange[0] = 0D;
612 qualityRange[1] = newmax;
616 * Complete the given consensus and quuality annotation rows. Note: currently
617 * this method will enlarge the given annotation row if it is too small,
618 * otherwise will leave its length unchanged.
620 * @param conservation
621 * conservation annotation row
623 * (optional - may be null)
625 * first column for conservation
627 * extent of conservation
629 public void completeAnnotations(AlignmentAnnotation conservation,
630 AlignmentAnnotation quality2, int istart, int alWidth)
632 char[] sequence = getConsSequence().getSequence();
644 maxB = 0f - minB; // scalable range for colouring both Conservation and
654 if (conservation != null && conservation.annotations != null
655 && conservation.annotations.length < alWidth)
657 conservation.annotations = new Annotation[alWidth];
660 if (quality2 != null)
662 quality2.graphMax = (float) qualityRange[1];
663 if (quality2.annotations != null
664 && quality2.annotations.length < alWidth)
666 quality2.annotations = new Annotation[alWidth];
668 qmin = (float) qualityRange[0];
669 qmax = (float) qualityRange[1];
672 for (int i = istart; i < alWidth; i++)
678 if (Character.isDigit(c))
691 if (conservation != null)
693 float vprop = value - min;
695 int consp = i - start;
696 String conssym = (value > 0 && consp > -1 && consp < consSymbs.length) ? consSymbs[consp]
698 conservation.annotations[i] = new Annotation(String.valueOf(c),
699 conssym, ' ', value, new Color(minR + (maxR * vprop), minG
700 + (maxG * vprop), minB + (maxB * vprop)));
704 if (quality2 != null)
706 value = quality.elementAt(i).floatValue();
707 float vprop = value - qmin;
709 quality2.annotations[i] = new Annotation(" ",
710 String.valueOf(value), ' ', value, new Color(minR
711 + (maxR * vprop), minG + (maxG * vprop), minB
718 * construct and call the calculation methods on a new Conservation object
721 * - name of conservation
723 * - minimum number of conserved residues needed to indicate
724 * conservation (typically 3)
727 * first column in calculation window
729 * last column in calculation window
731 * positive (true) or negative (false) conservation
732 * @param consPercGaps
733 * percentage of gaps tolerated in column
735 * flag indicating if alignment quality should be calculated
736 * @return Conservation object ready for use in visualization
738 public static Conservation calculateConservation(String name,
739 int threshold, List<SequenceI> seqs, int start, int end,
740 boolean posOrNeg, int consPercGaps, boolean calcQuality)
742 Conservation cons = new Conservation(name, threshold, seqs, start, end);
744 cons.verdict(posOrNeg, consPercGaps);