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.datamodel;
23 import jalview.util.Comparison;
24 import jalview.util.Format;
25 import jalview.util.QuickSort;
26 import jalview.util.SparseCount;
29 * A class to count occurrences of residues in a profile, optimised for speed
30 * and memory footprint.
35 public class ResidueCount
38 * A data bean to hold the results of counting symbols
40 public class SymbolCounts
43 * the symbols seen (as char values), in no particular order
45 public final char[] symbols;
48 * the counts for each symbol, in the same order as the symbols
50 public final int[] values;
52 SymbolCounts(char[] s, int[] v)
59 private static final int TOUPPERCASE = 'A' - 'a';
62 * nucleotide symbols to count (including N unknown)
64 private static final String NUCS = "ACGNTU";
67 * amino acid symbols to count (including X unknown)
68 * NB we also include U so as to support counting of RNA bases
69 * in the "don't know" case of nucleotide / peptide
71 private static final String AAS = "ACDEFGHIKLMNPQRSTUVWXY";
73 private static final int GAP_COUNT = 0;
76 * fast lookup tables holding the index into our count
77 * arrays of each symbol; index 0 is reserved for gap counting
79 private static int[] NUC_INDEX = new int[26];
81 private static int[] AA_INDEX = new int[26];
84 for (int i = 0; i < NUCS.length(); i++)
86 NUC_INDEX[NUCS.charAt(i) - 'A'] = i + 1;
88 for (int i = 0; i < AAS.length(); i++)
90 AA_INDEX[AAS.charAt(i) - 'A'] = i + 1;
95 * counts array, just big enough for the nucleotide or peptide
96 * character set (plus gap counts in position 0)
98 private short[] counts;
101 * alternative array of int counts for use if any count
102 * exceeds the maximum value of short (32767)
104 private int[] intCounts;
107 * flag set if we switch from short to int counts
109 private boolean useIntCounts;
112 * general-purpose counter, only for use for characters
113 * that are not in the expected alphabet
115 private SparseCount otherData;
118 * keeps track of the maximum count value recorded
119 * (if this class ever allows decrements, would need to
120 * calculate this on request instead)
125 * if we think we are counting nucleotide, can get by with smaller
126 * array to hold counts
128 private boolean isNucleotide;
131 * Default constructor allocates arrays able to count either nucleotide or
132 * peptide bases. Use this constructor if not sure which the data is.
134 public ResidueCount()
140 * Constructor that allocates an array just big enough for the anticipated
141 * characters, plus one position to count gaps
143 public ResidueCount(boolean nucleotide)
145 isNucleotide = nucleotide;
146 int charsToCount = nucleotide ? NUCS.length() : AAS.length();
147 counts = new short[charsToCount + 1];
151 * Increments the count for the given character. The supplied character may be
152 * upper or lower case but counts are for the upper case only. Gap characters
153 * (space, ., -) are all counted together.
156 * @return the new value of the count for the character
158 public int add(final char c)
160 char u = toUpperCase(c);
162 int offset = getOffset(u);
165 * offset 0 is reserved for gap counting, so 0 here means either
166 * an unexpected character, or a gap character passed in error
170 if (Comparison.isGap(u))
176 newValue = addOtherCharacter(u);
181 newValue = increment(offset);
187 * Increment the count at the specified offset. If this would result in short
188 * overflow, promote to counting int values instead.
191 * @return the new value of the count at this offset
193 int increment(int offset)
198 newValue = intCounts[offset];
199 intCounts[offset] = ++newValue;
203 if (counts[offset] == Short.MAX_VALUE)
206 newValue = intCounts[offset];
207 intCounts[offset] = ++newValue;
211 newValue = counts[offset];
212 counts[offset] = (short) ++newValue;
215 maxCount = Math.max(maxCount, newValue);
220 * Switch from counting in short to counting in int
222 synchronized void handleOverflow()
224 intCounts = new int[counts.length];
225 for (int i = 0; i < counts.length; i++)
227 intCounts[i] = counts[i];
234 * Returns this character's offset in the count array
239 int getOffset(char c)
242 if ('A' <= c && c <= 'Z')
244 offset = isNucleotide ? NUC_INDEX[c - 'A'] : AA_INDEX[c - 'A'];
253 protected char toUpperCase(final char c)
256 if ('a' <= c && c <= 'z')
258 u = (char) (c + TOUPPERCASE);
264 * Increment count for some unanticipated character. The first time this
265 * called, a SparseCount is instantiated to hold these 'extra' counts.
268 * @return the new value of the count for the character
270 int addOtherCharacter(char c)
272 if (otherData == null)
274 otherData = new SparseCount();
276 int newValue = otherData.add(c, 1);
277 maxCount = Math.max(maxCount, newValue);
282 * Set count for some unanticipated character. The first time this called, a
283 * SparseCount is instantiated to hold these 'extra' counts.
288 void setOtherCharacter(char c, int value)
290 if (otherData == null)
292 otherData = new SparseCount();
294 otherData.put(c, value);
298 * Increment count of gap characters
300 * @return the new count of gaps
307 newValue = ++intCounts[GAP_COUNT];
311 newValue = ++counts[GAP_COUNT];
317 * Answers true if we are counting ints (only after overflow of short counts)
321 boolean isCountingInts()
327 * Sets the count for the given character. The supplied character may be upper
328 * or lower case but counts are for the upper case only.
333 public void put(char c, int count)
335 char u = toUpperCase(c);
336 int offset = getOffset(u);
339 * offset 0 is reserved for gap counting, so 0 here means either
340 * an unexpected character, or a gap character passed in error
344 if (Comparison.isGap(u))
350 setOtherCharacter(u, count);
351 maxCount = Math.max(maxCount, count);
357 maxCount = Math.max(maxCount, count);
362 * Sets the count at the specified offset. If this would result in short
363 * overflow, promote to counting int values instead.
368 void set(int offset, int value)
372 intCounts[offset] = value;
376 if (value > Short.MAX_VALUE || value < Short.MIN_VALUE)
379 intCounts[offset] = value;
383 counts[offset] = (short) value;
389 * Returns the count for the given character, or zero if no count held
394 public int getCount(char c)
396 char u = toUpperCase(c);
397 int offset = getOffset(u);
400 if (!Comparison.isGap(u))
402 // should have called getGapCount()
403 return otherData == null ? 0 : otherData.get(u);
406 return useIntCounts ? intCounts[offset] : counts[offset];
409 public int getGapCount()
411 return useIntCounts ? intCounts[0] : counts[0];
415 * Answers true if this object wraps a counter for unexpected characters
419 boolean isUsingOtherData()
421 return otherData != null;
425 * Returns the character (or concatenated characters) for the symbol(s) with
426 * the given count in the profile. Can be used to get the modal residue by
427 * supplying the modal count value. Returns an empty string if no symbol has
428 * the given count. The symbols are in alphabetic order of standard peptide or
429 * nucleotide characters, followed by 'other' symbols if any.
433 public String getResiduesForCount(int count)
441 * find counts for the given value and append the
442 * corresponding symbol
444 StringBuilder modal = new StringBuilder();
447 for (int i = 1; i < intCounts.length; i++)
449 if (intCounts[i] == count)
452 isNucleotide ? NUCS.charAt(i - 1) : AAS.charAt(i - 1));
458 for (int i = 1; i < counts.length; i++)
460 if (counts[i] == count)
463 isNucleotide ? NUCS.charAt(i - 1) : AAS.charAt(i - 1));
467 if (otherData != null)
469 for (int i = 0; i < otherData.size(); i++)
471 if (otherData.valueAt(i) == count)
473 modal.append((char) otherData.keyAt(i));
477 return modal.toString();
481 * Returns the highest count for any symbol(s) in the profile (excluding gap)
485 public int getModalCount()
491 * Returns the number of distinct symbols with a non-zero count (excluding the
501 for (int i = 1; i < intCounts.length; i++)
503 if (intCounts[i] > 0)
511 for (int i = 1; i < counts.length; i++)
521 * include 'other' characters recorded (even if count is zero
522 * though that would be a strange use case)
524 if (otherData != null)
526 size += otherData.size();
533 * Returns a data bean holding those symbols that have a non-zero count
534 * (excluding the gap symbol), with their counts.
538 public SymbolCounts getSymbolCounts()
541 char[] symbols = new char[size];
542 int[] values = new int[size];
547 for (int i = 1; i < intCounts.length; i++)
549 if (intCounts[i] > 0)
551 char symbol = isNucleotide ? NUCS.charAt(i - 1)
554 values[j] = intCounts[i];
561 for (int i = 1; i < counts.length; i++)
565 char symbol = isNucleotide ? NUCS.charAt(i - 1)
568 values[j] = counts[i];
573 if (otherData != null)
575 for (int i = 0; i < otherData.size(); i++)
577 symbols[j] = (char) otherData.keyAt(i);
578 values[j] = otherData.valueAt(i);
583 return new SymbolCounts(symbols, values);
587 * Returns a tooltip string showing residues in descending order of their
588 * percentage frequency in the profile
591 * the divisor for residue counts (may or may not include gapped
593 * @param percentageDecPl
594 * the number of decimal places to show in percentages
597 public String getTooltip(int normaliseBy, int percentageDecPl)
599 SymbolCounts symbolCounts = getSymbolCounts();
600 char[] ca = symbolCounts.symbols;
601 int[] vl = symbolCounts.values;
604 * sort characters into ascending order of their counts
606 QuickSort.sort(vl, ca);
609 * traverse in reverse order (highest count first) to build tooltip
611 boolean first = true;
612 StringBuilder sb = new StringBuilder(64);
613 for (int c = ca.length - 1; c >= 0; c--)
615 final char residue = ca[c];
616 // TODO combine residues which share a percentage
617 // (see AAFrequency.completeCdnaConsensus)
618 float tval = (vl[c] * 100f) / normaliseBy;
619 sb.append(first ? "" : "; ").append(residue).append(" ");
620 Format.appendPercentage(sb, tval, percentageDecPl);
624 return sb.toString();
628 * Returns a string representation of the symbol counts, for debug purposes.
631 public String toString()
633 StringBuilder sb = new StringBuilder();
635 SymbolCounts sc = getSymbolCounts();
636 for (int i = 0; i < sc.symbols.length; i++)
638 sb.append(sc.symbols[i]).append(":").append(sc.values[i]).append(" ");
641 return sb.toString();