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.Profile;
28 import jalview.datamodel.ProfileI;
29 import jalview.datamodel.Profiles;
30 import jalview.datamodel.ProfilesI;
31 import jalview.datamodel.ResidueCount;
32 import jalview.datamodel.ResidueCount.SymbolCounts;
33 import jalview.datamodel.SequenceI;
34 import jalview.ext.android.SparseIntArray;
35 import jalview.util.Comparison;
36 import jalview.util.Format;
37 import jalview.util.MappingUtils;
38 import jalview.util.QuickSort;
40 import java.awt.Color;
41 import java.util.Arrays;
42 import java.util.Hashtable;
43 import java.util.List;
46 * Takes in a vector or array of sequences and column start and column end and
47 * returns a new Hashtable[] of size maxSeqLength, if Hashtable not supplied.
48 * This class is used extensively in calculating alignment colourschemes that
49 * depend on the amount of conservation in each alignment column.
54 public class AAFrequency
56 public static final String PROFILE = "P";
59 * Quick look-up of String value of char 'A' to 'Z'
61 private static final String[] CHARS = new String['Z' - 'A' + 1];
65 for (char c = 'A'; c <= 'Z'; c++)
67 CHARS[c - 'A'] = String.valueOf(c);
71 public static final ProfilesI calculate(List<SequenceI> list, int start,
74 return calculate(list, start, end, false);
77 public static final ProfilesI calculate(List<SequenceI> sequences,
78 int start, int end, boolean profile)
80 SequenceI[] seqs = new SequenceI[sequences.size()];
82 synchronized (sequences)
84 for (int i = 0; i < sequences.size(); i++)
86 seqs[i] = sequences.get(i);
87 int length = seqs[i].getLength();
99 ProfilesI reply = calculate(seqs, width, start, end, profile);
105 * Calculate the consensus symbol(s) for each column in the given range.
109 * the full width of the alignment
111 * start column (inclusive, base zero)
113 * end column (exclusive)
114 * @param saveFullProfile
115 * if true, store all symbol counts
117 public static final ProfilesI calculate(final SequenceI[] sequences,
118 int width, int start, int end, boolean saveFullProfile)
120 // long now = System.currentTimeMillis();
121 int seqCount = sequences.length;
122 boolean nucleotide = false;
123 int nucleotideCount = 0;
124 int peptideCount = 0;
126 ProfileI[] result = new ProfileI[width];
128 for (int column = start; column < end; column++)
131 * Apply a heuristic to detect nucleotide data (which can
132 * be counted in more compact arrays); here we test for
133 * more than 90% nucleotide; recheck every 10 columns in case
134 * of misleading data e.g. highly conserved Alanine in peptide!
135 * Mistakenly guessing nucleotide has a small performance cost,
136 * as it will result in counting in sparse arrays.
137 * Mistakenly guessing peptide has a small space cost,
138 * as it will use a larger than necessary array to hold counts.
140 if (nucleotideCount > 100 && column % 10 == 0)
142 nucleotide = (9 * peptideCount < nucleotideCount);
144 ResidueCount residueCounts = new ResidueCount(nucleotide);
146 for (int row = 0; row < seqCount; row++)
148 if (sequences[row] == null)
151 .println("WARNING: Consensus skipping null sequence - possible race condition.");
154 char[] seq = sequences[row].getSequence();
155 if (seq.length > column)
157 char c = seq[column];
158 residueCounts.add(c);
159 if (Comparison.isNucleotide(c))
163 else if (!Comparison.isGap(c))
171 * count a gap if the sequence doesn't reach this column
173 residueCounts.addGap();
177 int maxCount = residueCounts.getModalCount();
178 String maxResidue = residueCounts.getResiduesForCount(maxCount);
179 int gapCount = residueCounts.getGapCount();
180 ProfileI profile = new Profile(seqCount, gapCount, maxCount,
185 profile.setCounts(residueCounts);
188 result[column] = profile;
190 return new Profiles(result);
191 // long elapsed = System.currentTimeMillis() - now;
192 // System.out.println(elapsed);
196 * Make an estimate of the profile size we are going to compute i.e. how many
197 * different characters may be present in it. Overestimating has a cost of
198 * using more memory than necessary. Underestimating has a cost of needing to
199 * extend the SparseIntArray holding the profile counts.
201 * @param profileSizes
202 * counts of sizes of profiles so far encountered
205 static int estimateProfileSize(SparseIntArray profileSizes)
207 if (profileSizes.size() == 0)
213 * could do a statistical heuristic here e.g. 75%ile
214 * for now just return the largest value
216 return profileSizes.keyAt(profileSizes.size() - 1);
220 * Derive the consensus annotations to be added to the alignment for display.
221 * This does not recompute the raw data, but may be called on a change in
222 * display options, such as 'ignore gaps', which may in turn result in a
223 * change in the derived values.
226 * the annotation row to add annotations to
228 * the source consensus data
230 * start column (inclusive)
232 * end column (exclusive)
234 * if true, normalise residue percentages ignoring gaps
235 * @param showSequenceLogo
236 * if true include all consensus symbols, else just show modal
239 * number of sequences
241 public static void completeConsensus(AlignmentAnnotation consensus,
242 ProfilesI profiles, int startCol, int endCol, boolean ignoreGaps,
243 boolean showSequenceLogo, long nseq)
245 // long now = System.currentTimeMillis();
246 if (consensus == null || consensus.annotations == null
247 || consensus.annotations.length < endCol)
250 * called with a bad alignment annotation row
251 * wait for it to be initialised properly
256 for (int i = startCol; i < endCol; i++)
258 ProfileI profile = profiles.get(i);
262 * happens if sequences calculated over were
263 * shorter than alignment width
265 consensus.annotations[i] = null;
269 final int dp = getPercentageDp(nseq);
271 float value = profile.getPercentageIdentity(ignoreGaps);
273 String description = getTooltip(profile, value, showSequenceLogo,
276 String modalResidue = profile.getModalResidue();
277 if ("".equals(modalResidue))
281 else if (modalResidue.length() > 1)
285 consensus.annotations[i] = new Annotation(modalResidue, description,
288 // long elapsed = System.currentTimeMillis() - now;
289 // System.out.println(-elapsed);
293 * Derive the gap count annotation row.
296 * the annotation row to add annotations to
298 * the source consensus data
300 * start column (inclusive)
302 * end column (exclusive)
304 public static void completeGapAnnot(AlignmentAnnotation gaprow,
305 ProfilesI profiles, int startCol, int endCol, long nseq)
307 if (gaprow == null || gaprow.annotations == null
308 || gaprow.annotations.length < endCol)
311 * called with a bad alignment annotation row
312 * wait for it to be initialised properly
316 // always set ranges again
317 gaprow.graphMax = nseq;
319 double scale = 0.8/nseq;
320 for (int i = startCol; i < endCol; i++)
322 ProfileI profile = profiles.get(i);
326 * happens if sequences calculated over were
327 * shorter than alignment width
329 gaprow.annotations[i] = null;
333 final int gapped = profile.getNonGapped();
335 String description = "" + gapped;
337 gaprow.annotations[i] = new Annotation("", description,
338 '\0', gapped, jalview.util.ColorUtils.bleachColour(
339 Color.DARK_GRAY, (float) scale * gapped));
344 * Returns a tooltip showing either
346 * <li>the full profile (percentages of all residues present), if
347 * showSequenceLogo is true, or</li>
348 * <li>just the modal (most common) residue(s), if showSequenceLogo is false</li>
350 * Percentages are as a fraction of all sequence, or only ungapped sequences
351 * if ignoreGaps is true.
355 * @param showSequenceLogo
358 * the number of decimal places to format percentages to
361 static String getTooltip(ProfileI profile, float pid,
362 boolean showSequenceLogo, boolean ignoreGaps, int dp)
364 ResidueCount counts = profile.getCounts();
366 String description = null;
367 if (counts != null && showSequenceLogo)
369 int normaliseBy = ignoreGaps ? profile.getNonGapped() : profile
371 description = counts.getTooltip(normaliseBy, dp);
375 StringBuilder sb = new StringBuilder(64);
376 String maxRes = profile.getModalResidue();
377 if (maxRes.length() > 1)
379 sb.append("[").append(maxRes).append("]");
385 if (maxRes.length() > 0)
388 Format.appendPercentage(sb, pid, dp);
391 description = sb.toString();
397 * Returns the sorted profile for the given consensus data. The returned array
401 * [profileType, numberOfValues, nonGapCount, charValue1, percentage1, charValue2, percentage2, ...]
402 * in descending order of percentage value
406 * the data object from which to extract and sort values
408 * if true, only non-gapped values are included in percentage
412 public static int[] extractProfile(ProfileI profile, boolean ignoreGaps)
414 int[] rtnval = new int[64];
415 ResidueCount counts = profile.getCounts();
421 SymbolCounts symbolCounts = counts.getSymbolCounts();
422 char[] symbols = symbolCounts.symbols;
423 int[] values = symbolCounts.values;
424 QuickSort.sort(values, symbols);
425 int nextArrayPos = 2;
426 int totalPercentage = 0;
427 final int divisor = ignoreGaps ? profile.getNonGapped() : profile
431 * traverse the arrays in reverse order (highest counts first)
433 for (int i = symbols.length - 1; i >= 0; i--)
435 int theChar = symbols[i];
436 int charCount = values[i];
438 rtnval[nextArrayPos++] = theChar;
439 final int percentage = (charCount * 100) / divisor;
440 rtnval[nextArrayPos++] = percentage;
441 totalPercentage += percentage;
443 rtnval[0] = symbols.length;
444 rtnval[1] = totalPercentage;
445 int[] result = new int[rtnval.length + 1];
446 result[0] = AlignmentAnnotation.SEQUENCE_PROFILE;
447 System.arraycopy(rtnval, 0, result, 1, rtnval.length);
453 * Extract a sorted extract of cDNA codon profile data. The returned array
457 * [profileType, numberOfValues, totalCount, charValue1, percentage1, charValue2, percentage2, ...]
458 * in descending order of percentage value, where the character values encode codon triplets
464 public static int[] extractCdnaProfile(Hashtable hashtable,
467 // this holds #seqs, #ungapped, and then codon count, indexed by encoded
469 int[] codonCounts = (int[]) hashtable.get(PROFILE);
470 int[] sortedCounts = new int[codonCounts.length - 2];
471 System.arraycopy(codonCounts, 2, sortedCounts, 0,
472 codonCounts.length - 2);
474 int[] result = new int[3 + 2 * sortedCounts.length];
475 // first value is just the type of profile data
476 result[0] = AlignmentAnnotation.CDNA_PROFILE;
478 char[] codons = new char[sortedCounts.length];
479 for (int i = 0; i < codons.length; i++)
481 codons[i] = (char) i;
483 QuickSort.sort(sortedCounts, codons);
484 int totalPercentage = 0;
485 int distinctValuesCount = 0;
487 int divisor = ignoreGaps ? codonCounts[1] : codonCounts[0];
488 for (int i = codons.length - 1; i >= 0; i--)
490 final int codonCount = sortedCounts[i];
493 break; // nothing else of interest here
495 distinctValuesCount++;
496 result[j++] = codons[i];
497 final int percentage = codonCount * 100 / divisor;
498 result[j++] = percentage;
499 totalPercentage += percentage;
501 result[2] = totalPercentage;
504 * Just return the non-zero values
506 // todo next value is redundant if we limit the array to non-zero counts
507 result[1] = distinctValuesCount;
508 return Arrays.copyOfRange(result, 0, j);
512 * Compute a consensus for the cDNA coding for a protein alignment.
515 * the protein alignment (which should hold mappings to cDNA
518 * the consensus data stores to be populated (one per column)
520 public static void calculateCdna(AlignmentI alignment,
521 Hashtable[] hconsensus)
523 final char gapCharacter = alignment.getGapCharacter();
524 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
525 if (mappings == null || mappings.isEmpty())
530 int cols = alignment.getWidth();
531 for (int col = 0; col < cols; col++)
533 // todo would prefer a Java bean for consensus data
534 Hashtable<String, int[]> columnHash = new Hashtable<String, int[]>();
535 // #seqs, #ungapped seqs, counts indexed by (codon encoded + 1)
536 int[] codonCounts = new int[66];
537 codonCounts[0] = alignment.getSequences().size();
538 int ungappedCount = 0;
539 for (SequenceI seq : alignment.getSequences())
541 if (seq.getCharAt(col) == gapCharacter)
545 List<char[]> codons = MappingUtils
546 .findCodonsFor(seq, col, mappings);
547 for (char[] codon : codons)
549 int codonEncoded = CodingUtils.encodeCodon(codon);
550 if (codonEncoded >= 0)
552 codonCounts[codonEncoded + 2]++;
557 codonCounts[1] = ungappedCount;
558 // todo: sort values here, save counts and codons?
559 columnHash.put(PROFILE, codonCounts);
560 hconsensus[col] = columnHash;
565 * Derive displayable cDNA consensus annotation from computed consensus data.
567 * @param consensusAnnotation
568 * the annotation row to be populated for display
569 * @param consensusData
570 * the computed consensus data
571 * @param showProfileLogo
572 * if true show all symbols present at each position, else only the
575 * the number of sequences in the alignment
577 public static void completeCdnaConsensus(
578 AlignmentAnnotation consensusAnnotation,
579 Hashtable[] consensusData, boolean showProfileLogo, int nseqs)
581 if (consensusAnnotation == null
582 || consensusAnnotation.annotations == null
583 || consensusAnnotation.annotations.length < consensusData.length)
585 // called with a bad alignment annotation row - wait for it to be
586 // initialised properly
590 // ensure codon triplet scales with font size
591 consensusAnnotation.scaleColLabel = true;
592 for (int col = 0; col < consensusData.length; col++)
594 Hashtable hci = consensusData[col];
597 // gapped protein column?
600 // array holds #seqs, #ungapped, then codon counts indexed by codon
601 final int[] codonCounts = (int[]) hci.get(PROFILE);
605 * First pass - get total count and find the highest
607 final char[] codons = new char[codonCounts.length - 2];
608 for (int j = 2; j < codonCounts.length; j++)
610 final int codonCount = codonCounts[j];
611 codons[j - 2] = (char) (j - 2);
612 totalCount += codonCount;
616 * Sort array of encoded codons by count ascending - so the modal value
617 * goes to the end; start by copying the count (dropping the first value)
619 int[] sortedCodonCounts = new int[codonCounts.length - 2];
620 System.arraycopy(codonCounts, 2, sortedCodonCounts, 0,
621 codonCounts.length - 2);
622 QuickSort.sort(sortedCodonCounts, codons);
624 int modalCodonEncoded = codons[codons.length - 1];
625 int modalCodonCount = sortedCodonCounts[codons.length - 1];
626 String modalCodon = String.valueOf(CodingUtils
627 .decodeCodon(modalCodonEncoded));
628 if (sortedCodonCounts.length > 1
629 && sortedCodonCounts[codons.length - 2] == sortedCodonCounts[codons.length - 1])
632 * two or more codons share the modal count
636 float pid = sortedCodonCounts[sortedCodonCounts.length - 1] * 100
637 / (float) totalCount;
640 * todo ? Replace consensus hashtable with sorted arrays of codons and
641 * counts (non-zero only). Include total count in count array [0].
645 * Scan sorted array backwards for most frequent values first. Show
646 * repeated values compactly.
648 StringBuilder mouseOver = new StringBuilder(32);
649 StringBuilder samePercent = new StringBuilder();
650 String percent = null;
651 String lastPercent = null;
652 int percentDecPl = getPercentageDp(nseqs);
654 for (int j = codons.length - 1; j >= 0; j--)
656 int codonCount = sortedCodonCounts[j];
660 * remaining codons are 0% - ignore, but finish off the last one if
663 if (samePercent.length() > 0)
665 mouseOver.append(samePercent).append(": ").append(percent)
670 int codonEncoded = codons[j];
671 final int pct = codonCount * 100 / totalCount;
672 String codon = String
673 .valueOf(CodingUtils.decodeCodon(codonEncoded));
674 StringBuilder sb = new StringBuilder();
675 Format.appendPercentage(sb, pct, percentDecPl);
676 percent = sb.toString();
677 if (showProfileLogo || codonCount == modalCodonCount)
679 if (percent.equals(lastPercent) && j > 0)
681 samePercent.append(samePercent.length() == 0 ? "" : ", ");
682 samePercent.append(codon);
686 if (samePercent.length() > 0)
688 mouseOver.append(samePercent).append(": ")
689 .append(lastPercent).append("% ");
691 samePercent.setLength(0);
692 samePercent.append(codon);
694 lastPercent = percent;
698 consensusAnnotation.annotations[col] = new Annotation(modalCodon,
699 mouseOver.toString(), ' ', pid);
704 * Returns the number of decimal places to show for profile percentages. For
705 * less than 100 sequences, returns zero (the integer percentage value will be
706 * displayed). For 100-999 sequences, returns 1, for 1000-9999 returns 2, etc.
711 protected static int getPercentageDp(long nseq)