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.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.SecondaryStructureCount;
34 import jalview.datamodel.SequenceI;
35 import jalview.ext.android.SparseIntArray;
36 import jalview.util.Comparison;
37 import jalview.util.Format;
38 import jalview.util.MappingUtils;
39 import jalview.util.QuickSort;
41 import java.awt.Color;
42 import java.util.Arrays;
43 import java.util.Hashtable;
44 import java.util.List;
47 * Takes in a vector or array of sequences and column start and column end and
48 * returns a new Hashtable[] of size maxSeqLength, if Hashtable not supplied.
49 * This class is used extensively in calculating alignment colourschemes that
50 * depend on the amount of conservation in each alignment column.
55 public class AAFrequency
57 public static final String PROFILE = "P";
58 private static final String SS_ANNOTATION_LABEL = "Secondary Structure";
59 private static final char COIL = 'C';
62 * Quick look-up of String value of char 'A' to 'Z'
64 private static final String[] CHARS = new String['Z' - 'A' + 1];
68 for (char c = 'A'; c <= 'Z'; c++)
70 CHARS[c - 'A'] = String.valueOf(c);
74 public static final ProfilesI calculate(List<SequenceI> list, int start,
77 return calculate(list, start, end, false);
80 public static final ProfilesI calculate(List<SequenceI> sequences,
81 int start, int end, boolean profile)
83 SequenceI[] seqs = new SequenceI[sequences.size()];
85 synchronized (sequences)
87 for (int i = 0; i < sequences.size(); i++)
89 seqs[i] = sequences.get(i);
90 int length = seqs[i].getLength();
102 ProfilesI reply = calculate(seqs, width, start, end, profile);
108 * Calculate the consensus symbol(s) for each column in the given range.
112 * the full width of the alignment
114 * start column (inclusive, base zero)
116 * end column (exclusive)
117 * @param saveFullProfile
118 * if true, store all symbol counts
120 public static final ProfilesI calculate(final SequenceI[] sequences,
121 int width, int start, int end, boolean saveFullProfile)
123 // long now = System.currentTimeMillis();
124 int seqCount = sequences.length;
125 boolean nucleotide = false;
126 int nucleotideCount = 0;
127 int peptideCount = 0;
129 ProfileI[] result = new ProfileI[width];
131 for (int column = start; column < end; column++)
134 * Apply a heuristic to detect nucleotide data (which can
135 * be counted in more compact arrays); here we test for
136 * more than 90% nucleotide; recheck every 10 columns in case
137 * of misleading data e.g. highly conserved Alanine in peptide!
138 * Mistakenly guessing nucleotide has a small performance cost,
139 * as it will result in counting in sparse arrays.
140 * Mistakenly guessing peptide has a small space cost,
141 * as it will use a larger than necessary array to hold counts.
143 if (nucleotideCount > 100 && column % 10 == 0)
145 nucleotide = (9 * peptideCount < nucleotideCount);
147 ResidueCount residueCounts = new ResidueCount(nucleotide);
149 for (int row = 0; row < seqCount; row++)
151 if (sequences[row] == null)
153 jalview.bin.Console.errPrintln(
154 "WARNING: Consensus skipping null sequence - possible race condition.");
157 if (sequences[row].getLength() > column)
159 char c = sequences[row].getCharAt(column);
160 residueCounts.add(c);
161 if (Comparison.isNucleotide(c))
165 else if (!Comparison.isGap(c))
173 * count a gap if the sequence doesn't reach this column
175 residueCounts.addGap();
179 int maxCount = residueCounts.getModalCount();
180 String maxResidue = residueCounts.getResiduesForCount(maxCount);
181 int gapCount = residueCounts.getGapCount();
182 ProfileI profile = new Profile(seqCount, gapCount, maxCount,
187 profile.setCounts(residueCounts);
190 result[column] = profile;
192 return new Profiles(result);
193 // long elapsed = System.currentTimeMillis() - now;
194 // jalview.bin.Console.outPrintln(elapsed);
198 public static final ProfilesI calculateSS(List<SequenceI> list, int start,
201 return calculateSS(list, start, end, false);
204 public static final ProfilesI calculateSS(List<SequenceI> sequences,
205 int start, int end, boolean profile)
207 SequenceI[] seqs = new SequenceI[sequences.size()];
209 synchronized (sequences)
211 for (int i = 0; i < sequences.size(); i++)
213 seqs[i] = sequences.get(i);
214 int length = seqs[i].getLength();
226 ProfilesI reply = calculateSS(seqs, width, start, end, profile);
231 public static final ProfilesI calculateSS(final SequenceI[] sequences,
232 int width, int start, int end, boolean saveFullProfile)
234 // long now = System.currentTimeMillis();
235 int seqCount = sequences.length;
237 ProfileI[] result = new ProfileI[width];
239 for (int column = start; column < end; column++)
242 * Apply a heuristic to detect nucleotide data (which can
243 * be counted in more compact arrays); here we test for
244 * more than 90% nucleotide; recheck every 10 columns in case
245 * of misleading data e.g. highly conserved Alanine in peptide!
246 * Mistakenly guessing nucleotide has a small performance cost,
247 * as it will result in counting in sparse arrays.
248 * Mistakenly guessing peptide has a small space cost,
249 * as it will use a larger than necessary array to hold counts.
254 SecondaryStructureCount ssCounts = new SecondaryStructureCount();
256 for (int row = 0; row < seqCount; row++)
258 if (sequences[row] == null)
260 jalview.bin.Console.errPrintln(
261 "WARNING: Consensus skipping null sequence - possible race condition.");
265 char c = sequences[row].getCharAt(column);
267 if (sequences[row].getLength() > column && !Comparison.isGap(c))
270 AlignmentAnnotation[] aa = sequences[row].getAnnotation(SS_ANNOTATION_LABEL);
274 int seqPosition = sequences[row].findPosition(column);
276 if (aa[0].getAnnotationForPosition(seqPosition) != null) {
277 ss = aa[0].getAnnotationForPosition(seqPosition).secondaryStructure;
279 //There is no representation for coil and it can be either ' ' or null.
288 //secondaryStructures[row][column] = ss;
297 * count a gap if the sequence doesn't reach this column
303 int maxSSCount = ssCounts.getModalCount();
304 String maxSS = ssCounts.getSSForCount(maxSSCount);
305 int gapCount = ssCounts.getGapCount();
306 ProfileI profile = new Profile(maxSS, ssCount, gapCount,
311 profile.setSSCounts(ssCounts);
314 result[column] = profile;
316 return new Profiles(result);
317 // long elapsed = System.currentTimeMillis() - now;
318 // jalview.bin.Console.outPrintln(elapsed);
322 * Make an estimate of the profile size we are going to compute i.e. how many
323 * different characters may be present in it. Overestimating has a cost of
324 * using more memory than necessary. Underestimating has a cost of needing to
325 * extend the SparseIntArray holding the profile counts.
327 * @param profileSizes
328 * counts of sizes of profiles so far encountered
331 static int estimateProfileSize(SparseIntArray profileSizes)
333 if (profileSizes.size() == 0)
339 * could do a statistical heuristic here e.g. 75%ile
340 * for now just return the largest value
342 return profileSizes.keyAt(profileSizes.size() - 1);
346 * Derive the consensus annotations to be added to the alignment for display.
347 * This does not recompute the raw data, but may be called on a change in
348 * display options, such as 'ignore gaps', which may in turn result in a
349 * change in the derived values.
352 * the annotation row to add annotations to
354 * the source consensus data
356 * start column (inclusive)
358 * end column (exclusive)
360 * if true, normalise residue percentages ignoring gaps
361 * @param showSequenceLogo
362 * if true include all consensus symbols, else just show modal
365 * number of sequences
367 public static void completeConsensus(AlignmentAnnotation consensus,
368 ProfilesI profiles, int startCol, int endCol, boolean ignoreGaps,
369 boolean showSequenceLogo, long nseq)
371 // long now = System.currentTimeMillis();
372 if (consensus == null || consensus.annotations == null
373 || consensus.annotations.length < endCol)
376 * called with a bad alignment annotation row
377 * wait for it to be initialised properly
382 for (int i = startCol; i < endCol; i++)
384 ProfileI profile = profiles.get(i);
388 * happens if sequences calculated over were
389 * shorter than alignment width
391 consensus.annotations[i] = null;
395 final int dp = getPercentageDp(nseq);
397 float value = profile.getPercentageIdentity(ignoreGaps);
399 String description = getTooltip(profile, value, showSequenceLogo,
402 String modalResidue = profile.getModalResidue();
403 if ("".equals(modalResidue))
407 else if (modalResidue.length() > 1)
411 consensus.annotations[i] = new Annotation(modalResidue, description,
414 // long elapsed = System.currentTimeMillis() - now;
415 // jalview.bin.Console.outPrintln(-elapsed);
419 public static void completeSSConsensus(AlignmentAnnotation ssConsensus,
420 ProfilesI profiles, int startCol, int endCol, boolean ignoreGaps,
421 boolean showSequenceLogo, long nseq)
423 // long now = System.currentTimeMillis();
424 if (ssConsensus == null || ssConsensus.annotations == null
425 || ssConsensus.annotations.length < endCol)
428 * called with a bad alignment annotation row
429 * wait for it to be initialised properly
434 for (int i = startCol; i < endCol; i++)
436 ProfileI profile = profiles.get(i);
440 * happens if sequences calculated over were
441 * shorter than alignment width
443 ssConsensus.annotations[i] = null;
447 final int dp = getPercentageDp(nseq);
449 float value = profile.getSSPercentageIdentity(ignoreGaps);
451 String description = getSSTooltip(profile, value, showSequenceLogo,
454 String modalSS = profile.getModalSS();
455 if ("".equals(modalSS))
459 else if (modalSS.length() > 1)
463 ssConsensus.annotations[i] = new Annotation(modalSS, description,
466 // long elapsed = System.currentTimeMillis() - now;
467 // jalview.bin.Console.outPrintln(-elapsed);
471 * Derive the gap count annotation row.
474 * the annotation row to add annotations to
476 * the source consensus data
478 * start column (inclusive)
480 * end column (exclusive)
482 public static void completeGapAnnot(AlignmentAnnotation gaprow,
483 ProfilesI profiles, int startCol, int endCol, long nseq)
485 if (gaprow == null || gaprow.annotations == null
486 || gaprow.annotations.length < endCol)
489 * called with a bad alignment annotation row
490 * wait for it to be initialised properly
494 // always set ranges again
495 gaprow.graphMax = nseq;
497 double scale = 0.8 / nseq;
498 for (int i = startCol; i < endCol; i++)
500 ProfileI profile = profiles.get(i);
504 * happens if sequences calculated over were
505 * shorter than alignment width
507 gaprow.annotations[i] = null;
511 final int gapped = profile.getNonGapped();
513 String description = "" + gapped;
515 gaprow.annotations[i] = new Annotation("", description, '\0', gapped,
516 jalview.util.ColorUtils.bleachColour(Color.DARK_GRAY,
517 (float) scale * gapped));
522 * Returns a tooltip showing either
524 * <li>the full profile (percentages of all residues present), if
525 * showSequenceLogo is true, or</li>
526 * <li>just the modal (most common) residue(s), if showSequenceLogo is
529 * Percentages are as a fraction of all sequence, or only ungapped sequences
530 * if ignoreGaps is true.
534 * @param showSequenceLogo
537 * the number of decimal places to format percentages to
540 static String getTooltip(ProfileI profile, float pid,
541 boolean showSequenceLogo, boolean ignoreGaps, int dp)
543 ResidueCount counts = profile.getCounts();
545 String description = null;
546 if (counts != null && showSequenceLogo)
548 int normaliseBy = ignoreGaps ? profile.getNonGapped()
549 : profile.getHeight();
550 description = counts.getTooltip(normaliseBy, dp);
554 StringBuilder sb = new StringBuilder(64);
555 String maxRes = profile.getModalResidue();
556 if (maxRes.length() > 1)
558 sb.append("[").append(maxRes).append("]");
564 if (maxRes.length() > 0)
567 Format.appendPercentage(sb, pid, dp);
570 description = sb.toString();
575 static String getSSTooltip(ProfileI profile, float pid,
576 boolean showSequenceLogo, boolean ignoreGaps, int dp)
578 SecondaryStructureCount counts = profile.getSSCounts();
580 String description = null;
581 if (counts != null && showSequenceLogo)
583 int normaliseBy = ignoreGaps ? profile.getNonGapped()
584 : profile.getHeight();
585 description = counts.getTooltip(normaliseBy, dp);
589 StringBuilder sb = new StringBuilder(64);
590 String maxSS = profile.getModalSS();
591 if (maxSS.length() > 1)
593 sb.append("[").append(maxSS).append("]");
599 if (maxSS.length() > 0)
602 Format.appendPercentage(sb, pid, dp);
605 description = sb.toString();
611 * Returns the sorted profile for the given consensus data. The returned array
615 * [profileType, numberOfValues, totalPercent, charValue1, percentage1, charValue2, percentage2, ...]
616 * in descending order of percentage value
620 * the data object from which to extract and sort values
622 * if true, only non-gapped values are included in percentage
626 public static int[] extractProfile(ProfileI profile, boolean ignoreGaps)
631 if (profile.getCounts() != null)
633 ResidueCount counts = profile.getCounts();
634 SymbolCounts symbolCounts = counts.getSymbolCounts();
635 symbols = symbolCounts.symbols;
636 values = symbolCounts.values;
639 else if(profile.getSSCounts() != null)
641 SecondaryStructureCount counts = profile.getSSCounts();
643 SecondaryStructureCount.SymbolCounts symbolCounts = counts.getSymbolCounts();
644 symbols = symbolCounts.symbols;
645 values = symbolCounts.values;
652 QuickSort.sort(values, symbols);
653 int totalPercentage = 0;
654 final int divisor = ignoreGaps ? profile.getNonGapped()
655 : profile.getHeight();
658 * traverse the arrays in reverse order (highest counts first)
660 int[] result = new int[3 + 2 * symbols.length];
661 int nextArrayPos = 3;
662 int nonZeroCount = 0;
664 for (int i = symbols.length - 1; i >= 0; i--)
666 int theChar = symbols[i];
667 int charCount = values[i];
668 final int percentage = (charCount * 100) / divisor;
672 * this count (and any remaining) round down to 0% - discard
677 result[nextArrayPos++] = theChar;
678 result[nextArrayPos++] = percentage;
679 totalPercentage += percentage;
683 * truncate array if any zero values were discarded
685 if (nonZeroCount < symbols.length)
687 int[] tmp = new int[3 + 2 * nonZeroCount];
688 System.arraycopy(result, 0, tmp, 0, tmp.length);
693 * fill in 'header' values
695 result[0] = AlignmentAnnotation.SEQUENCE_PROFILE;
696 result[1] = nonZeroCount;
697 result[2] = totalPercentage;
703 * Extract a sorted extract of cDNA codon profile data. The returned array
707 * [profileType, numberOfValues, totalPercentage, charValue1, percentage1, charValue2, percentage2, ...]
708 * in descending order of percentage value, where the character values encode codon triplets
714 public static int[] extractCdnaProfile(
715 Hashtable<String, Object> hashtable, boolean ignoreGaps)
717 // this holds #seqs, #ungapped, and then codon count, indexed by encoded
719 int[] codonCounts = (int[]) hashtable.get(PROFILE);
720 int[] sortedCounts = new int[codonCounts.length - 2];
721 System.arraycopy(codonCounts, 2, sortedCounts, 0,
722 codonCounts.length - 2);
724 int[] result = new int[3 + 2 * sortedCounts.length];
725 // first value is just the type of profile data
726 result[0] = AlignmentAnnotation.CDNA_PROFILE;
728 char[] codons = new char[sortedCounts.length];
729 for (int i = 0; i < codons.length; i++)
731 codons[i] = (char) i;
733 QuickSort.sort(sortedCounts, codons);
734 int totalPercentage = 0;
735 int distinctValuesCount = 0;
737 int divisor = ignoreGaps ? codonCounts[1] : codonCounts[0];
738 for (int i = codons.length - 1; i >= 0; i--)
740 final int codonCount = sortedCounts[i];
743 break; // nothing else of interest here
745 final int percentage = codonCount * 100 / divisor;
749 * this (and any remaining) values rounded down to 0 - discard
753 distinctValuesCount++;
754 result[j++] = codons[i];
755 result[j++] = percentage;
756 totalPercentage += percentage;
758 result[2] = totalPercentage;
761 * Just return the non-zero values
763 // todo next value is redundant if we limit the array to non-zero counts
764 result[1] = distinctValuesCount;
765 return Arrays.copyOfRange(result, 0, j);
769 * Compute a consensus for the cDNA coding for a protein alignment.
772 * the protein alignment (which should hold mappings to cDNA
775 * the consensus data stores to be populated (one per column)
777 public static void calculateCdna(AlignmentI alignment,
778 Hashtable<String, Object>[] hconsensus)
780 final char gapCharacter = alignment.getGapCharacter();
781 List<AlignedCodonFrame> mappings = alignment.getCodonFrames();
782 if (mappings == null || mappings.isEmpty())
787 int cols = alignment.getWidth();
788 for (int col = 0; col < cols; col++)
790 // todo would prefer a Java bean for consensus data
791 Hashtable<String, Object> columnHash = new Hashtable<>();
792 // #seqs, #ungapped seqs, counts indexed by (codon encoded + 1)
793 int[] codonCounts = new int[66];
794 codonCounts[0] = alignment.getSequences().size();
795 int ungappedCount = 0;
796 for (SequenceI seq : alignment.getSequences())
798 if (seq.getCharAt(col) == gapCharacter)
802 List<char[]> codons = MappingUtils.findCodonsFor(seq, col,
804 for (char[] codon : codons)
806 int codonEncoded = CodingUtils.encodeCodon(codon);
807 if (codonEncoded >= 0)
809 codonCounts[codonEncoded + 2]++;
815 codonCounts[1] = ungappedCount;
816 // todo: sort values here, save counts and codons?
817 columnHash.put(PROFILE, codonCounts);
818 hconsensus[col] = columnHash;
823 * Derive displayable cDNA consensus annotation from computed consensus data.
825 * @param consensusAnnotation
826 * the annotation row to be populated for display
827 * @param consensusData
828 * the computed consensus data
829 * @param showProfileLogo
830 * if true show all symbols present at each position, else only the
833 * the number of sequences in the alignment
835 public static void completeCdnaConsensus(
836 AlignmentAnnotation consensusAnnotation,
837 Hashtable<String, Object>[] consensusData,
838 boolean showProfileLogo, int nseqs)
840 if (consensusAnnotation == null
841 || consensusAnnotation.annotations == null
842 || consensusAnnotation.annotations.length < consensusData.length)
844 // called with a bad alignment annotation row - wait for it to be
845 // initialised properly
849 // ensure codon triplet scales with font size
850 consensusAnnotation.scaleColLabel = true;
851 for (int col = 0; col < consensusData.length; col++)
853 Hashtable<String, Object> hci = consensusData[col];
856 // gapped protein column?
859 // array holds #seqs, #ungapped, then codon counts indexed by codon
860 final int[] codonCounts = (int[]) hci.get(PROFILE);
864 * First pass - get total count and find the highest
866 final char[] codons = new char[codonCounts.length - 2];
867 for (int j = 2; j < codonCounts.length; j++)
869 final int codonCount = codonCounts[j];
870 codons[j - 2] = (char) (j - 2);
871 totalCount += codonCount;
875 * Sort array of encoded codons by count ascending - so the modal value
876 * goes to the end; start by copying the count (dropping the first value)
878 int[] sortedCodonCounts = new int[codonCounts.length - 2];
879 System.arraycopy(codonCounts, 2, sortedCodonCounts, 0,
880 codonCounts.length - 2);
881 QuickSort.sort(sortedCodonCounts, codons);
883 int modalCodonEncoded = codons[codons.length - 1];
884 int modalCodonCount = sortedCodonCounts[codons.length - 1];
885 String modalCodon = String
886 .valueOf(CodingUtils.decodeCodon(modalCodonEncoded));
887 if (sortedCodonCounts.length > 1 && sortedCodonCounts[codons.length
888 - 2] == sortedCodonCounts[codons.length - 1])
891 * two or more codons share the modal count
895 float pid = sortedCodonCounts[sortedCodonCounts.length - 1] * 100
896 / (float) totalCount;
899 * todo ? Replace consensus hashtable with sorted arrays of codons and
900 * counts (non-zero only). Include total count in count array [0].
904 * Scan sorted array backwards for most frequent values first. Show
905 * repeated values compactly.
907 StringBuilder mouseOver = new StringBuilder(32);
908 StringBuilder samePercent = new StringBuilder();
909 String percent = null;
910 String lastPercent = null;
911 int percentDecPl = getPercentageDp(nseqs);
913 for (int j = codons.length - 1; j >= 0; j--)
915 int codonCount = sortedCodonCounts[j];
919 * remaining codons are 0% - ignore, but finish off the last one if
922 if (samePercent.length() > 0)
924 mouseOver.append(samePercent).append(": ").append(percent)
929 int codonEncoded = codons[j];
930 final int pct = codonCount * 100 / totalCount;
931 String codon = String
932 .valueOf(CodingUtils.decodeCodon(codonEncoded));
933 StringBuilder sb = new StringBuilder();
934 Format.appendPercentage(sb, pct, percentDecPl);
935 percent = sb.toString();
936 if (showProfileLogo || codonCount == modalCodonCount)
938 if (percent.equals(lastPercent) && j > 0)
940 samePercent.append(samePercent.length() == 0 ? "" : ", ");
941 samePercent.append(codon);
945 if (samePercent.length() > 0)
947 mouseOver.append(samePercent).append(": ").append(lastPercent)
950 samePercent.setLength(0);
951 samePercent.append(codon);
953 lastPercent = percent;
957 consensusAnnotation.annotations[col] = new Annotation(modalCodon,
958 mouseOver.toString(), ' ', pid);
963 * Returns the number of decimal places to show for profile percentages. For
964 * less than 100 sequences, returns zero (the integer percentage value will be
965 * displayed). For 100-999 sequences, returns 1, for 1000-9999 returns 2, etc.
970 protected static int getPercentageDp(long nseq)