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