2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.7)
3 * Copyright (C) 2011 J Procter, AM Waterhouse, J Engelhardt, LM Lui, 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;
103 for (s = 0; s < sSize; s++)
105 sarray[s] = (SequenceI) sequences.get(s);
106 if (sarray[s].getLength() > maxLength)
108 maxLength = sarray[s].getLength();
111 } catch (ArrayIndexOutOfBoundsException ex)
113 // bail - another thread has modified the sequence array, so the current calculation is probably invalid.
114 this.sequences=new SequenceI[0];
120 * Translate sequence i into a numerical representation and store it in the
121 * i'th position of the seqNums array.
125 private void calcSeqNum(int i)
127 String sq = null; // for dumb jbuilder not-inited exception warning
130 int sSize = sequences.length;
132 if ((i > -1) && (i < sSize))
134 sq = sequences[i].getSequenceAsString();
136 if (seqNums.size() <= i)
138 seqNums.addElement(new int[sq.length() + 1]);
141 if (sq.hashCode() != ((int[]) seqNums.elementAt(i))[0])
145 seqNumsChanged = true;
153 sqnum = new int[len + 1]; // better to always make a new array -
154 // sequence can change its length
155 sqnum[0] = sq.hashCode();
157 for (j = 1; j <= len; j++)
159 sqnum[j] = jalview.schemes.ResidueProperties.aaIndex[sq
163 seqNums.setElementAt(sqnum, i);
167 System.out.println("SEQUENCE HAS BEEN DELETED!!!");
172 // JBPNote INFO level debug
174 .println("ERROR: calcSeqNum called with out of range sequence index for Alignment\n");
179 * Calculates the conservation values for given set of sequences
181 public void calculate()
183 Hashtable resultHash, ht;
184 int thresh, j, jSize = sequences.length;
185 int[] values; // Replaces residueHash
186 String type, res = null;
188 Enumeration enumeration2;
190 total = new Hashtable[maxLength];
192 for (int i = start; i <= end; i++)
194 values = new int[255];
196 for (j = 0; j < jSize; j++)
198 if (sequences[j].getLength() > i)
200 c = sequences[j].getCharAt(i);
203 { // lookup the base aa code symbol
204 c = (char) jalview.schemes.ResidueProperties.aaIndex[sequences[j]
212 // recover canonical aa symbol
213 c = jalview.schemes.ResidueProperties.aa[c].charAt(0);
218 // original behaviour - operate on ascii symbols directly
219 // No need to check if its a '-'
220 if (c == '.' || c == ' ')
225 if (!canonicaliseAa && 'a' <= c && c <= 'z')
227 c -= (32); // 32 = 'a' - 'A'
238 // What is the count threshold to count the residues in residueHash()
239 thresh = (threshold * (jSize)) / 100;
241 // loop over all the found residues
242 resultHash = new Hashtable();
243 for (char v = '-'; v < 'Z'; v++)
246 if (values[v] > thresh)
248 res = String.valueOf(v);
250 // Now loop over the properties
251 enumeration2 = propHash.keys();
253 while (enumeration2.hasMoreElements())
255 type = (String) enumeration2.nextElement();
256 ht = (Hashtable) propHash.get(type);
258 // Have we ticked this before?
259 if (!resultHash.containsKey(type))
261 if (ht.containsKey(res))
263 resultHash.put(type, ht.get(res));
267 resultHash.put(type, ht.get("-"));
270 else if (((Integer) resultHash.get(type)).equals((Integer) ht
273 resultHash.put(type, new Integer(-1));
279 if (total.length>0) {
280 total[i - start] = resultHash;
285 /*****************************************************************************
286 * count conservation for the j'th column of the alignment
288 * @return { gap count, conserved residue count}
290 public int[] countConsNGaps(int j)
295 int[] r = new int[2];
297 int i, iSize = sequences.length;
300 for (i = 0; i < iSize; i++)
302 if (j >= sequences[i].getLength())
308 c = sequences[i].getCharAt(j); // gaps do not have upper/lower case
310 if (jalview.util.Comparison.isGap((c)))
330 r[0] = (nres == cons) ? 1 : 0;
337 * Calculates the conservation sequence
340 * if true, poitiveve conservation; false calculates negative
342 * @param percentageGaps
343 * commonly used value is 25
345 public void verdict(boolean consflag, float percentageGaps)
347 StringBuffer consString = new StringBuffer();
353 Hashtable resultHash;
354 Enumeration enumeration;
356 // NOTE THIS SHOULD CHECK IF THE CONSEQUENCE ALREADY
357 // EXISTS AND NOT OVERWRITE WITH '-', BUT THIS CASE
358 // DOES NOT EXIST IN JALVIEW 2.1.2
359 for (int i = 0; i < start; i++)
361 consString.append('-');
364 for (int i = start; i <= end; i++)
366 gapcons = countConsNGaps(i);
367 totGaps = gapcons[1];
368 pgaps = ((float) totGaps * 100) / (float) sequences.length;
370 if (percentageGaps > pgaps)
372 resultHash = total[i - start];
374 // Now find the verdict
376 enumeration = resultHash.keys();
378 while (enumeration.hasMoreElements())
380 type = (String) enumeration.nextElement();
381 result = (Integer) resultHash.get(type);
383 // Do we want to count +ve conservation or +ve and -ve cons.?
386 if (result.intValue() == 1)
393 if (result.intValue() != -1)
402 consString.append(count); // Conserved props!=Identity
406 consString.append((gapcons[0] == 1) ? "*" : "+");
411 consString.append('-');
415 consSequence = new Sequence(name, consString.toString(), start, end);
421 * @return Conservation sequence
423 public Sequence getConsSequence()
428 // From Alignment.java in jalview118
429 public void findQuality()
431 findQuality(0, maxLength - 1);
437 private void percentIdentity2()
439 seqNums = new Vector();
441 int i = 0, iSize = sequences.length;
442 // Do we need to calculate this again?
443 for (i = 0; i < iSize; i++)
448 if ((cons2 == null) || seqNumsChanged)
450 cons2 = new int[maxLength][24];
452 // Initialize the array
453 for (int j = 0; j < 24; j++)
455 for (i = 0; i < maxLength; i++)
464 while (j < sequences.length)
466 sqnum = (int[]) seqNums.elementAt(j);
468 for (i = 1; i < sqnum.length; i++)
470 cons2[i - 1][sqnum[i]]++;
473 for (i = sqnum.length - 1; i < maxLength; i++)
475 cons2[i][23]++; // gap count
484 * for (int i=start; i <= end; i++) { int max = -1000; int maxi = -1; int
487 * for (int j=0;j<24;j++) { if (cons2[i][j] > max) { max = cons2[i][j];
488 * maxi = i; maxj = j; } } }
494 * Calculates the quality of the set of sequences
501 public void findQuality(int start, int end)
503 quality = new Vector();
506 int[][] BLOSUM62 = jalview.schemes.ResidueProperties.getBLOSUM62();
508 // Loop over columns // JBPNote Profiling info
509 // long ts = System.currentTimeMillis();
510 // long te = System.currentTimeMillis();
513 int size = seqNums.size();
514 int[] lengths = new int[size];
515 double tot, bigtot, sr, tmp;
517 int l, j, i, ii, i2, k, seqNum;
519 for (l = 0; l < size; l++)
521 lengths[l] = ((int[]) seqNums.elementAt(l)).length - 1;
524 for (j = start; j <= end; j++)
528 // First Xr = depends on column only
531 for (ii = 0; ii < 24; ii++)
535 for (i2 = 0; i2 < 24; i2++)
537 x[ii] += (((double) cons2[j][i2] * BLOSUM62[ii][i2]) + 4);
543 // Now calculate D for each position and sum
544 for (k = 0; k < size; k++)
548 seqNum = (j < lengths[k]) ? ((int[]) seqNums.elementAt(k))[j + 1]
549 : 23; // Sequence, or gap at the end
551 // This is a loop over r
552 for (i = 0; i < 23; i++)
556 sr = (double) BLOSUM62[i][seqNum] + 4;
558 // Calculate X with another loop over residues
559 // System.out.println("Xi " + i + " " + x[i] + " " + sr);
562 tot += (xx[i] * xx[i]);
565 bigtot += Math.sqrt(tot);
568 // This is the quality for one column
574 // bigtot = bigtot * (size-cons2[j][23])/size;
575 quality.addElement(new Double(bigtot));
577 // Need to normalize by gaps
580 double newmax = -10000;
582 for (j = start; j <= end; j++)
584 tmp = ((Double) quality.elementAt(j)).doubleValue();
585 tmp = ((max - tmp) * (size - cons2[j][23])) / size;
587 // System.out.println(tmp+ " " + j);
588 quality.setElementAt(new Double(tmp), j);
596 // System.out.println("Quality " + s);
597 qualityRange[0] = new Double(0);
598 qualityRange[1] = new Double(newmax);
602 * complete the given consensus and quuality annotation rows. Note: currently
603 * this method will enlarge the given annotation row if it is too small,
604 * otherwise will leave its length unchanged.
606 * @param conservation
607 * conservation annotation row
609 * (optional - may be null)
611 * first column for conservation
613 * extent of conservation
615 public void completeAnnotations(AlignmentAnnotation conservation,
616 AlignmentAnnotation quality2, int istart, int alWidth)
618 char[] sequence = getConsSequence().getSequence();
630 maxB = 0f - minB; // scalable range for colouring both Conservation and
640 if (conservation.annotations != null
641 && conservation.annotations.length < alWidth)
643 conservation.annotations = new Annotation[alWidth];
646 if (quality2 != null)
648 quality2.graphMax = qualityRange[1].floatValue();
649 if (quality2.annotations != null
650 && quality2.annotations.length < alWidth)
652 quality2.annotations = new Annotation[alWidth];
654 qmin = qualityRange[0].floatValue();
655 qmax = qualityRange[1].floatValue();
658 for (int i = 0; i < alWidth; i++)
664 if (Character.isDigit(c))
666 value = (int) (c - '0');
677 float vprop = value - min;
679 conservation.annotations[i] = new Annotation(String.valueOf(c),
680 String.valueOf(value), ' ', value, new Color(minR
681 + (maxR * vprop), minG + (maxG * vprop), minB
685 if (quality2 != null)
687 value = ((Double) quality.elementAt(i)).floatValue();
688 vprop = value - qmin;
690 quality2.annotations[i] = new Annotation(" ",
691 String.valueOf(value), ' ', value, new Color(minR
692 + (maxR * vprop), minG + (maxG * vprop), minB
699 * construct and call the calculation methods on a new Conservation object
700 * @param name - name of conservation
701 * @param consHash - hash table of properties for each amino acid (normally ResidueProperties.propHash)
702 * @param threshold - minimum number of conserved residues needed to indicate conservation (typically 3)
704 * @param start first column in calculation window
705 * @param end last column in calculation window
706 * @param posOrNeg positive (true) or negative (false) conservation
707 * @param consPercGaps percentage of gaps tolerated in column
708 * @param calcQuality flag indicating if alignment quality should be calculated
709 * @return Conservation object ready for use in visualization
711 public static Conservation calculateConservation(String name,
712 Hashtable consHash, int threshold, List<SequenceI> seqs, int start, int end, boolean posOrNeg, int consPercGaps, boolean calcQuality)
714 Conservation cons = new Conservation(name, consHash, threshold, seqs, start,end);
715 return calculateConservation(cons, posOrNeg, consPercGaps, calcQuality);
718 * @param b positive (true) or negative (false) conservation
719 * @param consPercGaps percentage of gaps tolerated in column
720 * @param calcQuality flag indicating if alignment quality should be calculated
721 * @return Conservation object ready for use in visualization
723 public static Conservation calculateConservation(Conservation cons, boolean b, int consPercGaps, boolean calcQuality)
726 cons.verdict(b, consPercGaps);