From e4ec899a879503f2e56d836d5b8cbe1b18ffc370 Mon Sep 17 00:00:00 2001 From: Eric Banks Date: Tue, 29 Jan 2013 15:51:07 -0500 Subject: [PATCH] First pass at adding unit tests for the RR framework: I have added 3 tests and all 3 uncovered RR bugs! One of the fixes was critical: SlidingWindow was not converting between global and relative positions correctly. Besides not being correct, it was resulting in a massive slow down of the RR traversal. That fix definitely breaks at least one of the integration tests, but it's not worth changing md5s now because I'll be changing things all over RR for the next few days, so I am going to let that test fail indefinitely until I can confirm general correctness of the tool. --- .../reducereads/HeaderElement.java | 8 +- .../reducereads/SimpleGenomeLoc.java | 31 ++- .../reducereads/SlidingWindow.java | 42 +++- .../reducereads/HeaderElementUnitTest.java | 134 +++++++++++ .../reducereads/SimpleGenomeLocUnitTest.java | 106 ++++++++ .../reducereads/SlidingWindowUnitTest.java | 227 ++++++++++++++++++ 6 files changed, 521 insertions(+), 27 deletions(-) create mode 100644 protected/java/test/org/broadinstitute/sting/gatk/walkers/compression/reducereads/HeaderElementUnitTest.java create mode 100644 protected/java/test/org/broadinstitute/sting/gatk/walkers/compression/reducereads/SimpleGenomeLocUnitTest.java create mode 100644 protected/java/test/org/broadinstitute/sting/gatk/walkers/compression/reducereads/SlidingWindowUnitTest.java diff --git a/protected/java/src/org/broadinstitute/sting/gatk/walkers/compression/reducereads/HeaderElement.java b/protected/java/src/org/broadinstitute/sting/gatk/walkers/compression/reducereads/HeaderElement.java index 1e7805fce..13d3d1b4c 100644 --- a/protected/java/src/org/broadinstitute/sting/gatk/walkers/compression/reducereads/HeaderElement.java +++ b/protected/java/src/org/broadinstitute/sting/gatk/walkers/compression/reducereads/HeaderElement.java @@ -244,7 +244,7 @@ public class HeaderElement { * * @return whether or not the HeaderElement is variant due to excess insertions */ - private boolean isVariantFromMismatches(double minVariantProportion) { + protected boolean isVariantFromMismatches(double minVariantProportion) { BaseIndex mostCommon = consensusBaseCounts.baseIndexWithMostProbabilityWithoutIndels(); double mostCommonProportion = consensusBaseCounts.baseCountProportionWithoutIndels(mostCommon); return mostCommonProportion != 0.0 && mostCommonProportion < (1 - minVariantProportion); @@ -256,11 +256,11 @@ public class HeaderElement { * * @return true if we had more soft clipped bases contributing to this site than matches/mismatches. */ - private boolean isVariantFromSoftClips() { - return nSoftClippedBases >= (consensusBaseCounts.totalCount() - nSoftClippedBases); + protected boolean isVariantFromSoftClips() { + return nSoftClippedBases > 0 && nSoftClippedBases >= (consensusBaseCounts.totalCount() - nSoftClippedBases); } - private boolean basePassesFilters(byte baseQual, int minBaseQual, int baseMappingQuality, int minMappingQual) { + protected boolean basePassesFilters(byte baseQual, int minBaseQual, int baseMappingQuality, int minMappingQual) { return baseQual >= minBaseQual && baseMappingQuality >= minMappingQual; } diff --git a/protected/java/src/org/broadinstitute/sting/gatk/walkers/compression/reducereads/SimpleGenomeLoc.java b/protected/java/src/org/broadinstitute/sting/gatk/walkers/compression/reducereads/SimpleGenomeLoc.java index a3ebb132f..85a1f8df1 100644 --- a/protected/java/src/org/broadinstitute/sting/gatk/walkers/compression/reducereads/SimpleGenomeLoc.java +++ b/protected/java/src/org/broadinstitute/sting/gatk/walkers/compression/reducereads/SimpleGenomeLoc.java @@ -78,6 +78,13 @@ public class SimpleGenomeLoc extends GenomeLoc { return finished; } + /** + * Merges 2 *contiguous* locs into 1 + * + * @param a SimpleGenomeLoc #1 + * @param b SimpleGenomeLoc #2 + * @return one merged loc + */ @Requires("a != null && b != null") public static SimpleGenomeLoc merge(SimpleGenomeLoc a, SimpleGenomeLoc b) throws ReviewedStingException { if(GenomeLoc.isUnmapped(a) || GenomeLoc.isUnmapped(b)) { @@ -88,7 +95,6 @@ public class SimpleGenomeLoc extends GenomeLoc { throw new ReviewedStingException("The two genome locs need to be contiguous"); } - return new SimpleGenomeLoc(a.getContig(), a.contigIndex, Math.min(a.getStart(), b.getStart()), Math.max(a.getStop(), b.getStop()), @@ -101,19 +107,22 @@ public class SimpleGenomeLoc extends GenomeLoc { * @param sortedLocs a sorted list of contiguous locs * @return one merged loc */ + @Requires("sortedLocs != null") public static SimpleGenomeLoc merge(SortedSet sortedLocs) { - SimpleGenomeLoc previousLoc = null; - for (SimpleGenomeLoc loc : sortedLocs) { - if (loc.isUnmapped()) { + SimpleGenomeLoc result = null; + + for ( SimpleGenomeLoc loc : sortedLocs ) { + if ( loc.isUnmapped() ) throw new ReviewedStingException("Tried to merge unmapped genome locs"); - } - if (previousLoc != null && !previousLoc.contiguousP(loc)) { + + if ( result == null ) + result = loc; + else if ( !result.contiguousP(loc) ) throw new ReviewedStingException("The genome locs need to be contiguous"); - } - previousLoc = loc; + else + result = merge(result, loc); } - SimpleGenomeLoc firstLoc = sortedLocs.first(); - SimpleGenomeLoc lastLoc = sortedLocs.last(); - return merge(firstLoc, lastLoc); + + return result; } } diff --git a/protected/java/src/org/broadinstitute/sting/gatk/walkers/compression/reducereads/SlidingWindow.java b/protected/java/src/org/broadinstitute/sting/gatk/walkers/compression/reducereads/SlidingWindow.java index e91120f1c..57a11f640 100644 --- a/protected/java/src/org/broadinstitute/sting/gatk/walkers/compression/reducereads/SlidingWindow.java +++ b/protected/java/src/org/broadinstitute/sting/gatk/walkers/compression/reducereads/SlidingWindow.java @@ -46,6 +46,7 @@ package org.broadinstitute.sting.gatk.walkers.compression.reducereads; +import com.google.java.contract.Ensures; import com.google.java.contract.Requires; import net.sf.samtools.Cigar; import net.sf.samtools.CigarElement; @@ -135,6 +136,15 @@ public class SlidingWindow { return header.isEmpty() ? -1 : header.peek().getLocation(); } + // for testing only + protected SlidingWindow(final String contig, final int contigIndex, final int startLocation) { + this.contig = contig; + this.contigIndex = contigIndex; + nContigs = 1; + this.windowHeader = new LinkedList(); + windowHeader.addFirst(new HeaderElement(startLocation)); + this.readsInWindow = new TreeSet(); + } public SlidingWindow(String contig, int contigIndex, int contextSize, SAMFileHeader samHeader, GATKSAMReadGroupRecord readGroupAttribute, int windowNumber, final double minAltProportionToTriggerVariant, final double minIndelProportionToTriggerVariant, int minBaseQual, int minMappingQuality, int downsampleCoverage, final ReduceReads.DownsampleStrategy downsampleStrategy, boolean hasIndelQualities, int nContigs, boolean allowPolyploidReduction) { this.contextSize = contextSize; @@ -193,14 +203,17 @@ public class SlidingWindow { } /** - * returns the next complete or incomplete variant region between 'from' (inclusive) and 'to' (exclusive) + * Returns the next complete (or incomplete if closeLastRegion is true) variant region between 'from' (inclusive) and 'to' (exclusive) + * but converted to global coordinates. * - * @param from beginning window header index of the search window (inclusive) - * @param to end window header index of the search window (exclusive) + * @param from beginning window header index of the search window (inclusive); note that this uses local coordinates + * @param to end window header index of the search window (exclusive); note that this uses local coordinates * @param variantSite boolean array with true marking variant regions - * @return null if nothing is variant, start/stop if there is a complete variant region, start/-1 if there is an incomplete variant region. + * @param closeLastRegion if the last index is variant (so it's an incomplete region), should we close (and return as an interval) the location or ignore it? + * @return null if nothing is variant, start/stop if there is a complete variant region, start/-1 if there is an incomplete variant region. All coordinates returned are global. */ - private SimpleGenomeLoc findNextVariantRegion(int from, int to, boolean[] variantSite, boolean forceClose) { + @Requires({"from >= 0", "from <= to", "to <= variantSite.length"}) + private SimpleGenomeLoc findNextVariantRegion(int from, int to, boolean[] variantSite, boolean closeLastRegion) { boolean foundStart = false; final int windowHeaderStart = getStartLocation(windowHeader); int variantRegionStartIndex = 0; @@ -215,22 +228,27 @@ public class SlidingWindow { } final int refStart = windowHeaderStart + variantRegionStartIndex; final int refStop = windowHeaderStart + to - 1; - return (foundStart && forceClose) ? new SimpleGenomeLoc(contig, contigIndex, refStart, refStop, true) : null; + return (foundStart && closeLastRegion) ? new SimpleGenomeLoc(contig, contigIndex, refStart, refStop, true) : null; } /** * Creates a list with all the complete and incomplete variant regions within 'from' (inclusive) and 'to' (exclusive) * - * @param from beginning window header index of the search window (inclusive) - * @param to end window header index of the search window (exclusive) + * @param from beginning window header index of the search window (inclusive); note that this uses local coordinates + * @param to end window header index of the search window (exclusive); note that this uses local coordinates * @param variantSite boolean array with true marking variant regions - * @return a list with start/stops of variant regions following findNextVariantRegion description + * @return a list with start/stops of variant regions following findNextVariantRegion description in global coordinates */ - private CompressionStash findVariantRegions(int from, int to, boolean[] variantSite, boolean forceClose) { + @Requires({"from >= 0", "from <= to", "to <= variantSite.length"}) + @Ensures("result != null") + protected CompressionStash findVariantRegions(int from, int to, boolean[] variantSite, boolean closeLastRegion) { + final int windowHeaderStart = getStartLocation(windowHeader); + CompressionStash regions = new CompressionStash(); int index = from; while(index < to) { - SimpleGenomeLoc result = findNextVariantRegion(index, to, variantSite, forceClose); + // returns results in global coordinates + SimpleGenomeLoc result = findNextVariantRegion(index, to, variantSite, closeLastRegion); if (result == null) break; @@ -238,7 +256,7 @@ public class SlidingWindow { if (!result.isFinished()) break; - index = result.getStop() + 1; + index = result.getStop() - windowHeaderStart + 1; // go back to local coordinates } return regions; } diff --git a/protected/java/test/org/broadinstitute/sting/gatk/walkers/compression/reducereads/HeaderElementUnitTest.java b/protected/java/test/org/broadinstitute/sting/gatk/walkers/compression/reducereads/HeaderElementUnitTest.java new file mode 100644 index 000000000..b6af954a0 --- /dev/null +++ b/protected/java/test/org/broadinstitute/sting/gatk/walkers/compression/reducereads/HeaderElementUnitTest.java @@ -0,0 +1,134 @@ +/* +* By downloading the PROGRAM you agree to the following terms of use: +* +* BROAD INSTITUTE - SOFTWARE LICENSE AGREEMENT - FOR ACADEMIC NON-COMMERCIAL RESEARCH PURPOSES ONLY +* +* This Agreement is made between the Broad Institute, Inc. with a principal address at 7 Cambridge Center, Cambridge, MA 02142 (BROAD) and the LICENSEE and is effective at the date the downloading is completed (EFFECTIVE DATE). +* +* WHEREAS, LICENSEE desires to license the PROGRAM, as defined hereinafter, and BROAD wishes to have this PROGRAM utilized in the public interest, subject only to the royalty-free, nonexclusive, nontransferable license rights of the United States Government pursuant to 48 CFR 52.227-14; and +* WHEREAS, LICENSEE desires to license the PROGRAM and BROAD desires to grant a license on the following terms and conditions. +* NOW, THEREFORE, in consideration of the promises and covenants made herein, the parties hereto agree as follows: +* +* 1. DEFINITIONS +* 1.1 PROGRAM shall mean copyright in the object code and source code known as GATK2 and related documentation, if any, as they exist on the EFFECTIVE DATE and can be downloaded from http://www.broadinstitute/GATK on the EFFECTIVE DATE. +* +* 2. LICENSE +* 2.1 Grant. Subject to the terms of this Agreement, BROAD hereby grants to LICENSEE, solely for academic non-commercial research purposes, a non-exclusive, non-transferable license to: (a) download, execute and display the PROGRAM and (b) create bug fixes and modify the PROGRAM. +* The LICENSEE may apply the PROGRAM in a pipeline to data owned by users other than the LICENSEE and provide these users the results of the PROGRAM provided LICENSEE does so for academic non-commercial purposes only. For clarification purposes, academic sponsored research is not a commercial use under the terms of this Agreement. +* 2.2 No Sublicensing or Additional Rights. LICENSEE shall not sublicense or distribute the PROGRAM, in whole or in part, without prior written permission from BROAD. LICENSEE shall ensure that all of its users agree to the terms of this Agreement. LICENSEE further agrees that it shall not put the PROGRAM on a network, server, or other similar technology that may be accessed by anyone other than the LICENSEE and its employees and users who have agreed to the terms of this agreement. +* 2.3 License Limitations. Nothing in this Agreement shall be construed to confer any rights upon LICENSEE by implication, estoppel, or otherwise to any computer software, trademark, intellectual property, or patent rights of BROAD, or of any other entity, except as expressly granted herein. LICENSEE agrees that the PROGRAM, in whole or part, shall not be used for any commercial purpose, including without limitation, as the basis of a commercial software or hardware product or to provide services. LICENSEE further agrees that the PROGRAM shall not be copied or otherwise adapted in order to circumvent the need for obtaining a license for use of the PROGRAM. +* +* 3. OWNERSHIP OF INTELLECTUAL PROPERTY +* LICENSEE acknowledges that title to the PROGRAM shall remain with BROAD. The PROGRAM is marked with the following BROAD copyright notice and notice of attribution to contributors. LICENSEE shall retain such notice on all copies. LICENSEE agrees to include appropriate attribution if any results obtained from use of the PROGRAM are included in any publication. +* Copyright 2012 Broad Institute, Inc. +* Notice of attribution: The GATK2 program was made available through the generosity of Medical and Population Genetics program at the Broad Institute, Inc. +* LICENSEE shall not use any trademark or trade name of BROAD, or any variation, adaptation, or abbreviation, of such marks or trade names, or any names of officers, faculty, students, employees, or agents of BROAD except as states above for attribution purposes. +* +* 4. INDEMNIFICATION +* LICENSEE shall indemnify, defend, and hold harmless BROAD, and their respective officers, faculty, students, employees, associated investigators and agents, and their respective successors, heirs and assigns, (Indemnitees), against any liability, damage, loss, or expense (including reasonable attorneys fees and expenses) incurred by or imposed upon any of the Indemnitees in connection with any claims, suits, actions, demands or judgments arising out of any theory of liability (including, without limitation, actions in the form of tort, warranty, or strict liability and regardless of whether such action has any factual basis) pursuant to any right or license granted under this Agreement. +* +* 5. NO REPRESENTATIONS OR WARRANTIES +* THE PROGRAM IS DELIVERED AS IS. BROAD MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE PROGRAM OR THE COPYRIGHT, EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, WHETHER OR NOT DISCOVERABLE. BROAD EXTENDS NO WARRANTIES OF ANY KIND AS TO PROGRAM CONFORMITY WITH WHATEVER USER MANUALS OR OTHER LITERATURE MAY BE ISSUED FROM TIME TO TIME. +* IN NO EVENT SHALL BROAD OR ITS RESPECTIVE DIRECTORS, OFFICERS, EMPLOYEES, AFFILIATED INVESTIGATORS AND AFFILIATES BE LIABLE FOR INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, INCLUDING, WITHOUT LIMITATION, ECONOMIC DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER BROAD SHALL BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT SHALL KNOW OF THE POSSIBILITY OF THE FOREGOING. +* +* 6. ASSIGNMENT +* This Agreement is personal to LICENSEE and any rights or obligations assigned by LICENSEE without the prior written consent of BROAD shall be null and void. +* +* 7. MISCELLANEOUS +* 7.1 Export Control. LICENSEE gives assurance that it will comply with all United States export control laws and regulations controlling the export of the PROGRAM, including, without limitation, all Export Administration Regulations of the United States Department of Commerce. Among other things, these laws and regulations prohibit, or require a license for, the export of certain types of software to specified countries. +* 7.2 Termination. LICENSEE shall have the right to terminate this Agreement for any reason upon prior written notice to BROAD. If LICENSEE breaches any provision hereunder, and fails to cure such breach within thirty (30) days, BROAD may terminate this Agreement immediately. Upon termination, LICENSEE shall provide BROAD with written assurance that the original and all copies of the PROGRAM have been destroyed, except that, upon prior written authorization from BROAD, LICENSEE may retain a copy for archive purposes. +* 7.3 Survival. The following provisions shall survive the expiration or termination of this Agreement: Articles 1, 3, 4, 5 and Sections 2.2, 2.3, 7.3, and 7.4. +* 7.4 Notice. Any notices under this Agreement shall be in writing, shall specifically refer to this Agreement, and shall be sent by hand, recognized national overnight courier, confirmed facsimile transmission, confirmed electronic mail, or registered or certified mail, postage prepaid, return receipt requested. All notices under this Agreement shall be deemed effective upon receipt. +* 7.5 Amendment and Waiver; Entire Agreement. This Agreement may be amended, supplemented, or otherwise modified only by means of a written instrument signed by all parties. Any waiver of any rights or failure to act in a specific instance shall relate only to such instance and shall not be construed as an agreement to waive any rights or fail to act in any other instance, whether or not similar. This Agreement constitutes the entire agreement among the parties with respect to its subject matter and supersedes prior agreements or understandings between the parties relating to its subject matter. +* 7.6 Binding Effect; Headings. This Agreement shall be binding upon and inure to the benefit of the parties and their respective permitted successors and assigns. All headings are for convenience only and shall not affect the meaning of any provision of this Agreement. +* 7.7 Governing Law. This Agreement shall be construed, governed, interpreted and applied in accordance with the internal laws of the Commonwealth of Massachusetts, U.S.A., without regard to conflict of laws principles. +*/ + +package org.broadinstitute.sting.gatk.walkers.compression.reducereads; + + +import org.broadinstitute.sting.BaseTest; +import org.testng.Assert; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.util.ArrayList; +import java.util.List; + +public class HeaderElementUnitTest extends BaseTest { + + private class HETest { + public byte base, baseQual, insQual, delQual; + public int MQ; + public boolean isClip; + + private HETest(final byte base, final byte baseQual, final byte insQual, final byte delQual, final int MQ, final boolean isClip) { + this.base = base; + this.baseQual = baseQual; + this.insQual = insQual; + this.delQual = delQual; + this.MQ = MQ; + this.isClip = isClip; + } + } + + private static final byte byteA = (byte)'A'; + private static final byte byte10 = (byte)10; + private static final byte byte20 = (byte)20; + private static final int minBaseQual = 20; + private static final int minMappingQual = 20; + + @DataProvider(name = "data") + public Object[][] createData() { + List tests = new ArrayList(); + + tests.add(new Object[]{new HETest(byteA, byte20, byte20, byte20, 20, false)}); + tests.add(new Object[]{new HETest(byteA, byte10, byte20, byte20, 20, false)}); + tests.add(new Object[]{new HETest(byteA, byte20, byte20, byte20, 10, false)}); + tests.add(new Object[]{new HETest(byteA, byte20, byte20, byte20, 20, true)}); + + return tests.toArray(new Object[][]{}); + } + + @Test(dataProvider = "data", enabled = true) + public void testHE(HETest test) { + + HeaderElement headerElement = new HeaderElement(1000, 0); + + // first test that if we add and then remove it, we have no data + headerElement.addBase(test.base, test.baseQual, test.insQual, test.delQual, test.MQ, minBaseQual, minMappingQual, test.isClip); + headerElement.addInsertionToTheRight(); + headerElement.removeBase(test.base, test.baseQual, test.insQual, test.delQual, test.MQ, minBaseQual, minMappingQual, test.isClip); + headerElement.removeInsertionToTheRight(); + testHeaderIsEmpty(headerElement); + + // now, test that the data was added as expected + for ( int i = 0; i < 10; i++ ) + headerElement.addBase(test.base, test.baseQual, test.insQual, test.delQual, test.MQ, minBaseQual, minMappingQual, test.isClip); + testHeaderData(headerElement, test); + + // test the insertion adding functionality + for ( int i = 0; i < 10; i++ ) + headerElement.addInsertionToTheRight(); + Assert.assertEquals(headerElement.numInsertionsToTheRight(), 10); + } + + private void testHeaderIsEmpty(final HeaderElement headerElement) { + Assert.assertFalse(headerElement.hasConsensusData()); + Assert.assertFalse(headerElement.hasFilteredData()); + Assert.assertFalse(headerElement.hasInsertionToTheRight()); + Assert.assertTrue(headerElement.isEmpty()); + Assert.assertEquals(headerElement.getRMS(), 0.0); + } + + private void testHeaderData(final HeaderElement headerElement, final HETest test) { + Assert.assertEquals(headerElement.getRMS(), (double)test.MQ); + Assert.assertEquals(headerElement.isVariantFromSoftClips(), test.isClip); + Assert.assertFalse(headerElement.isEmpty()); + Assert.assertFalse(headerElement.hasInsertionToTheRight()); + Assert.assertEquals(headerElement.hasConsensusData(), headerElement.basePassesFilters(test.baseQual, minBaseQual, test.MQ, minMappingQual)); + Assert.assertEquals(headerElement.hasFilteredData(), !headerElement.basePassesFilters(test.baseQual, minBaseQual, test.MQ, minMappingQual)); + Assert.assertFalse(headerElement.isVariantFromMismatches(0.05)); + Assert.assertEquals(headerElement.isVariant(0.05, 0.05), test.isClip); + } +} diff --git a/protected/java/test/org/broadinstitute/sting/gatk/walkers/compression/reducereads/SimpleGenomeLocUnitTest.java b/protected/java/test/org/broadinstitute/sting/gatk/walkers/compression/reducereads/SimpleGenomeLocUnitTest.java new file mode 100644 index 000000000..cbac7e3c1 --- /dev/null +++ b/protected/java/test/org/broadinstitute/sting/gatk/walkers/compression/reducereads/SimpleGenomeLocUnitTest.java @@ -0,0 +1,106 @@ +/* +* By downloading the PROGRAM you agree to the following terms of use: +* +* BROAD INSTITUTE - SOFTWARE LICENSE AGREEMENT - FOR ACADEMIC NON-COMMERCIAL RESEARCH PURPOSES ONLY +* +* This Agreement is made between the Broad Institute, Inc. with a principal address at 7 Cambridge Center, Cambridge, MA 02142 (BROAD) and the LICENSEE and is effective at the date the downloading is completed (EFFECTIVE DATE). +* +* WHEREAS, LICENSEE desires to license the PROGRAM, as defined hereinafter, and BROAD wishes to have this PROGRAM utilized in the public interest, subject only to the royalty-free, nonexclusive, nontransferable license rights of the United States Government pursuant to 48 CFR 52.227-14; and +* WHEREAS, LICENSEE desires to license the PROGRAM and BROAD desires to grant a license on the following terms and conditions. +* NOW, THEREFORE, in consideration of the promises and covenants made herein, the parties hereto agree as follows: +* +* 1. DEFINITIONS +* 1.1 PROGRAM shall mean copyright in the object code and source code known as GATK2 and related documentation, if any, as they exist on the EFFECTIVE DATE and can be downloaded from http://www.broadinstitute/GATK on the EFFECTIVE DATE. +* +* 2. LICENSE +* 2.1 Grant. Subject to the terms of this Agreement, BROAD hereby grants to LICENSEE, solely for academic non-commercial research purposes, a non-exclusive, non-transferable license to: (a) download, execute and display the PROGRAM and (b) create bug fixes and modify the PROGRAM. +* The LICENSEE may apply the PROGRAM in a pipeline to data owned by users other than the LICENSEE and provide these users the results of the PROGRAM provided LICENSEE does so for academic non-commercial purposes only. For clarification purposes, academic sponsored research is not a commercial use under the terms of this Agreement. +* 2.2 No Sublicensing or Additional Rights. LICENSEE shall not sublicense or distribute the PROGRAM, in whole or in part, without prior written permission from BROAD. LICENSEE shall ensure that all of its users agree to the terms of this Agreement. LICENSEE further agrees that it shall not put the PROGRAM on a network, server, or other similar technology that may be accessed by anyone other than the LICENSEE and its employees and users who have agreed to the terms of this agreement. +* 2.3 License Limitations. Nothing in this Agreement shall be construed to confer any rights upon LICENSEE by implication, estoppel, or otherwise to any computer software, trademark, intellectual property, or patent rights of BROAD, or of any other entity, except as expressly granted herein. LICENSEE agrees that the PROGRAM, in whole or part, shall not be used for any commercial purpose, including without limitation, as the basis of a commercial software or hardware product or to provide services. LICENSEE further agrees that the PROGRAM shall not be copied or otherwise adapted in order to circumvent the need for obtaining a license for use of the PROGRAM. +* +* 3. OWNERSHIP OF INTELLECTUAL PROPERTY +* LICENSEE acknowledges that title to the PROGRAM shall remain with BROAD. The PROGRAM is marked with the following BROAD copyright notice and notice of attribution to contributors. LICENSEE shall retain such notice on all copies. LICENSEE agrees to include appropriate attribution if any results obtained from use of the PROGRAM are included in any publication. +* Copyright 2012 Broad Institute, Inc. +* Notice of attribution: The GATK2 program was made available through the generosity of Medical and Population Genetics program at the Broad Institute, Inc. +* LICENSEE shall not use any trademark or trade name of BROAD, or any variation, adaptation, or abbreviation, of such marks or trade names, or any names of officers, faculty, students, employees, or agents of BROAD except as states above for attribution purposes. +* +* 4. INDEMNIFICATION +* LICENSEE shall indemnify, defend, and hold harmless BROAD, and their respective officers, faculty, students, employees, associated investigators and agents, and their respective successors, heirs and assigns, (Indemnitees), against any liability, damage, loss, or expense (including reasonable attorneys fees and expenses) incurred by or imposed upon any of the Indemnitees in connection with any claims, suits, actions, demands or judgments arising out of any theory of liability (including, without limitation, actions in the form of tort, warranty, or strict liability and regardless of whether such action has any factual basis) pursuant to any right or license granted under this Agreement. +* +* 5. NO REPRESENTATIONS OR WARRANTIES +* THE PROGRAM IS DELIVERED AS IS. BROAD MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE PROGRAM OR THE COPYRIGHT, EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, WHETHER OR NOT DISCOVERABLE. BROAD EXTENDS NO WARRANTIES OF ANY KIND AS TO PROGRAM CONFORMITY WITH WHATEVER USER MANUALS OR OTHER LITERATURE MAY BE ISSUED FROM TIME TO TIME. +* IN NO EVENT SHALL BROAD OR ITS RESPECTIVE DIRECTORS, OFFICERS, EMPLOYEES, AFFILIATED INVESTIGATORS AND AFFILIATES BE LIABLE FOR INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, INCLUDING, WITHOUT LIMITATION, ECONOMIC DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER BROAD SHALL BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT SHALL KNOW OF THE POSSIBILITY OF THE FOREGOING. +* +* 6. ASSIGNMENT +* This Agreement is personal to LICENSEE and any rights or obligations assigned by LICENSEE without the prior written consent of BROAD shall be null and void. +* +* 7. MISCELLANEOUS +* 7.1 Export Control. LICENSEE gives assurance that it will comply with all United States export control laws and regulations controlling the export of the PROGRAM, including, without limitation, all Export Administration Regulations of the United States Department of Commerce. Among other things, these laws and regulations prohibit, or require a license for, the export of certain types of software to specified countries. +* 7.2 Termination. LICENSEE shall have the right to terminate this Agreement for any reason upon prior written notice to BROAD. If LICENSEE breaches any provision hereunder, and fails to cure such breach within thirty (30) days, BROAD may terminate this Agreement immediately. Upon termination, LICENSEE shall provide BROAD with written assurance that the original and all copies of the PROGRAM have been destroyed, except that, upon prior written authorization from BROAD, LICENSEE may retain a copy for archive purposes. +* 7.3 Survival. The following provisions shall survive the expiration or termination of this Agreement: Articles 1, 3, 4, 5 and Sections 2.2, 2.3, 7.3, and 7.4. +* 7.4 Notice. Any notices under this Agreement shall be in writing, shall specifically refer to this Agreement, and shall be sent by hand, recognized national overnight courier, confirmed facsimile transmission, confirmed electronic mail, or registered or certified mail, postage prepaid, return receipt requested. All notices under this Agreement shall be deemed effective upon receipt. +* 7.5 Amendment and Waiver; Entire Agreement. This Agreement may be amended, supplemented, or otherwise modified only by means of a written instrument signed by all parties. Any waiver of any rights or failure to act in a specific instance shall relate only to such instance and shall not be construed as an agreement to waive any rights or fail to act in any other instance, whether or not similar. This Agreement constitutes the entire agreement among the parties with respect to its subject matter and supersedes prior agreements or understandings between the parties relating to its subject matter. +* 7.6 Binding Effect; Headings. This Agreement shall be binding upon and inure to the benefit of the parties and their respective permitted successors and assigns. All headings are for convenience only and shall not affect the meaning of any provision of this Agreement. +* 7.7 Governing Law. This Agreement shall be construed, governed, interpreted and applied in accordance with the internal laws of the Commonwealth of Massachusetts, U.S.A., without regard to conflict of laws principles. +*/ + +package org.broadinstitute.sting.gatk.walkers.compression.reducereads; + + +import org.broadinstitute.sting.BaseTest; +import org.broadinstitute.sting.utils.exceptions.ReviewedStingException; +import org.testng.Assert; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.util.*; + +public class SimpleGenomeLocUnitTest extends BaseTest { + + private static final SimpleGenomeLoc loc1 = new SimpleGenomeLoc("1", 0, 10, 20, false); + private static final SimpleGenomeLoc loc2 = new SimpleGenomeLoc("1", 0, 21, 30, false); + private static final SimpleGenomeLoc loc3 = new SimpleGenomeLoc("1", 0, 31, 40, false); + + private class SGLTest { + public List locs; + + private SGLTest(final List locs) { + this.locs = locs; + } + } + + @DataProvider(name = "SGLtest") + public Object[][] createFindVariantRegionsData() { + List tests = new ArrayList(); + + tests.add(new Object[]{new SGLTest(Arrays.asList(loc1))}); + tests.add(new Object[]{new SGLTest(Arrays.asList(loc1, loc2))}); + tests.add(new Object[]{new SGLTest(Arrays.asList(loc1, loc2, loc3))}); + + return tests.toArray(new Object[][]{}); + } + + @Test(dataProvider = "SGLtest", enabled = true) + public void testSimpleGenomeLoc(SGLTest test) { + testMerge(test.locs); + } + + @Test(expectedExceptions = ReviewedStingException.class) + public void testNotContiguousLocs() { + final List locs = new ArrayList(1); + locs.add(loc1); + locs.add(loc3); + testMerge(locs); + } + + private void testMerge(final List locs) { + SimpleGenomeLoc result1 = locs.get(0); + for ( int i = 1; i < locs.size(); i++ ) + result1 = SimpleGenomeLoc.merge(result1, locs.get(i)); + + SimpleGenomeLoc result2 = SimpleGenomeLoc.merge(new TreeSet(locs)); + Assert.assertEquals(result1, result2); + Assert.assertEquals(result1.getStart(), locs.get(0).getStart()); + Assert.assertEquals(result1.getStop(), locs.get(locs.size() - 1).getStop()); + } +} diff --git a/protected/java/test/org/broadinstitute/sting/gatk/walkers/compression/reducereads/SlidingWindowUnitTest.java b/protected/java/test/org/broadinstitute/sting/gatk/walkers/compression/reducereads/SlidingWindowUnitTest.java new file mode 100644 index 000000000..cfb8c53b4 --- /dev/null +++ b/protected/java/test/org/broadinstitute/sting/gatk/walkers/compression/reducereads/SlidingWindowUnitTest.java @@ -0,0 +1,227 @@ +/* +* Copyright (c) 2012 The Broad Institute +* +* Permission is hereby granted, free of charge, to any person +* obtaining a copy of this software and associated documentation +* files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, +* copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following +* conditions: +* +* The above copyright notice and this permission notice shall be +* included in all copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR +* THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +package org.broadinstitute.sting.gatk.walkers.compression.reducereads; + +import net.sf.samtools.SAMFileHeader; +import net.sf.samtools.SAMReadGroupRecord; +import net.sf.samtools.SAMRecord; +import org.broadinstitute.sting.BaseTest; +import org.broadinstitute.sting.gatk.GenomeAnalysisEngine; +import org.broadinstitute.sting.utils.sam.ArtificialSAMUtils; +import org.broadinstitute.sting.utils.sam.ArtificialSingleSampleReadStream; +import org.broadinstitute.sting.utils.sam.ArtificialSingleSampleReadStreamAnalyzer; +import org.testng.Assert; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class SlidingWindowUnitTest extends BaseTest { + + ////////////////////////////////////////////////////////////////////////////////////// + //// This section tests the findVariantRegions() method and related functionality //// + ////////////////////////////////////////////////////////////////////////////////////// + + private static final int variantRegionLength = 1000; + private static final int globalStartPosition = 1000000; + private static final SimpleGenomeLoc loc90to95 = new SimpleGenomeLoc("1", 0, 1000090, 1000095, false); + private static final SimpleGenomeLoc loc96to99 = new SimpleGenomeLoc("1", 0, 1000096, 1000099, false); + private static final SimpleGenomeLoc loc100to110 = new SimpleGenomeLoc("1", 0, 1000100, 1000110, false); + private static final SimpleGenomeLoc loc999 = new SimpleGenomeLoc("1", 0, 1000999, 1000999, false); + + private class FindVariantRegionsTest { + public List locs, expectedResult; + public boolean[] variantRegionBitset; + + private FindVariantRegionsTest(final List locs) { + this.locs = locs; + this.expectedResult = locs; + variantRegionBitset = createBitset(locs); + } + + private FindVariantRegionsTest(final List locs, final List expectedResult) { + this.locs = locs; + this.expectedResult = expectedResult; + variantRegionBitset = createBitset(locs); + } + } + + private static boolean[] createBitset(final List locs) { + boolean[] variantRegionBitset = new boolean[variantRegionLength]; + for ( SimpleGenomeLoc loc : locs ) { + final int stop = loc.getStop() - globalStartPosition; + for ( int i = loc.getStart() - globalStartPosition; i <= stop; i++ ) + variantRegionBitset[i] = true; + } + return variantRegionBitset; + } + + @DataProvider(name = "findVariantRegions") + public Object[][] createFindVariantRegionsData() { + List tests = new ArrayList(); + + tests.add(new Object[]{new FindVariantRegionsTest(Arrays.asList(loc90to95))}); + tests.add(new Object[]{new FindVariantRegionsTest(Arrays.asList(loc90to95, loc100to110))}); + tests.add(new Object[]{new FindVariantRegionsTest(Arrays.asList(loc90to95, loc96to99, loc100to110), Arrays.asList(new SimpleGenomeLoc("1", 0, 1000090, 1000110, false)))}); + tests.add(new Object[]{new FindVariantRegionsTest(Arrays.asList(loc90to95, loc999))}); + tests.add(new Object[]{new FindVariantRegionsTest(Arrays.asList(loc999))}); + + return tests.toArray(new Object[][]{}); + } + + @Test(dataProvider = "findVariantRegions", enabled = true) + public void testFindVariantRegions(FindVariantRegionsTest test) { + final SlidingWindow slidingWindow = new SlidingWindow("1", 0, globalStartPosition); + final CompressionStash locs = slidingWindow.findVariantRegions(0, variantRegionLength, test.variantRegionBitset, true); + int index = 0; + for ( final SimpleGenomeLoc loc : locs ) { + Assert.assertTrue(loc.equals(test.expectedResult.get(index++))); + } + } + + @Test(enabled = true) + public void testNoClosingRegions() { + final SlidingWindow slidingWindow = new SlidingWindow("1", 0, globalStartPosition); + final CompressionStash locs = slidingWindow.findVariantRegions(0, variantRegionLength, createBitset(Arrays.asList(loc90to95, loc999)), false); + Assert.assertEquals(locs.size(), 1); + Assert.assertEquals(locs.iterator().next(), loc90to95); + } + + + + + + + + + + + + + + /* + + private static class DownsamplingReadsIteratorTest extends TestDataProvider { + private DownsamplingReadsIterator downsamplingIter; + private int targetCoverage; + private ArtificialSingleSampleReadStream stream; + private ArtificialSingleSampleReadStreamAnalyzer streamAnalyzer; + + public DownsamplingReadsIteratorTest( ArtificialSingleSampleReadStream stream, int targetCoverage ) { + super(DownsamplingReadsIteratorTest.class); + + this.stream = stream; + this.targetCoverage = targetCoverage; + + setName(String.format("%s: targetCoverage=%d numContigs=%d stacksPerContig=%d readsPerStack=%d-%d distanceBetweenStacks=%d-%d readLength=%d-%d unmappedReads=%d", + getClass().getSimpleName(), + targetCoverage, + stream.getNumContigs(), + stream.getNumStacksPerContig(), + stream.getMinReadsPerStack(), + stream.getMaxReadsPerStack(), + stream.getMinDistanceBetweenStacks(), + stream.getMaxDistanceBetweenStacks(), + stream.getMinReadLength(), + stream.getMaxReadLength(), + stream.getNumUnmappedReads())); + } + + public void run() { + streamAnalyzer = new PositionallyDownsampledArtificialSingleSampleReadStreamAnalyzer(stream, targetCoverage); + downsamplingIter = new DownsamplingReadsIterator(stream.getStingSAMIterator(), new SimplePositionalDownsampler(targetCoverage)); + + streamAnalyzer.analyze(downsamplingIter); + + // Check whether the observed properties of the downsampled stream are what they should be + streamAnalyzer.validate(); + + // Allow memory used by this test to be reclaimed + stream = null; + streamAnalyzer = null; + downsamplingIter = null; + } + } + + @DataProvider(name = "DownsamplingReadsIteratorTestDataProvider") + public Object[][] createDownsamplingReadsIteratorTests() { + SAMFileHeader header = ArtificialSAMUtils.createArtificialSamHeader(5, 1, 10000); + String readGroupID = "testReadGroup"; + SAMReadGroupRecord readGroup = new SAMReadGroupRecord(readGroupID); + readGroup.setSample("testSample"); + header.addReadGroup(readGroup); + + // Values that don't vary across tests + int targetCoverage = 10; + int minReadLength = 50; + int maxReadLength = 100; + int minDistanceBetweenStacks = 1; + int maxDistanceBetweenStacks = maxReadLength + 1; + + GenomeAnalysisEngine.resetRandomGenerator(); + + // brute force testing! + for ( int numContigs : Arrays.asList(1, 2, 5) ) { + for ( int stacksPerContig : Arrays.asList(1, 2, 10) ) { + for ( int minReadsPerStack : Arrays.asList(1, targetCoverage / 2, targetCoverage, targetCoverage - 1, targetCoverage + 1, targetCoverage * 2) ) { + for ( int maxReadsPerStack : Arrays.asList(1, targetCoverage / 2, targetCoverage, targetCoverage - 1, targetCoverage + 1, targetCoverage * 2) ) { + for ( int numUnmappedReads : Arrays.asList(0, 1, targetCoverage, targetCoverage * 2) ) { + // Only interested in sane read stream configurations here + if ( minReadsPerStack <= maxReadsPerStack ) { + new DownsamplingReadsIteratorTest(new ArtificialSingleSampleReadStream(header, + readGroupID, + numContigs, + stacksPerContig, + minReadsPerStack, + maxReadsPerStack, + minDistanceBetweenStacks, + maxDistanceBetweenStacks, + minReadLength, + maxReadLength, + numUnmappedReads), + targetCoverage); + } + } + } + } + } + } + + return DownsamplingReadsIteratorTest.getTests(DownsamplingReadsIteratorTest.class); + } + + @Test(dataProvider = "DownsamplingReadsIteratorTestDataProvider") + public void runDownsamplingReadsIteratorTest( DownsamplingReadsIteratorTest test ) { + logger.warn("Running test: " + test); + + GenomeAnalysisEngine.resetRandomGenerator(); + test.run(); + } + + */ +}