public void TestGetEdges() { //make test variables Graph graph = new Graph(); List <Edge> list = new List <Edge>(); list.Add(new Edge("_0", "_3", 8, "_1")); list.Add(new Edge("_9", "_3", 5, "_3")); list.Add(new Edge("_0", "_5", 4, "_2")); list.Add(new Edge("_5", "_3", 3, "_8")); //add values to graph graph.addNode("_9"); graph.addNode("_3"); graph.addNode("_5"); graph.addNode("_0"); graph.addEdge(8, "_0", "_3", "_1"); graph.addEdge(3, "_5", "_3", "_8"); graph.addEdge(5, "_9", "_3", "_3"); graph.addEdge(4, "_0", "_5", "_2"); var result = graph.GetEdges(); Assert.AreEqual(list.Count, result.Count); }
public IEnumerator getGraphFromNode(string title) { Debug.Log("reached getGraphFromNode"); yield return(StartCoroutine(parseContentFromHTML(title))); Graph graph = new Graph(); Graph.Information info = new Graph.Information(title); Graph.Node firstNode = new Graph.Node(info); firstNode.setPosition(0.0f, 0.0f, 0.0f); graph.addNode(firstNode); //we assume that we don't go deeper here. //another approach would be to go the same route as Coroutine "getGraph" //we use this approach here because it's easier to implement and unterstand //plus the depth is unlikely to go deeper if (activeNode.getSubchapters() != null) { foreach (Graph.Information.Chapter subChapter in activeNode.getSubchapters()) { Graph.Information neighborInfo = new Graph.Information(subChapter.getTitle()); Graph.Node nextNode = new Graph.Node(neighborInfo); nextNode.setPosition(Random.Range(-DEFAULT_WIDTH / 2, DEFAULT_WIDTH / 2), Random.Range(-DEFAULT_HEIGHT / 2, DEFAULT_HEIGHT / 2), Random.Range(-DEFAULT_LENGTH / 2, DEFAULT_LENGTH / 2)); Graph.Edge nextedge = new Graph.Edge(firstNode, nextNode); graph.addNode(nextNode); graph.addEdge(nextedge); if (subChapter.getSubchapters() != null) { foreach (Graph.Information.Chapter subSubChapter in subChapter.getSubchapters()) { Graph.Information subNeighborInfo = new Graph.Information(subSubChapter.getTitle()); Graph.Node subNextNode = new Graph.Node(subNeighborInfo); subNextNode.setPosition(Random.Range(-DEFAULT_WIDTH / 2, DEFAULT_WIDTH / 2), Random.Range(-DEFAULT_HEIGHT / 2, DEFAULT_HEIGHT / 2), Random.Range(-DEFAULT_LENGTH / 2, DEFAULT_LENGTH / 2)); Graph.Edge subNextedge = new Graph.Edge(nextNode, subNextNode); graph.addNode(subNextNode); graph.addEdge(subNextedge); if (subSubChapter.getSubchapters() != null) { foreach (Graph.Information.Chapter subSubSubChapter in subChapter.getSubchapters()) { Graph.Information subSubNeighborInfo = new Graph.Information(subSubChapter.getTitle()); Graph.Node subSubNextNode = new Graph.Node(subSubNeighborInfo); subSubNextNode.setPosition(Random.Range(-DEFAULT_WIDTH / 2, DEFAULT_WIDTH / 2), Random.Range(-DEFAULT_HEIGHT / 2, DEFAULT_HEIGHT / 2), Random.Range(-DEFAULT_LENGTH / 2, DEFAULT_LENGTH / 2)); Graph.Edge subSubNextedge = new Graph.Edge(subNextNode, subSubNextNode); graph.addNode(subSubNextNode); graph.addEdge(subSubNextedge); } } } } } } setGraph(graph, 100.0f, 100.0f, 100.0f); drawGraph(); }
/// <summary> /// combain the two graph (a copy from GraphLibTest) /// </summary> /// <param name="g1"></param> /// <param name="g2"></param> /// <param name="IsoNode"></param> /// <returns> the graph combined or null</returns> public static Graph CreateIsoGraph(Graph g1, Graph g2, List <String[]> IsoNode) { if (IsoNode.Count != 0) { Graph ResultGraph = new Graph("IsoGraph", "IsoGraph", false); ResultGraph.IsDirected = g1.IsDirected; Node currentNode; Edge currentEdge; //Ajout des éléments du graphe 1 foreach (Node n in g1.ListNodes) { currentNode = new Node(g1.Name + "_" + n.Id); ResultGraph.addNode(currentNode); } foreach (Edge e in g1.ListEdges) { currentEdge = new Edge(g1.Name + "_" + e.Id); currentEdge.NodeSource = ResultGraph.findNode(g1.Name + "_" + e.NodeSource.Id); currentEdge.NodeTarget = ResultGraph.findNode(g1.Name + "_" + e.NodeTarget.Id); ResultGraph.addEdge(currentEdge); } //Ajout des éléments du graphe 2 foreach (Node n in g2.ListNodes) { currentNode = new Node(g2.Name + "_" + n.Id); //currentNode.Label = n.Label; ResultGraph.addNode(currentNode); } foreach (Edge e in g2.ListEdges) { //currentEdge = new Edge(e.Id, ResultGraph.findNode("2-" + e.NodeSource.Id), ResultGraph.findNode("2-" + e.NodeTarget.Id), e.Label); currentEdge = new Edge(g2.Name + "_" + e.Id); currentEdge.NodeSource = ResultGraph.findNode(g2.Name + "_" + e.NodeSource.Id); currentEdge.NodeTarget = ResultGraph.findNode(g2.Name + "_" + e.NodeTarget.Id); ResultGraph.addEdge(currentEdge); } //Ajout des arcs d'isomorphismes int cpt = 0; foreach (String[] s in IsoNode) { currentEdge = new Edge("Iso" + cpt); currentEdge.NodeSource = ResultGraph.findNode(g1.Name + "_" + s[0]); currentEdge.NodeTarget = ResultGraph.findNode(g2.Name + "_" + s[1]); ResultGraph.addEdge(currentEdge); cpt++; } return(ResultGraph); } else { return(null); } }
public void TestHasEdge() { Graph graph = new Graph(); graph.addNode("_0"); graph.addNode("_1"); graph.addEdge(5, "_0", "_1", "_0"); var result = graph.hasEdge(new Edge("_0", "_1", 0, "_0")); Assert.IsTrue(result); }
public static Graph createNewGraph() { Graph g = new Graph(); Node[] temp = new Node[6]; temp[0] = new Node("a", 3); temp[1] = new Node("b", 0); temp[2] = new Node("c", 0); temp[3] = new Node("d", 1); temp[4] = new Node("e", 1); temp[5] = new Node("f", 0); temp[0].addAdjacent(temp[1]); temp[0].addAdjacent(temp[2]); temp[0].addAdjacent(temp[3]); temp[3].addAdjacent(temp[4]); temp[4].addAdjacent(temp[5]); for (int i = 0; i < 6; i++) { g.addNode(temp[i]); } return(g); }
// Use this for initialization void Start() { //Random.InitState(123); float[,] heightmap = new float[1024, 1024]; for (int x = 0; x < 1024; x++) { for (int y = 0; y < 1024; y++) { heightmap[x, y] = getHeight(x, y); } } RoadNetworkGenerator rng = GetComponent <RoadNetworkGenerator>(); Graph <Vector2, Segment> roadGraph = rng.generateNetwork(heightmap); roadGraph.addNode(new Vector2(511, 511)); Dictionary <Vector2, Vector3> pos = new Dictionary <Vector2, Vector3>(); foreach (Vector2 v in roadGraph.edges.Keys) { pos.Add(v, new Vector3(v.x, heightmap[(int)v.x + 512, (int)v.y + 512], v.y)); } transform.GetChild(0).GetComponent <RoadPGraph>().heightmap = heightmap; transform.GetChild(0).GetComponent <RoadPGraph>().drawGraph(roadGraph, pos); TestRenderer renderer = new TestRenderer(heightmap, 1024, 1024); transform.GetChild(1).GetComponent <PhysicalMap>().init(1024, 1024); transform.GetChild(1).GetComponent <PhysicalMap>().draw(renderer); }
public void TestAddNodeAndHasNode() { Graph graph = new Graph(); graph.addNode("_0"); var result = graph.hasVertex("_0"); Assert.IsTrue(result); }
public void TestRemoveEdgeGraph() { Graph graph = new Graph(); Edge edge = new Edge("_9", "_3", 5, "_3"); graph.addNode("_9"); graph.addNode("_3"); graph.addEdge(5, "_9", "_3", "_3"); graph.removeEdge("_9", "_3"); graph.removeEdge("_3", "_3"); var result = graph.hasEdge(edge); Assert.IsFalse(result); }
public void TestGetVertex() { Graph graph = new Graph(); Vertex vertex = new Vertex("_9"); graph.addNode("_9"); var result = graph.GetVertex("_9"); Assert.AreEqual(vertex.data, result.data); }
public Path run() { Graph graph = new Graph(_xinit, new RectangleNode()); //Boolean busy = false; RectangleNode node = null; RectangleNode newnode = null; bestSoFar = graph.getRandomNode(node); for (int iter = 0; iter < _maxiter; iter++) { //if (busy) // node = newnode; //else node = graph.getRandomNode(node); if (node == null) { return(minimizePath(graph.traceBack(bestSoFar))); } newnode = _tactics.apply(node, _domain, graph); //or only node? if (newnode == null) { continue; } //busy = newnode.isBusy(); if (_validator.validate(newnode, node, _domain, graph)) { graph.addNode(newnode, node, newnode.getState().getAction()); if (newnode.getState().numberOfCollectibles() < bestSoFar.getState().numberOfCollectibles()) { bestSoFar = newnode; } // GOAL ACHIEVED if (newnode.getState().numberOfCollectibles() == 0) { return(minimizePath(graph.traceBack(newnode))); } } //else //{ // //busy = node.isBusy(); // //if (busy) // // graph.rollBack(node); // //busy = false; // if (node.isBusy()) // graph.rollBack(node); //} } return(minimizePath(graph.traceBack(bestSoFar))); }
public void TestGetVertices() { Graph graph = new Graph(); List <Vertex> list = new List <Vertex>(); list.Add(new Vertex("_0")); list.Add(new Vertex("_3")); list.Add(new Vertex("_5")); list.Add(new Vertex("_9")); graph.addNode("_9"); graph.addNode("_3"); graph.addNode("_5"); graph.addNode("_0"); var result = graph.GetVertices(); Assert.AreEqual(result.Count, list.Count); }
private void buildGraph() { //GameObject temp = GameObject.Find ("GridCreator");//GetComponent<GridCreator>.getWidth(); //int width = temp.GetComponent<GameObject>().width; int width = 40; int height = 20; int n = waypoints.Count; navGraph = new AdjacencyListGraph(); for (int i = 0; i < n; i++) { navGraph.addNode(i); } int side = 0; for (int i = 0; i < n; i++) { Vector2 pos = getVector(i, width); if (pos.y % 2 == 0) { side = -1; } else { side = 1; } if (pos.x - 1 >= 0) // add left edge { navGraph.addEdge(i, getNo(pos.x - 1f, pos.y, width)); } if (pos.x + 1 < width) // add right edge { navGraph.addEdge(i, getNo(pos.x + 1f, pos.y, width)); } if (pos.y - 1 >= 0) // add directly below edge { navGraph.addEdge(i, getNo(pos.x, pos.y - 1f, width)); } if (pos.y + 1 < height) // add directly above edge { navGraph.addEdge(i, getNo(pos.x, pos.y + 1f, width)); } if (pos.y - 1 >= 0 && pos.x + side >= 0 && pos.x + side < width) // add below to the side edge { navGraph.addEdge(i, getNo(pos.x + side, pos.y - 1f, width)); } if (pos.y + 1 < height && pos.x + side >= 0 && pos.x + side < width) // add above to the side edge { navGraph.addEdge(i, getNo(pos.x + side, pos.y + 1f, width)); } } }
public void TestRemoveNode() { Graph graph = new Graph(); graph.addNode("_0"); graph.removeVertex("_0"); var result = graph.hasVertex("_0"); Assert.IsFalse(result); }
public void RRG(int max_nodes, Graph G) { //float edgeLength = 5.0f; //float nodeMinDistance = 2.5f; //float addEdgeMaxLength = 10.0f; print(edgeLength); print(addEdgeMaxLength); int max_iter = 10000; Node close_node = null; Vector3 new_coord = new Vector3(0, 0, 0); for (int i = 0; i < max_nodes && max_iter > 0; i++) { //For all the new nodes; bool found = false; for (max_iter = 10000; !found && max_iter > 0; max_iter--) { Vector3 goal = Pseudo_random(Margin); //Find random point close_node = G.FindClosestNode(goal, G); //Find closest node float distance = Vector3.Distance(close_node.getPosition(), goal); //And compute the distance if (distance > edgeLength) { //skip if B too close new_coord = Vector3.Lerp(close_node.getPosition(), goal, edgeLength / distance); //distance = Vector3.Distance(new_coord, G.FindClosestNode(new_coord, G).getPosition()); //if (distance > nodeMinDistance) //{ //skip if C too close to another point WE DONT F*****G NEED THIS CHECK, BECAUSE CLOSE_NODE WILL ALWAISE BE THE CLOSEST TO B if (!position_collision(Margin, new_coord) && !IsCollidingOnEdge(close_node.getPosition(), new_coord)) { found = true; } //} } } //Debug.Log(max_iter); int idx = G.addNode(new Node(new_coord)); G.addEdge(idx, close_node.getId()); for (int j = 0; j < G.getSize() - 1; j++) { Node temp = G.getNode(j); float checkDistance = Vector3.Distance(temp.getPosition(), G.getNode(idx).getPosition()); if (checkDistance < addEdgeMaxLength && j != idx && !IsCollidingOnEdge(temp.getPosition(), G.getNode(idx).getPosition())) { G.addEdge(j, idx); } } } }
static void Main(string[] args) { Graph <string, int> graph = new Graph <string, int>(); graph.addNode("start"); graph.addNode("end"); graph.addNode("v1"); graph.addNode("v2"); graph.addNode("v3"); graph.AddUnidirectedEdge(100, "start", "end"); graph.AddUnidirectedEdge(5, "start", "v1"); graph.AddBidirectedEdge(6, "v2", "v1"); graph.AddUnidirectedEdge(7, "v2", "v3"); graph.AddUnidirectedEdge(8, "v3", "end"); graph.AddUnidirectedEdge(1, "v3", "v1"); graph.AddUnidirectedEdge(2, "start", "v2"); graph.removeEdge(6); Djkstra <string, int> djkstra = new Djkstra <string, int>() { costExtractor = i => i, start = "start", end = "end", graph = graph }; var result = djkstra.findRoute(); foreach (var item in result) { Console.WriteLine(item); } Console.ReadKey(); }
private void initLiveObjectsGraph() { graphLiveObjects.reset(); foreach (Graph.Node node in levelData.liveObjectsNodes) { graphLiveObjects.addNode(node); } foreach (Graph.Connection connection in levelData.liveObjectsLinks) { graphLiveObjects.addLink(connection); } }
public void TestKruskal() { float expected = 10; Graph graph = new Graph(); classicAlgorithms ca = new classicAlgorithms(); graph.addNode("_0"); graph.addNode("_1"); graph.addNode("_2"); graph.addNode("_3"); graph.addNode("_4"); graph.addEdge(3, "_0", "_4", "_1"); graph.addEdge(21, "_0", "_3", "_2"); graph.addEdge(3, "_1", "_2", "_3"); graph.addEdge(31, "_1", "_4", "_4"); graph.addEdge(2, "_2", "_4", "_5"); graph.addEdge(2, "_3", "_4", "_6"); var result = ca.kruskal(ref graph); Assert.AreEqual(expected, result.getGraphWeight()); }
// function to return a deep copy of this graph public Graph cloneGraph() { Graph copyGraph = new Graph(); //ArrayList nodes = new ArrayList(); // deep copy nodes foreach (Node node in this.reflexVertices) { copyGraph.addNode(new Node(node.getPosition(), node.vertexObject)); } // add neighbors to the nodes we just copied for (int i = 0; i < reflexVertices.Count; i++) { foreach (Node neighbor in ((Node)reflexVertices[i]).getNeighbors()) { ((Node)copyGraph.getReflexVertices()[i]).addNeightbor((Node)copyGraph.getReflexVertices()[reflexVertices.IndexOf(neighbor)]); } } return(copyGraph); }
//execute dijkstra without a goal public Graph dijkstraNoDest(string src, ref Graph g) { Graph mst = new Graph(); List <Vertex> visitedNodes = new List <Vertex>();//contains visted nodes and their edge id List <Vertex> unvisitedNodes = new List <Vertex>(); Dictionary <Vertex, distance> distances = new Dictionary <Vertex, distance>(); //check that the source and destination exists if (g.hasVertex(src)) { //add the source node has been visited and add its distance distances.Add(g.GetVertex(src), new distance(0, g.GetVertex(src))); //set all nodes distances and mark unvisted foreach (Vertex v in g.GetVertices()) { if (v.data != src) { distances.Add(v, new distance(float.MaxValue, null)); //set unkown distance to infinity } unvisitedNodes.Add(v); //add to a list of unvisited nodes } var prevNode = g.GetVertex(src); var currentNode = g.GetVertex(src); //while goal hasnt been reached try and get a suitable goal while (unvisitedNodes.Count > 0) { //find lowest distance and set the current distance that and recored the parent node foreach (Edge e in currentNode.neighbours) { //check that set distances if (e.node1 != currentNode.data) { if (e.weight + distances[currentNode].dist < distances[g.GetVertex(e.node1)].dist && !visitedNodes.Contains(g.GetVertex(e.node2))) { distances[g.GetVertex(e.node1)].dist = e.weight + distances[currentNode].dist; distances[g.GetVertex(e.node1)].prevVertex = currentNode; } } else if (e.node2 != currentNode.data) { if (e.weight + distances[currentNode].dist < distances[g.GetVertex(e.node2)].dist && !visitedNodes.Contains(g.GetVertex(e.node2))) { distances[g.GetVertex(e.node2)].dist = e.weight + distances[currentNode].dist; distances[g.GetVertex(e.node2)].prevVertex = currentNode; } } } visitedNodes.Add(currentNode); unvisitedNodes.Remove(currentNode); Vertex lowestDist = null; //select next node that hasnt been visted that has lowest diastance foreach (KeyValuePair <Vertex, distance> kvp in distances) { if (lowestDist == null && !visitedNodes.Contains(kvp.Key)) { lowestDist = kvp.Key; } if (!visitedNodes.Contains(kvp.Key)) { if (distances[kvp.Key].dist < distances[lowestDist].dist) { lowestDist = kvp.Key; } } } currentNode = lowestDist; } } //build mst foreach (Vertex v in visitedNodes) { foreach (Edge e in v.neighbours) { if (e.node1 != v.data) { if (e.node1 == distances[v].prevVertex.data) { if (!mst.hasVertex(e.node1)) { mst.addNode(e.node1); } if (!mst.hasVertex(e.node2)) { mst.addNode(e.node2); } if (!mst.hasEdge(e)) { mst.addEdge(e.weight, e.node1, e.node2, e.data); } } } else if (e.node2 != v.data) { if (e.node2 == distances[v].prevVertex.data) { if (!mst.hasVertex(e.node1)) { mst.addNode(e.node1); } if (!mst.hasVertex(e.node2)) { mst.addNode(e.node2); } if (!mst.hasEdge(e)) { mst.addEdge(e.weight, e.node1, e.node2, e.data); } } } } } return(mst); }
static void Main(string[] args) { Console.Write("This project contains 13 packages demonstrating requirement 3:\n"); Console.Write("1) DemoExecutive\n"); Console.Write("2) DemoReqs\n"); Console.Write("3) DependencyAnalysis\n"); Console.Write("4) Display\n"); Console.Write("5) Element\n"); Console.Write("6) FileMgr\n"); Console.Write("7) Parser\n"); Console.Write("8) SemiExp\n"); Console.Write("9) StrongComponent\n"); Console.Write("10) TestHarness\n"); Console.Write("11) Toker\n"); Console.Write("12) TypeTable\n"); Console.Write("13) AutomatedTestUnit\n"); Console.Write("\n ======================\n"); Console.Write("\n Demonstrating Parser"); Console.Write("\n ======================\n"); ShowCommandLine(args); List <string> files = ProcessCommandline(args); DepAnalysis da = new DepAnalysis(); foreach (string file in files) { Console.Write("\n Processing file {0}\n", System.IO.Path.GetFileName(file)); ITokenCollection semi = Factory.create(); //semi.displayNewLines = false; if (!semi.open(file as string)) { Console.Write("\n Can't open {0}\n\n", args[0]); return; } Console.Write("\n Type and Function Analysis"); Console.Write("\n ----------------------------"); BuildCodeAnalyzer builder = new BuildCodeAnalyzer(semi); Parser parser = builder.build(); try { while (semi.get().Count > 0) { parser.parse(semi); } } catch (Exception ex) { Console.Write("\n\n {0}\n", ex.Message); } Repository rep = Repository.getInstance(); List <Elem> table = rep.locations; TypeTable.TypeTable tt = new TypeTable.TypeTable(); ///shows typetable foreach (Elem e in table) { tt.add(e.type, e.name); if (e.type == "using") { da.add(System.IO.Path.GetFileName(file), e.name); } } tt.show(); Console.WriteLine("Showing TypeTables of files demonstrating requirement 5:\n"); Console.Write("\n TypeTable contains types: "); foreach (var elem in tt.table) { Console.Write("{0} ", elem.Key); } ////Display.showMetricsTable(table); Console.Write("\n"); semi.close(); } var nodes = new List <CsNode <string, string> >(); foreach (var elem in da.table) { nodes.Add(new CsNode <string, string>(elem.Key)); //Console.Write("\n {0} depends on", elem.Key); } nodes.ToArray(); //foreach (var elem in da.table) //{ // foreach (var item in elem.Value) // { // //nodes[IndexOf(elem.Key)].addChild(nodes[IndexOf(item.file)], "edge" + elem.Key + " " + item.file); // //nodes[0].addChild(item.file, "edge" + elem.Key + " " + item.file); // //nodes[nodes.IndexOf(elem.Value)].addChild(nodes[nodes.IndexOf(item.file)], "edge" + elem.Key + " " + item.file); // Console.Write("\n {0}.cs", item.file); // } //} //iterate through list of list elements of a file //da.table --gets table, for (int i = 0; i < da.table.Count; i++) { var item = da.table.ElementAt(i); for (int j = 0; j < item.Value.Count; j++) { //Console.WriteLine(i+"^"+ da.table.Values); nodes[i].addChild(nodes[j], "edge" + i + j); } } Graph <string, string> graph = new Graph <string, string>("Fred"); for (int i = 0; i < da.table.Count; i++) { graph.addNode(nodes[i]); } graph.startNode = nodes[0]; //Console.WriteLine("\n Showing graph walk starting at node[0]\n"); //Console.Write("\n\n starting walk at {0}", graph.startNode.name); //Console.Write("\n not showing backtracks"); //graph.walk(); Console.WriteLine("Showing dependencies between files demonstrating requrement 4:\n\n"); //shows dependency analysis da.show(); Console.Write("\n\n"); Console.Write("Showing all strong components, if any, in the file collection, based on the dependency analysis demonstrating requirement 6:\n\n"); graph.startNode = nodes[0]; graph.Tarjan(); Console.Write("\n\n"); Console.WriteLine("This demo executive file demonstrates all the outputs and is well formatted as per requirement 7 and 8\n"); Console.ReadLine(); }
/// <summary> /// Generate the reduced visibility graph of this map using Signed area of a triangle test (SAT) /// </summary> /// <param name="terrainCorners"></param> /// <param name="obstacles"></param> /// return the RVGraph Graph generateRVgraph(GameObject[] terrainCorners, ArrayList obstacles) { Graph rvgraph = new Graph(); // To construct a reduced visibility graph: // a) if 2 reflex vertices are end points of the same edge -> join them with an edge // b) if 2 reflex vertices can be joined by a “bitangent line”, add an edge between them. ArrayList terrainVertices = new ArrayList(); // list stores terrain vertices as Node // Add terrain vertices into a list as node foreach (GameObject obj in terrainCorners) { terrainVertices.Add(new Graph.Node(obj.transform.position, obj)); } // ------------------------ // connect terrain reflex vertices to terrain reflex vertices if "bitangent", checking use SAT test // SAT test for 2D: say we have points P0, P1, P1 // (p1x-p0x)(p2y-p0y)-(p2x-p0x)(p1y-p0y) > 0: p2 is “left” of p0->p1 // (p1x-p0x)(p2y-p0y)-(p2x-p0x)(p1y-p0y) < 0: p2 is “right” of p0->p1 // (p1x-p0x)(p2y-p0y)-(p2x-p0x)(p1y-p0y) = 0: p2 is colinear with of p0->p1 Vector2 point1; Vector2 point2; Vector2 point1Prev; // previous vertex of point1 Vector2 point2Prev; // previous vertex of point2 Vector2 point1Next; // next vertex of point1 Vector2 point2Next; // next vertex of point2 Graph.Node node1; Graph.Node node2; Vector3 direction; // used for raycast for (int i = 0; i < terrainVertices.Count; i++) { node1 = (Graph.Node)terrainVertices[i]; for (int k = 0; k < terrainVertices.Count; k++) { node2 = (Graph.Node)terrainVertices[k]; // skip if vertext1 and vertex2 are the same if (node1.Equals(node2)) { continue; } else { // if both vertices are reflex vertices, do SAT test if (node1.vertexObject.CompareTag("ReflexVertex") && node2.vertexObject.CompareTag("ReflexVertex")) { direction = (node2.getPosition() - node1.getPosition()).normalized; // if there is obstacle between node1 and node2, continue if (Physics.Raycast(node1.getPosition(), direction, Vector3.Distance(node1.getPosition(), node2.getPosition()))) { continue; } else // if no obstacle in between, do SAT test { // we have vertices on x-z plane (fixed y), so set 2D vector of x and z point1 = new Vector2(node1.getPosition().x, node1.getPosition().z); point2 = new Vector2(node2.getPosition().x, node2.getPosition().z); // handle cases where point1 of point2 has index of 0 or Length of array if (i == 0) { point1Prev = new Vector2(((Graph.Node)terrainVertices[terrainVertices.Count - 1]).getPosition().x, ((Graph.Node)terrainVertices[terrainVertices.Count - 1]).getPosition().z); point1Next = new Vector2(((Graph.Node)terrainVertices[i + 1]).getPosition().x, ((Graph.Node)terrainVertices[i + 1]).getPosition().z); } else if (i == terrainVertices.Count - 1) { point1Prev = new Vector2(((Graph.Node)terrainVertices[i - 1]).getPosition().x, ((Graph.Node)terrainVertices[i - 1]).getPosition().z); point1Next = new Vector2(((Graph.Node)terrainVertices[0]).getPosition().x, ((Graph.Node)terrainVertices[0]).getPosition().z); } else { point1Prev = new Vector2(((Graph.Node)terrainVertices[i - 1]).getPosition().x, ((Graph.Node)terrainVertices[i - 1]).getPosition().z); point1Next = new Vector2(((Graph.Node)terrainVertices[i + 1]).getPosition().x, ((Graph.Node)terrainVertices[i + 1]).getPosition().z); } if (k == 0) { point2Prev = new Vector2(((Graph.Node)terrainVertices[terrainVertices.Count - 1]).getPosition().x, ((Graph.Node)terrainVertices[terrainVertices.Count - 1]).getPosition().z); point2Next = new Vector2(((Graph.Node)terrainVertices[k + 1]).getPosition().x, ((Graph.Node)terrainVertices[k + 1]).getPosition().z); } else if (k == terrainVertices.Count - 1) { point2Prev = new Vector2(((Graph.Node)terrainVertices[k - 1]).getPosition().x, ((Graph.Node)terrainVertices[k - 1]).getPosition().z); point2Next = new Vector2(((Graph.Node)terrainVertices[0]).getPosition().x, ((Graph.Node)terrainVertices[0]).getPosition().z); } else { point2Prev = new Vector2(((Graph.Node)terrainVertices[k - 1]).getPosition().x, ((Graph.Node)terrainVertices[k - 1]).getPosition().z); point2Next = new Vector2(((Graph.Node)terrainVertices[k + 1]).getPosition().x, ((Graph.Node)terrainVertices[k + 1]).getPosition().z); } // if the prev and next node of the reflex vertices is one to the left and one to the right as the SAT result, node1 and node2 are not bitangent if (((point2.x - point1.x) * (point2Prev.y - point1.y) - (point2Prev.x - point1.x) * (point2.y - point1.y) > 0 && (point2.x - point1.x) * (point2Next.y - point1.y) - (point2Next.x - point1.x) * (point2.y - point1.y) < 0) || ((point2.x - point1.x) * (point2Prev.y - point1.y) - (point2Prev.x - point1.x) * (point2.y - point1.y) < 0 && (point2.x - point1.x) * (point2Next.y - point1.y) - (point2Next.x - point1.x) * (point2.y - point1.y) > 0) || ((point1.x - point2.x) * (point1Prev.y - point2.y) - (point1Prev.x - point2.x) * (point1.y - point2.y) > 0 && (point1.x - point2.x) * (point1Next.y - point2.y) - (point1Next.x - point2.x) * (point1.y - point2.y) < 0) || ((point1.x - point2.x) * (point1Prev.y - point2.y) - (point1Prev.x - point2.x) * (point1.y - point2.y) < 0 && (point1.x - point2.x) * (point1Next.y - point2.y) - (point1Next.x - point2.x) * (point1.y - point2.y) > 0) ) { // in this case, node1 and node2 are not bitangent continue; } else { // otherwise, they are bitangent, add them as neighbor in RVGraph node1.addNeightbor(node2); node2.addNeightbor(node1); } } } } } } // ------------------------ //ArrayList obstacleVertices = new ArrayList(); // list stores obstacle vertices as Node ArrayList obstaclesList = new ArrayList(); // list stores list of obstacle vertices // Add obstacles reflex vertices into a list and them put each list into a list of obstacle foreach (GameObject obj in obstacles) { ArrayList obsNodes = new ArrayList(); // store the list of vertices of this obstacle as Nodes Transform[] allChildren = obj.GetComponentsInChildren <Transform>(); foreach (Transform child in allChildren) { if (child.tag != "Cube") { obsNodes.Add(new Graph.Node(child.position, child.gameObject)); } } obstaclesList.Add(obsNodes); } // ------------------------ // connect obstacle reflex vertices to obstacle reflex vertices if "bitangent", checking use SAT test foreach (ArrayList obstacleVertices in obstaclesList) { foreach (ArrayList obstacleVertices2 in obstaclesList) { for (int i = 0; i < obstacleVertices.Count; i++) { node1 = (Graph.Node)obstacleVertices[i]; for (int k = 0; k < obstacleVertices2.Count; k++) { node2 = (Graph.Node)obstacleVertices2[k]; // skip if vertext1 and vertex2 are the same if (node1.Equals(node2)) { continue; } else { // if both vertices are reflex vertices, do SAT test if (node1.vertexObject.CompareTag("ReflexVertex") && node2.vertexObject.CompareTag("ReflexVertex")) { direction = (node2.getPosition() - node1.getPosition()).normalized; // if there is obstacle between node1 and node2, continue if (Physics.Raycast(node1.getPosition(), direction, Vector3.Distance(node1.getPosition(), node2.getPosition()))) { continue; } else // if no obstacle in between, do SAT test { // we have vertices on x-z plane (fixed y), so set 2D vector of x and z point1 = new Vector2(node1.getPosition().x, node1.getPosition().z); point2 = new Vector2(node2.getPosition().x, node2.getPosition().z); // handle cases where point1 of point2 has index of 0 or Length of array if (i == 0) { point1Prev = new Vector2(((Graph.Node)obstacleVertices[obstacleVertices.Count - 1]).getPosition().x, ((Graph.Node)obstacleVertices[obstacleVertices.Count - 1]).getPosition().z); point1Next = new Vector2(((Graph.Node)obstacleVertices[i + 1]).getPosition().x, ((Graph.Node)obstacleVertices[i + 1]).getPosition().z); } else if (i == obstacleVertices.Count - 1) { point1Prev = new Vector2(((Graph.Node)obstacleVertices[i - 1]).getPosition().x, ((Graph.Node)obstacleVertices[i - 1]).getPosition().z); point1Next = new Vector2(((Graph.Node)obstacleVertices[0]).getPosition().x, ((Graph.Node)obstacleVertices[0]).getPosition().z); } else { point1Prev = new Vector2(((Graph.Node)obstacleVertices[i - 1]).getPosition().x, ((Graph.Node)obstacleVertices[i - 1]).getPosition().z); point1Next = new Vector2(((Graph.Node)obstacleVertices[i + 1]).getPosition().x, ((Graph.Node)obstacleVertices[i + 1]).getPosition().z); } if (k == 0) { point2Prev = new Vector2(((Graph.Node)obstacleVertices2[obstacleVertices2.Count - 1]).getPosition().x, ((Graph.Node)obstacleVertices2[obstacleVertices2.Count - 1]).getPosition().z); point2Next = new Vector2(((Graph.Node)obstacleVertices2[k + 1]).getPosition().x, ((Graph.Node)obstacleVertices2[k + 1]).getPosition().z); } else if (k == obstacleVertices2.Count - 1) { point2Prev = new Vector2(((Graph.Node)obstacleVertices2[k - 1]).getPosition().x, ((Graph.Node)obstacleVertices2[k - 1]).getPosition().z); point2Next = new Vector2(((Graph.Node)obstacleVertices2[0]).getPosition().x, ((Graph.Node)obstacleVertices2[0]).getPosition().z); } else { point2Prev = new Vector2(((Graph.Node)obstacleVertices2[k - 1]).getPosition().x, ((Graph.Node)obstacleVertices2[k - 1]).getPosition().z); point2Next = new Vector2(((Graph.Node)obstacleVertices2[k + 1]).getPosition().x, ((Graph.Node)obstacleVertices2[k + 1]).getPosition().z); } // if the prev and next node of the reflex vertices is one to the left and one to the right as the SAT result, node1 and node2 are not bitangent if (((point2.x - point1.x) * (point2Prev.y - point1.y) - (point2Prev.x - point1.x) * (point2.y - point1.y) > 0 && (point2.x - point1.x) * (point2Next.y - point1.y) - (point2Next.x - point1.x) * (point2.y - point1.y) < 0) || ((point2.x - point1.x) * (point2Prev.y - point1.y) - (point2Prev.x - point1.x) * (point2.y - point1.y) < 0 && (point2.x - point1.x) * (point2Next.y - point1.y) - (point2Next.x - point1.x) * (point2.y - point1.y) > 0) || ((point1.x - point2.x) * (point1Prev.y - point2.y) - (point1Prev.x - point2.x) * (point1.y - point2.y) > 0 && (point1.x - point2.x) * (point1Next.y - point2.y) - (point1Next.x - point2.x) * (point1.y - point2.y) < 0) || ((point1.x - point2.x) * (point1Prev.y - point2.y) - (point1Prev.x - point2.x) * (point1.y - point2.y) < 0 && (point1.x - point2.x) * (point1Next.y - point2.y) - (point1Next.x - point2.x) * (point1.y - point2.y) > 0) ) { // in this case, node1 and node2 are not bitangent continue; } else { // otherwise, they are bitangent, add them as neighbor in RVGraph node1.addNeightbor(node2); node2.addNeightbor(node1); } } } } } } } } // ------------------------ // connect obstacle reflex vertices to terrain reflex vertices if "bitangent", checking use SAT test foreach (ArrayList obstacleVertices in obstaclesList) { for (int i = 0; i < obstacleVertices.Count; i++) { node1 = (Graph.Node)obstacleVertices[i]; for (int k = 0; k < terrainVertices.Count; k++) { node2 = (Graph.Node)terrainVertices[k]; // skip if vertext1 and vertex2 are the same if (node1.Equals(node2)) { continue; } else { // if both vertices are reflex vertices, do SAT test if (node1.vertexObject.CompareTag("ReflexVertex") && node2.vertexObject.CompareTag("ReflexVertex")) { direction = (node2.getPosition() - node1.getPosition()).normalized; // if there is obstacle between node1 and node2, continue if (Physics.Raycast(node1.getPosition(), direction, Vector3.Distance(node1.getPosition(), node2.getPosition()))) { continue; } else // if no obstacle in between, do SAT test { // we have vertices on x-z plane (fixed y), so set 2D vector of x and z point1 = new Vector2(node1.getPosition().x, node1.getPosition().z); point2 = new Vector2(node2.getPosition().x, node2.getPosition().z); // handle cases where point1 of point2 has index of 0 or Length of array if (i == 0) { point1Prev = new Vector2(((Graph.Node)obstacleVertices[obstacleVertices.Count - 1]).getPosition().x, ((Graph.Node)obstacleVertices[obstacleVertices.Count - 1]).getPosition().z); point1Next = new Vector2(((Graph.Node)obstacleVertices[i + 1]).getPosition().x, ((Graph.Node)obstacleVertices[i + 1]).getPosition().z); } else if (i == obstacleVertices.Count - 1) { point1Prev = new Vector2(((Graph.Node)obstacleVertices[i - 1]).getPosition().x, ((Graph.Node)obstacleVertices[i - 1]).getPosition().z); point1Next = new Vector2(((Graph.Node)obstacleVertices[0]).getPosition().x, ((Graph.Node)obstacleVertices[0]).getPosition().z); } else { point1Prev = new Vector2(((Graph.Node)obstacleVertices[i - 1]).getPosition().x, ((Graph.Node)obstacleVertices[i - 1]).getPosition().z); point1Next = new Vector2(((Graph.Node)obstacleVertices[i + 1]).getPosition().x, ((Graph.Node)obstacleVertices[i + 1]).getPosition().z); } if (k == 0) { point2Prev = new Vector2(((Graph.Node)terrainVertices[terrainVertices.Count - 1]).getPosition().x, ((Graph.Node)terrainVertices[terrainVertices.Count - 1]).getPosition().z); point2Next = new Vector2(((Graph.Node)terrainVertices[k + 1]).getPosition().x, ((Graph.Node)terrainVertices[k + 1]).getPosition().z); } else if (k == terrainVertices.Count - 1) { point2Prev = new Vector2(((Graph.Node)terrainVertices[k - 1]).getPosition().x, ((Graph.Node)terrainVertices[k - 1]).getPosition().z); point2Next = new Vector2(((Graph.Node)terrainVertices[0]).getPosition().x, ((Graph.Node)terrainVertices[0]).getPosition().z); } else { point2Prev = new Vector2(((Graph.Node)terrainVertices[k - 1]).getPosition().x, ((Graph.Node)terrainVertices[k - 1]).getPosition().z); point2Next = new Vector2(((Graph.Node)terrainVertices[k + 1]).getPosition().x, ((Graph.Node)terrainVertices[k + 1]).getPosition().z); } // if the prev and next node of the reflex vertices is one to the left and one to the right as the SAT result, node1 and node2 are not bitangent if (((point2.x - point1.x) * (point2Prev.y - point1.y) - (point2Prev.x - point1.x) * (point2.y - point1.y) > 0 && (point2.x - point1.x) * (point2Next.y - point1.y) - (point2Next.x - point1.x) * (point2.y - point1.y) < 0) || ((point2.x - point1.x) * (point2Prev.y - point1.y) - (point2Prev.x - point1.x) * (point2.y - point1.y) < 0 && (point2.x - point1.x) * (point2Next.y - point1.y) - (point2Next.x - point1.x) * (point2.y - point1.y) > 0) || ((point1.x - point2.x) * (point1Prev.y - point2.y) - (point1Prev.x - point2.x) * (point1.y - point2.y) > 0 && (point1.x - point2.x) * (point1Next.y - point2.y) - (point1Next.x - point2.x) * (point1.y - point2.y) < 0) || ((point1.x - point2.x) * (point1Prev.y - point2.y) - (point1Prev.x - point2.x) * (point1.y - point2.y) < 0 && (point1.x - point2.x) * (point1Next.y - point2.y) - (point1Next.x - point2.x) * (point1.y - point2.y) > 0) ) { // in this case, node1 and node2 are not bitangent continue; } else { // otherwise, they are bitangent, add them as neighbor in RVGraph node1.addNeightbor(node2); node2.addNeightbor(node1); } } } } } } } // ------------------------ // add all terrain reflex vertices into the RVgraph foreach (Graph.Node node in terrainVertices) { if (node.vertexObject.CompareTag("ReflexVertex")) { rvgraph.addNode(node); } } // add all obstacle reflex vertices into the RVgraph foreach (ArrayList obstacleVertices in obstaclesList) { foreach (Graph.Node node in obstacleVertices) { if (node.vertexObject.CompareTag("ReflexVertex")) { rvgraph.addNode(node); } } } return(rvgraph); }
//run algorithm public Graph run(int k, ref Graph graph, int iterations) { genCount = 0; temp = graph; population = new Population();; float graphMaxFitness = graph.getGraphWeight(); population.init(k, ref graph, graphMaxFitness, rnd); Graph mst = null; if (strongest == null) { strongest = population.getFittest(); } else if (strongest.getFitness() > population.getFittest().getFitness()) { strongest = population.getFittest(); } //perform algorithm while fitness > target weight while (genCount < iterations) { genCount++; //perform selection selection(); int lestFitI = population.getLeastFittestIndex(); //do crossover crossover(); //add the fittest offspring to population addFittestOffspring(); population.calculateFitness(); //5% chance to mutate if (rnd.Next(0, 100) < 20) { mutation(); population.calculateFitness(); } if (strongest.getFitness() > fittest.getFitness()) { strongest = fittest; } } //build mst foreach (Edge e in strongest.chromosome) { if (mst == null) { mst = new Graph(); mst.addNode(e.node1); mst.addNode(e.node2); mst.addEdge(e.weight, e.node1, e.node2, e.data); } if (!mst.hasVertex(e.node1)) { mst.addNode(e.node1); } if (!mst.hasVertex(e.node2)) { mst.addNode(e.node2); } if (!mst.hasEdge(e)) { mst.addEdge(e.weight, e.node1, e.node2, e.data); } } return(mst); }
//Will create the graph treating all reachable areas as nodes private void createGraph() { currentGraph = new Graph(); int height = boolTiles.GetLength (0); int width = boolTiles.GetLength (1); //Here is where we form our graph //First we add all of the nodes for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { if (boolTiles[i, j] == true) { currentGraph.addNode(new Node(i, j)); } } } //Now we add all of our connections foreach(Node node in currentGraph.nodes.Values) { int nodeHeight = node.heightPos; int nodeWidth = node.widthPos; bool isUp = nodeHeight > 0; bool isRight = nodeWidth < (width - 1); bool isDown = nodeHeight < (height - 1); bool isLeft = nodeWidth > 0; /* //We need to check upper left pos if (isUp && isLeft && boolTiles[nodeHeight - 1, nodeWidth - 1]) { currentGraph.addEdge(node, currentGraph.getNodeByLocation(nodeHeight - 1, nodeWidth - 1)); } */ //We need to check upper pos if (isUp && boolTiles[nodeHeight - 1, nodeWidth]) { currentGraph.addEdge(node, currentGraph.getNodeByLocation(nodeHeight - 1, nodeWidth)); } /* //We need to check upper right pos if (isUp && isRight && boolTiles[nodeHeight - 1, nodeWidth + 1]) { currentGraph.addEdge(node, currentGraph.getNodeByLocation(nodeHeight - 1, nodeWidth + 1)); } */ //We need to check right pos if (isRight && boolTiles[nodeHeight, nodeWidth + 1]) { currentGraph.addEdge(node, currentGraph.getNodeByLocation(nodeHeight, nodeWidth + 1)); } /* //We need to check lower right pos if (isDown && isRight && boolTiles[nodeHeight + 1, nodeWidth + 1]) { currentGraph.addEdge(node, currentGraph.getNodeByLocation(nodeHeight + 1, nodeWidth + 1)); } */ //We need to check lower pos if (isDown && boolTiles[nodeHeight + 1, nodeWidth]) { currentGraph.addEdge(node, currentGraph.getNodeByLocation(nodeHeight + 1, nodeWidth)); } /* //We need to check lower left pos if (isDown && isLeft && boolTiles[nodeHeight + 1, nodeWidth - 1]) { currentGraph.addEdge(node, currentGraph.getNodeByLocation(nodeHeight + 1, nodeWidth - 1)); } */ //We need to check left pos if (isLeft && boolTiles[nodeHeight, nodeWidth - 1]) { currentGraph.addEdge(node, currentGraph.getNodeByLocation(nodeHeight, nodeWidth - 1)); } } }
public Graph parse() { Graph graph = new Graph(); string line; Random rng = new Random(); // Read the file and line by line and fill the graph. System.IO.StreamReader file = new System.IO.StreamReader(filepath); if (file == null) { Console.WriteLine ("file not found"); return null; } while((line = file.ReadLine()) != null) { if(line.Equals(" node")) { int id; string sid; string name; string[] words; char[] separatingChars = { ' ' }; file.ReadLine(); // [ sid = file.ReadLine(); // id ie. id 0 words = sid.Split(separatingChars, System.StringSplitOptions.RemoveEmptyEntries ); id = Int32.Parse(words[1]); name = file.ReadLine(); // name ie. lable "Beak" words = name.Split(separatingChars, System.StringSplitOptions.RemoveEmptyEntries ); name = words[1]; graph.addNode(new Graph.Node(id, name, rng.Next(-100, 100), rng.Next(-100, 100), rng.Next(-100, 100))); } else if(line.Equals(" edge")) { int target, source; string s; string[] words; char[] separatingChars = { ' ' }; file.ReadLine(); // [ s = file.ReadLine(); // source ie. source 19 words = s.Split(separatingChars, System.StringSplitOptions.RemoveEmptyEntries ); source = Int32.Parse(words[1]); s = file.ReadLine(); // target ie. target 1 words = s.Split(separatingChars, System.StringSplitOptions.RemoveEmptyEntries ); target = Int32.Parse(words[1]); graph.addEdge(source, target); } } file.Close(); return graph; }
//calculate the fitness public void calcFitness() { fitness = 0; bool actualtree = true; Graph temp = null; foreach (Edge e in chromosome) { //add to temporary graph to check if edges already exist if (temp == null) { temp = new Graph(); if (!temp.hasVertex(e.node1)) { temp.addNode(e.node1); } if (!temp.hasVertex(e.node2)) { temp.addNode(e.node2); } } if (!temp.hasVertex(e.node1)) { temp.addNode(e.node1); } if (!temp.hasVertex(e.node2)) { temp.addNode(e.node2); } //add edge to temp graph for comparisons if (temp.hasEdge(e)) { fitness += MaxFitness; actualtree = false; } if (!temp.hasEdge(e)) { temp.addEdge(e.weight, e.node1, e.node2, e.data); } //add the weight to fitness fitness += e.weight; } if (temp.GetEdges().Count != genes.Count - 1) { fitness += MaxFitness * 2; actualtree = false; } var ca = new classicAlgorithms(); Vertex startV = null; //chooese a start vertex that has more than 1 neighbour foreach (Vertex v in temp.GetVertices()) { if (v.neighbours.Count > 1) { startV = v; } } if (startV == null) { startV = temp.getRandomVertex(); } if (ca.checkCycle(temp, startV) && startV != null) { fitness += MaxFitness; actualtree = false; } if (actualtree == true) { fitness = temp.getGraphWeight(); } }
static void Main(String[] args) { int n = Convert.ToInt32(Console.ReadLine()); int m = Convert.ToInt32(Console.ReadLine()); int[,] grid = new int[n, m]; for (int grid_i = 0; grid_i < n; grid_i++) { string[] grid_temp = Console.ReadLine().Split(' '); for (int k = 0; k < m; k++) { grid[grid_i, k] = Convert.ToInt32(grid_temp[k]); } } Graph cells = new Graph(); // add all cells to the graph for (int i = 0; i < grid.GetLength(0); i++) { for (int j = 0; j < grid.GetLength(1); j++) { Point pt = new Point(i, j); cells.addNode(pt, grid[i, j]); // Console.Write("{0} ", grid[i,j]); } // Console.WriteLine(); } // the corners are special cases // add edges for upper left corner cells.addEdge((new Point(0, 0)).GetHashCode(), (new Point(0, 1)).GetHashCode()); cells.addEdge((new Point(0, 0)).GetHashCode(), (new Point(1, 1)).GetHashCode()); cells.addEdge((new Point(0, 0)).GetHashCode(), (new Point(1, 0)).GetHashCode()); // add edges for upper right corner cells.addEdge((new Point(0, m - 1)).GetHashCode(), (new Point(1, m - 1)).GetHashCode()); cells.addEdge((new Point(0, m - 1)).GetHashCode(), (new Point(1, m - 2)).GetHashCode()); cells.addEdge((new Point(0, m - 1)).GetHashCode(), (new Point(0, m - 2)).GetHashCode()); //add edges for lower left corner cells.addEdge((new Point(n - 1, 0)).GetHashCode(), (new Point(n - 2, 0)).GetHashCode()); cells.addEdge((new Point(n - 1, 0)).GetHashCode(), (new Point(n - 2, 1)).GetHashCode()); cells.addEdge((new Point(n - 1, 0)).GetHashCode(), (new Point(n - 1, 1)).GetHashCode()); // add edges for lower right corner cells.addEdge((new Point(n - 1, m - 1)).GetHashCode(), (new Point(n - 2, m - 1)).GetHashCode()); cells.addEdge((new Point(n - 1, m - 1)).GetHashCode(), (new Point(n - 2, m - 2)).GetHashCode()); cells.addEdge((new Point(n - 1, m - 1)).GetHashCode(), (new Point(n - 1, m - 2)).GetHashCode()); // add edges for first row - special case for (int k = 1; k < grid.GetLength(1) - 1; k++) { cells.AddEdge((new Point(0, k)).GetHashCode(), (new Point(0, k + 1)).GetHashCode()); cells.AddEdge((new Point(0, k)).GetHashCode(), (new Point(1, k + 1)).GetHashCode()); cells.AddEdge((new Point(0, k)).GetHashCode(), (new Point(1, k)).GetHashCode()); cells.AddEdge((new Point(0, k)).GetHashCode(), (new Point(1, k - 1)).GetHashCode()); cells.AddEdge((new Point(0, k)).GetHashCode(), (new Point(0, k - 1)).GetHashCode()); } // add edges for interior cells for (int m = 1; m < grid.GetLength(0) - 1; m++) { for (int n = 1; n < grid.GetLength(1) - 1; n++) { cells.AddEdge((new Point(m, n)).GetHashCode(), (new Point(m - 1, n - 1)).GetHashCode()); cells.AddEdge((new Point(m, n)).GetHashCode(), (new Point(m - 1, n)).GetHashCode()); cells.AddEdge((new Point(m, n)).GetHashCode(), (new Point(m - 1, n + 1)).GetHashCode()); cells.AddEdge((new Point(m, n)).GetHashCode(), (new Point(m, n + 1)).GetHashCode()); cells.AddEdge((new Point(m, n)).GetHashCode(), (new Point(m + 1, n + 1)).GetHashCode()); cells.AddEdge((new Point(m, n)).GetHashCode(), (new Point(m + 1, n)).GetHashCode()); cells.AddEdge((new Point(m, n)).GetHashCode(), (new Point(m + 1, n - 1)).GetHashCode()); cells.AddEdge((new Point(m, n)).GetHashCode(), (new Point(m, n - 1)).GetHashCode()); } } }
//execute the boruvka algorithm and returns mst //execute the boruvka algorithm and returns mst public Graph boruvka(ref Graph g) { List <Graph> components = new List <Graph>(); List <KeyValuePair <int, int> > mergeIndex = new List <KeyValuePair <int, int> >(); //set up each component with single vertices foreach (Vertex v in g.GetVertices()) { var graph = new Graph(); graph.addNode(v.data); components.Add(graph); } Edge minEdge; //loop through while there are more than 1 component while (components.Count > 1) { //loop through each component foreach (Graph comp in components) { minEdge = null; //find the smallest edge foreach (Vertex v in comp.GetVertices()) { foreach (Edge e in g.GetVertex(v.data).neighbours) { if (minEdge == null) { minEdge = e; } if (v.data != e.node1) { if (minEdge.weight > e.weight && !comp.hasVertex(e.node1)) { minEdge = e; } } else { if (minEdge.weight > e.weight && !comp.hasVertex(e.node2)) { minEdge = e; } } } } //add edge to component if (minEdge != null) { if (!comp.hasVertex(minEdge.node1)) { comp.addNode(minEdge.node1); } if (!comp.hasVertex(minEdge.node2)) { comp.addNode(minEdge.node2); } if (!comp.hasEdge(minEdge)) { comp.addEdge(minEdge.weight, minEdge.node1, minEdge.node2, minEdge.data); } if (components.IndexOf(comp) > 0) { for (int k = 0; k < components.IndexOf(comp); k++) { if (components[k].hasVertex(minEdge.node1) || components[k].hasVertex(minEdge.node2)) { mergeIndex.Add(new KeyValuePair <int, int>(components.IndexOf(comp), k)); break; } } } } } //remove components that are connected to other components if (mergeIndex.Count > 0) { for (int k = mergeIndex.Count - 1; k >= 0; k--) { components[mergeIndex[k].Value].mergeGraph(components[mergeIndex[k].Key]); } for (int k = mergeIndex.Count - 1; k >= 0; k--) { components.RemoveAt(mergeIndex[k].Key); } mergeIndex.Clear(); } //merge the last two components if (components.Count == 2) { Edge min = null; //select the component with least edges if (components[0].edges > components[1].edges) { //find the smallest edge foreach (Vertex v in components[1].GetVertices()) { foreach (Edge e in g.GetVertex(v.data).neighbours) { if (!components[0].hasEdge(e) && !components[1].hasEdge(e)) { if (min == null) { min = e; } else if (min.weight > e.weight) { min = e; } } } } components[0].mergeGraph(components[1]); components[0].addEdge(min.weight, min.node1, min.node2, min.data); components.RemoveAt(1); } else { //find the smallest edge foreach (Vertex v in components[0].GetVertices()) { foreach (Edge e in g.GetVertex(v.data).neighbours) { if (!components[1].hasEdge(e) && !components[0].hasEdge(e)) { if (min == null) { min = e; } else if (min.weight > e.weight) { min = e; } } } } components[1].mergeGraph(components[0]); components[1].addEdge(min.weight, min.node1, min.node2, min.data); components.RemoveAt(0); } } } return(components[0]); }
private void Start() { // get the car controller m_Car = GetComponent <CarController>(); terrain_manager = terrain_manager_game_object.GetComponent <TerrainManager>(); Transform ColliderBottom = m_Car.transform.Find("Colliders").Find("ColliderBottom"); Vector3 scale = ColliderBottom.localScale; Margin = scale.z / 2; sideMargin = scale.x / 2; // Plan your path here // Replace the code below that makes a random path // ... Vector3 start_pos = terrain_manager.myInfo.start_pos; goal_pos = terrain_manager.myInfo.goal_pos; Node StartNode = new Node(new Vector3(start_pos.x, 1, start_pos.z)); DroneGraph = new Graph(); DroneGraph.addNode(StartNode); int n = 3000; RRG(n, DroneGraph); killFuckers(DroneGraph); computeDiStanceToWall(DroneGraph); for (int i = 0; i < DroneGraph.getSize(); i++) { GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube); Collider c = cube.GetComponent <Collider>(); c.enabled = false; Vector3 position = DroneGraph.getNode(i).getPosition(); //Debug.Log("Node n." + i.ToString()); //foreach (object o in DroneGraph.getAdjList(i)) //{ // Debug.Log(o); //} cube.transform.position = new Vector3(position.x, 1, position.z); cube.transform.localScale = new Vector3(0.5f, 0.5f, 0.5f); for (int j = 0; j < DroneGraph.getAdjList(i).Count; j++) { Debug.DrawLine(DroneGraph.getNode(i).getPosition(), DroneGraph.getNode(DroneGraph.getAdjList(i)[j]).getPosition(), Color.red, 100f); //Debug.Log(DroneGraph.getNode(i).getPosition() +" - "+ DroneGraph.getNode(j).getPosition()); } //Debug.Log("Adj list of node " + i.ToString()); //var strings = string.Join(", ", DroneGraph.getAdjList(i)); //Debug.Log(strings); } Node goalN = DroneGraph.FindClosestNode(goal_pos, DroneGraph); int goal_idx = goalN.getId(); List <int> path = new List <int>(); //paths=dfs(DroneGraph, goal_idx); ASuperStar(DroneGraph, goal_idx); path = getBestPath(DroneGraph, goal_idx); Vector3 old_wp = start_pos; Debug.Log("Printing space now"); foreach (var wp in path) { //Debug.Log(Vector3.Distance(old_wp, DroneGraph.getNode(wp).getPosition())); Debug.DrawLine(old_wp, DroneGraph.getNode(wp).getPosition(), Color.cyan, 100f); old_wp = DroneGraph.getNode(wp).getPosition(); } my_path = pathHelp(DroneGraph, path); }
// Create the Graph and Add Nodes void InitializeGraphStructure() { if (InputData == InputType.StanfordSnap) { if (dataset != null) { // split each line if (graphData.Equals(String.Empty)) { String s = dataset.text.Replace("\r", "\n"); lines = s.Split("\n"[0]); print("loading previous dataset"); } else { graphData.Replace("\r", "\n"); lines = graphData.Split("\n"[0]); print("loading menu dataset"); } // loop through each line for (int i = 0; i < lines.Length; ++i) { string[] node_features = lines[i].Split(new char[0]); Node current_node = null; //print(node_features[0] + " : current Node"); // if node does not exist in graph if (graph.checkNode(node_features[0]) == null && node_features[0].Equals(String.Empty) == false) { current_node = new Node(node_features[0], ""); } else { // if node does exist in graph current_node = graph.checkNode(node_features[0]); } if (current_node != null) { // loop through each property of the text file for (int j = 0; j < node_features.Length; ++j) { //print(node_features[j]); // first node is label if (current_node.NodeID1.Equals(String.Empty)) { print("found empty node " + i); } if (j == 0 || current_node.NodeID1.Equals(String.Empty)) { } else { // if cluster size is lesser than.. if (j < 1000) { if (graph.checkNode(node_features[j]) == null && node_features[j] != "") { Node adjNode = new Node(node_features[j], ""); adjNode.addAdjacency(current_node); current_node.addAdjacency(adjNode); graph.addNode(adjNode); } else { if (graph.checkNode(node_features[j]) != null) { Node nodeFound = graph.checkNode(node_features[j]); current_node.addAdjacency(nodeFound); nodeFound.addAdjacency(current_node); graph.updateNode(nodeFound); } } } else { } } } // Add a node to the graph after setting it if (graph.checkNode(node_features[0]) == null) { graph.addNode(current_node); } else { graph.updateNode(current_node); } } } } } //axisScale = axisScale * (graph.nodes.Count / 1000); //k_clusters = graph.nodes.Count / 100; }
public void makeMap() { terrain_manager = terrain_manager_game_object.GetComponent <TerrainManager>(); print(terrain_manager); terrainInfo = terrain_manager.myInfo; print(terrainInfo); float[, ] traversability = terrainInfo.traversability; terrainInfo = terrain_manager.myInfo; float tileXSize = (terrainInfo.x_high - terrainInfo.x_low) / terrainInfo.x_N; float tileZSize = (terrainInfo.z_high - terrainInfo.z_low) / terrainInfo.z_N; float factor = 4.5f; float[, ] newTerrain = new float[(int)Mathf.Floor(tileXSize * tileXSize / factor), (int)Mathf.Floor(tileZSize * tileZSize / factor)]; stepx = (terrainInfo.x_high - terrainInfo.x_low) / newTerrain.GetLength(0); stepz = (terrainInfo.z_high - terrainInfo.z_low) / newTerrain.GetLength(1); for (int i = 0; i < newTerrain.GetLength(0); i++) { float posx = terrainInfo.x_low + stepx / 2 + stepx * i; for (int j = 0; j < newTerrain.GetLength(1); j++) { float posz = terrainInfo.z_low + stepz / 2 + stepz * j; newTerrain[i, j] = terrainInfo.traversability[terrainInfo.get_i_index(posx), terrainInfo.get_j_index(posz)]; } } int xLen = newTerrain.GetLength(0); int zLen = newTerrain.GetLength(1); nodeIdMatrix = new int[xLen, zLen]; mapGraph = new Graph(); int nodeId; float wallMargin = 2.0f; for (int i = 0; i < xLen; i++) { float posx = terrainInfo.x_low + stepx / 2 + stepx * i; for (int j = 0; j < zLen; j++) { float posz = terrainInfo.z_low + stepz / 2 + stepz * j; if (newTerrain[i, j] == 0.0f && 0.0f == checkTrav(posx, posz + wallMargin) && 0.0f == checkTrav(posx, posz - wallMargin) && 0.0f == checkTrav(posx + wallMargin, posz) && 0.0f == checkTrav(posx - wallMargin, posz)) { /*GameObject cube = GameObject.CreatePrimitive (PrimitiveType.Cube); * Collider c = cube.GetComponent<Collider> (); * c.enabled = false; * cube.transform.localScale = new Vector3 (0.5f, 0.5f, 0.5f); * cube.transform.position = new Vector3 (posx, 0, posz);*/ nodeIdMatrix[i, j] = mapGraph.addNode(new Node(posx, posz)); mapGraph.getNode(nodeIdMatrix[i, j]).setIndex(i, j); } else { nodeIdMatrix[i, j] = -1; } } } float timeDraw = 1; LayerMask mask = LayerMask.GetMask("Wall"); RaycastHit hit; for (int i = 0; i < xLen; i++) { for (int j = 0; j < zLen; j++) { if (nodeIdMatrix[i, j] != -1) { nodeId = nodeIdMatrix[i, j]; if (nodeIdMatrix[i, j + 1] != -1) { Debug.DrawLine(mapGraph.getNode(nodeId).getPosition(), mapGraph.getNode(nodeIdMatrix[i, j + 1]).getPosition(), Color.cyan, timeDraw); mapGraph.addEdge(nodeId, nodeIdMatrix[i, j + 1]); } if (nodeIdMatrix[i, j - 1] != -1) { Debug.DrawLine(mapGraph.getNode(nodeId).getPosition(), mapGraph.getNode(nodeIdMatrix[i, j - 1]).getPosition(), Color.cyan, timeDraw); mapGraph.addEdge(nodeId, nodeIdMatrix[i, j - 1]); } if (nodeIdMatrix[i + 1, j] != -1) { Debug.DrawLine(mapGraph.getNode(nodeId).getPosition(), mapGraph.getNode(nodeIdMatrix[i + 1, j]).getPosition(), Color.cyan, timeDraw); mapGraph.addEdge(nodeId, nodeIdMatrix[i + 1, j]); } if (nodeIdMatrix[i - 1, j] != -1) { Debug.DrawLine(mapGraph.getNode(nodeId).getPosition(), mapGraph.getNode(nodeIdMatrix[i - 1, j]).getPosition(), Color.cyan, timeDraw); mapGraph.addEdge(nodeId, nodeIdMatrix[i - 1, j]); } Vector3 from = mapGraph.getNode(nodeId).getPosition(); /* * if(nodeIdMatrix[i-1,j-1] != -1 && !Physics.Raycast(from , mapGraph.getNode(nodeIdMatrix[i-1,j-1]).getPosition()-from, out hit,Vector3.Distance(mapGraph.getNode(nodeIdMatrix[i-1,j-1]).getPosition(),from) , mask)){ * Debug.DrawLine(from,mapGraph.getNode(nodeIdMatrix[i-1,j-1]).getPosition(),Color.cyan,timeDraw); * mapGraph.addEdge(nodeId,nodeIdMatrix[i-1,j-1]);} * * * if(nodeIdMatrix[i-1,j+1] != -1 && !Physics.Raycast(from , mapGraph.getNode(nodeIdMatrix[i-1,j+1]).getPosition()-from, out hit,Vector3.Distance(mapGraph.getNode(nodeIdMatrix[i-1,j+1]).getPosition(),from) , mask)){ * Debug.DrawLine(from,mapGraph.getNode(nodeIdMatrix[i-1,j+1]).getPosition(),Color.cyan,timeDraw); * mapGraph.addEdge(nodeId,nodeIdMatrix[i-1,j+1]);} * * * if(nodeIdMatrix[i+1,j-1] != -1 && !Physics.Raycast(from , mapGraph.getNode(nodeIdMatrix[i+1,j-1]).getPosition()-from, out hit,Vector3.Distance(mapGraph.getNode(nodeIdMatrix[i+1,j-1]).getPosition(),from) , mask)){ * Debug.DrawLine(from,mapGraph.getNode(nodeIdMatrix[i+1,j-1]).getPosition(),Color.cyan,timeDraw); * mapGraph.addEdge(nodeId,nodeIdMatrix[i+1,j-1]);} * * * if(nodeIdMatrix[i+1,j+1] != -1 && !Physics.Raycast(from , mapGraph.getNode(nodeIdMatrix[i+1,j+1]).getPosition()-from, out hit,Vector3.Distance(mapGraph.getNode(nodeIdMatrix[i+1,j+1]).getPosition(),from) , mask)){ * Debug.DrawLine(from,mapGraph.getNode(nodeIdMatrix[i+1,j+1]).getPosition(),Color.cyan,timeDraw); * mapGraph.addEdge(nodeId,nodeIdMatrix[i+1,j+1]);}*/ } } } }
//execute the kruskal algorithm public Graph kruskal(ref Graph g) { Graph mst = null; List <Edge> edges = g.GetEdges(); Edge[] orderedEdges = new Edge[edges.Count]; Edge minEdge; int i = 0; //sort edges while (edges.Count != 0) { minEdge = null; foreach (Edge e in edges) { if (minEdge == null) { minEdge = e; } else if (e.weight < minEdge.weight) { minEdge = e; } } edges.Remove(minEdge); orderedEdges[i] = minEdge; i++; } //build mst for (int k = 0; k < orderedEdges.Length - 1; k++) { if (mst == null) { mst = new Graph(); mst.addNode(orderedEdges[k].node1); mst.addNode(orderedEdges[k].node2); mst.addEdge(orderedEdges[k].weight, orderedEdges[k].node1, orderedEdges[k].node2, orderedEdges[k].data); } if (mst.hasVertex(orderedEdges[k].node2) && mst.hasVertex(orderedEdges[k].node1)) { if (mst.GetVertex(orderedEdges[k].node2).neighbours.Count <= 2 && mst.GetVertex(orderedEdges[k].node1).neighbours.Count <= 2) { if (!mst.hasVertex(orderedEdges[k].node1)) { mst.addNode(orderedEdges[k].node1); } if (!mst.hasVertex(orderedEdges[k].node2)) { mst.addNode(orderedEdges[k].node2); } if (!mst.hasEdge(orderedEdges[k])) { mst.addEdge(orderedEdges[k].weight, orderedEdges[k].node1, orderedEdges[k].node2, orderedEdges[k].data); } if (checkCycle(mst, mst.GetVertex(orderedEdges[k].node1))) { mst.removeEdge(orderedEdges[k].node1, orderedEdges[k].data); mst.removeEdge(orderedEdges[k].node2, orderedEdges[k].data); } } } else if (!mst.hasVertex(orderedEdges[k].node1) || !mst.hasVertex(orderedEdges[k].node2)) { if (!mst.hasVertex(orderedEdges[k].node1)) { mst.addNode(orderedEdges[k].node1); } if (!mst.hasVertex(orderedEdges[k].node2)) { mst.addNode(orderedEdges[k].node2); } if (!mst.hasEdge(orderedEdges[k])) { mst.addEdge(orderedEdges[k].weight, orderedEdges[k].node1, orderedEdges[k].node2, orderedEdges[k].data); } } } return(mst); }
private void AddNode_Click(object sender, EventArgs e) { graph.addNode(new Node(NodeNameTf.Text, Double.Parse(NodeWeightTf.Text), Double.Parse(xTB.Text), Double.Parse(yTB.Text))); MessageBox.Show("Node added"); }