def store(self, distance_hash, n): self.order = n self._dbl_lvl_dict = _get_dbl_level_dict(distance_hash) sp_dijkstra = Dijkstra(self._dbl_lvl_dict, self.order) for i in range(self.order): self.ub_matrix.append([1] * self.order) for i in range(self.order): nodes = list(range(self.order)) sp = sp_dijkstra.shortest_path(nodes, i) for index in range(self.order): # distance, node, parent self.ub_matrix[i][index] = sp[index][0] self.ub_matrix[index][i] = sp[index][0] self.search_started = [False] * n for i in range(n): self.lb_matrix.append([0] * n) if n - i - 1 != 0: self.uncalculated[i] = set(range(i + 1, n)) for k in distance_hash.keys(): x, y = k self.lb_matrix[x][y] = distance_hash[k] self.lb_matrix[y][x] = distance_hash[k] self.uncalculated[min(x, y)].remove(max(x, y)) if len(self.uncalculated[min(x, y)]) == 0: del self.uncalculated[min(x, y)] self.sparse_matrix = SparseMatrix(distance_hash, n) if self.max_path_length == 2: for i in range(n): for j in range(i + 1, n): self._update(i, j) else: for i in range(n): self._dfs(i)
def test_tushar_roy(self): ''' example from Tushar Roy's video https://www.youtube.com/watch?v=lAXZGERcDf4 ''' start_vertex = 'a' verticies = ['a', 'b', 'c', 'd', 'e', 'f'] # edge_weights = {('a','b') : 2, ('a','f') : 4, ('a','d'):5, ('b','c') : 4, ('f','c') : 3, ('f','d') : 2, ('d','e') : 1} edge_weights = { ('a', 'b'): 2, ('a', 'f'): 4, ('a', 'd'): 5, ('b', 'c'): 4, ('c', 'f'): 3, ('d', 'f'): 2, ('d', 'e'): 1 } djk = Dijkstra(start_vertex, verticies, edge_weights) # pdb.set_trace() djk.iterate() # self.assertRaises(ValueError, djk.iterate) # print("parents=", djk.parents) self.assertEqual(6, len(djk.parents)) #parents is empty # print("parents=", djk.parents) self.assertEqual([], djk.parents['a']) self.assertEqual(['a'], djk.parents['b']) self.assertEqual(['a'], djk.parents['d']) self.assertEqual(['a'], djk.parents['f']) self.assertEqual(['b'], djk.parents['c'])
def store_nodeLandmarks(self): dijk_obj = Dijkstra(_get_dbl_level_dict(self.G, self.noNodes), self.noNodes) for landmark in self.nodeLandmarks: if landmark in self.sp: continue self.sp[landmark] = dijk_obj.shortest_path(self.vertices, landmark)
class DijkstraTest(PathTest, unittest.TestCase): def create_path(self, g, u, v): self.path = Dijkstra(g, u, v) def test_path_to_with_weight(self): g = Graph.from_dict({ 0: [(1, 5), (2, 10)], 1: [(4, 5)], 2: [(3, 1)], 3: [(5, 6)], 4: [(5, 5), (6, 10)], 5: [(6, 2)] }) self.create_path(g, 0, 6) self.assertListEqual(self.path.path_to(1), [0, 1]) self.assertListEqual(self.path.path_to(2), [0, 2]) self.assertListEqual(self.path.path_to(3), [0, 2, 3]) self.assertListEqual(self.path.path_to(4), [0, 1, 4]) self.assertListEqual(self.path.path_to(5), [0, 1, 4, 5]) def test_partial_path_with_weight(self): g = Graph.from_dict({ 0: [(1, 5), (2, 1)], 1: [(4, 5)], 2: [(3, 21)], 3: [(5, 6)], 4: [(5, 5), (6, 10)], 5: [(3, 1)] }) self.create_path(g, 0, 3) self.assertListEqual(self.path.path_to(1), [0, 1]) self.assertListEqual(self.path.path_to(2), [0, 2]) self.assertListEqual(self.path.path_to(3), [0, 1, 4, 5, 3])
def find_paths(self): self.d = Dijkstra(_get_dbl_level_dict(self.G), len(self.nodes)) self.dijkPaths = {} for each in self.sampled: for e in each: if self.dijkPaths.get(e, -1) == -1: self.dijkPaths[e] = self.d.shortest_path(self.nodes, e)
def JohnsonAlgorithm(graph: WeightedDirectedGraph, verbose=True): graph_edges_with_extra_node = graph.edges + [ WeightedEdge('new_node', 0, node) for node in graph.nodes ] graph_with_extra_node = WeightedDirectedGraph( graph_edges_with_extra_node.copy()) try: bf_shortest_distances, predecessors = BellmanFord( graph_with_extra_node, 'new_node', verbose=False) except Exception as e: return str(e) for edge in graph.edges: edge.weight = edge.weight + bf_shortest_distances[ edge.head] - bf_shortest_distances[edge.tail] all_pairs_shortest_distance = {} for source_node in graph.nodes: if verbose: print('\nShortest Distance with vertex ' + str(source_node) + ' as the source:\n') dijkstra_shortest_distances, predecessors = Dijkstra(graph, source_node, verbose=verbose) dijkstra_shortest_distances = { k: (v + bf_shortest_distances[k] - bf_shortest_distances[source_node]) for k, v in dijkstra_shortest_distances.items() } all_pairs_shortest_distance[source_node] = dijkstra_shortest_distances return all_pairs_shortest_distance
def main(): i = No("I") a = No("A") b = No("B") c = No("C") d = No("D") e = No("E") f = No("F") t = No("T") i.Conectar(a, 6) i.Conectar(b, 2) a.Conectar(c, 4) a.Conectar(e, 2) b.Conectar(a, 4) b.Conectar(c, 3) b.Conectar(d, 7) c.Conectar(e, 2) c.Conectar(d, 3) d.Conectar(t, 2) e.Conectar(t, 4) e.Conectar(f, 7) f.Conectar(t, 3) algoritmo = Dijkstra() caminho_mais_curto = algoritmo.EncontrarCaminhoMaisCurto(i, t) print(*InverterCaminho(caminho_mais_curto).items(), sep="\n")
def __init__(self, edge_list, order_val, k): self.edge_list = edge_list self.k = k self.order_val = order_val self.dbl_dict = _get_dbl_level_dict(self.edge_list) self.d = Dijkstra(self.dbl_dict, self.order_val) self.landmarks = None self.dijk_dict = {}
def generate_shortest_path_test(edges): print("\n### Generate shortest path test") try: d = Dijkstra(make_dict_graph(edges), "O", "T") distance_total, path = d.generate_shortest_path() print(f" {path} \n") except: print("Error")
def store_edgeLandmarks(self): dijk_obj = Dijkstra(_get_dbl_level_dict(self.G, self.noNodes), self.noNodes) for (x, y) in self.edgeLandmarks: if x not in self.sp: self.sp[x] = dijk_obj.shortest_path(self.vertices, x) if y not in self.sp: self.sp[y] = dijk_obj.shortest_path(self.vertices, y)
def test_one_point(self): ''' test simple 1 point ''' start_vertex = 0 verticies = [0] edge_weights = {} djk = Dijkstra(start_vertex, verticies, edge_weights) djk.iterate() # self.assertRaises(ValueError, djk.iterate) self.assertEqual(1, len(djk.parents)) #parents is empty self.assertEqual([], djk.parents[0]) self.assertEqual({0: 0}, djk.distances)
def main(stdscr, filename, player_x, player_y): curses.noecho() stdscr.keypad(True) for y, line in enumerate(open(filename, 'r').read()[:-1].split('\n')): for x, char in enumerate(line): if char == 'A': goal_x, goal_y = x, y dungeon = Dungeon(filename) dijkstra = Dijkstra(dungeon, goal_x, goal_y) dijkstra.find() while True: stdscr.clear() #dijkstra.find() path = list(dijkstra.pathFrom(player_x, player_y)) for y, line in enumerate(dungeon.cells): for x, cell in enumerate(line): if cell in path[1:]: stdscr.addch(y, x, '.') elif x == player_x and y == player_y: stdscr.addch(y, x, '@') else: stdscr.addch(y, x, cell.char) if len(path) != 0: dist = path[0].dist else: dist = float('inf') stdscr.addstr(20, 0, 'A: %s' % str(dist)) key = stdscr.getkey() if key == 'q': break elif key == 'h' or key == 'a': player_x -= 1 if player_x < 0: player_x += 1 elif key == 'l' or key == 'd': player_x += 1 if player_x >= len(dungeon.cells[0]): player_x -= 1 elif key == 'k' or key == 'w': player_y -= 1 if player_y < 0: player_y += 1 elif key == 'j' or key == 's': player_y += 1 if player_y > len(dungeon.cells) - 1: player_y -= 1
def dijkstra_algorithm_test(edges): print("\n### Dijkstra alogrith test") try: d = Dijkstra(make_dict_graph(edges), "O", "T") distance_total, prev = d.dijkstra_algorithm() print(f" Total distance: {distance_total}") for p in prev: if prev[p] != None: print(f" {prev[p]} ") except: print("Error...")
def testDijkstra(): filename = "testG1.txt" sparG = SparseGraph(5, True) ReadGraph(sparG, filename) #sparG.show() dij = Dijkstra(sparG, 0) for i in range(sparG.V()): if (dij.hasPathTo(i)): dij.showPath(i) else: print "No Path To %d " % i
def test_two_point(self): ''' test simple 2 point ''' start_vertex = 0 verticies = [0, 1] edge_weights = {(0, 1): 1} djk = Dijkstra(start_vertex, verticies, edge_weights) # pdb.set_trace() djk.iterate() # self.assertRaises(ValueError, djk.iterate) # print("parents=", djk.parents) self.assertEqual(2, len(djk.parents)) #parents is empty self.assertEqual([], djk.parents[0]) self.assertEqual([0], djk.parents[1]) self.assertEqual({0: 0, 1: 1}, djk.distances)
def main(filename): dungeon = Dungeon(filename) for y, line in enumerate(open(filename, 'r').read()[:-1].split('\n')): for x, char in enumerate(line): if char == 'A': Ax, Ay = x, y elif char == 'B': Bx, By = x, y dijkstra = Dijkstra(dungeon, Ax, Ay) dijkstra.find() path = dijkstra.pathFrom(Bx, By) print(list(path))
def test_dijkstra(self): graph = [[(2, 1), (5, 2)], [(2, 0), (4, 2), (6, 3), (10, 4)], [(5, 0), (4, 1), (2, 3)], [(2, 2), (6, 1), (1, 5)], [(10, 1), (3, 5), (5, 6)], [(1, 3), (3, 4), (9, 6)], [(5, 4), (9, 5)]] djk = Dijkstra() actual = djk.dijkstra(graph, 0) expected = [0, 2, 5, 7, 11, 8, 16] assert actual == expected actual = djk.dijkstra(graph, 0, 6) expected = [0, 2, 3, 5, 4, 6] assert actual == expected
def min_directional_distance(edge_id, adj_list): """Find the shortest directional distance from the specified edge to all the other edges in the graph. :param edge_id: the ID of the source edge :param adj_list: the adjacency list, e.g., G = [{1: 0, 26: 1, 50: 1}, {16: 1, 2: 0, 27: 1}, ...] indicates that the edge 0 is incident with the edges 1, 26, and 50, and distances from those edges are G[0][1] = 0, G[0][26] = 1, and G[0][50] = 1. :return: a dictionary of shortest directional distances from the specified edge """ num_lines = len( adj_list ) // 2 # the total number of line segments (i.e., undirected edges) source_id_1 = edge_id source_id_2 = edge_id + num_lines # Run dijkstra twice, respectively based on the two directed source edges D1, P1 = Dijkstra(adj_list, source_id_1) D2, P2 = Dijkstra(adj_list, source_id_2) # Compare D1 and D2 to get the shortest distance for each directed edge dict_min_dist = {} for k in D1: if k in D2: dict_min_dist[k] = min(D1[k], D2[k]) else: dict_min_dist[k] = D1[k] for k in D2: if k in D1: continue else: dict_min_dist[k] = D2[k] # Compare the pairs of flipped edges to find the real shortest distance for the line segment dict_real_min_dist = {} for k, v in dict_min_dist.items(): # find the ID of the opposite edge, assuming k is no smaller than the total number of line segments i = k - num_lines # find the ID of the opposite edge, assuming k is smaller than the total number of line segments j = k + num_lines if i >= 0: if i in dict_min_dist: dict_real_min_dist[i] = min(dict_min_dist[i], v) else: dict_real_min_dist[i] = v else: if j in dict_min_dist: dict_real_min_dist[k] = min(v, dict_min_dist[j]) else: dict_real_min_dist[k] = v return dict_real_min_dist
def test_four_point_a(self): ''' test simple 4 point ''' start_vertex = 0 verticies = [0, 1, 2, 3] edge_weights = {(0, 1): 1, (0, 2): 1, (1, 3): 1, (2, 3): 2} djk = Dijkstra(start_vertex, verticies, edge_weights) # pdb.set_trace() djk.iterate() # self.assertRaises(ValueError, djk.iterate) # print("parents=", djk.parents) self.assertEqual(4, len(djk.parents)) #parents is empty self.assertEqual([], djk.parents[0]) self.assertEqual([0], djk.parents[1]) self.assertEqual([0], djk.parents[2]) self.assertEqual([1], djk.parents[3]) self.assertEqual({0: 0, 1: 1, 2: 1, 3: 2}, djk.distances)
class Isochroner(): def __init__(self, grapher, starting_vertex): self.grapher = grapher self.dijkstra = Dijkstra(grapher.graph) self.starting_vertex = starting_vertex self.geoms_to_lines = self.assign_geoms_to_lines() def assign_geoms_to_lines(self): geom_aggregator = [] for edge in self.grapher.edges: geom_aggregator.append([edge.line(), edge.source(), edge.target()]) bus_lines = [row[0] for row in geom_aggregator] bus_lines = set(bus_lines) geom_to_lines = {line: [] for line in bus_lines} for row in geom_aggregator: geom_to_lines[row[0]].append((row[1], row[2])) return geom_to_lines def is_line_in_edge(self, line, edge): return edge in self.geoms_to_lines[line] def create_isochrones(self): isochrones = [] start = self.starting_vertex for vertex in self.grapher.graph.vertices(): if vertex != start: isochrones.append(self.dijkstra.min_path(start, vertex)) return isochrones
def __init__(self, locations, latitude_min, latitude_max, longitude_min, longitude_max): center_latitude = latitude_min + (latitude_max - latitude_min) // 2 center_longitude = longitude_min + (longitude_max - longitude_min) // 2 self.top_left_location = Location("top_left", latitude_min, longitude_min) self.bottom_right_location = Location("bottom_right", latitude_max, longitude_max) self.center_location = Location("center", center_latitude, center_longitude) self.width = calc_distance(latitude_min, center_longitude, latitude_max, center_longitude) self.height = calc_distance(center_latitude, longitude_min, center_latitude, longitude_max) self.locations = locations self.dijkstra = Dijkstra(self.locations) self.selected_citys = [] self.road_paths = []
def __init__(self, data, width, height, targets): self.mat = np.array(data, dtype="int32").reshape(height, width) self.potentials = {} graph, nodes = make_graph(self) self.pathfinding = Dijkstra(graph, nodes) self.generate_potential_for_targets(targets)
def __init__(self, graph, vertices_count): self.graph = graph extra_vertex = {} for tail in graph.keys(): for head in graph[tail]: extra_vertex[tail] = 0 extra_vertex[head] = 0 self.graph[0] = extra_vertex B = Bellman_ford(self.graph, vertices_count + 1, source_vertex=0) self.p_values = B.distances self.graph.pop(0) self.graph_double_prime = defaultdict(dict) for tail in graph.keys(): for head in graph[tail]: self.graph_double_prime[tail][head] = graph[tail][head] + self.p_values[tail] - self.p_values[head] self.shortest_paths_dist_prime = {} for i in range(1, vertices_count +1 ): print(i) D = Dijkstra(self.graph_double_prime, vertices_count, source_vertex=i) for j in D.shortest_path_dist.keys(): self.shortest_paths_dist_prime[(i, j)] = D.shortest_path_dist[j] self.shortest_path_dist = {} for tail, head in self.shortest_paths_dist_prime.keys(): self.shortest_path_dist[(tail, head)] = self.shortest_paths_dist_prime[(tail, head)] - self.p_values[tail] + self.p_values[head]
def create(self, method_name): if method_name == "dijkstra": return Dijkstra() elif method_name == "astar": return AStar() else: return AStar()
def johnson(network): """ Calculates the shortest path using Johnson's algorithm Parameters ---------- src : str, int An arbitrary node that does not exist in the STN. Returns ------- distance_matrix : List[List[int]] A 2-D list representing the shortest distances between all the nodes """ distance_matrix = [[] for x in range(network.length)] potential_function = BellmanFord.bellman_ford(network) if not potential_function: return False for node_idx in range(network.length): distance_matrix[node_idx] = Dijkstra.dijkstra( network, node_idx, potential_function=potential_function) if network.flag: network.flag = False # network.distance_matrix = distance_matrix return distance_matrix
def path_callback(self, map): self.map = map if self.firstCall == False: rospy.loginfo("+++++++++++++++++initX: " + str(self.initx) + " initY: " + str(self.inity) + " goalX: " + str(self.goalx) + " goalY: " + str(self.goaly)) self.firstCall = True if self.world != 0: dijkstra = Dijkstra(self.map) self.path = dijkstra.planning(self.initx, self.inity, self.goalx, self.goaly) self.save_as_yaml(self.path) x, y = self.path x = x[::-1] y = y[::-1] my_path = Path() my_path.header.frame_id = "map" my_path.header.stamp = rospy.get_rostime() size = range(len(self.path[0])) poses = [] for i in size: p_stamp = PoseStamped() p_stamp.pose.position.x = x[i] p_stamp.pose.position.y = y[i] p_stamp.pose.position.z = 0 p_stamp.header.frame_id = "map" p_stamp.header.stamp = rospy.get_rostime() poses.append(p_stamp) my_path.poses = poses self.pathPublisher.publish(my_path) else: poses = [] self.path = [(self.goalx, self.goaly)] my_path = Path() my_path.header.frame_id = "map" my_path.header.stamp = rospy.get_rostime() for i in range(2): p_stamp = PoseStamped() p_stamp.pose.position.x = self.goalx p_stamp.pose.position.y = self.goaly p_stamp.pose.position.z = 0 p_stamp.header.frame_id = "map" p_stamp.header.stamp = rospy.get_rostime() poses.append(p_stamp) my_path.poses = poses self.pathPublisher.publish(my_path)
def test2(): inf = np.inf scan=[inf, inf, inf, inf, inf, inf, 2.122950792312622, 1.8218177556991577, 1.59413743019104, 1.423231601715088, 1.323502540588379, 1.3081393241882324, 1.3145588636398315, 1.3490028381347656, 1.335472822189331, 1.319705605506897, 1.3400593996047974, 1.3491653203964233, 1.3466880321502686, 1.3696467876434326, 1.3745601177215576, 1.3833107948303223, 1.3923722505569458, 1.4062138795852661, 1.3897963762283325, 1.4243078231811523, 1.4298373460769653, 1.4416676759719849, 1.450016736984253, 1.471937656402588, 1.5024218559265137, 1.4850928783416748, 1.5270593166351318, 1.5272008180618286, 1.5350757837295532, 1.5613079071044922, 1.58877432346344, 1.6090070009231567, 1.6587506532669067, 1.6668319702148438, 1.6823045015335083, 1.711564540863037, 1.7509064674377441, 1.7584381103515625, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, 2.650038242340088, 2.6445717811584473, 2.631784677505493, 2.6164636611938477, 2.6125850677490234, 2.5924696922302246, 2.5889229774475098, 2.5727877616882324, 2.5825552940368652, 2.5913491249084473, 2.5679054260253906, 2.575549840927124, 2.5961365699768066, 2.578033447265625, 2.563906669616699, 2.576000690460205, 2.586289644241333, 2.5772287845611572, 2.5811655521392822, 2.5825459957122803, 2.588222026824951, 2.5943994522094727, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, 2.9890737533569336, 2.9071550369262695, 2.8188626766204834, 2.7494678497314453, 2.67634916305542, 2.6266491413116455, 2.5653467178344727, 2.5333642959594727, 2.4661786556243896, 2.4012131690979004, 2.3687829971313477, 2.323002338409424, 2.2887566089630127, 2.2677664756774902, 2.296781539916992, 2.3500185012817383, 2.360821008682251, 2.453289031982422, 2.4872214794158936, 2.548398017883301, 2.6022679805755615, 2.6568949222564697, 2.7322375774383545, 2.7981326580047607, 2.8849222660064697, 2.9328646659851074, 3.0372416973114014, inf, inf, inf, inf, inf, 3.4685451984405518, 3.4392693042755127, 3.423564910888672, 3.389524221420288, 3.3799402713775635, 3.355445146560669, 3.335869073867798, 3.295499086380005, 3.285273551940918, 3.2675883769989014, 3.2415120601654053, 3.2439682483673096, 3.21799898147583, 3.207578659057617, 3.2076492309570312, 3.3214356899261475, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, 1.7193019390106201, 1.679825782775879, 1.650679349899292, 1.6179615259170532, 1.5983997583389282, 1.5532128810882568, 1.5364797115325928, 1.5386948585510254, 1.5013322830200195, 1.4845850467681885, 1.4534012079238892, 1.444892168045044, 1.4262295961380005, 1.4062203168869019, 1.4057549238204956, 1.3824982643127441, 1.367220163345337, 1.3536320924758911, 1.3183528184890747, 1.3393183946609497, 1.312820553779602, 1.3034974336624146, 1.2918084859848022, 1.2986373901367188, 1.2754086256027222, 1.271276831626892, 1.2715413570404053, 1.2496140003204346, 1.220840334892273, 1.259627103805542, 1.2267930507659912, 1.2130810022354126, 1.2276153564453125, 1.2212096452713013, 1.281704306602478, 1.3779208660125732, 1.5410783290863037, 1.7324031591415405, 1.9674873352050781, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, 2.966913938522339, 2.879478931427002, 2.812376022338867, 2.7323076725006104, 2.667478322982788, 2.613341808319092, 2.5557971000671387, 2.4918932914733887, 2.439162492752075, 2.3888156414031982, 2.3447256088256836, 2.304054021835327, 2.2600510120391846, 2.2221076488494873, 2.216076374053955, 2.2552261352539062, 2.31876802444458, 2.357189178466797, 2.396010398864746, 2.4466495513916016, 2.4985275268554688, 2.564828395843506, 2.634127140045166, 2.671659231185913, 2.7563955783843994, 2.829598903656006, 2.9014203548431396, 2.9869801998138428, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf] o = Mapper() prob_map = Mapper.main(o,scan) d =Dijkstra() d(prob_map , [36,36], [50,30]) print('\n ' + '-'*30 + "\n> Starting operation ...\n " + '-'*30 + '\n') start_time = time.time() final_path = d.find_path() print('\n ' + '-'*30 + "\n> Time taken: {:.4} seconds.\n ".format(time.time() - start_time) + '-'*30 + '\n') d.draw_final_graph(final_path)
def get_route(vehicle): if vehicle.path_finder_algorithm == PathFinderAlgorithm.VALIDATOR: """ DIJKSTRA """ start = time.time() d_path, d_visited = Dijkstra.find_route_nodes(vehicle) path = PathFinder._print_route_results(start, d_path, d_visited, vehicle, 'Dijkstra') """ ALT ALGORITHM """ start = time.time() alt_path, alt_visited = Alt.find_route_nodes(vehicle) PathFinder._print_route_results(start, alt_path, alt_visited, vehicle, 'ALT') """ A STAR ALGORITHM """ start = time.time() a_star_path, a_star_visited = AStar.find_route_nodes(vehicle) PathFinder._print_route_results(start, a_star_path, a_star_visited, vehicle, 'A*') if GeneralSettings.debug_print: print "--------------------------------------------------------" return path if vehicle.path_finder_algorithm == PathFinderAlgorithm.DIJKSTRA: start = time.time() path, _ = Dijkstra.find_route_nodes(vehicle) if GeneralSettings.debug_print: print("Dijkstra.get_route elapsed time: %.2f ms" % ((time.time() - start) * 1000)) return path elif vehicle.path_finder_algorithm == PathFinderAlgorithm.ALT: start = time.time() path, _ = Alt.find_route_nodes(vehicle) if GeneralSettings.debug_print: print("Alt.get_route elapsed time: %.2f ms" % ((time.time() - start) * 1000)) return path elif vehicle.path_finder_algorithm == PathFinderAlgorithm.A_STAR: start = time.time() path, _ = AStar.find_route_nodes(vehicle) if GeneralSettings.debug_print: print("A star.get_route elapsed time: %.2f ms" % ((time.time() - start) * 1000)) return path else: raise ValueError("Invalid vehicles path finder algorithm value.")
class Grid(object): """Represents the field for the walkers data -- contains the map representation according to config.Cell. Use ioutil.parse_map to generate the input. width -- the width of the given map data height -- the height of the given map data targets -- list of targets for which a potential should be generateted """ def __init__(self, data, width, height, targets): self.mat = np.array(data, dtype="int32").reshape(height, width) self.potentials = {} graph, nodes = make_graph(self) self.pathfinding = Dijkstra(graph, nodes) self.generate_potential_for_targets(targets) def generate_potential_for_targets(self, targets): # Generate potential fields for target in targets: x, y = target["pos"] if not self.is_empty(target["pos"]): raise RuntimeError("Tried to place a target on an occupied cell") p = self.pathfinding.calc_potential(x, y) self.potentials[target["name"]] = p # Place Target on map self.mat[x, y] = Cell.TARGET def is_empty(self, pos): x, y = pos[0], pos[1] return self.mat[x, y] in (Cell.EMPTY, Cell.TARGET) @staticmethod def neighbour_pos_in_direction(pos, direction): return pos + decode_rot(direction) @property def width(self): return self.mat.shape[1] @property def height(self): return self.mat.shape[0] def find_obstacles(self): """Returns a list of tuple containing the obstacles of the map (including the outer borders)""" return [(x, y) for x, y in product(range(self.height), range(self.width)) if self.mat[x, y] == Cell.WALL] def __getitem__(self, pos): return self.mat[tuple(pos)] def __setitem__(self, pos, val): self.mat[tuple(pos)] = val
def runRerouting(obstacle_list, start_grid, end_grid, is_save=False): # start and goal position sx = start_grid[0] # [m] sy = start_grid[1] # [m] gx = end_grid[0] # [m] gy = end_grid[1] # [m] grid_size = 0.4 # [m] robot_radius = 0.3 # [m] # set obstacle positions ox, oy = [], [] path = [] for i in range(len(obstacle_list)): ox.append(obstacle_list[i][0]) oy.append(obstacle_list[i][1]) if show_animation: # pragma: no cover plt.title("Rerouting") plt.plot(ox, oy, ".k") plt.plot(sx, sy, "og") plt.plot(gx, gy, "xb") plt.grid(True) plt.axis("equal") dijkstra = Dijkstra(ox, oy, grid_size, robot_radius) rx, ry = dijkstra.planning(sx, sy, gx, gy) for i in range(len(rx)): path.append([i, 1]) path.append([rx[i], ry[i]]) if show_animation: # pragma: no cover plt.plot(rx, ry, "-r") if is_save: fig = plt.gcf() fig.savefig(save_path + 'task3_rerouted.png') plt.pause(0.01) plt.show() plt.close('all') return path
def setup_algos(root): controller = root.winfo_children()[0] cell_grid = root.winfo_children()[1].winfo_children()[0] a_star = Astar(cell_grid) Button(controller, text="A*", width=10, command=a_star.trace).grid(row=0, column=8) dijkstra = Dijkstra(cell_grid) Button(controller, text="Dijkstra", width=10, command=dijkstra.trace).grid(row=1, column=8)
def __init__(self): self.fr = FlowRetrieval() self.fs = FlowStatistics() self.fm = FlowManagement() self.dj = Dijkstra() self.g = Graph() #self.fm.deleteAllFlow() try: self.hostlist = self.fs.list_of_hosts() self.switchlist = self.fs.list_of_switches() except: traceback.print_exc() self.hostdict = {} for i in range(1, len(self.hostlist) + 1): self.hostdict[i] = self.hostlist[i - 1] self.switchdict = {} for i in range(1, len(self.switchlist) + 1): self.switchdict[i] = self.switchlist[i - 1]
def x_reach(edge_id, max_cross, adj_list, na_seg_len): """Conduct intersection reach analysis. :param edge_id: the ID of the source edge :param max_cross: the maximum number of intersections allowed to cross :param adj_list: an adjacency list, e.g., G = [{12: 0, 1: 1, 24: 1}, {0: 1, 24:1, 2: 1, 16:1}, ...] indicates that the edge 0 is adjacent with edges 12, 1, and 24, and the cross distances from those edges are G[0][12] = 0, G[0][1] = 1, and G[0][24] = 1. :param na_seg_len: a list listing the length of each line segment :return: the total street length accessible within max_cross intersections and the list of lines that can be reached """ D, P = Dijkstra(adj_list, edge_id) # find all the edges that are no more than max_cross intersections away from the source edge list_reached_edges = [k for k, v in D.items() if v <= max_cross] # compute the total length of the reached edges total_len = 0 for i in list_reached_edges: total_len += na_seg_len[i] return total_len, list_reached_edges
def test_dijkstra(): graph = Graph() nodes = [] while True: str = input() if str == "-1": break first, second, weight = str.split(' ') if first not in nodes: nodes.append(first) if second not in nodes: nodes.append(second) graph.add_edge(first, second, int(weight)) dijkstra = Dijkstra(graph, nodes[0]) dijkstra.do_dijkstra() print("weights : ") for v in nodes: print("%s : %s" % (v, dijkstra.get_distance(v))) mst = [] for n in nodes: path = dijkstra.get_path(n) if len(path) == 1: continue for i in range(len(path) - 1): edge = path[i] + " ---- " + path[i + 1] if edge not in mst: mst.append(edge) print("MST : ") for edge in mst: print(edge)
class AStar: def __init__(self, graph, start, target): self._dijkstra = Dijkstra(graph, start, target, lambda f : f.distance + f.get_heuristic(target)) self._comparison = 0 self._moviments = 0 self._iterations = 0 @property def comparison(self): return self._comparison @property def moviments(self): return self._moviments @property def iterations(self): return self._iterations def run(self): self._dijkstra.run() self._comparison = self._dijkstra.comparison self._moviments = self._dijkstra.moviments self._iterations = self._dijkstra.iterations
def main(): # First create a grid with grid.py grid = createGrid() # Then pass the grid to be processed by the Dijkstra algorithm # Note that I break encapsulation of the grid.py context here. # Good or bad...? dijkstraGrid = Dijkstra(grid) dijkstraGrid.printShortestPathFor('a', 'k') # I need a fresh grid if I want to do it twice. # See what I mean about context scoped state? # The old grid should be clean of Dijkstra state... grid = createGrid() dijkstraGrid = Dijkstra(grid) dijkstraGrid.printShortestPathFor('h', 'b')
import dijkstra from dijkstra import Dijkstra from adapton_list import * dijkstra.key = dijkstra.BINARY_DOUBLE_KEY test1 = Dijkstra(6, [0, 0, 1, 1, 2, 3, 4], [1, 2, 3, 4, 4, 5, 5], l2ll([5, 5, 5, 5, 5, 5, 5])) trace1 = test1.compute_trace(0) dis11 = test1.compute_dis(0, trace1) dis12 = test1.compute_dis(0, [0, 1, 2, 3, 4, 5]) if dis11 != [0, 5, 5, 10, 10, 15]: print "Test Case 1 Fail!" elif dis12 != [0, 5, 5, 10, 10, 15]: print "Test Case 1 Fail!" else: print "Test Case 1 Pass!" test2 = Dijkstra(6, [0, 0, 1, 1, 2, 3, 4], [1, 2, 3, 4, 4, 5, 5], l2ll([5, 4, 5, 5, 5, 5, 5])) trace2 = test2.compute_trace(0) dis2 = test2.compute_dis(0, trace2) if dis2 != [0, 5, 4, 10, 9, 14]: print "Test Case 2 Fail!" else: print "Test Case 2 Pass!" test3 = Dijkstra(6, [0, 0, 1, 1, 2, 3, 4], [1, 2, 3, 4, 4, 5, 5], l2ll([5, 4, 5, 5, 7, 5, 5])) trace3 = test3.compute_trace(0) dis3 = test3.compute_dis(0, trace3) if dis3 != [0, 5, 4, 10, 10, 15]: print "Test Case 3 Fail!" else:
import dijkstra from dijkstra import Dijkstra from Adapton.Lazy import * # You need to add AdaptonPython/Source to the PYTHONPATH from adapton_list import * dijkstra.key = dijkstra.BINARY_DOUBLE_KEY test1 = Dijkstra(6, [0,0,1,1,2,3,4,0], [1,2,3,4,4,5,5,0], l2ll([5,5,5,5,5,5,5,0])) trace1 = test1.compute_trace(0) dis11 = test1.distances_adap(0, trace1) dis12 = test1.distances_adap(0, [0,1,2,3,4,5]) print ll2l(dis11) if (ll2l(dis11) != [0,5,5,10,10,15]): print "Test Case 1 Fail!" elif (ll2l(dis12) != [0,5,5,10,10,15]): print "Test Case 1 Fail!" else: print "Test Case 1 Pass!" test2 = Dijkstra(6, [0,0,1,1,2,3,4,0], [1,2,3,4,4,5,5,0], l2ll([5,4,5,5,5,5,5,0])) trace2 = test2.compute_trace(0) dis2 = test2.distances_adap(0, trace2) print "Distance: ", ll2l(dis2) if (ll2l(dis2) != [0,5,4,10,9,14]): print "Test Case 2 Fail!" else: print "Test Case 2 Pass!" input_ad3 = l2ll([5,4,5,5,7,5,5,0]) test3 = Dijkstra(6, [0,0,1,1,2,3,4,0], [1,2,3,4,4,5,5,0], input_ad3) trace3 = test3.compute_trace(0)
def __init__(self, graph, start, target): self._dijkstra = Dijkstra(graph, start, target, lambda f : f.distance + f.get_heuristic(target)) self._comparison = 0 self._moviments = 0 self._iterations = 0
def test_dijkstraChallenge1(self): args = dijkstraChallenge1() d = Dijkstra(args[0], args[1], args[2]) d.doComplete() actual = d.printS() self.assertEquals(actual, args[3])
def transitive_closure(D, kind='metric', algorithm='dense', *args, **kwargs): """ Compute the transitive closure (All-Pairs-Shortest-Paths; APSP) using different shortest path measures on the distance graph (adjacency matrix) with values in the ``[0,inf]`` interval. .. math:: c_{ij} = min_{k}( metric ( a_{ik} , b_{kj} ) ) Args: D (matrix or dict): The [D]istance matrix. Accepted formats for kind ``dense`` is a numpy array; for ``dijkstra`` is a either a numpy array, a scipy sparse matrix or edgelist dictionary. kind (string): type of closure to compute: ``metric`` or ``ultrametric``. algorithm (string): type of algorithm to use: ``dense`` or ``dijkstra``. verbose (bool): Prints statements as it computes. Returns: C (matrix or dict): transitive closure dense matrix or a edgelist dictionary, depending on input Examples: >>> # using dense matrix >>> P = np.array([ [1.,.9,.1,0.], [.9,1.,.8,0.], [.1,.8,1.,.6], [0.,0.,.6,1.], ], dtype=float) >>> D = prox2dist(P) >>> transitive_closure(D, kind='metric', algorithm='dense', verbose=True) [ 0. ,.11111111, 0.36111111, 1.02777778], [ 0.11111111, 0., 0.25, 0.91666667], [ 0.36111111, 0.25, 0., 0.66666667], [ 1.02777778, 0.91666667, 0.66666667, 0.] >>> # using an edgelist >>> D = { ('a','b'): 0.11111111, ('a','c'): 9., ('b','c'): 0.25, ('c','d'): 0.66666667, } >>> transitive_closure(D, kind='metric', algorithm='dijkstra', verbose=True) >>> # using a sparse matrix >>> Dsp = csr_matrix(D) >>> transitive_closure(Dsp, kind='metric', algorithm='dijkstra', verbose=True) Note: Dense matrix is slow for large graphs. If your network is large and/or sparse, use Dijkstra. Metric: :math:`(min,+)` Ultrametric: :math:`(min,max)` -- also known as maximum flow. Semantic proximity: TODO .. math:: [ 1 + \\sum_{i=2}^{n-1} log k(v_i) ]^{-1} """ _check_for_metric_type(kind) _check_for_algorithm(algorithm) # Algorithm - Dense if algorithm == 'dense': # Numpy object if (type(D).__module__ == np.__name__): return _transitive_closure_dense_numpy(D, kind, *args, **kwargs) else: raise TypeError("Input is not a numpy object.") # Dijkstra elif algorithm == 'dijkstra': dij = Dijkstra(*args, **kwargs) # Numpy object if (type(D).__module__ == np.__name__): dij.from_numpy_matrix(D) # Edgelist object elif (isinstance(D, dict)): dij.from_edgelist(D) # Sparse Matrix elif (ssp.issparse(D)): dij.from_sparse_matrix(D) else: raise TypeError("Invalid Input. For the Dijkstra algorithm, input must be `Numpy matrix`, `Scipy Sparse Matrix` or `Edgelist dict`") dij.all_pairs_shortest_paths(kind=kind) return dij.get_shortest_distances_sparse()