Clover icon

Coverage Report

  1. Project Clover database Mon Nov 18 2024 09:38:20 GMT
  2. Package jalview.analysis

File AAFrequency.java

 

Coverage histogram

../../img/srcFileCovDistChart9.png
7% of files have more coverage

Code metrics

152
318
18
1
976
620
112
0.35
17.67
18
6.22

Classes

Class Line # Actions
AAFrequency 55 318 112
0.8504098785%
 

Contributing tests

This file is covered by 97 tests. .

Source view

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