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;
27 import jalview.schemes.ResidueProperties;
28 import jalview.util.Comparison;
30 import java.awt.Color;
31 import java.util.Enumeration;
32 import java.util.Hashtable;
33 import java.util.List;
34 import java.util.Vector;
36 import javajs.util.DebugJS;
39 * Calculates conservation values for a given set of sequences
44 public class Conservation
46 SequenceI[] sequences;
52 Vector seqNums; // vector of int vectors where first is sequence checksum
54 int maxLength = 0; // used by quality calcs
56 boolean seqNumsChanged = false; // updated after any change via calcSeqNum;
60 boolean canonicaliseAa = true; // if true then conservation calculation will
62 // map all symbols to canonical aa numbering
63 // rather than consider conservation of that
66 /** Stores calculated quality values */
67 public Vector quality;
69 /** Stores maximum and minimum values of quality values */
70 public Double[] qualityRange = new Double[2];
72 String consString = "";
74 Sequence consSequence;
84 private String[] consSymbs;
87 * Creates a new Conservation object.
90 * Name of conservation
92 * hash of properties for each symbol
94 * to count the residues in residueHash(). commonly used value is 3
96 * sequences to be used in calculation
98 * start residue position
100 * end residue position
102 public Conservation(String name, Hashtable propHash, int threshold,
103 List<SequenceI> sequences, int start, int end)
106 this.propHash = propHash;
107 this.threshold = threshold;
111 maxLength = end - start + 1; // default width includes bounds of
114 int s, sSize = sequences.size();
115 SequenceI[] sarray = new SequenceI[sSize];
116 this.sequences = sarray;
119 for (s = 0; s < sSize; s++)
121 sarray[s] = sequences.get(s);
122 if (sarray[s].getLength() > maxLength)
124 maxLength = sarray[s].getLength();
127 } catch (ArrayIndexOutOfBoundsException ex)
129 // bail - another thread has modified the sequence array, so the current
130 // calculation is probably invalid.
131 this.sequences = new SequenceI[0];
137 * Translate sequence i into a numerical representation and store it in the
138 * i'th position of the seqNums array.
142 private void calcSeqNum(int i)
144 String sq = null; // for dumb jbuilder not-inited exception warning
147 int sSize = sequences.length;
149 if ((i > -1) && (i < sSize))
151 sq = sequences[i].getSequenceAsString();
153 if (seqNums.size() <= i)
155 seqNums.addElement(new int[sq.length() + 1]);
158 if (sq.hashCode() != ((int[]) seqNums.elementAt(i))[0])
162 seqNumsChanged = true;
170 sqnum = new int[len + 1]; // better to always make a new array -
171 // sequence can change its length
172 sqnum[0] = sq.hashCode();
174 for (j = 1; j <= len; j++)
176 sqnum[j] = ResidueProperties.aaIndex[sq
180 seqNums.setElementAt(sqnum, i);
184 System.out.println("SEQUENCE HAS BEEN DELETED!!!");
189 // JBPNote INFO level debug
191 .println("ERROR: calcSeqNum called with out of range sequence index for Alignment\n");
196 * Calculates the conservation values for given set of sequences
198 public void calculate()
200 Hashtable resultHash, ht;
201 int thresh, j, jSize = sequences.length;
202 int[] values; // Replaces residueHash
203 String type, res = null;
205 Enumeration enumeration2;
207 total = new Hashtable[maxLength];
209 for (int i = start; i <= end; i++)
211 values = new int[255];
213 for (j = 0; j < jSize; j++)
215 if (sequences[j].getLength() > i)
217 c = sequences[j].getCharAt(i);
220 { // lookup the base aa code symbol
221 c = (char) ResidueProperties.aaIndex[sequences[j]
229 // recover canonical aa symbol
230 c = ResidueProperties.aa[c].charAt(0);
235 // original behaviour - operate on ascii symbols directly
236 // No need to check if its a '-'
237 if (c == '.' || c == ' ')
242 if (!canonicaliseAa && 'a' <= c && c <= 'z')
244 c -= (32); // 32 = 'a' - 'A'
255 // What is the count threshold to count the residues in residueHash()
256 thresh = (threshold * (jSize)) / 100;
258 // loop over all the found residues
259 resultHash = new Hashtable();
260 for (char v = '-'; v < 'Z'; v++)
263 if (values[v] > thresh)
265 res = String.valueOf(v);
267 // Now loop over the properties
268 enumeration2 = propHash.keys();
270 while (enumeration2.hasMoreElements())
272 type = (String) enumeration2.nextElement();
273 ht = (Hashtable) propHash.get(type);
275 // Have we ticked this before?
276 if (!resultHash.containsKey(type))
278 if (ht.containsKey(res))
280 resultHash.put(type, ht.get(res));
284 resultHash.put(type, ht.get("-"));
287 else if (((Integer) resultHash.get(type)).equals(ht
290 resultHash.put(type, new Integer(-1));
296 if (total.length > 0)
298 total[i - start] = resultHash;
303 /*****************************************************************************
304 * count conservation for the j'th column of the alignment
306 * @return { gap count, conserved residue count}
308 public int[] countConsNGaps(int j)
313 int[] r = new int[2];
315 int i, iSize = sequences.length;
318 for (i = 0; i < iSize; i++)
320 if (j >= sequences[i].getLength())
326 c = sequences[i].getCharAt(j); // gaps do not have upper/lower case
328 if (Comparison.isGap((c)))
348 r[0] = (nres == cons) ? 1 : 0;
355 * Calculates the conservation sequence
358 * if true, poitiveve conservation; false calculates negative
360 * @param percentageGaps
361 * commonly used value is 25
363 public void verdict(boolean consflag, float percentageGaps)
365 StringBuffer consString = new StringBuffer();
371 Hashtable resultHash;
372 Enumeration enumeration;
374 // NOTE THIS SHOULD CHECK IF THE CONSEQUENCE ALREADY
375 // EXISTS AND NOT OVERWRITE WITH '-', BUT THIS CASE
376 // DOES NOT EXIST IN JALVIEW 2.1.2
377 for (int i = 0; i < start; i++)
379 consString.append('-');
381 consSymbs = new String[end-start+1];
382 for (int i = start; i <= end; i++)
384 gapcons = countConsNGaps(i);
385 totGaps = gapcons[1];
386 pgaps = ((float) totGaps * 100) / sequences.length;
387 consSymbs[i-start]=new String();
389 if (percentageGaps > pgaps)
391 resultHash = total[i - start];
392 // Now find the verdict
394 enumeration = resultHash.keys();
396 while (enumeration.hasMoreElements())
398 type = (String) enumeration.nextElement();
399 result = (Integer) resultHash.get(type);
400 // Do we want to count +ve conservation or +ve and -ve cons.?
403 if (result.intValue() == 1)
405 consSymbs[i-start] = type+" "+consSymbs[i-start];
411 if (result.intValue() != -1)
414 if (result.intValue()==0) {
415 consSymbs[i-start] = consSymbs[i-start]+ " !"+type;
417 consSymbs[i-start] = type+" "+consSymbs[i-start];
428 consString.append("" + count); // BH SB append issue here // Conserved props!=Identity
432 consString.append((gapcons[0] == 1) ? "*" : "+");
437 consString.append('-');
441 consSequence = new Sequence(name, consString.toString(), start, end);
447 * @return Conservation sequence
449 public Sequence getConsSequence()
454 // From Alignment.java in jalview118
455 public void findQuality()
457 findQuality(0, maxLength - 1);
463 private void percentIdentity2()
465 seqNums = new Vector();
467 int i = 0, iSize = sequences.length;
468 // Do we need to calculate this again?
469 for (i = 0; i < iSize; i++)
474 if ((cons2 == null) || seqNumsChanged)
476 cons2 = new int[maxLength][24];
478 // Initialize the array
479 for (int j = 0; j < 24; j++)
481 for (i = 0; i < maxLength; i++)
490 while (j < sequences.length)
492 sqnum = (int[]) seqNums.elementAt(j);
494 for (i = 1; i < sqnum.length; i++)
496 cons2[i - 1][sqnum[i]]++;
499 for (i = sqnum.length - 1; i < maxLength; i++)
501 cons2[i][23]++; // gap count
510 * for (int i=start; i <= end; i++) { int max = -1000; int maxi = -1; int
513 * for (int j=0;j<24;j++) { if (cons2[i][j] > max) { max = cons2[i][j];
514 * maxi = i; maxj = j; } } }
520 * Calculates the quality of the set of sequences
527 public void findQuality(int start, int end)
529 quality = new Vector();
532 int[][] BLOSUM62 = ResidueProperties.getBLOSUM62();
534 // Loop over columns // JBPNote Profiling info
535 // long ts = System.currentTimeMillis();
536 // long te = System.currentTimeMillis();
539 int size = seqNums.size();
540 int[] lengths = new int[size];
541 double tot, bigtot, sr, tmp;
543 int l, j, i, ii, i2, k, seqNum;
545 for (l = 0; l < size; l++)
547 lengths[l] = ((int[]) seqNums.elementAt(l)).length - 1;
550 for (j = start; j <= end; j++)
554 // First Xr = depends on column only
557 for (ii = 0; ii < 24; ii++)
561 for (i2 = 0; i2 < 24; i2++)
563 x[ii] += (((double) cons2[j][i2] * BLOSUM62[ii][i2]) + 4);
569 // Now calculate D for each position and sum
570 for (k = 0; k < size; k++)
574 seqNum = (j < lengths[k]) ? ((int[]) seqNums.elementAt(k))[j + 1]
575 : 23; // Sequence, or gap at the end
577 // This is a loop over r
578 for (i = 0; i < 23; i++)
582 sr = (double) BLOSUM62[i][seqNum] + 4;
584 // Calculate X with another loop over residues
585 // System.out.println("Xi " + i + " " + x[i] + " " + sr);
588 tot += (xx[i] * xx[i]);
591 bigtot += Math.sqrt(tot);
594 // This is the quality for one column
600 // bigtot = bigtot * (size-cons2[j][23])/size;
601 quality.addElement(new Double(bigtot));
603 // Need to normalize by gaps
606 double newmax = -10000;
608 for (j = start; j <= end; j++)
610 tmp = ((Double) quality.elementAt(j)).doubleValue();
611 tmp = ((max - tmp) * (size - cons2[j][23])) / size;
613 // System.out.println(tmp+ " " + j);
614 quality.setElementAt(new Double(tmp), j);
622 // System.out.println("Quality " + s);
623 qualityRange[0] = new Double(0);
624 qualityRange[1] = new Double(newmax);
628 * complete the given consensus and quuality annotation rows. Note: currently
629 * this method will enlarge the given annotation row if it is too small,
630 * otherwise will leave its length unchanged.
632 * @param conservation
633 * conservation annotation row
635 * (optional - may be null)
637 * first column for conservation
639 * extent of conservation
641 public void completeAnnotations(AlignmentAnnotation conservation,
642 AlignmentAnnotation quality2, int istart, int alWidth)
644 char[] sequence = getConsSequence().getSequence();
656 maxB = 0f - minB; // scalable range for colouring both Conservation and
666 if (conservation.annotations != null
667 && conservation.annotations.length < alWidth)
669 conservation.annotations = new Annotation[alWidth];
672 if (quality2 != null)
674 quality2.graphMax = qualityRange[1].floatValue();
675 if (quality2.annotations != null
676 && quality2.annotations.length < alWidth)
678 quality2.annotations = new Annotation[alWidth];
680 qmin = qualityRange[0].floatValue();
681 qmax = qualityRange[1].floatValue();
684 for (int i = 0; i < alWidth; i++)
690 if (Character.isDigit(c))
703 float vprop = value - min;
705 conservation.annotations[i] = new Annotation(String.valueOf(c),
706 consSymbs[i-start], ' ', value, new Color(minR
707 + (maxR * vprop), minG + (maxG * vprop), minB
711 if (quality2 != null)
713 value = ((Double) quality.elementAt(i)).floatValue();
714 vprop = value - qmin;
716 quality2.annotations[i] = new Annotation(" ",
717 String.valueOf(value), ' ', value, new Color(minR
718 + (maxR * vprop), minG + (maxG * vprop), minB
722 // DebugJS._("Conservation");
727 * construct and call the calculation methods on a new Conservation object
730 * - name of conservation
732 * - hash table of properties for each amino acid (normally
733 * ResidueProperties.propHash)
735 * - minimum number of conserved residues needed to indicate
736 * conservation (typically 3)
739 * first column in calculation window
741 * last column in calculation window
743 * positive (true) or negative (false) conservation
744 * @param consPercGaps
745 * percentage of gaps tolerated in column
747 * flag indicating if alignment quality should be calculated
748 * @return Conservation object ready for use in visualization
750 public static Conservation calculateConservation(String name,
751 Hashtable consHash, int threshold, List<SequenceI> seqs,
752 int start, int end, boolean posOrNeg, int consPercGaps,
755 Conservation cons = new Conservation(name, consHash, threshold, seqs,
757 return calculateConservation(cons, posOrNeg, consPercGaps, calcQuality);
762 * positive (true) or negative (false) conservation
763 * @param consPercGaps
764 * percentage of gaps tolerated in column
766 * flag indicating if alignment quality should be calculated
767 * @return Conservation object ready for use in visualization
769 public static Conservation calculateConservation(Conservation cons,
770 boolean b, int consPercGaps, boolean calcQuality)
773 cons.verdict(b, consPercGaps);