diff --git a/protected/java/src/org/broadinstitute/sting/gatk/walkers/genotyper/UnifiedArgumentCollection.java b/protected/java/src/org/broadinstitute/sting/gatk/walkers/genotyper/UnifiedArgumentCollection.java index 4fae3d6e3..ff6bc5407 100644 --- a/protected/java/src/org/broadinstitute/sting/gatk/walkers/genotyper/UnifiedArgumentCollection.java +++ b/protected/java/src/org/broadinstitute/sting/gatk/walkers/genotyper/UnifiedArgumentCollection.java @@ -85,7 +85,7 @@ public class UnifiedArgumentCollection extends StandardCallerArgumentCollection * The PairHMM implementation to use for -glm INDEL genotype likelihood calculations. The various implementations balance a tradeoff of accuracy and runtime. */ @Argument(fullName = "pair_hmm_implementation", shortName = "pairHMM", doc = "The PairHMM implementation to use for -glm INDEL genotype likelihood calculations", required = false) - public PairHMM.HMM_IMPLEMENTATION pairHMM = PairHMM.HMM_IMPLEMENTATION.LOGLESS_CACHING; + public PairHMM.HMM_IMPLEMENTATION pairHMM = PairHMM.HMM_IMPLEMENTATION.ARRAY_LOGLESS; /** * The minimum confidence needed in a given base for it to be used in variant calling. Note that the base quality of a base diff --git a/protected/java/src/org/broadinstitute/sting/gatk/walkers/haplotypecaller/HaplotypeCaller.java b/protected/java/src/org/broadinstitute/sting/gatk/walkers/haplotypecaller/HaplotypeCaller.java index 0b95ed07e..7edf55fed 100644 --- a/protected/java/src/org/broadinstitute/sting/gatk/walkers/haplotypecaller/HaplotypeCaller.java +++ b/protected/java/src/org/broadinstitute/sting/gatk/walkers/haplotypecaller/HaplotypeCaller.java @@ -387,7 +387,7 @@ public class HaplotypeCaller extends ActiveRegionWalker, In */ @Hidden @Argument(fullName = "pair_hmm_implementation", shortName = "pairHMM", doc = "The PairHMM implementation to use for genotype likelihood calculations", required = false) - public PairHMM.HMM_IMPLEMENTATION pairHMM = PairHMM.HMM_IMPLEMENTATION.LOGLESS_CACHING; + public PairHMM.HMM_IMPLEMENTATION pairHMM = PairHMM.HMM_IMPLEMENTATION.ARRAY_LOGLESS; @Hidden @Argument(fullName="keepRG", shortName="keepRG", doc="Only use read from this read group when making calls (but use all reads to build the assembly)", required = false) diff --git a/protected/java/src/org/broadinstitute/sting/gatk/walkers/haplotypecaller/LikelihoodCalculationEngine.java b/protected/java/src/org/broadinstitute/sting/gatk/walkers/haplotypecaller/LikelihoodCalculationEngine.java index e6e76ba90..0d55797bc 100644 --- a/protected/java/src/org/broadinstitute/sting/gatk/walkers/haplotypecaller/LikelihoodCalculationEngine.java +++ b/protected/java/src/org/broadinstitute/sting/gatk/walkers/haplotypecaller/LikelihoodCalculationEngine.java @@ -58,6 +58,7 @@ import org.broadinstitute.sting.utils.genotyper.MostLikelyAllele; import org.broadinstitute.sting.utils.genotyper.PerReadAlleleLikelihoodMap; import org.broadinstitute.sting.utils.haplotype.Haplotype; import org.broadinstitute.sting.utils.haplotype.HaplotypeScoreComparator; +import org.broadinstitute.sting.utils.pairhmm.ArrayLoglessPairHMM; import org.broadinstitute.sting.utils.pairhmm.Log10PairHMM; import org.broadinstitute.sting.utils.pairhmm.LoglessPairHMM; import org.broadinstitute.sting.utils.pairhmm.CnyPairHMM; @@ -98,8 +99,13 @@ public class LikelihoodCalculationEngine { return new LoglessPairHMM(); else return new CnyPairHMM(); + case ARRAY_LOGLESS: + if (noFpga || !CnyPairHMM.isAvailable()) + return new ArrayLoglessPairHMM(); + else + return new CnyPairHMM(); default: - throw new UserException.BadArgumentValue("pairHMM", "Specified pairHMM implementation is unrecognized or incompatible with the HaplotypeCaller. Acceptable options are ORIGINAL, EXACT, CACHING, and LOGLESS_CACHING."); + throw new UserException.BadArgumentValue("pairHMM", "Specified pairHMM implementation is unrecognized or incompatible with the HaplotypeCaller. Acceptable options are ORIGINAL, EXACT, CACHING, LOGLESS_CACHING, and ARRAY_LOGLESS."); } } }; @@ -258,9 +264,10 @@ public class LikelihoodCalculationEngine { // iterate over all haplotypes, calculating the likelihood of the read for each haplotype for( int jjj = 0; jjj < numHaplotypes; jjj++ ) { final Haplotype haplotype = haplotypes.get(jjj); + final byte[] nextHaplotypeBases = (jjj == numHaplotypes - 1) ? null : haplotypes.get(jjj+1).getBases(); final boolean isFirstHaplotype = jjj == 0; final double log10l = pairHMM.get().computeReadLikelihoodGivenHaplotypeLog10(haplotype.getBases(), - readBases, readQuals, readInsQuals, readDelQuals, overallGCP, isFirstHaplotype); + readBases, readQuals, readInsQuals, readDelQuals, overallGCP, isFirstHaplotype, nextHaplotypeBases); if ( WRITE_LIKELIHOODS_TO_FILE ) { likelihoodsStream.printf("%s %s %s %s %s %s %f%n", diff --git a/protected/java/src/org/broadinstitute/sting/gatk/walkers/indels/PairHMMIndelErrorModel.java b/protected/java/src/org/broadinstitute/sting/gatk/walkers/indels/PairHMMIndelErrorModel.java index c77557da6..3c6e409b9 100644 --- a/protected/java/src/org/broadinstitute/sting/gatk/walkers/indels/PairHMMIndelErrorModel.java +++ b/protected/java/src/org/broadinstitute/sting/gatk/walkers/indels/PairHMMIndelErrorModel.java @@ -53,6 +53,7 @@ import org.broadinstitute.sting.utils.MathUtils; import org.broadinstitute.sting.utils.clipping.ReadClipper; import org.broadinstitute.sting.utils.exceptions.UserException; import org.broadinstitute.sting.utils.genotyper.PerReadAlleleLikelihoodMap; +import org.broadinstitute.sting.utils.pairhmm.ArrayLoglessPairHMM; import org.broadinstitute.sting.utils.pairhmm.Log10PairHMM; import org.broadinstitute.sting.utils.pairhmm.LoglessPairHMM; import org.broadinstitute.sting.utils.pairhmm.PairHMM; @@ -120,8 +121,11 @@ public class PairHMMIndelErrorModel { case LOGLESS_CACHING: pairHMM = new LoglessPairHMM(); break; + case ARRAY_LOGLESS: + pairHMM = new ArrayLoglessPairHMM(); + break; default: - throw new UserException.BadArgumentValue("pairHMM", "Specified pairHMM implementation is unrecognized or incompatible with the UnifiedGenotyper. Acceptable options are ORIGINAL, EXACT or LOGLESS_CACHING."); + throw new UserException.BadArgumentValue("pairHMM", "Specified pairHMM implementation is unrecognized or incompatible with the UnifiedGenotyper. Acceptable options are ORIGINAL, EXACT, LOGLESS_CACHING, or ARRAY_LOGLESS."); } // fill gap penalty table, affine naive model: @@ -365,7 +369,10 @@ public class PairHMMIndelErrorModel { baseDeletionQualities = contextLogGapOpenProbabilities; } + byte[] currentHaplotypeBases = null; boolean firstHap = true; + double readLikelihood; + Allele currentAllele = null; for (Allele a: haplotypeMap.keySet()) { Haplotype haplotype = haplotypeMap.get(a); @@ -381,34 +388,65 @@ public class PairHMMIndelErrorModel { final long indStart = startLocationInRefForHaplotypes - haplotype.getStartPosition(); final long indStop = stopLocationInRefForHaplotypes - haplotype.getStartPosition(); - double readLikelihood; + if (DEBUG) System.out.format("indStart: %d indStop: %d WinStart:%d WinStop:%d start: %d stop: %d readLength: %d C:%s\n", indStart, indStop, ref.getWindow().getStart(), ref.getWindow().getStop(), startLocationInRefForHaplotypes, stopLocationInRefForHaplotypes, read.getReadLength(), read.getCigar().toString()); - final byte[] haplotypeBases = Arrays.copyOfRange(haplotype.getBases(), (int)indStart, (int)indStop); + // peak at the next haplotype in the list + final byte[] nextHaplotypeBases = Arrays.copyOfRange(haplotype.getBases(), (int)indStart, (int)indStop); + // process the current haplotype in the list + if (currentHaplotypeBases != null) { + // it's possible that the indel starts at the last base of the haplotypes + if ( currentHaplotypeBases.length == 0 ) { + readLikelihood = -Double.MAX_VALUE; + } else { + if (firstHap) { + //no need to reallocate arrays for each new haplotype, as length won't change + pairHMM.initialize(readBases.length, currentHaplotypeBases.length); + firstHap = false; + } + readLikelihood = pairHMM.computeReadLikelihoodGivenHaplotypeLog10(currentHaplotypeBases, readBases, readQuals, + baseInsertionQualities, baseDeletionQualities, contextLogGapContinuationProbabilities, firstHap, nextHaplotypeBases); + } + + if (DEBUG) { + System.out.println("H:"+new String(currentHaplotypeBases)); + System.out.println("R:"+new String(readBases)); + System.out.format("L:%4.2f\n",readLikelihood); + } + + perReadAlleleLikelihoodMap.add(p, currentAllele, readLikelihood); + readLikelihoods[readIdx][j++] = readLikelihood; + } + // update the current haplotype + currentHaplotypeBases = nextHaplotypeBases; + currentAllele = a; + } + // process the final haplotype + if (currentHaplotypeBases != null) { // it's possible that the indel starts at the last base of the haplotypes - if ( haplotypeBases.length == 0 ) { + if ( currentHaplotypeBases.length == 0 ) { readLikelihood = -Double.MAX_VALUE; } else { if (firstHap) { //no need to reallocate arrays for each new haplotype, as length won't change - pairHMM.initialize(readBases.length, haplotypeBases.length); + pairHMM.initialize(readBases.length, currentHaplotypeBases.length); firstHap = false; } - - readLikelihood = pairHMM.computeReadLikelihoodGivenHaplotypeLog10(haplotypeBases, readBases, readQuals, - baseInsertionQualities, baseDeletionQualities, contextLogGapContinuationProbabilities, firstHap); + // there is no next haplotype, so pass null for nextHaplotypeBases. + readLikelihood = pairHMM.computeReadLikelihoodGivenHaplotypeLog10(currentHaplotypeBases, readBases, readQuals, + baseInsertionQualities, baseDeletionQualities, contextLogGapContinuationProbabilities, firstHap, null); } if (DEBUG) { - System.out.println("H:"+new String(haplotypeBases)); + System.out.println("H:"+new String(currentHaplotypeBases)); System.out.println("R:"+new String(readBases)); System.out.format("L:%4.2f\n",readLikelihood); } - perReadAlleleLikelihoodMap.add(p, a, readLikelihood); + perReadAlleleLikelihoodMap.add(p, currentAllele, readLikelihood); readLikelihoods[readIdx][j++] = readLikelihood; } } diff --git a/protected/java/src/org/broadinstitute/sting/utils/pairhmm/ArrayLoglessPairHMM.java b/protected/java/src/org/broadinstitute/sting/utils/pairhmm/ArrayLoglessPairHMM.java new file mode 100644 index 000000000..26eb745bd --- /dev/null +++ b/protected/java/src/org/broadinstitute/sting/utils/pairhmm/ArrayLoglessPairHMM.java @@ -0,0 +1,359 @@ +/* +* 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.sting.utils.pairhmm; + +import com.google.java.contract.Ensures; +import com.google.java.contract.Requires; +import org.broadinstitute.sting.utils.QualityUtils; +import java.util.Arrays; + +/** + * Created with IntelliJ IDEA. + * User: bradt + * Date: 6/11/13 + */ +public class ArrayLoglessPairHMM extends PairHMM { + private static final double INITIAL_CONDITION = Math.pow(2, 1020); + private static final double INITIAL_CONDITION_LOG10 = Math.log10(INITIAL_CONDITION); + + // we divide e by 3 because the observed base could have come from any of the non-observed alleles + protected static final double TRISTATE_CORRECTION = 3.0; + + private static final int matchToMatch = 0; + private static final int indelToMatch = 1; + private static final int matchToInsertion = 2; + private static final int insertionToInsertion = 3; + private static final int matchToDeletion = 4; + private static final int deletionToDeletion = 5; + + protected double[][] transition = null; // The transition probabilities cache + protected double[][] prior = null; // The prior probabilities cache + + // Array declarations for arrays implementation + private double[] currentMatchArray = null; + private double[] currentDeleteArray = null; + private double[] currentInsertArray = null; + private double[] parentMatchArray = null; + private double[] parentDeleteArray = null; + private double[] parentInsertArray = null; + private double[] grandparentMatchArray = null; + private double[] grandparentDeleteArray = null; + private double[] grandparentInsertArray = null; + + // When successive haplotypes have a common prefix, these arrays store cached info from the previous haplotype; for reading + private double[] matchCacheArray = null; + private double[] deleteCacheArray = null; + private double[] insertCacheArray = null; + + // These arrays store cache info for use with the next haplotype; for writing + private double[] nextMatchCacheArray = null; + private double[] nextDeleteCacheArray = null; + private double[] nextInsertCacheArray = null; + + // Used when caching to store our intermediate sum at point of first difference bw successive haplotypes + private double partialSum; + + + /** + * {@inheritDoc} + */ + @Override + public void initialize(final int readMaxLength, final int haplotypeMaxLength ) { + super.initialize(readMaxLength, haplotypeMaxLength); + + transition = new double[paddedMaxReadLength][6]; + prior = new double[paddedMaxReadLength][paddedMaxHaplotypeLength]; + + // Initialize all arrays + // Final Cell of array is a padding cell, initialized to zero. + currentMatchArray = new double[paddedMaxReadLength]; + currentDeleteArray = new double[paddedMaxReadLength]; + currentInsertArray = new double[paddedMaxReadLength]; + + parentMatchArray = new double[paddedMaxReadLength]; + parentDeleteArray = new double[paddedMaxReadLength]; + parentInsertArray = new double[paddedMaxReadLength]; + + grandparentMatchArray = new double[paddedMaxReadLength]; + grandparentDeleteArray = new double[paddedMaxReadLength]; + grandparentInsertArray = new double[paddedMaxReadLength]; + + // Initialize the special arrays used for caching when successive haplotypes have a common prefix + matchCacheArray = new double[paddedMaxReadLength]; + deleteCacheArray = new double[paddedMaxReadLength]; + insertCacheArray = new double[paddedMaxReadLength]; + + nextMatchCacheArray = new double[paddedMaxReadLength]; + nextDeleteCacheArray = new double[paddedMaxReadLength]; + nextInsertCacheArray = new double [paddedMaxReadLength]; + } + + + /** + * {@inheritDoc} + */ + @Override + public double subComputeReadLikelihoodGivenHaplotypeLog10( final byte[] haplotypeBases, + final byte[] readBases, + final byte[] readQuals, + final byte[] insertionGOP, + final byte[] deletionGOP, + final byte[] overallGCP, + int hapStartIndex, + final boolean recacheReadValues, + final int nextHapStartIndex) { + + if ( ! constantsAreInitialized) { + initializeProbabilities(transition, insertionGOP, deletionGOP, overallGCP); + + // note that we initialized the constants + constantsAreInitialized = true; + } + initializePriors(haplotypeBases, readBases, readQuals, hapStartIndex); + + // Some housekeeping to be done if we are starting a new read + if (recacheReadValues) { + hapStartIndex = 0; + + initializeProbabilities(transition, insertionGOP, deletionGOP, overallGCP); + // note that we initialized the constants + constantsAreInitialized = true; + + // Pad the ends of the Match and Insert arrays with 0. Analogous to the first row in the Match, Insert matrices of N2MemoryPairHMM + grandparentMatchArray[readBases.length] = 0; + grandparentInsertArray[readBases.length] = 0; + parentMatchArray[readBases.length] = 0; + parentInsertArray[readBases.length] = 0; + currentMatchArray[readBases.length] = 0; + currentInsertArray[readBases.length] = 0; + matchCacheArray[readBases.length] = 0; + insertCacheArray[readBases.length] = 0; + nextMatchCacheArray[readBases.length] = 0; + nextInsertCacheArray[readBases.length] = 0; + } + // if we have not cached from prev haplotype, clear any info we may have accumulated in a previous HMM iteration + if (hapStartIndex == 0) { + Arrays.fill(matchCacheArray, 0, readBases.length, 0); + Arrays.fill(deleteCacheArray, 0, readBases.length, 0); + Arrays.fill(insertCacheArray, 0, readBases.length, 0); + + partialSum = 0; + + // Padding value for the deletion arrays. Let's us have free deletions at the beginning + // Needs to be reset when starting a new read or when hap length changes (ie when hapStartIndex is 0) + final double initialValue = INITIAL_CONDITION / haplotypeBases.length; + // Pad the deletion arrays. Akin to padding the first row in the deletion matrix + parentDeleteArray[readBases.length] = initialValue; + grandparentDeleteArray[readBases.length] = initialValue; + currentDeleteArray[readBases.length] = initialValue; + deleteCacheArray[readBases.length] = initialValue; + nextDeleteCacheArray[readBases.length] = initialValue; + } + // We build up our solution by looking at position [0] in the match, insert arrays. Need to set to 0 before we start. + grandparentMatchArray[0] = 0; + grandparentInsertArray[0] = 0; + parentMatchArray[0] = 0; + parentInsertArray[0] = 0; + currentMatchArray[0] = 0; + currentInsertArray[0] = 0; + + // Array implementation. Start by initializing some array parameters + // Number of diagonals for a matrix = rows + cols - 1; + final int maxDiagonals = readBases.length + haplotypeBases.length - hapStartIndex - 1; + // The array indices we want to fill will be between these values + int startFill; + int endFill; + // The position of the arrays to be updated + int arrayIndex; + // The coordinate in our priors and transition matrices corresponding to a given position in the read/haplotype alignment + int matrixRow; + int matrixCol; + // The final answer prior to log10 correction + double finalArraySumProbabilities = partialSum; + // This array will contain the partial sum to cache for the next haplotype + final int cacheSumIndex = nextHapStartIndex - hapStartIndex + readBases.length - 1; + + // Perform dynamic programming using arrays, as if over diagonals of a hypothetical read/haplotype alignment matrix + for (int i = 1; i <= maxDiagonals; i++) { + // set the bounds for cells we wish to fill in the arrays + startFill = Math.max(readBases.length - i, 0); + endFill = Math.min(maxDiagonals - i + 1, readBases.length); + + // apply any previously cached array information + if (i <= readBases.length) { + // apply caching info necessary for calculating current DELETE array values + parentMatchArray[startFill] = matchCacheArray[startFill]; + parentDeleteArray[startFill] = deleteCacheArray[startFill]; + // apply caching info necessary for calculating current MATCH array values + grandparentMatchArray[startFill + 1] = matchCacheArray[startFill + 1]; + grandparentDeleteArray[startFill + 1] = deleteCacheArray[startFill + 1]; + grandparentInsertArray[startFill + 1] = insertCacheArray[startFill + 1]; + } + + // fill in the cells for our arrays + for (arrayIndex = startFill; arrayIndex < endFill; arrayIndex++) { + + // translate the array position into a row, column in the priors and transition matrices + matrixRow = readBases.length - arrayIndex - 1; + matrixCol = i - matrixRow - 1 + hapStartIndex; + + // update cell for each of our new arrays. Prior, transition matrices are padded +1 row,col + updateArrayCell(arrayIndex, prior[matrixRow+1][matrixCol+1], transition[matrixRow+1]); + + // Set up caching for the next haplotype + // At the position of the final similar base between this haplotype and the next one, remember the mid-array values + if (matrixCol == nextHapStartIndex - 1) { + nextMatchCacheArray[arrayIndex] = currentMatchArray[arrayIndex]; + nextDeleteCacheArray[arrayIndex] = currentDeleteArray[arrayIndex]; + nextInsertCacheArray[arrayIndex] = currentInsertArray[arrayIndex]; + } + } + + // final probability is the log10 sum of the last element in the Match and Insertion state arrays + // this way we ignore all paths that ended in deletions! (huge) + // but we have to sum all the paths ending in the M and I arrays, because they're no longer extended. + // Where i > readBases.length, array[0] corresponds to bottom row of a [read] x [haplotype] matrix. Before this, they carries the 0's we set above. + finalArraySumProbabilities += currentInsertArray[0] + currentMatchArray[0]; + + // Partial sum for caching the next haplotype: + // At the position of the last similar base between this haplotype and the next one... + // ...remember the partial sum, so that we can start here on the next hap. + if (i == cacheSumIndex) + partialSum = finalArraySumProbabilities; + + // rotate array references + double[] tempMatchArray = grandparentMatchArray; + double[] tempDeleteArray = grandparentDeleteArray; + double[] tempInsertArray = grandparentInsertArray; + + grandparentMatchArray = parentMatchArray; + grandparentDeleteArray = parentDeleteArray; + grandparentInsertArray = parentInsertArray; + + parentMatchArray = currentMatchArray; + parentDeleteArray = currentDeleteArray; + parentInsertArray = currentInsertArray; + + currentMatchArray = tempMatchArray; + currentDeleteArray = tempDeleteArray; + currentInsertArray = tempInsertArray; + } + // The cache arrays we wrote for this haplotype will be read for the next haplotype. + matchCacheArray = nextMatchCacheArray.clone(); + deleteCacheArray = nextDeleteCacheArray.clone(); + insertCacheArray = nextInsertCacheArray.clone(); + + //return result + return Math.log10(finalArraySumProbabilities) - INITIAL_CONDITION_LOG10; + } + + /** + * Initializes the matrix that holds all the constants related to the editing + * distance between the read and the haplotype. + * + * @param haplotypeBases the bases of the haplotype + * @param readBases the bases of the read + * @param readQuals the base quality scores of the read + * @param startIndex where to start updating the distanceMatrix (in case this read is similar to the previous read) + */ + public void initializePriors(final byte[] haplotypeBases, final byte[] readBases, final byte[] readQuals, final int startIndex) { + + // initialize the pBaseReadLog10 matrix for all combinations of read x haplotype bases + // Abusing the fact that java initializes arrays with 0.0, so no need to fill in rows and columns below 2. + + for (int i = 0; i < readBases.length; i++) { + final byte x = readBases[i]; + final byte qual = readQuals[i]; + for (int j = startIndex; j < haplotypeBases.length; j++) { + final byte y = haplotypeBases[j]; + prior[i+1][j+1] = ( x == y || x == (byte) 'N' || y == (byte) 'N' ? + QualityUtils.qualToProb(qual) : (QualityUtils.qualToErrorProb(qual) / (doNotUseTristateCorrection ? 1.0 : TRISTATE_CORRECTION)) ); + } + } + } + + /** + * Initializes the matrix that holds all the constants related to quality scores. + * + * @param insertionGOP insertion quality scores of the read + * @param deletionGOP deletion quality scores of the read + * @param overallGCP overall gap continuation penalty + */ + @Requires({ + "insertionGOP != null", + "deletionGOP != null", + "overallGCP != null" + }) + @Ensures("constantsAreInitialized") + protected static void initializeProbabilities(final double[][] transition, final byte[] insertionGOP, final byte[] deletionGOP, final byte[] overallGCP) { + for (int i = 0; i < insertionGOP.length; i++) { + final int qualIndexGOP = Math.min(insertionGOP[i] + deletionGOP[i], Byte.MAX_VALUE); + transition[i+1][matchToMatch] = QualityUtils.qualToProb((byte) qualIndexGOP); + transition[i+1][indelToMatch] = QualityUtils.qualToProb(overallGCP[i]); + transition[i+1][matchToInsertion] = QualityUtils.qualToErrorProb(insertionGOP[i]); + transition[i+1][insertionToInsertion] = QualityUtils.qualToErrorProb(overallGCP[i]); + transition[i+1][matchToDeletion] = QualityUtils.qualToErrorProb(deletionGOP[i]); + transition[i+1][deletionToDeletion] = QualityUtils.qualToErrorProb(overallGCP[i]); + } + } + + /** + * Updates a cell in the HMM arrays + * + * @param indK index in the arrays to update + * @param prior the likelihood editing distance matrix for the read x haplotype + * @param transition an array with the six transition relevant to this location + */ + private void updateArrayCell( final int indK, final double prior, final double[] transition) { + currentMatchArray[indK] = prior * ( grandparentMatchArray[indK + 1] * transition[matchToMatch] + + grandparentInsertArray[indK + 1] * transition[indelToMatch] + + grandparentDeleteArray[indK + 1] * transition[indelToMatch] ); + currentInsertArray[indK] = parentMatchArray[indK + 1] * transition[matchToInsertion] + parentInsertArray[indK + 1] * transition[insertionToInsertion]; + currentDeleteArray[indK] = parentMatchArray[indK] * transition[matchToDeletion] + parentDeleteArray[indK] * transition[deletionToDeletion]; + } + +} diff --git a/protected/java/src/org/broadinstitute/sting/utils/pairhmm/CnyPairHMM.java b/protected/java/src/org/broadinstitute/sting/utils/pairhmm/CnyPairHMM.java index 0afd4afe2..d92b918ba 100644 --- a/protected/java/src/org/broadinstitute/sting/utils/pairhmm/CnyPairHMM.java +++ b/protected/java/src/org/broadinstitute/sting/utils/pairhmm/CnyPairHMM.java @@ -191,7 +191,8 @@ public final class CnyPairHMM extends PairHMM implements BatchPairHMM { final byte[] deletionGOP, final byte[] overallGCP, final int hapStartIndex, - final boolean recacheReadValues ) { + final boolean recacheReadValues, + final int nextHapStartIndex) { return 0.0; } diff --git a/protected/java/src/org/broadinstitute/sting/utils/pairhmm/LoglessPairHMM.java b/protected/java/src/org/broadinstitute/sting/utils/pairhmm/LoglessPairHMM.java index 49148c152..e745ca1f5 100644 --- a/protected/java/src/org/broadinstitute/sting/utils/pairhmm/LoglessPairHMM.java +++ b/protected/java/src/org/broadinstitute/sting/utils/pairhmm/LoglessPairHMM.java @@ -92,7 +92,8 @@ public final class LoglessPairHMM extends N2MemoryPairHMM { final byte[] deletionGOP, final byte[] overallGCP, final int hapStartIndex, - final boolean recacheReadValues ) { + final boolean recacheReadValues, + final int nextHapStartIndex) { if (previousHaplotypeBases == null || previousHaplotypeBases.length != haplotypeBases.length) { final double initialValue = INITIAL_CONDITION / haplotypeBases.length; diff --git a/protected/java/src/org/broadinstitute/sting/utils/pairhmm/PairHMMTestData.java b/protected/java/src/org/broadinstitute/sting/utils/pairhmm/PairHMMTestData.java index 3d8137ecf..7fef514d9 100644 --- a/protected/java/src/org/broadinstitute/sting/utils/pairhmm/PairHMMTestData.java +++ b/protected/java/src/org/broadinstitute/sting/utils/pairhmm/PairHMMTestData.java @@ -67,12 +67,14 @@ import java.util.zip.GZIPInputStream; */ public class PairHMMTestData { public final String ref; + public final String nextRef; private final String read; public final byte[] baseQuals, insQuals, delQuals, gcp; public final double log10l; - PairHMMTestData(String ref, String read, byte[] baseQuals, byte[] insQuals, byte[] delQuals, byte[] gcp, double log10l) { + PairHMMTestData(String ref, String nextRef, String read, byte[] baseQuals, byte[] insQuals, byte[] delQuals, byte[] gcp, double log10l) { this.ref = ref; + this.nextRef = nextRef; this.read = read; this.baseQuals = baseQuals; this.insQuals = insQuals; @@ -81,8 +83,9 @@ public class PairHMMTestData { this.log10l = log10l; } - PairHMMTestData(String ref, String read, final byte qual) { + PairHMMTestData(String ref, String nextRef, String read, final byte qual) { this.ref = ref; + this.nextRef = nextRef; this.read = read; this.baseQuals = this.insQuals = this.delQuals = Utils.dupBytes(qual, read.length()); this.gcp = Utils.dupBytes((byte)10, read.length()); @@ -92,13 +95,14 @@ public class PairHMMTestData { public double runHMM(final PairHMM hmm) { hmm.initialize(getRead().length(), ref.length()); return hmm.computeReadLikelihoodGivenHaplotypeLog10(ref.getBytes(), getRead().getBytes(), - baseQuals, insQuals, delQuals, gcp, true); + baseQuals, insQuals, delQuals, gcp, true, null); } @Override public String toString() { return "Info{" + "ref='" + ref + '\'' + + ", nextRef=" + nextRef + '\'' + ", read='" + getRead() + '\'' + ", log10l=" + log10l + '}'; @@ -115,7 +119,7 @@ public class PairHMMTestData { hmm.initialize(first.getRead().length(), maxHaplotypeLen); for ( final PairHMMTestData datum : data ) { hmm.computeReadLikelihoodGivenHaplotypeLog10(datum.ref.getBytes(), datum.getRead().getBytes(), - datum.baseQuals, datum.insQuals, datum.delQuals, datum.gcp, false); + datum.baseQuals, datum.insQuals, datum.delQuals, datum.gcp, false, datum.nextRef.getBytes()); } } @@ -136,22 +140,44 @@ public class PairHMMTestData { in = new GZIPInputStream(in); } + String[] nextEntry; + String[] thisEntry = null; for ( final String line : new XReadLines(in) ) { - final String[] parts = line.split(" "); - final PairHMMTestData info = new PairHMMTestData( - parts[0], parts[1], - SAMUtils.fastqToPhred(parts[2]), - SAMUtils.fastqToPhred(parts[3]), - SAMUtils.fastqToPhred(parts[4]), - SAMUtils.fastqToPhred(parts[5]), - Double.parseDouble(parts[6])); + // peak at the next entry (to get the haplotype bases) + nextEntry = line.split(" "); + // process the current entry + if (thisEntry != null) { + final PairHMMTestData info = new PairHMMTestData( + thisEntry[0], nextEntry[0], thisEntry[1], + SAMUtils.fastqToPhred(thisEntry[2]), + SAMUtils.fastqToPhred(thisEntry[3]), + SAMUtils.fastqToPhred(thisEntry[4]), + SAMUtils.fastqToPhred(thisEntry[5]), + Double.parseDouble(thisEntry[6])); - if ( ! results.containsKey(info.read) ) { - results.put(info.read, new LinkedList()); + if ( ! results.containsKey(info.read) ) { + results.put(info.read, new LinkedList()); + } + final List byHap = results.get(info.read); + byHap.add(info); } - final List byHap = results.get(info.read); - byHap.add(info); + // update the current entry + thisEntry = nextEntry; } + // process the final entry + final PairHMMTestData info = new PairHMMTestData( + thisEntry[0], null, thisEntry[1], + SAMUtils.fastqToPhred(thisEntry[2]), + SAMUtils.fastqToPhred(thisEntry[3]), + SAMUtils.fastqToPhred(thisEntry[4]), + SAMUtils.fastqToPhred(thisEntry[5]), + Double.parseDouble(thisEntry[6])); + + if ( ! results.containsKey(info.read) ) { + results.put(info.read, new LinkedList()); + } + final List byHap = results.get(info.read); + byHap.add(info); return results; } diff --git a/protected/java/test/org/broadinstitute/sting/utils/pairhmm/PairHMMUnitTest.java b/protected/java/test/org/broadinstitute/sting/utils/pairhmm/PairHMMUnitTest.java index 7334eec3f..b235f95c8 100644 --- a/protected/java/test/org/broadinstitute/sting/utils/pairhmm/PairHMMUnitTest.java +++ b/protected/java/test/org/broadinstitute/sting/utils/pairhmm/PairHMMUnitTest.java @@ -72,16 +72,18 @@ public class PairHMMUnitTest extends BaseTest { final N2MemoryPairHMM exactHMM = new Log10PairHMM(true); // the log truth implementation final N2MemoryPairHMM originalHMM = new Log10PairHMM(false); // the reference implementation final N2MemoryPairHMM loglessHMM = new LoglessPairHMM(); + final PairHMM arrayHMM = new ArrayLoglessPairHMM(); @BeforeClass public void initialize() { exactHMM.doNotUseTristateCorrection(); originalHMM.doNotUseTristateCorrection(); loglessHMM.doNotUseTristateCorrection(); + arrayHMM.doNotUseTristateCorrection(); } - private List getHMMs() { - return Arrays.asList(exactHMM, originalHMM, loglessHMM); + private List getHMMs() { + return Arrays.asList(exactHMM, originalHMM, loglessHMM, arrayHMM); } // -------------------------------------------------------------------------------- @@ -91,8 +93,8 @@ public class PairHMMUnitTest extends BaseTest { // -------------------------------------------------------------------------------- private class BasicLikelihoodTestProvider { - final String ref, read; - final byte[] refBasesWithContext, readBasesWithContext; + final String ref, nextRef, read; + final byte[] refBasesWithContext, nextRefBasesWithContext, readBasesWithContext; final int baseQual, insQual, delQual, gcp; final int expectedQual; final boolean left, right; @@ -100,28 +102,30 @@ public class PairHMMUnitTest extends BaseTest { final static String LEFT_FLANK = "GATTTATCATCGAGTCTGC"; final static String RIGHT_FLANK = "CATGGATCGTTATCAGCTATCTCGAGGGATTCACTTAACAGTTTTA"; - public BasicLikelihoodTestProvider(final String ref, final String read, final int baseQual, final int insQual, final int delQual, final int expectedQual, final int gcp ) { - this(ref, read, baseQual, insQual, delQual, expectedQual, gcp, false, false); + public BasicLikelihoodTestProvider(final String ref, final String nextRef, final String read, final int baseQual, final int insQual, final int delQual, final int expectedQual, final int gcp ) { + this(ref, nextRef, read, baseQual, insQual, delQual, expectedQual, gcp, false, false); } - public BasicLikelihoodTestProvider(final String ref, final String read, final int baseQual, final int insQual, final int delQual, final int expectedQual, final int gcp, final boolean left, final boolean right) { + public BasicLikelihoodTestProvider(final String ref, final String nextRef, final String read, final int baseQual, final int insQual, final int delQual, final int expectedQual, final int gcp, final boolean left, final boolean right) { this.baseQual = baseQual; this.delQual = delQual; this.insQual = insQual; this.gcp = gcp; this.read = read; this.ref = ref; + this.nextRef = nextRef; this.expectedQual = expectedQual; this.left = left; this.right = right; refBasesWithContext = asBytes(ref, left, right); + nextRefBasesWithContext = asBytes(nextRef, left, right); readBasesWithContext = asBytes(read, false, false); } @Override public String toString() { - return String.format("ref=%s read=%s b/i/d/c quals = %d/%d/%d/%d l/r flank = %b/%b e[qual]=%d", ref, read, baseQual, insQual, delQual, gcp, left, right, expectedQual); + return String.format("ref=%s nextRef=%s read=%s b/i/d/c quals = %d/%d/%d/%d l/r flank = %b/%b e[qual]=%d", ref, nextRef, read, baseQual, insQual, delQual, gcp, left, right, expectedQual); } public double expectedLogL() { @@ -129,7 +133,7 @@ public class PairHMMUnitTest extends BaseTest { } public double getTolerance(final PairHMM hmm) { - if ( hmm instanceof LoglessPairHMM) + if ( hmm instanceof LoglessPairHMM || hmm instanceof ArrayLoglessPairHMM) return toleranceFromExact(); if ( hmm instanceof Log10PairHMM ) { return ((Log10PairHMM)hmm).isDoingExactLog10Calculations() ? toleranceFromExact() : toleranceFromReference(); @@ -154,11 +158,14 @@ public class PairHMMUnitTest extends BaseTest { return pairHMM.computeReadLikelihoodGivenHaplotypeLog10( refBasesWithContext, readBasesWithContext, qualAsBytes(baseQual, false, anchorIndel), qualAsBytes(insQual, true, anchorIndel), qualAsBytes(delQual, true, anchorIndel), - qualAsBytes(gcp, false, anchorIndel), true); + qualAsBytes(gcp, false, anchorIndel), true, nextRefBasesWithContext); } private byte[] asBytes(final String bases, final boolean left, final boolean right) { - return ( (left ? LEFT_FLANK : "") + CONTEXT + bases + CONTEXT + (right ? RIGHT_FLANK : "")).getBytes(); + if(bases == null) + return null; + else + return ( (left ? LEFT_FLANK : "") + CONTEXT + bases + CONTEXT + (right ? RIGHT_FLANK : "")).getBytes(); } private byte[] qualAsBytes(final int phredQual, final boolean doGOP, final boolean anchorIndel) { @@ -204,7 +211,8 @@ public class PairHMMUnitTest extends BaseTest { final String ref = new String(new byte[]{refBase}); final String read = new String(new byte[]{readBase}); final int expected = refBase == readBase ? 0 : baseQual; - tests.add(new Object[]{new BasicLikelihoodTestProvider(ref, read, baseQual, indelQual, indelQual, expected, gcp)}); + // runBasicLikelihoodTests uses calcLogL(), which runs HMM with recacheReads=true. Since we will not cache, should pass null in place of a nextRef + tests.add(new Object[]{new BasicLikelihoodTestProvider(ref, null, read, baseQual, indelQual, indelQual, expected, gcp)}); } } @@ -220,10 +228,11 @@ public class PairHMMUnitTest extends BaseTest { final String ref = insertionP ? small : big; final String read = insertionP ? big : small; - tests.add(new Object[]{new BasicLikelihoodTestProvider(ref, read, baseQual, indelQual, indelQual, expected, gcp)}); - tests.add(new Object[]{new BasicLikelihoodTestProvider(ref, read, baseQual, indelQual, indelQual, expected, gcp, true, false)}); - tests.add(new Object[]{new BasicLikelihoodTestProvider(ref, read, baseQual, indelQual, indelQual, expected, gcp, false, true)}); - tests.add(new Object[]{new BasicLikelihoodTestProvider(ref, read, baseQual, indelQual, indelQual, expected, gcp, true, true)}); + // runBasicLikelihoodTests uses calcLogL(), which runs HMM with recacheReads=true. Since we will not cache, should pass null in place of a nextRef + tests.add(new Object[]{new BasicLikelihoodTestProvider(ref, null, read, baseQual, indelQual, indelQual, expected, gcp)}); + tests.add(new Object[]{new BasicLikelihoodTestProvider(ref, null, read, baseQual, indelQual, indelQual, expected, gcp, true, false)}); + tests.add(new Object[]{new BasicLikelihoodTestProvider(ref, null, read, baseQual, indelQual, indelQual, expected, gcp, false, true)}); + tests.add(new Object[]{new BasicLikelihoodTestProvider(ref, null, read, baseQual, indelQual, indelQual, expected, gcp, true, true)}); } } } @@ -261,7 +270,8 @@ public class PairHMMUnitTest extends BaseTest { for ( final boolean leftFlank : Arrays.asList(true, false) ) for ( final boolean rightFlank : Arrays.asList(true, false) ) - tests.add(new Object[]{new BasicLikelihoodTestProvider(ref, read, baseQual, indelQual, indelQual, -0, gcp, leftFlank, rightFlank)}); + // runOptimizedLikelihoodTests uses calcLogL(), which runs HMM with recacheReads=true. Since we will not cache, should pass null in place of a nextRef + tests.add(new Object[]{new BasicLikelihoodTestProvider(ref, null, read, baseQual, indelQual, indelQual, -0, gcp, leftFlank, rightFlank)}); } } } @@ -302,6 +312,7 @@ public class PairHMMUnitTest extends BaseTest { } } + @Test(enabled = !DEBUG) public void testMismatchInEveryPositionInTheReadWithCenteredHaplotype() { final byte[] haplotype1 = "TTCTCTTCTGTTGTGGCTGGTT".getBytes(); @@ -323,7 +334,7 @@ public class PairHMMUnitTest extends BaseTest { final byte[] mread = Arrays.copyOfRange(haplotype1,offset,haplotype1.length-offset); // change single base at position k to C. If it's a C, change to T mread[k] = ( mread[k] == (byte)'C' ? (byte)'T' : (byte)'C'); - final double res1 = loglessHMM.computeReadLikelihoodGivenHaplotypeLog10(haplotype1, mread, quals, gop, gop, gcp, false); + final double res1 = loglessHMM.computeReadLikelihoodGivenHaplotypeLog10(haplotype1, mread, quals, gop, gop, gcp, true, null); final double expected = Math.log10(1.0/haplotype1.length * Math.pow(QualityUtils.qualToProb(matchQual), mread.length-1) * QualityUtils.qualToErrorProb(mismatchQual)); Assert.assertEquals(res1, expected, 1e-2); } @@ -351,7 +362,7 @@ public class PairHMMUnitTest extends BaseTest { final byte[] mread = Arrays.copyOfRange(haplotype1,offset,haplotype1.length); // change single base at position k to C. If it's a C, change to T mread[k] = ( mread[k] == (byte)'C' ? (byte)'T' : (byte)'C'); - final double res1 = loglessHMM.computeReadLikelihoodGivenHaplotypeLog10(haplotype1, mread, quals, gop, gop, gcp, false); + final double res1 = loglessHMM.computeReadLikelihoodGivenHaplotypeLog10(haplotype1, mread, quals, gop, gop, gcp, true , null); final double expected = Math.log10(1.0/haplotype1.length * Math.pow(QualityUtils.qualToProb(matchQual), mread.length-1) * QualityUtils.qualToErrorProb(mismatchQual)); Assert.assertEquals(res1, expected, 1e-2); } @@ -382,11 +393,12 @@ public class PairHMMUnitTest extends BaseTest { final byte delQual = 37; final byte gcp = 10; hmm.initialize(readBases.length, refBases.length); + // running HMM with no haplotype caching. Should therefore pass null in place of nextRef bases final double d = hmm.computeReadLikelihoodGivenHaplotypeLog10( refBases, readBases, Utils.dupBytes(baseQual, readBases.length), Utils.dupBytes(insQual, readBases.length), Utils.dupBytes(delQual, readBases.length), - Utils.dupBytes(gcp, readBases.length), true); + Utils.dupBytes(gcp, readBases.length), true, null); Assert.assertTrue(d <= 0.0, "Likelihoods should be <= 0 but got "+ d); } @@ -399,11 +411,12 @@ public class PairHMMUnitTest extends BaseTest { final byte delQual = 100; final byte gcp = 100; hmm.initialize(readBases.length, refBases.length); + // running HMM with no haplotype caching. Should therefore pass null in place of nextRef bases double d = hmm.computeReadLikelihoodGivenHaplotypeLog10( refBases, readBases, Utils.dupBytes(baseQual, readBases.length), Utils.dupBytes(insQual, readBases.length), Utils.dupBytes(delQual, readBases.length), - Utils.dupBytes(gcp, readBases.length), true); + Utils.dupBytes(gcp, readBases.length), true, null); double expected = 0; final double initialCondition = ((double) Math.abs(refBases.length-readBases.length+1))/refBases.length; if (readBases.length < refBases.length) { @@ -445,11 +458,12 @@ public class PairHMMUnitTest extends BaseTest { final byte delQual = 40; final byte gcp = 10; hmm.initialize(readBases.length, refBases.length); + // running HMM with no haplotype caching. Should therefore pass null in place of nextRef bases hmm.computeReadLikelihoodGivenHaplotypeLog10( refBases, readBases, Utils.dupBytes(baseQual, readBases.length), Utils.dupBytes(insQual, readBases.length), Utils.dupBytes(delQual, readBases.length), - Utils.dupBytes(gcp, readBases.length), true); + Utils.dupBytes(gcp, readBases.length), true, null); } @Test(enabled = !DEBUG) @@ -460,20 +474,27 @@ public class PairHMMUnitTest extends BaseTest { final byte insQual = 40; final byte delQual = 40; final byte gcp = 10; - + // running HMMs with no haplotype caching. Should therefore pass null in place of nextRef bases exactHMM.initialize(readBases.length, refBases.length); exactHMM.computeReadLikelihoodGivenHaplotypeLog10( refBases, readBases, Utils.dupBytes(baseQual, readBases.length), Utils.dupBytes(insQual, readBases.length), Utils.dupBytes(delQual, readBases.length), - Utils.dupBytes(gcp, readBases.length), true); + Utils.dupBytes(gcp, readBases.length), true, null); loglessHMM.initialize(readBases.length, refBases.length); loglessHMM.computeReadLikelihoodGivenHaplotypeLog10( refBases, readBases, Utils.dupBytes(baseQual, readBases.length), Utils.dupBytes(insQual, readBases.length), Utils.dupBytes(delQual, readBases.length), - Utils.dupBytes(gcp, readBases.length), true); + Utils.dupBytes(gcp, readBases.length), true, null); + + arrayHMM.initialize(readBases.length, refBases.length); + arrayHMM.computeReadLikelihoodGivenHaplotypeLog10( refBases, readBases, + Utils.dupBytes(baseQual, readBases.length), + Utils.dupBytes(insQual, readBases.length), + Utils.dupBytes(delQual, readBases.length), + Utils.dupBytes(gcp, readBases.length), true, null); } @DataProvider(name = "JustHMMProvider") @@ -498,7 +519,8 @@ public class PairHMMUnitTest extends BaseTest { final byte[] gcp = Utils.dupBytes((byte) 10, delQual.length); hmm.initialize(readBases.length + 100, refBases.length + 100); for ( int nExtraMaxSize = 0; nExtraMaxSize < 100; nExtraMaxSize++ ) { - hmm.computeReadLikelihoodGivenHaplotypeLog10( refBases, readBases, quals, insQual, delQual, gcp, true); + // running HMM with no haplotype caching. Should therefore pass null in place of nextRef bases + hmm.computeReadLikelihoodGivenHaplotypeLog10( refBases, readBases, quals, insQual, delQual, gcp, true, null); } } @@ -506,10 +528,12 @@ public class PairHMMUnitTest extends BaseTest { public Object[][] makeHaplotypeIndexingProvider() { List tests = new ArrayList(); + // First difference (root2, root3) is the base position immediately following first difference (root1, root2) final String root1 = "ACGTGTCAAACCGGGTT"; - final String root2 = "ACGTGTCACACTGGGTT"; // differs in two locations + final String root2 = "ACGTGTCACACTGGGTT"; // differs in two locations from root1 + final String root3 = "ACGTGTCACTCCGCGTT"; // differs in two locations from root2 - final String read1 = "ACGTGTCACACTGGATT"; // 1 diff from 2, 2 diff from root1 + final String read1 = "ACGTGTCACACTGGATT"; // 1 diff from 2, 2 diff from root1, 2 diff from root3 final String read2 = root1; // same as root1 final String read3 = root2; // same as root2 final String read4 = "ACGTGTCACACTGGATTCGAT"; @@ -521,7 +545,7 @@ public class PairHMMUnitTest extends BaseTest { // int readLength = read.length(); { for ( int readLength = 10; readLength < read.length(); readLength++ ) { final String myRead = read.substring(0, readLength); - tests.add(new Object[]{hmm, root1, root2, myRead}); + tests.add(new Object[]{hmm, root1, root2, root3, myRead}); } } } @@ -530,7 +554,7 @@ public class PairHMMUnitTest extends BaseTest { } @Test(enabled = !DEBUG, dataProvider = "HaplotypeIndexingProvider") - void testHaplotypeIndexing(final PairHMM hmm, final String root1, final String root2, final String read) { + void testHaplotypeIndexing(final PairHMM hmm, final String root1, final String root2, final String root3, final String read) { final double TOLERANCE = 1e-9; final String prefix = "AACCGGTTTTTGGGCCCAAACGTACGTACAGTTGGTCAACATCGATCAGGTTCCGGAGTAC"; @@ -544,24 +568,30 @@ public class PairHMMUnitTest extends BaseTest { final String myPrefix = prefix.substring(prefixStart, prefix.length()); final String hap1 = myPrefix + root1; final String hap2 = myPrefix + root2; + final String hap3 = myPrefix + root3; final int hapStart = PairHMM.findFirstPositionWhereHaplotypesDiffer(hap1.getBytes(), hap2.getBytes()); - final double actual1 = testHaplotypeIndexingCalc(hmm, hap1, read, 0, true); - final double actual2 = testHaplotypeIndexingCalc(hmm, hap2, read, hapStart, false); - final double expected2 = testHaplotypeIndexingCalc(hmm, hap2, read, 0, true); - Assert.assertEquals(actual2, expected2, TOLERANCE, "Caching calculation failed for read " + read + " against haplotype with prefix '" + myPrefix + // Run the HMM on the first haplotype, peaking ahead the second, to set up caching + // Then run on the second haplotype in both cached and uncached mode, and verify that results are the same + // When evaluating actual2, it is important that we both apply old caching from hap1 and set up new caching for hap3, to ensure read/write operations do not cause conflicts + final double actual1 = testHaplotypeIndexingCalc(hmm, hap1, hap2, read, 0, true); + final double actual2 = testHaplotypeIndexingCalc(hmm, hap2, hap3, read, hapStart, false); + final double expected2 = testHaplotypeIndexingCalc(hmm, hap2, null, read, 0, true); + Assert.assertEquals(actual2, expected2, TOLERANCE, "HMM " + hmm.getClass() + " Caching calculation failed for read " + read + " against haplotype with prefix '" + myPrefix + "' expected " + expected2 + " but got " + actual2 + " with hapStart of " + hapStart); } } - private double testHaplotypeIndexingCalc(final PairHMM hmm, final String hap, final String read, final int hapStart, final boolean recache) { + private double testHaplotypeIndexingCalc(final PairHMM hmm, final String hap, final String nextHap, final String read, final int hapStart, final boolean recache) { final byte[] readBases = read.getBytes(); + // if not peaking ahead to capture info for a future cache run, the next haplotype will be null, and this should be passed to HMM + final byte[] nextHapBases = nextHap == null ? null : nextHap.getBytes(); final byte[] baseQuals = Utils.dupBytes((byte)30, readBases.length); final byte[] insQuals = Utils.dupBytes((byte)45, readBases.length); final byte[] delQuals = Utils.dupBytes((byte)40, readBases.length); final byte[] gcp = Utils.dupBytes((byte)10, readBases.length); - double d = hmm.computeReadLikelihoodGivenHaplotypeLog10(hap.getBytes(), readBases, baseQuals, insQuals, delQuals, gcp, recache); + double d = hmm.computeReadLikelihoodGivenHaplotypeLog10(hap.getBytes(), readBases, baseQuals, insQuals, delQuals, gcp, recache, nextHapBases); Assert.assertTrue(MathUtils.goodLog10Probability(d), "Likelihoods = " + d + " was bad for read " + read + " and ref " + hap + " with hapStart " + hapStart); return d; } @@ -576,7 +606,6 @@ public class PairHMMUnitTest extends BaseTest { for ( final boolean oneIsDiff : Arrays.asList(true, false) ) { final byte[] hap1 = Utils.dupBytes((byte)'A', haplotypeSize1); final byte[] hap2 = Utils.dupBytes((byte)'A', haplotypeSize2); - final int expected = oneIsDiff ? makeDiff(hap1, differingSite, minLength) : makeDiff(hap2, differingSite, minLength); @@ -604,6 +633,10 @@ public class PairHMMUnitTest extends BaseTest { myLoglessPairHMM.doNotUseTristateCorrection(); tests.add(new Object[]{myLoglessPairHMM}); + final ArrayLoglessPairHMM myArrayLoglessPairHMM = new ArrayLoglessPairHMM(); + myArrayLoglessPairHMM.doNotUseTristateCorrection(); + tests.add(new Object[]{myArrayLoglessPairHMM}); + final Log10PairHMM myLog10PairHMM = new Log10PairHMM(true); myLog10PairHMM.doNotUseTristateCorrection(); tests.add(new Object[]{myLog10PairHMM}); @@ -619,7 +652,7 @@ public class PairHMMUnitTest extends BaseTest { // didn't call initialize => should exception out double d = hmm.computeReadLikelihoodGivenHaplotypeLog10( refBases, readBases, - baseQuals, baseQuals, baseQuals, baseQuals, true); + baseQuals, baseQuals, baseQuals, baseQuals, true, null); } @Test(enabled = true, expectedExceptions = IllegalArgumentException.class, dataProvider = "JustHMMProvider") @@ -630,7 +663,7 @@ public class PairHMMUnitTest extends BaseTest { hmm.initialize(3, 3); double d = hmm.computeReadLikelihoodGivenHaplotypeLog10( refBases, readBases, - baseQuals, baseQuals, baseQuals, baseQuals, true); + baseQuals, baseQuals, baseQuals, baseQuals, true, null); } @Test(enabled = true, expectedExceptions = IllegalArgumentException.class, dataProvider = "JustHMMProvider") @@ -641,6 +674,6 @@ public class PairHMMUnitTest extends BaseTest { hmm.initialize(2, 3); double d = hmm.computeReadLikelihoodGivenHaplotypeLog10( refBases, readBases, - baseQuals, baseQuals, baseQuals, baseQuals, true); + baseQuals, baseQuals, baseQuals, baseQuals, true, null); } } \ No newline at end of file diff --git a/public/java/src/org/broadinstitute/sting/utils/pairhmm/Log10PairHMM.java b/public/java/src/org/broadinstitute/sting/utils/pairhmm/Log10PairHMM.java index a75c9426c..e7bc5cb56 100644 --- a/public/java/src/org/broadinstitute/sting/utils/pairhmm/Log10PairHMM.java +++ b/public/java/src/org/broadinstitute/sting/utils/pairhmm/Log10PairHMM.java @@ -101,7 +101,8 @@ public final class Log10PairHMM extends N2MemoryPairHMM { final byte[] deletionGOP, final byte[] overallGCP, final int hapStartIndex, - final boolean recacheReadValues ) { + final boolean recacheReadValues, + final int nextHapStartIndex) { if (previousHaplotypeBases == null || previousHaplotypeBases.length != haplotypeBases.length) { // set the initial value (free deletions in the beginning) for the first row in the deletion matrix diff --git a/public/java/src/org/broadinstitute/sting/utils/pairhmm/N2MemoryPairHMM.java b/public/java/src/org/broadinstitute/sting/utils/pairhmm/N2MemoryPairHMM.java index 1b277d3d8..a091a0716 100644 --- a/public/java/src/org/broadinstitute/sting/utils/pairhmm/N2MemoryPairHMM.java +++ b/public/java/src/org/broadinstitute/sting/utils/pairhmm/N2MemoryPairHMM.java @@ -44,10 +44,6 @@ abstract class N2MemoryPairHMM extends PairHMM { protected double[][] insertionMatrix = null; protected double[][] deletionMatrix = null; - // only used for debugging purposes - protected boolean doNotUseTristateCorrection = false; - protected void doNotUseTristateCorrection() { doNotUseTristateCorrection = true; } - /** * Initialize this PairHMM, making it suitable to run against a read and haplotype with given lengths * diff --git a/public/java/src/org/broadinstitute/sting/utils/pairhmm/PairHMM.java b/public/java/src/org/broadinstitute/sting/utils/pairhmm/PairHMM.java index f4f70ac63..eb52f4a85 100644 --- a/public/java/src/org/broadinstitute/sting/utils/pairhmm/PairHMM.java +++ b/public/java/src/org/broadinstitute/sting/utils/pairhmm/PairHMM.java @@ -43,6 +43,7 @@ public abstract class PairHMM { protected boolean constantsAreInitialized = false; protected byte[] previousHaplotypeBases; + protected int hapStartIndex; public enum HMM_IMPLEMENTATION { /* Very slow implementation which uses very accurate log10 sum functions. Only meant to be used as a reference test implementation */ @@ -51,6 +52,8 @@ public abstract class PairHMM { ORIGINAL, /* Optimized version of the PairHMM which caches per-read computations and operations in real space to avoid costly sums of log10'ed likelihoods */ LOGLESS_CACHING, + /* Logless caching PairHMM that stores computations in 1D arrays instead of matrices, and which proceeds diagonally over the (read x haplotype) intersection matrix */ + ARRAY_LOGLESS } protected int maxHaplotypeLength, maxReadLength; @@ -58,6 +61,10 @@ public abstract class PairHMM { protected int paddedReadLength, paddedHaplotypeLength; private boolean initialized = false; + // only used for debugging purposes + protected boolean doNotUseTristateCorrection = false; + protected void doNotUseTristateCorrection() { doNotUseTristateCorrection = true; } + /** * Initialize this PairHMM, making it suitable to run against a read and haplotype with given lengths * @@ -109,7 +116,8 @@ public abstract class PairHMM { final byte[] insertionGOP, final byte[] deletionGOP, final byte[] overallGCP, - final boolean recacheReadValues ) { + final boolean recacheReadValues, + final byte[] nextHaploytpeBases) { if ( ! initialized ) throw new IllegalStateException("Must call initialize before calling computeReadLikelihoodGivenHaplotypeLog10"); if ( haplotypeBases == null ) throw new IllegalArgumentException("haplotypeBases cannot be null"); if ( haplotypeBases.length > maxHaplotypeLength ) throw new IllegalArgumentException("Haplotype bases is too long, got " + haplotypeBases.length + " but max is " + maxHaplotypeLength); @@ -123,9 +131,13 @@ public abstract class PairHMM { paddedReadLength = readBases.length + 1; paddedHaplotypeLength = haplotypeBases.length + 1; - final int hapStartIndex = (previousHaplotypeBases == null || haplotypeBases.length != previousHaplotypeBases.length || recacheReadValues) ? 0 : findFirstPositionWhereHaplotypesDiffer(haplotypeBases, previousHaplotypeBases); + hapStartIndex = (recacheReadValues) ? 0 : hapStartIndex; - double result = subComputeReadLikelihoodGivenHaplotypeLog10(haplotypeBases, readBases, readQuals, insertionGOP, deletionGOP, overallGCP, hapStartIndex, recacheReadValues); + // Pre-compute the difference between the current haplotype and the next one to be run + // Looking ahead is necessary for the ArrayLoglessPairHMM implementation + final int nextHapStartIndex = (nextHaploytpeBases == null || haplotypeBases.length != nextHaploytpeBases.length) ? 0 : findFirstPositionWhereHaplotypesDiffer(haplotypeBases, nextHaploytpeBases); + + double result = subComputeReadLikelihoodGivenHaplotypeLog10(haplotypeBases, readBases, readQuals, insertionGOP, deletionGOP, overallGCP, hapStartIndex, recacheReadValues, nextHapStartIndex); if ( ! MathUtils.goodLog10Probability(result) ) throw new IllegalStateException("PairHMM Log Probability cannot be greater than 0: " + String.format("haplotype: %s, read: %s, result: %f", Arrays.toString(haplotypeBases), Arrays.toString(readBases), result)); @@ -134,6 +146,10 @@ public abstract class PairHMM { // Warning: This assumes no downstream modification of the haplotype bases (saves us from copying the array). It is okay for the haplotype caller and the Unified Genotyper. previousHaplotypeBases = haplotypeBases; + // For the next iteration, the hapStartIndex for the next haploytpe becomes the index for the current haplotype + // The array implementation has to look ahead to the next haplotype to store caching info. It cannot do this if nextHapStart is before hapStart + hapStartIndex = (nextHapStartIndex < hapStartIndex) ? 0: nextHapStartIndex; + return result; } @@ -149,7 +165,8 @@ public abstract class PairHMM { final byte[] deletionGOP, final byte[] overallGCP, final int hapStartIndex, - final boolean recacheReadValues ); + final boolean recacheReadValues, + final int nextHapStartIndex); /** * Compute the first position at which two haplotypes differ