private static void RunConnectedComponentsAndCheck <TVertex, TEdge>(
            [NotNull] IUndirectedGraph <TVertex, TEdge> graph)
            where TEdge : IEdge <TVertex>
        {
            var algorithm = new ConnectedComponentsAlgorithm <TVertex, TEdge>(graph);

            algorithm.Compute();

            Assert.AreEqual(graph.VertexCount, algorithm.Components.Count);
            if (graph.VertexCount == 0)
            {
                Assert.IsTrue(algorithm.ComponentCount == 0);
                return;
            }

            Assert.Positive(algorithm.ComponentCount);
            Assert.LessOrEqual(algorithm.ComponentCount, graph.VertexCount);
            foreach (KeyValuePair <TVertex, int> pair in algorithm.Components)
            {
                Assert.GreaterOrEqual(pair.Value, 0);
                Assert.IsTrue(pair.Value < algorithm.ComponentCount, $"{pair.Value} < {algorithm.ComponentCount}");
            }

            foreach (TVertex vertex in graph.Vertices)
            {
                foreach (TEdge edge in graph.AdjacentEdges(vertex))
                {
                    Assert.AreEqual(algorithm.Components[edge.Source], algorithm.Components[edge.Target]);
                }
            }
        }
Beispiel #2
0
        private void Compute <TVertex, TEdge>(IUndirectedGraph <TVertex, TEdge> g)
            where TEdge : IEdge <TVertex>
        {
            var dfs = new ConnectedComponentsAlgorithm <TVertex, TEdge>(g);

            dfs.Compute();
            if (g.VertexCount == 0)
            {
                Assert.Equal(0, dfs.ComponentCount);
                return;
            }

            Assert.True(0 < dfs.ComponentCount);
            Assert.True(dfs.ComponentCount <= g.VertexCount);
            foreach (var kv in dfs.Components)
            {
                Assert.True(0 <= kv.Value);
                Assert.True(kv.Value < dfs.ComponentCount);
            }

            foreach (var vertex in g.Vertices)
            {
                foreach (var edge in g.AdjacentEdges(vertex))
                {
                    Assert.Equal(dfs.Components[edge.Source], dfs.Components[edge.Target]);
                }
            }
        }
