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