class DeliveryGraph: """Graph lib wrapper Parameters data (list(tuple)): The data should be a list of tuple. Each tuple should have 3 values. The first value should be the node A The second value should be the node B The last value should be the weight between node A and node B exemple: data = [('NodeA', 'Node B', 10.5)] """ def __init__(self): self.graph = Graph() def populate_graph(self, data): for item in data: self.graph.add_edge(item[0], item[1], item[2]) def shortest_path(self, nodeA, nodeB): dijkstra = DijkstraSPF(self.graph, nodeA) return dijkstra.get_path(nodeB) def shortest_distance(self, nodeA, nodeB): dijkstra = DijkstraSPF(self.graph, nodeA) return dijkstra.get_distance(nodeB)
def test_graph(): G = Graph() G.add_edge(1, 2, 3) G.add_edge(1, 3, 2) assert G.get_edge_weight(1, 2) == 3 assert G.get_edge_weight(1, 3) == 2 assert G.get_adjacent_nodes(1) == {2, 3}
def create_vis_graph(vertices: List[List[float]], holes: List[List[List[float]]] = None) -> Graph: """ Create a visibility graph based on the vertices of the polygon :param vertices: List[List[float]] :return: Graph object """ graph = Graph() for i in range(len(vertices)): for j in range(i + 1, len(vertices)): vis = True for k in range(len(vertices)): k1 = k k2 = (k + 1) % (len(vertices)) if (k1 == i) and (k2 == j): vis = True break if not diagonal(i, j, vertices) and ( (i + 1) % len(vertices)) != j and ( (j + 1) % len(vertices)) != i: vis = False break if intersectProp(vertices[i], vertices[j], vertices[k1], vertices[k2]): vis = False break if vis: d = l2_dist(vertices[i], vertices[j]) graph.add_edge(i, j, d) graph.add_edge(j, i, d) return graph
def CalculoRota(request): parametros = JSONParser().parse(request) if not checkRequestValido(parametros): return JsonResponse({'mensagem': 'Parametros invalidos'}, status=status.HTTP_400_BAD_REQUEST) #obter rotas rotas = Rota.objects.all() rotas = rotas.filter(mapa__nome__icontains= parametros['mapa']) #checar se os objetos existem no banco if not rotas.exists(): return JsonResponse({'mensagem': 'Mapa nao encontrado'}, status=status.HTTP_404_NOT_FOUND) if not rotas.filter(origem__icontains= parametros['origem']): return JsonResponse({'mensagem': 'Origem nao encontrada no mapa'}, status=status.HTTP_404_NOT_FOUND) if not rotas.filter(destino__icontains= parametros['destino']): return JsonResponse({'mensagem': 'Destino nao encontrado no mapa'}, status=status.HTTP_404_NOT_FOUND) graph = Graph() for rota in rotas: graph.add_edge(rota.origem, rota.destino, rota.distancia) dijkstra = DijkstraSPF(graph, parametros['origem']) caminho = dijkstra.get_path(parametros['destino']) gasto = dijkstra.get_distance(parametros['destino'])/parametros['autonomia']*parametros['valorLitro'] return JsonResponse({'origem': parametros['origem'],'destino': parametros['destino'],'gasto': gasto,'rota': caminho}, status=status.HTTP_200_OK)
def create_graph(number_of_elements): global graph graph = Graph(number_of_elements) for i in range(1, number_of_elements): for j in range(i, number_of_elements + 1): if i % 2 == 1: if max(i - j, j - i) <= 3 and i != j: graph.add_edge(i, j) else: if max(i - j, j - i) <= 2 and i != j: graph.add_edge(i, j) start = time.time() (path_output, weight_output) = graph.dijkstra_shortest_path(int(from_entry.get()), int(to_entry.get())) end = time.time() visualize_shortest_path(path_output) print("output ", path_output[::-1]) print("time ", end - start) running_time.set("Running Time:" + str("{0:.2f}".format(round((end - start) * 1000, 2))) + "ms") string = "Path: " for i in range(len(path_output[::-1]) - 1): string += str(path_output[::-1][i]) + " -> " path_var.set(string + str(path_output[::-1][len(path_output) - 1])) weight_var.set("Total Weight: " + str(weight_output)) print(graph.dijkstra_shortest_path_distances(int(to_entry.get())))
def get_itinerary(start, destination): # We check if the starting and ending point begins by B1 or B3 if not start.startswith('B3') and not start.startswith('B1'): raise ValueError( f'Start name should start with either B1 or B3. Got {start}') if not destination.startswith('B3') and not destination.startswith('B1'): raise ValueError( f'Start name should start with either B1 or B3. Got {destination}') # We get all the rooms saved in the database rooms = query_db("SELECT name, linked_to FROM points") graph = Graph() for room in rooms: # We convert each room into a dictionary and we get the current room name room = dict(room) room_name = room.get("name", "") if room_name: # For each room connected to our current room for room_connected_and_distance in room.get("linked_to", "").split("|"): # On the connected room we get the name of the room and the distance room_connected, distance = room_connected_and_distance.split( ";") # We add the connection in our graph graph.add_edge(room_name, room_connected, int(distance)) # We generate our dijkstra and we search ou path dijkstra = DijkstraSPF(graph, start) itinerary_list = dijkstra.get_path(destination) return itinerary_list
def createGraph(): graph = Graph() f = open("p1_graph.txt", "r") for line in f: line = line.strip() path_values = line.split(",") graph.add_edge(int(path_values[0]),int(path_values[1]),int(path_values[2])) return graph
def load_graph(data): g = Graph() for i, row in enumerate(data): for j, element in enumerate(row): g.add_node(str(i) + '_' + str(j)) for m, n in get_neighbors(data, i, j): g.add_edge(str(m) + '_' + str(n), str(i) + '_' + str(j), data[i][j]) return g
def build_dijkstra_graph(stations: list) -> Graph: g = Graph() # Build the graph edges for s in stations: for n in s.neighbours: g.add_edge(s.id, n.station.id, n.get_wtt()) return g
def check_solution(adj_matrix): from dijkstra import Graph, DijkstraSPF n = len(adj_matrix) node_names = [str(i) for i in adj_matrix] graph = Graph() for i in range(n): for j in range(n): graph.add_edge(node_names[i], node_names[j], adj_matrix[i, j]) solution = DijkstraSPF(graph, node_names[0]) result = [solution.get_distance(i) for i in node_names] return result
def from_file(): instance = Graph() path = os.path.join(os.path.dirname(__file__), 'dijkstraData.txt') testfile = open(path, 'r') while testfile: line = testfile.readline().rstrip() if not line: break values = line.split('\t') head = int(values.pop(0)) for pair in values: tail, weight = map(int, pair.split(',')) instance.add_edge(head, tail, weight) return instance
def delivery_process(request): if request.method == 'POST': body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) map_name = body['map_name'] origin = body['origin'] destination = body['destination'] truck_range = body['truck_range'] fuel_cost = body['fuel_cost'] if map_name == "" or map_name == "[]" or map_name is None: return JsonResponse("Invalid Parameters", status=status.HTTP_400_BAD_REQUEST, safe=False) deliveries = Delivery.objects.all() deliveries = deliveries.filter(map_name__icontains=map_name) if deliveries.count() == 0: return JsonResponse("Invalid Parameters: map name not found", status=status.HTTP_400_BAD_REQUEST, safe=False) deliveries_serializer = DeliverySerializer(deliveries, many=True) deliveries = dict(deliveries_serializer.data[0])['routes'] nodes = set([origin, destination]) g = Graph() for delivery in deliveries: route = list(delivery.items()) nodes.add(route[0][1]) nodes.add(route[1][1]) g.add_edge(route[0][1], route[1][1], route[2][1]) dijkstra = DijkstraSPF(g, origin) shortest_distance = dijkstra.get_distance(destination) path = " -> ".join(dijkstra.get_path(destination)) cost = (shortest_distance / truck_range) * fuel_cost return JsonResponse({"route": path, "cost": cost}, safe=False)
def test_dijkstra(): nodes = ("S", "T", "A", "B", "C", "D", "E", "F", "G") S, T, A, B, C, D, E, F, G = nodes graph = Graph() graph.add_edge(S, A, 4) graph.add_edge(S, B, 3) graph.add_edge(S, D, 7) graph.add_edge(A, C, 1) graph.add_edge(B, S, 3) graph.add_edge(B, D, 4) graph.add_edge(C, E, 1) graph.add_edge(C, D, 3) graph.add_edge(D, E, 1) graph.add_edge(D, T, 3) graph.add_edge(D, F, 5) graph.add_edge(E, G, 2) graph.add_edge(G, E, 2) graph.add_edge(G, T, 3) graph.add_edge(T, F, 5) dijkstra = DijkstraSPF(graph, S) for v in nodes: print("%3s %3s" % (v, dijkstra.get_distance(v))) assert dijkstra.get_distance(T) == 10 assert dijkstra.get_path(T) == ["S", "D", "T"]
} padding = 50 graph = Graph() for x in range(target_x + padding + 1): for y in range(target_y + padding + 1): rt = RegionType(region_type(x, y)) for tool in allowed_tools[rt]: graph.add_vertex(Region(x, y, tool)) for x in range(target_x + padding): for y in range(target_y + padding): rt = region_type(x, y) tools = allowed_tools[rt] t1, t2 = tools graph.add_edge(Region(x, y, t1), Region(x, y, t2), 7) for n in ((x + 1, y), (x, y + 1)): rt_n = region_type(*n) if rt == rt_n: graph.add_edge(Region(x, y, t1), Region(*n, t1), 1) graph.add_edge(Region(x, y, t2), Region(*n, t2), 1) else: overlap = tools.intersection(allowed_tools[rt_n]).pop() graph.add_edge(Region(x, y, overlap), Region(*n, overlap), 1) start = Region(0, 0, Tool.TORCH) end = Region(target_x, target_y, Tool.TORCH) dijkstra(graph, graph.get_vertex(start), graph.get_vertex(end)) target = graph.get_vertex(end)
def main(args): parser = argparse.ArgumentParser("") parser.add_argument('-d', '--date') parser.add_argument('-s', '--station') try: global opt opt = parser.parse_args(args[1:]) except: parser.print_help() raise df = pd.read_csv("northern-taiwan.csv") # Declare global variable global station_dict global graph # Setup station map station_dict = {} score_dict = {} stat_df = df.groupby("station_name_tw")["line_code"].apply( list).reset_index() for name, line in zip(stat_df.station_name_tw, stat_df.line_code): station_dict[name] = [x + name for x in line] # Setup station graph graph = Graph() MRT_line = ["R", "BR", "G", "O", "BL"] for line in MRT_line: temp = df[df.station_code.str.match("{}[0-9]+$".format(line))] namelst = temp.station_name_tw.tolist() codelst = temp.station_code.tolist() lst = [x + y for x, y in zip(codelst, namelst)] # Avoid the last element for t, n in zip(lst[:-1], lst[1:]): tid = re.search(r'\d+', t).group() nid = re.search(r'\d+', n).group() if int(tid) + 1 != int(nid): continue t, n = t.replace(tid, "", 1), n.replace(nid, "", 1) score_dict["{}-{}".format(t.lstrip(ascii_letters), n.lstrip(ascii_letters))] = 0 score_dict["{}-{}".format(n.lstrip(ascii_letters), t.lstrip(ascii_letters))] = 0 graph.add_edge(t, n, 1) graph.add_edge(n, t, 1) Add_Edge("R中山", "G中山", graph, 0.5) Add_Edge("R中正紀念堂", "G中正紀念堂", graph, 0.1) Add_Edge("BR南京復興", "G南京復興", graph, 1.5) Add_Edge("BR南港展覽館", "BL南港展覽館", graph, 0.5) Add_Edge("G古亭", "O古亭", graph, 0.1) Add_Edge("R台北車站", "BL台北車站", graph, 1.5) Add_Edge("BR大安", "R大安", graph, 1.5) Add_Edge("BR忠孝復興", "BL忠孝復興", graph, 1.5) Add_Edge("O忠孝新生", "BL忠孝新生", graph, 0.5) Add_Edge("R東門", "O東門", graph, 0.5) Add_Edge("G松江南京", "O松江南京", graph, 1.5) Add_Edge("R民權西路", "O民權西路", graph, 0.5) Add_Edge("G西門", "BL西門", graph, 0.5) Add_Edge("R北投", "R新北投", graph, 1) Add_Edge("G七張", "G小碧潭", graph, 1) Add_Edge("O大橋頭站", "O三重國小", graph, 1) score_dict["{}-{}".format("北投", "新北投")] = 0 score_dict["{}-{}".format("新北投", "北投")] = 0 score_dict["{}-{}".format("七張", "小碧潭")] = 0 score_dict["{}-{}".format("小碧潭", "七張")] = 0 score_dict["{}-{}".format("大橋頭站", "三重國小")] = 0 score_dict["{}-{}".format("三重國小", "大橋頭站")] = 0 print(Find_Path("東門", "南京復興")) print(Find_Path("善導寺", "南京復興")) return for i in range(24): df = pd.read_csv("Pipe_{}_{}.csv".format(i, opt.date)) for start, end, weight, in zip(df.GetIn, df.GetOut, df.Count): score, path = Find_Path(start, end) for t, n in zip(path[:-1], path[1:]): score_dict["{}-{}".format(t, n)] += weight score_dict["{}-{}".format(n, t)] += weight total = sum(score_dict.values(), 0.0) / 2 score_dict = { k: 0 if v == 0 else v / total for k, v in score_dict.items() } with open('{}_{}.json'.format(i, opt.date), 'w', encoding='utf-8-sig') as f: json.dump(score_dict, f, indent=4, ensure_ascii=False) score_dict = dict.fromkeys(score_dict, 0)
plotter2.add_visibility_graph(lines) plotter2.add_robot(source, dist) plotter2.show_graph() # step 3: with open(query, 'r') as f: dest = tuple(map(float, f.readline().split(','))) lines = get_visibility_graph(c_space_obstacles, source, dest) # TODO: fill in the next line graph = Graph() for l in lines: graph.add_node(l.coords[0]) graph.add_node(l.coords[1]) graph.add_edge(l.coords[0], l.coords[1], l.length) graph.add_edge(l.coords[1], l.coords[0], l.length) visited, path = dijsktra(graph, source) shortest_path = [] curr = dest while True: shortest_path.insert(0, curr) if curr == source: break curr = path[curr] cost = visited[dest] # shortest_path, cost = None, None plotter3 = Plotter() plotter3.add_robot(source, dist)
def create_vis_graph_with_holes(vertices: List[List[float]], holes: List[List[List[float]]]) -> Graph: """ Create a visibility graph based on the vertices of the polygon with holes (can be empty) :param vertices: List[List[float]] :return: Graph object """ graph = Graph() vertices = copy.deepcopy(vertices) main_poly = copy.deepcopy(vertices) all_polys = [main_poly] + holes for h in holes: vertices += h for h in holes + [main_poly]: for i in range(len(h)): j = (i + 1) % len(h) d = l2_dist(h[i], h[j]) ii = vertices.index(h[i]) jj = vertices.index(h[j]) graph.add_edge(ii, jj, d) graph.add_edge(jj, ii, d) for i in range(len(vertices)): for j in range(i + 1, len(vertices)): vis = True # Check to see if (i, j) intersects with (k1, k2) or not, along with other conditions for visibility for poly in all_polys: for k in range(len(poly)): k1 = k k2 = (k + 1) % (len(poly)) edge = [poly[k1], poly[k2]] if not is_actual_edge(all_polys, edge): continue # Intersect with some edges if intersectProp(vertices[i], vertices[j], poly[k1], poly[k2]): vis = False break if not vis: break edge_ij = [vertices[i], vertices[j]] # Exclude the exterior diagonals of the main polygon if vertices[i] in main_poly and vertices[j] in main_poly: # Not inter diagonal if not diagonal(i, j, main_poly): continue # Exclude the interior diagonals of the holes if vertices[i] not in main_poly and is_same_poly( all_polys, edge_ij): # Not external diagonal is_diag = False for h in holes: if vertices[i] in h and vertices[j] in h: if diagonal(h.index(vertices[i]), h.index(vertices[j]), h): is_diag = True break if is_diag: continue if vis: d = l2_dist(vertices[i], vertices[j]) graph.add_edge(i, j, d) graph.add_edge(j, i, d) return graph
# -*- coding: utf-8 -*- """ Created on Thu Nov 19 17:26:13 2020 @author: Joaquin """ from dijkstra import Graph, DijkstraSPF A, B, C, D, E, F, G = nodos = list("ABCDEFG") grafo = Graph() grafo.add_edge(F, C, 15) grafo.add_edge(F, B, 5) grafo.add_edge(F, E, 40) grafo.add_edge(E, G, 10) grafo.add_edge(E, B, 20) grafo.add_edge(D, B, 40) grafo.add_edge(D, G, 45) grafo.add_edge(D, F, 10) grafo.add_edge(D, E, 35) grafo.add_edge(C, E, 5) grafo.add_edge(C, G, 25) grafo.add_edge(A, G, 75) grafo.add_edge(A, D, 20)
def handler(event, context): status_code = 200 total_elapsed = 0 total_turns = 0 m = eval(event['map_matrix']) map_matrix = Map.map_matrix_transfer(m) start_position = eval(event['start_position']) start_direction = event['start_direction'] # Algorithm, default=DFS algorithm = 'dfs' if 'algorithm' in event: algorithm = event['algorithm'] if algorithm == "bfs" or algorithm == "dfs": if algorithm == "bfs": # run with bfs robot = Robot(map_matrix, start_position, start_direction) sweeper = BFSSweeper(robot) else: # run with dfs robot = Robot(map_matrix, start_position, start_direction) sweeper = DFSSweeper(robot) start = time.time() sweeper.sweep() path_history = robot.path_history finished_x = path_history[len(path_history) - 1][0] finished_y = path_history[len(path_history) - 1][1] back_path_steps = 0 if str(start_position['x']) + '_' + str(start_position['y']) != str( finished_x) + '_' + str(finished_y): graph = Graph() # print(map_matrix) for i in range(len(map_matrix)): for j in range(len(map_matrix[i])): floor_type = map_matrix[i][j] if floor_type == 0: graph.add_node(str(j) + '_' + str(i)) near_spots = find_adjacent_spot(i, j, map_matrix) for spot_inf in near_spots: spot = spot_inf[0] weight = spot_inf[1] graph.add_edge(str(j) + '_' + str(i), spot, weight) back_path_result = shortest_path( graph, str(finished_x) + '_' + str(finished_y), str(start_position['x']) + '_' + str(start_position['y'])) back_path_steps = back_path_result[0] back_path_arr = back_path_result[1] for back_spot_str in back_path_arr: back_spot_arr = back_spot_str.split('_') back_spot_x = int(back_spot_arr[0]) back_spot_y = int(back_spot_arr[1]) path_history.append([back_spot_x, back_spot_y]) elapsed = time.time() - start path = Map.path_append_attributes(m, path_history) total_elapsed += elapsed total_steps = robot.move_count + back_path_steps total_turns += robot.turn_count result = { "path": str(path), "steps_taken": total_steps, "turns_taken": total_turns, "times_taken": round(total_elapsed * 1000, 6) } elif algorithm == "dijkstra": if 'end_position' in event: end_position = eval(event['end_position']) graph = Graph() for i in range(len(map_matrix)): for j in range(len(map_matrix[i])): floor_type = map_matrix[i][j] if floor_type == 0: graph.add_node(str(j) + '_' + str(i)) near_spots = find_adjacent_spot(i, j, map_matrix) for spot_inf in near_spots: spot = spot_inf[0] weight = spot_inf[1] graph.add_edge(str(j) + '_' + str(i), spot, weight) start = time.time() to_path_result = shortest_path( graph, str(start_position['x']) + '_' + str(start_position['y']), str(end_position['x']) + '_' + str(end_position['y'])) back_path_result = shortest_path( graph, str(end_position['x']) + '_' + str(end_position['y']), str(start_position['x']) + '_' + str(start_position['y'])) elapsed = time.time() - start to_path_steps = to_path_result[0] to_path_arr = to_path_result[1] back_path_steps = back_path_result[0] back_path_arr = back_path_result[1] path_history = [] for to_spot_str in to_path_arr: to_spot_arr = to_spot_str.split('_') to_spot_x = int(to_spot_arr[0]) to_spot_y = int(to_spot_arr[1]) path_history.append([to_spot_x, to_spot_y]) for back_spot_str in back_path_arr: back_spot_arr = back_spot_str.split('_') back_spot_x = int(back_spot_arr[0]) back_spot_y = int(back_spot_arr[1]) path_history.append([back_spot_x, back_spot_y]) path = Map.path_append_attributes(m, path_history) total_steps = to_path_steps + back_path_steps result = { "path": str(path), "steps_taken": total_steps, "turns_taken": 0, "times_taken": round(elapsed * 1000, 6) } else: status_code = 401 result = { "type": "Params error", "code": "401", "reason": "Required param not exist" } return { "statusCode": status_code, "headers": { "Content-Type": "application/json" }, "body": result }
def generateST(argv): tdfile = '' obfile = '' trespassers = 0 outputfile = '' try: opts, args = getopt.getopt(argv, "ha:b:o:n:", ["tdfile=", "obfile=", "ofile=", "number="]) except getopt.GetoptError: print( 'generateSTData.py -a <tdfile> -b <obfile> -o <outputfile> -n <number>' ) sys.exit(2) for opt, arg in opts: if opt == '-h': print( 'generateSTData.py -a <tdfile> -b <obfile> -o <outputfile> -n <number>' ) sys.exit() elif opt in ("-a", "--tdfile"): tdfile = arg elif opt in ("-b", "--obfile"): obfile = arg elif opt in ("-n", "--number"): trespassers = int(arg) elif opt in ("-o", "--ofile"): outputfile = arg tdsegments = genfromtxt(tdfile, delimiter=',') obsegments = genfromtxt(obfile, delimiter=',') stsegments = np.zeros((tdsegments.shape[0] + 1, obsegments.shape[1])) # print(obsegments[:,0]) # print(segments) entries = np.where(tdsegments[:, 0] < 1) exits = np.where(tdsegments[:, tdsegments.shape[1] - 1] < 1) # print(vertice_keys) # vertice_keys = g.get_vertices() # for key in vertice_keys: # vertex = g.get_vertex(key) # print(vertex) # for v in g: # for w in v.get_connections(): # vid = v.get_id() # wid = w.get_id() # print('( %s , %s, %f)' % (vid, wid, v.get_weight(w))) for x in range(trespassers): # construct graph g = Graph() for x in range(tdsegments.shape[0]): for y in range(tdsegments.shape[1]): if tdsegments[x, y] < 1.0: g.add_vertex('a_(' + str(x) + ',' + str(y) + ')', x, y) vertice_keys = g.get_vertices() for key in vertice_keys: vertex = g.get_vertex(key) # print(vertex) v_i = vertex.get_i() v_j = vertex.get_j() if (v_i - 1 >= 0 and v_j - 1 >= 0) and tdsegments[v_i - 1, v_j - 1] < 1: next_vertex = g.get_vertex('a_(' + str(v_i - 1) + ',' + str(v_j - 1) + ')') cost = tdsegments[v_i - 1, v_j - 1] + (1 - obsegments[v_i - 1, v_j - 1]) g.add_edge(vertex.get_id(), next_vertex.get_id(), cost) if v_i - 1 >= 0 and tdsegments[v_i - 1, v_j] < 1: next_vertex = g.get_vertex('a_(' + str(v_i - 1) + ',' + str(v_j) + ')') cost = tdsegments[v_i - 1, v_j] + (1 - obsegments[v_i - 1, v_j]) g.add_edge(vertex.get_id(), next_vertex.get_id(), cost) if (v_i - 1 >= 0 and v_j + 1 <= tdsegments.shape[1] - 1 ) and tdsegments[v_i - 1, v_j + 1] < 1: next_vertex = g.get_vertex('a_(' + str(v_i - 1) + ',' + str(v_j + 1) + ')') cost = tdsegments[v_i - 1, v_j + 1] + (1 - obsegments[v_i - 1, v_j + 1]) g.add_edge(vertex.get_id(), next_vertex.get_id(), cost) if (v_j + 1 <= tdsegments.shape[1] - 1) and tdsegments[v_i, v_j + 1] < 1: next_vertex = g.get_vertex('a_(' + str(v_i) + ',' + str(v_j + 1) + ')') cost = tdsegments[v_i, v_j + 1] + (1 - obsegments[v_i, v_j + 1]) g.add_edge(vertex.get_id(), next_vertex.get_id(), cost) if (v_i + 1 <= tdsegments.shape[0] - 1 and v_j + 1 <= tdsegments.shape[1] - 1 ) and tdsegments[v_i + 1, v_j + 1] < 1: next_vertex = g.get_vertex('a_(' + str(v_i + 1) + ',' + str(v_j + 1) + ')') cost = tdsegments[v_i + 1, v_j + 1] + (1 - obsegments[v_i + 1, v_j + 1]) g.add_edge(vertex.get_id(), next_vertex.get_id(), cost) if (v_i + 1 <= tdsegments.shape[0] - 1) and tdsegments[v_i + 1, v_j] < 1: next_vertex = g.get_vertex('a_(' + str(v_i + 1) + ',' + str(v_j) + ')') cost = tdsegments[v_i + 1, v_j] + (1 - obsegments[v_i + 1, v_j]) g.add_edge(vertex.get_id(), next_vertex.get_id(), cost) if (v_i + 1 <= tdsegments.shape[0] - 1 and v_j - 1 >= 0) and tdsegments[v_i + 1, v_j - 1] < 1: next_vertex = g.get_vertex('a_(' + str(v_i + 1) + ',' + str(v_j - 1) + ')') cost = tdsegments[v_i + 1, v_j - 1] + (1 - obsegments[v_i + 1, v_j - 1]) g.add_edge(vertex.get_id(), next_vertex.get_id(), cost) if (v_j - 1 >= 0) and tdsegments[v_i, v_j - 1] < 1: next_vertex = g.get_vertex('a_(' + str(v_i) + ',' + str(v_j - 1) + ')') cost = tdsegments[v_i, v_j - 1] + (1 - obsegments[v_i, v_j - 1]) g.add_edge(vertex.get_id(), next_vertex.get_id(), cost) entry_s = np.random.choice(entries[0], 1) exit_s = np.random.choice(exits[0], 1) dijk = Dijkstra(g) entry_vertex = 'a_(' + str(entry_s[0]) + ',0)' exit_vertex = 'a_(' + str( exit_s[0]) + ',' + str(tdsegments.shape[1] - 1) + ')' print("Entry %s" % entry_vertex) print("Exit %s" % exit_vertex) traversed_g = dijk.traversing(entry_vertex, exit_vertex) end_vertex = traversed_g.get_vertex(exit_vertex) print(end_vertex) path = [end_vertex] dijk.shortest(end_vertex, path) print("Shortest Path") for s in path[::-1]: print(s.get_id()) stsegments[s.get_i() + 1, s.get_j()] = stsegments[s.get_i() + 1, s.get_j()] + 1 dijk = None stsegments[0, :] = trespassers np.savetxt(outputfile, stsegments, delimiter=",")