def run_Dijkstra(): N = 6 graph = go.GraphObj(N) # For loop goes here! # Possible to shorten code by over 10 lines... graph.add_node(go.Node(0), go.Node(1, dist=5)) graph.add_node(go.Node(0), go.Node(2, dist=1)) graph.add_node(go.Node(0), go.Node(3, dist=4)) graph.add_node(go.Node(1), go.Node(0, dist=5)) graph.add_node(go.Node(1), go.Node(2, dist=3)) graph.add_node(go.Node(1), go.Node(4, dist=8)) graph.add_node(go.Node(2), go.Node(0, dist=1)) graph.add_node(go.Node(2), go.Node(1, dist=3)) graph.add_node(go.Node(2), go.Node(3, dist=2)) graph.add_node(go.Node(2), go.Node(4, dist=1)) graph.add_node(go.Node(3), go.Node(0, dist=4)) graph.add_node(go.Node(3), go.Node(2, dist=2)) graph.add_node(go.Node(3), go.Node(4, dist=2)) graph.add_node(go.Node(3), go.Node(5, dist=1)) graph.add_node(go.Node(4), go.Node(1, dist=8)) graph.add_node(go.Node(4), go.Node(2, dist=1)) graph.add_node(go.Node(4), go.Node(3, dist=2)) graph.add_node(go.Node(4), go.Node(5, dist=3)) graph.add_node(go.Node(5), go.Node(3, dist=1)) graph.add_node(go.Node(5), go.Node(4, dist=3)) graph.create("dict", dt=np.object) start = 0 dijkstra = fsp_search.Dijkstra(graph.get()) path = dijkstra(start) return start, path
def main(): graph = Graph.Graph(edges_txt_src) #graph.show_edges() dijkstra = Dijkstra.Dijkstra(graph) dijkstra.shortestPath(1, 7) dijkstra.getPath(1, 7)
def main(): arrows, end_img, home_img = loadFiles() running = True g = grid(WIDTH, HEIGHT) # g.walls.append(vec(5, 5)) start = vec(3, 20) end = vec(30, 2) path = AStar(g, start, end) astar = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: if astar: astar = False else: astar = True if event.type == pygame.MOUSEBUTTONDOWN: pos = vec(pygame.mouse.get_pos()) // GRIDHEIGHT if event.button == 1: if pos not in g.walls: g.walls.append(pos) else: g.walls.remove(pos) elif event.button == 3: end = pos elif event.button == 2: start = pos if astar: path = AStar(g, start, end) else: path = Dijkstra(g, start, end) screen.fill((0, 0, 0)) g.drawGrid(screen) g.drawWalls(screen) for node in path: x, y = node rect = pygame.Rect(x * GRIDWIDTH, y * GRIDHEIGHT, GRIDWIDTH, GRIDHEIGHT) pygame.draw.rect(screen, (30, 30, 30), rect) if vec2tuple(start) in path: current = start + path[vec2tuple(start)] while current != end: x = current.x * GRIDWIDTH + GRIDWIDTH / 2 y = current.y * GRIDHEIGHT + GRIDHEIGHT / 2 a = vec2tuple(path[(current.x, current.y)]) img = arrows[a] screen.blit(img, img.get_rect(center=(x, y))) current = current + path[vec2tuple(current)] g.drawGrid(screen) g.draw_icons(screen, start, end, end_img, home_img) pygame.display.flip() pygame.quit()
def aplica_dijkstra(): if sys.version_info[0] < 3: pathDoArquivo = tk.Open().show() else: pathDoArquivo = filedialog.askopenfilename() G = nx.read_gexf(pathDoArquivo) G = dks.Dijkstra(G, G.nodes()[0]) pathDoArquivo = pathDoArquivo.replace(".gexf", "_Dijkstra.gexf") nx.write_gexf(G, pathDoArquivo) nx.draw(G) plt.show()
def run(): global flag, p, cost gui.redraw(height, width, cellSize, initializer.gridworld) if algoflag == 1: path = BFS().search(initializer.gridworld, start, goal) elif algoflag == 2: path = Dijkstra().search(initializer.gridworld, start, goal) else: path = AStar().search(initializer.gridworld, start, goal) if flag == False: if path == True and initializer.gridworld.cells[goal[0]][ goal[1]].visited == False: if algoflag == 1: BFS().search(initializer.gridworld, start, goal) elif algoflag == 2: Dijkstra().search(initializer.gridworld, start, goal) else: AStar().search(initializer.gridworld, start, goal) else: if algoflag == 1: p, explored, cost = BFS().makepath(initializer.gridworld) elif algoflag == 2: p, explored, cost = Dijkstra().makepath(initializer.gridworld) else: p, explored, cost = AStar().makepath(initializer.gridworld) flag = True gui.redraw(height, width, cellSize, initializer.gridworld) else: print('Path found!') print('The path is:', p) print('The cost is:', cost[goal]) print('GUI will exit in:', t, 'seconds') time.sleep(t) sys.exit() root.after(1, run)
def test4(): n = 10 m = 20 connection = gen_weighted_connection(n, m) g = create_graph(SparseWeightedGraph, n, connection) sp = WeightedShortestPath(g, 0) for i in xrange(n): sp.show_path(i) print "-" * 10 dij = Dijkstra(g, 0) for i in xrange(n): print i, dij.shortest_dist_to(i), dij.show_path(i)
def main(file="default.txt"): c = crud.Crud(file) r = c.read() co = r[0] col = r[0][0] r.remove(co) i = bp.BPLs(r, int(col)) i.Miner() j = diji.Dijkstra(r, int(col)) j.Miner() k = BEL.BELs(r, int(col)) k.Miner() l = aes.AEstrela(r, int(col)) l.Miner()
def buildDijkstra(self): """ Initializes the graph structure used by Antti's Dijkstra. Called automatically when needed. """ dijkstraNodes = self.tokensById.values( ) + self.dependenciesById.values() dijkstraEdges = [] for node in self.dependenciesById.values(): edgeIn = DijkstraEdge(node.fro, node) edgeOut = DijkstraEdge(node, node.to) node.incoming = [edgeIn] node.outgoing = [edgeOut] node.fro.outgoing.append(edgeIn) node.to.incoming.append(edgeOut) self.dijkstra = Dijkstra.Dijkstra(dijkstraNodes, dijkstraEdges)
def shortestPath(G, start, end): """ Find a single shortest path from the given start vertex to the given end vertex. The input has the same conventions as Dijkstra(). The output is a list of the vertices in order along the shortest path. """ D, P = Dijkstra(G, start, end) Path = [] while 1: Path.append(end) if end == start: break end = P[end] Path.reverse() return Path
def getDijkstraPaths(self, verbose=True): """Identifies all potential paths through the centerline of the vascular tree. It stores them in a dictionary paths. the key = index, value = the points along the path""" try: if (verbose): print "+++++ getDijkstraPaths +++++" # Run Dijkstra's algorithm import Dijkstra G = self.G self.seed = self.getGraphTarget() self.paths = {} maxPath = -1 maxPathNode = None count = 0 dpaths = Dijkstra.Dijkstra(G, self.seed) items = dpaths[0].items() items.sort(lambda x, y: int(x[1] - y[1]), reverse=True) self.paths = {} for ii in items: sind = ii[0] if (not self.paths.has_key(sind)): path = [sind] while (True): try: sind = dpaths[1][sind] path.append(sind) except: break self.paths[ii[0]] = path pathItems = self.paths.items() #creates a list of the paths pathItems.sort( lambda x, y: int(len(x[1]) - len(y[1])), reverse=True) #sorts the paths by length, longest to shortest self.maxPathNode = pathItems[0][ 0] #Identifies the location of the longest path node, where it begins self.maxPath = len(pathItems[0][1]) #Identifies the longest path except Exception, error: print "failed in getDijkstraPaths()", error sys.exit()
def runSearchAlgorithm(self, alg): if(self.startNode == None or self.endNode == None): return if alg.get() == "DFS": dfs = DFS(self.g,self.startNode, self.endNode, GUI = self) dfs.run() elif alg.get() == "BFS": bfs = BFS(self.g,self.startNode, self.endNode, GUI = self) bfs.run() elif alg.get() == "A*": a_star = A_Star(self.g, self.startNode, self.endNode, GUI = self) a_star.run() elif alg.get() == "WA*": w = simpledialog.askinteger("Input", "Choose a weight for WA*", parent=self.win, minvalue=0, maxvalue=10000) wa_star = WA_Star(self.g, self.startNode, self.endNode, weight = w, GUI = self) wa_star.run() else: dijkstra = Dijkstra(self.g, self.startNode, self.endNode, GUI=self) dijkstra.run()
def test_path(self): A = Node('A') B = Node('B') C = Node('C') D = Node('D') E = Node('E') F = Node('F') G = Node('G') H = Node('H') I = Node('I') J = Node('J') K = Node('K') L = Node('L') M = Node('M') A.add_connection(B, 4) A.add_connection(K, 10) A.add_connection(E, 5) B.add_connection(C, 7) K.add_connection(C, 6) K.add_connection(E, 7) K.add_connection(L, 15) K.add_connection(G, 6) E.add_connection(F, 7) F.add_connection(H, 4) F.add_connection(G, 2) H.add_connection(I, 1) G.add_connection(I, 5) G.add_connection(L, 2) I.add_connection(L, 3) I.add_connection(J, 4) J.add_connection(L, 11) J.add_connection(M, 1) M.add_connection(L, 2) L.add_connection(D, 5) D.add_connection(C, 9) dx = Dijkstra(A, J, [A, B, C, D, E, F, G, H, I, J, K, L, M]) self.assertEqual(dx.get_route(), "A->E->F->G->L->M->J", "The path should be \nA->E->F->G->L->M->J")
def Johnson(A): printCosts(A) N = len(A) d = potencjal(A) if not d: return None for v in range(N): for u in range(N): A[u][v] = A[u][v] + d[-1][u] - d[-1][v] print printCosts(A) d2 = [] for u in range(N): d2 = Dijkstra(u,A) #for u in range(N): # dfg = Dijkstra(u,A) # BLAD dla u=1 #for v in range(N): # A[u][v] = d2[v] + d[-1][u] - d[-1][v] return A
def aplica_todos(): if sys.version_info[0] < 3: pathDoArquivo = tk.Open().show() else: pathDoArquivo = filedialog.askopenfilename() G = nx.read_gexf(pathDoArquivo) M = krl.Kruskal(G) pathDoArquivoNovo = pathDoArquivo.replace(".gexf", "_MST_Kruskal.gexf") nx.write_gexf(M, pathDoArquivoNovo) M = pr.Prim(G, G.nodes()[0]) pathDoArquivoNovo = pathDoArquivo.replace(".gexf", "_MST_Prim.gexf") nx.write_gexf(G, pathDoArquivoNovo) M = bfs.BFS(G, G.nodes()[0]) pathDoArquivoNovo = pathDoArquivo.replace(".gexf", "_BFS.gexf") nx.write_gexf(M, pathDoArquivoNovo) M = dfs.DFS(G, G.nodes()[0]) pathDoArquivoNovo = pathDoArquivo.replace(".gexf", "_DFS.gexf") nx.write_gexf(M, pathDoArquivoNovo) M = dks.Dijkstra(G, G.nodes()[0]) pathDoArquivoNovo = pathDoArquivo.replace(".gexf", "_Dijkstra.gexf") nx.write_gexf(M, pathDoArquivoNovo) M = wp.WelshPowell(G, G.nodes()[0]) pathDoArquivoNovo = pathDoArquivo.replace(".gexf", "_WelshPowell.gexf") nx.write_gexf(M, pathDoArquivoNovo)
G[0][3].value = 30 G[0][4].value = 100 G[2][4].value = 10 G[3][2].value = 20 G[3][4].value = 60 print 'The Available Routes Are List As Follows: ' for i in range(0, n): for j in range(0, n): if G[i][j].value < inf: print '\t[', i + 1, ',', j + 1, '] ==> The Direct Distance is', G[ i][j].value print for i in range(0, n): S = [] Dijkstra.Dijkstra(S, G, n, i) print 'When The Source Vertex is', i + 1, '\n', '*' * 20 isEmpty = True for j in range(1, n): if S[j].distance < inf: isEmpty = False if isEmpty == True: print '\tThis Vertex Cannot Be The Source\n', '*' * 20, '\n' break for j in range(1, n): if S[j].distance < inf: print '\t[', i + 1, ',', S[ j].end + 1, '] ==> The Shortest Distance is', S[j].distance print '*' * 20, '\n'
G.add_node('s') G.add_node('y') G.add_node('z') G.add_edge('s', 't', weight=10) G.add_edge('t', 'x', weight=1) G.add_edge('s', 'y', weight=5) G.add_edge('t', 'y', weight=2) G.add_edge('y', 'z', weight=2) G.add_edge('y', 't', weight=3) G.add_edge('y', 'x', weight=9) G.add_edge('x', 'z', weight=4) G.add_edge('z', 'x', weight=6) G.add_edge('z', 's', weight=7) H = d.Dijkstra(G, 's') labels = {} for v1, v2, data in H.edges(data=True): labels[(v1, v2)] = data['weight'] # pos = nx.spring_layout(G) # nx.draw(G, pos) # nx.draw_networkx_edge_labels(G, pos, labels) pos = nx.spring_layout(H) nx.draw(H, pos) nx.draw_networkx_edge_labels(H, pos, labels) plt.show()
def main(): Dijkstra.Dijkstra()
# Dijkstra from Node import * from Dijkstra import * # all nodes start with dst = infinity a = Node('a') b = Node('b') c = Node('c') d = Node('d') e = Node('e') f = Node('f') g = Node('g') h = Node('h') # (node, weight) a.adj = {(b, 15), (c, 2), (d, 3)} b.adj = {(a, 15), (c, 8), (e, 2), (f, 1)} c.adj = {(a, 2), (b, 8), (f, 7), (g, 5)} d.adj = {(a, 3), (e, 1)} e.adj = {(b, 2), (d, 1)} f.adj = {(b, 1), (c, 7), (g, 2)} g.adj = {(c, 5), (f, 2), (h, 1)} h.adj = {(g, 1)} V = [a, b, c, d, e, f, g, h] Dijkstra(a, V) # fill V again since Dijkstra emptied it V = [a, b, c, d, e, f, g, h] print_shortest_paths(V)
from Dijkstra import * print("Taille du labyrinthe : 8") print("Nombre de répétition : 10") moyenneDistanceObjectif = 0 for _ in range(10): Labyrinthe, celluleDepart = DFS(8, 8) carteLabyrinthe = Dijkstra(Labyrinthe, celluleDepart) solutionLabyrinthe, distanceObjectif = cheminSolution(carteLabyrinthe) moyenneDistanceObjectif += distanceObjectif print("Moyenne : ", moyenneDistanceObjectif / 10) print("") print("Taille du labyrinthe : 16") print("Nombre de répétition : 10") moyenneDistanceObjectif = 0 for _ in range(10): Labyrinthe, celluleDepart = DFS(16, 16) carteLabyrinthe = Dijkstra(Labyrinthe, celluleDepart) solutionLabyrinthe, distanceObjectif = cheminSolution(carteLabyrinthe) moyenneDistanceObjectif += distanceObjectif print("Moyenne : ", moyenneDistanceObjectif / 10) print("") print("Taille du labyrinthe : 32") print("Nombre de répétition : 10") moyenneDistanceObjectif = 0 for _ in range(10): Labyrinthe, celluleDepart = DFS(32, 32) carteLabyrinthe = Dijkstra(Labyrinthe, celluleDepart) solutionLabyrinthe, distanceObjectif = cheminSolution(carteLabyrinthe) moyenneDistanceObjectif += distanceObjectif print("Moyenne : ", moyenneDistanceObjectif / 10)
DiW.addEdge(DiWeightedEdge.DiWeightedEdge(0,4,9)) DiW.addEdge(DiWeightedEdge.DiWeightedEdge(1,7,4)) DiW.addEdge(DiWeightedEdge.DiWeightedEdge(1,3,15)) DiW.addEdge(DiWeightedEdge.DiWeightedEdge(1,2,12)) DiW.addEdge(DiWeightedEdge.DiWeightedEdge(7,2,7)) DiW.addEdge(DiWeightedEdge.DiWeightedEdge(7,5,6)) DiW.addEdge(DiWeightedEdge.DiWeightedEdge(4,7,5)) DiW.addEdge(DiWeightedEdge.DiWeightedEdge(4,5,4)) DiW.addEdge(DiWeightedEdge.DiWeightedEdge(4,6,20)) DiW.addEdge(DiWeightedEdge.DiWeightedEdge(5,2,1)) DiW.addEdge(DiWeightedEdge.DiWeightedEdge(5,6,13)) DiW.addEdge(DiWeightedEdge.DiWeightedEdge(2,3,3)) DiW.addEdge(DiWeightedEdge.DiWeightedEdge(2,6,11)) DiW.addEdge(DiWeightedEdge.DiWeightedEdge(3,6,9)) Dij = Dijkstra.Dijkstra(DiW,8,0) ed= Dij.edgeTo[2] print ed.fromm()
import Dijkstra import Map import Node import PRM # size: list, a list which show max range of map, [min_x, max_x, min_y, max_y] # n: number of obstacle size = [0, 20, 0, 20] n = 1 # generate map map = Map.Map(size, n) initial = Node.Node(1, 1) goal = Node.Node(19, 19) number_of_node = 100 nearest_neighbor = 5 prm = PRM.PRM(map, number_of_node, nearest_neighbor, initial, goal) prm.Roadmap_construction() prm.solve_query() di = Dijkstra(prm) di.shorted_path() prm.Plot() di.Plot()
while(endNode == startNode): print("End node must not be start node") startNode = input("What is your start node? (0 to " + str(g.nodesWide * g.nodesTall - 1) + ")") startNode = int(startNode) endNode = input("What is your end node? (0 to " + str(g.nodesWide * g.nodesTall - 1) + ")") endNode = int(endNode) alg = input("What algorithm do you want to use? (1: BFS, 2: DFS, 3: Dijkstra's, 4: A*, 5: WA*)") while(alg not in ["1", "2", "3", "4", "5"]): alg = input("What algorithm do you want to use? (1: BFS, 2: DFS, 3: Dijkstra's)") if alg == "1": bfs = BFS(g, startNode, endNode) bfs.run() elif alg == "2": dfs = DFS(g, startNode, endNode) dfs.run() elif alg == "3": dijkstra = Dijkstra(g, startNode, endNode) dijkstra.run() elif alg == "4": a_star = A_Star(g, startNode, endNode) a_star.run() elif alg == "5": w = input("What weight would you like to use for WA* (1 to 10000)") w = int(w) while (w < 1 or w > 10000): print("Weight must be between 0 and 10000") w = input("What weight would you like to use for WA* (1 to 10000)") w = int(w) wa_star = WA_Star(g, startNode, endNode, weight=w) wa_star.run()
def main(): if len(sys.argv) == 2: configFileName = sys.argv[1] else: configFileName = "office.config" cfgReader = ConfigFileReader.ConfigFileReader(configFileName) ret, height, width, numRobots, R, baseX, baseY, initLocs, obstacles = cfgReader.readCfg( ) if ret == -1: print 'readCfg() Unsuccessful!' sys.exit(-1) else: print 'Read the config file', configFileName k = 2 T = 100000 algo = CAC.CAC(height, width, obstacles, numRobots, initLocs, T) if height <= 10: xoffset = 300 else: xoffset = 100 if width <= 10: yoffset = 300 else: yoffset = 100 maxScreenHeight = 700 cellSize = int(floor(maxScreenHeight / (height + 2))) root = Tk() gui = GridUI.GridUI(root, height, width, cellSize, algo.gridworld, algo.robots, algo.frontier) guiHeight = str((height + 2) * cellSize) guiWidth = str((width + 2) * cellSize) xOffset = str(xoffset) yOffset = str(yoffset) geometryParam = guiWidth + 'x' + guiHeight + '+' + xOffset + '+' + yOffset root.geometry(geometryParam) ALGOFLAG = 1 if ALGOFLAG == 1: astar = Dijkstra.Dijkstra() path, covered, cost = astar.aStarSearch(algo.gridworld, (0, 0), (35, 40)) cost = cost[(35, 40)] if ALGOFLAG == 2: astar = AStar.AStar() path, covered, cost = astar.aStarSearch(algo.gridworld, (0, 0), (35, 40)) cost = cost[(35, 40)] if ALGOFLAG == 3: astar = AStar_arjun.AStar() path, cost = astar.aStarSearch(algo.gridworld, (0, 0), (35, 40)) cost = cost[(35, 40)] if ALGOFLAG == 4: astar = JPS.JPS() covered = astar.jps(algo.gridworld, (0, 0), (35, 40)) path, cost = astar.full_path(covered) print 'cost:', cost if TIMER == True: print("--- %s seconds ---" % (time.time() - start_time)) def run(): gui.redraw(height, width, cellSize, algo.gridworld, algo.robots, path) #gui.redraw(height, width, cellSize, algo.gridworld, algo.robots, covered) root.after(1, run) root.after(1, run) root.mainloop()
np.savez(tmpfile, Nodespos=Nodespos, EdgesW=EdgesW, Nodes=Nodes, Map=Map) else: # Temporary load npzfile = np.load(tmpfile) Nodespos = npzfile[npzfile.files[0]] EdgesW = npzfile[npzfile.files[1]] Nodes = npzfile[npzfile.files[2]] Map = npzfile[npzfile.files[3]] plt.figure() plt.plot(Nodespos[0, :], Nodespos[1, :], '*r') plt.figure() plt.imshow(ndimage.interpolation.rotate(Map, 90)) ## Dijkstra algorithm simu StrNodeIndx = 0 EndNodeIndx = len( Nodes ) - 1 # The algorithm would try to find the minimum distance route to the endpt # Nodes_dist,Nodes_prev = Dijkstra_Path_Dist(Nodes,StrNodeIndx) path, path_length, pathpos = Dijkstra(Nodes, StrNodeIndx, EndNodeIndx) plt.figure() plt.plot(Nodespos[0, :], Nodespos[1, :], '*r') plt.plot(pathpos[0, :], pathpos[1, :], '--') ## plt.show()