コード例 #1
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="g"></param>
 public ConnectedComponentsAlgorithm(IVertexListGraph g)
 {
     if (g==null)
         throw new ArgumentNullException("g");
     m_VisitedGraph = g;
     m_Components = new VertexIntDictionary();
 }
コード例 #2
0
 /// <summary>
 /// Constructs the algorithm around <paramref name="g"/>.
 /// </summary>
 /// <remarks>
 /// </remarks>
 /// <param name="g">visted graph</param>
 /// <exception cref="ArgumentNullException">g is a null reference</exception>
 public CyclePoppingRandomTreeAlgorithm(
     IVertexListGraph g)
 {
     if (g==null)
         throw new ArgumentNullException("g");
     this.visitedGraph = g;
 }
コード例 #3
0
		/// <summary>
		/// Transitive closure constructor
		/// </summary>
		/// <param name="g">
		/// Graph whose transitive closre needs to be 
		/// computed
		/// </param>
		/// <exception cref="ArgumentNullException">
		/// <paramref name="g"/> is a <null/>.
		/// </exception>
		public TransitiveClosureAlgorithm(IVertexListGraph g)
		{
			if (g==null)
				throw new ArgumentNullException("g");
			this.visitedGraph = g;	
			cg = new AdjacencyGraph();
		}
コード例 #4
0
 /// <summary>
 /// Construct a filtered graph with an edge and a vertex predicate.
 /// </summary>
 /// <param name="g">graph to filter</param>
 /// <param name="edgePredicate">edge predicate</param>
 /// <param name="vertexPredicate">vertex predicate</param>
 /// <exception cref="ArgumentNullException">
 /// g, edgePredicate or vertexPredicate are null
 /// </exception>
 public FilteredVertexListGraph(
     IVertexListGraph g,
     IEdgePredicate edgePredicate,
     IVertexPredicate vertexPredicate)
     : base(g,edgePredicate,vertexPredicate)
 {
 }
コード例 #5
0
 /// <summary>
 /// Construct a graph that filters in-edges
 /// </summary>
 /// <param name="g">graph to filter</param>
 /// <param name="vertexPredicate">vertex predicate</param>
 /// <exception cref="ArgumentNullException">
 /// g or vertexPredicate is null
 /// </exception>
 public FilteredVertexListGraph(
     IVertexListGraph g,
     IVertexPredicate vertexPredicate
     )
     : base(g,new KeepAllEdgesPredicate(), vertexPredicate)
 {
 }
コード例 #6
0
 /// <summary>
 /// Condensation Graph constructor
 /// </summary>
 /// <param name="g">Input graph from 
 /// which condensation graph is created</param>
 public CondensationGraphAlgorithm(IVertexListGraph g)
 {
     if (g==null)
         throw new ArgumentNullException("g");
     this.visitedGraph = g;
     this.components = null;
 }
コード例 #7
0
        public void ComputeCriticalPath(IVertexListGraph<string, Edge<string>> g)
        {
            // is this a dag ?
            bool isDag = AlgoUtility.IsDirectedAcyclicGraph(g);

            var relaxer = new CriticalDistanceRelaxer();
            var vertices = new List<string>(g.Vertices);
            foreach (string root in vertices)
            {
                if (isDag)
                    Search(g, root, relaxer);
                else
                {
                    try
                    {
                        Search(g, root, relaxer);
                        Assert.Fail("should have found the acyclic graph");
                    }
                    catch (NonAcyclicGraphException)
                    {
                        Console.WriteLine("NonAcyclicGraphException caught (as expected)");
                    }
                }
            }
        }
コード例 #8
0
 public VertexCoverageMetric(IVertexListGraph graph)
 {
     if (graph == null)
     {
         throw new ArgumentNullException("graph");
     }
     this.graph = graph;
 }
コード例 #9
0
 //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);
 }
コード例 #10
0
        /// <summary>
        /// Builds a new sorter
        /// </summary>
        /// <param name="g">Graph to sort</param>
        public TopologicalSortAlgorithm(IVertexListGraph g)
        {
            if (g==null)
                throw new ArgumentNullException("g");

            m_VisitedGraph = g;
            m_Vertices = new ArrayList();
        }
