diff --git a/protected/java/src/org/broadinstitute/sting/gatk/walkers/haplotypecaller/BaseGraph.java b/protected/java/src/org/broadinstitute/sting/gatk/walkers/haplotypecaller/BaseGraph.java index c3f371ec7..80e5148db 100644 --- a/protected/java/src/org/broadinstitute/sting/gatk/walkers/haplotypecaller/BaseGraph.java +++ b/protected/java/src/org/broadinstitute/sting/gatk/walkers/haplotypecaller/BaseGraph.java @@ -336,9 +336,18 @@ public class BaseGraph extends DefaultDirectedGraph extends DefaultDirectedGraph PRUNE_FACTOR ) { graphWriter.println("\t" + getEdgeSource(edge).toString() + " -> " + getEdgeTarget(edge).toString() + " [" + (edge.getMultiplicity() <= pruneFactor ? "style=dotted,color=grey," : "") + "label=\"" + edge.getMultiplicity() + "\"];"); -// } if( edge.isRef() ) { graphWriter.println("\t" + getEdgeSource(edge).toString() + " -> " + getEdgeTarget(edge).toString() + " [color=red];"); } - //if( !edge.isRef() && edge.getMultiplicity() <= PRUNE_FACTOR ) { System.out.println("Graph pruning warning!"); } } for( final T v : vertexSet() ) { @@ -436,6 +441,30 @@ public class BaseGraph extends DefaultDirectedGraph edgesToRemove = new ArrayList(); + for( final BaseEdge e : edgeSet() ) { + if( e.getMultiplicity() <= pruneFactor && !e.isRef() ) { // remove non-reference edges with weight less than or equal to the pruning factor + edgesToRemove.add(e); + } + } + removeAllEdges(edgesToRemove); + + removeSingletonOrphanVertices(); + } + + /** + * Remove all vertices in the graph that have in and out degree of 0 + */ + protected void removeSingletonOrphanVertices() { // Run through the graph and clean up singular orphaned nodes final List verticesToRemove = new LinkedList(); for( final T v : vertexSet() ) { @@ -446,65 +475,54 @@ public class BaseGraph extends DefaultDirectedGraph toRemove = new HashSet(vertexSet()); + + final T refV = getReferenceSourceVertex(); + if ( refV != null ) { + for ( final T v : new BaseGraphIterator(this, refV, true, true) ) { + toRemove.remove(v); + } + } + + removeAllVertices(toRemove); + } + + /** + * Remove all vertices in the graph that aren't on a path from the reference source vertex to the reference sink vertex + * + * More aggressive reference pruning algorithm than removeVerticesNotConnectedToRefRegardlessOfEdgeDirection, + * as it requires vertices to not only be connected by a series of directed edges but also prunes away + * paths that do not also meet eventually with the reference sink vertex + */ protected void removePathsNotConnectedToRef() { if ( getReferenceSourceVertex() == null || getReferenceSinkVertex() == null ) { throw new IllegalStateException("Graph must have ref source and sink vertices"); } + // get the set of vertices we can reach by going forward from the ref source + final Set onPathFromRefSource = new HashSet(vertexSet().size()); + for ( final T v : new BaseGraphIterator(this, getReferenceSourceVertex(), false, true) ) { + onPathFromRefSource.add(v); + } + + // get the set of vertices we can reach by going backward from the ref sink + final Set onPathFromRefSink = new HashSet(vertexSet().size()); + for ( final T v : new BaseGraphIterator(this, getReferenceSinkVertex(), true, false) ) { + onPathFromRefSink.add(v); + } + + // we want to remove anything that's not in both the sink and source sets final Set verticesToRemove = new HashSet(vertexSet()); - final DepthFirstIterator dfi = new DepthFirstIterator(this, getReferenceSourceVertex()); - while ( dfi.hasNext() ) { - final T accessibleFromRefSource = dfi.next(); - // we also want to prune all sinks that aren't the reference sink - if ( ! isNonRefSink(accessibleFromRefSource) ) - verticesToRemove.remove(accessibleFromRefSource); - } - + onPathFromRefSource.retainAll(onPathFromRefSink); + verticesToRemove.removeAll(onPathFromRefSource); removeAllVertices(verticesToRemove); } - protected void pruneGraph( final int pruneFactor ) { - final List edgesToRemove = new ArrayList(); - for( final BaseEdge e : edgeSet() ) { - if( e.getMultiplicity() <= pruneFactor && !e.isRef() ) { // remove non-reference edges with weight less than or equal to the pruning factor - edgesToRemove.add(e); - } - } - removeAllEdges(edgesToRemove); - - // Run through the graph and clean up singular orphaned nodes - final List verticesToRemove = new ArrayList(); - for( final T v : vertexSet() ) { - if( inDegreeOf(v) == 0 && outDegreeOf(v) == 0 ) { - verticesToRemove.add(v); - } - } - - removeAllVertices(verticesToRemove); - } - - public void removeVerticesNotConnectedToRef() { - final HashSet toRemove = new HashSet(vertexSet()); - final HashSet visited = new HashSet(); - - final LinkedList toVisit = new LinkedList(); - final T refV = getReferenceSourceVertex(); - if ( refV != null ) { - toVisit.add(refV); - while ( ! toVisit.isEmpty() ) { - final T v = toVisit.pop(); - if ( ! visited.contains(v) ) { - toRemove.remove(v); - visited.add(v); - for ( final T prev : incomingVerticesOf(v) ) toVisit.add(prev); - for ( final T next : outgoingVerticesOf(v) ) toVisit.add(next); - } - } - - removeAllVertices(toRemove); - } - } - /** * Semi-lenient comparison of two graphs, truing true if g1 and g2 have similar structure * diff --git a/protected/java/src/org/broadinstitute/sting/gatk/walkers/haplotypecaller/BaseGraphIterator.java b/protected/java/src/org/broadinstitute/sting/gatk/walkers/haplotypecaller/BaseGraphIterator.java new file mode 100644 index 000000000..8841f835c --- /dev/null +++ b/protected/java/src/org/broadinstitute/sting/gatk/walkers/haplotypecaller/BaseGraphIterator.java @@ -0,0 +1,120 @@ +/* +* 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.HashSet; +import java.util.Iterator; +import java.util.LinkedList; + +/** + * General iterator that can iterate over all vertices in a BaseGraph, following either + * incoming, outgoing edge (as well as both or none) edges. Supports traversal of graphs + * with cycles and other crazy structures. Will only ever visit each vertex once. The + * order in which the vertices are visited is undefined. + * + * User: depristo + * Date: 3/24/13 + * Time: 4:41 PM + */ +public class BaseGraphIterator implements Iterator, Iterable { + final HashSet visited = new HashSet(); + final LinkedList toVisit = new LinkedList(); + final BaseGraph graph; + final boolean followIncomingEdges, followOutgoingEdges; + + /** + * Create a new BaseGraphIterator starting its traversal at start + * + * Note that if both followIncomingEdges and followOutgoingEdges are false, we simply return the + * start vertex + * + * @param graph the graph to iterator over. Cannot be null + * @param start the vertex to start at. Cannot be null + * @param followIncomingEdges should we follow incoming edges during our + * traversal? (goes backward through the graph) + * @param followOutgoingEdges should we follow outgoing edges during out traversal? + */ + public BaseGraphIterator(final BaseGraph graph, final T start, + final boolean followIncomingEdges, final boolean followOutgoingEdges) { + if ( graph == null ) throw new IllegalArgumentException("graph cannot be null"); + if ( start == null ) throw new IllegalArgumentException("start cannot be null"); + if ( ! graph.containsVertex(start) ) throw new IllegalArgumentException("start " + start + " must be in graph but it isn't"); + this.graph = graph; + this.followIncomingEdges = followIncomingEdges; + this.followOutgoingEdges = followOutgoingEdges; + + toVisit.add(start); + } + + @Override + public Iterator iterator() { + return this; + } + + @Override + public boolean hasNext() { + return ! toVisit.isEmpty(); + } + + @Override + public T next() { + final T v = toVisit.pop(); + + if ( ! visited.contains(v) ) { + visited.add(v); + if ( followIncomingEdges ) for ( final T prev : graph.incomingVerticesOf(v) ) toVisit.add(prev); + if ( followOutgoingEdges ) for ( final T next : graph.outgoingVerticesOf(v) ) toVisit.add(next); + } + + return v; + } + + @Override + public void remove() { + throw new UnsupportedOperationException("Doesn't implement remove"); + } +} diff --git a/protected/java/src/org/broadinstitute/sting/gatk/walkers/haplotypecaller/DeBruijnAssembler.java b/protected/java/src/org/broadinstitute/sting/gatk/walkers/haplotypecaller/DeBruijnAssembler.java index 9c6c255df..e9961519c 100644 --- a/protected/java/src/org/broadinstitute/sting/gatk/walkers/haplotypecaller/DeBruijnAssembler.java +++ b/protected/java/src/org/broadinstitute/sting/gatk/walkers/haplotypecaller/DeBruijnAssembler.java @@ -183,11 +183,18 @@ public class DeBruijnAssembler extends LocalAssemblyEngine { private SeqGraph toSeqGraph(final DeBruijnGraph deBruijnGraph) { final SeqGraph seqGraph = deBruijnGraph.convertToSequenceGraph(); if ( debugGraphTransformations ) seqGraph.printGraph(new File("sequenceGraph.1.dot"), pruneFactor); + + // the very first thing we need to do is zip up the graph, or pruneGraph will be too aggressive + seqGraph.zipLinearChains(); + if ( debugGraphTransformations ) seqGraph.printGraph(new File("sequenceGraph.2.zipped.dot"), pruneFactor); + + // now go through and prune the graph, removing vertices no longer connected to the reference chain seqGraph.pruneGraph(pruneFactor); - seqGraph.removeVerticesNotConnectedToRef(); - if ( debugGraphTransformations ) seqGraph.printGraph(new File("sequenceGraph.2.pruned.dot"), pruneFactor); + seqGraph.removeVerticesNotConnectedToRefRegardlessOfEdgeDirection(); + + if ( debugGraphTransformations ) seqGraph.printGraph(new File("sequenceGraph.3.pruned.dot"), pruneFactor); seqGraph.simplifyGraph(); - if ( debugGraphTransformations ) seqGraph.printGraph(new File("sequenceGraph.3.merged.dot"), pruneFactor); + if ( debugGraphTransformations ) seqGraph.printGraph(new File("sequenceGraph.4.merged.dot"), pruneFactor); // The graph has degenerated in some way, so the reference source and/or sink cannot be id'd. Can // happen in cases where for example the reference somehow manages to acquire a cycle, or @@ -196,7 +203,7 @@ public class DeBruijnAssembler extends LocalAssemblyEngine { return null; seqGraph.removePathsNotConnectedToRef(); - if ( debugGraphTransformations ) seqGraph.printGraph(new File("sequenceGraph.4.refcleaned.dot"), pruneFactor); + if ( debugGraphTransformations ) seqGraph.printGraph(new File("sequenceGraph.5.refcleaned.dot"), pruneFactor); return seqGraph; } diff --git a/protected/java/test/org/broadinstitute/sting/gatk/walkers/haplotypecaller/BaseGraphUnitTest.java b/protected/java/test/org/broadinstitute/sting/gatk/walkers/haplotypecaller/BaseGraphUnitTest.java index 463e861b1..db4127ddb 100644 --- a/protected/java/test/org/broadinstitute/sting/gatk/walkers/haplotypecaller/BaseGraphUnitTest.java +++ b/protected/java/test/org/broadinstitute/sting/gatk/walkers/haplotypecaller/BaseGraphUnitTest.java @@ -49,22 +49,12 @@ package org.broadinstitute.sting.gatk.walkers.haplotypecaller; import org.broadinstitute.sting.BaseTest; import org.testng.Assert; import org.testng.annotations.BeforeMethod; -import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import scala.actors.threadpool.Arrays; import java.io.File; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; +import java.util.*; -/** - * Created with IntelliJ IDEA. - * User: depristo - * Date: 3/15/13 - * Time: 3:36 PM - * To change this template use File | Settings | File Templates. - */ public class BaseGraphUnitTest extends BaseTest { SeqGraph graph; SeqVertex v1, v2, v3, v4, v5; @@ -105,6 +95,80 @@ public class BaseGraphUnitTest extends BaseTest { assertVertexSetEquals(graph.incomingVerticesOf(v5), v4); } + @Test + public void testRemoveSingletonOrphanVertices() throws Exception { + // all vertices in graph are connected + final List kept = new LinkedList(graph.vertexSet()); + final SeqVertex rm1 = new SeqVertex("CAGT"); + final SeqVertex rm2 = new SeqVertex("AGTC"); + graph.addVertices(rm1, rm2); + Assert.assertEquals(graph.vertexSet().size(), kept.size() + 2); + final BaseEdge rm12e = new BaseEdge(false, 1); + graph.addEdge(rm1, rm2, rm12e); + + final SeqGraph original = (SeqGraph)graph.clone(); + graph.removeSingletonOrphanVertices(); + Assert.assertTrue(BaseGraph.graphEquals(original, graph), "Graph with disconnected component but edges between components shouldn't be modified"); + + graph.removeEdge(rm12e); // now we should be able to remove rm1 and rm2 + graph.removeSingletonOrphanVertices(); + Assert.assertTrue(graph.vertexSet().containsAll(kept)); + Assert.assertFalse(graph.containsVertex(rm1)); + Assert.assertFalse(graph.containsVertex(rm2)); + } + + @Test + public void testRemovePathsNotConnectedToRef() throws Exception { + final SeqGraph graph = new SeqGraph(); + + SeqVertex src = new SeqVertex("A"); + SeqVertex end = new SeqVertex("A"); + SeqVertex g1 = new SeqVertex("C"); + SeqVertex g2 = new SeqVertex("G"); + SeqVertex g3 = new SeqVertex("T"); + SeqVertex g4 = new SeqVertex("AA"); + SeqVertex g5 = new SeqVertex("AA"); + SeqVertex g6 = new SeqVertex("AA"); + SeqVertex g8 = new SeqVertex("AA"); + SeqVertex g7 = new SeqVertex("AA"); + SeqVertex b1 = new SeqVertex("CC"); + SeqVertex b2 = new SeqVertex("GG"); + SeqVertex b3 = new SeqVertex("TT"); + SeqVertex b4 = new SeqVertex("AAA"); + SeqVertex b5 = new SeqVertex("CCC"); + SeqVertex b6 = new SeqVertex("GGG"); + SeqVertex b7 = new SeqVertex("AAAA"); + SeqVertex b8 = new SeqVertex("GGGG"); + SeqVertex b9 = new SeqVertex("CCCC"); + + graph.addVertices(src, end, g1, g2, g3, g4, g5, g6, g7, g8); + graph.addEdges(new BaseEdge(true, 1), src, g1, g2, g4, end); + graph.addEdges(src, g1, g5, g6, g7, end); + graph.addEdges(src, g1, g5, g8, g7, end); + graph.addEdges(src, g1, g3, end); + + // the current state of the graph is the good one + final SeqGraph good = (SeqGraph)graph.clone(); + + // now add the bads to the graph + graph.addVertices(b1, b2, b3, b4, b5, b6, b7, b8, b9); + graph.addEdges(src, b1); // source -> b1 is dead + graph.addEdges(b6, src); // x -> source is bad + graph.addEdges(g4, b2); // off random vertex is bad + graph.addEdges(g3, b3, b4); // two vertices that don't connect to end are bad + graph.addEdges(end, b5); // vertex off end is bad + graph.addEdges(g3, b7, b8, b7); // cycle is bad + graph.addEdges(g3, b9, b9); // self-cycle is bad + + final boolean debug = true; + if ( debug ) good.printGraph(new File("expected.dot"), 0); + if ( debug ) graph.printGraph(new File("bad.dot"), 0); + graph.removePathsNotConnectedToRef(); + if ( debug ) graph.printGraph(new File("actual.dot"), 0); + + Assert.assertTrue(BaseGraph.graphEquals(graph, good), "Failed to remove exactly the bad nodes"); + } + @Test public void testPrintEmptyGraph() throws Exception { final File tmp = File.createTempFile("tmp", "dot");