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