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.
56 public class AAFrequency
58 public static final String PROFILE = "P";
60 private static final String AMINO = "amino";
62 private static final String DNA = "DNA";
64 private static final String RNA = "RNA";
67 * Quick look-up of String value of char 'A' to 'Z'
69 private static final String[] CHARS = new String['Z' - 'A' + 1];
73 for (char c = 'A'; c <= 'Z'; c++)
75 CHARS[c - 'A'] = String.valueOf(c);
79 public static final ProfilesI calculate(List<SequenceI> list, int start,
82 return calculate(list, start, end, false);
85 public static final ProfilesI calculate(List<SequenceI> sequences,
86 int start, int end, boolean profile)
88 SequenceI[] seqs = new SequenceI[sequences.size()];
90 synchronized (sequences)
92 for (int i = 0; i < sequences.size(); i++)
94 seqs[i] = sequences.get(i);
95 int length = seqs[i].getLength();
107 ProfilesI reply = calculate(seqs, width, start, end, profile);
115 * Calculate the consensus symbol(s) for each column in the given range.
119 * the full width of the alignment
121 * start column (inclusive, base zero)
123 * end column (exclusive)
124 * @param saveFullProfile
125 * if true, store all symbol counts
127 public static final ProfilesI calculate(final SequenceI[] sequences,
128 int width, int start, int end, boolean saveFullProfile)
130 // long now = System.currentTimeMillis();
131 int seqCount = sequences.length;
132 boolean nucleotide = false;
133 int nucleotideCount = 0;
134 int peptideCount = 0;
136 ProfileI[] result = new ProfileI[width];
138 for (int column = start; column < end; column++)
141 * Apply a heuristic to detect nucleotide data (which can
142 * be counted in more compact arrays); here we test for
143 * more than 90% nucleotide; recheck every 10 columns in case
144 * of misleading data e.g. highly conserved Alanine in peptide!
145 * Mistakenly guessing nucleotide has a small performance cost,
146 * as it will result in counting in sparse arrays.
147 * Mistakenly guessing peptide has a small space cost,
148 * as it will use a larger than necessary array to hold counts.
150 if (nucleotideCount > 100 && column % 10 == 0)
152 nucleotide = (9 * peptideCount < nucleotideCount);
154 ResidueCount residueCounts = new ResidueCount(nucleotide);
156 for (int row = 0; row < seqCount; row++)
158 if (sequences[row] == null)
161 "WARNING: Consensus skipping null sequence - possible race condition.");
164 if (sequences[row].getLength() > column)
166 char c = sequences[row].getCharAt(column);
167 residueCounts.add(c);
168 if (Comparison.isNucleotide(c))
172 else if (!Comparison.isGap(c))
180 * count a gap if the sequence doesn't reach this column
182 residueCounts.addGap();
186 int maxCount = residueCounts.getModalCount();
187 String maxResidue = residueCounts.getResiduesForCount(maxCount);
188 int gapCount = residueCounts.getGapCount();
189 ProfileI profile = new Profile(seqCount, gapCount, maxCount,
194 profile.setCounts(residueCounts);
197 result[column] = profile;
199 return new Profiles(result);
200 // long elapsed = System.currentTimeMillis() - now;
201 // System.out.println(elapsed);
205 * Returns the full set of profiles for a hidden Markov model. The underlying
206 * data is the raw probabilities of a residue being emitted at each node,
207 * however the profiles returned by this function contain the percentage
208 * chance of a residue emission.
212 * The width of the Profile array (Profiles) to be returned.
214 * The alignment column on which the first profile is based.
216 * The alignment column on which the last profile is based.
217 * @param saveFullProfile
218 * Flag for saving the counts for each profile
219 * @param removeBelowBackground
220 * Flag for removing any characters with a match emission probability
221 * less than its background frequency
224 public static ProfilesI calculateHMMProfiles(final HiddenMarkovModel hmm,
225 int width, int start, int end, boolean saveFullProfile,
226 boolean removeBelowBackground, boolean infoLetterHeight)
228 ProfileI[] result = new ProfileI[width];
229 int symbolCount = hmm.getNumberOfSymbols();
230 for (int column = start; column < end; column++)
232 ResidueCount counts = new ResidueCount();
233 for (char symbol : hmm.getSymbols())
235 int value = getAnalogueCount(hmm, column, symbol,
236 removeBelowBackground, infoLetterHeight);
237 counts.put(symbol, value);
239 int maxCount = counts.getModalCount();
240 String maxResidue = counts.getResiduesForCount(maxCount);
241 int gapCount = counts.getGapCount();
242 ProfileI profile = new Profile(symbolCount, gapCount, maxCount,
247 profile.setCounts(counts);
250 result[column] = profile;
252 return new Profiles(result);
256 * Make an estimate of the profile size we are going to compute i.e. how many
257 * different characters may be present in it. Overestimating has a cost of
258 * using more memory than necessary. Underestimating has a cost of needing to
259 * extend the SparseIntArray holding the profile counts.
261 * @param profileSizes
262 * counts of sizes of profiles so far encountered
265 static int estimateProfileSize(SparseIntArray profileSizes)
267 if (profileSizes.size() == 0)
273 * could do a statistical heuristic here e.g. 75%ile
274 * for now just return the largest value
276 return profileSizes.keyAt(profileSizes.size() - 1);
280 * Derive the consensus annotations to be added to the alignment for display.
281 * This does not recompute the raw data, but may be called on a change in
282 * display options, such as 'ignore gaps', which may in turn result in a
283 * change in the derived values.
286 * the annotation row to add annotations to
288 * the source consensus data
290 * start column (inclusive)
292 * end column (exclusive)
294 * if true, normalise residue percentages ignoring gaps
295 * @param showSequenceLogo
296 * if true include all consensus symbols, else just show modal
299 * number of sequences
301 public static void completeConsensus(AlignmentAnnotation consensus,
302 ProfilesI profiles, int startCol, int endCol, boolean ignoreGaps,
303 boolean showSequenceLogo, long nseq)
305 // long now = System.currentTimeMillis();
306 if (consensus == null || consensus.annotations == null
307 || consensus.annotations.length < endCol)
310 * called with a bad alignment annotation row
311 * wait for it to be initialised properly
316 for (int i = startCol; i < endCol; i++)
318 ProfileI profile = profiles.get(i);
322 * happens if sequences calculated over were
323 * shorter than alignment width
325 consensus.annotations[i] = null;
329 final int dp = getPercentageDp(nseq);
331 float value = profile.getPercentageIdentity(ignoreGaps);
333 String description = getTooltip(profile, value, showSequenceLogo,
336 String modalResidue = profile.getModalResidue();
337 if ("".equals(modalResidue))
341 else if (modalResidue.length() > 1)
345 consensus.annotations[i] = new Annotation(modalResidue, description,
348 // long elapsed = System.currentTimeMillis() - now;
349 // System.out.println(-elapsed);
353 * Derive the information annotations to be added to the alignment for
354 * display. This does not recompute the raw data, but may be called on a
355 * change in display options, such as 'ignore below background frequency',
356 * which may in turn result in a change in the derived values.
359 * the annotation row to add annotations to
361 * the source information data
363 * start column (inclusive)
365 * end column (exclusive)
367 * if true, normalise residue percentages
368 * @param showSequenceLogo
369 * if true include all information symbols, else just show modal
372 * number of sequences
374 public static float completeInformation(AlignmentAnnotation information,
375 ProfilesI profiles, int startCol, int endCol, long nseq,
378 // long now = System.currentTimeMillis();
379 if (information == null || information.annotations == null
380 || information.annotations.length < endCol)
383 * called with a bad alignment annotation row
384 * wait for it to be initialised properly
391 for (int i = startCol; i < endCol; i++)
393 ProfileI profile = profiles.get(i);
397 * happens if sequences calculated over were
398 * shorter than alignment width
400 information.annotations[i] = null;
404 HiddenMarkovModel hmm;
406 SequenceI hmmSeq = information.sequenceRef;
408 hmm = hmmSeq.getHMM();
410 Float value = getInformationContent(i, hmm);
417 String description = value + " bits";
418 information.annotations[i] = new Annotation(
419 Character.toString(Character
420 .toUpperCase(hmm.getConsensusAtAlignColumn(i))),
421 description, ' ', value);
423 if (max > currentMax)
425 information.graphMax = max;
430 information.graphMax = currentMax;
436 * Derive the gap count annotation row.
439 * the annotation row to add annotations to
441 * the source consensus data
443 * start column (inclusive)
445 * end column (exclusive)
447 public static void completeGapAnnot(AlignmentAnnotation gaprow,
448 ProfilesI profiles, int startCol, int endCol, long nseq)
450 if (gaprow == null || gaprow.annotations == null
451 || gaprow.annotations.length < endCol)
454 * called with a bad alignment annotation row
455 * wait for it to be initialised properly
459 // always set ranges again
460 gaprow.graphMax = nseq;
462 double scale = 0.8 / nseq;
463 for (int i = startCol; i < endCol; i++)
465 ProfileI profile = profiles.get(i);
469 * happens if sequences calculated over were
470 * shorter than alignment width
472 gaprow.annotations[i] = null;
476 final int gapped = profile.getNonGapped();
478 String description = "" + gapped;
480 gaprow.annotations[i] = new Annotation("", description, '\0', gapped,
481 jalview.util.ColorUtils.bleachColour(Color.DARK_GRAY,
482 (float) scale * gapped));
487 * Returns a tooltip showing either
489 * <li>the full profile (percentages of all residues present), if
490 * showSequenceLogo is true, or</li>
491 * <li>just the modal (most common) residue(s), if showSequenceLogo is
494 * Percentages are as a fraction of all sequence, or only ungapped sequences
495 * if ignoreGaps is true.
499 * @param showSequenceLogo
502 * the number of decimal places to format percentages to
505 static String getTooltip(ProfileI profile, float pid,
506 boolean showSequenceLogo, boolean ignoreGaps, int dp)
508 ResidueCount counts = profile.getCounts();
510 String description = null;
511 if (counts != null && showSequenceLogo)
513 int normaliseBy = ignoreGaps ? profile.getNonGapped()
514 : profile.getHeight();
515 description = counts.getTooltip(normaliseBy, dp);
519 StringBuilder sb = new StringBuilder(64);
520 String maxRes = profile.getModalResidue();
521 if (maxRes.length() > 1)
523 sb.append("[").append(maxRes).append("]");
529 if (maxRes.length() > 0)
532 Format.appendPercentage(sb, pid, dp);
535 description = sb.toString();
541 * Returns the sorted profile for the given consensus data. The returned array
545 * [profileType, numberOfValues, nonGapCount, charValue1, percentage1, charValue2, percentage2, ...]
546 * in descending order of percentage value
550 * the data object from which to extract and sort values
552 * if true, only non-gapped values are included in percentage
556 public static int[] extractProfile(ProfileI profile, boolean ignoreGaps)
558 int[] rtnval = new int[64];
559 ResidueCount counts = profile.getCounts();
565 SymbolCounts symbolCounts = counts.getSymbolCounts();
566 char[] symbols = symbolCounts.symbols;
567 int[] values = symbolCounts.values;
568 QuickSort.sort(values, symbols);
569 int nextArrayPos = 2;
570 int totalPercentage = 0;
571 final int divisor = ignoreGaps ? profile.getNonGapped()
572 : profile.getHeight();
575 * traverse the arrays in reverse order (highest counts first)
577 for (int i = symbols.length - 1; i >= 0; i--)
579 int theChar = symbols[i];
580 int charCount = values[i];
582 rtnval[nextArrayPos++] = theChar;
583 final int percentage = (charCount * 100) / divisor;
584 rtnval[nextArrayPos++] = percentage;
585 totalPercentage += percentage;
587 rtnval[0] = symbols.length;
588 rtnval[1] = totalPercentage;
589 int[] result = new int[rtnval.length + 1];
590 result[0] = AlignmentAnnotation.SEQUENCE_PROFILE;
591 System.arraycopy(rtnval, 0, result, 1, rtnval.length);
598 * Extract a sorted extract of cDNA codon profile data. The returned array
602 * [profileType, numberOfValues, totalCount, charValue1, percentage1, charValue2, percentage2, ...]
603 * in descending order of percentage value, where the character values encode codon triplets
609 public static int[] extractCdnaProfile(Hashtable hashtable,
612 // this holds #seqs, #ungapped, and then codon count, indexed by encoded
614 int[] codonCounts = (int[]) hashtable.get(PROFILE);
615 int[] sortedCounts = new int[codonCounts.length - 2];
616 System.arraycopy(codonCounts, 2, sortedCounts, 0,
617 codonCounts.length - 2);
619 int[] result = new int[3 + 2 * sortedCounts.length];
620 // first value is just the type of profile data
621 result[0] = AlignmentAnnotation.CDNA_PROFILE;
623 char[] codons = new char[sortedCounts.length];
624 for (int i = 0; i < codons.length; i++)
626 codons[i] = (char) i;
628 QuickSort.sort(sortedCounts, codons);
629 int totalPercentage = 0;
630 int distinctValuesCount = 0;
632 int divisor = ignoreGaps ? codonCounts[1] : codonCounts[0];
633 for (int i = codons.length - 1; i >= 0; i--)
635 final int codonCount = sortedCounts[i];
638 break; // nothing else of interest here
640 distinctValuesCount++;
641 result[j++] = codons[i];
642 final int percentage = codonCount * 100 / divisor;
643 result[j++] = percentage;
644 totalPercentage += percentage;
646 result[2] = totalPercentage;
649 * Just return the non-zero values
651 // todo next value is redundant if we limit the array to non-zero counts
652 result[1] = distinctValuesCount;
653 return Arrays.copyOfRange(result, 0, j);
657 * Compute a consensus for the cDNA coding for a protein alignment.
660 * the protein alignment (which should hold mappings to cDNA
663 * the consensus data stores to be populated (one per column)
665 public static void calculateCdna(AlignmentI alignment,
666 Hashtable[] hconsensus)
668 final char gapCharacter = alignment.getGapCharacter();
669 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
670 if (mappings == null || mappings.isEmpty())
675 int cols = alignment.getWidth();
676 for (int col = 0; col < cols; col++)
678 // todo would prefer a Java bean for consensus data
679 Hashtable<String, int[]> columnHash = new Hashtable<>();
680 // #seqs, #ungapped seqs, counts indexed by (codon encoded + 1)
681 int[] codonCounts = new int[66];
682 codonCounts[0] = alignment.getSequences().size();
683 int ungappedCount = 0;
684 for (SequenceI seq : alignment.getSequences())
686 if (seq.getCharAt(col) == gapCharacter)
690 List<char[]> codons = MappingUtils.findCodonsFor(seq, col,
692 for (char[] codon : codons)
694 int codonEncoded = CodingUtils.encodeCodon(codon);
695 if (codonEncoded >= 0)
697 codonCounts[codonEncoded + 2]++;
702 codonCounts[1] = ungappedCount;
703 // todo: sort values here, save counts and codons?
704 columnHash.put(PROFILE, codonCounts);
705 hconsensus[col] = columnHash;
710 * Derive displayable cDNA consensus annotation from computed consensus data.
712 * @param consensusAnnotation
713 * the annotation row to be populated for display
714 * @param consensusData
715 * the computed consensus data
716 * @param showProfileLogo
717 * if true show all symbols present at each position, else only the
720 * the number of sequences in the alignment
722 public static void completeCdnaConsensus(
723 AlignmentAnnotation consensusAnnotation,
724 Hashtable[] consensusData, boolean showProfileLogo, int nseqs)
726 if (consensusAnnotation == null
727 || consensusAnnotation.annotations == null
728 || consensusAnnotation.annotations.length < consensusData.length)
730 // called with a bad alignment annotation row - wait for it to be
731 // initialised properly
735 // ensure codon triplet scales with font size
736 consensusAnnotation.scaleColLabel = true;
737 for (int col = 0; col < consensusData.length; col++)
739 Hashtable hci = consensusData[col];
742 // gapped protein column?
745 // array holds #seqs, #ungapped, then codon counts indexed by codon
746 final int[] codonCounts = (int[]) hci.get(PROFILE);
750 * First pass - get total count and find the highest
752 final char[] codons = new char[codonCounts.length - 2];
753 for (int j = 2; j < codonCounts.length; j++)
755 final int codonCount = codonCounts[j];
756 codons[j - 2] = (char) (j - 2);
757 totalCount += codonCount;
761 * Sort array of encoded codons by count ascending - so the modal value
762 * goes to the end; start by copying the count (dropping the first value)
764 int[] sortedCodonCounts = new int[codonCounts.length - 2];
765 System.arraycopy(codonCounts, 2, sortedCodonCounts, 0,
766 codonCounts.length - 2);
767 QuickSort.sort(sortedCodonCounts, codons);
769 int modalCodonEncoded = codons[codons.length - 1];
770 int modalCodonCount = sortedCodonCounts[codons.length - 1];
771 String modalCodon = String
772 .valueOf(CodingUtils.decodeCodon(modalCodonEncoded));
773 if (sortedCodonCounts.length > 1 && sortedCodonCounts[codons.length
774 - 2] == sortedCodonCounts[codons.length - 1])
777 * two or more codons share the modal count
781 float pid = sortedCodonCounts[sortedCodonCounts.length - 1] * 100
782 / (float) totalCount;
785 * todo ? Replace consensus hashtable with sorted arrays of codons and
786 * counts (non-zero only). Include total count in count array [0].
790 * Scan sorted array backwards for most frequent values first. Show
791 * repeated values compactly.
793 StringBuilder mouseOver = new StringBuilder(32);
794 StringBuilder samePercent = new StringBuilder();
795 String percent = null;
796 String lastPercent = null;
797 int percentDecPl = getPercentageDp(nseqs);
799 for (int j = codons.length - 1; j >= 0; j--)
801 int codonCount = sortedCodonCounts[j];
805 * remaining codons are 0% - ignore, but finish off the last one if
808 if (samePercent.length() > 0)
810 mouseOver.append(samePercent).append(": ").append(percent)
815 int codonEncoded = codons[j];
816 final int pct = codonCount * 100 / totalCount;
817 String codon = String
818 .valueOf(CodingUtils.decodeCodon(codonEncoded));
819 StringBuilder sb = new StringBuilder();
820 Format.appendPercentage(sb, pct, percentDecPl);
821 percent = sb.toString();
822 if (showProfileLogo || codonCount == modalCodonCount)
824 if (percent.equals(lastPercent) && j > 0)
826 samePercent.append(samePercent.length() == 0 ? "" : ", ");
827 samePercent.append(codon);
831 if (samePercent.length() > 0)
833 mouseOver.append(samePercent).append(": ").append(lastPercent)
836 samePercent.setLength(0);
837 samePercent.append(codon);
839 lastPercent = percent;
843 consensusAnnotation.annotations[col] = new Annotation(modalCodon,
844 mouseOver.toString(), ' ', pid);
849 * Returns the number of decimal places to show for profile percentages. For
850 * less than 100 sequences, returns zero (the integer percentage value will be
851 * displayed). For 100-999 sequences, returns 1, for 1000-9999 returns 2, etc.
856 protected static int getPercentageDp(long nseq)
868 * Returns the information content at a specified column.
871 * Index of the column, starting from 0.
874 public static float getInformationContent(int column,
875 HiddenMarkovModel hmm)
877 float informationContent = 0f;
879 for (char symbol : hmm.getSymbols())
882 freq = ResidueProperties.backgroundFrequencies
883 .get(hmm.getAlphabetType()).get(symbol);
884 Double hmmProb = hmm.getMatchEmissionProbability(column, symbol);
885 float prob = hmmProb.floatValue();
886 informationContent += prob * (Math.log(prob / freq) / Math.log(2));
890 return informationContent;
894 * Produces a HMM profile for a column in an alignment
897 * Alignment annotation for which the profile is being calculated.
899 * Column in the alignment the profile is being made for.
900 * @param removeBelowBackground
901 * Boolean indicating whether to ignore residues with probabilities
902 * less than their background frequencies.
905 public static int[] extractHMMProfile(HiddenMarkovModel hmm, int column,
906 boolean removeBelowBackground, boolean infoHeight)
911 int size = hmm.getNumberOfSymbols();
912 char symbols[] = new char[size];
913 int values[] = new int[size];
914 List<Character> charList = hmm.getSymbols();
915 Integer totalCount = 0;
917 for (int i = 0; i < size; i++)
919 char symbol = charList.get(i);
921 int value = getAnalogueCount(hmm, column, symbol,
922 removeBelowBackground, infoHeight);
927 QuickSort.sort(values, symbols);
929 int[] profile = new int[3 + size * 2];
931 profile[0] = AlignmentAnnotation.SEQUENCE_PROFILE;
938 for (int k = size - 1; k >= 0; k--)
941 Integer value = values[k];
942 if (removeBelowBackground)
944 percentage = (value.floatValue() / totalCount.floatValue())
949 percentage = value.floatValue() / 100f;
951 int intPercent = Math.round(percentage);
952 profile[arrayPos] = symbols[k];
953 profile[arrayPos + 1] = intPercent;
963 * Converts the emission probability of a residue at a column in the alignment
964 * to a 'count' to allow for processing by the annotation renderer.
968 * @param removeBelowBackground
969 * When true, this method returns 0 for any symbols with a match
970 * emission probability less than the background frequency.
974 static int getAnalogueCount(HiddenMarkovModel hmm, int column,
975 char symbol, boolean removeBelowBackground, boolean infoHeight)
979 value = hmm.getMatchEmissionProbability(column, symbol);
982 freq = ResidueProperties.backgroundFrequencies
983 .get(hmm.getAlphabetType()).get(symbol);
984 if (value < freq && removeBelowBackground)
991 value = value * (Math.log(value / freq) / Math.log(2));
994 value = value * 10000;
995 return Math.round(value.floatValue());