2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
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
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
21 package jalview.analysis;
23 import java.awt.Color;
26 import jalview.datamodel.*;
29 * Calculates conservation values for a given set of sequences
34 public class Conservation
36 SequenceI[] sequences;
42 Vector seqNums; // vector of int vectors where first is sequence checksum
44 int maxLength = 0; // used by quality calcs
46 boolean seqNumsChanged = false; // updated after any change via calcSeqNum;
50 boolean canonicaliseAa = true; // if true then conservation calculation will
52 // map all symbols to canonical aa numbering
53 // rather than consider conservation of that
56 /** Stores calculated quality values */
57 public Vector quality;
59 /** Stores maximum and minimum values of quality values */
60 public Double[] qualityRange = new Double[2];
62 String consString = "";
64 Sequence consSequence;
74 private String[] consSymbs;
77 * Creates a new Conservation object.
80 * Name of conservation
82 * hash of properties for each symbol
84 * to count the residues in residueHash(). commonly used value is 3
86 * sequences to be used in calculation
88 * start residue position
90 * end residue position
92 public Conservation(String name, Hashtable propHash, int threshold,
93 List<SequenceI> sequences, int start, int end)
96 this.propHash = propHash;
97 this.threshold = threshold;
101 maxLength = end - start + 1; // default width includes bounds of
104 int s, sSize = sequences.size();
105 SequenceI[] sarray = new SequenceI[sSize];
106 this.sequences = sarray;
109 for (s = 0; s < sSize; s++)
111 sarray[s] = (SequenceI) sequences.get(s);
112 if (sarray[s].getLength() > maxLength)
114 maxLength = sarray[s].getLength();
117 } catch (ArrayIndexOutOfBoundsException ex)
119 // bail - another thread has modified the sequence array, so the current
120 // calculation is probably invalid.
121 this.sequences = new SequenceI[0];
127 * Translate sequence i into a numerical representation and store it in the
128 * i'th position of the seqNums array.
132 private void calcSeqNum(int i)
134 String sq = null; // for dumb jbuilder not-inited exception warning
137 int sSize = sequences.length;
139 if ((i > -1) && (i < sSize))
141 sq = sequences[i].getSequenceAsString();
143 if (seqNums.size() <= i)
145 seqNums.addElement(new int[sq.length() + 1]);
148 if (sq.hashCode() != ((int[]) seqNums.elementAt(i))[0])
152 seqNumsChanged = true;
160 sqnum = new int[len + 1]; // better to always make a new array -
161 // sequence can change its length
162 sqnum[0] = sq.hashCode();
164 for (j = 1; j <= len; j++)
166 sqnum[j] = jalview.schemes.ResidueProperties.aaIndex[sq
170 seqNums.setElementAt(sqnum, i);
174 System.out.println("SEQUENCE HAS BEEN DELETED!!!");
179 // JBPNote INFO level debug
181 .println("ERROR: calcSeqNum called with out of range sequence index for Alignment\n");
186 * Calculates the conservation values for given set of sequences
188 public void calculate()
190 Hashtable resultHash, ht;
191 int thresh, j, jSize = sequences.length;
192 int[] values; // Replaces residueHash
193 String type, res = null;
195 Enumeration enumeration2;
197 total = new Hashtable[maxLength];
199 for (int i = start; i <= end; i++)
201 values = new int[255];
203 for (j = 0; j < jSize; j++)
205 if (sequences[j].getLength() > i)
207 c = sequences[j].getCharAt(i);
210 { // lookup the base aa code symbol
211 c = (char) jalview.schemes.ResidueProperties.aaIndex[sequences[j]
219 // recover canonical aa symbol
220 c = jalview.schemes.ResidueProperties.aa[c].charAt(0);
225 // original behaviour - operate on ascii symbols directly
226 // No need to check if its a '-'
227 if (c == '.' || c == ' ')
232 if (!canonicaliseAa && 'a' <= c && c <= 'z')
234 c -= (32); // 32 = 'a' - 'A'
245 // What is the count threshold to count the residues in residueHash()
246 thresh = (threshold * (jSize)) / 100;
248 // loop over all the found residues
249 resultHash = new Hashtable();
250 for (char v = '-'; v < 'Z'; v++)
253 if (values[v] > thresh)
255 res = String.valueOf(v);
257 // Now loop over the properties
258 enumeration2 = propHash.keys();
260 while (enumeration2.hasMoreElements())
262 type = (String) enumeration2.nextElement();
263 ht = (Hashtable) propHash.get(type);
265 // Have we ticked this before?
266 if (!resultHash.containsKey(type))
268 if (ht.containsKey(res))
270 resultHash.put(type, ht.get(res));
274 resultHash.put(type, ht.get("-"));
277 else if (((Integer) resultHash.get(type)).equals((Integer) ht
280 resultHash.put(type, new Integer(-1));
286 if (total.length > 0)
288 total[i - start] = resultHash;
293 /*****************************************************************************
294 * count conservation for the j'th column of the alignment
296 * @return { gap count, conserved residue count}
298 public int[] countConsNGaps(int j)
303 int[] r = new int[2];
305 int i, iSize = sequences.length;
308 for (i = 0; i < iSize; i++)
310 if (j >= sequences[i].getLength())
316 c = sequences[i].getCharAt(j); // gaps do not have upper/lower case
318 if (jalview.util.Comparison.isGap((c)))
338 r[0] = (nres == cons) ? 1 : 0;
345 * Calculates the conservation sequence
348 * if true, poitiveve conservation; false calculates negative
350 * @param percentageGaps
351 * commonly used value is 25
353 public void verdict(boolean consflag, float percentageGaps)
355 StringBuffer consString = new StringBuffer();
361 Hashtable resultHash;
362 Enumeration enumeration;
364 // NOTE THIS SHOULD CHECK IF THE CONSEQUENCE ALREADY
365 // EXISTS AND NOT OVERWRITE WITH '-', BUT THIS CASE
366 // DOES NOT EXIST IN JALVIEW 2.1.2
367 for (int i = 0; i < start; i++)
369 consString.append('-');
371 consSymbs = new String[end-start+1];
372 for (int i = start; i <= end; i++)
374 gapcons = countConsNGaps(i);
375 totGaps = gapcons[1];
376 pgaps = ((float) totGaps * 100) / (float) sequences.length;
377 consSymbs[i-start]=new String();
379 if (percentageGaps > pgaps)
381 resultHash = total[i - start];
382 // Now find the verdict
384 enumeration = resultHash.keys();
386 while (enumeration.hasMoreElements())
388 type = (String) enumeration.nextElement();
389 result = (Integer) resultHash.get(type);
390 // Do we want to count +ve conservation or +ve and -ve cons.?
393 if (result.intValue() == 1)
395 consSymbs[i-start] = type+" "+consSymbs[i-start];
401 if (result.intValue() != -1)
404 if (result.intValue()==0) {
405 consSymbs[i-start] = consSymbs[i-start]+ " !"+type;
407 consSymbs[i-start] = type+" "+consSymbs[i-start];
418 consString.append(count); // Conserved props!=Identity
422 consString.append((gapcons[0] == 1) ? "*" : "+");
427 consString.append('-');
431 consSequence = new Sequence(name, consString.toString(), start, end);
437 * @return Conservation sequence
439 public Sequence getConsSequence()
444 // From Alignment.java in jalview118
445 public void findQuality()
447 findQuality(0, maxLength - 1);
453 private void percentIdentity2()
455 seqNums = new Vector();
457 int i = 0, iSize = sequences.length;
458 // Do we need to calculate this again?
459 for (i = 0; i < iSize; i++)
464 if ((cons2 == null) || seqNumsChanged)
466 cons2 = new int[maxLength][24];
468 // Initialize the array
469 for (int j = 0; j < 24; j++)
471 for (i = 0; i < maxLength; i++)
480 while (j < sequences.length)
482 sqnum = (int[]) seqNums.elementAt(j);
484 for (i = 1; i < sqnum.length; i++)
486 cons2[i - 1][sqnum[i]]++;
489 for (i = sqnum.length - 1; i < maxLength; i++)
491 cons2[i][23]++; // gap count
500 * for (int i=start; i <= end; i++) { int max = -1000; int maxi = -1; int
503 * for (int j=0;j<24;j++) { if (cons2[i][j] > max) { max = cons2[i][j];
504 * maxi = i; maxj = j; } } }
510 * Calculates the quality of the set of sequences
517 public void findQuality(int start, int end)
519 quality = new Vector();
522 int[][] BLOSUM62 = jalview.schemes.ResidueProperties.getBLOSUM62();
524 // Loop over columns // JBPNote Profiling info
525 // long ts = System.currentTimeMillis();
526 // long te = System.currentTimeMillis();
529 int size = seqNums.size();
530 int[] lengths = new int[size];
531 double tot, bigtot, sr, tmp;
533 int l, j, i, ii, i2, k, seqNum;
535 for (l = 0; l < size; l++)
537 lengths[l] = ((int[]) seqNums.elementAt(l)).length - 1;
540 for (j = start; j <= end; j++)
544 // First Xr = depends on column only
547 for (ii = 0; ii < 24; ii++)
551 for (i2 = 0; i2 < 24; i2++)
553 x[ii] += (((double) cons2[j][i2] * BLOSUM62[ii][i2]) + 4);
559 // Now calculate D for each position and sum
560 for (k = 0; k < size; k++)
564 seqNum = (j < lengths[k]) ? ((int[]) seqNums.elementAt(k))[j + 1]
565 : 23; // Sequence, or gap at the end
567 // This is a loop over r
568 for (i = 0; i < 23; i++)
572 sr = (double) BLOSUM62[i][seqNum] + 4;
574 // Calculate X with another loop over residues
575 // System.out.println("Xi " + i + " " + x[i] + " " + sr);
578 tot += (xx[i] * xx[i]);
581 bigtot += Math.sqrt(tot);
584 // This is the quality for one column
590 // bigtot = bigtot * (size-cons2[j][23])/size;
591 quality.addElement(new Double(bigtot));
593 // Need to normalize by gaps
596 double newmax = -10000;
598 for (j = start; j <= end; j++)
600 tmp = ((Double) quality.elementAt(j)).doubleValue();
601 tmp = ((max - tmp) * (size - cons2[j][23])) / size;
603 // System.out.println(tmp+ " " + j);
604 quality.setElementAt(new Double(tmp), j);
612 // System.out.println("Quality " + s);
613 qualityRange[0] = new Double(0);
614 qualityRange[1] = new Double(newmax);
618 * complete the given consensus and quuality annotation rows. Note: currently
619 * this method will enlarge the given annotation row if it is too small,
620 * otherwise will leave its length unchanged.
622 * @param conservation
623 * conservation annotation row
625 * (optional - may be null)
627 * first column for conservation
629 * extent of conservation
631 public void completeAnnotations(AlignmentAnnotation conservation,
632 AlignmentAnnotation quality2, int istart, int alWidth)
634 char[] sequence = getConsSequence().getSequence();
646 maxB = 0f - minB; // scalable range for colouring both Conservation and
656 if (conservation.annotations != null
657 && conservation.annotations.length < alWidth)
659 conservation.annotations = new Annotation[alWidth];
662 if (quality2 != null)
664 quality2.graphMax = qualityRange[1].floatValue();
665 if (quality2.annotations != null
666 && quality2.annotations.length < alWidth)
668 quality2.annotations = new Annotation[alWidth];
670 qmin = qualityRange[0].floatValue();
671 qmax = qualityRange[1].floatValue();
674 for (int i = 0; i < alWidth; i++)
680 if (Character.isDigit(c))
682 value = (int) (c - '0');
693 float vprop = value - min;
695 conservation.annotations[i] = new Annotation(String.valueOf(c),
696 consSymbs[i-start], ' ', value, new Color(minR
697 + (maxR * vprop), minG + (maxG * vprop), minB
701 if (quality2 != null)
703 value = ((Double) quality.elementAt(i)).floatValue();
704 vprop = value - qmin;
706 quality2.annotations[i] = new Annotation(" ",
707 String.valueOf(value), ' ', value, new Color(minR
708 + (maxR * vprop), minG + (maxG * vprop), minB
715 * construct and call the calculation methods on a new Conservation object
718 * - name of conservation
720 * - hash table of properties for each amino acid (normally
721 * ResidueProperties.propHash)
723 * - minimum number of conserved residues needed to indicate
724 * conservation (typically 3)
727 * first column in calculation window
729 * last column in calculation window
731 * positive (true) or negative (false) conservation
732 * @param consPercGaps
733 * percentage of gaps tolerated in column
735 * flag indicating if alignment quality should be calculated
736 * @return Conservation object ready for use in visualization
738 public static Conservation calculateConservation(String name,
739 Hashtable consHash, int threshold, List<SequenceI> seqs,
740 int start, int end, boolean posOrNeg, int consPercGaps,
743 Conservation cons = new Conservation(name, consHash, threshold, seqs,
745 return calculateConservation(cons, posOrNeg, consPercGaps, calcQuality);
750 * positive (true) or negative (false) conservation
751 * @param consPercGaps
752 * percentage of gaps tolerated in column
754 * flag indicating if alignment quality should be calculated
755 * @return Conservation object ready for use in visualization
757 public static Conservation calculateConservation(Conservation cons,
758 boolean b, int consPercGaps, boolean calcQuality)
761 cons.verdict(b, consPercGaps);