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
This commit is contained in:
Mark DePristo 2013-04-10 10:54:25 -04:00
parent 35293cde49
commit 50cdffc61f
17 changed files with 1048 additions and 668 deletions

View File

@ -56,13 +56,14 @@ import org.apache.log4j.Logger;
import org.broadinstitute.sting.gatk.walkers.haplotypecaller.graphs.*; import org.broadinstitute.sting.gatk.walkers.haplotypecaller.graphs.*;
import org.broadinstitute.sting.utils.GenomeLoc; import org.broadinstitute.sting.utils.GenomeLoc;
import org.broadinstitute.sting.utils.MathUtils; 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.activeregion.ActiveRegion;
import org.broadinstitute.sting.utils.exceptions.UserException; import org.broadinstitute.sting.utils.exceptions.UserException;
import org.broadinstitute.sting.utils.haplotype.Haplotype; import org.broadinstitute.sting.utils.haplotype.Haplotype;
import org.broadinstitute.sting.utils.sam.AlignmentUtils; import org.broadinstitute.sting.utils.sam.AlignmentUtils;
import org.broadinstitute.sting.utils.sam.GATKSAMRecord; import org.broadinstitute.sting.utils.sam.GATKSAMRecord;
import org.broadinstitute.sting.utils.sam.ReadUtils; 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.Allele;
import org.broadinstitute.variant.variantcontext.VariantContext; 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 NUM_BEST_PATHS_PER_KMER_GRAPH = 25;
private static final int GRAPH_KMER_STEP = 6; 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 debug;
private final boolean debugGraphTransformations; private final boolean debugGraphTransformations;
private final int minKmer; private final int minKmer;
@ -587,7 +582,7 @@ public class DeBruijnAssembler extends LocalAssemblyEngine {
private boolean addHaplotypeForGGA( final Haplotype haplotype, final byte[] ref, final List<Haplotype> haplotypeList, final int activeRegionStart, final int activeRegionStop, final boolean FORCE_INCLUSION_FOR_GGA_MODE ) { private boolean addHaplotypeForGGA( final Haplotype haplotype, final byte[] ref, final List<Haplotype> haplotypeList, final int activeRegionStart, final int activeRegionStop, final boolean FORCE_INCLUSION_FOR_GGA_MODE ) {
if( haplotype == null ) { return false; } 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() ); haplotype.setAlignmentStartHapwrtRef( swConsensus.getAlignmentStart2wrt1() );
if( swConsensus.getCigar().toString().contains("S") || swConsensus.getCigar().getReferenceLength() < 60 || swConsensus.getAlignmentStart2wrt1() < 0 ) { // protect against unhelpful haplotype alignments 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 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() ); h.setAlignmentStartHapwrtRef( swConsensus2.getAlignmentStart2wrt1() );
if ( haplotype.isArtificialHaplotype() ) { if ( haplotype.isArtificialHaplotype() ) {

View File

@ -59,7 +59,7 @@ import org.broadinstitute.sting.gatk.walkers.RodWalker;
import org.broadinstitute.sting.gatk.walkers.Window; import org.broadinstitute.sting.gatk.walkers.Window;
import org.broadinstitute.sting.utils.GenomeLoc; import org.broadinstitute.sting.utils.GenomeLoc;
import org.broadinstitute.sting.utils.haplotype.Haplotype; 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.sting.utils.help.HelpConstants;
import org.broadinstitute.variant.vcf.VCFHeader; import org.broadinstitute.variant.vcf.VCFHeader;
import org.broadinstitute.variant.vcf.VCFHeaderLine; import org.broadinstitute.variant.vcf.VCFHeaderLine;

View File

@ -52,7 +52,8 @@ import net.sf.samtools.Cigar;
import net.sf.samtools.CigarElement; import net.sf.samtools.CigarElement;
import net.sf.samtools.CigarOperator; import net.sf.samtools.CigarOperator;
import org.apache.commons.lang.ArrayUtils; 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 org.broadinstitute.sting.utils.sam.AlignmentUtils;
import java.util.*; import java.util.*;
@ -85,10 +86,8 @@ public class Path<T extends BaseVertex> {
// used in the bubble state machine to apply Smith-Waterman to the bubble sequence // 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 // these values were chosen via optimization against the NA12878 knowledge base
private static final double SW_MATCH = 20.0; public static final Parameters NEW_SW_PARAMETERS = new Parameters(20.0, -20.0, -26.0, -0.1);
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;
private static final byte[] STARTING_SW_ANCHOR_BYTES = "XXXXXXXXX".getBytes(); private static final byte[] STARTING_SW_ANCHOR_BYTES = "XXXXXXXXX".getBytes();
/** /**
@ -107,6 +106,16 @@ public class Path<T extends BaseVertex> {
this.graph = graph; this.graph = graph;
} }
/**
* Convenience constructor for testing that creates a path through vertices in graph
*/
protected static <T extends BaseVertex> Path<T> makePath(final List<T> vertices, final BaseGraph<T> graph) {
Path<T> path = new Path<T>(vertices.get(0), graph);
for ( int i = 1; i < vertices.size(); i++ )
path = new Path<T>(path, graph.getEdge(path.lastVertex, vertices.get(i)));
return path;
}
/** /**
* Create a new Path extending p with edge * Create a new Path extending p with edge
* *
@ -362,7 +371,7 @@ public class Path<T extends BaseVertex> {
padding = ArrayUtils.addAll(padding, padding); // double the size of the padding each time 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[] reference = ArrayUtils.addAll( ArrayUtils.addAll(padding, refBytes), padding );
final byte[] alternate = ArrayUtils.addAll( ArrayUtils.addAll(padding, bubbleBytes), 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 ) { if( swConsensus.getAlignmentStart2wrt1() == 0 && !swConsensus.getCigar().toString().contains("S") && swConsensus.getCigar().getReferenceLength() == reference.length ) {
goodAlignment = true; goodAlignment = true;
} }

View File

@ -62,7 +62,8 @@ import org.broadinstitute.sting.gatk.walkers.BAQMode;
import org.broadinstitute.sting.gatk.walkers.ReadWalker; import org.broadinstitute.sting.gatk.walkers.ReadWalker;
import org.broadinstitute.sting.utils.BaseUtils; import org.broadinstitute.sting.utils.BaseUtils;
import org.broadinstitute.sting.utils.GenomeLoc; 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.Utils;
import org.broadinstitute.sting.utils.baq.BAQ; import org.broadinstitute.sting.utils.baq.BAQ;
import org.broadinstitute.sting.utils.collections.Pair; import org.broadinstitute.sting.utils.collections.Pair;
@ -328,10 +329,7 @@ public class IndelRealigner extends ReadWalker<Integer, Integer> {
// fraction of mismatches that need to no longer mismatch for a column to be considered cleaned // 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 MISMATCH_COLUMN_CLEANED_FRACTION = 0.75;
private static final double SW_MATCH = 30.0; // 1.0; private final static Parameters swParameters = new Parameters(30.0, -10.0, -10.0, -2.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;
// reference base padding size // reference base padding size
// TODO -- make this a command-line argument if the need arises // TODO -- make this a command-line argument if the need arises
@ -999,7 +997,7 @@ public class IndelRealigner extends ReadWalker<Integer, Integer> {
private void createAndAddAlternateConsensus(final byte[] read, final Set<Consensus> altConsensesToPopulate, final byte[] reference) { private void createAndAddAlternateConsensus(final byte[] read, final Set<Consensus> altConsensesToPopulate, final byte[] reference) {
// do a pairwise alignment against the 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); Consensus c = createAlternateConsensus(swConsensus.getAlignmentStart2wrt1(), swConsensus.getCigar(), reference, read);
if ( c != null ) if ( c != null )
altConsensesToPopulate.add(c); altConsensesToPopulate.add(c);
@ -1016,7 +1014,7 @@ public class IndelRealigner extends ReadWalker<Integer, Integer> {
} }
// do a pairwise alignment against the reference // do a pairwise alignment against the reference
SWalignmentRuns++; 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()); Consensus c = createAlternateConsensus(swConsensus.getAlignmentStart2wrt1(), swConsensus.getCigar(), reference, read.getReadBases());
if ( c != null ) { if ( c != null ) {
altConsensesToPopulate.add(c); altConsensesToPopulate.add(c);

View File

@ -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<Haplotype> haplotypes,
final GenomeLoc paddedReferenceLoc,
final List<Haplotype> bestHaplotypes,
final Set<Haplotype> calledHaplotypes,
final Map<String, PerReadAlleleLikelihoodMap> stratifiedReadMap) {
writeHaplotypesAsReads(haplotypes, new HashSet<Haplotype>(bestHaplotypes), paddedReferenceLoc);
// we need to remap the Alleles back to the Haplotypes; inefficient but unfortunately this is a requirement currently
final Map<Allele, Haplotype> alleleToHaplotypeMap = new HashMap<Allele, Haplotype>(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<GATKSAMRecord, Map<Allele, Double>> entry : readAlleleLikelihoodMap.getLikelihoodReadMap().entrySet() ) {
final MostLikelyAllele bestAllele = PerReadAlleleLikelihoodMap.getMostLikelyAllele(entry.getValue());
writeReadAgainstHaplotype(entry.getKey(), alleleToHaplotypeMap.get(bestAllele.getMostLikelyAllele()), paddedReferenceLoc.getStart());
}
}
}
}

View File

@ -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<Haplotype> haplotypes,
final GenomeLoc paddedReferenceLoc,
final List<Haplotype> bestHaplotypes,
final Set<Haplotype> calledHaplotypes,
final Map<String, PerReadAlleleLikelihoodMap> 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<Allele, Haplotype> alleleToHaplotypeMap = new HashMap<Allele, Haplotype>(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<Allele> 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<GATKSAMRecord, Map<Allele, Double>> 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());
}
}
}
}
}

View File

@ -1,35 +1,57 @@
/* /*
* Copyright (c) 2012 The Broad Institute * By downloading the PROGRAM you agree to the following terms of use:
* *
* Permission is hereby granted, free of charge, to any person * BROAD INSTITUTE - SOFTWARE LICENSE AGREEMENT - FOR ACADEMIC NON-COMMERCIAL RESEARCH PURPOSES ONLY
* obtaining a copy of this software and associated documentation *
* files (the "Software"), to deal in the Software without * 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).
* restriction, including without limitation the rights to use, *
* copy, modify, merge, publish, distribute, sublicense, and/or sell * 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
* copies of the Software, and to permit persons to whom the * WHEREAS, LICENSEE desires to license the PROGRAM and BROAD desires to grant a license on the following terms and conditions.
* Software is furnished to do so, subject to the following * NOW, THEREFORE, in consideration of the promises and covenants made herein, the parties hereto agree as follows:
* conditions: *
* * 1. DEFINITIONS
* The above copyright notice and this permission notice shall be * 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.
* included in all copies or substantial portions of the Software. *
* * 2. LICENSE
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * 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.
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * 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.
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * 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.
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * 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.
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, *
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * 3. OWNERSHIP OF INTELLECTUAL PROPERTY
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * 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.
* THE USE OR OTHER DEALINGS IN THE SOFTWARE. * 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; package org.broadinstitute.sting.utils.haplotypeBAMWriter;
import net.sf.samtools.*; import net.sf.samtools.*;
import org.broadinstitute.sting.gatk.io.StingSAMFileWriter; 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.GenomeLoc;
import org.broadinstitute.sting.utils.haplotype.Haplotype; 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.Utils;
import org.broadinstitute.sting.utils.genotyper.PerReadAlleleLikelihoodMap; import org.broadinstitute.sting.utils.genotyper.PerReadAlleleLikelihoodMap;
import org.broadinstitute.sting.utils.sam.AlignmentUtils; import org.broadinstitute.sting.utils.sam.AlignmentUtils;
@ -191,7 +213,7 @@ public abstract class HaplotypeBAMWriter {
try { try {
// compute the smith-waterman alignment of read -> haplotype // 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()); //swPairwiseAlignment.printAlignment(haplotype.getBases(), originalRead.getReadBases());
if ( swPairwiseAlignment.getAlignmentStart2wrt1() == -1 ) if ( swPairwiseAlignment.getAlignmentStart2wrt1() == -1 )
// sw can fail (reasons not clear) so if it happens just don't write the read // sw can fail (reasons not clear) so if it happens just don't write the read

View File

@ -57,9 +57,9 @@ import org.broadinstitute.sting.BaseTest;
import org.broadinstitute.sting.utils.*; import org.broadinstitute.sting.utils.*;
import org.broadinstitute.sting.utils.fasta.CachingIndexedFastaSequenceFile; import org.broadinstitute.sting.utils.fasta.CachingIndexedFastaSequenceFile;
import org.broadinstitute.sting.utils.haplotype.Haplotype; 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.Allele;
import org.broadinstitute.variant.variantcontext.VariantContext; import org.broadinstitute.variant.variantcontext.VariantContext;
import org.broadinstitute.variant.variantcontext.VariantContextBuilder;
import org.testng.Assert; import org.testng.Assert;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider; import org.testng.annotations.DataProvider;

View File

@ -49,6 +49,8 @@ package org.broadinstitute.sting.gatk.walkers.haplotypecaller.graphs;
import net.sf.samtools.Cigar; import net.sf.samtools.Cigar;
import net.sf.samtools.CigarElement; import net.sf.samtools.CigarElement;
import net.sf.samtools.CigarOperator; 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.Utils;
import org.broadinstitute.sting.utils.sam.AlignmentUtils; import org.broadinstitute.sting.utils.sam.AlignmentUtils;
import org.testng.Assert; import org.testng.Assert;
@ -63,7 +65,9 @@ import java.util.*;
* Date: 1/31/13 * Date: 1/31/13
*/ */
public class KBestPathsUnitTest { public class KBestPathsUnitTest extends BaseTest {
private final static boolean DEBUG = false;
@DataProvider(name = "BasicPathFindingData") @DataProvider(name = "BasicPathFindingData")
public Object[][] makeBasicPathFindingData() { public Object[][] makeBasicPathFindingData() {
List<Object[]> tests = new ArrayList<Object[]>(); List<Object[]> tests = new ArrayList<Object[]>();
@ -96,7 +100,7 @@ public class KBestPathsUnitTest {
return vertices; 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) { public void testBasicPathFinding(final int nStartNodes, final int nBranchesPerBubble, final int nEndNodes, final boolean addCycle, final boolean allowCycles) {
SeqGraph graph = new SeqGraph(); 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)); 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() { public void testPathFindingComplexCycle() {
SeqGraph graph = new SeqGraph(); SeqGraph graph = new SeqGraph();
@ -148,7 +152,7 @@ public class KBestPathsUnitTest {
Assert.assertEquals(paths.size(), 1, "Didn't find the expected number of paths"); Assert.assertEquals(paths.size(), 1, "Didn't find the expected number of paths");
} }
@Test @Test(enabled = !DEBUG)
public void testPathFindingCycleLastNode() { public void testPathFindingCycleLastNode() {
SeqGraph graph = new SeqGraph(); SeqGraph graph = new SeqGraph();
@ -175,7 +179,7 @@ public class KBestPathsUnitTest {
return tests.toArray(new Object[][]{}); return tests.toArray(new Object[][]{});
} }
@Test(dataProvider = "BasicBubbleDataProvider", enabled = true) @Test(dataProvider = "BasicBubbleDataProvider", enabled = !DEBUG)
public void testBasicBubbleData(final int refBubbleLength, final int altBubbleLength) { public void testBasicBubbleData(final int refBubbleLength, final int altBubbleLength) {
// Construct the assembly graph // Construct the assembly graph
SeqGraph graph = new SeqGraph(3); SeqGraph graph = new SeqGraph(3);
@ -232,7 +236,7 @@ public class KBestPathsUnitTest {
return tests.toArray(new Object[][]{}); return tests.toArray(new Object[][]{});
} }
@Test(dataProvider = "GetBasesData", enabled = true) @Test(dataProvider = "GetBasesData", enabled = !DEBUG)
public void testGetBases(final List<String> frags) { public void testGetBases(final List<String> frags) {
// Construct the assembly graph // Construct the assembly graph
SeqGraph graph = new SeqGraph(3); SeqGraph graph = new SeqGraph(3);
@ -268,7 +272,7 @@ public class KBestPathsUnitTest {
return tests.toArray(new Object[][]{}); 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) { public void testTripleBubbleData(final int refBubbleLength, final int altBubbleLength, final boolean offRefBeginning, final boolean offRefEnding) {
// Construct the assembly graph // Construct the assembly graph
SeqGraph graph = new SeqGraph(); SeqGraph graph = new SeqGraph();
@ -371,4 +375,120 @@ public class KBestPathsUnitTest {
Assert.assertEquals(path.calculateCigar().toString(), AlignmentUtils.consolidateCigar(expectedCigar).toString(), "Cigar string mismatch"); 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<SeqVertex> pathFinder = new KBestPaths<SeqVertex>();
final List<Path<SeqVertex>> paths = pathFinder.getKBestPaths(graph, top, bot);
Assert.assertEquals(paths.size(), 2);
final Path<SeqVertex> refPath = paths.get(0);
final Path<SeqVertex> 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<SeqVertex> pathFinder = new KBestPaths<SeqVertex>();
final List<Path<SeqVertex>> paths = pathFinder.getKBestPaths(graph, top, bot);
Assert.assertEquals(paths.size(), 2);
final Path<SeqVertex> refPath = paths.get(0);
final Path<SeqVertex> 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<Object[]> tests = new ArrayList<Object[]>();
final List<List<String>> 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<String> 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<SeqVertex> 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");
}
} }

View File

@ -1,26 +1,47 @@
/* /*
* Copyright (c) 2012 The Broad Institute * By downloading the PROGRAM you agree to the following terms of use:
* *
* Permission is hereby granted, free of charge, to any person * BROAD INSTITUTE - SOFTWARE LICENSE AGREEMENT - FOR ACADEMIC NON-COMMERCIAL RESEARCH PURPOSES ONLY
* obtaining a copy of this software and associated documentation *
* files (the "Software"), to deal in the Software without * 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).
* restriction, including without limitation the rights to use, *
* copy, modify, merge, publish, distribute, sublicense, and/or sell * 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
* copies of the Software, and to permit persons to whom the * WHEREAS, LICENSEE desires to license the PROGRAM and BROAD desires to grant a license on the following terms and conditions.
* Software is furnished to do so, subject to the following * NOW, THEREFORE, in consideration of the promises and covenants made herein, the parties hereto agree as follows:
* conditions: *
* * 1. DEFINITIONS
* The above copyright notice and this permission notice shall be * 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.
* included in all copies or substantial portions of the Software. *
* * 2. LICENSE
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * 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.
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * 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.
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * 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.
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * 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.
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, *
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * 3. OWNERSHIP OF INTELLECTUAL PROPERTY
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * 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.
* THE USE OR OTHER DEALINGS IN THE SOFTWARE. * 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; package org.broadinstitute.sting.utils.haplotypeBAMWriter;
@ -28,7 +49,7 @@ package org.broadinstitute.sting.utils.haplotypeBAMWriter;
import net.sf.samtools.*; import net.sf.samtools.*;
import org.broadinstitute.sting.BaseTest; import org.broadinstitute.sting.BaseTest;
import org.broadinstitute.sting.utils.haplotype.Haplotype; 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.Utils;
import org.broadinstitute.sting.utils.sam.AlignmentUtils; import org.broadinstitute.sting.utils.sam.AlignmentUtils;
import org.broadinstitute.sting.utils.sam.ArtificialSAMUtils; import org.broadinstitute.sting.utils.sam.ArtificialSAMUtils;

View File

@ -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. * 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.broadinstitute.sting.BaseTest;
import org.testng.Assert; import org.testng.Assert;
@ -91,4 +91,30 @@ public class SWPairwiseAlignmentUnitTest extends BaseTest {
Assert.assertEquals(sw.getAlignmentStart2wrt1(), expectedStart); Assert.assertEquals(sw.getAlignmentStart2wrt1(), expectedStart);
Assert.assertEquals(sw.getCigar().toString(), expectedCigar); 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);
}
} }

View File

@ -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<Haplotype> haplotypes,
final GenomeLoc paddedReferenceLoc,
final List<Haplotype> bestHaplotypes,
final Set<Haplotype> calledHaplotypes,
final Map<String, PerReadAlleleLikelihoodMap> stratifiedReadMap) {
writeHaplotypesAsReads(haplotypes, new HashSet<Haplotype>(bestHaplotypes), paddedReferenceLoc);
// we need to remap the Alleles back to the Haplotypes; inefficient but unfortunately this is a requirement currently
final Map<Allele, Haplotype> alleleToHaplotypeMap = new HashMap<Allele, Haplotype>(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<GATKSAMRecord, Map<Allele, Double>> entry : readAlleleLikelihoodMap.getLikelihoodReadMap().entrySet() ) {
final MostLikelyAllele bestAllele = PerReadAlleleLikelihoodMap.getMostLikelyAllele(entry.getValue());
writeReadAgainstHaplotype(entry.getKey(), alleleToHaplotypeMap.get(bestAllele.getMostLikelyAllele()), paddedReferenceLoc.getStart());
}
}
}
}

View File

@ -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<Haplotype> haplotypes,
final GenomeLoc paddedReferenceLoc,
final List<Haplotype> bestHaplotypes,
final Set<Haplotype> calledHaplotypes,
final Map<String, PerReadAlleleLikelihoodMap> 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<Allele, Haplotype> alleleToHaplotypeMap = new HashMap<Allele, Haplotype>(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<Allele> 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<GATKSAMRecord, Map<Allele, Double>> 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());
}
}
}
}
}

View File

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

View File

@ -1,424 +1,458 @@
/* /*
* Copyright (c) 2012 The Broad Institute * Copyright (c) 2012 The Broad Institute
* *
* Permission is hereby granted, free of charge, to any person * Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation * obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without * files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, * restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell * copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the * copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following * Software is furnished to do so, subject to the following
* conditions: * conditions:
* *
* The above copyright notice and this permission notice shall be * The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software. * included in all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
* THE USE OR OTHER DEALINGS IN THE SOFTWARE. * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/ */
package org.broadinstitute.sting.utils; package org.broadinstitute.sting.utils.smithwaterman;
import net.sf.samtools.Cigar; import net.sf.samtools.Cigar;
import net.sf.samtools.CigarElement; import net.sf.samtools.CigarElement;
import net.sf.samtools.CigarOperator; import net.sf.samtools.CigarOperator;
import org.broadinstitute.sting.utils.collections.Pair; import org.broadinstitute.sting.utils.exceptions.StingException;
import org.broadinstitute.sting.utils.exceptions.StingException; import org.broadinstitute.sting.utils.sam.AlignmentUtils;
import org.broadinstitute.sting.utils.sam.AlignmentUtils;
import java.util.*;
import java.util.*;
/**
/** * Pairwise discrete smith-waterman alignment
* Pairwise discrete smith-waterman alignment *
* * ************************************************************************
* ************************************************************************ * **** IMPORTANT NOTE: ****
* **** IMPORTANT NOTE: **** * **** This class assumes that all bytes come from UPPERCASED chars! ****
* **** This class assumes that all bytes come from UPPERCASED chars! **** * ************************************************************************
* ************************************************************************ *
* * User: asivache
* User: asivache * Date: Mar 23, 2009
* Date: Mar 23, 2009 * Time: 1:54:54 PM
* Time: 1:54:54 PM */
*/ public final class SWPairwiseAlignment {
public final class SWPairwiseAlignment { private int alignment_offset; // offset of s2 w/respect to s1
private int alignment_offset; // offset of s2 w/respect to s1 private Cigar alignmentCigar;
private Cigar alignmentCigar;
private final Parameters parameters;
private final double w_match;
private final double w_mismatch; private static final int MSTATE = 0;
private final double w_open; private static final int ISTATE = 1;
private final double w_extend; private static final int DSTATE = 2;
private static final int CLIP = 3;
private static final int MSTATE = 0;
private static final int ISTATE = 1; protected static boolean cutoff = false;
private static final int DSTATE = 2; private static boolean DO_SOFTCLIP = true;
private static final int CLIP = 3;
/**
protected static boolean cutoff = false; * The SW scoring matrix, stored for debugging purposes if keepScoringMatrix is true
private static boolean DO_SOFTCLIP = true; */
protected double[] SW = null;
double[] SW;
/**
public SWPairwiseAlignment(byte[] seq1, byte[] seq2, double match, double mismatch, double open, double extend ) { * Only for testing purposes in the SWPairwiseAlignmentMain function
w_match = match; * set to true to keep SW scoring matrix after align call
w_mismatch = mismatch; */
w_open = open; protected static boolean keepScoringMatrix = false;
w_extend = extend;
align(seq1,seq2); /**
} * Create a new SW pairwise aligner.
*
public SWPairwiseAlignment(byte[] seq1, byte[] seq2) { * @deprecated in favor of constructors using the Parameter or ParameterSet class
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) */
} @Deprecated
public SWPairwiseAlignment(byte[] seq1, byte[] seq2, double match, double mismatch, double open, double extend ) {
public Cigar getCigar() { return alignmentCigar ; } this(seq1, seq2, new Parameters(match, mismatch, open, extend));
}
public int getAlignmentStart2wrt1() { return alignment_offset; }
/**
public void align(final byte[] a, final byte[] b) { * Create a new SW pairwise aligner
final int n = a.length; *
final int m = b.length; * After creating the object the two sequences are aligned with an internal call to align(seq1, seq2)
double [] sw = new double[(n+1)*(m+1)]; *
SW = sw; * @param seq1 the first sequence we want to align
int [] btrack = new int[(n+1)*(m+1)]; * @param seq2 the second sequence we want to align
* @param parameters the SW parameters to use
calculateMatrix(a, b, sw, btrack); */
calculateCigar(n, m, sw, btrack); // length of the segment (continuous matches, insertions or deletions) public SWPairwiseAlignment(byte[] seq1, byte[] seq2, Parameters parameters) {
} this.parameters = parameters;
align(seq1,seq2);
}
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; * Create a new SW pairwise aligner
*
//final double MATRIX_MIN_CUTOFF=-1e100; // never let matrix elements drop below this cutoff * After creating the object the two sequences are aligned with an internal call to align(seq1, seq2)
final double MATRIX_MIN_CUTOFF; // never let matrix elements drop below this cutoff *
if ( cutoff ) MATRIX_MIN_CUTOFF = 0.0; * @param seq1 the first sequence we want to align
else MATRIX_MIN_CUTOFF = -1e100; * @param seq2 the second sequence we want to align
* @param namedParameters the named parameter set to get our parameters from
double [] best_gap_v = new double[m+1]; */
Arrays.fill(best_gap_v,-1.0e40); public SWPairwiseAlignment(byte[] seq1, byte[] seq2, SWParameterSet namedParameters) {
int [] gap_size_v = new int[m+1]; this(seq1, seq2, namedParameters.parameters);
double [] best_gap_h = new double[n+1]; }
Arrays.fill(best_gap_h,-1.0e40);
int [] gap_size_h = new int[n+1]; public SWPairwiseAlignment(byte[] seq1, byte[] seq2) {
this(seq1,seq2,SWParameterSet.ORIGINAL_DEFAULT);
// 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 public Cigar getCigar() { return alignmentCigar ; }
final int row_offset = row_offset_1 + m; public int getAlignmentStart2wrt1() { return alignment_offset; }
// On the entrance into the loop, row_offset_1 is the (linear) offset public void align(final byte[] a, final byte[] b) {
// of the first element of row (i-1) and row_offset is the linear offset of the final int n = a.length;
// start of row i final int m = b.length;
double [] sw = new double[(n+1)*(m+1)];
for ( int j = 1, data_offset_1 = row_offset_1 ; j < m ; j++, data_offset_1++ ) { if ( keepScoringMatrix ) SW = sw;
int [] btrack = new int[(n+1)*(m+1)];
// data_offset_1 is linearized offset of element [i-1][j-1]
calculateMatrix(a, b, sw, btrack);
final byte b_base = b[j-1]; // letter in b at the current pos calculateCigar(n, m, sw, btrack); // length of the segment (continuous matches, insertions or deletions)
}
// 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);
private void calculateMatrix(final byte[] a, final byte[] b, double [] sw, int [] btrack ) {
// optimized "traversal" of all the matrix cells above the current one (i.e. traversing final int n = a.length+1;
// all 'step down' events that would end in the current cell. The optimized code final int m = b.length+1;
// 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 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 a gap (length 1) was just opened above, this is the cost of arriving to the current cell: if ( cutoff ) MATRIX_MIN_CUTOFF = 0.0;
double prev_gap = sw[data_offset_1+1]+w_open; else MATRIX_MIN_CUTOFF = -1e100;
best_gap_v[j] += w_extend; // for the gaps that were already opened earlier, extending them by 1 costs w_extend double [] best_gap_v = new double[m+1];
Arrays.fill(best_gap_v,-1.0e40);
if ( prev_gap > best_gap_v[j] ) { int [] gap_size_v = new int[m+1];
// opening a gap just before the current cell results in better score than extending by one double [] best_gap_h = new double[n+1];
// the best previously opened gap. This will hold for ALL cells below: since any gap Arrays.fill(best_gap_h,-1.0e40);
// once opened always costs w_extend to extend by another base, we will always get a better score int [] gap_size_h = new int[n+1];
// 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; // build smith-waterman matrix and keep backtrack info:
gap_size_v[j] = 1; // remember that the best step-down gap from above has length 1 (we just opened it) 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
} else { byte a_base = a[i-1]; // letter in a at the current pos
// previous best gap is still the best, even after extension by another base, so we just record that extension:
gap_size_v[j]++; final int row_offset = row_offset_1 + m;
}
// On the entrance into the loop, row_offset_1 is the (linear) offset
final double step_down = best_gap_v[j] ; // of the first element of row (i-1) and row_offset is the linear offset of the
final int kd = gap_size_v[j]; // start of row i
// optimized "traversal" of all the matrix cells to the left of the current one (i.e. traversing for ( int j = 1, data_offset_1 = row_offset_1 ; j < m ; j++, data_offset_1++ ) {
// 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: // data_offset_1 is linearized offset of element [i-1][j-1]
// the optimization works ONLY for linear w(k)=wopen+(k-1)*wextend!!!!
final byte b_base = b[j-1]; // letter in b at the current pos
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 // in other words, step_diag = sw[i-1][j-1] + wd(a_base,b_base);
best_gap_h[i] += w_extend; // previous best gap would cost us that much if extended by another base double step_diag = sw[data_offset_1] + wd(a_base,b_base);
if ( prev_gap > best_gap_h[i] ) { // optimized "traversal" of all the matrix cells above the current one (i.e. traversing
// newly opened gap is better (score-wise) than any previous gap with the same row index i; since // all 'step down' events that would end in the current cell. The optimized code
// gap penalty is linear with k, this new gap location is going to remain better than any previous ones // does exactly the same thing as the commented out loop below. IMPORTANT:
best_gap_h[i] = prev_gap; // the optimization works ONLY for linear w(k)=wopen+(k-1)*wextend!!!!
gap_size_h[i] = 1;
} else { // if a gap (length 1) was just opened above, this is the cost of arriving to the current cell:
gap_size_h[i]++; 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
final double step_right = best_gap_h[i];
final int ki = gap_size_h[i]; if ( prev_gap > best_gap_v[j] ) {
// opening a gap just before the current cell results in better score than extending by one
if ( step_down > step_right ) { // the best previously opened gap. This will hold for ALL cells below: since any gap
if ( step_down > step_diag ) { // once opened always costs w_extend to extend by another base, we will always get a better score
sw[data_offset] = Math.max(MATRIX_MIN_CUTOFF,step_down); // by arriving to any cell below from the gap we just opened (prev_gap) rather than from the previous best gap
btrack[data_offset] = kd ; // positive=vertical best_gap_v[j] = prev_gap;
} else { gap_size_v[j] = 1; // remember that the best step-down gap from above has length 1 (we just opened it)
sw[data_offset] = Math.max(MATRIX_MIN_CUTOFF,step_diag); } else {
btrack[data_offset] = 0; // 0 = diagonal // previous best gap is still the best, even after extension by another base, so we just record that extension:
} gap_size_v[j]++;
} else { }
// step_down <= step_right
if ( step_right > step_diag ) { final double step_down = best_gap_v[j] ;
sw[data_offset] = Math.max(MATRIX_MIN_CUTOFF,step_right); final int kd = gap_size_v[j];
btrack[data_offset] = -ki; // negative = horizontal
} else { // optimized "traversal" of all the matrix cells to the left of the current one (i.e. traversing
sw[data_offset] = Math.max(MATRIX_MIN_CUTOFF,step_diag); // all 'step right' events that would end in the current cell. The optimized code
btrack[data_offset] = 0; // 0 = diagonal // 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
// IMPORTANT, IMPORTANT, IMPORTANT: best_gap_h[i] += parameters.w_extend; // previous best gap would cost us that much if extended by another base
// note that we update this (secondary) outer loop variable here,
// so that we DO NOT need to update it if ( prev_gap > best_gap_h[i] ) {
// in the for() statement itself. // newly opened gap is better (score-wise) than any previous gap with the same row index i; since
row_offset_1 = row_offset; // 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]++;
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; final double step_right = best_gap_h[i];
final int ki = gap_size_h[i];
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) if ( step_down > step_right ) {
if ( step_down > step_diag ) {
// look for largest score. we use >= combined with the traversal direction sw[data_offset] = Math.max(MATRIX_MIN_CUTOFF,step_down);
// to ensure that if two scores are equal, the one closer to diagonal gets picked btrack[data_offset] = kd ; // positive=vertical
for ( int i = 1, data_offset = m+1+m ; i < n+1 ; i++, data_offset += (m+1) ) { } else {
// data_offset is the offset of [i][m] sw[data_offset] = Math.max(MATRIX_MIN_CUTOFF,step_diag);
if ( sw[data_offset] >= maxscore ) { btrack[data_offset] = 0; // 0 = diagonal
p1 = i; p2 = m ; maxscore = sw[data_offset]; }
} } else {
} // step_down <= step_right
if ( step_right > step_diag ) {
for ( int j = 1, data_offset = n*(m+1)+1 ; j < m+1 ; j++, data_offset++ ) { sw[data_offset] = Math.max(MATRIX_MIN_CUTOFF,step_right);
// data_offset is the offset of [n][j] btrack[data_offset] = -ki; // negative = horizontal
if ( sw[data_offset] > maxscore || sw[data_offset] == maxscore && Math.abs(n-j) < Math.abs(p1 - p2)) { } else {
p1 = n; sw[data_offset] = Math.max(MATRIX_MIN_CUTOFF,step_diag);
p2 = j ; btrack[data_offset] = 0; // 0 = diagonal
maxscore = sw[data_offset]; }
segment_length = m - j ; // end of sequence 2 is overhanging; we will just record it as 'M' segment }
} }
}
// IMPORTANT, IMPORTANT, IMPORTANT:
List<CigarElement> lce = new ArrayList<CigarElement>(5); // note that we update this (secondary) outer loop variable here,
// so that we DO NOT need to update it
if ( segment_length > 0 && DO_SOFTCLIP ) { // in the for() statement itself.
lce.add(makeElement(CLIP, segment_length)); row_offset_1 = row_offset;
segment_length = 0; }
} }
// we will be placing all insertions and deletions into sequence b, so the states are named w/regard
// to that sequence 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 state = MSTATE; int p1 = 0, p2 = 0;
int data_offset = p1*(m+1)+p2; // offset of element [p1][p2] double maxscore = Double.NEGATIVE_INFINITY; // sw scores are allowed to be negative
do { int segment_length = 0; // length of the segment (continuous matches, insertions or deletions)
int btr = btrack[data_offset];
// look for largest score. we use >= combined with the traversal direction
int new_state; // to ensure that if two scores are equal, the one closer to diagonal gets picked
int step_length = 1; 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 ( btr > 0 ) { if ( sw[data_offset] >= maxscore ) {
new_state = DSTATE; p1 = i; p2 = m ; maxscore = sw[data_offset];
step_length = btr; }
} else if ( btr < 0 ) { }
new_state = ISTATE;
step_length = (-btr); for ( int j = 1, data_offset = n*(m+1)+1 ; j < m+1 ; j++, data_offset++ ) {
} else new_state = MSTATE; // and step_length =1, already set above // 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)) {
// move to next best location in the sw matrix: p1 = n;
switch( new_state ) { p2 = j ;
case MSTATE: data_offset -= (m+2); p1--; p2--; break; // move back along the diag in the sw matrix maxscore = sw[data_offset];
case ISTATE: data_offset -= step_length; p2 -= step_length; break; // move left segment_length = m - j ; // end of sequence 2 is overhanging; we will just record it as 'M' segment
case DSTATE: data_offset -= (m+1)*step_length; p1 -= step_length; break; // move up }
} }
// now let's see if the state actually changed: List<CigarElement> lce = new ArrayList<CigarElement>(5);
if ( new_state == state ) segment_length+=step_length;
else { if ( segment_length > 0 && DO_SOFTCLIP ) {
// state changed, lets emit previous segment, whatever it was (Insertion Deletion, or (Mis)Match). lce.add(makeElement(CLIP, segment_length));
lce.add(makeElement(state, segment_length)); segment_length = 0;
segment_length = step_length; }
state = new_state;
} // we will be placing all insertions and deletions into sequence b, so the states are named w/regard
// next condition is equivalent to while ( sw[p1][p2] != 0 ) (with modified p1 and/or p2: // to that sequence
} while ( p1 > 0 && p2 > 0 );
int state = MSTATE;
// 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 int data_offset = p1*(m+1)+p2; // offset of element [p1][p2]
// those extra bases sticking out of the ref into the first cigar element if DO_SOFTCLIP is false; do {
// otherwise they will be softclipped. For instance, int btr = btrack[data_offset];
// 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 int new_state;
// DO_SOFTCLIP is false or 2S3M if DO_SOFTCLIP is true. int step_length = 1;
// The consumers need to check for the alignment offset and deal with it properly.
if (DO_SOFTCLIP ) { if ( btr > 0 ) {
lce.add(makeElement(state, segment_length)); new_state = DSTATE;
if ( p2> 0 ) lce.add(makeElement(CLIP, p2)); step_length = btr;
alignment_offset = p1 ; } else if ( btr < 0 ) {
} else { new_state = ISTATE;
lce.add(makeElement(state, segment_length + p2)); step_length = (-btr);
alignment_offset = p1 - p2; } else new_state = MSTATE; // and step_length =1, already set above
}
// move to next best location in the sw matrix:
Collections.reverse(lce); switch( new_state ) {
alignmentCigar = AlignmentUtils.consolidateCigar(new Cigar(lce)); 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
private CigarElement makeElement(int state, int segment_length) { }
CigarOperator o = null;
switch(state) { // now let's see if the state actually changed:
case MSTATE: o = CigarOperator.M; break; if ( new_state == state ) segment_length+=step_length;
case ISTATE: o = CigarOperator.I; break; else {
case DSTATE: o = CigarOperator.D; break; // state changed, lets emit previous segment, whatever it was (Insertion Deletion, or (Mis)Match).
case CLIP: o = CigarOperator.S; break; lce.add(makeElement(state, segment_length));
} segment_length = step_length;
return new CigarElement(segment_length,o); state = new_state;
} }
// next condition is equivalent to while ( sw[p1][p2] != 0 ) (with modified p1 and/or p2:
private double wd(byte x, byte y) { } while ( p1 > 0 && p2 > 0 );
return (x == y ? w_match : w_mismatch);
} // 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
public void printAlignment(byte[] ref, byte[] read) { // those extra bases sticking out of the ref into the first cigar element if DO_SOFTCLIP is false;
printAlignment(ref,read,100); // 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
public void printAlignment(byte[] ref, byte[] read, int width) { // DO_SOFTCLIP is false or 2S3M if DO_SOFTCLIP is true.
StringBuilder bread = new StringBuilder(); // The consumers need to check for the alignment offset and deal with it properly.
StringBuilder bref = new StringBuilder(); if (DO_SOFTCLIP ) {
StringBuilder match = new StringBuilder(); lce.add(makeElement(state, segment_length));
if ( p2> 0 ) lce.add(makeElement(CLIP, p2));
int i = 0; alignment_offset = p1 ;
int j = 0; } else {
lce.add(makeElement(state, segment_length + p2));
final int offset = getAlignmentStart2wrt1(); alignment_offset = p1 - p2;
}
Cigar cigar = getCigar();
Collections.reverse(lce);
if ( ! DO_SOFTCLIP ) { alignmentCigar = AlignmentUtils.consolidateCigar(new Cigar(lce));
}
// we need to go through all the hassle below only if we do not do softclipping;
// otherwise offset is never negative private CigarElement makeElement(int state, int segment_length) {
if ( offset < 0 ) { CigarOperator o = null;
for ( ; j < (-offset) ; j++ ) { switch(state) {
bread.append((char)read[j]); case MSTATE: o = CigarOperator.M; break;
bref.append(' '); case ISTATE: o = CigarOperator.I; break;
match.append(' '); case DSTATE: o = CigarOperator.D; break;
} case CLIP: o = CigarOperator.S; break;
// at negative offsets, our cigar's first element carries overhanging bases }
// that we have just printed above. Tweak the first element to return new CigarElement(segment_length,o);
// exclude those bases. Here we create a new list of cigar elements, so the original }
// list/original cigar are unchanged (they are unmodifiable anyway!)
private double wd(byte x, byte y) {
List<CigarElement> tweaked = new ArrayList<CigarElement>(); return (x == y ? parameters.w_match : parameters.w_mismatch);
tweaked.addAll(cigar.getCigarElements()); }
tweaked.set(0,new CigarElement(cigar.getCigarElement(0).getLength()+offset,
cigar.getCigarElement(0).getOperator())); public void printAlignment(byte[] ref, byte[] read) {
cigar = new Cigar(tweaked); printAlignment(ref,read,100);
} }
}
public void printAlignment(byte[] ref, byte[] read, int width) {
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 StringBuilder bread = new StringBuilder();
for ( ; i < getAlignmentStart2wrt1() ; i++ ) { StringBuilder bref = new StringBuilder();
bref.append((char)ref[i]); StringBuilder match = new StringBuilder();
bread.append(' ');
match.append(' '); int i = 0;
} int j = 0;
}
final int offset = getAlignmentStart2wrt1();
for ( CigarElement e : cigar.getCigarElements() ) {
switch (e.getOperator()) { Cigar cigar = getCigar();
case M :
for ( int z = 0 ; z < e.getLength() ; z++, i++, j++ ) { if ( ! DO_SOFTCLIP ) {
bref.append((i<ref.length)?(char)ref[i]:' ');
bread.append((j < read.length)?(char)read[j]:' '); // we need to go through all the hassle below only if we do not do softclipping;
match.append( ( i<ref.length && j < read.length ) ? (ref[i] == read[j] ? '.':'*' ) : ' ' ); // otherwise offset is never negative
} if ( offset < 0 ) {
break; for ( ; j < (-offset) ; j++ ) {
case I : bread.append((char)read[j]);
for ( int z = 0 ; z < e.getLength(); z++, j++ ) { bref.append(' ');
bref.append('-'); match.append(' ');
bread.append((char)read[j]); }
match.append('I'); // at negative offsets, our cigar's first element carries overhanging bases
} // that we have just printed above. Tweak the first element to
break; // exclude those bases. Here we create a new list of cigar elements, so the original
case S : // list/original cigar are unchanged (they are unmodifiable anyway!)
for ( int z = 0 ; z < e.getLength(); z++, j++ ) {
bref.append(' '); List<CigarElement> tweaked = new ArrayList<CigarElement>();
bread.append((char)read[j]); tweaked.addAll(cigar.getCigarElements());
match.append('S'); tweaked.set(0,new CigarElement(cigar.getCigarElement(0).getLength()+offset,
} cigar.getCigarElement(0).getOperator()));
break; cigar = new Cigar(tweaked);
case D: }
for ( int z = 0 ; z < e.getLength(); z++ , i++ ) { }
bref.append((char)ref[i]);
bread.append('-'); 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
match.append('D'); for ( ; i < getAlignmentStart2wrt1() ; i++ ) {
} bref.append((char)ref[i]);
break; bread.append(' ');
default: match.append(' ');
throw new StingException("Unexpected Cigar element:" + e.getOperator()); }
} }
}
for ( ; i < ref.length; i++ ) bref.append((char)ref[i]); for ( CigarElement e : cigar.getCigarElements() ) {
for ( ; j < read.length; j++ ) bread.append((char)read[j]); switch (e.getOperator()) {
case M :
int pos = 0 ; for ( int z = 0 ; z < e.getLength() ; z++, i++, j++ ) {
int maxlength = Math.max(match.length(),Math.max(bread.length(),bref.length())); bref.append((i<ref.length)?(char)ref[i]:' ');
while ( pos < maxlength ) { bread.append((j < read.length)?(char)read[j]:' ');
print_cautiously(match,pos,width); match.append( ( i<ref.length && j < read.length ) ? (ref[i] == read[j] ? '.':'*' ) : ' ' );
print_cautiously(bread,pos,width); }
print_cautiously(bref,pos,width); break;
System.out.println(); case I :
pos += width; for ( int z = 0 ; z < e.getLength(); z++, j++ ) {
} bref.append('-');
} bread.append((char)read[j]);
match.append('I');
/** String builder's substring is extremely stupid: instead of trimming and/or returning an empty }
* string when one end/both ends of the interval are out of range, it crashes with an break;
* exception. This utility function simply prints the substring if the interval is within the index range case S :
* or trims accordingly if it is not. for ( int z = 0 ; z < e.getLength(); z++, j++ ) {
* @param s bref.append(' ');
* @param start bread.append((char)read[j]);
* @param width match.append('S');
*/ }
private static void print_cautiously(StringBuilder s, int start, int width) { break;
if ( start >= s.length() ) { case D:
System.out.println(); for ( int z = 0 ; z < e.getLength(); z++ , i++ ) {
return; bref.append((char)ref[i]);
} bread.append('-');
int end = Math.min(start+width,s.length()); match.append('D');
System.out.println(s.substring(start,end)); }
} break;
} default:
throw new StingException("Unexpected Cigar element:" + e.getOperator());
}
}
for ( ; i < ref.length; i++ ) bref.append((char)ref[i]);
for ( ; j < read.length; j++ ) bread.append((char)read[j]);
int pos = 0 ;
int maxlength = Math.max(match.length(),Math.max(bread.length(),bref.length()));
while ( pos < maxlength ) {
print_cautiously(match,pos,width);
print_cautiously(bread,pos,width);
print_cautiously(bref,pos,width);
System.out.println();
pos += width;
}
}
/** String builder's substring is extremely stupid: instead of trimming and/or returning an empty
* string when one end/both ends of the interval are out of range, it crashes with an
* exception. This utility function simply prints the substring if the interval is within the index range
* or trims accordingly if it is not.
* @param s
* @param start
* @param width
*/
private static void print_cautiously(StringBuilder s, int start, int width) {
if ( start >= s.length() ) {
System.out.println();
return;
}
int end = Math.min(start+width,s.length());
System.out.println(s.substring(start,end));
}
}

View File

@ -23,8 +23,9 @@
* THE USE OR OTHER DEALINGS IN THE SOFTWARE. * 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 org.broadinstitute.sting.utils.collections.Pair;
import java.util.ArrayList; import java.util.ArrayList;
@ -100,6 +101,7 @@ public class SWPairwiseAlignmentMain {
w_extend = (ext == null ? -2.0 : ext.doubleValue()); 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); 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()+ System.out.println("start="+a.getAlignmentStart2wrt1()+", cigar="+a.getCigar()+

View File

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