2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.1)
3 * Copyright (C) 2014 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 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/>.
17 * The Jalview Authors are detailed in the 'AUTHORS' file.
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 is 3
82 * sequences to be used in calculation
84 * start residue position
86 * end residue position
88 public Conservation(String name, Hashtable propHash, int threshold,
89 List<SequenceI> 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;
105 for (s = 0; s < sSize; s++)
107 sarray[s] = (SequenceI) sequences.get(s);
108 if (sarray[s].getLength() > maxLength)
110 maxLength = sarray[s].getLength();
113 } catch (ArrayIndexOutOfBoundsException ex)
115 // bail - another thread has modified the sequence array, so the current
116 // calculation is probably invalid.
117 this.sequences = new SequenceI[0];
123 * Translate sequence i into a numerical representation and store it in the
124 * i'th position of the seqNums array.
128 private void calcSeqNum(int i)
130 String sq = null; // for dumb jbuilder not-inited exception warning
133 int sSize = sequences.length;
135 if ((i > -1) && (i < sSize))
137 sq = sequences[i].getSequenceAsString();
139 if (seqNums.size() <= i)
141 seqNums.addElement(new int[sq.length() + 1]);
144 if (sq.hashCode() != ((int[]) seqNums.elementAt(i))[0])
148 seqNumsChanged = true;
156 sqnum = new int[len + 1]; // better to always make a new array -
157 // sequence can change its length
158 sqnum[0] = sq.hashCode();
160 for (j = 1; j <= len; j++)
162 sqnum[j] = jalview.schemes.ResidueProperties.aaIndex[sq
166 seqNums.setElementAt(sqnum, i);
170 System.out.println("SEQUENCE HAS BEEN DELETED!!!");
175 // JBPNote INFO level debug
177 .println("ERROR: calcSeqNum called with out of range sequence index for Alignment\n");
182 * Calculates the conservation values for given set of sequences
184 public void calculate()
186 Hashtable resultHash, ht;
187 int thresh, j, jSize = sequences.length;
188 int[] values; // Replaces residueHash
189 String type, res = null;
191 Enumeration enumeration2;
193 total = new Hashtable[maxLength];
195 for (int i = start; i <= end; i++)
197 values = new int[255];
199 for (j = 0; j < jSize; j++)
201 if (sequences[j].getLength() > i)
203 c = sequences[j].getCharAt(i);
206 { // lookup the base aa code symbol
207 c = (char) jalview.schemes.ResidueProperties.aaIndex[sequences[j]
215 // recover canonical aa symbol
216 c = jalview.schemes.ResidueProperties.aa[c].charAt(0);
221 // original behaviour - operate on ascii symbols directly
222 // No need to check if its a '-'
223 if (c == '.' || c == ' ')
228 if (!canonicaliseAa && 'a' <= c && c <= 'z')
230 c -= (32); // 32 = 'a' - 'A'
241 // What is the count threshold to count the residues in residueHash()
242 thresh = (threshold * (jSize)) / 100;
244 // loop over all the found residues
245 resultHash = new Hashtable();
246 for (char v = '-'; v < 'Z'; v++)
249 if (values[v] > thresh)
251 res = String.valueOf(v);
253 // Now loop over the properties
254 enumeration2 = propHash.keys();
256 while (enumeration2.hasMoreElements())
258 type = (String) enumeration2.nextElement();
259 ht = (Hashtable) propHash.get(type);
261 // Have we ticked this before?
262 if (!resultHash.containsKey(type))
264 if (ht.containsKey(res))
266 resultHash.put(type, ht.get(res));
270 resultHash.put(type, ht.get("-"));
273 else if (((Integer) resultHash.get(type)).equals((Integer) ht
276 resultHash.put(type, new Integer(-1));
282 if (total.length > 0)
284 total[i - start] = resultHash;
289 /*****************************************************************************
290 * count conservation for the j'th column of the alignment
292 * @return { gap count, conserved residue count}
294 public int[] countConsNGaps(int j)
299 int[] r = new int[2];
301 int i, iSize = sequences.length;
304 for (i = 0; i < iSize; i++)
306 if (j >= sequences[i].getLength())
312 c = sequences[i].getCharAt(j); // gaps do not have upper/lower case
314 if (jalview.util.Comparison.isGap((c)))
334 r[0] = (nres == cons) ? 1 : 0;
341 * Calculates the conservation sequence
344 * if true, poitiveve conservation; false calculates negative
346 * @param percentageGaps
347 * commonly used value is 25
349 public void verdict(boolean consflag, float percentageGaps)
351 StringBuffer consString = new StringBuffer();
357 Hashtable resultHash;
358 Enumeration enumeration;
360 // NOTE THIS SHOULD CHECK IF THE CONSEQUENCE ALREADY
361 // EXISTS AND NOT OVERWRITE WITH '-', BUT THIS CASE
362 // DOES NOT EXIST IN JALVIEW 2.1.2
363 for (int i = 0; i < start; i++)
365 consString.append('-');
368 for (int i = start; i <= end; i++)
370 gapcons = countConsNGaps(i);
371 totGaps = gapcons[1];
372 pgaps = ((float) totGaps * 100) / (float) sequences.length;
374 if (percentageGaps > pgaps)
376 resultHash = total[i - start];
378 // Now find the verdict
380 enumeration = resultHash.keys();
382 while (enumeration.hasMoreElements())
384 type = (String) enumeration.nextElement();
385 result = (Integer) resultHash.get(type);
387 // Do we want to count +ve conservation or +ve and -ve cons.?
390 if (result.intValue() == 1)
397 if (result.intValue() != -1)
406 consString.append(count); // Conserved props!=Identity
410 consString.append((gapcons[0] == 1) ? "*" : "+");
415 consString.append('-');
419 consSequence = new Sequence(name, consString.toString(), start, end);
425 * @return Conservation sequence
427 public Sequence getConsSequence()
432 // From Alignment.java in jalview118
433 public void findQuality()
435 findQuality(0, maxLength - 1);
441 private void percentIdentity2()
443 seqNums = new Vector();
445 int i = 0, iSize = sequences.length;
446 // Do we need to calculate this again?
447 for (i = 0; i < iSize; i++)
452 if ((cons2 == null) || seqNumsChanged)
454 cons2 = new int[maxLength][24];
456 // Initialize the array
457 for (int j = 0; j < 24; j++)
459 for (i = 0; i < maxLength; i++)
468 while (j < sequences.length)
470 sqnum = (int[]) seqNums.elementAt(j);
472 for (i = 1; i < sqnum.length; i++)
474 cons2[i - 1][sqnum[i]]++;
477 for (i = sqnum.length - 1; i < maxLength; i++)
479 cons2[i][23]++; // gap count
488 * for (int i=start; i <= end; i++) { int max = -1000; int maxi = -1; int
491 * for (int j=0;j<24;j++) { if (cons2[i][j] > max) { max = cons2[i][j];
492 * maxi = i; maxj = j; } } }
498 * Calculates the quality of the set of sequences
505 public void findQuality(int start, int end)
507 quality = new Vector();
510 int[][] BLOSUM62 = jalview.schemes.ResidueProperties.getBLOSUM62();
512 // Loop over columns // JBPNote Profiling info
513 // long ts = System.currentTimeMillis();
514 // long te = System.currentTimeMillis();
517 int size = seqNums.size();
518 int[] lengths = new int[size];
519 double tot, bigtot, sr, tmp;
521 int l, j, i, ii, i2, k, seqNum;
523 for (l = 0; l < size; l++)
525 lengths[l] = ((int[]) seqNums.elementAt(l)).length - 1;
528 for (j = start; j <= end; j++)
532 // First Xr = depends on column only
535 for (ii = 0; ii < 24; ii++)
539 for (i2 = 0; i2 < 24; i2++)
541 x[ii] += (((double) cons2[j][i2] * BLOSUM62[ii][i2]) + 4);
547 // Now calculate D for each position and sum
548 for (k = 0; k < size; k++)
552 seqNum = (j < lengths[k]) ? ((int[]) seqNums.elementAt(k))[j + 1]
553 : 23; // Sequence, or gap at the end
555 // This is a loop over r
556 for (i = 0; i < 23; i++)
560 sr = (double) BLOSUM62[i][seqNum] + 4;
562 // Calculate X with another loop over residues
563 // System.out.println("Xi " + i + " " + x[i] + " " + sr);
566 tot += (xx[i] * xx[i]);
569 bigtot += Math.sqrt(tot);
572 // This is the quality for one column
578 // bigtot = bigtot * (size-cons2[j][23])/size;
579 quality.addElement(new Double(bigtot));
581 // Need to normalize by gaps
584 double newmax = -10000;
586 for (j = start; j <= end; j++)
588 tmp = ((Double) quality.elementAt(j)).doubleValue();
589 tmp = ((max - tmp) * (size - cons2[j][23])) / size;
591 // System.out.println(tmp+ " " + j);
592 quality.setElementAt(new Double(tmp), j);
600 // System.out.println("Quality " + s);
601 qualityRange[0] = new Double(0);
602 qualityRange[1] = new Double(newmax);
606 * complete the given consensus and quuality annotation rows. Note: currently
607 * this method will enlarge the given annotation row if it is too small,
608 * otherwise will leave its length unchanged.
610 * @param conservation
611 * conservation annotation row
613 * (optional - may be null)
615 * first column for conservation
617 * extent of conservation
619 public void completeAnnotations(AlignmentAnnotation conservation,
620 AlignmentAnnotation quality2, int istart, int alWidth)
622 char[] sequence = getConsSequence().getSequence();
634 maxB = 0f - minB; // scalable range for colouring both Conservation and
644 if (conservation.annotations != null
645 && conservation.annotations.length < alWidth)
647 conservation.annotations = new Annotation[alWidth];
650 if (quality2 != null)
652 quality2.graphMax = qualityRange[1].floatValue();
653 if (quality2.annotations != null
654 && quality2.annotations.length < alWidth)
656 quality2.annotations = new Annotation[alWidth];
658 qmin = qualityRange[0].floatValue();
659 qmax = qualityRange[1].floatValue();
662 for (int i = 0; i < alWidth; i++)
668 if (Character.isDigit(c))
670 value = (int) (c - '0');
681 float vprop = value - min;
683 conservation.annotations[i] = new Annotation(String.valueOf(c),
684 String.valueOf(value), ' ', value, new Color(minR
685 + (maxR * vprop), minG + (maxG * vprop), minB
689 if (quality2 != null)
691 value = ((Double) quality.elementAt(i)).floatValue();
692 vprop = value - qmin;
694 quality2.annotations[i] = new Annotation(" ",
695 String.valueOf(value), ' ', value, new Color(minR
696 + (maxR * vprop), minG + (maxG * vprop), minB
703 * construct and call the calculation methods on a new Conservation object
706 * - name of conservation
708 * - hash table of properties for each amino acid (normally
709 * ResidueProperties.propHash)
711 * - minimum number of conserved residues needed to indicate
712 * conservation (typically 3)
715 * first column in calculation window
717 * last column in calculation window
719 * positive (true) or negative (false) conservation
720 * @param consPercGaps
721 * percentage of gaps tolerated in column
723 * flag indicating if alignment quality should be calculated
724 * @return Conservation object ready for use in visualization
726 public static Conservation calculateConservation(String name,
727 Hashtable consHash, int threshold, List<SequenceI> seqs,
728 int start, int end, boolean posOrNeg, int consPercGaps,
731 Conservation cons = new Conservation(name, consHash, threshold, seqs,
733 return calculateConservation(cons, posOrNeg, consPercGaps, calcQuality);
738 * positive (true) or negative (false) conservation
739 * @param consPercGaps
740 * percentage of gaps tolerated in column
742 * flag indicating if alignment quality should be calculated
743 * @return Conservation object ready for use in visualization
745 public static Conservation calculateConservation(Conservation cons,
746 boolean b, int consPercGaps, boolean calcQuality)
749 cons.verdict(b, consPercGaps);