コード例 #11
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="g"></param>
 /// <param name="capacities"></param>
 /// <param name="reversedEdges"></param>
 public EdmondsKarpMaximumFlowAlgorithm(
     IVertexListGraph g,
     EdgeDoubleDictionary capacities,
     EdgeEdgeDictionary reversedEdges
     )
     : base(g,capacities,reversedEdges)
 {
 }
コード例 #12
0
        /// <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();
        }
コード例 #13
0
 public BreadthFirstSearchAlgorithm(IVertexListGraph g)
 {
     if (g == null)
     {
         throw new ArgumentNullException("g");
     }
     this.m_VisitedGraph = g;
     this.m_Colors = new VertexColorDictionary();
     this.m_Q = new VertexBuffer();
 }
コード例 #14
0
 public DepthFirstSearchAlgorithm(IVertexListGraph g)
 {
     this.maxDepth = 0x7fffffff;
     if (g == null)
     {
         throw new ArgumentNullException("g");
     }
     this.visitedGraph = g;
     this.colors = new VertexColorDictionary();
 }
コード例 #15
0
        /// <summary>
        /// Builds a new sorter
        /// </summary>
        /// <param name="g">Graph to sort</param>
        /// <param name="vertices">vertices list</param>
        public TopologicalSortAlgorithm(IVertexListGraph g, IList vertices)
        {
            if (g==null)
                throw new ArgumentNullException("g");
            if (vertices == null)
                throw new ArgumentNullException("vertices");

            m_VisitedGraph = g;
            m_Vertices = vertices;
        }
コード例 #16
0
ファイル: RandomGraph.cs プロジェクト: timonela/mb-unit
		/// <summary>
		/// Picks a vertex randomly in the vertex list
		/// </summary>
		/// <param name="g">vertex list</param>
		/// <param name="rnd">random generator</param>
		/// <returns>randomaly chosen vertex</returns>
		public static IVertex Vertex(IVertexListGraph g, Random rnd)
		{
			if (g == null)
				throw new ArgumentNullException("g");
			if (rnd == null)
				throw new ArgumentNullException("random generator");
			if (g.VerticesCount == 0)
				throw new ArgumentException("g is empty");

			return Vertex(g.Vertices,g.VerticesCount,rnd);
		}
コード例 #17
0
 public void Iteration(IVertexListGraph g)
 {
     int n = g.VerticesCount;
     int i = 0;
     foreach(IVertex v in g.Vertices)
     {
         v.ToString();
         ++i;
     }
     Assert.AreEqual(n,i);
 }
コード例 #18
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="g"></param>
 public StrongComponentsAlgorithm(IVertexListGraph g)
 {
     if (g==null)
         throw new ArgumentNullException("g");
     m_VisitedGraph = g;
     m_Components = new VertexIntDictionary();
     m_Roots = new VertexVertexDictionary();
     m_DiscoverTimes = new VertexIntDictionary();
     m_Stack = new Stack();
     m_Count = 0;
     m_DfsTime = 0;
 }
コード例 #19
0
 /// <summary>
 /// Construct a strong component algorithm
 /// </summary>
 /// <param name="g">graph to apply algorithm on</param>
 /// <exception cref="ArgumentNullException">graph is null</exception>
 public StrongComponentsAlgorithm(IVertexListGraph g)
 {
     if (g==null)
         throw new ArgumentNullException("g");
     this.visitedGraph = g;
     this.components = new VertexIntDictionary();
     this.roots = new VertexVertexDictionary();
     this.discoverTimes = new VertexIntDictionary();
     this.stack = new Stack();
     this.count = 0;
     this.dfsTime = 0;
 }
コード例 #20
0
        public void RoundRobinTest(IVertexListGraph<string, Edge<string>> g)
        {
            if (g.VertexCount == 0)
                return;

            RandomWalkAlgorithm<String, Edge<string>> walker =
                new RandomWalkAlgorithm<String, Edge<string>>(g);
            walker.EdgeChain = new NormalizedMarkovEdgeChain<string, Edge<string>>();

            string root = TraversalHelper.GetFirstVertex(g);
            walker.Generate(root);
        }
コード例 #21
0
 public RandomWalkAlgorithm(IVertexListGraph g)
 {
     this.visitedGraph = null;
     this.endPredicate = null;
     this.edgeChain = new NormalizedMarkovEdgeChain();
     this.rnd = new Random((int) DateTime.Now.Ticks);
     if (g == null)
     {
         throw new ArgumentNullException("g");
     }
     this.visitedGraph = g;
 }
