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.ext.android.SparseIntArray;
28 import jalview.schemes.ResidueProperties;
30 import java.awt.Color;
31 import java.util.Hashtable;
32 import java.util.List;
34 import java.util.Vector;
37 * Calculates conservation values for a given set of sequences
42 public class Conservation
44 SequenceI[] sequences;
50 Vector<int[]> seqNums; // vector of int vectors where first is sequence
53 int maxLength = 0; // used by quality calcs
55 boolean seqNumsChanged = false; // updated after any change via calcSeqNum;
57 Map<String, Integer>[] total;
59 boolean canonicaliseAa = true; // if true then conservation calculation will
61 // map all symbols to canonical aa numbering
62 // rather than consider conservation of that
65 /** Stores calculated quality values */
66 private Vector<Double> quality;
68 /** Stores maximum and minimum values of quality values */
69 private double[] qualityRange = new double[2];
71 private Sequence consSequence;
73 private int threshold;
75 private String name = "";
77 private int[][] cons2;
79 private String[] consSymbs;
82 * Creates a new Conservation object.
85 * Name of conservation
87 * to count the residues in residueHash(). commonly used value is 3
89 * sequences to be used in calculation
91 * start residue position
93 * end residue position
95 public Conservation(String name, int threshold,
96 List<SequenceI> sequences, int start, int end)
99 this.threshold = threshold;
103 maxLength = end - start + 1; // default width includes bounds of
106 int s, sSize = sequences.size();
107 SequenceI[] sarray = new SequenceI[sSize];
108 this.sequences = sarray;
111 for (s = 0; s < sSize; s++)
113 sarray[s] = sequences.get(s);
114 if (sarray[s].getLength() > maxLength)
116 maxLength = sarray[s].getLength();
119 } catch (ArrayIndexOutOfBoundsException ex)
121 // bail - another thread has modified the sequence array, so the current
122 // calculation is probably invalid.
123 this.sequences = new SequenceI[0];
129 * Translate sequence i into a numerical representation and store it in the
130 * i'th position of the seqNums array.
134 private void calcSeqNum(int i)
136 String sq = null; // for dumb jbuilder not-inited exception warning
139 int sSize = sequences.length;
141 if ((i > -1) && (i < sSize))
143 sq = sequences[i].getSequenceAsString();
145 if (seqNums.size() <= i)
147 seqNums.addElement(new int[sq.length() + 1]);
150 if (sq.hashCode() != seqNums.elementAt(i)[0])
154 seqNumsChanged = true;
162 sqnum = new int[len + 1]; // better to always make a new array -
163 // sequence can change its length
164 sqnum[0] = sq.hashCode();
166 for (j = 1; j <= len; j++)
168 sqnum[j] = jalview.schemes.ResidueProperties.aaIndex[sq
172 seqNums.setElementAt(sqnum, i);
176 System.out.println("SEQUENCE HAS BEEN DELETED!!!");
181 // JBPNote INFO level debug
183 .println("ERROR: calcSeqNum called with out of range sequence index for Alignment\n");
188 * Calculates the conservation values for given set of sequences
190 public void calculate()
192 int thresh, j, jSize = sequences.length;
193 // int[] values; // Replaces residueHash
194 SparseIntArray values = new SparseIntArray();
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) ResidueProperties.aaIndex[sequences[j].getCharAt(i)];
218 // recover canonical aa symbol
219 c = ResidueProperties.aa[c].charAt(0);
224 // original behaviour - operate on ascii symbols directly
225 // No need to check if its a '-'
226 if (c == '.' || c == ' ')
234 values.put(c, values.get(c) + 1);
239 values.put('-', values.get('-') + 1);
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 Hashtable<String, Integer> resultHash = new Hashtable<String, Integer>();
248 for (char v = '-'; v < 'Z'; v++)
251 // if (values[v] > thresh)
252 if (values.get(v) > thresh)
254 String res = String.valueOf(v);
256 // Now loop over the properties
257 for (String type : ResidueProperties.propHash.keySet())
259 Map<String, Integer> ht = ResidueProperties.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 (!resultHash.get(type).equals(ht.get(res)))
275 resultHash.put(type, new Integer(-1));
281 if (total.length > 0)
283 total[i - start] = resultHash;
288 /*****************************************************************************
289 * count conservation for the j'th column of the alignment
291 * @return { gap count, conserved residue count}
293 public int[] countConsNGaps(int j)
298 int[] r = new int[2];
300 int i, iSize = sequences.length;
303 for (i = 0; i < iSize; i++)
305 if (j >= sequences[i].getLength())
311 c = sequences[i].getCharAt(j); // gaps do not have upper/lower case
313 if (jalview.util.Comparison.isGap((c)))
334 r[0] = (nres == cons) ? 1 : 0;
341 * Returns the upper-cased character if between 'a' and 'z', else the
347 char toUpperCase(char c)
349 if ('a' <= c && c <= 'z')
351 c -= (32); // 32 = 'a' - 'A'
357 * Calculates the conservation sequence
360 * if true, positive conservation; false calculates negative
362 * @param percentageGaps
363 * commonly used value is 25
365 public void verdict(boolean consflag, float percentageGaps)
367 StringBuffer consString = new StringBuffer();
369 // NOTE THIS SHOULD CHECK IF THE CONSEQUENCE ALREADY
370 // EXISTS AND NOT OVERWRITE WITH '-', BUT THIS CASE
371 // DOES NOT EXIST IN JALVIEW 2.1.2
372 for (int i = 0; i < start; i++)
374 consString.append('-');
376 consSymbs = new String[end - start + 1];
377 for (int i = start; i <= end; i++)
379 int[] gapcons = countConsNGaps(i);
380 int totGaps = gapcons[1];
381 float pgaps = ((float) totGaps * 100) / sequences.length;
382 consSymbs[i - start] = new String();
384 if (percentageGaps > pgaps)
386 Map<String, Integer> resultHash = total[i - start];
387 // Now find the verdict
389 for (String type : resultHash.keySet())
391 int result = resultHash.get(type).intValue();
392 // Do we want to count +ve conservation or +ve and -ve cons.?
397 consSymbs[i - start] = type + " " + consSymbs[i - start];
407 consSymbs[i - start] = consSymbs[i - start] + " !" + type;
411 consSymbs[i - start] = type + " " + consSymbs[i - start];
420 consString.append(count); // Conserved props!=Identity
424 consString.append((gapcons[0] == 1) ? "*" : "+");
429 consString.append('-');
433 consSequence = new Sequence(name, consString.toString(), start, end);
439 * @return Conservation sequence
441 public Sequence getConsSequence()
446 // From Alignment.java in jalview118
447 public void findQuality()
449 findQuality(0, maxLength - 1);
455 private void percentIdentity2()
457 seqNums = new Vector<int[]>();
459 int i = 0, iSize = sequences.length;
460 // Do we need to calculate this again?
461 for (i = 0; i < iSize; i++)
466 if ((cons2 == null) || seqNumsChanged)
468 cons2 = new int[maxLength][24];
470 // Initialize the array
471 for (int j = 0; j < 24; j++)
473 for (i = 0; i < maxLength; i++)
482 while (j < sequences.length)
484 sqnum = seqNums.elementAt(j);
486 for (i = 1; i < sqnum.length; i++)
488 cons2[i - 1][sqnum[i]]++;
491 for (i = sqnum.length - 1; i < maxLength; i++)
493 cons2[i][23]++; // gap count
502 * for (int i=start; i <= end; i++) { int max = -1000; int maxi = -1; int
505 * for (int j=0;j<24;j++) { if (cons2[i][j] > max) { max = cons2[i][j];
506 * maxi = i; maxj = j; } } }
512 * Calculates the quality of the set of sequences
519 public void findQuality(int startRes, int endRes)
521 quality = new Vector<Double>();
524 int[][] BLOSUM62 = ResidueProperties.getBLOSUM62();
526 // Loop over columns // JBPNote Profiling info
527 // long ts = System.currentTimeMillis();
528 // long te = System.currentTimeMillis();
531 int size = seqNums.size();
532 int[] lengths = new int[size];
533 double tot, bigtot, sr, tmp;
535 int l, j, i, ii, i2, k, seqNum;
537 for (l = 0; l < size; l++)
539 lengths[l] = seqNums.elementAt(l).length - 1;
542 for (j = startRes; j <= endRes; j++)
546 // First Xr = depends on column only
549 for (ii = 0; ii < 24; ii++)
553 for (i2 = 0; i2 < 24; i2++)
555 x[ii] += (((double) cons2[j][i2] * BLOSUM62[ii][i2]) + 4);
561 // Now calculate D for each position and sum
562 for (k = 0; k < size; k++)
566 seqNum = (j < lengths[k]) ? seqNums.elementAt(k)[j + 1]
567 : 23; // Sequence, or gap at the end
569 // This is a loop over r
570 for (i = 0; i < 23; i++)
574 sr = (double) BLOSUM62[i][seqNum] + 4;
576 // Calculate X with another loop over residues
577 // System.out.println("Xi " + i + " " + x[i] + " " + sr);
580 tot += (xx[i] * xx[i]);
583 bigtot += Math.sqrt(tot);
586 // This is the quality for one column
592 // bigtot = bigtot * (size-cons2[j][23])/size;
593 quality.addElement(new Double(bigtot));
595 // Need to normalize by gaps
598 double newmax = -10000;
600 for (j = startRes; j <= endRes; j++)
602 tmp = quality.elementAt(j).doubleValue();
603 tmp = ((max - tmp) * (size - cons2[j][23])) / size;
605 // System.out.println(tmp+ " " + j);
606 quality.setElementAt(new Double(tmp), j);
614 // System.out.println("Quality " + s);
615 qualityRange[0] = 0D;
616 qualityRange[1] = newmax;
620 * Complete the given consensus and quuality annotation rows. Note: currently
621 * this method will enlarge the given annotation row if it is too small,
622 * otherwise will leave its length unchanged.
624 * @param conservation
625 * conservation annotation row
627 * (optional - may be null)
629 * first column for conservation
631 * extent of conservation
633 public void completeAnnotations(AlignmentAnnotation conservation,
634 AlignmentAnnotation quality2, int istart, int alWidth)
636 char[] sequence = getConsSequence().getSequence();
648 maxB = 0f - minB; // scalable range for colouring both Conservation and
658 if (conservation != null && conservation.annotations != null
659 && conservation.annotations.length < alWidth)
661 conservation.annotations = new Annotation[alWidth];
664 if (quality2 != null)
666 quality2.graphMax = (float) qualityRange[1];
667 if (quality2.annotations != null
668 && quality2.annotations.length < alWidth)
670 quality2.annotations = new Annotation[alWidth];
672 qmin = (float) qualityRange[0];
673 qmax = (float) qualityRange[1];
676 for (int i = istart; i < alWidth; i++)
682 if (Character.isDigit(c))
695 if (conservation != null)
697 float vprop = value - min;
699 int consp = i - start;
700 String conssym = (value > 0 && consp > -1 && consp < consSymbs.length) ? consSymbs[consp]
702 conservation.annotations[i] = new Annotation(String.valueOf(c),
703 conssym, ' ', value, new Color(minR + (maxR * vprop), minG
704 + (maxG * vprop), minB + (maxB * vprop)));
708 if (quality2 != null)
710 value = quality.elementAt(i).floatValue();
711 float vprop = value - qmin;
713 quality2.annotations[i] = new Annotation(" ",
714 String.valueOf(value), ' ', value, new Color(minR
715 + (maxR * vprop), minG + (maxG * vprop), minB
722 * construct and call the calculation methods on a new Conservation object
725 * - name of conservation
727 * - minimum number of conserved residues needed to indicate
728 * conservation (typically 3)
731 * first column in calculation window
733 * last column in calculation window
735 * positive (true) or negative (false) conservation
736 * @param consPercGaps
737 * percentage of gaps tolerated in column
739 * flag indicating if alignment quality should be calculated
740 * @return Conservation object ready for use in visualization
742 public static Conservation calculateConservation(String name,
743 int threshold, List<SequenceI> seqs, int start, int end,
744 boolean posOrNeg, int consPercGaps, boolean calcQuality)
746 Conservation cons = new Conservation(name, threshold, seqs, start, end);
748 cons.verdict(posOrNeg, consPercGaps);