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