From b0a4cb9f0cf2f9631b54d8b64be478c8a14f8a86 Mon Sep 17 00:00:00 2001
From: Valentin Ruano-Rubio
+ * If there is no reference allele, it returns -1. If there is more than one reference allele,
+ * it returns the first occurrence (lowest index).
+ *
+ * Repeats in the input array will be ignored (keeping the first one). The order of alleles in the
+ * resulting list is the same as in the natural traversal of the input collection.
+ *
+ *
+ * Repeats in the input collection will be ignored (keeping the first one). The order of alleles in the
+ * resulting list is the same as in the natural traversal of the input collection.
+ *
+ *
+ * Repeats in the input collection are ignored (just the first occurrence is kept).
+ * Sample names will be sorted based on the traversal order
+ * of the original collection.
+ *
+ * Repeats in the input array are ignored (just the first occurrence is kept).
+ * Sample names will be sorted based on the traversal order
+ * of the original array.
+ *
+ * Implementing classes must guarantee that the sample list will remain constant through the life of the object.
+ *
+ * Uses a primitive int value map for efficiency sake.
+ *
+ * Elements will be indexed as they appear in the input array. Repeats will be ignored.
+ *
+ * Elements will be indexed as they appear in the collection. Repeats will be ignored.
+ *
+ * Elements are sorted by their index within the set.
+ *
+ * This view changes as the indexed set changes but it cannot be used to update its contents.
+ * In such case a {@link UnsupportedOperationException} exception will be thrown if the calling
+ * code tries to tho just that.
+ *
+ * An element index is valid iff is within [0,{@link #size()}).
+ *
+ * If the element was already in th set nothing will happen and the method will return {@code false}. However,
+ * if the element is new to this set, it will assigned the next index available (equal to the size before addition).
+ * The method will return {@code true} in this case.
+ *
+ * If the element was not present in the set, nothing happens and the method return false. However,
+ * if the element is new to this set, it will be assigned the next index available (equal to the size
+ * before addition).
+ * The method will return {@code true} in this case.
+ *
+ * A partial permutation is one in that no all original elements take part of.
+ *
Alleles are represented herein by their indices running from 0 to N-1 where N is the number of alleles.
+ * + *Each allele present in a genotype (count != 0) has a rank, that is the 0-based ordinal of + * that allele amongst the ones present in the genotype as sorted by their index.
+ * + *For example:
+ * + *0/0/2/2 has two alleles with indices 0 and 2, both with count 2. + * The rank of 0 is 0 whereas the rank of 2 is 1.
+ * + *2/4/4/7 has three alleles with indices 2, 4 and 7. 2 and 7 have count 1 whereas 4 has count 2. + * The rank of 2 is 0, the rank of 4 is 1. and the rank of 7 is 2.
+ * + *In contrast, in both examples above both 3 and 10 (and many others) are absent thus they have no rank (represented by -1 whenever applies).
+ * + *{@link GenotypeAlleleCounts} instances have themselves their own index (returned by {@link #index() index()}, that indicate their 0-based ordinal within the possible genotype combinations with the same ploidy.
+ * + *For example, for ploidy 3:
+ * + *| Index | Genotype | + *
|---|---|
| 0 | 0/0/0 |
| 1 | 0/0/1 |
| 2 | 0/1/1 |
| 3 | 1/1/1 |
| 4 | 0/0/2 |
| 6 | 0/1/2 |
| 7 | 1/1/2 |
| 8 | 0/2/2 |
| 9 | 1/2/2 |
| 10 | 2/2/2 |
| 11 | 0/0/3 |
| 12 | 0/1/3 |
| 13 | 1/1/3 |
| 14 | 0/2/3 |
| 15 | 1/2/3 |
| 16 | 2/2/3 |
| 17 | 0/3/3 |
| ... | ... |
This method assumes that the invoker is passing a well formatted and sorted allele frequency array. + * Not checks are done for the sake of performance.
+ * + *
+ * The input argument {@code sortedAlleleCounts} list the index of alleles included in the unphased genotype
+ * and their frequency in the genotype in a single array using consecutive pairs:
+ *
+ *
[allele_1,freq_1,allele_2,freq_2, ... , allele_i, freq_i, ... , allele_n, freq_n]+ * + *
+ * The {@code ploidy} provided must be equal to the sum of all frequencies in {@code sortedAlleleCounts} + *
+ * @param ploidy the genotype ploidy. + * @param sortedAlleleCounts sorted allele counts following the restrictions above. + * @param index the genotype index. + */ + private GenotypeAlleleCounts(final int ploidy, final int index, final int... sortedAlleleCounts) { + this.ploidy = ploidy; + this.sortedAlleleCounts = sortedAlleleCounts; + distinctAlleleCount = sortedAlleleCounts.length >> 1; + log10CombinationCount = -1; + this.index = index; + } + + /** + * Returns the log10 of the number of possible allele combinations that would give raise to this allele count. + * @return 0 or less. + */ + public double log10CombinationCount() { + if (log10CombinationCount == -1) + return log10CombinationCount = calculateLog10CombinationCount(); + else + return log10CombinationCount; + } + + /** + * Calculates log10 combination count. + * + * @return 0 or less. + */ + private double calculateLog10CombinationCount() { + if (ploidy <= 1) + return 0; + else { + final int[] counts = new int[distinctAlleleCount]; + for (int i = 0, j = 1; i < distinctAlleleCount; i++, j+=2) + counts[i] = sortedAlleleCounts[j]; + return MathUtils.log10MultinomialCoefficient(ploidy, counts); + } + } + + /** + * Returns the genotype's ploidy. + * @return 0 or greater. + */ + public int ploidy() { + return ploidy; + } + + /** + * Increases the allele counts a number of times. + * + *+ * This method must not be invoked on cached genotype-allele-counts that are meant to remain constant, + * such as the ones contained in {@link GenotypeLikelihoodCalculators#genotypeTableByPloidy}. + *
+ * + * @param times the number of times to increase. + * + * @throws IllegalArgumentException if {@code times} is negative. + */ + protected void increase(final int times) { + for (int i = 0; i < times; i++) + increase(); + } + + /** + * Updates the genotype counts to match the next genotype. + * + *+ * This method must not be invoked on cached genotype-allele-counts that are meant to remain constant, + * such as the ones contained in {@link GenotypeLikelihoodCalculators#genotypeTableByPloidy} + *
+ */ + protected void increase() { + // if the ploidy is zero there is only one possible genotype. + if (distinctAlleleCount == 0) + return; + + // Worth make this case faster. + if (distinctAlleleCount == 1) { + if (ploidy == 1) { + sortedAlleleCounts[0]++; + } else { + if (sortedAlleleCounts.length < 4) + sortedAlleleCounts = Arrays.copyOf(sortedAlleleCounts,4); + sortedAlleleCounts[2] = sortedAlleleCounts[0] + 1; + sortedAlleleCounts[3] = 1; + sortedAlleleCounts[0] = 0; + sortedAlleleCounts[1] = ploidy - 1; + distinctAlleleCount = 2; + } + } else { + // Now, all the following ifs are just the way to avoid working with dynamically sizing List
+ * In this string allele calls appear in alleleIndex order with as many repeats as copies of each allele. So
+ * for example:
+ *
+ * 0 # haploid reference. + * 0/0 # typical diploid calls + * 0/1 + * 1/1 + * 0/0/1/3/3 # pentaploid with to ref, one first alt. and 2 third alt. allele + *+ * + * + * + * @return never {@code null}. + */ + public String toUnphasedGenotypeString() { + if (ploidy == 0) return ""; + final StringBuilder sb = new StringBuilder(distinctAlleleCount * 3); + for (int i = 0; i < distinctAlleleCount; i += 2) { + final int alleleIndex = sortedAlleleCounts[i]; + final int alleleCount = sortedAlleleCounts[i + 1]; + for (int j = 0; j < alleleCount; j++) + sb.append(alleleIndex).append('/'); + + } + sb.setLength(sb.length() - 1); + return sb.toString(); + } + + @Override + public String toString() { + // Perhaps we should change in the future, but the unphased genotype representation seems to be + // a good one. + return toUnphasedGenotypeString(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(final Object o) { + if (o instanceof GenotypeAlleleCounts) + return equals((GenotypeAlleleCounts)o); + else + return false; + } + + /** + * Compares with another genotype. + * @param o the other genotype. + * @return never {@code null}. + */ + public boolean equals(final GenotypeAlleleCounts o) { + if (o == this) + return true; + if (o == null) + return false; + if (ploidy != o.ploidy) + return false; + return Arrays.equals(sortedAlleleCounts, o.sortedAlleleCounts); + } + + /** + * Returns the index of this genotype allele count within all possible genotypes with the same ploidy. + * + * @return 0 or greater. + */ + public int index() { + return index; + } + + /** + * Compares to genotypes. + * + *
A genotype with larger ploidy is considered greater than one with a lower ploidy. If both genotypes have + * the same ploidy, then the genotype with the largest allele index or largest count if these are the same
. + * + * @param other genotype to compare to. + * + * @throws IllegalArgumentException if {@code other} is {@code null}. + * + * @return 0 if both genotypes are equivalent, < 0 if this genotype is less than {@code other} and > 0 + * if this genotype is greater than {@code other}. + */ + @Override + public int compareTo(final GenotypeAlleleCounts other) { + if (other == this) + return 0; + if (other == null) + throw new IllegalArgumentException("input genotype cannot be null"); + if (other.ploidy == ploidy) + return index - other.index; + else + return ploidy - other.ploidy; + } + + @Override + public int hashCode() { + return ((31 + ploidy) * 31 ) + index; + } + + /** + * Implements binary search across allele indexes. + * @param index the target index. + * @param from first inclusive possible rank. + * @param to last exclusive possible rank. + * @return -1 or less if the allele index is not in the genotype false otherwise. You can obtain + * the potential insertion point (within the interval [from,to]) as {@code -result - 1} + */ + private int alleleIndexToRank(final int index,final int from, final int to) { + if (to <= from) + return - from - 1; + if (from == to - 1) { + final int onlyIndex = sortedAlleleCounts[from << 1]; + return onlyIndex == index ? from : (onlyIndex > index) ? -from - 1 : -to - 1; + } + + final int mid = (to + from) >> 1; + final int midIndex = sortedAlleleCounts[mid << 1]; + if (midIndex == index) + return mid; + else if (midIndex < index) + return alleleIndexToRank(index,mid + 1,to); + else + return alleleIndexToRank(index,0,mid); + } + + /** + * Returns the count of an allele in the genotype given is rank in the genotype (not the allele index itself). + * + * @param rank of the requested allele within the genotype. + * + * @throws IllegalArgumentException if {@code rank} is out the the valid range [0,{@link #distinctAlleleCount}) + * + * @return 1 or greater. + */ + public int alleleCountAt(final int rank) { + if (rank < 0 || rank >= distinctAlleleCount) + throw new IllegalArgumentException("the rank is out of range"); + return sortedAlleleCounts[(rank << 1) + 1]; + } + + /** + * Checks whether this genotype contain at least one call on a particular allele index. + * + * @param index the target allele. + * + * @throws IllegalArgumentException if {@code index} is negative. + * + * @return {@code true} iff the genotype contains that allele index. + */ + public boolean containsAllele(final int index) { + return alleleRankFor(index) >= 0; + } + + /** + * Returns the count of an allele in the genotype given it index. + * + * @return 0 if the allele is not present in the genotype, 1 or more otherwise. + */ + public int alleleCountFor(final int index) { + final int rank = alleleRankFor(index); + return rank < 0 ? 0 : alleleCountAt(rank); + } + + /** + * Returns the allele counts for each allele index to maximum. + * @param maximumAlleleIndex the maximum allele index required. + * @throws IllegalArgumentException if {@code maximumAlleleIndex} is less than 0. + * @return never {@code null}, an array of exactly {@code maximumAlleleIndex + 1} positions with the counts + * of each allele where the position in the array is equal to its index. + */ + public int[] alleleCountsByIndex(final int maximumAlleleIndex) { + if (maximumAlleleIndex < 0) + throw new IllegalArgumentException("the requested allele count cannot be less than 0"); + final int[] result = new int[maximumAlleleIndex + 1]; + copyAlleleCountsByIndex(result, 0, 0, maximumAlleleIndex); + return result; + } + + + private void copyAlleleCountsByIndex(final int[] dest, final int offset, final int minimumAlleleIndex, final int maximumAlleleIndex) { + + // First we determine what section of the sortedAlleleCounts array contains the counts of interest, + // By the present allele rank range of interest. + final int minimumAlleleRank = alleleRankFor(minimumAlleleIndex); + final int maximumAlleleRank = alleleRankFor(maximumAlleleIndex); + + // If the min or max allele index are absent (returned rank < 0) we note where the would be inserted; that + // way we avoid going through the rest of positions in the sortedAlleleCounts array. + // The range of interest is then [startRank,endRank]. + final int startRank = minimumAlleleRank < 0 ? - minimumAlleleRank - 1 : minimumAlleleRank; + final int endRank = maximumAlleleRank < 0 ? - maximumAlleleRank - 2 : maximumAlleleRank; + + // Iteration variables: + int nextIndex = minimumAlleleIndex; // next index that we want to output the count for. + int nextRank = startRank; // next rank to query in sortedAlleleCounts. + int nextSortedAlleleCountsOffset = nextRank << 1; // offset in sortedAlleleCounts where the info is present for the next rank. + int nextDestOffset = offset; // next offset in destination array where to set the count for the nextIndex. + + while (nextRank++ <= endRank) { + final int alleleIndex = sortedAlleleCounts[nextSortedAlleleCountsOffset++]; + // fill non-present allele counts with 0s. + while (alleleIndex > nextIndex) { + dest[nextDestOffset++] = 0; + nextIndex++; + } + // It is guaranteed that at this point alleleIndex == nextIndex + // thanks to the condition of the enclosing while: there must be at least one index of interest that + // it is present in remaning (nextRank,endRank] interval as otherwise endRank would be less than nextRank. + dest[nextDestOffset++] = sortedAlleleCounts[nextSortedAlleleCountsOffset++]; + nextIndex++; + } + // Finally we take care of trailing requested allele indices. + while (nextIndex++ <= maximumAlleleIndex) + dest[nextDestOffset++] = 0; + } + + /** + * Copies the sorted allele counts into an array. + * + *+ * Sorted allele counts are disposed as an even-sized array where even positions indicate the allele index and + * the following odd positions the number of copies of that allele in this genotype allele count: + *
+ *+ * [ allele_0, freq_0, allele_1, freq_1 ... ] + *+ * + *
+ * With {@code offset} you can indicate an alternative first position in the destination array. + *
+ * + * @param dest where to copy the counts. + * @param offset starting position. + * + * @throws IllegalArgumentException if {@code dest} is {@code null}, {@code offset} is less than 0 + * or {@code dest} is not large enough considering the number of alleles present in this genotype + * allele counts and the {@code offset} provided. A total of + *{@link #distinctAlleleCount()} * 2 positions
+ * are required for the job.
+ */
+ public void copyAlleleCounts(final int[] dest, final int offset) {
+ if (dest == null)
+ throw new IllegalArgumentException("the destination cannot be null");
+ if (offset < 0)
+ throw new IllegalArgumentException("the offset cannot be negative");
+ final int sortedAlleleCountsLength = distinctAlleleCount << 1;
+ if (offset + sortedAlleleCountsLength > dest.length)
+ throw new IllegalArgumentException("the input array does not have enough capacity");
+ System.arraycopy(sortedAlleleCounts,0,dest,offset,sortedAlleleCountsLength);
+ }
+
+ /**
+ * Instantiates the first genotype possible provided a total ploidy.
+ * @param ploidy the ploidy of the genotype.
+ *
+ * @throws java.lang.IllegalArgumentException if ploidy is less than 0.
+ *
+ * @return never {@code null}.
+ */
+ protected static GenotypeAlleleCounts first(final int ploidy) {
+ if (ploidy < 0)
+ throw new IllegalArgumentException("the ploidy must be 0 or greater");
+ else if (ploidy == 0)
+ return new GenotypeAlleleCounts(0,0);
+ else
+ return new GenotypeAlleleCounts(ploidy, 0, 0, ploidy);
+ }
+
+ /**
+ * Makes the next genotype in likelihood indexing order.
+ *
+ * @param g the original genotype.
+ *
+ * @throws IllegalArgumentException if {@code g} is {@code null}.
+ *
+ * @return never {@code null}.
+ */
+ public static GenotypeAlleleCounts makeNextGenotype(final GenotypeAlleleCounts g) {
+ if (g == null)
+ throw new IllegalArgumentException("the next genotype");
+ return g.next();
+ }
+
+ /**
+ * Returns the largest allele index present in the genotype.
+ *
+ * @return -1 if there is no alleles (ploidy == 0), 0 or greater otherwise.
+ */
+ public int maximumAlleleIndex() {
+ if (distinctAlleleCount == 0)
+ return -1;
+ else
+ return sortedAlleleCounts[(distinctAlleleCount - 1) << 1];
+ }
+
+ /**
+ * Returns the smallest allele index present in the genotype.
+ *
+ * @return -1 if there is no allele (ploidy == 0), 0 or greater otherwise.
+ */
+ public int minimumAlleleIndex() {
+ if (distinctAlleleCount == 0)
+ return -1;
+ else
+ return sortedAlleleCounts[0];
+ }
+
+ /**
+ * Creates an independent copy of this genotype.
+ * @return never {@code null}.
+ */
+ @Override
+ protected GenotypeAlleleCounts clone() {
+ return new GenotypeAlleleCounts(ploidy,index,Arrays.copyOf(sortedAlleleCounts,distinctAlleleCount << 1));
+ }
+}
diff --git a/protected/gatk-tools-protected/src/main/java/org/broadinstitute/gatk/genotyping/GenotypeLikelihoodCalculator.java b/protected/gatk-tools-protected/src/main/java/org/broadinstitute/gatk/genotyping/GenotypeLikelihoodCalculator.java
new file mode 100644
index 000000000..ff824ac26
--- /dev/null
+++ b/protected/gatk-tools-protected/src/main/java/org/broadinstitute/gatk/genotyping/GenotypeLikelihoodCalculator.java
@@ -0,0 +1,568 @@
+/*
+* By downloading the PROGRAM you agree to the following terms of use:
+*
+* BROAD INSTITUTE - SOFTWARE LICENSE AGREEMENT - FOR ACADEMIC NON-COMMERCIAL RESEARCH PURPOSES ONLY
+*
+* This Agreement is made between the Broad Institute, Inc. with a principal address at 7 Cambridge Center, Cambridge, MA 02142 (BROAD) and the LICENSEE and is effective at the date the downloading is completed (EFFECTIVE DATE).
+*
+* WHEREAS, LICENSEE desires to license the PROGRAM, as defined hereinafter, and BROAD wishes to have this PROGRAM utilized in the public interest, subject only to the royalty-free, nonexclusive, nontransferable license rights of the United States Government pursuant to 48 CFR 52.227-14; and
+* WHEREAS, LICENSEE desires to license the PROGRAM and BROAD desires to grant a license on the following terms and conditions.
+* NOW, THEREFORE, in consideration of the promises and covenants made herein, the parties hereto agree as follows:
+*
+* 1. DEFINITIONS
+* 1.1 PROGRAM shall mean copyright in the object code and source code known as GATK2 and related documentation, if any, as they exist on the EFFECTIVE DATE and can be downloaded from http://www.broadinstitute/GATK on the EFFECTIVE DATE.
+*
+* 2. LICENSE
+* 2.1 Grant. Subject to the terms of this Agreement, BROAD hereby grants to LICENSEE, solely for academic non-commercial research purposes, a non-exclusive, non-transferable license to: (a) download, execute and display the PROGRAM and (b) create bug fixes and modify the PROGRAM.
+* The LICENSEE may apply the PROGRAM in a pipeline to data owned by users other than the LICENSEE and provide these users the results of the PROGRAM provided LICENSEE does so for academic non-commercial purposes only. For clarification purposes, academic sponsored research is not a commercial use under the terms of this Agreement.
+* 2.2 No Sublicensing or Additional Rights. LICENSEE shall not sublicense or distribute the PROGRAM, in whole or in part, without prior written permission from BROAD. LICENSEE shall ensure that all of its users agree to the terms of this Agreement. LICENSEE further agrees that it shall not put the PROGRAM on a network, server, or other similar technology that may be accessed by anyone other than the LICENSEE and its employees and users who have agreed to the terms of this agreement.
+* 2.3 License Limitations. Nothing in this Agreement shall be construed to confer any rights upon LICENSEE by implication, estoppel, or otherwise to any computer software, trademark, intellectual property, or patent rights of BROAD, or of any other entity, except as expressly granted herein. LICENSEE agrees that the PROGRAM, in whole or part, shall not be used for any commercial purpose, including without limitation, as the basis of a commercial software or hardware product or to provide services. LICENSEE further agrees that the PROGRAM shall not be copied or otherwise adapted in order to circumvent the need for obtaining a license for use of the PROGRAM.
+*
+* 3. OWNERSHIP OF INTELLECTUAL PROPERTY
+* LICENSEE acknowledges that title to the PROGRAM shall remain with BROAD. The PROGRAM is marked with the following BROAD copyright notice and notice of attribution to contributors. LICENSEE shall retain such notice on all copies. LICENSEE agrees to include appropriate attribution if any results obtained from use of the PROGRAM are included in any publication.
+* Copyright 2012 Broad Institute, Inc.
+* Notice of attribution: The GATK2 program was made available through the generosity of Medical and Population Genetics program at the Broad Institute, Inc.
+* LICENSEE shall not use any trademark or trade name of BROAD, or any variation, adaptation, or abbreviation, of such marks or trade names, or any names of officers, faculty, students, employees, or agents of BROAD except as states above for attribution purposes.
+*
+* 4. INDEMNIFICATION
+* LICENSEE shall indemnify, defend, and hold harmless BROAD, and their respective officers, faculty, students, employees, associated investigators and agents, and their respective successors, heirs and assigns, (Indemnitees), against any liability, damage, loss, or expense (including reasonable attorneys fees and expenses) incurred by or imposed upon any of the Indemnitees in connection with any claims, suits, actions, demands or judgments arising out of any theory of liability (including, without limitation, actions in the form of tort, warranty, or strict liability and regardless of whether such action has any factual basis) pursuant to any right or license granted under this Agreement.
+*
+* 5. NO REPRESENTATIONS OR WARRANTIES
+* THE PROGRAM IS DELIVERED AS IS. BROAD MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE PROGRAM OR THE COPYRIGHT, EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, WHETHER OR NOT DISCOVERABLE. BROAD EXTENDS NO WARRANTIES OF ANY KIND AS TO PROGRAM CONFORMITY WITH WHATEVER USER MANUALS OR OTHER LITERATURE MAY BE ISSUED FROM TIME TO TIME.
+* IN NO EVENT SHALL BROAD OR ITS RESPECTIVE DIRECTORS, OFFICERS, EMPLOYEES, AFFILIATED INVESTIGATORS AND AFFILIATES BE LIABLE FOR INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, INCLUDING, WITHOUT LIMITATION, ECONOMIC DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER BROAD SHALL BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT SHALL KNOW OF THE POSSIBILITY OF THE FOREGOING.
+*
+* 6. ASSIGNMENT
+* This Agreement is personal to LICENSEE and any rights or obligations assigned by LICENSEE without the prior written consent of BROAD shall be null and void.
+*
+* 7. MISCELLANEOUS
+* 7.1 Export Control. LICENSEE gives assurance that it will comply with all United States export control laws and regulations controlling the export of the PROGRAM, including, without limitation, all Export Administration Regulations of the United States Department of Commerce. Among other things, these laws and regulations prohibit, or require a license for, the export of certain types of software to specified countries.
+* 7.2 Termination. LICENSEE shall have the right to terminate this Agreement for any reason upon prior written notice to BROAD. If LICENSEE breaches any provision hereunder, and fails to cure such breach within thirty (30) days, BROAD may terminate this Agreement immediately. Upon termination, LICENSEE shall provide BROAD with written assurance that the original and all copies of the PROGRAM have been destroyed, except that, upon prior written authorization from BROAD, LICENSEE may retain a copy for archive purposes.
+* 7.3 Survival. The following provisions shall survive the expiration or termination of this Agreement: Articles 1, 3, 4, 5 and Sections 2.2, 2.3, 7.3, and 7.4.
+* 7.4 Notice. Any notices under this Agreement shall be in writing, shall specifically refer to this Agreement, and shall be sent by hand, recognized national overnight courier, confirmed facsimile transmission, confirmed electronic mail, or registered or certified mail, postage prepaid, return receipt requested. All notices under this Agreement shall be deemed effective upon receipt.
+* 7.5 Amendment and Waiver; Entire Agreement. This Agreement may be amended, supplemented, or otherwise modified only by means of a written instrument signed by all parties. Any waiver of any rights or failure to act in a specific instance shall relate only to such instance and shall not be construed as an agreement to waive any rights or fail to act in any other instance, whether or not similar. This Agreement constitutes the entire agreement among the parties with respect to its subject matter and supersedes prior agreements or understandings between the parties relating to its subject matter.
+* 7.6 Binding Effect; Headings. This Agreement shall be binding upon and inure to the benefit of the parties and their respective permitted successors and assigns. All headings are for convenience only and shall not affect the meaning of any provision of this Agreement.
+* 7.7 Governing Law. This Agreement shall be construed, governed, interpreted and applied in accordance with the internal laws of the Commonwealth of Massachusetts, U.S.A., without regard to conflict of laws principles.
+*/
+package org.broadinstitute.gatk.genotyping;
+
+import htsjdk.variant.variantcontext.Allele;
+import htsjdk.variant.variantcontext.GenotypeLikelihoods;
+import org.broadinstitute.gatk.utils.MathUtils;
+import org.broadinstitute.gatk.utils.collections.IntMaxHeap;
+import org.broadinstitute.gatk.utils.genotyper.ReadLikelihoods;
+
+/**
+ * Helper to calculate genotype likelihoods given a ploidy and an allele count (number of possible distinct alleles).
+ *
+ * + * Notice that for performance this class is thread-unsafe an so it cannot be shared between thread in a multi-thread run. + *
+ * + * @author Valentin Ruano-Rubio <valentin@broadinstitute.org> + */ +public class GenotypeLikelihoodCalculator { + + /** + * Maximum number of components (or distinct alleles) for any genotype with this calculator ploidy and allele count. + */ + private int maximumDistinctAllelesInGenotype; + + /** + * Offset table for this calculator. + * + *+ * This is a shallow copy of {@link GenotypeLikelihoodCalculators#alleleFirstGenotypeOffsetByPloidy} when the calculator was created + * thus it follows the same format as that array. Please refer to its documentation. + *
+ * + *You can assume that this offset table contain at least (probably more) the numbers corresponding to the allele count and ploidy for this calculator. + * However since it might have more than that and so you must use {@link #alleleCount} and {@link #ploidy} when + * iterating through this array rather that its length or the length of its components.
. + */ + private final int[][] alleleFirstGenotypeOffsetByPloidy; + + /** + * Genotype table for this calculator. + * + *It is ensure that it contains all the genotypes for this calculator ploidy and allele count, maybe more. For + * that reason you must use {@link #genotypeCount} when iterating through this array and not relay on its length.
+ */ + private final GenotypeAlleleCounts[] genotypeAlleleCounts; + + + /** + * Number of genotypes given this calculator {@link #ploidy} and {@link #alleleCount}. + */ + private final int genotypeCount; + + /** + * Number of genotyping alleles for this calculator. + */ + private final int alleleCount; + + /** + * Ploidy for this calculator. + */ + private final int ploidy; + + /** + * Max-heap for integers used for this calculator internally. + */ + private final IntMaxHeap alleleHeap; + + /** + * Cache of the last genotype-allele-count requested using {@link #genotypeAlleleCountsAt(int)}, when it + * goes beyond the maximum genotype-allele-count static capacity. Check on that method documentation for details. + */ + private transient GenotypeAlleleCounts lastOverheadCounts; + + /** + * Buffer used as a temporary container for likelihood components for genotypes stratified by alleles, allele frequency and reads. + * + *To improve performance we use a 1-dimensional array to implement a 3-dimensional one as some of those dimension + * have typically very low depths (allele and allele frequency)
+ * + *
+ * The value contained in position [a][f][r] == log10Lk(read[r] | allele[a]) + log10(f) . Exception is
+ * for f == 0 whose value is undefined (in practice 0.0) and never used.
+ *
+ * It is indexed by read, then by allele and then by the number of copies of the allele. For the latter + * there are as many entries as the ploidy of the calculator + 1 (to accommodate zero copies although is + * never used in practice). + *
+ */ + private double[] readAlleleLikelihoodByAlleleCount = null; + + /** + * Buffer used as a temporary container for likelihood components for genotypes stratified by reads. + * + *+ * It is indexed by genotype index and then by read index. The read capacity is increased as needed by calling + * {@link #ensureReadCapacity(int) ensureReadCapacity}. + *
+ */ + private final double[][] readLikelihoodsByGenotypeIndex; + + /** + * Indicates how many reads the calculator supports. + * + *This figure is increased dynamically as per the + * calculation request calling {@link #ensureReadCapacity(int) ensureReadCapacity}.
+ */ + private int readCapacity = -1; + + /** + * Caches the log10 of the first few integers up to the ploidy supported by the calculator. + *This is in fact a shallow copy if {@link GenotypeLikelihoodCalculators#ploidyLog10}
and is not meant to be modified by + * this class. + */ + private final double[] log10; + + /** + * Buffer field use as a temporal container for sorted allele counts when calculating the likelihood of a + * read in a genotype. + *+ * This array follows the same format as {@link GenotypeAlleleCounts#sortedAlleleCounts}. Each component in the + * genotype takes up two positions in the array where the first indicate the allele index and the second its frequency in the + * genotype. Only non-zero frequency alleles are represented, taking up the first positions of the array. + *
+ * + *+ * This array is sized so that it can accommodate the maximum possible number of distinct alleles in any + * genotype supported by the calculator, value stored in {@link #maximumDistinctAllelesInGenotype}. + *
+ */ + private final int[] genotypeAllelesAndCounts; + + /** + * Buffer field use as a temporal container for component likelihoods when calculating the likelihood of a + * read in a genotype. It is stratified by read and the allele component of the genotype likelihood... that is + * the part of the likelihood sum that correspond to a particular allele in the genotype. + * + *+ * It is implemented in a 1-dimensional array since typically one of the dimensions is rather small. Its size + * is equal to {@link #readCapacity} times {@link #maximumDistinctAllelesInGenotype}. + *
+ * + *+ * More concretely [r][i] == log10Lk(read[r] | allele[i]) + log(freq[i]) where allele[i] is the ith allele + * in the genotype of interest and freq[i] is the number of times it occurs in that genotype. + *
+ */ + private double[] readGenotypeLikelihoodComponents; + + /** + * Creates a new calculator providing its ploidy and number of genotyping alleles. + */ + protected GenotypeLikelihoodCalculator(final int ploidy, final int alleleCount, + final int[][] alleleFirstGenotypeOffsetByPloidy, + final GenotypeAlleleCounts[][] genotypeTableByPloidy, + final double[] ploidyLog10) { + this.alleleFirstGenotypeOffsetByPloidy = alleleFirstGenotypeOffsetByPloidy; + genotypeAlleleCounts = genotypeTableByPloidy[ploidy]; + this.alleleCount = alleleCount; + this.ploidy = ploidy; + genotypeCount = this.alleleFirstGenotypeOffsetByPloidy[ploidy][alleleCount]; + if (genotypeCount == GenotypeLikelihoodCalculators.GENOTYPE_COUNT_OVERFLOW) + throw new IllegalArgumentException( + String.format("the combination of ploidy (%s) and number of alleles (%s) results in a very large number of genotypes (> %s). You need to limit ploidy or the number of alternative alleles to analyze this locus", + ploidy,alleleCount,Integer.MAX_VALUE)); + alleleHeap = new IntMaxHeap(ploidy); + readLikelihoodsByGenotypeIndex = new double[genotypeCount][]; + log10 = ploidyLog10; + // The number of possible components is limited by distinct allele count and ploidy. + maximumDistinctAllelesInGenotype = Math.min(ploidy, alleleCount); + genotypeAllelesAndCounts = new int[maximumDistinctAllelesInGenotype << 1]; + } + + /** + * Makes sure that temporal arrays and matrices are prepared for a number of reads to process. + * @param requestedCapacity number of read that need to be processed. + */ + public void ensureReadCapacity(final int requestedCapacity) { + if (requestedCapacity < 0) + throw new IllegalArgumentException("illegal capacity value"); + if (readCapacity == -1) { // first time call. + final int minimumCapacity = Math.max(requestedCapacity,10); // Never go too small, 10 is the minimum. + readAlleleLikelihoodByAlleleCount = new double[minimumCapacity * alleleCount * (ploidy+1)]; + for (int i = 0; i < genotypeCount; i++) + readLikelihoodsByGenotypeIndex[i] = new double[minimumCapacity]; + readGenotypeLikelihoodComponents = new double[ploidy * minimumCapacity]; + readCapacity = minimumCapacity; + } else if (readCapacity < requestedCapacity) { + final int doubleCapacity = (requestedCapacity << 1); + readAlleleLikelihoodByAlleleCount = new double[doubleCapacity * alleleCount * (ploidy+1)]; + for (int i = 0; i < genotypeCount; i++) + readLikelihoodsByGenotypeIndex[i] = new double[doubleCapacity]; + readGenotypeLikelihoodComponents = new double[maximumDistinctAllelesInGenotype * doubleCapacity]; + readCapacity = doubleCapacity; + } + } + + /** + * Give a list of alleles, returns the likelihood array index. + * + *This operation is thread-unsafe.
+ * + * @param alleleIndices the indices of the alleles in the genotype, there should be as many repetition of an + * index as copies of that allele in the genotype. Allele indices do not need to be sorted in + * any particular way. + * + * @return never {@code null}. + */ + public int allelesToIndex(final int... alleleIndices) { + // Special case ploidy == 0. + if (ploidy == 0) return 0; + + alleleHeap.clear(); + alleleHeap.add(alleleIndices); + return alleleHeapToIndex(); + } + + /** + * Returns the number of possible genotypes given ploidy and the maximum allele index. + * @return never {@code null}. + */ + public int genotypeCount() { + return genotypeCount; + } + + /** + * Returns the genotype associated to a particular likelihood index. + * + *If {@code index} is larger than {@link GenotypeLikelihoodCalculators#MAXIMUM_STRONG_REF_GENOTYPE_PER_PLOIDY}, + * this method will reconstruct that genotype-allele-count iteratively from the largest strongly referenced count available. + * or the last requested index genotype. + *
+ * + *Therefore if you are iterating through all genotype-allele-counts you should do sequentially and incrementally, to + * avoid a large efficiency drop
. + * + * @param index query likelihood-index. + * @return never {@code null}. + */ + public GenotypeAlleleCounts genotypeAlleleCountsAt(final int index) { + if (index < 0 || index >= genotypeCount) + throw new IllegalArgumentException("invalid likelihood index: " + index + " >= " + genotypeCount + + " (genotype count for nalleles = " + alleleCount + " and ploidy " + ploidy ); + if (index < GenotypeLikelihoodCalculators.MAXIMUM_STRONG_REF_GENOTYPE_PER_PLOIDY) + return genotypeAlleleCounts[index]; + else if (lastOverheadCounts == null || lastOverheadCounts.index() > index) { + final GenotypeAlleleCounts result = genotypeAlleleCounts[GenotypeLikelihoodCalculators.MAXIMUM_STRONG_REF_GENOTYPE_PER_PLOIDY - 1].clone(); + result.increase(index - GenotypeLikelihoodCalculators.MAXIMUM_STRONG_REF_GENOTYPE_PER_PLOIDY + 1); + lastOverheadCounts = result; + return result.clone(); + } else { + lastOverheadCounts.increase(index - lastOverheadCounts.index()); + return lastOverheadCounts.clone(); + } + } + + /** + * Calculate the likelihoods given the list of alleles and the likelihood map. + * + *This operation is thread-unsafe.
+ * + * @param likelihoods the likelihood matrix all alleles vs all reads. + * + * @throws IllegalArgumentException if {@code alleleList} is {@code null} or {@code likelihoods} is {@code null} + * or the alleleList size does not match the allele-count of this calculator, or there are missing allele vs + * read combinations in {@code likelihoods}. + * + * @return never {@code null}. + */ + public GenotypeLikelihoods genotypeLikelihoods(final ReadLikelihoods.Matrix likelihoods) { + if (likelihoods == null) + throw new IllegalArgumentException("the likelihood map cannot be null"); + + if (likelihoods.alleleCount() != alleleCount) + throw new IllegalArgumentException("mismatch between allele list and alleleCount"); + + + final int readCount = likelihoods.readCount(); + + + ensureReadCapacity(readCount); + + /// [x][y][z] = z * LnLk(Read_x | Allele_y) + final double[] readLikelihoodComponentsByAlleleCount + = readLikelihoodComponentsByAlleleCount(likelihoods); + final double[][] genotypeLikelihoodByRead = genotypeLikelihoodByRead(readLikelihoodComponentsByAlleleCount,readCount); + final double[] readLikelihoodsByGenotypeIndex = genotypeLikelihoods(genotypeLikelihoodByRead, readCount); + return GenotypeLikelihoods.fromLog10Likelihoods(readLikelihoodsByGenotypeIndex); + } + + /** + * Calculates the final genotype likelihood array out of the likelihoods for each genotype per read. + * + * @param readLikelihoodsByGenotypeIndex [g][r] likelihoods for each genotype g and r. + * @param readCount number of reads in the input likelihood arrays in {@code genotypeLikelihoodByRead}. + * @return never {@code null}, one position per genotype where the i entry is the likelihood of the ith + * genotype (0-based). + */ + private double[] genotypeLikelihoods(final double[][] readLikelihoodsByGenotypeIndex, final int readCount) { + final double[] result = new double[genotypeCount]; + final double denominator = readCount * log10[ploidy]; // instead of dividing each read likelihood by ploidy + // ( so subtract log10(ploidy) ) we multiply them all and the divide by ploidy^readCount (so substract readCount * log10(ploidy) ) + for (int g = 0; g < genotypeCount; g++) { + final double[] likelihoodsByRead = readLikelihoodsByGenotypeIndex[g]; + double s = - denominator; + for (int r = 0; r < readCount; r++) + s += likelihoodsByRead[r]; + result[g] = s; + } + return result; + } + + /** + * Calculates the likelihood component of each read on each genotype. + * + * @param readLikelihoodComponentsByAlleleCount [a][f][r] likelihood stratified by allele a, frequency in genotype f and + * read r. + * @param readCount number of reads in {@code readLikelihoodComponentsByAlleleCount}. + * @return never {@code null}. + */ + private double[][] genotypeLikelihoodByRead(final double[] readLikelihoodComponentsByAlleleCount, final int readCount) { + + // Here we don't use the convenience of {@link #genotypeAlleleCountsAt(int)} within the loop to spare instantiations of + // GenotypeAlleleCounts class when we are dealing with many genotypes. + GenotypeAlleleCounts alleleCounts = genotypeAlleleCounts[0]; + + for (int genotypeIndex = 0; genotypeIndex < genotypeCount; genotypeIndex++) { + final double[] readLikelihoods = this.readLikelihoodsByGenotypeIndex[genotypeIndex]; + final int componentCount = alleleCounts.distinctAlleleCount(); + switch (componentCount) { + case 1: // + singleComponentGenotypeLikelihoodByRead(alleleCounts, readLikelihoods, readLikelihoodComponentsByAlleleCount, readCount); + break; + case 2: + twoComponentGenotypeLikelihoodByRead(alleleCounts,readLikelihoods,readLikelihoodComponentsByAlleleCount, readCount); + break; + default: + manyComponentGenotypeLikelihoodByRead(alleleCounts,readLikelihoods,readLikelihoodComponentsByAlleleCount, readCount); + } + if (genotypeIndex < genotypeCount - 1) + alleleCounts = nextGenotypeAlleleCounts(alleleCounts); + } + return readLikelihoodsByGenotypeIndex; + } + + private GenotypeAlleleCounts nextGenotypeAlleleCounts(final GenotypeAlleleCounts alleleCounts) { + final int index = alleleCounts.index(); + final GenotypeAlleleCounts result; + final int cmp = index - GenotypeLikelihoodCalculators.MAXIMUM_STRONG_REF_GENOTYPE_PER_PLOIDY + 1; + if (cmp < 0) + result = genotypeAlleleCounts[index + 1]; + else if (cmp == 0) { + result = genotypeAlleleCounts[index].clone(); + result.increase(); + } else { + alleleCounts.increase(); + result = alleleCounts; + } + return result; + } + + /** + * General genotype likelihood component by thread calculator. It does not make any assumption in the exact + * number of alleles present in the genotype. + */ + private void manyComponentGenotypeLikelihoodByRead(final GenotypeAlleleCounts genotypeAlleleCounts, + final double[] likelihoodByRead, + final double[]readLikelihoodComponentsByAlleleCount, + final int readCount) { + + // First we collect the allele likelihood component for all reads and place it + // in readGenotypeLikelihoodComponents for the final calculation per read. + genotypeAlleleCounts.copyAlleleCounts(genotypeAllelesAndCounts,0); + final int componentCount = genotypeAlleleCounts.distinctAlleleCount(); + final int alleleDataSize = (ploidy + 1) * readCount; + for (int c = 0,cc = 0; c < componentCount; c++) { + final int alleleIndex = genotypeAllelesAndCounts[cc++]; + final int alleleCount = genotypeAllelesAndCounts[cc++]; + // alleleDataOffset will point to the index of the first read likelihood for that allele and allele count. + int alleleDataOffset = alleleDataSize * alleleIndex + alleleCount * readCount; + for (int r = 0, readDataOffset = c; r < readCount; r++, readDataOffset += maximumDistinctAllelesInGenotype) + readGenotypeLikelihoodComponents[readDataOffset] = readLikelihoodComponentsByAlleleCount[alleleDataOffset++]; + } + + // Calculate the likelihood per read. + for (int r = 0, readDataOffset = 0; r < readCount; r++, readDataOffset += maximumDistinctAllelesInGenotype) + likelihoodByRead[r] = MathUtils.approximateLog10SumLog10(readGenotypeLikelihoodComponents, readDataOffset, readDataOffset + componentCount); + } + + /** + * Calculates the likelihood component by read for a given genotype allele count assuming that there are + * exactly two alleles present in the genotype (with arbitrary non-zero counts each). + */ + private void twoComponentGenotypeLikelihoodByRead(final GenotypeAlleleCounts genotypeAlleleCounts, + final double[] likelihoodByRead, + final double[] readLikelihoodComponentsByAlleleCount, + final int readCount) { + final int allele0 = genotypeAlleleCounts.alleleIndexAt(0); + final int freq0 = genotypeAlleleCounts.alleleCountAt(0); + final int allele1 = genotypeAlleleCounts.alleleIndexAt(1); + final int freq1 = ploidy - freq0; // no need to get it from genotypeAlleleCounts. + int allele0LnLkOffset = readCount * ((ploidy + 1) * allele0 + freq0); + int allele1LnLkOffset = readCount * ((ploidy + 1) * allele1 + freq1); + for (int r = 0; r < readCount; r++) { + final double lnLk0 = readLikelihoodComponentsByAlleleCount[allele0LnLkOffset++]; + final double lnLk1 = readLikelihoodComponentsByAlleleCount[allele1LnLkOffset++]; + likelihoodByRead[r] = MathUtils.approximateLog10SumLog10(lnLk0,lnLk1); + } + } + + /** + * Calculates the likelihood component by read for a given genotype allele count assuming that there are + * exactly one allele present in the genotype. + */ + private void singleComponentGenotypeLikelihoodByRead(final GenotypeAlleleCounts genotypeAlleleCounts, + final double[] likelihoodByRead, final double[] readLikelihoodComponentsByAlleleCount, final int readCount) { + final int allele = genotypeAlleleCounts.alleleIndexAt(0); + // the count of the only component must be = ploidy. + int offset = (allele * (ploidy + 1) + ploidy) * readCount; + for (int r = 0; r < readCount; r++) + likelihoodByRead[r] = + readLikelihoodComponentsByAlleleCount[offset++]; + } + + /** + * Returns a 3rd matrix with the likelihood components. + * + *+ * result[y][z][x] := z * lnLk ( read_x | allele_y ). + *+ * + * @return never {@code null}. + */ + private double[] readLikelihoodComponentsByAlleleCount(final ReadLikelihoods.Matrix likelihoods) { + final int readCount = likelihoods.readCount(); + final int alleleDataSize = readCount * (ploidy + 1); + + // frequency1Offset = readCount to skip the useless frequency == 0. So now we are at the start frequency == 1 + // frequency1Offset += alleleDataSize to skip to the next allele index data location (+ readCount) at each iteration. + for (int a = 0, frequency1Offset = readCount; a < alleleCount; a++, frequency1Offset += alleleDataSize) { + likelihoods.copyAlleleLikelihoods(a, readAlleleLikelihoodByAlleleCount, frequency1Offset); + + // p = 2 because the frequency == 1 we already have it. + for (int frequency = 2, destinationOffset = frequency1Offset + readCount; frequency <= ploidy; frequency++) { + final double log10frequency = log10[frequency]; + for (int r = 0, sourceOffset = frequency1Offset; r < readCount; r++) + readAlleleLikelihoodByAlleleCount[destinationOffset++] = + readAlleleLikelihoodByAlleleCount[sourceOffset++] + log10frequency; + } + } + return readAlleleLikelihoodByAlleleCount; + } + + /** + * Returns the ploidy for this genotype likelihood calculator. + * @return 0 or greater. + */ + public int ploidy() { + return ploidy; + } + + /** + * Returns the total number of alleles for this genotype calculator. + * @return the number of alleles considered by this calculator. + */ + public int alleleCount() { + return alleleCount; + } + + /** + * Returns the likelihood index given the allele counts. + * + * @param alleleCountArray the query allele counts. This must follow the format returned by + * {@link GenotypeAlleleCounts#copyAlleleCounts} with 0 offset. + * + * @throws IllegalArgumentException if {@code alleleCountArray} is not a valid {@code allele count array}: + *
+ * This class provide genotype likelihood calculators with any number of alleles able given an arbitrary ploidy and allele + * count (number of distinct alleles). + *
+ * + *+ * This class is thread-safe. + *
+ * + * @author Valentin Ruano-Rubio <valentin@broadinstitute.org> + */ +public class GenotypeLikelihoodCalculators { + + /** + * Maximum possible number of genotypes that this calculator can handle. + */ + public static final int MAXIMUM_STRONG_REF_GENOTYPE_PER_PLOIDY = 1000; + + /** + * Mark to indicate genotype-count overflow due to a large number of allele and ploidy; + */ + protected static final int GENOTYPE_COUNT_OVERFLOW = -1; + + /** + * The current maximum allele index supported by the tables. + *+ * Its initial value indicates the initial capacity of the shared {@link #alleleFirstGenotypeOffsetByPloidy} table. + * Feel free to change it to anything reasonable that is non-negative. + *
+ */ + private static int maximumAllele = 1; // its initial value is the initial capacity of the shared tables. + + /** + * The current maximum ploidy supported by the tables. + *+ * Its initial value indicates the initial capacity of the shared {@link #genotypeTableByPloidy}. Feel free + * to change it to anything reasonable that is non-negative. + *
+ */ + private static int maximumPloidy = 2; // its initial value is the initial capacity of the shared tables. + + /** + * Shared copy of the offset table as described in {@link #buildGenotypeAlleleCountsTable(int, int, int[][])}. + * + * This reference holds the largest requested so far in terms of maximum-allele and maximum-ploidy. + */ + private volatile static int[][] alleleFirstGenotypeOffsetByPloidy = + buildAlleleFirstGenotypeOffsetTable(maximumPloidy, maximumAllele); + + + /** + * Shared table of genotypes give the ploidy sorted by their index in the likelihood array. + * + *+ * Its format is described in {@link #buildGenotypeAlleleCountsTable(int, int, int[][])}. + *
+ */ + private volatile static GenotypeAlleleCounts[][] genotypeTableByPloidy = + buildGenotypeAlleleCountsTable(maximumPloidy,maximumAllele,alleleFirstGenotypeOffsetByPloidy); + + + + /** + * Build the table with the genotype offsets based on ploidy and the maximum allele index with representation + * in the genotype. + *+ * The result is a matrix containing the offset of the first genotype that contain a particular allele + * stratified by ploidy. + *
+ * Row (first dimension) represent the ploidy, whereas + * the second dimension represents the allele. + *
+ * + *
+ * Thus the value a position [p][a] indicates how many genotypes of ploidy p there are before the first
+ * one that contains allele a.
+ *
+ * For example, considering ploidy 3 and alleles A, B, C, D, etc ... (indexed 0, 1, 2, ... respectively):
+ *
+ * [3][A] == [3][0] == 0 as the first genotype AAA contains A.
+ *
+ * [3][C] == [3][2] == 4 as the first genotype that contains C, AAC follows: AAA AAB ABB BBB
+ *
+ * [4][D] == [4][3] == 14 as the first genotype that contains D, AAAD follows: AAAA AAAB AABB ABBB BBBB AAAC
+ * AABC ABBC BBBC AACC ABCC BBCC ACCC BCCC CCCC.
+ *
+ *
+ * This value are calculated recursively as follows: + *
+ *+ * + * Offset[p][a] := Offset[p-1][a] + Offset[p][a-1] when a > 0, p > 0 + * 0 when a == 0 + * 1 otherwise + * + * + * 0 1 1 1 1 1 1 ... + * 0 1 2 3 4 5 6 ... + * 0 1 3 6 10 15 21 ... + * 0 1 4 10 20 35 56 ... + * 0 1 5 15 35 70 126 ... + * 0 .................. + *+ * + *
+ * Note: if someone can come with a close form computable 0(1) (respect to ploidy and allele count) + * please let the author know. + *
+ * + *+ * The matrix is guaranteed to have as many rows as indicated by {@code maximumPloidy} + 1; the first + * row refers to the special case of ploidy == 0, the second row to ploidy 1 and so forth. Thus the ploidy + * matches the index. + *
+ *+ * The matrix is guaranteed to have as many columns as indicate by {@code maximumAllele} + 1. In this case however + * the first allele index 0 is a sense allele (typically the reference allele). The reason to have at least the total + * genotype count up to allele count {@link @alleleCapacity} that is equal to the offset of the first genotype + * of the following allele; thus we need an extra one. + *
+ * + *+ * Although it might seem non-sense to have genotypes of ploidy 0. The values in the first row are used when + * filling up values in row 1 and so forth so it is present for programmatic convenience. + * Offsets in this row are 0 for the first column and 1 for any others. + *
+ * + * @param maximumPloidy maximum supported ploidy. + * @param maximumAllele maximum supported allele index. + * + * @throws IllegalArgumentException if {@code maximumPloidy} or {@code maximumAllele} is negative. + * + * @return never {@code null}, the matrix described with enough information to address + * problems concerning up to the requested maximum allele index and ploidy. + */ + private static int[][] buildAlleleFirstGenotypeOffsetTable(final int maximumPloidy, final int maximumAllele) { + checkPloidyAndMaximumAllele(maximumPloidy, maximumAllele); + final int rowCount = maximumPloidy + 1; + final int colCount = maximumAllele + 1; + final int[][] result = new int[rowCount][colCount]; + + // Ploidy 0 array must be { 0, 1, 1, ...., 1} + Arrays.fill(result[0],1,colCount,1); + // Now we take care of the rest of ploidies. + // We leave the first allele offset to it correct value 0 by starting with allele := 1. + for (int ploidy = 1; ploidy < rowCount; ploidy++) + for (int allele = 1; allele < colCount; allele++) { + result[ploidy][allele] = result[ploidy][allele - 1] + result[ploidy - 1][allele]; + if (result[ploidy][allele] < result[ploidy][allele - 1]) + result[ploidy][allele] = GENOTYPE_COUNT_OVERFLOW; + } + return result; + } + + /** + * Composes a table with the lists of all possible genotype allele counts given the the ploidy and maximum allele index. + *+ * The resulting matrix has at least as many rows as {@code maximumPloidy } + 1 as the first row with index 0 correspond + * to ploidy == 0. Each row array has as many positions as necessary to contain all possible genotype-allele-counts in increasing order. + * This quantity varies with the ploidy. + *
+ * + *
+ * Therefore result[3][4] would contain the 5th genotype with ploidy 3, and result[4].length
+ * would be equal to the count of possible genotypes for ploidy 4.
+ *
+ * The result is guarantee to have exactly {@code length} positions and the elements are sorted + * in agreement with the standard way to display genotypes following the VCF standard. + *
+ * + *Notice that is possible to request ploidy ==0. In that case the resulting array will have repetitions + * of the empty genotype allele count. + *
+ * + *+ * For example, + * + *
+ * ploidy = 1, length = 5 : [ {A}, {B}, {C}, {D}, {E} ]
+ * ploidy = 2, length = 7 : [ {AA}, {AB}, {BB}, {AC}, {BC}, {CC}, {AD}
+ * ploidy = 3, length = 10 : [ {AAA}, {AAB}, {ABB}, {BBB}, {AAC}, {ABC}, {BBC}, {BCC}, {CCC}, {AAD} ]
+ *
+ *
+ *
+ * @param ploidy requested ploidy.
+ * @param alleleCount number of different alleles that the genotype table must support.
+ * @param genotypeOffsetTable table with the offset of the first genotype that contain an allele given
+ * the ploidy and its index.
+ *
+ * @throws IllegalArgumentException if {@code ploidy} or {@code length} is negative.
+ *
+ * @return never {@code null}, follows the specification above.
+ */
+ private static GenotypeAlleleCounts[] buildGenotypeAlleleCountsArray(final int ploidy, final int alleleCount, final int[][] genotypeOffsetTable) {
+ if (ploidy < 0)
+ throw new IllegalArgumentException("the requested ploidy cannot be negative: " + ploidy);
+ if (alleleCount < 0)
+ throw new IllegalArgumentException("the requested maximum allele cannot be negative: " + alleleCount);
+ final int length = genotypeOffsetTable[ploidy][alleleCount];
+ final int strongRefLength = length == GENOTYPE_COUNT_OVERFLOW ? MAXIMUM_STRONG_REF_GENOTYPE_PER_PLOIDY : Math.min(length, MAXIMUM_STRONG_REF_GENOTYPE_PER_PLOIDY);
+ final GenotypeAlleleCounts[] result = new GenotypeAlleleCounts[strongRefLength];
+ result[0] = GenotypeAlleleCounts.first(ploidy);
+ for (int genotypeIndex = 1; genotypeIndex < strongRefLength; genotypeIndex++)
+ result[genotypeIndex] = result[genotypeIndex-1].next();
+ return result;
+ }
+
+ /**
+ * Cached log10 values for the first integer up to the maximum ploidy requested thus far.
+ */
+ private volatile static double[] ploidyLog10;
+
+ // Initialize {@link #ploidyLog10}.
+ static {
+ ploidyLog10 = new double[maximumPloidy + 1];
+ for (int i = 0; i <= maximumPloidy; i++)
+ ploidyLog10[i] = Math.log10(i);
+ }
+
+ /**
+ * Returns an instance given its ploidy and the number of alleles.
+ *
+ * @param alleleCount the required allele-count.
+ * @param ploidy the required ploidy-count.
+ *
+ * @throws IllegalArgumentException if either {@code ploidy} or {@code alleleCount} is {@code null}, or
+ * the resulting number of genotypes is too large.
+ *
+ * @return never {@code null}.
+ */
+ public static GenotypeLikelihoodCalculator getInstance(final int ploidy,
+ final int alleleCount) {
+ checkPloidyAndMaximumAllele(ploidy, alleleCount);
+ if (alleleCount < 0)
+ throw new IllegalArgumentException("the allele count cannot be negative");
+ if (ploidy < 0)
+ throw new IllegalArgumentException("the ploidy count cannot be negative");
+
+ // Non-thread safe (fast) check on tables capacities,
+ // if not enough capacity we expand the tables in a thread-safe manner:
+ if (alleleCount > maximumAllele || ploidy > maximumPloidy)
+ ensureCapacity(alleleCount, ploidy);
+
+ // At this point the tables must have at least the requested capacity, likely to be much more.
+ return new GenotypeLikelihoodCalculator(ploidy,alleleCount,alleleFirstGenotypeOffsetByPloidy,genotypeTableByPloidy,ploidyLog10);
+ }
+
+ /**
+ * Thread safe update of shared tables
+ *
+ * @param requestedMaximumAllele the new requested maximum allele maximum.
+ * @param requestedMaximumPloidy the new requested ploidy maximum.
+ */
+ private synchronized static void ensureCapacity(final int requestedMaximumAllele, final int requestedMaximumPloidy) {
+
+ final boolean needsToExpandAlleleCapacity = requestedMaximumAllele > maximumAllele;
+ final boolean needsToExpandPloidyCapacity = requestedMaximumPloidy > maximumPloidy;
+
+ // Double check with the lock on to avoid double work.
+ if (!needsToExpandAlleleCapacity && !needsToExpandPloidyCapacity)
+ return;
+
+ final int newMaximumPloidy = Math.max(maximumPloidy,requestedMaximumPloidy);
+ final int newMaximumAllele = Math.max(maximumAllele,requestedMaximumAllele);
+
+ // Update tables first.
+ alleleFirstGenotypeOffsetByPloidy = buildAlleleFirstGenotypeOffsetTable(newMaximumPloidy,newMaximumAllele);
+ genotypeTableByPloidy = buildGenotypeAlleleCountsTable(newMaximumPloidy,newMaximumAllele,alleleFirstGenotypeOffsetByPloidy);
+
+ if (needsToExpandPloidyCapacity)
+ ploidyLog10 = ploidyLog10Extension(newMaximumPloidy);
+
+ // Since tables are volatile fields, it is guaranteed that tables changes will be seen before
+ // than any change on ploidyCapacity and alleleCapacity ensuring that the non-thread safe
+ // capacity verification test in {@link #getInstance} wont ever allow a thread
+ // to proceed to use a table without the required capacity.
+ // Just after updating tables update the capacity fields:
+
+ if (needsToExpandAlleleCapacity)
+ maximumAllele = requestedMaximumAllele;
+ if (needsToExpandPloidyCapacity)
+ maximumPloidy = requestedMaximumPloidy;
+ }
+
+ /**
+ * Extends the existing {@link #ploidyLog10} with more log10 as needed by maximum-ploidy expansion.
+ * @param newMaximumPloidy the new maximum ploidy.
+ *
+ * @return never code {@code null}.
+ */
+ private static double[] ploidyLog10Extension(final int newMaximumPloidy) {
+ final int start = ploidyLog10.length;
+ final double[] result = Arrays.copyOf(ploidyLog10,newMaximumPloidy + 1);
+ for (int i = start; i < result.length; i++)
+ result[i] = Math.log10(i);
+ return result;
+ }
+
+ /**
+ * Perform value checks on maximumPloidy and allele passed to diverse methods in this class.
+ * + * Throws an exception if there is any issues. + *
+ * + * @param ploidy the maximum ploidy value. + * @param maximumAllele the maximum allele value. + * + * @throws IllegalArgumentException if either value is negative. + */ + private static void checkPloidyAndMaximumAllele(final int ploidy, final int maximumAllele) { + if (ploidy < 0) + throw new IllegalArgumentException("the ploidy provided cannot be negative: " + ploidy); + if (maximumAllele < 0) + throw new IllegalArgumentException("the maximum allele index provided cannot be negative: " + maximumAllele); + } + + private static void checkOffsetTableCapacity(final int[][] offsetTable, final int maximumPloidy, final int maximumAllele) { + if (offsetTable == null) + throw new IllegalArgumentException("the allele first genotype offset table provided cannot be null"); + if (offsetTable.length <= maximumPloidy ) + throw new IllegalArgumentException("the allele first genotype offset table provided does not have enough " + + "capacity for requested maximum ploidy: " + maximumPloidy); + if (offsetTable[0].length < maximumAllele) + throw new IllegalArgumentException("the allele first genotype offset table provided does not have enough " + + "capacity for requested maximum allele index: " + maximumAllele); + } + + +} \ No newline at end of file diff --git a/protected/gatk-tools-protected/src/main/java/org/broadinstitute/gatk/utils/collections/IntMaxHeap.java b/protected/gatk-tools-protected/src/main/java/org/broadinstitute/gatk/utils/collections/IntMaxHeap.java new file mode 100644 index 000000000..760052b8c --- /dev/null +++ b/protected/gatk-tools-protected/src/main/java/org/broadinstitute/gatk/utils/collections/IntMaxHeap.java @@ -0,0 +1,230 @@ +/* +* By downloading the PROGRAM you agree to the following terms of use: +* +* BROAD INSTITUTE - SOFTWARE LICENSE AGREEMENT - FOR ACADEMIC NON-COMMERCIAL RESEARCH PURPOSES ONLY +* +* This Agreement is made between the Broad Institute, Inc. with a principal address at 7 Cambridge Center, Cambridge, MA 02142 (BROAD) and the LICENSEE and is effective at the date the downloading is completed (EFFECTIVE DATE). +* +* WHEREAS, LICENSEE desires to license the PROGRAM, as defined hereinafter, and BROAD wishes to have this PROGRAM utilized in the public interest, subject only to the royalty-free, nonexclusive, nontransferable license rights of the United States Government pursuant to 48 CFR 52.227-14; and +* WHEREAS, LICENSEE desires to license the PROGRAM and BROAD desires to grant a license on the following terms and conditions. +* NOW, THEREFORE, in consideration of the promises and covenants made herein, the parties hereto agree as follows: +* +* 1. DEFINITIONS +* 1.1 PROGRAM shall mean copyright in the object code and source code known as GATK2 and related documentation, if any, as they exist on the EFFECTIVE DATE and can be downloaded from http://www.broadinstitute/GATK on the EFFECTIVE DATE. +* +* 2. LICENSE +* 2.1 Grant. Subject to the terms of this Agreement, BROAD hereby grants to LICENSEE, solely for academic non-commercial research purposes, a non-exclusive, non-transferable license to: (a) download, execute and display the PROGRAM and (b) create bug fixes and modify the PROGRAM. +* The LICENSEE may apply the PROGRAM in a pipeline to data owned by users other than the LICENSEE and provide these users the results of the PROGRAM provided LICENSEE does so for academic non-commercial purposes only. For clarification purposes, academic sponsored research is not a commercial use under the terms of this Agreement. +* 2.2 No Sublicensing or Additional Rights. LICENSEE shall not sublicense or distribute the PROGRAM, in whole or in part, without prior written permission from BROAD. LICENSEE shall ensure that all of its users agree to the terms of this Agreement. LICENSEE further agrees that it shall not put the PROGRAM on a network, server, or other similar technology that may be accessed by anyone other than the LICENSEE and its employees and users who have agreed to the terms of this agreement. +* 2.3 License Limitations. Nothing in this Agreement shall be construed to confer any rights upon LICENSEE by implication, estoppel, or otherwise to any computer software, trademark, intellectual property, or patent rights of BROAD, or of any other entity, except as expressly granted herein. LICENSEE agrees that the PROGRAM, in whole or part, shall not be used for any commercial purpose, including without limitation, as the basis of a commercial software or hardware product or to provide services. LICENSEE further agrees that the PROGRAM shall not be copied or otherwise adapted in order to circumvent the need for obtaining a license for use of the PROGRAM. +* +* 3. OWNERSHIP OF INTELLECTUAL PROPERTY +* LICENSEE acknowledges that title to the PROGRAM shall remain with BROAD. The PROGRAM is marked with the following BROAD copyright notice and notice of attribution to contributors. LICENSEE shall retain such notice on all copies. LICENSEE agrees to include appropriate attribution if any results obtained from use of the PROGRAM are included in any publication. +* Copyright 2012 Broad Institute, Inc. +* Notice of attribution: The GATK2 program was made available through the generosity of Medical and Population Genetics program at the Broad Institute, Inc. +* LICENSEE shall not use any trademark or trade name of BROAD, or any variation, adaptation, or abbreviation, of such marks or trade names, or any names of officers, faculty, students, employees, or agents of BROAD except as states above for attribution purposes. +* +* 4. INDEMNIFICATION +* LICENSEE shall indemnify, defend, and hold harmless BROAD, and their respective officers, faculty, students, employees, associated investigators and agents, and their respective successors, heirs and assigns, (Indemnitees), against any liability, damage, loss, or expense (including reasonable attorneys fees and expenses) incurred by or imposed upon any of the Indemnitees in connection with any claims, suits, actions, demands or judgments arising out of any theory of liability (including, without limitation, actions in the form of tort, warranty, or strict liability and regardless of whether such action has any factual basis) pursuant to any right or license granted under this Agreement. +* +* 5. NO REPRESENTATIONS OR WARRANTIES +* THE PROGRAM IS DELIVERED AS IS. BROAD MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE PROGRAM OR THE COPYRIGHT, EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, WHETHER OR NOT DISCOVERABLE. BROAD EXTENDS NO WARRANTIES OF ANY KIND AS TO PROGRAM CONFORMITY WITH WHATEVER USER MANUALS OR OTHER LITERATURE MAY BE ISSUED FROM TIME TO TIME. +* IN NO EVENT SHALL BROAD OR ITS RESPECTIVE DIRECTORS, OFFICERS, EMPLOYEES, AFFILIATED INVESTIGATORS AND AFFILIATES BE LIABLE FOR INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, INCLUDING, WITHOUT LIMITATION, ECONOMIC DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER BROAD SHALL BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT SHALL KNOW OF THE POSSIBILITY OF THE FOREGOING. +* +* 6. ASSIGNMENT +* This Agreement is personal to LICENSEE and any rights or obligations assigned by LICENSEE without the prior written consent of BROAD shall be null and void. +* +* 7. MISCELLANEOUS +* 7.1 Export Control. LICENSEE gives assurance that it will comply with all United States export control laws and regulations controlling the export of the PROGRAM, including, without limitation, all Export Administration Regulations of the United States Department of Commerce. Among other things, these laws and regulations prohibit, or require a license for, the export of certain types of software to specified countries. +* 7.2 Termination. LICENSEE shall have the right to terminate this Agreement for any reason upon prior written notice to BROAD. If LICENSEE breaches any provision hereunder, and fails to cure such breach within thirty (30) days, BROAD may terminate this Agreement immediately. Upon termination, LICENSEE shall provide BROAD with written assurance that the original and all copies of the PROGRAM have been destroyed, except that, upon prior written authorization from BROAD, LICENSEE may retain a copy for archive purposes. +* 7.3 Survival. The following provisions shall survive the expiration or termination of this Agreement: Articles 1, 3, 4, 5 and Sections 2.2, 2.3, 7.3, and 7.4. +* 7.4 Notice. Any notices under this Agreement shall be in writing, shall specifically refer to this Agreement, and shall be sent by hand, recognized national overnight courier, confirmed facsimile transmission, confirmed electronic mail, or registered or certified mail, postage prepaid, return receipt requested. All notices under this Agreement shall be deemed effective upon receipt. +* 7.5 Amendment and Waiver; Entire Agreement. This Agreement may be amended, supplemented, or otherwise modified only by means of a written instrument signed by all parties. Any waiver of any rights or failure to act in a specific instance shall relate only to such instance and shall not be construed as an agreement to waive any rights or fail to act in any other instance, whether or not similar. This Agreement constitutes the entire agreement among the parties with respect to its subject matter and supersedes prior agreements or understandings between the parties relating to its subject matter. +* 7.6 Binding Effect; Headings. This Agreement shall be binding upon and inure to the benefit of the parties and their respective permitted successors and assigns. All headings are for convenience only and shall not affect the meaning of any provision of this Agreement. +* 7.7 Governing Law. This Agreement shall be construed, governed, interpreted and applied in accordance with the internal laws of the Commonwealth of Massachusetts, U.S.A., without regard to conflict of laws principles. +*/ +package org.broadinstitute.gatk.utils.collections; + +import java.util.Arrays; + +/** + * Simple integer heap with quick look-up of the minimum value. + * + * @author Valentin Ruano-Rubio <valentin@broadinstitute.org> + */ +public class IntMaxHeap { + + private int size; + + private int[] values; + + /** + * Creates a new empty heap indicating its initial capacity. + * @param initialCapacity number of elements you expect to have at most in the heap. + * + * @throws IllegalArgumentException if {@code initialCapacity} is negative. + */ + public IntMaxHeap(final int initialCapacity) { + if (initialCapacity < 0) + throw new IllegalArgumentException(); + // We force it to have at least length 1 so that the capacity expansion works when adding; + // it doubles current length and twice 0 = 0. + values = new int[initialCapacity == 0 ? 1 : initialCapacity]; + } + + /** + * Adds a new element to the heap. + * + *The heap with grow if it runs out of capacity to hold the new element
+ * + * @param v the new element. + */ + public void add(final int v) { + // Double capacity if overflow: + ensureCapacity(size + 1); + addWithoutCheckingCapacity(v); + } + + /** + * Implements the heap addition floating up the value. + * @param v the value to add. + */ + private void addWithoutCheckingCapacity(final int v) { + int p; + values[p = size++] = v; + + // Float up the recently added element: + while (p > 0) { + final int q = (p - 1) >> 1; // parent index. + final int u = values[q]; // parent value. + + //Finish check and update: + if (u >= v) + break; + values[p] = u; + values[q] = v; + p = q; + } + } + + /** + * Add several integers into the heap. + * @param v values to add. + */ + public void add(final int ... v) { + if (v == null) + throw new IllegalArgumentException("the input array cannot be null"); + ensureCapacity(v.length + size); + for (int i : v) + addWithoutCheckingCapacity(i); + } + + private void ensureCapacity(final int newSize) { + if (newSize > values.length) + values = Arrays.copyOf(values,Math.max(newSize,10 + values.length << 1)); + } + + /** + * Returns the current minimum element. + * + * @throws IllegalStateException if the heap is empty. + * + * @return the minimum element in the heap. + */ + public int peek() { + if (size == 0) + throw new IllegalStateException("the heap is empty"); + return values[0]; + } + + /** + * Returns the minimum element of the heap and removes it. + * + * @throws IllegalStateException if the heap is empty. + * + * @return the minimum element in the heap before removing it. + */ + public int remove() { + if (size == 0) + throw new IllegalArgumentException("the heap is empty"); + final int result = values[0]; + removeUpdate(); + return result; + } + + /** + * Updates the heap after a removal, sinking the last element from the top-down. + */ + private void removeUpdate() { + // if the remove make the heap to be empty there is nothing to do. + if (--size == 0) + return; + + final int v = values[size]; // the last value. + + int p; + values[p = 0] = v; + + // limit := first index in the heap that does not have any descendants within the heap. + final int limit = (size >> 1); + + // Sorry! for the big loop but doesn't seem to be any other *practical* option that would reduce its size. + while (p < limit) { + + // Initialize variables: + final int r = (p + 1) << 1; // left descendant index. + final int l = r - 1; // right descendant index (no guarantee to be in the heap). + int u = v; // will contain min(v,values[l],values[r]). + int q = p; // wilL contain argmin_x(values[x], x in {p,l,r}). + + // Check left descendant: + int lv = values[l]; // left descendant value. + if (lv > u) { // is the left descendant'v value more than v. + u = lv; + q = l; + } + + // Check right descendant: + if (r < size) { // make sure that r is within the heap. + int rv = values[r]; + if (rv > u) { // is the right descendant's value less than v or left's + u = rv; + q = r; + } + } + + // Finish check and update: + if (p == q) // q == p if neither left or right descendants are less than v. + break; + + values[p] = u; + values[q] = v; + p = q; + } + } + + /** + * Checks whether the heap is empty. + * + * @return {@code true} iff the heap is empty. + */ + public boolean isEmpty() { + return size == 0; + } + + /** + * Returns the current size of the heap. + * + * @return 0 or greater. + */ + public int size() { + return size; + } + + /** + * Removes all elements from the heap. + */ + public void clear() { + size = 0; + } +} diff --git a/public/gatk-tools-public/src/main/java/org/broadinstitute/gatk/utils/MathUtils.java b/public/gatk-tools-public/src/main/java/org/broadinstitute/gatk/utils/MathUtils.java index 56d19c64a..4e47da387 100644 --- a/public/gatk-tools-public/src/main/java/org/broadinstitute/gatk/utils/MathUtils.java +++ b/public/gatk-tools-public/src/main/java/org/broadinstitute/gatk/utils/MathUtils.java @@ -151,6 +151,32 @@ public class MathUtils { return approximateLog10SumLog10(vals, vals.length); } + /** + * Calculate the approximate log10 sum of an array range. + * @param vals the input values. + * @param fromIndex the first inclusive index in the input array. + * @param toIndex index following the last element to sum in the input array (exclusive). + * @return the approximate sum. + * @throws IllegalArgumentException if {@code vals} is {@code null} or {@code fromIndex} is out of bounds + * or if {@code toIndex} is larger than + * the length of the input array or {@code fromIndex} is larger than {@code toIndex}. + */ + public static double approximateLog10SumLog10(final double[] vals, final int fromIndex, final int toIndex) { + if (fromIndex == toIndex) return Double.NEGATIVE_INFINITY; + final int maxElementIndex = MathUtils.maxElementIndex(vals,fromIndex,toIndex); + double approxSum = vals[maxElementIndex]; + + for (int i = fromIndex; i < toIndex; i++) { + final double val; + if (i == maxElementIndex || (val = vals[i]) == Double.NEGATIVE_INFINITY) + continue; + final double diff = approxSum - val; + if (diff < JacobianLogTable.MAX_TOLERANCE) + approxSum += JacobianLogTable.get(diff); + } + return approxSum; + } + public static double approximateLog10SumLog10(final double[] vals, final int endIndex) { final int maxElementIndex = MathUtils.maxElementIndex(vals, endIndex); From 4f993e8dbef64036269a05d0de3a8199d4b50c79 Mon Sep 17 00:00:00 2001 From: Valentin Ruano-RubioIn order to save CPU time the indices contained in this array (not the array itself) is + * lazily initialized by invoking {@link #readIndexBySampleIndex(int)}.
*/ private final Object2IntMap- * The matrix is indexed by allele and the by read index. - * - *
- * result[a][r] == lnLk(Read_r | Allele_a) - *- * - * - *
- * The matrix is live and changes to it update the likelihood in the collection, please use with care. - *
- * - * @param sampleIndex the sample index. - * - * @return never {@code null}. - */ - /* package */ double[][] sampleValues(final int sampleIndex) { - checkSampleIndex(sampleIndex); - return valuesBySampleIndex[sampleIndex]; - } - - /** * Returns a read vs allele likelihood matrix corresponding to a sample. * @@ -441,7 +337,7 @@ public class ReadLikelihoods implements Cloneable { if (maximumLikelihoodDifferenceCap == Double.NEGATIVE_INFINITY && !bestToZero) return; - final int alleleCount = alleles.length; + final int alleleCount = alleles.alleleCount(); if (alleleCount == 0) // trivial case there is no alleles. return; else if (alleleCount == 1 && !bestToZero) @@ -469,19 +365,20 @@ public class ReadLikelihoods implements Cloneable { final double bestAbsoluteLikelihood = Math.max(bestAlternativeAllele.likelihood,referenceLikelihood); + final int alleleCount = alleles.alleleCount(); if (bestToZero) { if (bestAbsoluteLikelihood == Double.NEGATIVE_INFINITY) - for (int a = 0; a < alleles.length; a++) + for (int a = 0; a < alleleCount; a++) sampleValues[a][readIndex] = 0; else if (worstLikelihoodCap != Double.NEGATIVE_INFINITY) - for (int a = 0; a < alleles.length; a++) + for (int a = 0; a < alleleCount; a++) sampleValues[a][readIndex] = (sampleValues[a][readIndex] < worstLikelihoodCap ? worstLikelihoodCap : sampleValues[a][readIndex]) - bestAbsoluteLikelihood; else - for (int a = 0; a < alleles.length; a++) + for (int a = 0; a < alleleCount; a++) sampleValues[a][readIndex] -= bestAbsoluteLikelihood; } else // else if (maximumReferenceLikelihoodFall != Double.NEGATIVE_INFINITY ) { // - // Guarantee to be the case by enclosing code. - for (int a = 0; a < alleles.length; a++) + // Guarantee to be the case by enclosing code. + for (int a = 0; a < alleleCount; a++) if (sampleValues[a][readIndex] < worstLikelihoodCap) sampleValues[a][readIndex] = worstLikelihoodCap; } @@ -499,9 +396,8 @@ public class ReadLikelihoods implements Cloneable { * @return never {@code null}. */ public List- * If not, it throws an exception. - *
- * @param alleleIndex the target sample index. - * - * @throws IllegalArgumentException if {@code alleleIndex} is invalid, i.e. outside the range [0,{@link #sampleCount}). - */ - private void checkAlleleIndex(final int alleleIndex) { - if (alleleIndex < 0 || alleleIndex >= alleles.length) - throw new IllegalArgumentException("invalid allele index: " + alleleIndex); - } } \ No newline at end of file From f08dcbc160abcccd9acec7df748ac38868949757 Mon Sep 17 00:00:00 2001 From: Valentin Ruano-Rubio+ * Notice that this constructor does not check whether the likelihood array lengths corresponds to the sample plodies and + * number of alleles. + *
+ * + * @param alleles the genotyping alleles. + * @param ploidyModel the ploidy model. + * @param likelihoods the actual genotype likelihoods, one element per sample. + * + * @throws IllegalArgumentException if any argument is {@code null}, or the number of samples in {@code ploidyModel} + * does not correspond with the number of likelihoods arrays in {@code likelihoods} + */ + GenotypingLikelihoods(final AlleleList alleles, final PloidyModel ploidyModel, + final List+ * Consequently genotypes calls between samples are totally independent conditional to the frequencies in + * the population they coming from. And genotypes should exhibit the ratios expected under HWE. + *
+ * Therefore each sample genotype likelihoods can be considered to + * be independent from all other samples. + * + * @author Valentin Ruano-Rubio <valentin@broadinstitute.org> + */ +public class InfiniteRandomMatingPopulationModel implements GenotypingModel { + + @Override + public GenotypingLikelihoods calculateLikelihoods(final AlleleList genotypingAlleles, final GenotypingData data) { + if (genotypingAlleles == null) + throw new IllegalArgumentException("the allele cannot be null"); + if (data == null) + throw new IllegalArgumentException("the genotyping data cannot be null"); + + final AlleleListPermutation permutation = AlleleListUtils.permutation(data,genotypingAlleles); + final AlleleLikelihoodMatrixMapper alleleLikelihoodMatrixMapper = AlleleLikelihoodMatrixMapper.newInstance(permutation); + + final int sampleCount = data.sampleCount(); + + switch (sampleCount) { + case 0: return noSampleLikelihoods(permutation,data); + case 1: return singleSampleLikelihoods(genotypingAlleles,data,alleleLikelihoodMatrixMapper); + default: + final PloidyModel ploidyModel = data.ploidyModel(); + return ploidyModel.isHomogeneous() ? multiSampleHomogeneousPloidyModelLikelihoods(genotypingAlleles, data, alleleLikelihoodMatrixMapper, sampleCount, ploidyModel) + : multiSampleHeterogeneousPloidyModelLikelihoods(genotypingAlleles, data, alleleLikelihoodMatrixMapper, sampleCount, ploidyModel); + } + } + + private GenotypingLikelihoods noSampleLikelihoods(final AlleleList genotypingAlleles, + final GenotypingData data) { + @SuppressWarnings("unchecked") + final List+ * It must match the sum of all ploidies across samples. + *
+ * + * @return 0 or greater. + */ + public int totalPloidy(); +} From 9ee9da36bb206d57b07987bdc10c9bbda69f3516 Mon Sep 17 00:00:00 2001 From: Valentin Ruano-Rubio