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