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);
114 * Calculate the consensus symbol(s) for each column in the given range.
118 * the full width of the alignment
120 * start column (inclusive, base zero)
122 * end column (exclusive)
123 * @param saveFullProfile
124 * if true, store all symbol counts
126 public static final ProfilesI calculate(final SequenceI[] sequences,
127 int width, int start, int end, boolean saveFullProfile)
129 // long now = System.currentTimeMillis();
130 int seqCount = sequences.length;
131 boolean nucleotide = false;
132 int nucleotideCount = 0;
133 int peptideCount = 0;
135 ProfileI[] result = new ProfileI[width];
137 for (int column = start; column < end; column++)
140 * Apply a heuristic to detect nucleotide data (which can
141 * be counted in more compact arrays); here we test for
142 * more than 90% nucleotide; recheck every 10 columns in case
143 * of misleading data e.g. highly conserved Alanine in peptide!
144 * Mistakenly guessing nucleotide has a small performance cost,
145 * as it will result in counting in sparse arrays.
146 * Mistakenly guessing peptide has a small space cost,
147 * as it will use a larger than necessary array to hold counts.
149 if (nucleotideCount > 100 && column % 10 == 0)
151 nucleotide = (9 * peptideCount < nucleotideCount);
153 ResidueCount residueCounts = new ResidueCount(nucleotide);
155 for (int row = 0; row < seqCount; row++)
157 if (sequences[row] == null)
160 .println("WARNING: Consensus skipping null sequence - possible race condition.");
163 char[] seq = sequences[row].getSequence();
164 if (seq.length > column)
166 char c = seq[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 * Make an estimate of the profile size we are going to compute i.e. how many
206 * different characters may be present in it. Overestimating has a cost of
207 * using more memory than necessary. Underestimating has a cost of needing to
208 * extend the SparseIntArray holding the profile counts.
210 * @param profileSizes
211 * counts of sizes of profiles so far encountered
214 static int estimateProfileSize(SparseIntArray profileSizes)
216 if (profileSizes.size() == 0)
222 * could do a statistical heuristic here e.g. 75%ile
223 * for now just return the largest value
225 return profileSizes.keyAt(profileSizes.size() - 1);
229 * Derive the consensus annotations to be added to the alignment for display.
230 * This does not recompute the raw data, but may be called on a change in
231 * display options, such as 'ignore gaps', which may in turn result in a
232 * change in the derived values.
235 * the annotation row to add annotations to
237 * the source consensus data
239 * start column (inclusive)
241 * end column (exclusive)
243 * if true, normalise residue percentages ignoring gaps
244 * @param showSequenceLogo
245 * if true include all consensus symbols, else just show modal
248 * number of sequences
250 public static void completeConsensus(AlignmentAnnotation consensus,
251 ProfilesI profiles, int startCol, int endCol, boolean ignoreGaps,
252 boolean showSequenceLogo, long nseq)
254 // long now = System.currentTimeMillis();
255 if (consensus == null || consensus.annotations == null
256 || consensus.annotations.length < endCol)
259 * called with a bad alignment annotation row
260 * wait for it to be initialised properly
265 for (int i = startCol; i < endCol; i++)
267 ProfileI profile = profiles.get(i);
271 * happens if sequences calculated over were
272 * shorter than alignment width
274 consensus.annotations[i] = null;
278 final int dp = getPercentageDp(nseq);
280 float value = profile.getPercentageIdentity(ignoreGaps);
282 String description = getTooltip(profile, value, showSequenceLogo,
285 String modalResidue = profile.getModalResidue();
286 if ("".equals(modalResidue))
290 else if (modalResidue.length() > 1)
294 consensus.annotations[i] = new Annotation(modalResidue, description,
297 // long elapsed = System.currentTimeMillis() - now;
298 // System.out.println(-elapsed);
302 * Derive the gap count annotation row.
305 * the annotation row to add annotations to
307 * the source consensus data
309 * start column (inclusive)
311 * end column (exclusive)
313 public static void completeGapAnnot(AlignmentAnnotation gaprow,
314 ProfilesI profiles, int startCol, int endCol, long nseq)
316 if (gaprow == null || gaprow.annotations == null
317 || gaprow.annotations.length < endCol)
320 * called with a bad alignment annotation row
321 * wait for it to be initialised properly
325 // always set ranges again
326 gaprow.graphMax = nseq;
328 double scale = 0.8/nseq;
329 for (int i = startCol; i < endCol; i++)
331 ProfileI profile = profiles.get(i);
335 * happens if sequences calculated over were
336 * shorter than alignment width
338 gaprow.annotations[i] = null;
342 final int gapped = profile.getNonGapped();
344 String description = "" + gapped;
346 gaprow.annotations[i] = new Annotation("", description,
347 '\0', gapped, jalview.util.ColorUtils.bleachColour(
348 Color.DARK_GRAY, (float) scale * gapped));
353 * Returns a tooltip showing either
355 * <li>the full profile (percentages of all residues present), if
356 * showSequenceLogo is true, or</li>
357 * <li>just the modal (most common) residue(s), if showSequenceLogo is false</li>
359 * Percentages are as a fraction of all sequence, or only ungapped sequences
360 * if ignoreGaps is true.
364 * @param showSequenceLogo
367 * the number of decimal places to format percentages to
370 static String getTooltip(ProfileI profile, float pid,
371 boolean showSequenceLogo, boolean ignoreGaps, int dp)
373 ResidueCount counts = profile.getCounts();
375 String description = null;
376 if (counts != null && showSequenceLogo)
378 int normaliseBy = ignoreGaps ? profile.getNonGapped() : profile
380 description = counts.getTooltip(normaliseBy, dp);
384 StringBuilder sb = new StringBuilder(64);
385 String maxRes = profile.getModalResidue();
386 if (maxRes.length() > 1)
388 sb.append("[").append(maxRes).append("]");
394 if (maxRes.length() > 0)
397 Format.appendPercentage(sb, pid, dp);
400 description = sb.toString();
406 * Returns the sorted profile for the given consensus data. The returned array
410 * [profileType, numberOfValues, nonGapCount, charValue1, percentage1, charValue2, percentage2, ...]
411 * in descending order of percentage value
415 * the data object from which to extract and sort values
417 * if true, only non-gapped values are included in percentage
421 public static int[] extractProfile(ProfileI profile, boolean ignoreGaps)
423 int[] rtnval = new int[64];
424 ResidueCount counts = profile.getCounts();
430 SymbolCounts symbolCounts = counts.getSymbolCounts();
431 char[] symbols = symbolCounts.symbols;
432 int[] values = symbolCounts.values;
433 QuickSort.sort(values, symbols);
434 int nextArrayPos = 2;
435 int totalPercentage = 0;
436 final int divisor = ignoreGaps ? profile.getNonGapped() : profile
440 * traverse the arrays in reverse order (highest counts first)
442 for (int i = symbols.length - 1; i >= 0; i--)
444 int theChar = symbols[i];
445 int charCount = values[i];
447 rtnval[nextArrayPos++] = theChar;
448 final int percentage = (charCount * 100) / divisor;
449 rtnval[nextArrayPos++] = percentage;
450 totalPercentage += percentage;
452 rtnval[0] = symbols.length;
453 rtnval[1] = totalPercentage;
454 int[] result = new int[rtnval.length + 1];
455 result[0] = AlignmentAnnotation.SEQUENCE_PROFILE;
456 System.arraycopy(rtnval, 0, result, 1, rtnval.length);
463 * Extract a sorted extract of cDNA codon profile data. The returned array
467 * [profileType, numberOfValues, totalCount, charValue1, percentage1, charValue2, percentage2, ...]
468 * in descending order of percentage value, where the character values encode codon triplets
474 public static int[] extractCdnaProfile(Hashtable hashtable,
477 // this holds #seqs, #ungapped, and then codon count, indexed by encoded
479 int[] codonCounts = (int[]) hashtable.get(PROFILE);
480 int[] sortedCounts = new int[codonCounts.length - 2];
481 System.arraycopy(codonCounts, 2, sortedCounts, 0,
482 codonCounts.length - 2);
484 int[] result = new int[3 + 2 * sortedCounts.length];
485 // first value is just the type of profile data
486 result[0] = AlignmentAnnotation.CDNA_PROFILE;
488 char[] codons = new char[sortedCounts.length];
489 for (int i = 0; i < codons.length; i++)
491 codons[i] = (char) i;
493 QuickSort.sort(sortedCounts, codons);
494 int totalPercentage = 0;
495 int distinctValuesCount = 0;
497 int divisor = ignoreGaps ? codonCounts[1] : codonCounts[0];
498 for (int i = codons.length - 1; i >= 0; i--)
500 final int codonCount = sortedCounts[i];
503 break; // nothing else of interest here
505 distinctValuesCount++;
506 result[j++] = codons[i];
507 final int percentage = codonCount * 100 / divisor;
508 result[j++] = percentage;
509 totalPercentage += percentage;
511 result[2] = totalPercentage;
514 * Just return the non-zero values
516 // todo next value is redundant if we limit the array to non-zero counts
517 result[1] = distinctValuesCount;
518 return Arrays.copyOfRange(result, 0, j);
522 * Compute a consensus for the cDNA coding for a protein alignment.
525 * the protein alignment (which should hold mappings to cDNA
528 * the consensus data stores to be populated (one per column)
530 public static void calculateCdna(AlignmentI alignment,
531 Hashtable[] hconsensus)
533 final char gapCharacter = alignment.getGapCharacter();
534 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
535 if (mappings == null || mappings.isEmpty())
540 int cols = alignment.getWidth();
541 for (int col = 0; col < cols; col++)
543 // todo would prefer a Java bean for consensus data
544 Hashtable<String, int[]> columnHash = new Hashtable<>();
545 // #seqs, #ungapped seqs, counts indexed by (codon encoded + 1)
546 int[] codonCounts = new int[66];
547 codonCounts[0] = alignment.getSequences().size();
548 int ungappedCount = 0;
549 for (SequenceI seq : alignment.getSequences())
551 if (seq.getCharAt(col) == gapCharacter)
555 List<char[]> codons = MappingUtils
556 .findCodonsFor(seq, col, mappings);
557 for (char[] codon : codons)
559 int codonEncoded = CodingUtils.encodeCodon(codon);
560 if (codonEncoded >= 0)
562 codonCounts[codonEncoded + 2]++;
567 codonCounts[1] = ungappedCount;
568 // todo: sort values here, save counts and codons?
569 columnHash.put(PROFILE, codonCounts);
570 hconsensus[col] = columnHash;
575 * Derive displayable cDNA consensus annotation from computed consensus data.
577 * @param consensusAnnotation
578 * the annotation row to be populated for display
579 * @param consensusData
580 * the computed consensus data
581 * @param showProfileLogo
582 * if true show all symbols present at each position, else only the
585 * the number of sequences in the alignment
587 public static void completeCdnaConsensus(
588 AlignmentAnnotation consensusAnnotation,
589 Hashtable[] consensusData, boolean showProfileLogo, int nseqs)
591 if (consensusAnnotation == null
592 || consensusAnnotation.annotations == null
593 || consensusAnnotation.annotations.length < consensusData.length)
595 // called with a bad alignment annotation row - wait for it to be
596 // initialised properly
600 // ensure codon triplet scales with font size
601 consensusAnnotation.scaleColLabel = true;
602 for (int col = 0; col < consensusData.length; col++)
604 Hashtable hci = consensusData[col];
607 // gapped protein column?
610 // array holds #seqs, #ungapped, then codon counts indexed by codon
611 final int[] codonCounts = (int[]) hci.get(PROFILE);
615 * First pass - get total count and find the highest
617 final char[] codons = new char[codonCounts.length - 2];
618 for (int j = 2; j < codonCounts.length; j++)
620 final int codonCount = codonCounts[j];
621 codons[j - 2] = (char) (j - 2);
622 totalCount += codonCount;
626 * Sort array of encoded codons by count ascending - so the modal value
627 * goes to the end; start by copying the count (dropping the first value)
629 int[] sortedCodonCounts = new int[codonCounts.length - 2];
630 System.arraycopy(codonCounts, 2, sortedCodonCounts, 0,
631 codonCounts.length - 2);
632 QuickSort.sort(sortedCodonCounts, codons);
634 int modalCodonEncoded = codons[codons.length - 1];
635 int modalCodonCount = sortedCodonCounts[codons.length - 1];
636 String modalCodon = String.valueOf(CodingUtils
637 .decodeCodon(modalCodonEncoded));
638 if (sortedCodonCounts.length > 1
639 && sortedCodonCounts[codons.length - 2] == sortedCodonCounts[codons.length - 1])
642 * two or more codons share the modal count
646 float pid = sortedCodonCounts[sortedCodonCounts.length - 1] * 100
647 / (float) totalCount;
650 * todo ? Replace consensus hashtable with sorted arrays of codons and
651 * counts (non-zero only). Include total count in count array [0].
655 * Scan sorted array backwards for most frequent values first. Show
656 * repeated values compactly.
658 StringBuilder mouseOver = new StringBuilder(32);
659 StringBuilder samePercent = new StringBuilder();
660 String percent = null;
661 String lastPercent = null;
662 int percentDecPl = getPercentageDp(nseqs);
664 for (int j = codons.length - 1; j >= 0; j--)
666 int codonCount = sortedCodonCounts[j];
670 * remaining codons are 0% - ignore, but finish off the last one if
673 if (samePercent.length() > 0)
675 mouseOver.append(samePercent).append(": ").append(percent)
680 int codonEncoded = codons[j];
681 final int pct = codonCount * 100 / totalCount;
682 String codon = String
683 .valueOf(CodingUtils.decodeCodon(codonEncoded));
684 StringBuilder sb = new StringBuilder();
685 Format.appendPercentage(sb, pct, percentDecPl);
686 percent = sb.toString();
687 if (showProfileLogo || codonCount == modalCodonCount)
689 if (percent.equals(lastPercent) && j > 0)
691 samePercent.append(samePercent.length() == 0 ? "" : ", ");
692 samePercent.append(codon);
696 if (samePercent.length() > 0)
698 mouseOver.append(samePercent).append(": ")
699 .append(lastPercent).append("% ");
701 samePercent.setLength(0);
702 samePercent.append(codon);
704 lastPercent = percent;
708 consensusAnnotation.annotations[col] = new Annotation(modalCodon,
709 mouseOver.toString(), ' ', pid);
714 * Returns the number of decimal places to show for profile percentages. For
715 * less than 100 sequences, returns zero (the integer percentage value will be
716 * displayed). For 100-999 sequences, returns 1, for 1000-9999 returns 2, etc.
721 protected static int getPercentageDp(long nseq)
733 * Produces a HMM profile for a column in an alignment
736 * Alignment annotation for which the profile is being calculated.
738 * Column in the alignment the profile is being made for.
739 * @param removeBelowBackground
740 * Boolean indicating whether to ignore residues with probabilities
741 * less than their background frequencies.
744 public static int[] getHMMProfileFor(HiddenMarkovModel hmm, int column,
745 boolean removeBelowBackground)
750 String alph = hmm.getAlphabetType();
751 int size = hmm.getNumberOfSymbols();
752 char symbols[] = new char[size];
753 int values[] = new int[size];
754 List<Character> charList = hmm.getSymbols();
755 Integer totalCount = 0;
757 for (int i = 0; i < size; i++)
759 char symbol = charList.get(i);
763 value = hmm.getMatchEmissionProbability(column, symbol);
766 if (AMINO.equals(alph) && removeBelowBackground)
768 freq = ResidueProperties.aminoBackgroundFrequencies.get(symbol);
774 else if (DNA.equals(alph) && removeBelowBackground)
776 freq = ResidueProperties.dnaBackgroundFrequencies.get(symbol);
782 else if (RNA.equals(alph) && removeBelowBackground)
784 freq = ResidueProperties.rnaBackgroundFrequencies
791 value = value * 10000;
792 values[i] = value.intValue();
793 totalCount += value.intValue();
796 QuickSort.sort(values, symbols);
798 int[] profile = new int[3 + size * 2];
800 profile[0] = AlignmentAnnotation.SEQUENCE_PROFILE;
802 profile[2] = totalCount / 100;
807 for (int k = size - 1; k >= 0; k--)
810 Integer value = values[k];
811 percentage = (value.doubleValue() / totalCount.doubleValue())
813 profile[arrayPos] = symbols[k];
814 profile[arrayPos + 1] = percentage.intValue();