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.util.Arrays;
41 import java.util.Hashtable;
42 import java.util.List;
45 * Takes in a vector or array of sequences and column start and column end and
46 * returns a new Hashtable[] of size maxSeqLength, if Hashtable not supplied.
47 * This class is used extensively in calculating alignment colourschemes that
48 * depend on the amount of conservation in each alignment column.
53 public class AAFrequency
55 public static final String PROFILE = "P";
58 * Quick look-up of String value of char 'A' to 'Z'
60 private static final String[] CHARS = new String['Z' - 'A' + 1];
64 for (char c = 'A'; c <= 'Z'; c++)
66 CHARS[c - 'A'] = String.valueOf(c);
70 public static final ProfilesI calculate(List<SequenceI> list,
73 return calculate(list, start, end, false);
76 public static final ProfilesI calculate(List<SequenceI> sequences,
77 int start, int end, boolean profile)
79 SequenceI[] seqs = new SequenceI[sequences.size()];
81 synchronized (sequences)
83 for (int i = 0; i < sequences.size(); i++)
85 seqs[i] = sequences.get(i);
86 int length = seqs[i].getLength();
98 ProfilesI reply = calculate(seqs, width, start, end, profile);
104 * Calculate the consensus symbol(s) for each column in the given range.
108 * the full width of the alignment
110 * start column (inclusive, base zero)
112 * end column (exclusive)
113 * @param saveFullProfile
114 * if true, store all symbol counts
116 public static final ProfilesI calculate(final SequenceI[] sequences,
117 int width, int start, int end, boolean saveFullProfile)
119 // long now = System.currentTimeMillis();
120 int seqCount = sequences.length;
121 boolean nucleotide = false;
122 int nucleotideCount = 0;
123 int peptideCount = 0;
125 ProfileI[] result = new ProfileI[width];
127 for (int column = start; column < end; column++)
130 * Apply a heuristic to detect nucleotide data (which can
131 * be counted in more compact arrays); here we test for
132 * more than 90% nucleotide; recheck every 10 columns in case
133 * of misleading data e.g. highly conserved Alanine in peptide!
134 * Mistakenly guessing nucleotide has a small performance cost,
135 * as it will result in counting in sparse arrays.
136 * Mistakenly guessing peptide has a small space cost,
137 * as it will use a larger than necessary array to hold counts.
139 if (nucleotideCount > 100 && column % 10 == 0)
141 nucleotide = (9 * peptideCount < nucleotideCount);
143 ResidueCount residueCounts = new ResidueCount(nucleotide);
145 for (int row = 0; row < seqCount; row++)
147 if (sequences[row] == null)
150 .println("WARNING: Consensus skipping null sequence - possible race condition.");
153 char[] seq = sequences[row].getSequence();
154 if (seq.length > column)
156 char c = seq[column];
157 residueCounts.add(c);
158 if (Comparison.isNucleotide(c))
162 else if (!Comparison.isGap(c))
170 * count a gap if the sequence doesn't reach this column
172 residueCounts.addGap();
176 int maxCount = residueCounts.getModalCount();
177 String maxResidue = residueCounts.getResiduesForCount(maxCount);
178 int gapCount = residueCounts.getGapCount();
179 ProfileI profile = new Profile(seqCount, gapCount, maxCount,
184 profile.setCounts(residueCounts);
187 result[column] = profile;
189 return new Profiles(result);
190 // long elapsed = System.currentTimeMillis() - now;
191 // System.out.println(elapsed);
195 * Make an estimate of the profile size we are going to compute i.e. how many
196 * different characters may be present in it. Overestimating has a cost of
197 * using more memory than necessary. Underestimating has a cost of needing to
198 * extend the SparseIntArray holding the profile counts.
200 * @param profileSizes
201 * counts of sizes of profiles so far encountered
204 static int estimateProfileSize(SparseIntArray profileSizes)
206 if (profileSizes.size() == 0)
212 * could do a statistical heuristic here e.g. 75%ile
213 * for now just return the largest value
215 return profileSizes.keyAt(profileSizes.size() - 1);
219 * Derive the consensus annotations to be added to the alignment for display.
220 * This does not recompute the raw data, but may be called on a change in
221 * display options, such as 'ignore gaps', which may in turn result in a
222 * change in the derived values.
225 * the annotation row to add annotations to
227 * the source consensus data
229 * start column (inclusive)
231 * end column (exclusive)
233 * if true, normalise residue percentages ignoring gaps
234 * @param showSequenceLogo
235 * if true include all consensus symbols, else just show modal
238 * number of sequences
240 public static void completeConsensus(AlignmentAnnotation consensus,
241 ProfilesI profiles, int startCol, int endCol, boolean ignoreGaps,
242 boolean showSequenceLogo, long nseq)
244 // long now = System.currentTimeMillis();
245 if (consensus == null || consensus.annotations == null
246 || consensus.annotations.length < endCol)
249 * called with a bad alignment annotation row
250 * wait for it to be initialised properly
255 for (int i = startCol; i < endCol; i++)
257 ProfileI profile = profiles.get(i);
261 * happens if sequences calculated over were
262 * shorter than alignment width
264 consensus.annotations[i] = null;
268 final int dp = getPercentageDp(nseq);
270 float value = profile.getPercentageIdentity(ignoreGaps);
272 String description = getTooltip(profile, value, showSequenceLogo,
275 String modalResidue = profile.getModalResidue();
276 if ("".equals(modalResidue))
280 else if (modalResidue.length() > 1)
284 consensus.annotations[i] = new Annotation(modalResidue, description,
287 // long elapsed = System.currentTimeMillis() - now;
288 // System.out.println(-elapsed);
292 * Returns a tooltip showing either
294 * <li>the full profile (percentages of all residues present), if
295 * showSequenceLogo is true, or</li>
296 * <li>just the modal (most common) residue(s), if showSequenceLogo is false</li>
298 * Percentages are as a fraction of all sequence, or only ungapped sequences
299 * if ignoreGaps is true.
303 * @param showSequenceLogo
306 * the number of decimal places to format percentages to
309 static String getTooltip(ProfileI profile, float pid,
310 boolean showSequenceLogo, boolean ignoreGaps, int dp)
312 ResidueCount counts = profile.getCounts();
314 String description = null;
315 if (counts != null && showSequenceLogo)
317 int normaliseBy = ignoreGaps ? profile.getNonGapped() : profile
319 description = counts.getTooltip(normaliseBy, dp);
323 StringBuilder sb = new StringBuilder(64);
324 String maxRes = profile.getModalResidue();
325 if (maxRes.length() > 1)
327 sb.append("[").append(maxRes).append("]");
333 if (maxRes.length() > 0)
336 Format.appendPercentage(sb, pid, dp);
339 description = sb.toString();
345 * Returns the sorted profile for the given consensus data. The returned array
349 * [profileType, numberOfValues, nonGapCount, charValue1, percentage1, charValue2, percentage2, ...]
350 * in descending order of percentage value
354 * the data object from which to extract and sort values
356 * if true, only non-gapped values are included in percentage
360 public static int[] extractProfile(ProfileI profile,
363 int[] rtnval = new int[64];
364 ResidueCount counts = profile.getCounts();
370 SymbolCounts symbolCounts = counts.getSymbolCounts();
371 char[] symbols = symbolCounts.symbols;
372 int[] values = symbolCounts.values;
373 QuickSort.sort(values, symbols);
374 int nextArrayPos = 2;
375 int totalPercentage = 0;
376 final int divisor = ignoreGaps ? profile.getNonGapped() : profile
380 * traverse the arrays in reverse order (highest counts first)
382 for (int i = symbols.length - 1; i >= 0; i--)
384 int theChar = symbols[i];
385 int charCount = values[i];
387 rtnval[nextArrayPos++] = theChar;
388 final int percentage = (charCount * 100) / divisor;
389 rtnval[nextArrayPos++] = percentage;
390 totalPercentage += percentage;
392 rtnval[0] = symbols.length;
393 rtnval[1] = totalPercentage;
394 int[] result = new int[rtnval.length + 1];
395 result[0] = AlignmentAnnotation.SEQUENCE_PROFILE;
396 System.arraycopy(rtnval, 0, result, 1, rtnval.length);
402 * Extract a sorted extract of cDNA codon profile data. The returned array
406 * [profileType, numberOfValues, totalCount, charValue1, percentage1, charValue2, percentage2, ...]
407 * in descending order of percentage value, where the character values encode codon triplets
413 public static int[] extractCdnaProfile(Hashtable hashtable,
416 // this holds #seqs, #ungapped, and then codon count, indexed by encoded
418 int[] codonCounts = (int[]) hashtable.get(PROFILE);
419 int[] sortedCounts = new int[codonCounts.length - 2];
420 System.arraycopy(codonCounts, 2, sortedCounts, 0,
421 codonCounts.length - 2);
423 int[] result = new int[3 + 2 * sortedCounts.length];
424 // first value is just the type of profile data
425 result[0] = AlignmentAnnotation.CDNA_PROFILE;
427 char[] codons = new char[sortedCounts.length];
428 for (int i = 0; i < codons.length; i++)
430 codons[i] = (char) i;
432 QuickSort.sort(sortedCounts, codons);
433 int totalPercentage = 0;
434 int distinctValuesCount = 0;
436 int divisor = ignoreGaps ? codonCounts[1] : codonCounts[0];
437 for (int i = codons.length - 1; i >= 0; i--)
439 final int codonCount = sortedCounts[i];
442 break; // nothing else of interest here
444 distinctValuesCount++;
445 result[j++] = codons[i];
446 final int percentage = codonCount * 100 / divisor;
447 result[j++] = percentage;
448 totalPercentage += percentage;
450 result[2] = totalPercentage;
453 * Just return the non-zero values
455 // todo next value is redundant if we limit the array to non-zero counts
456 result[1] = distinctValuesCount;
457 return Arrays.copyOfRange(result, 0, j);
461 * Compute a consensus for the cDNA coding for a protein alignment.
464 * the protein alignment (which should hold mappings to cDNA
467 * the consensus data stores to be populated (one per column)
469 public static void calculateCdna(AlignmentI alignment,
470 Hashtable[] hconsensus)
472 final char gapCharacter = alignment.getGapCharacter();
473 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
474 if (mappings == null || mappings.isEmpty())
479 int cols = alignment.getWidth();
480 for (int col = 0; col < cols; col++)
482 // todo would prefer a Java bean for consensus data
483 Hashtable<String, int[]> columnHash = new Hashtable<String, int[]>();
484 // #seqs, #ungapped seqs, counts indexed by (codon encoded + 1)
485 int[] codonCounts = new int[66];
486 codonCounts[0] = alignment.getSequences().size();
487 int ungappedCount = 0;
488 for (SequenceI seq : alignment.getSequences())
490 if (seq.getCharAt(col) == gapCharacter)
494 List<char[]> codons = MappingUtils
495 .findCodonsFor(seq, col, mappings);
496 for (char[] codon : codons)
498 int codonEncoded = CodingUtils.encodeCodon(codon);
499 if (codonEncoded >= 0)
501 codonCounts[codonEncoded + 2]++;
506 codonCounts[1] = ungappedCount;
507 // todo: sort values here, save counts and codons?
508 columnHash.put(PROFILE, codonCounts);
509 hconsensus[col] = columnHash;
514 * Derive displayable cDNA consensus annotation from computed consensus data.
516 * @param consensusAnnotation
517 * the annotation row to be populated for display
518 * @param consensusData
519 * the computed consensus data
520 * @param showProfileLogo
521 * if true show all symbols present at each position, else only the
524 * the number of sequences in the alignment
526 public static void completeCdnaConsensus(
527 AlignmentAnnotation consensusAnnotation,
528 Hashtable[] consensusData, boolean showProfileLogo, int nseqs)
530 if (consensusAnnotation == null
531 || consensusAnnotation.annotations == null
532 || consensusAnnotation.annotations.length < consensusData.length)
534 // called with a bad alignment annotation row - wait for it to be
535 // initialised properly
539 // ensure codon triplet scales with font size
540 consensusAnnotation.scaleColLabel = true;
541 for (int col = 0; col < consensusData.length; col++)
543 Hashtable hci = consensusData[col];
546 // gapped protein column?
549 // array holds #seqs, #ungapped, then codon counts indexed by codon
550 final int[] codonCounts = (int[]) hci.get(PROFILE);
554 * First pass - get total count and find the highest
556 final char[] codons = new char[codonCounts.length - 2];
557 for (int j = 2; j < codonCounts.length; j++)
559 final int codonCount = codonCounts[j];
560 codons[j - 2] = (char) (j - 2);
561 totalCount += codonCount;
565 * Sort array of encoded codons by count ascending - so the modal value
566 * goes to the end; start by copying the count (dropping the first value)
568 int[] sortedCodonCounts = new int[codonCounts.length - 2];
569 System.arraycopy(codonCounts, 2, sortedCodonCounts, 0,
570 codonCounts.length - 2);
571 QuickSort.sort(sortedCodonCounts, codons);
573 int modalCodonEncoded = codons[codons.length - 1];
574 int modalCodonCount = sortedCodonCounts[codons.length - 1];
575 String modalCodon = String.valueOf(CodingUtils
576 .decodeCodon(modalCodonEncoded));
577 if (sortedCodonCounts.length > 1
578 && sortedCodonCounts[codons.length - 2] == sortedCodonCounts[codons.length - 1])
581 * two or more codons share the modal count
585 float pid = sortedCodonCounts[sortedCodonCounts.length - 1] * 100
586 / (float) totalCount;
589 * todo ? Replace consensus hashtable with sorted arrays of codons and
590 * counts (non-zero only). Include total count in count array [0].
594 * Scan sorted array backwards for most frequent values first. Show
595 * repeated values compactly.
597 StringBuilder mouseOver = new StringBuilder(32);
598 StringBuilder samePercent = new StringBuilder();
599 String percent = null;
600 String lastPercent = null;
601 int percentDecPl = getPercentageDp(nseqs);
603 for (int j = codons.length - 1; j >= 0; j--)
605 int codonCount = sortedCodonCounts[j];
609 * remaining codons are 0% - ignore, but finish off the last one if
612 if (samePercent.length() > 0)
614 mouseOver.append(samePercent).append(": ").append(percent)
619 int codonEncoded = codons[j];
620 final int pct = codonCount * 100 / totalCount;
621 String codon = String
622 .valueOf(CodingUtils.decodeCodon(codonEncoded));
623 StringBuilder sb = new StringBuilder();
624 Format.appendPercentage(sb, pct, percentDecPl);
625 percent = sb.toString();
626 if (showProfileLogo || codonCount == modalCodonCount)
628 if (percent.equals(lastPercent) && j > 0)
630 samePercent.append(samePercent.length() == 0 ? "" : ", ");
631 samePercent.append(codon);
635 if (samePercent.length() > 0)
637 mouseOver.append(samePercent).append(": ")
638 .append(lastPercent).append("% ");
640 samePercent.setLength(0);
641 samePercent.append(codon);
643 lastPercent = percent;
647 consensusAnnotation.annotations[col] = new Annotation(modalCodon,
648 mouseOver.toString(), ' ', pid);
653 * Returns the number of decimal places to show for profile percentages. For
654 * less than 100 sequences, returns zero (the integer percentage value will be
655 * displayed). For 100-999 sequences, returns 1, for 1000-9999 returns 2, etc.
660 protected static int getPercentageDp(long nseq)