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