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