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 jalview.datamodel.AlignmentAnnotation;
24 import jalview.datamodel.Annotation;
25 import jalview.datamodel.Sequence;
26 import jalview.datamodel.SequenceI;
28 import java.awt.Color;
29 import java.util.Enumeration;
30 import java.util.Hashtable;
31 import java.util.List;
32 import java.util.Vector;
35 * Calculates conservation values for a given set of sequences
40 public class Conservation
42 SequenceI[] sequences;
48 Vector seqNums; // vector of int vectors where first is sequence checksum
50 int maxLength = 0; // used by quality calcs
52 boolean seqNumsChanged = false; // updated after any change via calcSeqNum;
56 boolean canonicaliseAa = true; // if true then conservation calculation will
58 // map all symbols to canonical aa numbering
59 // rather than consider conservation of that
62 /** Stores calculated quality values */
63 public Vector quality;
65 /** Stores maximum and minimum values of quality values */
66 public Double[] qualityRange = new Double[2];
68 String consString = "";
70 Sequence consSequence;
80 private String[] consSymbs;
83 * Creates a new Conservation object.
86 * Name of conservation
88 * hash of properties for each symbol
90 * to count the residues in residueHash(). commonly used value is 3
92 * sequences to be used in calculation
94 * start residue position
96 * end residue position
98 public Conservation(String name, Hashtable propHash, int threshold,
99 List<SequenceI> sequences, int start, int end)
102 this.propHash = propHash;
103 this.threshold = threshold;
107 maxLength = end - start + 1; // default width includes bounds of
110 int s, sSize = sequences.size();
111 SequenceI[] sarray = new SequenceI[sSize];
112 this.sequences = sarray;
115 for (s = 0; s < sSize; s++)
117 sarray[s] = sequences.get(s);
118 if (sarray[s].getLength() > maxLength)
120 maxLength = sarray[s].getLength();
123 } catch (ArrayIndexOutOfBoundsException ex)
125 // bail - another thread has modified the sequence array, so the current
126 // calculation is probably invalid.
127 this.sequences = new SequenceI[0];
133 * Translate sequence i into a numerical representation and store it in the
134 * i'th position of the seqNums array.
138 private void calcSeqNum(int i)
140 String sq = null; // for dumb jbuilder not-inited exception warning
143 int sSize = sequences.length;
145 if ((i > -1) && (i < sSize))
147 sq = sequences[i].getSequenceAsString();
149 if (seqNums.size() <= i)
151 seqNums.addElement(new int[sq.length() + 1]);
154 if (sq.hashCode() != ((int[]) seqNums.elementAt(i))[0])
158 seqNumsChanged = true;
166 sqnum = new int[len + 1]; // better to always make a new array -
167 // sequence can change its length
168 sqnum[0] = sq.hashCode();
170 for (j = 1; j <= len; j++)
172 sqnum[j] = jalview.schemes.ResidueProperties.aaIndex[sq
176 seqNums.setElementAt(sqnum, i);
180 System.out.println("SEQUENCE HAS BEEN DELETED!!!");
185 // JBPNote INFO level debug
187 .println("ERROR: calcSeqNum called with out of range sequence index for Alignment\n");
192 * Calculates the conservation values for given set of sequences
194 public void calculate()
196 Hashtable resultHash, ht;
197 int thresh, j, jSize = sequences.length;
198 int[] values; // Replaces residueHash
199 String type, res = null;
201 Enumeration enumeration2;
203 total = new Hashtable[maxLength];
205 for (int i = start; i <= end; i++)
207 values = new int[255];
209 for (j = 0; j < jSize; j++)
211 if (sequences[j].getLength() > i)
213 c = sequences[j].getCharAt(i);
216 { // lookup the base aa code symbol
217 c = (char) jalview.schemes.ResidueProperties.aaIndex[sequences[j]
225 // recover canonical aa symbol
226 c = jalview.schemes.ResidueProperties.aa[c].charAt(0);
231 // original behaviour - operate on ascii symbols directly
232 // No need to check if its a '-'
233 if (c == '.' || c == ' ')
248 // What is the count threshold to count the residues in residueHash()
249 thresh = (threshold * (jSize)) / 100;
251 // loop over all the found residues
252 resultHash = new Hashtable();
253 for (char v = '-'; v < 'Z'; v++)
256 if (values[v] > thresh)
258 res = String.valueOf(v);
260 // Now loop over the properties
261 enumeration2 = propHash.keys();
263 while (enumeration2.hasMoreElements())
265 type = (String) enumeration2.nextElement();
266 ht = (Hashtable) propHash.get(type);
268 // Have we ticked this before?
269 if (!resultHash.containsKey(type))
271 if (ht.containsKey(res))
273 resultHash.put(type, ht.get(res));
277 resultHash.put(type, ht.get("-"));
280 else if (((Integer) resultHash.get(type)).equals(ht.get(res)) == false)
282 resultHash.put(type, new Integer(-1));
288 if (total.length > 0)
290 total[i - start] = resultHash;
295 /*****************************************************************************
296 * count conservation for the j'th column of the alignment
298 * @return { gap count, conserved residue count}
300 public int[] countConsNGaps(int j)
305 int[] r = new int[2];
307 int i, iSize = sequences.length;
310 for (i = 0; i < iSize; i++)
312 if (j >= sequences[i].getLength())
318 c = sequences[i].getCharAt(j); // gaps do not have upper/lower case
320 if (jalview.util.Comparison.isGap((c)))
341 r[0] = (nres == cons) ? 1 : 0;
348 * Returns the upper-cased character if between 'a' and 'z', else the
354 char toUpperCase(char c)
356 if ('a' <= c && c <= 'z')
358 c -= (32); // 32 = 'a' - 'A'
364 * Calculates the conservation sequence
367 * if true, poitiveve conservation; false calculates negative
369 * @param percentageGaps
370 * commonly used value is 25
372 public void verdict(boolean consflag, float percentageGaps)
374 StringBuffer consString = new StringBuffer();
380 Hashtable resultHash;
381 Enumeration enumeration;
383 // NOTE THIS SHOULD CHECK IF THE CONSEQUENCE ALREADY
384 // EXISTS AND NOT OVERWRITE WITH '-', BUT THIS CASE
385 // DOES NOT EXIST IN JALVIEW 2.1.2
386 for (int i = 0; i < start; i++)
388 consString.append('-');
390 consSymbs = new String[end - start + 1];
391 for (int i = start; i <= end; i++)
393 gapcons = countConsNGaps(i);
394 totGaps = gapcons[1];
395 pgaps = ((float) totGaps * 100) / sequences.length;
396 consSymbs[i - start] = new String();
398 if (percentageGaps > pgaps)
400 resultHash = total[i - start];
401 // Now find the verdict
403 enumeration = resultHash.keys();
405 while (enumeration.hasMoreElements())
407 type = (String) enumeration.nextElement();
408 result = (Integer) resultHash.get(type);
409 // Do we want to count +ve conservation or +ve and -ve cons.?
412 if (result.intValue() == 1)
414 consSymbs[i - start] = type + " " + consSymbs[i - start];
420 if (result.intValue() != -1)
423 if (result.intValue() == 0)
425 consSymbs[i - start] = consSymbs[i - start] + " !" + type;
429 consSymbs[i - start] = type + " " + consSymbs[i - start];
440 consString.append(count); // Conserved props!=Identity
444 consString.append((gapcons[0] == 1) ? "*" : "+");
449 consString.append('-');
453 consSequence = new Sequence(name, consString.toString(), start, end);
459 * @return Conservation sequence
461 public Sequence getConsSequence()
466 // From Alignment.java in jalview118
467 public void findQuality()
469 findQuality(0, maxLength - 1);
475 private void percentIdentity2()
477 seqNums = new Vector();
479 int i = 0, iSize = sequences.length;
480 // Do we need to calculate this again?
481 for (i = 0; i < iSize; i++)
486 if ((cons2 == null) || seqNumsChanged)
488 cons2 = new int[maxLength][24];
490 // Initialize the array
491 for (int j = 0; j < 24; j++)
493 for (i = 0; i < maxLength; i++)
502 while (j < sequences.length)
504 sqnum = (int[]) seqNums.elementAt(j);
506 for (i = 1; i < sqnum.length; i++)
508 cons2[i - 1][sqnum[i]]++;
511 for (i = sqnum.length - 1; i < maxLength; i++)
513 cons2[i][23]++; // gap count
522 * for (int i=start; i <= end; i++) { int max = -1000; int maxi = -1; int
525 * for (int j=0;j<24;j++) { if (cons2[i][j] > max) { max = cons2[i][j];
526 * maxi = i; maxj = j; } } }
532 * Calculates the quality of the set of sequences
539 public void findQuality(int start, int end)
541 quality = new Vector();
544 int[][] BLOSUM62 = jalview.schemes.ResidueProperties.getBLOSUM62();
546 // Loop over columns // JBPNote Profiling info
547 // long ts = System.currentTimeMillis();
548 // long te = System.currentTimeMillis();
551 int size = seqNums.size();
552 int[] lengths = new int[size];
553 double tot, bigtot, sr, tmp;
555 int l, j, i, ii, i2, k, seqNum;
557 for (l = 0; l < size; l++)
559 lengths[l] = ((int[]) seqNums.elementAt(l)).length - 1;
562 for (j = start; j <= end; j++)
566 // First Xr = depends on column only
569 for (ii = 0; ii < 24; ii++)
573 for (i2 = 0; i2 < 24; i2++)
575 x[ii] += (((double) cons2[j][i2] * BLOSUM62[ii][i2]) + 4);
581 // Now calculate D for each position and sum
582 for (k = 0; k < size; k++)
586 seqNum = (j < lengths[k]) ? ((int[]) seqNums.elementAt(k))[j + 1]
587 : 23; // Sequence, or gap at the end
589 // This is a loop over r
590 for (i = 0; i < 23; i++)
594 sr = (double) BLOSUM62[i][seqNum] + 4;
596 // Calculate X with another loop over residues
597 // System.out.println("Xi " + i + " " + x[i] + " " + sr);
600 tot += (xx[i] * xx[i]);
603 bigtot += Math.sqrt(tot);
606 // This is the quality for one column
612 // bigtot = bigtot * (size-cons2[j][23])/size;
613 quality.addElement(new Double(bigtot));
615 // Need to normalize by gaps
618 double newmax = -10000;
620 for (j = start; j <= end; j++)
622 tmp = ((Double) quality.elementAt(j)).doubleValue();
623 tmp = ((max - tmp) * (size - cons2[j][23])) / size;
625 // System.out.println(tmp+ " " + j);
626 quality.setElementAt(new Double(tmp), j);
634 // System.out.println("Quality " + s);
635 qualityRange[0] = new Double(0);
636 qualityRange[1] = new Double(newmax);
640 * complete the given consensus and quuality annotation rows. Note: currently
641 * this method will enlarge the given annotation row if it is too small,
642 * otherwise will leave its length unchanged.
644 * @param conservation
645 * conservation annotation row
647 * (optional - may be null)
649 * first column for conservation
651 * extent of conservation
653 public void completeAnnotations(AlignmentAnnotation conservation,
654 AlignmentAnnotation quality2, int istart, int alWidth)
656 char[] sequence = getConsSequence().getSequence();
668 maxB = 0f - minB; // scalable range for colouring both Conservation and
678 if (conservation.annotations != null
679 && conservation.annotations.length < alWidth)
681 conservation.annotations = new Annotation[alWidth];
684 if (quality2 != null)
686 quality2.graphMax = qualityRange[1].floatValue();
687 if (quality2.annotations != null
688 && quality2.annotations.length < alWidth)
690 quality2.annotations = new Annotation[alWidth];
692 qmin = qualityRange[0].floatValue();
693 qmax = qualityRange[1].floatValue();
696 for (int i = 0; i < alWidth; i++)
702 if (Character.isDigit(c))
715 float vprop = value - min;
717 int consp = i - start;
718 String conssym = (value > 0 && consp > -1 && consp < consSymbs.length) ? consSymbs[consp]
720 conservation.annotations[i] = new Annotation(String.valueOf(c),
721 conssym, ' ', value, new Color(minR + (maxR * vprop), minG
722 + (maxG * vprop), minB + (maxB * vprop)));
725 if (quality2 != null)
727 value = ((Double) quality.elementAt(i)).floatValue();
728 vprop = value - qmin;
730 quality2.annotations[i] = new Annotation(" ",
731 String.valueOf(value), ' ', value, new Color(minR
732 + (maxR * vprop), minG + (maxG * vprop), minB
739 * construct and call the calculation methods on a new Conservation object
742 * - name of conservation
744 * - hash table of properties for each amino acid (normally
745 * ResidueProperties.propHash)
747 * - minimum number of conserved residues needed to indicate
748 * conservation (typically 3)
751 * first column in calculation window
753 * last column in calculation window
755 * positive (true) or negative (false) conservation
756 * @param consPercGaps
757 * percentage of gaps tolerated in column
759 * flag indicating if alignment quality should be calculated
760 * @return Conservation object ready for use in visualization
762 public static Conservation calculateConservation(String name,
763 Hashtable consHash, int threshold, List<SequenceI> seqs,
764 int start, int end, boolean posOrNeg, int consPercGaps,
767 Conservation cons = new Conservation(name, consHash, threshold, seqs,
769 return calculateConservation(cons, posOrNeg, consPercGaps, calcQuality);
774 * positive (true) or negative (false) conservation
775 * @param consPercGaps
776 * percentage of gaps tolerated in column
778 * flag indicating if alignment quality should be calculated
779 * @return Conservation object ready for use in visualization
781 public static Conservation calculateConservation(Conservation cons,
782 boolean b, int consPercGaps, boolean calcQuality)
785 cons.verdict(b, consPercGaps);