2 * Jalview - A Sequence Alignment Editor and Viewer (Development Version 2.4.1)
3 * Copyright (C) 2009 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
19 package jalview.analysis;
21 import java.awt.Color;
24 import jalview.datamodel.*;
27 * Calculates conservation values for a given set of sequences
32 public class Conservation
34 SequenceI[] sequences;
40 Vector seqNums; // vector of int vectors where first is sequence checksum
42 int maxLength = 0; // used by quality calcs
44 boolean seqNumsChanged = false; // updated after any change via calcSeqNum;
48 boolean canonicaliseAa = true; // if true then conservation calculation will
50 // map all symbols to canonical aa numbering
51 // rather than consider conservation of that
54 /** Stores calculated quality values */
55 public Vector quality;
57 /** Stores maximum and minimum values of quality values */
58 public Double[] qualityRange = new Double[2];
60 String consString = "";
62 Sequence consSequence;
73 * Creates a new Conservation object.
76 * Name of conservation
78 * hash of properties for each symbol
80 * to count the residues in residueHash(). commonly used value
83 * sequences to be used in calculation
85 * start residue position
87 * end residue position
89 public Conservation(String name, Hashtable propHash, int threshold,
90 Vector sequences, int start, int end)
94 this.propHash = propHash;
95 this.threshold = threshold;
99 maxLength = end - start + 1; // default width includes bounds of
102 int s, sSize = sequences.size();
103 SequenceI[] sarray = new SequenceI[sSize];
104 this.sequences = sarray;
106 for (s = 0; s < sSize; s++)
108 sarray[s] = (SequenceI) sequences.elementAt(s);
109 if (sarray[s].getLength() > maxLength)
111 maxLength = sarray[s].getLength();
117 * Translate sequence i into a numerical representation and store it in the
118 * i'th position of the seqNums array.
122 private void calcSeqNum(int i)
124 String sq = null; // for dumb jbuilder not-inited exception warning
127 int sSize = sequences.length;
129 if ((i > -1) && (i < sSize))
131 sq = sequences[i].getSequenceAsString();
133 if (seqNums.size() <= i)
135 seqNums.addElement(new int[sq.length() + 1]);
138 if (sq.hashCode() != ((int[]) seqNums.elementAt(i))[0])
142 seqNumsChanged = true;
150 sqnum = new int[len + 1]; // better to always make a new array -
151 // sequence can change its length
152 sqnum[0] = sq.hashCode();
154 for (j = 1; j <= len; j++)
156 sqnum[j] = jalview.schemes.ResidueProperties.aaIndex[sq
160 seqNums.setElementAt(sqnum, i);
164 System.out.println("SEQUENCE HAS BEEN DELETED!!!");
169 // JBPNote INFO level debug
171 .println("ERROR: calcSeqNum called with out of range sequence index for Alignment\n");
176 * Calculates the conservation values for given set of sequences
178 public void calculate()
180 Hashtable resultHash, ht;
181 int thresh, j, jSize = sequences.length;
182 int[] values; // Replaces residueHash
183 String type, res = null;
185 Enumeration enumeration2;
187 total = new Hashtable[maxLength];
189 for (int i = start; i <= end; i++)
191 values = new int[255];
193 for (j = 0; j < jSize; j++)
195 if (sequences[j].getLength() > i)
197 c = sequences[j].getCharAt(i);
200 { // lookup the base aa code symbol
201 c = (char) jalview.schemes.ResidueProperties.aaIndex[sequences[j]
209 // recover canonical aa symbol
210 c = jalview.schemes.ResidueProperties.aa[c].charAt(0);
215 // original behaviour - operate on ascii symbols directly
216 // No need to check if its a '-'
217 if (c == '.' || c == ' ')
222 if (!canonicaliseAa && 'a' <= c && c <= 'z')
224 c -= (32); // 32 = 'a' - 'A'
235 // What is the count threshold to count the residues in residueHash()
236 thresh = (threshold * (jSize)) / 100;
238 // loop over all the found residues
239 resultHash = new Hashtable();
240 for (char v = '-'; v < 'Z'; v++)
243 if (values[v] > thresh)
245 res = String.valueOf(v);
247 // Now loop over the properties
248 enumeration2 = propHash.keys();
250 while (enumeration2.hasMoreElements())
252 type = (String) enumeration2.nextElement();
253 ht = (Hashtable) propHash.get(type);
255 // Have we ticked this before?
256 if (!resultHash.containsKey(type))
258 if (ht.containsKey(res))
260 resultHash.put(type, ht.get(res));
264 resultHash.put(type, ht.get("-"));
267 else if (((Integer) resultHash.get(type)).equals((Integer) ht
270 resultHash.put(type, new Integer(-1));
276 total[i - start] = resultHash;
280 /*****************************************************************************
281 * count conservation for the j'th column of the alignment
283 * @return { gap count, conserved residue count}
285 public int[] countConsNGaps(int j)
290 int[] r = new int[2];
292 int i, iSize = sequences.length;
295 for (i = 0; i < iSize; i++)
297 if (j >= sequences[i].getLength())
303 c = sequences[i].getCharAt(j); // gaps do not have upper/lower case
305 if (jalview.util.Comparison.isGap((c)))
325 r[0] = (nres == cons) ? 1 : 0;
332 * Calculates the conservation sequence
335 * if true, poitiveve conservation; false calculates negative
337 * @param percentageGaps
338 * commonly used value is 25
340 public void verdict(boolean consflag, float percentageGaps)
342 StringBuffer consString = new StringBuffer();
348 Hashtable resultHash;
349 Enumeration enumeration;
351 // NOTE THIS SHOULD CHECK IF THE CONSEQUENCE ALREADY
352 // EXISTS AND NOT OVERWRITE WITH '-', BUT THIS CASE
353 // DOES NOT EXIST IN JALVIEW 2.1.2
354 for (int i = 0; i < start; i++)
356 consString.append('-');
359 for (int i = start; i <= end; i++)
361 gapcons = countConsNGaps(i);
362 totGaps = gapcons[1];
363 pgaps = ((float) totGaps * 100) / (float) sequences.length;
365 if (percentageGaps > pgaps)
367 resultHash = total[i - start];
369 // Now find the verdict
371 enumeration = resultHash.keys();
373 while (enumeration.hasMoreElements())
375 type = (String) enumeration.nextElement();
376 result = (Integer) resultHash.get(type);
378 // Do we want to count +ve conservation or +ve and -ve cons.?
381 if (result.intValue() == 1)
388 if (result.intValue() != -1)
397 consString.append(count); // Conserved props!=Identity
401 consString.append((gapcons[0] == 1) ? "*" : "+");
406 consString.append('-');
410 consSequence = new Sequence(name, consString.toString(), start, end);
416 * @return Conservation sequence
418 public Sequence getConsSequence()
423 // From Alignment.java in jalview118
424 public void findQuality()
426 findQuality(0, maxLength - 1);
432 private void percentIdentity2()
434 seqNums = new Vector();
436 int i = 0, iSize = sequences.length;
437 // Do we need to calculate this again?
438 for (i = 0; i < iSize; i++)
443 if ((cons2 == null) || seqNumsChanged)
445 cons2 = new int[maxLength][24];
447 // Initialize the array
448 for (int j = 0; j < 24; j++)
450 for (i = 0; i < maxLength; i++)
459 while (j < sequences.length)
461 sqnum = (int[]) seqNums.elementAt(j);
463 for (i = 1; i < sqnum.length; i++)
465 cons2[i - 1][sqnum[i]]++;
468 for (i = sqnum.length - 1; i < maxLength; i++)
470 cons2[i][23]++; // gap count
479 * for (int i=start; i <= end; i++) { int max = -1000; int maxi = -1; int
482 * for (int j=0;j<24;j++) { if (cons2[i][j] > max) { max = cons2[i][j];
483 * maxi = i; maxj = j; } } }
489 * Calculates the quality of the set of sequences
496 public void findQuality(int start, int end)
498 quality = new Vector();
501 int[][] BLOSUM62 = jalview.schemes.ResidueProperties.getBLOSUM62();
503 // Loop over columns // JBPNote Profiling info
504 // long ts = System.currentTimeMillis();
505 // long te = System.currentTimeMillis();
508 int size = seqNums.size();
509 int[] lengths = new int[size];
510 double tot, bigtot, sr, tmp;
512 int l, j, i, ii, i2, k, seqNum;
514 for (l = 0; l < size; l++)
516 lengths[l] = ((int[]) seqNums.elementAt(l)).length - 1;
519 for (j = start; j <= end; j++)
523 // First Xr = depends on column only
526 for (ii = 0; ii < 24; ii++)
530 for (i2 = 0; i2 < 24; i2++)
532 x[ii] += (((double) cons2[j][i2] * BLOSUM62[ii][i2]) + 4);
538 // Now calculate D for each position and sum
539 for (k = 0; k < size; k++)
543 seqNum = (j < lengths[k]) ? ((int[]) seqNums.elementAt(k))[j + 1]
544 : 23; // Sequence, or gap at the end
546 // This is a loop over r
547 for (i = 0; i < 23; i++)
551 sr = (double) BLOSUM62[i][seqNum] + 4;
553 // Calculate X with another loop over residues
554 // System.out.println("Xi " + i + " " + x[i] + " " + sr);
557 tot += (xx[i] * xx[i]);
560 bigtot += Math.sqrt(tot);
563 // This is the quality for one column
569 // bigtot = bigtot * (size-cons2[j][23])/size;
570 quality.addElement(new Double(bigtot));
572 // Need to normalize by gaps
575 double newmax = -10000;
577 for (j = start; j <= end; j++)
579 tmp = ((Double) quality.elementAt(j)).doubleValue();
580 tmp = ((max - tmp) * (size - cons2[j][23])) / size;
582 // System.out.println(tmp+ " " + j);
583 quality.setElementAt(new Double(tmp), j);
591 // System.out.println("Quality " + s);
592 qualityRange[0] = new Double(0);
593 qualityRange[1] = new Double(newmax);
597 * complete the given consensus and quuality annotation rows.
598 * Note: currently this method will enlarge the given annotation row if it is too small, otherwise will leave its length unchanged.
599 * @param conservation conservation annotation row
600 * @param quality2 (optional - may be null)
601 * @param istart first column for conservation
602 * @param alWidth extent of conservation
604 public void completeAnnotations(AlignmentAnnotation conservation,
605 AlignmentAnnotation quality2, int istart, int alWidth)
607 char[] sequence = getConsSequence().getSequence();
619 maxB = 0f - minB; // scalable range for colouring both Conservation and
629 if (conservation.annotations !=null && conservation.annotations.length<alWidth)
630 { conservation.annotations = new Annotation[alWidth]; }
633 if (quality2 != null)
635 quality2.graphMax = qualityRange[1].floatValue();
636 if (quality2.annotations!=null && quality2.annotations.length<alWidth) {
637 quality2.annotations = new Annotation[alWidth];
639 qmin = qualityRange[0].floatValue();
640 qmax = qualityRange[1].floatValue();
643 for (int i = 0; i < alWidth; i++)
649 if (Character.isDigit(c))
651 value = (int) (c - '0');
662 float vprop = value - min;
664 conservation.annotations[i] = new Annotation(String.valueOf(c),
665 String.valueOf(value), ' ', value, new Color(minR
666 + (maxR * vprop), minG + (maxG * vprop), minB
670 if (quality2 != null)
672 value = ((Double) quality.elementAt(i)).floatValue();
673 vprop = value - qmin;
675 quality2.annotations[i] = new Annotation(" ", String
676 .valueOf(value), ' ', value, new Color(minR
677 + (maxR * vprop), minG + (maxG * vprop), minB