コード例 #22
0
		/// <summary>
		/// Constructs the algorithm around <paramref name="g"/> using
		/// the <paramref name="edgeChain"/> Markov chain.
		/// </summary>
		/// <param name="g">visited graph</param>
		/// <param name="edgeChain">
		/// Markov <see cref="IEdge"/> chain generator
		/// </param>
		/// <exception cref="ArgumentNullException">
		/// <paramref name="g"/> or <paramref name="edgeChain"/>
		/// is a null reference
		/// </exception>
		public CyclePoppingRandomTreeAlgorithm(
			IVertexListGraph g,
			IMarkovEdgeChain edgeChain
			)
		{
			if (g==null)
				throw new ArgumentNullException("g");
			if (edgeChain==null)
				throw new ArgumentNullException("edgeChain");

			this.visitedGraph = g;
			this.edgeChain = edgeChain;
		}
 public CyclePoppingRandomTreeAlgorithm(IVertexListGraph g)
 {
     this.visitedGraph = null;
     this.colors = new VertexColorDictionary();
     this.edgeChain = new NormalizedMarkovEdgeChain();
     this.successors = new VertexEdgeDictionary();
     this.rnd = new Random((int) DateTime.Now.Ticks);
     if (g == null)
     {
         throw new ArgumentNullException("g");
     }
     this.visitedGraph = g;
 }
コード例 #24
0
 public ConnectedComponentsAlgorithm(IVertexListGraph g, VertexIntDictionary components)
 {
     if (g == null)
     {
         throw new ArgumentNullException("g");
     }
     if (components == null)
     {
         throw new ArgumentNullException("components");
     }
     this.visitedGraph = g;
     this.components = components;
 }
コード例 #25
0
		/// <summary>
		/// Builds a new Dijsktra searcher.
		/// </summary>
		/// <param name="g">The graph</param>
		/// <param name="weights">Edge weights</param>
		/// <exception cref="ArgumentNullException">Any argument is null</exception>
		/// <remarks>This algorithm uses the <seealso cref="BreadthFirstSearchAlgorithm"/>.</remarks>
		public DijkstraShortestPathAlgorithm(
			IVertexListGraph g, 
			EdgeDoubleDictionary weights
			)
		{
			if (g == null)
				throw new ArgumentNullException("g");
			if (weights == null)
				throw new ArgumentNullException("Weights");

			this.visitedGraph = g;
			this.colors = new VertexColorDictionary();
			this.distances = new VertexDoubleDictionary();
			this.weights = weights;
			this.vertexQueue = null;
		}
コード例 #26
0
        private void Search(
            IVertexListGraph<string, Edge<string>> g, 
            string root, IDistanceRelaxer relaxer)
        {
            DagShortestPathAlgorithm<string, Edge<string>> algo = 
                new DagShortestPathAlgorithm<string, Edge<string>>(
                    g,
                    DagShortestPathAlgorithm<string, Edge<string>>.UnaryWeightsFromVertexList(g),
                    relaxer
                    );
            VertexPredecessorRecorderObserver<string, Edge<string>> predecessors = new VertexPredecessorRecorderObserver<string, Edge<string>>();
            predecessors.Attach(algo);
            algo.Compute(root);

            Verify(algo, predecessors);
        }
コード例 #27
0
		/// <summary>
		/// Builds a new Dagsearcher.
		/// </summary>
		/// <param name="g">Acyclic graph</param>
		/// <param name="weights">Edge weights</param>
		/// <exception cref="ArgumentNullException">Any argument is null</exception>
		/// <remarks>This algorithm uses the <seealso cref="BreadthFirstSearchAlgorithm"/>.</remarks>
		public DagShortestPathAlgorithm(
			IVertexListGraph g, 
			EdgeDoubleDictionary weights
			)
		{
			if (g == null)
				throw new ArgumentNullException("g");
			if (weights == null)
				throw new ArgumentNullException("Weights");

			m_VisitedGraph = g;
			m_Colors = new VertexColorDictionary();
			m_Distances = new VertexDoubleDictionary();
			m_Predecessors = new VertexVertexDictionary();
			m_Weights = weights;
		}
