From 5f49c95cc1f167ea9f4b5f4909848cffa54173b5 Mon Sep 17 00:00:00 2001 From: Mauricio Carneiro Date: Thu, 31 Jan 2013 11:51:13 -0500 Subject: [PATCH] Added distance across contigs calculation to GenomeLocs -- distance across contigs is calculated given a sequence dictionary (from SAMFileHeader) -- unit test added GSATDG-45 --- licensing/private_license.txt | 44 +-------- .../targets/BaseCoverageDistribution.java | 67 ++++++++++++- ...seCoverageDistributionIntegrationTest.java | 97 +++++++++++++++++++ .../broadinstitute/sting/utils/GenomeLoc.java | 34 +++++++ .../sting/utils/GenomeLocUnitTest.java | 50 +++++++++- 5 files changed, 240 insertions(+), 52 deletions(-) mode change 100644 => 120000 licensing/private_license.txt create mode 100644 protected/java/test/org/broadinstitute/sting/gatk/walkers/diagnostics/targets/BaseCoverageDistributionIntegrationTest.java 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..cd236a53a 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 @@ -51,12 +51,13 @@ 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.HashMap; +import java.util.LinkedList; import java.util.Map; /** @@ -64,18 +65,31 @@ import java.util.Map; * Date: 1/27/13 * Time: 11:16 AM */ -@By(DataSource.REFERENCE) public class BaseCoverageDistribution extends LocusWalker> { @Output(required = true) private PrintStream out; + private GenomeLoc previousLocus = null; + private long uncoveredBases = 0L; + private final LinkedList intervalList = new LinkedList(); + @Override public boolean includeReadsWithDeletionAtLoci() { return true; } + @Override + public void initialize() { + if (getToolkit().getIntervals() != null) + intervalList.addAll(getToolkit().getIntervals()); + } + @Override public Integer map(RefMetaDataTracker tracker, ReferenceContext ref, AlignmentContext context) { + GenomeLoc currentLocus = ref.getLocus(); + tallyUncoveredBases(currentLocus); + previousLocus = currentLocus; + System.out.println("DEBUG: " + currentLocus + " - " + context.getBasePileup().getReads().size() + " - " + uncoveredBases); return context.getBasePileup().getReads().size(); // I want the reads instead of the base pileup because I want to count deletions. } @@ -95,10 +109,55 @@ public class BaseCoverageDistribution extends LocusWalker result) { + tallyUncoveredBasesTillEndOfTraversal(); GATKReport report = GATKReport.newSimpleReport("BaseCoverageDistribution", "Coverage", "Count"); + report.addRow(0, uncoveredBases); for (Map.Entry entry : result.entrySet()) { report.addRow(entry.getKey(), entry.getValue()); } report.print(out); } -} + + private void tallyUncoveredBasesTillEndOfTraversal() { + GenomeLocParser parser = getToolkit().getGenomeLocParser(); + GenomeLoc lastLocus; + if (intervalList.isEmpty()) { //whole genome, add up all contigs past previousLocus + int lastContigLength = getToolkit().getSAMFileHeader().getSequence(0).getSequenceLength(); + String lastContigName = getToolkit().getSAMFileHeader().getSequence(0).getSequenceName(); + int lastContigIndex = getToolkit().getSAMFileHeader().getSequence(0).getSequenceIndex(); + lastLocus = parser.createGenomeLoc(lastContigName, lastContigIndex, 1, lastContigLength); + } else { + GenomeLoc lastInterval = intervalList.getLast(); + lastLocus = parser.createGenomeLoc(lastInterval.getContig(), lastInterval.getContigIndex(), lastInterval.getStop(), lastInterval.getStop()); + } + tallyUncoveredBases(lastLocus); + } + + 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); + System.out.println("ZEROLOC: " + zeroLoc.toString()); + 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..f2ecd3b2c --- /dev/null +++ b/protected/java/test/org/broadinstitute/sting/gatk/walkers/diagnostics/targets/BaseCoverageDistributionIntegrationTest.java @@ -0,0 +1,97 @@ +/* +* 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.Test; + +import java.util.Arrays; + +/** + * Short one line description of the walker. + * + *

[Long description of the walker]

+ * + * + *

Input

[Description of the Input]

+ * + *

Output

[Description of the Output]

+ * + *

Examples

+ *
+ *    java
+ *      -jar GenomeAnalysisTK.jar
+ *      -T [walker name]
+ *  
+ * + * @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"; + + private void DTTest(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); + } + + @Test(enabled = true) + public void testSingleInterval() { + DTTest("testSingleInterval ", "-L " + "chr1:90000-100000", "45368696dc008d1a07fb2b05fbafd1f4"); + } + @Test(enabled = true) + public void testMultipleIntervals() { + DTTest("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"); + } + + @Test(enabled = true) + public void testNoIntervals() { + DTTest("testNoIntervals ", "", ""); // needs to be checked... is not tallying 0's correctly! + } +} 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 + + } + }