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.ext.android.SparseIntArray;
29 import jalview.util.Format;
30 import jalview.util.MappingUtils;
31 import jalview.util.QuickSort;
33 import java.util.Arrays;
34 import java.util.Hashtable;
35 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];
130 SparseIntArray values = new SparseIntArray();
132 for (j = 0; j < jSize; j++)
134 if (sequences[j] == null)
137 .println("WARNING: Consensus skipping null sequence - possible race condition.");
140 seq = sequences[j].getSequence();
145 if (c == '.' || c == ' ')
153 values.put('-', values.get('-') + 1);
156 else if ('a' <= c && c <= 'z')
163 values.put(c, values.get(c) + 1);
169 values.put('-', values.get('-') + 1);
174 maxResidue = String.valueOf(c);
179 // FIXME iterate over values keys instead
180 for (v = 'A'; v <= 'Z'; v++)
182 // TODO why ignore values[v] == 1?
183 int count = values.get(v); // values[v];
184 if (count < 1 /* 2 */|| count < maxCount)
189 if (count > maxCount)
191 maxResidue = CHARS[v - 'A'];
193 else if (count == maxCount)
195 maxResidue += CHARS[v - 'A'];
200 if (maxResidue.length() == 0)
206 // TODO use a 1-dimensional array with jSize, nongap in [0] and [1]
207 // residueHash.put(PROFILE, new int[][] { values,
208 // new int[] { jSize, nongap } });
209 residueHash.put(PROFILE, new Profile(values, jSize, nongap));
211 residueHash.put(MAXCOUNT, new Integer(maxCount));
212 residueHash.put(MAXRESIDUE, maxResidue);
214 percentage = ((float) maxCount * 100) / jSize;
215 residueHash.put(PID_GAPS, new Float(percentage));
219 // calculate for non-gapped too
220 percentage = ((float) maxCount * 100) / nongap;
222 residueHash.put(PID_NOGAPS, new Float(percentage));
224 result[i] = residueHash;
229 * Compute all or part of the annotation row from the given consensus
233 * - pre-allocated annotation row
237 * @param ignoreGapsInConsensusCalculation
238 * @param includeAllConsSymbols
241 public static void completeConsensus(AlignmentAnnotation consensus,
242 Hashtable[] hconsensus, int iStart, int width,
243 boolean ignoreGapsInConsensusCalculation,
244 boolean includeAllConsSymbols, long nseq)
246 completeConsensus(consensus, hconsensus, iStart, width,
247 ignoreGapsInConsensusCalculation, includeAllConsSymbols, null,
252 * Derive the consensus annotations to be added to the alignment for display.
253 * This does not recompute the raw data, but may be called on a change in
254 * display options, such as 'show logo', which may in turn result in a change
255 * in the derived values.
258 * the annotation row to add annotations to
260 * the source consensus data
265 * @param ignoreGapsInConsensusCalculation
266 * if true, use the consensus calculated ignoring gaps
267 * @param includeAllConsSymbols
268 * if true include all consensus symbols, else just show modal
272 * number of sequences
274 public static void completeConsensus(AlignmentAnnotation consensus,
275 Hashtable[] hconsensus, int iStart, int width,
276 boolean ignoreGapsInConsensusCalculation,
277 boolean includeAllConsSymbols, char[] alphabet, long nseq)
279 if (consensus == null || consensus.annotations == null
280 || consensus.annotations.length < width)
282 // called with a bad alignment annotation row - wait for it to be
283 // initialised properly
287 final Format fmt = getPercentageFormat(nseq);
289 for (int i = iStart; i < width; i++)
292 if (i >= hconsensus.length || ((hci = hconsensus[i]) == null))
294 // happens if sequences calculated over were shorter than alignment
296 consensus.annotations[i] = null;
299 Float fv = (Float) hci
300 .get(ignoreGapsInConsensusCalculation ? PID_NOGAPS : PID_GAPS);
303 consensus.annotations[i] = null;
304 // data has changed below us .. give up and
307 float value = fv.floatValue();
308 String maxRes = hci.get(AAFrequency.MAXRESIDUE).toString();
309 StringBuilder mouseOver = new StringBuilder(64);
310 if (maxRes.length() > 1)
312 mouseOver.append("[").append(maxRes).append("] ");
317 mouseOver.append(hci.get(AAFrequency.MAXRESIDUE) + " ");
319 // int[][] profile = (int[][]) hci.get(AAFrequency.PROFILE);
320 Profile profile = (Profile) hci.get(AAFrequency.PROFILE);
321 if (profile != null && includeAllConsSymbols)
323 int sequenceCount = profile.height;// profile[1][0];
324 int nonGappedCount = profile.nonGapped;// [1][1];
325 int normalisedBy = ignoreGapsInConsensusCalculation ? nonGappedCount
327 mouseOver.setLength(0);
328 // TODO do this sort once only in calculate()?
329 // char[][] ca = new char[profile[0].length][];
330 // /int length = profile[0].length;
331 int length = profile.profile.size();
332 char[] ca = new char[length];
333 // float[] vl = new float[length];
334 int[] vl = new int[length];
335 for (int c = 0; c < ca.length; c++)
337 int theChar = profile.profile.keyAt(c);
338 ca[c] = (char) theChar;// c;
339 // ca[c] = new char[]
341 vl[c] = profile.profile.get(theChar);// profile[0][c];
345 * sort characters into ascending order of their counts
347 QuickSort.sort(vl, ca);
350 * traverse in reverse order (highest count first) to build tooltip
352 // for (int p = 0, c = ca.length - 1; profile[0][ca[c]] > 0; c--)
353 for (int p = 0, c = ca.length - 1; c >= 0; c--)
355 final char residue = ca[c];
358 // float tval = profile[0][residue] * 100f / normalisedBy;
359 // float tval = profile[0][residue] * 100f / normalisedBy;
360 float tval = (vl[c] * 100f) / normalisedBy;
362 .append((((p == 0) ? "" : "; ")))
365 .append(((fmt != null) ? fmt.form(tval) : ((int) tval)))
374 (((fmt != null) ? fmt.form(value) : ((int) value))))
377 consensus.annotations[i] = new Annotation(maxRes,
378 mouseOver.toString(), ' ', value);
383 * Returns a Format designed to show all significant figures for profile
384 * percentages. For less than 100 sequences, returns null (the integer
385 * percentage value will be displayed). For 100-999 sequences, returns "%3.1f"
390 protected static Format getPercentageFormat(long nseq)
398 return scale <= 1 ? null : new Format("%3." + (scale - 1) + "f");
402 * Returns the sorted profile for the given consensus data. The returned array
406 * [profileType, numberOfValues, nonGapCount, charValue1, percentage1, charValue2, percentage2, ...]
407 * in descending order of percentage value
411 * the data table from which to extract and sort values
413 * if true, only non-gapped values are included in percentage
417 public static int[] extractProfile(Hashtable hconsensus,
420 int[] rtnval = new int[64];
421 // int[][] profile = (int[][]) hconsensus.get(AAFrequency.PROFILE);
422 Profile profile = (Profile) hconsensus.get(AAFrequency.PROFILE);
427 // int profileLength = profile[0].length;
428 int profileLength = profile.profile.size();
429 char[] ca = new char[profileLength];
430 float[] vl = new float[profileLength];
431 // for (int c = 0; c < ca.length; c++)
434 // vl[c] = profile[0][c];
436 for (int i = 0; i < profileLength; i++)
438 int c = profile.profile.keyAt(i);
440 vl[i] = profile.profile.get(c);
442 QuickSort.sort(vl, ca);
443 int nextArrayPos = 2;
444 int totalPercentage = 0;
445 int distinctValuesCount = 0;
446 final int divisor = ignoreGaps ? profile.nonGapped : profile.height;
447 // final int divisor = profile[1][ignoreGaps ? 1 : 0];
448 int j = profile.profile.size();
449 for (int i = 0; i < j; i++)
450 // for (int c = ca.length - 1; profile[0][ca[c]] > 0; c--)
452 int theChar = profile.profile.keyAt(i);
453 int charCount = profile.profile.get(theChar);
458 // rtnval[nextArrayPos++] = ca[c];
459 rtnval[nextArrayPos++] = theChar;
460 // final int percentage = (int) (profile[0][ca[c]] * 100f / divisor);
461 final int percentage = (charCount * 100) / divisor;
462 rtnval[nextArrayPos++] = percentage;
463 totalPercentage += percentage;
464 distinctValuesCount++;
467 rtnval[0] = distinctValuesCount;
468 rtnval[1] = totalPercentage;
469 int[] result = new int[rtnval.length + 1];
470 result[0] = AlignmentAnnotation.SEQUENCE_PROFILE;
471 System.arraycopy(rtnval, 0, result, 1, rtnval.length);
477 * Extract a sorted extract of cDNA codon profile data. The returned array
481 * [profileType, numberOfValues, totalCount, charValue1, percentage1, charValue2, percentage2, ...]
482 * in descending order of percentage value, where the character values encode codon triplets
488 public static int[] extractCdnaProfile(Hashtable hashtable,
491 // this holds #seqs, #ungapped, and then codon count, indexed by encoded
493 int[] codonCounts = (int[]) hashtable.get(PROFILE);
494 int[] sortedCounts = new int[codonCounts.length - 2];
495 System.arraycopy(codonCounts, 2, sortedCounts, 0,
496 codonCounts.length - 2);
498 int[] result = new int[3 + 2 * sortedCounts.length];
499 // first value is just the type of profile data
500 result[0] = AlignmentAnnotation.CDNA_PROFILE;
502 char[] codons = new char[sortedCounts.length];
503 for (int i = 0; i < codons.length; i++)
505 codons[i] = (char) i;
507 QuickSort.sort(sortedCounts, codons);
508 int totalPercentage = 0;
509 int distinctValuesCount = 0;
511 int divisor = ignoreGaps ? codonCounts[1] : codonCounts[0];
512 for (int i = codons.length - 1; i >= 0; i--)
514 final int codonCount = sortedCounts[i];
517 break; // nothing else of interest here
519 distinctValuesCount++;
520 result[j++] = codons[i];
521 final int percentage = codonCount * 100 / divisor;
522 result[j++] = percentage;
523 totalPercentage += percentage;
525 result[2] = totalPercentage;
528 * Just return the non-zero values
530 // todo next value is redundant if we limit the array to non-zero counts
531 result[1] = distinctValuesCount;
532 return Arrays.copyOfRange(result, 0, j);
536 * Compute a consensus for the cDNA coding for a protein alignment.
539 * the protein alignment (which should hold mappings to cDNA
542 * the consensus data stores to be populated (one per column)
544 public static void calculateCdna(AlignmentI alignment,
545 Hashtable[] hconsensus)
547 final char gapCharacter = alignment.getGapCharacter();
548 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
549 if (mappings == null || mappings.isEmpty())
554 int cols = alignment.getWidth();
555 for (int col = 0; col < cols; col++)
557 // todo would prefer a Java bean for consensus data
558 Hashtable<String, int[]> columnHash = new Hashtable<String, int[]>();
559 // #seqs, #ungapped seqs, counts indexed by (codon encoded + 1)
560 int[] codonCounts = new int[66];
561 codonCounts[0] = alignment.getSequences().size();
562 int ungappedCount = 0;
563 for (SequenceI seq : alignment.getSequences())
565 if (seq.getCharAt(col) == gapCharacter)
569 List<char[]> codons = MappingUtils
570 .findCodonsFor(seq, col, mappings);
571 for (char[] codon : codons)
573 int codonEncoded = CodingUtils.encodeCodon(codon);
574 if (codonEncoded >= 0)
576 codonCounts[codonEncoded + 2]++;
581 codonCounts[1] = ungappedCount;
582 // todo: sort values here, save counts and codons?
583 columnHash.put(PROFILE, codonCounts);
584 hconsensus[col] = columnHash;
589 * Derive displayable cDNA consensus annotation from computed consensus data.
591 * @param consensusAnnotation
592 * the annotation row to be populated for display
593 * @param consensusData
594 * the computed consensus data
595 * @param showProfileLogo
596 * if true show all symbols present at each position, else only the
599 * the number of sequences in the alignment
601 public static void completeCdnaConsensus(
602 AlignmentAnnotation consensusAnnotation,
603 Hashtable[] consensusData, boolean showProfileLogo, int nseqs)
605 if (consensusAnnotation == null
606 || consensusAnnotation.annotations == null
607 || consensusAnnotation.annotations.length < consensusData.length)
609 // called with a bad alignment annotation row - wait for it to be
610 // initialised properly
614 // ensure codon triplet scales with font size
615 consensusAnnotation.scaleColLabel = true;
616 for (int col = 0; col < consensusData.length; col++)
618 Hashtable hci = consensusData[col];
621 // gapped protein column?
624 // array holds #seqs, #ungapped, then codon counts indexed by codon
625 final int[] codonCounts = (int[]) hci.get(PROFILE);
629 * First pass - get total count and find the highest
631 final char[] codons = new char[codonCounts.length - 2];
632 for (int j = 2; j < codonCounts.length; j++)
634 final int codonCount = codonCounts[j];
635 codons[j - 2] = (char) (j - 2);
636 totalCount += codonCount;
640 * Sort array of encoded codons by count ascending - so the modal value
641 * goes to the end; start by copying the count (dropping the first value)
643 int[] sortedCodonCounts = new int[codonCounts.length - 2];
644 System.arraycopy(codonCounts, 2, sortedCodonCounts, 0,
645 codonCounts.length - 2);
646 QuickSort.sort(sortedCodonCounts, codons);
648 int modalCodonEncoded = codons[codons.length - 1];
649 int modalCodonCount = sortedCodonCounts[codons.length - 1];
650 String modalCodon = String.valueOf(CodingUtils
651 .decodeCodon(modalCodonEncoded));
652 if (sortedCodonCounts.length > 1
653 && sortedCodonCounts[codons.length - 2] == sortedCodonCounts[codons.length - 1])
656 * two or more codons share the modal count
660 float pid = sortedCodonCounts[sortedCodonCounts.length - 1] * 100
661 / (float) totalCount;
664 * todo ? Replace consensus hashtable with sorted arrays of codons and
665 * counts (non-zero only). Include total count in count array [0].
669 * Scan sorted array backwards for most frequent values first. Show
670 * repeated values compactly.
672 StringBuilder mouseOver = new StringBuilder(32);
673 StringBuilder samePercent = new StringBuilder();
674 String percent = null;
675 String lastPercent = null;
676 Format fmt = getPercentageFormat(nseqs);
678 for (int j = codons.length - 1; j >= 0; j--)
680 int codonCount = sortedCodonCounts[j];
684 * remaining codons are 0% - ignore, but finish off the last one if
687 if (samePercent.length() > 0)
689 mouseOver.append(samePercent).append(": ").append(percent)
694 int codonEncoded = codons[j];
695 final int pct = codonCount * 100 / totalCount;
696 String codon = String
697 .valueOf(CodingUtils.decodeCodon(codonEncoded));
698 percent = fmt == null ? Integer.toString(pct) : fmt.form(pct);
699 if (showProfileLogo || codonCount == modalCodonCount)
701 if (percent.equals(lastPercent) && j > 0)
703 samePercent.append(samePercent.length() == 0 ? "" : ", ");
704 samePercent.append(codon);
708 if (samePercent.length() > 0)
710 mouseOver.append(samePercent).append(": ")
711 .append(lastPercent).append("% ");
713 samePercent.setLength(0);
714 samePercent.append(codon);
716 lastPercent = percent;
720 consensusAnnotation.annotations[col] = new Annotation(modalCodon,
721 mouseOver.toString(), ' ', pid);