public void GraphWithSelfEdges() { AdjacencyGraph <string, Edge <string> > g = new AdjacencyGraph <string, Edge <string> >(false); g.AddVertex("v1"); g.AddEdge(new Edge <string>("v1", "v1")); foreach (string v in g.Vertices) { parents[v] = v; } // compute dfs.Compute(); CheckDfs(); }
/// <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); }
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} )); }
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 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; }
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); } } }
/// <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; }
public void DepthFirstSearch(IVertexAndEdgeListGraph<string, Edge<string>> g) { var bfs = new DepthFirstSearchAlgorithm<string, Edge<string>>(g); bfs.Compute(); }
/// <summary> /// Executes edge dfs /// </summary> /// <param name="g"></param> public void TestAllActions(IVertexAndEdgeListGraph g, string path) { // Testing dfs all apth DepthFirstSearchAlgorithm dfs = new DepthFirstSearchAlgorithm(g); PredecessorRecorderVisitor visv = new PredecessorRecorderVisitor(); dfs.RegisterPredecessorRecorderHandlers(visv); IVertex s0 = Traversal.FirstVertexIf(g.Vertices, new NameEqualPredicate("S0")); dfs.Compute(s0); Console.WriteLine("vertex paths"); foreach(EdgeCollection ec in visv.AllPaths()) { foreach(IEdge edge in ec) { Console.WriteLine("{0}->{1}, {2}", ((NamedVertex)edge.Source).Name, ((NamedVertex)edge.Target).Name, ((NamedEdge)edge).Name ); } Console.WriteLine(); } // end of dfs test GraphvizAlgorithm gw = RenderActions(g,path); // The all action algorithms EdgeDepthFirstSearchAlgorithm edfs = CreateEdgeDfs(g); // add tracer AlgorithmTracerVisitor vis = AddTracer(edfs,path); // add predecessor recorder EdgePredecessorRecorderVisitor erec = AddPredecessorRecorder(edfs); // computing all actions edfs.Compute(s0); // display end path edges OutputEndPathEdges(erec); // display all actions path OutputAllActions(erec,gw,path); }
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; }
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; }
public void GraphWithSelfEdgesPUT(AdjacencyGraph g, int loopBound, bool self) { Random rnd; //new Random(); var choose1 = PexChoose.FromCall(this); rnd = choose1.ChooseValue<Random>("Random object"); Init(); for (int i = 0; i < loopBound; ++i) { for (int j = 0; j < i * i; ++j) { RandomGraph.Graph(g, i, j, rnd, true); Init(); DepthFirstSearchAlgorithm dfs = new DepthFirstSearchAlgorithm(g); dfs.StartVertex += new VertexHandler(this.StartVertex); dfs.DiscoverVertex += new VertexHandler(this.DiscoverVertex); dfs.ExamineEdge += new EdgeHandler(this.ExamineEdge); dfs.TreeEdge += new EdgeHandler(this.TreeEdge); dfs.BackEdge += new EdgeHandler(this.BackEdge); dfs.ForwardOrCrossEdge += new EdgeHandler(this.FowardOrCrossEdge); dfs.FinishVertex += new VertexHandler(this.FinishVertex); Parents.Clear(); DiscoverTimes.Clear(); FinishTimes.Clear(); m_Time = 0; foreach (IVertex v in g.Vertices) Parents[v] = v; var choose = PexChoose.FromCall(this); if (choose.ChooseValue<bool>("to add a self ede")) { IVertex selfEdge = RandomGraph.Vertex(g, rnd); g.AddEdge(selfEdge, selfEdge); } // compute dfs.Compute(); CheckDfs(g, dfs); } } }
public TypeDependencyGraph TypeDepAnalysis(List<TypeReference> typesToExamine) { TypeDependencyGraph tdg = new TypeDependencyGraph(); StrongComponentsAlgorithm scgo = new StrongComponentsAlgorithm(this); scgo.Compute(); Dictionary<int, List<IVertex>> sccMap = new Dictionary<int, List<IVertex>>(); foreach (System.Collections.DictionaryEntry de in scgo.Components) { IVertex v = (IVertex)de.Key; int scc_id = (int)de.Value; if (!sccMap.ContainsKey(scc_id)) { sccMap[scc_id] = new List<IVertex>(); } sccMap[scc_id].Add(v); } Stack<List<TypeVertex>> PendingEdges = new Stack<List<TypeVertex>>(); List<TypeVertex> VertexToRemove = new List<TypeVertex>(); VertexEventHandler discV = delegate(Object s, VertexEventArgs e) { PendingEdges.Push(new List<TypeVertex>()); TypeVertex tv = (TypeVertex)e.Vertex; if (scgo.Components.Contains(tv) && sccMap[scgo.Components[tv]].Count > 1) { tv.SCCNum = scgo.Components[tv]; tdg.AddVertex(tv); } else if (typesToExamine.Contains(tv.TypeRef)) { tdg.AddVertex(tv); } else { VertexToRemove.Add(tv); } }; VertexEventHandler finishV = delegate(Object s, VertexEventArgs e) { TypeVertex tv = (TypeVertex)e.Vertex; List<TypeVertex> pes = PendingEdges.Pop(); if (tdg.ContainsVertex(tv)) { foreach (TypeVertex target in pes) { if (tdg.ContainsVertex(target) && !tdg.ContainsEdge(tv, target)) tdg.AddEdge(tv, target); } } }; EdgeEventHandler treeedge = delegate(Object o, EdgeEventArgs e) { PendingEdges.Peek().Add((TypeVertex)e.Edge.Target); }; DepthFirstSearchAlgorithm dfs = new DepthFirstSearchAlgorithm(this); dfs.DiscoverVertex += discV; dfs.FinishVertex += finishV; dfs.TreeEdge += treeedge; dfs.Compute(); foreach (TypeVertex v in VertexToRemove) { this.RemoveVertex(v); } return tdg; }
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 void GraphWithSelfEdges() { AdjacencyGraph g = new AdjacencyGraph( new QuickGraph.Providers.VertexAndEdgeProvider(), true ); RandomGraph.Graph(g,20,100,new Random(),true); DepthFirstSearchAlgorithm dfs = new DepthFirstSearchAlgorithm(g); dfs.StartVertex += new VertexHandler( this.StartVertex); dfs.DiscoverVertex += new VertexHandler(this.DiscoverVertex); dfs.ExamineEdge += new EdgeHandler(this.ExamineEdge); dfs.TreeEdge += new EdgeHandler(this.TreeEdge); dfs.BackEdge += new EdgeHandler(this.BackEdge); dfs.ForwardOrCrossEdge += new EdgeHandler(this.FowardOrCrossEdge); dfs.FinishVertex += new VertexHandler(this.FinishVertex); Parents.Clear(); DiscoverTimes.Clear(); FinishTimes.Clear(); m_Time = 0; foreach(IVertex v in g.Vertices) Parents[v] = v; // compute dfs.Compute(); CheckDfs(g,dfs); }
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) ) ); } } } }
/// <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; }
/// <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(); }
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 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; }
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(); }
/// <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(); }
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> /// 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> /// 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; }