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();
115 * Translate sequence i into a numerical representation and store it in the
116 * i'th position of the seqNums array.
120 private void calcSeqNum(int i)
122 String sq = null; // for dumb jbuilder not-inited exception warning
125 int sSize = sequences.length;
127 if ((i > -1) && (i < sSize))
129 sq = sequences[i].getSequenceAsString();
131 if (seqNums.size() <= i)
133 seqNums.addElement(new int[sq.length() + 1]);
136 if (sq.hashCode() != ((int[]) seqNums.elementAt(i))[0])
140 seqNumsChanged = true;
148 sqnum = new int[len + 1]; // better to always make a new array -
149 // sequence can change its length
150 sqnum[0] = sq.hashCode();
152 for (j = 1; j <= len; j++)
154 sqnum[j] = jalview.schemes.ResidueProperties.aaIndex[sq
158 seqNums.setElementAt(sqnum, i);
162 System.out.println("SEQUENCE HAS BEEN DELETED!!!");
167 // JBPNote INFO level debug
169 .println("ERROR: calcSeqNum called with out of range sequence index for Alignment\n");
174 * Calculates the conservation values for given set of sequences
176 public void calculate()
178 Hashtable resultHash, ht;
179 int thresh, j, jSize = sequences.length;
180 int[] values; // Replaces residueHash
181 String type, res = null;
183 Enumeration enumeration2;
185 total = new Hashtable[maxLength];
187 for (int i = start; i <= end; i++)
189 values = new int[255];
191 for (j = 0; j < jSize; j++)
193 if (sequences[j].getLength() > i)
195 c = sequences[j].getCharAt(i);
198 { // lookup the base aa code symbol
199 c = (char) jalview.schemes.ResidueProperties.aaIndex[sequences[j]
207 // recover canonical aa symbol
208 c = jalview.schemes.ResidueProperties.aa[c].charAt(0);
213 // original behaviour - operate on ascii symbols directly
214 // No need to check if its a '-'
215 if (c == '.' || c == ' ')
220 if (!canonicaliseAa && 'a' <= c && c <= 'z')
222 c -= (32); // 32 = 'a' - 'A'
233 // What is the count threshold to count the residues in residueHash()
234 thresh = (threshold * (jSize)) / 100;
236 // loop over all the found residues
237 resultHash = new Hashtable();
238 for (char v = '-'; v < 'Z'; v++)
241 if (values[v] > thresh)
243 res = String.valueOf(v);
245 // Now loop over the properties
246 enumeration2 = propHash.keys();
248 while (enumeration2.hasMoreElements())
250 type = (String) enumeration2.nextElement();
251 ht = (Hashtable) propHash.get(type);
253 // Have we ticked this before?
254 if (!resultHash.containsKey(type))
256 if (ht.containsKey(res))
258 resultHash.put(type, ht.get(res));
262 resultHash.put(type, ht.get("-"));
265 else if (((Integer) resultHash.get(type)).equals((Integer) ht
268 resultHash.put(type, new Integer(-1));
274 total[i - start] = resultHash;
278 /*****************************************************************************
279 * count conservation for the j'th column of the alignment
281 * @return { gap count, conserved residue count}
283 public int[] countConsNGaps(int j)
288 int[] r = new int[2];
290 int i, iSize = sequences.length;
293 for (i = 0; i < iSize; i++)
295 if (j >= sequences[i].getLength())
301 c = sequences[i].getCharAt(j); // gaps do not have upper/lower case
303 if (jalview.util.Comparison.isGap((c)))
323 r[0] = (nres == cons) ? 1 : 0;
330 * Calculates the conservation sequence
333 * if true, poitiveve conservation; false calculates negative
335 * @param percentageGaps
336 * commonly used value is 25
338 public void verdict(boolean consflag, float percentageGaps)
340 StringBuffer consString = new StringBuffer();
346 Hashtable resultHash;
347 Enumeration enumeration;
349 // NOTE THIS SHOULD CHECK IF THE CONSEQUENCE ALREADY
350 // EXISTS AND NOT OVERWRITE WITH '-', BUT THIS CASE
351 // DOES NOT EXIST IN JALVIEW 2.1.2
352 for (int i = 0; i < start; i++)
354 consString.append('-');
357 for (int i = start; i <= end; i++)
359 gapcons = countConsNGaps(i);
360 totGaps = gapcons[1];
361 pgaps = ((float) totGaps * 100) / (float) sequences.length;
363 if (percentageGaps > pgaps)
365 resultHash = total[i - start];
367 // Now find the verdict
369 enumeration = resultHash.keys();
371 while (enumeration.hasMoreElements())
373 type = (String) enumeration.nextElement();
374 result = (Integer) resultHash.get(type);
376 // Do we want to count +ve conservation or +ve and -ve cons.?
379 if (result.intValue() == 1)
386 if (result.intValue() != -1)
395 consString.append(count); // Conserved props!=Identity
399 consString.append((gapcons[0] == 1) ? "*" : "+");
404 consString.append('-');
408 consSequence = new Sequence(name, consString.toString(), start, end);
414 * @return Conservation sequence
416 public Sequence getConsSequence()
421 // From Alignment.java in jalview118
422 public void findQuality()
424 findQuality(0, maxLength - 1);
430 private void percentIdentity2()
432 seqNums = new Vector();
434 int i = 0, iSize = sequences.length;
435 // Do we need to calculate this again?
436 for (i = 0; i < iSize; i++)
441 if ((cons2 == null) || seqNumsChanged)
443 cons2 = new int[maxLength][24];
445 // Initialize the array
446 for (int j = 0; j < 24; j++)
448 for (i = 0; i < maxLength; i++)
457 while (j < sequences.length)
459 sqnum = (int[]) seqNums.elementAt(j);
461 for (i = 1; i < sqnum.length; i++)
463 cons2[i - 1][sqnum[i]]++;
466 for (i = sqnum.length - 1; i < maxLength; i++)
468 cons2[i][23]++; // gap count
477 * for (int i=start; i <= end; i++) { int max = -1000; int maxi = -1; int
480 * for (int j=0;j<24;j++) { if (cons2[i][j] > max) { max = cons2[i][j];
481 * maxi = i; maxj = j; } } }
487 * Calculates the quality of the set of sequences
494 public void findQuality(int start, int end)
496 quality = new Vector();
499 int[][] BLOSUM62 = jalview.schemes.ResidueProperties.getBLOSUM62();
501 // Loop over columns // JBPNote Profiling info
502 // long ts = System.currentTimeMillis();
503 // long te = System.currentTimeMillis();
506 int size = seqNums.size();
507 int[] lengths = new int[size];
508 double tot, bigtot, sr, tmp;
510 int l, j, i, ii, i2, k, seqNum;
512 for (l = 0; l < size; l++)
514 lengths[l] = ((int[]) seqNums.elementAt(l)).length - 1;
517 for (j = start; j <= end; j++)
521 // First Xr = depends on column only
524 for (ii = 0; ii < 24; ii++)
528 for (i2 = 0; i2 < 24; i2++)
530 x[ii] += (((double) cons2[j][i2] * BLOSUM62[ii][i2]) + 4);
536 // Now calculate D for each position and sum
537 for (k = 0; k < size; k++)
541 seqNum = (j < lengths[k]) ? ((int[]) seqNums.elementAt(k))[j + 1]
542 : 23; // Sequence, or gap at the end
544 // This is a loop over r
545 for (i = 0; i < 23; i++)
549 sr = (double) BLOSUM62[i][seqNum] + 4;
551 // Calculate X with another loop over residues
552 // System.out.println("Xi " + i + " " + x[i] + " " + sr);
555 tot += (xx[i] * xx[i]);
558 bigtot += Math.sqrt(tot);
561 // This is the quality for one column
567 // bigtot = bigtot * (size-cons2[j][23])/size;
568 quality.addElement(new Double(bigtot));
570 // Need to normalize by gaps
573 double newmax = -10000;
575 for (j = start; j <= end; j++)
577 tmp = ((Double) quality.elementAt(j)).doubleValue();
578 tmp = ((max - tmp) * (size - cons2[j][23])) / size;
580 // System.out.println(tmp+ " " + j);
581 quality.setElementAt(new Double(tmp), j);
589 // System.out.println("Quality " + s);
590 qualityRange[0] = new Double(0);
591 qualityRange[1] = new Double(newmax);
595 * complete the given consensus and quuality annotation rows. Note: currently
596 * this method will enlarge the given annotation row if it is too small,
597 * otherwise will leave its length unchanged.
599 * @param conservation
600 * conservation annotation row
602 * (optional - may be null)
604 * first column for conservation
606 * extent of conservation
608 public void completeAnnotations(AlignmentAnnotation conservation,
609 AlignmentAnnotation quality2, int istart, int alWidth)
611 char[] sequence = getConsSequence().getSequence();
623 maxB = 0f - minB; // scalable range for colouring both Conservation and
633 if (conservation.annotations != null
634 && conservation.annotations.length < alWidth)
636 conservation.annotations = new Annotation[alWidth];
639 if (quality2 != null)
641 quality2.graphMax = qualityRange[1].floatValue();
642 if (quality2.annotations != null
643 && quality2.annotations.length < alWidth)
645 quality2.annotations = new Annotation[alWidth];
647 qmin = qualityRange[0].floatValue();
648 qmax = qualityRange[1].floatValue();
651 for (int i = 0; i < alWidth; i++)
657 if (Character.isDigit(c))
659 value = (int) (c - '0');
670 float vprop = value - min;
672 conservation.annotations[i] = new Annotation(String.valueOf(c),
673 String.valueOf(value), ' ', value, new Color(minR
674 + (maxR * vprop), minG + (maxG * vprop), minB
678 if (quality2 != null)
680 value = ((Double) quality.elementAt(i)).floatValue();
681 vprop = value - qmin;
683 quality2.annotations[i] = new Annotation(" ",
684 String.valueOf(value), ' ', value, new Color(minR
685 + (maxR * vprop), minG + (maxG * vprop), minB