aa0deedbf6485797ef0023aa2c0e19dddc3c69d4
[jalview.git] / src / jalview / analysis / AAFrequency.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.analysis;
22
23 import jalview.datamodel.AlignedCodonFrame;
24 import jalview.datamodel.AlignmentAnnotation;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.Annotation;
27 import jalview.datamodel.Profile;
28 import jalview.datamodel.ProfileI;
29 import jalview.datamodel.Profiles;
30 import jalview.datamodel.ProfilesI;
31 import jalview.datamodel.ResidueCount;
32 import jalview.datamodel.ResidueCount.SymbolCounts;
33 import jalview.datamodel.SequenceI;
34 import jalview.ext.android.SparseIntArray;
35 import jalview.util.Comparison;
36 import jalview.util.Format;
37 import jalview.util.MappingUtils;
38 import jalview.util.QuickSort;
39
40 import java.awt.Color;
41 import java.util.Arrays;
42 import java.util.Hashtable;
43 import java.util.List;
44
45 /**
46  * Takes in a vector or array of sequences and column start and column end and
47  * returns a new Hashtable[] of size maxSeqLength, if Hashtable not supplied.
48  * This class is used extensively in calculating alignment colourschemes that
49  * depend on the amount of conservation in each alignment column.
50  * 
51  * @author $author$
52  * @version $Revision$
53  */
54 public class AAFrequency
55 {
56   public static final String PROFILE = "P";
57
58   /*
59    * Quick look-up of String value of char 'A' to 'Z'
60    */
61   private static final String[] CHARS = new String['Z' - 'A' + 1];
62
63   static
64   {
65     for (char c = 'A'; c <= 'Z'; c++)
66     {
67       CHARS[c - 'A'] = String.valueOf(c);
68     }
69   }
70
71   public static final ProfilesI calculate(List<SequenceI> list, int start,
72           int end)
73   {
74     return calculate(list, start, end, false);
75   }
76
77   public static final ProfilesI calculate(List<SequenceI> sequences,
78           int start, int end, boolean profile)
79   {
80     SequenceI[] seqs = new SequenceI[sequences.size()];
81     int width = 0;
82     synchronized (sequences)
83     {
84       for (int i = 0; i < sequences.size(); i++)
85       {
86         seqs[i] = sequences.get(i);
87         int length = seqs[i].getLength();
88         if (length > width)
89         {
90           width = length;
91         }
92       }
93
94       if (end >= width)
95       {
96         end = width;
97       }
98
99       ProfilesI reply = calculate(seqs, width, start, end, profile);
100       return reply;
101     }
102   }
103
104   /**
105    * Calculate the consensus symbol(s) for each column in the given range.
106    * 
107    * @param sequences
108    * @param width
109    *          the full width of the alignment
110    * @param start
111    *          start column (inclusive, base zero)
112    * @param end
113    *          end column (exclusive)
114    * @param saveFullProfile
115    *          if true, store all symbol counts
116    */
117   public static final ProfilesI calculate(final SequenceI[] sequences,
118           int width, int start, int end, boolean saveFullProfile)
119   {
120     // long now = System.currentTimeMillis();
121     int seqCount = sequences.length;
122     boolean nucleotide = false;
123     int nucleotideCount = 0;
124     int peptideCount = 0;
125
126     ProfileI[] result = new ProfileI[width];
127
128     for (int column = start; column < end; column++)
129     {
130       /*
131        * Apply a heuristic to detect nucleotide data (which can
132        * be counted in more compact arrays); here we test for
133        * more than 90% nucleotide; recheck every 10 columns in case
134        * of misleading data e.g. highly conserved Alanine in peptide!
135        * Mistakenly guessing nucleotide has a small performance cost,
136        * as it will result in counting in sparse arrays.
137        * Mistakenly guessing peptide has a small space cost, 
138        * as it will use a larger than necessary array to hold counts. 
139        */
140       if (nucleotideCount > 100 && column % 10 == 0)
141       {
142         nucleotide = (9 * peptideCount < nucleotideCount);
143       }
144       ResidueCount residueCounts = new ResidueCount(nucleotide);
145
146       for (int row = 0; row < seqCount; row++)
147       {
148         if (sequences[row] == null)
149         {
150           System.err.println(
151                   "WARNING: Consensus skipping null sequence - possible race condition.");
152           continue;
153         }
154         if (sequences[row].getLength() > column)
155         {
156           char c = sequences[row].getCharAt(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     float threshhold = 100;
256     if (consensus.getThreshold()!=null)
257     {
258       threshhold =  consensus.getThreshold().value;
259     }
260     for (int i = startCol; i < endCol; i++)
261     {
262       ProfileI profile = profiles.get(i);
263       if (profile == null)
264       {
265         /*
266          * happens if sequences calculated over were 
267          * shorter than alignment width
268          */
269         consensus.annotations[i] = null;
270         return;
271       }
272
273       final int dp = getPercentageDp(nseq);
274
275       float value = profile.getPercentageIdentity(ignoreGaps);
276
277       String description = getTooltip(profile, value, showSequenceLogo,
278               ignoreGaps, dp);
279
280       String modalResidue = profile.getModalResidue();
281       if ("".equals(modalResidue) || threshhold>value)
282       {
283         modalResidue = "-";
284       }
285       else if (modalResidue.length() > 1)
286       {
287         modalResidue = "+";
288       }
289       consensus.annotations[i] = new Annotation(modalResidue, description,
290               ' ', value);
291     }
292     // long elapsed = System.currentTimeMillis() - now;
293     // System.out.println(-elapsed);
294   }
295
296   /**
297    * Derive the gap count annotation row.
298    * 
299    * @param gaprow
300    *          the annotation row to add annotations to
301    * @param profiles
302    *          the source consensus data
303    * @param startCol
304    *          start column (inclusive)
305    * @param endCol
306    *          end column (exclusive)
307    */
308   public static void completeGapAnnot(AlignmentAnnotation gaprow,
309           ProfilesI profiles, int startCol, int endCol, long nseq)
310   {
311     if (gaprow == null || gaprow.annotations == null
312             || gaprow.annotations.length < endCol)
313     {
314       /*
315        * called with a bad alignment annotation row 
316        * wait for it to be initialised properly
317        */
318       return;
319     }
320     // always set ranges again
321     gaprow.graphMax = nseq;
322     gaprow.graphMin = 0;
323     double scale = 0.8 / nseq;
324     for (int i = startCol; i < endCol; i++)
325     {
326       ProfileI profile = profiles.get(i);
327       if (profile == null)
328       {
329         /*
330          * happens if sequences calculated over were 
331          * shorter than alignment width
332          */
333         gaprow.annotations[i] = null;
334         return;
335       }
336
337       final int gapped = profile.getNonGapped();
338
339       String description = "" + gapped;
340
341       gaprow.annotations[i] = new Annotation("", description, '\0', gapped,
342               jalview.util.ColorUtils.bleachColour(Color.DARK_GRAY,
343                       (float) scale * gapped));
344     }
345   }
346
347   /**
348    * Returns a tooltip showing either
349    * <ul>
350    * <li>the full profile (percentages of all residues present), if
351    * showSequenceLogo is true, or</li>
352    * <li>just the modal (most common) residue(s), if showSequenceLogo is
353    * false</li>
354    * </ul>
355    * Percentages are as a fraction of all sequence, or only ungapped sequences
356    * if ignoreGaps is true.
357    * 
358    * @param profile
359    * @param pid
360    * @param showSequenceLogo
361    * @param ignoreGaps
362    * @param dp
363    *          the number of decimal places to format percentages to
364    * @return
365    */
366   static String getTooltip(ProfileI profile, float pid,
367           boolean showSequenceLogo, boolean ignoreGaps, int dp)
368   {
369     ResidueCount counts = profile.getCounts();
370
371     String description = null;
372     if (counts != null && showSequenceLogo)
373     {
374       int normaliseBy = ignoreGaps ? profile.getNonGapped()
375               : profile.getHeight();
376       description = counts.getTooltip(normaliseBy, dp);
377     }
378     else
379     {
380       StringBuilder sb = new StringBuilder(64);
381       String maxRes = profile.getModalResidue();
382       if (maxRes.length() > 1)
383       {
384         sb.append("[").append(maxRes).append("]");
385       }
386       else
387       {
388         sb.append(maxRes);
389       }
390       if (maxRes.length() > 0)
391       {
392         sb.append(" ");
393         Format.appendPercentage(sb, pid, dp);
394         sb.append("%");
395       }
396       description = sb.toString();
397     }
398     return description;
399   }
400
401   /**
402    * Returns the sorted profile for the given consensus data. The returned array
403    * contains
404    * 
405    * <pre>
406    *    [profileType, numberOfValues, totalPercent, charValue1, percentage1, charValue2, percentage2, ...]
407    * in descending order of percentage value
408    * </pre>
409    * 
410    * @param profile
411    *          the data object from which to extract and sort values
412    * @param ignoreGaps
413    *          if true, only non-gapped values are included in percentage
414    *          calculations
415    * @return
416    */
417   public static int[] extractProfile(ProfileI profile, boolean ignoreGaps)
418   {
419     ResidueCount counts = profile.getCounts();
420     if (counts == null)
421     {
422       return null;
423     }
424
425     SymbolCounts symbolCounts = counts.getSymbolCounts();
426     char[] symbols = symbolCounts.symbols;
427     int[] values = symbolCounts.values;
428     QuickSort.sort(values, symbols);
429     int totalPercentage = 0;
430     final int divisor = ignoreGaps ? profile.getNonGapped()
431             : profile.getHeight();
432
433     /*
434      * traverse the arrays in reverse order (highest counts first)
435      */
436     int[] result = new int[3 + 2 * symbols.length];
437     int nextArrayPos = 3;
438     int nonZeroCount = 0;
439
440     for (int i = symbols.length - 1; i >= 0; i--)
441     {
442       int theChar = symbols[i];
443       int charCount = values[i];
444       final int percentage = (charCount * 100) / divisor;
445       if (percentage == 0)
446       {
447         /*
448          * this count (and any remaining) round down to 0% - discard
449          */
450         break;
451       }
452       nonZeroCount++;
453       result[nextArrayPos++] = theChar;
454       result[nextArrayPos++] = percentage;
455       totalPercentage += percentage;
456     }
457
458     /*
459      * truncate array if any zero values were discarded
460      */
461     if (nonZeroCount < symbols.length)
462     {
463       int[] tmp = new int[3 + 2 * nonZeroCount];
464       System.arraycopy(result, 0, tmp, 0, tmp.length);
465       result = tmp;
466     }
467
468     /*
469      * fill in 'header' values
470      */
471     result[0] = AlignmentAnnotation.SEQUENCE_PROFILE;
472     result[1] = nonZeroCount;
473     result[2] = totalPercentage;
474
475     return result;
476   }
477
478   /**
479    * Extract a sorted extract of cDNA codon profile data. The returned array
480    * contains
481    * 
482    * <pre>
483    *    [profileType, numberOfValues, totalPercentage, charValue1, percentage1, charValue2, percentage2, ...]
484    * in descending order of percentage value, where the character values encode codon triplets
485    * </pre>
486    * 
487    * @param hashtable
488    * @return
489    */
490   public static int[] extractCdnaProfile(
491           Hashtable<String, Object> hashtable, boolean ignoreGaps)
492   {
493     // this holds #seqs, #ungapped, and then codon count, indexed by encoded
494     // codon triplet
495     int[] codonCounts = (int[]) hashtable.get(PROFILE);
496     int[] sortedCounts = new int[codonCounts.length - 2];
497     System.arraycopy(codonCounts, 2, sortedCounts, 0,
498             codonCounts.length - 2);
499
500     int[] result = new int[3 + 2 * sortedCounts.length];
501     // first value is just the type of profile data
502     result[0] = AlignmentAnnotation.CDNA_PROFILE;
503
504     char[] codons = new char[sortedCounts.length];
505     for (int i = 0; i < codons.length; i++)
506     {
507       codons[i] = (char) i;
508     }
509     QuickSort.sort(sortedCounts, codons);
510     int totalPercentage = 0;
511     int distinctValuesCount = 0;
512     int j = 3;
513     int divisor = ignoreGaps ? codonCounts[1] : codonCounts[0];
514     for (int i = codons.length - 1; i >= 0; i--)
515     {
516       final int codonCount = sortedCounts[i];
517       if (codonCount == 0)
518       {
519         break; // nothing else of interest here
520       }
521       final int percentage = codonCount * 100 / divisor;
522       if (percentage == 0)
523       {
524         /*
525          * this (and any remaining) values rounded down to 0 - discard
526          */
527         break;
528       }
529       distinctValuesCount++;
530       result[j++] = codons[i];
531       result[j++] = percentage;
532       totalPercentage += percentage;
533     }
534     result[2] = totalPercentage;
535
536     /*
537      * Just return the non-zero values
538      */
539     // todo next value is redundant if we limit the array to non-zero counts
540     result[1] = distinctValuesCount;
541     return Arrays.copyOfRange(result, 0, j);
542   }
543
544   /**
545    * Compute a consensus for the cDNA coding for a protein alignment.
546    * 
547    * @param alignment
548    *          the protein alignment (which should hold mappings to cDNA
549    *          sequences)
550    * @param hconsensus
551    *          the consensus data stores to be populated (one per column)
552    */
553   public static void calculateCdna(AlignmentI alignment,
554           Hashtable<String, Object>[] hconsensus)
555   {
556     final char gapCharacter = alignment.getGapCharacter();
557     List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
558     if (mappings == null || mappings.isEmpty())
559     {
560       return;
561     }
562
563     int cols = alignment.getWidth();
564     for (int col = 0; col < cols; col++)
565     {
566       // todo would prefer a Java bean for consensus data
567       Hashtable<String, Object> columnHash = new Hashtable<>();
568       // #seqs, #ungapped seqs, counts indexed by (codon encoded + 1)
569       int[] codonCounts = new int[66];
570       codonCounts[0] = alignment.getSequences().size();
571       int ungappedCount = 0;
572       for (SequenceI seq : alignment.getSequences())
573       {
574         if (seq.getCharAt(col) == gapCharacter)
575         {
576           continue;
577         }
578         List<char[]> codons = MappingUtils.findCodonsFor(seq, col,
579                 mappings);
580         for (char[] codon : codons)
581         {
582           int codonEncoded = CodingUtils.encodeCodon(codon);
583           if (codonEncoded >= 0)
584           {
585             codonCounts[codonEncoded + 2]++;
586             ungappedCount++;
587             break;
588           }
589         }
590       }
591       codonCounts[1] = ungappedCount;
592       // todo: sort values here, save counts and codons?
593       columnHash.put(PROFILE, codonCounts);
594       hconsensus[col] = columnHash;
595     }
596   }
597
598   /**
599    * Derive displayable cDNA consensus annotation from computed consensus data.
600    * 
601    * @param consensusAnnotation
602    *          the annotation row to be populated for display
603    * @param consensusData
604    *          the computed consensus data
605    * @param showProfileLogo
606    *          if true show all symbols present at each position, else only the
607    *          modal value
608    * @param nseqs
609    *          the number of sequences in the alignment
610    */
611   public static void completeCdnaConsensus(
612           AlignmentAnnotation consensusAnnotation,
613           Hashtable<String, Object>[] consensusData,
614           boolean showProfileLogo, int nseqs)
615   {
616     if (consensusAnnotation == null
617             || consensusAnnotation.annotations == null
618             || consensusAnnotation.annotations.length < consensusData.length)
619     {
620       // called with a bad alignment annotation row - wait for it to be
621       // initialised properly
622       return;
623     }
624
625     // ensure codon triplet scales with font size
626     consensusAnnotation.scaleColLabel = true;
627     for (int col = 0; col < consensusData.length; col++)
628     {
629       Hashtable<String, Object> hci = consensusData[col];
630       if (hci == null)
631       {
632         // gapped protein column?
633         continue;
634       }
635       // array holds #seqs, #ungapped, then codon counts indexed by codon
636       final int[] codonCounts = (int[]) hci.get(PROFILE);
637       int totalCount = 0;
638
639       /*
640        * First pass - get total count and find the highest
641        */
642       final char[] codons = new char[codonCounts.length - 2];
643       for (int j = 2; j < codonCounts.length; j++)
644       {
645         final int codonCount = codonCounts[j];
646         codons[j - 2] = (char) (j - 2);
647         totalCount += codonCount;
648       }
649
650       /*
651        * Sort array of encoded codons by count ascending - so the modal value
652        * goes to the end; start by copying the count (dropping the first value)
653        */
654       int[] sortedCodonCounts = new int[codonCounts.length - 2];
655       System.arraycopy(codonCounts, 2, sortedCodonCounts, 0,
656               codonCounts.length - 2);
657       QuickSort.sort(sortedCodonCounts, codons);
658
659       int modalCodonEncoded = codons[codons.length - 1];
660       int modalCodonCount = sortedCodonCounts[codons.length - 1];
661       String modalCodon = String
662               .valueOf(CodingUtils.decodeCodon(modalCodonEncoded));
663       if (sortedCodonCounts.length > 1 && sortedCodonCounts[codons.length
664               - 2] == sortedCodonCounts[codons.length - 1])
665       {
666         /*
667          * two or more codons share the modal count
668          */
669         modalCodon = "+";
670       }
671       float pid = sortedCodonCounts[sortedCodonCounts.length - 1] * 100
672               / (float) totalCount;
673
674       /*
675        * todo ? Replace consensus hashtable with sorted arrays of codons and
676        * counts (non-zero only). Include total count in count array [0].
677        */
678
679       /*
680        * Scan sorted array backwards for most frequent values first. Show
681        * repeated values compactly.
682        */
683       StringBuilder mouseOver = new StringBuilder(32);
684       StringBuilder samePercent = new StringBuilder();
685       String percent = null;
686       String lastPercent = null;
687       int percentDecPl = getPercentageDp(nseqs);
688
689       for (int j = codons.length - 1; j >= 0; j--)
690       {
691         int codonCount = sortedCodonCounts[j];
692         if (codonCount == 0)
693         {
694           /*
695            * remaining codons are 0% - ignore, but finish off the last one if
696            * necessary
697            */
698           if (samePercent.length() > 0)
699           {
700             mouseOver.append(samePercent).append(": ").append(percent)
701                     .append("% ");
702           }
703           break;
704         }
705         int codonEncoded = codons[j];
706         final int pct = codonCount * 100 / totalCount;
707         String codon = String
708                 .valueOf(CodingUtils.decodeCodon(codonEncoded));
709         StringBuilder sb = new StringBuilder();
710         Format.appendPercentage(sb, pct, percentDecPl);
711         percent = sb.toString();
712         if (showProfileLogo || codonCount == modalCodonCount)
713         {
714           if (percent.equals(lastPercent) && j > 0)
715           {
716             samePercent.append(samePercent.length() == 0 ? "" : ", ");
717             samePercent.append(codon);
718           }
719           else
720           {
721             if (samePercent.length() > 0)
722             {
723               mouseOver.append(samePercent).append(": ").append(lastPercent)
724                       .append("% ");
725             }
726             samePercent.setLength(0);
727             samePercent.append(codon);
728           }
729           lastPercent = percent;
730         }
731       }
732
733       consensusAnnotation.annotations[col] = new Annotation(modalCodon,
734               mouseOver.toString(), ' ', pid);
735     }
736   }
737
738   /**
739    * Returns the number of decimal places to show for profile percentages. For
740    * less than 100 sequences, returns zero (the integer percentage value will be
741    * displayed). For 100-999 sequences, returns 1, for 1000-9999 returns 2, etc.
742    * 
743    * @param nseq
744    * @return
745    */
746   protected static int getPercentageDp(long nseq)
747   {
748     int scale = 0;
749     while (nseq >= 100)
750     {
751       scale++;
752       nseq /= 10;
753     }
754     return scale;
755   }
756 }