Beispiel #3
0
        public void Compute <TVertex, TEdge>([PexAssumeNotNull] IUndirectedGraph <TVertex, TEdge> g)
            where TEdge : IEdge <TVertex>
        {
            var dfs = new ConnectedComponentsAlgorithm <TVertex, TEdge>(g);

            dfs.Compute();
            if (g.VertexCount == 0)
            {
                Assert.IsTrue(dfs.ComponentCount == 0);
                return;
            }

            Assert.IsTrue(0 < dfs.ComponentCount);
            Assert.IsTrue(dfs.ComponentCount <= g.VertexCount);
            foreach (var kv in dfs.Components)
            {
                Assert.IsTrue(0 <= kv.Value);
                Assert.IsTrue(kv.Value < dfs.ComponentCount, "{0} < {1}", kv.Value, dfs.ComponentCount);
            }

            foreach (var vertex in g.Vertices)
            {
                foreach (var edge in g.AdjacentEdges(vertex))
                {
                    Assert.AreEqual(dfs.Components[edge.Source], dfs.Components[edge.Target]);
                }
            }
        }
        /// <summary>
        /// Dijsktra algoritam za trazenje najmanjeg rastojanja i odgovarajucih
        /// putanja. Graf mora imati sve pozitivne tezine grana ali moze da bude neusmeren
        /// i/ili da sadrzi cikluse (petlje).
        /// </summary>
        /// <param name="start"></param>
        public void Dijkstra_shortest_path(IUndirectedGraph <TVertex, TEdge> graph, TVertex start)
        {
            //Inicijalizujemo kolekcije
            Initialize(graph, start);
            minQueue.Clear();
            minQueue.Insert(start);

            while (minQueue.Count > 0)
            {
                TVertex u = minQueue.Remove();
                if (vertexColors[u] == VertexColor.Black)
                {
                    continue;
                }

                vertexColors[u] = VertexColor.Black;
                OnExamineVertex(u);

                foreach (TEdge edge in graph.AdjacentEdges(u))
                {
                    TVertex v = graph.MateOf(u, edge);
                    if (RelaxEdge(u, v, edge))
                    {
                        vertexColors[edge.Target] = VertexColor.Gray;
                        minQueue.Insert(v);
                        OnEdgeRelaxed(edge);
                    }
                }
            }
        }
        private static void Compute <TVertex, TEdge>([NotNull] IUndirectedGraph <TVertex, TEdge> graph)
            where TEdge : IEdge <TVertex>
        {
            var dfs = new ConnectedComponentsAlgorithm <TVertex, TEdge>(graph);

            dfs.Compute();
            if (graph.VertexCount == 0)
            {
                Assert.IsTrue(dfs.ComponentCount == 0);
                return;
            }

            Assert.IsTrue(0 < dfs.ComponentCount);
            Assert.IsTrue(dfs.ComponentCount <= graph.VertexCount);
            foreach (KeyValuePair <TVertex, int> pair in dfs.Components)
            {
                Assert.IsTrue(0 <= pair.Value);
                Assert.IsTrue(pair.Value < dfs.ComponentCount, $"{pair.Value} < {dfs.ComponentCount}");
            }

            foreach (TVertex vertex in graph.Vertices)
            {
                foreach (TEdge edge in graph.AdjacentEdges(vertex))
                {
                    Assert.AreEqual(dfs.Components[edge.Source], dfs.Components[edge.Target]);
                }
            }
        }
 private static void GenerateRootedTree <T>(IUndirectedGraph <Cluster <T>, ClusterEdge <T> > unrootedTree, Cluster <T> parent, Cluster <T> node, BidirectionalGraph <Cluster <T>, ClusterEdge <T> > rootedTree)
 {
     foreach (ClusterEdge <T> edge in unrootedTree.AdjacentEdges(node).Where(e => e.GetOtherVertex(node) != parent))
     {
         Cluster <T> otherCluster = edge.GetOtherVertex(node);
         rootedTree.AddVertex(otherCluster);
         rootedTree.AddEdge(new ClusterEdge <T>(node, otherCluster, edge.Length));
         GenerateRootedTree(unrootedTree, node, otherCluster, rootedTree);
     }
 }
        public static void ContainsEdgeAssertions(
            [NotNull] IUndirectedGraph <int, IEdge <int> > graph,
            [NotNull] IEdge <int> e12,
            [NotNull] IEdge <int> f12,
            [CanBeNull] IEdge <int> e21,
            [CanBeNull] IEdge <int> f21)
        {
            Assert.AreEqual(1, graph.AdjacentDegree(1));
            Assert.AreEqual(1, graph.AdjacentDegree(2));
            Assert.AreEqual(1, graph.AdjacentEdges(1).Count());
            Assert.AreEqual(1, graph.AdjacentEdges(2).Count());

            // e12 must be present in u, because we added it.
            Assert.IsTrue(graph.ContainsEdge(e12));

            // f12 is also in u, because e12 == f12.
            Assert.IsTrue(graph.ContainsEdge(f12));

            // e21 and f21 are not in u, because ContainsEdge has semantics that
            // if it returns true for an edge, that edge must be physically present in
            // the collection of edges inside u.
            if (e21 != null)
            {
                Assert.IsFalse(graph.ContainsEdge(e21));
            }
            if (f21 != null)
            {
                Assert.IsFalse(graph.ContainsEdge(f21));
            }

            // There must be an edge between vertices 1, 2.
            Assert.IsTrue(graph.ContainsEdge(1, 2));

            // There is also an edge between vertices 2, 1, because the graph is undirected.
            Assert.IsTrue(graph.ContainsEdge(2, 1));

            // Obviously no edge between vertices 1, 3, as vertex 3 is not even present in the graph.
            Assert.IsFalse(graph.ContainsEdge(1, 3));
        }
