1 package jalview.datamodel;
3 import jalview.util.Comparison;
4 import jalview.util.Format;
5 import jalview.util.QuickSort;
6 import jalview.util.SparseCount;
9 * A class to count occurrences of residues in a profile, optimised for speed
10 * and memory footprint.
14 public class ResidueCount
17 * A data bean to hold the results of counting symbols
19 public class SymbolCounts
22 * the symbols seen (as char values), in no particular order
24 public final char[] symbols;
27 * the counts for each symbol, in the same order as the symbols
29 public final int[] values;
31 SymbolCounts(char[] s, int[] v)
38 private static final int TOUPPERCASE = 'A' - 'a';
41 * nucleotide symbols to count (including N unknown)
43 private static final String NUCS = "ACGNTU";
46 * amino acid symbols to count (including X unknown)
47 * NB we also include U so as to support counting of RNA bases
48 * in the "don't know" case of nucleotide / peptide
50 private static final String AAS = "ACDEFGHIKLMNPQRSTUVWXY";
52 private static final int GAP_COUNT = 0;
55 * fast lookup tables holding the index into our count
56 * arrays of each symbol; index 0 is reserved for gap counting
58 private static int[] NUC_INDEX = new int[26];
60 private static int[] AA_INDEX = new int[26];
63 for (int i = 0; i < NUCS.length(); i++)
65 NUC_INDEX[NUCS.charAt(i) - 'A'] = i + 1;
67 for (int i = 0; i < AAS.length(); i++)
69 AA_INDEX[AAS.charAt(i) - 'A'] = i + 1;
74 * counts array, just big enough for the nucleotide or peptide
75 * character set (plus gap counts in position 0)
77 private short[] counts;
80 * alternative array of int counts for use if any count
81 * exceeds the maximum value of short (32767)
83 private int[] intCounts;
86 * flag set if we switch from short to int counts
88 private boolean useIntCounts;
91 * general-purpose counter, only for use for characters
92 * that are not in the expected alphabet
94 private SparseCount otherData;
97 * keeps track of the maximum count value recorded
98 * (if this class ever allows decrements, would need to
99 * calculate this on request instead)
104 * if we think we are counting nucleotide, can get by with smaller
105 * array to hold counts
107 private boolean isNucleotide;
110 * Default constructor allocates arrays able to count either nucleotide or
111 * peptide bases. Use this constructor if not sure which the data is.
113 public ResidueCount()
119 * Constructor that allocates an array just big enough for the anticipated
120 * characters, plus one position to count gaps
122 public ResidueCount(boolean nucleotide)
124 isNucleotide = nucleotide;
125 int charsToCount = nucleotide ? NUCS.length() : AAS.length();
126 counts = new short[charsToCount + 1];
130 * Increments the count for the given character. The supplied character may be
131 * upper or lower case but counts are for the upper case only. Gap characters
132 * (space, ., -) are all counted together.
135 * @return the new value of the count for the character
137 public int add(final char c)
139 char u = toUpperCase(c);
141 int offset = getOffset(u);
144 * offset 0 is reserved for gap counting, so 0 here means either
145 * an unexpected character, or a gap character passed in error
149 if (Comparison.isGap(u))
155 newValue = addOtherCharacter(u);
160 newValue = increment(offset);
166 * Increment the count at the specified offset. If this would result in short
167 * overflow, promote to counting int values instead.
170 * @return the new value of the count at this offset
172 int increment(int offset)
177 newValue = intCounts[offset];
178 intCounts[offset] = ++newValue;
182 if (counts[offset] == Short.MAX_VALUE)
185 newValue = intCounts[offset];
186 intCounts[offset] = ++newValue;
190 newValue = counts[offset];
191 counts[offset] = (short) ++newValue;
194 maxCount = Math.max(maxCount, newValue);
199 * Switch from counting in short to counting in int
201 synchronized void handleOverflow()
203 intCounts = new int[counts.length];
204 for (int i = 0; i < counts.length; i++)
206 intCounts[i] = counts[i];
213 * Returns this character's offset in the count array
218 int getOffset(char c)
221 if ('A' <= c && c <= 'Z')
223 offset = isNucleotide ? NUC_INDEX[c - 'A'] : AA_INDEX[c - 'A'];
232 protected char toUpperCase(final char c)
235 if ('a' <= c && c <= 'z')
237 u = (char) (c + TOUPPERCASE);
243 * Increment count for some unanticipated character. The first time this
244 * called, a SparseCount is instantiated to hold these 'extra' counts.
247 * @return the new value of the count for the character
249 int addOtherCharacter(char c)
251 if (otherData == null)
253 otherData = new SparseCount();
255 int newValue = otherData.add(c, 1);
256 maxCount = Math.max(maxCount, newValue);
261 * Set count for some unanticipated character. The first time this called, a
262 * SparseCount is instantiated to hold these 'extra' counts.
267 void setOtherCharacter(char c, int value)
269 if (otherData == null)
271 otherData = new SparseCount();
273 otherData.put(c, value);
277 * Increment count of gap characters
279 * @return the new count of gaps
286 newValue = ++intCounts[GAP_COUNT];
290 newValue = ++counts[GAP_COUNT];
296 * Answers true if we are counting ints (only after overflow of short counts)
300 boolean isCountingInts()
306 * Sets the count for the given character. The supplied character may be upper
307 * or lower case but counts are for the upper case only.
312 public void put(char c, int count)
314 char u = toUpperCase(c);
315 int offset = getOffset(u);
318 * offset 0 is reserved for gap counting, so 0 here means either
319 * an unexpected character, or a gap character passed in error
323 if (Comparison.isGap(u))
329 setOtherCharacter(u, count);
330 maxCount = Math.max(maxCount, count);
336 maxCount = Math.max(maxCount, count);
341 * Sets the count at the specified offset. If this would result in short
342 * overflow, promote to counting int values instead.
347 void set(int offset, int value)
351 intCounts[offset] = value;
355 if (value > Short.MAX_VALUE || value < Short.MIN_VALUE)
358 intCounts[offset] = value;
362 counts[offset] = (short) value;
368 * Returns the count for the given character, or zero if no count held
373 public int getCount(char c)
375 char u = toUpperCase(c);
376 int offset = getOffset(u);
379 if (!Comparison.isGap(u))
381 // should have called getGapCount()
382 return otherData == null ? 0 : otherData.get(u);
385 return useIntCounts ? intCounts[offset] : counts[offset];
388 public int getGapCount()
390 return useIntCounts ? intCounts[0] : counts[0];
394 * Answers true if this object wraps a counter for unexpected characters
398 boolean isUsingOtherData()
400 return otherData != null;
404 * Returns the character (or concatenated characters) for the symbol(s) with
405 * the given count in the profile. Can be used to get the modal residue by
406 * supplying the modal count value. Returns an empty string if no symbol has
407 * the given count. The symbols are in alphabetic order of standard peptide or
408 * nucleotide characters, followed by 'other' symbols if any.
412 public String getResiduesForCount(int count)
420 * find counts for the given value and append the
421 * corresponding symbol
423 StringBuilder modal = new StringBuilder();
426 for (int i = 1; i < intCounts.length; i++)
428 if (intCounts[i] == count)
430 modal.append(isNucleotide ? NUCS.charAt(i - 1) : AAS
437 for (int i = 1; i < counts.length; i++)
439 if (counts[i] == count)
441 modal.append(isNucleotide ? NUCS.charAt(i - 1) : AAS
446 if (otherData != null)
448 for (int i = 0; i < otherData.size(); i++)
450 if (otherData.valueAt(i) == count)
452 modal.append((char) otherData.keyAt(i));
456 return modal.toString();
460 * Returns the highest count for any symbol(s) in the profile (excluding gap)
464 public int getModalCount()
470 * Returns the number of distinct symbols with a non-zero count (excluding the
479 for (int i = 1; i < intCounts.length; i++)
481 if (intCounts[i] > 0)
489 for (int i = 1; i < counts.length; i++)
499 * include 'other' characters recorded (even if count is zero
500 * though that would be a strange use case)
502 if (otherData != null)
504 size += otherData.size();
511 * Returns a data bean holding those symbols that have a non-zero count
512 * (excluding the gap symbol), with their counts.
516 public SymbolCounts getSymbolCounts()
519 char[] symbols = new char[size];
520 int[] values = new int[size];
525 for (int i = 1; i < intCounts.length; i++)
527 if (intCounts[i] > 0)
529 char symbol = isNucleotide ? NUCS.charAt(i - 1) : AAS
532 values[j] = intCounts[i];
539 for (int i = 1; i < counts.length; i++)
543 char symbol = isNucleotide ? NUCS.charAt(i - 1) : AAS
546 values[j] = counts[i];
551 if (otherData != null)
553 for (int i = 0; i < otherData.size(); i++)
555 symbols[j] = (char) otherData.keyAt(i);
556 values[j] = otherData.valueAt(i);
561 return new SymbolCounts(symbols, values);
565 * Returns a tooltip string showing residues in descending order of their
566 * percentage frequency in the profile
569 * the divisor for residue counts (may or may not include gapped
571 * @param percentageDecPl
572 * the number of decimal places to show in percentages
575 public String getTooltip(int normaliseBy, int percentageDecPl)
577 SymbolCounts symbolCounts = getSymbolCounts();
578 char[] ca = symbolCounts.symbols;
579 int[] vl = symbolCounts.values;
582 * sort characters into ascending order of their counts
584 QuickSort.sort(vl, ca);
587 * traverse in reverse order (highest count first) to build tooltip
589 boolean first = true;
590 StringBuilder sb = new StringBuilder(64);
591 for (int c = ca.length - 1; c >= 0; c--)
593 final char residue = ca[c];
594 // TODO combine residues which share a percentage
595 // (see AAFrequency.completeCdnaConsensus)
596 float tval = (vl[c] * 100f) / normaliseBy;
597 sb.append(first ? "" : "; ").append(residue).append(" ");
598 Format.appendPercentage(sb, tval, percentageDecPl);
602 return sb.toString();
606 * Returns a string representation of the symbol counts, for debug purposes.
609 public String toString()
611 StringBuilder sb = new StringBuilder();
613 SymbolCounts sc = getSymbolCounts();
614 for (int i = 0; i < sc.symbols.length; i++)
616 sb.append(sc.symbols[i]).append(":").append(sc.values[i]).append(" ");
619 return sb.toString();