Merge branch 'master' of github.com:broadinstitute/gsa-unstable

This commit is contained in:
Ami Levy-Moonshine 2013-01-29 16:33:20 -05:00
commit a1908a0eca
18 changed files with 896 additions and 719 deletions

View File

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

View File

@ -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<SimpleGenomeLoc> 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;
}
}

View File

@ -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<HeaderElement>();
windowHeader.addFirst(new HeaderElement(startLocation));
this.readsInWindow = new TreeSet<GATKSAMRecord>();
}
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;
}

View File

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

View File

@ -75,6 +75,7 @@ public class BaseRecalibration {
private final boolean disableIndelQuals;
private final int preserveQLessThan;
private final double globalQScorePrior;
private final boolean emitOriginalQuals;
private final NestedIntegerArray<Double> globalDeltaQs;
@ -83,13 +84,13 @@ public class BaseRecalibration {
/**
* 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
* @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 +103,7 @@ public class BaseRecalibration {
this.disableIndelQuals = disableIndelQuals;
this.preserveQLessThan = preserveQLessThan;
this.globalQScorePrior = globalQScorePrior;
this.emitOriginalQuals = emitOriginalQuals;
logger.info("Calculating cached tables...");
@ -264,8 +266,8 @@ public class BaseRecalibration {
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 : empiricalQualRG.getEstimatedQReported() );
final double globalDeltaQEmpirical = empiricalQualRG.getEmpiricalQuality(aggregrateQReported);
result = globalDeltaQEmpirical - aggregrateQReported;
}
@ -277,8 +279,8 @@ 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(globalDeltaQ + qualFromRead);
result = deltaQReportedEmpirical - (globalDeltaQ + qualFromRead);
}
return result;
@ -310,8 +312,8 @@ public class BaseRecalibration {
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;
}

View File

@ -77,6 +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 org.broadinstitute.sting.utils.exceptions.ReviewedStingException;
/**
@ -221,8 +222,13 @@ public class RecalDatum {
}
public final double getEmpiricalQuality() {
if (empiricalQuality == UNINITIALIZED)
calcEmpiricalQuality();
return getEmpiricalQuality(getEstimatedQReported());
}
public synchronized final double getEmpiricalQuality(final double conditionalPrior) {
if (empiricalQuality == UNINITIALIZED) {
calcEmpiricalQuality(conditionalPrior);
}
return empiricalQuality;
}
@ -319,13 +325,13 @@ public class RecalDatum {
*/
@Requires("empiricalQuality == UNINITIALIZED")
@Ensures("empiricalQuality != UNINITIALIZED")
private synchronized void calcEmpiricalQuality() {
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, getEstimatedQReported());
final double empiricalQual = RecalDatum.bayesianEstimateOfEmpiricalQuality(observations, mismatches, conditionalPrior);
// This is the old and busted point estimate approach:
//final double empiricalQual = -10 * Math.log10(getEmpiricalErrorRate());

View File

@ -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); // don't set the value here because we will want to recompute with a different conditional Q score prior value
return datum;
}

View File

