def __init__(self, source_file=None): with open(source_file) as f: maze = [list(line.strip('\r\n')) for line in f] self.width = max([len(row) for row in maze]) self.height = len(maze) self.loc_warp = dict() self.warp_loc = defaultdict(set) self.graph = Graph() self.interior = set() self.exterior = set() # Copy the file to the local dict: self.maze = self.copy_to_dict(maze) # Identify all the wormhole tokens: self.parse_warps() # Populate graph: self.build_graph() # Start/finish for the maze: self.source = self.warp_loc['AA'].pop() self.target = self.warp_loc['ZZ'].pop() # Part 2: self.scores = dict()
class TestGraph(unittest.TestCase): def setUp(self): self.g = Graph(6) connectivity_array = [[1, 2, 7], [1, 6, 14], [1, 3, 9], [3, 6, 2], [3, 4, 11], [6, 5, 9], [4, 5, 6], [2, 4, 15]] for x in connectivity_array: self.g.connect(x[0] - 1, x[1] - 1, x[2]) self.g.connect(x[1] - 1, x[0] - 1, x[2]) def test_dijkstra(self): self.assertEqual(dijkstra(self.g, 0), {0: 0, 1: 7, 2: 9, 3: 20, 4: 20, 5: 11}) def test_zero_dijkstra(self): g = Graph(2) self.assertEqual(dijkstra(g, 0), {0: 0, 1: float("inf")}) def test_floyd(self): self.assertEqual(floyd(self.g)[0], [0, 7, 9, 20, 20, 11]) def test_floyd_negative(self): inf = float("inf") g = Graph(4) g.edges = [[0, inf, -2, inf], [4, 0, 3, inf], [inf, inf, 0, 2], [inf, -1, inf, 0]] expected = [[0, -1, -2, 0], [4, 0, 2, 4], [5, 1, 0, 2], [3, -1, 1, 0]] self.assertEqual(floyd(g), expected) def test_find_firestation(self): self.assertEqual(find_firestation_floyd(self.g), find_firestation_dijkstra(self.g))
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)
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 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 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 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 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 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 test_floyd_negative(self): inf = float("inf") g = Graph(4) g.edges = [[0, inf, -2, inf], [4, 0, 3, inf], [inf, inf, 0, 2], [inf, -1, inf, 0]] expected = [[0, -1, -2, 0], [4, 0, 2, 4], [5, 1, 0, 2], [3, -1, 1, 0]] self.assertEqual(floyd(g), expected)
def findPathBetweenTwoStationInSameLayer(id1, id2, layerName): if id1 == id2: return [id1] layer = mapNameToLayer[layerName] graph = mapNameToGraph[layerName] # listFakeId = convertFakeId([id1, id2], layer) g = Graph() route = g.dijkstra(graph, listFakeId[0], listFakeId[1]) return convertToTrustId(route, layer)
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 generate_random_graph(nodes, edges_per_node, max_weight): graph = Graph() for node_index in range(1, nodes + 1): for edge_index in range(edges_per_node): weight = randint(1, max_weight) neighbour = node_index while neighbour == node_index: neighbour = randint(0, nodes) graph.add_edge_with_cost(node_index, neighbour, weight) return graph
def find_shortest_traversal(matrix, node_list): """ Given a matrix and a list of nodes, this function will output the shortest traversal visiting the nodes in that order. :param matrix: The matrix :param node_list: The list of nodes :return: List with path """ path = [node_list[0]] graph = Graph() for i in range(len(node_list[:-1])): path.extend(graph.dijkstra(graph=matrix, src=node_list[i])[node_list[i+1]+1][1:]) return path
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 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 get_distance_dict(adj_mat): """ Returns a dictionary of the shortest distances from all node to all others in the parameter adjacency matrix. :param adj_mat: A adjacency matrix (mxn array) for the graph to calculate distances from :return: A dictionary with shortest distances from all nodes to all others """ distances = {} graph = Graph() for i in range(len(adj_mat)): distances[i] = {} for i in range(len(adj_mat)): for j in range(len(adj_mat)): distances[i][j] = graph.dijkstra(adj_mat, i)[0][j] return distances
def SPLIT(Distancias, Demandas, permutacion, capacidad, orden): NODOS = [i for i in range(len(permutacion) + 1)] GRAFO = [] RUTAS = [] for i in range(len(NODOS)): for j in range(i + 1, len(NODOS)): r = [0] acum = 0 for k in range(j, i, -1): r.append(permutacion[k - 1]) acum = acum + Demandas[permutacion[k - 1]] r.append(0) r.reverse() if (acum <= capacidad): d = calcularDistancia(r, Distancias, orden) arco = (i, j, round(d, 2)) GRAFO.append(arco) RUTAS.append(r) print("GRAFO:") for i in range(len(GRAFO)): print(GRAFO[i], ":", RUTAS[i]) sec = list(Graph(GRAFO).dijkstra(NODOS[0], NODOS[-1])) print("Secuencia: ", sec) PETALOS, FO = obtenerPetalos(GRAFO, RUTAS, sec) print("PETALOS PERMUTACIÓN:") print(PETALOS, FO, sum(FO)) return (PETALOS, FO, sum(FO))
def draw_vis_graph(vertices: List[List[float]], g: Graph) -> None: """ Draw the visibility graph of the vertices in a polygon :param vertices: List[List[float]]], list of vertices :param g: Graph, the graph computed from create_vis_graph or create_vis_graph_with_holes :return: None """ for node in list(g.get_nodes()): for neighbor in list(g.get_adjacent_nodes(node)): v1 = vertices[node] v2 = vertices[neighbor] plt.plot([v1[0], v2[0]], [v1[1], v2[1]], color='r', linewidth=0.5) if node != 30: plt.text(v1[0] + 0.5, v1[1], str(node)) if neighbor != 30: plt.text(v2[0] + 0.5, v2[1], str(neighbor))
def main(): count = 0 input = open('dij10.txt', 'r') x = input.read() tamanhoMatriz = 0 #leitura do arquivo da matriz de adjacencia for row, line in enumerate(x.split('\n')): for col, val in enumerate(line.split(' ')): if (count == 0): tamanhoMatriz = int(val) count += 1 break break count = 0 matriz = np.zeros((tamanhoMatriz, tamanhoMatriz)) matrizFinal = np.zeros((tamanhoMatriz, tamanhoMatriz)) for row, line in enumerate(x.split('\n')): for col, val in enumerate(line.split(' ')): if (count == 0): tamanhoMatriz = int(val) count += 1 break else: count += 2 matriz[int(row - 1)][int(col)] = int(val) for i in range(0, tamanhoMatriz): for j in range(i, tamanhoMatriz): if i == j: continue else: matrizFinal[i][j] = matriz[i][j - i - 1] matrizFinal[j][i] = matriz[i][j - i - 1] print('Matriz de adjacencias: \n') print(matrizFinal) g = Graph(tamanhoMatriz) g.graph = matrizFinal g.dijkstra(2) count -= 1
def get_shortest_path(src, dst, link_costs, ROUTER_ID_MAPPING): if src == dst: return 0, int(ROUTER_ID_MAPPING[src]) # Make link_costs symmetrical symm_link_costs = [] for link in link_costs: symm_link_costs.append(link) symm_link_costs.append((link[1], link[0], link[2])) network = Graph(symm_link_costs) try: shortest_path = network.dijkstra(src, dst) except: return 65535, 65535 path_cost = 0 for hop in range(len(shortest_path)-1): path_cost += utils.get_link_cost(shortest_path[hop], shortest_path[hop+1], symm_link_costs) return path_cost, int(ROUTER_ID_MAPPING[shortest_path[1]])
def get_distance_list_fast(self, adj_mat): """ Returns a list of the shortest distances from all node to all others in the parameter adjacency matrix. index corresponds to node, value correponds to distances. :param adj_mat: An adjacency matrix (mxn array) for the graph to calculate distances from :return: A list with shortest distances from all nodes to all others """ distances = [0 for j in range(len(adj_mat))] dijkstras = [0 for j in range(len(adj_mat))] graph = Graph() for i in range(len(adj_mat)): distances[i] = [0 for j in range(len(adj_mat))] dijkstras[i] = graph.dijkstra(adj_mat, i)[0] for i in range(len(adj_mat)): for j in range(len(adj_mat)): distances[i][j] = dijkstras[i][j] return distances
def test_abstract_dijkstra_spf(): graph = Graph() with pytest.raises(NotImplementedError): AbstractDijkstraSPF.get_adjacent_nodes(graph, 0) with pytest.raises(NotImplementedError): AbstractDijkstraSPF.get_edge_weight(graph, 0, 1)
def main(condition, threshold, co, experiment, rounds): # coalition = 10: psfa, others: baseline for t in range(experiment): dynamic_change(stream_rates, traffic_condition[condition]) i_nodes = copy.deepcopy(nodes) i_edges = copy.deepcopy(edges) i_stream_rate = copy.deepcopy(stream_rates) graph = Graph(i_nodes, i_edges, i_stream_rate) if co == 10: coalitions = dk.coalition(graph, i_stream_rate, threshold) else: coalitions = adapt_baseline( form_baseline(baseline_groups[co - 1], i_stream_rate), i_stream_rate) group_lanes = [e[0] for e in coalitions] group_streams = [e[1] for e in coalitions] #print('group_streams = ', group_streams) interval_times = interval_time(group_streams, total_duration, minimum_waiting_time) streams = {lane: stream_rates[lane] for lane in nodes} prob_car = {lane: stream_rates[lane] / 100 for lane in nodes} #0.25 total_number = 0 pass_cars = 0 accident = 0 pre_acc = 0 for i in range(rounds): for c in range(len(coalitions)): group = coalitions[c][0] for j in range(int(interval_times[c])): #every 10 seconds all_cars = [] for lane in group: all_cars = all_cars + lane_list[lane].car_list accident_analysis = current_accident(all_cars) accident = accident + accident_analysis[0] remove_crash_cars(accident_analysis[1], all_cars) pre_acc = pre_acc + tellCollapse(all_cars) pre_acc = pre_acc + tellCollapse(all_cars) for lane in group: pass_cars = pass_cars + lane_list[lane].move_all() if random.uniform(0, 1) < prob_car[lane]: lane_list[lane].car_list.append( Car(lane, lane + str(i) + str(j))) stat_pass_cars.append(pass_cars / rounds) stat_accident.append(accident / rounds) stat_pred_accident.append(pre_acc / rounds) return stat_pass_cars, stat_accident, stat_pred_accident
def get_path_dict(adj_mat): """ Returns a dictionary where the key values are node-indexes and the values are a new dict. The keys in this new dict are all nodes in graph. The values for these keys are shortest paths from original node to key node. :param adj_mat: :return: """ paths = {} graph = Graph() for i in range(len(adj_mat)): paths[i] = {} for i in range(len(adj_mat)): for j in range(len(adj_mat)): if i == j: paths[i][j] = [i] else: paths[i][j] = graph.dijkstra(adj_mat, i)[j+1] return paths
def calculate_cluster_distances(ad_mat, indexes): """ Calculate the distances between the given list of indexes in the given adjacency matrix, using dijkstra. :param ad_mat: The adjacency matrix representing the graph :param indexes: The indexes you want to calculate distances for :return: A dict {node: {other_node: distance}} """ distances = {} graph = Graph() # Each node maintains a list with nodes distances to itself for i in indexes: for j in indexes: distances[i] = {j:0} for i in indexes: for j in indexes: try: distances[i][j] = graph.dijkstra(ad_mat, i)[0][j] except: distances[i][j] = 0 return distances
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 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 create_new_nodeset_graph_and_paint(screen, num_of_nodes, connections_per_node): global nodes, g #nodes = generate_list_of_connected_nodes(260, 5) nodes = generate_list_of_connected_nodes(num_of_nodes, connections_per_node) #nodes = generate_list_of_connected_nodes(160, 2) g = Graph() generate_graph_from_node_list(g, nodes) screen.fill((0, 0, 0)) draw_node_list(screen, nodes) return g
def compute_graphs(self, data, my_coords: Coords): graphs = list() # Crea tots els ordres possibles de recorregut used_orders = set() for i, key_order in enumerate(permutations(data.keys(), len(data)), start=1): if key_order in used_orders: continue used_orders.add(key_order) used_orders.add(key_order[::-1]) # Only one direction is enough init = time() ordered_shops = list() ordered_shops.append([Shop(identifier='A', coords=my_coords)]) ordered_shops.extend([data[key] for key in key_order]) ordered_shops.append([Shop(identifier='B', coords=my_coords)]) graph = Graph(self.compute_edges(ordered_shops)) graphs.append(graph) print(f'Computed subgraph {i} in {time() - init:.2f}s') return graphs
def output_path(ad_mat): # Create a graph graph = Graph() visited = [0] # Start at node 0 home_drops = [] path = [0] while len(visited) != len(ad_mat): remaining = [] for node in range(len(ad_mat)): if node not in visited: remaining.append(node) best = remaining[0] for j in remaining[1:]: if graph.dijkstra(ad_mat, visited[-1])[0][j] < graph.dijkstra( ad_mat, visited[-1])[0][best]: best = j path.extend(graph.dijkstra(ad_mat, visited[-1])[best + 1][1:]) visited.append(best) # Route from end node to start node path.extend(graph.dijkstra(ad_mat, visited[-1])[1][1:]) return path
# coding: utf-8 from dijkstra import Graph example = { 'a': { 'b': 12, 'c': 4 }, 'b': { 'a': 12, 'd': 5, 'e': 3 }, 'c': { 'a': 4, 'd': 2, 'f': 6 }, 'd': { 'b': 5, 'c': 2, 'g': 8 }, 'e': { 'b': 3, 'h': 7 }, 'f': { 'c': 6, 'g': 5 }, 'g': { 'd': 8, 'f': 5, 'h': 3 }, 'h': { 'e': 7, 'g': 3 }, } graph = Graph(example, 'a', 'h') graph.dijkstra() print "Melhor caminho: " + str(graph.shortest_path()) print "Distâncias por vértice: " + str(graph.shortest_path_distance())