//private VertexIntDictionary components; ///// <summary> /// Initializes a new instance of the CompressNamespacesAlgorithm class. /// </summary> /// <param name="inputGraph"></param> public CompressNamespacesAlgorithm(IVertexListGraph inputGraph) { this.visitedGraph = inputGraph; dfs = new DepthFirstSearchAlgorithm(inputGraph); dfs.FinishVertex += new VertexEventHandler(dfs_FinishVertex); dfs.DiscoverVertex += new VertexEventHandler(dfs_DiscoverVertex); dfs.TreeEdge += new EdgeEventHandler(dfs_TreeEdge); }
/// <summary> /// Checks that the graph does not have cyclies /// </summary> /// <param name="g">graph to test</param> /// <exception cref="ArgumentNullException">g is a null reference</exception> /// <exception cref="NonAcyclicGraphException">graph contains a cycle</exception> public static void CheckAcyclic(IVertexListGraph g) { if (g==null) throw new ArgumentNullException("g"); DepthFirstSearchAlgorithm dfs = new DepthFirstSearchAlgorithm(g); dfs.BackEdge +=new EdgeEventHandler(dfs_BackEdge); dfs.Compute(); }
public void Should_throw_exception_when_traversing_cyclic_graph() { var found = new HashSet<int>(); var algorithm = new DepthFirstSearchAlgorithm<int, SEdge<int>>(_adjacencyGraph); algorithm.DiscoverVertex += v => found.Add(v); algorithm.ExamineEdge += e => { if (algorithm.GetVertexColor(e.Target) != GraphColor.White) throw new Exception("cycle!"); }; Assert.That(() => algorithm.Compute(10), Throws.Exception); }
private static List<Library> ComputeIndirectDeps(DependencyGraph graph, Library lib) { var indirectDeps = new List<Library>(); var dfs = new DepthFirstSearchAlgorithm<Library, Dependency>(graph); dfs.SetRootVertex(lib); dfs.DiscoverVertex += indirectDeps.Add; dfs.Compute(); return indirectDeps; }
public void Should_visit_all_vertices_reachable_from_one() { var found = new HashSet<int>(); var algorithm = new DepthFirstSearchAlgorithm<int, SEdge<int>>(_adjacencyGraph); algorithm.DiscoverVertex += v => found.Add(v); algorithm.ExamineEdge += e => { if (algorithm.GetVertexColor(e.Target) != GraphColor.White) throw new Exception("cycle!"); }; algorithm.Compute(1); Assert.That(found.OrderBy(i => i).ToArray(), Is.EquivalentTo(new[] {1, 2, 3, 4} )); }
public static IEnumerable<object> GetAssociated(object obj) { if (!_dependencies.ContainsVertex(obj)) return new[] {obj}; var dependencies = new List<object>(); var searchAlgorithm = new DepthFirstSearchAlgorithm<object, SEdge<object>>(_dependencies); searchAlgorithm.DiscoverVertex += dependencies.Add; searchAlgorithm.Compute(obj); return dependencies; }
public void Compute(IList vertices) { if (vertices != null) { this.m_Vertices = vertices; } DepthFirstSearchAlgorithm algorithm = new DepthFirstSearchAlgorithm(this.VisitedGraph); algorithm.BackEdge += new EdgeEventHandler(this, (IntPtr) this.BackEdge); algorithm.FinishVertex += new VertexEventHandler(this, (IntPtr) this.FinishVertex); this.m_Vertices.Clear(); algorithm.Compute(); }
public EdgeCollectionCollection GetAllEdgePaths() { if (this.graph.VerticesCount==0) return new EdgeCollectionCollection(); DepthFirstSearchAlgorithm efs = new DepthFirstSearchAlgorithm(this.graph); PredecessorRecorderVisitor vis =new PredecessorRecorderVisitor(); efs.RegisterPredecessorRecorderHandlers(vis); // get root vertex efs.Compute(this.Graph.Root); return vis.AllPaths(); }
public void Init() { parents = new Dictionary <string, string>(); discoverTimes = new Dictionary <string, int>(); finishTimes = new Dictionary <string, int>(); time = 0; g = new AdjacencyGraph <string, Edge <string> >(true); dfs = new DepthFirstSearchAlgorithm <string, Edge <string> >(g); dfs.StartVertex += new VertexEventHandler <string>(this.StartVertex); dfs.DiscoverVertex += new VertexEventHandler <string>(this.DiscoverVertex); dfs.ExamineEdge += new EdgeEventHandler <string, Edge <string> >(this.ExamineEdge); dfs.TreeEdge += new EdgeEventHandler <string, Edge <string> >(this.TreeEdge); dfs.BackEdge += new EdgeEventHandler <string, Edge <string> >(this.BackEdge); dfs.ForwardOrCrossEdge += new EdgeEventHandler <string, Edge <string> >(this.FowardOrCrossEdge); dfs.FinishVertex += new VertexEventHandler <string>(this.FinishVertex); }
private static IEnumerable <TVertex> RootsIterator <TVertex>( AdjacencyGraph <TVertex> visitedGraph) { var notRoots = new Dictionary <TVertex, bool>(visitedGraph.VertexCount); var dfs = new DepthFirstSearchAlgorithm <TVertex>(visitedGraph); dfs.ExamineEdge += e => notRoots[e.Target] = false; dfs.Compute(); foreach (var vertex in visitedGraph.Vertices) { bool value; if (!notRoots.TryGetValue(vertex, out value)) { yield return(vertex); } } }
public void Init() { parents = new Dictionary<string,string>(); discoverTimes = new Dictionary<string,int>(); finishTimes = new Dictionary<string,int>(); time = 0; g = new AdjacencyGraph<string,Edge<string>>(true); dfs = new DepthFirstSearchAlgorithm<string, Edge<string>>(g); dfs.StartVertex += new VertexEventHandler<string>(this.StartVertex); dfs.DiscoverVertex += new VertexEventHandler<string>(this.DiscoverVertex); dfs.ExamineEdge += new EdgeEventHandler<string, Edge<string>>(this.ExamineEdge); dfs.TreeEdge += new EdgeEventHandler<string, Edge<string>>(this.TreeEdge); dfs.BackEdge += new EdgeEventHandler<string, Edge<string>>(this.BackEdge); dfs.ForwardOrCrossEdge += new EdgeEventHandler<string, Edge<string>>(this.FowardOrCrossEdge); dfs.FinishVertex += new VertexEventHandler<string>(this.FinishVertex); }
public static void CloneOutVertexTree(IVertexListGraph g, ISerializableVertexAndEdgeListGraph sub, IVertex v, int maxDepth) { if (g == null) { throw new ArgumentNullException("g"); } if (sub == null) { throw new ArgumentNullException("sub"); } if (v == null) { throw new ArgumentNullException("v"); } DepthFirstSearchAlgorithm algorithm = new DepthFirstSearchAlgorithm(g); PopulatorVisitor visitor = new PopulatorVisitor(sub); algorithm.StartVertex += new VertexEventHandler(visitor, (IntPtr) this.StartVertex); algorithm.TreeEdge += new EdgeEventHandler(visitor, (IntPtr) this.TreeEdge); algorithm.MaxDepth = maxDepth; algorithm.Initialize(); algorithm.Visit(v, 0); }
public static void CloneOutVertexTree( IVertexListGraph g, ISerializableVertexAndEdgeListGraph sub, IVertex v, int maxDepth ) { if (g==null) throw new ArgumentNullException("g"); if (sub==null) throw new ArgumentNullException("sub"); if (v==null) throw new ArgumentNullException("v"); DepthFirstSearchAlgorithm dfs = new DepthFirstSearchAlgorithm(g); PopulatorVisitor pop = new PopulatorVisitor(sub); dfs.StartVertex += new VertexEventHandler(pop.StartVertex); dfs.TreeEdge += new EdgeEventHandler(pop.TreeEdge); dfs.MaxDepth = maxDepth; dfs.Initialize(); dfs.Visit(v,0); }
/// <summary> /// Records all the vertices that are part of the out-subtree of v /// </summary> /// <param name="g">visited graph</param> /// <param name="v">root vertex</param> /// <param name="maxDepth">Maximum exploration depth</param> /// <returns></returns> public static VertexCollection OutVertexTree( IVertexListGraph g, IVertex v, int maxDepth ) { if (g==null) throw new ArgumentNullException("g"); if (v==null) throw new ArgumentNullException("v"); DepthFirstSearchAlgorithm dfs = new DepthFirstSearchAlgorithm(g); dfs.BackEdge +=new EdgeEventHandler(dfs_BackEdge); VertexRecorderVisitor vis =new VertexRecorderVisitor(); vis.Vertices.Add(v); dfs.TreeEdge +=new EdgeEventHandler(vis.RecordTarget); dfs.MaxDepth = maxDepth; dfs.Initialize(); dfs.Visit(v,0); return vis.Vertices; }
/// <summary> /// Computes the topological sort and stores it in the list. /// </summary> /// <param name="vertices">Vertex list that will contain the results</param> public void Compute(IList vertices) { if (vertices != null) m_Vertices = vertices; DepthFirstSearchAlgorithm dfs = new DepthFirstSearchAlgorithm(VisitedGraph); dfs.BackEdge += new EdgeEventHandler(this.BackEdge); dfs.FinishVertex += new VertexEventHandler(this.FinishVertex); m_Vertices.Clear(); dfs.Compute(); }
private static IEnumerable<PropertyInfo> GetDependentProperties(AdjacencyGraph<PropertyInfo, STaggedEdge<PropertyInfo, string>> graph, PropertyInfo property) { property = graph.Vertices.SingleOrDefault(v => v.DeclaringType == property.DeclaringType && v.Name == property.Name); if (property == null) return Enumerable.Empty<PropertyInfo>(); var dependentProperties = new List<PropertyInfo>(); var searchAlgorithm = new DepthFirstSearchAlgorithm<PropertyInfo, STaggedEdge<PropertyInfo, string>>(graph); searchAlgorithm.DiscoverVertex += discoveredProperty => { if (discoveredProperty != property) dependentProperties.Add(discoveredProperty); }; searchAlgorithm.Compute(property); return dependentProperties; }
/// <summary> /// Return the indices of all doors that depend on this door (not including itself) /// </summary> /// <param name="parentDoorId"></param> /// <returns></returns> private List<int> GetDependentDoorIndices(int parentDoorId) { try { var dfs = new DepthFirstSearchAlgorithm<int, Edge<int>>(lockDependencyGraph); dfs.DiscoverVertex += dfsDependencyVertexAction; foundVertices = new List<int>(); dfs.Compute(parentDoorId); foundVertices.Remove(parentDoorId); return foundVertices; } catch (Exception) { throw new ApplicationException("Can't find door index"); } }
/// <summary> /// Checks that the sub graph rooted at <paramref name="ref"/> does not have cyclies /// </summary> /// <param name="g">graph to test</param> /// <exception cref="ArgumentNullException">g is a null reference</exception> /// <exception cref="NonAcyclicGraphException">graph contains a cycle</exception> public static void CheckAcyclic(IVertexListGraph g, IVertex root) { if (g==null) throw new ArgumentNullException("g"); if (root==null) throw new ArgumentNullException("root"); DepthFirstSearchAlgorithm dfs = new DepthFirstSearchAlgorithm(g); dfs.BackEdge +=new EdgeEventHandler(dfs_BackEdge); dfs.Initialize(); dfs.Visit(root,0); dfs.Compute(); }
/// <summary> /// Checks if there exists a path between source and target /// </summary> /// <param name="source">source vertex</param> /// <param name="target">target vertex</param> /// <param name="g">graph</param> /// <returns>true if target is reachable from source</returns> public static bool IsReachable( IVertex source, IVertex target, IVertexListGraph g) { if (source==null) throw new ArgumentNullException("source"); if (target==null) throw new ArgumentNullException("target"); if (g==null) throw new ArgumentNullException("g"); DepthFirstSearchAlgorithm dfs = new DepthFirstSearchAlgorithm(g); dfs.Compute(source); return dfs.Colors[target]!=GraphColor.White; }
public void GraphWithSelfEdgesPUT2() { AdjacencyGraph g = null; DepthFirstSearchAlgorithm bfs = new DepthFirstSearchAlgorithm(g); }
protected void CheckDfs(IVertexListGraph g, DepthFirstSearchAlgorithm dfs) { // check // all vertices should be black foreach(IVertex v in g.Vertices) { Assert.IsTrue( dfs.Colors.Contains(v)); Assert.AreEqual(dfs.Colors[v],GraphColor.Black); } // check parenthesis structure of discover/finish times // See CLR p.480 foreach(IVertex u in g.Vertices) { foreach(IVertex v in g.Vertices) { if (u != v) { Assert.IsTrue( FinishTimes[u] < DiscoverTimes[v] || FinishTimes[v] < DiscoverTimes[u] || ( DiscoverTimes[v] < DiscoverTimes[u] && FinishTimes[u] < FinishTimes[v] && IsDescendant(u, v) ) || ( DiscoverTimes[u] < DiscoverTimes[v] && FinishTimes[v] < FinishTimes[u] && IsDescendant(v, u) ) ); } } } }
/// <summary> /// Executes the algorithm /// </summary> /// <remarks> /// The output of the algorithm is recorded in the component property /// Components, which will contain numbers giving the component ID /// assigned to each vertex. /// </remarks> /// <returns>The number of components is the return value of the function.</returns> public int Compute() { m_Components.Clear(); m_Roots.Clear(); m_DiscoverTimes.Clear(); m_Count = 0; m_DfsTime = 0; DepthFirstSearchAlgorithm dfs = new DepthFirstSearchAlgorithm(VisitedGraph); dfs.DiscoverVertex += new VertexHandler(this.DiscoverVertex); dfs.FinishVertex += new VertexHandler(this.FinishVertex); dfs.Compute(); return ++m_Count; }
private bool HasCycles(IVertexListGraph<IBuilder, EquatableEdge<IBuilder>> graph) { var dfs = new DepthFirstSearchAlgorithm<IBuilder, EquatableEdge<IBuilder>>(graph); Boolean isDag = true; EdgeAction<IBuilder, EquatableEdge<IBuilder>> onBackEdge = edge => { isDag = false; log.DebugFormat("Back edge: {0} -> {1}", edge.Source, edge.Target); }; try { dfs.BackEdge += onBackEdge; dfs.Compute(); } finally { dfs.BackEdge -= onBackEdge; } return !isDag; }
/// <summary> /// Executes the algorithm /// </summary> /// <returns>The total number of components is the return value of the function</returns> public int Compute() { m_Count = int.MaxValue; m_Components.Clear(); DepthFirstSearchAlgorithm dfs = new DepthFirstSearchAlgorithm(VisitedGraph); dfs.StartVertex += new VertexHandler(this.StartVertex); dfs.DiscoverVertex += new VertexHandler(this.DiscoverVertex); return m_Count; }
public void DepthFirstSearch(IVertexAndEdgeListGraph<string, Edge<string>> g) { var bfs = new DepthFirstSearchAlgorithm<string, Edge<string>>(g); bfs.Compute(); }
public int Compute(IVertex startVertex) { if (startVertex == null) { throw new ArgumentNullException("startVertex"); } this.count = -1; this.components.Clear(); DepthFirstSearchAlgorithm algorithm = new DepthFirstSearchAlgorithm(this.VisitedGraph); algorithm.StartVertex += new VertexEventHandler(this, (IntPtr) this.StartVertex); algorithm.DiscoverVertex += new VertexEventHandler(this, (IntPtr) this.DiscoverVertex); algorithm.Compute(startVertex); return ++this.count; }
/// <summary> /// Executes the algorithm /// </summary> /// <remarks> /// The output of the algorithm is recorded in the component property /// Components, which will contain numbers giving the component ID /// assigned to each vertex. /// </remarks> /// <returns>The number of components is the return value of the function.</returns> public int Compute() { this.Components.Clear(); this.Roots.Clear(); this.DiscoverTimes.Clear(); count = 0; dfsTime = 0; DepthFirstSearchAlgorithm dfs = new DepthFirstSearchAlgorithm(VisitedGraph); dfs.DiscoverVertex += new VertexEventHandler(this.DiscoverVertex); dfs.FinishVertex += new VertexEventHandler(this.FinishVertex); dfs.Compute(); return count; }
/// <summary> /// Computes the leaves from the <paramref name="root"/> vertex. /// </summary> /// <param name="g">graph containing the vertex</param> /// <param name="root">root of the tree</param> /// <returns>leaf vertices</returns> public static IVertexEnumerable Sinks( IVertexListGraph g, IVertex root ) { if (g==null) throw new ArgumentNullException("g"); if (root==null) throw new ArgumentNullException("root"); DepthFirstSearchAlgorithm dfs = new DepthFirstSearchAlgorithm(g); SinkRecorderVisitor sinks = new SinkRecorderVisitor(g); dfs.RegisterVertexColorizerHandlers(sinks); dfs.Initialize(); dfs.Visit(root,0); return sinks.Sinks; }
private GcTypeHeap TouchingInPlace(string typeNames) { if (String.IsNullOrEmpty(typeNames)) throw new ArgumentNullException("typeNames"); var filter = FilterHelper.ToFilter(typeNames); Console.WriteLine("filtering nodes not connected to type matching '{0}'", filter); var colors = new Dictionary<GcType, GraphColor>(this.graph.VertexCount); foreach (var type in this.graph.Vertices) colors.Add(type, GraphColor.White); var rgraph = new ReversedBidirectionalGraph<GcType, GcTypeEdge>(graph); foreach (var type in this.graph.Vertices) { if (filter.Match(type.Name)) { { // parents var dfs = new DepthFirstSearchAlgorithm<GcType, ReversedEdge<GcType, GcTypeEdge>>(rgraph, colors); dfs.Visit(type, -1); } { // children var dfs = new DepthFirstSearchAlgorithm<GcType, GcTypeEdge>(graph, colors); dfs.Visit(type, -1); } } } // remove all white vertices this.graph.RemoveVertexIf(t => colors[t] == GraphColor.White); Console.WriteLine("resulting {0} types, {1} edges", graph.VertexCount, graph.EdgeCount); return this; }
public int Compute() { this.Components.Clear(); this.Roots.Clear(); this.DiscoverTimes.Clear(); this.count = 0; this.dfsTime = 0; DepthFirstSearchAlgorithm algorithm = new DepthFirstSearchAlgorithm(this.VisitedGraph); algorithm.DiscoverVertex += new VertexEventHandler(this, (IntPtr) this.DiscoverVertex); algorithm.FinishVertex += new VertexEventHandler(this, (IntPtr) this.FinishVertex); algorithm.Compute(); return this.count; }
public void DepthFirstSearch <TVertex, TEdge>([PexAssumeNotNull] IVertexListGraph <TVertex, TEdge> g) where TEdge : IEdge <TVertex> { var parents = new Dictionary <TVertex, TVertex>(); var discoverTimes = new Dictionary <TVertex, int>(); var finishTimes = new Dictionary <TVertex, int>(); int time = 0; var dfs = new DepthFirstSearchAlgorithm <TVertex, TEdge>(g); dfs.StartVertex += args => { Assert.AreEqual(dfs.VertexColors[args], GraphColor.White); Assert.IsFalse(parents.ContainsKey(args)); parents[args] = args; }; dfs.DiscoverVertex += args => { Assert.AreEqual(dfs.VertexColors[args], GraphColor.Gray); Assert.AreEqual(dfs.VertexColors[parents[args]], GraphColor.Gray); discoverTimes[args] = time++; }; dfs.ExamineEdge += args => { Assert.AreEqual(dfs.VertexColors[args.Source], GraphColor.Gray); }; dfs.TreeEdge += args => { Assert.AreEqual(dfs.VertexColors[args.Target], GraphColor.White); parents[args.Target] = args.Source; }; dfs.BackEdge += args => { Assert.AreEqual(dfs.VertexColors[args.Target], GraphColor.Gray); }; dfs.ForwardOrCrossEdge += args => { Assert.AreEqual(dfs.VertexColors[args.Target], GraphColor.Black); }; dfs.FinishVertex += args => { Assert.AreEqual(dfs.VertexColors[args], GraphColor.Black); finishTimes[args] = time++; }; dfs.Compute(); // check // all vertices should be black foreach (var v in g.Vertices) { Assert.IsTrue(dfs.VertexColors.ContainsKey(v)); Assert.AreEqual(dfs.VertexColors[v], GraphColor.Black); } foreach (var u in g.Vertices) { foreach (var v in g.Vertices) { if (!u.Equals(v)) { Assert.IsTrue( finishTimes[u] < discoverTimes[v] || finishTimes[v] < discoverTimes[u] || ( discoverTimes[v] < discoverTimes[u] && finishTimes[u] < finishTimes[v] && IsDescendant(parents, u, v) ) || ( discoverTimes[u] < discoverTimes[v] && finishTimes[v] < finishTimes[u] && IsDescendant(parents, v, u) ) ); } } } }
private void depthFirstSearchAlgorithmItem_Click(object sender, System.EventArgs e) { if (this.netronPanel.Graph==null) throw new Exception("Generate a graph first"); // clear colors ResetVertexAndEdgeColors(); // create algorithm this.edgeColors=new EdgeColorDictionary(); foreach(IEdge edge in this.netronPanel.Graph.Edges) this.edgeColors[edge]=GraphColor.White; this.vertexColors = new VertexColorDictionary(); DepthFirstSearchAlgorithm dfs = new DepthFirstSearchAlgorithm( this.netronPanel.Graph, this.vertexColors); // create tracer LayoutAlgorithmTraverVisitor tracer = new LayoutAlgorithmTraverVisitor(this.netronPanel.Populator); // link to algo dfs.RegisterTreeEdgeBuilderHandlers(tracer); dfs.RegisterVertexColorizerHandlers(tracer); dfs.TreeEdge +=new EdgeEventHandler(dfs_TreeEdge); dfs.BackEdge +=new EdgeEventHandler(dfs_BackEdge); dfs.ForwardOrCrossEdge +=new EdgeEventHandler(dfs_ForwardOrCrossEdge); // add handler to tracers tracer.UpdateVertex +=new ShapeVertexEventHandler(tracer_UpdateVertex); tracer.UpdateEdge +=new ConnectionEdgeEventHandler(tracer_UpdateEdge); // running algorithm Thread thread = new Thread(new ThreadStart(dfs.Compute)); thread.Start(); }
public RunPipeCollection AllTestPipes() { if (this.graph.VerticesCount == 1) { // only the root vertex return new RunPipeCollection(); } DepthFirstSearchAlgorithm dfs = new DepthFirstSearchAlgorithm( this.graph ); // attach leaf recorder PredecessorRecorderVisitor pred = new PredecessorRecorderVisitor(); dfs.RegisterPredecessorRecorderHandlers(pred); dfs.Compute(this.Root); // create pipies RunPipeCollection pipes = new RunPipeCollection(); foreach(EdgeCollection edges in pred.AllPaths()) { RunPipe pipe = new RunPipe(this.Fixture); foreach(IEdge e in edges) { pipe.Invokers.Add((RunInvokerVertex)e.Target); } pipes.Add(pipe); } return pipes; }