Ejemplo n.º 1
0
        public void Prim12240()
        {
            var g = new UndirectedGraph <int, Edge <int> >();

            // (1,2), (3,2),(3,4),(1,4)
            g.AddVerticesAndEdge(new Edge <int>(1, 2));
            g.AddVerticesAndEdge(new Edge <int>(3, 2));
            g.AddVerticesAndEdge(new Edge <int>(3, 4));
            g.AddVerticesAndEdge(new Edge <int>(1, 4));

            var cost = CompareRoot(g);

            Assert.AreEqual(9, cost);
        }
Ejemplo n.º 2
0
        public void Clear()
        {
            int verticesRemoved = 0;
            int edgesRemoved    = 0;

            var graph = new UndirectedGraph <int, Edge <int> >();

            // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local
            graph.VertexRemoved += v =>
            {
                Assert.IsNotNull(v);
                // ReSharper disable once AccessToModifiedClosure
                ++verticesRemoved;
            };
            // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local
            graph.EdgeRemoved += e =>
            {
                Assert.IsNotNull(e);
                // ReSharper disable once AccessToModifiedClosure
                ++edgesRemoved;
            };

            AssertEmptyGraph(graph);

            graph.Clear();
            AssertEmptyGraph(graph);
            CheckCounters(0, 0);

            graph.AddVerticesAndEdge(new Edge <int>(1, 2));
            graph.AddVerticesAndEdge(new Edge <int>(2, 3));
            graph.AddVerticesAndEdge(new Edge <int>(3, 1));

            graph.Clear();
            AssertEmptyGraph(graph);
            CheckCounters(3, 3);

            #region Local function

            void CheckCounters(int expectedVerticesRemoved, int expectedEdgesRemoved)
            {
                Assert.AreEqual(expectedVerticesRemoved, verticesRemoved);
                Assert.AreEqual(expectedEdgesRemoved, edgesRemoved);
                verticesRemoved = 0;
                edgesRemoved    = 0;
            }

            #endregion
        }
Ejemplo n.º 3
0
        // Cria objeto QuickGraph
        private void CriaObjQuickGraph()
        {
            //QuickGraph
            _quickGraph = new UndirectedGraph <string, Edge <string> >();

            // map de custos
            _edgeCost = new Dictionary <Edge <string>, double>();

            // para todos os elementos da matriz de incidencia
            foreach (KeyValuePair <string, List <string> > kvp in _matrizIncidencia)
            {
                // aresta
                string sAresta1 = kvp.Key;

                // vertices
                string vertice1 = (kvp.Value)[0];
                string vertice2 = (kvp.Value)[1];

                //cria aresta
                Edge <string> aresta = new Edge <string>(vertice1, vertice2);

                // Adiciona vertices e arestas
                _quickGraph.AddVerticesAndEdge(aresta);

                // Custo de todas as arestas eh 1
                _edgeCost.Add(aresta, 1);
            }
        }
