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.AlignedCodonFrame;
24 import jalview.datamodel.AlignmentAnnotation;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.Annotation;
27 import jalview.datamodel.SequenceI;
28 import jalview.util.Format;
29 import jalview.util.MappingUtils;
30 import jalview.util.QuickSort;
32 import java.util.Arrays;
33 import java.util.Hashtable;
34 import java.util.List;
38 * Takes in a vector or array of sequences and column start and column end and
39 * returns a new Hashtable[] of size maxSeqLength, if Hashtable not supplied.
40 * This class is used extensively in calculating alignment colourschemes that
41 * depend on the amount of conservation in each alignment column.
46 public class AAFrequency
48 private static final int TO_UPPER_CASE = 'A' - 'a'; // -32
50 public static final String MAXCOUNT = "C";
52 public static final String MAXRESIDUE = "R";
54 public static final String PID_GAPS = "G";
56 public static final String PID_NOGAPS = "N";
58 public static final String PROFILE = "P";
60 public static final String ENCODED_CHARS = "E";
63 * Quick look-up of String value of char 'A' to 'Z'
65 private static final String[] CHARS = new String['Z' - 'A' + 1];
69 for (char c = 'A'; c <= 'Z'; c++)
71 CHARS[c - 'A'] = String.valueOf(c);
75 public static final Hashtable[] calculate(List<SequenceI> list,
78 return calculate(list, start, end, false);
81 public static final Hashtable[] calculate(List<SequenceI> sequences,
82 int start, int end, boolean profile)
84 SequenceI[] seqs = new SequenceI[sequences.size()];
86 synchronized (sequences)
88 for (int i = 0; i < sequences.size(); i++)
90 seqs[i] = sequences.get(i);
91 if (seqs[i].getLength() > width)
93 width = seqs[i].getLength();
97 Hashtable[] reply = new Hashtable[width];
104 calculate(seqs, start, end, reply, profile);
109 public static final void calculate(SequenceI[] sequences, int start,
110 int end, Hashtable[] result, boolean profile)
112 Hashtable residueHash;
113 int maxCount, nongap, i, j, v;
114 int jSize = sequences.length;
119 int[] values = new int[255];
123 for (i = start; i < end; i++)
125 residueHash = new Hashtable();
129 values = new int[255];
131 for (j = 0; j < jSize; j++)
133 if (sequences[j] == null)
136 .println("WARNING: Consensus skipping null sequence - possible race condition.");
139 seq = sequences[j].getSequence();
144 if (c == '.' || c == ' ')
154 else if ('a' <= c && c <= 'z')
170 maxResidue = String.valueOf(c);
175 for (v = 'A'; v <= 'Z'; v++)
177 // TODO why ignore values[v] == 1?
178 if (values[v] < 1 /* 2 */|| values[v] < maxCount)
183 if (values[v] > maxCount)
185 maxResidue = CHARS[v - 'A'];
187 else if (values[v] == maxCount)
189 maxResidue += CHARS[v - 'A'];
191 maxCount = values[v];
194 if (maxResidue.length() == 0)
200 // TODO use a 1-dimensional array with jSize, nongap in [0] and [1]
201 residueHash.put(PROFILE, new int[][]
203 { jSize, nongap } });
205 residueHash.put(MAXCOUNT, new Integer(maxCount));
206 residueHash.put(MAXRESIDUE, maxResidue);
208 percentage = ((float) maxCount * 100) / jSize;
209 residueHash.put(PID_GAPS, new Float(percentage));
213 // calculate for non-gapped too
214 percentage = ((float) maxCount * 100) / nongap;
216 residueHash.put(PID_NOGAPS, new Float(percentage));
218 result[i] = residueHash;
223 * Compute all or part of the annotation row from the given consensus
227 * - pre-allocated annotation row
231 * @param ignoreGapsInConsensusCalculation
232 * @param includeAllConsSymbols
235 public static void completeConsensus(AlignmentAnnotation consensus,
236 Hashtable[] hconsensus, int iStart, int width,
237 boolean ignoreGapsInConsensusCalculation,
238 boolean includeAllConsSymbols, long nseq)
240 completeConsensus(consensus, hconsensus, iStart, width,
241 ignoreGapsInConsensusCalculation, includeAllConsSymbols, null,
246 * Derive the consensus annotations to be added to the alignment for display.
247 * This does not recompute the raw data, but may be called on a change in
248 * display options, such as 'show logo', which may in turn result in a change
249 * in the derived values.
252 * the annotation row to add annotations to
254 * the source consensus data
259 * @param ignoreGapsInConsensusCalculation
260 * if true, use the consensus calculated ignoring gaps
261 * @param includeAllConsSymbols
262 * if true include all consensus symbols, else just show modal
266 * number of sequences
268 public static void completeConsensus(AlignmentAnnotation consensus,
269 Hashtable[] hconsensus, int iStart, int width,
270 boolean ignoreGapsInConsensusCalculation,
271 boolean includeAllConsSymbols, char[] alphabet, long nseq)
273 if (consensus == null || consensus.annotations == null
274 || consensus.annotations.length < width)
276 // called with a bad alignment annotation row - wait for it to be
277 // initialised properly
281 final Format fmt = getPercentageFormat(nseq);
283 for (int i = iStart; i < width; i++)
286 if (i >= hconsensus.length || ((hci = hconsensus[i]) == null))
288 // happens if sequences calculated over were shorter than alignment
290 consensus.annotations[i] = null;
293 Float fv = (Float) hci
294 .get(ignoreGapsInConsensusCalculation ? PID_NOGAPS : PID_GAPS);
297 consensus.annotations[i] = null;
298 // data has changed below us .. give up and
301 float value = fv.floatValue();
302 String maxRes = hci.get(AAFrequency.MAXRESIDUE).toString();
303 StringBuilder mouseOver = new StringBuilder(64);
304 if (maxRes.length() > 1)
306 mouseOver.append("[").append(maxRes).append("] ");
311 mouseOver.append(hci.get(AAFrequency.MAXRESIDUE) + " ");
313 int[][] profile = (int[][]) hci.get(AAFrequency.PROFILE);
314 int sequenceCount = profile[1][0];
315 int nonGappedCount = profile[1][1];
316 int normalisedBy = ignoreGapsInConsensusCalculation ? nonGappedCount
318 if (profile != null && includeAllConsSymbols)
320 mouseOver.setLength(0);
321 if (alphabet != null)
323 for (int c = 0; c < alphabet.length; c++)
325 float tval = profile[0][alphabet[c]] * 100f / normalisedBy;
327 .append(((c == 0) ? "" : "; "))
330 .append(((fmt != null) ? fmt.form(tval) : ((int) tval)))
336 // TODO do this sort once only in calculate()?
337 // char[][] ca = new char[profile[0].length][];
338 char[] ca = new char[profile[0].length];
339 float[] vl = new float[profile[0].length];
340 for (int c = 0; c < ca.length; c++)
343 // ca[c] = new char[]
345 vl[c] = profile[0][c];
347 QuickSort.sort(vl, ca);
348 for (int p = 0, c = ca.length - 1; profile[0][ca[c]] > 0; c--)
350 final char residue = ca[c];
353 float tval = profile[0][residue] * 100f / normalisedBy;
355 .append((((p == 0) ? "" : "; ")))
358 .append(((fmt != null) ? fmt.form(tval)
359 : ((int) tval))).append("%");
368 (((fmt != null) ? fmt.form(value) : ((int) value))))
371 consensus.annotations[i] = new Annotation(maxRes,
372 mouseOver.toString(), ' ',
378 * Returns a Format designed to show all significant figures for profile
379 * percentages. For less than 100 sequences, returns null (the integer
380 * percentage value will be displayed). For 100-999 sequences, returns "%3.1f"
385 protected static Format getPercentageFormat(long nseq)
393 return scale <= 1 ? null : new Format("%3." + (scale - 1) + "f");
397 * Returns the sorted profile for the given consensus data. The returned array
401 * [profileType, numberOfValues, nonGapCount, charValue1, percentage1, charValue2, percentage2, ...]
402 * in descending order of percentage value
406 * the data table from which to extract and sort values
408 * if true, only non-gapped values are included in percentage
412 public static int[] extractProfile(Hashtable hconsensus,
415 int[] rtnval = new int[64];
416 int[][] profile = (int[][]) hconsensus.get(AAFrequency.PROFILE);
421 char[] ca = new char[profile[0].length];
422 float[] vl = new float[profile[0].length];
423 for (int c = 0; c < ca.length; c++)
426 vl[c] = profile[0][c];
428 QuickSort.sort(vl, ca);
429 int nextArrayPos = 2;
430 int totalPercentage = 0;
431 int distinctValuesCount = 0;
432 final int divisor = profile[1][ignoreGaps ? 1 : 0];
433 for (int c = ca.length - 1; profile[0][ca[c]] > 0; c--)
437 rtnval[nextArrayPos++] = ca[c];
438 final int percentage = (int) (profile[0][ca[c]] * 100f / divisor);
439 rtnval[nextArrayPos++] = percentage;
440 totalPercentage += percentage;
441 distinctValuesCount++;
444 rtnval[0] = distinctValuesCount;
445 rtnval[1] = totalPercentage;
446 int[] result = new int[rtnval.length + 1];
447 result[0] = AlignmentAnnotation.SEQUENCE_PROFILE;
448 System.arraycopy(rtnval, 0, result, 1, rtnval.length);
454 * Extract a sorted extract of cDNA codon profile data. The returned array
458 * [profileType, numberOfValues, totalCount, charValue1, percentage1, charValue2, percentage2, ...]
459 * in descending order of percentage value, where the character values encode codon triplets
465 public static int[] extractCdnaProfile(Hashtable hashtable, boolean ignoreGaps)
467 // this holds #seqs, #ungapped, and then codon count, indexed by encoded
469 int[] codonCounts = (int[]) hashtable.get(PROFILE);
470 int[] sortedCounts = new int[codonCounts.length - 2];
471 System.arraycopy(codonCounts, 2, sortedCounts, 0,
472 codonCounts.length - 2);
474 int[] result = new int[3 + 2 * sortedCounts.length];
475 // first value is just the type of profile data
476 result[0] = AlignmentAnnotation.CDNA_PROFILE;
478 char[] codons = new char[sortedCounts.length];
479 for (int i = 0; i < codons.length; i++)
481 codons[i] = (char) i;
483 QuickSort.sort(sortedCounts, codons);
484 int totalPercentage = 0;
485 int distinctValuesCount = 0;
487 int divisor = ignoreGaps ? codonCounts[1] : codonCounts[0];
488 for (int i = codons.length - 1; i >= 0; i--)
490 final int codonCount = sortedCounts[i];
493 break; // nothing else of interest here
495 distinctValuesCount++;
496 result[j++] = codons[i];
497 final int percentage = codonCount * 100 / divisor;
498 result[j++] = percentage;
499 totalPercentage += percentage;
501 result[2] = totalPercentage;
504 * Just return the non-zero values
506 // todo next value is redundant if we limit the array to non-zero counts
507 result[1] = distinctValuesCount;
508 return Arrays.copyOfRange(result, 0, j);
512 * Compute a consensus for the cDNA coding for a protein alignment.
515 * the protein alignment (which should hold mappings to cDNA
518 * the consensus data stores to be populated (one per column)
520 public static void calculateCdna(AlignmentI alignment,
521 Hashtable[] hconsensus)
523 final char gapCharacter = alignment.getGapCharacter();
524 Set<AlignedCodonFrame> mappings = alignment.getCodonFrames();
525 if (mappings == null || mappings.isEmpty())
530 int cols = alignment.getWidth();
531 for (int col = 0; col < cols; col++)
533 // todo would prefer a Java bean for consensus data
534 Hashtable<String, int[]> columnHash = new Hashtable<String, int[]>();
535 // #seqs, #ungapped seqs, counts indexed by (codon encoded + 1)
536 int[] codonCounts = new int[66];
537 codonCounts[0] = alignment.getSequences().size();
538 int ungappedCount = 0;
539 for (SequenceI seq : alignment.getSequences())
541 if (seq.getCharAt(col) == gapCharacter)
545 char[] codon = MappingUtils.findCodonFor(seq, col, mappings);
546 int codonEncoded = CodingUtils.encodeCodon(codon);
547 if (codonEncoded >= 0)
549 codonCounts[codonEncoded + 2]++;
553 codonCounts[1] = ungappedCount;
554 // todo: sort values here, save counts and codons?
555 columnHash.put(PROFILE, codonCounts);
556 hconsensus[col] = columnHash;
561 * Derive displayable cDNA consensus annotation from computed consensus data.
563 * @param consensusAnnotation
564 * the annotation row to be populated for display
565 * @param consensusData
566 * the computed consensus data
567 * @param showProfileLogo
568 * if true show all symbols present at each position, else only the
571 * the number of sequences in the alignment
573 public static void completeCdnaConsensus(
574 AlignmentAnnotation consensusAnnotation,
575 Hashtable[] consensusData, boolean showProfileLogo, int nseqs)
577 if (consensusAnnotation == null
578 || consensusAnnotation.annotations == null
579 || consensusAnnotation.annotations.length < consensusData.length)
581 // called with a bad alignment annotation row - wait for it to be
582 // initialised properly
586 // ensure codon triplet scales with font size
587 consensusAnnotation.scaleColLabel = true;
588 for (int col = 0; col < consensusData.length; col++)
590 Hashtable hci = consensusData[col];
593 // gapped protein column?
596 // array holds #seqs, #ungapped, then codon counts indexed by codon
597 final int[] codonCounts = (int[]) hci.get(PROFILE);
599 StringBuilder mouseOver = new StringBuilder(32);
602 * First pass - get total count and find the highest
604 final char[] codons = new char[codonCounts.length - 2];
605 for (int j = 2; j < codonCounts.length; j++)
607 final int codonCount = codonCounts[j];
608 codons[j - 2] = (char) (j - 2);
609 totalCount += codonCount;
613 * Sort array of encoded codons by count ascending - so the modal value
614 * goes to the end; start by copying the count (dropping the first value)
616 int[] sortedCodonCounts = new int[codonCounts.length - 2];
617 System.arraycopy(codonCounts, 2, sortedCodonCounts, 0,
618 codonCounts.length - 2);
619 QuickSort.sort(sortedCodonCounts, codons);
621 int modalCodonEncoded = codons[codons.length - 1];
622 int modalCodonCount = sortedCodonCounts[codons.length - 1];
623 String modalCodon = String.valueOf(CodingUtils
624 .decodeCodon(modalCodonEncoded));
625 if (sortedCodonCounts.length > 1
626 && sortedCodonCounts[codons.length - 2] == modalCodonEncoded)
630 float pid = sortedCodonCounts[sortedCodonCounts.length - 1] * 100
631 / (float) totalCount;
634 * todo ? Replace consensus hashtable with sorted arrays of codons and
635 * counts (non-zero only). Include total count in count array [0].
639 * Scan sorted array backwards for most frequent values first.
641 for (int j = codons.length - 1; j >= 0; j--)
643 int codonCount = sortedCodonCounts[j];
648 int codonEncoded = codons[j];
649 final int pct = codonCount * 100 / totalCount;
650 String codon = String
651 .valueOf(CodingUtils.decodeCodon(codonEncoded));
652 Format fmt = getPercentageFormat(nseqs);
653 String formatted = fmt == null ? Integer.toString(pct) : fmt
655 if (showProfileLogo || codonCount == modalCodonCount)
657 mouseOver.append(codon).append(": ").append(formatted)
662 consensusAnnotation.annotations[col] = new Annotation(modalCodon,
663 mouseOver.toString(), ' ', pid);