Beispiel #8
0
 private static void GenerateHierarchicalVertices(BidirectionalGraph <HierarchicalGraphVertex, HierarchicalGraphEdge> graph, HierarchicalGraphVertex vertex,
                                                  IUndirectedGraph <Cluster <Variety>, ClusterEdge <Variety> > tree, Cluster <Variety> parent, Cluster <Variety> cluster)
 {
     foreach (ClusterEdge <Variety> edge in tree.AdjacentEdges(cluster).Where(e => e.GetOtherVertex(cluster) != parent))
     {
         Cluster <Variety> target = edge.GetOtherVertex(cluster);
         double            depth  = vertex.Depth + edge.Length;
         var newVertex            = target.DataObjects.Count == 1 ? new HierarchicalGraphVertex(target.DataObjects.First(), depth) : new HierarchicalGraphVertex(depth);
         graph.AddVertex(newVertex);
         graph.AddEdge(new HierarchicalGraphEdge(vertex, newVertex, edge.Length));
         GenerateHierarchicalVertices(graph, newVertex, tree, cluster, target);
     }
 }
        public ArrayUndirectedGraph(
            IUndirectedGraph <TVertex, TEdge> graph)
        {
            Contract.Requires(graph != null);

            this.edgeEqualityComparer = graph.EdgeEqualityComparer;
            this.edgeCount            = graph.EdgeCount;
            this.vertexEdges          = new Dictionary <TVertex, TEdge[]>(graph.VertexCount);
            foreach (var v in graph.Vertices)
            {
                var edges = Enumerable.ToArray(graph.AdjacentEdges(v));
                this.vertexEdges.Add(v, edges);
            }
        }
        private static void AssertSameProperties <TVertex, TEdge>(IUndirectedGraph <TVertex, TEdge> graph)
            where TEdge : IEdge <TVertex>
        {
            ArrayUndirectedGraph <TVertex, TEdge> undirectedGraph = graph.ToArrayUndirectedGraph();

            Assert.AreEqual(graph.VertexCount, undirectedGraph.VertexCount);
            CollectionAssert.AreEqual(graph.Vertices, undirectedGraph.Vertices);

            Assert.AreEqual(graph.EdgeCount, undirectedGraph.EdgeCount);
            CollectionAssert.AreEqual(graph.Edges, undirectedGraph.Edges);

            foreach (TVertex vertex in graph.Vertices)
            {
                CollectionAssert.AreEqual(graph.AdjacentEdges(vertex), undirectedGraph.AdjacentEdges(vertex));
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ArrayUndirectedGraph{TVertex,TEdge}"/> class.
        /// </summary>
        /// <param name="visitedGraph">Graph to visit.</param>
        public ArrayUndirectedGraph([NotNull] IUndirectedGraph <TVertex, TEdge> visitedGraph)
        {
            if (visitedGraph is null)
            {
                throw new ArgumentNullException(nameof(visitedGraph));
            }

            EdgeEqualityComparer = visitedGraph.EdgeEqualityComparer;
            EdgeCount            = visitedGraph.EdgeCount;
            _vertexEdges         = new Dictionary <TVertex, TEdge[]>(visitedGraph.VertexCount);
            foreach (TVertex vertex in visitedGraph.Vertices)
            {
                _vertexEdges.Add(
                    vertex,
                    visitedGraph.AdjacentEdges(vertex).ToArray());
            }
        }
Beispiel #12
0
        public static bool PathExistsInGraph(IUndirectedGraph<int, IUndirectedEdge<int>> graph, IEnumerable<IContent> path)
        {
            var pathList = path.ToList();
            if (!graph.ContainsVertex(pathList[0].Id)) return false;

            var nextIndex = 1;
            var node = pathList[0].Id;
            while (node != pathList.Last().Id)
            {
                var nextNode = pathList[nextIndex].Id;
                if (!graph.AdjacentEdges(node).Any(edge => edge.Target == nextNode || edge.Source == nextNode)) return false;
                node = nextNode;
                nextIndex++;
            }

            return true;
        }
Beispiel #13
0
        protected void SearchInternal(TVertex u)
        {
            vertexColors[u] = VertexColor.Gray;
            OnDiscoverVertex(u);

            foreach (TEdge e in graph.AdjacentEdges(u))
            {
                OnExamineEdge(e);
                TVertex v = e.Target;

                if (vertexColors[v] == VertexColor.White)
                {
                    SearchInternal(v);
                }
            }

            vertexColors[u] = VertexColor.Black;
            OnFinishVertex(u);
        }
Beispiel #14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ArrayUndirectedGraph{TVertex,TEdge}"/> class.
        /// </summary>
        /// <param name="baseGraph">Wrapped graph.</param>
        /// <exception cref="T:System.ArgumentNullException"><paramref name="baseGraph"/> is <see langword="null"/>.</exception>
        public ArrayUndirectedGraph([NotNull] IUndirectedGraph <TVertex, TEdge> baseGraph)
        {
            if (baseGraph is null)
            {
                throw new ArgumentNullException(nameof(baseGraph));
            }

            AllowParallelEdges   = baseGraph.AllowParallelEdges;
            EdgeEqualityComparer = baseGraph.EdgeEqualityComparer;
            EdgeCount            = baseGraph.EdgeCount;
            _vertexEdges         = new Dictionary <TVertex, TEdge[]>(baseGraph.VertexCount);
            foreach (TVertex vertex in baseGraph.Vertices)
            {
                _vertexEdges.Add(
                    vertex,
                    baseGraph.AdjacentEdges(vertex).ToArray());
            }

            _edges = new List <TEdge>(baseGraph.Edges);
        }
        private static double GetLongestPath <T>(IUndirectedGraph <Cluster <T>, ClusterEdge <T> > tree, Cluster <T> parent, Cluster <T> node, double len, IEnumerable <ClusterEdge <T> > path,
                                                 out Cluster <T> deepestNode, out IEnumerable <ClusterEdge <T> > deepestPath)
        {
            deepestNode = node;
            deepestPath = path;
            double maxDepth = 0;

            foreach (ClusterEdge <T> childEdge in tree.AdjacentEdges(node).Where(e => e.GetOtherVertex(node) != parent))
            {
                Cluster <T> cdn;
                IEnumerable <ClusterEdge <T> > cdp;
                double depth = GetLongestPath(tree, node, childEdge.GetOtherVertex(node), childEdge.Length, path.Concat(childEdge), out cdn, out cdp);
                if (depth >= maxDepth)
                {
                    deepestNode = cdn;
                    maxDepth    = depth;
                    deepestPath = cdp;
                }
            }
            return(maxDepth + len);
        }
Beispiel #16
0
        public void Search(IUndirectedGraph <TVertex, TEdge> graph, IEnumerable <TVertex> roots = null)
        {
            Initialize(graph);

            if (roots == null || roots.Count() == 0)
            {
                throw new ArgumentException("Root nodes must be supplied to bfs search in undirected graph.");
            }

            foreach (var root in roots)
            {
                vertexColors[root] = VertexColor.Gray;
                OnDiscoverVertex(root);
            }

            Queue <TVertex> queue = new Queue <TVertex>(roots);

            while (queue.Count > 0)
            {
                TVertex u = queue.Dequeue();
                OnExamineVertex(u);

                foreach (TEdge e in graph.AdjacentEdges(u))
                {
                    TVertex v = e.Target;
                    OnExamineEdge(e);

                    if (vertexColors[v] == VertexColor.White)
                    {
                        vertexColors[v] = VertexColor.Gray;
                        OnDiscoverVertex(v);
                        queue.Enqueue(v);
                    }
                }

                vertexColors[u] = VertexColor.Black;
                OnFinishVertex(u);
            }
        }
Beispiel #17
0
        private static void GenerateHierarchicalVertices(BidirectionalGraph<HierarchicalGraphVertex, HierarchicalGraphEdge> graph, HierarchicalGraphVertex vertex,
			IUndirectedGraph<Cluster<Variety>, ClusterEdge<Variety>> tree, Cluster<Variety> parent, Cluster<Variety> cluster)
        {
            foreach (ClusterEdge<Variety> edge in tree.AdjacentEdges(cluster).Where(e => e.GetOtherVertex(cluster) != parent))
            {
                Cluster<Variety> target = edge.GetOtherVertex(cluster);
                double depth = vertex.Depth + edge.Length;
                var newVertex = target.DataObjects.Count == 1 ? new HierarchicalGraphVertex(target.DataObjects.First(), depth) : new HierarchicalGraphVertex(depth);
                graph.AddVertex(newVertex);
                graph.AddEdge(new HierarchicalGraphEdge(vertex, newVertex, edge.Length));
                GenerateHierarchicalVertices(graph, newVertex, tree, cluster, target);
            }
        }
        public static void ContainsEdgeAssertions(IUndirectedGraph<int, IEdge<int>> g,
            IEdge<int> e12,
            IEdge<int> f12,
            IEdge<int> e21,
            IEdge<int> f21)
        {
            Assert.AreEqual(1, g.AdjacentDegree(1));
            Assert.AreEqual(1, g.AdjacentDegree(2));
            Assert.AreEqual(1, g.AdjacentEdges(1).Count());
            Assert.AreEqual(1, g.AdjacentEdges(2).Count());

            // e12 must be present in u, because we added it.
            Assert.IsTrue(g.ContainsEdge(e12));

            // f12 is also in u, because e12 == f12.
            Assert.IsTrue(g.ContainsEdge(f12));

            // e21 and f21 are not in u, because ContainsEdge has semantics that 
            // if it returns true for an edge, that edge must be physically present in 
            // the collection of edges inside u.
            if (e21 != null) Assert.IsFalse(g.ContainsEdge(e21));
            if (f21 != null) Assert.IsFalse(g.ContainsEdge(f21));

            // there must be an edge between vertices 1, 2.
            Assert.IsTrue(g.ContainsEdge(1, 2));

            // there is also an edge between vertices 2, 1, because the graph is undirected.
            Assert.IsTrue(g.ContainsEdge(2, 1));

            // obviously no edge between vertices 1, 3, as vertex 3 is not even present in the graph.
            Assert.IsFalse(g.ContainsEdge(1, 3));
        }