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