Ejemplo n.º 4
0
        public void clearTest()
        {
            var graph = new UndirectedGraph <int, IEdge <int> >();

            graph.AddVerticesAndEdge(new EquatableEdge <int>(1, 2));
            graph.AddVerticesAndEdge(new EquatableEdge <int>(2, 3));
            Assert.AreEqual(graph.EdgeCount, 2);
            Assert.AreEqual(graph.VertexCount, 3);
            Assert.IsFalse(graph.IsEdgesEmpty);
            Assert.IsFalse(graph.IsVerticesEmpty);
            graph.Clear();
            Assert.AreEqual(graph.EdgeCount, 0);
            Assert.AreEqual(graph.VertexCount, 0);
            Assert.IsTrue(graph.IsEdgesEmpty);
            Assert.IsTrue(graph.IsVerticesEmpty);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Reads the content of the file whose name is supplied and constructs the nodes and edges for
        /// the given <paramref name="newGRaphInstance"/>. It is assumed the file uploaded contains edges
        /// (pairs of nodes connecting with each other).
        /// </summary>
        /// <param name="filename">The uploaded filename</param>
        /// <param name="newGraphInstance"></param>
        /// <returns>A string containing feedback of the processing</returns>
        private static string LoadGraph <T>(string filename, UndirectedGraph <T> newGraphInstance)
        {
            var       lines = File.ReadAllLines(filename);
            Stopwatch sw    = Stopwatch.StartNew();

            //Parallelizing this actually made it take longer to process my datasets
            string[] tmp;
            T        temp_node;
            T        temp_node2;

            foreach (var line in lines)
            {
                if (line.StartsWith("#"))
                {
                    continue;
                }
                tmp        = line.Split(new string[] { " ", "\t" }, StringSplitOptions.None);
                temp_node  = (T)Convert.ChangeType(tmp[0], typeof(T));
                temp_node2 = (T)Convert.ChangeType(tmp[1], typeof(T));

                newGraphInstance.AddVerticesAndEdge(new Edge <T>(temp_node, temp_node2));
            }
            sw.Stop();
            filename = new FileInfo(filename).Name;
            var nodeCount = newGraphInstance.VertexCount;
            var edgeCount = newGraphInstance.EdgeCount;
            var inv       = (nodeCount * nodeCount) / edgeCount;
            var sparse    = inv > 64;
            var invDeg    = string.Format("{0} ({1} Graph)", inv, inv > 64 ? "Sparse" : "Dense");

            return($"\tFile loaded: {filename}\n\nNumber of lines in file:\t{edgeCount}\nNumber of nodes:\t\t{nodeCount}\nInv Degree:\t{invDeg}\nTime Taken to Process:\t{sw.ElapsedMilliseconds:N2} ms");
        }
Ejemplo n.º 6
0
        private void RefreshAdjacencyList()
        {
            _adjacencyGraph.Clear();
            var finishedVertices = new HashSet <Piece>();

            foreach (KeyValuePair <Piece, Hex> kvp in _playedPieces)
            {
                foreach (Hex directionHex in Neighborhood.neighborDirections)
                {
                    // don't do the center
                    if (directionHex.Equals(new Hex(0, 0)))
                    {
                        continue;
                    }

                    Hex   adjacentHex = kvp.Value + directionHex;
                    Piece adjacentPiece;
                    if (TryGetPieceAtHex(adjacentHex, out adjacentPiece))
                    {
                        if (!finishedVertices.Contains(adjacentPiece))
                        {
                            _adjacencyGraph.AddVerticesAndEdge(new UndirectedEdge <Piece>(kvp.Key, adjacentPiece));
                        }
                    }
                }
                finishedVertices.Add(kvp.Key);
            }
        }
Ejemplo n.º 7
0
        public void generateUndirectedGraph(int FedID, string networkName)
        {
            string sqlStmt = "SELECT a.node_id, b.elementid, b.elementtype, b.name, b.body_major_axis_centroid from " + DBOperation.formatTabName(networkName) + "_node$ a, "
                             + "bimrl_element_" + FedID.ToString("X4") + " b where a.node_name = b.elementid";
            OracleCommand command = new OracleCommand(sqlStmt, DBOperation.DBConn);

            try
            {
                // Populate Dict with node information (with basic information from BIMRL_ELEMENT)
                OracleDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    int    nodeID   = reader.GetInt32(0);
                    string elemID   = reader.GetString(1);
                    string elemType = reader.GetString(2);
                    string name     = string.Empty;
                    if (!reader.IsDBNull(3))
                    {
                        name = reader.GetString(3);
                    }
                    Point3D centroid = null;
                    if (!reader.IsDBNull(4))
                    {
                        SdoGeometry sdogeom = reader.GetValue(4) as SdoGeometry;
                        centroid = new Point3D(sdogeom.SdoPoint.XD.Value, sdogeom.SdoPoint.YD.Value, sdogeom.SdoPoint.ZD.Value);
                    }
                    NodeDict.Add(nodeID, new Tuple <string, string, string, Point3D>(elemID, elemType, name, centroid));
                    ElemIDToNodeIDDict.Add(elemID, nodeID);
                }
                reader.Dispose();

                // generate the graph
                sqlStmt             = "Select link_id, start_node_id, end_node_id from " + DBOperation.formatTabName(networkName) + "_link$ where active='Y'";
                command.CommandText = sqlStmt;
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    int linkID    = reader.GetInt32(0);
                    int startNode = reader.GetInt32(1);
                    int endNode   = reader.GetInt32(2);

                    var edge = new TaggedEdge <int, int>(startNode, endNode, linkID);
                    graph.AddVerticesAndEdge(edge);
                }
                reader.Dispose();
                command.Dispose();
            }
            catch (OracleException e)
            {
                string excStr = "%%Error - " + e.Message + "\n\t" + sqlStmt;
                refBimrlCommon.StackPushError(excStr);
                command.Dispose();
            }
            catch (SystemException e)
            {
                string excStr = "%%Error - " + e.Message + "\n\t" + sqlStmt;
                refBimrlCommon.StackPushError(excStr);
                throw;
            }
        }
 private UndirectedGraph<int, TaggedUndirectedEdge<int, double>> createGraph(List<TaggedUndirectedEdge<int, double>> edges)
 {
     var g = new UndirectedGraph<int, TaggedUndirectedEdge<int, double>>(true);
     foreach (TaggedUndirectedEdge<int, double> edge in edges)
     {
         g.AddVerticesAndEdge(edge);
     }
     return g;
 }
 private UndirectedGraph<int, UndirectedEdge<int>> constructGraph(Tuple<int, int>[] vertices)
 {
     var g = new UndirectedGraph<int, UndirectedEdge<int>>();
     foreach (var pair in vertices)
     {
         g.AddVerticesAndEdge(new UndirectedEdge<int>(pair.Item1, pair.Item2));
     }
     return g;
 }
