private INode Emit(AST a, IGraph to) { String text = a.getText(); int iType = a.Type; String type = parserpackage.GetTypeName(iType); NodeType currentNodeType = GetNodeType(type, to); INode currentNode = to.AddNode(currentNodeType); currentNode.SetAttribute("value", text); if (a.getNumberOfChildren() > 0) { List <AST> l = GetChildren(a); INode previousChild = null; foreach (AST current in l) { INode childNode = Emit(current, to); EdgeType childType = GetEdgeType("child", to); to.AddEdge(childType, currentNode, childNode); if (previousChild != null) { EdgeType nextType = GetEdgeType("next", to); to.AddEdge(nextType, previousChild, childNode); } previousChild = childNode; } } return(currentNode); }
public void Edges_AddValid() { var vertices = Enumerable.Range(0, 100).ToList(); vertices.ForEach(x => graph.AddVertex(x)); var edges = vertices.Take(20).Select(x => new Edge <int>(x, x + 1)).ToList(); edges.ForEach(x => graph.AddEdge(x.From, x.To)); var actualEdges = graph.Edges.Select(x => new Edge <int>(x.From, x.To)); Assert.IsTrue(edges.SequenceEqualWithoutOrder(actualEdges)); }
/// <summary> /// Switches the data around for the two given vertices. /// </summary> /// <typeparam name="TEdgeData"></typeparam> /// <param name="graph"></param> /// <param name="vertex1"></param> /// <param name="vertex2"></param> public static void Switch <TEdgeData>(this IGraph <TEdgeData> graph, uint vertex1, uint vertex2) where TEdgeData : IGraphEdgeData { // get all existing data. var edges1 = new List <Edge <TEdgeData> >(graph.GetEdges(vertex1)); var edges2 = new List <Edge <TEdgeData> >(graph.GetEdges(vertex2)); float vertex1Latitude, vertex1Longitude; graph.GetVertex(vertex1, out vertex1Latitude, out vertex1Longitude); float vertex2Latitude, vertex2Longitude; graph.GetVertex(vertex2, out vertex2Latitude, out vertex2Longitude); // remove all edges. graph.RemoveEdges(vertex1); graph.RemoveEdges(vertex2); // update location. graph.SetVertex(vertex1, vertex2Latitude, vertex2Longitude); graph.SetVertex(vertex2, vertex1Latitude, vertex1Longitude); // add edges again. foreach (var edge in edges1) { // update existing data. if (edge.Neighbour == vertex1) { edge.Neighbour = vertex2; } else if (edge.Neighbour == vertex2) { edge.Neighbour = vertex1; } graph.AddEdge(vertex2, edge.Neighbour, edge.EdgeData, edge.Intermediates); } foreach (var edge in edges2) { // update existing data. if (edge.Neighbour == vertex1) { edge.Neighbour = vertex2; } else if (edge.Neighbour == vertex2) { edge.Neighbour = vertex1; } graph.AddEdge(vertex1, edge.Neighbour, edge.EdgeData, edge.Intermediates); } }
public static void buildGraph(IGraph <string> graph, List <ValueTuple <int, int, int> > edges) { foreach (var edge in edges) { graph.AddEdge(edge.Item1, edge.Item2, edge.Item3); } }
private void ReadEdge(XmlReader myReader) { var eId = myReader.GetAttribute(GraphMLTokens.ID); var sourceID = myReader.GetAttribute(GraphMLTokens.SOURCE); var targetID = myReader.GetAttribute(GraphMLTokens.TARGET); var sourceVertex = _Vertices[sourceID]; var targetVertex = _Vertices[targetID]; IEdge edge = null; if (sourceVertex != null && targetVertex != null) { edge = _Graph.AddEdge(eId, sourceVertex, targetVertex); } if (edge != null) // has been added { using (var edgeDataReader = myReader.ReadSubtree()) { while (edgeDataReader.Read()) { if (edgeDataReader.Name == GraphMLTokens.DATA) { ReadAttribute(edge, myReader); } } } } }
} //图 public SymbolGraph(string filename, string delim, SearchTableOptions options = SearchTableOptions.RedBlack) { st = SearchTableExamples.CreateSearchTable <string, int?>(options); Scanner scanner = new Scanner(new StreamReader(File.OpenRead(filename))); while (scanner.HasNextLine()) //构造索引 { string[] a = scanner.ReadLine().Split(delim); //为每个不同的字符串关联一个索引 for (int i = 0; i < a.Length; i++) { if (!st.Contains(a[i])) { st.Put(a[i], st.Size); } } } keys = new string[st.Size]; //用来获得顶点名反向索引 foreach (string name in st.Keys()) { keys[st.Get(name) ?? -1] = name; } G = new Graph(st.Size); scanner = new Scanner(new StreamReader(File.OpenRead(filename))); //第二遍 while (scanner.HasNextLine()) { string[] a = scanner.ReadLine().Split(delim); //将每一行的第一个顶点和该行的其他顶点相连 int v = st.Get(a[0]) ?? -1; for (int i = 1; i < a.Length; i++) { G.AddEdge(v, st.Get(a[i]) ?? -1); } } }
public override void Open(TextReader reader, IGraph graph) { base.Open(reader, graph); var lines = ReadAllLines(reader); var list = new List <IEnumerable <int> >(); foreach (var line in lines) { var verticesIndexes = line.Split(' ').Select(x => ParseStringTo <int>(x)); list.Add(verticesIndexes); } foreach (var column in list) { var parentVertexIndex = column.First(); var parentVertex = graph.AddVertex(parentVertexIndex); var vertices = column.Skip(1); foreach (var vertex in vertices) { var targetVertex = graph.AddVertex(vertex); graph.AddEdge(parentVertex, targetVertex, true); } } }
private IGraph <T> BuildGraph(Vertex <T> vEnd, VertexData[] vTable) { //Instantiate an instance of the child type graph using reflection thing IGraph <T> result = (IGraph <T>)GetType().Assembly. CreateInstance(this.GetType().FullName); /* * Add the end vertex to result * dataLast <-- vTable (location of vEnd) * previous <-- previous of dataLast * while previous is not null * add prevous to result * add the edge from last and previous * dataLast <-- vTable(location of previous) * previous <-- dataLast previous * return result */ result.AddVertex(vEnd.Data); VertexData dataLast = vTable[vEnd.Index]; Vertex <T> previous = dataLast.vPrevious; while (previous != null) { result.AddVertex(previous.Data); result.AddEdge(dataLast.vVertex.Data, previous.Data); dataLast = vTable[previous.Index]; previous = dataLast.vPrevious; } return(result); }
private INode Emit(AST a, IGraph to) { String text = a.getText(); int iType = a.Type; String type = parserpackage.GetTypeName(iType); NodeType currentNodeType = GetNodeType(type, to); INode currentNode = to.AddNode(currentNodeType); currentNode.SetAttribute("value", text); if (a.getNumberOfChildren() > 0) { List<AST> l = GetChildren(a); INode previousChild = null; foreach (AST current in l) { INode childNode = Emit(current, to); EdgeType childType = GetEdgeType("child", to); to.AddEdge(childType, currentNode, childNode); if (previousChild != null) { EdgeType nextType = GetEdgeType("next", to); to.AddEdge(nextType, previousChild, childNode); } previousChild = childNode; } } return currentNode; }
private void DoMapping() { var graph = mapDescription.GetGraph(); var stageOneGraph = mapDescription.GetStageOneGraph(); foreach (var vertex in graph.Vertices) { // Create vertices mapping nodeToIntMapping.Add(vertex, nodeToIntMapping.Count); mappedGraph.AddVertex(nodeToIntMapping[vertex]); // Store room description roomDescriptions[nodeToIntMapping[vertex]] = mapDescription.GetRoomDescription(vertex); } // Handle main graph edges foreach (var edge in graph.Edges) { mappedGraph.AddEdge(nodeToIntMapping[edge.From], nodeToIntMapping[edge.To]); } // Handle stage one graph vertices foreach (var vertex in stageOneGraph.Vertices) { mappedStageOneGraph.AddVertex(nodeToIntMapping[vertex]); } // Handle stage one graph edges foreach (var edge in stageOneGraph.Edges) { mappedStageOneGraph.AddEdge(nodeToIntMapping[edge.From], nodeToIntMapping[edge.To]); } }
private void DoMapping() { var graph = levelDescription.GetGraph(); var stageOneGraph = levelDescription.GetGraphWithoutCorridors(); foreach (var vertex in graph.Vertices) { var roomNode = CreateRoomNode(vertex); // Create vertices mapping mappedGraph.AddVertex(roomNode); // Store room description roomDescriptions[roomNode.Id] = levelDescription.GetRoomDescription(vertex); } // Handle main graph edges foreach (var edge in graph.Edges) { mappedGraph.AddEdge(GetRoomNode(edge.From), GetRoomNode(edge.To)); } // Handle stage one graph vertices foreach (var vertex in stageOneGraph.Vertices) { mappedStageOneGraph.AddVertex(GetRoomNode(vertex)); } // Handle stage one graph edges foreach (var edge in stageOneGraph.Edges) { mappedStageOneGraph.AddEdge(GetRoomNode(edge.From), GetRoomNode(edge.To)); } }
private string MakeGraph(IGraph <ComparableTuple> gra, string result) { for (int i = 0; i < numClusters; i++) { for (int j = 0; j < vertexPerCluster; j++) { gra.AddVertex(new ComparableTuple(i, j)); } } for (int i = 0; i < numClusters; i++) { MakeCluster(gra, i); result = result + string.Format("Cluster {0} finished.", i) + "\n"; } for (int i = 0; i < numClusters; i++) { for (int j = 0; j < numClusters; j++) { gra.AddEdge(new ComparableTuple(i, 0), new ComparableTuple(j, 0)); } } result = result + "\n"; result = result + string.Format(string.Format("Graph connected")) + "\n"; return(result); }
/// <summary> /// Copy the vertex/edges of one graph over to another graph. /// The id of the elements in the from graph are attempted to be used in the to graph. /// This method only works for graphs where the user can control the element ids. /// </summary> /// <param name="from">the graph to copy from</param> /// <param name="to">the graph to copy to</param> public static void CopyGraph(this IGraph from, IGraph to) { if (@from == null) { throw new ArgumentNullException(nameof(@from)); } if (to == null) { throw new ArgumentNullException(nameof(to)); } foreach (var fromVertex in @from.GetVertices()) { var toVertex = to.AddVertex(fromVertex.Id); fromVertex.CopyProperties(toVertex); } foreach (var fromEdge in from.GetEdges()) { var outVertex = to.GetVertex(fromEdge.GetVertex(Direction.Out).Id); var inVertex = to.GetVertex(fromEdge.GetVertex(Direction.In).Id); var toEdge = to.AddEdge(fromEdge.Id, outVertex, inVertex, fromEdge.Label); fromEdge.CopyProperties(toEdge); } }
private static void ImportGraph(IGraph graph, XmlDocument doc, XmlElement graphnode) { IGraphModel model = graph.Model; Dictionary <String, INode> nodemap = new Dictionary <string, INode>(); foreach (XmlElement nodeelem in graphnode.GetElementsByTagName("node")) { String nodetype = GetGrGenName(GetTypeName(nodeelem)); NodeType type = model.NodeModel.GetType(nodetype); if (type == null) { throw new Exception("Unknown node type: \"" + nodetype + "\""); } INode node = graph.AddNode(type); ReadAttributes(node, nodeelem); nodemap[nodeelem.GetAttribute("id")] = node; } foreach (XmlElement edgeelem in graphnode.GetElementsByTagName("edge")) { String edgetype = GetGrGenName(GetTypeName(edgeelem)); EdgeType type = model.EdgeModel.GetType(edgetype); if (type == null) { throw new Exception("Unknown edge type: \"" + edgetype + "\""); } INode src = GetNode(edgeelem, "from", nodemap); INode tgt = GetNode(edgeelem, "to", nodemap); IEdge edge = graph.AddEdge(type, src, tgt); ReadAttributes(edge, edgeelem); } }
static void MakeGraph(IGraph <ComparableTuple> gra) { for (int i = 0; i < numClusters; i++) { for (int j = 0; j < vertexPerCluster; j++) { gra.AddVertex(new ComparableTuple(i, j)); } } for (int i = 0; i < numClusters; i++) { MakeCluster(gra, i); System.Diagnostics.Debug.WriteLine(string.Format("Cluster {0} finished.", i)); } for (int i = 0; i < numClusters; i++) { for (int j = 0; j < numClusters; j++) { gra.AddEdge(new ComparableTuple(i, 0), new ComparableTuple(j, 0)); } } System.Diagnostics.Debug.WriteLine(string.Format("Graph connected")); }
public void RegioGraaf_c_AddUndirectedEdge_3_DirectedAndUndirected() { // Arrange IGraph graph = DSBuilder.CreateGraphEmpty(); var expected = StringWithoutSpaces( "A [ B(20) ] " + "B [ A(20) C(30) D(40) ] " + "C [ B(30) D(50) ] " + "D [ B(40) ] "); graph.GetVertex("A"); graph.GetVertex("B"); graph.GetVertex("C"); graph.GetVertex("D"); // Act graph.AddUndirectedEdge("A", "B", 20); graph.AddUndirectedEdge("B", "C", 30); graph.AddUndirectedEdge("B", "D", 40); graph.AddEdge("C", "D", 50); string actual = StringWithoutSpaces(graph.ToString()); // Assert Assert.AreEqual(expected, actual); }
/// <note> /// Raises an edgeAdded event. /// </note> public IEdge AddEdge(object id, IVertex outVertex, IVertex inVertex, string label) { GraphContract.ValidateAddEdge(id, outVertex, inVertex, label); var outVertexToSet = outVertex; if (outVertex is EventVertex) { outVertexToSet = (outVertex as EventVertex).Vertex; } var inVertexToSet = inVertex; if (inVertex is EventVertex) { inVertexToSet = (inVertex as EventVertex).Vertex; } if (inVertexToSet == null || outVertexToSet == null) { throw new InvalidOperationException(); } var edge = BaseGraph.AddEdge(id, outVertexToSet, inVertexToSet, label); OnEdgeAdded(edge); return(new EventEdge(edge, this)); }
public SymbolGraph(T[,] inputs) { indexes = new LinearProbingHashSymbolTable <T, int>(); // 构建顶点到索引的映射 for (int i = 0; i < inputs.GetLength(0); i++) { for (int j = 0; j < inputs.GetLength(1); j++) { if (!indexes.Contains(inputs[i, j])) { indexes.Put(inputs[i, j], indexes.Size); } } } // 构建索引到顶点的映射 keys = new T[indexes.Size]; foreach (var item in indexes) { keys[indexes.Get(item.Key)] = item.Key; } // 构建图 graph = new UndirectedGraph(indexes.Size); for (int i = 0; i < inputs.GetLength(0); i++) { int v = indexes.Get(inputs[i, 0]); for (int j = 1; j < inputs.GetLength(1); j++) { graph.AddEdge(v, Index(inputs[i, j])); } } }
// // Second Case Initialization private static void _initializeFirstCaseGraph(ref IGraph <string> graph) { // Clear the graph graph.Clear(); // // Add vertices var verticesSet = new string[] { "a", "b", "c" }; graph.AddVertices(verticesSet); // // Add Edges graph.AddEdge("a", "b"); graph.AddEdge("b", "c"); graph.AddEdge("c", "a"); }
public void GraphWithAdjList_AddEdge_EmptyGraph_ThrowsException() { // Arrange var exceptionThrown = false; // Act try { _graph.AddEdge(1, 2); } catch (InvalidOperationException) { exceptionThrown = true; } // Assert Assert.IsTrue(exceptionThrown); }
public static E AddEdge( IGraph <V, E> graph, V sourceVertex, V targetVertex) { var edge = graph.EdgeFactory.CreateEdge(sourceVertex, targetVertex); return(graph.AddEdge(sourceVertex, targetVertex, edge) ? edge : default(E)); }
public override void Open(TextReader reader, IGraph graph) { base.Open(reader, graph); double graphHeight = 0.0; int verticesCount = 0; foreach (var line in ReadAllLines(reader)) { var parts = SplitByWhitespacesWithQuotes(line); var statementType = parts[0]; parts = parts.Skip(1).ToArray(); if (statementType == "graph") { graphHeight = ParseStringTo <double>(parts[2]) * MonitorDpi; if (parts.Length != 3) { throw new InputFileFormatException("Properties count of \"graph\" must be 3"); } } else if (statementType == "node") { if (parts.Length != 10) { throw new InputFileFormatException("Properties count of \"node\" must be 10"); } var name = parts[0]; var x = ParseStringTo <double>(parts[1]); var y = ParseStringTo <double>(parts[2]); var label = parts[5]; if (label.StartsWith("\"") && label.EndsWith("\"")) { label = label.Substring(1, label.Length - 2); } graph.AddVertex(x * MonitorDpi, (graphHeight - y * MonitorDpi), ++verticesCount, name, label); } else if (statementType == "edge") { if (parts.Length < 7) { throw new InputFileFormatException("Properties count of \"edge\" must be more then 7"); } var tailName = parts[0]; var headName = parts[1]; var e = graph.AddEdge(graph.FindVertexByName(tailName), graph.FindVertexByName(headName)); } else if (statementType == "stop") { break; } } }
public static E AddEdgeWithVertices( IGraph <V, E> graph, V sourceVertex, V targetVertex) { graph.AddVertex(sourceVertex); graph.AddVertex(targetVertex); return(graph.AddEdge(sourceVertex, targetVertex)); }
static void MakeCluster(IGraph <ComparableTuple> gra, int i) { for (int j = 0; j < vertexPerCluster; j++) { for (int k = j; k < vertexPerCluster; k++) { gra.AddEdge(new ComparableTuple(i, j), new ComparableTuple(i, k)); } } }
public static void ThreadWorker() { int total = operationsPerThread; GraphOperation op; int u, v; Random rand = new Random(); int vertexId = 1; while (total > 0) { op = GetRandomOperation(rand); u = rand.Next() % vertexId; v = rand.Next() % vertexId; switch (op) { case GraphOperation.AddVertex: u = vertexId; vertexId++; graph.AddVertex(u); break; case GraphOperation.AddEdge: graph.AddEdge(u, v); break; case GraphOperation.RemoveVertex: graph.RemoveVertex(u); break; case GraphOperation.RemoveEdge: graph.RemoveEdge(u, v); break; case GraphOperation.ContainsVertex: graph.ContainsVertex(u); break; case GraphOperation.ContainsEdge: break; case GraphOperation.BFS: IExtendedGraph extendedGraph = graph as IExtendedGraph; if (extendedGraph != null) { extendedGraph.BFS(u); } break; } total--; } }
public TSPTest() { m_points = new List <Vertex>() { new Vertex(0, 0), new Vertex(2, 0), new Vertex(0, 1), new Vertex(1.5f, -1) }; m_graph = new AdjacencyListGraph(m_points); m_graph.AddEdge(m_points[0], m_points[2]); m_graph.AddEdge(m_points[2], m_points[1]); m_graph.AddEdge(m_points[1], m_points[3]); m_graph.AddEdge(m_points[3], m_points[0]); m_complete4 = new AdjacencyListGraph(m_points); m_complete4.MakeComplete(); expTSP = 1 + Mathf.Sqrt(5) + Mathf.Sqrt(1.25f) + Mathf.Sqrt(3.25f); }
public static bool AddEdgeWithVertices( IGraph <V, E> targetGraph, IGraph <V, E> sourceGraph, E edge) { V sourceVertex = edge.Source; V targetVertex = edge.Target; targetGraph.AddVertex(sourceVertex); targetGraph.AddVertex(targetVertex); return(targetGraph.AddEdge(sourceVertex, targetVertex, edge)); }
public IEdge AddEdge(object id, IVertex outVertex, IVertex inVertex, string label) { GraphContract.ValidateAddEdge(id, outVertex, inVertex, label); var edge = new PartitionEdge(BaseGraph.AddEdge(id, ((PartitionVertex)outVertex).Vertex, ((PartitionVertex)inVertex).Vertex, label), this); edge.SetPartition(_writePartition); return(edge); }
private void TryAddEdge(int dataId, int callbackId) { // The callback is called when the data is modified _dataToRegisteredCallbacks.AddOneToOne(dataId, callbackId); int publishingCallback; if (_publishedDataToPublishingCallback.TryGetValue(dataId, out publishingCallback)) { // we have found the id of a callback who publishes dataId when called _graph.AddEdge(publishingCallback, callbackId); } }
/// <summary> /// Add a road tour segment between 2 points /// </summary> /// <param name="a_point1"></param> /// <param name="a_point2"></param> public void AddSegment(TourPoint a_point1, TourPoint a_point2) { // Dont add edge to itself or double edges if (a_point1 == a_point2 || m_graph.ContainsEdge(a_point1.Vertex, a_point2.Vertex)) { return; } //instantiate new road mesh object var roadmesh = Instantiate(m_roadMeshPrefab, Vector3.forward, Quaternion.identity) as GameObject; roadmesh.transform.parent = this.transform; roadmesh.name = $"mesh({a_point1.Vertex}, {a_point2.Vertex})"; //remember segment for destoryal later instantObjects.Add(roadmesh); //create road mesh var roadmeshScript = roadmesh.GetComponent <ReshapingMesh>(); roadmeshScript.CreateNewMesh(a_point1.transform.position, a_point2.transform.position); //create road edge var edge = m_graph.AddEdge(a_point1.Vertex, a_point2.Vertex); //error check if (edge == null) { throw new InvalidOperationException("Edge could not be added to graph"); } //link edge to segment roadmesh.GetComponent <TourSegment>().Edge = edge; //check the solution CheckSolution(); UpdateTextField(); }
protected List <Room> SetupMainPath(int length) { var mainPath = new List <Room>(); // Prepare rooms on the main path mainPath.Add(new Room() { Type = RoomType.Spawn }); for (int i = 0; i < length - 2; i++) { mainPath.Add(new Room() { Type = RoomType.Basic }); } mainPath.Add(new Room() { Type = RoomType.Boss }); // Add vertices to levelGraph foreach (var room in mainPath) { LevelGraph.AddVertex(room); } // Add edges to levelGraph for (int i = 0; i < mainPath.Count - 1; i++) { LevelGraph.AddEdge(mainPath[i], mainPath[i + 1]); } return(mainPath); }
// // Second Case Initialization private static void _initializeSecondCaseGraph(ref IGraph<string> graph) { // Clear the graph graph.Clear(); // // Add vertices var verticesSet = new string[] { "a", "b", "c", "d", "e", "f", "s", "v", "x", "y", "z" }; graph.AddVertices (verticesSet); // // Add edges // Connected Component #1 // the vertex "e" won't be connected to any other vertex // Connected Component #2 graph.AddEdge("a", "s"); graph.AddEdge("a", "d"); graph.AddEdge("s", "x"); graph.AddEdge("s", "a"); graph.AddEdge("x", "d"); // Connected Component #3 graph.AddEdge("b", "c"); graph.AddEdge("b", "v"); graph.AddEdge("c", "f"); graph.AddEdge("c", "v"); graph.AddEdge("f", "b"); // Connected Component #4 graph.AddEdge("y", "z"); }
// // Second Case Initialization private static void _initializeFirstCaseGraph(ref IGraph<string> graph) { // Clear the graph graph.Clear(); // // Add vertices var verticesSet = new string[] { "a", "b", "c" }; graph.AddVertices (verticesSet); // // Add Edges graph.AddEdge("a", "b"); graph.AddEdge("b", "c"); graph.AddEdge("c", "a"); }
public bool Read(IGraph myGraph, FileStream myInputStream) { // use a streamreader .. better handling StreamReader reader = null; // stores the added vertices for fast retrieval var addedVertices = new Dictionary<string, IVertex>(); try { reader = new StreamReader(myInputStream); String line; // current line in file String[] edge; // contains source and target vertex id IVertex source; // source vertex IVertex target; // target vertex var count = 0L; // number of processed edges while ((line = reader.ReadLine()) != null) { if (!line.StartsWith(EdgeListTokens.LINE_COMMENT)) // just a comment { // line look like that "0 1", splitting it to get source and target id edge = line.Split(EdgeListTokens.SOURCE_TARGET_SEPARATOR); // got two id's? if (edge.Length == 2) { // check if source has been added before if (!addedVertices.TryGetValue(edge[0], out source)) { // if not, create new vertex source = myGraph.AddVertex(edge[0]); addedVertices.Add(edge[0], source); } // check if target has been added before if (!addedVertices.TryGetValue(edge[1], out target)) { // if not, create new vertex target = myGraph.AddVertex(edge[1]); addedVertices.Add(edge[1], target); } if (myGraph.AddEdge(source, target) != null) { count++; } } } } } catch (IOException ex) { // TODO add logging here return false; } finally { reader.Close(); } return true; }