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