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 char[] seq = sequences[row].getSequence();
165 if (seq.length > column)
167 char c = seq[column];
168 residueCounts.add(c);
169 if (Comparison.isNucleotide(c))
173 else if (!Comparison.isGap(c))
181 * count a gap if the sequence doesn't reach this column
183 residueCounts.addGap();
187 int maxCount = residueCounts.getModalCount();
188 String maxResidue = residueCounts.getResiduesForCount(maxCount);
189 int gapCount = residueCounts.getGapCount();
190 ProfileI profile = new Profile(seqCount, gapCount, maxCount,
195 profile.setCounts(residueCounts);
198 result[column] = profile;
200 return new Profiles(result);
201 // long elapsed = System.currentTimeMillis() - now;
202 // System.out.println(elapsed);
206 * Returns the full set of profiles for a hidden Markov model. The underlying
207 * data is the raw probabilities of a residue being emitted at each node,
208 * however the profiles returned by this function contain the percentage
209 * chance of a residue emission.
213 * The width of the Profile array (Profiles) to be returned.
215 * The alignment column on which the first profile is based.
217 * The alignment column on which the last profile is based.
218 * @param saveFullProfile
219 * Flag for saving the counts for each profile
220 * @param removeBelowBackground
221 * Flag for removing any characters with a match emission probability
222 * less than its background frequency
225 public static ProfilesI calculateHMMProfiles(final HiddenMarkovModel hmm,
226 int width, int start, int end, boolean saveFullProfile,
227 boolean removeBelowBackground, boolean infoLetterHeight)
229 ProfileI[] result = new ProfileI[width];
230 int symbolCount = hmm.getNumberOfSymbols();
231 for (int column = start; column < end; column++)
233 ResidueCount counts = new ResidueCount();
234 for (char symbol : hmm.getSymbols())
236 int value = getAnalogueCount(hmm, column, symbol,
237 removeBelowBackground, infoLetterHeight);
238 counts.put(symbol, value);
240 int maxCount = counts.getModalCount();
241 String maxResidue = counts.getResiduesForCount(maxCount);
242 int gapCount = counts.getGapCount();
243 ProfileI profile = new Profile(symbolCount, gapCount, maxCount,
248 profile.setCounts(counts);
251 result[column] = profile;
253 return new Profiles(result);
257 * Make an estimate of the profile size we are going to compute i.e. how many
258 * different characters may be present in it. Overestimating has a cost of
259 * using more memory than necessary. Underestimating has a cost of needing to
260 * extend the SparseIntArray holding the profile counts.
262 * @param profileSizes
263 * counts of sizes of profiles so far encountered
266 static int estimateProfileSize(SparseIntArray profileSizes)
268 if (profileSizes.size() == 0)
274 * could do a statistical heuristic here e.g. 75%ile
275 * for now just return the largest value
277 return profileSizes.keyAt(profileSizes.size() - 1);
281 * Derive the consensus annotations to be added to the alignment for display.
282 * This does not recompute the raw data, but may be called on a change in
283 * display options, such as 'ignore gaps', which may in turn result in a
284 * change in the derived values.
287 * the annotation row to add annotations to
289 * the source consensus data
291 * start column (inclusive)
293 * end column (exclusive)
295 * if true, normalise residue percentages ignoring gaps
296 * @param showSequenceLogo
297 * if true include all consensus symbols, else just show modal
300 * number of sequences
302 public static void completeConsensus(AlignmentAnnotation consensus,
303 ProfilesI profiles, int startCol, int endCol, boolean ignoreGaps,
304 boolean showSequenceLogo, long nseq)
306 // long now = System.currentTimeMillis();
307 if (consensus == null || consensus.annotations == null
308 || consensus.annotations.length < endCol)
311 * called with a bad alignment annotation row
312 * wait for it to be initialised properly
317 for (int i = startCol; i < endCol; i++)
319 ProfileI profile = profiles.get(i);
323 * happens if sequences calculated over were
324 * shorter than alignment width
326 consensus.annotations[i] = null;
330 final int dp = getPercentageDp(nseq);
332 float value = profile.getPercentageIdentity(ignoreGaps);
334 String description = getTooltip(profile, value, showSequenceLogo,
337 String modalResidue = profile.getModalResidue();
338 if ("".equals(modalResidue))
342 else if (modalResidue.length() > 1)
346 consensus.annotations[i] = new Annotation(modalResidue, description,
349 // long elapsed = System.currentTimeMillis() - now;
350 // System.out.println(-elapsed);
354 * Derive the information annotations to be added to the alignment for
355 * display. This does not recompute the raw data, but may be called on a
356 * change in display options, such as 'ignore below background frequency',
357 * which may in turn result in a change in the derived values.
360 * the annotation row to add annotations to
362 * the source information data
364 * start column (inclusive)
366 * end column (exclusive)
368 * if true, normalise residue percentages
369 * @param showSequenceLogo
370 * if true include all information symbols, else just show modal
373 * number of sequences
375 public static float completeInformation(AlignmentAnnotation information,
376 ProfilesI profiles, int startCol, int endCol, long nseq,
379 // long now = System.currentTimeMillis();
380 if (information == null || information.annotations == null
381 || information.annotations.length < endCol)
384 * called with a bad alignment annotation row
385 * wait for it to be initialised properly
392 for (int i = startCol; i < endCol; i++)
394 ProfileI profile = profiles.get(i);
398 * happens if sequences calculated over were
399 * shorter than alignment width
401 information.annotations[i] = null;
405 HiddenMarkovModel hmm;
407 SequenceI hmmSeq = information.sequenceRef;
409 hmm = hmmSeq.getHMM();
411 Float value = getInformationContent(i, hmm);
418 String description = value + " bits";
419 information.annotations[i] = new Annotation(
420 Character.toString(Character
421 .toUpperCase(hmm.getConsensusAtAlignColumn(i))),
422 description, ' ', value);
424 if (max > currentMax)
426 information.graphMax = max;
431 information.graphMax = currentMax;
437 * Derive the gap count annotation row.
440 * the annotation row to add annotations to
442 * the source consensus data
444 * start column (inclusive)
446 * end column (exclusive)
448 public static void completeGapAnnot(AlignmentAnnotation gaprow,
449 ProfilesI profiles, int startCol, int endCol, long nseq)
451 if (gaprow == null || gaprow.annotations == null
452 || gaprow.annotations.length < endCol)
455 * called with a bad alignment annotation row
456 * wait for it to be initialised properly
460 // always set ranges again
461 gaprow.graphMax = nseq;
463 double scale = 0.8 / nseq;
464 for (int i = startCol; i < endCol; i++)
466 ProfileI profile = profiles.get(i);
470 * happens if sequences calculated over were
471 * shorter than alignment width
473 gaprow.annotations[i] = null;
477 final int gapped = profile.getNonGapped();
479 String description = "" + gapped;
481 gaprow.annotations[i] = new Annotation("", description, '\0', gapped,
482 jalview.util.ColorUtils.bleachColour(Color.DARK_GRAY,
483 (float) scale * gapped));
488 * Returns a tooltip showing either
490 * <li>the full profile (percentages of all residues present), if
491 * showSequenceLogo is true, or</li>
492 * <li>just the modal (most common) residue(s), if showSequenceLogo is
495 * Percentages are as a fraction of all sequence, or only ungapped sequences
496 * if ignoreGaps is true.
500 * @param showSequenceLogo
503 * the number of decimal places to format percentages to
506 static String getTooltip(ProfileI profile, float pid,
507 boolean showSequenceLogo, boolean ignoreGaps, int dp)
509 ResidueCount counts = profile.getCounts();
511 String description = null;
512 if (counts != null && showSequenceLogo)
514 int normaliseBy = ignoreGaps ? profile.getNonGapped()
515 : profile.getHeight();
516 description = counts.getTooltip(normaliseBy, dp);
520 StringBuilder sb = new StringBuilder(64);
521 String maxRes = profile.getModalResidue();
522 if (maxRes.length() > 1)
524 sb.append("[").append(maxRes).append("]");
530 if (maxRes.length() > 0)
533 Format.appendPercentage(sb, pid, dp);
536 description = sb.toString();
542 * Returns the sorted profile for the given consensus data. The returned array
546 * [profileType, numberOfValues, nonGapCount, charValue1, percentage1, charValue2, percentage2, ...]
547 * in descending order of percentage value
551 * the data object from which to extract and sort values
553 * if true, only non-gapped values are included in percentage
557 public static int[] extractProfile(ProfileI profile, boolean ignoreGaps)
559 int[] rtnval = new int[64];
560 ResidueCount counts = profile.getCounts();
566 SymbolCounts symbolCounts = counts.getSymbolCounts();
567 char[] symbols = symbolCounts.symbols;
568 int[] values = symbolCounts.values;
569 QuickSort.sort(values, symbols);
570 int nextArrayPos = 2;
571 int totalPercentage = 0;
572 final int divisor = ignoreGaps ? profile.getNonGapped()
573 : profile.getHeight();
576 * traverse the arrays in reverse order (highest counts first)
578 for (int i = symbols.length - 1; i >= 0; i--)
580 int theChar = symbols[i];
581 int charCount = values[i];
583 rtnval[nextArrayPos++] = theChar;
584 final int percentage = (charCount * 100) / divisor;
585 rtnval[nextArrayPos++] = percentage;
586 totalPercentage += percentage;
588 rtnval[0] = symbols.length;
589 rtnval[1] = totalPercentage;
590 int[] result = new int[rtnval.length + 1];
591 result[0] = AlignmentAnnotation.SEQUENCE_PROFILE;
592 System.arraycopy(rtnval, 0, result, 1, rtnval.length);
599 * Extract a sorted extract of cDNA codon profile data. The returned array
603 * [profileType, numberOfValues, totalCount, charValue1, percentage1, charValue2, percentage2, ...]
604 * in descending order of percentage value, where the character values encode codon triplets
610 public static int[] extractCdnaProfile(Hashtable hashtable,
613 // this holds #seqs, #ungapped, and then codon count, indexed by encoded
615 int[] codonCounts = (int[]) hashtable.get(PROFILE);
616 int[] sortedCounts = new int[codonCounts.length - 2];
617 System.arraycopy(codonCounts, 2, sortedCounts, 0,
618 codonCounts.length - 2);
620 int[] result = new int[3 + 2 * sortedCounts.length];
621 // first value is just the type of profile data
622 result[0] = AlignmentAnnotation.CDNA_PROFILE;
624 char[] codons = new char[sortedCounts.length];
625 for (int i = 0; i < codons.length; i++)
627 codons[i] = (char) i;
629 QuickSort.sort(sortedCounts, codons);
630 int totalPercentage = 0;
631 int distinctValuesCount = 0;
633 int divisor = ignoreGaps ? codonCounts[1] : codonCounts[0];
634 for (int i = codons.length - 1; i >= 0; i--)
636 final int codonCount = sortedCounts[i];
639 break; // nothing else of interest here
641 distinctValuesCount++;
642 result[j++] = codons[i];
643 final int percentage = codonCount * 100 / divisor;
644 result[j++] = percentage;
645 totalPercentage += percentage;
647 result[2] = totalPercentage;
650 * Just return the non-zero values
652 // todo next value is redundant if we limit the array to non-zero counts
653 result[1] = distinctValuesCount;
654 return Arrays.copyOfRange(result, 0, j);
658 * Compute a consensus for the cDNA coding for a protein alignment.
661 * the protein alignment (which should hold mappings to cDNA
664 * the consensus data stores to be populated (one per column)
666 public static void calculateCdna(AlignmentI alignment,
667 Hashtable[] hconsensus)
669 final char gapCharacter = alignment.getGapCharacter();
670 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
671 if (mappings == null || mappings.isEmpty())
676 int cols = alignment.getWidth();
677 for (int col = 0; col < cols; col++)
679 // todo would prefer a Java bean for consensus data
680 Hashtable<String, int[]> columnHash = new Hashtable<>();
681 // #seqs, #ungapped seqs, counts indexed by (codon encoded + 1)
682 int[] codonCounts = new int[66];
683 codonCounts[0] = alignment.getSequences().size();
684 int ungappedCount = 0;
685 for (SequenceI seq : alignment.getSequences())
687 if (seq.getCharAt(col) == gapCharacter)
691 List<char[]> codons = MappingUtils.findCodonsFor(seq, col,
693 for (char[] codon : codons)
695 int codonEncoded = CodingUtils.encodeCodon(codon);
696 if (codonEncoded >= 0)
698 codonCounts[codonEncoded + 2]++;
703 codonCounts[1] = ungappedCount;
704 // todo: sort values here, save counts and codons?
705 columnHash.put(PROFILE, codonCounts);
706 hconsensus[col] = columnHash;
711 * Derive displayable cDNA consensus annotation from computed consensus data.
713 * @param consensusAnnotation
714 * the annotation row to be populated for display
715 * @param consensusData
716 * the computed consensus data
717 * @param showProfileLogo
718 * if true show all symbols present at each position, else only the
721 * the number of sequences in the alignment
723 public static void completeCdnaConsensus(
724 AlignmentAnnotation consensusAnnotation,
725 Hashtable[] consensusData, boolean showProfileLogo, int nseqs)
727 if (consensusAnnotation == null
728 || consensusAnnotation.annotations == null
729 || consensusAnnotation.annotations.length < consensusData.length)
731 // called with a bad alignment annotation row - wait for it to be
732 // initialised properly
736 // ensure codon triplet scales with font size
737 consensusAnnotation.scaleColLabel = true;
738 for (int col = 0; col < consensusData.length; col++)
740 Hashtable hci = consensusData[col];
743 // gapped protein column?
746 // array holds #seqs, #ungapped, then codon counts indexed by codon
747 final int[] codonCounts = (int[]) hci.get(PROFILE);
751 * First pass - get total count and find the highest
753 final char[] codons = new char[codonCounts.length - 2];
754 for (int j = 2; j < codonCounts.length; j++)
756 final int codonCount = codonCounts[j];
757 codons[j - 2] = (char) (j - 2);
758 totalCount += codonCount;
762 * Sort array of encoded codons by count ascending - so the modal value
763 * goes to the end; start by copying the count (dropping the first value)
765 int[] sortedCodonCounts = new int[codonCounts.length - 2];
766 System.arraycopy(codonCounts, 2, sortedCodonCounts, 0,
767 codonCounts.length - 2);
768 QuickSort.sort(sortedCodonCounts, codons);
770 int modalCodonEncoded = codons[codons.length - 1];
771 int modalCodonCount = sortedCodonCounts[codons.length - 1];
772 String modalCodon = String
773 .valueOf(CodingUtils.decodeCodon(modalCodonEncoded));
774 if (sortedCodonCounts.length > 1 && sortedCodonCounts[codons.length
775 - 2] == sortedCodonCounts[codons.length - 1])
778 * two or more codons share the modal count
782 float pid = sortedCodonCounts[sortedCodonCounts.length - 1] * 100
783 / (float) totalCount;
786 * todo ? Replace consensus hashtable with sorted arrays of codons and
787 * counts (non-zero only). Include total count in count array [0].
791 * Scan sorted array backwards for most frequent values first. Show
792 * repeated values compactly.
794 StringBuilder mouseOver = new StringBuilder(32);
795 StringBuilder samePercent = new StringBuilder();
796 String percent = null;
797 String lastPercent = null;
798 int percentDecPl = getPercentageDp(nseqs);
800 for (int j = codons.length - 1; j >= 0; j--)
802 int codonCount = sortedCodonCounts[j];
806 * remaining codons are 0% - ignore, but finish off the last one if
809 if (samePercent.length() > 0)
811 mouseOver.append(samePercent).append(": ").append(percent)
816 int codonEncoded = codons[j];
817 final int pct = codonCount * 100 / totalCount;
818 String codon = String
819 .valueOf(CodingUtils.decodeCodon(codonEncoded));
820 StringBuilder sb = new StringBuilder();
821 Format.appendPercentage(sb, pct, percentDecPl);
822 percent = sb.toString();
823 if (showProfileLogo || codonCount == modalCodonCount)
825 if (percent.equals(lastPercent) && j > 0)
827 samePercent.append(samePercent.length() == 0 ? "" : ", ");
828 samePercent.append(codon);
832 if (samePercent.length() > 0)
834 mouseOver.append(samePercent).append(": ").append(lastPercent)
837 samePercent.setLength(0);
838 samePercent.append(codon);
840 lastPercent = percent;
844 consensusAnnotation.annotations[col] = new Annotation(modalCodon,
845 mouseOver.toString(), ' ', pid);
850 * Returns the number of decimal places to show for profile percentages. For
851 * less than 100 sequences, returns zero (the integer percentage value will be
852 * displayed). For 100-999 sequences, returns 1, for 1000-9999 returns 2, etc.
857 protected static int getPercentageDp(long nseq)
869 * Returns the information content at a specified column.
872 * Index of the column, starting from 0.
875 public static float getInformationContent(int column,
876 HiddenMarkovModel hmm)
878 float informationContent = 0f;
880 for (char symbol : hmm.getSymbols())
883 freq = ResidueProperties.backgroundFrequencies
884 .get(hmm.getAlphabetType()).get(symbol);
885 Double hmmProb = hmm.getMatchEmissionProbability(column, symbol);
886 float prob = hmmProb.floatValue();
887 informationContent += prob * (Math.log(prob / freq) / Math.log(2));
891 return informationContent;
895 * Produces a HMM profile for a column in an alignment
898 * Alignment annotation for which the profile is being calculated.
900 * Column in the alignment the profile is being made for.
901 * @param removeBelowBackground
902 * Boolean indicating whether to ignore residues with probabilities
903 * less than their background frequencies.
906 public static int[] extractHMMProfile(HiddenMarkovModel hmm, int column,
907 boolean removeBelowBackground, boolean infoHeight)
912 int size = hmm.getNumberOfSymbols();
913 char symbols[] = new char[size];
914 int values[] = new int[size];
915 List<Character> charList = hmm.getSymbols();
916 Integer totalCount = 0;
918 for (int i = 0; i < size; i++)
920 char symbol = charList.get(i);
922 int value = getAnalogueCount(hmm, column, symbol,
923 removeBelowBackground, infoHeight);
928 QuickSort.sort(values, symbols);
930 int[] profile = new int[3 + size * 2];
932 profile[0] = AlignmentAnnotation.SEQUENCE_PROFILE;
939 for (int k = size - 1; k >= 0; k--)
942 Integer value = values[k];
943 if (removeBelowBackground)
945 percentage = (value.floatValue() / totalCount.floatValue())
950 percentage = value.floatValue() / 100f;
952 int intPercent = Math.round(percentage);
953 profile[arrayPos] = symbols[k];
954 profile[arrayPos + 1] = intPercent;
964 * Converts the emission probability of a residue at a column in the alignment
965 * to a 'count' to allow for processing by the annotation renderer.
969 * @param removeBelowBackground
970 * When true, this method returns 0 for any symbols with a match
971 * emission probability less than the background frequency.
975 static int getAnalogueCount(HiddenMarkovModel hmm, int column,
976 char symbol, boolean removeBelowBackground, boolean infoHeight)
980 value = hmm.getMatchEmissionProbability(column, symbol);
983 freq = ResidueProperties.backgroundFrequencies
984 .get(hmm.getAlphabetType()).get(symbol);
985 if (value < freq && removeBelowBackground)
992 value = value * (Math.log(value / freq) / Math.log(2));
995 value = value * 10000;
996 return Math.round(value.floatValue());