Ejemplo n.º 10
0
        private UndirectedGraph <int, UndirectedEdge <int> > constructGraph(Tuple <int, int>[] vertices)
        {
            var g = new UndirectedGraph <int, UndirectedEdge <int> >();

            foreach (var pair in vertices)
            {
                g.AddVerticesAndEdge(new UndirectedEdge <int>(pair.Item1, pair.Item2));
            }
            return(g);
        }
Ejemplo n.º 11
0
        private UndirectedGraph <int, TaggedUndirectedEdge <int, double> > createGraph(List <TaggedUndirectedEdge <int, double> > edges)
        {
            var g = new UndirectedGraph <int, TaggedUndirectedEdge <int, double> >(true);

            foreach (TaggedUndirectedEdge <int, double> edge in edges)
            {
                g.AddVerticesAndEdge(edge);
            }
            return(g);
        }
Ejemplo n.º 12
0
        public void ContainsEdge_UndirectedEdge()
        {
            var graph = new UndirectedGraph <int, IEdge <int> >();
            var e12   = new EquatableUndirectedEdge <int>(1, 2);
            var f12   = new EquatableUndirectedEdge <int>(1, 2);

            graph.AddVerticesAndEdge(e12);

            ContainsEdgeAssertions(graph, e12, f12, null, null);
        }
