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