コード例 #28
0
        public void RoundRobinTestWithVisitor(IVertexListGraph<string, Edge<string>> g)
        {
            if (g.VertexCount == 0)
                return;

            RandomWalkAlgorithm<String, Edge<string>> walker =
                new RandomWalkAlgorithm<String, Edge<string>>(g);
            walker.EdgeChain = new NormalizedMarkovEdgeChain<string, Edge<string>>();

            string root = TraversalHelper.GetFirstVertex(g);

            EdgeRecorderObserver<string, Edge<string>> vis = new EdgeRecorderObserver<string, Edge<string>>();
            vis.Attach(walker);
            walker.Generate(root);
            vis.Detach(walker);
        }
コード例 #29
0
 public BreadthFirstSearchAlgorithm(IVertexListGraph g, VertexBuffer q, VertexColorDictionary colors)
 {
     if (g == null)
     {
         throw new ArgumentNullException("g");
     }
     if (q == null)
     {
         throw new ArgumentNullException("Stack Q is null");
     }
     if (colors == null)
     {
         throw new ArgumentNullException("Colors");
     }
     this.m_VisitedGraph = g;
     this.m_Colors = colors;
     this.m_Q = q;
 }
コード例 #30
0
		/// <summary>Constructs a maximum flow algorithm.</summary>
		/// <param name="g">Graph to compute maximum flow on.</param>
		/// <param name="capacities">edge capacities</param>
		/// <param name="reversedEdges">reversed edge map</param>
		/// <exception cref="ArgumentNullException"><paramref name="g"/> or
		/// <paramref name="capacities"/> or <paramref name="reversedEdges"/> is a null
		/// reference.
		/// </exception>
		public MaximumFlowAlgorithm(
			IVertexListGraph g,
			EdgeDoubleDictionary capacities,
			EdgeEdgeDictionary reversedEdges
			)
		{
			if (g==null)
				throw new ArgumentNullException("g");
			if (capacities==null)
				throw new ArgumentNullException("capacities");
			if (reversedEdges==null)
				throw new ArgumentNullException("reversedEdges");
		
			this.visitedGraph=g;
			this.capacities=capacities;
			this.reversedEdges=reversedEdges;
		
			this.predecessors=new VertexEdgeDictionary();
			this.residualCapacities=new EdgeDoubleDictionary();
			this.colors = new VertexColorDictionary();
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="DepthFirstSearchAlgorithm{TVertex,TEdge}"/> class.
 /// </summary>
 /// <param name="host">Host to use if set, otherwise use this reference.</param>
 /// <param name="visitedGraph">Graph to visit.</param>
 public DepthFirstSearchAlgorithm(
     IAlgorithmComponent host,
     IVertexListGraph <TVertex, TEdge> visitedGraph)
     : this(host, visitedGraph, new Dictionary <TVertex, GraphColor>(), edges => edges)
 {
 }
コード例 #32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TarjanOfflineLeastCommonAncestorAlgorithm{TVertex,TEdge}"/> class.
 /// </summary>
 /// <param name="visitedGraph">Graph to visit.</param>
 /// <exception cref="T:System.ArgumentNullException"><paramref name="visitedGraph"/> is <see langword="null"/>.</exception>
 public TarjanOfflineLeastCommonAncestorAlgorithm(
     [NotNull] IVertexListGraph <TVertex, TEdge> visitedGraph)
     : this(null, visitedGraph)
 {
 }
コード例 #33
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CyclePoppingRandomTreeAlgorithm{TVertex,TEdge}"/> class.
 /// </summary>
 /// <param name="visitedGraph">Graph to visit.</param>
 /// <param name="edgeChain">Edge chain strategy to use.</param>
 public CyclePoppingRandomTreeAlgorithm(
     [NotNull] IVertexListGraph <TVertex, TEdge> visitedGraph,
     [NotNull] IMarkovEdgeChain <TVertex, TEdge> edgeChain)
     : this(null, visitedGraph, edgeChain)
 {
 }
コード例 #34
0
 public StronglyConnectedComponentsAlgorithm(
     IVertexListGraph <TVertex, TEdge> g)
     : this(g, new Dictionary <TVertex, int>())
 {
 }
コード例 #35
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StronglyConnectedComponentsAlgorithm{TVertex,TEdge}"/> class.
 /// </summary>
 /// <param name="visitedGraph">Graph to visit.</param>
 public StronglyConnectedComponentsAlgorithm(
     [NotNull] IVertexListGraph <TVertex, TEdge> visitedGraph)
     : this(visitedGraph, new Dictionary <TVertex, int>())
 {
 }
コード例 #36
0
 private static void DagCriticalPath_Test <TVertex, TEdge>(
     [NotNull] IVertexListGraph <TVertex, TEdge> graph)
     where TEdge : IEdge <TVertex>
 {
     DagAlgorithm_Test(graph, DistanceRelaxers.CriticalDistance);
 }
 private static void DagShortestPath_Test <TVertex, TEdge>(IVertexListGraph <TVertex, TEdge> graph)
     where TEdge : IEdge <TVertex>
 {
     DagAlgorithm_Test(graph, DistanceRelaxers.ShortestDistance);
 }
コード例 #38
0
ファイル: CycleDetector.cs プロジェクト: fagan2888/Schematic
        private IReadOnlyCollection <IReadOnlyCollection <Identifier> > GetCyclePaths(IVertexListGraph <Identifier, SEquatableEdge <Identifier> > graph)
        {
            if (graph == null)
            {
                throw new ArgumentNullException(nameof(graph));
            }

            var examinedEdges = new List <IEdge <Identifier> >();
            var cycles        = new List <IReadOnlyCollection <Identifier> >();
            var dfs           = new DepthFirstSearchAlgorithm <Identifier, SEquatableEdge <Identifier> >(graph);

            void onExamineEdge(SEquatableEdge <Identifier> e) => examinedEdges.Add(e);
            void onCyclingEdgeFound(SEquatableEdge <Identifier> e) => OnCyclingEdgeFound(examinedEdges, cycles, e);

            try
            {
                dfs.ExamineEdge += onExamineEdge;
                dfs.BackEdge    += onCyclingEdgeFound;
                dfs.Compute();
                return(cycles);
            }
            finally
            {
                dfs.ExamineEdge -= onExamineEdge;
                dfs.BackEdge    -= onCyclingEdgeFound;
            }
        }
コード例 #39
0
        private static void RunRandomWalkAndCheck <TVertex, TEdge>(
            [NotNull] IVertexListGraph <TVertex, TEdge> graph)
            where TEdge : IEdge <TVertex>
        {
            if (graph.VertexCount == 0)
            {
                return;
            }

            foreach (TVertex root in graph.Vertices)
            {
                RandomWalkAlgorithm <TVertex, TEdge> walker1 = CreateAlgorithm();
                bool calledStart1      = false;
                bool calledEnd1        = false;
                var  encounteredEdges1 = new List <TEdge>();
                walker1.StartVertex += vertex =>
                {
                    Assert.IsFalse(calledStart1);
                    calledStart1 = true;
                    Assert.AreEqual(root, vertex);
                };
                walker1.TreeEdge += edge =>
                {
                    Assert.IsNotNull(edge);
                    encounteredEdges1.Add(edge);
                };
                walker1.EndVertex += vertex =>
                {
                    Assert.IsFalse(calledEnd1);
                    calledEnd1 = true;
                    Assert.IsNotNull(vertex);
                };

                RandomWalkAlgorithm <TVertex, TEdge> walker2 = CreateAlgorithm();
                bool calledStart2      = false;
                bool calledEnd2        = false;
                var  encounteredEdges2 = new List <TEdge>();
                walker2.StartVertex += vertex =>
                {
                    Assert.IsFalse(calledStart2);
                    calledStart2 = true;
                    Assert.AreEqual(root, vertex);
                };
                walker2.TreeEdge += edge =>
                {
                    Assert.IsNotNull(edge);
                    encounteredEdges2.Add(edge);
                };
                walker2.EndVertex += vertex =>
                {
                    Assert.IsFalse(calledEnd2);
                    calledEnd2 = true;
                    Assert.IsNotNull(vertex);
                };

                RandomWalkAlgorithm <TVertex, TEdge> walker3 = CreateAlgorithm();
                bool calledStart3      = false;
                bool calledEnd3        = false;
                var  encounteredEdges3 = new List <TEdge>();
                walker3.StartVertex += vertex =>
                {
                    Assert.IsFalse(calledStart3);
                    calledStart3 = true;
                    Assert.AreEqual(root, vertex);
                };
                walker3.TreeEdge += edge =>
                {
                    Assert.IsNotNull(edge);
                    encounteredEdges3.Add(edge);
                };
                walker3.EndVertex += vertex =>
                {
                    Assert.IsFalse(calledEnd3);
                    calledEnd3 = true;
                    Assert.IsNotNull(vertex);
                };

                var vis1 = new EdgeRecorderObserver <TVertex, TEdge>();
                using (vis1.Attach(walker1))
                    walker1.Generate(root);
                Assert.IsTrue(calledStart1);
                Assert.IsTrue(calledEnd1);

                walker2.SetRootVertex(root);
                var vis2 = new EdgeRecorderObserver <TVertex, TEdge>();
                using (vis2.Attach(walker2))
                    walker2.Compute();
                Assert.IsTrue(calledStart2);
                Assert.IsTrue(calledEnd2);

                var vis3 = new EdgeRecorderObserver <TVertex, TEdge>();
                using (vis3.Attach(walker3))
                    walker3.Generate(root, 100);
                Assert.IsTrue(calledStart3);
                Assert.IsTrue(calledEnd3);

                CollectionAssert.AreEqual(vis1.Edges, encounteredEdges1);
                CollectionAssert.AreEqual(vis1.Edges, encounteredEdges2);
                CollectionAssert.AreEqual(vis1.Edges, encounteredEdges3);
                CollectionAssert.AreEqual(vis1.Edges, vis2.Edges);
                CollectionAssert.AreEqual(vis1.Edges, vis3.Edges);
            }

            #region Local function

            RandomWalkAlgorithm <TVertex, TEdge> CreateAlgorithm()
            {
                var walker = new RandomWalkAlgorithm <TVertex, TEdge>(graph)
                {
                    EdgeChain = new NormalizedMarkovEdgeChain <TVertex, TEdge>
                    {
                        Rand = new Random(123456)
                    }
                };

                return(walker);
            }

            #endregion
        }
コード例 #40
0
        private static void RunDFSAndCheck <TVertex, TEdge>(
            [NotNull] IVertexListGraph <TVertex, TEdge> graph,
            int maxDepth = int.MaxValue)
            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>(graph)
            {
                MaxDepth = maxDepth
            };

            dfs.InitializeVertex += vertex =>
            {
                Assert.AreEqual(GraphColor.White, dfs.VerticesColors[vertex]);
            };

            dfs.StartVertex += vertex =>
            {
                Assert.AreEqual(GraphColor.White, dfs.VerticesColors[vertex]);
                Assert.IsFalse(parents.ContainsKey(vertex));
                parents[vertex] = vertex;
            };

            dfs.DiscoverVertex += vertex =>
            {
                Assert.AreEqual(GraphColor.Gray, dfs.VerticesColors[vertex]);
                Assert.AreEqual(GraphColor.Gray, dfs.VerticesColors[parents[vertex]]);

                discoverTimes[vertex] = time++;
            };

            dfs.ExamineEdge += edge =>
            {
                Assert.AreEqual(GraphColor.Gray, dfs.VerticesColors[edge.Source]);
            };

            dfs.TreeEdge += edge =>
            {
                Assert.AreEqual(GraphColor.White, dfs.VerticesColors[edge.Target]);
                parents[edge.Target] = edge.Source;
            };

            dfs.BackEdge += edge =>
            {
                Assert.AreEqual(GraphColor.Gray, dfs.VerticesColors[edge.Target]);
            };

            dfs.ForwardOrCrossEdge += edge =>
            {
                Assert.AreEqual(GraphColor.Black, dfs.VerticesColors[edge.Target]);
            };

            dfs.FinishVertex += vertex =>
            {
                Assert.AreEqual(GraphColor.Black, dfs.VerticesColors[vertex]);
                finishTimes[vertex] = time++;
            };

            dfs.Compute();

            // Check
            // All vertices should be black
            foreach (TVertex vertex in graph.Vertices)
            {
                Assert.IsTrue(dfs.VerticesColors.ContainsKey(vertex));
                Assert.AreEqual(dfs.VerticesColors[vertex], GraphColor.Black);
            }

            foreach (TVertex u in graph.Vertices)
            {
                foreach (TVertex v in graph.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>
 /// Initializes a new instance of the <see cref="WeaklyConnectedComponentsAlgorithm{TVertex,TEdge}"/> class.
 /// </summary>
 /// <param name="visitedGraph">Graph to visit.</param>
 /// <param name="components">Graph components.</param>
 public WeaklyConnectedComponentsAlgorithm(
     IVertexListGraph <TVertex, TEdge> visitedGraph,
     IDictionary <TVertex, int> components)
     : this(null, visitedGraph, components)
 {
 }
コード例 #42
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DepthFirstSearchAlgorithm{TVertex,TEdge}"/> class.
 /// </summary>
 /// <param name="visitedGraph">Graph to visit.</param>
 public DepthFirstSearchAlgorithm([NotNull] IVertexListGraph <TVertex, TEdge> visitedGraph)
     : this(visitedGraph, new Dictionary <TVertex, GraphColor>())
 {
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="WeaklyConnectedComponentsAlgorithm{TVertex,TEdge}"/> class.
 /// </summary>
 /// <param name="visitedGraph">Graph to visit.</param>
 public WeaklyConnectedComponentsAlgorithm(
     IVertexListGraph <TVertex, TEdge> visitedGraph)
     : this(visitedGraph, new Dictionary <TVertex, int>())
 {
 }
コード例 #44
0
        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)
                            )
                            );
                    }
                }
            }
        }
