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