def main(BP): klt_node = 'i' #The node, where the KLT should be dropped klt = False #Determine the shortest route through Dijkstra shortestWay1 = Dijkstra.dijkstra('a', klt_node) shortestWay2 = Dijkstra.dijkstra(klt_node, 'o') shortestWay2.pop(0) shortestWay = shortestWay1 + ["klt"] + shortestWay2 print('My route: ' + str(shortestWay)) shortestWay.pop(0) #Move the robot to the startnode ################ stop = follower.line_follower(BP, 400, 7, 0.01, [5]) if stop == "Red": #functions.driveforward_mm(BP, functions.marker_offset) print("Startkoten erreicht") #Build a loop which leads the robot through the network by using the route calculated above by Dijkstra ################ #Your code here# ################ while len(shortestWay) != 0: find_new_path(BP, shortestWay, klt_node) print("Naechster Node") stop = follower.line_follower(BP, 400, 7, 0.01, [5])
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 find_min_dist(self, start, vertex_list): #시작점 start, 꼭지점 리스트vertex_list graph = self.__graph_dict time = {} #꼭지점 : 시간 for v in vertex_list: time[v] = Dijkstra.dijkstra_path_time(self.__graph_dict, start, v) path = [start] min_time = 10000000 for vertex, time in time.items(): if min_time>time: min_time = time path = Dijkstra.dijkstra_path(self.__graph_dict, start, vertex) return path, min_time
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 initilization(): print('Initialize the environment') ParseTopologyFile.parse_aSHIIP_topology_bi_directional( POMDPSettings.TOPOLOGY_FILE_NAME, POMDPSettings.adjacent_matrix) if POMDPSettings.USER_INPUT_TARGET_NODE: while (True): print("Please enter the target node. Any number between [0-%s]" % (len(POMDPSettings.adjacent_matrix) - 1)) user_input_target_node = int(input()) if user_input_target_node > len(POMDPSettings.adjacent_matrix) - 1: print("No Such Node. Please try again") continue POMDPSettings.target_node.append( user_input_target_node ) ########### Assuming one target node currently, so index will be 0 break else: POMDPSettings.target_node = POMDPSettings.STATIC_TARGET_NODE print("Target Node : %s" % (POMDPSettings.target_node)) ############################################# Now we are assuming just one target for each POMDP agent ############################# target_resource = POMDPSettings.target_node[0] POMDPSettings.all_pair_shortest_path[ target_resource] = Dijkstra.Dijkstra_algorithm_unweighted( target_resource, POMDPSettings.adjacent_matrix) # PrintLibrary.all_pair_shortest_path_print(POMDPSettings.all_pair_shortest_path) ######## Print the shortest path knowledge ############# print('******* End of static environment initialization ***************')
def calculateEdgeBetweenness(self, graph): lstVertexes = graph.vertexes matBetweenness = {} for itr1 in range(len(lstVertexes)): matBetweenness[lstVertexes[itr1]] = {} for itr2 in range(len(lstVertexes)): matBetweenness[lstVertexes[itr1]][lstVertexes[itr2]] = 0.0 print("Calculating Betweenness ") for itr1 in range(len(lstVertexes)): print(".",end="") sys.stdout.flush() dist, path, routes = Dijkstra.performAllDestinationDijkstra(graph, lstVertexes[itr1]) for itr2 in range(len(lstVertexes)): if itr1 == itr2: continue # Remember that "routes" is a dictionary with a string key as a station name # lstVertexes[itr1] is the source # lstVertexes[itr2] is the destination # routes[lstVertexes[itr2] is the list of the station in the path between the source and the destination # You need to increase the matrix of the edge-betweenness if routes[lstVertexes[itr2]] != None: for itr3 in range(len(routes[lstVertexes[itr2]])-1): srcIncludedEdge = routes[lstVertexes[itr2]][itr3] dstIncludedEdge = routes[lstVertexes[itr2]][itr3+1] ?????????[srcIncludedEdge][dstIncludedEdge] = ?????????[srcIncludedEdge][dstIncludedEdge] + 1 ?????????[dstIncludedEdge][srcIncludedEdge] = ?????????[dstIncludedEdge][srcIncludedEdge] + 1 print() return matBetweenness
def determine_State_Space(): initialize_state_space_data_structure() ####################################### State Space Determination ##################################################################### ################### 1.1 First Find the shortest path ############################################################### for com_node in POMDPSettings.compromised_nodes_current_time: POMDPSettings.possible_nodes_for_state[ com_node] = Dijkstra.shortest_route(com_node, POMDPSettings.target_node[0], POMDPSettings.adjacent_matrix) print( "*************** Shortest Path from Source: %s to Destination : %s --> %s" "********************" % (com_node, POMDPSettings.target_node[0], POMDPSettings.possible_nodes_for_state[com_node])) ############## 1.2 Determine Possible State Space ################################################################## POMDPComponentGenerator.generate_initial_state_space( POMDPSettings.possible_nodes_for_state) ###################### 1.3 Determine their parent states ############################################################### POMDPComponentGenerator.update_state_value_from_leaves() for state in POMDPSettings.state_space: state.set_possible_parent_nodes() state.determine_state_value() Utilities.reachable_from_other_nodes()
def weiMaker(vertPos, edgeWei): X = np.empty(0, dtype=float) Y = np.empty(0, dtype=float) with open(vertPos, 'r') as file: AAA = csv.reader(file) for row in AAA: X = np.concatenate((X, [float(row[1])])) Y = np.concatenate((Y, [float(row[2])])) file.close() A = np.empty(0, dtype=int) B = np.empty(0, dtype=int) V = np.empty(0, dtype=float) with open(edgeWei, 'r') as file: AAA = csv.reader(file) for row in AAA: A = np.concatenate((A, [int(row[0])])) B = np.concatenate((B, [int(row[1])])) V = np.concatenate((V, [float(row[2])])) file.close() wei = Dijkstra.calcWei(X, Y, A, B, V) return wei
def dijkstra(): global picture, boton_kruskal, boton_edmonds, boton_dijkstra, boton_atras, e, window, s, t actualS() actualT() Dijkstra.main(s, t) e.destroy() borrar_botones() picture = 'path_Dijkstra.png' e = Example(window) e.pack(fill=BOTH, expand=YES) boton_atras = Button(window, text="atras", command=menu, bg="black", fg="white") boton_atras.place(x=0, y=0, width=100, height=30)
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 find_path(source , distination , mygraph) : update_wieght() path = Dijkstra.dijkstra(mygraph , source) mypath = [] while (distination != source ) : mypath.append(distination) distination = path[distination] mypath.append(source) return mypath
def compute_shortest_path(self, from_node, to_node, OVERLAY_GRAPH): ''' Call dijkstra's algorthm and return the shortest path. :param from_node: the root node :param to_node: the destination node :param OVERLAY_GRAPH: the overlay graph :return: the shortest path ''' path = Dijkstra.dijkstras(from_node, to_node, OVERLAY_GRAPH) return path
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 find_shortest_path(graph, start_node, end_node): path = Dijkstra.shortestpath(graph, start_node, end_node, visited=[], distances={}, predecessors={}) if path: return path[1]
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 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 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 eden(i): bfs = BFS.main("./labyrinths/" + i) print("---") ids = IDS.main("./labyrinths/" + i) print("---") dfs = DFS.main("./labyrinths/" + i) print("---") tss = TSS.main("./labyrinths/" + i) print("---") ast = AStar.main("./labyrinths/" + i) print("---") dijkstra = Dijkstra.main("./labyrinths/" + i) print("---") greedy = Greedy.main("./labyrinths/" + i) print("---") greedyHeuristics = GreedyHeuristics.main("./labyrinths/" + i) print("###########################################################################")
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 isomap(trainmatdata, testmatdata, k, type, dimenson): nodemat = hstack((trainmatdata, testmatdata)) #矩阵合并 nodenum = size(nodemat, 1) #节点数,即数据量 wgraph = mat(zeros((nodenum, nodenum))) - 1 #节点的连接权重矩阵,初始值都设为-1,表示无穷大 for num1 in range(nodenum): node1 = nodemat[:, num1] distances = [] #存储该节点到所有节点的距离(包括自身) for num2 in range(nodenum): node2 = nodemat[:, num2] distances.append(linalg.norm(node1 - node2)) #取最近的k+1个节点,将距离写入连接权重矩阵(距离最近的为自身) indices = argsort(distances) for count in range(k + 1): wgraph[num1, indices[count]] = distances[indices[count]] #将wgraph转化为对称矩阵,即无向图 for i in range(nodenum): for j in range(nodenum): if (wgraph[i, j] != -1): wgraph[j, i] = wgraph[i, j] #计算所有点对之间的最短距离 if (type == 'dijkstra'): distgraph = [] for i in range(nodenum): mindists = Dijkstra.dijkstra(wgraph, i) if (size(mindists) == 0): #图不连通 return [] distgraph.append(mindists) distgraph = mat(distgraph) elif (type == 'floyd'): distgraph = Floyd.floyd(wgraph) if (size(distgraph) == 0): #图不连通 return [] else: print u'最短距离算法类型错误' return [] #运行MDS算法 result = MDS.mds(distgraph, dimenson) return result
def create_map2(data_cross, data_road, car): vertexs = [False] # 顶点们 edges = dict() # 道路权值 for i in range(len(data_cross[0])): vertexs.append(ds.Vertex(i + 1, [])) for i in range(len(data_road[0])): value = data_road[1][i] / min(car[3], data_road[2][i]) if data_road[6][i] == 1: # 双行道 vertexs[data_road[4][i]].outList.append(data_road[5][i]) vertexs[data_road[5][i]].outList.append(data_road[4][i]) edges[(data_road[4][i], data_road[5][i])] = value edges[(data_road[5][i], data_road[4][i])] = value else: # 单行道 vertexs[data_road[4][i]].outList.append(data_road[5][i]) edges[(data_road[4][i], data_road[5][i])] = value vset = vertexs.copy() vset.remove(False) vset = set(vset) return vertexs, vset, edges
def init_data(): #拿到所有的街道节点 # street_nodes, list = data2map() street_nodes, list = data_to_map() #节点的个数 size = len(street_nodes) print("拿到所有的街道节点数据,共有%s个节点,下面开始写入文件中..." % size) #将计算得到的数据写入到txt文件中 for key in street_nodes: node = street_nodes[key] distance, path = Dijkstra.dijkstra(node, street_nodes, list) # print(type(distance)) print("拿到第%s节点的数据,开始写入到对应文件中.." % node.id) # file_path = "distances/distance" + str(node.id) + ".txt" file_path = "distances/distance" + str(node.id) + ".txt" print("%s文件写入完成" % file_path) DataOperate.write_distancedata_to_txt(distance, file_path) # file_path = "paths/path" + str(node.id) + ".txt" file_path = "paths/path" + str(node.id) + ".txt" print("%s文件写入完成" % file_path) DataOperate.write_distancedata_to_txt(path, file_path)
def View_path(): start = start_point.get() end = end_point.get() if start == "출발지 선택": return False if end == "도착지 선택": return False (arrival_time, path_list) = Dijkstra.dijkstra(start, end) folium_draw_line.draw_path(path_list) # 도착시간을 알려주는 label 추가 arrive_time = math.ceil(arrival_time) hour = (arrive_time - arrive_time % 60) / 60 arrive_time = deltaTime(hour, arrive_time % 60, 0) arrival_text = "도착 예정 시간은 " + \ str(arrive_time.hour)+"시 "+str(arrive_time.minute)+"분 입니다." arrive_label = tk.Label(window, text=arrival_text, bg="white", width=32, height=1, font=("맑은 고딕", 15), bd=1) arrive_label.place(x=162, y=240) # 경로를 알려주는 web을 여는 버튼 추가 way = tk.Button(window, text="!! Go To Check !!", font=("맑은 고딕", 15), relief="solid", fg='Green', bg='white', width=25, height=1, command=open_html) way.place(x=200, y=300)
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)
def calculate_path(self, start): g = Dijkstra.Graph() nodes = {} i = 0 for t in self.white_tiles: nodes[i] = t.id i += 1 for n in self.white_tiles: l = -1 vertex = {} for k in range(0, len(nodes)): if nodes[k] == n.id: l = k break for i in range(1, len(n.neighbour_ids) + 1): for j in range(0, len(nodes)): if n.neighbour_ids[i - 1][0] == nodes[j][ 0] and n.neighbour_ids[i - 1][1] == nodes[j][1]: tmp = str(j) vertex[tmp] = n.neighbour_distances[i] break l = str(l) g.add_vertex(l, vertex) s, t = 0, 0 for i in range(0, len(nodes)): if nodes[i] == start.id: s = str(i) if nodes[i] == self.target.id: t = str(i) tmp_path = g.shortest_path(s, t) path = [] for v in tmp_path: path.append(nodes.get(int(v))) return path
def initialization(): create_state_space() # Utilities.print_space_properties() ################ Print Space Properties ParseTopologyFile.parse_aSHIIP_topology(POMDPSettings.TOPOLOGY_FILE_NAME, POMDPSettings.adjacent_matrix) # Utilities.print_Topology(POMDPSettings.adjacent_matrix) ###################### What is the target node and find distance matrix of these nodes to other nodes ############################# while (True): print("Please enter the target node. Any number between [0-%s]" % (len(POMDPSettings.adjacent_matrix) - 1)) user_input_target_node = int(input()) if user_input_target_node > len(POMDPSettings.adjacent_matrix) - 1: print("No Such Node. Please try again") continue POMDPSettings.target_node.append( user_input_target_node ) ########### Assuming one target node currently, so index will be 0 break print("Target Node : %s" % (POMDPSettings.target_node)) Utilities.generate_inital_probability() print("Initial Belief %s" % (POMDPSettings.initial_belief_position)) POMDPSettings.all_pair_shortest_path[POMDPSettings.target_node[0]] = \ Dijkstra.Dijkstra_algorithm_unweighted(POMDPSettings.target_node[0],POMDPSettings.adjacent_matrix) POMDPModules.generate_initial_state()
def __init__(self): graph = Graph() self.outFile = open("output", 'w') try: filename = sys.argv[1] f = open(filename, 'r') for line in f: split = line.split() graph.addEdge(split[0], split[1], split[2]) f.close() except IndexError: print("Input file was not passed while calling the function") while(True): userInput = input().split() if userInput == None or len(userInput) == 0: continue self.writeInFile(" ".join(userInput)) command = userInput.pop(0) if command == "print": if len(userInput) != 0: print("print wont take argument.\nUsage :print") continue for key,value in sorted(graph.vertexMap.items()): if not graph.vertexMap[key].status: key += " DOWN" print(key) self.writeInFile(key) orderedAdj = sorted(value.adj, key = lambda x: x.destination.name) for edge in orderedAdj : s = "" if not edge.status: s = "DOWN" self.writeInFile((" %s %s %s" %(edge.destination.name, edge.transit_time, s))) print(" %s %s %s" %(edge.destination.name, edge.transit_time, s)) self.writeInFile("") elif command=="addedge": if len(userInput) != 3: print("addedge takes exactly 3 arguments.\nUsage :addedge <source Vertex> " "<destination Vertex> <transit time>") continue tailvertex, headvertex, transit_time = userInput[0],userInput[1], userInput[2] graph.updateEdge(tailvertex, headvertex, transit_time) elif command == "deleteedge": if len(userInput) != 2: print("addedge takes exactly 2 arguments.\nUsage :deleteedge <source Vertex> " "<destination Vertex>") continue tailvertex, headvertex = userInput[0],userInput[1] graph.deleteEdge(tailvertex, headvertex) elif command == "edgeup": if len(userInput) != 2: print("edgeup takes exactly 2 arguments.\nUsage :edgeup <source Vertex> " "<destination Vertex>") continue tailvertex, headvertex = userInput[0],userInput[1] graph.upEdgeStatus(tailvertex, headvertex) elif command == "edgedown": if len(userInput) != 2: print("edgedown takes exactly 2 arguments.\nUsage :edgedown <source Vertex> " "<destination Vertex>") continue tailvertex, headvertex = userInput[0],userInput[1] graph.downEdgeStatus(tailvertex, headvertex) elif command == "vertexup": if len(userInput) != 1: print("vertexup takes exactly 1 argument.\nUsage :vertexup <Vertex name>") continue vertex = userInput[0] graph.upVertexStatus(vertex) elif command == "vertexdown" : if len(userInput) != 1: print("vertexdown takes exactly 1 argument.\nUsage :vertexdown <Vertex name>") continue vertex = userInput[0] graph.downVertexStatus(vertex) elif command == "reachable": if len(userInput) != 0: print("reachable wont take argument.\nUsage :reachable") continue # BFS(graph).printReachableVerticesFromAllSource() self.graph = graph bfs = BFS(self.graph) self.printReachableVerticesFromAllSource(bfs) elif command == "path": if len(userInput) != 2: print("vertexdown takes exactly 2 argument.\nUsage :path <source Vertex>" " <destination Vertex>") continue source, destination = userInput[0],userInput[1] dijkstra = Dijkstra() source, destination = dijkstra.minPath(graph, source, destination) self.str = "" if self.printPath(source, destination) == "": self.str = "No path found from "+ source.name + " to "+ destination.name else: self.str += (" %.2f" % round(destination.d, 2)) print(self.str) self.writeInFile(self.str) elif command == "quit": sys.exit(0) else: print("Incorrect command. The following commands are available" "\nprint\naddedge\nedgedown\nedgeup\nvertexdown\nvertexup\nreachable\npath") pass self.outFile.close()
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys sys.path.append("../lib") import pprint import Dijkstra matrix=Dijkstra.loadMatrix("matrix.txt") graph=Dijkstra.convertMatrixToGraph(matrix, up=True, left=False) (vertices, edges)=graph vertices.extend(["begin", "end"]) lastIndex=len(matrix)-1 for i in range(0, len(matrix)): edges.append(("begin", (i, 0), matrix[i][0])) edges.append(((i, lastIndex), "end", 0)) newGraph=(vertices, edges) result=Dijkstra.shortestPath(newGraph, "begin", "end", 0) (distance, path)=result pprint.pprint(distance)
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()
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys sys.path.append("../lib") import pprint import Dijkstra matrix=Dijkstra.loadMatrix("matrix.txt") graph=Dijkstra.convertMatrixToGraph(matrix, up=True, left=True) lastIndex=len(matrix)-1 result=Dijkstra.shortestPath(graph, (0, 0), (lastIndex, lastIndex), matrix[0][0]) (distance, path)=result pprint.pprint(distance)
input_file = "tealady_tree.json" #input_file = "people_tree.json" tree = ConceptTree(input_file) tree.generateLattice_v2() for edge in tree.lattice: print(edge) for att in tree.attribute_labels: print att, tree.attribute_labels[att] #tree.visualiseLattice("testvis.gz", view=True) att_dict = tree.attribute_labels att_list = att_dict.keys() total = len(att_list) dist_matrix = np.zeros((total,total)) new_edge_list = [] for edge in tree.lattice: new_edge_list.append((edge[0], edge[1], 1)) new_edge_list.append((edge[1], edge[0], 1)) for i in range(total): if i % 100 == 0: print("Completed " + str(i) + " rows") for j in range(i+1, total): dist = Dijkstra.dijkstra(new_edge_list, att_dict[att_list[i]], att_dict[att_list[j]]) try: dist_matrix[i][j] = dist[0] except: dist_matrix[i][j] = dist print(dist_matrix)
def messageReceived(msg): global idRequestMax global rootObject global traitementTaxiEnCours global theShortestPath print("in messageReceived") print(msg) try: jsonReceived = json.loads(msg) if jsonReceived['id'] == 0: #Si le message vient du cab # si on n'est pas en train de traiter une requete if traitementTaxiEnCours == False: traitementTaxiEnCours = True print("from taxi (not traitementTaxiEnCours)") idRequest = jsonReceived['idCabRequest'] accepted = jsonReceived['accepted'] # si le taxi a accepté la requête if accepted == True: # request idRequest accepted # faire recherche de plus court chemin # { # "idCabRequest":0, # "area": "Quartier Nord", # "location": { # "area": "Quartier Nord", # "locationType": "vertex", # "location": "b" # } # } theShortestPath = [] for req in rootObject['cabRequest']: if req['idCabRequest'] == idRequest: print "from" print(unicode(str( rootObject['cabInfo']['loc_now']['area']) + "." + str(rootObject['cabInfo']['loc_now']['location']))) print "to" print(unicode(str(req['location']['area']) + "." + str( req['location']['location']))) #on calcule le chemin vers la destination theShortestPath = Dijkstra.doDijkstra(rootObject, unicode(str( rootObject['cabInfo']['loc_now']['area']) + "." + str( rootObject['cabInfo']['loc_now']['location'])), unicode(str(req['location']['area']) + "." + str( req['location']['location']))) print("theShortestPath after dodijkstra") print(theShortestPath) # et on lance le deplacement dans un nouveau thread mover = MoverRunner() mover.start() pass else: print("request rejected by taxi") pass # supprimer la requete effectuée avec l'id idRequest de la liste de requetes for req in rootObject["cabRequest"]: if req["idCabRequest"] == idRequest: rootObject["cabRequest"].remove(req) pass pass traitementTaxiEnCours = False else: #request idRequest rejected (rejection des reponses multiples du taxi (appui long sur le bouton)) print("from taxi rejected( traitementTaxiEnCours)") pass else: # msg from client print("from client") print(jsonReceived['cabRequest']) jsonReceived['cabRequest']['idCabRequest'] = idRequestMax + 1 print(jsonReceived['cabRequest']) idRequestMax += 1 print("----------------------------------") print("rootObject:") print(rootObject) rootObject['cabRequest'].append(jsonReceived['cabRequest']) print(rootObject) pass except Exception as n: print("Exception Received:") print(n) return pass
#!/usr/bin/python # Filename: Main.py import Dijkstra inf = float('inf') G = [] n = 5 for i in range(0, n): G.append([]) for j in range(0, n): G[i].append(Dijkstra.vertex(i, j)) G[0][1].value = 10 G[1][2].value = 50 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)