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