def find_path(self, graph, s, e, cost_func=None, heuristic_func=None): start = s.closest_object end = e.closest_object annex = None split_ways = {} if isinstance(start, Street) or isinstance(end, Street): annex = dijkstar.Graph() if isinstance(start, Street): start, *start_ways = self.split_way(start, s.geom, -1, -1, -2, graph, annex) split_ways.update({w.id: w for w in start_ways}) if isinstance(end, Street): end, *end_ways = self.split_way(end, e.geom, -2, -3, -4, graph, annex) split_ways.update({w.id: w for w in end_ways}) try: nodes, edge_attrs, costs, total_weight = dijkstar.find_path( graph, start.id, end.id, annex=annex, cost_func=cost_func, heuristic_func=heuristic_func) except dijkstar.NoPathError: raise NoRouteError(s, e) assert nodes[0] == start.id assert nodes[-1] == end.id return nodes, edge_attrs, split_ways
def run(self): quiet = self.quiet graph = dijkstar.Graph() q = Street.__table__.select() result = self.session.execute(q) num_rows = result.rowcount if not quiet: timer = Timer() timer.start() template = '\rBuilding graph from {} streets... {{:.0%}}' template = template.format(num_rows) print(template.format(0), end='') for i, r in enumerate(result): edge = (r.id, r.base_cost, r.name or r.description) graph.add_edge(r.start_node_id, r.end_node_id, edge) if not r.oneway_bicycle: graph.add_edge(r.end_node_id, r.start_node_id, edge) if not quiet: print(template.format(i / num_rows), end='') if not quiet: timer.stop() print(template.format(1), timer) timer.start() if not quiet: print(f'Saving graph to {self.path}... ', end='', flush=True) graph.marshal(str(self.path)) if not quiet: print('Done', timer) timer.stop()
def maze_to_graph(maze): """ Transforms input into graph. """ graph = dijkstar.Graph() for i, row in enumerate(maze): for j, node in enumerate(row): node_id, node_item = node cost = {"cost": 1} # skip walls, we want only empty corridors and lamps if node_item == WALL: continue # right if j < len(row)-1 and row[j+1][1] != WALL: graph.add_edge(node_id, row[j+1][0], cost) # left if j > 0 and row[j-1][1] != WALL: graph.add_edge(node_id, row[j-1][0], cost) # down if i+1 < len(maze) and maze[i+1][j][1] != WALL: graph.add_edge(node_id, maze[i+1][j][0], cost) # up if i > 0 and maze[i-1][j][1] != WALL: graph.add_edge(node_id, maze[i-1][j][0], cost) return graph
def generate_graph(stars): graph = dijkstar.Graph() for star in stars: for edge in stars[star]['edges']: graph.add_edge(star, edge, 1) graph.dump(graph_save_path) return graph
def __init__(self): self.graph = dj.Graph() #first floor graph nodes self.initFirstFloor(self.graph) #second floor graph nodes self.initSecondFloor(self.graph) #third floor graph nodes self.initThirdFloor(self.graph)
def run(self): timer = Timer() timer.start() graph = dijkstar.Graph() q = Street.__table__.select() result = self.engine.execute(q) num_rows = result.rowcount template = '\rBuilding graph from {} streets... {{:.0%}}' template = template.format(num_rows) print(template.format(0), end='') for i, r in enumerate(result): edge = ( r.id, r.geom.reproject(DEFAULT_SRID, 2913).length, r.name, r.highway, r.bicycle, r.cycleway, ) graph.add_edge(r.start_node_id, r.end_node_id, edge) if r.oneway_bicycle: # Ensure end node is in graph; this is relevant for one # way streets near the boundary of the graph. if r.end_node_id not in graph: graph.add_node(r.end_node_id) else: graph.add_edge(r.end_node_id, r.start_node_id, edge) print(template.format(i / num_rows), end='') timer.stop() print(template.format(1), timer) session = self.session() if self.clean: print('Removing previous graphs...', end='') count = session.query(Graph).delete() print('Removed', count, 'previous graph%s' % ('' if count == 1 else 's')) timer.start() print('Saving graph to database... ', end='') file = io.BytesIO() graph.marshal(file) file.seek(0) session.add(Graph(data=file.getvalue())) session.commit() print('Done', timer) timer.stop()
def graph_G(auto): graph = dj.Graph() pos = auto.transitions sts = auto.states_set() for state in sts: t = pos[state].keys() for eve in t: graph.add_edge(state, pos[state][eve], eve.weight) return graph
def generate_safe_graph(stars): safe_graph = dijkstar.Graph() for star in stars: for edge in stars[star]['edges']: edge_sec = get_rounded_sec(edge) if get_sec_status(edge_sec) == 'nullsec': cost = 10000 else: cost = 1 safe_graph.add_edge(star, edge, cost) safe_graph.dump(safe_graph_save_path) return safe_graph
def graph_G(auto, black, initial): graph = dj.Graph() pos = auto.transitions sts = auto.states_set() for state in sts: t = pos[state].keys() for eve in t: if state == initial: if eve not in black: graph.add_edge(state, pos[state][eve], eve.weight) else: graph.add_edge(state, pos[state][eve], eve.weight) return graph
def GRAPH_VISION(auto, black, initial, r): d = DIST(auto, initial, r) graph = dj.Graph() pos = auto.transitions sts = auto.states_set() for state in sts: t = pos[state].keys() for eve in t: s2 = pos[state][eve] if state in d: if eve not in black: graph.add_edge(state, pos[state][eve], eve.weight) else: graph.add_edge(state, pos[state][eve], eve.weight) return graph
def build_scaffolding(m): g = dijkstar.Graph() for y, row in enumerate(m): for x, col in enumerate(row): if m[y][x] == '#' or m[y][x] == '^': neighbors = get_neighbors((x, y), m) t = (x, y) if t not in g: g.add_node((x, y)) for neighbor in neighbors: n1, n2 = neighbor if m[n2][n1] == '#' or m[n2][n1] == '^': if neighbor not in g: g.add_node(neighbor) g.add_edge(t, neighbor, 1) g.add_edge(neighbor, t, 1) return g
def make_graph(maze_side_length): """ Makes graph where nodes are rooms and edges are walls. @maze_side_length is number of rooms of the maze in one direction. """ graph = dijkstar.Graph() cost = {"cost": 1} for row_id in range(maze_side_length): for room_id in range(maze_side_length): # add edge: current->right if room_id < maze_side_length - 1: graph.add_edge((row_id, room_id), (row_id, room_id + 1), cost) # add edge: current->left if room_id >= 1: graph.add_edge((row_id, room_id), (row_id, room_id - 1), cost) # add edge: current->bottom if row_id < maze_side_length - 1: graph.add_edge((row_id, room_id), (row_id + 1, room_id), cost) # add edge: current->top if row_id >= 1: graph.add_edge((row_id, room_id), (row_id - 1, room_id), cost) return graph
def prepare_graph(cells_file): ''' Create a Graph object from a file containing all cells' id :param str cells_file: Path to the cells file :return: A graph object ''' cells = pd.read_csv(cells_file, header=None, names=['id']) cells = cells['id']\ .str.split(':')\ .apply(lambda x: tuple([int(x[0]), int(x[1])])).tolist() graph = dijkstar.Graph() for cell in cells: poss_neighbour = [(cell[0] + i, cell[1] + j) for i in [-1, 0, 1] for j in [-1, 0, 1]] for neighbour in poss_neighbour: if neighbour in cells: graph.add_edge(cell, neighbour, {'cost': 1}) return graph
def handle(): if flask.request.method == 'GET': return flask.Response(status=200) if flask.request.method == 'POST': maze_data = flask.request.get_json() corridors = maze_data['corridors'] end = maze_data['end'] rooms = maze_data['rooms'] start = maze_data['start'] pp(maze_data) graph = dijkstar.Graph() for edge in corridors: graph.add_edge(edge[0], edge[1], {'cost': 1}) graph.add_edge(edge[1], edge[0], {'cost': 1}) cost_fun = lambda u, v, e, prev_e: e['cost'] # Invalid input flat_corridors = [i[0] for i in corridors] + [i[1] for i in corridors] if start not in rooms or end not in rooms or \ (len(flat_corridors) == 0 and len(rooms) == 2): return flask.jsonify({"solution": None, "length": None, "error": "Invalid input"}), 200 # Path does not exist try: solution = dijkstar.find_path(graph, start, end, cost_func=cost_fun) except dijkstar.algorithm.NoPathError: return flask.jsonify({"solution": None, "length": None, "status": "No solution found"}), 200 # Correct solution return flask.jsonify({"solution": solution.nodes, "length": len(solution.nodes), "status": "OK"}), 200
def make_graph(pyramid_level): """ Makes graph where nodes are rooms and edges are walls. @pyramid_level is number of pyramid levels, starts from 0! Graph will looks like this. Nodes are numbered. 1 | 2---3---4 | | 5---6---7---8---9 """ graph = dijkstar.Graph() cost = {"cost": 1} # give each node ID, from top to bottom and left to right """ make horizontal connections in graph e.g. for pyramid_level == 2 1 2---3---4 5---6---7---8---9 """ current_node_id = 1 for level in range(pyramid_level + 1): nodes_per_level = level * 2 + 1 for node in range(nodes_per_level): if node < nodes_per_level - 1: a = current_node_id b = current_node_id + 1 if _DEBUG: print("connecting:", a, b) print("connecting:", b, a) graph.add_edge(a, b, cost) graph.add_edge(b, a, cost) current_node_id += 1 """ make vertical connections in graph e.g. for pyramid_level == 2 1 | 2 3 4 | | 5 6 7 8 9 """ next_node_offset = 2 # goes up by N+2 per level current_node_id = 1 for level in range(pyramid_level): nodes_per_level = level * 2 + 1 if _DEBUG: print("nodes_per_level:", nodes_per_level) print("next_node_offset:", next_node_offset) print("current_node_id:", current_node_id) for node_id in range(current_node_id, current_node_id + nodes_per_level, 2): a = node_id b = node_id + next_node_offset if _DEBUG: print("node_id:", node_id) print("connecting:", a, b) print("connecting:", b, a) graph.add_edge(a, b, cost) graph.add_edge(b, a, cost) next_node_offset += 2 current_node_id += nodes_per_level return graph
def solve_maze(maze_txt): """ Solves number maze and prints results. Transforms input into graph and uses dijkstar library to get shortest path. Input: S2 1 1 3 3 2 1 1 2 1 1 2 3 1 2 X is transformed by first assigning each node unique id: [[(0, 'S2'), (1, '1'), (2, '1'), (3, '3')], [(4, '3'), (5, '2'), (6, '1'), (7, '1')], [(8, '2'), (9, '1'), (10, '1'), (11, '2')], [(12, '3'), (13, '1'), (14, '2'), (15, 'X')]] and then converted to directed graph: (0, {2: {'cost': 1}, 8: {'cost': 1}}) (1, {0: {'cost': 1}, 2: {'cost': 1}, 5: {'cost': 1}}) (2, {1: {'cost': 1}, 3: {'cost': 1}, 6: {'cost': 1}}) (3, {0: {'cost': 1}, 15: {'cost': 1}}) (4, {7: {'cost': 1}}) (5, {7: {'cost': 1}, 13: {'cost': 1}}) (6, {2: {'cost': 1}, 5: {'cost': 1}, 7: {'cost': 1}, 10: {'cost': 1}}) (7, {3: {'cost': 1}, 6: {'cost': 1}, 11: {'cost': 1}}) (8, {0: {'cost': 1}, 10: {'cost': 1}}) (9, {5: {'cost': 1}, 8: {'cost': 1}, 10: {'cost': 1}, 13: {'cost': 1}}) (10, {6: {'cost': 1}, 9: {'cost': 1}, 11: {'cost': 1}, 14: {'cost': 1}}) (11, {3: {'cost': 1}, 9: {'cost': 1}}) (12, {0: {'cost': 1}, 15: {'cost': 1}}) (13, {9: {'cost': 1}, 12: {'cost': 1}, 14: {'cost': 1}}) (14, {6: {'cost': 1}, 12: {'cost': 1}}) in which, the path is found. """ maze = load_maze(maze_txt) graph = dijkstar.Graph() start = maze[0][0][0] end = maze[-1][-1][0] from pprint import pprint as pp pp(maze) # Transform input into graph for i, row in enumerate(maze): for j, node in enumerate(row): if node[1] == 'X': # stop when we hit the end# continue elif node[1] == "S2": number = 2 else: number = int(node[1]) # right if j + number < len(row): graph.add_edge(node[0], row[j + number][0], {"cost": 1}) # left if j - number >= 0: graph.add_edge(node[0], row[j - number][0], {"cost": 1}) # top if i - number >= 0: graph.add_edge(node[0], maze[i - number][j][0], {"cost": 1}) # down if i + number < len(maze): graph.add_edge(node[0], maze[i + number][j][0], {"cost": 1}) if _DEBUG: for i in graph.items(): pp(i) cost_func = lambda u, v, e, prev_e: e['cost'] result = dijkstar.find_path(graph, start, end, cost_func=cost_func) nodes_ids = result.nodes # Get final path final_path = [] for node_id in nodes_ids: for row in maze: for i, node in row: if node_id == i: final_path.append((i, node)) return final_path