Fast DeBruijnGraph creation using the kmer counter

-- The previous creation algorithm used the following algorithm:

for each kmer1 -> kmer2 in each read
  add kmers 1 and 2 to the graph
  add edge kmer1 -> kmer2 in the graph, if it's not present (does check)
  update edge count by 1 if kmer1 -> kmer2 already existed in the graph

-- This algorithm had O(reads * kmers / read * (getEdge cost + addEdge cost)).  This is actually pretty expensive because get and add edges is expensive in jgrapht.
-- The new approach uses the following algorithm:

for each kmer1 -> kmer2 in each read
  add kmers 1 and 2 to a kmer counter, that counts kmer1+kmer2 in a fast hashmap

for each kmer pair 1 and 2 in the hash counter
  add edge kmer1 -> kmer2 in the graph, if it's not present (does check) with multiplicity count from map
  update edge count by count from map if kmer1 -> kmer2 already existed in the graph

-- This algorithm ensures that we add very much fewer edges
-- Additionally, created a fast kmer class that lets us create kmers from larger byte[]s of bases without cutting up the byte[] itself.
-- Overall runtimes are greatly reduced using this algorith
This commit is contained in:
Mark DePristo 2013-04-08 07:17:53 -04:00
parent 7d267639d8
commit bf42be44fc
7 changed files with 555 additions and 96 deletions

View File

