From d665a8ba0caf7a5a5da592ca6a1e52571c8a5d59 Mon Sep 17 00:00:00 2001 From: Ryan Poplin Date: Mon, 28 Jan 2013 15:56:33 -0500 Subject: [PATCH 1/7] The Bayesian calculation of Qemp in the BQSR is now hierarchical. This fixes issues in which the covariate bins were very sparse and the prior estimate being used was the original quality score. This resulted in large correction factors for each covariate which breaks the equation. There is also now a new option, qlobalQScorePrior, which can be used to ignore the given (very high) quality scores and instead use this value as the prior. --- .../recalibration/BQSRReadTransformer.java | 2 +- .../recalibration/BaseRecalibration.java | 58 ++++++++++--------- .../sting/utils/recalibration/RecalDatum.java | 46 +++++++++++---- .../arguments/GATKArgumentCollection.java | 3 + .../utils/recalibration/BQSRArgumentSet.java | 8 +++ 5 files changed, 80 insertions(+), 37 deletions(-) diff --git a/protected/java/src/org/broadinstitute/sting/utils/recalibration/BQSRReadTransformer.java b/protected/java/src/org/broadinstitute/sting/utils/recalibration/BQSRReadTransformer.java index f6e63deec..c85072fa2 100644 --- a/protected/java/src/org/broadinstitute/sting/utils/recalibration/BQSRReadTransformer.java +++ b/protected/java/src/org/broadinstitute/sting/utils/recalibration/BQSRReadTransformer.java @@ -67,7 +67,7 @@ public class BQSRReadTransformer extends ReadTransformer { this.enabled = engine.hasBQSRArgumentSet(); if ( enabled ) { final BQSRArgumentSet args = engine.getBQSRArgumentSet(); - this.bqsr = new BaseRecalibration(args.getRecalFile(), args.getQuantizationLevels(), args.shouldDisableIndelQuals(), args.getPreserveQscoresLessThan(), args.shouldEmitOriginalQuals()); + this.bqsr = new BaseRecalibration(args.getRecalFile(), args.getQuantizationLevels(), args.shouldDisableIndelQuals(), args.getPreserveQscoresLessThan(), args.shouldEmitOriginalQuals(), args.getGlobalQScorePrior()); } final BQSRMode mode = WalkerManager.getWalkerAnnotation(walker, BQSRMode.class); return mode.ApplicationTime(); diff --git a/protected/java/src/org/broadinstitute/sting/utils/recalibration/BaseRecalibration.java b/protected/java/src/org/broadinstitute/sting/utils/recalibration/BaseRecalibration.java index 828f91c6f..6852cc40f 100644 --- a/protected/java/src/org/broadinstitute/sting/utils/recalibration/BaseRecalibration.java +++ b/protected/java/src/org/broadinstitute/sting/utils/recalibration/BaseRecalibration.java @@ -75,12 +75,12 @@ public class BaseRecalibration { private final boolean disableIndelQuals; private final int preserveQLessThan; + private final double globalQScorePrior; private final boolean emitOriginalQuals; private final NestedIntegerArray globalDeltaQs; private final NestedIntegerArray deltaQReporteds; - /** * Constructor using a GATK Report file * @@ -89,7 +89,7 @@ public class BaseRecalibration { * @param disableIndelQuals if true, do not emit base indel qualities * @param preserveQLessThan preserve quality scores less than this value */ - public BaseRecalibration(final File RECAL_FILE, final int quantizationLevels, final boolean disableIndelQuals, final int preserveQLessThan, final boolean emitOriginalQuals) { + public BaseRecalibration(final File RECAL_FILE, final int quantizationLevels, final boolean disableIndelQuals, final int preserveQLessThan, final boolean emitOriginalQuals, final double globalQScorePrior) { RecalibrationReport recalibrationReport = new RecalibrationReport(RECAL_FILE); recalibrationTables = recalibrationReport.getRecalibrationTables(); @@ -102,6 +102,7 @@ public class BaseRecalibration { this.disableIndelQuals = disableIndelQuals; this.preserveQLessThan = preserveQLessThan; + this.globalQScorePrior = globalQScorePrior; this.emitOriginalQuals = emitOriginalQuals; logger.info("Calculating cached tables..."); @@ -112,13 +113,16 @@ public class BaseRecalibration { // be done upfront, on initialization of this BaseRecalibration structure // final NestedIntegerArray byReadGroupTable = recalibrationTables.getReadGroupTable(); - globalDeltaQs = new NestedIntegerArray( byReadGroupTable.getDimensions() ); + final NestedIntegerArray byQualTable = recalibrationTables.getQualityScoreTable(); + + globalDeltaQs = new NestedIntegerArray( byQualTable.getDimensions() ); logger.info("Calculating global delta Q table..."); - for ( NestedIntegerArray.Leaf leaf : byReadGroupTable.getAllLeaves() ) { + for ( NestedIntegerArray.Leaf leaf : byQualTable.getAllLeaves() ) { final int rgKey = leaf.keys[0]; - final int eventIndex = leaf.keys[1]; - final double globalDeltaQ = calculateGlobalDeltaQ(rgKey, EventType.eventFrom(eventIndex)); - globalDeltaQs.put(globalDeltaQ, rgKey, eventIndex); + final int qual = leaf.keys[1]; + final int eventIndex = leaf.keys[2]; + final double globalDeltaQ = calculateGlobalDeltaQ(rgKey, EventType.eventFrom(eventIndex), (byte) qual); + globalDeltaQs.put(globalDeltaQ, rgKey, qual, eventIndex); } @@ -127,7 +131,6 @@ public class BaseRecalibration { // into a matrix indexed by rgGroup, qual, and event type. // the code below actually creates this cache with a NestedIntegerArray calling into the actual // calculateDeltaQReported code. - final NestedIntegerArray byQualTable = recalibrationTables.getQualityScoreTable(); deltaQReporteds = new NestedIntegerArray( byQualTable.getDimensions() ); logger.info("Calculating delta Q reported table..."); for ( NestedIntegerArray.Leaf leaf : byQualTable.getAllLeaves() ) { @@ -135,7 +138,7 @@ public class BaseRecalibration { final int qual = leaf.keys[1]; final int eventIndex = leaf.keys[2]; final EventType event = EventType.eventFrom(eventIndex); - final double globalDeltaQ = getGlobalDeltaQ(rgKey, event); + final double globalDeltaQ = getGlobalDeltaQ(rgKey, event, (byte)qual); final double deltaQReported = calculateDeltaQReported(rgKey, qual, event, globalDeltaQ, (byte)qual); deltaQReporteds.put(deltaQReported, rgKey, qual, eventIndex); } @@ -188,17 +191,17 @@ public class BaseRecalibration { // the rg key is constant over the whole read, the global deltaQ is too final int rgKey = fullReadKeySet[0][0]; - final double globalDeltaQ = getGlobalDeltaQ(rgKey, errorModel); for (int offset = 0; offset < readLength; offset++) { // recalibrate all bases in the read final byte origQual = quals[offset]; + final double globalDeltaQ = getGlobalDeltaQ(rgKey, errorModel, origQual); // only recalibrate usable qualities (the original quality will come from the instrument -- reported quality) if ( origQual >= preserveQLessThan ) { // get the keyset for this base using the error model final int[] keySet = fullReadKeySet[offset]; - final double deltaQReported = getDeltaQReported(keySet[0], keySet[1], errorModel, globalDeltaQ); - final double deltaQCovariates = calculateDeltaQCovariates(recalibrationTables, keySet, errorModel, globalDeltaQ, deltaQReported, origQual); + final double deltaQReported = getDeltaQReported(keySet[0], keySet[1], errorModel, globalDeltaQ, origQual); + final double deltaQCovariates = calculateDeltaQCovariates(recalibrationTables, keySet, errorModel, deltaQReported, globalDeltaQ, origQual); // calculate the recalibrated qual using the BQSR formula double recalibratedQualDouble = origQual + globalDeltaQ + deltaQReported + deltaQCovariates; @@ -218,11 +221,12 @@ public class BaseRecalibration { } } - private double getGlobalDeltaQ(final int rgKey, final EventType errorModel) { - final Double cached = globalDeltaQs.get(rgKey, errorModel.ordinal()); + private double getGlobalDeltaQ(final int rgKey, final EventType errorModel, final byte qualFromRead) { + + final Double cached = globalDeltaQs.get(rgKey, (int) qualFromRead, errorModel.ordinal()); if ( TEST_CACHING ) { - final double calcd = calculateGlobalDeltaQ(rgKey, errorModel); + final double calcd = calculateGlobalDeltaQ(rgKey, errorModel, qualFromRead); if ( calcd != cached ) throw new IllegalStateException("calculated " + calcd + " and cached " + cached + " global delta q not equal at " + rgKey + " / " + errorModel); } @@ -230,7 +234,8 @@ public class BaseRecalibration { return cachedWithDefault(cached); } - private double getDeltaQReported(final int rgKey, final int qualKey, final EventType errorModel, final double globalDeltaQ) { + private double getDeltaQReported(final int rgKey, final int qualKey, final EventType errorModel, final double globalDeltaQ, final byte origQual) { + final Double cached = deltaQReporteds.get(rgKey, qualKey, errorModel.ordinal()); if ( TEST_CACHING ) { @@ -240,6 +245,7 @@ public class BaseRecalibration { } return cachedWithDefault(cached); + } /** @@ -258,14 +264,14 @@ public class BaseRecalibration { * @param errorModel the event type * @return global delta Q */ - private double calculateGlobalDeltaQ(final int rgKey, final EventType errorModel) { + private double calculateGlobalDeltaQ(final int rgKey, final EventType errorModel, final byte qualFromRead) { double result = 0.0; final RecalDatum empiricalQualRG = recalibrationTables.getReadGroupTable().get(rgKey, errorModel.ordinal()); if (empiricalQualRG != null) { - final double globalDeltaQEmpirical = empiricalQualRG.getEmpiricalQuality(); - final double aggregrateQReported = empiricalQualRG.getEstimatedQReported(); + final double aggregrateQReported = ( globalQScorePrior > 0.0 && errorModel.equals(EventType.BASE_SUBSTITUTION) ? globalQScorePrior : qualFromRead ); + final double globalDeltaQEmpirical = empiricalQualRG.getEmpiricalQuality( aggregrateQReported ); result = globalDeltaQEmpirical - aggregrateQReported; } @@ -277,14 +283,14 @@ public class BaseRecalibration { final RecalDatum empiricalQualQS = recalibrationTables.getQualityScoreTable().get(rgKey, qualKey, errorModel.ordinal()); if (empiricalQualQS != null) { - final double deltaQReportedEmpirical = empiricalQualQS.getEmpiricalQuality(); - result = deltaQReportedEmpirical - qualFromRead - globalDeltaQ; + final double deltaQReportedEmpirical = empiricalQualQS.getEmpiricalQuality( qualFromRead + globalDeltaQ ); + result = deltaQReportedEmpirical - ( qualFromRead + globalDeltaQ ); } return result; } - private double calculateDeltaQCovariates(final RecalibrationTables recalibrationTables, final int[] key, final EventType errorModel, final double globalDeltaQ, final double deltaQReported, final byte qualFromRead) { + private double calculateDeltaQCovariates(final RecalibrationTables recalibrationTables, final int[] key, final EventType errorModel, final double deltaQReported, final double globalDeltaQ, final byte qualFromRead) { double result = 0.0; // for all optional covariates @@ -294,7 +300,7 @@ public class BaseRecalibration { result += calculateDeltaQCovariate(recalibrationTables.getTable(i), key[0], key[1], key[i], errorModel, - globalDeltaQ, deltaQReported, qualFromRead); + deltaQReported, globalDeltaQ, qualFromRead); } return result; @@ -305,13 +311,13 @@ public class BaseRecalibration { final int qualKey, final int tableKey, final EventType errorModel, - final double globalDeltaQ, final double deltaQReported, + final double globalDeltaQ, final byte qualFromRead) { final RecalDatum empiricalQualCO = table.get(rgKey, qualKey, tableKey, errorModel.ordinal()); if (empiricalQualCO != null) { - final double deltaQCovariateEmpirical = empiricalQualCO.getEmpiricalQuality(); - return deltaQCovariateEmpirical - qualFromRead - (globalDeltaQ + deltaQReported); + final double deltaQCovariateEmpirical = empiricalQualCO.getEmpiricalQuality( deltaQReported + globalDeltaQ + qualFromRead ); + return deltaQCovariateEmpirical - ( deltaQReported + globalDeltaQ + qualFromRead ); } else { return 0.0; } diff --git a/protected/java/src/org/broadinstitute/sting/utils/recalibration/RecalDatum.java b/protected/java/src/org/broadinstitute/sting/utils/recalibration/RecalDatum.java index 9430caaac..743c56ee5 100644 --- a/protected/java/src/org/broadinstitute/sting/utils/recalibration/RecalDatum.java +++ b/protected/java/src/org/broadinstitute/sting/utils/recalibration/RecalDatum.java @@ -78,6 +78,9 @@ import org.apache.commons.math.optimization.fitting.GaussianFunction; import org.broadinstitute.sting.utils.MathUtils; import org.broadinstitute.sting.utils.QualityUtils; +import java.util.HashMap; +import java.util.Map; + /** * An individual piece of recalibration data. Each bin counts up the number of observations and the number @@ -111,6 +114,11 @@ public class RecalDatum { */ private double empiricalQuality; + /** + * the empirical quality for datums that have been collapsed together (by read group and reported quality, for example) + */ + private Map empiricalQualityMap; + /** * number of bases seen in total */ @@ -148,6 +156,7 @@ public class RecalDatum { numMismatches = _numMismatches; estimatedQReported = reportedQuality; empiricalQuality = UNINITIALIZED; + empiricalQualityMap = new HashMap(); } /** @@ -159,6 +168,7 @@ public class RecalDatum { this.numMismatches = copy.getNumMismatches(); this.estimatedQReported = copy.estimatedQReported; this.empiricalQuality = copy.empiricalQuality; + empiricalQualityMap = copy.empiricalQualityMap; } /** @@ -172,6 +182,7 @@ public class RecalDatum { increment(other.getNumObservations(), other.getNumMismatches()); estimatedQReported = -10 * Math.log10(sumErrors / getNumObservations()); empiricalQuality = UNINITIALIZED; + empiricalQualityMap = new HashMap(); } public synchronized void setEstimatedQReported(final double estimatedQReported) { @@ -314,22 +325,37 @@ public class RecalDatum { return getNumObservations() * QualityUtils.qualToErrorProb(estimatedQReported); } + /** + * Calculate empirical quality score from mismatches, observations, and the given conditional prior (expensive operation) + */ + public double getEmpiricalQuality(final double conditionalPriorQ) { + + final int priorQKey = MathUtils.fastRound(conditionalPriorQ); + Double returnQ = empiricalQualityMap.get(priorQKey); + + if( returnQ == null ) { + // smoothing is one error and one non-error observation + final long mismatches = (long)(getNumMismatches() + 0.5) + SMOOTHING_CONSTANT; + final long observations = getNumObservations() + SMOOTHING_CONSTANT + SMOOTHING_CONSTANT; + + final double empiricalQual = RecalDatum.bayesianEstimateOfEmpiricalQuality(observations, mismatches, conditionalPriorQ); + + // This is the old and busted point estimate approach: + //final double empiricalQual = -10 * Math.log10(getEmpiricalErrorRate()); + + returnQ = Math.min(empiricalQual, (double) QualityUtils.MAX_RECALIBRATED_Q_SCORE); + empiricalQualityMap.put( priorQKey, returnQ ); + } + return returnQ; + } + /** * Calculate and cache the empirical quality score from mismatches and observations (expensive operation) */ @Requires("empiricalQuality == UNINITIALIZED") @Ensures("empiricalQuality != UNINITIALIZED") private synchronized void calcEmpiricalQuality() { - - // smoothing is one error and one non-error observation - final long mismatches = (long)(getNumMismatches() + 0.5) + SMOOTHING_CONSTANT; - final long observations = getNumObservations() + SMOOTHING_CONSTANT + SMOOTHING_CONSTANT; - - final double empiricalQual = RecalDatum.bayesianEstimateOfEmpiricalQuality(observations, mismatches, getEstimatedQReported()); - - // This is the old and busted point estimate approach: - //final double empiricalQual = -10 * Math.log10(getEmpiricalErrorRate()); - + final double empiricalQual = getEmpiricalQuality(getEstimatedQReported()); empiricalQuality = Math.min(empiricalQual, (double) QualityUtils.MAX_RECALIBRATED_Q_SCORE); } diff --git a/public/java/src/org/broadinstitute/sting/gatk/arguments/GATKArgumentCollection.java b/public/java/src/org/broadinstitute/sting/gatk/arguments/GATKArgumentCollection.java index 9cd88001c..6520947d4 100644 --- a/public/java/src/org/broadinstitute/sting/gatk/arguments/GATKArgumentCollection.java +++ b/public/java/src/org/broadinstitute/sting/gatk/arguments/GATKArgumentCollection.java @@ -241,6 +241,9 @@ public class GATKArgumentCollection { @Argument(fullName = "preserve_qscores_less_than", shortName = "preserveQ", doc = "Bases with quality scores less than this threshold won't be recalibrated (with -BQSR)", required = false) public int PRESERVE_QSCORES_LESS_THAN = QualityUtils.MIN_USABLE_Q_SCORE; + @Argument(fullName = "qlobalQScorePrior", shortName = "qlobalQScorePrior", doc = "The global Qscore Bayesian prior to use in the BQSR. If specified, this value will be used as the prior for all mismatch quality scores instead of the actual reported quality score", required = false) + public double globalQScorePrior = -1.0; + // -------------------------------------------------------------------------------------------------------------- // // Other utility arguments diff --git a/public/java/src/org/broadinstitute/sting/utils/recalibration/BQSRArgumentSet.java b/public/java/src/org/broadinstitute/sting/utils/recalibration/BQSRArgumentSet.java index dbf70f4ce..600700484 100644 --- a/public/java/src/org/broadinstitute/sting/utils/recalibration/BQSRArgumentSet.java +++ b/public/java/src/org/broadinstitute/sting/utils/recalibration/BQSRArgumentSet.java @@ -36,6 +36,7 @@ public class BQSRArgumentSet { private boolean disableIndelQuals; private boolean emitOriginalQuals; private int PRESERVE_QSCORES_LESS_THAN; + private double globalQScorePrior; public BQSRArgumentSet(final GATKArgumentCollection args) { this.BQSR_RECAL_FILE = args.BQSR_RECAL_FILE; @@ -43,6 +44,7 @@ public class BQSRArgumentSet { this.disableIndelQuals = args.disableIndelQuals; this.emitOriginalQuals = args.emitOriginalQuals; this.PRESERVE_QSCORES_LESS_THAN = args.PRESERVE_QSCORES_LESS_THAN; + this.globalQScorePrior = args.globalQScorePrior; } public File getRecalFile() { return BQSR_RECAL_FILE; } @@ -55,6 +57,8 @@ public class BQSRArgumentSet { public int getPreserveQscoresLessThan() { return PRESERVE_QSCORES_LESS_THAN; } + public double getGlobalQScorePrior() { return globalQScorePrior; } + public void setRecalFile(final File BQSR_RECAL_FILE) { this.BQSR_RECAL_FILE = BQSR_RECAL_FILE; } @@ -74,4 +78,8 @@ public class BQSRArgumentSet { public void setPreserveQscoresLessThan(final int PRESERVE_QSCORES_LESS_THAN) { this.PRESERVE_QSCORES_LESS_THAN = PRESERVE_QSCORES_LESS_THAN; } + + public void setGlobalQScorePrior(final double globalQScorePrior) { + this.globalQScorePrior = globalQScorePrior; + } } From 1f254d29df1c249de917a85ae5c8a756742f9697 Mon Sep 17 00:00:00 2001 From: Ryan Poplin Date: Mon, 28 Jan 2013 22:16:43 -0500 Subject: [PATCH 2/7] Don't set the empirical quality when reading in the recal table because then we won't be using the new quality estimates for the prior since the value is cached. --- .../recalibration/BaseRecalibration.java | 60 +++++++++---------- .../sting/utils/recalibration/RecalDatum.java | 58 ++++++------------ .../recalibration/RecalibrationReport.java | 4 +- 3 files changed, 51 insertions(+), 71 deletions(-) diff --git a/protected/java/src/org/broadinstitute/sting/utils/recalibration/BaseRecalibration.java b/protected/java/src/org/broadinstitute/sting/utils/recalibration/BaseRecalibration.java index 6852cc40f..ba18f5c96 100644 --- a/protected/java/src/org/broadinstitute/sting/utils/recalibration/BaseRecalibration.java +++ b/protected/java/src/org/broadinstitute/sting/utils/recalibration/BaseRecalibration.java @@ -81,9 +81,10 @@ public class BaseRecalibration { private final NestedIntegerArray globalDeltaQs; private final NestedIntegerArray deltaQReporteds; + /** * Constructor using a GATK Report file - * + * * @param RECAL_FILE a GATK Report file containing the recalibration information * @param quantizationLevels number of bins to quantize the quality scores * @param disableIndelQuals if true, do not emit base indel qualities @@ -113,16 +114,13 @@ public class BaseRecalibration { // be done upfront, on initialization of this BaseRecalibration structure // final NestedIntegerArray byReadGroupTable = recalibrationTables.getReadGroupTable(); - final NestedIntegerArray byQualTable = recalibrationTables.getQualityScoreTable(); - - globalDeltaQs = new NestedIntegerArray( byQualTable.getDimensions() ); + globalDeltaQs = new NestedIntegerArray( byReadGroupTable.getDimensions() ); logger.info("Calculating global delta Q table..."); - for ( NestedIntegerArray.Leaf leaf : byQualTable.getAllLeaves() ) { + for ( NestedIntegerArray.Leaf leaf : byReadGroupTable.getAllLeaves() ) { final int rgKey = leaf.keys[0]; - final int qual = leaf.keys[1]; - final int eventIndex = leaf.keys[2]; - final double globalDeltaQ = calculateGlobalDeltaQ(rgKey, EventType.eventFrom(eventIndex), (byte) qual); - globalDeltaQs.put(globalDeltaQ, rgKey, qual, eventIndex); + final int eventIndex = leaf.keys[1]; + final double globalDeltaQ = calculateGlobalDeltaQ(rgKey, EventType.eventFrom(eventIndex)); + globalDeltaQs.put(globalDeltaQ, rgKey, eventIndex); } @@ -131,6 +129,7 @@ public class BaseRecalibration { // into a matrix indexed by rgGroup, qual, and event type. // the code below actually creates this cache with a NestedIntegerArray calling into the actual // calculateDeltaQReported code. + final NestedIntegerArray byQualTable = recalibrationTables.getQualityScoreTable(); deltaQReporteds = new NestedIntegerArray( byQualTable.getDimensions() ); logger.info("Calculating delta Q reported table..."); for ( NestedIntegerArray.Leaf leaf : byQualTable.getAllLeaves() ) { @@ -138,7 +137,7 @@ public class BaseRecalibration { final int qual = leaf.keys[1]; final int eventIndex = leaf.keys[2]; final EventType event = EventType.eventFrom(eventIndex); - final double globalDeltaQ = getGlobalDeltaQ(rgKey, event, (byte)qual); + final double globalDeltaQ = getGlobalDeltaQ(rgKey, event); final double deltaQReported = calculateDeltaQReported(rgKey, qual, event, globalDeltaQ, (byte)qual); deltaQReporteds.put(deltaQReported, rgKey, qual, eventIndex); } @@ -191,17 +190,17 @@ public class BaseRecalibration { // the rg key is constant over the whole read, the global deltaQ is too final int rgKey = fullReadKeySet[0][0]; + final double globalDeltaQ = getGlobalDeltaQ(rgKey, errorModel); for (int offset = 0; offset < readLength; offset++) { // recalibrate all bases in the read final byte origQual = quals[offset]; - final double globalDeltaQ = getGlobalDeltaQ(rgKey, errorModel, origQual); // only recalibrate usable qualities (the original quality will come from the instrument -- reported quality) if ( origQual >= preserveQLessThan ) { // get the keyset for this base using the error model final int[] keySet = fullReadKeySet[offset]; - final double deltaQReported = getDeltaQReported(keySet[0], keySet[1], errorModel, globalDeltaQ, origQual); - final double deltaQCovariates = calculateDeltaQCovariates(recalibrationTables, keySet, errorModel, deltaQReported, globalDeltaQ, origQual); + final double deltaQReported = getDeltaQReported(keySet[0], keySet[1], errorModel, globalDeltaQ); + final double deltaQCovariates = calculateDeltaQCovariates(recalibrationTables, keySet, errorModel, globalDeltaQ, deltaQReported, origQual); // calculate the recalibrated qual using the BQSR formula double recalibratedQualDouble = origQual + globalDeltaQ + deltaQReported + deltaQCovariates; @@ -213,6 +212,10 @@ public class BaseRecalibration { final byte recalibratedQualityScore = quantizationInfo.getQuantizedQuals().get(recalibratedQual); quals[offset] = recalibratedQualityScore; + if( quals[offset] > QualityUtils.MAX_REASONABLE_Q_SCORE ) { + System.out.println("A"); + //calculateDeltaQCovariates(recalibrationTables, keySet, errorModel, globalDeltaQ, deltaQReported, origQual); + } } } @@ -221,12 +224,11 @@ public class BaseRecalibration { } } - private double getGlobalDeltaQ(final int rgKey, final EventType errorModel, final byte qualFromRead) { - - final Double cached = globalDeltaQs.get(rgKey, (int) qualFromRead, errorModel.ordinal()); + private double getGlobalDeltaQ(final int rgKey, final EventType errorModel) { + final Double cached = globalDeltaQs.get(rgKey, errorModel.ordinal()); if ( TEST_CACHING ) { - final double calcd = calculateGlobalDeltaQ(rgKey, errorModel, qualFromRead); + final double calcd = calculateGlobalDeltaQ(rgKey, errorModel); if ( calcd != cached ) throw new IllegalStateException("calculated " + calcd + " and cached " + cached + " global delta q not equal at " + rgKey + " / " + errorModel); } @@ -234,8 +236,7 @@ public class BaseRecalibration { return cachedWithDefault(cached); } - private double getDeltaQReported(final int rgKey, final int qualKey, final EventType errorModel, final double globalDeltaQ, final byte origQual) { - + private double getDeltaQReported(final int rgKey, final int qualKey, final EventType errorModel, final double globalDeltaQ) { final Double cached = deltaQReporteds.get(rgKey, qualKey, errorModel.ordinal()); if ( TEST_CACHING ) { @@ -245,7 +246,6 @@ public class BaseRecalibration { } return cachedWithDefault(cached); - } /** @@ -264,14 +264,14 @@ public class BaseRecalibration { * @param errorModel the event type * @return global delta Q */ - private double calculateGlobalDeltaQ(final int rgKey, final EventType errorModel, final byte qualFromRead) { + private double calculateGlobalDeltaQ(final int rgKey, final EventType errorModel) { double result = 0.0; final RecalDatum empiricalQualRG = recalibrationTables.getReadGroupTable().get(rgKey, errorModel.ordinal()); if (empiricalQualRG != null) { - final double aggregrateQReported = ( globalQScorePrior > 0.0 && errorModel.equals(EventType.BASE_SUBSTITUTION) ? globalQScorePrior : qualFromRead ); - final double globalDeltaQEmpirical = empiricalQualRG.getEmpiricalQuality( aggregrateQReported ); + final double aggregrateQReported = ( globalQScorePrior > 0.0 && errorModel.equals(EventType.BASE_SUBSTITUTION) ? globalQScorePrior : empiricalQualRG.getEstimatedQReported() ); + final double globalDeltaQEmpirical = empiricalQualRG.getEmpiricalQuality(aggregrateQReported); result = globalDeltaQEmpirical - aggregrateQReported; } @@ -283,14 +283,14 @@ public class BaseRecalibration { final RecalDatum empiricalQualQS = recalibrationTables.getQualityScoreTable().get(rgKey, qualKey, errorModel.ordinal()); if (empiricalQualQS != null) { - final double deltaQReportedEmpirical = empiricalQualQS.getEmpiricalQuality( qualFromRead + globalDeltaQ ); - result = deltaQReportedEmpirical - ( qualFromRead + globalDeltaQ ); + final double deltaQReportedEmpirical = empiricalQualQS.getEmpiricalQuality(globalDeltaQ + qualFromRead); + result = deltaQReportedEmpirical - (globalDeltaQ + qualFromRead); } return result; } - private double calculateDeltaQCovariates(final RecalibrationTables recalibrationTables, final int[] key, final EventType errorModel, final double deltaQReported, final double globalDeltaQ, final byte qualFromRead) { + private double calculateDeltaQCovariates(final RecalibrationTables recalibrationTables, final int[] key, final EventType errorModel, final double globalDeltaQ, final double deltaQReported, final byte qualFromRead) { double result = 0.0; // for all optional covariates @@ -300,7 +300,7 @@ public class BaseRecalibration { result += calculateDeltaQCovariate(recalibrationTables.getTable(i), key[0], key[1], key[i], errorModel, - deltaQReported, globalDeltaQ, qualFromRead); + globalDeltaQ, deltaQReported, qualFromRead); } return result; @@ -311,13 +311,13 @@ public class BaseRecalibration { final int qualKey, final int tableKey, final EventType errorModel, - final double deltaQReported, final double globalDeltaQ, + final double deltaQReported, final byte qualFromRead) { final RecalDatum empiricalQualCO = table.get(rgKey, qualKey, tableKey, errorModel.ordinal()); if (empiricalQualCO != null) { - final double deltaQCovariateEmpirical = empiricalQualCO.getEmpiricalQuality( deltaQReported + globalDeltaQ + qualFromRead ); - return deltaQCovariateEmpirical - ( deltaQReported + globalDeltaQ + qualFromRead ); + final double deltaQCovariateEmpirical = empiricalQualCO.getEmpiricalQuality(deltaQReported + globalDeltaQ + qualFromRead); + return deltaQCovariateEmpirical - (deltaQReported + globalDeltaQ + qualFromRead); } else { return 0.0; } diff --git a/protected/java/src/org/broadinstitute/sting/utils/recalibration/RecalDatum.java b/protected/java/src/org/broadinstitute/sting/utils/recalibration/RecalDatum.java index 743c56ee5..67794c248 100644 --- a/protected/java/src/org/broadinstitute/sting/utils/recalibration/RecalDatum.java +++ b/protected/java/src/org/broadinstitute/sting/utils/recalibration/RecalDatum.java @@ -77,9 +77,7 @@ import com.google.java.contract.Requires; import org.apache.commons.math.optimization.fitting.GaussianFunction; import org.broadinstitute.sting.utils.MathUtils; import org.broadinstitute.sting.utils.QualityUtils; - -import java.util.HashMap; -import java.util.Map; +import org.broadinstitute.sting.utils.exceptions.ReviewedStingException; /** @@ -114,11 +112,6 @@ public class RecalDatum { */ private double empiricalQuality; - /** - * the empirical quality for datums that have been collapsed together (by read group and reported quality, for example) - */ - private Map empiricalQualityMap; - /** * number of bases seen in total */ @@ -156,7 +149,6 @@ public class RecalDatum { numMismatches = _numMismatches; estimatedQReported = reportedQuality; empiricalQuality = UNINITIALIZED; - empiricalQualityMap = new HashMap(); } /** @@ -168,7 +160,6 @@ public class RecalDatum { this.numMismatches = copy.getNumMismatches(); this.estimatedQReported = copy.estimatedQReported; this.empiricalQuality = copy.empiricalQuality; - empiricalQualityMap = copy.empiricalQualityMap; } /** @@ -182,7 +173,6 @@ public class RecalDatum { increment(other.getNumObservations(), other.getNumMismatches()); estimatedQReported = -10 * Math.log10(sumErrors / getNumObservations()); empiricalQuality = UNINITIALIZED; - empiricalQualityMap = new HashMap(); } public synchronized void setEstimatedQReported(final double estimatedQReported) { @@ -232,8 +222,13 @@ public class RecalDatum { } public final double getEmpiricalQuality() { - if (empiricalQuality == UNINITIALIZED) - calcEmpiricalQuality(); + return getEmpiricalQuality(getEstimatedQReported()); + } + + public final double getEmpiricalQuality(final double conditionalPrior) { + if (empiricalQuality == UNINITIALIZED) { + calcEmpiricalQuality(conditionalPrior); + } return empiricalQuality; } @@ -325,37 +320,22 @@ public class RecalDatum { return getNumObservations() * QualityUtils.qualToErrorProb(estimatedQReported); } - /** - * Calculate empirical quality score from mismatches, observations, and the given conditional prior (expensive operation) - */ - public double getEmpiricalQuality(final double conditionalPriorQ) { - - final int priorQKey = MathUtils.fastRound(conditionalPriorQ); - Double returnQ = empiricalQualityMap.get(priorQKey); - - if( returnQ == null ) { - // smoothing is one error and one non-error observation - final long mismatches = (long)(getNumMismatches() + 0.5) + SMOOTHING_CONSTANT; - final long observations = getNumObservations() + SMOOTHING_CONSTANT + SMOOTHING_CONSTANT; - - final double empiricalQual = RecalDatum.bayesianEstimateOfEmpiricalQuality(observations, mismatches, conditionalPriorQ); - - // This is the old and busted point estimate approach: - //final double empiricalQual = -10 * Math.log10(getEmpiricalErrorRate()); - - returnQ = Math.min(empiricalQual, (double) QualityUtils.MAX_RECALIBRATED_Q_SCORE); - empiricalQualityMap.put( priorQKey, returnQ ); - } - return returnQ; - } - /** * Calculate and cache the empirical quality score from mismatches and observations (expensive operation) */ @Requires("empiricalQuality == UNINITIALIZED") @Ensures("empiricalQuality != UNINITIALIZED") - private synchronized void calcEmpiricalQuality() { - final double empiricalQual = getEmpiricalQuality(getEstimatedQReported()); + private synchronized void calcEmpiricalQuality(final double conditionalPrior) { + + // smoothing is one error and one non-error observation + final long mismatches = (long)(getNumMismatches() + 0.5) + SMOOTHING_CONSTANT; + final long observations = getNumObservations() + SMOOTHING_CONSTANT + SMOOTHING_CONSTANT; + + final double empiricalQual = RecalDatum.bayesianEstimateOfEmpiricalQuality(observations, mismatches, conditionalPrior); + + // This is the old and busted point estimate approach: + //final double empiricalQual = -10 * Math.log10(getEmpiricalErrorRate()); + empiricalQuality = Math.min(empiricalQual, (double) QualityUtils.MAX_RECALIBRATED_Q_SCORE); } diff --git a/protected/java/src/org/broadinstitute/sting/utils/recalibration/RecalibrationReport.java b/protected/java/src/org/broadinstitute/sting/utils/recalibration/RecalibrationReport.java index 3fdbd63bd..bf8f00ca4 100644 --- a/protected/java/src/org/broadinstitute/sting/utils/recalibration/RecalibrationReport.java +++ b/protected/java/src/org/broadinstitute/sting/utils/recalibration/RecalibrationReport.java @@ -246,7 +246,7 @@ public class RecalibrationReport { private RecalDatum getRecalDatum(final GATKReportTable reportTable, final int row, final boolean hasEstimatedQReportedColumn) { final long nObservations = asLong(reportTable.get(row, RecalUtils.NUMBER_OBSERVATIONS_COLUMN_NAME)); final double nErrors = asDouble(reportTable.get(row, RecalUtils.NUMBER_ERRORS_COLUMN_NAME)); - final double empiricalQuality = asDouble(reportTable.get(row, RecalUtils.EMPIRICAL_QUALITY_COLUMN_NAME)); + //final double empiricalQuality = asDouble(reportTable.get(row, RecalUtils.EMPIRICAL_QUALITY_COLUMN_NAME)); // the estimatedQreported column only exists in the ReadGroup table final double estimatedQReported = hasEstimatedQReportedColumn ? @@ -255,7 +255,7 @@ public class RecalibrationReport { final RecalDatum datum = new RecalDatum(nObservations, nErrors, (byte)1); datum.setEstimatedQReported(estimatedQReported); - datum.setEmpiricalQuality(empiricalQuality); + //datum.setEmpiricalQuality(empiricalQuality); return datum; } From e9c3a0acdf2f7669138f1849643baa2ddf2d45ef Mon Sep 17 00:00:00 2001 From: Ryan Poplin Date: Mon, 28 Jan 2013 22:18:58 -0500 Subject: [PATCH 3/7] fix typo --- .../sting/gatk/arguments/GATKArgumentCollection.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/public/java/src/org/broadinstitute/sting/gatk/arguments/GATKArgumentCollection.java b/public/java/src/org/broadinstitute/sting/gatk/arguments/GATKArgumentCollection.java index 6520947d4..b4d6051d9 100644 --- a/public/java/src/org/broadinstitute/sting/gatk/arguments/GATKArgumentCollection.java +++ b/public/java/src/org/broadinstitute/sting/gatk/arguments/GATKArgumentCollection.java @@ -241,7 +241,7 @@ public class GATKArgumentCollection { @Argument(fullName = "preserve_qscores_less_than", shortName = "preserveQ", doc = "Bases with quality scores less than this threshold won't be recalibrated (with -BQSR)", required = false) public int PRESERVE_QSCORES_LESS_THAN = QualityUtils.MIN_USABLE_Q_SCORE; - @Argument(fullName = "qlobalQScorePrior", shortName = "qlobalQScorePrior", doc = "The global Qscore Bayesian prior to use in the BQSR. If specified, this value will be used as the prior for all mismatch quality scores instead of the actual reported quality score", required = false) + @Argument(fullName = "globalQScorePrior", shortName = "globalQScorePrior", doc = "The global Qscore Bayesian prior to use in the BQSR. If specified, this value will be used as the prior for all mismatch quality scores instead of the actual reported quality score", required = false) public double globalQScorePrior = -1.0; // -------------------------------------------------------------------------------------------------------------- From 35543b9cbab7ff489b2eb8fb3bdbf518f9e3cf0d Mon Sep 17 00:00:00 2001 From: Ryan Poplin Date: Tue, 29 Jan 2013 09:47:57 -0500 Subject: [PATCH 4/7] updating BQSR integration test values for the PR half of BQSR. --- .../sting/utils/recalibration/BaseRecalibration.java | 4 ---- .../sting/utils/recalibration/RecalDatum.java | 2 +- .../sting/utils/recalibration/RecalibrationReport.java | 2 +- .../sting/gatk/walkers/bqsr/BQSRIntegrationTest.java | 8 ++++---- 4 files changed, 6 insertions(+), 10 deletions(-) diff --git a/protected/java/src/org/broadinstitute/sting/utils/recalibration/BaseRecalibration.java b/protected/java/src/org/broadinstitute/sting/utils/recalibration/BaseRecalibration.java index ba18f5c96..1f4e92ad7 100644 --- a/protected/java/src/org/broadinstitute/sting/utils/recalibration/BaseRecalibration.java +++ b/protected/java/src/org/broadinstitute/sting/utils/recalibration/BaseRecalibration.java @@ -212,10 +212,6 @@ public class BaseRecalibration { final byte recalibratedQualityScore = quantizationInfo.getQuantizedQuals().get(recalibratedQual); quals[offset] = recalibratedQualityScore; - if( quals[offset] > QualityUtils.MAX_REASONABLE_Q_SCORE ) { - System.out.println("A"); - //calculateDeltaQCovariates(recalibrationTables, keySet, errorModel, globalDeltaQ, deltaQReported, origQual); - } } } diff --git a/protected/java/src/org/broadinstitute/sting/utils/recalibration/RecalDatum.java b/protected/java/src/org/broadinstitute/sting/utils/recalibration/RecalDatum.java index 67794c248..0b4441439 100644 --- a/protected/java/src/org/broadinstitute/sting/utils/recalibration/RecalDatum.java +++ b/protected/java/src/org/broadinstitute/sting/utils/recalibration/RecalDatum.java @@ -225,7 +225,7 @@ public class RecalDatum { return getEmpiricalQuality(getEstimatedQReported()); } - public final double getEmpiricalQuality(final double conditionalPrior) { + public synchronized final double getEmpiricalQuality(final double conditionalPrior) { if (empiricalQuality == UNINITIALIZED) { calcEmpiricalQuality(conditionalPrior); } diff --git a/protected/java/src/org/broadinstitute/sting/utils/recalibration/RecalibrationReport.java b/protected/java/src/org/broadinstitute/sting/utils/recalibration/RecalibrationReport.java index bf8f00ca4..e3ab16639 100644 --- a/protected/java/src/org/broadinstitute/sting/utils/recalibration/RecalibrationReport.java +++ b/protected/java/src/org/broadinstitute/sting/utils/recalibration/RecalibrationReport.java @@ -255,7 +255,7 @@ public class RecalibrationReport { final RecalDatum datum = new RecalDatum(nObservations, nErrors, (byte)1); datum.setEstimatedQReported(estimatedQReported); - //datum.setEmpiricalQuality(empiricalQuality); + //datum.setEmpiricalQuality(empiricalQuality); // don't set the value here because we will want to recompute with a different conditional Q score prior value return datum; } diff --git a/protected/java/test/org/broadinstitute/sting/gatk/walkers/bqsr/BQSRIntegrationTest.java b/protected/java/test/org/broadinstitute/sting/gatk/walkers/bqsr/BQSRIntegrationTest.java index b8a409d2f..254bfd92c 100644 --- a/protected/java/test/org/broadinstitute/sting/gatk/walkers/bqsr/BQSRIntegrationTest.java +++ b/protected/java/test/org/broadinstitute/sting/gatk/walkers/bqsr/BQSRIntegrationTest.java @@ -188,12 +188,12 @@ public class BQSRIntegrationTest extends WalkerTest { public Object[][] createPRTestData() { List tests = new ArrayList(); - tests.add(new Object[]{1, new PRTest(" -qq -1", "5226c06237b213b9e9b25a32ed92d09a")}); - tests.add(new Object[]{1, new PRTest(" -qq 6", "b592a5c62b952a012e18adb898ea9c33")}); - tests.add(new Object[]{1, new PRTest(" -DIQ", "8977bea0c57b808e65e9505eb648cdf7")}); + tests.add(new Object[]{1, new PRTest(" -qq -1", "64622d37e234e57cf472068a00b4ec89")}); + tests.add(new Object[]{1, new PRTest(" -qq 6", "735270581d1ee836f3f99d68ecbd5f24")}); + tests.add(new Object[]{1, new PRTest(" -DIQ", "1e3b0a11f246a238ac4c06b084142715")}); for ( final int nct : Arrays.asList(1, 2, 4) ) { - tests.add(new Object[]{nct, new PRTest("", "ab2f209ab98ad3432e208cbd524a4c4a")}); + tests.add(new Object[]{nct, new PRTest("", "39ecde2c2ba4a7c109e65372618a419a")}); } return tests.toArray(new Object[][]{}); From c11197e3617af59ba14bf6b3b729ebbc78ce65b1 Mon Sep 17 00:00:00 2001 From: Guillermo del Angel Date: Tue, 29 Jan 2013 10:10:24 -0500 Subject: [PATCH 5/7] Refactored repeat covariates to eliminate duplicated code - now all inherit from basic RepeatCovariate abstract class. Comprehensive unit tests coming... --- .../covariates/RepeatCovariate.java | 281 ++++++++++++++++++ .../covariates/RepeatLengthCovariate.java | 232 +-------------- .../RepeatUnitAndLengthCovariate.java | 221 +------------- .../covariates/RepeatUnitCovariate.java | 207 +------------ 4 files changed, 292 insertions(+), 649 deletions(-) create mode 100644 protected/java/src/org/broadinstitute/sting/utils/recalibration/covariates/RepeatCovariate.java diff --git a/protected/java/src/org/broadinstitute/sting/utils/recalibration/covariates/RepeatCovariate.java b/protected/java/src/org/broadinstitute/sting/utils/recalibration/covariates/RepeatCovariate.java new file mode 100644 index 000000000..d500a8ef9 --- /dev/null +++ b/protected/java/src/org/broadinstitute/sting/utils/recalibration/covariates/RepeatCovariate.java @@ -0,0 +1,281 @@ +/* +* 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.recalibration.covariates; + +import com.google.java.contract.Ensures; +import com.google.java.contract.Requires; +import org.broadinstitute.sting.gatk.walkers.bqsr.RecalibrationArgumentCollection; +import org.broadinstitute.sting.utils.recalibration.ReadCovariates; +import org.broadinstitute.sting.utils.sam.GATKSAMRecord; +import org.broadinstitute.variant.utils.BaseUtils; +import org.broadinstitute.variant.utils.Pair; +import org.broadinstitute.variant.variantcontext.VariantContextUtils; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +public abstract class RepeatCovariate implements ExperimentalCovariate { + final int MAX_REPEAT_LENGTH = 20; + final int MAX_STR_UNIT_LENGTH = 8; + private final HashMap repeatLookupTable = new HashMap(); + private final HashMap repeatReverseLookupTable = new HashMap(); + private int nextId = 0; + + // Initialize any member variables using the command-line arguments passed to the walkers + @Override + public void initialize(final RecalibrationArgumentCollection RAC) { + } + + @Override + public void recordValues(final GATKSAMRecord read, final ReadCovariates values) { + // store the original bases and then write Ns over low quality ones + final byte[] originalBases = read.getReadBases().clone(); + + final boolean negativeStrand = read.getReadNegativeStrandFlag(); + byte[] bases = read.getReadBases(); + if (negativeStrand) + bases = BaseUtils.simpleReverseComplement(bases); + + // don't record reads with N's + if (!BaseUtils.isAllRegularBases(bases)) + return; + + for (int i = 0; i < bases.length; i++) { + final Pair res = findTandemRepeatUnits(bases, i); + // to merge repeat unit and repeat length to get covariate value: + final String repeatID = getCovariateValueFromUnitAndLength(res.first, res.second); + final int key = keyForRepeat(repeatID); + + final int readOffset = (negativeStrand ? bases.length - i - 1 : i); + values.addCovariate(key, key, key, readOffset); + } + + // put the original bases back in + read.setReadBases(originalBases); + + } + + private Pair findTandemRepeatUnits(byte[] readBases, int offset) { + int maxBW = 0; + byte[] bestBWRepeatUnit = new byte[]{readBases[offset]}; + for (int str = 1; str <= MAX_STR_UNIT_LENGTH; str++) { + // fix repeat unit length + //edge case: if candidate tandem repeat unit falls beyond edge of read, skip + if (offset+1-str < 0) + break; + + // get backward repeat unit and # repeats + byte[] backwardRepeatUnit = Arrays.copyOfRange(readBases, offset - str + 1, offset + 1); + maxBW = VariantContextUtils.findNumberofRepetitions(backwardRepeatUnit, Arrays.copyOfRange(readBases, 0, offset + 1), false); + if (maxBW > 1) { + bestBWRepeatUnit = backwardRepeatUnit.clone(); + break; + } + } + byte[] bestRepeatUnit = bestBWRepeatUnit; + int maxRL = maxBW; + + if (offset < readBases.length-1) { + byte[] bestFWRepeatUnit = new byte[]{readBases[offset+1]}; + int maxFW = 0; + for (int str = 1; str <= MAX_STR_UNIT_LENGTH; str++) { + // fix repeat unit length + //edge case: if candidate tandem repeat unit falls beyond edge of read, skip + if (offset+str+1 > readBases.length) + break; + + // get forward repeat unit and # repeats + byte[] forwardRepeatUnit = Arrays.copyOfRange(readBases, offset +1, offset+str+1); + maxFW = VariantContextUtils.findNumberofRepetitions(forwardRepeatUnit,Arrays.copyOfRange(readBases, offset+1, readBases.length), true); + if (maxFW > 1) { + bestFWRepeatUnit = forwardRepeatUnit.clone(); + break; + } + } + // if FW repeat unit = BW repeat unit it means we're in the middle of a tandem repeat - add FW and BW components + if (Arrays.equals(bestFWRepeatUnit, bestBWRepeatUnit)) { + maxRL = maxBW + maxFW; + bestRepeatUnit = bestFWRepeatUnit; // arbitrary + } + else { + // tandem repeat starting forward from current offset + maxRL = maxFW; + bestRepeatUnit = bestFWRepeatUnit; + + } +/* if (maxFW > maxBW) { + // tandem repeat starting forward from current offset + maxRL = maxFW; + bestRepeatUnit = bestFWRepeatUnit; + } + else if (maxFW < maxBW) { + maxRL = maxBW; + bestRepeatUnit = bestBWRepeatUnit; + } */ + /* else { + // maxFW = maxBW but repeat units different: not in a tandem repeat. + maxRL = 1; + bestRepeatUnit = bestBWRepeatUnit; // arbitrary + } */ + + } + + + + if(maxRL > MAX_REPEAT_LENGTH) { maxRL = MAX_REPEAT_LENGTH; } + return new Pair(bestRepeatUnit, maxRL); + + } + @Override + public final Object getValue(final String str) { + return str; + } + + @Override + public synchronized String formatKey(final int key) { + // This method is synchronized so that we don't attempt to do a get() + // from the reverse lookup table while that table is being updated + return repeatReverseLookupTable.get(key); + } + + @Requires({"repeatLength>=0", "repeatFromUnitAndLength != null"}) + @Ensures("result != null") + protected abstract String getCovariateValueFromUnitAndLength(final byte[] repeatFromUnitAndLength, final int repeatLength); + + + @Override + public int keyFromValue(final Object value) { + return keyForRepeat((String) value); + } + + /** + * Get the mapping from read group names to integer key values for all read groups in this covariate + * @return a set of mappings from read group names -> integer key values + */ + public Set> getKeyMap() { + return repeatLookupTable.entrySet(); + } + + private int keyForRepeat(final String repeatID) { + // Rather than synchronize this entire method (which would be VERY expensive for walkers like the BQSR), + // synchronize only the table updates. + + // Before entering the synchronized block, check to see if this read group is not in our tables. + // If it's not, either we will have to insert it, OR another thread will insert it first. + // This preliminary check avoids doing any synchronization most of the time. + if ( ! repeatLookupTable.containsKey(repeatID) ) { + + synchronized ( this ) { + + // Now we need to make sure the key is STILL not there, since another thread may have come along + // and inserted it while we were waiting to enter this synchronized block! + if ( ! repeatLookupTable.containsKey(repeatID) ) { + repeatLookupTable.put(repeatID, nextId); + repeatReverseLookupTable.put(nextId, repeatID); + nextId++; + } + } + } + + return repeatLookupTable.get(repeatID); + } + + + /** + * Splits repeat unit and num repetitions from covariate value. + * For example, if value if "ATG4" it returns (ATG,4) + * @param value Covariate value + * @return Split pair + */ + @Requires("value != null") + @Ensures({"result.first != null","result.second>=0"}) + public static Pair getRUandNRfromCovariate(final String value) { + + int k = 0; + for ( k=0; k < value.length(); k++ ) { + if (!BaseUtils.isRegularBase(value.getBytes()[k])) + break; + } + Integer nr = Integer.valueOf(value.substring(k,value.length())); // will throw NumberFormatException if format illegal + if (k == value.length() || nr <= 0) + throw new IllegalStateException("Covariate is not of form (Repeat Unit) + Integer"); + + return new Pair(value.substring(0,k), nr); + } + + /** + * Gets bases from tandem repeat representation (Repeat Unit),(Number of Repeats). + * For example, (AGC),3 returns AGCAGCAGC + * @param repeatUnit Tandem repeat unit + * @param numRepeats Number of repeats + * @return Expanded String + */ + @Requires({"numRepeats > 0","repeatUnit != null"}) + @Ensures("result != null") + public static String getBasesFromRUandNR(final String repeatUnit, final int numRepeats) { + final StringBuilder sb = new StringBuilder(); + + for (int i=0; i < numRepeats; i++) + sb.append(repeatUnit); + + return sb.toString(); + } + + // version given covariate key + public static String getBasesFromRUandNR(final String covariateValue) { + Pair pair = getRUandNRfromCovariate(covariateValue); + return getBasesFromRUandNR(pair.getFirst(), pair.getSecond()); + } + + @Override + public abstract int maximumKeyValue(); + + + +} diff --git a/protected/java/src/org/broadinstitute/sting/utils/recalibration/covariates/RepeatLengthCovariate.java b/protected/java/src/org/broadinstitute/sting/utils/recalibration/covariates/RepeatLengthCovariate.java index b6266a543..48f3d4b60 100644 --- a/protected/java/src/org/broadinstitute/sting/utils/recalibration/covariates/RepeatLengthCovariate.java +++ b/protected/java/src/org/broadinstitute/sting/utils/recalibration/covariates/RepeatLengthCovariate.java @@ -48,234 +48,13 @@ package org.broadinstitute.sting.utils.recalibration.covariates; import com.google.java.contract.Ensures; import com.google.java.contract.Requires; -import org.broadinstitute.sting.gatk.walkers.bqsr.RecalibrationArgumentCollection; -import org.broadinstitute.sting.utils.recalibration.ReadCovariates; -import org.broadinstitute.sting.utils.sam.GATKSAMRecord; -import org.broadinstitute.variant.utils.BaseUtils; -import org.broadinstitute.variant.utils.Pair; -import org.broadinstitute.variant.variantcontext.VariantContextUtils; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -public class RepeatLengthCovariate implements ExperimentalCovariate { - final int MAX_REPEAT_LENGTH = 20; - final int MAX_STR_UNIT_LENGTH = 1; // =1 will restrict effectively to detecting homopolymer runs - public final boolean RECORD_REPUNIT_WITH_REPLENGTH = false; - private final HashMap repeatLookupTable = new HashMap(); - private final HashMap repeatReverseLookupTable = new HashMap(); - private int nextId = 0; - - // Initialize any member variables using the command-line arguments passed to the walkers - @Override - public void initialize(final RecalibrationArgumentCollection RAC) { - } - - @Override - public void recordValues(final GATKSAMRecord read, final ReadCovariates values) { - // store the original bases and then write Ns over low quality ones - final byte[] originalBases = read.getReadBases().clone(); - - final boolean negativeStrand = read.getReadNegativeStrandFlag(); - byte[] bases = read.getReadBases(); - if (negativeStrand) - bases = BaseUtils.simpleReverseComplement(bases); - - // don't record reads with N's - if (!BaseUtils.isAllRegularBases(bases)) - return; - - for (int i = 0; i < bases.length; i++) { - final Pair res = findTandemRepeatUnits(bases, i); - // merge repeat unit and repeat length to get covariate value - final String repeatID = repeatFromUnitAndLength(res.first, res.second); - final int key = keyForRepeat(repeatID); - - final int readOffset = (negativeStrand ? bases.length - i - 1 : i); - values.addCovariate(key, key, key, readOffset); - } - - // put the original bases back in - read.setReadBases(originalBases); - - } - - private Pair findTandemRepeatUnits(byte[] readBases, int offset) { - int maxBW = 0; - byte[] bestBWRepeatUnit = new byte[]{readBases[offset]}; - for (int str = 1; str <= MAX_STR_UNIT_LENGTH; str++) { - // fix repeat unit length - //edge case: if candidate tandem repeat unit falls beyond edge of read, skip - if (offset+1-str < 0) - break; - - // get backward repeat unit and # repeats - byte[] backwardRepeatUnit = Arrays.copyOfRange(readBases, offset - str+1, offset+1); - maxBW = VariantContextUtils.findNumberofRepetitions(backwardRepeatUnit,Arrays.copyOfRange(readBases, 0, offset+1), false); - if (maxBW > 1) { - bestBWRepeatUnit = backwardRepeatUnit.clone(); - break; - } - } - byte[] bestRepeatUnit = bestBWRepeatUnit; - int maxRL = maxBW; - - if (offset < readBases.length-1) { - byte[] bestFWRepeatUnit = new byte[]{readBases[offset+1]}; - int maxFW = 0; - for (int str = 1; str <= MAX_STR_UNIT_LENGTH; str++) { - // fix repeat unit length - //edge case: if candidate tandem repeat unit falls beyond edge of read, skip - if (offset+str+1 > readBases.length) - break; - - // get forward repeat unit and # repeats - byte[] forwardRepeatUnit = Arrays.copyOfRange(readBases, offset +1, offset+str+1); - maxFW = VariantContextUtils.findNumberofRepetitions(forwardRepeatUnit,Arrays.copyOfRange(readBases, offset+1, readBases.length), true); - if (maxFW > 1) { - bestFWRepeatUnit = forwardRepeatUnit.clone(); - break; - } - } - // if FW repeat unit = BW repeat unit it means we're in the middle of a tandem repeat - add FW and BW components - if (Arrays.equals(bestFWRepeatUnit, bestBWRepeatUnit)) { - maxRL = maxBW + maxFW; - bestRepeatUnit = bestFWRepeatUnit; // arbitrary - } - else { - // tandem repeat starting forward from current offset - maxRL = maxFW; - bestRepeatUnit = bestFWRepeatUnit; - - } -/* if (maxFW > maxBW) { - // tandem repeat starting forward from current offset - maxRL = maxFW; - bestRepeatUnit = bestFWRepeatUnit; - } - else if (maxFW < maxBW) { - maxRL = maxBW; - bestRepeatUnit = bestBWRepeatUnit; - } */ - /* else { - // maxFW = maxBW but repeat units different: not in a tandem repeat. - maxRL = 1; - bestRepeatUnit = bestBWRepeatUnit; // arbitrary - } */ - - } - - - - if(maxRL > MAX_REPEAT_LENGTH) { maxRL = MAX_REPEAT_LENGTH; } - return new Pair(bestRepeatUnit, maxRL); - - } - @Override - public final Object getValue(final String str) { - return str; - } - - @Override - public synchronized String formatKey(final int key) { - // This method is synchronized so that we don't attempt to do a get() - // from the reverse lookup table while that table is being updated - return repeatReverseLookupTable.get(key); - } - - @Override - public int keyFromValue(final Object value) { - return keyForRepeat((String) value); - } - - /** - * Get the mapping from read group names to integer key values for all read groups in this covariate - * @return a set of mappings from read group names -> integer key values - */ - public Set> getKeyMap() { - return repeatLookupTable.entrySet(); - } +public class RepeatLengthCovariate extends RepeatCovariate { @Requires({"repeatLength>=0", "repeatFromUnitAndLength != null"}) @Ensures("result != null") - private String repeatFromUnitAndLength(final byte[] repeatFromUnitAndLength, final int repeatLength) { - if (RECORD_REPUNIT_WITH_REPLENGTH) - return new String(repeatFromUnitAndLength) + String.format("%d",repeatLength); - else - return String.format("%d",repeatLength); - } - - private int keyForRepeat(final String repeatID) { - // Rather than synchronize this entire method (which would be VERY expensive for walkers like the BQSR), - // synchronize only the table updates. - - // Before entering the synchronized block, check to see if this read group is not in our tables. - // If it's not, either we will have to insert it, OR another thread will insert it first. - // This preliminary check avoids doing any synchronization most of the time. - if ( ! repeatLookupTable.containsKey(repeatID) ) { - - synchronized ( this ) { - - // Now we need to make sure the key is STILL not there, since another thread may have come along - // and inserted it while we were waiting to enter this synchronized block! - if ( ! repeatLookupTable.containsKey(repeatID) ) { - repeatLookupTable.put(repeatID, nextId); - repeatReverseLookupTable.put(nextId, repeatID); - nextId++; - } - } - } - - return repeatLookupTable.get(repeatID); - } - - - /** - * Splits repeat unit and num repetitions from covariate value. - * For example, if value if "ATG4" it returns (ATG,4) - * @param value Covariate value - * @return Split pair - */ - @Requires("value != null") - @Ensures({"result.first != null","result.second>=0"}) - public static Pair getRUandNRfromCovariate(final String value) { - - int k = 0; - for ( k=0; k < value.length(); k++ ) { - if (!BaseUtils.isRegularBase(value.getBytes()[k])) - break; - } - Integer nr = Integer.valueOf(value.substring(k,value.length())); // will throw NumberFormatException if format illegal - if (k == value.length() || nr <= 0) - throw new IllegalStateException("Covariate is not of form (Repeat Unit) + Integer"); - - return new Pair(value.substring(0,k), nr); - } - - /** - * Gets bases from tandem repeat representation (Repeat Unit),(Number of Repeats). - * For example, (AGC),3 returns AGCAGCAGC - * @param repeatUnit Tandem repeat unit - * @param numRepeats Number of repeats - * @return Expanded String - */ - @Requires({"numRepeats > 0","repeatUnit != null"}) - @Ensures("result != null") - public static String getBasesFromRUandNR(final String repeatUnit, final int numRepeats) { - final StringBuilder sb = new StringBuilder(); - - for (int i=0; i < numRepeats; i++) - sb.append(repeatUnit); - - return sb.toString(); - } - - // version given covariate key - public static String getBasesFromRUandNR(final String covariateValue) { - Pair pair = getRUandNRfromCovariate(covariateValue); - return getBasesFromRUandNR(pair.getFirst(), pair.getSecond()); + protected String getCovariateValueFromUnitAndLength(final byte[] repeatFromUnitAndLength, final int repeatLength) { + return String.format("%d",repeatLength); } @Override @@ -284,10 +63,7 @@ public class RepeatLengthCovariate implements ExperimentalCovariate { //return repeatLookupTable.size() - 1; // max possible values of covariate: for repeat unit, length is up to MAX_STR_UNIT_LENGTH, // so we have 4^MAX_STR_UNIT_LENGTH * MAX_REPEAT_LENGTH possible values - if (RECORD_REPUNIT_WITH_REPLENGTH) - return (1<<(2*MAX_STR_UNIT_LENGTH)) * MAX_REPEAT_LENGTH +1; - else - return (1+MAX_REPEAT_LENGTH); + return (1+MAX_REPEAT_LENGTH); } } diff --git a/protected/java/src/org/broadinstitute/sting/utils/recalibration/covariates/RepeatUnitAndLengthCovariate.java b/protected/java/src/org/broadinstitute/sting/utils/recalibration/covariates/RepeatUnitAndLengthCovariate.java index 36c5d57d3..5822b9e05 100644 --- a/protected/java/src/org/broadinstitute/sting/utils/recalibration/covariates/RepeatUnitAndLengthCovariate.java +++ b/protected/java/src/org/broadinstitute/sting/utils/recalibration/covariates/RepeatUnitAndLengthCovariate.java @@ -62,222 +62,12 @@ import java.util.Map; import java.util.Set; -public class RepeatUnitAndLengthCovariate implements ExperimentalCovariate { - final int MAX_REPEAT_LENGTH = 20; - final int MAX_STR_UNIT_LENGTH = 8; - public final boolean RECORD_REPUNIT_WITH_REPLENGTH = true; - private final HashMap repeatLookupTable = new HashMap(); - private final HashMap repeatReverseLookupTable = new HashMap(); - private int nextId = 0; - - // Initialize any member variables using the command-line arguments passed to the walkers - @Override - public void initialize(final RecalibrationArgumentCollection RAC) { - } - - @Override - public void recordValues(final GATKSAMRecord read, final ReadCovariates values) { - // store the original bases and then write Ns over low quality ones - final byte[] originalBases = read.getReadBases().clone(); - - final boolean negativeStrand = read.getReadNegativeStrandFlag(); - byte[] bases = read.getReadBases(); - if (negativeStrand) - bases = BaseUtils.simpleReverseComplement(bases); - - // don't record reads with N's - if (!BaseUtils.isAllRegularBases(bases)) - return; - - for (int i = 0; i < bases.length; i++) { - final Pair res = findTandemRepeatUnits(bases, i); - // merge repeat unit and repeat length to get covariate value - final String repeatID = repeatFromUnitAndLength(res.first, res.second); - final int key = keyForRepeat(repeatID); - - final int readOffset = (negativeStrand ? bases.length - i - 1 : i); - values.addCovariate(key, key, key, readOffset); - } - - // put the original bases back in - read.setReadBases(originalBases); - - } - - private Pair findTandemRepeatUnits(byte[] readBases, int offset) { - int maxBW = 0; - byte[] bestBWRepeatUnit = new byte[]{readBases[offset]}; - for (int str = 1; str <= MAX_STR_UNIT_LENGTH; str++) { - // fix repeat unit length - //edge case: if candidate tandem repeat unit falls beyond edge of read, skip - if (offset+1-str < 0) - break; - - // get backward repeat unit and # repeats - byte[] backwardRepeatUnit = Arrays.copyOfRange(readBases, offset - str+1, offset+1); - maxBW = VariantContextUtils.findNumberofRepetitions(backwardRepeatUnit,Arrays.copyOfRange(readBases, 0, offset+1), false); - if (maxBW > 1) { - bestBWRepeatUnit = backwardRepeatUnit.clone(); - break; - } - } - byte[] bestRepeatUnit = bestBWRepeatUnit; - int maxRL = maxBW; - - if (offset < readBases.length-1) { - byte[] bestFWRepeatUnit = new byte[]{readBases[offset+1]}; - int maxFW = 0; - for (int str = 1; str <= MAX_STR_UNIT_LENGTH; str++) { - // fix repeat unit length - //edge case: if candidate tandem repeat unit falls beyond edge of read, skip - if (offset+str+1 > readBases.length) - break; - - // get forward repeat unit and # repeats - byte[] forwardRepeatUnit = Arrays.copyOfRange(readBases, offset +1, offset+str+1); - maxFW = VariantContextUtils.findNumberofRepetitions(forwardRepeatUnit,Arrays.copyOfRange(readBases, offset+1, readBases.length), true); - if (maxFW > 1) { - bestFWRepeatUnit = forwardRepeatUnit.clone(); - break; - } - } - // if FW repeat unit = BW repeat unit it means we're in the middle of a tandem repeat - add FW and BW components - if (Arrays.equals(bestFWRepeatUnit, bestBWRepeatUnit)) { - maxRL = maxBW + maxFW; - bestRepeatUnit = bestFWRepeatUnit; // arbitrary - } - else { - // tandem repeat starting forward from current offset - maxRL = maxFW; - bestRepeatUnit = bestFWRepeatUnit; - - } -/* if (maxFW > maxBW) { - // tandem repeat starting forward from current offset - maxRL = maxFW; - bestRepeatUnit = bestFWRepeatUnit; - } - else if (maxFW < maxBW) { - maxRL = maxBW; - bestRepeatUnit = bestBWRepeatUnit; - } */ - /* else { - // maxFW = maxBW but repeat units different: not in a tandem repeat. - maxRL = 1; - bestRepeatUnit = bestBWRepeatUnit; // arbitrary - } */ - - } - - - - if(maxRL > MAX_REPEAT_LENGTH) { maxRL = MAX_REPEAT_LENGTH; } - return new Pair(bestRepeatUnit, maxRL); - - } - @Override - public final Object getValue(final String str) { - return str; - } - - @Override - public synchronized String formatKey(final int key) { - // This method is synchronized so that we don't attempt to do a get() - // from the reverse lookup table while that table is being updated - return repeatReverseLookupTable.get(key); - } - - @Override - public int keyFromValue(final Object value) { - return keyForRepeat((String) value); - } - - /** - * Get the mapping from read group names to integer key values for all read groups in this covariate - * @return a set of mappings from read group names -> integer key values - */ - public Set> getKeyMap() { - return repeatLookupTable.entrySet(); - } +public class RepeatUnitAndLengthCovariate extends RepeatCovariate { @Requires({"repeatLength>=0", "repeatFromUnitAndLength != null"}) @Ensures("result != null") - private String repeatFromUnitAndLength(final byte[] repeatFromUnitAndLength, final int repeatLength) { - if (RECORD_REPUNIT_WITH_REPLENGTH) - return new String(repeatFromUnitAndLength) + String.format("%d",repeatLength); - else - return String.format("%d",repeatLength); - } - - private int keyForRepeat(final String repeatID) { - // Rather than synchronize this entire method (which would be VERY expensive for walkers like the BQSR), - // synchronize only the table updates. - - // Before entering the synchronized block, check to see if this read group is not in our tables. - // If it's not, either we will have to insert it, OR another thread will insert it first. - // This preliminary check avoids doing any synchronization most of the time. - if ( ! repeatLookupTable.containsKey(repeatID) ) { - - synchronized ( this ) { - - // Now we need to make sure the key is STILL not there, since another thread may have come along - // and inserted it while we were waiting to enter this synchronized block! - if ( ! repeatLookupTable.containsKey(repeatID) ) { - repeatLookupTable.put(repeatID, nextId); - repeatReverseLookupTable.put(nextId, repeatID); - nextId++; - } - } - } - - return repeatLookupTable.get(repeatID); - } - - - /** - * Splits repeat unit and num repetitions from covariate value. - * For example, if value if "ATG4" it returns (ATG,4) - * @param value Covariate value - * @return Split pair - */ - @Requires("value != null") - @Ensures({"result.first != null","result.second>=0"}) - public static Pair getRUandNRfromCovariate(final String value) { - - int k = 0; - for ( k=0; k < value.length(); k++ ) { - if (!BaseUtils.isRegularBase(value.getBytes()[k])) - break; - } - Integer nr = Integer.valueOf(value.substring(k,value.length())); // will throw NumberFormatException if format illegal - if (k == value.length() || nr <= 0) - throw new IllegalStateException("Covariate is not of form (Repeat Unit) + Integer"); - - return new Pair(value.substring(0,k), nr); - } - - /** - * Gets bases from tandem repeat representation (Repeat Unit),(Number of Repeats). - * For example, (AGC),3 returns AGCAGCAGC - * @param repeatUnit Tandem repeat unit - * @param numRepeats Number of repeats - * @return Expanded String - */ - @Requires({"numRepeats > 0","repeatUnit != null"}) - @Ensures("result != null") - public static String getBasesFromRUandNR(final String repeatUnit, final int numRepeats) { - final StringBuilder sb = new StringBuilder(); - - for (int i=0; i < numRepeats; i++) - sb.append(repeatUnit); - - return sb.toString(); - } - - // version given covariate key - public static String getBasesFromRUandNR(final String covariateValue) { - Pair pair = getRUandNRfromCovariate(covariateValue); - return getBasesFromRUandNR(pair.getFirst(), pair.getSecond()); + protected String getCovariateValueFromUnitAndLength(final byte[] repeatFromUnitAndLength, final int repeatLength) { + return new String(repeatFromUnitAndLength) + String.format("%d",repeatLength); } @Override @@ -286,10 +76,7 @@ public class RepeatUnitAndLengthCovariate implements ExperimentalCovariate { //return repeatLookupTable.size() - 1; // max possible values of covariate: for repeat unit, length is up to MAX_STR_UNIT_LENGTH, // so we have 4^MAX_STR_UNIT_LENGTH * MAX_REPEAT_LENGTH possible values - if (RECORD_REPUNIT_WITH_REPLENGTH) - return (1<<(2*MAX_STR_UNIT_LENGTH)) * MAX_REPEAT_LENGTH +1; - else - return (1+MAX_REPEAT_LENGTH); + return (1<<(2*MAX_STR_UNIT_LENGTH)) * MAX_REPEAT_LENGTH +1; } } diff --git a/protected/java/src/org/broadinstitute/sting/utils/recalibration/covariates/RepeatUnitCovariate.java b/protected/java/src/org/broadinstitute/sting/utils/recalibration/covariates/RepeatUnitCovariate.java index 9e98e741e..ed843310d 100644 --- a/protected/java/src/org/broadinstitute/sting/utils/recalibration/covariates/RepeatUnitCovariate.java +++ b/protected/java/src/org/broadinstitute/sting/utils/recalibration/covariates/RepeatUnitCovariate.java @@ -66,214 +66,13 @@ import java.util.Set; * Date: 11/3/12 */ -public class RepeatUnitCovariate implements ExperimentalCovariate { - final int MAX_REPEAT_LENGTH = 20; - final int MAX_STR_UNIT_LENGTH = 8; - private final HashMap repeatLookupTable = new HashMap(); - private final HashMap repeatReverseLookupTable = new HashMap(); - private int nextId = 0; +public class RepeatUnitCovariate extends RepeatCovariate { - // Initialize any member variables using the command-line arguments passed to the walkers - @Override - public void initialize(final RecalibrationArgumentCollection RAC) { - } - - @Override - public void recordValues(final GATKSAMRecord read, final ReadCovariates values) { - // store the original bases and then write Ns over low quality ones - final byte[] originalBases = read.getReadBases().clone(); - - final boolean negativeStrand = read.getReadNegativeStrandFlag(); - byte[] bases = read.getReadBases(); - if (negativeStrand) - bases = BaseUtils.simpleReverseComplement(bases); - - // don't record reads with N's - if (!BaseUtils.isAllRegularBases(bases)) - return; - - for (int i = 0; i < bases.length; i++) { - final Pair res = findTandemRepeatUnits(bases, i); - // to merge repeat unit and repeat length to get covariate value: - //final String repeatID = repeatFromUnitAndLength(res.first, res.second); - final String repeatID = new String(res.first); - final int key = keyForRepeat(repeatID); - - final int readOffset = (negativeStrand ? bases.length - i - 1 : i); - values.addCovariate(key, key, key, readOffset); - } - - // put the original bases back in - read.setReadBases(originalBases); + protected String getCovariateValueFromUnitAndLength(final byte[] repeatFromUnitAndLength, final int repeatLength) { + return new String(repeatFromUnitAndLength); } - private Pair findTandemRepeatUnits(byte[] readBases, int offset) { - int maxBW = 0; - byte[] bestBWRepeatUnit = new byte[]{readBases[offset]}; - for (int str = 1; str <= MAX_STR_UNIT_LENGTH; str++) { - // fix repeat unit length - //edge case: if candidate tandem repeat unit falls beyond edge of read, skip - if (offset+1-str < 0) - break; - - // get backward repeat unit and # repeats - byte[] backwardRepeatUnit = Arrays.copyOfRange(readBases, offset - str+1, offset+1); - maxBW = VariantContextUtils.findNumberofRepetitions(backwardRepeatUnit,Arrays.copyOfRange(readBases, 0, offset+1), false); - if (maxBW > 1) { - bestBWRepeatUnit = backwardRepeatUnit.clone(); - break; - } - } - byte[] bestRepeatUnit = bestBWRepeatUnit; - int maxRL = maxBW; - - if (offset < readBases.length-1) { - byte[] bestFWRepeatUnit = new byte[]{readBases[offset+1]}; - int maxFW = 0; - for (int str = 1; str <= MAX_STR_UNIT_LENGTH; str++) { - // fix repeat unit length - //edge case: if candidate tandem repeat unit falls beyond edge of read, skip - if (offset+str+1 > readBases.length) - break; - - // get forward repeat unit and # repeats - byte[] forwardRepeatUnit = Arrays.copyOfRange(readBases, offset +1, offset+str+1); - maxFW = VariantContextUtils.findNumberofRepetitions(forwardRepeatUnit,Arrays.copyOfRange(readBases, offset+1, readBases.length), true); - if (maxFW > 1) { - bestFWRepeatUnit = forwardRepeatUnit.clone(); - break; - } - } - // if FW repeat unit = BW repeat unit it means we're in the middle of a tandem repeat - add FW and BW components - if (Arrays.equals(bestFWRepeatUnit, bestBWRepeatUnit)) { - maxRL = maxBW + maxFW; - bestRepeatUnit = bestFWRepeatUnit; // arbitrary - } - else { - // tandem repeat starting forward from current offset - maxRL = maxFW; - bestRepeatUnit = bestFWRepeatUnit; - - } -/* if (maxFW > maxBW) { - // tandem repeat starting forward from current offset - maxRL = maxFW; - bestRepeatUnit = bestFWRepeatUnit; - } - else if (maxFW < maxBW) { - maxRL = maxBW; - bestRepeatUnit = bestBWRepeatUnit; - } */ - /* else { - // maxFW = maxBW but repeat units different: not in a tandem repeat. - maxRL = 1; - bestRepeatUnit = bestBWRepeatUnit; // arbitrary - } */ - - } - - - - if(maxRL > MAX_REPEAT_LENGTH) { maxRL = MAX_REPEAT_LENGTH; } - return new Pair(bestRepeatUnit, maxRL); - - } - @Override - public final Object getValue(final String str) { - return str; - } - - @Override - public synchronized String formatKey(final int key) { - // This method is synchronized so that we don't attempt to do a get() - // from the reverse lookup table while that table is being updated - return repeatReverseLookupTable.get(key); - } - - @Override - public int keyFromValue(final Object value) { - return keyForRepeat((String) value); - } - - /** - * Get the mapping from read group names to integer key values for all read groups in this covariate - * @return a set of mappings from read group names -> integer key values - */ - public Set> getKeyMap() { - return repeatLookupTable.entrySet(); - } - - private int keyForRepeat(final String repeatID) { - // Rather than synchronize this entire method (which would be VERY expensive for walkers like the BQSR), - // synchronize only the table updates. - - // Before entering the synchronized block, check to see if this read group is not in our tables. - // If it's not, either we will have to insert it, OR another thread will insert it first. - // This preliminary check avoids doing any synchronization most of the time. - if ( ! repeatLookupTable.containsKey(repeatID) ) { - - synchronized ( this ) { - - // Now we need to make sure the key is STILL not there, since another thread may have come along - // and inserted it while we were waiting to enter this synchronized block! - if ( ! repeatLookupTable.containsKey(repeatID) ) { - repeatLookupTable.put(repeatID, nextId); - repeatReverseLookupTable.put(nextId, repeatID); - nextId++; - } - } - } - - return repeatLookupTable.get(repeatID); - } - - - /** - * Splits repeat unit and num repetitions from covariate value. - * For example, if value if "ATG4" it returns (ATG,4) - * @param value Covariate value - * @return Split pair - */ - @Requires("value != null") - @Ensures({"result.first != null","result.second>=0"}) - public static Pair getRUandNRfromCovariate(final String value) { - - int k = 0; - for ( k=0; k < value.length(); k++ ) { - if (!BaseUtils.isRegularBase(value.getBytes()[k])) - break; - } - Integer nr = Integer.valueOf(value.substring(k,value.length())); // will throw NumberFormatException if format illegal - if (k == value.length() || nr <= 0) - throw new IllegalStateException("Covariate is not of form (Repeat Unit) + Integer"); - - return new Pair(value.substring(0,k), nr); - } - - /** - * Gets bases from tandem repeat representation (Repeat Unit),(Number of Repeats). - * For example, (AGC),3 returns AGCAGCAGC - * @param repeatUnit Tandem repeat unit - * @param numRepeats Number of repeats - * @return Expanded String - */ - @Requires({"numRepeats > 0","repeatUnit != null"}) - @Ensures("result != null") - public static String getBasesFromRUandNR(final String repeatUnit, final int numRepeats) { - final StringBuilder sb = new StringBuilder(); - - for (int i=0; i < numRepeats; i++) - sb.append(repeatUnit); - - return sb.toString(); - } - - // version given covariate key - public static String getBasesFromRUandNR(final String covariateValue) { - Pair pair = getRUandNRfromCovariate(covariateValue); - return getBasesFromRUandNR(pair.getFirst(), pair.getSecond()); - } @Override public synchronized int maximumKeyValue() { From 1d5b29e764662424993a62a1c86bd7aa78759704 Mon Sep 17 00:00:00 2001 From: Guillermo del Angel Date: Tue, 29 Jan 2013 15:23:02 -0500 Subject: [PATCH 6/7] Unit tests for repeat covariates: generate 100 random reads consisting of tandem repeat units of random content and size, and check that covariates match expected values at all positions in reads. Fixed corner case where value of covariate at border between 2 tandem repeats of different length/content wasn't consistent --- .../covariates/RepeatCovariate.java | 28 +++---- ...est.java => RepeatCovariatesUnitTest.java} | 77 +++++++++++++------ 2 files changed, 63 insertions(+), 42 deletions(-) rename protected/java/test/org/broadinstitute/sting/utils/recalibration/{RepeatLengthCovariateUnitTest.java => RepeatCovariatesUnitTest.java} (81%) diff --git a/protected/java/src/org/broadinstitute/sting/utils/recalibration/covariates/RepeatCovariate.java b/protected/java/src/org/broadinstitute/sting/utils/recalibration/covariates/RepeatCovariate.java index d500a8ef9..a836fbb5e 100644 --- a/protected/java/src/org/broadinstitute/sting/utils/recalibration/covariates/RepeatCovariate.java +++ b/protected/java/src/org/broadinstitute/sting/utils/recalibration/covariates/RepeatCovariate.java @@ -61,8 +61,8 @@ import java.util.Map; import java.util.Set; public abstract class RepeatCovariate implements ExperimentalCovariate { - final int MAX_REPEAT_LENGTH = 20; - final int MAX_STR_UNIT_LENGTH = 8; + public static final int MAX_REPEAT_LENGTH = 20; + public static final int MAX_STR_UNIT_LENGTH = 8; private final HashMap repeatLookupTable = new HashMap(); private final HashMap repeatReverseLookupTable = new HashMap(); private int nextId = 0; @@ -144,25 +144,17 @@ public abstract class RepeatCovariate implements ExperimentalCovariate { bestRepeatUnit = bestFWRepeatUnit; // arbitrary } else { - // tandem repeat starting forward from current offset - maxRL = maxFW; + // tandem repeat starting forward from current offset. + // It could be the case that best BW unit was differnet from FW unit, but that BW still contains FW unit. + // For example, TTCTT(C) CCC - at (C) place, best BW unit is (TTC)2, best FW unit is (C)3. + // but correct representation at that place might be (C)4. + // Hence, if the FW and BW units don't match, check if BW unit can still be a part of FW unit and add + // representations to total + maxBW = VariantContextUtils.findNumberofRepetitions(bestFWRepeatUnit, Arrays.copyOfRange(readBases, 0, offset + 1), false); + maxRL = maxFW + maxBW; bestRepeatUnit = bestFWRepeatUnit; } -/* if (maxFW > maxBW) { - // tandem repeat starting forward from current offset - maxRL = maxFW; - bestRepeatUnit = bestFWRepeatUnit; - } - else if (maxFW < maxBW) { - maxRL = maxBW; - bestRepeatUnit = bestBWRepeatUnit; - } */ - /* else { - // maxFW = maxBW but repeat units different: not in a tandem repeat. - maxRL = 1; - bestRepeatUnit = bestBWRepeatUnit; // arbitrary - } */ } diff --git a/protected/java/test/org/broadinstitute/sting/utils/recalibration/RepeatLengthCovariateUnitTest.java b/protected/java/test/org/broadinstitute/sting/utils/recalibration/RepeatCovariatesUnitTest.java similarity index 81% rename from protected/java/test/org/broadinstitute/sting/utils/recalibration/RepeatLengthCovariateUnitTest.java rename to protected/java/test/org/broadinstitute/sting/utils/recalibration/RepeatCovariatesUnitTest.java index d08276147..e4311a534 100644 --- a/protected/java/test/org/broadinstitute/sting/utils/recalibration/RepeatLengthCovariateUnitTest.java +++ b/protected/java/test/org/broadinstitute/sting/utils/recalibration/RepeatCovariatesUnitTest.java @@ -49,7 +49,7 @@ import com.google.java.contract.Requires; import net.sf.samtools.SAMFileHeader; import org.broadinstitute.sting.BaseTest; import org.broadinstitute.sting.gatk.walkers.bqsr.RecalibrationArgumentCollection; -import org.broadinstitute.sting.utils.recalibration.covariates.RepeatLengthCovariate; +import org.broadinstitute.sting.utils.recalibration.covariates.*; import org.broadinstitute.sting.utils.sam.ArtificialSAMUtils; import org.broadinstitute.sting.utils.sam.GATKSAMReadGroupRecord; import org.broadinstitute.sting.utils.sam.GATKSAMRecord; @@ -65,9 +65,11 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Random; -public class RepeatLengthCovariateUnitTest { +public class RepeatCovariatesUnitTest { - RepeatLengthCovariate covariate; + RepeatLengthCovariate rlCovariate; + RepeatUnitCovariate ruCovariate; + RepeatUnitAndLengthCovariate rurlCovariate; RecalibrationArgumentCollection RAC; @@ -75,8 +77,12 @@ public class RepeatLengthCovariateUnitTest { @BeforeClass public void init() { RAC = new RecalibrationArgumentCollection(); - covariate = new RepeatLengthCovariate(); - covariate.initialize(RAC); + rlCovariate = new RepeatLengthCovariate(); + ruCovariate = new RepeatUnitCovariate(); + rurlCovariate = new RepeatUnitAndLengthCovariate(); + rlCovariate.initialize(RAC); + ruCovariate.initialize(RAC); + rurlCovariate.initialize(RAC); } @@ -136,9 +142,9 @@ public class RepeatLengthCovariateUnitTest { @Test(enabled = true) public void testManyObservations() { final int NUM_UNITS = 10; - final int MAX_REPEAT_UNIT_LENGTH = 6; - final int MAX_NUM_REPETITIONS = 5; - final int NUM_TEST_CASES = 1; + final int MAX_REPEAT_UNIT_LENGTH = RepeatCovariate.MAX_STR_UNIT_LENGTH; + final int MAX_NUM_REPETITIONS = RepeatCovariate.MAX_REPEAT_LENGTH; + final int NUM_TEST_CASES = 100; Random random = new Random(); @@ -161,29 +167,52 @@ public class RepeatLengthCovariateUnitTest { } - // final String readBases = sb.toString(); - final String readBases = "TTTTTTTTAATGGGGGAGGGAGGGAGACTTACTTACTTACTTACTTATCGGAATCGGATATATAACGGCTTTCTTCTTCCCCCCA"; + final String readBases = sb.toString(); System.out.println(readBases); + final int readLength = readBases.length(); - final byte[] readQuals = new byte[readBases.length()]; + final byte[] readQuals = new byte[readLength]; Arrays.fill(readQuals,(byte)30); - final GATKSAMRecord read = ArtificialSAMUtils.createArtificialRead(readBases.getBytes(),readQuals,readBases.length()+"M"); + final GATKSAMRecord read = ArtificialSAMUtils.createArtificialRead(readBases.getBytes(),readQuals,readLength+"M"); + + Covariate[] requestedCovariates = new Covariate[3]; + requestedCovariates[0] = rlCovariate; + requestedCovariates[1] = ruCovariate; + requestedCovariates[2] = rurlCovariate; + ReadCovariates rc = RecalUtils.computeCovariates(read, requestedCovariates); + + // check that the length is correct + Assert.assertEquals(rc.getMismatchesKeySet().length, readLength); + Assert.assertEquals(rc.getInsertionsKeySet().length, readLength); + Assert.assertEquals(rc.getDeletionsKeySet().length, readLength); - final ReadCovariates values = new ReadCovariates(read.getReadLength(),1); - covariate.recordValues( read, values); - final int fullReadKeySet[][] = values.getKeySet(EventType.BASE_SUBSTITUTION); for (int offset = 0; offset < readBases.length(); offset++) { // recalibrate all bases in the read - final int[] keySet = fullReadKeySet[offset]; - final String val = covariate.formatKey(keySet[0]); - System.out.format("offset %d:%s\n", offset, val); -// final String repeatString = RepeatLengthCovariate.getBasesFromRUandNR(val); -// final String partialRead = readBases.substring(0,offset+1); - // Assert.assertTrue(partialRead.endsWith(repeatString)); - } - //values. - int k=0; + // check RepeatLength + final String rlValM = rlCovariate.formatKey(rc.getMismatchesKeySet(offset)[0]); + final String rlValI = rlCovariate.formatKey(rc.getInsertionsKeySet(offset)[0]); + final String rlValD = rlCovariate.formatKey(rc.getDeletionsKeySet(offset)[0]); + // check RepeatUnit + final String ruValM = ruCovariate.formatKey(rc.getMismatchesKeySet(offset)[1]); + final String ruValI = ruCovariate.formatKey(rc.getInsertionsKeySet(offset)[1]); + final String ruValD = ruCovariate.formatKey(rc.getDeletionsKeySet(offset)[1]); + // check RepeatUnitAndLength + final String rurlValM = rurlCovariate.formatKey(rc.getMismatchesKeySet(offset)[2]); + final String rurlValI = rurlCovariate.formatKey(rc.getInsertionsKeySet(offset)[2]); + final String rurlValD = rurlCovariate.formatKey(rc.getDeletionsKeySet(offset)[2]); + // check all 3 values are identical + Assert.assertEquals(rlValD,rlValI); + Assert.assertEquals(rlValM,rlValI); + Assert.assertEquals(ruValD,ruValI); + Assert.assertEquals(ruValM,ruValI); + Assert.assertEquals(rurlValD,rurlValI); + Assert.assertEquals(rurlValM,rurlValI); + int fw = VariantContextUtils.findNumberofRepetitions(ruValM.getBytes(), readBases.substring(offset+1,readLength).getBytes(),true); + int bw = VariantContextUtils.findNumberofRepetitions(ruValM.getBytes(), readBases.substring(0,offset+1).getBytes(),false); + Assert.assertEquals(Math.min(fw+bw,RepeatCovariate.MAX_REPEAT_LENGTH),(int)Integer.valueOf(rlValM)); + } + } From e4ec899a879503f2e56d836d5b8cbe1b18ffc370 Mon Sep 17 00:00:00 2001 From: Eric Banks Date: Tue, 29 Jan 2013 15:51:07 -0500 Subject: [PATCH 7/7] First pass at adding unit tests for the RR framework: I have added 3 tests and all 3 uncovered RR bugs! One of the fixes was critical: SlidingWindow was not converting between global and relative positions correctly. Besides not being correct, it was resulting in a massive slow down of the RR traversal. That fix definitely breaks at least one of the integration tests, but it's not worth changing md5s now because I'll be changing things all over RR for the next few days, so I am going to let that test fail indefinitely until I can confirm general correctness of the tool. --- .../reducereads/HeaderElement.java | 8 +- .../reducereads/SimpleGenomeLoc.java | 31 ++- .../reducereads/SlidingWindow.java | 42 +++- .../reducereads/HeaderElementUnitTest.java | 134 +++++++++++ .../reducereads/SimpleGenomeLocUnitTest.java | 106 ++++++++ .../reducereads/SlidingWindowUnitTest.java | 227 ++++++++++++++++++ 6 files changed, 521 insertions(+), 27 deletions(-) create mode 100644 protected/java/test/org/broadinstitute/sting/gatk/walkers/compression/reducereads/HeaderElementUnitTest.java create mode 100644 protected/java/test/org/broadinstitute/sting/gatk/walkers/compression/reducereads/SimpleGenomeLocUnitTest.java create mode 100644 protected/java/test/org/broadinstitute/sting/gatk/walkers/compression/reducereads/SlidingWindowUnitTest.java diff --git a/protected/java/src/org/broadinstitute/sting/gatk/walkers/compression/reducereads/HeaderElement.java b/protected/java/src/org/broadinstitute/sting/gatk/walkers/compression/reducereads/HeaderElement.java index 1e7805fce..13d3d1b4c 100644 --- a/protected/java/src/org/broadinstitute/sting/gatk/walkers/compression/reducereads/HeaderElement.java +++ b/protected/java/src/org/broadinstitute/sting/gatk/walkers/compression/reducereads/HeaderElement.java @@ -244,7 +244,7 @@ public class HeaderElement { * * @return whether or not the HeaderElement is variant due to excess insertions */ - private boolean isVariantFromMismatches(double minVariantProportion) { + protected boolean isVariantFromMismatches(double minVariantProportion) { BaseIndex mostCommon = consensusBaseCounts.baseIndexWithMostProbabilityWithoutIndels(); double mostCommonProportion = consensusBaseCounts.baseCountProportionWithoutIndels(mostCommon); return mostCommonProportion != 0.0 && mostCommonProportion < (1 - minVariantProportion); @@ -256,11 +256,11 @@ public class HeaderElement { * * @return true if we had more soft clipped bases contributing to this site than matches/mismatches. */ - private boolean isVariantFromSoftClips() { - return nSoftClippedBases >= (consensusBaseCounts.totalCount() - nSoftClippedBases); + protected boolean isVariantFromSoftClips() { + return nSoftClippedBases > 0 && nSoftClippedBases >= (consensusBaseCounts.totalCount() - nSoftClippedBases); } - private boolean basePassesFilters(byte baseQual, int minBaseQual, int baseMappingQuality, int minMappingQual) { + protected boolean basePassesFilters(byte baseQual, int minBaseQual, int baseMappingQuality, int minMappingQual) { return baseQual >= minBaseQual && baseMappingQuality >= minMappingQual; } diff --git a/protected/java/src/org/broadinstitute/sting/gatk/walkers/compression/reducereads/SimpleGenomeLoc.java b/protected/java/src/org/broadinstitute/sting/gatk/walkers/compression/reducereads/SimpleGenomeLoc.java index a3ebb132f..85a1f8df1 100644 --- a/protected/java/src/org/broadinstitute/sting/gatk/walkers/compression/reducereads/SimpleGenomeLoc.java +++ b/protected/java/src/org/broadinstitute/sting/gatk/walkers/compression/reducereads/SimpleGenomeLoc.java @@ -78,6 +78,13 @@ public class SimpleGenomeLoc extends GenomeLoc { return finished; } + /** + * Merges 2 *contiguous* locs into 1 + * + * @param a SimpleGenomeLoc #1 + * @param b SimpleGenomeLoc #2 + * @return one merged loc + */ @Requires("a != null && b != null") public static SimpleGenomeLoc merge(SimpleGenomeLoc a, SimpleGenomeLoc b) throws ReviewedStingException { if(GenomeLoc.isUnmapped(a) || GenomeLoc.isUnmapped(b)) { @@ -88,7 +95,6 @@ public class SimpleGenomeLoc extends GenomeLoc { throw new ReviewedStingException("The two genome locs need to be contiguous"); } - return new SimpleGenomeLoc(a.getContig(), a.contigIndex, Math.min(a.getStart(), b.getStart()), Math.max(a.getStop(), b.getStop()), @@ -101,19 +107,22 @@ public class SimpleGenomeLoc extends GenomeLoc { * @param sortedLocs a sorted list of contiguous locs * @return one merged loc */ + @Requires("sortedLocs != null") public static SimpleGenomeLoc merge(SortedSet sortedLocs) { - SimpleGenomeLoc previousLoc = null; - for (SimpleGenomeLoc loc : sortedLocs) { - if (loc.isUnmapped()) { + SimpleGenomeLoc result = null; + + for ( SimpleGenomeLoc loc : sortedLocs ) { + if ( loc.isUnmapped() ) throw new ReviewedStingException("Tried to merge unmapped genome locs"); - } - if (previousLoc != null && !previousLoc.contiguousP(loc)) { + + if ( result == null ) + result = loc; + else if ( !result.contiguousP(loc) ) throw new ReviewedStingException("The genome locs need to be contiguous"); - } - previousLoc = loc; + else + result = merge(result, loc); } - SimpleGenomeLoc firstLoc = sortedLocs.first(); - SimpleGenomeLoc lastLoc = sortedLocs.last(); - return merge(firstLoc, lastLoc); + + return result; } } diff --git a/protected/java/src/org/broadinstitute/sting/gatk/walkers/compression/reducereads/SlidingWindow.java b/protected/java/src/org/broadinstitute/sting/gatk/walkers/compression/reducereads/SlidingWindow.java index e91120f1c..57a11f640 100644 --- a/protected/java/src/org/broadinstitute/sting/gatk/walkers/compression/reducereads/SlidingWindow.java +++ b/protected/java/src/org/broadinstitute/sting/gatk/walkers/compression/reducereads/SlidingWindow.java @@ -46,6 +46,7 @@ package org.broadinstitute.sting.gatk.walkers.compression.reducereads; +import com.google.java.contract.Ensures; import com.google.java.contract.Requires; import net.sf.samtools.Cigar; import net.sf.samtools.CigarElement; @@ -135,6 +136,15 @@ public class SlidingWindow { return header.isEmpty() ? -1 : header.peek().getLocation(); } + // for testing only + protected SlidingWindow(final String contig, final int contigIndex, final int startLocation) { + this.contig = contig; + this.contigIndex = contigIndex; + nContigs = 1; + this.windowHeader = new LinkedList(); + windowHeader.addFirst(new HeaderElement(startLocation)); + this.readsInWindow = new TreeSet(); + } public SlidingWindow(String contig, int contigIndex, int contextSize, SAMFileHeader samHeader, GATKSAMReadGroupRecord readGroupAttribute, int windowNumber, final double minAltProportionToTriggerVariant, final double minIndelProportionToTriggerVariant, int minBaseQual, int minMappingQuality, int downsampleCoverage, final ReduceReads.DownsampleStrategy downsampleStrategy, boolean hasIndelQualities, int nContigs, boolean allowPolyploidReduction) { this.contextSize = contextSize; @@ -193,14 +203,17 @@ public class SlidingWindow { } /** - * returns the next complete or incomplete variant region between 'from' (inclusive) and 'to' (exclusive) + * Returns the next complete (or incomplete if closeLastRegion is true) variant region between 'from' (inclusive) and 'to' (exclusive) + * but converted to global coordinates. * - * @param from beginning window header index of the search window (inclusive) - * @param to end window header index of the search window (exclusive) + * @param from beginning window header index of the search window (inclusive); note that this uses local coordinates + * @param to end window header index of the search window (exclusive); note that this uses local coordinates * @param variantSite boolean array with true marking variant regions - * @return null if nothing is variant, start/stop if there is a complete variant region, start/-1 if there is an incomplete variant region. + * @param closeLastRegion if the last index is variant (so it's an incomplete region), should we close (and return as an interval) the location or ignore it? + * @return null if nothing is variant, start/stop if there is a complete variant region, start/-1 if there is an incomplete variant region. All coordinates returned are global. */ - private SimpleGenomeLoc findNextVariantRegion(int from, int to, boolean[] variantSite, boolean forceClose) { + @Requires({"from >= 0", "from <= to", "to <= variantSite.length"}) + private SimpleGenomeLoc findNextVariantRegion(int from, int to, boolean[] variantSite, boolean closeLastRegion) { boolean foundStart = false; final int windowHeaderStart = getStartLocation(windowHeader); int variantRegionStartIndex = 0; @@ -215,22 +228,27 @@ public class SlidingWindow { } final int refStart = windowHeaderStart + variantRegionStartIndex; final int refStop = windowHeaderStart + to - 1; - return (foundStart && forceClose) ? new SimpleGenomeLoc(contig, contigIndex, refStart, refStop, true) : null; + return (foundStart && closeLastRegion) ? new SimpleGenomeLoc(contig, contigIndex, refStart, refStop, true) : null; } /** * Creates a list with all the complete and incomplete variant regions within 'from' (inclusive) and 'to' (exclusive) * - * @param from beginning window header index of the search window (inclusive) - * @param to end window header index of the search window (exclusive) + * @param from beginning window header index of the search window (inclusive); note that this uses local coordinates + * @param to end window header index of the search window (exclusive); note that this uses local coordinates * @param variantSite boolean array with true marking variant regions - * @return a list with start/stops of variant regions following findNextVariantRegion description + * @return a list with start/stops of variant regions following findNextVariantRegion description in global coordinates */ - private CompressionStash findVariantRegions(int from, int to, boolean[] variantSite, boolean forceClose) { + @Requires({"from >= 0", "from <= to", "to <= variantSite.length"}) + @Ensures("result != null") + protected CompressionStash findVariantRegions(int from, int to, boolean[] variantSite, boolean closeLastRegion) { + final int windowHeaderStart = getStartLocation(windowHeader); + CompressionStash regions = new CompressionStash(); int index = from; while(index < to) { - SimpleGenomeLoc result = findNextVariantRegion(index, to, variantSite, forceClose); + // returns results in global coordinates + SimpleGenomeLoc result = findNextVariantRegion(index, to, variantSite, closeLastRegion); if (result == null) break; @@ -238,7 +256,7 @@ public class SlidingWindow { if (!result.isFinished()) break; - index = result.getStop() + 1; + index = result.getStop() - windowHeaderStart + 1; // go back to local coordinates } return regions; } diff --git a/protected/java/test/org/broadinstitute/sting/gatk/walkers/compression/reducereads/HeaderElementUnitTest.java b/protected/java/test/org/broadinstitute/sting/gatk/walkers/compression/reducereads/HeaderElementUnitTest.java new file mode 100644 index 000000000..b6af954a0 --- /dev/null +++ b/protected/java/test/org/broadinstitute/sting/gatk/walkers/compression/reducereads/HeaderElementUnitTest.java @@ -0,0 +1,134 @@ +/* +* 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.gatk.walkers.compression.reducereads; + + +import org.broadinstitute.sting.BaseTest; +import org.testng.Assert; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.util.ArrayList; +import java.util.List; + +public class HeaderElementUnitTest extends BaseTest { + + private class HETest { + public byte base, baseQual, insQual, delQual; + public int MQ; + public boolean isClip; + + private HETest(final byte base, final byte baseQual, final byte insQual, final byte delQual, final int MQ, final boolean isClip) { + this.base = base; + this.baseQual = baseQual; + this.insQual = insQual; + this.delQual = delQual; + this.MQ = MQ; + this.isClip = isClip; + } + } + + private static final byte byteA = (byte)'A'; + private static final byte byte10 = (byte)10; + private static final byte byte20 = (byte)20; + private static final int minBaseQual = 20; + private static final int minMappingQual = 20; + + @DataProvider(name = "data") + public Object[][] createData() { + List tests = new ArrayList(); + + tests.add(new Object[]{new HETest(byteA, byte20, byte20, byte20, 20, false)}); + tests.add(new Object[]{new HETest(byteA, byte10, byte20, byte20, 20, false)}); + tests.add(new Object[]{new HETest(byteA, byte20, byte20, byte20, 10, false)}); + tests.add(new Object[]{new HETest(byteA, byte20, byte20, byte20, 20, true)}); + + return tests.toArray(new Object[][]{}); + } + + @Test(dataProvider = "data", enabled = true) + public void testHE(HETest test) { + + HeaderElement headerElement = new HeaderElement(1000, 0); + + // first test that if we add and then remove it, we have no data + headerElement.addBase(test.base, test.baseQual, test.insQual, test.delQual, test.MQ, minBaseQual, minMappingQual, test.isClip); + headerElement.addInsertionToTheRight(); + headerElement.removeBase(test.base, test.baseQual, test.insQual, test.delQual, test.MQ, minBaseQual, minMappingQual, test.isClip); + headerElement.removeInsertionToTheRight(); + testHeaderIsEmpty(headerElement); + + // now, test that the data was added as expected + for ( int i = 0; i < 10; i++ ) + headerElement.addBase(test.base, test.baseQual, test.insQual, test.delQual, test.MQ, minBaseQual, minMappingQual, test.isClip); + testHeaderData(headerElement, test); + + // test the insertion adding functionality + for ( int i = 0; i < 10; i++ ) + headerElement.addInsertionToTheRight(); + Assert.assertEquals(headerElement.numInsertionsToTheRight(), 10); + } + + private void testHeaderIsEmpty(final HeaderElement headerElement) { + Assert.assertFalse(headerElement.hasConsensusData()); + Assert.assertFalse(headerElement.hasFilteredData()); + Assert.assertFalse(headerElement.hasInsertionToTheRight()); + Assert.assertTrue(headerElement.isEmpty()); + Assert.assertEquals(headerElement.getRMS(), 0.0); + } + + private void testHeaderData(final HeaderElement headerElement, final HETest test) { + Assert.assertEquals(headerElement.getRMS(), (double)test.MQ); + Assert.assertEquals(headerElement.isVariantFromSoftClips(), test.isClip); + Assert.assertFalse(headerElement.isEmpty()); + Assert.assertFalse(headerElement.hasInsertionToTheRight()); + Assert.assertEquals(headerElement.hasConsensusData(), headerElement.basePassesFilters(test.baseQual, minBaseQual, test.MQ, minMappingQual)); + Assert.assertEquals(headerElement.hasFilteredData(), !headerElement.basePassesFilters(test.baseQual, minBaseQual, test.MQ, minMappingQual)); + Assert.assertFalse(headerElement.isVariantFromMismatches(0.05)); + Assert.assertEquals(headerElement.isVariant(0.05, 0.05), test.isClip); + } +} diff --git a/protected/java/test/org/broadinstitute/sting/gatk/walkers/compression/reducereads/SimpleGenomeLocUnitTest.java b/protected/java/test/org/broadinstitute/sting/gatk/walkers/compression/reducereads/SimpleGenomeLocUnitTest.java new file mode 100644 index 000000000..cbac7e3c1 --- /dev/null +++ b/protected/java/test/org/broadinstitute/sting/gatk/walkers/compression/reducereads/SimpleGenomeLocUnitTest.java @@ -0,0 +1,106 @@ +/* +* 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.gatk.walkers.compression.reducereads; + + +import org.broadinstitute.sting.BaseTest; +import org.broadinstitute.sting.utils.exceptions.ReviewedStingException; +import org.testng.Assert; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.util.*; + +public class SimpleGenomeLocUnitTest extends BaseTest { + + private static final SimpleGenomeLoc loc1 = new SimpleGenomeLoc("1", 0, 10, 20, false); + private static final SimpleGenomeLoc loc2 = new SimpleGenomeLoc("1", 0, 21, 30, false); + private static final SimpleGenomeLoc loc3 = new SimpleGenomeLoc("1", 0, 31, 40, false); + + private class SGLTest { + public List locs; + + private SGLTest(final List locs) { + this.locs = locs; + } + } + + @DataProvider(name = "SGLtest") + public Object[][] createFindVariantRegionsData() { + List tests = new ArrayList(); + + tests.add(new Object[]{new SGLTest(Arrays.asList(loc1))}); + tests.add(new Object[]{new SGLTest(Arrays.asList(loc1, loc2))}); + tests.add(new Object[]{new SGLTest(Arrays.asList(loc1, loc2, loc3))}); + + return tests.toArray(new Object[][]{}); + } + + @Test(dataProvider = "SGLtest", enabled = true) + public void testSimpleGenomeLoc(SGLTest test) { + testMerge(test.locs); + } + + @Test(expectedExceptions = ReviewedStingException.class) + public void testNotContiguousLocs() { + final List locs = new ArrayList(1); + locs.add(loc1); + locs.add(loc3); + testMerge(locs); + } + + private void testMerge(final List locs) { + SimpleGenomeLoc result1 = locs.get(0); + for ( int i = 1; i < locs.size(); i++ ) + result1 = SimpleGenomeLoc.merge(result1, locs.get(i)); + + SimpleGenomeLoc result2 = SimpleGenomeLoc.merge(new TreeSet(locs)); + Assert.assertEquals(result1, result2); + Assert.assertEquals(result1.getStart(), locs.get(0).getStart()); + Assert.assertEquals(result1.getStop(), locs.get(locs.size() - 1).getStop()); + } +} diff --git a/protected/java/test/org/broadinstitute/sting/gatk/walkers/compression/reducereads/SlidingWindowUnitTest.java b/protected/java/test/org/broadinstitute/sting/gatk/walkers/compression/reducereads/SlidingWindowUnitTest.java new file mode 100644 index 000000000..cfb8c53b4 --- /dev/null +++ b/protected/java/test/org/broadinstitute/sting/gatk/walkers/compression/reducereads/SlidingWindowUnitTest.java @@ -0,0 +1,227 @@ +/* +* Copyright (c) 2012 The Broad Institute +* +* Permission is hereby granted, free of charge, to any person +* obtaining a copy of this software and associated documentation +* files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, +* copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following +* conditions: +* +* The above copyright notice and this permission notice shall be +* included in all copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR +* THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +package org.broadinstitute.sting.gatk.walkers.compression.reducereads; + +import net.sf.samtools.SAMFileHeader; +import net.sf.samtools.SAMReadGroupRecord; +import net.sf.samtools.SAMRecord; +import org.broadinstitute.sting.BaseTest; +import org.broadinstitute.sting.gatk.GenomeAnalysisEngine; +import org.broadinstitute.sting.utils.sam.ArtificialSAMUtils; +import org.broadinstitute.sting.utils.sam.ArtificialSingleSampleReadStream; +import org.broadinstitute.sting.utils.sam.ArtificialSingleSampleReadStreamAnalyzer; +import org.testng.Assert; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class SlidingWindowUnitTest extends BaseTest { + + ////////////////////////////////////////////////////////////////////////////////////// + //// This section tests the findVariantRegions() method and related functionality //// + ////////////////////////////////////////////////////////////////////////////////////// + + private static final int variantRegionLength = 1000; + private static final int globalStartPosition = 1000000; + private static final SimpleGenomeLoc loc90to95 = new SimpleGenomeLoc("1", 0, 1000090, 1000095, false); + private static final SimpleGenomeLoc loc96to99 = new SimpleGenomeLoc("1", 0, 1000096, 1000099, false); + private static final SimpleGenomeLoc loc100to110 = new SimpleGenomeLoc("1", 0, 1000100, 1000110, false); + private static final SimpleGenomeLoc loc999 = new SimpleGenomeLoc("1", 0, 1000999, 1000999, false); + + private class FindVariantRegionsTest { + public List locs, expectedResult; + public boolean[] variantRegionBitset; + + private FindVariantRegionsTest(final List locs) { + this.locs = locs; + this.expectedResult = locs; + variantRegionBitset = createBitset(locs); + } + + private FindVariantRegionsTest(final List locs, final List expectedResult) { + this.locs = locs; + this.expectedResult = expectedResult; + variantRegionBitset = createBitset(locs); + } + } + + private static boolean[] createBitset(final List locs) { + boolean[] variantRegionBitset = new boolean[variantRegionLength]; + for ( SimpleGenomeLoc loc : locs ) { + final int stop = loc.getStop() - globalStartPosition; + for ( int i = loc.getStart() - globalStartPosition; i <= stop; i++ ) + variantRegionBitset[i] = true; + } + return variantRegionBitset; + } + + @DataProvider(name = "findVariantRegions") + public Object[][] createFindVariantRegionsData() { + List tests = new ArrayList(); + + tests.add(new Object[]{new FindVariantRegionsTest(Arrays.asList(loc90to95))}); + tests.add(new Object[]{new FindVariantRegionsTest(Arrays.asList(loc90to95, loc100to110))}); + tests.add(new Object[]{new FindVariantRegionsTest(Arrays.asList(loc90to95, loc96to99, loc100to110), Arrays.asList(new SimpleGenomeLoc("1", 0, 1000090, 1000110, false)))}); + tests.add(new Object[]{new FindVariantRegionsTest(Arrays.asList(loc90to95, loc999))}); + tests.add(new Object[]{new FindVariantRegionsTest(Arrays.asList(loc999))}); + + return tests.toArray(new Object[][]{}); + } + + @Test(dataProvider = "findVariantRegions", enabled = true) + public void testFindVariantRegions(FindVariantRegionsTest test) { + final SlidingWindow slidingWindow = new SlidingWindow("1", 0, globalStartPosition); + final CompressionStash locs = slidingWindow.findVariantRegions(0, variantRegionLength, test.variantRegionBitset, true); + int index = 0; + for ( final SimpleGenomeLoc loc : locs ) { + Assert.assertTrue(loc.equals(test.expectedResult.get(index++))); + } + } + + @Test(enabled = true) + public void testNoClosingRegions() { + final SlidingWindow slidingWindow = new SlidingWindow("1", 0, globalStartPosition); + final CompressionStash locs = slidingWindow.findVariantRegions(0, variantRegionLength, createBitset(Arrays.asList(loc90to95, loc999)), false); + Assert.assertEquals(locs.size(), 1); + Assert.assertEquals(locs.iterator().next(), loc90to95); + } + + + + + + + + + + + + + + /* + + private static class DownsamplingReadsIteratorTest extends TestDataProvider { + private DownsamplingReadsIterator downsamplingIter; + private int targetCoverage; + private ArtificialSingleSampleReadStream stream; + private ArtificialSingleSampleReadStreamAnalyzer streamAnalyzer; + + public DownsamplingReadsIteratorTest( ArtificialSingleSampleReadStream stream, int targetCoverage ) { + super(DownsamplingReadsIteratorTest.class); + + this.stream = stream; + this.targetCoverage = targetCoverage; + + setName(String.format("%s: targetCoverage=%d numContigs=%d stacksPerContig=%d readsPerStack=%d-%d distanceBetweenStacks=%d-%d readLength=%d-%d unmappedReads=%d", + getClass().getSimpleName(), + targetCoverage, + stream.getNumContigs(), + stream.getNumStacksPerContig(), + stream.getMinReadsPerStack(), + stream.getMaxReadsPerStack(), + stream.getMinDistanceBetweenStacks(), + stream.getMaxDistanceBetweenStacks(), + stream.getMinReadLength(), + stream.getMaxReadLength(), + stream.getNumUnmappedReads())); + } + + public void run() { + streamAnalyzer = new PositionallyDownsampledArtificialSingleSampleReadStreamAnalyzer(stream, targetCoverage); + downsamplingIter = new DownsamplingReadsIterator(stream.getStingSAMIterator(), new SimplePositionalDownsampler(targetCoverage)); + + streamAnalyzer.analyze(downsamplingIter); + + // Check whether the observed properties of the downsampled stream are what they should be + streamAnalyzer.validate(); + + // Allow memory used by this test to be reclaimed + stream = null; + streamAnalyzer = null; + downsamplingIter = null; + } + } + + @DataProvider(name = "DownsamplingReadsIteratorTestDataProvider") + public Object[][] createDownsamplingReadsIteratorTests() { + SAMFileHeader header = ArtificialSAMUtils.createArtificialSamHeader(5, 1, 10000); + String readGroupID = "testReadGroup"; + SAMReadGroupRecord readGroup = new SAMReadGroupRecord(readGroupID); + readGroup.setSample("testSample"); + header.addReadGroup(readGroup); + + // Values that don't vary across tests + int targetCoverage = 10; + int minReadLength = 50; + int maxReadLength = 100; + int minDistanceBetweenStacks = 1; + int maxDistanceBetweenStacks = maxReadLength + 1; + + GenomeAnalysisEngine.resetRandomGenerator(); + + // brute force testing! + for ( int numContigs : Arrays.asList(1, 2, 5) ) { + for ( int stacksPerContig : Arrays.asList(1, 2, 10) ) { + for ( int minReadsPerStack : Arrays.asList(1, targetCoverage / 2, targetCoverage, targetCoverage - 1, targetCoverage + 1, targetCoverage * 2) ) { + for ( int maxReadsPerStack : Arrays.asList(1, targetCoverage / 2, targetCoverage, targetCoverage - 1, targetCoverage + 1, targetCoverage * 2) ) { + for ( int numUnmappedReads : Arrays.asList(0, 1, targetCoverage, targetCoverage * 2) ) { + // Only interested in sane read stream configurations here + if ( minReadsPerStack <= maxReadsPerStack ) { + new DownsamplingReadsIteratorTest(new ArtificialSingleSampleReadStream(header, + readGroupID, + numContigs, + stacksPerContig, + minReadsPerStack, + maxReadsPerStack, + minDistanceBetweenStacks, + maxDistanceBetweenStacks, + minReadLength, + maxReadLength, + numUnmappedReads), + targetCoverage); + } + } + } + } + } + } + + return DownsamplingReadsIteratorTest.getTests(DownsamplingReadsIteratorTest.class); + } + + @Test(dataProvider = "DownsamplingReadsIteratorTestDataProvider") + public void runDownsamplingReadsIteratorTest( DownsamplingReadsIteratorTest test ) { + logger.warn("Running test: " + test); + + GenomeAnalysisEngine.resetRandomGenerator(); + test.run(); + } + + */ +}