2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8)
3 * Copyright (C) 2012 J Procter, AM Waterhouse, LM Lui, J Engelhardt, G Barton, M Clamp, S Searle
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 of the License, or (at your option) any later version.
11 * Jalview is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty
13 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 * PURPOSE. See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
18 package jalview.analysis;
20 import java.awt.Color;
23 import jalview.datamodel.*;
26 * Calculates conservation values for a given set of sequences
31 public class Conservation
33 SequenceI[] sequences;
39 Vector seqNums; // vector of int vectors where first is sequence checksum
41 int maxLength = 0; // used by quality calcs
43 boolean seqNumsChanged = false; // updated after any change via calcSeqNum;
47 boolean canonicaliseAa = true; // if true then conservation calculation will
49 // map all symbols to canonical aa numbering
50 // rather than consider conservation of that
53 /** Stores calculated quality values */
54 public Vector quality;
56 /** Stores maximum and minimum values of quality values */
57 public Double[] qualityRange = new Double[2];
59 String consString = "";
61 Sequence consSequence;
72 * Creates a new Conservation object.
75 * Name of conservation
77 * hash of properties for each symbol
79 * to count the residues in residueHash(). commonly used value is 3
81 * sequences to be used in calculation
83 * start residue position
85 * end residue position
87 public Conservation(String name, Hashtable propHash, int threshold,
88 List<SequenceI> sequences, int start, int end)
91 this.propHash = propHash;
92 this.threshold = threshold;
96 maxLength = end - start + 1; // default width includes bounds of
99 int s, sSize = sequences.size();
100 SequenceI[] sarray = new SequenceI[sSize];
101 this.sequences = sarray;
104 for (s = 0; s < sSize; s++)
106 sarray[s] = (SequenceI) sequences.get(s);
107 if (sarray[s].getLength() > maxLength)
109 maxLength = sarray[s].getLength();
112 } catch (ArrayIndexOutOfBoundsException ex)
114 // bail - another thread has modified the sequence array, so the current
115 // calculation is probably invalid.
116 this.sequences = new SequenceI[0];
122 * Translate sequence i into a numerical representation and store it in the
123 * i'th position of the seqNums array.
127 private void calcSeqNum(int i)
129 String sq = null; // for dumb jbuilder not-inited exception warning
132 int sSize = sequences.length;
134 if ((i > -1) && (i < sSize))
136 sq = sequences[i].getSequenceAsString();
138 if (seqNums.size() <= i)
140 seqNums.addElement(new int[sq.length() + 1]);
143 if (sq.hashCode() != ((int[]) seqNums.elementAt(i))[0])
147 seqNumsChanged = true;
155 sqnum = new int[len + 1]; // better to always make a new array -
156 // sequence can change its length
157 sqnum[0] = sq.hashCode();
159 for (j = 1; j <= len; j++)
161 sqnum[j] = jalview.schemes.ResidueProperties.aaIndex[sq
165 seqNums.setElementAt(sqnum, i);
169 System.out.println("SEQUENCE HAS BEEN DELETED!!!");
174 // JBPNote INFO level debug
176 .println("ERROR: calcSeqNum called with out of range sequence index for Alignment\n");
181 * Calculates the conservation values for given set of sequences
183 public void calculate()
185 Hashtable resultHash, ht;
186 int thresh, j, jSize = sequences.length;
187 int[] values; // Replaces residueHash
188 String type, res = null;
190 Enumeration enumeration2;
192 total = new Hashtable[maxLength];
194 for (int i = start; i <= end; i++)
196 values = new int[255];
198 for (j = 0; j < jSize; j++)
200 if (sequences[j].getLength() > i)
202 c = sequences[j].getCharAt(i);
205 { // lookup the base aa code symbol
206 c = (char) jalview.schemes.ResidueProperties.aaIndex[sequences[j]
214 // recover canonical aa symbol
215 c = jalview.schemes.ResidueProperties.aa[c].charAt(0);
220 // original behaviour - operate on ascii symbols directly
221 // No need to check if its a '-'
222 if (c == '.' || c == ' ')
227 if (!canonicaliseAa && 'a' <= c && c <= 'z')
229 c -= (32); // 32 = 'a' - 'A'
240 // What is the count threshold to count the residues in residueHash()
241 thresh = (threshold * (jSize)) / 100;
243 // loop over all the found residues
244 resultHash = new Hashtable();
245 for (char v = '-'; v < 'Z'; v++)
248 if (values[v] > thresh)
250 res = String.valueOf(v);
252 // Now loop over the properties
253 enumeration2 = propHash.keys();
255 while (enumeration2.hasMoreElements())
257 type = (String) enumeration2.nextElement();
258 ht = (Hashtable) propHash.get(type);
260 // Have we ticked this before?
261 if (!resultHash.containsKey(type))
263 if (ht.containsKey(res))
265 resultHash.put(type, ht.get(res));
269 resultHash.put(type, ht.get("-"));
272 else if (((Integer) resultHash.get(type)).equals((Integer) ht
275 resultHash.put(type, new Integer(-1));
281 if (total.length > 0)
283 total[i - start] = resultHash;
288 /*****************************************************************************
289 * count conservation for the j'th column of the alignment
291 * @return { gap count, conserved residue count}
293 public int[] countConsNGaps(int j)
298 int[] r = new int[2];
300 int i, iSize = sequences.length;
303 for (i = 0; i < iSize; i++)
305 if (j >= sequences[i].getLength())
311 c = sequences[i].getCharAt(j); // gaps do not have upper/lower case
313 if (jalview.util.Comparison.isGap((c)))
333 r[0] = (nres == cons) ? 1 : 0;
340 * Calculates the conservation sequence
343 * if true, poitiveve conservation; false calculates negative
345 * @param percentageGaps
346 * commonly used value is 25
348 public void verdict(boolean consflag, float percentageGaps)
350 StringBuffer consString = new StringBuffer();
356 Hashtable resultHash;
357 Enumeration enumeration;
359 // NOTE THIS SHOULD CHECK IF THE CONSEQUENCE ALREADY
360 // EXISTS AND NOT OVERWRITE WITH '-', BUT THIS CASE
361 // DOES NOT EXIST IN JALVIEW 2.1.2
362 for (int i = 0; i < start; i++)
364 consString.append('-');
367 for (int i = start; i <= end; i++)
369 gapcons = countConsNGaps(i);
370 totGaps = gapcons[1];
371 pgaps = ((float) totGaps * 100) / (float) sequences.length;
373 if (percentageGaps > pgaps)
375 resultHash = total[i - start];
377 // Now find the verdict
379 enumeration = resultHash.keys();
381 while (enumeration.hasMoreElements())
383 type = (String) enumeration.nextElement();
384 result = (Integer) resultHash.get(type);
386 // Do we want to count +ve conservation or +ve and -ve cons.?
389 if (result.intValue() == 1)
396 if (result.intValue() != -1)
405 consString.append(count); // Conserved props!=Identity
409 consString.append((gapcons[0] == 1) ? "*" : "+");
414 consString.append('-');
418 consSequence = new Sequence(name, consString.toString(), start, end);
424 * @return Conservation sequence
426 public Sequence getConsSequence()
431 // From Alignment.java in jalview118
432 public void findQuality()
434 findQuality(0, maxLength - 1);
440 private void percentIdentity2()
442 seqNums = new Vector();
444 int i = 0, iSize = sequences.length;
445 // Do we need to calculate this again?
446 for (i = 0; i < iSize; i++)
451 if ((cons2 == null) || seqNumsChanged)
453 cons2 = new int[maxLength][24];
455 // Initialize the array
456 for (int j = 0; j < 24; j++)
458 for (i = 0; i < maxLength; i++)
467 while (j < sequences.length)
469 sqnum = (int[]) seqNums.elementAt(j);
471 for (i = 1; i < sqnum.length; i++)
473 cons2[i - 1][sqnum[i]]++;
476 for (i = sqnum.length - 1; i < maxLength; i++)
478 cons2[i][23]++; // gap count
487 * for (int i=start; i <= end; i++) { int max = -1000; int maxi = -1; int
490 * for (int j=0;j<24;j++) { if (cons2[i][j] > max) { max = cons2[i][j];
491 * maxi = i; maxj = j; } } }
497 * Calculates the quality of the set of sequences
504 public void findQuality(int start, int end)
506 quality = new Vector();
509 int[][] BLOSUM62 = jalview.schemes.ResidueProperties.getBLOSUM62();
511 // Loop over columns // JBPNote Profiling info
512 // long ts = System.currentTimeMillis();
513 // long te = System.currentTimeMillis();
516 int size = seqNums.size();
517 int[] lengths = new int[size];
518 double tot, bigtot, sr, tmp;
520 int l, j, i, ii, i2, k, seqNum;
522 for (l = 0; l < size; l++)
524 lengths[l] = ((int[]) seqNums.elementAt(l)).length - 1;
527 for (j = start; j <= end; j++)
531 // First Xr = depends on column only
534 for (ii = 0; ii < 24; ii++)
538 for (i2 = 0; i2 < 24; i2++)
540 x[ii] += (((double) cons2[j][i2] * BLOSUM62[ii][i2]) + 4);
546 // Now calculate D for each position and sum
547 for (k = 0; k < size; k++)
551 seqNum = (j < lengths[k]) ? ((int[]) seqNums.elementAt(k))[j + 1]
552 : 23; // Sequence, or gap at the end
554 // This is a loop over r
555 for (i = 0; i < 23; i++)
559 sr = (double) BLOSUM62[i][seqNum] + 4;
561 // Calculate X with another loop over residues
562 // System.out.println("Xi " + i + " " + x[i] + " " + sr);
565 tot += (xx[i] * xx[i]);
568 bigtot += Math.sqrt(tot);
571 // This is the quality for one column
577 // bigtot = bigtot * (size-cons2[j][23])/size;
578 quality.addElement(new Double(bigtot));
580 // Need to normalize by gaps
583 double newmax = -10000;
585 for (j = start; j <= end; j++)
587 tmp = ((Double) quality.elementAt(j)).doubleValue();
588 tmp = ((max - tmp) * (size - cons2[j][23])) / size;
590 // System.out.println(tmp+ " " + j);
591 quality.setElementAt(new Double(tmp), j);
599 // System.out.println("Quality " + s);
600 qualityRange[0] = new Double(0);
601 qualityRange[1] = new Double(newmax);
605 * complete the given consensus and quuality annotation rows. Note: currently
606 * this method will enlarge the given annotation row if it is too small,
607 * otherwise will leave its length unchanged.
609 * @param conservation
610 * conservation annotation row
612 * (optional - may be null)
614 * first column for conservation
616 * extent of conservation
618 public void completeAnnotations(AlignmentAnnotation conservation,
619 AlignmentAnnotation quality2, int istart, int alWidth)
621 char[] sequence = getConsSequence().getSequence();
633 maxB = 0f - minB; // scalable range for colouring both Conservation and
643 if (conservation.annotations != null
644 && conservation.annotations.length < alWidth)
646 conservation.annotations = new Annotation[alWidth];
649 if (quality2 != null)
651 quality2.graphMax = qualityRange[1].floatValue();
652 if (quality2.annotations != null
653 && quality2.annotations.length < alWidth)
655 quality2.annotations = new Annotation[alWidth];
657 qmin = qualityRange[0].floatValue();
658 qmax = qualityRange[1].floatValue();
661 for (int i = 0; i < alWidth; i++)
667 if (Character.isDigit(c))
669 value = (int) (c - '0');
680 float vprop = value - min;
682 conservation.annotations[i] = new Annotation(String.valueOf(c),
683 String.valueOf(value), ' ', value, new Color(minR
684 + (maxR * vprop), minG + (maxG * vprop), minB
688 if (quality2 != null)
690 value = ((Double) quality.elementAt(i)).floatValue();
691 vprop = value - qmin;
693 quality2.annotations[i] = new Annotation(" ",
694 String.valueOf(value), ' ', value, new Color(minR
695 + (maxR * vprop), minG + (maxG * vprop), minB
702 * construct and call the calculation methods on a new Conservation object
705 * - name of conservation
707 * - hash table of properties for each amino acid (normally
708 * ResidueProperties.propHash)
710 * - minimum number of conserved residues needed to indicate
711 * conservation (typically 3)
714 * first column in calculation window
716 * last column in calculation window
718 * positive (true) or negative (false) conservation
719 * @param consPercGaps
720 * percentage of gaps tolerated in column
722 * flag indicating if alignment quality should be calculated
723 * @return Conservation object ready for use in visualization
725 public static Conservation calculateConservation(String name,
726 Hashtable consHash, int threshold, List<SequenceI> seqs,
727 int start, int end, boolean posOrNeg, int consPercGaps,
730 Conservation cons = new Conservation(name, consHash, threshold, seqs,
732 return calculateConservation(cons, posOrNeg, consPercGaps, calcQuality);
737 * positive (true) or negative (false) conservation
738 * @param consPercGaps
739 * percentage of gaps tolerated in column
741 * flag indicating if alignment quality should be calculated
742 * @return Conservation object ready for use in visualization
744 public static Conservation calculateConservation(Conservation cons,
745 boolean b, int consPercGaps, boolean calcQuality)
748 cons.verdict(b, consPercGaps);