Ejemplo n.º 13
0
        public static (List <HashSet <int> >, UndirectedGraph <int, IEdge <int> >, Dictionary <int, (int, int)>) GetBFSTree(UndirectedGraph <int, IEdge <int> > graph, int root)
        {
            UndirectedGraph <int, IEdge <int> > BFSTree = new UndirectedGraph <int, IEdge <int> >(false);
            List <HashSet <int> >        levels         = new List <HashSet <int> >();
            Dictionary <int, (int, int)> dict           = new Dictionary <int, (int, int)>();

            HashSet <int> enqueued         = new HashSet <int>();
            int           level            = 0;
            int           intNumberOnLevel = 0;

            levels.Add(new HashSet <int>());

            Queue <int> queue         = new Queue <int>();
            int         nextLevelMark = -1;

            queue.Enqueue(root);
            enqueued.Add(root);
            queue.Enqueue(nextLevelMark);

            while (queue.Count > 0)
            {
                int v = queue.Dequeue();

                //Moving to next level
                if (v == nextLevelMark)
                {
                    level++;
                    if (queue.Count == 0)
                    {
                        break;
                    }
                    queue.Enqueue(nextLevelMark);
                    levels.Add(new HashSet <int>());
                    intNumberOnLevel = 0;
                    continue;
                }

                levels[level].Add(v);
                dict.Add(v, (level, intNumberOnLevel));
                intNumberOnLevel++;

                //Add all v neighbours to queue
                foreach (IEdge <int> e in graph.AdjacentEdges(v))
                {
                    if (!enqueued.Contains(e.GetOtherVertex(v)))
                    {
                        queue.Enqueue(e.GetOtherVertex(v));
                        enqueued.Add(e.GetOtherVertex(v));
                        BFSTree.AddVerticesAndEdge(new Edge <int>(v, e.GetOtherVertex(v)));
                    }
                }
            }
            levels.Add(new HashSet <int>());
            return(levels, BFSTree, dict);
        }
        private static UndirectedGraph <int, UndirectedEdge <int> > ConstructGraph([NotNull] IEnumerable <Vertices> vertices)
        {
            var graph = new UndirectedGraph <int, UndirectedEdge <int> >();

            foreach (Vertices pair in vertices)
            {
                graph.AddVerticesAndEdge(new UndirectedEdge <int>(pair.Source, pair.Target));
            }

            return(graph);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Add a room connection to the map. New nodes will be created for previously unseen rooms
        /// </summary>
        /// <param name="startRoom"></param>
        /// <param name="endRoom"></param>
        public void AddRoomConnection(int startRoom, int endRoom)
        {
            try
            {
                TaggedEdge <int, string> possibleEdge = null;

                baseGraph.TryGetEdge(startRoom, endRoom, out possibleEdge);

                if (possibleEdge == null)
                {
                    baseGraph.AddVerticesAndEdge(new TaggedEdge <int, string>(startRoom, endRoom, ""));
                }
            }
            catch (KeyNotFoundException)
            {
                //Vertex not in graph, OK to add
                baseGraph.AddVerticesAndEdge(new TaggedEdge <int, string>(startRoom, endRoom, ""));
            }
            //Other exceptions passed up
        }
Ejemplo n.º 16
0
        public void ContainsEdgeTest2()
        {
            var u   = new UndirectedGraph <int, IEdge <int> >();
            var e12 = new EquatableEdge <int>(1, 2);
            var f12 = new EquatableEdge <int>(1, 2);
            var e21 = new EquatableEdge <int>(2, 1);
            var f21 = new EquatableEdge <int>(2, 1);

            u.AddVerticesAndEdge(e12);

            ContainsEdgeAssertions(u, e12, f12, e21, f21);
        }
        private static UndirectedGraph <int, TaggedUndirectedEdge <int, double> > CreateGraph(
            [NotNull, ItemNotNull] IEnumerable <TaggedUndirectedEdge <int, double> > edges)
        {
            var graph = new UndirectedGraph <int, TaggedUndirectedEdge <int, double> >(true);

            foreach (TaggedUndirectedEdge <int, double> edge in edges)
            {
                graph.AddVerticesAndEdge(edge);
            }

            return(graph);
        }
        public static UndirectedGraph <int, UndirectedEdge <int> > CreateUndirectedGraph(
            IEnumerable <Vertices> vertices)
        {
            var graph = new UndirectedGraph <int, UndirectedEdge <int> >();

            foreach (Vertices pair in vertices)
            {
                graph.AddVerticesAndEdge(new UndirectedEdge <int>(pair.Source, pair.Target));
            }

            return(graph);
        }
Ejemplo n.º 19
0
        public void ContainsEdge_DirectedEdge()
        {
            var graph = new UndirectedGraph <int, IEdge <int> >();
            var e12   = new EquatableEdge <int>(1, 2);
            var f12   = new EquatableEdge <int>(1, 2);
            var e21   = new EquatableEdge <int>(2, 1);
            var f21   = new EquatableEdge <int>(2, 1);

            graph.AddVerticesAndEdge(e12);

            ContainsEdgeAssertions(graph, e12, f12, e21, f21);
        }
        private static IList <Edge> ComputeShortestPath(Edge branch, IEnumerable <Edge> delaunyEdges, Matrix volumeIndexToNormalizedVolumeCoordinates)
        {
            var graph = new UndirectedGraph <Vector3, Edge <Vector3> >();

            foreach (var delaunyEdge in delaunyEdges)
            {
                graph.AddVerticesAndEdge(new Edge <Vector3>(delaunyEdge.P1, delaunyEdge.P2));
            }

            var dijkstraShortestPathAlgorithm = new UndirectedDijkstraShortestPathAlgorithm <Vector3, Edge <Vector3> >(graph, edge => CalculateEdgeWeights(edge, volumeIndexToNormalizedVolumeCoordinates));
            var visitor = new UndirectedVertexPredecessorRecorderObserver <Vector3, Edge <Vector3> >();

            using (visitor.Attach(dijkstraShortestPathAlgorithm))
            {
                dijkstraShortestPathAlgorithm.Compute(branch.P1);
            }

            IEnumerable <Edge <Vector3> > shortestPath;

            visitor.TryGetPath(branch.P2, out shortestPath);

            var edgeList         = (from edge in shortestPath select new Edge {
                P1 = edge.Source, P2 = edge.Target
            }).ToList();
            var orientedEdgeList = new List <Edge>();

            var edgeListP1 = edgeList[0].P1;
            var edgeListP2 = edgeList[0].P2;

            orientedEdgeList.Add(!edgeList[0].P1.Equals(branch.P1)
                                      ? new Edge {
                P1 = edgeListP2, P2 = edgeListP1
            }
                                      : new Edge {
                P1 = edgeListP1, P2 = edgeListP2
            });

            for (int i = 1; i < edgeList.Count; i++)
            {
                edgeListP1 = edgeList[i].P1;
                edgeListP2 = edgeList[i].P2;

                orientedEdgeList.Add(!edgeList[i].P1.Equals(orientedEdgeList[i - 1].P2)
                                          ? new Edge {
                    P1 = edgeListP2, P2 = edgeListP1
                }
                                          : new Edge {
                    P1 = edgeListP1, P2 = edgeListP2
                });
            }

            return(orientedEdgeList);
        }
Ejemplo n.º 21
0
        public void Run()
        {
            var g = new UndirectedGraph <int, TaggedUndirectedEdge <int, int> >();

            var e1 = new TaggedUndirectedEdge <int, int>(1, 2, 57);
            var e2 = new TaggedUndirectedEdge <int, int>(1, 4, 65);
            var e3 = new TaggedUndirectedEdge <int, int>(2, 3, 500);
            var e4 = new TaggedUndirectedEdge <int, int>(2, 4, 1);
            var e5 = new TaggedUndirectedEdge <int, int>(3, 4, 78);
            var e6 = new TaggedUndirectedEdge <int, int>(3, 5, 200);

            g.AddVerticesAndEdge(e1);
            g.AddVerticesAndEdge(e2);
            g.AddVerticesAndEdge(e3);
            g.AddVerticesAndEdge(e4);
            g.AddVerticesAndEdge(e5);
            g.AddVerticesAndEdge(e6);

            foreach (var v in g.Edges)
            {
                Console.WriteLine(v);
            }
            Console.WriteLine("--------");
            //Func<TaggedUndirectedEdge<int, int>, double> edgeWeights = (q) =>
            //{
            //    g.Edges.SingleOrDefault(m => q == m).Tag;
            //};

            var mst = g.MinimumSpanningTreePrim(e => e.Tag).ToList();

            foreach (var v in mst)
            {
                Console.WriteLine(v);
            }
        }
Ejemplo n.º 22
0
 public RandomPlanar(double density, Random random)
 {
     _density    = Math.Clamp(density, 0, 1);
     this.random = random;
     Graph       = new UndirectedGraph <int, IEdge <int> >();
     Graph.AddVerticesAndEdge(new Edge <int>(0, 1));
     _faces = new List <Face>()
     {
         new Face(random, new List <int> {
             0, 1
         })
     };
 }
Ejemplo n.º 23
0
        public void GetVertexColor()
        {
            var graph = new UndirectedGraph <int, Edge <int> >();

            graph.AddVerticesAndEdge(new Edge <int>(1, 2));

            var algorithm = new UndirectedDijkstraShortestPathAlgorithm <int, Edge <int> >(graph, edge => 1.0);

            algorithm.Compute(1);

            Assert.AreEqual(GraphColor.Black, algorithm.GetVertexColor(1));
            Assert.AreEqual(GraphColor.Black, algorithm.GetVertexColor(2));
        }
Ejemplo n.º 24
0
        public static UndirectedGraph <TVertex, TEdge> CreateUndirectedGraph <TVertex, TEdge>(
            [NotNull, ItemNotNull] IEnumerable <TEdge> edges)
            where TEdge : IEdge <TVertex>, ITagged <double>
        {
            var graph = new UndirectedGraph <TVertex, TEdge>(true);

            foreach (TEdge edge in edges)
            {
                graph.AddVerticesAndEdge(edge);
            }

            return(graph);
        }
Ejemplo n.º 25
0
        public void removeIsolatedVertices()
        {
            var graph = new UndirectedGraph <int, IEdge <int> >();

            graph.AddVertex(1);
            var edge = new EquatableEdge <int>(2, 3);

            graph.AddVerticesAndEdge(edge);
            graph.RemoveVertexIf(graph.IsAdjacentEdgesEmpty);
            Assert.IsTrue(graph.ContainsVertex(2));
            Assert.IsTrue(graph.ContainsEdge(edge));
            Assert.IsTrue(graph.ContainsEdge(2, 3));
            Assert.IsTrue(graph.ContainsEdge(3, 2));
            Assert.IsFalse(graph.ContainsVertex(1));
        }
Ejemplo n.º 26
0
        private static UndirectedGraph <int, Edge <int> > GetGraphFromEdges(IEnumerable <Edge <int> > edges)
        {
            //var edgeComparer = new EdgeComparer();
            var graphFromEdges = new UndirectedGraph <int, Edge <int> >();

            foreach (var edge in edges)
            {
                graphFromEdges.AddVerticesAndEdge(edge);
            }
            if (graphFromEdges.EdgeCount != edges.Count())
            {
                throw new ArgumentException("AugmentingPathGraph creation error");
            }
            return(graphFromEdges);
        }
Ejemplo n.º 27
0
        public void toBidirectionalGraphTest()
        {
            var graph = new UndirectedGraph <int, IEdge <int> >();

            graph.AddVertex(1);
            var edge = new EquatableEdge <int>(2, 3);

            graph.AddVerticesAndEdge(edge);
            var bidirectionalGraph = graph.ToBidirectionalGraph();

            Assert.IsTrue(bidirectionalGraph.ContainsVertex(1));
            Assert.IsTrue(bidirectionalGraph.ContainsVertex(2));
            Assert.IsTrue(bidirectionalGraph.ContainsVertex(3));
            Assert.IsTrue(bidirectionalGraph.ContainsEdge(2, 3));
            Assert.IsFalse(bidirectionalGraph.ContainsEdge(3, 2));
        }
Ejemplo n.º 28
0
        public void UndirectedEdgesMayBeFoundInEitherOrientation()
        {
            var mapNoCycles = new UndirectedGraph <int, TaggedEdge <int, string> >();

            mapNoCycles.AddVerticesAndEdge(new TaggedEdge <int, string>(1, 2, ""));

            TaggedEdge <int, string> possibleEdge = null;

            mapNoCycles.TryGetEdge(2, 1, out possibleEdge);
            Assert.IsNotNull(possibleEdge);

            TaggedEdge <int, string> possibleEdge2 = null;

            mapNoCycles.TryGetEdge(1, 2, out possibleEdge2);
            Assert.IsNotNull(possibleEdge2);
        }
Ejemplo n.º 29
0
        public void GetVertexColor()
        {
            var graph = new UndirectedGraph <int, Edge <int> >();

            graph.AddVerticesAndEdge(new Edge <int>(1, 2));

            var algorithm = new UndirectedBreadthFirstSearchAlgorithm <int, Edge <int> >(graph);

            // Algorithm not run
            // ReSharper disable once ReturnValueOfPureMethodIsNotUsed
            Assert.Throws <VertexNotFoundException>(() => algorithm.GetVertexColor(1));

            algorithm.Compute(1);

            Assert.AreEqual(GraphColor.Black, algorithm.GetVertexColor(1));
            Assert.AreEqual(GraphColor.Black, algorithm.GetVertexColor(2));
        }
Ejemplo n.º 30
0
        public void RemoveEdges_Throws()
        {
            int verticesRemoved = 0;
            int edgesRemoved    = 0;

            var graph = new UndirectedGraph <int, Edge <int> >();

            // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local
            graph.VertexRemoved += v =>
            {
                Assert.IsNotNull(v);
                ++verticesRemoved;
            };

            // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local
            graph.EdgeRemoved += e =>
            {
                Assert.IsNotNull(e);
                ++edgesRemoved;
            };

            var edge = new Edge <int>(1, 2);

            graph.AddVerticesAndEdge(edge);

            // ReSharper disable once AssignNullToNotNullAttribute
            Assert.Throws <ArgumentNullException>(() => graph.RemoveEdges(null));
            AssertHasEdges(graph, new[] { edge });
            CheckCounters();

            Assert.Throws <ArgumentNullException>(() => graph.RemoveEdges(new[] { edge, null }));
            Assert.AreEqual(0, edgesRemoved);
            AssertHasEdges(graph, new[] { edge });
            CheckCounters();

            #region Local function

            void CheckCounters()
            {
                Assert.AreEqual(0, verticesRemoved);
                Assert.AreEqual(0, edgesRemoved);
            }

            #endregion
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Reads the content of the file whose name is supplied and constructs the nodes and edges for
        /// the given <paramref name="newGRaphInstance"/>. It is assumed the file uploaded contains edges
        /// (pairs of nodes connecting with each other).
        /// </summary>
        /// <param name="filename">The uploaded filename</param>
        /// <returns>A string containing feedback of the processing</returns>
        public static UndirectedGraph <int> LoadGraph(string[] lines)
        {
            //since system io is not used, lines is given as an array of the lines in the txt file
            //just like what readalllines does
            //do note that the first line in the file was not read

            //var lines = File.ReadAllLines(filename);

            UndirectedGraph <int> newGraphInstance;

            newGraphInstance = new UndirectedGraph <int>();
            //not needed since demo doesnt use q graphs
            //if (isQueryGraph)
            //{
            //    //newGraphInstance = new QueryGraph(Path.GetFileNameWithoutExtension(filename))
            //    //{
            //    //};
            //}
            //else
            //{
            //    newGraphInstance = new UndirectedGraph<int>();
            //}
            //Parallelizing this actually made it take longer to process my datasets
            string[] tmp;
            foreach (var line in lines)
            {
                if (line.StartsWith("#"))
                {
                    continue;
                }
                tmp = line.Split(new string[] { " ", "\t" }, StringSplitOptions.RemoveEmptyEntries);
                if (tmp.Length < 2)
                {
                    continue;
                }

                //newGraphInstance.AddVerticesAndEdge(new Edge<int>(tmp[0], tmp[1]));
                newGraphInstance.AddVerticesAndEdge(int.Parse(tmp[0]), int.Parse(tmp[1]));
            }
            return(newGraphInstance);
        }
        public HashSet<HashSet<int>> GetMaxDomaticPartition(int[] vertices, Tuple<int, int>[] edges)
        {
            var graph = new UndirectedGraph<int, Edge<int>>();
            graph.AddVertexRange(vertices);
            foreach (var edge in edges)
            {
                graph.AddVerticesAndEdge(new Edge<int>(edge.Item1, edge.Item2));
            }

            var algo = new DomaticPartition<int, Edge<int>>(graph);
            IEnumerable<IEnumerable<int>> partition = algo.GetMaxSizePartition();

            var hashsetPartition = new HashSet<HashSet<int>>();
            foreach (var set in partition)
            {
                var curSet = new HashSet<int>(set);
                hashsetPartition.Add(curSet);
            }

            return hashsetPartition;
        }
Ejemplo n.º 33
0
        private DegeneracyResult AnalyzeDegeneracy(string file)
        {
            var graph = new UndirectedGraph <int, Edge <int> >();

            this.rowByRow(file, row =>
            {
                var split = row.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);

                int v;
                int u;

                if (split.Length != 2 || !int.TryParse(split[0], out v) || !int.TryParse(split[1], out u))
                {
                    return;
                }

                graph.AddVerticesAndEdge(new Edge <int>(u, v));
            });

            return(graph.CoreDecomposition());
        }
        public void ContainsEdgeTest1()
        {
            var u = new UndirectedGraph<int, IEdge<int>>();
            var e12 = new SEquatableUndirectedEdge<int>(1, 2);
            var f12 = new SEquatableUndirectedEdge<int>(1, 2);
                        
            bool exceptionOccurred = false;
            try
            {
                new SEquatableUndirectedEdge<int>(2, 1);
            }
            catch (ArgumentException e)
            {
                exceptionOccurred = true;
            }
            Assert.IsTrue(exceptionOccurred);

            u.AddVerticesAndEdge(e12);

            ContainsEdgeAssertions(u, e12, f12, null, null);
        }
        public void ContainsEdgeTest2()
        {
            var u = new UndirectedGraph<int, IEdge<int>>();
            var e12 = new EquatableEdge<int>(1, 2);
            var f12 = new EquatableEdge<int>(1, 2);
            var e21 = new EquatableEdge<int>(2, 1);
            var f21 = new EquatableEdge<int>(2, 1);

            u.AddVerticesAndEdge(e12);

            ContainsEdgeAssertions(u, e12, f12, e21, f21);
        }
Ejemplo n.º 36
0
        public void UndirectedEdgesMayBeFoundInEitherOrientation()
        {
            var mapNoCycles = new UndirectedGraph<int, TaggedEdge<int, string>>();

            mapNoCycles.AddVerticesAndEdge(new TaggedEdge<int, string>(1, 2, ""));

            TaggedEdge<int, string> possibleEdge = null;

            mapNoCycles.TryGetEdge(2, 1, out possibleEdge);
            Assert.IsNotNull(possibleEdge);

            TaggedEdge<int, string> possibleEdge2 = null;

            mapNoCycles.TryGetEdge(1, 2, out possibleEdge2);
            Assert.IsNotNull(possibleEdge2);
        }