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