From 50cdffc61f904acc0c485f62f7fc47f62edb1b0e Mon Sep 17 00:00:00 2001 From: Mark DePristo Date: Wed, 10 Apr 2013 10:54:25 -0400 Subject: [PATCH] Slightly improved Smith-Waterman parameter values for HaplotypeCaller Path comparisons Key improvement --------------- -- The haplotype caller was producing unstable calls when comparing the following two haplotypes: ref: ACAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGA alt: TGTGTGTGTGTGTGACAGAGAGAGAGAGAGAGAGAGAGAGAGAGA in which the alt and ref haplotypes differ in having indel at both the start and end of the bubble. The previous parameter values used in the Path algorithm were set so that such haplotype comparisons would result in the either the above alignment or the following alignment depending on exactly how many GA units were present in the bubble. ref: ACAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGA alt: TGTGTGTGTGTGTGACAGAGAGAGAGAGAGAGAGAGAGAGAGAGA The number of elements could vary depending on how the graph was built, and resulted in real differences in the calls between BWA mem and BWA-SW calls. I added a few unit tests for this case, and found a set of SW parameter values with lower gap-extension penalties that significantly favor the first alignment, which is the right thing to do, as we really don't mind large indels in the haplotypes relative to having lots of mismatches. -- Expanded the unit tests in both SW and KBestPaths to look at complex events like this, and to check as well somewhat sysmatically that we are finding many types of expected mutational events. -- Verified that this change doesn't alter our calls on 20:10,000,000-11,000,000 at all General code cleanup -------------------- -- Move Smith-Waterman to its own package in utils -- Refactored out SWParameters class in SWPairwiseAlignment, and made constructors take either a named parameter set or a Parameter object directly. Depreciated old call to inline constants. This makes it easier to group all of the SW parameters into a single object for callers -- Update users of SW code to use new Parameter class -- Also moved haplotype bam writers to protected so they can use the Path SW parameter, which is protected -- Removed the storage of the SW scoring matrix in SWPairwiseAligner by default. Only the SWPairwiseAlignmentMain test program needs this, so added a gross protected static variable that enables its storage --- .../haplotypecaller/DeBruijnAssembler.java | 13 +- .../haplotypecaller/HaplotypeResolver.java | 2 +- .../walkers/haplotypecaller/graphs/Path.java | 21 +- .../gatk/walkers/indels/IndelRealigner.java | 12 +- .../AllHaplotypeBAMWriter.java | 98 ++ .../CalledHaplotypeBAMWriter.java | 108 +++ .../HaplotypeBAMWriter.java | 70 +- .../GenotypingEngineUnitTest.java | 2 +- .../graphs/KBestPathsUnitTest.java | 134 ++- .../HaplotypeBAMWriterUnitTest.java | 67 +- .../SWPairwiseAlignmentUnitTest.java | 28 +- .../AllHaplotypeBAMWriter.java | 77 -- .../CalledHaplotypeBAMWriter.java | 87 -- .../sting/utils/smithwaterman/Parameters.java | 60 ++ .../SWPairwiseAlignment.java | 882 +++++++++--------- .../SWPairwiseAlignmentMain.java | 4 +- .../utils/smithwaterman/SWParameterSet.java | 51 + 17 files changed, 1048 insertions(+), 668 deletions(-) create mode 100644 protected/java/src/org/broadinstitute/sting/utils/haplotypeBAMWriter/AllHaplotypeBAMWriter.java create mode 100644 protected/java/src/org/broadinstitute/sting/utils/haplotypeBAMWriter/CalledHaplotypeBAMWriter.java rename {public => protected}/java/src/org/broadinstitute/sting/utils/haplotypeBAMWriter/HaplotypeBAMWriter.java (61%) rename {public => protected}/java/test/org/broadinstitute/sting/utils/haplotypeBAMWriter/HaplotypeBAMWriterUnitTest.java (59%) rename protected/java/test/org/broadinstitute/sting/utils/{ => smithwaterman}/SWPairwiseAlignmentUnitTest.java (88%) delete mode 100644 public/java/src/org/broadinstitute/sting/utils/haplotypeBAMWriter/AllHaplotypeBAMWriter.java delete mode 100644 public/java/src/org/broadinstitute/sting/utils/haplotypeBAMWriter/CalledHaplotypeBAMWriter.java create mode 100644 public/java/src/org/broadinstitute/sting/utils/smithwaterman/Parameters.java rename public/java/src/org/broadinstitute/sting/utils/{ => smithwaterman}/SWPairwiseAlignment.java (88%) rename public/java/src/org/broadinstitute/sting/utils/{ => smithwaterman}/SWPairwiseAlignmentMain.java (98%) create mode 100644 public/java/src/org/broadinstitute/sting/utils/smithwaterman/SWParameterSet.java diff --git a/protected/java/src/org/broadinstitute/sting/gatk/walkers/haplotypecaller/DeBruijnAssembler.java b/protected/java/src/org/broadinstitute/sting/gatk/walkers/haplotypecaller/DeBruijnAssembler.java index 8b89bb1bb..5ce65e13f 100644 --- a/protected/java/src/org/broadinstitute/sting/gatk/walkers/haplotypecaller/DeBruijnAssembler.java +++ b/protected/java/src/org/broadinstitute/sting/gatk/walkers/haplotypecaller/DeBruijnAssembler.java @@ -56,13 +56,14 @@ import org.apache.log4j.Logger; import org.broadinstitute.sting.gatk.walkers.haplotypecaller.graphs.*; import org.broadinstitute.sting.utils.GenomeLoc; import org.broadinstitute.sting.utils.MathUtils; -import org.broadinstitute.sting.utils.SWPairwiseAlignment; +import org.broadinstitute.sting.utils.smithwaterman.SWPairwiseAlignment; import org.broadinstitute.sting.utils.activeregion.ActiveRegion; import org.broadinstitute.sting.utils.exceptions.UserException; import org.broadinstitute.sting.utils.haplotype.Haplotype; import org.broadinstitute.sting.utils.sam.AlignmentUtils; import org.broadinstitute.sting.utils.sam.GATKSAMRecord; import org.broadinstitute.sting.utils.sam.ReadUtils; +import org.broadinstitute.sting.utils.smithwaterman.SWParameterSet; import org.broadinstitute.variant.variantcontext.Allele; import org.broadinstitute.variant.variantcontext.VariantContext; @@ -86,12 +87,6 @@ public class DeBruijnAssembler extends LocalAssemblyEngine { private static final int NUM_BEST_PATHS_PER_KMER_GRAPH = 25; private static final int GRAPH_KMER_STEP = 6; - // Smith-Waterman parameters originally copied from IndelRealigner, only used during GGA mode - private static final double SW_MATCH = 5.0; // 1.0; - private static final double SW_MISMATCH = -10.0; //-1.0/3.0; - private static final double SW_GAP = -22.0; //-1.0-1.0/3.0; - private static final double SW_GAP_EXTEND = -1.2; //-1.0/.0; - private final boolean debug; private final boolean debugGraphTransformations; private final int minKmer; @@ -587,7 +582,7 @@ public class DeBruijnAssembler extends LocalAssemblyEngine { private boolean addHaplotypeForGGA( final Haplotype haplotype, final byte[] ref, final List haplotypeList, final int activeRegionStart, final int activeRegionStop, final boolean FORCE_INCLUSION_FOR_GGA_MODE ) { if( haplotype == null ) { return false; } - final SWPairwiseAlignment swConsensus = new SWPairwiseAlignment( ref, haplotype.getBases(), SW_MATCH, SW_MISMATCH, SW_GAP, SW_GAP_EXTEND ); + final SWPairwiseAlignment swConsensus = new SWPairwiseAlignment( ref, haplotype.getBases(), SWParameterSet.STANDARD_NGS ); haplotype.setAlignmentStartHapwrtRef( swConsensus.getAlignmentStart2wrt1() ); if( swConsensus.getCigar().toString().contains("S") || swConsensus.getCigar().getReferenceLength() < 60 || swConsensus.getAlignmentStart2wrt1() < 0 ) { // protect against unhelpful haplotype alignments @@ -616,7 +611,7 @@ public class DeBruijnAssembler extends LocalAssemblyEngine { } final Haplotype h = new Haplotype( newHaplotypeBases ); - final SWPairwiseAlignment swConsensus2 = new SWPairwiseAlignment( ref, h.getBases(), SW_MATCH, SW_MISMATCH, SW_GAP, SW_GAP_EXTEND ); + final SWPairwiseAlignment swConsensus2 = new SWPairwiseAlignment( ref, h.getBases(), SWParameterSet.STANDARD_NGS ); h.setAlignmentStartHapwrtRef( swConsensus2.getAlignmentStart2wrt1() ); if ( haplotype.isArtificialHaplotype() ) { diff --git a/protected/java/src/org/broadinstitute/sting/gatk/walkers/haplotypecaller/HaplotypeResolver.java b/protected/java/src/org/broadinstitute/sting/gatk/walkers/haplotypecaller/HaplotypeResolver.java index 134863b8b..01ab421b3 100644 --- a/protected/java/src/org/broadinstitute/sting/gatk/walkers/haplotypecaller/HaplotypeResolver.java +++ b/protected/java/src/org/broadinstitute/sting/gatk/walkers/haplotypecaller/HaplotypeResolver.java @@ -59,7 +59,7 @@ import org.broadinstitute.sting.gatk.walkers.RodWalker; import org.broadinstitute.sting.gatk.walkers.Window; import org.broadinstitute.sting.utils.GenomeLoc; import org.broadinstitute.sting.utils.haplotype.Haplotype; -import org.broadinstitute.sting.utils.SWPairwiseAlignment; +import org.broadinstitute.sting.utils.smithwaterman.SWPairwiseAlignment; import org.broadinstitute.sting.utils.help.HelpConstants; import org.broadinstitute.variant.vcf.VCFHeader; import org.broadinstitute.variant.vcf.VCFHeaderLine; diff --git a/protected/java/src/org/broadinstitute/sting/gatk/walkers/haplotypecaller/graphs/Path.java b/protected/java/src/org/broadinstitute/sting/gatk/walkers/haplotypecaller/graphs/Path.java index d91ec0e37..9d2d680c9 100644 --- a/protected/java/src/org/broadinstitute/sting/gatk/walkers/haplotypecaller/graphs/Path.java +++ b/protected/java/src/org/broadinstitute/sting/gatk/walkers/haplotypecaller/graphs/Path.java @@ -52,7 +52,8 @@ import net.sf.samtools.Cigar; import net.sf.samtools.CigarElement; import net.sf.samtools.CigarOperator; import org.apache.commons.lang.ArrayUtils; -import org.broadinstitute.sting.utils.SWPairwiseAlignment; +import org.broadinstitute.sting.utils.smithwaterman.Parameters; +import org.broadinstitute.sting.utils.smithwaterman.SWPairwiseAlignment; import org.broadinstitute.sting.utils.sam.AlignmentUtils; import java.util.*; @@ -85,10 +86,8 @@ public class Path { // used in the bubble state machine to apply Smith-Waterman to the bubble sequence // these values were chosen via optimization against the NA12878 knowledge base - private static final double SW_MATCH = 20.0; - private static final double SW_MISMATCH = -15.0; - private static final double SW_GAP = -26.0; - private static final double SW_GAP_EXTEND = -1.1; + public static final Parameters NEW_SW_PARAMETERS = new Parameters(20.0, -20.0, -26.0, -0.1); + private static final byte[] STARTING_SW_ANCHOR_BYTES = "XXXXXXXXX".getBytes(); /** @@ -107,6 +106,16 @@ public class Path { this.graph = graph; } + /** + * Convenience constructor for testing that creates a path through vertices in graph + */ + protected static Path makePath(final List vertices, final BaseGraph graph) { + Path path = new Path(vertices.get(0), graph); + for ( int i = 1; i < vertices.size(); i++ ) + path = new Path(path, graph.getEdge(path.lastVertex, vertices.get(i))); + return path; + } + /** * Create a new Path extending p with edge * @@ -362,7 +371,7 @@ public class Path { padding = ArrayUtils.addAll(padding, padding); // double the size of the padding each time final byte[] reference = ArrayUtils.addAll( ArrayUtils.addAll(padding, refBytes), padding ); final byte[] alternate = ArrayUtils.addAll( ArrayUtils.addAll(padding, bubbleBytes), padding ); - swConsensus = new SWPairwiseAlignment( reference, alternate, SW_MATCH, SW_MISMATCH, SW_GAP, SW_GAP_EXTEND ); + swConsensus = new SWPairwiseAlignment( reference, alternate, NEW_SW_PARAMETERS ); if( swConsensus.getAlignmentStart2wrt1() == 0 && !swConsensus.getCigar().toString().contains("S") && swConsensus.getCigar().getReferenceLength() == reference.length ) { goodAlignment = true; } diff --git a/protected/java/src/org/broadinstitute/sting/gatk/walkers/indels/IndelRealigner.java b/protected/java/src/org/broadinstitute/sting/gatk/walkers/indels/IndelRealigner.java index 7d8243c98..c0848663e 100644 --- a/protected/java/src/org/broadinstitute/sting/gatk/walkers/indels/IndelRealigner.java +++ b/protected/java/src/org/broadinstitute/sting/gatk/walkers/indels/IndelRealigner.java @@ -62,7 +62,8 @@ import org.broadinstitute.sting.gatk.walkers.BAQMode; import org.broadinstitute.sting.gatk.walkers.ReadWalker; import org.broadinstitute.sting.utils.BaseUtils; import org.broadinstitute.sting.utils.GenomeLoc; -import org.broadinstitute.sting.utils.SWPairwiseAlignment; +import org.broadinstitute.sting.utils.smithwaterman.Parameters; +import org.broadinstitute.sting.utils.smithwaterman.SWPairwiseAlignment; import org.broadinstitute.sting.utils.Utils; import org.broadinstitute.sting.utils.baq.BAQ; import org.broadinstitute.sting.utils.collections.Pair; @@ -328,10 +329,7 @@ public class IndelRealigner extends ReadWalker { // fraction of mismatches that need to no longer mismatch for a column to be considered cleaned private static final double MISMATCH_COLUMN_CLEANED_FRACTION = 0.75; - private static final double SW_MATCH = 30.0; // 1.0; - private static final double SW_MISMATCH = -10.0; //-1.0/3.0; - private static final double SW_GAP = -10.0; //-1.0-1.0/3.0; - private static final double SW_GAP_EXTEND = -2.0; //-1.0/.0; + private final static Parameters swParameters = new Parameters(30.0, -10.0, -10.0, -2.0); // reference base padding size // TODO -- make this a command-line argument if the need arises @@ -999,7 +997,7 @@ public class IndelRealigner extends ReadWalker { private void createAndAddAlternateConsensus(final byte[] read, final Set altConsensesToPopulate, final byte[] reference) { // do a pairwise alignment against the reference - SWPairwiseAlignment swConsensus = new SWPairwiseAlignment(reference, read, SW_MATCH, SW_MISMATCH, SW_GAP, SW_GAP_EXTEND); + SWPairwiseAlignment swConsensus = new SWPairwiseAlignment(reference, read, swParameters); Consensus c = createAlternateConsensus(swConsensus.getAlignmentStart2wrt1(), swConsensus.getCigar(), reference, read); if ( c != null ) altConsensesToPopulate.add(c); @@ -1016,7 +1014,7 @@ public class IndelRealigner extends ReadWalker { } // do a pairwise alignment against the reference SWalignmentRuns++; - SWPairwiseAlignment swConsensus = new SWPairwiseAlignment(reference, read.getReadBases(), SW_MATCH, SW_MISMATCH, SW_GAP, SW_GAP_EXTEND); + SWPairwiseAlignment swConsensus = new SWPairwiseAlignment(reference, read.getReadBases(), swParameters); Consensus c = createAlternateConsensus(swConsensus.getAlignmentStart2wrt1(), swConsensus.getCigar(), reference, read.getReadBases()); if ( c != null ) { altConsensesToPopulate.add(c); diff --git a/protected/java/src/org/broadinstitute/sting/utils/haplotypeBAMWriter/AllHaplotypeBAMWriter.java b/protected/java/src/org/broadinstitute/sting/utils/haplotypeBAMWriter/AllHaplotypeBAMWriter.java new file mode 100644 index 000000000..54061c781 --- /dev/null +++ b/protected/java/src/org/broadinstitute/sting/utils/haplotypeBAMWriter/AllHaplotypeBAMWriter.java @@ -0,0 +1,98 @@ +/* +* By downloading the PROGRAM you agree to the following terms of use: +* +* BROAD INSTITUTE - SOFTWARE LICENSE AGREEMENT - FOR ACADEMIC NON-COMMERCIAL RESEARCH PURPOSES ONLY +* +* This Agreement is made between the Broad Institute, Inc. with a principal address at 7 Cambridge Center, Cambridge, MA 02142 (BROAD) and the LICENSEE and is effective at the date the downloading is completed (EFFECTIVE DATE). +* +* WHEREAS, LICENSEE desires to license the PROGRAM, as defined hereinafter, and BROAD wishes to have this PROGRAM utilized in the public interest, subject only to the royalty-free, nonexclusive, nontransferable license rights of the United States Government pursuant to 48 CFR 52.227-14; and +* WHEREAS, LICENSEE desires to license the PROGRAM and BROAD desires to grant a license on the following terms and conditions. +* NOW, THEREFORE, in consideration of the promises and covenants made herein, the parties hereto agree as follows: +* +* 1. DEFINITIONS +* 1.1 PROGRAM shall mean copyright in the object code and source code known as GATK2 and related documentation, if any, as they exist on the EFFECTIVE DATE and can be downloaded from http://www.broadinstitute/GATK on the EFFECTIVE DATE. +* +* 2. LICENSE +* 2.1 Grant. Subject to the terms of this Agreement, BROAD hereby grants to LICENSEE, solely for academic non-commercial research purposes, a non-exclusive, non-transferable license to: (a) download, execute and display the PROGRAM and (b) create bug fixes and modify the PROGRAM. +* The LICENSEE may apply the PROGRAM in a pipeline to data owned by users other than the LICENSEE and provide these users the results of the PROGRAM provided LICENSEE does so for academic non-commercial purposes only. For clarification purposes, academic sponsored research is not a commercial use under the terms of this Agreement. +* 2.2 No Sublicensing or Additional Rights. LICENSEE shall not sublicense or distribute the PROGRAM, in whole or in part, without prior written permission from BROAD. LICENSEE shall ensure that all of its users agree to the terms of this Agreement. LICENSEE further agrees that it shall not put the PROGRAM on a network, server, or other similar technology that may be accessed by anyone other than the LICENSEE and its employees and users who have agreed to the terms of this agreement. +* 2.3 License Limitations. Nothing in this Agreement shall be construed to confer any rights upon LICENSEE by implication, estoppel, or otherwise to any computer software, trademark, intellectual property, or patent rights of BROAD, or of any other entity, except as expressly granted herein. LICENSEE agrees that the PROGRAM, in whole or part, shall not be used for any commercial purpose, including without limitation, as the basis of a commercial software or hardware product or to provide services. LICENSEE further agrees that the PROGRAM shall not be copied or otherwise adapted in order to circumvent the need for obtaining a license for use of the PROGRAM. +* +* 3. OWNERSHIP OF INTELLECTUAL PROPERTY +* LICENSEE acknowledges that title to the PROGRAM shall remain with BROAD. The PROGRAM is marked with the following BROAD copyright notice and notice of attribution to contributors. LICENSEE shall retain such notice on all copies. LICENSEE agrees to include appropriate attribution if any results obtained from use of the PROGRAM are included in any publication. +* Copyright 2012 Broad Institute, Inc. +* Notice of attribution: The GATK2 program was made available through the generosity of Medical and Population Genetics program at the Broad Institute, Inc. +* LICENSEE shall not use any trademark or trade name of BROAD, or any variation, adaptation, or abbreviation, of such marks or trade names, or any names of officers, faculty, students, employees, or agents of BROAD except as states above for attribution purposes. +* +* 4. INDEMNIFICATION +* LICENSEE shall indemnify, defend, and hold harmless BROAD, and their respective officers, faculty, students, employees, associated investigators and agents, and their respective successors, heirs and assigns, (Indemnitees), against any liability, damage, loss, or expense (including reasonable attorneys fees and expenses) incurred by or imposed upon any of the Indemnitees in connection with any claims, suits, actions, demands or judgments arising out of any theory of liability (including, without limitation, actions in the form of tort, warranty, or strict liability and regardless of whether such action has any factual basis) pursuant to any right or license granted under this Agreement. +* +* 5. NO REPRESENTATIONS OR WARRANTIES +* THE PROGRAM IS DELIVERED AS IS. BROAD MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE PROGRAM OR THE COPYRIGHT, EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, WHETHER OR NOT DISCOVERABLE. BROAD EXTENDS NO WARRANTIES OF ANY KIND AS TO PROGRAM CONFORMITY WITH WHATEVER USER MANUALS OR OTHER LITERATURE MAY BE ISSUED FROM TIME TO TIME. +* IN NO EVENT SHALL BROAD OR ITS RESPECTIVE DIRECTORS, OFFICERS, EMPLOYEES, AFFILIATED INVESTIGATORS AND AFFILIATES BE LIABLE FOR INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, INCLUDING, WITHOUT LIMITATION, ECONOMIC DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER BROAD SHALL BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT SHALL KNOW OF THE POSSIBILITY OF THE FOREGOING. +* +* 6. ASSIGNMENT +* This Agreement is personal to LICENSEE and any rights or obligations assigned by LICENSEE without the prior written consent of BROAD shall be null and void. +* +* 7. MISCELLANEOUS +* 7.1 Export Control. LICENSEE gives assurance that it will comply with all United States export control laws and regulations controlling the export of the PROGRAM, including, without limitation, all Export Administration Regulations of the United States Department of Commerce. Among other things, these laws and regulations prohibit, or require a license for, the export of certain types of software to specified countries. +* 7.2 Termination. LICENSEE shall have the right to terminate this Agreement for any reason upon prior written notice to BROAD. If LICENSEE breaches any provision hereunder, and fails to cure such breach within thirty (30) days, BROAD may terminate this Agreement immediately. Upon termination, LICENSEE shall provide BROAD with written assurance that the original and all copies of the PROGRAM have been destroyed, except that, upon prior written authorization from BROAD, LICENSEE may retain a copy for archive purposes. +* 7.3 Survival. The following provisions shall survive the expiration or termination of this Agreement: Articles 1, 3, 4, 5 and Sections 2.2, 2.3, 7.3, and 7.4. +* 7.4 Notice. Any notices under this Agreement shall be in writing, shall specifically refer to this Agreement, and shall be sent by hand, recognized national overnight courier, confirmed facsimile transmission, confirmed electronic mail, or registered or certified mail, postage prepaid, return receipt requested. All notices under this Agreement shall be deemed effective upon receipt. +* 7.5 Amendment and Waiver; Entire Agreement. This Agreement may be amended, supplemented, or otherwise modified only by means of a written instrument signed by all parties. Any waiver of any rights or failure to act in a specific instance shall relate only to such instance and shall not be construed as an agreement to waive any rights or fail to act in any other instance, whether or not similar. This Agreement constitutes the entire agreement among the parties with respect to its subject matter and supersedes prior agreements or understandings between the parties relating to its subject matter. +* 7.6 Binding Effect; Headings. This Agreement shall be binding upon and inure to the benefit of the parties and their respective permitted successors and assigns. All headings are for convenience only and shall not affect the meaning of any provision of this Agreement. +* 7.7 Governing Law. This Agreement shall be construed, governed, interpreted and applied in accordance with the internal laws of the Commonwealth of Massachusetts, U.S.A., without regard to conflict of laws principles. +*/ + +package org.broadinstitute.sting.utils.haplotypeBAMWriter; + +import net.sf.samtools.*; +import org.broadinstitute.sting.utils.GenomeLoc; +import org.broadinstitute.sting.utils.haplotype.Haplotype; +import org.broadinstitute.sting.utils.genotyper.MostLikelyAllele; +import org.broadinstitute.sting.utils.genotyper.PerReadAlleleLikelihoodMap; +import org.broadinstitute.sting.utils.sam.GATKSAMRecord; +import org.broadinstitute.variant.variantcontext.Allele; + +import java.util.*; + +/** + * A haplotype bam writer that writes out all haplotypes as reads and then + * the alignment of reach read to its best match among the best haplotypes. + * + * Primarily useful for people working on the HaplotypeCaller method itself + * + * User: depristo + * Date: 2/22/13 + * Time: 1:50 PM + */ +class AllHaplotypeBAMWriter extends HaplotypeBAMWriter { + public AllHaplotypeBAMWriter(final SAMFileWriter bamWriter) { + super(bamWriter); + } + + /** + * {@inheritDoc} + */ + @Override + public void writeReadsAlignedToHaplotypes(final List haplotypes, + final GenomeLoc paddedReferenceLoc, + final List bestHaplotypes, + final Set calledHaplotypes, + final Map stratifiedReadMap) { + writeHaplotypesAsReads(haplotypes, new HashSet(bestHaplotypes), paddedReferenceLoc); + + // we need to remap the Alleles back to the Haplotypes; inefficient but unfortunately this is a requirement currently + final Map alleleToHaplotypeMap = new HashMap(haplotypes.size()); + for ( final Haplotype haplotype : haplotypes ) + alleleToHaplotypeMap.put(Allele.create(haplotype.getBases()), haplotype); + + // next, output the interesting reads for each sample aligned against the appropriate haplotype + for ( final PerReadAlleleLikelihoodMap readAlleleLikelihoodMap : stratifiedReadMap.values() ) { + for ( Map.Entry> entry : readAlleleLikelihoodMap.getLikelihoodReadMap().entrySet() ) { + final MostLikelyAllele bestAllele = PerReadAlleleLikelihoodMap.getMostLikelyAllele(entry.getValue()); + writeReadAgainstHaplotype(entry.getKey(), alleleToHaplotypeMap.get(bestAllele.getMostLikelyAllele()), paddedReferenceLoc.getStart()); + } + } + } +} diff --git a/protected/java/src/org/broadinstitute/sting/utils/haplotypeBAMWriter/CalledHaplotypeBAMWriter.java b/protected/java/src/org/broadinstitute/sting/utils/haplotypeBAMWriter/CalledHaplotypeBAMWriter.java new file mode 100644 index 000000000..d63cf65fc --- /dev/null +++ b/protected/java/src/org/broadinstitute/sting/utils/haplotypeBAMWriter/CalledHaplotypeBAMWriter.java @@ -0,0 +1,108 @@ +/* +* By downloading the PROGRAM you agree to the following terms of use: +* +* BROAD INSTITUTE - SOFTWARE LICENSE AGREEMENT - FOR ACADEMIC NON-COMMERCIAL RESEARCH PURPOSES ONLY +* +* This Agreement is made between the Broad Institute, Inc. with a principal address at 7 Cambridge Center, Cambridge, MA 02142 (BROAD) and the LICENSEE and is effective at the date the downloading is completed (EFFECTIVE DATE). +* +* WHEREAS, LICENSEE desires to license the PROGRAM, as defined hereinafter, and BROAD wishes to have this PROGRAM utilized in the public interest, subject only to the royalty-free, nonexclusive, nontransferable license rights of the United States Government pursuant to 48 CFR 52.227-14; and +* WHEREAS, LICENSEE desires to license the PROGRAM and BROAD desires to grant a license on the following terms and conditions. +* NOW, THEREFORE, in consideration of the promises and covenants made herein, the parties hereto agree as follows: +* +* 1. DEFINITIONS +* 1.1 PROGRAM shall mean copyright in the object code and source code known as GATK2 and related documentation, if any, as they exist on the EFFECTIVE DATE and can be downloaded from http://www.broadinstitute/GATK on the EFFECTIVE DATE. +* +* 2. LICENSE +* 2.1 Grant. Subject to the terms of this Agreement, BROAD hereby grants to LICENSEE, solely for academic non-commercial research purposes, a non-exclusive, non-transferable license to: (a) download, execute and display the PROGRAM and (b) create bug fixes and modify the PROGRAM. +* The LICENSEE may apply the PROGRAM in a pipeline to data owned by users other than the LICENSEE and provide these users the results of the PROGRAM provided LICENSEE does so for academic non-commercial purposes only. For clarification purposes, academic sponsored research is not a commercial use under the terms of this Agreement. +* 2.2 No Sublicensing or Additional Rights. LICENSEE shall not sublicense or distribute the PROGRAM, in whole or in part, without prior written permission from BROAD. LICENSEE shall ensure that all of its users agree to the terms of this Agreement. LICENSEE further agrees that it shall not put the PROGRAM on a network, server, or other similar technology that may be accessed by anyone other than the LICENSEE and its employees and users who have agreed to the terms of this agreement. +* 2.3 License Limitations. Nothing in this Agreement shall be construed to confer any rights upon LICENSEE by implication, estoppel, or otherwise to any computer software, trademark, intellectual property, or patent rights of BROAD, or of any other entity, except as expressly granted herein. LICENSEE agrees that the PROGRAM, in whole or part, shall not be used for any commercial purpose, including without limitation, as the basis of a commercial software or hardware product or to provide services. LICENSEE further agrees that the PROGRAM shall not be copied or otherwise adapted in order to circumvent the need for obtaining a license for use of the PROGRAM. +* +* 3. OWNERSHIP OF INTELLECTUAL PROPERTY +* LICENSEE acknowledges that title to the PROGRAM shall remain with BROAD. The PROGRAM is marked with the following BROAD copyright notice and notice of attribution to contributors. LICENSEE shall retain such notice on all copies. LICENSEE agrees to include appropriate attribution if any results obtained from use of the PROGRAM are included in any publication. +* Copyright 2012 Broad Institute, Inc. +* Notice of attribution: The GATK2 program was made available through the generosity of Medical and Population Genetics program at the Broad Institute, Inc. +* LICENSEE shall not use any trademark or trade name of BROAD, or any variation, adaptation, or abbreviation, of such marks or trade names, or any names of officers, faculty, students, employees, or agents of BROAD except as states above for attribution purposes. +* +* 4. INDEMNIFICATION +* LICENSEE shall indemnify, defend, and hold harmless BROAD, and their respective officers, faculty, students, employees, associated investigators and agents, and their respective successors, heirs and assigns, (Indemnitees), against any liability, damage, loss, or expense (including reasonable attorneys fees and expenses) incurred by or imposed upon any of the Indemnitees in connection with any claims, suits, actions, demands or judgments arising out of any theory of liability (including, without limitation, actions in the form of tort, warranty, or strict liability and regardless of whether such action has any factual basis) pursuant to any right or license granted under this Agreement. +* +* 5. NO REPRESENTATIONS OR WARRANTIES +* THE PROGRAM IS DELIVERED AS IS. BROAD MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE PROGRAM OR THE COPYRIGHT, EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, WHETHER OR NOT DISCOVERABLE. BROAD EXTENDS NO WARRANTIES OF ANY KIND AS TO PROGRAM CONFORMITY WITH WHATEVER USER MANUALS OR OTHER LITERATURE MAY BE ISSUED FROM TIME TO TIME. +* IN NO EVENT SHALL BROAD OR ITS RESPECTIVE DIRECTORS, OFFICERS, EMPLOYEES, AFFILIATED INVESTIGATORS AND AFFILIATES BE LIABLE FOR INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, INCLUDING, WITHOUT LIMITATION, ECONOMIC DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER BROAD SHALL BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT SHALL KNOW OF THE POSSIBILITY OF THE FOREGOING. +* +* 6. ASSIGNMENT +* This Agreement is personal to LICENSEE and any rights or obligations assigned by LICENSEE without the prior written consent of BROAD shall be null and void. +* +* 7. MISCELLANEOUS +* 7.1 Export Control. LICENSEE gives assurance that it will comply with all United States export control laws and regulations controlling the export of the PROGRAM, including, without limitation, all Export Administration Regulations of the United States Department of Commerce. Among other things, these laws and regulations prohibit, or require a license for, the export of certain types of software to specified countries. +* 7.2 Termination. LICENSEE shall have the right to terminate this Agreement for any reason upon prior written notice to BROAD. If LICENSEE breaches any provision hereunder, and fails to cure such breach within thirty (30) days, BROAD may terminate this Agreement immediately. Upon termination, LICENSEE shall provide BROAD with written assurance that the original and all copies of the PROGRAM have been destroyed, except that, upon prior written authorization from BROAD, LICENSEE may retain a copy for archive purposes. +* 7.3 Survival. The following provisions shall survive the expiration or termination of this Agreement: Articles 1, 3, 4, 5 and Sections 2.2, 2.3, 7.3, and 7.4. +* 7.4 Notice. Any notices under this Agreement shall be in writing, shall specifically refer to this Agreement, and shall be sent by hand, recognized national overnight courier, confirmed facsimile transmission, confirmed electronic mail, or registered or certified mail, postage prepaid, return receipt requested. All notices under this Agreement shall be deemed effective upon receipt. +* 7.5 Amendment and Waiver; Entire Agreement. This Agreement may be amended, supplemented, or otherwise modified only by means of a written instrument signed by all parties. Any waiver of any rights or failure to act in a specific instance shall relate only to such instance and shall not be construed as an agreement to waive any rights or fail to act in any other instance, whether or not similar. This Agreement constitutes the entire agreement among the parties with respect to its subject matter and supersedes prior agreements or understandings between the parties relating to its subject matter. +* 7.6 Binding Effect; Headings. This Agreement shall be binding upon and inure to the benefit of the parties and their respective permitted successors and assigns. All headings are for convenience only and shall not affect the meaning of any provision of this Agreement. +* 7.7 Governing Law. This Agreement shall be construed, governed, interpreted and applied in accordance with the internal laws of the Commonwealth of Massachusetts, U.S.A., without regard to conflict of laws principles. +*/ + +package org.broadinstitute.sting.utils.haplotypeBAMWriter; + +import net.sf.samtools.SAMFileWriter; +import org.broadinstitute.sting.utils.GenomeLoc; +import org.broadinstitute.sting.utils.haplotype.Haplotype; +import org.broadinstitute.sting.utils.genotyper.MostLikelyAllele; +import org.broadinstitute.sting.utils.genotyper.PerReadAlleleLikelihoodMap; +import org.broadinstitute.sting.utils.sam.GATKSAMRecord; +import org.broadinstitute.variant.variantcontext.Allele; + +import java.util.*; + +/** + * Writes a BAM containing just the reads in stratifiedReadMap aligned to their + * most likely haplotype among all of the called haplotypes. + * + * Primarily useful for users of the HaplotypeCaller who want to better understand the + * support of their calls w.r.t. the reads. + * + * User: depristo + * Date: 2/22/13 + * Time: 1:50 PM + */ +class CalledHaplotypeBAMWriter extends HaplotypeBAMWriter { + public CalledHaplotypeBAMWriter(final SAMFileWriter bamWriter) { + super(bamWriter); + } + + /** + * {@inheritDoc} + */ + @Override + public void writeReadsAlignedToHaplotypes(final List haplotypes, + final GenomeLoc paddedReferenceLoc, + final List bestHaplotypes, + final Set calledHaplotypes, + final Map stratifiedReadMap) { + if ( calledHaplotypes.isEmpty() ) // only write out called haplotypes + return; + + writeHaplotypesAsReads(calledHaplotypes, calledHaplotypes, paddedReferenceLoc); + + // we need to remap the Alleles back to the Haplotypes; inefficient but unfortunately this is a requirement currently + final Map alleleToHaplotypeMap = new HashMap(haplotypes.size()); + for ( final Haplotype haplotype : calledHaplotypes ) { + alleleToHaplotypeMap.put(Allele.create(haplotype.getBases()), haplotype); + } + + // the set of all alleles that were actually called + final Set allelesOfCalledHaplotypes = alleleToHaplotypeMap.keySet(); + + // next, output the interesting reads for each sample aligned against one of the called haplotypes + for ( final PerReadAlleleLikelihoodMap readAlleleLikelihoodMap : stratifiedReadMap.values() ) { + for ( Map.Entry> entry : readAlleleLikelihoodMap.getLikelihoodReadMap().entrySet() ) { + if ( entry.getKey().getMappingQuality() > 0 ) { + final MostLikelyAllele bestAllele = PerReadAlleleLikelihoodMap.getMostLikelyAllele(entry.getValue(), allelesOfCalledHaplotypes); + writeReadAgainstHaplotype(entry.getKey(), alleleToHaplotypeMap.get(bestAllele.getMostLikelyAllele()), paddedReferenceLoc.getStart()); + } + } + } + } +} diff --git a/public/java/src/org/broadinstitute/sting/utils/haplotypeBAMWriter/HaplotypeBAMWriter.java b/protected/java/src/org/broadinstitute/sting/utils/haplotypeBAMWriter/HaplotypeBAMWriter.java similarity index 61% rename from public/java/src/org/broadinstitute/sting/utils/haplotypeBAMWriter/HaplotypeBAMWriter.java rename to protected/java/src/org/broadinstitute/sting/utils/haplotypeBAMWriter/HaplotypeBAMWriter.java index c80287bca..2eea664d9 100644 --- a/public/java/src/org/broadinstitute/sting/utils/haplotypeBAMWriter/HaplotypeBAMWriter.java +++ b/protected/java/src/org/broadinstitute/sting/utils/haplotypeBAMWriter/HaplotypeBAMWriter.java @@ -1,35 +1,57 @@ /* -* 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. +* By downloading the PROGRAM you agree to the following terms of use: +* +* BROAD INSTITUTE - SOFTWARE LICENSE AGREEMENT - FOR ACADEMIC NON-COMMERCIAL RESEARCH PURPOSES ONLY +* +* This Agreement is made between the Broad Institute, Inc. with a principal address at 7 Cambridge Center, Cambridge, MA 02142 (BROAD) and the LICENSEE and is effective at the date the downloading is completed (EFFECTIVE DATE). +* +* WHEREAS, LICENSEE desires to license the PROGRAM, as defined hereinafter, and BROAD wishes to have this PROGRAM utilized in the public interest, subject only to the royalty-free, nonexclusive, nontransferable license rights of the United States Government pursuant to 48 CFR 52.227-14; and +* WHEREAS, LICENSEE desires to license the PROGRAM and BROAD desires to grant a license on the following terms and conditions. +* NOW, THEREFORE, in consideration of the promises and covenants made herein, the parties hereto agree as follows: +* +* 1. DEFINITIONS +* 1.1 PROGRAM shall mean copyright in the object code and source code known as GATK2 and related documentation, if any, as they exist on the EFFECTIVE DATE and can be downloaded from http://www.broadinstitute/GATK on the EFFECTIVE DATE. +* +* 2. LICENSE +* 2.1 Grant. Subject to the terms of this Agreement, BROAD hereby grants to LICENSEE, solely for academic non-commercial research purposes, a non-exclusive, non-transferable license to: (a) download, execute and display the PROGRAM and (b) create bug fixes and modify the PROGRAM. +* The LICENSEE may apply the PROGRAM in a pipeline to data owned by users other than the LICENSEE and provide these users the results of the PROGRAM provided LICENSEE does so for academic non-commercial purposes only. For clarification purposes, academic sponsored research is not a commercial use under the terms of this Agreement. +* 2.2 No Sublicensing or Additional Rights. LICENSEE shall not sublicense or distribute the PROGRAM, in whole or in part, without prior written permission from BROAD. LICENSEE shall ensure that all of its users agree to the terms of this Agreement. LICENSEE further agrees that it shall not put the PROGRAM on a network, server, or other similar technology that may be accessed by anyone other than the LICENSEE and its employees and users who have agreed to the terms of this agreement. +* 2.3 License Limitations. Nothing in this Agreement shall be construed to confer any rights upon LICENSEE by implication, estoppel, or otherwise to any computer software, trademark, intellectual property, or patent rights of BROAD, or of any other entity, except as expressly granted herein. LICENSEE agrees that the PROGRAM, in whole or part, shall not be used for any commercial purpose, including without limitation, as the basis of a commercial software or hardware product or to provide services. LICENSEE further agrees that the PROGRAM shall not be copied or otherwise adapted in order to circumvent the need for obtaining a license for use of the PROGRAM. +* +* 3. OWNERSHIP OF INTELLECTUAL PROPERTY +* LICENSEE acknowledges that title to the PROGRAM shall remain with BROAD. The PROGRAM is marked with the following BROAD copyright notice and notice of attribution to contributors. LICENSEE shall retain such notice on all copies. LICENSEE agrees to include appropriate attribution if any results obtained from use of the PROGRAM are included in any publication. +* Copyright 2012 Broad Institute, Inc. +* Notice of attribution: The GATK2 program was made available through the generosity of Medical and Population Genetics program at the Broad Institute, Inc. +* LICENSEE shall not use any trademark or trade name of BROAD, or any variation, adaptation, or abbreviation, of such marks or trade names, or any names of officers, faculty, students, employees, or agents of BROAD except as states above for attribution purposes. +* +* 4. INDEMNIFICATION +* LICENSEE shall indemnify, defend, and hold harmless BROAD, and their respective officers, faculty, students, employees, associated investigators and agents, and their respective successors, heirs and assigns, (Indemnitees), against any liability, damage, loss, or expense (including reasonable attorneys fees and expenses) incurred by or imposed upon any of the Indemnitees in connection with any claims, suits, actions, demands or judgments arising out of any theory of liability (including, without limitation, actions in the form of tort, warranty, or strict liability and regardless of whether such action has any factual basis) pursuant to any right or license granted under this Agreement. +* +* 5. NO REPRESENTATIONS OR WARRANTIES +* THE PROGRAM IS DELIVERED AS IS. BROAD MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE PROGRAM OR THE COPYRIGHT, EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, WHETHER OR NOT DISCOVERABLE. BROAD EXTENDS NO WARRANTIES OF ANY KIND AS TO PROGRAM CONFORMITY WITH WHATEVER USER MANUALS OR OTHER LITERATURE MAY BE ISSUED FROM TIME TO TIME. +* IN NO EVENT SHALL BROAD OR ITS RESPECTIVE DIRECTORS, OFFICERS, EMPLOYEES, AFFILIATED INVESTIGATORS AND AFFILIATES BE LIABLE FOR INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, INCLUDING, WITHOUT LIMITATION, ECONOMIC DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER BROAD SHALL BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT SHALL KNOW OF THE POSSIBILITY OF THE FOREGOING. +* +* 6. ASSIGNMENT +* This Agreement is personal to LICENSEE and any rights or obligations assigned by LICENSEE without the prior written consent of BROAD shall be null and void. +* +* 7. MISCELLANEOUS +* 7.1 Export Control. LICENSEE gives assurance that it will comply with all United States export control laws and regulations controlling the export of the PROGRAM, including, without limitation, all Export Administration Regulations of the United States Department of Commerce. Among other things, these laws and regulations prohibit, or require a license for, the export of certain types of software to specified countries. +* 7.2 Termination. LICENSEE shall have the right to terminate this Agreement for any reason upon prior written notice to BROAD. If LICENSEE breaches any provision hereunder, and fails to cure such breach within thirty (30) days, BROAD may terminate this Agreement immediately. Upon termination, LICENSEE shall provide BROAD with written assurance that the original and all copies of the PROGRAM have been destroyed, except that, upon prior written authorization from BROAD, LICENSEE may retain a copy for archive purposes. +* 7.3 Survival. The following provisions shall survive the expiration or termination of this Agreement: Articles 1, 3, 4, 5 and Sections 2.2, 2.3, 7.3, and 7.4. +* 7.4 Notice. Any notices under this Agreement shall be in writing, shall specifically refer to this Agreement, and shall be sent by hand, recognized national overnight courier, confirmed facsimile transmission, confirmed electronic mail, or registered or certified mail, postage prepaid, return receipt requested. All notices under this Agreement shall be deemed effective upon receipt. +* 7.5 Amendment and Waiver; Entire Agreement. This Agreement may be amended, supplemented, or otherwise modified only by means of a written instrument signed by all parties. Any waiver of any rights or failure to act in a specific instance shall relate only to such instance and shall not be construed as an agreement to waive any rights or fail to act in any other instance, whether or not similar. This Agreement constitutes the entire agreement among the parties with respect to its subject matter and supersedes prior agreements or understandings between the parties relating to its subject matter. +* 7.6 Binding Effect; Headings. This Agreement shall be binding upon and inure to the benefit of the parties and their respective permitted successors and assigns. All headings are for convenience only and shall not affect the meaning of any provision of this Agreement. +* 7.7 Governing Law. This Agreement shall be construed, governed, interpreted and applied in accordance with the internal laws of the Commonwealth of Massachusetts, U.S.A., without regard to conflict of laws principles. */ package org.broadinstitute.sting.utils.haplotypeBAMWriter; import net.sf.samtools.*; import org.broadinstitute.sting.gatk.io.StingSAMFileWriter; +import org.broadinstitute.sting.gatk.walkers.haplotypecaller.graphs.Path; import org.broadinstitute.sting.utils.GenomeLoc; import org.broadinstitute.sting.utils.haplotype.Haplotype; -import org.broadinstitute.sting.utils.SWPairwiseAlignment; +import org.broadinstitute.sting.utils.smithwaterman.SWPairwiseAlignment; import org.broadinstitute.sting.utils.Utils; import org.broadinstitute.sting.utils.genotyper.PerReadAlleleLikelihoodMap; import org.broadinstitute.sting.utils.sam.AlignmentUtils; @@ -191,7 +213,7 @@ public abstract class HaplotypeBAMWriter { try { // compute the smith-waterman alignment of read -> haplotype - final SWPairwiseAlignment swPairwiseAlignment = new SWPairwiseAlignment(haplotype.getBases(), originalRead.getReadBases(), 5.0, -10.0, -22.0, -1.2); + final SWPairwiseAlignment swPairwiseAlignment = new SWPairwiseAlignment(haplotype.getBases(), originalRead.getReadBases(), Path.NEW_SW_PARAMETERS); //swPairwiseAlignment.printAlignment(haplotype.getBases(), originalRead.getReadBases()); if ( swPairwiseAlignment.getAlignmentStart2wrt1() == -1 ) // sw can fail (reasons not clear) so if it happens just don't write the read diff --git a/protected/java/test/org/broadinstitute/sting/gatk/walkers/haplotypecaller/GenotypingEngineUnitTest.java b/protected/java/test/org/broadinstitute/sting/gatk/walkers/haplotypecaller/GenotypingEngineUnitTest.java index 6a66d9845..8633a1d9d 100644 --- a/protected/java/test/org/broadinstitute/sting/gatk/walkers/haplotypecaller/GenotypingEngineUnitTest.java +++ b/protected/java/test/org/broadinstitute/sting/gatk/walkers/haplotypecaller/GenotypingEngineUnitTest.java @@ -57,9 +57,9 @@ import org.broadinstitute.sting.BaseTest; import org.broadinstitute.sting.utils.*; import org.broadinstitute.sting.utils.fasta.CachingIndexedFastaSequenceFile; import org.broadinstitute.sting.utils.haplotype.Haplotype; +import org.broadinstitute.sting.utils.smithwaterman.SWPairwiseAlignment; import org.broadinstitute.variant.variantcontext.Allele; import org.broadinstitute.variant.variantcontext.VariantContext; -import org.broadinstitute.variant.variantcontext.VariantContextBuilder; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; diff --git a/protected/java/test/org/broadinstitute/sting/gatk/walkers/haplotypecaller/graphs/KBestPathsUnitTest.java b/protected/java/test/org/broadinstitute/sting/gatk/walkers/haplotypecaller/graphs/KBestPathsUnitTest.java index 3c6327842..90fdf1fa4 100644 --- a/protected/java/test/org/broadinstitute/sting/gatk/walkers/haplotypecaller/graphs/KBestPathsUnitTest.java +++ b/protected/java/test/org/broadinstitute/sting/gatk/walkers/haplotypecaller/graphs/KBestPathsUnitTest.java @@ -49,6 +49,8 @@ package org.broadinstitute.sting.gatk.walkers.haplotypecaller.graphs; import net.sf.samtools.Cigar; import net.sf.samtools.CigarElement; import net.sf.samtools.CigarOperator; +import net.sf.samtools.TextCigarCodec; +import org.broadinstitute.sting.BaseTest; import org.broadinstitute.sting.utils.Utils; import org.broadinstitute.sting.utils.sam.AlignmentUtils; import org.testng.Assert; @@ -63,7 +65,9 @@ import java.util.*; * Date: 1/31/13 */ -public class KBestPathsUnitTest { +public class KBestPathsUnitTest extends BaseTest { + private final static boolean DEBUG = false; + @DataProvider(name = "BasicPathFindingData") public Object[][] makeBasicPathFindingData() { List tests = new ArrayList(); @@ -96,7 +100,7 @@ public class KBestPathsUnitTest { return vertices; } - @Test(dataProvider = "BasicPathFindingData", enabled = true) + @Test(dataProvider = "BasicPathFindingData", enabled = !DEBUG) public void testBasicPathFinding(final int nStartNodes, final int nBranchesPerBubble, final int nEndNodes, final boolean addCycle, final boolean allowCycles) { SeqGraph graph = new SeqGraph(); @@ -128,7 +132,7 @@ public class KBestPathsUnitTest { Assert.assertTrue(justOne.get(0).pathsAreTheSame(best), "Best path from complete enumerate " + best + " not the same as from k = 1 search " + justOne.get(0)); } - @Test + @Test(enabled = !DEBUG) public void testPathFindingComplexCycle() { SeqGraph graph = new SeqGraph(); @@ -148,7 +152,7 @@ public class KBestPathsUnitTest { Assert.assertEquals(paths.size(), 1, "Didn't find the expected number of paths"); } - @Test + @Test(enabled = !DEBUG) public void testPathFindingCycleLastNode() { SeqGraph graph = new SeqGraph(); @@ -175,7 +179,7 @@ public class KBestPathsUnitTest { return tests.toArray(new Object[][]{}); } - @Test(dataProvider = "BasicBubbleDataProvider", enabled = true) + @Test(dataProvider = "BasicBubbleDataProvider", enabled = !DEBUG) public void testBasicBubbleData(final int refBubbleLength, final int altBubbleLength) { // Construct the assembly graph SeqGraph graph = new SeqGraph(3); @@ -232,7 +236,7 @@ public class KBestPathsUnitTest { return tests.toArray(new Object[][]{}); } - @Test(dataProvider = "GetBasesData", enabled = true) + @Test(dataProvider = "GetBasesData", enabled = !DEBUG) public void testGetBases(final List frags) { // Construct the assembly graph SeqGraph graph = new SeqGraph(3); @@ -268,7 +272,7 @@ public class KBestPathsUnitTest { return tests.toArray(new Object[][]{}); } - @Test(dataProvider = "TripleBubbleDataProvider", enabled = true) + @Test(dataProvider = "TripleBubbleDataProvider", enabled = !DEBUG) public void testTripleBubbleData(final int refBubbleLength, final int altBubbleLength, final boolean offRefBeginning, final boolean offRefEnding) { // Construct the assembly graph SeqGraph graph = new SeqGraph(); @@ -371,4 +375,120 @@ public class KBestPathsUnitTest { Assert.assertEquals(path.calculateCigar().toString(), AlignmentUtils.consolidateCigar(expectedCigar).toString(), "Cigar string mismatch"); } + + @Test(enabled = !DEBUG) + public void testIntraNodeInsertionDeletion() { + // Construct the assembly graph + SeqGraph graph = new SeqGraph(); + final SeqVertex top = new SeqVertex("T"); + final SeqVertex bot = new SeqVertex("T"); + final SeqVertex alt = new SeqVertex("AAACCCCC"); + final SeqVertex ref = new SeqVertex("CCCCCGGG"); + + graph.addVertices(top, bot, alt, ref); + graph.addEdges(new BaseEdge(true, 1), top, ref, bot); + graph.addEdges(new BaseEdge(false, 1), top, alt, bot); + + final KBestPaths pathFinder = new KBestPaths(); + final List> paths = pathFinder.getKBestPaths(graph, top, bot); + + Assert.assertEquals(paths.size(), 2); + + final Path refPath = paths.get(0); + final Path altPath = paths.get(1); + + Assert.assertEquals(refPath.calculateCigar().toString(), "10M"); + Assert.assertEquals(altPath.calculateCigar().toString(), "1M3I5M3D1M"); + } + + @Test(enabled = !DEBUG) + public void testHardSWPath() { + // Construct the assembly graph + SeqGraph graph = new SeqGraph(); + final SeqVertex top = new SeqVertex( "NNN"); + final SeqVertex bot = new SeqVertex( "NNN"); + final SeqVertex alt = new SeqVertex( "ACAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGA" ); + final SeqVertex ref = new SeqVertex( "TGTGTGTGTGTGTGACAGAGAGAGAGAGAGAGAGAGAGAGAGAGA" ); + graph.addVertices(top, bot, alt, ref); + graph.addEdges(new BaseEdge(true, 1), top, ref, bot); + graph.addEdges(new BaseEdge(false, 1), top, alt, bot); + + final KBestPaths pathFinder = new KBestPaths(); + final List> paths = pathFinder.getKBestPaths(graph, top, bot); + + Assert.assertEquals(paths.size(), 2); + + final Path refPath = paths.get(0); + final Path altPath = paths.get(1); + + logger.warn("RefPath : " + refPath + " cigar " + refPath.calculateCigar()); + logger.warn("AltPath : " + altPath + " cigar " + altPath.calculateCigar()); + + Assert.assertEquals(refPath.calculateCigar().toString(), "51M"); + Assert.assertEquals(altPath.calculateCigar().toString(), "3M14D2M20I32M"); + } + + // ----------------------------------------------------------------- + // + // Systematic tests to ensure that we get the correct SW result for + // a variety of variants in the ref vs alt bubble + // + // ----------------------------------------------------------------- + + @DataProvider(name = "SystematicRefAltSWTestData") + public Object[][] makeSystematicRefAltSWTestData() { + List tests = new ArrayList(); + + final List> allDiffs = Arrays.asList( + Arrays.asList("G", "C", "1M"), + Arrays.asList("G", "", "1D"), + Arrays.asList("", "C", "1I"), + Arrays.asList("AAA", "CGT", "3D3I"), + Arrays.asList("TAT", "CAC", "3M"), + Arrays.asList("AAAAA", "", "5D"), + Arrays.asList("", "AAAAA", "5I"), + Arrays.asList("AAAAACC", "CCGGGGGG", "5D2M6I") + ); + + for ( final String prefix : Arrays.asList("", "X", "XXXXXXXXXXXXX")) { + for ( final String end : Arrays.asList("", "X", "XXXXXXXXXXXXX")) { + for ( final List diffs : allDiffs ) + tests.add(new Object[]{prefix, end, diffs.get(0), diffs.get(1), diffs.get(2)}); + } + } + + return tests.toArray(new Object[][]{}); + } + + @Test(dataProvider = "SystematicRefAltSWTestData", enabled = true) + public void testRefAltSW(final String prefix, final String end, final String refMid, final String altMid, final String midCigar) { + // Construct the assembly graph + SeqGraph graph = new SeqGraph(); + + SeqVertex top = new SeqVertex(""); + SeqVertex ref = new SeqVertex(prefix + refMid + end); + SeqVertex alt = new SeqVertex(prefix + altMid + end); + SeqVertex bot = new SeqVertex(""); + + graph.addVertices(top, ref, alt, bot); + graph.addEdges(new BaseEdge(true, 1), top, ref, bot); + graph.addEdges(new BaseEdge(false, 1), top, alt, bot); + + // Construct the test path + Path path = Path.makePath(Arrays.asList(top, alt, bot), graph); + + Cigar expected = new Cigar(); + if ( ! prefix.equals("") ) expected.add(new CigarElement(prefix.length(), CigarOperator.M)); + for ( final CigarElement elt : TextCigarCodec.getSingleton().decode(midCigar).getCigarElements() ) expected.add(elt); + if ( ! end.equals("") ) expected.add(new CigarElement(end.length(), CigarOperator.M)); + expected = AlignmentUtils.consolidateCigar(expected); + + final Cigar pathCigar = path.calculateCigar(); + + logger.warn("diffs: " + ref + " vs. " + alt + " cigar " + midCigar); + logger.warn("Path " + path + " with cigar " + pathCigar); + logger.warn("Expected cigar " + expected); + + Assert.assertEquals(pathCigar, expected, "Cigar mismatch"); + } } diff --git a/public/java/test/org/broadinstitute/sting/utils/haplotypeBAMWriter/HaplotypeBAMWriterUnitTest.java b/protected/java/test/org/broadinstitute/sting/utils/haplotypeBAMWriter/HaplotypeBAMWriterUnitTest.java similarity index 59% rename from public/java/test/org/broadinstitute/sting/utils/haplotypeBAMWriter/HaplotypeBAMWriterUnitTest.java rename to protected/java/test/org/broadinstitute/sting/utils/haplotypeBAMWriter/HaplotypeBAMWriterUnitTest.java index db16582b8..91a2988aa 100644 --- a/public/java/test/org/broadinstitute/sting/utils/haplotypeBAMWriter/HaplotypeBAMWriterUnitTest.java +++ b/protected/java/test/org/broadinstitute/sting/utils/haplotypeBAMWriter/HaplotypeBAMWriterUnitTest.java @@ -1,26 +1,47 @@ /* -* 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. +* By downloading the PROGRAM you agree to the following terms of use: +* +* BROAD INSTITUTE - SOFTWARE LICENSE AGREEMENT - FOR ACADEMIC NON-COMMERCIAL RESEARCH PURPOSES ONLY +* +* This Agreement is made between the Broad Institute, Inc. with a principal address at 7 Cambridge Center, Cambridge, MA 02142 (BROAD) and the LICENSEE and is effective at the date the downloading is completed (EFFECTIVE DATE). +* +* WHEREAS, LICENSEE desires to license the PROGRAM, as defined hereinafter, and BROAD wishes to have this PROGRAM utilized in the public interest, subject only to the royalty-free, nonexclusive, nontransferable license rights of the United States Government pursuant to 48 CFR 52.227-14; and +* WHEREAS, LICENSEE desires to license the PROGRAM and BROAD desires to grant a license on the following terms and conditions. +* NOW, THEREFORE, in consideration of the promises and covenants made herein, the parties hereto agree as follows: +* +* 1. DEFINITIONS +* 1.1 PROGRAM shall mean copyright in the object code and source code known as GATK2 and related documentation, if any, as they exist on the EFFECTIVE DATE and can be downloaded from http://www.broadinstitute/GATK on the EFFECTIVE DATE. +* +* 2. LICENSE +* 2.1 Grant. Subject to the terms of this Agreement, BROAD hereby grants to LICENSEE, solely for academic non-commercial research purposes, a non-exclusive, non-transferable license to: (a) download, execute and display the PROGRAM and (b) create bug fixes and modify the PROGRAM. +* The LICENSEE may apply the PROGRAM in a pipeline to data owned by users other than the LICENSEE and provide these users the results of the PROGRAM provided LICENSEE does so for academic non-commercial purposes only. For clarification purposes, academic sponsored research is not a commercial use under the terms of this Agreement. +* 2.2 No Sublicensing or Additional Rights. LICENSEE shall not sublicense or distribute the PROGRAM, in whole or in part, without prior written permission from BROAD. LICENSEE shall ensure that all of its users agree to the terms of this Agreement. LICENSEE further agrees that it shall not put the PROGRAM on a network, server, or other similar technology that may be accessed by anyone other than the LICENSEE and its employees and users who have agreed to the terms of this agreement. +* 2.3 License Limitations. Nothing in this Agreement shall be construed to confer any rights upon LICENSEE by implication, estoppel, or otherwise to any computer software, trademark, intellectual property, or patent rights of BROAD, or of any other entity, except as expressly granted herein. LICENSEE agrees that the PROGRAM, in whole or part, shall not be used for any commercial purpose, including without limitation, as the basis of a commercial software or hardware product or to provide services. LICENSEE further agrees that the PROGRAM shall not be copied or otherwise adapted in order to circumvent the need for obtaining a license for use of the PROGRAM. +* +* 3. OWNERSHIP OF INTELLECTUAL PROPERTY +* LICENSEE acknowledges that title to the PROGRAM shall remain with BROAD. The PROGRAM is marked with the following BROAD copyright notice and notice of attribution to contributors. LICENSEE shall retain such notice on all copies. LICENSEE agrees to include appropriate attribution if any results obtained from use of the PROGRAM are included in any publication. +* Copyright 2012 Broad Institute, Inc. +* Notice of attribution: The GATK2 program was made available through the generosity of Medical and Population Genetics program at the Broad Institute, Inc. +* LICENSEE shall not use any trademark or trade name of BROAD, or any variation, adaptation, or abbreviation, of such marks or trade names, or any names of officers, faculty, students, employees, or agents of BROAD except as states above for attribution purposes. +* +* 4. INDEMNIFICATION +* LICENSEE shall indemnify, defend, and hold harmless BROAD, and their respective officers, faculty, students, employees, associated investigators and agents, and their respective successors, heirs and assigns, (Indemnitees), against any liability, damage, loss, or expense (including reasonable attorneys fees and expenses) incurred by or imposed upon any of the Indemnitees in connection with any claims, suits, actions, demands or judgments arising out of any theory of liability (including, without limitation, actions in the form of tort, warranty, or strict liability and regardless of whether such action has any factual basis) pursuant to any right or license granted under this Agreement. +* +* 5. NO REPRESENTATIONS OR WARRANTIES +* THE PROGRAM IS DELIVERED AS IS. BROAD MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE PROGRAM OR THE COPYRIGHT, EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, WHETHER OR NOT DISCOVERABLE. BROAD EXTENDS NO WARRANTIES OF ANY KIND AS TO PROGRAM CONFORMITY WITH WHATEVER USER MANUALS OR OTHER LITERATURE MAY BE ISSUED FROM TIME TO TIME. +* IN NO EVENT SHALL BROAD OR ITS RESPECTIVE DIRECTORS, OFFICERS, EMPLOYEES, AFFILIATED INVESTIGATORS AND AFFILIATES BE LIABLE FOR INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, INCLUDING, WITHOUT LIMITATION, ECONOMIC DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER BROAD SHALL BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT SHALL KNOW OF THE POSSIBILITY OF THE FOREGOING. +* +* 6. ASSIGNMENT +* This Agreement is personal to LICENSEE and any rights or obligations assigned by LICENSEE without the prior written consent of BROAD shall be null and void. +* +* 7. MISCELLANEOUS +* 7.1 Export Control. LICENSEE gives assurance that it will comply with all United States export control laws and regulations controlling the export of the PROGRAM, including, without limitation, all Export Administration Regulations of the United States Department of Commerce. Among other things, these laws and regulations prohibit, or require a license for, the export of certain types of software to specified countries. +* 7.2 Termination. LICENSEE shall have the right to terminate this Agreement for any reason upon prior written notice to BROAD. If LICENSEE breaches any provision hereunder, and fails to cure such breach within thirty (30) days, BROAD may terminate this Agreement immediately. Upon termination, LICENSEE shall provide BROAD with written assurance that the original and all copies of the PROGRAM have been destroyed, except that, upon prior written authorization from BROAD, LICENSEE may retain a copy for archive purposes. +* 7.3 Survival. The following provisions shall survive the expiration or termination of this Agreement: Articles 1, 3, 4, 5 and Sections 2.2, 2.3, 7.3, and 7.4. +* 7.4 Notice. Any notices under this Agreement shall be in writing, shall specifically refer to this Agreement, and shall be sent by hand, recognized national overnight courier, confirmed facsimile transmission, confirmed electronic mail, or registered or certified mail, postage prepaid, return receipt requested. All notices under this Agreement shall be deemed effective upon receipt. +* 7.5 Amendment and Waiver; Entire Agreement. This Agreement may be amended, supplemented, or otherwise modified only by means of a written instrument signed by all parties. Any waiver of any rights or failure to act in a specific instance shall relate only to such instance and shall not be construed as an agreement to waive any rights or fail to act in any other instance, whether or not similar. This Agreement constitutes the entire agreement among the parties with respect to its subject matter and supersedes prior agreements or understandings between the parties relating to its subject matter. +* 7.6 Binding Effect; Headings. This Agreement shall be binding upon and inure to the benefit of the parties and their respective permitted successors and assigns. All headings are for convenience only and shall not affect the meaning of any provision of this Agreement. +* 7.7 Governing Law. This Agreement shall be construed, governed, interpreted and applied in accordance with the internal laws of the Commonwealth of Massachusetts, U.S.A., without regard to conflict of laws principles. */ package org.broadinstitute.sting.utils.haplotypeBAMWriter; @@ -28,7 +49,7 @@ package org.broadinstitute.sting.utils.haplotypeBAMWriter; import net.sf.samtools.*; import org.broadinstitute.sting.BaseTest; import org.broadinstitute.sting.utils.haplotype.Haplotype; -import org.broadinstitute.sting.utils.SWPairwiseAlignment; +import org.broadinstitute.sting.utils.smithwaterman.SWPairwiseAlignment; import org.broadinstitute.sting.utils.Utils; import org.broadinstitute.sting.utils.sam.AlignmentUtils; import org.broadinstitute.sting.utils.sam.ArtificialSAMUtils; diff --git a/protected/java/test/org/broadinstitute/sting/utils/SWPairwiseAlignmentUnitTest.java b/protected/java/test/org/broadinstitute/sting/utils/smithwaterman/SWPairwiseAlignmentUnitTest.java similarity index 88% rename from protected/java/test/org/broadinstitute/sting/utils/SWPairwiseAlignmentUnitTest.java rename to protected/java/test/org/broadinstitute/sting/utils/smithwaterman/SWPairwiseAlignmentUnitTest.java index c55b4147d..c8fc458e8 100644 --- a/protected/java/test/org/broadinstitute/sting/utils/SWPairwiseAlignmentUnitTest.java +++ b/protected/java/test/org/broadinstitute/sting/utils/smithwaterman/SWPairwiseAlignmentUnitTest.java @@ -44,7 +44,7 @@ * 7.7 Governing Law. This Agreement shall be construed, governed, interpreted and applied in accordance with the internal laws of the Commonwealth of Massachusetts, U.S.A., without regard to conflict of laws principles. */ -package org.broadinstitute.sting.utils; +package org.broadinstitute.sting.utils.smithwaterman; import org.broadinstitute.sting.BaseTest; import org.testng.Assert; @@ -91,4 +91,30 @@ public class SWPairwiseAlignmentUnitTest extends BaseTest { Assert.assertEquals(sw.getAlignmentStart2wrt1(), expectedStart); Assert.assertEquals(sw.getCigar().toString(), expectedCigar); } + + @Test(enabled = true) + public void testIndelsAtStartAndEnd() { + final String match = "CCCCC"; + final String reference = "AAA" + match; + final String read = match + "GGG"; + final int expectedStart = 3; + final String expectedCigar = "5M3S"; + final SWPairwiseAlignment sw = new SWPairwiseAlignment(reference.getBytes(), read.getBytes()); + sw.printAlignment(reference.getBytes(), read.getBytes()); + Assert.assertEquals(sw.getAlignmentStart2wrt1(), expectedStart); + Assert.assertEquals(sw.getCigar().toString(), expectedCigar); + } + + @Test(enabled = true) + public void testDegenerateAlignmentWithIndelsAtBothEnds() { + logger.warn("testDegenerateAlignmentWithIndelsAtBothEnds"); + final String ref = "TGTGTGTGTGTGTGACAGAGAGAGAGAGAGAGAGAGAGAGAGAGA"; + final String alt = "ACAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGA"; + final int expectedStart = 14; + final String expectedCigar = "31M20S"; + final SWPairwiseAlignment sw = new SWPairwiseAlignment(ref.getBytes(), alt.getBytes(), SWParameterSet.STANDARD_NGS); + sw.printAlignment(ref.getBytes(), alt.getBytes()); + Assert.assertEquals(sw.getAlignmentStart2wrt1(), expectedStart); + Assert.assertEquals(sw.getCigar().toString(), expectedCigar); + } } diff --git a/public/java/src/org/broadinstitute/sting/utils/haplotypeBAMWriter/AllHaplotypeBAMWriter.java b/public/java/src/org/broadinstitute/sting/utils/haplotypeBAMWriter/AllHaplotypeBAMWriter.java deleted file mode 100644 index 9936bd9ab..000000000 --- a/public/java/src/org/broadinstitute/sting/utils/haplotypeBAMWriter/AllHaplotypeBAMWriter.java +++ /dev/null @@ -1,77 +0,0 @@ -/* -* 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.utils.haplotypeBAMWriter; - -import net.sf.samtools.*; -import org.broadinstitute.sting.utils.GenomeLoc; -import org.broadinstitute.sting.utils.haplotype.Haplotype; -import org.broadinstitute.sting.utils.genotyper.MostLikelyAllele; -import org.broadinstitute.sting.utils.genotyper.PerReadAlleleLikelihoodMap; -import org.broadinstitute.sting.utils.sam.GATKSAMRecord; -import org.broadinstitute.variant.variantcontext.Allele; - -import java.util.*; - -/** - * A haplotype bam writer that writes out all haplotypes as reads and then - * the alignment of reach read to its best match among the best haplotypes. - * - * Primarily useful for people working on the HaplotypeCaller method itself - * - * User: depristo - * Date: 2/22/13 - * Time: 1:50 PM - */ -class AllHaplotypeBAMWriter extends HaplotypeBAMWriter { - public AllHaplotypeBAMWriter(final SAMFileWriter bamWriter) { - super(bamWriter); - } - - /** - * {@inheritDoc} - */ - @Override - public void writeReadsAlignedToHaplotypes(final List haplotypes, - final GenomeLoc paddedReferenceLoc, - final List bestHaplotypes, - final Set calledHaplotypes, - final Map stratifiedReadMap) { - writeHaplotypesAsReads(haplotypes, new HashSet(bestHaplotypes), paddedReferenceLoc); - - // we need to remap the Alleles back to the Haplotypes; inefficient but unfortunately this is a requirement currently - final Map alleleToHaplotypeMap = new HashMap(haplotypes.size()); - for ( final Haplotype haplotype : haplotypes ) - alleleToHaplotypeMap.put(Allele.create(haplotype.getBases()), haplotype); - - // next, output the interesting reads for each sample aligned against the appropriate haplotype - for ( final PerReadAlleleLikelihoodMap readAlleleLikelihoodMap : stratifiedReadMap.values() ) { - for ( Map.Entry> entry : readAlleleLikelihoodMap.getLikelihoodReadMap().entrySet() ) { - final MostLikelyAllele bestAllele = PerReadAlleleLikelihoodMap.getMostLikelyAllele(entry.getValue()); - writeReadAgainstHaplotype(entry.getKey(), alleleToHaplotypeMap.get(bestAllele.getMostLikelyAllele()), paddedReferenceLoc.getStart()); - } - } - } -} diff --git a/public/java/src/org/broadinstitute/sting/utils/haplotypeBAMWriter/CalledHaplotypeBAMWriter.java b/public/java/src/org/broadinstitute/sting/utils/haplotypeBAMWriter/CalledHaplotypeBAMWriter.java deleted file mode 100644 index 08b4fff7c..000000000 --- a/public/java/src/org/broadinstitute/sting/utils/haplotypeBAMWriter/CalledHaplotypeBAMWriter.java +++ /dev/null @@ -1,87 +0,0 @@ -/* -* 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.utils.haplotypeBAMWriter; - -import net.sf.samtools.SAMFileWriter; -import org.broadinstitute.sting.utils.GenomeLoc; -import org.broadinstitute.sting.utils.haplotype.Haplotype; -import org.broadinstitute.sting.utils.genotyper.MostLikelyAllele; -import org.broadinstitute.sting.utils.genotyper.PerReadAlleleLikelihoodMap; -import org.broadinstitute.sting.utils.sam.GATKSAMRecord; -import org.broadinstitute.variant.variantcontext.Allele; - -import java.util.*; - -/** - * Writes a BAM containing just the reads in stratifiedReadMap aligned to their - * most likely haplotype among all of the called haplotypes. - * - * Primarily useful for users of the HaplotypeCaller who want to better understand the - * support of their calls w.r.t. the reads. - * - * User: depristo - * Date: 2/22/13 - * Time: 1:50 PM - */ -class CalledHaplotypeBAMWriter extends HaplotypeBAMWriter { - public CalledHaplotypeBAMWriter(final SAMFileWriter bamWriter) { - super(bamWriter); - } - - /** - * {@inheritDoc} - */ - @Override - public void writeReadsAlignedToHaplotypes(final List haplotypes, - final GenomeLoc paddedReferenceLoc, - final List bestHaplotypes, - final Set calledHaplotypes, - final Map stratifiedReadMap) { - if ( calledHaplotypes.isEmpty() ) // only write out called haplotypes - return; - - writeHaplotypesAsReads(calledHaplotypes, calledHaplotypes, paddedReferenceLoc); - - // we need to remap the Alleles back to the Haplotypes; inefficient but unfortunately this is a requirement currently - final Map alleleToHaplotypeMap = new HashMap(haplotypes.size()); - for ( final Haplotype haplotype : calledHaplotypes ) { - alleleToHaplotypeMap.put(Allele.create(haplotype.getBases()), haplotype); - } - - // the set of all alleles that were actually called - final Set allelesOfCalledHaplotypes = alleleToHaplotypeMap.keySet(); - - // next, output the interesting reads for each sample aligned against one of the called haplotypes - for ( final PerReadAlleleLikelihoodMap readAlleleLikelihoodMap : stratifiedReadMap.values() ) { - for ( Map.Entry> entry : readAlleleLikelihoodMap.getLikelihoodReadMap().entrySet() ) { - if ( entry.getKey().getMappingQuality() > 0 ) { - final MostLikelyAllele bestAllele = PerReadAlleleLikelihoodMap.getMostLikelyAllele(entry.getValue(), allelesOfCalledHaplotypes); - writeReadAgainstHaplotype(entry.getKey(), alleleToHaplotypeMap.get(bestAllele.getMostLikelyAllele()), paddedReferenceLoc.getStart()); - } - } - } - } -} diff --git a/public/java/src/org/broadinstitute/sting/utils/smithwaterman/Parameters.java b/public/java/src/org/broadinstitute/sting/utils/smithwaterman/Parameters.java new file mode 100644 index 000000000..d4364afdf --- /dev/null +++ b/public/java/src/org/broadinstitute/sting/utils/smithwaterman/Parameters.java @@ -0,0 +1,60 @@ +/* +* 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.utils.smithwaterman; + +/** + * Holds the core Smith-Waterman alignment parameters of + * + * match value, and mismatch, gap open and gap extension penalties + * + * User: depristo + * Date: 4/11/13 + * Time: 12:03 PM + */ +public final class Parameters { + public final double w_match; + public final double w_mismatch; + public final double w_open; + public final double w_extend; + + /** + * Create a new set of SW parameters + * @param w_match the match score + * @param w_mismatch the mismatch penalty + * @param w_open the gap open penalty + * @param w_extend the gap extension penalty + */ + public Parameters(double w_match, double w_mismatch, double w_open, double w_extend) { + if ( w_mismatch > 0 ) throw new IllegalArgumentException("w_mismatch must be <= 0 but got " + w_mismatch); + if ( w_open> 0 ) throw new IllegalArgumentException("w_open must be <= 0 but got " + w_open); + if ( w_extend> 0 ) throw new IllegalArgumentException("w_extend must be <= 0 but got " + w_extend); + + this.w_match = w_match; + this.w_mismatch = w_mismatch; + this.w_open = w_open; + this.w_extend = w_extend; + } +} diff --git a/public/java/src/org/broadinstitute/sting/utils/SWPairwiseAlignment.java b/public/java/src/org/broadinstitute/sting/utils/smithwaterman/SWPairwiseAlignment.java similarity index 88% rename from public/java/src/org/broadinstitute/sting/utils/SWPairwiseAlignment.java rename to public/java/src/org/broadinstitute/sting/utils/smithwaterman/SWPairwiseAlignment.java index 6c8beb32d..890faa82a 100644 --- a/public/java/src/org/broadinstitute/sting/utils/SWPairwiseAlignment.java +++ b/public/java/src/org/broadinstitute/sting/utils/smithwaterman/SWPairwiseAlignment.java @@ -1,424 +1,458 @@ -/* -* 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.utils; - -import net.sf.samtools.Cigar; -import net.sf.samtools.CigarElement; -import net.sf.samtools.CigarOperator; -import org.broadinstitute.sting.utils.collections.Pair; -import org.broadinstitute.sting.utils.exceptions.StingException; -import org.broadinstitute.sting.utils.sam.AlignmentUtils; - -import java.util.*; - -/** - * Pairwise discrete smith-waterman alignment - * - * ************************************************************************ - * **** IMPORTANT NOTE: **** - * **** This class assumes that all bytes come from UPPERCASED chars! **** - * ************************************************************************ - * - * User: asivache - * Date: Mar 23, 2009 - * Time: 1:54:54 PM - */ -public final class SWPairwiseAlignment { - private int alignment_offset; // offset of s2 w/respect to s1 - private Cigar alignmentCigar; - - private final double w_match; - private final double w_mismatch; - private final double w_open; - private final double w_extend; - - private static final int MSTATE = 0; - private static final int ISTATE = 1; - private static final int DSTATE = 2; - private static final int CLIP = 3; - - protected static boolean cutoff = false; - private static boolean DO_SOFTCLIP = true; - - double[] SW; - - public SWPairwiseAlignment(byte[] seq1, byte[] seq2, double match, double mismatch, double open, double extend ) { - w_match = match; - w_mismatch = mismatch; - w_open = open; - w_extend = extend; - align(seq1,seq2); - } - - public SWPairwiseAlignment(byte[] seq1, byte[] seq2) { - this(seq1,seq2,1.0,-1.0/3.0,-1.0-1.0/3.0,-1.0/3.0); // match=1, mismatch = -1/3, gap=-(1+k/3) - } - - public Cigar getCigar() { return alignmentCigar ; } - - public int getAlignmentStart2wrt1() { return alignment_offset; } - - public void align(final byte[] a, final byte[] b) { - final int n = a.length; - final int m = b.length; - double [] sw = new double[(n+1)*(m+1)]; - SW = sw; - int [] btrack = new int[(n+1)*(m+1)]; - - calculateMatrix(a, b, sw, btrack); - calculateCigar(n, m, sw, btrack); // length of the segment (continuous matches, insertions or deletions) - } - - - private void calculateMatrix(final byte[] a, final byte[] b, double [] sw, int [] btrack ) { - final int n = a.length+1; - final int m = b.length+1; - - //final double MATRIX_MIN_CUTOFF=-1e100; // never let matrix elements drop below this cutoff - final double MATRIX_MIN_CUTOFF; // never let matrix elements drop below this cutoff - if ( cutoff ) MATRIX_MIN_CUTOFF = 0.0; - else MATRIX_MIN_CUTOFF = -1e100; - - double [] best_gap_v = new double[m+1]; - Arrays.fill(best_gap_v,-1.0e40); - int [] gap_size_v = new int[m+1]; - double [] best_gap_h = new double[n+1]; - Arrays.fill(best_gap_h,-1.0e40); - int [] gap_size_h = new int[n+1]; - - // build smith-waterman matrix and keep backtrack info: - for ( int i = 1, row_offset_1 = 0 ; i < n ; i++ ) { // we do NOT update row_offset_1 here, see comment at the end of this outer loop - byte a_base = a[i-1]; // letter in a at the current pos - - final int row_offset = row_offset_1 + m; - - // On the entrance into the loop, row_offset_1 is the (linear) offset - // of the first element of row (i-1) and row_offset is the linear offset of the - // start of row i - - for ( int j = 1, data_offset_1 = row_offset_1 ; j < m ; j++, data_offset_1++ ) { - - // data_offset_1 is linearized offset of element [i-1][j-1] - - final byte b_base = b[j-1]; // letter in b at the current pos - - // in other words, step_diag = sw[i-1][j-1] + wd(a_base,b_base); - double step_diag = sw[data_offset_1] + wd(a_base,b_base); - - // optimized "traversal" of all the matrix cells above the current one (i.e. traversing - // all 'step down' events that would end in the current cell. The optimized code - // does exactly the same thing as the commented out loop below. IMPORTANT: - // the optimization works ONLY for linear w(k)=wopen+(k-1)*wextend!!!! - - // if a gap (length 1) was just opened above, this is the cost of arriving to the current cell: - double prev_gap = sw[data_offset_1+1]+w_open; - - best_gap_v[j] += w_extend; // for the gaps that were already opened earlier, extending them by 1 costs w_extend - - if ( prev_gap > best_gap_v[j] ) { - // opening a gap just before the current cell results in better score than extending by one - // the best previously opened gap. This will hold for ALL cells below: since any gap - // once opened always costs w_extend to extend by another base, we will always get a better score - // by arriving to any cell below from the gap we just opened (prev_gap) rather than from the previous best gap - best_gap_v[j] = prev_gap; - gap_size_v[j] = 1; // remember that the best step-down gap from above has length 1 (we just opened it) - } else { - // previous best gap is still the best, even after extension by another base, so we just record that extension: - gap_size_v[j]++; - } - - final double step_down = best_gap_v[j] ; - final int kd = gap_size_v[j]; - - // optimized "traversal" of all the matrix cells to the left of the current one (i.e. traversing - // all 'step right' events that would end in the current cell. The optimized code - // does exactly the same thing as the commented out loop below. IMPORTANT: - // the optimization works ONLY for linear w(k)=wopen+(k-1)*wextend!!!! - - final int data_offset = row_offset + j; // linearized offset of element [i][j] - prev_gap = sw[data_offset-1]+w_open; // what would it cost us to open length 1 gap just to the left from current cell - best_gap_h[i] += w_extend; // previous best gap would cost us that much if extended by another base - - if ( prev_gap > best_gap_h[i] ) { - // newly opened gap is better (score-wise) than any previous gap with the same row index i; since - // gap penalty is linear with k, this new gap location is going to remain better than any previous ones - best_gap_h[i] = prev_gap; - gap_size_h[i] = 1; - } else { - gap_size_h[i]++; - } - - final double step_right = best_gap_h[i]; - final int ki = gap_size_h[i]; - - if ( step_down > step_right ) { - if ( step_down > step_diag ) { - sw[data_offset] = Math.max(MATRIX_MIN_CUTOFF,step_down); - btrack[data_offset] = kd ; // positive=vertical - } else { - sw[data_offset] = Math.max(MATRIX_MIN_CUTOFF,step_diag); - btrack[data_offset] = 0; // 0 = diagonal - } - } else { - // step_down <= step_right - if ( step_right > step_diag ) { - sw[data_offset] = Math.max(MATRIX_MIN_CUTOFF,step_right); - btrack[data_offset] = -ki; // negative = horizontal - } else { - sw[data_offset] = Math.max(MATRIX_MIN_CUTOFF,step_diag); - btrack[data_offset] = 0; // 0 = diagonal - } - } - } - - // IMPORTANT, IMPORTANT, IMPORTANT: - // note that we update this (secondary) outer loop variable here, - // so that we DO NOT need to update it - // in the for() statement itself. - row_offset_1 = row_offset; - } - } - - - private void calculateCigar(int n, int m, double [] sw, int [] btrack) { - // p holds the position we start backtracking from; we will be assembling a cigar in the backwards order - int p1 = 0, p2 = 0; - - double maxscore = Double.NEGATIVE_INFINITY; // sw scores are allowed to be negative - int segment_length = 0; // length of the segment (continuous matches, insertions or deletions) - - // look for largest score. we use >= combined with the traversal direction - // to ensure that if two scores are equal, the one closer to diagonal gets picked - for ( int i = 1, data_offset = m+1+m ; i < n+1 ; i++, data_offset += (m+1) ) { - // data_offset is the offset of [i][m] - if ( sw[data_offset] >= maxscore ) { - p1 = i; p2 = m ; maxscore = sw[data_offset]; - } - } - - for ( int j = 1, data_offset = n*(m+1)+1 ; j < m+1 ; j++, data_offset++ ) { - // data_offset is the offset of [n][j] - if ( sw[data_offset] > maxscore || sw[data_offset] == maxscore && Math.abs(n-j) < Math.abs(p1 - p2)) { - p1 = n; - p2 = j ; - maxscore = sw[data_offset]; - segment_length = m - j ; // end of sequence 2 is overhanging; we will just record it as 'M' segment - } - } - - List lce = new ArrayList(5); - - if ( segment_length > 0 && DO_SOFTCLIP ) { - lce.add(makeElement(CLIP, segment_length)); - segment_length = 0; - } - - // we will be placing all insertions and deletions into sequence b, so the states are named w/regard - // to that sequence - - int state = MSTATE; - - int data_offset = p1*(m+1)+p2; // offset of element [p1][p2] - do { - int btr = btrack[data_offset]; - - int new_state; - int step_length = 1; - - if ( btr > 0 ) { - new_state = DSTATE; - step_length = btr; - } else if ( btr < 0 ) { - new_state = ISTATE; - step_length = (-btr); - } else new_state = MSTATE; // and step_length =1, already set above - - // move to next best location in the sw matrix: - switch( new_state ) { - case MSTATE: data_offset -= (m+2); p1--; p2--; break; // move back along the diag in the sw matrix - case ISTATE: data_offset -= step_length; p2 -= step_length; break; // move left - case DSTATE: data_offset -= (m+1)*step_length; p1 -= step_length; break; // move up - } - - // now let's see if the state actually changed: - if ( new_state == state ) segment_length+=step_length; - else { - // state changed, lets emit previous segment, whatever it was (Insertion Deletion, or (Mis)Match). - lce.add(makeElement(state, segment_length)); - segment_length = step_length; - state = new_state; - } -// next condition is equivalent to while ( sw[p1][p2] != 0 ) (with modified p1 and/or p2: - } while ( p1 > 0 && p2 > 0 ); - - // post-process the last segment we are still keeping; - // NOTE: if reads "overhangs" the ref on the left (i.e. if p2>0) we are counting - // those extra bases sticking out of the ref into the first cigar element if DO_SOFTCLIP is false; - // otherwise they will be softclipped. For instance, - // if read length is 5 and alignment starts at offset -2 (i.e. read starts before the ref, and only - // last 3 bases of the read overlap with/align to the ref), the cigar will be still 5M if - // DO_SOFTCLIP is false or 2S3M if DO_SOFTCLIP is true. - // The consumers need to check for the alignment offset and deal with it properly. - if (DO_SOFTCLIP ) { - lce.add(makeElement(state, segment_length)); - if ( p2> 0 ) lce.add(makeElement(CLIP, p2)); - alignment_offset = p1 ; - } else { - lce.add(makeElement(state, segment_length + p2)); - alignment_offset = p1 - p2; - } - - Collections.reverse(lce); - alignmentCigar = AlignmentUtils.consolidateCigar(new Cigar(lce)); - } - - private CigarElement makeElement(int state, int segment_length) { - CigarOperator o = null; - switch(state) { - case MSTATE: o = CigarOperator.M; break; - case ISTATE: o = CigarOperator.I; break; - case DSTATE: o = CigarOperator.D; break; - case CLIP: o = CigarOperator.S; break; - } - return new CigarElement(segment_length,o); - } - - private double wd(byte x, byte y) { - return (x == y ? w_match : w_mismatch); - } - - public void printAlignment(byte[] ref, byte[] read) { - printAlignment(ref,read,100); - } - - public void printAlignment(byte[] ref, byte[] read, int width) { - StringBuilder bread = new StringBuilder(); - StringBuilder bref = new StringBuilder(); - StringBuilder match = new StringBuilder(); - - int i = 0; - int j = 0; - - final int offset = getAlignmentStart2wrt1(); - - Cigar cigar = getCigar(); - - if ( ! DO_SOFTCLIP ) { - - // we need to go through all the hassle below only if we do not do softclipping; - // otherwise offset is never negative - if ( offset < 0 ) { - for ( ; j < (-offset) ; j++ ) { - bread.append((char)read[j]); - bref.append(' '); - match.append(' '); - } - // at negative offsets, our cigar's first element carries overhanging bases - // that we have just printed above. Tweak the first element to - // exclude those bases. Here we create a new list of cigar elements, so the original - // list/original cigar are unchanged (they are unmodifiable anyway!) - - List tweaked = new ArrayList(); - tweaked.addAll(cigar.getCigarElements()); - tweaked.set(0,new CigarElement(cigar.getCigarElement(0).getLength()+offset, - cigar.getCigarElement(0).getOperator())); - cigar = new Cigar(tweaked); - } - } - - if ( offset > 0 ) { // note: the way this implementation works, cigar will ever start from S *only* if read starts before the ref, i.e. offset = 0 - for ( ; i < getAlignmentStart2wrt1() ; i++ ) { - bref.append((char)ref[i]); - bread.append(' '); - match.append(' '); - } - } - - for ( CigarElement e : cigar.getCigarElements() ) { - switch (e.getOperator()) { - case M : - for ( int z = 0 ; z < e.getLength() ; z++, i++, j++ ) { - bref.append((i= s.length() ) { - System.out.println(); - return; - } - int end = Math.min(start+width,s.length()); - System.out.println(s.substring(start,end)); - } -} +/* +* 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.utils.smithwaterman; + +import net.sf.samtools.Cigar; +import net.sf.samtools.CigarElement; +import net.sf.samtools.CigarOperator; +import org.broadinstitute.sting.utils.exceptions.StingException; +import org.broadinstitute.sting.utils.sam.AlignmentUtils; + +import java.util.*; + +/** + * Pairwise discrete smith-waterman alignment + * + * ************************************************************************ + * **** IMPORTANT NOTE: **** + * **** This class assumes that all bytes come from UPPERCASED chars! **** + * ************************************************************************ + * + * User: asivache + * Date: Mar 23, 2009 + * Time: 1:54:54 PM + */ +public final class SWPairwiseAlignment { + private int alignment_offset; // offset of s2 w/respect to s1 + private Cigar alignmentCigar; + + private final Parameters parameters; + + private static final int MSTATE = 0; + private static final int ISTATE = 1; + private static final int DSTATE = 2; + private static final int CLIP = 3; + + protected static boolean cutoff = false; + private static boolean DO_SOFTCLIP = true; + + /** + * The SW scoring matrix, stored for debugging purposes if keepScoringMatrix is true + */ + protected double[] SW = null; + + /** + * Only for testing purposes in the SWPairwiseAlignmentMain function + * set to true to keep SW scoring matrix after align call + */ + protected static boolean keepScoringMatrix = false; + + /** + * Create a new SW pairwise aligner. + * + * @deprecated in favor of constructors using the Parameter or ParameterSet class + */ + @Deprecated + public SWPairwiseAlignment(byte[] seq1, byte[] seq2, double match, double mismatch, double open, double extend ) { + this(seq1, seq2, new Parameters(match, mismatch, open, extend)); + } + + /** + * Create a new SW pairwise aligner + * + * After creating the object the two sequences are aligned with an internal call to align(seq1, seq2) + * + * @param seq1 the first sequence we want to align + * @param seq2 the second sequence we want to align + * @param parameters the SW parameters to use + */ + public SWPairwiseAlignment(byte[] seq1, byte[] seq2, Parameters parameters) { + this.parameters = parameters; + align(seq1,seq2); + } + + /** + * Create a new SW pairwise aligner + * + * After creating the object the two sequences are aligned with an internal call to align(seq1, seq2) + * + * @param seq1 the first sequence we want to align + * @param seq2 the second sequence we want to align + * @param namedParameters the named parameter set to get our parameters from + */ + public SWPairwiseAlignment(byte[] seq1, byte[] seq2, SWParameterSet namedParameters) { + this(seq1, seq2, namedParameters.parameters); + } + + public SWPairwiseAlignment(byte[] seq1, byte[] seq2) { + this(seq1,seq2,SWParameterSet.ORIGINAL_DEFAULT); + } + + public Cigar getCigar() { return alignmentCigar ; } + + public int getAlignmentStart2wrt1() { return alignment_offset; } + + public void align(final byte[] a, final byte[] b) { + final int n = a.length; + final int m = b.length; + double [] sw = new double[(n+1)*(m+1)]; + if ( keepScoringMatrix ) SW = sw; + int [] btrack = new int[(n+1)*(m+1)]; + + calculateMatrix(a, b, sw, btrack); + calculateCigar(n, m, sw, btrack); // length of the segment (continuous matches, insertions or deletions) + } + + + private void calculateMatrix(final byte[] a, final byte[] b, double [] sw, int [] btrack ) { + final int n = a.length+1; + final int m = b.length+1; + + //final double MATRIX_MIN_CUTOFF=-1e100; // never let matrix elements drop below this cutoff + final double MATRIX_MIN_CUTOFF; // never let matrix elements drop below this cutoff + if ( cutoff ) MATRIX_MIN_CUTOFF = 0.0; + else MATRIX_MIN_CUTOFF = -1e100; + + double [] best_gap_v = new double[m+1]; + Arrays.fill(best_gap_v,-1.0e40); + int [] gap_size_v = new int[m+1]; + double [] best_gap_h = new double[n+1]; + Arrays.fill(best_gap_h,-1.0e40); + int [] gap_size_h = new int[n+1]; + + // build smith-waterman matrix and keep backtrack info: + for ( int i = 1, row_offset_1 = 0 ; i < n ; i++ ) { // we do NOT update row_offset_1 here, see comment at the end of this outer loop + byte a_base = a[i-1]; // letter in a at the current pos + + final int row_offset = row_offset_1 + m; + + // On the entrance into the loop, row_offset_1 is the (linear) offset + // of the first element of row (i-1) and row_offset is the linear offset of the + // start of row i + + for ( int j = 1, data_offset_1 = row_offset_1 ; j < m ; j++, data_offset_1++ ) { + + // data_offset_1 is linearized offset of element [i-1][j-1] + + final byte b_base = b[j-1]; // letter in b at the current pos + + // in other words, step_diag = sw[i-1][j-1] + wd(a_base,b_base); + double step_diag = sw[data_offset_1] + wd(a_base,b_base); + + // optimized "traversal" of all the matrix cells above the current one (i.e. traversing + // all 'step down' events that would end in the current cell. The optimized code + // does exactly the same thing as the commented out loop below. IMPORTANT: + // the optimization works ONLY for linear w(k)=wopen+(k-1)*wextend!!!! + + // if a gap (length 1) was just opened above, this is the cost of arriving to the current cell: + double prev_gap = sw[data_offset_1+1]+parameters.w_open; + + best_gap_v[j] += parameters.w_extend; // for the gaps that were already opened earlier, extending them by 1 costs w_extend + + if ( prev_gap > best_gap_v[j] ) { + // opening a gap just before the current cell results in better score than extending by one + // the best previously opened gap. This will hold for ALL cells below: since any gap + // once opened always costs w_extend to extend by another base, we will always get a better score + // by arriving to any cell below from the gap we just opened (prev_gap) rather than from the previous best gap + best_gap_v[j] = prev_gap; + gap_size_v[j] = 1; // remember that the best step-down gap from above has length 1 (we just opened it) + } else { + // previous best gap is still the best, even after extension by another base, so we just record that extension: + gap_size_v[j]++; + } + + final double step_down = best_gap_v[j] ; + final int kd = gap_size_v[j]; + + // optimized "traversal" of all the matrix cells to the left of the current one (i.e. traversing + // all 'step right' events that would end in the current cell. The optimized code + // does exactly the same thing as the commented out loop below. IMPORTANT: + // the optimization works ONLY for linear w(k)=wopen+(k-1)*wextend!!!! + + final int data_offset = row_offset + j; // linearized offset of element [i][j] + prev_gap = sw[data_offset-1]+parameters.w_open; // what would it cost us to open length 1 gap just to the left from current cell + best_gap_h[i] += parameters.w_extend; // previous best gap would cost us that much if extended by another base + + if ( prev_gap > best_gap_h[i] ) { + // newly opened gap is better (score-wise) than any previous gap with the same row index i; since + // gap penalty is linear with k, this new gap location is going to remain better than any previous ones + best_gap_h[i] = prev_gap; + gap_size_h[i] = 1; + } else { + gap_size_h[i]++; + } + + final double step_right = best_gap_h[i]; + final int ki = gap_size_h[i]; + + if ( step_down > step_right ) { + if ( step_down > step_diag ) { + sw[data_offset] = Math.max(MATRIX_MIN_CUTOFF,step_down); + btrack[data_offset] = kd ; // positive=vertical + } else { + sw[data_offset] = Math.max(MATRIX_MIN_CUTOFF,step_diag); + btrack[data_offset] = 0; // 0 = diagonal + } + } else { + // step_down <= step_right + if ( step_right > step_diag ) { + sw[data_offset] = Math.max(MATRIX_MIN_CUTOFF,step_right); + btrack[data_offset] = -ki; // negative = horizontal + } else { + sw[data_offset] = Math.max(MATRIX_MIN_CUTOFF,step_diag); + btrack[data_offset] = 0; // 0 = diagonal + } + } + } + + // IMPORTANT, IMPORTANT, IMPORTANT: + // note that we update this (secondary) outer loop variable here, + // so that we DO NOT need to update it + // in the for() statement itself. + row_offset_1 = row_offset; + } + } + + + private void calculateCigar(int n, int m, double [] sw, int [] btrack) { + // p holds the position we start backtracking from; we will be assembling a cigar in the backwards order + int p1 = 0, p2 = 0; + + double maxscore = Double.NEGATIVE_INFINITY; // sw scores are allowed to be negative + int segment_length = 0; // length of the segment (continuous matches, insertions or deletions) + + // look for largest score. we use >= combined with the traversal direction + // to ensure that if two scores are equal, the one closer to diagonal gets picked + for ( int i = 1, data_offset = m+1+m ; i < n+1 ; i++, data_offset += (m+1) ) { + // data_offset is the offset of [i][m] + if ( sw[data_offset] >= maxscore ) { + p1 = i; p2 = m ; maxscore = sw[data_offset]; + } + } + + for ( int j = 1, data_offset = n*(m+1)+1 ; j < m+1 ; j++, data_offset++ ) { + // data_offset is the offset of [n][j] + if ( sw[data_offset] > maxscore || sw[data_offset] == maxscore && Math.abs(n-j) < Math.abs(p1 - p2)) { + p1 = n; + p2 = j ; + maxscore = sw[data_offset]; + segment_length = m - j ; // end of sequence 2 is overhanging; we will just record it as 'M' segment + } + } + + List lce = new ArrayList(5); + + if ( segment_length > 0 && DO_SOFTCLIP ) { + lce.add(makeElement(CLIP, segment_length)); + segment_length = 0; + } + + // we will be placing all insertions and deletions into sequence b, so the states are named w/regard + // to that sequence + + int state = MSTATE; + + int data_offset = p1*(m+1)+p2; // offset of element [p1][p2] + do { + int btr = btrack[data_offset]; + + int new_state; + int step_length = 1; + + if ( btr > 0 ) { + new_state = DSTATE; + step_length = btr; + } else if ( btr < 0 ) { + new_state = ISTATE; + step_length = (-btr); + } else new_state = MSTATE; // and step_length =1, already set above + + // move to next best location in the sw matrix: + switch( new_state ) { + case MSTATE: data_offset -= (m+2); p1--; p2--; break; // move back along the diag in the sw matrix + case ISTATE: data_offset -= step_length; p2 -= step_length; break; // move left + case DSTATE: data_offset -= (m+1)*step_length; p1 -= step_length; break; // move up + } + + // now let's see if the state actually changed: + if ( new_state == state ) segment_length+=step_length; + else { + // state changed, lets emit previous segment, whatever it was (Insertion Deletion, or (Mis)Match). + lce.add(makeElement(state, segment_length)); + segment_length = step_length; + state = new_state; + } +// next condition is equivalent to while ( sw[p1][p2] != 0 ) (with modified p1 and/or p2: + } while ( p1 > 0 && p2 > 0 ); + + // post-process the last segment we are still keeping; + // NOTE: if reads "overhangs" the ref on the left (i.e. if p2>0) we are counting + // those extra bases sticking out of the ref into the first cigar element if DO_SOFTCLIP is false; + // otherwise they will be softclipped. For instance, + // if read length is 5 and alignment starts at offset -2 (i.e. read starts before the ref, and only + // last 3 bases of the read overlap with/align to the ref), the cigar will be still 5M if + // DO_SOFTCLIP is false or 2S3M if DO_SOFTCLIP is true. + // The consumers need to check for the alignment offset and deal with it properly. + if (DO_SOFTCLIP ) { + lce.add(makeElement(state, segment_length)); + if ( p2> 0 ) lce.add(makeElement(CLIP, p2)); + alignment_offset = p1 ; + } else { + lce.add(makeElement(state, segment_length + p2)); + alignment_offset = p1 - p2; + } + + Collections.reverse(lce); + alignmentCigar = AlignmentUtils.consolidateCigar(new Cigar(lce)); + } + + private CigarElement makeElement(int state, int segment_length) { + CigarOperator o = null; + switch(state) { + case MSTATE: o = CigarOperator.M; break; + case ISTATE: o = CigarOperator.I; break; + case DSTATE: o = CigarOperator.D; break; + case CLIP: o = CigarOperator.S; break; + } + return new CigarElement(segment_length,o); + } + + private double wd(byte x, byte y) { + return (x == y ? parameters.w_match : parameters.w_mismatch); + } + + public void printAlignment(byte[] ref, byte[] read) { + printAlignment(ref,read,100); + } + + public void printAlignment(byte[] ref, byte[] read, int width) { + StringBuilder bread = new StringBuilder(); + StringBuilder bref = new StringBuilder(); + StringBuilder match = new StringBuilder(); + + int i = 0; + int j = 0; + + final int offset = getAlignmentStart2wrt1(); + + Cigar cigar = getCigar(); + + if ( ! DO_SOFTCLIP ) { + + // we need to go through all the hassle below only if we do not do softclipping; + // otherwise offset is never negative + if ( offset < 0 ) { + for ( ; j < (-offset) ; j++ ) { + bread.append((char)read[j]); + bref.append(' '); + match.append(' '); + } + // at negative offsets, our cigar's first element carries overhanging bases + // that we have just printed above. Tweak the first element to + // exclude those bases. Here we create a new list of cigar elements, so the original + // list/original cigar are unchanged (they are unmodifiable anyway!) + + List tweaked = new ArrayList(); + tweaked.addAll(cigar.getCigarElements()); + tweaked.set(0,new CigarElement(cigar.getCigarElement(0).getLength()+offset, + cigar.getCigarElement(0).getOperator())); + cigar = new Cigar(tweaked); + } + } + + if ( offset > 0 ) { // note: the way this implementation works, cigar will ever start from S *only* if read starts before the ref, i.e. offset = 0 + for ( ; i < getAlignmentStart2wrt1() ; i++ ) { + bref.append((char)ref[i]); + bread.append(' '); + match.append(' '); + } + } + + for ( CigarElement e : cigar.getCigarElements() ) { + switch (e.getOperator()) { + case M : + for ( int z = 0 ; z < e.getLength() ; z++, i++, j++ ) { + bref.append((i= s.length() ) { + System.out.println(); + return; + } + int end = Math.min(start+width,s.length()); + System.out.println(s.substring(start,end)); + } +} diff --git a/public/java/src/org/broadinstitute/sting/utils/SWPairwiseAlignmentMain.java b/public/java/src/org/broadinstitute/sting/utils/smithwaterman/SWPairwiseAlignmentMain.java similarity index 98% rename from public/java/src/org/broadinstitute/sting/utils/SWPairwiseAlignmentMain.java rename to public/java/src/org/broadinstitute/sting/utils/smithwaterman/SWPairwiseAlignmentMain.java index a49d7e5e6..8c832fa75 100644 --- a/public/java/src/org/broadinstitute/sting/utils/SWPairwiseAlignmentMain.java +++ b/public/java/src/org/broadinstitute/sting/utils/smithwaterman/SWPairwiseAlignmentMain.java @@ -23,8 +23,9 @@ * THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -package org.broadinstitute.sting.utils; +package org.broadinstitute.sting.utils.smithwaterman; +import org.broadinstitute.sting.utils.Utils; import org.broadinstitute.sting.utils.collections.Pair; import java.util.ArrayList; @@ -100,6 +101,7 @@ public class SWPairwiseAlignmentMain { w_extend = (ext == null ? -2.0 : ext.doubleValue()); + SWPairwiseAlignment.keepScoringMatrix = true; SWPairwiseAlignment a = new SWPairwiseAlignment(ref.getBytes(),read.getBytes(),w_match,w_mismatch,w_open,w_extend); System.out.println("start="+a.getAlignmentStart2wrt1()+", cigar="+a.getCigar()+ diff --git a/public/java/src/org/broadinstitute/sting/utils/smithwaterman/SWParameterSet.java b/public/java/src/org/broadinstitute/sting/utils/smithwaterman/SWParameterSet.java new file mode 100644 index 000000000..100780023 --- /dev/null +++ b/public/java/src/org/broadinstitute/sting/utils/smithwaterman/SWParameterSet.java @@ -0,0 +1,51 @@ +/* +* 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.utils.smithwaterman; + +/** + * Handy named collection of common Smith-waterman parameter sets + * + * User: depristo + * Date: 4/11/13 + * Time: 12:02 PM + */ +public enum SWParameterSet { + // match=1, mismatch = -1/3, gap=-(1+k/3) + ORIGINAL_DEFAULT(new Parameters(1.0,-1.0/3.0,-1.0-1.0/3.0,-1.0/3.0)), + + /** + * A standard set of values for NGS alignments + */ + STANDARD_NGS(new Parameters(5.0, -10.0, -22.0, -1.2)); + + protected Parameters parameters; + + SWParameterSet(final Parameters parameters) { + if ( parameters == null ) throw new IllegalArgumentException("parameters cannot be null"); + + this.parameters = parameters; + } +}