Merge branch 'develop' into update_212_Dec_merge_with_21125_chamges
[jalview.git] / src / jalview / analysis / AAFrequency.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
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.
11  *  
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.
16  * 
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.
20  */
21 package jalview.analysis;
22
23 import jalview.datamodel.AlignedCodonFrame;
24 import jalview.datamodel.AlignmentAnnotation;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.Annotation;
27 import jalview.datamodel.HiddenMarkovModel;
28 import jalview.datamodel.Profile;
29 import jalview.datamodel.ProfileI;
30 import jalview.datamodel.Profiles;
31 import jalview.datamodel.ProfilesI;
32 import jalview.datamodel.ResidueCount;
33 import jalview.datamodel.ResidueCount.SymbolCounts;
34 import jalview.datamodel.SequenceI;
35 import jalview.ext.android.SparseIntArray;
36 import jalview.schemes.ResidueProperties;
37 import jalview.util.Comparison;
38 import jalview.util.Format;
39 import jalview.util.MappingUtils;
40 import jalview.util.QuickSort;
41
42 import java.awt.Color;
43 import java.util.Arrays;
44 import java.util.Hashtable;
45 import java.util.List;
46
47 /**
48  * Takes in a vector or array of sequences and column start and column end and
49  * returns a new Hashtable[] of size maxSeqLength, if Hashtable not supplied.
50  * This class is used extensively in calculating alignment colourschemes that
51  * depend on the amount of conservation in each alignment column.
52  * 
53  */
54 public class AAFrequency
55 {
56   private static final double LOG2 = Math.log(2);
57
58   public static final String PROFILE = "P";
59
60   public static final ProfilesI calculate(List<SequenceI> list, int start,
61           int end)
62   {
63     return calculate(list, start, end, false);
64   }
65
66   public static final ProfilesI calculate(List<SequenceI> sequences,
67           int start, int end, boolean profile)
68   {
69     SequenceI[] seqs = new SequenceI[sequences.size()];
70     int width = 0;
71     synchronized (sequences)
72     {
73       for (int i = 0; i < sequences.size(); i++)
74       {
75         seqs[i] = sequences.get(i);
76         int length = seqs[i].getLength();
77         if (length > width)
78         {
79           width = length;
80         }
81       }
82
83       if (end >= width)
84       {
85         end = width;
86       }
87
88       ProfilesI reply = calculate(seqs, width, start, end, profile);
89       return reply;
90     }
91   }
92
93   /**
94    * Calculate the consensus symbol(s) for each column in the given range.
95    * 
96    * @param sequences
97    * @param width
98    *          the full width of the alignment
99    * @param start
100    *          start column (inclusive, base zero)
101    * @param end
102    *          end column (exclusive)
103    * @param saveFullProfile
104    *          if true, store all symbol counts
105    */
106   public static final ProfilesI calculate(final SequenceI[] sequences,
107           int width, int start, int end, boolean saveFullProfile)
108   {
109     // long now = System.currentTimeMillis();
110     int seqCount = sequences.length;
111     boolean nucleotide = false;
112     int nucleotideCount = 0;
113     int peptideCount = 0;
114
115     ProfileI[] result = new ProfileI[width];
116
117     for (int column = start; column < end; column++)
118     {
119       /*
120        * Apply a heuristic to detect nucleotide data (which can
121        * be counted in more compact arrays); here we test for
122        * more than 90% nucleotide; recheck every 10 columns in case
123        * of misleading data e.g. highly conserved Alanine in peptide!
124        * Mistakenly guessing nucleotide has a small performance cost,
125        * as it will result in counting in sparse arrays.
126        * Mistakenly guessing peptide has a small space cost, 
127        * as it will use a larger than necessary array to hold counts. 
128        */
129       if (nucleotideCount > 100 && column % 10 == 0)
130       {
131         nucleotide = (9 * peptideCount < nucleotideCount);
132       }
133       ResidueCount residueCounts = new ResidueCount(nucleotide);
134
135       for (int row = 0; row < seqCount; row++)
136       {
137         if (sequences[row] == null)
138         {
139           System.err.println(
140                   "WARNING: Consensus skipping null sequence - possible race condition.");
141           continue;
142         }
143         if (sequences[row].getLength() > column)
144         {
145           char c = sequences[row].getCharAt(column);
146           residueCounts.add(c);
147           if (Comparison.isNucleotide(c))
148           {
149             nucleotideCount++;
150           }
151           else if (!Comparison.isGap(c))
152           {
153             peptideCount++;
154           }
155         }
156         else
157         {
158           /*
159            * count a gap if the sequence doesn't reach this column
160            */
161           residueCounts.addGap();
162         }
163       }
164
165       int maxCount = residueCounts.getModalCount();
166       String maxResidue = residueCounts.getResiduesForCount(maxCount);
167       int gapCount = residueCounts.getGapCount();
168       ProfileI profile = new Profile(seqCount, gapCount, maxCount,
169               maxResidue);
170
171       if (saveFullProfile)
172       {
173         profile.setCounts(residueCounts);
174       }
175
176       result[column] = profile;
177     }
178     return new Profiles(result);
179     // long elapsed = System.currentTimeMillis() - now;
180     // System.out.println(elapsed);
181   }
182
183   /**
184    * Returns the full set of profiles for a hidden Markov model. The underlying
185    * data is the raw probabilities of a residue being emitted at each node,
186    * however the profiles returned by this function contain the percentage
187    * chance of a residue emission.
188    * 
189    * @param hmm
190    * @param width
191    *          The width of the Profile array (Profiles) to be returned.
192    * @param start
193    *          The alignment column on which the first profile is based.
194    * @param end
195    *          The alignment column on which the last profile is based.
196    * @param removeBelowBackground
197    *          if true, symbols with a match emission probability less than
198    *          background frequency are ignored
199    * @return
200    */
201   public static ProfilesI calculateHMMProfiles(final HiddenMarkovModel hmm,
202           int width, int start, int end, boolean removeBelowBackground,
203           boolean infoLetterHeight)
204   {
205     ProfileI[] result = new ProfileI[width];
206     char[] symbols = hmm.getSymbols().toCharArray();
207     int symbolCount = symbols.length;
208     for (int column = start; column < end; column++)
209     {
210       ResidueCount counts = new ResidueCount();
211       for (char symbol : symbols)
212       {
213         int value = getAnalogueCount(hmm, column, symbol,
214                 removeBelowBackground, infoLetterHeight);
215         counts.put(symbol, value);
216       }
217       int maxCount = counts.getModalCount();
218       String maxResidue = counts.getResiduesForCount(maxCount);
219       int gapCount = counts.getGapCount();
220       ProfileI profile = new Profile(symbolCount, gapCount, maxCount,
221               maxResidue);
222       profile.setCounts(counts);
223
224       result[column] = profile;
225     }
226     return new Profiles(result);
227   }
228
229   /**
230    * Make an estimate of the profile size we are going to compute i.e. how many
231    * different characters may be present in it. Overestimating has a cost of
232    * using more memory than necessary. Underestimating has a cost of needing to
233    * extend the SparseIntArray holding the profile counts.
234    * 
235    * @param profileSizes
236    *          counts of sizes of profiles so far encountered
237    * @return
238    */
239   static int estimateProfileSize(SparseIntArray profileSizes)
240   {
241     if (profileSizes.size() == 0)
242     {
243       return 4;
244     }
245
246     /*
247      * could do a statistical heuristic here e.g. 75%ile
248      * for now just return the largest value
249      */
250     return profileSizes.keyAt(profileSizes.size() - 1);
251   }
252
253   /**
254    * Derive the consensus annotations to be added to the alignment for display.
255    * This does not recompute the raw data, but may be called on a change in
256    * display options, such as 'ignore gaps', which may in turn result in a
257    * change in the derived values.
258    * 
259    * @param consensus
260    *          the annotation row to add annotations to
261    * @param profiles
262    *          the source consensus data
263    * @param startCol
264    *          start column (inclusive)
265    * @param endCol
266    *          end column (exclusive)
267    * @param ignoreGaps
268    *          if true, normalise residue percentages ignoring gaps
269    * @param showSequenceLogo
270    *          if true include all consensus symbols, else just show modal
271    *          residue
272    * @param nseq
273    *          number of sequences
274    */
275   public static void completeConsensus(AlignmentAnnotation consensus,
276           ProfilesI profiles, int startCol, int endCol, boolean ignoreGaps,
277           boolean showSequenceLogo, long nseq)
278   {
279     // long now = System.currentTimeMillis();
280     if (consensus == null || consensus.annotations == null
281             || consensus.annotations.length < endCol)
282     {
283       /*
284        * called with a bad alignment annotation row 
285        * wait for it to be initialised properly
286        */
287       return;
288     }
289
290     for (int i = startCol; i < endCol; i++)
291     {
292       ProfileI profile = profiles.get(i);
293       if (profile == null)
294       {
295         /*
296          * happens if sequences calculated over were 
297          * shorter than alignment width
298          */
299         consensus.annotations[i] = null;
300         return;
301       }
302
303       final int dp = getPercentageDp(nseq);
304
305       float value = profile.getPercentageIdentity(ignoreGaps);
306
307       String description = getTooltip(profile, value, showSequenceLogo,
308               ignoreGaps, dp);
309
310       String modalResidue = profile.getModalResidue();
311       if ("".equals(modalResidue))
312       {
313         modalResidue = "-";
314       }
315       else if (modalResidue.length() > 1)
316       {
317         modalResidue = "+";
318       }
319       consensus.annotations[i] = new Annotation(modalResidue, description,
320               ' ', value);
321     }
322     // long elapsed = System.currentTimeMillis() - now;
323     // System.out.println(-elapsed);
324   }
325
326   /**
327    * Derive the information annotations to be added to the alignment for
328    * display. This does not recompute the raw data, but may be called on a
329    * change in display options, such as 'ignore below background frequency',
330    * which may in turn result in a change in the derived values.
331    * 
332    * @param information
333    *          the annotation row to add annotations to
334    * @param profiles
335    *          the source information data
336    * @param startCol
337    *          start column (inclusive)
338    * @param endCol
339    *          end column (exclusive)
340    * @param ignoreGaps
341    *          if true, normalise residue percentages
342    * @param showSequenceLogo
343    *          if true include all information symbols, else just show modal
344    *          residue
345    */
346   public static float completeInformation(AlignmentAnnotation information,
347           ProfilesI profiles, int startCol, int endCol)
348   {
349     // long now = System.currentTimeMillis();
350     if (information == null || information.annotations == null)
351     {
352       /*
353        * called with a bad alignment annotation row 
354        * wait for it to be initialised properly
355        */
356       return 0;
357     }
358
359     float max = 0f;
360     SequenceI hmmSeq = information.sequenceRef;
361
362     int seqLength = hmmSeq.getLength();
363     if (information.annotations.length < seqLength)
364     {
365       return 0;
366     }
367
368     HiddenMarkovModel hmm = hmmSeq.getHMM();
369
370     for (int column = startCol; column < endCol; column++)
371     {
372       if (column >= seqLength)
373       {
374         // hmm consensus sequence is shorter than the alignment
375         break;
376       }
377       
378       float value = hmm.getInformationContent(column);
379       boolean isNaN = Float.isNaN(value);
380       if (!isNaN)
381       {
382         max = Math.max(max, value);
383       }
384
385       String description = isNaN ? null
386               : String.format("%.4f bits", value);
387       information.annotations[column] = new Annotation(
388               Character.toString(
389                       Character.toUpperCase(hmmSeq.getCharAt(column))),
390               description, ' ', value);
391     }
392
393     information.graphMax = max;
394     return max;
395   }
396
397   /**
398    * Derive the occupancy count annotation
399    * 
400    * @param occupancy
401    *          the annotation row to add annotations to
402    * @param profiles
403    *          the source consensus data
404    * @param startCol
405    *          start column (inclusive)
406    * @param endCol
407    *          end column (exclusive)
408    */
409   public static void completeGapAnnot(AlignmentAnnotation occupancy,
410           ProfilesI profiles, int startCol, int endCol, long nseq)
411   {
412     if (occupancy == null || occupancy.annotations == null
413             || occupancy.annotations.length < endCol)
414     {
415       /*
416        * called with a bad alignment annotation row 
417        * wait for it to be initialised properly
418        */
419       return;
420     }
421     // always set ranges again
422     occupancy.graphMax = nseq;
423     occupancy.graphMin = 0;
424     double scale = 0.8 / nseq;
425     for (int i = startCol; i < endCol; i++)
426     {
427       ProfileI profile = profiles.get(i);
428       if (profile == null)
429       {
430         /*
431          * happens if sequences calculated over were 
432          * shorter than alignment width
433          */
434         occupancy.annotations[i] = null;
435         return;
436       }
437
438       final int gapped = profile.getNonGapped();
439
440       String description = "" + gapped;
441
442       occupancy.annotations[i] = new Annotation("", description, '\0',
443               gapped,
444               jalview.util.ColorUtils.bleachColour(Color.DARK_GRAY,
445                       (float) scale * gapped));
446     }
447   }
448
449   /**
450    * Returns a tooltip showing either
451    * <ul>
452    * <li>the full profile (percentages of all residues present), if
453    * showSequenceLogo is true, or</li>
454    * <li>just the modal (most common) residue(s), if showSequenceLogo is
455    * false</li>
456    * </ul>
457    * Percentages are as a fraction of all sequence, or only ungapped sequences
458    * if ignoreGaps is true.
459    * 
460    * @param profile
461    * @param pid
462    * @param showSequenceLogo
463    * @param ignoreGaps
464    * @param dp
465    *          the number of decimal places to format percentages to
466    * @return
467    */
468   static String getTooltip(ProfileI profile, float pid,
469           boolean showSequenceLogo, boolean ignoreGaps, int dp)
470   {
471     ResidueCount counts = profile.getCounts();
472
473     String description = null;
474     if (counts != null && showSequenceLogo)
475     {
476       int normaliseBy = ignoreGaps ? profile.getNonGapped()
477               : profile.getHeight();
478       description = counts.getTooltip(normaliseBy, dp);
479     }
480     else
481     {
482       StringBuilder sb = new StringBuilder(64);
483       String maxRes = profile.getModalResidue();
484       if (maxRes.length() > 1)
485       {
486         sb.append("[").append(maxRes).append("]");
487       }
488       else
489       {
490         sb.append(maxRes);
491       }
492       if (maxRes.length() > 0)
493       {
494         sb.append(" ");
495         Format.appendPercentage(sb, pid, dp);
496         sb.append("%");
497       }
498       description = sb.toString();
499     }
500     return description;
501   }
502
503   /**
504    * Returns the sorted profile for the given consensus data. The returned array
505    * contains
506    * 
507    * <pre>
508    *    [profileType, numberOfValues, totalPercent, charValue1, percentage1, charValue2, percentage2, ...]
509    * in descending order of percentage value
510    * </pre>
511    * 
512    * @param profile
513    *          the data object from which to extract and sort values
514    * @param ignoreGaps
515    *          if true, only non-gapped values are included in percentage
516    *          calculations
517    * @return
518    */
519   public static int[] extractProfile(ProfileI profile, boolean ignoreGaps)
520   {
521     ResidueCount counts = profile.getCounts();
522     if (counts == null)
523     {
524       return null;
525     }
526
527     SymbolCounts symbolCounts = counts.getSymbolCounts();
528     char[] symbols = symbolCounts.symbols;
529     int[] values = symbolCounts.values;
530     QuickSort.sort(values, symbols);
531     int totalPercentage = 0;
532     final int divisor = ignoreGaps ? profile.getNonGapped()
533             : profile.getHeight();
534
535     /*
536      * traverse the arrays in reverse order (highest counts first)
537      */
538     int[] result = new int[3 + 2 * symbols.length];
539     int nextArrayPos = 3;
540     int nonZeroCount = 0;
541
542     for (int i = symbols.length - 1; i >= 0; i--)
543     {
544       int theChar = symbols[i];
545       int charCount = values[i];
546       final int percentage = (charCount * 100) / divisor;
547       if (percentage == 0)
548       {
549         /*
550          * this count (and any remaining) round down to 0% - discard
551          */
552         break;
553       }
554       nonZeroCount++;
555       result[nextArrayPos++] = theChar;
556       result[nextArrayPos++] = percentage;
557       totalPercentage += percentage;
558     }
559
560     /*
561      * truncate array if any zero values were discarded
562      */
563     if (nonZeroCount < symbols.length)
564     {
565       int[] tmp = new int[3 + 2 * nonZeroCount];
566       System.arraycopy(result, 0, tmp, 0, tmp.length);
567       result = tmp;
568     }
569
570     /*
571      * fill in 'header' values
572      */
573     result[0] = AlignmentAnnotation.SEQUENCE_PROFILE;
574     result[1] = nonZeroCount;
575     result[2] = totalPercentage;
576
577     return result;
578   }
579
580
581   /**
582    * Extract a sorted extract of cDNA codon profile data. The returned array
583    * contains
584    * 
585    * <pre>
586    *    [profileType, numberOfValues, totalPercentage, charValue1, percentage1, charValue2, percentage2, ...]
587    * in descending order of percentage value, where the character values encode codon triplets
588    * </pre>
589    * 
590    * @param hashtable
591    * @return
592    */
593   public static int[] extractCdnaProfile(
594           Hashtable<String, Object> hashtable, boolean ignoreGaps)
595   {
596     // this holds #seqs, #ungapped, and then codon count, indexed by encoded
597     // codon triplet
598     int[] codonCounts = (int[]) hashtable.get(PROFILE);
599     int[] sortedCounts = new int[codonCounts.length - 2];
600     System.arraycopy(codonCounts, 2, sortedCounts, 0,
601             codonCounts.length - 2);
602
603     int[] result = new int[3 + 2 * sortedCounts.length];
604     // first value is just the type of profile data
605     result[0] = AlignmentAnnotation.CDNA_PROFILE;
606
607     char[] codons = new char[sortedCounts.length];
608     for (int i = 0; i < codons.length; i++)
609     {
610       codons[i] = (char) i;
611     }
612     QuickSort.sort(sortedCounts, codons);
613     int totalPercentage = 0;
614     int distinctValuesCount = 0;
615     int j = 3;
616     int divisor = ignoreGaps ? codonCounts[1] : codonCounts[0];
617     for (int i = codons.length - 1; i >= 0; i--)
618     {
619       final int codonCount = sortedCounts[i];
620       if (codonCount == 0)
621       {
622         break; // nothing else of interest here
623       }
624       final int percentage = codonCount * 100 / divisor;
625       if (percentage == 0)
626       {
627         /*
628          * this (and any remaining) values rounded down to 0 - discard
629          */
630         break;
631       }
632       distinctValuesCount++;
633       result[j++] = codons[i];
634       result[j++] = percentage;
635       totalPercentage += percentage;
636     }
637     result[2] = totalPercentage;
638
639     /*
640      * Just return the non-zero values
641      */
642     // todo next value is redundant if we limit the array to non-zero counts
643     result[1] = distinctValuesCount;
644     return Arrays.copyOfRange(result, 0, j);
645   }
646
647   /**
648    * Compute a consensus for the cDNA coding for a protein alignment.
649    * 
650    * @param alignment
651    *          the protein alignment (which should hold mappings to cDNA
652    *          sequences)
653    * @param hconsensus
654    *          the consensus data stores to be populated (one per column)
655    */
656   public static void calculateCdna(AlignmentI alignment,
657           Hashtable<String, Object>[] hconsensus)
658   {
659     final char gapCharacter = alignment.getGapCharacter();
660     List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
661     if (mappings == null || mappings.isEmpty())
662     {
663       return;
664     }
665
666     int cols = alignment.getWidth();
667     for (int col = 0; col < cols; col++)
668     {
669       // todo would prefer a Java bean for consensus data
670       Hashtable<String, Object> columnHash = new Hashtable<>();
671       // #seqs, #ungapped seqs, counts indexed by (codon encoded + 1)
672       int[] codonCounts = new int[66];
673       codonCounts[0] = alignment.getSequences().size();
674       int ungappedCount = 0;
675       for (SequenceI seq : alignment.getSequences())
676       {
677         if (seq.getCharAt(col) == gapCharacter)
678         {
679           continue;
680         }
681         List<char[]> codons = MappingUtils.findCodonsFor(seq, col,
682                 mappings);
683         for (char[] codon : codons)
684         {
685           int codonEncoded = CodingUtils.encodeCodon(codon);
686           if (codonEncoded >= 0)
687           {
688             codonCounts[codonEncoded + 2]++;
689             ungappedCount++;
690             break;
691           }
692         }
693       }
694       codonCounts[1] = ungappedCount;
695       // todo: sort values here, save counts and codons?
696       columnHash.put(PROFILE, codonCounts);
697       hconsensus[col] = columnHash;
698     }
699   }
700
701   /**
702    * Derive displayable cDNA consensus annotation from computed consensus data.
703    * 
704    * @param consensusAnnotation
705    *          the annotation row to be populated for display
706    * @param consensusData
707    *          the computed consensus data
708    * @param showProfileLogo
709    *          if true show all symbols present at each position, else only the
710    *          modal value
711    * @param nseqs
712    *          the number of sequences in the alignment
713    */
714   public static void completeCdnaConsensus(
715           AlignmentAnnotation consensusAnnotation,
716           Hashtable<String, Object>[] consensusData,
717           boolean showProfileLogo, int nseqs)
718   {
719     if (consensusAnnotation == null
720             || consensusAnnotation.annotations == null
721             || consensusAnnotation.annotations.length < consensusData.length)
722     {
723       // called with a bad alignment annotation row - wait for it to be
724       // initialised properly
725       return;
726     }
727
728     // ensure codon triplet scales with font size
729     consensusAnnotation.scaleColLabel = true;
730     for (int col = 0; col < consensusData.length; col++)
731     {
732       Hashtable<String, Object> hci = consensusData[col];
733       if (hci == null)
734       {
735         // gapped protein column?
736         continue;
737       }
738       // array holds #seqs, #ungapped, then codon counts indexed by codon
739       final int[] codonCounts = (int[]) hci.get(PROFILE);
740       int totalCount = 0;
741
742       /*
743        * First pass - get total count and find the highest
744        */
745       final char[] codons = new char[codonCounts.length - 2];
746       for (int j = 2; j < codonCounts.length; j++)
747       {
748         final int codonCount = codonCounts[j];
749         codons[j - 2] = (char) (j - 2);
750         totalCount += codonCount;
751       }
752
753       /*
754        * Sort array of encoded codons by count ascending - so the modal value
755        * goes to the end; start by copying the count (dropping the first value)
756        */
757       int[] sortedCodonCounts = new int[codonCounts.length - 2];
758       System.arraycopy(codonCounts, 2, sortedCodonCounts, 0,
759               codonCounts.length - 2);
760       QuickSort.sort(sortedCodonCounts, codons);
761
762       int modalCodonEncoded = codons[codons.length - 1];
763       int modalCodonCount = sortedCodonCounts[codons.length - 1];
764       String modalCodon = String
765               .valueOf(CodingUtils.decodeCodon(modalCodonEncoded));
766       if (sortedCodonCounts.length > 1 && sortedCodonCounts[codons.length
767               - 2] == sortedCodonCounts[codons.length - 1])
768       {
769         /*
770          * two or more codons share the modal count
771          */
772         modalCodon = "+";
773       }
774       float pid = sortedCodonCounts[sortedCodonCounts.length - 1] * 100
775               / (float) totalCount;
776
777       /*
778        * todo ? Replace consensus hashtable with sorted arrays of codons and
779        * counts (non-zero only). Include total count in count array [0].
780        */
781
782       /*
783        * Scan sorted array backwards for most frequent values first. Show
784        * repeated values compactly.
785        */
786       StringBuilder mouseOver = new StringBuilder(32);
787       StringBuilder samePercent = new StringBuilder();
788       String percent = null;
789       String lastPercent = null;
790       int percentDecPl = getPercentageDp(nseqs);
791
792       for (int j = codons.length - 1; j >= 0; j--)
793       {
794         int codonCount = sortedCodonCounts[j];
795         if (codonCount == 0)
796         {
797           /*
798            * remaining codons are 0% - ignore, but finish off the last one if
799            * necessary
800            */
801           if (samePercent.length() > 0)
802           {
803             mouseOver.append(samePercent).append(": ").append(percent)
804                     .append("% ");
805           }
806           break;
807         }
808         int codonEncoded = codons[j];
809         final int pct = codonCount * 100 / totalCount;
810         String codon = String
811                 .valueOf(CodingUtils.decodeCodon(codonEncoded));
812         StringBuilder sb = new StringBuilder();
813         Format.appendPercentage(sb, pct, percentDecPl);
814         percent = sb.toString();
815         if (showProfileLogo || codonCount == modalCodonCount)
816         {
817           if (percent.equals(lastPercent) && j > 0)
818           {
819             samePercent.append(samePercent.length() == 0 ? "" : ", ");
820             samePercent.append(codon);
821           }
822           else
823           {
824             if (samePercent.length() > 0)
825             {
826               mouseOver.append(samePercent).append(": ").append(lastPercent)
827                       .append("% ");
828             }
829             samePercent.setLength(0);
830             samePercent.append(codon);
831           }
832           lastPercent = percent;
833         }
834       }
835
836       consensusAnnotation.annotations[col] = new Annotation(modalCodon,
837               mouseOver.toString(), ' ', pid);
838     }
839   }
840
841   /**
842    * Returns the number of decimal places to show for profile percentages. For
843    * less than 100 sequences, returns zero (the integer percentage value will be
844    * displayed). For 100-999 sequences, returns 1, for 1000-9999 returns 2, etc.
845    * 
846    * @param nseq
847    * @return
848    */
849   protected static int getPercentageDp(long nseq)
850   {
851     int scale = 0;
852     while (nseq >= 100)
853     {
854       scale++;
855       nseq /= 10;
856     }
857     return scale;
858   }
859
860   /**
861    * Returns the sorted HMM profile for the given column of the alignment. The
862    * returned array contains
863    * 
864    * <pre>
865    *    [profileType=0, numberOfValues, 100, charValue1, percentage1, charValue2, percentage2, ...]
866    * in descending order of percentage value
867    * </pre>
868    * 
869    * @param hmm
870    * @param column
871    * @param removeBelowBackground
872    *          if true, ignores residues with probability less than their
873    *          background frequency
874    * @param infoHeight
875    *          if true, uses the log ratio 'information' measure to scale the
876    *          value
877    * @return
878    */
879   public static int[] extractHMMProfile(HiddenMarkovModel hmm, int column,
880           boolean removeBelowBackground, boolean infoHeight)
881   {
882     if (hmm == null)
883     {
884       return null;
885     }
886     String alphabet = hmm.getSymbols();
887     int size = alphabet.length();
888     char symbols[] = new char[size];
889     int values[] = new int[size];
890     int totalCount = 0;
891
892     for (int i = 0; i < size; i++)
893     {
894       char symbol = alphabet.charAt(i);
895       symbols[i] = symbol;
896       int value = getAnalogueCount(hmm, column, symbol,
897               removeBelowBackground, infoHeight);
898       values[i] = value;
899       totalCount += value;
900     }
901
902     /*
903      * sort symbols by increasing emission probability
904      */
905     QuickSort.sort(values, symbols);
906
907     int[] profile = new int[3 + size * 2];
908
909     profile[0] = AlignmentAnnotation.SEQUENCE_PROFILE;
910     profile[1] = size;
911     profile[2] = 100;
912
913     /*
914      * order symbol/count profile by decreasing emission probability
915      */
916     if (totalCount != 0)
917     {
918       int arrayPos = 3;
919       for (int k = size - 1; k >= 0; k--)
920       {
921         Float percentage;
922         int value = values[k];
923         if (removeBelowBackground)
924         {
925           percentage = ((float) value) / totalCount * 100f;
926         }
927         else
928         {
929           percentage = value / 100f;
930         }
931         int intPercent = Math.round(percentage);
932         profile[arrayPos] = symbols[k];
933         profile[arrayPos + 1] = intPercent;
934         arrayPos += 2;
935       }
936     }
937     return profile;
938   }
939
940   /**
941    * Converts the emission probability of a residue at a column in the alignment
942    * to a 'count', suitable for rendering as an annotation value
943    * 
944    * @param hmm
945    * @param column
946    * @param symbol
947    * @param removeBelowBackground
948    *          if true, returns 0 for any symbol with a match emission
949    *          probability less than the background frequency
950    * @infoHeight if true, uses the log ratio 'information content' to scale the
951    *             value
952    * @return
953    */
954   static int getAnalogueCount(HiddenMarkovModel hmm, int column,
955           char symbol, boolean removeBelowBackground, boolean infoHeight)
956   {
957     double value = hmm.getMatchEmissionProbability(column, symbol);
958     double freq = ResidueProperties.backgroundFrequencies
959             .get(hmm.getAlphabetType()).get(symbol);
960     if (value < freq && removeBelowBackground)
961     {
962       return 0;
963     }
964
965     if (infoHeight)
966     {
967       value = value * (Math.log(value / freq) / LOG2);
968     }
969
970     value = value * 10000d;
971     return Math.round((float) value);
972   }
973 }