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 saveFullProfile
197 * Flag for saving the counts for each profile
198 * @param removeBelowBackground
199 * Flag for removing any characters with a match emission probability
200 * less than its background frequency
203 public static ProfilesI calculateHMMProfiles(final HiddenMarkovModel hmm,
204 int width, int start, int end, boolean saveFullProfile,
205 boolean removeBelowBackground, boolean infoLetterHeight)
207 ProfileI[] result = new ProfileI[width];
208 int symbolCount = hmm.getNumberOfSymbols();
209 for (int column = start; column < end; column++)
211 ResidueCount counts = new ResidueCount();
212 for (char symbol : hmm.getSymbols())
214 int value = getAnalogueCount(hmm, column, symbol,
215 removeBelowBackground, infoLetterHeight);
216 counts.put(symbol, value);
218 int maxCount = counts.getModalCount();
219 String maxResidue = counts.getResiduesForCount(maxCount);
220 int gapCount = counts.getGapCount();
221 ProfileI profile = new Profile(symbolCount, gapCount, maxCount,
226 profile.setCounts(counts);
229 result[column] = profile;
231 return new Profiles(result);
235 * Make an estimate of the profile size we are going to compute i.e. how many
236 * different characters may be present in it. Overestimating has a cost of
237 * using more memory than necessary. Underestimating has a cost of needing to
238 * extend the SparseIntArray holding the profile counts.
240 * @param profileSizes
241 * counts of sizes of profiles so far encountered
244 static int estimateProfileSize(SparseIntArray profileSizes)
246 if (profileSizes.size() == 0)
252 * could do a statistical heuristic here e.g. 75%ile
253 * for now just return the largest value
255 return profileSizes.keyAt(profileSizes.size() - 1);
259 * Derive the consensus annotations to be added to the alignment for display.
260 * This does not recompute the raw data, but may be called on a change in
261 * display options, such as 'ignore gaps', which may in turn result in a
262 * change in the derived values.
265 * the annotation row to add annotations to
267 * the source consensus data
269 * start column (inclusive)
271 * end column (exclusive)
273 * if true, normalise residue percentages ignoring gaps
274 * @param showSequenceLogo
275 * if true include all consensus symbols, else just show modal
278 * number of sequences
280 public static void completeConsensus(AlignmentAnnotation consensus,
281 ProfilesI profiles, int startCol, int endCol, boolean ignoreGaps,
282 boolean showSequenceLogo, long nseq)
284 // long now = System.currentTimeMillis();
285 if (consensus == null || consensus.annotations == null
286 || consensus.annotations.length < endCol)
289 * called with a bad alignment annotation row
290 * wait for it to be initialised properly
295 for (int i = startCol; i < endCol; i++)
297 ProfileI profile = profiles.get(i);
301 * happens if sequences calculated over were
302 * shorter than alignment width
304 consensus.annotations[i] = null;
308 final int dp = getPercentageDp(nseq);
310 float value = profile.getPercentageIdentity(ignoreGaps);
312 String description = getTooltip(profile, value, showSequenceLogo,
315 String modalResidue = profile.getModalResidue();
316 if ("".equals(modalResidue))
320 else if (modalResidue.length() > 1)
324 consensus.annotations[i] = new Annotation(modalResidue, description,
327 // long elapsed = System.currentTimeMillis() - now;
328 // System.out.println(-elapsed);
332 * Derive the information annotations to be added to the alignment for
333 * display. This does not recompute the raw data, but may be called on a
334 * change in display options, such as 'ignore below background frequency',
335 * which may in turn result in a change in the derived values.
338 * the annotation row to add annotations to
340 * the source information data
342 * start column (inclusive)
344 * end column (exclusive)
346 * if true, normalise residue percentages
347 * @param showSequenceLogo
348 * if true include all information symbols, else just show modal
351 * number of sequences
353 public static float completeInformation(AlignmentAnnotation information,
354 ProfilesI profiles, int startCol, int endCol, long nseq,
357 // long now = System.currentTimeMillis();
358 if (information == null || information.annotations == null
359 || information.annotations.length < endCol)
362 * called with a bad alignment annotation row
363 * wait for it to be initialised properly
370 for (int i = startCol; i < endCol; i++)
372 ProfileI profile = profiles.get(i);
376 * happens if sequences calculated over were
377 * shorter than alignment width
379 information.annotations[i] = null;
383 SequenceI hmmSeq = information.sequenceRef;
385 HiddenMarkovModel hmm = hmmSeq.getHMM();
387 float value = hmm.getInformationContent(i);
394 String description = value + " bits";
395 information.annotations[i] = new Annotation(
396 Character.toString(Character
397 .toUpperCase(hmm.getConsensusAtAlignColumn(i))),
398 description, ' ', value);
400 if (max > currentMax)
402 information.graphMax = max;
407 information.graphMax = currentMax;
413 * Derive the gap count annotation row.
416 * the annotation row to add annotations to
418 * the source consensus data
420 * start column (inclusive)
422 * end column (exclusive)
424 public static void completeGapAnnot(AlignmentAnnotation gaprow,
425 ProfilesI profiles, int startCol, int endCol, long nseq)
427 if (gaprow == null || gaprow.annotations == null
428 || gaprow.annotations.length < endCol)
431 * called with a bad alignment annotation row
432 * wait for it to be initialised properly
436 // always set ranges again
437 gaprow.graphMax = nseq;
439 double scale = 0.8 / nseq;
440 for (int i = startCol; i < endCol; i++)
442 ProfileI profile = profiles.get(i);
446 * happens if sequences calculated over were
447 * shorter than alignment width
449 gaprow.annotations[i] = null;
453 final int gapped = profile.getNonGapped();
455 String description = "" + gapped;
457 gaprow.annotations[i] = new Annotation("", description, '\0', gapped,
458 jalview.util.ColorUtils.bleachColour(Color.DARK_GRAY,
459 (float) scale * gapped));
464 * Returns a tooltip showing either
466 * <li>the full profile (percentages of all residues present), if
467 * showSequenceLogo is true, or</li>
468 * <li>just the modal (most common) residue(s), if showSequenceLogo is
471 * Percentages are as a fraction of all sequence, or only ungapped sequences
472 * if ignoreGaps is true.
476 * @param showSequenceLogo
479 * the number of decimal places to format percentages to
482 static String getTooltip(ProfileI profile, float pid,
483 boolean showSequenceLogo, boolean ignoreGaps, int dp)
485 ResidueCount counts = profile.getCounts();
487 String description = null;
488 if (counts != null && showSequenceLogo)
490 int normaliseBy = ignoreGaps ? profile.getNonGapped()
491 : profile.getHeight();
492 description = counts.getTooltip(normaliseBy, dp);
496 StringBuilder sb = new StringBuilder(64);
497 String maxRes = profile.getModalResidue();
498 if (maxRes.length() > 1)
500 sb.append("[").append(maxRes).append("]");
506 if (maxRes.length() > 0)
509 Format.appendPercentage(sb, pid, dp);
512 description = sb.toString();
518 * Returns the sorted profile for the given consensus data. The returned array
522 * [profileType, numberOfValues, nonGapCount, charValue1, percentage1, charValue2, percentage2, ...]
523 * in descending order of percentage value
527 * the data object from which to extract and sort values
529 * if true, only non-gapped values are included in percentage
533 public static int[] extractProfile(ProfileI profile, boolean ignoreGaps)
535 int[] rtnval = new int[64];
536 ResidueCount counts = profile.getCounts();
542 SymbolCounts symbolCounts = counts.getSymbolCounts();
543 char[] symbols = symbolCounts.symbols;
544 int[] values = symbolCounts.values;
545 QuickSort.sort(values, symbols);
546 int nextArrayPos = 2;
547 int totalPercentage = 0;
548 final int divisor = ignoreGaps ? profile.getNonGapped()
549 : profile.getHeight();
552 * traverse the arrays in reverse order (highest counts first)
554 for (int i = symbols.length - 1; i >= 0; i--)
556 int theChar = symbols[i];
557 int charCount = values[i];
559 rtnval[nextArrayPos++] = theChar;
560 final int percentage = (charCount * 100) / divisor;
561 rtnval[nextArrayPos++] = percentage;
562 totalPercentage += percentage;
564 rtnval[0] = symbols.length;
565 rtnval[1] = totalPercentage;
566 int[] result = new int[rtnval.length + 1];
567 result[0] = AlignmentAnnotation.SEQUENCE_PROFILE;
568 System.arraycopy(rtnval, 0, result, 1, rtnval.length);
575 * Extract a sorted extract of cDNA codon profile data. The returned array
579 * [profileType, numberOfValues, totalCount, charValue1, percentage1, charValue2, percentage2, ...]
580 * in descending order of percentage value, where the character values encode codon triplets
586 public static int[] extractCdnaProfile(Hashtable hashtable,
589 // this holds #seqs, #ungapped, and then codon count, indexed by encoded
591 int[] codonCounts = (int[]) hashtable.get(PROFILE);
592 int[] sortedCounts = new int[codonCounts.length - 2];
593 System.arraycopy(codonCounts, 2, sortedCounts, 0,
594 codonCounts.length - 2);
596 int[] result = new int[3 + 2 * sortedCounts.length];
597 // first value is just the type of profile data
598 result[0] = AlignmentAnnotation.CDNA_PROFILE;
600 char[] codons = new char[sortedCounts.length];
601 for (int i = 0; i < codons.length; i++)
603 codons[i] = (char) i;
605 QuickSort.sort(sortedCounts, codons);
606 int totalPercentage = 0;
607 int distinctValuesCount = 0;
609 int divisor = ignoreGaps ? codonCounts[1] : codonCounts[0];
610 for (int i = codons.length - 1; i >= 0; i--)
612 final int codonCount = sortedCounts[i];
615 break; // nothing else of interest here
617 distinctValuesCount++;
618 result[j++] = codons[i];
619 final int percentage = codonCount * 100 / divisor;
620 result[j++] = percentage;
621 totalPercentage += percentage;
623 result[2] = totalPercentage;
626 * Just return the non-zero values
628 // todo next value is redundant if we limit the array to non-zero counts
629 result[1] = distinctValuesCount;
630 return Arrays.copyOfRange(result, 0, j);
634 * Compute a consensus for the cDNA coding for a protein alignment.
637 * the protein alignment (which should hold mappings to cDNA
640 * the consensus data stores to be populated (one per column)
642 public static void calculateCdna(AlignmentI alignment,
643 Hashtable[] hconsensus)
645 final char gapCharacter = alignment.getGapCharacter();
646 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
647 if (mappings == null || mappings.isEmpty())
652 int cols = alignment.getWidth();
653 for (int col = 0; col < cols; col++)
655 // todo would prefer a Java bean for consensus data
656 Hashtable<String, int[]> columnHash = new Hashtable<>();
657 // #seqs, #ungapped seqs, counts indexed by (codon encoded + 1)
658 int[] codonCounts = new int[66];
659 codonCounts[0] = alignment.getSequences().size();
660 int ungappedCount = 0;
661 for (SequenceI seq : alignment.getSequences())
663 if (seq.getCharAt(col) == gapCharacter)
667 List<char[]> codons = MappingUtils.findCodonsFor(seq, col,
669 for (char[] codon : codons)
671 int codonEncoded = CodingUtils.encodeCodon(codon);
672 if (codonEncoded >= 0)
674 codonCounts[codonEncoded + 2]++;
679 codonCounts[1] = ungappedCount;
680 // todo: sort values here, save counts and codons?
681 columnHash.put(PROFILE, codonCounts);
682 hconsensus[col] = columnHash;
687 * Derive displayable cDNA consensus annotation from computed consensus data.
689 * @param consensusAnnotation
690 * the annotation row to be populated for display
691 * @param consensusData
692 * the computed consensus data
693 * @param showProfileLogo
694 * if true show all symbols present at each position, else only the
697 * the number of sequences in the alignment
699 public static void completeCdnaConsensus(
700 AlignmentAnnotation consensusAnnotation,
701 Hashtable[] consensusData, boolean showProfileLogo, int nseqs)
703 if (consensusAnnotation == null
704 || consensusAnnotation.annotations == null
705 || consensusAnnotation.annotations.length < consensusData.length)
707 // called with a bad alignment annotation row - wait for it to be
708 // initialised properly
712 // ensure codon triplet scales with font size
713 consensusAnnotation.scaleColLabel = true;
714 for (int col = 0; col < consensusData.length; col++)
716 Hashtable hci = consensusData[col];
719 // gapped protein column?
722 // array holds #seqs, #ungapped, then codon counts indexed by codon
723 final int[] codonCounts = (int[]) hci.get(PROFILE);
727 * First pass - get total count and find the highest
729 final char[] codons = new char[codonCounts.length - 2];
730 for (int j = 2; j < codonCounts.length; j++)
732 final int codonCount = codonCounts[j];
733 codons[j - 2] = (char) (j - 2);
734 totalCount += codonCount;
738 * Sort array of encoded codons by count ascending - so the modal value
739 * goes to the end; start by copying the count (dropping the first value)
741 int[] sortedCodonCounts = new int[codonCounts.length - 2];
742 System.arraycopy(codonCounts, 2, sortedCodonCounts, 0,
743 codonCounts.length - 2);
744 QuickSort.sort(sortedCodonCounts, codons);
746 int modalCodonEncoded = codons[codons.length - 1];
747 int modalCodonCount = sortedCodonCounts[codons.length - 1];
748 String modalCodon = String
749 .valueOf(CodingUtils.decodeCodon(modalCodonEncoded));
750 if (sortedCodonCounts.length > 1 && sortedCodonCounts[codons.length
751 - 2] == sortedCodonCounts[codons.length - 1])
754 * two or more codons share the modal count
758 float pid = sortedCodonCounts[sortedCodonCounts.length - 1] * 100
759 / (float) totalCount;
762 * todo ? Replace consensus hashtable with sorted arrays of codons and
763 * counts (non-zero only). Include total count in count array [0].
767 * Scan sorted array backwards for most frequent values first. Show
768 * repeated values compactly.
770 StringBuilder mouseOver = new StringBuilder(32);
771 StringBuilder samePercent = new StringBuilder();
772 String percent = null;
773 String lastPercent = null;
774 int percentDecPl = getPercentageDp(nseqs);
776 for (int j = codons.length - 1; j >= 0; j--)
778 int codonCount = sortedCodonCounts[j];
782 * remaining codons are 0% - ignore, but finish off the last one if
785 if (samePercent.length() > 0)
787 mouseOver.append(samePercent).append(": ").append(percent)
792 int codonEncoded = codons[j];
793 final int pct = codonCount * 100 / totalCount;
794 String codon = String
795 .valueOf(CodingUtils.decodeCodon(codonEncoded));
796 StringBuilder sb = new StringBuilder();
797 Format.appendPercentage(sb, pct, percentDecPl);
798 percent = sb.toString();
799 if (showProfileLogo || codonCount == modalCodonCount)
801 if (percent.equals(lastPercent) && j > 0)
803 samePercent.append(samePercent.length() == 0 ? "" : ", ");
804 samePercent.append(codon);
808 if (samePercent.length() > 0)
810 mouseOver.append(samePercent).append(": ").append(lastPercent)
813 samePercent.setLength(0);
814 samePercent.append(codon);
816 lastPercent = percent;
820 consensusAnnotation.annotations[col] = new Annotation(modalCodon,
821 mouseOver.toString(), ' ', pid);
826 * Returns the number of decimal places to show for profile percentages. For
827 * less than 100 sequences, returns zero (the integer percentage value will be
828 * displayed). For 100-999 sequences, returns 1, for 1000-9999 returns 2, etc.
833 protected static int getPercentageDp(long nseq)
845 * Returns the sorted HMM profile for the given column of the alignment. The
846 * returned array contains
849 * [profileType=0, numberOfValues, 100, charValue1, percentage1, charValue2, percentage2, ...]
850 * in descending order of percentage value
855 * @param removeBelowBackground
856 * if true, ignores residues with probability less than their
857 * background frequency
859 * if true, uses the log ratio 'information' measure to scale the
863 public static int[] extractHMMProfile(HiddenMarkovModel hmm, int column,
864 boolean removeBelowBackground, boolean infoHeight)
870 int size = hmm.getNumberOfSymbols();
871 char symbols[] = new char[size];
872 int values[] = new int[size];
873 List<Character> charList = hmm.getSymbols();
876 for (int i = 0; i < size; i++)
878 char symbol = charList.get(i);
880 int value = getAnalogueCount(hmm, column, symbol,
881 removeBelowBackground, infoHeight);
887 * sort symbols by increasing emission probability
889 QuickSort.sort(values, symbols);
891 int[] profile = new int[3 + size * 2];
893 profile[0] = AlignmentAnnotation.SEQUENCE_PROFILE;
898 * order symbol/count profile by decreasing emission probability
903 for (int k = size - 1; k >= 0; k--)
906 int value = values[k];
907 if (removeBelowBackground)
909 percentage = ((float) value) / totalCount * 100f;
913 percentage = value / 100f;
915 int intPercent = Math.round(percentage);
916 profile[arrayPos] = symbols[k];
917 profile[arrayPos + 1] = intPercent;
925 * Converts the emission probability of a residue at a column in the alignment
926 * to a 'count', suitable for rendering as an annotation value
931 * @param removeBelowBackground
932 * if true, returns 0 for any symbol with a match emission
933 * probability less than the background frequency
934 * @infoHeight if true, uses the log ratio 'information content' to scale the
938 static int getAnalogueCount(HiddenMarkovModel hmm, int column,
939 char symbol, boolean removeBelowBackground, boolean infoHeight)
941 double value = hmm.getMatchEmissionProbability(column, symbol);
942 double freq = ResidueProperties.backgroundFrequencies
943 .get(hmm.getAlphabetType()).get(symbol);
944 if (value < freq && removeBelowBackground)
951 value = value * (Math.log(value / freq) / LOG2);
954 value = value * 10000d;
955 return Math.round((float) value);