2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
21 package jalview.analysis;
23 import jalview.datamodel.AlignedCodonFrame;
24 import jalview.datamodel.AlignmentAnnotation;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.Annotation;
27 import jalview.datamodel.SequenceI;
28 import jalview.ext.android.SparseIntArray;
29 import jalview.util.Format;
30 import jalview.util.MappingUtils;
31 import jalview.util.QuickSort;
33 import java.util.Arrays;
34 import java.util.Hashtable;
35 import java.util.List;
38 * Takes in a vector or array of sequences and column start and column end and
39 * returns a new Hashtable[] of size maxSeqLength, if Hashtable not supplied.
40 * This class is used extensively in calculating alignment colourschemes that
41 * depend on the amount of conservation in each alignment column.
46 public class AAFrequency
48 private static final int TO_UPPER_CASE = 'A' - 'a'; // -32
50 public static final String MAXCOUNT = "C";
52 public static final String MAXRESIDUE = "R";
54 public static final String PID_GAPS = "G";
56 public static final String PID_NOGAPS = "N";
58 public static final String PROFILE = "P";
60 public static final String ENCODED_CHARS = "E";
63 * Quick look-up of String value of char 'A' to 'Z'
65 private static final String[] CHARS = new String['Z' - 'A' + 1];
69 for (char c = 'A'; c <= 'Z'; c++)
71 CHARS[c - 'A'] = String.valueOf(c);
75 public static final Hashtable[] calculate(List<SequenceI> list,
78 return calculate(list, start, end, false);
81 public static final Hashtable[] calculate(List<SequenceI> sequences,
82 int start, int end, boolean profile)
84 SequenceI[] seqs = new SequenceI[sequences.size()];
86 synchronized (sequences)
88 for (int i = 0; i < sequences.size(); i++)
90 seqs[i] = sequences.get(i);
91 if (seqs[i].getLength() > width)
93 width = seqs[i].getLength();
97 Hashtable[] reply = new Hashtable[width];
104 calculate(seqs, start, end, reply, profile);
109 public static final void calculate(SequenceI[] sequences, int start,
110 int end, Hashtable[] result, boolean profile)
112 // long now = System.currentTimeMillis();
113 Hashtable residueHash;
114 int seqCount = sequences.length;
116 SparseIntArray profileSizes = new SparseIntArray();
118 for (int column = start; column < end; column++)
120 residueHash = new Hashtable();
122 String maxResidue = "";
124 // int [] values = new int[255];
125 int guessProfileSize = estimateProfileSize(profileSizes);
126 SparseIntArray values = new SparseIntArray(guessProfileSize);
128 for (int row = 0; row < seqCount; row++)
130 if (sequences[row] == null)
133 .println("WARNING: Consensus skipping null sequence - possible race condition.");
136 char[] seq = sequences[row].getSequence();
137 if (seq.length > column)
141 if (c == '.' || c == ' ')
149 // values.put('-', values.get('-') + 1);
150 values.increment('-');
153 else if ('a' <= c && c <= 'z')
160 // values.put(c, values.get(c) + 1);
166 // values.put('-', values.get('-') + 1);
167 values.increment('-');
172 maxResidue = String.valueOf(c);
177 // iterate over values keys not alphabet
178 // for (int v = 'A'; v <= 'Z'; v++)
179 for (int k = 0; k < values.size(); k++)
181 int v = values.keyAt(k);
182 int count = values.valueAt(k); // values[v];
183 if (count < 1 || count < maxCount)
188 if (count > maxCount)
190 maxResidue = String.valueOf((char) v);// CHARS[v - 'A'];
192 else if (count == maxCount)
194 maxResidue += String.valueOf((char) v); // CHARS[v - 'A'];
199 if (maxResidue.length() == 0)
205 // residueHash.put(PROFILE, new int[][] { values,
206 // new int[] { jSize, nongap } });
207 residueHash.put(PROFILE, new Profile(values, seqCount, nongap));
209 residueHash.put(MAXCOUNT, new Integer(maxCount));
210 residueHash.put(MAXRESIDUE, maxResidue);
212 float percentage = ((float) maxCount * 100) / seqCount;
213 residueHash.put(PID_GAPS, new Float(percentage));
217 // calculate for non-gapped too
218 percentage = ((float) maxCount * 100) / nongap;
220 residueHash.put(PID_NOGAPS, new Float(percentage));
222 result[column] = residueHash;
224 profileSizes.increment(values.size());
226 // long elapsed = System.currentTimeMillis() - now;
227 // System.out.println(elapsed);
231 * Make an estimate of the profile size we are going to compute i.e. how many
232 * different characters may be present in it. Overestimating has a cost of
233 * using more memory than necessary. Underestimating has a cost of needing to
234 * extend the SparseIntArray holding the profile counts.
236 * @param profileSizes
237 * counts of sizes of profiles so far encountered
240 static int estimateProfileSize(SparseIntArray profileSizes)
242 if (profileSizes.size() == 0)
248 * could do a statistical heuristic here e.g. 75%ile
249 * for now just return the largest value
251 return profileSizes.keyAt(profileSizes.size() - 1);
255 * Compute all or part of the annotation row from the given consensus
259 * - pre-allocated annotation row
263 * @param ignoreGapsInConsensusCalculation
264 * @param includeAllConsSymbols
267 public static void completeConsensus(AlignmentAnnotation consensus,
268 Hashtable[] hconsensus, int iStart, int width,
269 boolean ignoreGapsInConsensusCalculation,
270 boolean includeAllConsSymbols, long nseq)
272 completeConsensus(consensus, hconsensus, iStart, width,
273 ignoreGapsInConsensusCalculation, includeAllConsSymbols, null,
278 * Derive the consensus annotations to be added to the alignment for display.
279 * This does not recompute the raw data, but may be called on a change in
280 * display options, such as 'show logo', which may in turn result in a change
281 * in the derived values.
284 * the annotation row to add annotations to
286 * the source consensus data
291 * @param ignoreGapsInConsensusCalculation
292 * if true, use the consensus calculated ignoring gaps
293 * @param includeAllConsSymbols
294 * if true include all consensus symbols, else just show modal
298 * number of sequences
300 public static void completeConsensus(AlignmentAnnotation consensus,
301 Hashtable[] hconsensus, int iStart, int width,
302 boolean ignoreGapsInConsensusCalculation,
303 boolean includeAllConsSymbols, char[] alphabet, long nseq)
305 // long now = System.currentTimeMillis();
306 if (consensus == null || consensus.annotations == null
307 || consensus.annotations.length < width)
309 // called with a bad alignment annotation row - wait for it to be
310 // initialised properly
314 final Format fmt = getPercentageFormat(nseq);
316 for (int i = iStart; i < width; i++)
319 if (i >= hconsensus.length || ((hci = hconsensus[i]) == null))
321 // happens if sequences calculated over were shorter than alignment
323 consensus.annotations[i] = null;
326 Float fv = (Float) hci
327 .get(ignoreGapsInConsensusCalculation ? PID_NOGAPS : PID_GAPS);
330 consensus.annotations[i] = null;
331 // data has changed below us .. give up and
334 float value = fv.floatValue();
335 String maxRes = hci.get(AAFrequency.MAXRESIDUE).toString();
336 StringBuilder mouseOver = new StringBuilder(64);
337 if (maxRes.length() > 1)
339 mouseOver.append("[").append(maxRes).append("] ");
344 mouseOver.append(hci.get(AAFrequency.MAXRESIDUE) + " ");
346 // int[][] profile = (int[][]) hci.get(AAFrequency.PROFILE);
347 Profile profile = (Profile) hci.get(AAFrequency.PROFILE);
348 if (profile != null && includeAllConsSymbols)
350 int sequenceCount = profile.height;// profile[1][0];
351 int nonGappedCount = profile.nonGapped;// [1][1];
352 int normalisedBy = ignoreGapsInConsensusCalculation ? nonGappedCount
354 mouseOver.setLength(0);
355 // TODO do this sort once only in calculate()?
356 // char[][] ca = new char[profile[0].length][];
357 // /int length = profile[0].length;
358 int length = profile.profile.size();
359 char[] ca = new char[length];
360 // float[] vl = new float[length];
361 int[] vl = new int[length];
362 for (int c = 0; c < ca.length; c++)
364 int theChar = profile.profile.keyAt(c);
365 ca[c] = (char) theChar;// c;
366 // ca[c] = new char[]
368 vl[c] = profile.profile.valueAt(c);// profile[0][c];
372 * sort characters into ascending order of their counts
374 QuickSort.sort(vl, ca);
377 * traverse in reverse order (highest count first) to build tooltip
379 // for (int p = 0, c = ca.length - 1; profile[0][ca[c]] > 0; c--)
380 for (int p = 0, c = ca.length - 1; c >= 0; c--)
382 final char residue = ca[c];
385 // float tval = profile[0][residue] * 100f / normalisedBy;
386 // float tval = profile[0][residue] * 100f / normalisedBy;
387 float tval = (vl[c] * 100f) / normalisedBy;
389 .append((((p == 0) ? "" : "; ")))
392 .append(((fmt != null) ? fmt.form(tval) : ((int) tval)))
401 (((fmt != null) ? fmt.form(value) : ((int) value))))
404 consensus.annotations[i] = new Annotation(maxRes,
405 mouseOver.toString(), ' ', value);
407 // long elapsed = System.currentTimeMillis() - now;
408 // System.out.println(-elapsed);
412 * Returns a Format designed to show all significant figures for profile
413 * percentages. For less than 100 sequences, returns null (the integer
414 * percentage value will be displayed). For 100-999 sequences, returns "%3.1f"
419 protected static Format getPercentageFormat(long nseq)
427 return scale <= 1 ? null : new Format("%3." + (scale - 1) + "f");
431 * Returns the sorted profile for the given consensus data. The returned array
435 * [profileType, numberOfValues, nonGapCount, charValue1, percentage1, charValue2, percentage2, ...]
436 * in descending order of percentage value
440 * the data table from which to extract and sort values
442 * if true, only non-gapped values are included in percentage
446 public static int[] extractProfile(Hashtable hconsensus,
449 int[] rtnval = new int[64];
450 // int[][] profile = (int[][]) hconsensus.get(AAFrequency.PROFILE);
451 Profile profile = (Profile) hconsensus.get(AAFrequency.PROFILE);
456 // int profileLength = profile[0].length;
457 int profileLength = profile.profile.size();
458 char[] ca = new char[profileLength];
459 float[] vl = new float[profileLength];
460 // for (int c = 0; c < ca.length; c++)
463 // vl[c] = profile[0][c];
465 for (int i = 0; i < profileLength; i++)
467 int c = profile.profile.keyAt(i);
469 vl[i] = profile.profile.valueAt(i);
471 QuickSort.sort(vl, ca);
472 int nextArrayPos = 2;
473 int totalPercentage = 0;
474 int distinctValuesCount = 0;
475 final int divisor = ignoreGaps ? profile.nonGapped : profile.height;
476 // final int divisor = profile[1][ignoreGaps ? 1 : 0];
477 int j = profile.profile.size();
478 for (int i = 0; i < j; i++)
479 // for (int c = ca.length - 1; profile[0][ca[c]] > 0; c--)
481 int theChar = profile.profile.keyAt(i);
482 int charCount = profile.profile.valueAt(i);
487 // rtnval[nextArrayPos++] = ca[c];
488 rtnval[nextArrayPos++] = theChar;
489 // final int percentage = (int) (profile[0][ca[c]] * 100f / divisor);
490 final int percentage = (charCount * 100) / divisor;
491 rtnval[nextArrayPos++] = percentage;
492 totalPercentage += percentage;
493 distinctValuesCount++;
496 rtnval[0] = distinctValuesCount;
497 rtnval[1] = totalPercentage;
498 int[] result = new int[rtnval.length + 1];
499 result[0] = AlignmentAnnotation.SEQUENCE_PROFILE;
500 System.arraycopy(rtnval, 0, result, 1, rtnval.length);
506 * Extract a sorted extract of cDNA codon profile data. The returned array
510 * [profileType, numberOfValues, totalCount, charValue1, percentage1, charValue2, percentage2, ...]
511 * in descending order of percentage value, where the character values encode codon triplets
517 public static int[] extractCdnaProfile(Hashtable hashtable,
520 // this holds #seqs, #ungapped, and then codon count, indexed by encoded
522 int[] codonCounts = (int[]) hashtable.get(PROFILE);
523 int[] sortedCounts = new int[codonCounts.length - 2];
524 System.arraycopy(codonCounts, 2, sortedCounts, 0,
525 codonCounts.length - 2);
527 int[] result = new int[3 + 2 * sortedCounts.length];
528 // first value is just the type of profile data
529 result[0] = AlignmentAnnotation.CDNA_PROFILE;
531 char[] codons = new char[sortedCounts.length];
532 for (int i = 0; i < codons.length; i++)
534 codons[i] = (char) i;
536 QuickSort.sort(sortedCounts, codons);
537 int totalPercentage = 0;
538 int distinctValuesCount = 0;
540 int divisor = ignoreGaps ? codonCounts[1] : codonCounts[0];
541 for (int i = codons.length - 1; i >= 0; i--)
543 final int codonCount = sortedCounts[i];
546 break; // nothing else of interest here
548 distinctValuesCount++;
549 result[j++] = codons[i];
550 final int percentage = codonCount * 100 / divisor;
551 result[j++] = percentage;
552 totalPercentage += percentage;
554 result[2] = totalPercentage;
557 * Just return the non-zero values
559 // todo next value is redundant if we limit the array to non-zero counts
560 result[1] = distinctValuesCount;
561 return Arrays.copyOfRange(result, 0, j);
565 * Compute a consensus for the cDNA coding for a protein alignment.
568 * the protein alignment (which should hold mappings to cDNA
571 * the consensus data stores to be populated (one per column)
573 public static void calculateCdna(AlignmentI alignment,
574 Hashtable[] hconsensus)
576 final char gapCharacter = alignment.getGapCharacter();
577 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
578 if (mappings == null || mappings.isEmpty())
583 int cols = alignment.getWidth();
584 for (int col = 0; col < cols; col++)
586 // todo would prefer a Java bean for consensus data
587 Hashtable<String, int[]> columnHash = new Hashtable<String, int[]>();
588 // #seqs, #ungapped seqs, counts indexed by (codon encoded + 1)
589 int[] codonCounts = new int[66];
590 codonCounts[0] = alignment.getSequences().size();
591 int ungappedCount = 0;
592 for (SequenceI seq : alignment.getSequences())
594 if (seq.getCharAt(col) == gapCharacter)
598 List<char[]> codons = MappingUtils
599 .findCodonsFor(seq, col, mappings);
600 for (char[] codon : codons)
602 int codonEncoded = CodingUtils.encodeCodon(codon);
603 if (codonEncoded >= 0)
605 codonCounts[codonEncoded + 2]++;
610 codonCounts[1] = ungappedCount;
611 // todo: sort values here, save counts and codons?
612 columnHash.put(PROFILE, codonCounts);
613 hconsensus[col] = columnHash;
618 * Derive displayable cDNA consensus annotation from computed consensus data.
620 * @param consensusAnnotation
621 * the annotation row to be populated for display
622 * @param consensusData
623 * the computed consensus data
624 * @param showProfileLogo
625 * if true show all symbols present at each position, else only the
628 * the number of sequences in the alignment
630 public static void completeCdnaConsensus(
631 AlignmentAnnotation consensusAnnotation,
632 Hashtable[] consensusData, boolean showProfileLogo, int nseqs)
634 if (consensusAnnotation == null
635 || consensusAnnotation.annotations == null
636 || consensusAnnotation.annotations.length < consensusData.length)
638 // called with a bad alignment annotation row - wait for it to be
639 // initialised properly
643 // ensure codon triplet scales with font size
644 consensusAnnotation.scaleColLabel = true;
645 for (int col = 0; col < consensusData.length; col++)
647 Hashtable hci = consensusData[col];
650 // gapped protein column?
653 // array holds #seqs, #ungapped, then codon counts indexed by codon
654 final int[] codonCounts = (int[]) hci.get(PROFILE);
658 * First pass - get total count and find the highest
660 final char[] codons = new char[codonCounts.length - 2];
661 for (int j = 2; j < codonCounts.length; j++)
663 final int codonCount = codonCounts[j];
664 codons[j - 2] = (char) (j - 2);
665 totalCount += codonCount;
669 * Sort array of encoded codons by count ascending - so the modal value
670 * goes to the end; start by copying the count (dropping the first value)
672 int[] sortedCodonCounts = new int[codonCounts.length - 2];
673 System.arraycopy(codonCounts, 2, sortedCodonCounts, 0,
674 codonCounts.length - 2);
675 QuickSort.sort(sortedCodonCounts, codons);
677 int modalCodonEncoded = codons[codons.length - 1];
678 int modalCodonCount = sortedCodonCounts[codons.length - 1];
679 String modalCodon = String.valueOf(CodingUtils
680 .decodeCodon(modalCodonEncoded));
681 if (sortedCodonCounts.length > 1
682 && sortedCodonCounts[codons.length - 2] == sortedCodonCounts[codons.length - 1])
685 * two or more codons share the modal count
689 float pid = sortedCodonCounts[sortedCodonCounts.length - 1] * 100
690 / (float) totalCount;
693 * todo ? Replace consensus hashtable with sorted arrays of codons and
694 * counts (non-zero only). Include total count in count array [0].
698 * Scan sorted array backwards for most frequent values first. Show
699 * repeated values compactly.
701 StringBuilder mouseOver = new StringBuilder(32);
702 StringBuilder samePercent = new StringBuilder();
703 String percent = null;
704 String lastPercent = null;
705 Format fmt = getPercentageFormat(nseqs);
707 for (int j = codons.length - 1; j >= 0; j--)
709 int codonCount = sortedCodonCounts[j];
713 * remaining codons are 0% - ignore, but finish off the last one if
716 if (samePercent.length() > 0)
718 mouseOver.append(samePercent).append(": ").append(percent)
723 int codonEncoded = codons[j];
724 final int pct = codonCount * 100 / totalCount;
725 String codon = String
726 .valueOf(CodingUtils.decodeCodon(codonEncoded));
727 percent = fmt == null ? Integer.toString(pct) : fmt.form(pct);
728 if (showProfileLogo || codonCount == modalCodonCount)
730 if (percent.equals(lastPercent) && j > 0)
732 samePercent.append(samePercent.length() == 0 ? "" : ", ");
733 samePercent.append(codon);
737 if (samePercent.length() > 0)
739 mouseOver.append(samePercent).append(": ")
740 .append(lastPercent).append("% ");
742 samePercent.setLength(0);
743 samePercent.append(codon);
745 lastPercent = percent;
749 consensusAnnotation.annotations[col] = new Annotation(modalCodon,
750 mouseOver.toString(), ' ', pid);