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