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 .println("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);
205 public static ProfilesI calculateInformation(final HiddenMarkovModel hmm,
206 int width, int start, int end, boolean saveFullProfile,
207 boolean removeBelowBackground)
209 ProfileI[] result = new ProfileI[width];
210 int symbolCount = hmm.getNumberOfSymbols();
211 String alph = hmm.getAlphabetType();
212 for (int column = start; column < end; column++)
214 ResidueCount counts = new ResidueCount();
215 for (char symbol : hmm.getSymbols())
217 int value = getAnalogueCount(hmm, column, removeBelowBackground,
219 counts.put(symbol, value);
221 int maxCount = counts.getModalCount();
222 String maxResidue = counts.getResiduesForCount(maxCount);
223 int gapCount = counts.getGapCount();
224 ProfileI profile = new Profile(symbolCount, gapCount, maxCount,
229 profile.setCounts(counts);
232 result[column] = profile;
234 return new Profiles(result);
238 * Make an estimate of the profile size we are going to compute i.e. how many
239 * different characters may be present in it. Overestimating has a cost of
240 * using more memory than necessary. Underestimating has a cost of needing to
241 * extend the SparseIntArray holding the profile counts.
243 * @param profileSizes
244 * counts of sizes of profiles so far encountered
247 static int estimateProfileSize(SparseIntArray profileSizes)
249 if (profileSizes.size() == 0)
255 * could do a statistical heuristic here e.g. 75%ile
256 * for now just return the largest value
258 return profileSizes.keyAt(profileSizes.size() - 1);
262 * Derive the consensus annotations to be added to the alignment for display.
263 * This does not recompute the raw data, but may be called on a change in
264 * display options, such as 'ignore gaps', which may in turn result in a
265 * change in the derived values.
268 * the annotation row to add annotations to
270 * the source consensus data
272 * start column (inclusive)
274 * end column (exclusive)
276 * if true, normalise residue percentages ignoring gaps
277 * @param showSequenceLogo
278 * if true include all consensus symbols, else just show modal
281 * number of sequences
283 public static void completeConsensus(AlignmentAnnotation consensus,
284 ProfilesI profiles, int startCol, int endCol, boolean ignoreGaps,
285 boolean showSequenceLogo, long nseq)
287 // long now = System.currentTimeMillis();
288 if (consensus == null || consensus.annotations == null
289 || consensus.annotations.length < endCol)
292 * called with a bad alignment annotation row
293 * wait for it to be initialised properly
298 for (int i = startCol; i < endCol; i++)
300 ProfileI profile = profiles.get(i);
304 * happens if sequences calculated over were
305 * shorter than alignment width
307 consensus.annotations[i] = null;
311 final int dp = getPercentageDp(nseq);
313 float value = profile.getPercentageIdentity(ignoreGaps);
315 String description = getTooltip(profile, value, showSequenceLogo,
318 String modalResidue = profile.getModalResidue();
319 if ("".equals(modalResidue))
323 else if (modalResidue.length() > 1)
327 consensus.annotations[i] = new Annotation(modalResidue, description,
330 // long elapsed = System.currentTimeMillis() - now;
331 // System.out.println(-elapsed);
335 * Derive the information annotations to be added to the alignment for
336 * display. This does not recompute the raw data, but may be called on a
337 * change in display options, such as 'ignore below background frequency',
338 * which may in turn result in a change in the derived values.
341 * the annotation row to add annotations to
343 * the source information data
345 * start column (inclusive)
347 * end column (exclusive)
349 * if true, normalise residue percentages
350 * @param showSequenceLogo
351 * if true include all information symbols, else just show modal
354 * number of sequences
356 public static void completeInformation(AlignmentAnnotation information,
357 ProfilesI profiles, int startCol, int endCol,
358 boolean ignoreBelowBackground,
359 boolean showSequenceLogo, long nseq)
361 // long now = System.currentTimeMillis();
362 if (information == null || information.annotations == null
363 || information.annotations.length < endCol)
366 * called with a bad alignment annotation row
367 * wait for it to be initialised properly
374 for (int i = startCol; i < endCol; i++)
376 ProfileI profile = profiles.get(i);
380 * happens if sequences calculated over were
381 * shorter than alignment width
383 information.annotations[i] = null;
387 HiddenMarkovModel hmm;
389 SequenceI hmmSeq = information.sequenceRef;
391 hmm = hmmSeq.getHMM();
393 Float value = getInformationContent(i, hmm);
400 String description = value + " bits";
402 information.annotations[i] = new Annotation(" ", description,
405 information.graphMax = max;
406 // long elapsed = System.currentTimeMillis() - now;
407 // System.out.println(-elapsed);
411 * Derive the gap count annotation row.
414 * the annotation row to add annotations to
416 * the source consensus data
418 * start column (inclusive)
420 * end column (exclusive)
422 public static void completeGapAnnot(AlignmentAnnotation gaprow,
423 ProfilesI profiles, int startCol, int endCol, long nseq)
425 if (gaprow == null || gaprow.annotations == null
426 || gaprow.annotations.length < endCol)
429 * called with a bad alignment annotation row
430 * wait for it to be initialised properly
434 // always set ranges again
435 gaprow.graphMax = nseq;
437 double scale = 0.8/nseq;
438 for (int i = startCol; i < endCol; i++)
440 ProfileI profile = profiles.get(i);
444 * happens if sequences calculated over were
445 * shorter than alignment width
447 gaprow.annotations[i] = null;
451 final int gapped = profile.getNonGapped();
453 String description = "" + gapped;
455 gaprow.annotations[i] = new Annotation("", description,
456 '\0', gapped, jalview.util.ColorUtils.bleachColour(
457 Color.DARK_GRAY, (float) scale * gapped));
462 * Returns a tooltip showing either
464 * <li>the full profile (percentages of all residues present), if
465 * showSequenceLogo is true, or</li>
466 * <li>just the modal (most common) residue(s), if showSequenceLogo is false</li>
468 * Percentages are as a fraction of all sequence, or only ungapped sequences
469 * if ignoreGaps is true.
473 * @param showSequenceLogo
476 * the number of decimal places to format percentages to
479 static String getTooltip(ProfileI profile, float pid,
480 boolean showSequenceLogo, boolean ignoreGaps, int dp)
482 ResidueCount counts = profile.getCounts();
484 String description = null;
485 if (counts != null && showSequenceLogo)
487 int normaliseBy = ignoreGaps ? profile.getNonGapped() : profile
489 description = counts.getTooltip(normaliseBy, dp);
493 StringBuilder sb = new StringBuilder(64);
494 String maxRes = profile.getModalResidue();
495 if (maxRes.length() > 1)
497 sb.append("[").append(maxRes).append("]");
503 if (maxRes.length() > 0)
506 Format.appendPercentage(sb, pid, dp);
509 description = sb.toString();
515 * Returns the sorted profile for the given consensus data. The returned array
519 * [profileType, numberOfValues, nonGapCount, charValue1, percentage1, charValue2, percentage2, ...]
520 * in descending order of percentage value
524 * the data object from which to extract and sort values
526 * if true, only non-gapped values are included in percentage
530 public static int[] extractProfile(ProfileI profile, boolean ignoreGaps)
532 int[] rtnval = new int[64];
533 ResidueCount counts = profile.getCounts();
539 SymbolCounts symbolCounts = counts.getSymbolCounts();
540 char[] symbols = symbolCounts.symbols;
541 int[] values = symbolCounts.values;
542 QuickSort.sort(values, symbols);
543 int nextArrayPos = 2;
544 int totalPercentage = 0;
545 final int divisor = ignoreGaps ? profile.getNonGapped() : profile
549 * traverse the arrays in reverse order (highest counts first)
551 for (int i = symbols.length - 1; i >= 0; i--)
553 int theChar = symbols[i];
554 int charCount = values[i];
556 rtnval[nextArrayPos++] = theChar;
557 final int percentage = (charCount * 100) / divisor;
558 rtnval[nextArrayPos++] = percentage;
559 totalPercentage += percentage;
561 rtnval[0] = symbols.length;
562 rtnval[1] = totalPercentage;
563 int[] result = new int[rtnval.length + 1];
564 result[0] = AlignmentAnnotation.SEQUENCE_PROFILE;
565 System.arraycopy(rtnval, 0, result, 1, rtnval.length);
572 * Extract a sorted extract of cDNA codon profile data. The returned array
576 * [profileType, numberOfValues, totalCount, charValue1, percentage1, charValue2, percentage2, ...]
577 * in descending order of percentage value, where the character values encode codon triplets
583 public static int[] extractCdnaProfile(Hashtable hashtable,
586 // this holds #seqs, #ungapped, and then codon count, indexed by encoded
588 int[] codonCounts = (int[]) hashtable.get(PROFILE);
589 int[] sortedCounts = new int[codonCounts.length - 2];
590 System.arraycopy(codonCounts, 2, sortedCounts, 0,
591 codonCounts.length - 2);
593 int[] result = new int[3 + 2 * sortedCounts.length];
594 // first value is just the type of profile data
595 result[0] = AlignmentAnnotation.CDNA_PROFILE;
597 char[] codons = new char[sortedCounts.length];
598 for (int i = 0; i < codons.length; i++)
600 codons[i] = (char) i;
602 QuickSort.sort(sortedCounts, codons);
603 int totalPercentage = 0;
604 int distinctValuesCount = 0;
606 int divisor = ignoreGaps ? codonCounts[1] : codonCounts[0];
607 for (int i = codons.length - 1; i >= 0; i--)
609 final int codonCount = sortedCounts[i];
612 break; // nothing else of interest here
614 distinctValuesCount++;
615 result[j++] = codons[i];
616 final int percentage = codonCount * 100 / divisor;
617 result[j++] = percentage;
618 totalPercentage += percentage;
620 result[2] = totalPercentage;
623 * Just return the non-zero values
625 // todo next value is redundant if we limit the array to non-zero counts
626 result[1] = distinctValuesCount;
627 return Arrays.copyOfRange(result, 0, j);
631 * Compute a consensus for the cDNA coding for a protein alignment.
634 * the protein alignment (which should hold mappings to cDNA
637 * the consensus data stores to be populated (one per column)
639 public static void calculateCdna(AlignmentI alignment,
640 Hashtable[] hconsensus)
642 final char gapCharacter = alignment.getGapCharacter();
643 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
644 if (mappings == null || mappings.isEmpty())
649 int cols = alignment.getWidth();
650 for (int col = 0; col < cols; col++)
652 // todo would prefer a Java bean for consensus data
653 Hashtable<String, int[]> columnHash = new Hashtable<>();
654 // #seqs, #ungapped seqs, counts indexed by (codon encoded + 1)
655 int[] codonCounts = new int[66];
656 codonCounts[0] = alignment.getSequences().size();
657 int ungappedCount = 0;
658 for (SequenceI seq : alignment.getSequences())
660 if (seq.getCharAt(col) == gapCharacter)
664 List<char[]> codons = MappingUtils
665 .findCodonsFor(seq, col, mappings);
666 for (char[] codon : codons)
668 int codonEncoded = CodingUtils.encodeCodon(codon);
669 if (codonEncoded >= 0)
671 codonCounts[codonEncoded + 2]++;
676 codonCounts[1] = ungappedCount;
677 // todo: sort values here, save counts and codons?
678 columnHash.put(PROFILE, codonCounts);
679 hconsensus[col] = columnHash;
684 * Derive displayable cDNA consensus annotation from computed consensus data.
686 * @param consensusAnnotation
687 * the annotation row to be populated for display
688 * @param consensusData
689 * the computed consensus data
690 * @param showProfileLogo
691 * if true show all symbols present at each position, else only the
694 * the number of sequences in the alignment
696 public static void completeCdnaConsensus(
697 AlignmentAnnotation consensusAnnotation,
698 Hashtable[] consensusData, boolean showProfileLogo, int nseqs)
700 if (consensusAnnotation == null
701 || consensusAnnotation.annotations == null
702 || consensusAnnotation.annotations.length < consensusData.length)
704 // called with a bad alignment annotation row - wait for it to be
705 // initialised properly
709 // ensure codon triplet scales with font size
710 consensusAnnotation.scaleColLabel = true;
711 for (int col = 0; col < consensusData.length; col++)
713 Hashtable hci = consensusData[col];
716 // gapped protein column?
719 // array holds #seqs, #ungapped, then codon counts indexed by codon
720 final int[] codonCounts = (int[]) hci.get(PROFILE);
724 * First pass - get total count and find the highest
726 final char[] codons = new char[codonCounts.length - 2];
727 for (int j = 2; j < codonCounts.length; j++)
729 final int codonCount = codonCounts[j];
730 codons[j - 2] = (char) (j - 2);
731 totalCount += codonCount;
735 * Sort array of encoded codons by count ascending - so the modal value
736 * goes to the end; start by copying the count (dropping the first value)
738 int[] sortedCodonCounts = new int[codonCounts.length - 2];
739 System.arraycopy(codonCounts, 2, sortedCodonCounts, 0,
740 codonCounts.length - 2);
741 QuickSort.sort(sortedCodonCounts, codons);
743 int modalCodonEncoded = codons[codons.length - 1];
744 int modalCodonCount = sortedCodonCounts[codons.length - 1];
745 String modalCodon = String.valueOf(CodingUtils
746 .decodeCodon(modalCodonEncoded));
747 if (sortedCodonCounts.length > 1
748 && sortedCodonCounts[codons.length - 2] == sortedCodonCounts[codons.length - 1])
751 * two or more codons share the modal count
755 float pid = sortedCodonCounts[sortedCodonCounts.length - 1] * 100
756 / (float) totalCount;
759 * todo ? Replace consensus hashtable with sorted arrays of codons and
760 * counts (non-zero only). Include total count in count array [0].
764 * Scan sorted array backwards for most frequent values first. Show
765 * repeated values compactly.
767 StringBuilder mouseOver = new StringBuilder(32);
768 StringBuilder samePercent = new StringBuilder();
769 String percent = null;
770 String lastPercent = null;
771 int percentDecPl = getPercentageDp(nseqs);
773 for (int j = codons.length - 1; j >= 0; j--)
775 int codonCount = sortedCodonCounts[j];
779 * remaining codons are 0% - ignore, but finish off the last one if
782 if (samePercent.length() > 0)
784 mouseOver.append(samePercent).append(": ").append(percent)
789 int codonEncoded = codons[j];
790 final int pct = codonCount * 100 / totalCount;
791 String codon = String
792 .valueOf(CodingUtils.decodeCodon(codonEncoded));
793 StringBuilder sb = new StringBuilder();
794 Format.appendPercentage(sb, pct, percentDecPl);
795 percent = sb.toString();
796 if (showProfileLogo || codonCount == modalCodonCount)
798 if (percent.equals(lastPercent) && j > 0)
800 samePercent.append(samePercent.length() == 0 ? "" : ", ");
801 samePercent.append(codon);
805 if (samePercent.length() > 0)
807 mouseOver.append(samePercent).append(": ")
808 .append(lastPercent).append("% ");
810 samePercent.setLength(0);
811 samePercent.append(codon);
813 lastPercent = percent;
817 consensusAnnotation.annotations[col] = new Annotation(modalCodon,
818 mouseOver.toString(), ' ', pid);
823 * Returns the number of decimal places to show for profile percentages. For
824 * less than 100 sequences, returns zero (the integer percentage value will be
825 * displayed). For 100-999 sequences, returns 1, for 1000-9999 returns 2, etc.
830 protected static int getPercentageDp(long nseq)
842 * Returns the information content at a specified column.
845 * Index of the column, starting from 0.
848 public static float getInformationContent(int column,
849 HiddenMarkovModel hmm)
851 float informationContent = 0f;
853 for (char symbol : hmm.getSymbols())
856 freq = ResidueProperties.backgroundFrequencies
857 .get(hmm.getAlphabetType()).get(symbol);
858 Double hmmProb = hmm.getMatchEmissionProbability(column, symbol);
859 float prob = hmmProb.floatValue();
860 informationContent += prob * (Math.log(prob / freq) / Math.log(2));
864 return informationContent;
868 * Produces a HMM profile for a column in an alignment
871 * Alignment annotation for which the profile is being calculated.
873 * Column in the alignment the profile is being made for.
874 * @param removeBelowBackground
875 * Boolean indicating whether to ignore residues with probabilities
876 * less than their background frequencies.
879 public static int[] extractHMMProfile(HiddenMarkovModel hmm, int column,
880 boolean removeBelowBackground)
885 String alph = hmm.getAlphabetType();
886 int size = hmm.getNumberOfSymbols();
887 char symbols[] = new char[size];
888 int values[] = new int[size];
889 List<Character> charList = hmm.getSymbols();
890 Integer totalCount = 0;
892 for (int i = 0; i < size; i++)
894 char symbol = charList.get(i);
896 int value = getAnalogueCount(hmm, column, removeBelowBackground,
902 QuickSort.sort(values, symbols);
904 int[] profile = new int[3 + size * 2];
906 profile[0] = AlignmentAnnotation.SEQUENCE_PROFILE;
913 for (int k = size - 1; k >= 0; k--)
916 Integer value = values[k];
917 if (removeBelowBackground)
919 percentage = (value.floatValue() / totalCount.floatValue())
924 percentage = value.floatValue() / 100f;
926 int intPercent = Math.round(percentage);
927 profile[arrayPos] = symbols[k];
928 profile[arrayPos + 1] = intPercent;
937 private static int getAnalogueCount(HiddenMarkovModel hmm, int column,
938 boolean removeBelowBackground, String alph, char symbol)
942 value = hmm.getMatchEmissionProbability(column, symbol);
945 freq = ResidueProperties.backgroundFrequencies.get(alph).get(symbol);
946 if (value < freq && removeBelowBackground)
951 value = value * 10000;
952 return Math.round(value.floatValue());