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.HiddenMarkovModel;
28 import jalview.datamodel.Profile;
29 import jalview.datamodel.ProfileI;
30 import jalview.datamodel.Profiles;
31 import jalview.datamodel.ProfilesI;
32 import jalview.datamodel.ResidueCount;
33 import jalview.datamodel.ResidueCount.SymbolCounts;
34 import jalview.datamodel.SequenceI;
35 import jalview.ext.android.SparseIntArray;
36 import jalview.schemes.ResidueProperties;
37 import jalview.util.Comparison;
38 import jalview.util.Format;
39 import jalview.util.MappingUtils;
40 import jalview.util.QuickSort;
42 import java.awt.Color;
43 import java.util.Arrays;
44 import java.util.Hashtable;
45 import java.util.List;
48 * Takes in a vector or array of sequences and column start and column end and
49 * returns a new Hashtable[] of size maxSeqLength, if Hashtable not supplied.
50 * This class is used extensively in calculating alignment colourschemes that
51 * depend on the amount of conservation in each alignment column.
54 public class AAFrequency
56 private static final double LOG2 = Math.log(2);
58 public static final String PROFILE = "P";
60 public static final ProfilesI calculate(List<SequenceI> list, int start,
63 return calculate(list, start, end, false);
66 public static final ProfilesI calculate(List<SequenceI> sequences,
67 int start, int end, boolean profile)
69 SequenceI[] seqs = new SequenceI[sequences.size()];
71 synchronized (sequences)
73 for (int i = 0; i < sequences.size(); i++)
75 seqs[i] = sequences.get(i);
76 int length = seqs[i].getLength();
88 ProfilesI reply = calculate(seqs, width, start, end, profile);
94 * Calculate the consensus symbol(s) for each column in the given range.
98 * the full width of the alignment
100 * start column (inclusive, base zero)
102 * end column (exclusive)
103 * @param saveFullProfile
104 * if true, store all symbol counts
106 public static final ProfilesI calculate(final SequenceI[] sequences,
107 int width, int start, int end, boolean saveFullProfile)
109 // long now = System.currentTimeMillis();
110 int seqCount = sequences.length;
111 boolean nucleotide = false;
112 int nucleotideCount = 0;
113 int peptideCount = 0;
115 ProfileI[] result = new ProfileI[width];
117 for (int column = start; column < end; column++)
120 * Apply a heuristic to detect nucleotide data (which can
121 * be counted in more compact arrays); here we test for
122 * more than 90% nucleotide; recheck every 10 columns in case
123 * of misleading data e.g. highly conserved Alanine in peptide!
124 * Mistakenly guessing nucleotide has a small performance cost,
125 * as it will result in counting in sparse arrays.
126 * Mistakenly guessing peptide has a small space cost,
127 * as it will use a larger than necessary array to hold counts.
129 if (nucleotideCount > 100 && column % 10 == 0)
131 nucleotide = (9 * peptideCount < nucleotideCount);
133 ResidueCount residueCounts = new ResidueCount(nucleotide);
135 for (int row = 0; row < seqCount; row++)
137 if (sequences[row] == null)
140 "WARNING: Consensus skipping null sequence - possible race condition.");
143 if (sequences[row].getLength() > column)
145 char c = sequences[row].getCharAt(column);
146 residueCounts.add(c);
147 if (Comparison.isNucleotide(c))
151 else if (!Comparison.isGap(c))
159 * count a gap if the sequence doesn't reach this column
161 residueCounts.addGap();
165 int maxCount = residueCounts.getModalCount();
166 String maxResidue = residueCounts.getResiduesForCount(maxCount);
167 int gapCount = residueCounts.getGapCount();
168 ProfileI profile = new Profile(seqCount, gapCount, maxCount,
173 profile.setCounts(residueCounts);
176 result[column] = profile;
178 return new Profiles(result);
179 // long elapsed = System.currentTimeMillis() - now;
180 // System.out.println(elapsed);
184 * Returns the full set of profiles for a hidden Markov model. The underlying
185 * data is the raw probabilities of a residue being emitted at each node,
186 * however the profiles returned by this function contain the percentage
187 * chance of a residue emission.
191 * The width of the Profile array (Profiles) to be returned.
193 * The alignment column on which the first profile is based.
195 * The alignment column on which the last profile is based.
196 * @param removeBelowBackground
197 * if true, symbols with a match emission probability less than
198 * background frequency are ignored
201 public static ProfilesI calculateHMMProfiles(final HiddenMarkovModel hmm,
202 int width, int start, int end, boolean removeBelowBackground,
203 boolean infoLetterHeight)
205 ProfileI[] result = new ProfileI[width];
206 char[] symbols = hmm.getSymbols().toCharArray();
207 int symbolCount = symbols.length;
208 for (int column = start; column < end; column++)
210 ResidueCount counts = new ResidueCount();
211 for (char symbol : symbols)
213 int value = getAnalogueCount(hmm, column, symbol,
214 removeBelowBackground, infoLetterHeight);
215 counts.put(symbol, value);
217 int maxCount = counts.getModalCount();
218 String maxResidue = counts.getResiduesForCount(maxCount);
219 int gapCount = counts.getGapCount();
220 ProfileI profile = new Profile(symbolCount, gapCount, maxCount,
222 profile.setCounts(counts);
224 result[column] = profile;
226 return new Profiles(result);
230 * Make an estimate of the profile size we are going to compute i.e. how many
231 * different characters may be present in it. Overestimating has a cost of
232 * using more memory than necessary. Underestimating has a cost of needing to
233 * extend the SparseIntArray holding the profile counts.
235 * @param profileSizes
236 * counts of sizes of profiles so far encountered
239 static int estimateProfileSize(SparseIntArray profileSizes)
241 if (profileSizes.size() == 0)
247 * could do a statistical heuristic here e.g. 75%ile
248 * for now just return the largest value
250 return profileSizes.keyAt(profileSizes.size() - 1);
254 * Derive the consensus annotations to be added to the alignment for display.
255 * This does not recompute the raw data, but may be called on a change in
256 * display options, such as 'ignore gaps', which may in turn result in a
257 * change in the derived values.
260 * the annotation row to add annotations to
262 * the source consensus data
264 * start column (inclusive)
266 * end column (exclusive)
268 * if true, normalise residue percentages ignoring gaps
269 * @param showSequenceLogo
270 * if true include all consensus symbols, else just show modal
273 * number of sequences
275 public static void completeConsensus(AlignmentAnnotation consensus,
276 ProfilesI profiles, int startCol, int endCol, boolean ignoreGaps,
277 boolean showSequenceLogo, long nseq)
279 // long now = System.currentTimeMillis();
280 if (consensus == null || consensus.annotations == null
281 || consensus.annotations.length < endCol)
284 * called with a bad alignment annotation row
285 * wait for it to be initialised properly
290 for (int i = startCol; i < endCol; i++)
292 ProfileI profile = profiles.get(i);
296 * happens if sequences calculated over were
297 * shorter than alignment width
299 consensus.annotations[i] = null;
303 final int dp = getPercentageDp(nseq);
305 float value = profile.getPercentageIdentity(ignoreGaps);
307 String description = getTooltip(profile, value, showSequenceLogo,
310 String modalResidue = profile.getModalResidue();
311 if ("".equals(modalResidue))
315 else if (modalResidue.length() > 1)
319 consensus.annotations[i] = new Annotation(modalResidue, description,
322 // long elapsed = System.currentTimeMillis() - now;
323 // System.out.println(-elapsed);
327 * Derive the information annotations to be added to the alignment for
328 * display. This does not recompute the raw data, but may be called on a
329 * change in display options, such as 'ignore below background frequency',
330 * which may in turn result in a change in the derived values.
333 * the annotation row to add annotations to
335 * the source information data
337 * start column (inclusive)
339 * end column (exclusive)
341 * if true, normalise residue percentages
342 * @param showSequenceLogo
343 * if true include all information symbols, else just show modal
346 public static float completeInformation(AlignmentAnnotation information,
347 ProfilesI profiles, int startCol, int endCol)
349 // long now = System.currentTimeMillis();
350 if (information == null || information.annotations == null)
353 * called with a bad alignment annotation row
354 * wait for it to be initialised properly
360 SequenceI hmmSeq = information.sequenceRef;
362 int seqLength = hmmSeq.getLength();
363 if (information.annotations.length < seqLength)
368 HiddenMarkovModel hmm = hmmSeq.getHMM();
370 for (int column = startCol; column < endCol; column++)
372 if (column >= seqLength)
374 // hmm consensus sequence is shorter than the alignment
378 float value = hmm.getInformationContent(column);
379 boolean isNaN = Float.isNaN(value);
382 max = Math.max(max, value);
385 String description = isNaN ? null
386 : String.format("%.4f bits", value);
387 information.annotations[column] = new Annotation(
389 Character.toUpperCase(hmmSeq.getCharAt(column))),
390 description, ' ', value);
393 information.graphMax = max;
398 * Derive the occupancy count annotation
401 * the annotation row to add annotations to
403 * the source consensus data
405 * start column (inclusive)
407 * end column (exclusive)
409 public static void completeGapAnnot(AlignmentAnnotation occupancy,
410 ProfilesI profiles, int startCol, int endCol, long nseq)
412 if (occupancy == null || occupancy.annotations == null
413 || occupancy.annotations.length < endCol)
416 * called with a bad alignment annotation row
417 * wait for it to be initialised properly
421 // always set ranges again
422 occupancy.graphMax = nseq;
423 occupancy.graphMin = 0;
424 double scale = 0.8 / nseq;
425 for (int i = startCol; i < endCol; i++)
427 ProfileI profile = profiles.get(i);
431 * happens if sequences calculated over were
432 * shorter than alignment width
434 occupancy.annotations[i] = null;
438 final int gapped = profile.getNonGapped();
440 String description = "" + gapped;
442 occupancy.annotations[i] = new Annotation("", description, '\0',
444 jalview.util.ColorUtils.bleachColour(Color.DARK_GRAY,
445 (float) scale * gapped));
450 * Returns a tooltip showing either
452 * <li>the full profile (percentages of all residues present), if
453 * showSequenceLogo is true, or</li>
454 * <li>just the modal (most common) residue(s), if showSequenceLogo is
457 * Percentages are as a fraction of all sequence, or only ungapped sequences
458 * if ignoreGaps is true.
462 * @param showSequenceLogo
465 * the number of decimal places to format percentages to
468 static String getTooltip(ProfileI profile, float pid,
469 boolean showSequenceLogo, boolean ignoreGaps, int dp)
471 ResidueCount counts = profile.getCounts();
473 String description = null;
474 if (counts != null && showSequenceLogo)
476 int normaliseBy = ignoreGaps ? profile.getNonGapped()
477 : profile.getHeight();
478 description = counts.getTooltip(normaliseBy, dp);
482 StringBuilder sb = new StringBuilder(64);
483 String maxRes = profile.getModalResidue();
484 if (maxRes.length() > 1)
486 sb.append("[").append(maxRes).append("]");
492 if (maxRes.length() > 0)
495 Format.appendPercentage(sb, pid, dp);
498 description = sb.toString();
504 * Returns the sorted profile for the given consensus data. The returned array
508 * [profileType, numberOfValues, nonGapCount, charValue1, percentage1, charValue2, percentage2, ...]
509 * in descending order of percentage value
513 * the data object from which to extract and sort values
515 * if true, only non-gapped values are included in percentage
519 public static int[] extractProfile(ProfileI profile, boolean ignoreGaps)
521 int[] rtnval = new int[64];
522 ResidueCount counts = profile.getCounts();
528 SymbolCounts symbolCounts = counts.getSymbolCounts();
529 char[] symbols = symbolCounts.symbols;
530 int[] values = symbolCounts.values;
531 QuickSort.sort(values, symbols);
532 int nextArrayPos = 2;
533 int totalPercentage = 0;
534 final int divisor = ignoreGaps ? profile.getNonGapped()
535 : profile.getHeight();
538 * traverse the arrays in reverse order (highest counts first)
540 for (int i = symbols.length - 1; i >= 0; i--)
542 int theChar = symbols[i];
543 int charCount = values[i];
545 rtnval[nextArrayPos++] = theChar;
546 final int percentage = (charCount * 100) / divisor;
547 rtnval[nextArrayPos++] = percentage;
548 totalPercentage += percentage;
550 rtnval[0] = symbols.length;
551 rtnval[1] = totalPercentage;
552 int[] result = new int[rtnval.length + 1];
553 result[0] = AlignmentAnnotation.SEQUENCE_PROFILE;
554 System.arraycopy(rtnval, 0, result, 1, rtnval.length);
561 * Extract a sorted extract of cDNA codon profile data. The returned array
565 * [profileType, numberOfValues, totalCount, charValue1, percentage1, charValue2, percentage2, ...]
566 * in descending order of percentage value, where the character values encode codon triplets
572 public static int[] extractCdnaProfile(Hashtable hashtable,
575 // this holds #seqs, #ungapped, and then codon count, indexed by encoded
577 int[] codonCounts = (int[]) hashtable.get(PROFILE);
578 int[] sortedCounts = new int[codonCounts.length - 2];
579 System.arraycopy(codonCounts, 2, sortedCounts, 0,
580 codonCounts.length - 2);
582 int[] result = new int[3 + 2 * sortedCounts.length];
583 // first value is just the type of profile data
584 result[0] = AlignmentAnnotation.CDNA_PROFILE;
586 char[] codons = new char[sortedCounts.length];
587 for (int i = 0; i < codons.length; i++)
589 codons[i] = (char) i;
591 QuickSort.sort(sortedCounts, codons);
592 int totalPercentage = 0;
593 int distinctValuesCount = 0;
595 int divisor = ignoreGaps ? codonCounts[1] : codonCounts[0];
596 for (int i = codons.length - 1; i >= 0; i--)
598 final int codonCount = sortedCounts[i];
601 break; // nothing else of interest here
603 distinctValuesCount++;
604 result[j++] = codons[i];
605 final int percentage = codonCount * 100 / divisor;
606 result[j++] = percentage;
607 totalPercentage += percentage;
609 result[2] = totalPercentage;
612 * Just return the non-zero values
614 // todo next value is redundant if we limit the array to non-zero counts
615 result[1] = distinctValuesCount;
616 return Arrays.copyOfRange(result, 0, j);
620 * Compute a consensus for the cDNA coding for a protein alignment.
623 * the protein alignment (which should hold mappings to cDNA
626 * the consensus data stores to be populated (one per column)
628 public static void calculateCdna(AlignmentI alignment,
629 Hashtable[] hconsensus)
631 final char gapCharacter = alignment.getGapCharacter();
632 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
633 if (mappings == null || mappings.isEmpty())
638 int cols = alignment.getWidth();
639 for (int col = 0; col < cols; col++)
641 // todo would prefer a Java bean for consensus data
642 Hashtable<String, int[]> columnHash = new Hashtable<>();
643 // #seqs, #ungapped seqs, counts indexed by (codon encoded + 1)
644 int[] codonCounts = new int[66];
645 codonCounts[0] = alignment.getSequences().size();
646 int ungappedCount = 0;
647 for (SequenceI seq : alignment.getSequences())
649 if (seq.getCharAt(col) == gapCharacter)
653 List<char[]> codons = MappingUtils.findCodonsFor(seq, col,
655 for (char[] codon : codons)
657 int codonEncoded = CodingUtils.encodeCodon(codon);
658 if (codonEncoded >= 0)
660 codonCounts[codonEncoded + 2]++;
665 codonCounts[1] = ungappedCount;
666 // todo: sort values here, save counts and codons?
667 columnHash.put(PROFILE, codonCounts);
668 hconsensus[col] = columnHash;
673 * Derive displayable cDNA consensus annotation from computed consensus data.
675 * @param consensusAnnotation
676 * the annotation row to be populated for display
677 * @param consensusData
678 * the computed consensus data
679 * @param showProfileLogo
680 * if true show all symbols present at each position, else only the
683 * the number of sequences in the alignment
685 public static void completeCdnaConsensus(
686 AlignmentAnnotation consensusAnnotation,
687 Hashtable[] consensusData, boolean showProfileLogo, int nseqs)
689 if (consensusAnnotation == null
690 || consensusAnnotation.annotations == null
691 || consensusAnnotation.annotations.length < consensusData.length)
693 // called with a bad alignment annotation row - wait for it to be
694 // initialised properly
698 // ensure codon triplet scales with font size
699 consensusAnnotation.scaleColLabel = true;
700 for (int col = 0; col < consensusData.length; col++)
702 Hashtable hci = consensusData[col];
705 // gapped protein column?
708 // array holds #seqs, #ungapped, then codon counts indexed by codon
709 final int[] codonCounts = (int[]) hci.get(PROFILE);
713 * First pass - get total count and find the highest
715 final char[] codons = new char[codonCounts.length - 2];
716 for (int j = 2; j < codonCounts.length; j++)
718 final int codonCount = codonCounts[j];
719 codons[j - 2] = (char) (j - 2);
720 totalCount += codonCount;
724 * Sort array of encoded codons by count ascending - so the modal value
725 * goes to the end; start by copying the count (dropping the first value)
727 int[] sortedCodonCounts = new int[codonCounts.length - 2];
728 System.arraycopy(codonCounts, 2, sortedCodonCounts, 0,
729 codonCounts.length - 2);
730 QuickSort.sort(sortedCodonCounts, codons);
732 int modalCodonEncoded = codons[codons.length - 1];
733 int modalCodonCount = sortedCodonCounts[codons.length - 1];
734 String modalCodon = String
735 .valueOf(CodingUtils.decodeCodon(modalCodonEncoded));
736 if (sortedCodonCounts.length > 1 && sortedCodonCounts[codons.length
737 - 2] == sortedCodonCounts[codons.length - 1])
740 * two or more codons share the modal count
744 float pid = sortedCodonCounts[sortedCodonCounts.length - 1] * 100
745 / (float) totalCount;
748 * todo ? Replace consensus hashtable with sorted arrays of codons and
749 * counts (non-zero only). Include total count in count array [0].
753 * Scan sorted array backwards for most frequent values first. Show
754 * repeated values compactly.
756 StringBuilder mouseOver = new StringBuilder(32);
757 StringBuilder samePercent = new StringBuilder();
758 String percent = null;
759 String lastPercent = null;
760 int percentDecPl = getPercentageDp(nseqs);
762 for (int j = codons.length - 1; j >= 0; j--)
764 int codonCount = sortedCodonCounts[j];
768 * remaining codons are 0% - ignore, but finish off the last one if
771 if (samePercent.length() > 0)
773 mouseOver.append(samePercent).append(": ").append(percent)
778 int codonEncoded = codons[j];
779 final int pct = codonCount * 100 / totalCount;
780 String codon = String
781 .valueOf(CodingUtils.decodeCodon(codonEncoded));
782 StringBuilder sb = new StringBuilder();
783 Format.appendPercentage(sb, pct, percentDecPl);
784 percent = sb.toString();
785 if (showProfileLogo || codonCount == modalCodonCount)
787 if (percent.equals(lastPercent) && j > 0)
789 samePercent.append(samePercent.length() == 0 ? "" : ", ");
790 samePercent.append(codon);
794 if (samePercent.length() > 0)
796 mouseOver.append(samePercent).append(": ").append(lastPercent)
799 samePercent.setLength(0);
800 samePercent.append(codon);
802 lastPercent = percent;
806 consensusAnnotation.annotations[col] = new Annotation(modalCodon,
807 mouseOver.toString(), ' ', pid);
812 * Returns the number of decimal places to show for profile percentages. For
813 * less than 100 sequences, returns zero (the integer percentage value will be
814 * displayed). For 100-999 sequences, returns 1, for 1000-9999 returns 2, etc.
819 protected static int getPercentageDp(long nseq)
831 * Returns the sorted HMM profile for the given column of the alignment. The
832 * returned array contains
835 * [profileType=0, numberOfValues, 100, charValue1, percentage1, charValue2, percentage2, ...]
836 * in descending order of percentage value
841 * @param removeBelowBackground
842 * if true, ignores residues with probability less than their
843 * background frequency
845 * if true, uses the log ratio 'information' measure to scale the
849 public static int[] extractHMMProfile(HiddenMarkovModel hmm, int column,
850 boolean removeBelowBackground, boolean infoHeight)
856 String alphabet = hmm.getSymbols();
857 int size = alphabet.length();
858 char symbols[] = new char[size];
859 int values[] = new int[size];
862 for (int i = 0; i < size; i++)
864 char symbol = alphabet.charAt(i);
866 int value = getAnalogueCount(hmm, column, symbol,
867 removeBelowBackground, infoHeight);
873 * sort symbols by increasing emission probability
875 QuickSort.sort(values, symbols);
877 int[] profile = new int[3 + size * 2];
879 profile[0] = AlignmentAnnotation.SEQUENCE_PROFILE;
884 * order symbol/count profile by decreasing emission probability
889 for (int k = size - 1; k >= 0; k--)
892 int value = values[k];
893 if (removeBelowBackground)
895 percentage = ((float) value) / totalCount * 100f;
899 percentage = value / 100f;
901 int intPercent = Math.round(percentage);
902 profile[arrayPos] = symbols[k];
903 profile[arrayPos + 1] = intPercent;
911 * Converts the emission probability of a residue at a column in the alignment
912 * to a 'count', suitable for rendering as an annotation value
917 * @param removeBelowBackground
918 * if true, returns 0 for any symbol with a match emission
919 * probability less than the background frequency
920 * @infoHeight if true, uses the log ratio 'information content' to scale the
924 static int getAnalogueCount(HiddenMarkovModel hmm, int column,
925 char symbol, boolean removeBelowBackground, boolean infoHeight)
927 double value = hmm.getMatchEmissionProbability(column, symbol);
928 double freq = ResidueProperties.backgroundFrequencies
929 .get(hmm.getAlphabetType()).get(symbol);
930 if (value < freq && removeBelowBackground)
937 value = value * (Math.log(value / freq) / LOG2);
940 value = value * 10000d;
941 return Math.round((float) value);