@ -0,0 +1,273 @@
/*
* 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 {
public static final int MAX_REPEAT_LENGTH = 20;
public static final int MAX_STR_UNIT_LENGTH = 8;
private final HashMap<String, Integer> repeatLookupTable = new HashMap<String, Integer>();
private final HashMap<Integer, String> repeatReverseLookupTable = new HashMap<Integer, String>();
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<byte[], Integer> 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<byte[], Integer> 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.
// 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(maxRL > MAX_REPEAT_LENGTH) { maxRL = MAX_REPEAT_LENGTH; }
return new Pair<byte[], Integer>(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<Map.Entry<String, Integer>> 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<String,Integer> 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<String,Integer>(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<String,Integer> pair = getRUandNRfromCovariate(covariateValue);
return getBasesFromRUandNR(pair.getFirst(), pair.getSecond());
}
@Override
public abstract int maximumKeyValue();
}

View File

@ -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<String, Integer> repeatLookupTable = new HashMap<String, Integer>();
private final HashMap<Integer, String> repeatReverseLookupTable = new HashMap<Integer, String>();
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<byte[], Integer> 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<byte[], Integer> 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<byte[], Integer>(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<Map.Entry<String, Integer>> 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<String,Integer> 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<String,Integer>(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<String,Integer> 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);
}
}

View File

@ -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<String, Integer> repeatLookupTable = new HashMap<String, Integer>();
private final HashMap<Integer, String> repeatReverseLookupTable = new HashMap<Integer, String>();
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<byte[], Integer> 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<byte[], Integer> 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<byte[], Integer>(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<Map.Entry<String, Integer>> 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<String,Integer> 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<String,Integer>(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<String,Integer> 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;
}
}

View File

@ -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<String, Integer> repeatLookupTable = new HashMap<String, Integer>();
private final HashMap<Integer, String> repeatReverseLookupTable = new HashMap<Integer, String>();
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<byte[], Integer> 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<byte[], Integer> 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<byte[], Integer>(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<Map.Entry<String, Integer>> 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<String,Integer> 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<String,Integer>(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<String,Integer> pair = getRUandNRfromCovariate(covariateValue);
return getBasesFromRUandNR(pair.getFirst(), pair.getSecond());
}
@Override
public synchronized int maximumKeyValue() {

View File

@ -188,12 +188,12 @@ public class BQSRIntegrationTest extends WalkerTest {
public Object[][] createPRTestData() {
List<Object[]> tests = new ArrayList<Object[]>();
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[][]{});

View File

@ -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<Object[]> tests = new ArrayList<Object[]>();
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);
}
}

View File

@ -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<SimpleGenomeLoc> locs;
private SGLTest(final List<SimpleGenomeLoc> locs) {
this.locs = locs;
}
}
@DataProvider(name = "SGLtest")
public Object[][] createFindVariantRegionsData() {
List<Object[]> tests = new ArrayList<Object[]>();
tests.add(new Object[]{new SGLTest(Arrays.<SimpleGenomeLoc>asList(loc1))});
tests.add(new Object[]{new SGLTest(Arrays.<SimpleGenomeLoc>asList(loc1, loc2))});
tests.add(new Object[]{new SGLTest(Arrays.<SimpleGenomeLoc>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<SimpleGenomeLoc> locs = new ArrayList<SimpleGenomeLoc>(1);
locs.add(loc1);
locs.add(loc3);
testMerge(locs);
}
private void testMerge(final List<SimpleGenomeLoc> 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<SimpleGenomeLoc>(locs));
Assert.assertEquals(result1, result2);
Assert.assertEquals(result1.getStart(), locs.get(0).getStart());
Assert.assertEquals(result1.getStop(), locs.get(locs.size() - 1).getStop());
}
}

View File

@ -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<SimpleGenomeLoc> locs, expectedResult;
public boolean[] variantRegionBitset;
private FindVariantRegionsTest(final List<SimpleGenomeLoc> locs) {
this.locs = locs;
this.expectedResult = locs;
variantRegionBitset = createBitset(locs);
}
private FindVariantRegionsTest(final List<SimpleGenomeLoc> locs, final List<SimpleGenomeLoc> expectedResult) {
this.locs = locs;
this.expectedResult = expectedResult;
variantRegionBitset = createBitset(locs);
}
}
private static boolean[] createBitset(final List<SimpleGenomeLoc> 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<Object[]> tests = new ArrayList<Object[]>();
tests.add(new Object[]{new FindVariantRegionsTest(Arrays.<SimpleGenomeLoc>asList(loc90to95))});
tests.add(new Object[]{new FindVariantRegionsTest(Arrays.<SimpleGenomeLoc>asList(loc90to95, loc100to110))});
tests.add(new Object[]{new FindVariantRegionsTest(Arrays.<SimpleGenomeLoc>asList(loc90to95, loc96to99, loc100to110), Arrays.<SimpleGenomeLoc>asList(new SimpleGenomeLoc("1", 0, 1000090, 1000110, false)))});
tests.add(new Object[]{new FindVariantRegionsTest(Arrays.<SimpleGenomeLoc>asList(loc90to95, loc999))});
tests.add(new Object[]{new FindVariantRegionsTest(Arrays.<SimpleGenomeLoc>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.<SimpleGenomeLoc>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<SAMRecord>(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();
}
*/
}

View File

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

View File

@ -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 = "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;
// --------------------------------------------------------------------------------------------------------------
//
// Other utility arguments

View File

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