@ -252,14 +252,15 @@ public class DeBruijnAssembler extends LocalAssemblyEngine {
@Requires({"reads != null", "kmerLength > 0", "refHaplotype != null"})
protected DeBruijnGraph createGraphFromSequences( final List<GATKSAMRecord> reads, final int kmerLength, final Haplotype refHaplotype ) {
final DeBruijnGraph graph = new DeBruijnGraph(kmerLength);
final DeBruijnGraphBuilder builder = new DeBruijnGraphBuilder(graph);
// First pull kmers from the reference haplotype and add them to the graph
if ( ! addReferenceKmersToGraph(graph, refHaplotype.getBases()) )
if ( ! addReferenceKmersToGraph(builder, refHaplotype.getBases()) )
// something went wrong, so abort right now with a null graph
return null;
// now go through the graph already seeded with the reference sequence and add the read kmers to it
if ( ! addReadKmersToGraph(graph, reads) )
if ( ! addReadKmersToGraph(builder, reads) )
// some problem was detected adding the reads to the graph, return null to indicate we failed
return null;
@ -270,12 +271,12 @@ public class DeBruijnAssembler extends LocalAssemblyEngine {
/**
* Add the high-quality kmers from the reads to the graph
*
* @param graph a graph to add the read kmers to
* @param builder a debruijn graph builder to add the read kmers to
* @param reads a non-null list of reads whose kmers we want to add to the graph
* @return true if we successfully added the read kmers to the graph without corrupting it in some way
*/
protected boolean addReadKmersToGraph(final DeBruijnGraph graph, final List<GATKSAMRecord> reads) {
final int kmerLength = graph.getKmerSize();
protected boolean addReadKmersToGraph(final DeBruijnGraphBuilder builder, final List<GATKSAMRecord> reads) {
final int kmerLength = builder.getKmerSize();
// Next pull kmers out of every read and throw them on the graph
for( final GATKSAMRecord read : reads ) {
@ -285,6 +286,7 @@ public class DeBruijnAssembler extends LocalAssemblyEngine {
if( sequence.length > kmerLength + KMER_OVERLAP ) {
final int kmersInSequence = sequence.length - kmerLength + 1;
for( int iii = 0; iii < kmersInSequence - 1; iii++ ) {
// TODO -- this is quite expense as it does O(kmerLength^2 work) per read
// if the qualities of all the bases in the kmers are high enough
boolean badKmer = false;
for( int jjj = iii; jjj < iii + kmerLength + 1; jjj++) {
@ -304,12 +306,14 @@ public class DeBruijnAssembler extends LocalAssemblyEngine {
countNumber = MathUtils.arrayMax(Arrays.copyOfRange(reducedReadCounts, iii, iii + kmerLength));
}
graph.addKmerPairFromSeqToGraph(sequence, iii, false, countNumber);
builder.addKmerPairFromSeqToGraph(sequence, iii, countNumber);
}
}
}
}
builder.flushKmersToGraph(false);
// always returns true now, but it's possible that we'd add reads and decide we don't like the graph in some way
return true;
}
@ -317,17 +321,17 @@ public class DeBruijnAssembler extends LocalAssemblyEngine {
/**
* Add the kmers from the reference sequence to the DeBruijnGraph
*
* @param graph the graph to add the reference kmers to. Must be empty
* @param builder the graph to add the reference kmers to. Must be empty
* @param refSequence the reference sequence from which we'll get our kmers
* @return true if we succeeded in creating a good graph from the reference sequence, false otherwise
*/
protected boolean addReferenceKmersToGraph(final DeBruijnGraph graph, final byte[] refSequence) {
if ( graph == null ) throw new IllegalArgumentException("graph cannot be null");
if ( graph.vertexSet().size() != 0 ) throw new IllegalArgumentException("Reference sequences must be added before any other vertices, but got a graph with " + graph.vertexSet().size() + " vertices in it already: " + graph);
protected boolean addReferenceKmersToGraph(final DeBruijnGraphBuilder builder, final byte[] refSequence) {
if ( builder == null ) throw new IllegalArgumentException("graph cannot be null");
if ( builder.getGraph().vertexSet().size() != 0 )
throw new IllegalArgumentException("Reference sequences must be added before any other vertices, but got a graph with " + builder.getGraph().vertexSet().size() + " vertices in it already: " + builder.getGraph());
if ( refSequence == null ) throw new IllegalArgumentException("refSequence cannot be null");
final int kmerLength = graph.getKmerSize();
final int kmerLength = builder.getKmerSize();
if( refSequence.length < kmerLength + KMER_OVERLAP ) {
// not enough reference sequence to build a kmer graph of this length, return null
return false;
@ -335,11 +339,12 @@ public class DeBruijnAssembler extends LocalAssemblyEngine {
final int kmersInSequence = refSequence.length - kmerLength + 1;
for( int iii = 0; iii < kmersInSequence - 1; iii++ ) {
graph.addKmerPairFromSeqToGraph(refSequence, iii, true, 1);
builder.addKmerPairFromSeqToGraph(refSequence, iii, 1);
}
builder.flushKmersToGraph(true);
// we expect that every kmer in the sequence is unique, so that the graph has exactly kmersInSequence vertices
if ( graph.vertexSet().size() != kmersInSequence ) {
if ( builder.getGraph().vertexSet().size() != kmersInSequence ) {
if( debug ) logger.info("Cycle detected in reference graph for kmer = " + kmerLength + " ...skipping");
return false;
}

View File

@ -46,39 +46,65 @@
package org.broadinstitute.sting.gatk.walkers.haplotypecaller;
import org.broadinstitute.sting.BaseTest;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.apache.log4j.Logger;
import org.broadinstitute.sting.gatk.walkers.haplotypecaller.graphs.DeBruijnGraph;
public class KMerCounterUnitTest extends BaseTest {
@Test
public void testMyData() {
final KMerCounter counter = new KMerCounter(3);
/**
* User: depristo
* Date: 4/7/13
* Time: 4:14 PM
*/
public class DeBruijnGraphBuilder {
private final static Logger logger = Logger.getLogger(DeBruijnGraphBuilder.class);
Assert.assertNotNull(counter.toString());
private final int kmerSize;
private final DeBruijnGraph graph;
private final KmerCounter counter;
counter.addKmers(
"ATG", "ATG", "ATG", "ATG",
"ACC", "ACC", "ACC",
"AAA", "AAA",
"CTG",
"NNA",
"CCC"
);
testCounting(counter, "ATG", 4);
testCounting(counter, "ACC", 3);
testCounting(counter, "AAA", 2);
testCounting(counter, "CTG", 1);
testCounting(counter, "NNA", 1);
testCounting(counter, "CCC", 1);
testCounting(counter, "NNN", 0);
testCounting(counter, "NNC", 0);
Assert.assertNotNull(counter.toString());
public DeBruijnGraphBuilder(final DeBruijnGraph graph) {
if ( graph == null ) throw new IllegalArgumentException("Graph cannot be null");
this.kmerSize = graph.getKmerSize();
this.graph = graph;
this.counter = new KmerCounter(kmerSize + 1);
}
private void testCounting(final KMerCounter counter, final String in, final int expectedCount) {
Assert.assertEquals(counter.getKmerCount(in.getBytes()), expectedCount);
public DeBruijnGraph getGraph() {
return graph;
}
public int getKmerSize() {
return kmerSize;
}
/**
* Higher-level interface to #addKmersToGraph that adds a pair of kmers from a larger sequence of bytes to this
* graph. The kmers start at start (first) and start + 1 (second) have have length getKmerSize(). The
* edge between them is added with isRef and multiplicity
*
* @param sequence a sequence of bases from which we want to extract a pair of kmers
* @param start the start of the first kmer in sequence, must be between 0 and sequence.length - 2 - getKmerSize()
* @param multiplicity what's the multiplicity of the edge between these two kmers
*/
public void addKmerPairFromSeqToGraph( final byte[] sequence, final int start, final int multiplicity ) {
if ( sequence == null ) throw new IllegalArgumentException("Sequence cannot be null");
if ( start < 0 ) throw new IllegalArgumentException("start must be >= 0 but got " + start);
if ( start + 1 + getKmerSize() > sequence.length ) throw new IllegalArgumentException("start " + start + " is too big given kmerSize " + getKmerSize() + " and sequence length " + sequence.length);
final Kmer kmerPair = new Kmer(sequence, start, getKmerSize() + 1);
addKmerPair(kmerPair, multiplicity);
}
public void addKmerPair(final Kmer kmerPair, final int multiplicity) {
if ( kmerPair.length() != kmerSize + 1 ) throw new IllegalArgumentException("kmer pair must be of length kmerSize + 1 = " + kmerSize + 1 + " but got " + kmerPair.length());
counter.addKmer(kmerPair, multiplicity);
}
public void flushKmersToGraph(final boolean addRefEdges) {
for ( final KmerCounter.CountedKmer countedKmer : counter.getCountedKmers() ) {
final byte[] first = countedKmer.getKmer().subKmer(0, kmerSize).bases();
final byte[] second = countedKmer.getKmer().subKmer(1, kmerSize).bases();
graph.addKmersToGraph(first, second, addRefEdges, countedKmer.getCount());
}
counter.clear();
}
}

View File

@ -46,9 +46,9 @@
package org.broadinstitute.sting.gatk.walkers.haplotypecaller;
import org.apache.log4j.Logger;
import java.util.*;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* generic utility class that counts kmers
@ -59,13 +59,13 @@ import java.util.*;
* Date: 3/8/13
* Time: 1:16 PM
*/
public class KMerCounter {
private final static Logger logger = Logger.getLogger(KMerCounter.class);
public class KmerCounter {
//private final static Logger logger = Logger.getLogger(KmerCounter.class);
/**
* A map of for each kmer to its num occurrences in addKmers
*/
private final Map<String, CountedKmer> countsByKMer = new HashMap<String, CountedKmer>();
private final Map<Kmer, CountedKmer> countsByKMer = new HashMap<Kmer, CountedKmer>();
private final int kmerLength;
/**
@ -73,70 +73,72 @@ public class KMerCounter {
*
* @param kmerLength the length of kmers we'll be counting to error correct, must be >= 1
*/
public KMerCounter(final int kmerLength) {
public KmerCounter(final int kmerLength) {
if ( kmerLength < 1 ) throw new IllegalArgumentException("kmerLength must be > 0 but got " + kmerLength);
this.kmerLength = kmerLength;
}
/**
* For testing purposes
*
* @param kmers
*/
protected void addKmers(final String ... kmers) {
for ( final String kmer : kmers )
addKmer(kmer, 1);
}
/**
* Get the count of kmer in this kmer counter
* @param kmer a non-null counter to get
* @return a positive integer
*/
public int getKmerCount(final byte[] kmer) {
public int getKmerCount(final Kmer kmer) {
if ( kmer == null ) throw new IllegalArgumentException("kmer cannot be null");
final CountedKmer counted = countsByKMer.get(new String(kmer));
final CountedKmer counted = countsByKMer.get(kmer);
return counted == null ? 0 : counted.count;
}
public Collection<CountedKmer> getCountedKmers() {
return countsByKMer.values();
}
public void clear() {
countsByKMer.clear();
}
/**
* Add a kmer that occurred kmerCount times
*
* @param rawKmer a kmer
* @param kmer a kmer
* @param kmerCount the number of occurrences
*/
public void addKmer(final byte[] rawKmer, final int kmerCount) {
addKmer(new String(rawKmer), kmerCount);
}
protected void addKmer(final String rawKmer, final int kmerCount) {
if ( rawKmer.length() != kmerLength ) throw new IllegalArgumentException("bad kmer length " + rawKmer + " expected size " + kmerLength);
public void addKmer(final Kmer kmer, final int kmerCount) {
if ( kmer.length() != kmerLength ) throw new IllegalArgumentException("bad kmer length " + kmer + " expected size " + kmerLength);
if ( kmerCount < 0 ) throw new IllegalArgumentException("bad kmerCount " + kmerCount);
CountedKmer countFromMap = countsByKMer.get(rawKmer);
CountedKmer countFromMap = countsByKMer.get(kmer);
if ( countFromMap == null ) {
countFromMap = new CountedKmer(rawKmer);
countsByKMer.put(rawKmer, countFromMap);
countFromMap = new CountedKmer(kmer);
countsByKMer.put(kmer, countFromMap);
}
countFromMap.count += kmerCount;
}
@Override
public String toString() {
final StringBuilder b = new StringBuilder("KMerCounter{");
final StringBuilder b = new StringBuilder("KmerCounter{");
b.append("counting ").append(countsByKMer.size()).append(" distinct kmers");
b.append("\n}");
return b.toString();
}
private static class CountedKmer implements Comparable<CountedKmer> {
final String kmer;
int count;
protected static class CountedKmer implements Comparable<CountedKmer> {
final Kmer kmer;
int count = 0;
private CountedKmer(String kmer) {
private CountedKmer(final Kmer kmer) {
this.kmer = kmer;
}
public Kmer getKmer() {
return kmer;
}
public int getCount() {
return count;
}
@Override
public String toString() {
return "CountedKmer{" +
@ -150,4 +152,25 @@ public class KMerCounter {
return o.count - count;
}
}
// -------------------------------------------------------------------------------------
// Protected methods for testing purposes only
// -------------------------------------------------------------------------------------
/**
* For testing purposes only
*/
protected void addKmer(final String rawKmer, final int kmerCount) {
addKmer(new Kmer(rawKmer), kmerCount);
}
/**
* For testing purposes
*
* @param kmers
*/
protected void addKmers(final String ... kmers) {
for ( final String kmer : kmers )
addKmer(kmer, 1);
}
}

View File

@ -0,0 +1,207 @@
/*
* By downloading the PROGRAM you agree to the following terms of use:
*
* BROAD INSTITUTE - SOFTWARE LICENSE AGREEMENT - FOR ACADEMIC NON-COMMERCIAL RESEARCH PURPOSES ONLY
*
* This Agreement is made between the Broad Institute, Inc. with a principal address at 7 Cambridge Center, Cambridge, MA 02142 (BROAD) and the LICENSEE and is effective at the date the downloading is completed (EFFECTIVE DATE).
*
* WHEREAS, LICENSEE desires to license the PROGRAM, as defined hereinafter, and BROAD wishes to have this PROGRAM utilized in the public interest, subject only to the royalty-free, nonexclusive, nontransferable license rights of the United States Government pursuant to 48 CFR 52.227-14; and
* WHEREAS, LICENSEE desires to license the PROGRAM and BROAD desires to grant a license on the following terms and conditions.
* NOW, THEREFORE, in consideration of the promises and covenants made herein, the parties hereto agree as follows:
*
* 1. DEFINITIONS
* 1.1 PROGRAM shall mean copyright in the object code and source code known as GATK2 and related documentation, if any, as they exist on the EFFECTIVE DATE and can be downloaded from http://www.broadinstitute/GATK on the EFFECTIVE DATE.
*
* 2. LICENSE
* 2.1 Grant. Subject to the terms of this Agreement, BROAD hereby grants to LICENSEE, solely for academic non-commercial research purposes, a non-exclusive, non-transferable license to: (a) download, execute and display the PROGRAM and (b) create bug fixes and modify the PROGRAM.
* The LICENSEE may apply the PROGRAM in a pipeline to data owned by users other than the LICENSEE and provide these users the results of the PROGRAM provided LICENSEE does so for academic non-commercial purposes only. For clarification purposes, academic sponsored research is not a commercial use under the terms of this Agreement.
* 2.2 No Sublicensing or Additional Rights. LICENSEE shall not sublicense or distribute the PROGRAM, in whole or in part, without prior written permission from BROAD. LICENSEE shall ensure that all of its users agree to the terms of this Agreement. LICENSEE further agrees that it shall not put the PROGRAM on a network, server, or other similar technology that may be accessed by anyone other than the LICENSEE and its employees and users who have agreed to the terms of this agreement.
* 2.3 License Limitations. Nothing in this Agreement shall be construed to confer any rights upon LICENSEE by implication, estoppel, or otherwise to any computer software, trademark, intellectual property, or patent rights of BROAD, or of any other entity, except as expressly granted herein. LICENSEE agrees that the PROGRAM, in whole or part, shall not be used for any commercial purpose, including without limitation, as the basis of a commercial software or hardware product or to provide services. LICENSEE further agrees that the PROGRAM shall not be copied or otherwise adapted in order to circumvent the need for obtaining a license for use of the PROGRAM.
*
* 3. OWNERSHIP OF INTELLECTUAL PROPERTY
* LICENSEE acknowledges that title to the PROGRAM shall remain with BROAD. The PROGRAM is marked with the following BROAD copyright notice and notice of attribution to contributors. LICENSEE shall retain such notice on all copies. LICENSEE agrees to include appropriate attribution if any results obtained from use of the PROGRAM are included in any publication.
* Copyright 2012 Broad Institute, Inc.
* Notice of attribution: The GATK2 program was made available through the generosity of Medical and Population Genetics program at the Broad Institute, Inc.
* LICENSEE shall not use any trademark or trade name of BROAD, or any variation, adaptation, or abbreviation, of such marks or trade names, or any names of officers, faculty, students, employees, or agents of BROAD except as states above for attribution purposes.
*
* 4. INDEMNIFICATION
* LICENSEE shall indemnify, defend, and hold harmless BROAD, and their respective officers, faculty, students, employees, associated investigators and agents, and their respective successors, heirs and assigns, (Indemnitees), against any liability, damage, loss, or expense (including reasonable attorneys fees and expenses) incurred by or imposed upon any of the Indemnitees in connection with any claims, suits, actions, demands or judgments arising out of any theory of liability (including, without limitation, actions in the form of tort, warranty, or strict liability and regardless of whether such action has any factual basis) pursuant to any right or license granted under this Agreement.
*
* 5. NO REPRESENTATIONS OR WARRANTIES
* THE PROGRAM IS DELIVERED AS IS. BROAD MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE PROGRAM OR THE COPYRIGHT, EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, WHETHER OR NOT DISCOVERABLE. BROAD EXTENDS NO WARRANTIES OF ANY KIND AS TO PROGRAM CONFORMITY WITH WHATEVER USER MANUALS OR OTHER LITERATURE MAY BE ISSUED FROM TIME TO TIME.
* IN NO EVENT SHALL BROAD OR ITS RESPECTIVE DIRECTORS, OFFICERS, EMPLOYEES, AFFILIATED INVESTIGATORS AND AFFILIATES BE LIABLE FOR INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, INCLUDING, WITHOUT LIMITATION, ECONOMIC DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER BROAD SHALL BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT SHALL KNOW OF THE POSSIBILITY OF THE FOREGOING.
*
* 6. ASSIGNMENT
* This Agreement is personal to LICENSEE and any rights or obligations assigned by LICENSEE without the prior written consent of BROAD shall be null and void.
*
* 7. MISCELLANEOUS
* 7.1 Export Control. LICENSEE gives assurance that it will comply with all United States export control laws and regulations controlling the export of the PROGRAM, including, without limitation, all Export Administration Regulations of the United States Department of Commerce. Among other things, these laws and regulations prohibit, or require a license for, the export of certain types of software to specified countries.
* 7.2 Termination. LICENSEE shall have the right to terminate this Agreement for any reason upon prior written notice to BROAD. If LICENSEE breaches any provision hereunder, and fails to cure such breach within thirty (30) days, BROAD may terminate this Agreement immediately. Upon termination, LICENSEE shall provide BROAD with written assurance that the original and all copies of the PROGRAM have been destroyed, except that, upon prior written authorization from BROAD, LICENSEE may retain a copy for archive purposes.
* 7.3 Survival. The following provisions shall survive the expiration or termination of this Agreement: Articles 1, 3, 4, 5 and Sections 2.2, 2.3, 7.3, and 7.4.
* 7.4 Notice. Any notices under this Agreement shall be in writing, shall specifically refer to this Agreement, and shall be sent by hand, recognized national overnight courier, confirmed facsimile transmission, confirmed electronic mail, or registered or certified mail, postage prepaid, return receipt requested. All notices under this Agreement shall be deemed effective upon receipt.
* 7.5 Amendment and Waiver; Entire Agreement. This Agreement may be amended, supplemented, or otherwise modified only by means of a written instrument signed by all parties. Any waiver of any rights or failure to act in a specific instance shall relate only to such instance and shall not be construed as an agreement to waive any rights or fail to act in any other instance, whether or not similar. This Agreement constitutes the entire agreement among the parties with respect to its subject matter and supersedes prior agreements or understandings between the parties relating to its subject matter.
* 7.6 Binding Effect; Headings. This Agreement shall be binding upon and inure to the benefit of the parties and their respective permitted successors and assigns. All headings are for convenience only and shall not affect the meaning of any provision of this Agreement.
* 7.7 Governing Law. This Agreement shall be construed, governed, interpreted and applied in accordance with the internal laws of the Commonwealth of Massachusetts, U.S.A., without regard to conflict of laws principles.
*/
package org.broadinstitute.sting.gatk.walkers.haplotypecaller;
import java.util.Arrays;
/**
* Fast wrapper for byte[] kmers
*
* This objects has several important features that make it better than using a raw byte[] for a kmer:
*
* -- Can create kmer from a range of a larger byte[], allowing us to avoid Array.copyOfRange
* -- Fast equals and hashcode methods
* -- can get actual byte[] of the kmer, even if it's from a larger byte[], and this operation
* only does the work of that operation once, updating its internal state
*
* User: depristo
* Date: 4/8/13
* Time: 7:54 AM
*/
public class Kmer {
// this values may be updated in the course of interacting with this kmer
private byte[] bases;
protected int start;
// two constants
final protected int length;
final protected int hash;
/**
* Create a new kmer using all bases in kmer
* @param kmer a non-null byte[]
*/
public Kmer(byte[] kmer) {
this(kmer, 0, kmer.length);
}
/**
* Create a new kmer based on the string kmer
*
* This is not a good method to use for performance
*
* @param kmer the bases as a string
*/
public Kmer(final String kmer) {
this(kmer.getBytes());
}
/**
* Create a new kmer backed by the bases in bases, spanning start -> start + length
*
* Under no circumstances can bases be modified anywhere in the client code. This does not make a copy
* of bases for performance reasons
*
* @param bases an array of bases
* @param start the start of the kmer in bases, must be >= 0 and < bases.length
* @param length the length of the kmer. Must be >= 0 and start + length < bases.length
*/
public Kmer(final byte[] bases, final int start, final int length) {
if ( bases == null ) throw new IllegalArgumentException("bases cannot be null");
if ( start < 0 ) throw new IllegalArgumentException("start must be >= 0 but got " + start);
if ( length < 0 ) throw new IllegalArgumentException("length must be >= 0 but got " + length);
if ( (start + length) > bases.length ) throw new IllegalArgumentException("start + length " + (start + length) + " must be <= bases.length " + bases.length + " but got " + start + " with length " + length);
this.bases = bases;
this.start = start;
this.length = length;
this.hash = myHashCode(bases, start, length);
}
/**
* Create a new kmer that's a shallow copy of kmer
* @param kmer the kmer to shallow copy
*/
public Kmer(final Kmer kmer) {
this.bases = kmer.bases;
this.start = kmer.start;
this.length = kmer.length;
this.hash = kmer.hash;
}
/**
* Create a derived shallow kmer that starts at newStart and has newLength bases
* @param newStart the new start of kmer, where 0 means that start of the kmer, 1 means skip the first base
* @param newLength the new length
* @return a new kmer based on the data in this kmer. Does not make a copy, so shares most of the data
*/
public Kmer subKmer(final int newStart, final int newLength) {
return new Kmer(bases, start + newStart, newLength);
}
/**
* Get the bases of this kmer. May create a copy of the bases, depending on how this kmer was constructed.
*
* Note that this function is efficient in that if it needs to copy the bases this only occurs once.
*
* @return a non-null byte[] containing length() bases of this kmer, regardless of how this kmer was created
*/
public byte[] bases() {
if ( start != 0 || bases.length != length ) {
// update operation. Rip out the exact byte[] and update start so we don't ever do this again
bases = Arrays.copyOfRange(bases, start, start + length);
start = 0;
}
return bases;
}
/**
* The length of this kmer
* @return an integer >= 0
*/
public int length() {
return length;
}
@Override
public String toString() {
return "Kmer{" + new String(bases()) + "}";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final Kmer kmer = (Kmer) o;
// very fast test. If hash aren't equal you are done, otherwise compare the bases
if ( hash != kmer.hash ) return false;
if ( length != kmer.length ) return false;
for ( int i = 0; i < length; i++ )
if ( bases[start + i] != kmer.bases[kmer.start + i] )
return false;
return true;
}
@Override
public int hashCode() {
return hash;
}
/**
* Helper method that computes the hashcode for this kmer based only the bases in
* a[], starting at start and running length bases
*
* @param a a non-null bases array
* @param start where to start in bases
* @param length the length of the bases
* @return a hashcode value appropriate for a[start] -> a[start + length]
*/
private static int myHashCode(final byte a[], final int start, final int length) {
if (a == null)
return 0;
int result = 1;
for (int i = 0; i < length; i++)
result = 31 * result + a[start + i];
return result;
}
}

View File

@ -107,25 +107,6 @@ public final class DeBruijnGraph extends BaseGraph<DeBruijnVertex> {
addOrUpdateEdge(v1, v2, toAdd);
}
/**
* Higher-level interface to #addKmersToGraph that adds a pair of kmers from a larger sequence of bytes to this
* graph. The kmers start at start (first) and start + 1 (second) have have length getKmerSize(). The
* edge between them is added with isRef and multiplicity
*
* @param sequence a sequence of bases from which we want to extract a pair of kmers
* @param start the start of the first kmer in sequence, must be between 0 and sequence.length - 2 - getKmerSize()
* @param isRef should the edge between the two kmers be a reference edge?
* @param multiplicity what's the multiplicity of the edge between these two kmers
*/
public void addKmerPairFromSeqToGraph( final byte[] sequence, final int start, final boolean isRef, final int multiplicity ) {
if ( sequence == null ) throw new IllegalArgumentException("Sequence cannot be null");
if ( start < 0 ) throw new IllegalArgumentException("start must be >= 0 but got " + start);
if ( start + 1 + getKmerSize() > sequence.length ) throw new IllegalArgumentException("start " + start + " is too big given kmerSize " + getKmerSize() + " and sequence length " + sequence.length);
final byte[] kmer1 = Arrays.copyOfRange(sequence, start, start + getKmerSize());
final byte[] kmer2 = Arrays.copyOfRange(sequence, start + 1, start + 1 + getKmerSize());
addKmersToGraph(kmer1, kmer2, isRef, multiplicity);
}
/**
* Convert this kmer graph to a simple sequence graph.
*

View File

@ -0,0 +1,84 @@
/*
* By downloading the PROGRAM you agree to the following terms of use:
*
* BROAD INSTITUTE - SOFTWARE LICENSE AGREEMENT - FOR ACADEMIC NON-COMMERCIAL RESEARCH PURPOSES ONLY
*
* This Agreement is made between the Broad Institute, Inc. with a principal address at 7 Cambridge Center, Cambridge, MA 02142 (BROAD) and the LICENSEE and is effective at the date the downloading is completed (EFFECTIVE DATE).
*
* WHEREAS, LICENSEE desires to license the PROGRAM, as defined hereinafter, and BROAD wishes to have this PROGRAM utilized in the public interest, subject only to the royalty-free, nonexclusive, nontransferable license rights of the United States Government pursuant to 48 CFR 52.227-14; and
* WHEREAS, LICENSEE desires to license the PROGRAM and BROAD desires to grant a license on the following terms and conditions.
* NOW, THEREFORE, in consideration of the promises and covenants made herein, the parties hereto agree as follows:
*
* 1. DEFINITIONS
* 1.1 PROGRAM shall mean copyright in the object code and source code known as GATK2 and related documentation, if any, as they exist on the EFFECTIVE DATE and can be downloaded from http://www.broadinstitute/GATK on the EFFECTIVE DATE.
*
* 2. LICENSE
* 2.1 Grant. Subject to the terms of this Agreement, BROAD hereby grants to LICENSEE, solely for academic non-commercial research purposes, a non-exclusive, non-transferable license to: (a) download, execute and display the PROGRAM and (b) create bug fixes and modify the PROGRAM.
* The LICENSEE may apply the PROGRAM in a pipeline to data owned by users other than the LICENSEE and provide these users the results of the PROGRAM provided LICENSEE does so for academic non-commercial purposes only. For clarification purposes, academic sponsored research is not a commercial use under the terms of this Agreement.
* 2.2 No Sublicensing or Additional Rights. LICENSEE shall not sublicense or distribute the PROGRAM, in whole or in part, without prior written permission from BROAD. LICENSEE shall ensure that all of its users agree to the terms of this Agreement. LICENSEE further agrees that it shall not put the PROGRAM on a network, server, or other similar technology that may be accessed by anyone other than the LICENSEE and its employees and users who have agreed to the terms of this agreement.
* 2.3 License Limitations. Nothing in this Agreement shall be construed to confer any rights upon LICENSEE by implication, estoppel, or otherwise to any computer software, trademark, intellectual property, or patent rights of BROAD, or of any other entity, except as expressly granted herein. LICENSEE agrees that the PROGRAM, in whole or part, shall not be used for any commercial purpose, including without limitation, as the basis of a commercial software or hardware product or to provide services. LICENSEE further agrees that the PROGRAM shall not be copied or otherwise adapted in order to circumvent the need for obtaining a license for use of the PROGRAM.
*
* 3. OWNERSHIP OF INTELLECTUAL PROPERTY
* LICENSEE acknowledges that title to the PROGRAM shall remain with BROAD. The PROGRAM is marked with the following BROAD copyright notice and notice of attribution to contributors. LICENSEE shall retain such notice on all copies. LICENSEE agrees to include appropriate attribution if any results obtained from use of the PROGRAM are included in any publication.
* Copyright 2012 Broad Institute, Inc.
* Notice of attribution: The GATK2 program was made available through the generosity of Medical and Population Genetics program at the Broad Institute, Inc.
* LICENSEE shall not use any trademark or trade name of BROAD, or any variation, adaptation, or abbreviation, of such marks or trade names, or any names of officers, faculty, students, employees, or agents of BROAD except as states above for attribution purposes.
*
* 4. INDEMNIFICATION
* LICENSEE shall indemnify, defend, and hold harmless BROAD, and their respective officers, faculty, students, employees, associated investigators and agents, and their respective successors, heirs and assigns, (Indemnitees), against any liability, damage, loss, or expense (including reasonable attorneys fees and expenses) incurred by or imposed upon any of the Indemnitees in connection with any claims, suits, actions, demands or judgments arising out of any theory of liability (including, without limitation, actions in the form of tort, warranty, or strict liability and regardless of whether such action has any factual basis) pursuant to any right or license granted under this Agreement.
*
* 5. NO REPRESENTATIONS OR WARRANTIES
* THE PROGRAM IS DELIVERED AS IS. BROAD MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE PROGRAM OR THE COPYRIGHT, EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, WHETHER OR NOT DISCOVERABLE. BROAD EXTENDS NO WARRANTIES OF ANY KIND AS TO PROGRAM CONFORMITY WITH WHATEVER USER MANUALS OR OTHER LITERATURE MAY BE ISSUED FROM TIME TO TIME.
* IN NO EVENT SHALL BROAD OR ITS RESPECTIVE DIRECTORS, OFFICERS, EMPLOYEES, AFFILIATED INVESTIGATORS AND AFFILIATES BE LIABLE FOR INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, INCLUDING, WITHOUT LIMITATION, ECONOMIC DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER BROAD SHALL BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT SHALL KNOW OF THE POSSIBILITY OF THE FOREGOING.
*
* 6. ASSIGNMENT
* This Agreement is personal to LICENSEE and any rights or obligations assigned by LICENSEE without the prior written consent of BROAD shall be null and void.
*
* 7. MISCELLANEOUS
* 7.1 Export Control. LICENSEE gives assurance that it will comply with all United States export control laws and regulations controlling the export of the PROGRAM, including, without limitation, all Export Administration Regulations of the United States Department of Commerce. Among other things, these laws and regulations prohibit, or require a license for, the export of certain types of software to specified countries.
* 7.2 Termination. LICENSEE shall have the right to terminate this Agreement for any reason upon prior written notice to BROAD. If LICENSEE breaches any provision hereunder, and fails to cure such breach within thirty (30) days, BROAD may terminate this Agreement immediately. Upon termination, LICENSEE shall provide BROAD with written assurance that the original and all copies of the PROGRAM have been destroyed, except that, upon prior written authorization from BROAD, LICENSEE may retain a copy for archive purposes.
* 7.3 Survival. The following provisions shall survive the expiration or termination of this Agreement: Articles 1, 3, 4, 5 and Sections 2.2, 2.3, 7.3, and 7.4.
* 7.4 Notice. Any notices under this Agreement shall be in writing, shall specifically refer to this Agreement, and shall be sent by hand, recognized national overnight courier, confirmed facsimile transmission, confirmed electronic mail, or registered or certified mail, postage prepaid, return receipt requested. All notices under this Agreement shall be deemed effective upon receipt.
* 7.5 Amendment and Waiver; Entire Agreement. This Agreement may be amended, supplemented, or otherwise modified only by means of a written instrument signed by all parties. Any waiver of any rights or failure to act in a specific instance shall relate only to such instance and shall not be construed as an agreement to waive any rights or fail to act in any other instance, whether or not similar. This Agreement constitutes the entire agreement among the parties with respect to its subject matter and supersedes prior agreements or understandings between the parties relating to its subject matter.
* 7.6 Binding Effect; Headings. This Agreement shall be binding upon and inure to the benefit of the parties and their respective permitted successors and assigns. All headings are for convenience only and shall not affect the meaning of any provision of this Agreement.
* 7.7 Governing Law. This Agreement shall be construed, governed, interpreted and applied in accordance with the internal laws of the Commonwealth of Massachusetts, U.S.A., without regard to conflict of laws principles.
*/
package org.broadinstitute.sting.gatk.walkers.haplotypecaller;
import org.broadinstitute.sting.BaseTest;
import org.testng.Assert;
import org.testng.annotations.Test;
public class KmerCounterUnitTest extends BaseTest {
@Test
public void testMyData() {
final KmerCounter counter = new KmerCounter(3);
Assert.assertNotNull(counter.toString());
counter.addKmers(
"ATG", "ATG", "ATG", "ATG",
"ACC", "ACC", "ACC",
"AAA", "AAA",
"CTG",
"NNA",
"CCC"
);
testCounting(counter, "ATG", 4);
testCounting(counter, "ACC", 3);
testCounting(counter, "AAA", 2);
testCounting(counter, "CTG", 1);
testCounting(counter, "NNA", 1);
testCounting(counter, "CCC", 1);
testCounting(counter, "NNN", 0);
testCounting(counter, "NNC", 0);
Assert.assertNotNull(counter.toString());
}
private void testCounting(final KmerCounter counter, final String in, final int expectedCount) {
Assert.assertEquals(counter.getKmerCount(new Kmer(in)), expectedCount);
}
}

View File

@ -0,0 +1,133 @@
/*
* By downloading the PROGRAM you agree to the following terms of use:
*
* BROAD INSTITUTE - SOFTWARE LICENSE AGREEMENT - FOR ACADEMIC NON-COMMERCIAL RESEARCH PURPOSES ONLY
*
* This Agreement is made between the Broad Institute, Inc. with a principal address at 7 Cambridge Center, Cambridge, MA 02142 (BROAD) and the LICENSEE and is effective at the date the downloading is completed (EFFECTIVE DATE).
*
* WHEREAS, LICENSEE desires to license the PROGRAM, as defined hereinafter, and BROAD wishes to have this PROGRAM utilized in the public interest, subject only to the royalty-free, nonexclusive, nontransferable license rights of the United States Government pursuant to 48 CFR 52.227-14; and
* WHEREAS, LICENSEE desires to license the PROGRAM and BROAD desires to grant a license on the following terms and conditions.
* NOW, THEREFORE, in consideration of the promises and covenants made herein, the parties hereto agree as follows:
*
* 1. DEFINITIONS
* 1.1 PROGRAM shall mean copyright in the object code and source code known as GATK2 and related documentation, if any, as they exist on the EFFECTIVE DATE and can be downloaded from http://www.broadinstitute/GATK on the EFFECTIVE DATE.
*
* 2. LICENSE
* 2.1 Grant. Subject to the terms of this Agreement, BROAD hereby grants to LICENSEE, solely for academic non-commercial research purposes, a non-exclusive, non-transferable license to: (a) download, execute and display the PROGRAM and (b) create bug fixes and modify the PROGRAM.
* The LICENSEE may apply the PROGRAM in a pipeline to data owned by users other than the LICENSEE and provide these users the results of the PROGRAM provided LICENSEE does so for academic non-commercial purposes only. For clarification purposes, academic sponsored research is not a commercial use under the terms of this Agreement.
* 2.2 No Sublicensing or Additional Rights. LICENSEE shall not sublicense or distribute the PROGRAM, in whole or in part, without prior written permission from BROAD. LICENSEE shall ensure that all of its users agree to the terms of this Agreement. LICENSEE further agrees that it shall not put the PROGRAM on a network, server, or other similar technology that may be accessed by anyone other than the LICENSEE and its employees and users who have agreed to the terms of this agreement.
* 2.3 License Limitations. Nothing in this Agreement shall be construed to confer any rights upon LICENSEE by implication, estoppel, or otherwise to any computer software, trademark, intellectual property, or patent rights of BROAD, or of any other entity, except as expressly granted herein. LICENSEE agrees that the PROGRAM, in whole or part, shall not be used for any commercial purpose, including without limitation, as the basis of a commercial software or hardware product or to provide services. LICENSEE further agrees that the PROGRAM shall not be copied or otherwise adapted in order to circumvent the need for obtaining a license for use of the PROGRAM.
*
* 3. OWNERSHIP OF INTELLECTUAL PROPERTY
* LICENSEE acknowledges that title to the PROGRAM shall remain with BROAD. The PROGRAM is marked with the following BROAD copyright notice and notice of attribution to contributors. LICENSEE shall retain such notice on all copies. LICENSEE agrees to include appropriate attribution if any results obtained from use of the PROGRAM are included in any publication.
* Copyright 2012 Broad Institute, Inc.
* Notice of attribution: The GATK2 program was made available through the generosity of Medical and Population Genetics program at the Broad Institute, Inc.
* LICENSEE shall not use any trademark or trade name of BROAD, or any variation, adaptation, or abbreviation, of such marks or trade names, or any names of officers, faculty, students, employees, or agents of BROAD except as states above for attribution purposes.
*
* 4. INDEMNIFICATION
* LICENSEE shall indemnify, defend, and hold harmless BROAD, and their respective officers, faculty, students, employees, associated investigators and agents, and their respective successors, heirs and assigns, (Indemnitees), against any liability, damage, loss, or expense (including reasonable attorneys fees and expenses) incurred by or imposed upon any of the Indemnitees in connection with any claims, suits, actions, demands or judgments arising out of any theory of liability (including, without limitation, actions in the form of tort, warranty, or strict liability and regardless of whether such action has any factual basis) pursuant to any right or license granted under this Agreement.
*
* 5. NO REPRESENTATIONS OR WARRANTIES
* THE PROGRAM IS DELIVERED AS IS. BROAD MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE PROGRAM OR THE COPYRIGHT, EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, WHETHER OR NOT DISCOVERABLE. BROAD EXTENDS NO WARRANTIES OF ANY KIND AS TO PROGRAM CONFORMITY WITH WHATEVER USER MANUALS OR OTHER LITERATURE MAY BE ISSUED FROM TIME TO TIME.
* IN NO EVENT SHALL BROAD OR ITS RESPECTIVE DIRECTORS, OFFICERS, EMPLOYEES, AFFILIATED INVESTIGATORS AND AFFILIATES BE LIABLE FOR INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, INCLUDING, WITHOUT LIMITATION, ECONOMIC DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER BROAD SHALL BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT SHALL KNOW OF THE POSSIBILITY OF THE FOREGOING.
*
* 6. ASSIGNMENT
* This Agreement is personal to LICENSEE and any rights or obligations assigned by LICENSEE without the prior written consent of BROAD shall be null and void.
*
* 7. MISCELLANEOUS
* 7.1 Export Control. LICENSEE gives assurance that it will comply with all United States export control laws and regulations controlling the export of the PROGRAM, including, without limitation, all Export Administration Regulations of the United States Department of Commerce. Among other things, these laws and regulations prohibit, or require a license for, the export of certain types of software to specified countries.
* 7.2 Termination. LICENSEE shall have the right to terminate this Agreement for any reason upon prior written notice to BROAD. If LICENSEE breaches any provision hereunder, and fails to cure such breach within thirty (30) days, BROAD may terminate this Agreement immediately. Upon termination, LICENSEE shall provide BROAD with written assurance that the original and all copies of the PROGRAM have been destroyed, except that, upon prior written authorization from BROAD, LICENSEE may retain a copy for archive purposes.
* 7.3 Survival. The following provisions shall survive the expiration or termination of this Agreement: Articles 1, 3, 4, 5 and Sections 2.2, 2.3, 7.3, and 7.4.
* 7.4 Notice. Any notices under this Agreement shall be in writing, shall specifically refer to this Agreement, and shall be sent by hand, recognized national overnight courier, confirmed facsimile transmission, confirmed electronic mail, or registered or certified mail, postage prepaid, return receipt requested. All notices under this Agreement shall be deemed effective upon receipt.
* 7.5 Amendment and Waiver; Entire Agreement. This Agreement may be amended, supplemented, or otherwise modified only by means of a written instrument signed by all parties. Any waiver of any rights or failure to act in a specific instance shall relate only to such instance and shall not be construed as an agreement to waive any rights or fail to act in any other instance, whether or not similar. This Agreement constitutes the entire agreement among the parties with respect to its subject matter and supersedes prior agreements or understandings between the parties relating to its subject matter.
* 7.6 Binding Effect; Headings. This Agreement shall be binding upon and inure to the benefit of the parties and their respective permitted successors and assigns. All headings are for convenience only and shall not affect the meaning of any provision of this Agreement.
* 7.7 Governing Law. This Agreement shall be construed, governed, interpreted and applied in accordance with the internal laws of the Commonwealth of Massachusetts, U.S.A., without regard to conflict of laws principles.
*/
package org.broadinstitute.sting.gatk.walkers.haplotypecaller;
import org.broadinstitute.sting.BaseTest;
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 KmerUnitTest extends BaseTest {
@DataProvider(name = "KMerCreationData")
public Object[][] makeKMerCreationData() {
List<Object[]> tests = new ArrayList<Object[]>();
final String bases = "ACGTAACCGGTTAAACCCGGGTTT";
for ( int start = 0; start < bases.length(); start++ ) {
for ( int length = 1; start + length < bases.length(); length++ ) {
final String myBases = bases.substring(start, start+length);
tests.add(new Object[]{bases.getBytes(), start, length, myBases});
}
}
return tests.toArray(new Object[][]{});
}
@Test(dataProvider = "KMerCreationData")
public void testFullConstructor(final byte[] allBases, final int start, final int length, final String expected) {
testKmerCreation(new Kmer(allBases, start, length), start, length, expected);
}
@Test(dataProvider = "KMerCreationData")
public void testCopyConstructor(final byte[] allBases, final int start, final int length, final String expected) {
testKmerCreation(new Kmer(new Kmer(allBases, start, length)), start, length, expected);
}
@Test(dataProvider = "KMerCreationData")
public void testByteConstructor(final byte[] allBases, final int start, final int length, final String expected) {
testKmerCreation(new Kmer(Arrays.copyOfRange(allBases, start, start + length)), 0, length, expected);
}
@Test(dataProvider = "KMerCreationData")
public void testStringConstructor(final byte[] allBases, final int start, final int length, final String expected) {
testKmerCreation(new Kmer(new String(Arrays.copyOfRange(allBases, start, start + length))), 0, length, expected);
}
private void testKmerCreation(final Kmer kmer, final int start, final int length, final String expected) {
Assert.assertEquals(kmer.start, start);
Assert.assertEquals(kmer.length(), length);
Assert.assertEquals(new String(kmer.bases()), expected);
// check that the caching is working by calling again
Assert.assertEquals(kmer.start, 0);
Assert.assertEquals(kmer.length(), length);
Assert.assertEquals(new String(kmer.bases()), expected);
}
@Test
public void testEquals() {
final byte[] bases = "ACGTACGT".getBytes();
final Kmer eq1 = new Kmer(bases, 0, 3);
final Kmer eq2 = new Kmer(bases, 4, 3);
final Kmer eq3 = new Kmer(new Kmer(bases, 4, 3));
final Kmer eq4 = new Kmer(new Kmer(bases, 4, 3).bases());
final Kmer neq = new Kmer(bases, 1, 3);
// for ( final Kmer eq : Arrays.asList(eq1, eq2) ) { // TODO -- deal with me
for ( final Kmer eq : Arrays.asList(eq1, eq2, eq3, eq4) ) {
Assert.assertEquals(eq1, eq, "Should have been equal but wasn't: " + eq1.hash + " vs " + eq.hash); // , "should be equals " + eq1 + " with " + eq);
Assert.assertEquals(eq1.hashCode(), eq.hashCode());
Assert.assertNotEquals(eq, neq, "incorrectly equals " + eq + " with " + neq);
}
}
@Test
public void testSubkmer() {
final String bases = "ACGT";
final Kmer one = new Kmer(bases.getBytes());
for ( int start = 0; start < bases.length(); start++ ) {
for ( int length = 0; start + length < bases.length(); length++ ) {
Assert.assertEquals(new String(one.subKmer(start,length).bases()), bases.substring(start, start+length));
}
}
}
}