Added genotype allele counts and likelihood calculator utilities for arbitrary ploidy and number of alleles

This commit is contained in:
Valentin Ruano-Rubio 2014-06-04 01:36:52 -04:00
parent b0a4cb9f0c
commit 242cd0e58f
5 changed files with 1941 additions and 0 deletions

View File

@ -0,0 +1,707 @@
/*
* 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 org.broadinstitute.gatk.utils.MathUtils;
import java.util.Arrays;
/**
* Collection of allele counts for a genotype. It encompasses what alleles are present in the genotype and in what number.</p>
*
* <p>Alleles are represented herein by their indices running from <b>0</b> to <b>N-1</b> where <i>N</i> is the number of alleles.</p>
*
* <p>Each allele present in a genotype (count != 0) has a <i>rank</i>, that is the 0-based ordinal of
* that allele amongst the ones present in the genotype as sorted by their index.</p>
*
* <p>For example:</p>
*
* <p><b>0/0/2/2</b> has two alleles with indices <b>0</b> and <b>2</b>, both with count 2.
* The rank of <b>0</b> is <i>0</i> whereas the rank of <b>2</b> is <i>1</i>.</p>
*
* <p><b>2/4/4/7</b> has three alleles with indices <b>2</b>, <b>4</b> and <b>7</b>. <b>2</b> and <b>7</b> have count 1 whereas <b>4</b> has count 2.
* The rank of <b>2</b> is <i>0</i>, the rank of <b>4</b> is <i>1</i>. and the rank of <b>7</b> is <i>2</i>.</p>
*
* <p>In contrast, in both examples above both <b>3</b> and <b>10</b> (and many others) are absent thus they have no rank (represented by <i>-1</i> whenever applies).</p>
*
* <p>{@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.</p>
*
* <p>For example, for ploidy 3:</p>
*
* <table>
* <th>Index</th><th>Genotype</th>
* <tr><td>0</td><td><b>0/0/0</b></td></tr>
* <tr><td>1</td><td><b>0/0/1</b></td></tr>
* <tr><td>2</td><td><b>0/1/1</b></td></tr>
* <tr><td>3</td><td><b>1/1/1</b></td></tr>
* <tr><td>4</td><td><b>0/0/2</b></td></tr>
* <tr><td>6</td><td><b>0/1/2</b></td></tr>
* <tr><td>7</td><td><b>1/1/2</b></td></tr>
* <tr><td>8</td><td><b>0/2/2</b></td></tr>
* <tr><td>9</td><td><b>1/2/2</b></td></tr>
* <tr><td>10</td><td><b>2/2/2</b></td></tr>
* <tr><td>11</td><td><b>0/0/3</b></td></tr>
* <tr><td>12</td><td><b>0/1/3</b></td></tr>
* <tr><td>13</td><td><b>1/1/3</b></td></tr>
* <tr><td>14</td><td><b>0/2/3</b></td></tr>
* <tr><td>15</td><td><b>1/2/3</b></td></tr>
* <tr><td>16</td><td><b>2/2/3</b></td></tr>
* <tr><td>17</td><td><b>0/3/3</b></td></tr>
* <tr><td>...</td><td>...</td></tr>
* </table>
*
* The total number of possible genotypes is only bounded by the maximum allele index.
*
* @author Valentin Ruano-Rubio &lt;valentin@broadinstitute.org&gt;
*/
public class GenotypeAlleleCounts implements Comparable<GenotypeAlleleCounts>, Cloneable {
private double log10CombinationCount;
/**
* The ploidy of the genotype.
*/
private final int ploidy;
/**
* Sorted array of integer pairs as described in {@link #GenotypeAlleleCounts(int, int, int...)}.
*/
private int[] sortedAlleleCounts;
/**
* Number of different alleles in the genotype.
*/
private int distinctAlleleCount;
/**
* Index of this genotype within genotypes of the same ploidy.
*/
private int index;
/**
* Creates a new unphased genotype.
*
* <p>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.</p>
*
* <p>
* 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:<br/>
*
* <pre> [allele_1,freq_1,allele_2,freq_2, ... , allele_i, freq_i, ... , allele_n, freq_n]</pre>
*
* <br/>
* No entry can have frequency == 0 (these must be omitted) and entries are sorted by allele index without
* any repetitions so that if <i>i < j</i> then <i>allele_i < allele_j</i>.
*
* </p>
*
* <p>
* The {@code ploidy} provided must be equal to the sum of all frequencies in {@code sortedAlleleCounts}
* </p>
* @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.
*
* <p>
* 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}.
* </p>
*
* @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.
*
* <p>
* 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}
* </p>
*/
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<int[]>
// as the final size of the resulting new sorted-allele-counts array varies depending on the situation.
// this is considerably faster and the logic complexity would not be that different actually so it is worth
// the if indentations.
//
// Notice that at this point distinctAlleleCount >= 2 thus sortedAlleleCounts.length >= 4.
//
// We only need to look at the two lowest allele indices to decide what to do.
final int allele0 = sortedAlleleCounts[0];
final int freq0 = sortedAlleleCounts[1];
final int allele1 = sortedAlleleCounts[2];
final int allele0Plus1 = allele0 + 1;
final boolean allele0And1AreConsecutive = allele0Plus1 == allele1;
final int[] newSortedAlleleCounts;
// The rest of the sorted allele counts array contains junk
final int sortedAlleleCountsLength = distinctAlleleCount << 1;
if (freq0 == 1) { // in this case allele0 wont be present in the result and all is frequency should go to allele0 + 1.
if (allele0And1AreConsecutive) { // need just to remove the first allele and add 1 to the frequency of the second (freq1 += 1).
System.arraycopy(sortedAlleleCounts, 2, sortedAlleleCounts, 0, sortedAlleleCountsLength - 2); // shift left the first component away.
sortedAlleleCounts[1]++; // freq1 has become freq0.
distinctAlleleCount--;
} else // just need to mutate allele0 to allele0 + 1.
sortedAlleleCounts[0] = allele0Plus1;
} else { // && freq0 > 1 as per sortedAlleleCounts format restrictions. In this case allele0 will mutated to '0' with frequency decreased by 1.
if (allele0And1AreConsecutive) { // we don't need to add a component for allele0 + 1 since it already exists.
sortedAlleleCounts[0] = 0;
sortedAlleleCounts[1] = freq0 - 1;
sortedAlleleCounts[3]++;
} else { // we need to insert allele0 + 1 in the sorted-allele-counts array and give it frequency 1.
if (sortedAlleleCounts.length < sortedAlleleCountsLength + 2) // make room for the new component.
sortedAlleleCounts = Arrays.copyOf(sortedAlleleCounts,sortedAlleleCountsLength + 2);
System.arraycopy(sortedAlleleCounts, 2, sortedAlleleCounts, 4, sortedAlleleCountsLength - 2);
sortedAlleleCounts[0] = 0;
sortedAlleleCounts[1] = freq0 - 1;
sortedAlleleCounts[2] = allele0Plus1;
sortedAlleleCounts[3] = 1;
distinctAlleleCount++;
}
}
}
index++;
log10CombinationCount = -1;
}
/**
* Calculates the next genotype in likelihood indexing order.
* @return never null.
*/
protected GenotypeAlleleCounts next() {
// if the ploidy is zero there is only one possible genotype.
if (distinctAlleleCount == 0)
return this;
// Worth make this case faster.
if (distinctAlleleCount == 1) {
if (ploidy == 1) // A -> B , D -> E etc...
return new GenotypeAlleleCounts(1, index + 1, sortedAlleleCounts[0] + 1, 1);
else // AAAAA -> AAAAB, DDD -> AAE etc...
return new GenotypeAlleleCounts(ploidy, index + 1, 0, ploidy - 1, sortedAlleleCounts[0] + 1, 1);
}
// Now, all the following ifs are just the way to avoid working with dynamically sizing List<int[]>
// as the final size of the resulting new sorted-allele-counts array varies depending on the situation.
// this is considerably faster and the logic complexity would not be that different actually so it is worth
// the if indentations.
//
// Notice that at this point distinctAlleleCount >= 2 thus sortedAlleleCounts.length >= 4.
//
// We only need to look at the two lowest allele indices to decide what to do.
final int allele0 = sortedAlleleCounts[0];
final int freq0 = sortedAlleleCounts[1];
final int allele1 = sortedAlleleCounts[2];
final int allele0Plus1 = allele0 + 1;
final boolean allele0And1AreConsecutive = allele0Plus1 == allele1;
final int[] newSortedAlleleCounts;
// The rest of the sorted allele counts array contains junk
final int sortedAlleleCountsLength = distinctAlleleCount << 1;
if (freq0 == 1) { // in this case allele0 wont be present in the result and all is frequency should go to allele0 + 1.
if (allele0And1AreConsecutive) { // need just to remove the first allele and 1 to the frequency of the second (freq1 += 1).
newSortedAlleleCounts = Arrays.copyOfRange(sortedAlleleCounts,2,sortedAlleleCountsLength);
newSortedAlleleCounts[1]++;
} else { // just need to mutate allele0 to allele0 + 1.
newSortedAlleleCounts = Arrays.copyOf(sortedAlleleCounts,sortedAlleleCountsLength);
newSortedAlleleCounts[0] = allele0Plus1;
// newSortedAlleleCounts[1] = 1; // :) no need to do it because it is already the case (freq0 == 1).
}
} else { // && freq0 > 1 as per sortedAlleleCounts format restrictions. In this case allele0 will muttated to '0' with frequency decreased by 1.
if (allele0And1AreConsecutive) { // we don't need to add a component for allele0 + 1 since it already exists.
newSortedAlleleCounts = sortedAlleleCounts.clone();
newSortedAlleleCounts[0] = 0;
newSortedAlleleCounts[1] = freq0 - 1;
newSortedAlleleCounts[3]++;
} else { // we need to insert allele0 + 1 in the sorted-allele-counts array.
newSortedAlleleCounts = new int[sortedAlleleCountsLength + 2];
newSortedAlleleCounts[0] = 0;
newSortedAlleleCounts[1] = freq0 - 1;
newSortedAlleleCounts[2] = allele0Plus1;
newSortedAlleleCounts[3]++; // = 1 as the array was freshly created with 0s.
System.arraycopy(sortedAlleleCounts,2,newSortedAlleleCounts,4,sortedAlleleCountsLength - 2);
}
}
return new GenotypeAlleleCounts(ploidy, index + 1, newSortedAlleleCounts);
}
/**
* Returns the number of different alleles that participate in the genotype.
*
* @return 0 or greater.
*/
public int distinctAlleleCount() {
return distinctAlleleCount;
}
/**
* Returns the index of the allele from its rank in the genotype.
*
* @param rank the query rank.
*
* @throws IllegalArgumentException if the {@code rank} provided is outside the valid range [0,{@link #distinctAlleleCount()}).
*
* @return 0 or greater.
*/
public int alleleIndexAt(final int rank) {
if (rank < 0 || rank >= distinctAlleleCount)
throw new IllegalArgumentException("the requested rank " + rank + " is out of range [0," + distinctAlleleCount + ")");
return sortedAlleleCounts[rank << 1];
}
/**
* Returns the rank of an allele in the genotype by its index.
*
* @param index the target index.
*
* @throws IllegalArgumentException if {@code index} is less that 0. Indices can be arbitrarily large.
*
* @return -1 or less if the allele index is not present in the genotype, 0 to {@link #distinctAlleleCount()} - 1 otherwise.
* If negative, the absolute value can be used to determine where would be that index inserted within {@code [0,{@link #distinctAlleleCount()}]} as
* {@code - result - 1}.
*
*/
public int alleleRankFor(final int index) {
if (index < 0)
throw new IllegalArgumentException("the index must be 0 or greater");
return alleleIndexToRank(index, 0, distinctAlleleCount);
}
/**
* Generates a string that would represent the unphased genotype with this allele counts.
*
* <p>
* In this string allele calls appear in alleleIndex order with as many repeats as copies of each allele. So
* for example:<br/>
* <pre>
* 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
* </pre>
*
* </p>
*
* @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.
*
* <p>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</p>.
*
* @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.
*
* <p>
* 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:
* </p>
* <p><pre>
* [ allele_0, freq_0, allele_1, freq_1 ... ]
* </pre></p>
*
* <p>
* With {@code offset} you can indicate an alternative first position in the destination array.
* </p>
*
* @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
* <code>{@link #distinctAlleleCount()} * 2 positions</code>
* 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));
}
}

View File

@ -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).
*
* <p>
* Notice that for performance this class is thread-unsafe an so it cannot be shared between thread in a multi-thread run.
* </p>
*
* @author Valentin Ruano-Rubio &lt;valentin@broadinstitute.org&gt;
*/
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.
*
* <p>
* 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.
* </p>
*
* <p>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.</p>.
*/
private final int[][] alleleFirstGenotypeOffsetByPloidy;
/**
* Genotype table for this calculator.
*
* <p>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.</p>
*/
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.
*
* <p>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)</p>
*
* <p>
* The value contained in position <code>[a][f][r] == log10Lk(read[r] | allele[a]) + log10(f) </code>. Exception is
* for f == 0 whose value is undefined (in practice 0.0) and never used.
* </p>
*
* <p>
* 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).
* </p>
*/
private double[] readAlleleLikelihoodByAlleleCount = null;
/**
* Buffer used as a temporary container for likelihood components for genotypes stratified by reads.
*
* <p>
* It is indexed by genotype index and then by read index. The read capacity is increased as needed by calling
* {@link #ensureReadCapacity(int) ensureReadCapacity}.
* </p>
*/
private final double[][] readLikelihoodsByGenotypeIndex;
/**
* Indicates how many reads the calculator supports.
*
* <p>This figure is increased dynamically as per the
* calculation request calling {@link #ensureReadCapacity(int) ensureReadCapacity}.<p/>
*/
private int readCapacity = -1;
/**
* Caches the log10 of the first few integers up to the ploidy supported by the calculator.
* <p>This is in fact a shallow copy if {@link GenotypeLikelihoodCalculators#ploidyLog10}</p> and is not meant to be modified by
* this class. </p>
*/
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.
* <p>
* 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.
* </p>
*
* <p>
* 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}.
* </p>
*/
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.
*
* <p>
* 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}.
* </p>
*
* <p>
* 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.
* </p>
*/
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.
*
* <p>This operation is <b>thread-unsafe</b>.</p>
*
* @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.
*
* <p>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.
* </p>
*
* <p> Therefore if you are iterating through all genotype-allele-counts you should do sequentially and incrementally, to
* avoid a large efficiency drop </p>.
*
* @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.
*
* <p>This operation is <b>thread-unsafe</b>.</p>
*
* @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 <A extends Allele> GenotypeLikelihoods genotypeLikelihoods(final ReadLikelihoods.Matrix<A> 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 <i>[g][r]</i> likelihoods for each genotype <i>g</i> and <i>r</i>.
* @param readCount number of reads in the input likelihood arrays in {@code genotypeLikelihoodByRead}.
* @return never {@code null}, one position per genotype where the <i>i</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 <i>a</i>, frequency in genotype <i>f</i> and
* read <i>r</i>.
* @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.
*
* <pre>
* result[y][z][x] := z * lnLk ( read_x | allele_y ).
* </pre>
*
* @return never {@code null}.
*/
private <A extends Allele> double[] readLikelihoodComponentsByAlleleCount(final ReadLikelihoods.Matrix<A> 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}:
* <ul>
* <li>is {@code null},</li>
* <li>or its length is not even,</li>
* <li>or it contains any negatives,
* <li>or the count sum does not match the calculator ploidy,</li>
* <li>or any of the alleles therein is negative or greater than the maximum allele index.</li>
* </ul>
*
* @return 0 or greater but less than {@link #genotypeCount}.
*/
public int alleleCountsToIndex(final int ... alleleCountArray) {
if (alleleCountArray == null)
throw new IllegalArgumentException("the allele counts cannot be null");
if ((alleleCountArray.length & 1) != 0)
throw new IllegalArgumentException("the allele counts array cannot have odd length");
alleleHeap.clear();
for (int i = 0; i < alleleCountArray.length; i += 2) {
final int index = alleleCountArray[i];
final int count = alleleCountArray[i+1];
if (count < 0)
throw new IllegalArgumentException("no allele count can be less than 0");
for (int j = 0; j < count; j++)
alleleHeap.add(index);
}
return alleleHeapToIndex();
}
/**
* Transforms the content of the heap into an index.
* @return a valid likelihood index.
*/
private int alleleHeapToIndex() {
if (alleleHeap.size() != ploidy)
throw new IllegalArgumentException("the sum of allele counts must be equal to the ploidy of the calculator");
if (alleleHeap.peek() >= alleleCount)
throw new IllegalArgumentException("invalid allele " + alleleHeap.peek() + " more than the maximum " + (alleleCount - 1));
int result = 0;
for (int p = ploidy; p > 0; p--) {
final int allele = alleleHeap.remove();
if (allele < 0)
throw new IllegalArgumentException("invalid allele " + allele + " must be equal or greater than 0 ");
result += alleleFirstGenotypeOffsetByPloidy[p][allele];
}
return result;
}
}

View File

@ -0,0 +1,410 @@
/*
* 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 java.util.Arrays;
/**
* Genotype likelihood calculator utility.
*
* <p>
* This class provide genotype likelihood calculators with any number of alleles able given an arbitrary ploidy and allele
* count (number of distinct alleles).
* </p>
*
* <p>
* This class is thread-safe.
* </p>
*
* @author Valentin Ruano-Rubio &lt;valentin@broadinstitute.org&gt;
*/
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.
* <p>
* 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.
* </p>
*/
private static int maximumAllele = 1; // its initial value is the initial capacity of the shared tables.
/**
* The current maximum ploidy supported by the tables.
* <p>
* Its initial value indicates the initial capacity of the shared {@link #genotypeTableByPloidy}. Feel free
* to change it to anything reasonable that is non-negative.
* </p>
*/
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.
*
* <p>
* Its format is described in {@link #buildGenotypeAlleleCountsTable(int, int, int[][])}.
* </p>
*/
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.
* <p>
* The result is a matrix containing the offset of the first genotype that contain a particular allele
* stratified by ploidy.
* <p>
* Row (first dimension) represent the ploidy, whereas
* the second dimension represents the allele.
* </p>
*
* <p>
* Thus the value a position <i>[p][a]</i> indicates how many genotypes of ploidy <i>p</i> there are before the first
* one that contains allele <i>a</i>. <br/>
*
* For example, considering ploidy 3 and alleles A, B, C, D, etc ... (indexed 0, 1, 2, ... respectively):
* <br/>
* [3][A] == [3][0] == 0 as the first genotype AAA contains A.
* <br/>
* [3][C] == [3][2] == 4 as the first genotype that contains C, AAC follows: AAA AAB ABB BBB
* <br/>
* [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.
*
* </p>
*
* <p>
* This value are calculated recursively as follows:
* </p>
* <pre>
*
* 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 ..................
* </pre>
*
* <p>
* Note: if someone can come with a close form computable 0(1) (respect to ploidy and allele count)
* please let the author know.
* </p>
*
* <p>
* 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.
* </p>
* <p>
* 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.
* </p>
*
* <p>
* 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.
* </p>
*
* @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.
* <p>
* 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.
* </p>
*
* <p>
* Therefore <code>result[3][4]</code> would contain the 5th genotype with ploidy 3, and <code>result[4].length</code>
* would be equal to the count of possible genotypes for ploidy 4.
* </p>
*
* @param maximumPloidy maximum ploidy to use in queries to the resulting table.
* @param maximumAllele maximum allele index to use in queries to the resulting table.
* @param offsetTable an allele first genotype offset table as constructed using {@link #buildAlleleFirstGenotypeOffsetTable(int, int)}
* that supports at least up to {@code maximumAllele} and {@code maximumPloidy}.
*
* @throws IllegalArgumentException if {@code maximumPloidy} or {@code maximumAllele} is negative, or {@code offsetTable} is {@code null},
* or it does not have the capacity to handle the requested maximum ploidy or allele index.
*
* @return never {@code null}.
*/
private static GenotypeAlleleCounts[][] buildGenotypeAlleleCountsTable(final int maximumPloidy, final int maximumAllele, final int[][] offsetTable) {
checkPloidyAndMaximumAllele(maximumPloidy, maximumAllele);
checkOffsetTableCapacity(offsetTable,maximumPloidy,maximumAllele);
final int rowCount = maximumPloidy + 1;
final GenotypeAlleleCounts[][] result = new GenotypeAlleleCounts[rowCount][]; // each row has a different number of columns.
for (int ploidy = 0; ploidy <= maximumPloidy; ploidy++)
result[ploidy] = buildGenotypeAlleleCountsArray(ploidy, maximumAllele, offsetTable);
return result;
}
/**
* Builds a genotype-allele-counts array given the genotype ploidy and how many genotype you need.
* <p>
* 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.
* </p>
*
* <p> Notice that is possible to request ploidy ==0. In that case the resulting array will have repetitions
* of the empty genotype allele count.
* </p>
*
* <p>
* For example,
*
* <pre>
* 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} ]
* </pre>
* </p>
*
* @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.
* <p>
* Throws an exception if there is any issues.
* </p>
*
* @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);
}
}

View File

@ -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 &lt;valentin@broadinstitute.org&gt;
*/
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.
*
* <p>The heap with grow if it runs out of capacity to hold the new element</p>
*
* @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;
}
}

View File

@ -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);