diff --git a/licensing/private_license.txt b/licensing/private_license.txt
deleted file mode 100644
index 2f40c5089..000000000
--- a/licensing/private_license.txt
+++ /dev/null
@@ -1,43 +0,0 @@
- 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.
diff --git a/licensing/private_license.txt b/licensing/private_license.txt
new file mode 120000
index 000000000..d83474e7a
--- /dev/null
+++ b/licensing/private_license.txt
@@ -0,0 +1 @@
+protected_license.txt
\ No newline at end of file
diff --git a/protected/java/src/org/broadinstitute/sting/gatk/walkers/diagnostics/targets/BaseCoverageDistribution.java b/protected/java/src/org/broadinstitute/sting/gatk/walkers/diagnostics/targets/BaseCoverageDistribution.java
index 281c1c55d..2b79836b9 100644
--- a/protected/java/src/org/broadinstitute/sting/gatk/walkers/diagnostics/targets/BaseCoverageDistribution.java
+++ b/protected/java/src/org/broadinstitute/sting/gatk/walkers/diagnostics/targets/BaseCoverageDistribution.java
@@ -46,59 +46,255 @@
package org.broadinstitute.sting.gatk.walkers.diagnostics.targets;
+import org.broadinstitute.sting.commandline.Argument;
import org.broadinstitute.sting.commandline.Output;
import org.broadinstitute.sting.gatk.contexts.AlignmentContext;
import org.broadinstitute.sting.gatk.contexts.ReferenceContext;
import org.broadinstitute.sting.gatk.refdata.RefMetaDataTracker;
import org.broadinstitute.sting.gatk.report.GATKReport;
-import org.broadinstitute.sting.gatk.walkers.By;
-import org.broadinstitute.sting.gatk.walkers.DataSource;
import org.broadinstitute.sting.gatk.walkers.LocusWalker;
+import org.broadinstitute.sting.utils.GenomeLoc;
+import org.broadinstitute.sting.utils.GenomeLocParser;
import java.io.PrintStream;
+import java.util.ArrayList;
import java.util.HashMap;
+import java.util.LinkedList;
import java.util.Map;
/**
+ * Simple walker to plot the coverage distribution per base.
+ *
+ *
+ * Features of this walker:
+ *
includes a smart counting of uncovered bases without visiting the uncovered loci.
+ * includes reads with deletions in the loci (optionally can be turned off)
+ *
+ *
+ * Input
+ *
+ * The BAM file and an optional interval list (works for WGS as well)
+ *
+ *
+ * Output
+ *
+ * A GATK Report with the coverage distribution per base
+ *
+ *
+ * Examples
+ *
+ * java -Xmx4g -jar GenomeAnalysisTK.jar \
+ * -R ref.fasta \
+ * -T BaseCoverageDistribution \
+ * -I myData.bam \
+ * -L interesting.intervals \
+ * -fd \
+ * -o report.grp
+ *
* User: carneiro
* Date: 1/27/13
* Time: 11:16 AM
*/
-@By(DataSource.REFERENCE)
-public class BaseCoverageDistribution extends LocusWalker> {
- @Output(required = true)
+public class BaseCoverageDistribution extends LocusWalker, Map>> {
+ /**
+ * The output GATK Report table
+ */
+ @Output(required = true, doc = "The output GATK Report table")
private PrintStream out;
+ /**
+ * Whether or not a deletion should be counted towards the coverage of a site
+ */
+ @Argument(required = false, shortName="del", fullName = "include_deletions", doc ="whether or not to include reads with deletions on the loci in the pileup")
+ private boolean includeDeletions = true;
+
+ /**
+ * Whether or not to calculate and output a filtered coverage distribution. Bases will be filtered according to the
+ * minimum_mapping_quality and minimum_base_quality parameters below.
+ */
+ @Argument(required = false, shortName="fd", fullName = "filtered_distribution", doc ="calculate and report the filtered coverage distribution of bases")
+ private boolean calculateFilteredDistribution = false;
+
+ /**
+ * The minimum mapping quality a read must have to be counted towards the filtered coverage of a site
+ */
+ @Argument(required = false, shortName="mmq", fullName = "minimum_mapping_quality", doc ="minimum mapping quality of a read to include it in the filtered coverage distribution")
+ private byte minMappingQuality = 20;
+
+ /**
+ * The minimum base quality a base must have to be counted towards the filtered coverage of a site
+ */
+ @Argument(required = false, shortName="mbq", fullName = "minimum_base_quality", doc ="minimum base quality of a base to include it in the filtered coverage distribution")
+ private byte minBaseQuality = 17;
+
+ private GenomeLoc previousLocus = null;
+ private long uncoveredBases = 0L;
+ private final LinkedList intervalList = new LinkedList();
+
@Override
public boolean includeReadsWithDeletionAtLoci() {
- return true;
+ return includeDeletions;
}
@Override
- public Integer map(RefMetaDataTracker tracker, ReferenceContext ref, AlignmentContext context) {
- return context.getBasePileup().getReads().size(); // I want the reads instead of the base pileup because I want to count deletions.
+ public void initialize() {
+ if (getToolkit().getIntervals() != null)
+ intervalList.addAll(getToolkit().getIntervals()); // if the user provided intervals, keep track of them for uncovered bases calculation
}
@Override
- public Map reduceInit() {
- return new HashMap(10000);
+ public ArrayList map(RefMetaDataTracker tracker, ReferenceContext ref, AlignmentContext context) {
+ ArrayList result = new ArrayList(2);
+ GenomeLoc currentLocus = ref.getLocus();
+ tallyUncoveredBases(currentLocus);
+ previousLocus = currentLocus;
+ result.add(context.getBasePileup().getReads().size()); // I want the reads instead of the base pileup because I want to count deletions.
+ if (calculateFilteredDistribution)
+ result.add(context.getBasePileup().getBaseAndMappingFilteredPileup(minBaseQuality, minMappingQuality).getReads().size()); // filtered pileup
+ else {
+ result.add(result.get(0)); // repeat the same value as the unfiltered pileup if filters are not on
+ }
+ return result;
}
@Override
- public Map reduce(Integer value, Map sum) {
- Long curr = sum.get(value);
- if (curr == null)
- curr = 0L;
- sum.put(value, curr + 1);
+ public Map> reduceInit() {
+ return new HashMap>(10000);
+ }
+
+ @Override
+ public Map> reduce(ArrayList value, Map> sum) {
+ final int unfilteredCoverage = value.get(0);
+ final int filteredCoverage = value.get(1);
+ incrementSumArray(sum, unfilteredCoverage, 0);
+ incrementSumArray(sum, filteredCoverage, 1);
return sum;
}
@Override
- public void onTraversalDone(Map result) {
- GATKReport report = GATKReport.newSimpleReport("BaseCoverageDistribution", "Coverage", "Count");
- for (Map.Entry entry : result.entrySet()) {
- report.addRow(entry.getKey(), entry.getValue());
+ public void onTraversalDone(Map> result) {
+ tallyUncoveredBasesTillEndOfTraversal();
+ GATKReport report;
+
+ if (calculateFilteredDistribution) {
+ report = GATKReport.newSimpleReport("BaseCoverageDistribution", "Coverage", "Count", "Filtered");
+ } else {
+ report = GATKReport.newSimpleReport("BaseCoverageDistribution", "Coverage", "Count");
+ report.addRow(0, uncoveredBases); // preemptively add the uncovered bases row (since they'll never exist in the Map)
+ }
+
+ for (Map.Entry> entry : result.entrySet()) {
+ final ArrayList values = entry.getValue();
+ final int coverage = entry.getKey();
+ if (calculateFilteredDistribution) {
+ if (coverage == 0) { // special case for the uncovered bases. The filtered pileups may have an entry, but the unfiltered ones won't.
+ report.addRow(coverage, uncoveredBases, uncoveredBases + values.get(1));
+ } else {
+ report.addRow(coverage, values.get(0), values.get(1));
+ }
+ } else {
+ report.addRow(coverage, values.get(0));
+ }
+ }
+ // In case the filtered distribution never had a pileup filtered down to zero coverage, output the overall uncovered bases for both
+ if (calculateFilteredDistribution && !result.containsKey(0)) {
+ report.addRow(0, uncoveredBases, uncoveredBases);
}
report.print(out);
}
-}
+
+ /**
+ * Initializes the ArrayList if needed. Returns the initialized element (or previously initialized)
+ * this method is used directly by the incrementSumArray.
+ *
+ * @param sum the map
+ * @param coverage the key to the map to extract the array list
+ * @return if the ArrayList exists, return it. Otherwise, initialize it with 0 counters.
+ */
+ private ArrayList initializeSumArray(final Map> sum, final int coverage) {
+ ArrayList curr = sum.get(coverage);
+ if (curr == null) {
+ curr = new ArrayList(2);
+ curr.add(0L); // number of bases with this unfiltered coverage
+ curr.add(0L); // number of bases with this filtered coverage
+ sum.put(coverage, curr);
+ }
+ return curr;
+ }
+
+ /**
+ * Increments the counter for the given arrayindex (type of coverage : filtered or unfiltered) initializing if necessary
+ *
+ * @param sum the hash
+ * @param coverage the hash key
+ * @param arrayIndex which distribution to increment, 0 for unfiltered, 1 for filtered.
+ */
+ private void incrementSumArray(final Map> sum, final int coverage, final int arrayIndex) {
+ final ArrayList currentTally = initializeSumArray(sum, coverage);
+ currentTally.set(arrayIndex, currentTally.get(arrayIndex) + 1);
+ }
+
+ /**
+ * Counts all the uncovered loci after the end of traversal.
+ *
+ * - Modifies the global variable uncoveredBases
+ * - Uses global variables: intervalList and previousLocus
+ *
+ * takes into account that the traversal may have been due over a set of intervals, or over the whole genome.
+ */
+ private void tallyUncoveredBasesTillEndOfTraversal() {
+ GenomeLocParser parser = getToolkit().getGenomeLocParser();
+ GenomeLoc lastLocus;
+ if (intervalList.isEmpty()) { // whole genome, add up all contigs past previousLocus
+ final int lastContigIndex = getToolkit().getSAMFileHeader().getSequenceDictionary().size() - 1;
+ final int lastContigLength = getToolkit().getSAMFileHeader().getSequence(lastContigIndex).getSequenceLength();
+ final String lastContigName = getToolkit().getSAMFileHeader().getSequence(lastContigIndex).getSequenceName();
+ lastLocus = parser.createGenomeLoc(lastContigName, lastContigIndex, lastContigLength, lastContigLength);
+ } else {
+ GenomeLoc lastInterval = intervalList.getLast();
+ lastLocus = parser.createGenomeLoc(lastInterval.getContig(), lastInterval.getContigIndex(), lastInterval.getStop(), lastInterval.getStop());
+ }
+ tallyUncoveredBases(lastLocus);
+ }
+
+ /**
+ * Counts all the uncovered loci that have been skipped since the last visited locus. This method allows coverage
+ * tools to run with @By(DataSource.READS) instead of @By(DataSource.REFERENCE), while still accurately calculating
+ * uncovered bases
+ *
+ * //todo -- make this a generic capability of DepthOfCoverage and DiagnoseTargets
+ *
+ * - Modifies the global variable uncoveredBases
+ * - Uses global variables: intervalList and previousLocus
+ *
+ * takes into account that the traversal may have been due over a set of intervals, or over the whole genome.
+ *
+ * @param currentLocus the locus we are visiting right now
+ */
+ private void tallyUncoveredBases(GenomeLoc currentLocus) {
+ long distance = 0;
+ if (previousLocus == null) { // first base visited
+ GenomeLocParser parser = getToolkit().getGenomeLocParser();
+ if (intervalList.isEmpty()) { // if this is whole genome (no intervals requested), add what we missed.
+ final GenomeLoc zeroLoc = parser.createGenomeLoc(getToolkit().getSAMFileHeader().getSequence(0).getSequenceName(), 0, 1, 1);
+ distance += currentLocus.distanceAcrossContigs(zeroLoc, getToolkit().getSAMFileHeader());
+ } else { // if we are running on an interval list, add all intervals before the current locus to the uncovered bases counter
+ while (!intervalList.peek().containsP(currentLocus)) {
+ GenomeLoc interval = intervalList.removeFirst();
+ distance += interval.size();
+ }
+ distance += currentLocus.getStart() - intervalList.peek().getStart(); // now this is the interval that contains the current locus. Discount the bases from the beginning.
+ }
+ } else {
+ final GenomeLoc previousInterval = intervalList.peekFirst(); // peekFirst returns null if interval list is empty (WGS).
+ distance = currentLocus.distanceAcrossContigs(previousLocus, getToolkit().getSAMFileHeader()) - 1;
+ if (previousInterval != null && !previousInterval.containsP(currentLocus)) {
+ intervalList.removeFirst(); // we're done with the previous interval
+ final GenomeLoc currentInterval = intervalList.peekFirst();
+ distance -= currentInterval.distanceAcrossContigs(previousInterval, getToolkit().getSAMFileHeader()) - 1;
+ }
+ }
+
+ uncoveredBases += distance;
+ }
+}
\ No newline at end of file
diff --git a/protected/java/test/org/broadinstitute/sting/gatk/walkers/diagnostics/targets/BaseCoverageDistributionIntegrationTest.java b/protected/java/test/org/broadinstitute/sting/gatk/walkers/diagnostics/targets/BaseCoverageDistributionIntegrationTest.java
new file mode 100644
index 000000000..53153c100
--- /dev/null
+++ b/protected/java/test/org/broadinstitute/sting/gatk/walkers/diagnostics/targets/BaseCoverageDistributionIntegrationTest.java
@@ -0,0 +1,90 @@
+/*
+* 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.diagnostics.targets;
+
+import org.broadinstitute.sting.WalkerTest;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import java.util.Arrays;
+
+/**
+ * @author Mauricio Carneiro
+ * @since 2/6/13
+ */
+public class BaseCoverageDistributionIntegrationTest extends WalkerTest {
+ final static String REF = hg18Reference;
+ final String bam = validationDataLocation + "small_bam_for_countloci.withRG.bam";
+
+ @DataProvider(name = "BasicArguments")
+ public Object[][] basicArgumentsDataProvider() {
+ return new Object[][] {
+ // Tests simple counting on one interval with everything in the same contig including tallying of uncovered bases.
+ {"testSingleInterval ", "-L chr1:90000-100000", "45368696dc008d1a07fb2b05fbafd1f4"},
+ // Tests specially the tallying of uncovered bases across multiple intervals. Makes sure it's only adding the bases present in the intervals requested.
+ {"testMultipleIntervals ", "-L chr1:10-20 -L chr1:40-100 -L chr1:10,000-11,000 -L chr1:40,000-60,000 -L chr1:76,000-99,000 ", "45dafe59e5e54451b88c914d6ecbddc6"},
+ // Tests adding the entire genome around every covered base as uncovered. Especially tests the tally in the beginning and end of the run, adding up all chromosomes not visited (this test file only has reads on chr1).
+ {"testNoIntervals ", "", "c399f780f0b7da6be2614d837c368d1c"},
+
+ // the following three tests are equivalent but now include the filtered distribution option. These tests are aimed at the filtered distribution output.
+ {"testFilteredSingleInterval ", "-fd -L chr1:90000-100000", "7017cf191bf54e85111972a882e1d5fa"},
+ {"testFilteredMultipleIntervals ", "-fd -L chr1:10-20 -L chr1:40-100 -L chr1:10,000-11,000 -L chr1:40,000-60,000 -L chr1:76,000-99,000 ", "75d11cc02210676d6c19939fb0b9ab2e"},
+ {"testFilteredNoIntervals ", "-fd ", "e7abfa6c7be493de4557a64f66688148"},
+ };
+ }
+
+ @Test(dataProvider = "BasicArguments", enabled = true)
+ private void BaseCoverageDistributionTest(String testName, String args, String md5) {
+ String base = String.format("-T BaseCoverageDistribution -R %s -I %s ", REF, bam) + " -o %s ";
+ WalkerTestSpec spec = new WalkerTestSpec(base + args, Arrays.asList(md5));
+ executeTest(testName, spec);
+ }
+
+
+
+
+}
diff --git a/public/java/src/org/broadinstitute/sting/utils/GenomeLoc.java b/public/java/src/org/broadinstitute/sting/utils/GenomeLoc.java
index 0a271b64c..2a8a271e7 100644
--- a/public/java/src/org/broadinstitute/sting/utils/GenomeLoc.java
+++ b/public/java/src/org/broadinstitute/sting/utils/GenomeLoc.java
@@ -27,6 +27,7 @@ package org.broadinstitute.sting.utils;
import com.google.java.contract.Ensures;
import com.google.java.contract.Requires;
+import net.sf.samtools.SAMFileHeader;
import org.broadinstitute.sting.utils.exceptions.ReviewedStingException;
import java.io.Serializable;
@@ -623,4 +624,37 @@ public class GenomeLoc implements Comparable, Serializable, HasGenome
return result;
}
+
+ /**
+ * Calculates the distance between two genomeLocs across contigs (if necessary).
+ *
+ * Returns minDistance(other) if in same contig.
+ * Works with intervals!
+ * Uses the SAMFileHeader to extract the size of the contigs and follows the order in the dictionary.
+ *
+ * @param other the genome loc to compare to
+ * @param samFileHeader the contig information
+ * @return the sum of all the bases in between the genomeLocs, including entire contigs
+ */
+ public long distanceAcrossContigs(GenomeLoc other, SAMFileHeader samFileHeader) {
+ if (onSameContig(other))
+ return minDistance(other);
+
+ // add the distance from the first genomeLoc to the end of it's contig and the distance from the
+ // second genomeLoc to the beginning of it's contig.
+ long distance = 0;
+ if (contigIndex < other.contigIndex) {
+ distance += samFileHeader.getSequence(contigIndex).getSequenceLength() - stop;
+ distance += other.start;
+ } else {
+ distance += samFileHeader.getSequence(other.contigIndex).getSequenceLength() - other.stop;
+ distance += start;
+ }
+
+ // add any contig (in its entirety) in between the two genomeLocs
+ for (int i=Math.min(this.contigIndex, other.contigIndex) + 1; i < Math.max(this.contigIndex, other.contigIndex); i++) {
+ distance += samFileHeader.getSequence(i).getSequenceLength();
+ }
+ return distance;
+ }
}
diff --git a/public/java/test/org/broadinstitute/sting/utils/GenomeLocUnitTest.java b/public/java/test/org/broadinstitute/sting/utils/GenomeLocUnitTest.java
index ed91114a4..c3ab22b4c 100644
--- a/public/java/test/org/broadinstitute/sting/utils/GenomeLocUnitTest.java
+++ b/public/java/test/org/broadinstitute/sting/utils/GenomeLocUnitTest.java
@@ -29,23 +29,23 @@ package org.broadinstitute.sting.utils;
// the imports for unit testing.
+import net.sf.picard.reference.ReferenceSequenceFile;
+import net.sf.samtools.SAMFileHeader;
+import org.broadinstitute.sting.BaseTest;
import org.broadinstitute.sting.utils.exceptions.ReviewedStingException;
+import org.broadinstitute.sting.utils.fasta.CachingIndexedFastaSequenceFile;
import org.broadinstitute.sting.utils.interval.IntervalMergingRule;
import org.broadinstitute.sting.utils.interval.IntervalUtils;
+import org.broadinstitute.sting.utils.sam.ArtificialSAMUtils;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
-import org.broadinstitute.sting.BaseTest;
-import org.broadinstitute.sting.utils.fasta.CachingIndexedFastaSequenceFile;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
-import net.sf.picard.reference.ReferenceSequenceFile;
-import net.sf.picard.reference.IndexedFastaSequenceFile;
-
/**
* Basic unit test for GenomeLoc
*/
@@ -343,4 +343,44 @@ public class GenomeLocUnitTest extends BaseTest {
Assert.assertEquals(result1.getStop(), locs.get(locs.size() - 1).getStop());
}
+ // -------------------------------------------------------------------------------------
+ //
+ // testing distance functionality
+ //
+ // -------------------------------------------------------------------------------------
+
+ @Test(enabled=true)
+ public void testDistanceAcrossContigs() {
+ final int chrSize = 1000;
+ SAMFileHeader header = ArtificialSAMUtils.createArtificialSamHeader(10, 0, chrSize);
+ GenomeLocParser parser = new GenomeLocParser(header.getSequenceDictionary());
+ GenomeLoc loc1 = parser.createGenomeLoc("chr3", 500); // to check regular case
+ GenomeLoc loc2 = parser.createGenomeLoc("chr7", 200); // to check regular case
+ GenomeLoc loc3 = parser.createGenomeLoc("chr0", 1); // to check corner case
+ GenomeLoc loc4 = parser.createGenomeLoc("chr9", 1000);// to check corner case
+ GenomeLoc loc5 = parser.createGenomeLoc("chr7", 500); // to make sure it does the right thing when in the same chromosome
+
+ GenomeLoc loc6 = parser.createGenomeLoc("chr7", 200, 300);
+ GenomeLoc loc7 = parser.createGenomeLoc("chr7", 500, 600);
+ GenomeLoc loc8 = parser.createGenomeLoc("chr9", 500, 600);
+
+ // Locus comparisons
+ Assert.assertEquals(loc1.distanceAcrossContigs(loc2, header), 3*chrSize + chrSize-loc1.getStop() + loc2.getStart()); // simple case, smaller first
+ Assert.assertEquals(loc2.distanceAcrossContigs(loc1, header), 3*chrSize + chrSize-loc1.getStop() + loc2.getStart()); // simple case, bigger first
+
+ Assert.assertEquals(loc3.distanceAcrossContigs(loc4, header), 10*chrSize - 1); // corner case, smaller first
+ Assert.assertEquals(loc4.distanceAcrossContigs(loc3, header), 10*chrSize - 1); // corner case, bigger first
+
+ Assert.assertEquals(loc2.distanceAcrossContigs(loc5, header), 300); // same contig, smaller first
+ Assert.assertEquals(loc5.distanceAcrossContigs(loc2, header), 300); // same contig, bigger first
+
+ // Interval comparisons
+ Assert.assertEquals(loc6.distanceAcrossContigs(loc7, header), 200); // same contig, smaller first
+ Assert.assertEquals(loc7.distanceAcrossContigs(loc6, header), 200); // same contig, bigger first
+
+ Assert.assertEquals(loc7.distanceAcrossContigs(loc8, header), chrSize + chrSize-loc7.stop + loc8.getStart()); // across contigs, smaller first
+ Assert.assertEquals(loc8.distanceAcrossContigs(loc7, header), chrSize + chrSize-loc7.stop + loc8.getStart()); // across congits, bigger first
+
+ }
+
}