2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.6)
3 * Copyright (C) 2010 J Procter, AM Waterhouse, 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 Vector sequences, int start, int end)
92 this.propHash = propHash;
93 this.threshold = threshold;
97 maxLength = end - start + 1; // default width includes bounds of
100 int s, sSize = sequences.size();
101 SequenceI[] sarray = new SequenceI[sSize];
102 this.sequences = sarray;
104 for (s = 0; s < sSize; s++)
106 sarray[s] = (SequenceI) sequences.elementAt(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 calculation is probably invalid.
115 this.sequences=new SequenceI[0];
121 * Translate sequence i into a numerical representation and store it in the
122 * i'th position of the seqNums array.
126 private void calcSeqNum(int i)
128 String sq = null; // for dumb jbuilder not-inited exception warning
131 int sSize = sequences.length;
133 if ((i > -1) && (i < sSize))
135 sq = sequences[i].getSequenceAsString();
137 if (seqNums.size() <= i)
139 seqNums.addElement(new int[sq.length() + 1]);
142 if (sq.hashCode() != ((int[]) seqNums.elementAt(i))[0])
146 seqNumsChanged = true;
154 sqnum = new int[len + 1]; // better to always make a new array -
155 // sequence can change its length
156 sqnum[0] = sq.hashCode();
158 for (j = 1; j <= len; j++)
160 sqnum[j] = jalview.schemes.ResidueProperties.aaIndex[sq
164 seqNums.setElementAt(sqnum, i);
168 System.out.println("SEQUENCE HAS BEEN DELETED!!!");
173 // JBPNote INFO level debug
175 .println("ERROR: calcSeqNum called with out of range sequence index for Alignment\n");
180 * Calculates the conservation values for given set of sequences
182 public void calculate()
184 Hashtable resultHash, ht;
185 int thresh, j, jSize = sequences.length;
186 int[] values; // Replaces residueHash
187 String type, res = null;
189 Enumeration enumeration2;
191 total = new Hashtable[maxLength];
193 for (int i = start; i <= end; i++)
195 values = new int[255];
197 for (j = 0; j < jSize; j++)
199 if (sequences[j].getLength() > i)
201 c = sequences[j].getCharAt(i);
204 { // lookup the base aa code symbol
205 c = (char) jalview.schemes.ResidueProperties.aaIndex[sequences[j]
213 // recover canonical aa symbol
214 c = jalview.schemes.ResidueProperties.aa[c].charAt(0);
219 // original behaviour - operate on ascii symbols directly
220 // No need to check if its a '-'
221 if (c == '.' || c == ' ')
226 if (!canonicaliseAa && 'a' <= c && c <= 'z')
228 c -= (32); // 32 = 'a' - 'A'
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 resultHash = new Hashtable();
244 for (char v = '-'; v < 'Z'; v++)
247 if (values[v] > thresh)
249 res = String.valueOf(v);
251 // Now loop over the properties
252 enumeration2 = propHash.keys();
254 while (enumeration2.hasMoreElements())
256 type = (String) enumeration2.nextElement();
257 ht = (Hashtable) propHash.get(type);
259 // Have we ticked this before?
260 if (!resultHash.containsKey(type))
262 if (ht.containsKey(res))
264 resultHash.put(type, ht.get(res));
268 resultHash.put(type, ht.get("-"));
271 else if (((Integer) resultHash.get(type)).equals((Integer) ht
274 resultHash.put(type, new Integer(-1));
280 if (total.length>0) {
281 total[i - start] = resultHash;
286 /*****************************************************************************
287 * count conservation for the j'th column of the alignment
289 * @return { gap count, conserved residue count}
291 public int[] countConsNGaps(int j)
296 int[] r = new int[2];
298 int i, iSize = sequences.length;
301 for (i = 0; i < iSize; i++)
303 if (j >= sequences[i].getLength())
309 c = sequences[i].getCharAt(j); // gaps do not have upper/lower case
311 if (jalview.util.Comparison.isGap((c)))
331 r[0] = (nres == cons) ? 1 : 0;
338 * Calculates the conservation sequence
341 * if true, poitiveve conservation; false calculates negative
343 * @param percentageGaps
344 * commonly used value is 25
346 public void verdict(boolean consflag, float percentageGaps)
348 StringBuffer consString = new StringBuffer();
354 Hashtable resultHash;
355 Enumeration enumeration;
357 // NOTE THIS SHOULD CHECK IF THE CONSEQUENCE ALREADY
358 // EXISTS AND NOT OVERWRITE WITH '-', BUT THIS CASE
359 // DOES NOT EXIST IN JALVIEW 2.1.2
360 for (int i = 0; i < start; i++)
362 consString.append('-');
365 for (int i = start; i <= end; i++)
367 gapcons = countConsNGaps(i);
368 totGaps = gapcons[1];
369 pgaps = ((float) totGaps * 100) / (float) sequences.length;
371 if (percentageGaps > pgaps)
373 resultHash = total[i - start];
375 // Now find the verdict
377 enumeration = resultHash.keys();
379 while (enumeration.hasMoreElements())
381 type = (String) enumeration.nextElement();
382 result = (Integer) resultHash.get(type);
384 // Do we want to count +ve conservation or +ve and -ve cons.?
387 if (result.intValue() == 1)
394 if (result.intValue() != -1)
403 consString.append(count); // Conserved props!=Identity
407 consString.append((gapcons[0] == 1) ? "*" : "+");
412 consString.append('-');
416 consSequence = new Sequence(name, consString.toString(), start, end);
422 * @return Conservation sequence
424 public Sequence getConsSequence()
429 // From Alignment.java in jalview118
430 public void findQuality()
432 findQuality(0, maxLength - 1);
438 private void percentIdentity2()
440 seqNums = new Vector();
442 int i = 0, iSize = sequences.length;
443 // Do we need to calculate this again?
444 for (i = 0; i < iSize; i++)
449 if ((cons2 == null) || seqNumsChanged)
451 cons2 = new int[maxLength][24];
453 // Initialize the array
454 for (int j = 0; j < 24; j++)
456 for (i = 0; i < maxLength; i++)
465 while (j < sequences.length)
467 sqnum = (int[]) seqNums.elementAt(j);
469 for (i = 1; i < sqnum.length; i++)
471 cons2[i - 1][sqnum[i]]++;
474 for (i = sqnum.length - 1; i < maxLength; i++)
476 cons2[i][23]++; // gap count
485 * for (int i=start; i <= end; i++) { int max = -1000; int maxi = -1; int
488 * for (int j=0;j<24;j++) { if (cons2[i][j] > max) { max = cons2[i][j];
489 * maxi = i; maxj = j; } } }
495 * Calculates the quality of the set of sequences
502 public void findQuality(int start, int end)
504 quality = new Vector();
507 int[][] BLOSUM62 = jalview.schemes.ResidueProperties.getBLOSUM62();
509 // Loop over columns // JBPNote Profiling info
510 // long ts = System.currentTimeMillis();
511 // long te = System.currentTimeMillis();
514 int size = seqNums.size();
515 int[] lengths = new int[size];
516 double tot, bigtot, sr, tmp;
518 int l, j, i, ii, i2, k, seqNum;
520 for (l = 0; l < size; l++)
522 lengths[l] = ((int[]) seqNums.elementAt(l)).length - 1;
525 for (j = start; j <= end; j++)
529 // First Xr = depends on column only
532 for (ii = 0; ii < 24; ii++)
536 for (i2 = 0; i2 < 24; i2++)
538 x[ii] += (((double) cons2[j][i2] * BLOSUM62[ii][i2]) + 4);
544 // Now calculate D for each position and sum
545 for (k = 0; k < size; k++)
549 seqNum = (j < lengths[k]) ? ((int[]) seqNums.elementAt(k))[j + 1]
550 : 23; // Sequence, or gap at the end
552 // This is a loop over r
553 for (i = 0; i < 23; i++)
557 sr = (double) BLOSUM62[i][seqNum] + 4;
559 // Calculate X with another loop over residues
560 // System.out.println("Xi " + i + " " + x[i] + " " + sr);
563 tot += (xx[i] * xx[i]);
566 bigtot += Math.sqrt(tot);
569 // This is the quality for one column
575 // bigtot = bigtot * (size-cons2[j][23])/size;
576 quality.addElement(new Double(bigtot));
578 // Need to normalize by gaps
581 double newmax = -10000;
583 for (j = start; j <= end; j++)
585 tmp = ((Double) quality.elementAt(j)).doubleValue();
586 tmp = ((max - tmp) * (size - cons2[j][23])) / size;
588 // System.out.println(tmp+ " " + j);
589 quality.setElementAt(new Double(tmp), j);
597 // System.out.println("Quality " + s);
598 qualityRange[0] = new Double(0);
599 qualityRange[1] = new Double(newmax);
603 * complete the given consensus and quuality annotation rows. Note: currently
604 * this method will enlarge the given annotation row if it is too small,
605 * otherwise will leave its length unchanged.
607 * @param conservation
608 * conservation annotation row
610 * (optional - may be null)
612 * first column for conservation
614 * extent of conservation
616 public void completeAnnotations(AlignmentAnnotation conservation,
617 AlignmentAnnotation quality2, int istart, int alWidth)
619 char[] sequence = getConsSequence().getSequence();
631 maxB = 0f - minB; // scalable range for colouring both Conservation and
641 if (conservation.annotations != null
642 && conservation.annotations.length < alWidth)
644 conservation.annotations = new Annotation[alWidth];
647 if (quality2 != null)
649 quality2.graphMax = qualityRange[1].floatValue();
650 if (quality2.annotations != null
651 && quality2.annotations.length < alWidth)
653 quality2.annotations = new Annotation[alWidth];
655 qmin = qualityRange[0].floatValue();
656 qmax = qualityRange[1].floatValue();
659 for (int i = 0; i < alWidth; i++)
665 if (Character.isDigit(c))
667 value = (int) (c - '0');
678 float vprop = value - min;
680 conservation.annotations[i] = new Annotation(String.valueOf(c),
681 String.valueOf(value), ' ', value, new Color(minR
682 + (maxR * vprop), minG + (maxG * vprop), minB
686 if (quality2 != null)
688 value = ((Double) quality.elementAt(i)).floatValue();
689 vprop = value - qmin;
691 quality2.annotations[i] = new Annotation(" ",
692 String.valueOf(value), ' ', value, new Color(minR
693 + (maxR * vprop), minG + (maxG * vprop), minB