2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.0b1)
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;
72 private String[] consSymbs;
75 * Creates a new Conservation object.
78 * Name of conservation
80 * hash of properties for each symbol
82 * to count the residues in residueHash(). commonly used value is 3
84 * sequences to be used in calculation
86 * start residue position
88 * end residue position
90 public Conservation(String name, Hashtable propHash, int threshold,
91 List<SequenceI> 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;
107 for (s = 0; s < sSize; s++)
109 sarray[s] = (SequenceI) sequences.get(s);
110 if (sarray[s].getLength() > maxLength)
112 maxLength = sarray[s].getLength();
115 } catch (ArrayIndexOutOfBoundsException ex)
117 // bail - another thread has modified the sequence array, so the current
118 // calculation is probably invalid.
119 this.sequences = new SequenceI[0];
125 * Translate sequence i into a numerical representation and store it in the
126 * i'th position of the seqNums array.
130 private void calcSeqNum(int i)
132 String sq = null; // for dumb jbuilder not-inited exception warning
135 int sSize = sequences.length;
137 if ((i > -1) && (i < sSize))
139 sq = sequences[i].getSequenceAsString();
141 if (seqNums.size() <= i)
143 seqNums.addElement(new int[sq.length() + 1]);
146 if (sq.hashCode() != ((int[]) seqNums.elementAt(i))[0])
150 seqNumsChanged = true;
158 sqnum = new int[len + 1]; // better to always make a new array -
159 // sequence can change its length
160 sqnum[0] = sq.hashCode();
162 for (j = 1; j <= len; j++)
164 sqnum[j] = jalview.schemes.ResidueProperties.aaIndex[sq
168 seqNums.setElementAt(sqnum, i);
172 System.out.println("SEQUENCE HAS BEEN DELETED!!!");
177 // JBPNote INFO level debug
179 .println("ERROR: calcSeqNum called with out of range sequence index for Alignment\n");
184 * Calculates the conservation values for given set of sequences
186 public void calculate()
188 Hashtable resultHash, ht;
189 int thresh, j, jSize = sequences.length;
190 int[] values; // Replaces residueHash
191 String type, res = null;
193 Enumeration enumeration2;
195 total = new Hashtable[maxLength];
197 for (int i = start; i <= end; i++)
199 values = new int[255];
201 for (j = 0; j < jSize; j++)
203 if (sequences[j].getLength() > i)
205 c = sequences[j].getCharAt(i);
208 { // lookup the base aa code symbol
209 c = (char) jalview.schemes.ResidueProperties.aaIndex[sequences[j]
217 // recover canonical aa symbol
218 c = jalview.schemes.ResidueProperties.aa[c].charAt(0);
223 // original behaviour - operate on ascii symbols directly
224 // No need to check if its a '-'
225 if (c == '.' || c == ' ')
230 if (!canonicaliseAa && 'a' <= c && c <= 'z')
232 c -= (32); // 32 = 'a' - 'A'
243 // What is the count threshold to count the residues in residueHash()
244 thresh = (threshold * (jSize)) / 100;
246 // loop over all the found residues
247 resultHash = new Hashtable();
248 for (char v = '-'; v < 'Z'; v++)
251 if (values[v] > thresh)
253 res = String.valueOf(v);
255 // Now loop over the properties
256 enumeration2 = propHash.keys();
258 while (enumeration2.hasMoreElements())
260 type = (String) enumeration2.nextElement();
261 ht = (Hashtable) propHash.get(type);
263 // Have we ticked this before?
264 if (!resultHash.containsKey(type))
266 if (ht.containsKey(res))
268 resultHash.put(type, ht.get(res));
272 resultHash.put(type, ht.get("-"));
275 else if (((Integer) resultHash.get(type)).equals((Integer) ht
278 resultHash.put(type, new Integer(-1));
284 if (total.length > 0)
286 total[i - start] = resultHash;
291 /*****************************************************************************
292 * count conservation for the j'th column of the alignment
294 * @return { gap count, conserved residue count}
296 public int[] countConsNGaps(int j)
301 int[] r = new int[2];
303 int i, iSize = sequences.length;
306 for (i = 0; i < iSize; i++)
308 if (j >= sequences[i].getLength())
314 c = sequences[i].getCharAt(j); // gaps do not have upper/lower case
316 if (jalview.util.Comparison.isGap((c)))
336 r[0] = (nres == cons) ? 1 : 0;
343 * Calculates the conservation sequence
346 * if true, poitiveve conservation; false calculates negative
348 * @param percentageGaps
349 * commonly used value is 25
351 public void verdict(boolean consflag, float percentageGaps)
353 StringBuffer consString = new StringBuffer();
359 Hashtable resultHash;
360 Enumeration enumeration;
362 // NOTE THIS SHOULD CHECK IF THE CONSEQUENCE ALREADY
363 // EXISTS AND NOT OVERWRITE WITH '-', BUT THIS CASE
364 // DOES NOT EXIST IN JALVIEW 2.1.2
365 for (int i = 0; i < start; i++)
367 consString.append('-');
369 consSymbs = new String[end-start+1];
370 for (int i = start; i <= end; i++)
372 gapcons = countConsNGaps(i);
373 totGaps = gapcons[1];
374 pgaps = ((float) totGaps * 100) / (float) sequences.length;
375 consSymbs[i-start]=new String();
377 if (percentageGaps > pgaps)
379 resultHash = total[i - start];
380 // Now find the verdict
382 enumeration = resultHash.keys();
384 while (enumeration.hasMoreElements())
386 type = (String) enumeration.nextElement();
387 result = (Integer) resultHash.get(type);
388 // Do we want to count +ve conservation or +ve and -ve cons.?
391 if (result.intValue() == 1)
393 consSymbs[i-start] = type+" "+consSymbs[i-start];
399 if (result.intValue() != -1)
402 if (result.intValue()==0) {
403 consSymbs[i-start] = consSymbs[i-start]+ " !"+type;
405 consSymbs[i-start] = type+" "+consSymbs[i-start];
416 consString.append(count); // Conserved props!=Identity
420 consString.append((gapcons[0] == 1) ? "*" : "+");
425 consString.append('-');
429 consSequence = new Sequence(name, consString.toString(), start, end);
435 * @return Conservation sequence
437 public Sequence getConsSequence()
442 // From Alignment.java in jalview118
443 public void findQuality()
445 findQuality(0, maxLength - 1);
451 private void percentIdentity2()
453 seqNums = new Vector();
455 int i = 0, iSize = sequences.length;
456 // Do we need to calculate this again?
457 for (i = 0; i < iSize; i++)
462 if ((cons2 == null) || seqNumsChanged)
464 cons2 = new int[maxLength][24];
466 // Initialize the array
467 for (int j = 0; j < 24; j++)
469 for (i = 0; i < maxLength; i++)
478 while (j < sequences.length)
480 sqnum = (int[]) seqNums.elementAt(j);
482 for (i = 1; i < sqnum.length; i++)
484 cons2[i - 1][sqnum[i]]++;
487 for (i = sqnum.length - 1; i < maxLength; i++)
489 cons2[i][23]++; // gap count
498 * for (int i=start; i <= end; i++) { int max = -1000; int maxi = -1; int
501 * for (int j=0;j<24;j++) { if (cons2[i][j] > max) { max = cons2[i][j];
502 * maxi = i; maxj = j; } } }
508 * Calculates the quality of the set of sequences
515 public void findQuality(int start, int end)
517 quality = new Vector();
520 int[][] BLOSUM62 = jalview.schemes.ResidueProperties.getBLOSUM62();
522 // Loop over columns // JBPNote Profiling info
523 // long ts = System.currentTimeMillis();
524 // long te = System.currentTimeMillis();
527 int size = seqNums.size();
528 int[] lengths = new int[size];
529 double tot, bigtot, sr, tmp;
531 int l, j, i, ii, i2, k, seqNum;
533 for (l = 0; l < size; l++)
535 lengths[l] = ((int[]) seqNums.elementAt(l)).length - 1;
538 for (j = start; j <= end; j++)
542 // First Xr = depends on column only
545 for (ii = 0; ii < 24; ii++)
549 for (i2 = 0; i2 < 24; i2++)
551 x[ii] += (((double) cons2[j][i2] * BLOSUM62[ii][i2]) + 4);
557 // Now calculate D for each position and sum
558 for (k = 0; k < size; k++)
562 seqNum = (j < lengths[k]) ? ((int[]) seqNums.elementAt(k))[j + 1]
563 : 23; // Sequence, or gap at the end
565 // This is a loop over r
566 for (i = 0; i < 23; i++)
570 sr = (double) BLOSUM62[i][seqNum] + 4;
572 // Calculate X with another loop over residues
573 // System.out.println("Xi " + i + " " + x[i] + " " + sr);
576 tot += (xx[i] * xx[i]);
579 bigtot += Math.sqrt(tot);
582 // This is the quality for one column
588 // bigtot = bigtot * (size-cons2[j][23])/size;
589 quality.addElement(new Double(bigtot));
591 // Need to normalize by gaps
594 double newmax = -10000;
596 for (j = start; j <= end; j++)
598 tmp = ((Double) quality.elementAt(j)).doubleValue();
599 tmp = ((max - tmp) * (size - cons2[j][23])) / size;
601 // System.out.println(tmp+ " " + j);
602 quality.setElementAt(new Double(tmp), j);
610 // System.out.println("Quality " + s);
611 qualityRange[0] = new Double(0);
612 qualityRange[1] = new Double(newmax);
616 * complete the given consensus and quuality annotation rows. Note: currently
617 * this method will enlarge the given annotation row if it is too small,
618 * otherwise will leave its length unchanged.
620 * @param conservation
621 * conservation annotation row
623 * (optional - may be null)
625 * first column for conservation
627 * extent of conservation
629 public void completeAnnotations(AlignmentAnnotation conservation,
630 AlignmentAnnotation quality2, int istart, int alWidth)
632 char[] sequence = getConsSequence().getSequence();
644 maxB = 0f - minB; // scalable range for colouring both Conservation and
654 if (conservation.annotations != null
655 && conservation.annotations.length < alWidth)
657 conservation.annotations = new Annotation[alWidth];
660 if (quality2 != null)
662 quality2.graphMax = qualityRange[1].floatValue();
663 if (quality2.annotations != null
664 && quality2.annotations.length < alWidth)
666 quality2.annotations = new Annotation[alWidth];
668 qmin = qualityRange[0].floatValue();
669 qmax = qualityRange[1].floatValue();
672 for (int i = 0; i < alWidth; i++)
678 if (Character.isDigit(c))
680 value = (int) (c - '0');
691 float vprop = value - min;
693 conservation.annotations[i] = new Annotation(String.valueOf(c),
694 consSymbs[i-start], ' ', value, new Color(minR
695 + (maxR * vprop), minG + (maxG * vprop), minB
699 if (quality2 != null)
701 value = ((Double) quality.elementAt(i)).floatValue();
702 vprop = value - qmin;
704 quality2.annotations[i] = new Annotation(" ",
705 String.valueOf(value), ' ', value, new Color(minR
706 + (maxR * vprop), minG + (maxG * vprop), minB
713 * construct and call the calculation methods on a new Conservation object
716 * - name of conservation
718 * - hash table of properties for each amino acid (normally
719 * ResidueProperties.propHash)
721 * - minimum number of conserved residues needed to indicate
722 * conservation (typically 3)
725 * first column in calculation window
727 * last column in calculation window
729 * positive (true) or negative (false) conservation
730 * @param consPercGaps
731 * percentage of gaps tolerated in column
733 * flag indicating if alignment quality should be calculated
734 * @return Conservation object ready for use in visualization
736 public static Conservation calculateConservation(String name,
737 Hashtable consHash, int threshold, List<SequenceI> seqs,
738 int start, int end, boolean posOrNeg, int consPercGaps,
741 Conservation cons = new Conservation(name, consHash, threshold, seqs,
743 return calculateConservation(cons, posOrNeg, consPercGaps, calcQuality);
748 * positive (true) or negative (false) conservation
749 * @param consPercGaps
750 * percentage of gaps tolerated in column
752 * flag indicating if alignment quality should be calculated
753 * @return Conservation object ready for use in visualization
755 public static Conservation calculateConservation(Conservation cons,
756 boolean b, int consPercGaps, boolean calcQuality)
759 cons.verdict(b, consPercGaps);