コード例 #45
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StronglyConnectedComponentsAlgorithm{TVertex,TEdge}"/> class.
 /// </summary>
 /// <param name="visitedGraph">Graph to visit.</param>
 /// <param name="components">Graph components.</param>
 public StronglyConnectedComponentsAlgorithm(
     [NotNull] IVertexListGraph <TVertex, TEdge> visitedGraph,
     [NotNull] IDictionary <TVertex, int> components)
     : this(null, visitedGraph, components)
 {
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="DijkstraShortestPathAlgorithm{TVertex,TEdge}"/> class.
 /// </summary>
 /// <param name="visitedGraph">Graph to visit.</param>
 /// <param name="edgeWeights">Function that computes the weight for a given edge.</param>
 public DijkstraShortestPathAlgorithm(
     IVertexListGraph <TVertex, TEdge> visitedGraph,
     Func <TEdge, double> edgeWeights)
     : this(visitedGraph, edgeWeights, DistanceRelaxers.ShortestDistance)
 {
 }
コード例 #47
0
 public StronglyConnectedComponentsAlgorithm(
     IVertexListGraph <TVertex, TEdge> g,
     IDictionary <TVertex, int> components)
     : this(null, g, components)
 {
 }
コード例 #48
0
 public DepthFirstSearchAlgorithm(IVertexListGraph <TVertex, TEdge> g)
     : this(g, new Dictionary <TVertex, GraphColor>())
 {
 }
コード例 #49
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CyclePoppingRandomTreeAlgorithm{TVertex,TEdge}"/> class.
 /// </summary>
 /// <param name="visitedGraph">Graph to visit.</param>
 public CyclePoppingRandomTreeAlgorithm([NotNull] IVertexListGraph <TVertex, TEdge> visitedGraph)
     : this(visitedGraph, new NormalizedMarkovEdgeChain <TVertex, TEdge>())
 {
 }
コード例 #50
0
 public BreadthFirstSearchAlgorithm(IVertexListGraph <TVertex, TEdge> g)
     : this(g, new QuickGraph.Collections.Queue <TVertex>(), new Dictionary <TVertex, GraphColor>())
 {
 }
コード例 #51
0
 public TopologicalSortAlgorithm(IVertexListGraph <TVertex, TEdge> g)
     : this(g, new List <TVertex>())
 {
 }
コード例 #52
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TopologicalSortingAlgorithm{TVertex, TEdge}"/> class.
 /// </summary>
 /// <param name="graph">The graph.</param>
 /// <param name="vertices">The vertices for the graph.</param>
 /// <exception cref="ArgumentNullException"><paramref name="vertices"/> is <c>null</c>.</exception>
 public TopologicalSortingAlgorithm(IVertexListGraph <TVertex, TEdge> graph, IList <TVertex> vertices)
     : base(graph)
 {
     SortedVertices = vertices ?? throw new ArgumentNullException(nameof(vertices));
 }
コード例 #53
0
        /// <summary>
        /// Calculates the Strongly Connected Components of a graph. An SCC is known as sub-graph where every node
        /// in that sub-graph can traverse to any other node in that sub-graph. This method groups TVertex elements
        /// into a strongly connected component dictionary.
        /// </summary>
        /// <param name="graph">Graph to compute SCCs</param>
        /// <returns>Dictionary of SCCs</returns>
        public static Dictionary <int, List <TVertex> > CalculateStronglyConnectedComponents(IVertexListGraph <TVertex, TEdge> graph)
        {
            var cc = new QuickGraph.Algorithms.ConnectedComponents.StronglyConnectedComponentsAlgorithm <TVertex, TEdge>(graph);

            cc.Compute();

            var groups = cc.Components.GroupBy(kv => kv.Value);

            var sccs = new Dictionary <int, List <TVertex> >();

            foreach (var grouping in groups)
            {
                if (sccs.ContainsKey(grouping.Key) == false)
                {
                    sccs[grouping.Key] = new List <TVertex>();
                }

                foreach (var nodeKv in grouping)
                {
                    sccs[grouping.Key].Add(nodeKv.Key);
                }
            }

            // Removing single node SSCs
            var removals = new List <int>();

            foreach (var key in sccs.Keys)
            {
                if (sccs[key].Count < 2)
                {
                    removals.Add(key);
                }
            }

            foreach (var key in removals)
            {
                sccs.Remove(key);
            }

            return(sccs);
        }
コード例 #54
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TopologicalSortAlgorithm{TVertex,TEdge}"/> class.
 /// </summary>
 /// <param name="visitedGraph">Graph to visit.</param>
 public TopologicalSortAlgorithm([NotNull] IVertexListGraph <TVertex, TEdge> visitedGraph)
     : this(visitedGraph, new List <TVertex>())
 {
 }
コード例 #55
0
 public VertexAdjacencyMatrixBuilderAlgorithm(IVertexListGraph <TVertex, TEdge> visitedGraph)
     : base(visitedGraph)
 {
 }
コード例 #56
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BreadthFirstSearchAlgorithm{TVertex,TEdge}"/> class.
 /// </summary>
 /// <param name="visitedGraph">Graph to visit.</param>
 public BreadthFirstSearchAlgorithm([NotNull] IVertexListGraph <TVertex, TEdge> visitedGraph)
     : this(visitedGraph, new Collections.Queue <TVertex>(), new Dictionary <TVertex, GraphColor>())
 {
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="DepthFirstSearchAlgorithm{TVertex,TEdge}"/> class.
 /// </summary>
 /// <param name="visitedGraph">Graph to visit.</param>
 /// <param name="verticesColors">Vertices associated to their colors (treatment states).</param>
 public DepthFirstSearchAlgorithm(
     IVertexListGraph <TVertex, TEdge> visitedGraph,
     IDictionary <TVertex, GraphColor> verticesColors)
     : this(null, visitedGraph, verticesColors)
 {
 }
コード例 #58
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DagShortestPathAlgorithm{TVertex,TEdge}"/> class.
 /// </summary>
 /// <param name="visitedGraph">Graph to visit.</param>
 /// <param name="edgeWeights">Function that computes the weight for a given edge.</param>
 public DagShortestPathAlgorithm(
     [NotNull] IVertexListGraph <TVertex, TEdge> visitedGraph,
     [NotNull] Func <TEdge, double> edgeWeights)
     : this(visitedGraph, edgeWeights, DistanceRelaxers.ShortestDistance)
 {
 }
コード例 #59
0
        public static VertexPredecessorRecorderObserver <TVertex, TEdge> GetPredecessors <TVertex, TEdge> (this IVertexListGraph <TVertex, TEdge> graph, TVertex obj, VertexAction <TVertex> onVertex) where TEdge : IEdge <TVertex>
        {
            var bfsa = new BreadthFirstSearchAlgorithm <TVertex, TEdge> (graph);

            bfsa.ExamineVertex += (vertex) => {
                onVertex?.Invoke(vertex);
            };

            var vertexPredecessorRecorderObserver = new VertexPredecessorRecorderObserver <TVertex, TEdge> ();

            using (vertexPredecessorRecorderObserver.Attach(bfsa)) {
                bfsa.Compute(obj);
            }

            return(vertexPredecessorRecorderObserver);
        }
コード例 #60
0
 public TarjanOfflineLeastCommonAncestorAlgorithm(
     IAlgorithmComponent host,
     IVertexListGraph <TVertex, TEdge> visitedGraph)
     : base(host, visitedGraph)
 {
 }