From 2f5ef6db442859d9ac09ef6de1f9b7819f27098e Mon Sep 17 00:00:00 2001 From: Eric Banks Date: Wed, 1 May 2013 11:13:58 -0400 Subject: [PATCH] New faster Smith-Waterman implementation that is edge greedy and assumes that ref and haplotype have same global start/end points. * This version inherits from the original SW implementation so it can use the same matrix creation method. * A bunch of refactoring was done to the original version to clean it up a bit and to have it do the right thing for indels at the edges of the alignments. * Enum added for the overhang strategy to use; added implementation for the INDEL version of this strategy. * Lots of systematic testing added for this implementation. * NOT HOOKED UP TO HAPLOTYPE CALLER YET. Committing so that people can play around with this for now. --- ...EdgeGreedySWPairwiseAlignmentUnitTest.java | 259 ++++++++++++++++++ .../org/broadinstitute/sting/utils/Utils.java | 16 ++ .../GlobalEdgeGreedySWPairwiseAlignment.java | 217 +++++++++++++++ .../smithwaterman/SWPairwiseAlignment.java | 255 ++++++++++++----- .../utils/smithwaterman/SmithWaterman.java | 1 + .../sting/utils/UtilsUnitTest.java | 20 ++ .../smithwaterman/SmithWatermanBenchmark.java | 88 ++++++ 7 files changed, 784 insertions(+), 72 deletions(-) create mode 100644 protected/java/test/org/broadinstitute/sting/utils/smithwaterman/GlobalEdgeGreedySWPairwiseAlignmentUnitTest.java create mode 100644 public/java/src/org/broadinstitute/sting/utils/smithwaterman/GlobalEdgeGreedySWPairwiseAlignment.java create mode 100644 public/java/test/org/broadinstitute/sting/utils/smithwaterman/SmithWatermanBenchmark.java diff --git a/protected/java/test/org/broadinstitute/sting/utils/smithwaterman/GlobalEdgeGreedySWPairwiseAlignmentUnitTest.java b/protected/java/test/org/broadinstitute/sting/utils/smithwaterman/GlobalEdgeGreedySWPairwiseAlignmentUnitTest.java new file mode 100644 index 000000000..711a60436 --- /dev/null +++ b/protected/java/test/org/broadinstitute/sting/utils/smithwaterman/GlobalEdgeGreedySWPairwiseAlignmentUnitTest.java @@ -0,0 +1,259 @@ +/* +* 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.smithwaterman; + +import net.sf.samtools.TextCigarCodec; +import org.broadinstitute.sting.BaseTest; +import org.broadinstitute.sting.utils.Utils; +import org.broadinstitute.sting.utils.sam.AlignmentUtils; +import org.testng.Assert; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class GlobalEdgeGreedySWPairwiseAlignmentUnitTest extends BaseTest { + + private final static boolean DEBUG = false; + + @Test(enabled = !DEBUG) + public void testReadAlignedToRefComplexAlignment() { + final String reference = "AAAGGACTGACTG"; + final String read = "ACTGACTGACTG"; + final GlobalEdgeGreedySWPairwiseAlignment sw = new GlobalEdgeGreedySWPairwiseAlignment(reference.getBytes(), read.getBytes()); + Assert.assertEquals(sw.getCigar().toString(), "1M1D11M"); + } + + @Test(enabled = !DEBUG) + public void testIndelsAtStartAndEnd() { + final String match = "CCCCC"; + final String reference = "AAA" + match; + final String read = match + "GGG"; + final int expectedStart = 0; + final String expectedCigar = "3D5M3I"; + final GlobalEdgeGreedySWPairwiseAlignment sw = new GlobalEdgeGreedySWPairwiseAlignment(reference.getBytes(), read.getBytes()); + Assert.assertEquals(sw.getAlignmentStart2wrt1(), expectedStart); + Assert.assertEquals(sw.getCigar().toString(), expectedCigar); + } + + @Test(enabled = !DEBUG) + public void testDegenerateAlignmentWithIndelsAtBothEnds() { + logger.warn("testDegenerateAlignmentWithIndelsAtBothEnds"); + final String ref = "TGTGTGTGTGTGTGACAGAGAGAGAGAGAGAGAGAGAGAGAGAGA"; + final String alt = "ACAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGAGA"; + final int expectedStart = 0; + final String expectedCigar = "6I45M"; + final GlobalEdgeGreedySWPairwiseAlignment sw = new GlobalEdgeGreedySWPairwiseAlignment(ref.getBytes(), alt.getBytes(), SWParameterSet.STANDARD_NGS); + Assert.assertEquals(sw.getAlignmentStart2wrt1(), expectedStart); + Assert.assertEquals(sw.getCigar().toString(), expectedCigar); + } + + @Test(enabled = !DEBUG) + public void testAlignReallyLongDeletion() { + final String ref = "CGGCTAATTTTTGTATTTTTAGTAGAGACAGGGTTTCACCATGTTGGCCAGGCTGGTCTTGAACTCCTGACCTCAGGTGATCCACTCGCCTCGGTCTCCCAAAGTGTTGGGATTACAGGCATGAACCACTGCACCTGGCCTAGTGTTTGGGAAAACTATACTAGGAAAAGAATAGTTGCTTTAAGTCATTCTTTGATTATTCTGAGAATTGGCATATAGCTGCCATTATAACCTACTTTTGCTAAATATAATAATAATAATCATTATTTTTATTTTTTGAGACAGGGTCTTGTTTTGTCACCCCGGCTGGAGTGAAGTGGCGCAATCTCGGCTCACTGCAACCTCCACCTCCGGGTGCAAGCAATTCTCCTGCCTCAGCCTCTTGAGTAGCTAGGATTACAGGCACAAGCCATCATGCCCAGCTAATTTTTGTATTTTTAGTAGAGACAGGGTTTCACCATGTTGGTCAGGCTGGTCTTGAACTCCTGACCTCAGGT"; + final String alt = "CGGCTAATTTTTGTATTTTTAGTAGAGACAGGGTTTCACCATGTTGGTCAGGCTGGTCTTGAACTCCTGACCTCAGGT"; + + final GlobalEdgeGreedySWPairwiseAlignment sw = new GlobalEdgeGreedySWPairwiseAlignment(ref.getBytes(), alt.getBytes(), SWParameterSet.STANDARD_NGS); + Assert.assertEquals(sw.getAlignmentStart2wrt1(), 0); + Assert.assertEquals(sw.getCigar().toString(), "47M419D31M"); + } + + public static final Parameters params = new Parameters(20.0, -10.0, -26.0, -1.1); + @DataProvider(name = "SWData") + public Object[][] makeSWData() { + List tests = new ArrayList(); + + // simple cases + tests.add(new Object[]{"A", "C", "1M"}); + tests.add(new Object[]{"AAA", "AAA", "3M"}); + tests.add(new Object[]{"AAA", "AGA", "3M"}); + tests.add(new Object[]{"AAA", "GAA", "3M"}); + tests.add(new Object[]{"AAA", "AAG", "3M"}); + + // small single indels + tests.add(new Object[]{"ACACACAC", "ACACAC", "6M2D"}); + tests.add(new Object[]{"ACACAC", "ACACACAC", "6M2I"}); + tests.add(new Object[]{"XXACACACXX", "XXACACACACXX", "8M2I2M"}); + tests.add(new Object[]{"XXACACACXX", "XXACACXX", "6M2D2M"}); + tests.add(new Object[]{"ACGT", "AACGT", "1I4M"}); + tests.add(new Object[]{"ACGT", "ACCGT", "2M1I2M"}); + tests.add(new Object[]{"ACGT", "ACGGT", "3M1I1M"}); + tests.add(new Object[]{"ACGT", "ACGTT", "4M1I"}); + tests.add(new Object[]{"ACGT", "CGT", "1D3M"}); + tests.add(new Object[]{"ACGT", "AGT", "1M1D2M"}); + tests.add(new Object[]{"ACGT", "ACT", "2M1D1M"}); + tests.add(new Object[]{"ACGT", "ACG", "3M1D"}); + + // mismatches through out the sequences + final String ref = "ACGTAACCGGTT"; + for ( int diff = 0; diff < ref.length(); diff++ ) { + final byte[] altBases = ref.getBytes(); + altBases[diff] = 'N'; + tests.add(new Object[]{ref, new String(altBases), ref.length() + "M"}); + } + for ( int diff1 = 0; diff1 < ref.length(); diff1++ ) { + for ( int diff2 = 0; diff2 < ref.length(); diff2++ ) { + final byte[] altBases = ref.getBytes(); + altBases[diff1] = 'N'; + altBases[diff2] = 'N'; + tests.add(new Object[]{ref, new String(altBases), ref.length() + "M"}); + } + } + + // prefixes and suffixes matching + final String totalPrefix = "ACG"; + final String totalSuffix = "GCT"; + for ( int prefixSize = 0; prefixSize < totalPrefix.length(); prefixSize++) { + for ( int suffixSize = 0; suffixSize < totalPrefix.length(); suffixSize++) { + if ( prefixSize + suffixSize == 0 ) + continue; + for ( int indelSize = 1; indelSize < 50; indelSize++ ) { + final String prefix = totalPrefix.substring(0, prefixSize); + final String suffix = totalSuffix.substring(0, suffixSize); + final String insert = Utils.dupString("N", indelSize); + tests.add(new Object[]{prefix + suffix, prefix + insert + suffix, prefix.length() + "M" + indelSize + "I" + suffix.length() + "M"}); + tests.add(new Object[]{prefix + insert + suffix, prefix + suffix, prefix.length() + "M" + indelSize + "D" + suffix.length() + "M"}); + } + } + } + + // larger indels with prefixes/suffixes + tests.add(new Object[]{"ACTGTTTTGAACATCAGTTATTTTAAACTTTTAAGTTGTTAGCACAGCAAAAGCAACAAAATTCTAAGTGCAGTAATCACTTTACTGCGTGGTCATATGAAATCAAGGCAATGTTATGAGTATTACTGGAAAGCTGGACAGAGTAACGGGAAAAGTGACTAAAACTATGC", "CCTGTTTTGAACATCAGTTATTTTAAACTTTTAAGTTGTTAGCACAGCAAAAGCAACAAAATTCTAAGTGCAGTAATCACTTTACTGCGTGGTCATATGAAATCAAGGCAATGTTATGAGTATTACTGGAAAGCTGGACAGAGTAACGGGAAAAGTGACT", "160M10D"}); + tests.add(new Object[]{"LLLLLTATTAAGTAGTGCTCTATGTTGTCAACTAATTTATTTCCCATTTCAAACATTAGTTGACATGTTTTCATTTCTCTTTTGGAAGGAAACAACTAAATATGTTATCAATCCATCATTTACTTGTACAATAAATAAAGTTCTAAATCACTGCACAGTGTAAAATGGCAAATAGACTTCCCCATAACACAAAGCCATCCTGAAAAGTTTTGTTCATTTTAGAAGRRRRR", "LLLLLARRRRR", "5M219D6M"}); + tests.add(new Object[]{"LLLLLTATTTTTTRRRRR", "LLLLLARRRRR", "5M7D6M"}); + + // systematic testing + for ( final int forwardMatches : Arrays.asList(0, 1, 5, 10)) { + for ( final int forwardMismatches : Arrays.asList(0, 1, 2)) { + for ( final int middleMatches : Arrays.asList(0, 1, 5, 10)) { + for ( final int delSize : Arrays.asList(0, 1, 2, 3 )) { + for ( final int insSize : Arrays.asList(0, 1, 2, 3 )) { + for ( final int reverseMismatches : Arrays.asList(0, 1, 2)) { + for ( final int reverseMatches : Arrays.asList(0, 1, 5, 10)) { + // if there is an insertion and deletion, they should cancel each other out (at least partially) + final int overlap = Math.min(delSize, insSize); + final int myDelSize = delSize - overlap; + final int myInsSize = insSize - overlap; + + // this case is too difficult to create a CIGAR for because SW will (legitimately) prefer to switch the indel and mismatches + final int totalMismatches = forwardMismatches + reverseMismatches; + if ( (myDelSize > 0 || myInsSize > 0 ) && (totalMismatches >= myDelSize || totalMismatches >= myInsSize) ) + continue; + + final StringBuilder refBuilder = new StringBuilder(); + final StringBuilder altBuilder = new StringBuilder(); + final StringBuilder cigarBuilder = new StringBuilder(); + + refBuilder.append(Utils.dupString('A', forwardMatches + forwardMismatches + middleMatches)); + altBuilder.append(Utils.dupString('A', forwardMatches)); + altBuilder.append(Utils.dupString('C', forwardMismatches)); + altBuilder.append(Utils.dupString('A', middleMatches)); + cigarBuilder.append(forwardMatches + forwardMismatches + middleMatches); + cigarBuilder.append("M"); + + if ( myDelSize > 0 ) { + refBuilder.append(Utils.dupString('G', myDelSize)); + cigarBuilder.append(myDelSize); + cigarBuilder.append("D"); + } + if ( myInsSize > 0 ) { + altBuilder.append(Utils.dupString('T', myInsSize)); + cigarBuilder.append(myInsSize); + cigarBuilder.append("I"); + } + if ( overlap > 0 ) { + refBuilder.append(Utils.dupString('G', overlap)); + altBuilder.append(Utils.dupString('T', overlap)); + cigarBuilder.append(overlap); + cigarBuilder.append("M"); + } + if ( delSize > 0 || insSize > 0 ) { + refBuilder.append(Utils.dupString('A', middleMatches)); + altBuilder.append(Utils.dupString('A', middleMatches)); + cigarBuilder.append(middleMatches); + cigarBuilder.append("M"); + } + + refBuilder.append(Utils.dupString('A', reverseMismatches + reverseMatches)); + altBuilder.append(Utils.dupString('C', reverseMismatches)); + altBuilder.append(Utils.dupString('A', reverseMatches)); + cigarBuilder.append(reverseMismatches + reverseMatches); + cigarBuilder.append("M"); + + if ( refBuilder.length() > 0 && altBuilder.length() > 0 ) + tests.add(new Object[]{refBuilder.toString(), altBuilder.toString(), cigarBuilder.toString()}); + } + } + } + } + } + } + } + + return tests.toArray(new Object[][]{}); + } + + @Test(dataProvider = "SWData", enabled = !DEBUG) + public void testSW(final String seq1, final String seq2, final String expectedCigar) { + final GlobalEdgeGreedySWPairwiseAlignment alignment = new GlobalEdgeGreedySWPairwiseAlignment(seq1.getBytes(), seq2.getBytes(), new Parameters(5.0, -5.0, -25.0, -1.0)); + Assert.assertEquals(alignment.getCigar(), AlignmentUtils.consolidateCigar(TextCigarCodec.getSingleton().decode(expectedCigar))); + } + + /** + * For debugging purposes only + */ + @Test(enabled = DEBUG) + public void testDebugging() { + final String ref = "A"; + final String alt = "C"; + + final GlobalEdgeGreedySWPairwiseAlignment sw = new GlobalEdgeGreedySWPairwiseAlignment(ref.getBytes(), alt.getBytes(), new Parameters(5.0, -5.0, -25.0, -1.0)); + Assert.assertEquals(sw.getCigar().toString(), "1M"); + } +} diff --git a/public/java/src/org/broadinstitute/sting/utils/Utils.java b/public/java/src/org/broadinstitute/sting/utils/Utils.java index 5b2bba73c..73a538ee5 100644 --- a/public/java/src/org/broadinstitute/sting/utils/Utils.java +++ b/public/java/src/org/broadinstitute/sting/utils/Utils.java @@ -789,4 +789,20 @@ public class Utils { } return end; } + + /** + * Trim any number of bases from the front and/or back of an array + * + * @param seq the sequence to trim + * @param trimFromFront how much to trim from the front + * @param trimFromBack how much to trim from the back + * @return a non-null array; can be the original array (i.e. not a copy) + */ + public static byte[] trimArray(final byte[] seq, final int trimFromFront, final int trimFromBack) { + if ( trimFromFront + trimFromBack > seq.length ) + throw new IllegalArgumentException("trimming total is larger than the original array"); + + // don't perform array copies if we need to copy everything anyways + return ( trimFromFront == 0 && trimFromBack == 0 ) ? seq : Arrays.copyOfRange(seq, trimFromFront, seq.length - trimFromBack); + } } diff --git a/public/java/src/org/broadinstitute/sting/utils/smithwaterman/GlobalEdgeGreedySWPairwiseAlignment.java b/public/java/src/org/broadinstitute/sting/utils/smithwaterman/GlobalEdgeGreedySWPairwiseAlignment.java new file mode 100644 index 000000000..27ead2e48 --- /dev/null +++ b/public/java/src/org/broadinstitute/sting/utils/smithwaterman/GlobalEdgeGreedySWPairwiseAlignment.java @@ -0,0 +1,217 @@ +/* +* Copyright (c) 2012 The Broad Institute +* +* Permission is hereby granted, free of charge, to any person +* obtaining a copy of this software and associated documentation +* files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, +* copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following +* conditions: +* +* The above copyright notice and this permission notice shall be +* included in all copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR +* THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +package org.broadinstitute.sting.utils.smithwaterman; + +import net.sf.samtools.Cigar; +import net.sf.samtools.CigarElement; +import org.broadinstitute.sting.utils.Utils; +import org.broadinstitute.sting.utils.sam.AlignmentUtils; + +import java.util.*; + +/** + * Pairwise discrete Smith-Waterman alignment with an edge greedy implementation + * + * ************************************************************************ + * **** IMPORTANT NOTE: **** + * **** This class assumes that all bytes come from UPPERCASED chars! **** + * ************************************************************************ + * + * User: ebanks + */ +public final class GlobalEdgeGreedySWPairwiseAlignment extends SWPairwiseAlignment { + + private final static boolean DEBUG_MODE = false; + + /** + * Create a new greedy SW pairwise aligner + * + * @param reference the reference sequence we want to align + * @param alternate the alternate sequence we want to align + * @param parameters the SW parameters to use + */ + public GlobalEdgeGreedySWPairwiseAlignment(final byte[] reference, final byte[] alternate, final Parameters parameters) { + super(reference, alternate, parameters); + } + + /** + * Create a new SW pairwise aligner + * + * After creating the object the two sequences are aligned with an internal call to align(seq1, seq2) + * + * @param reference the reference sequence we want to align + * @param alternate the alternate sequence we want to align + * @param namedParameters the named parameter set to get our parameters from + */ + public GlobalEdgeGreedySWPairwiseAlignment(final byte[] reference, final byte[] alternate, final SWParameterSet namedParameters) { + this(reference, alternate, namedParameters.parameters); + } + + /** + * @see #GlobalEdgeGreedySWPairwiseAlignment(byte[], byte[], SWParameterSet) with original default parameters + */ + public GlobalEdgeGreedySWPairwiseAlignment(byte[] reference, byte[] alternate) { + this(reference, alternate, SWParameterSet.ORIGINAL_DEFAULT); + } + + /** + * Aligns the alternate sequence to the reference sequence + * + * @param reference ref sequence + * @param alternate alt sequence + */ + @Override + protected void align(final byte[] reference, final byte[] alternate) { + if ( reference == null || reference.length == 0 ) + throw new IllegalArgumentException("Non-null, non-empty reference sequences are required for the Smith-Waterman calculation"); + if ( alternate == null || alternate.length == 0 ) + throw new IllegalArgumentException("Non-null, non-empty alternate sequences are required for the Smith-Waterman calculation"); + + final int forwardEdgeMatch = Utils.longestCommonPrefix(reference, alternate, Integer.MAX_VALUE); + + // edge case: one sequence is a strict prefix of the other + if ( forwardEdgeMatch == reference.length || forwardEdgeMatch == alternate.length ) { + alignmentResult = new SWPairwiseAlignmentResult(makeCigarForStrictPrefixAndSuffix(reference, alternate, forwardEdgeMatch, 0), 0); + return; + } + + int reverseEdgeMatch = Utils.longestCommonSuffix(reference, alternate, Integer.MAX_VALUE); + + // edge case: one sequence is a strict suffix of the other + if ( reverseEdgeMatch == reference.length || reverseEdgeMatch == alternate.length ) { + alignmentResult = new SWPairwiseAlignmentResult(makeCigarForStrictPrefixAndSuffix(reference, alternate, 0, reverseEdgeMatch), 0); + return; + } + + final int sizeOfRefToAlign = reference.length - forwardEdgeMatch - reverseEdgeMatch; + final int sizeOfAltToAlign = alternate.length - forwardEdgeMatch - reverseEdgeMatch; + + // edge case: one sequence is a strict subset of the other accounting for both prefix and suffix + final int minSizeToAlign = Math.min(sizeOfRefToAlign, sizeOfAltToAlign); + if ( minSizeToAlign < 0 ) + reverseEdgeMatch += minSizeToAlign; + if ( sizeOfRefToAlign <= 0 || sizeOfAltToAlign <= 0 ) { + alignmentResult = new SWPairwiseAlignmentResult(makeCigarForStrictPrefixAndSuffix(reference, alternate, forwardEdgeMatch, reverseEdgeMatch), 0); + return; + } + + final byte[] refToAlign = Utils.trimArray(reference, forwardEdgeMatch, reverseEdgeMatch); + final byte[] altToAlign = Utils.trimArray(alternate, forwardEdgeMatch, reverseEdgeMatch); + + final double[] sw = new double[(sizeOfRefToAlign+1)*(sizeOfAltToAlign+1)]; + if ( keepScoringMatrix ) SW = sw; + final int[] btrack = new int[(sizeOfRefToAlign+1)*(sizeOfAltToAlign+1)]; + + calculateMatrix(refToAlign, altToAlign, sw, btrack, OVERHANG_STRATEGY.INDEL); + + if ( DEBUG_MODE ) { + System.out.println(new String(refToAlign) + " vs. " + new String(altToAlign)); + debugMatrix(sw, sizeOfRefToAlign+1, sizeOfAltToAlign+1); + System.out.println("----"); + debugMatrix(btrack, sizeOfRefToAlign + 1, sizeOfAltToAlign + 1); + System.out.println(); + } + + alignmentResult = calculateCigar(forwardEdgeMatch, reverseEdgeMatch, sizeOfRefToAlign, sizeOfAltToAlign, sw, btrack); + } + + private void debugMatrix(final double[] matrix, final int dim1, final int dim2) { + for ( int i = 0; i < dim1; i++ ) { + for ( int j = 0; j < dim2; j++ ) + System.out.print(String.format("%.1f ", matrix[i * dim2 + j])); + System.out.println(); + } + } + + private void debugMatrix(final int[] matrix, final int dim1, final int dim2) { + for ( int i = 0; i < dim1; i++ ) { + for ( int j = 0; j < dim2; j++ ) + System.out.print(matrix[i*dim2 + j] + " "); + System.out.println(); + } + } + + /** + * Creates a CIGAR for the case where the prefix/suffix match combination encompasses an entire sequence + * + * @param reference the reference sequence + * @param alternate the alternate sequence + * @param matchingPrefix the prefix match size + * @param matchingSuffix the suffix match size + * @return non-null CIGAR + */ + private Cigar makeCigarForStrictPrefixAndSuffix(final byte[] reference, final byte[] alternate, final int matchingPrefix, final int matchingSuffix) { + + final List result = new ArrayList(); + + // edge case: no D or I element + if ( reference.length == alternate.length ) { + result.add(makeElement(State.MATCH, matchingPrefix + matchingSuffix)); + } else { + // add the first M element + if ( matchingPrefix > 0 ) + result.add(makeElement(State.MATCH, matchingPrefix)); + + // add the D or I element + if ( alternate.length > reference.length ) + result.add(makeElement(State.INSERTION, alternate.length - reference.length)); + else // if ( reference.length > alternate.length ) + result.add(makeElement(State.DELETION, reference.length - alternate.length)); + + // add the last M element + if ( matchingSuffix > 0 ) + result.add(makeElement(State.MATCH, matchingSuffix)); + } + + return new Cigar(result); + } + + /** + * Calculates the CIGAR for the alignment from the back track matrix + * + * @param matchingPrefix the prefix match size + * @param matchingSuffix the suffix match size + * @param refLength length of the reference sequence + * @param altLength length of the alternate sequence + * @param sw the Smith-Waterman matrix to use + * @param btrack the back track matrix to use + * @return non-null SWPairwiseAlignmentResult object + */ + protected SWPairwiseAlignmentResult calculateCigar(final int matchingPrefix, final int matchingSuffix, + final int refLength, final int altLength, + final double[] sw, final int[] btrack) { + + final SWPairwiseAlignmentResult SW_result = calculateCigar(refLength, altLength, sw, btrack, OVERHANG_STRATEGY.INDEL); + + final LinkedList lce = new LinkedList(SW_result.cigar.getCigarElements()); + if ( matchingPrefix > 0 ) + lce.addFirst(makeElement(State.MATCH, matchingPrefix)); + if ( matchingSuffix > 0 ) + lce.addLast(makeElement(State.MATCH, matchingSuffix)); + + return new SWPairwiseAlignmentResult(AlignmentUtils.consolidateCigar(new Cigar(lce)), 0); + } +} \ No newline at end of file diff --git a/public/java/src/org/broadinstitute/sting/utils/smithwaterman/SWPairwiseAlignment.java b/public/java/src/org/broadinstitute/sting/utils/smithwaterman/SWPairwiseAlignment.java index 78f81ec5e..84c33d4a5 100644 --- a/public/java/src/org/broadinstitute/sting/utils/smithwaterman/SWPairwiseAlignment.java +++ b/public/java/src/org/broadinstitute/sting/utils/smithwaterman/SWPairwiseAlignment.java @@ -45,19 +45,43 @@ import java.util.*; * Date: Mar 23, 2009 * Time: 1:54:54 PM */ -public final class SWPairwiseAlignment implements SmithWaterman { - private int alignment_offset; // offset of s2 w/respect to s1 - private Cigar alignmentCigar; +public class SWPairwiseAlignment implements SmithWaterman { - private final Parameters parameters; + protected SWPairwiseAlignmentResult alignmentResult; - private static final int MSTATE = 0; - private static final int ISTATE = 1; - private static final int DSTATE = 2; - private static final int CLIP = 3; + protected final Parameters parameters; + + /** + * The state of a trace step through the matrix + */ + protected enum State { + MATCH, + INSERTION, + DELETION, + CLIP + } + + /** + * What strategy should we use when the best path does not start/end at the corners of the matrix? + */ + public enum OVERHANG_STRATEGY { + /* + * Add softclips for the overhangs + */ + SOFTCLIP, + /* + * Treat the overhangs as proper insertions/deletions + */ + INDEL, + /* + * Just ignore the overhangs + */ + IGNORE + } protected static boolean cutoff = false; - private boolean doSoftClipping = true; + + protected OVERHANG_STRATEGY overhang_strategy = OVERHANG_STRATEGY.SOFTCLIP; /** * The SW scoring matrix, stored for debugging purposes if keepScoringMatrix is true @@ -103,10 +127,6 @@ public final class SWPairwiseAlignment implements SmithWaterman { this.parameters = parameters; } - protected void setDoSoftClipping(final boolean doSoftClipping) { - this.doSoftClipping = doSoftClipping; - } - /** * Create a new SW pairwise aligner * @@ -125,42 +145,93 @@ public final class SWPairwiseAlignment implements SmithWaterman { } @Override - public Cigar getCigar() { return alignmentCigar ; } + public Cigar getCigar() { return alignmentResult.cigar ; } @Override - public int getAlignmentStart2wrt1() { return alignment_offset; } + public int getAlignmentStart2wrt1() { return alignmentResult.alignment_offset; } - public void align(final byte[] a, final byte[] b) { - final int n = a.length; - final int m = b.length; + /** + * Aligns the alternate sequence to the reference sequence + * + * @param reference ref sequence + * @param alternate alt sequence + */ + protected void align(final byte[] reference, final byte[] alternate) { + if ( reference == null || reference.length == 0 || alternate == null || alternate.length == 0 ) + throw new IllegalArgumentException("Non-null, non-empty sequences are required for the Smith-Waterman calculation"); + + final int n = reference.length; + final int m = alternate.length; double [] sw = new double[(n+1)*(m+1)]; if ( keepScoringMatrix ) SW = sw; int [] btrack = new int[(n+1)*(m+1)]; - calculateMatrix(a, b, sw, btrack); - calculateCigar(n, m, sw, btrack); // length of the segment (continuous matches, insertions or deletions) + calculateMatrix(reference, alternate, sw, btrack); + alignmentResult = calculateCigar(n, m, sw, btrack, overhang_strategy); // length of the segment (continuous matches, insertions or deletions) } + /** + * Calculates the SW matrices for the given sequences + * + * @param reference ref sequence + * @param alternate alt sequence + * @param sw the Smith-Waterman matrix to populate + * @param btrack the back track matrix to populate + */ + protected void calculateMatrix(final byte[] reference, final byte[] alternate, double[] sw, int[] btrack) { + calculateMatrix(reference, alternate, sw, btrack, overhang_strategy); + } - 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; + /** + * Calculates the SW matrices for the given sequences + * + * @param reference ref sequence + * @param alternate alt sequence + * @param sw the Smith-Waterman matrix to populate + * @param btrack the back track matrix to populate + * @param overhang_strategy the strategy to use for dealing with overhangs + */ + protected void calculateMatrix(final byte[] reference, final byte[] alternate, double[] sw, int[] btrack, final OVERHANG_STRATEGY overhang_strategy) { + if ( reference.length == 0 || alternate.length == 0 ) + throw new IllegalArgumentException("Non-null, non-empty sequences are required for the Smith-Waterman calculation"); + + final int n = reference.length+1; + final int m = alternate.length+1; //final double MATRIX_MIN_CUTOFF=-1e100; // never let matrix elements drop below this cutoff final double MATRIX_MIN_CUTOFF; // never let matrix elements drop below this cutoff if ( cutoff ) MATRIX_MIN_CUTOFF = 0.0; else MATRIX_MIN_CUTOFF = -1e100; - double [] best_gap_v = new double[m+1]; - Arrays.fill(best_gap_v,-1.0e40); - int [] gap_size_v = new int[m+1]; - double [] best_gap_h = new double[n+1]; + final double[] best_gap_v = new double[m+1]; + Arrays.fill(best_gap_v, -1.0e40); + final int[] gap_size_v = new int[m+1]; + final double[] best_gap_h = new double[n+1]; Arrays.fill(best_gap_h,-1.0e40); - int [] gap_size_h = new int[n+1]; + final int[] gap_size_h = new int[n+1]; + + // we need to initialize the SW matrix with gap penalties if we want to keep track of indels at the edges of alignments + if ( overhang_strategy == OVERHANG_STRATEGY.INDEL ) { + // initialize the first row + sw[1] = parameters.w_open; + double currentValue = parameters.w_open; + for ( int i = 2; i < m; i++ ) { + currentValue += parameters.w_extend; + sw[i] = currentValue; + } + + // initialize the first column + sw[m] = parameters.w_open; + currentValue = parameters.w_open; + for ( int i = 2; i < n; i++ ) { + currentValue += parameters.w_extend; + sw[i*m] = currentValue; + } + } // 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 + byte a_base = reference[i-1]; // letter in a at the current pos final int row_offset = row_offset_1 + m; @@ -172,10 +243,10 @@ public final class SWPairwiseAlignment implements SmithWaterman { // data_offset_1 is linearized offset of element [i-1][j-1] - final byte b_base = b[j-1]; // letter in b at the current pos + final byte b_base = alternate[j-1]; // letter in b at the current pos // in other words, step_diag = sw[i-1][j-1] + wd(a_base,b_base); - double step_diag = sw[data_offset_1] + wd(a_base,b_base); + final double step_diag = sw[data_offset_1] + wd(a_base,b_base); // optimized "traversal" of all the matrix cells above the current one (i.e. traversing // all 'step down' events that would end in the current cell. The optimized code @@ -251,65 +322,92 @@ public final class SWPairwiseAlignment implements SmithWaterman { } } + /* + * Class to store the result of calculating the CIGAR from the back track matrix + */ + protected final class SWPairwiseAlignmentResult { + public final Cigar cigar; + public final int alignment_offset; + public SWPairwiseAlignmentResult(final Cigar cigar, final int alignment_offset) { + this.cigar = cigar; + this.alignment_offset = alignment_offset; + } + } - private void calculateCigar(int n, int m, double [] sw, int [] btrack) { + /** + * Calculates the CIGAR for the alignment from the back track matrix + * + * @param refLength length of the reference sequence + * @param altLength length of the alternate sequence + * @param sw the Smith-Waterman matrix to use + * @param btrack the back track matrix to use + * @param overhang_strategy the strategy to use for dealing with overhangs + * @return non-null SWPairwiseAlignmentResult object + */ + protected SWPairwiseAlignmentResult calculateCigar(final int refLength, final int altLength, final double[] sw, final int[] btrack, final OVERHANG_STRATEGY overhang_strategy) { // p holds the position we start backtracking from; we will be assembling a cigar in the backwards order int p1 = 0, p2 = 0; double maxscore = Double.NEGATIVE_INFINITY; // sw scores are allowed to be negative int segment_length = 0; // length of the segment (continuous matches, insertions or deletions) - // look for largest score. we use >= combined with the traversal direction - // to ensure that if two scores are equal, the one closer to diagonal gets picked - for ( int i = 1, data_offset = m+1+m ; i < n+1 ; i++, data_offset += (m+1) ) { - // data_offset is the offset of [i][m] - if ( sw[data_offset] >= maxscore ) { - p1 = i; p2 = m ; maxscore = sw[data_offset]; + // if we want to consider overhangs as legitimate operators, then just start from the corner of the matrix + if ( overhang_strategy == OVERHANG_STRATEGY.INDEL ) { + p1 = refLength; + p2 = altLength; + } else { + // look for largest score. we use >= combined with the traversal direction + // to ensure that if two scores are equal, the one closer to diagonal gets picked + for ( int i = 1, data_offset = altLength+1+altLength ; i < refLength+1 ; i++, data_offset += (altLength+1) ) { + // data_offset is the offset of [i][m] + if ( sw[data_offset] >= maxscore ) { + p1 = i; p2 = altLength ; maxscore = sw[data_offset]; + } } - } - for ( int j = 1, data_offset = n*(m+1)+1 ; j < m+1 ; j++, data_offset++ ) { - // data_offset is the offset of [n][j] - if ( sw[data_offset] > maxscore || sw[data_offset] == maxscore && Math.abs(n-j) < Math.abs(p1 - p2)) { - p1 = n; - p2 = j ; - maxscore = sw[data_offset]; - segment_length = m - j ; // end of sequence 2 is overhanging; we will just record it as 'M' segment + for ( int j = 1, data_offset = refLength*(altLength+1)+1 ; j < altLength+1 ; j++, data_offset++ ) { + // data_offset is the offset of [n][j] + if ( sw[data_offset] > maxscore || sw[data_offset] == maxscore && Math.abs(refLength-j) < Math.abs(p1 - p2)) { + p1 = refLength; + p2 = j ; + maxscore = sw[data_offset]; + segment_length = altLength - j ; // end of sequence 2 is overhanging; we will just record it as 'M' segment + } } } List lce = new ArrayList(5); - if ( segment_length > 0 && doSoftClipping ) { - lce.add(makeElement(CLIP, segment_length)); + if ( segment_length > 0 && overhang_strategy == OVERHANG_STRATEGY.SOFTCLIP ) { + lce.add(makeElement(State.CLIP, segment_length)); segment_length = 0; } // we will be placing all insertions and deletions into sequence b, so the states are named w/regard // to that sequence - int state = MSTATE; + State state = State.MATCH; - int data_offset = p1*(m+1)+p2; // offset of element [p1][p2] + int data_offset = p1*(altLength+1)+p2; // offset of element [p1][p2] do { int btr = btrack[data_offset]; - int new_state; + State new_state; int step_length = 1; if ( btr > 0 ) { - new_state = DSTATE; + new_state = State.DELETION; step_length = btr; } else if ( btr < 0 ) { - new_state = ISTATE; + new_state = State.INSERTION; step_length = (-btr); - } else new_state = MSTATE; // and step_length =1, already set above + } else new_state = State.MATCH; // and step_length =1, already set above // move to next best location in the sw matrix: switch( new_state ) { - case MSTATE: data_offset -= (m+2); p1--; p2--; break; // move back along the diag in the sw matrix - case ISTATE: data_offset -= step_length; p2 -= step_length; break; // move left - case DSTATE: data_offset -= (m+1)*step_length; p1 -= step_length; break; // move up + case MATCH: data_offset -= (altLength+2); p1--; p2--; break; // move back along the diag in the sw matrix + case INSERTION: data_offset -= step_length; p2 -= step_length; break; // move left + case DELETION: data_offset -= (altLength+1)*step_length; p1 -= step_length; break; // move up } // now let's see if the state actually changed: @@ -320,7 +418,7 @@ public final class SWPairwiseAlignment implements SmithWaterman { segment_length = step_length; state = new_state; } -// next condition is equivalent to while ( sw[p1][p2] != 0 ) (with modified p1 and/or p2: + // next condition is equivalent to while ( sw[p1][p2] != 0 ) (with modified p1 and/or p2: } while ( p1 > 0 && p2 > 0 ); // post-process the last segment we are still keeping; @@ -331,28 +429,41 @@ public final class SWPairwiseAlignment implements SmithWaterman { // last 3 bases of the read overlap with/align to the ref), the cigar will be still 5M if // DO_SOFTCLIP is false or 2S3M if DO_SOFTCLIP is true. // The consumers need to check for the alignment offset and deal with it properly. - if (doSoftClipping ) { + final int alignment_offset; + if ( overhang_strategy == OVERHANG_STRATEGY.SOFTCLIP ) { lce.add(makeElement(state, segment_length)); - if ( p2> 0 ) lce.add(makeElement(CLIP, p2)); - alignment_offset = p1 ; - } else { + if ( p2 > 0 ) lce.add(makeElement(State.CLIP, p2)); + alignment_offset = p1; + } else if ( overhang_strategy == OVERHANG_STRATEGY.IGNORE ) { lce.add(makeElement(state, segment_length + p2)); alignment_offset = p1 - p2; + } else { // overhang_strategy == OVERHANG_STRATEGY.INDEL + + // take care of the actual alignment + lce.add(makeElement(state, segment_length)); + + // take care of overhangs at the beginning of the alignment + if ( p1 > 0 ) + lce.add(makeElement(State.DELETION, p1)); + else if ( p2 > 0 ) + lce.add(makeElement(State.INSERTION, p2)); + + alignment_offset = 0; } Collections.reverse(lce); - alignmentCigar = AlignmentUtils.consolidateCigar(new Cigar(lce)); + return new SWPairwiseAlignmentResult(AlignmentUtils.consolidateCigar(new Cigar(lce)), alignment_offset); } - private CigarElement makeElement(int state, int segment_length) { - CigarOperator o = null; - switch(state) { - case MSTATE: o = CigarOperator.M; break; - case ISTATE: o = CigarOperator.I; break; - case DSTATE: o = CigarOperator.D; break; - case CLIP: o = CigarOperator.S; break; + protected CigarElement makeElement(final State state, final int length) { + CigarOperator op = null; + switch (state) { + case MATCH: op = CigarOperator.M; break; + case INSERTION: op = CigarOperator.I; break; + case DELETION: op = CigarOperator.D; break; + case CLIP: op = CigarOperator.S; break; } - return new CigarElement(segment_length,o); + return new CigarElement(length, op); } private double wd(byte x, byte y) { @@ -375,7 +486,7 @@ public final class SWPairwiseAlignment implements SmithWaterman { Cigar cigar = getCigar(); - if ( ! doSoftClipping ) { + if ( overhang_strategy != OVERHANG_STRATEGY.SOFTCLIP ) { // we need to go through all the hassle below only if we do not do softclipping; // otherwise offset is never negative diff --git a/public/java/src/org/broadinstitute/sting/utils/smithwaterman/SmithWaterman.java b/public/java/src/org/broadinstitute/sting/utils/smithwaterman/SmithWaterman.java index 44fd889c5..3a8afca8c 100644 --- a/public/java/src/org/broadinstitute/sting/utils/smithwaterman/SmithWaterman.java +++ b/public/java/src/org/broadinstitute/sting/utils/smithwaterman/SmithWaterman.java @@ -42,6 +42,7 @@ import net.sf.samtools.Cigar; * Time: 8:24 AM */ public interface SmithWaterman { + /** * Get the cigar string for the alignment of this SmithWaterman class * @return a non-null cigar diff --git a/public/java/test/org/broadinstitute/sting/utils/UtilsUnitTest.java b/public/java/test/org/broadinstitute/sting/utils/UtilsUnitTest.java index 3c68b8753..0a6f9898e 100644 --- a/public/java/test/org/broadinstitute/sting/utils/UtilsUnitTest.java +++ b/public/java/test/org/broadinstitute/sting/utils/UtilsUnitTest.java @@ -216,4 +216,24 @@ public class UtilsUnitTest extends BaseTest { } } } + + @DataProvider(name = "trim") + public Object[][] createTrimTestData() { + List tests = new ArrayList(); + + final String s = "AAAA"; + for ( int front = 0; front < s.length(); front++ ) { + for ( int back = 0; back < s.length(); back++ ) { + if ( front + back <= s.length() ) + tests.add(new Object[]{s, front, back}); + } + } + + return tests.toArray(new Object[][]{}); + } + + @Test(dataProvider = "trim", enabled = true) + public void testTrim(final String s, final int frontTrim, final int backTrim) { + Assert.assertEquals(s.length() - frontTrim - backTrim, Utils.trimArray(s.getBytes(), frontTrim, backTrim).length); + } } diff --git a/public/java/test/org/broadinstitute/sting/utils/smithwaterman/SmithWatermanBenchmark.java b/public/java/test/org/broadinstitute/sting/utils/smithwaterman/SmithWatermanBenchmark.java new file mode 100644 index 000000000..ee8f411bf --- /dev/null +++ b/public/java/test/org/broadinstitute/sting/utils/smithwaterman/SmithWatermanBenchmark.java @@ -0,0 +1,88 @@ +/* +* Copyright (c) 2012 The Broad Institute +* +* Permission is hereby granted, free of charge, to any person +* obtaining a copy of this software and associated documentation +* files (the "Software"), to deal in the Software without +* restriction, including without limitation the rights to use, +* copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following +* conditions: +* +* The above copyright notice and this permission notice shall be +* included in all copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR +* THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +package org.broadinstitute.sting.utils.smithwaterman; + +import com.google.caliper.Param; +import com.google.caliper.SimpleBenchmark; +import org.broadinstitute.sting.utils.Utils; + +/** + * Caliper microbenchmark of parsing a VCF file + */ +public class SmithWatermanBenchmark extends SimpleBenchmark { + + @Param({"Original", "Greedy"}) + String version; // set automatically by framework + + @Param({"10", "50", "100", "500"}) + int sizeOfMiddleRegion; // set automatically by framework + + @Param({"10", "50", "100", "500"}) + int sizeOfEndRegions; // set automatically by framework + + String refString; + String hapString; + + @Override protected void setUp() { + final StringBuilder ref = new StringBuilder(); + final StringBuilder hap = new StringBuilder(); + + ref.append(Utils.dupString('A', sizeOfEndRegions)); + hap.append(Utils.dupString('A', sizeOfEndRegions)); + + // introduce a SNP + ref.append("X"); + hap.append("Y"); + + ref.append(Utils.dupString('A', sizeOfMiddleRegion)); + hap.append(Utils.dupString('A', sizeOfMiddleRegion)); + + // introduce a SNP + ref.append("X"); + hap.append("Y"); + + ref.append(Utils.dupString('A', sizeOfEndRegions)); + hap.append(Utils.dupString('A', sizeOfEndRegions)); + + refString = ref.toString(); + hapString = hap.toString(); + } + + public void timeSW(int rep) { + for ( int i = 0; i < rep; i++ ) { + final SmithWaterman sw; + if ( version.equals("Greedy") ) + sw = new GlobalEdgeGreedySWPairwiseAlignment(refString.getBytes(), hapString.getBytes()); + else + sw = new SWPairwiseAlignment(refString.getBytes(), hapString.getBytes()); + sw.getCigar(); + } + } + + public static void main(String[] args) { + com.google.caliper.Runner.main(SmithWatermanBenchmark.class, args); + } +}