+ profile.setCounts(residueCounts);
+ }
+
+ result[column] = profile;
+ }
+ return new Profiles(result);
+ // long elapsed = System.currentTimeMillis() - now;
+ // System.out.println(elapsed);
+ }
+
+ /**
+ * Make an estimate of the profile size we are going to compute i.e. how many
+ * different characters may be present in it. Overestimating has a cost of
+ * using more memory than necessary. Underestimating has a cost of needing to
+ * extend the SparseIntArray holding the profile counts.
+ *
+ * @param profileSizes
+ * counts of sizes of profiles so far encountered
+ * @return
+ */
+ static int estimateProfileSize(SparseIntArray profileSizes)
+ {
+ if (profileSizes.size() == 0)
+ {
+ return 4;
+ }
+
+ /*
+ * could do a statistical heuristic here e.g. 75%ile
+ * for now just return the largest value
+ */
+ return profileSizes.keyAt(profileSizes.size() - 1);
+ }
+
+ /**
+ * Derive the consensus annotations to be added to the alignment for display.
+ * This does not recompute the raw data, but may be called on a change in
+ * display options, such as 'ignore gaps', which may in turn result in a
+ * change in the derived values.
+ *
+ * @param consensus
+ * the annotation row to add annotations to
+ * @param profiles
+ * the source consensus data
+ * @param startCol
+ * start column (inclusive)
+ * @param endCol
+ * end column (exclusive)
+ * @param ignoreGaps
+ * if true, normalise residue percentages ignoring gaps
+ * @param showSequenceLogo
+ * if true include all consensus symbols, else just show modal
+ * residue
+ * @param nseq
+ * number of sequences
+ */
+ public static void completeConsensus(AlignmentAnnotation consensus,
+ ProfilesI profiles, int startCol, int endCol, boolean ignoreGaps,
+ boolean showSequenceLogo, long nseq)
+ {
+ // long now = System.currentTimeMillis();
+ if (consensus == null || consensus.annotations == null
+ || consensus.annotations.length < endCol)
+ {
+ /*
+ * called with a bad alignment annotation row
+ * wait for it to be initialised properly
+ */
+ return;
+ }
+
+ for (int i = startCol; i < endCol; i++)
+ {
+ ProfileI profile = profiles.get(i);
+ if (profile == null)
+ {
+ /*
+ * happens if sequences calculated over were
+ * shorter than alignment width
+ */
+ consensus.annotations[i] = null;
+ return;
+ }
+
+ final int dp = getPercentageDp(nseq);
+
+ float value = profile.getPercentageIdentity(ignoreGaps);
+
+ String description = getTooltip(profile, value, showSequenceLogo,
+ ignoreGaps, dp);
+
+ String modalResidue = profile.getModalResidue();
+ if ("".equals(modalResidue))
+ {
+ modalResidue = "-";
+ }
+ else if (modalResidue.length() > 1)
+ {
+ modalResidue = "+";
+ }
+ consensus.annotations[i] = new Annotation(modalResidue, description,
+ ' ', value);
+ }
+ // long elapsed = System.currentTimeMillis() - now;
+ // System.out.println(-elapsed);
+ }
+
+ /**
+ * Derive the gap count annotation row.
+ *
+ * @param gaprow
+ * the annotation row to add annotations to
+ * @param profiles
+ * the source consensus data
+ * @param startCol
+ * start column (inclusive)
+ * @param endCol
+ * end column (exclusive)
+ */
+ public static void completeGapAnnot(AlignmentAnnotation gaprow,
+ ProfilesI profiles, int startCol, int endCol, long nseq)
+ {
+ if (gaprow == null || gaprow.annotations == null
+ || gaprow.annotations.length < endCol)
+ {
+ /*
+ * called with a bad alignment annotation row
+ * wait for it to be initialised properly
+ */
+ return;
+ }
+ // always set ranges again
+ gaprow.graphMax = nseq;
+ gaprow.graphMin = 0;
+ double scale = 0.8 / nseq;
+ for (int i = startCol; i < endCol; i++)
+ {
+ ProfileI profile = profiles.get(i);
+ if (profile == null)
+ {
+ /*
+ * happens if sequences calculated over were
+ * shorter than alignment width
+ */
+ gaprow.annotations[i] = null;
+ return;
+ }
+
+ final int gapped = profile.getNonGapped();
+
+ String description = "" + gapped;
+
+ gaprow.annotations[i] = new Annotation("", description, '\0', gapped,
+ jalview.util.ColorUtils.bleachColour(Color.DARK_GRAY,
+ (float) scale * gapped));
+ }
+ }
+
+ /**
+ * Returns a tooltip showing either
+ * <ul>
+ * <li>the full profile (percentages of all residues present), if
+ * showSequenceLogo is true, or</li>
+ * <li>just the modal (most common) residue(s), if showSequenceLogo is
+ * false</li>
+ * </ul>
+ * Percentages are as a fraction of all sequence, or only ungapped sequences
+ * if ignoreGaps is true.
+ *
+ * @param profile
+ * @param pid
+ * @param showSequenceLogo
+ * @param ignoreGaps
+ * @param dp
+ * the number of decimal places to format percentages to
+ * @return
+ */
+ static String getTooltip(ProfileI profile, float pid,
+ boolean showSequenceLogo, boolean ignoreGaps, int dp)
+ {
+ ResidueCount counts = profile.getCounts();
+
+ String description = null;
+ if (counts != null && showSequenceLogo)
+ {
+ int normaliseBy = ignoreGaps ? profile.getNonGapped()
+ : profile.getHeight();
+ description = counts.getTooltip(normaliseBy, dp);
+ }
+ else
+ {
+ StringBuilder sb = new StringBuilder(64);
+ String maxRes = profile.getModalResidue();
+ if (maxRes.length() > 1)
+ {
+ sb.append("[").append(maxRes).append("]");
+ }
+ else
+ {
+ sb.append(maxRes);
+ }
+ if (maxRes.length() > 0)
+ {
+ sb.append(" ");
+ Format.appendPercentage(sb, pid, dp);
+ sb.append("%");
+ }
+ description = sb.toString();
+ }
+ return description;
+ }
+
+ /**
+ * Returns the sorted profile for the given consensus data. The returned array
+ * contains
+ *
+ * <pre>
+ * [profileType, numberOfValues, totalPercent, charValue1, percentage1, charValue2, percentage2, ...]
+ * in descending order of percentage value
+ * </pre>
+ *
+ * @param profile
+ * the data object from which to extract and sort values
+ * @param ignoreGaps
+ * if true, only non-gapped values are included in percentage
+ * calculations
+ * @return
+ */
+ public static int[] extractProfile(ProfileI profile, boolean ignoreGaps)
+ {
+ ResidueCount counts = profile.getCounts();
+ if (counts == null)
+ {
+ return null;
+ }
+
+ SymbolCounts symbolCounts = counts.getSymbolCounts();
+ char[] symbols = symbolCounts.symbols;
+ int[] values = symbolCounts.values;
+ QuickSort.sort(values, symbols);
+ int totalPercentage = 0;
+ final int divisor = ignoreGaps ? profile.getNonGapped()
+ : profile.getHeight();
+
+ /*
+ * traverse the arrays in reverse order (highest counts first)
+ */
+ int[] result = new int[3 + 2 * symbols.length];
+ int nextArrayPos = 3;
+ int nonZeroCount = 0;
+
+ for (int i = symbols.length - 1; i >= 0; i--)
+ {
+ int theChar = symbols[i];
+ int charCount = values[i];
+ final int percentage = (charCount * 100) / divisor;
+ if (percentage == 0)
+ {
+ /*
+ * this count (and any remaining) round down to 0% - discard
+ */
+ break;
+ }
+ nonZeroCount++;
+ result[nextArrayPos++] = theChar;
+ result[nextArrayPos++] = percentage;
+ totalPercentage += percentage;
+ }
+
+ /*
+ * truncate array if any zero values were discarded
+ */
+ if (nonZeroCount < symbols.length)
+ {
+ int[] tmp = new int[3 + 2 * nonZeroCount];
+ System.arraycopy(result, 0, tmp, 0, tmp.length);
+ result = tmp;
+ }
+
+ /*
+ * fill in 'header' values
+ */
+ result[0] = AlignmentAnnotation.SEQUENCE_PROFILE;
+ result[1] = nonZeroCount;
+ result[2] = totalPercentage;
+
+ return result;
+ }
+
+ /**
+ * Extract a sorted extract of cDNA codon profile data. The returned array
+ * contains
+ *
+ * <pre>
+ * [profileType, numberOfValues, totalPercentage, charValue1, percentage1, charValue2, percentage2, ...]
+ * in descending order of percentage value, where the character values encode codon triplets
+ * </pre>
+ *
+ * @param hashtable
+ * @return
+ */
+ public static int[] extractCdnaProfile(
+ Hashtable<String, Object> hashtable, boolean ignoreGaps)
+ {
+ // this holds #seqs, #ungapped, and then codon count, indexed by encoded
+ // codon triplet
+ int[] codonCounts = (int[]) hashtable.get(PROFILE);
+ int[] sortedCounts = new int[codonCounts.length - 2];
+ System.arraycopy(codonCounts, 2, sortedCounts, 0,
+ codonCounts.length - 2);
+
+ int[] result = new int[3 + 2 * sortedCounts.length];
+ // first value is just the type of profile data
+ result[0] = AlignmentAnnotation.CDNA_PROFILE;
+
+ char[] codons = new char[sortedCounts.length];
+ for (int i = 0; i < codons.length; i++)
+ {
+ codons[i] = (char) i;
+ }
+ QuickSort.sort(sortedCounts, codons);
+ int totalPercentage = 0;
+ int distinctValuesCount = 0;
+ int j = 3;
+ int divisor = ignoreGaps ? codonCounts[1] : codonCounts[0];
+ for (int i = codons.length - 1; i >= 0; i--)
+ {
+ final int codonCount = sortedCounts[i];
+ if (codonCount == 0)
+ {
+ break; // nothing else of interest here
+ }
+ final int percentage = codonCount * 100 / divisor;
+ if (percentage == 0)
+ {
+ /*
+ * this (and any remaining) values rounded down to 0 - discard
+ */
+ break;
+ }
+ distinctValuesCount++;
+ result[j++] = codons[i];
+ result[j++] = percentage;
+ totalPercentage += percentage;
+ }
+ result[2] = totalPercentage;
+
+ /*
+ * Just return the non-zero values
+ */
+ // todo next value is redundant if we limit the array to non-zero counts
+ result[1] = distinctValuesCount;
+ return Arrays.copyOfRange(result, 0, j);
+ }
+
+ /**
+ * Compute a consensus for the cDNA coding for a protein alignment.
+ *
+ * @param alignment
+ * the protein alignment (which should hold mappings to cDNA
+ * sequences)
+ * @param hconsensus
+ * the consensus data stores to be populated (one per column)
+ */
+ public static void calculateCdna(AlignmentI alignment,
+ Hashtable<String, Object>[] hconsensus)
+ {
+ final char gapCharacter = alignment.getGapCharacter();
+ List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
+ if (mappings == null || mappings.isEmpty())
+ {
+ return;
+ }