def __init__(self, node_file_path, link_file_path, dist_col="dist_corr"): self.graph3 = dijkstra.Graph() self.graph1 = dijkstra.Graph() links_df = pd.read_csv(link_file_path) for r, row in links_df.iterrows(): self.graph1.add_edge(row["frm_node"], row["to_node"], row[dist_col]) if row["n_link_sample"] >= 3: self.graph3.add_edge(row["frm_node"], row["to_node"], row[dist_col]) nodes_df = pd.read_csv(node_file_path) self.node_lat_arr = nodes_df["lat"].values self.node_lng_arr = nodes_df["lng"].values self.node_names = nodes_df["node"].values self.node_col = np.argwhere(nodes_df.columns.values == "node")[0][0]
def create_map(x_size, y_size, obs_list): grid = dij.Graph() for i in range(0, y_size): for j in range(0, x_size - 1): n1 = y_size * i + j n2 = n1 + 1 if not ((n1 in obs_list) or (n2 in obs_list)): grid.add_edge(n1, n2, 1) for j in range(x_size - 1, 0, -1): n1 = y_size * i + j n2 = n1 - 1 if not ((n1 in obs_list) or (n2 in obs_list)): grid.add_edge(n1, n2, 1) for j in range(0, x_size): for i in range(0, y_size - 1): n1 = y_size * i + j n2 = n1 + x_size if not ((n1 in obs_list) or (n2 in obs_list)): grid.add_edge(n1, n2, 1) for i in range(y_size - 1, 0, -1): n1 = y_size * i + j n2 = n1 - x_size if not ((n1 in obs_list) or (n2 in obs_list)): grid.add_edge(n1, n2, 1) return grid
def find_path(self): #create graph graph = dijkstra.Graph() #construct vertices and edges for i in range(self.rows): for j in range(self.cols): id = i * self.rows + j adjacent = [] if (i != 0): adjacent.append((i - 1) * self.rows + j) graph.add_edge(id, (i - 1) * self.rows + j, 1) if (j != 0): adjacent.append(i * self.rows + j - 1) graph.add_edge(id, i * self.rows + j - 1, 1) if (i != (self.rows - 1)): adjacent.append((i + 1) * self.rows + j) graph.add_edge(id, (i + 1) * self.rows + j, 1) if (j != (self.cols - 1)): adjacent.append(i * self.rows + j + 1) graph.add_edge(id, i * self.rows + j + 1, 1) new_v = dijkstra.Vertex(id, i, j, adjacent) graph.add_vertex(new_v) # update edges for obstacle nodes for edge in self.obstacles['costs']: id = edge['i'] * self.rows + edge['j'] graph.update_in_edges(id, edge['value']) #compute and convert the shortest path shortest_path = graph.shortest_path(self.wI * self.rows + self.wJ, self.eI * self.rows + self.eJ) dict_path = [{'i': v.i, 'j': v.j} for v in shortest_path] return {'steps': len(dict_path), 'path': dict_path}
def get_shortest_paths(self, router_id): """Return a list of shortest paths from router_id to all other nodes""" g = dijkstra.Graph() nodes = [] paths = {} for lsa in self.values(): nodes.append(lsa.adv_router) for data in lsa.networks.values(): neighbor_id, cost = data[:2] g.add_e(lsa.adv_router, neighbor_id, cost) if router_id in nodes: nodes.remove(router_id) # Find a shortest path from router_id to dest dist, prev = g.s_path(router_id) for dest in nodes: # Trace the path back using the prev array. path = [] current = dest while current in prev: path.insert(0, prev[current]) current = prev[current] try: cost = dist[dest] except KeyError: continue else: next_hop = (path[1] if len(path) > 1 else dest) paths[dest] = (next_hop, cost) return paths
def setUp(self): #testing out two different kinds of graphs, one based on speed limit + distance #and one based purely on distance self.speed_graph = dj.Graph('test_data.gpkg', 'dc_roads', 'road_nodes') self.length_graph = dj.Graph('test_data.gpkg', 'dc_roads', 'road_nodes', cost_field='km') #generate all the shortest paths to node 60288 self.speed_paths = self.speed_graph.dijkstra(60288) self.length_paths = self.length_graph.dijkstra(60288) self.testAdjList() self.testAdjListInsert() self.testSpeed() self.testLength()
def __init__(self, venue_id, lat, lon): # Set up member variables self.waypoints = {} self.graph = dijkstra.Graph() self.venue_id = venue_id # Create graph from the database self.create_graph(lat, lon)
def create_vgraph(coord, edges): graph = dijkstra.Graph() for i in range(0, len(coord)): graph.add_vertex(i) for j in range(0, len(coord)): if (i != j): if feasible_segment(coord[i], coord[j], edges): graph.add_edge(i, j, canvas.dist(coord[i], coord[j])) return graph
def get_dist_graph(self): # O(m*logn) graph = dijkstra.Graph() for i in self.edges: for j in self.edges[i]: graph.add_edge(i, j[0], self.distance(i, j[0])) return graph
def get_time_graph(self, time=False): # O(m*logn) graph = dijkstra.Graph() for i in self.edges: for j in self.edges[i]: if time and j[1][1]: continue graph.add_edge(i, j[0], self.time_dist(i, j)) return graph
def get_cost(source_tree): graph = dijkstra.Graph() for i, node in enumerate(source_tree): graph.add_node(i) graph.add_edge(node, i, 1) N = len(source_tree) cost = 100 * np.ones((N, N)) for d, h in enumerate(source_tree): for a in range(N): if a == h or a == d: cost[a, d] = 0 else: cost[a, d] = dijkstra.transformation(graph, a, h) return cost
def dijkstra(start, dest): keys = node.lsdb.keys() graph_array = [] for key in keys: node_array = node.lsdb[key] for n in node_array: graph_array.append((key, n, 1)) import dijkstra graph = dijkstra.Graph(graph_array) shortest_path = graph.dijkstra(start, dest) return shortest_path
def convert_road_matrix_to_distance_dict(route_map): graph = dijkstra.Graph() distance_dict = {} for node in range(0, len(route_map)): graph.add_node(node) for start_node in range(0, len(route_map)): for end_node in range(0, len(route_map)): distance = route_map[start_node][end_node] if distance >= 0: graph.add_edge(start_node, end_node, distance) for node in graph.nodes: distance_dict[node] = dijkstra.dijkstra(graph, node) return distance_dict
def create_graph(matrix): i = 0 j = 0 graph = [] while i < len(matrix): while j < len(matrix[i]): # only add the node if there is a route if matrix[i][j] > 0: graph.append((str(i), str(j), matrix[i][j])) j += 1 i += 1 j = 0 # this prints the nodes created for dijkstra # print(graph) return dijkstra.Graph(graph)
def tree_dijk(root, nodes, edges): flag = False graph = dk.Graph() list = [] for node in nodes: graph.add_node(node) for edge in edges: c, v1, v2 = edge.split(" ") graph.add_edge(str(v1), str(v2), int(c)) for i in nodes: if (i != root): cost, path = dk.shortest_path(graph, root, i, flag) list.append(path) return list
def linkStateRouting(data): grafoDatos = [] mensajeEnvio = {} for conexion in tablaConexionesPesos: grafoDatos.append((conexion[0], conexion[1], conexion[2])) grafoDatos.append((conexion[1], conexion[0], conexion[2])) graph = dijkstra.Graph(grafoDatos) data['receptor'] = graph.dijkstra(data["emisor"], data["receptor_final"])[1] for conexion in tablaConexionesPesos: if ((conexion[0] == data['emisor'] and conexion[1] == data['receptor']) or (conexion[1] == data['emisor'] and conexion[0] == data['receptor'])): data['distancia'] = data['distancia'] + conexion[2] data['path_appender'].append(nombreNodo) mensajeEnvio = data sio.emit( 'my_response', mensajeEnvio )
def __init__(self, description): self.__graph = dijkstra.Graph() self.__dumpDescription(description)
7178,2046,4419,744,8312,5356,6855,8839,319,2962,5662,47,6307,8662,68,4813,567,2712,9931,1678,3101,8227,6533,4933,6656,92,5846,4780,6256,6361,4323,9985,1231,2175,7178,3034,9744,6155,9165,7787,5836,9318,7860,9644,8941,6480,9443,8188,5928,161,6979,2352,5628,6991,1198,8067,5867,6620,3778,8426,2994,3122,3124,6335,3918,8897,2655,9670,634,1088,1576,8935,7255,474,8166,7417,9547,2886,5560,3842 6957,3111,26,7530,7143,1295,1744,6057,3009,1854,8098,5405,2234,4874,9447,2620,9303,27,7410,969,40,2966,5648,7596,8637,4238,3143,3679,7187,690,9980,7085,7714,9373,5632,7526,6707,3951,9734,4216,2146,3602,5371,6029,3039,4433,4855,4151,1449,3376,8009,7240,7027,4602,2947,9081,4045,8424,9352,8742,923,2705,4266,3232,2264,6761,363,2651,3383,7770,6730,7856,7340,9679,2158,610,4471,4608,910,6241 4417,6756,1013,8797,658,8809,5032,8703,7541,846,3357,2920,9817,1745,9980,7593,4667,3087,779,3218,6233,5568,4296,2289,2654,7898,5021,9461,5593,8214,9173,4203,2271,7980,2983,5952,9992,8399,3468,1776,3188,9314,1720,6523,2933,621,8685,5483,8986,6163,3444,9539,4320,155,3992,2828,2150,6071,524,2895,5468,8063,1210,3348,9071,4862,483,9017,4097,6186,9815,3610,5048,1644,1003,9865,9332,2145,1944,2213 9284,3803,4920,1927,6706,4344,7383,4786,9890,2010,5228,1224,3158,6967,8580,8990,8883,5213,76,8306,2031,4980,5639,9519,7184,5645,7769,3259,8077,9130,1317,3096,9624,3818,1770,695,2454,947,6029,3474,9938,3527,5696,4760,7724,7738,2848,6442,5767,6845,8323,4131,2859,7595,2500,4815,3660,9130,8580,7016,8231,4391,8369,3444,4069,4021,556,6154,627,2778,1496,4206,6356,8434,8491,3816,8231,3190,5575,1015 3787,7572,1788,6803,5641,6844,1961,4811,8535,9914,9999,1450,8857,738,4662,8569,6679,2225,7839,8618,286,2648,5342,2294,3205,4546,176,8705,3741,6134,8324,8021,7004,5205,7032,6637,9442,5539,5584,4819,5874,5807,8589,6871,9016,983,1758,3786,1519,6241,185,8398,495,3370,9133,3051,4549,9674,7311,9738,3316,9383,2658,2776,9481,7558,619,3943,3324,6491,4933,153,9738,4623,912,3595,7771,7939,1219,4405 2650,3883,4154,5809,315,7756,4430,1788,4451,1631,6461,7230,6017,5751,138,588,5282,2442,9110,9035,6349,2515,1570,6122,4192,4174,3530,1933,4186,4420,4609,5739,4135,2963,6308,1161,8809,8619,2796,3819,6971,8228,4188,1492,909,8048,2328,6772,8467,7671,9068,2226,7579,6422,7056,8042,3296,2272,3006,2196,7320,3238,3490,3102,37,1293,3212,4767,5041,8773,5794,4456,6174,7279,7054,2835,7053,9088,790,6640 3101,1057,7057,3826,6077,1025,2955,1224,1114,6729,5902,4698,6239,7203,9423,1804,4417,6686,1426,6941,8071,1029,4985,9010,6122,6597,1622,1574,3513,1684,7086,5505,3244,411,9638,4150,907,9135,829,981,1707,5359,8781,9751,5,9131,3973,7159,1340,6955,7514,7993,6964,8198,1933,2797,877,3993,4453,8020,9349,8646,2779,8679,2961,3547,3374,3510,1129,3568,2241,2625,9138,5974,8206,7669,7678,1833,8700,4480 4865,9912,8038,8238,782,3095,8199,1127,4501,7280,2112,2487,3626,2790,9432,1475,6312,8277,4827,2218,5806,7132,8752,1468,7471,6386,739,8762,8323,8120,5169,9078,9058,3370,9560,7987,8585,8531,5347,9312,1058,4271,1159,5286,5404,6925,8606,9204,7361,2415,560,586,4002,2644,1927,2824,768,4409,2942,3345,1002,808,4941,6267,7979,5140,8643,7553,9438,7320,4938,2666,4609,2778,8158,6730,3748,3867,1866,7181 171,3771,7134,8927,4778,2913,3326,2004,3089,7853,1378,1729,4777,2706,9578,1360,5693,3036,1851,7248,2403,2273,8536,6501,9216,613,9671,7131,7719,6425,773,717,8803,160,1114,7554,7197,753,4513,4322,8499,4533,2609,4226,8710,6627,644,9666,6260,4870,5744,7385,6542,6203,7703,6130,8944,5589,2262,6803,6381,7414,6888,5123,7320,9392,9061,6780,322,8975,7050,5089,1061,2260,3199,1150,1865,5386,9699,6501 3744,8454,6885,8277,919,1923,4001,6864,7854,5519,2491,6057,8794,9645,1776,5714,9786,9281,7538,6916,3215,395,2501,9618,4835,8846,9708,2813,3303,1794,8309,7176,2206,1602,1838,236,4593,2245,8993,4017,10,8215,6921,5206,4023,5932,6997,7801,262,7640,3107,8275,4938,7822,2425,3223,3886,2105,8700,9526,2088,8662,8034,7004,5710,2124,7164,3574,6630,9980,4242,2901,9471,1491,2117,4562,1130,9086,4117,6698 2810,2280,2331,1170,4554,4071,8387,1215,2274,9848,6738,1604,7281,8805,439,1298,8318,7834,9426,8603,6092,7944,1309,8828,303,3157,4638,4439,9175,1921,4695,7716,1494,1015,1772,5913,1127,1952,1950,8905,4064,9890,385,9357,7945,5035,7082,5369,4093,6546,5187,5637,2041,8946,1758,7111,6566,1027,1049,5148,7224,7248,296,6169,375,1656,7993,2816,3717,4279,4675,1609,3317,42,6201,3100,3144,163,9530,4531 7096,6070,1009,4988,3538,5801,7149,3063,2324,2912,7911,7002,4338,7880,2481,7368,3516,2016,7556,2193,1388,3865,8125,4637,4096,8114,750,3144,1938,7002,9343,4095,1392,4220,3455,6969,9647,1321,9048,1996,1640,6626,1788,314,9578,6630,2813,6626,4981,9908,7024,4355,3201,3521,3864,3303,464,1923,595,9801,3391,8366,8084,9374,1041,8807,9085,1892,9431,8317,9016,9221,8574,9981,9240,5395,2009,6310,2854,9255 8830,3145,2960,9615,8220,6061,3452,2918,6481,9278,2297,3385,6565,7066,7316,5682,107,7646,4466,68,1952,9603,8615,54,7191,791,6833,2560,693,9733,4168,570,9127,9537,1925,8287,5508,4297,8452,8795,6213,7994,2420,4208,524,5915,8602,8330,2651,8547,6156,1812,6271,7991,9407,9804,1553,6866,1128,2119,4691,9711,8315,5879,9935,6900,482,682,4126,1041,428,6247,3720,5882,7526,2582,4327,7725,3503,2631 2738,9323,721,7434,1453,6294,2957,3786,5722,6019,8685,4386,3066,9057,6860,499,5315,3045,5194,7111,3137,9104,941,586,3066,755,4177,8819,7040,5309,3583,3897,4428,7788,4721,7249,6559,7324,825,7311,3760,6064,6070,9672,4882,584,1365,9739,9331,5783,2624,7889,1604,1303,1555,7125,8312,425,8936,3233,7724,1480,403,7440,1784,1754,4721,1569,652,3893,4574,5692,9730,4813,9844,8291,9199,7101,3391,8914 6044,2928,9332,3328,8588,447,3830,1176,3523,2705,8365,6136,5442,9049,5526,8575,8869,9031,7280,706,2794,8814,5767,4241,7696,78,6570,556,5083,1426,4502,3336,9518,2292,1885,3740,3153,9348,9331,8051,2759,5407,9028,7840,9255,831,515,2612,9747,7435,8964,4971,2048,4900,5967,8271,1719,9670,2810,6777,1594,6367,6259,8316,3815,1689,6840,9437,4361,822,9619,3065,83,6344,7486,8657,8228,9635,6932,4864 8478,4777,6334,4678,7476,4963,6735,3096,5860,1405,5127,7269,7793,4738,227,9168,2996,8928,765,733,1276,7677,6258,1528,9558,3329,302,8901,1422,8277,6340,645,9125,8869,5952,141,8141,1816,9635,4025,4184,3093,83,2344,2747,9352,7966,1206,1126,1826,218,7939,2957,2729,810,8752,5247,4174,4038,8884,7899,9567,301,5265,5752,7524,4381,1669,3106,8270,6228,6373,754,2547,4240,2313,5514,3022,1040,9738 2265,8192,1763,1369,8469,8789,4836,52,1212,6690,5257,8918,6723,6319,378,4039,2421,8555,8184,9577,1432,7139,8078,5452,9628,7579,4161,7490,5159,8559,1011,81,478,5840,1964,1334,6875,8670,9900,739,1514,8692,522,9316,6955,1345,8132,2277,3193,9773,3923,4177,2183,1236,6747,6575,4874,6003,6409,8187,745,8776,9440,7543,9825,2582,7381,8147,7236,5185,7564,6125,218,7991,6394,391,7659,7456,5128,5294 2132,8992,8160,5782,4420,3371,3798,5054,552,5631,7546,4716,1332,6486,7892,7441,4370,6231,4579,2121,8615,1145,9391,1524,1385,2400,9437,2454,7896,7467,2928,8400,3299,4025,7458,4703,7206,6358,792,6200,725,4275,4136,7390,5984,4502,7929,5085,8176,4600,119,3568,76,9363,6943,2248,9077,9731,6213,5817,6729,4190,3092,6910,759,2682,8380,1254,9604,3011,9291,5329,9453,9746,2739,6522,3765,5634,1113,5789 5304,5499,564,2801,679,2653,1783,3608,7359,7797,3284,796,3222,437,7185,6135,8571,2778,7488,5746,678,6140,861,7750,803,9859,9918,2425,3734,2698,9005,4864,9818,6743,2475,132,9486,3825,5472,919,292,4411,7213,7699,6435,9019,6769,1388,802,2124,1345,8493,9487,8558,7061,8777,8833,2427,2238,5409,4957,8503,3171,7622,5779,6145,2417,5873,5563,5693,9574,9491,1937,7384,4563,6842,5432,2751,3406,7981 """ test_graph = dijkstra.Graph(test_matrix, 4) test_path = test_graph.make_path() for n in test_path: print(n) p = test_graph.calc_path_length(test_path) print(p) if p == 2297: graph = dijkstra.Graph(matrix, 4) path = graph.make_path() print(graph.calc_path_length(path))
def getCollection(): mapName = request.args.get('map') origin = request.args.get('origin') #Ponto de origem destiny = request.args.get('destiny') #Ponto final (chegada) price = request.args.get('price') autonomy = request.args.get('autonomy') steps = [] # Lista que ira ser preenchida com todos os passos do caminho dictPaths = {} # Dicionario com o valor de todos as rotas graph = dijkstra.Graph( ) # Lib que faz o grafico de vertex para calcular o dijkstra vertex = [] # Lista de vertex try: map = collection.find_one({'title': mapName}) except: response = jsonify( {'response': 'Application could not use the DB especifield'}) response.status_code = 500 return response # Fazendo a iteração para preencher uma lista # de vertex que serão usado na lib Graph() for vert in map['routes']: vertex.append(vert['origin']) vertex.append(vert['destiny']) # Iterando nos vertex setando para que nao se repitam for i in list(set(vertex)): graph.add_vertex(i) # Adicionando os vertexa lib Graph for vert in map['routes']: dictPaths[vert['origin'] + vert['destiny']] = vert['distance'] graph.add_edge(vert['origin'], vert['destiny'], vert['distance']) # Verificando se os pontos existem if origin not in vertex: response = jsonify({ 'response': 'The parameter origin does not contain on map %s' % mapName }) response.status_code = 400 return response if destiny not in vertex: response = jsonify({ 'response': 'The parameter destiny does not contain on map %s' % mapName }) response.status_code = 400 return response dijkstra.dijkstra(graph, graph.get_vertex(origin), graph.get_vertex(destiny)) target = graph.get_vertex(destiny) path = [target.get_id()] dijkstra.shortest(target, path) a = 0 while a < (len(path[::-1]) - 1): steps.append(path[::-1][a] + path[::-1][a + 1]) a = a + 1 total = 0 for i in steps: total = total + dictPaths[i] # Apenas formatando a lista para utf-8 pathList = [] for i in path[::-1]: pathList.append(i.encode('utf-8')) # Fazendo o calculo do custo nessa rota de menor distancia cost = float(total) / float(autonomy) * float(price) response = [] response.append({'Path': '%s' % pathList}) response.append({'Total KM': '%.2f' % total}) response.append({'Cost': '%.2f' % cost}) return jsonify(data=response)
#json.load(data_file) #Loading the file containing our vehicles-requets-edges distances datastore = json.load(open('data.json', 'r')) #Parsing the input JSON data file into 3 variables with key word in '.....' distances = datastore['distances'] requests = datastore['requests'] vehicles = datastore['vehicles'] #Iterating over all the items in vehicles and initializing the availability for each one to TRUE for vehicle in vehicles: vehicle['available'] = True #Creating an object of Dijkstra's class to use the methods inside g = dijkstra.Graph() #Iterating over all the elements in distances variable and adding vertices/nodes/points it to graph for distance in distances: #We are adding the zipcode1 and zipcode2(nodes) only after checking whether they already exist in the object 'g'(graph) or not #If the zipcode is present, we skip it and if not, we add it to our graph as a new vertex/node point if not distance['zipcode1'] in g.get_vertices(): g.add_vertex(distance['zipcode1']) if not distance['zipcode2'] in g.get_vertices(): g.add_vertex(distance['zipcode2']) #Adding the edges to the graph from start #passing vertices as arguments, we are drawing an edge between the two nodes and assigning thier weightage. g.add_edge(distance['zipcode1'], distance['zipcode2'], distance['distance'])
nodes = [[None for _ in range(image.width)] for __ in range(image.height)] for x in range(image.width): for y in range(image.height): pixel = pixels[x, y] if pixel == COLOR_WALL: nodes[y][x] = None else: nodes[y][x] = d.Node(x, y) if pixel == COLOR_START: initial_coords = (x, y) if pixel == COLOR_END: destination_coords = (x, y) graph = d.Graph(nodes, initial_coords, destination_coords) destination_distance = d.dijkstra(graph) initial_node = graph.graph[initial_coords[1]][initial_coords[0]] destination_node = graph.graph[destination_coords[1]][destination_coords[0]] nodes = graph.get_nodes() for node in nodes: if node: node.visited = False current_node = destination_node smallest_tentative_distance = destination_distance # Go from destination node to initial node to find path
def navigate(map_file, scale, entry_point, items_file, labels_file): # Each item "x" will have a file x_output.png which contains an image of the path output_file = "output.png" # Black COLOR_WALL = (0, 0, 0, 255) # White COLOR_PATH = (255, 255, 255, 255) # Red COLOR_START = (255, 0, 0, 255) # Green COLOR_END = (0, 255, 0, 255) # Blue COLOR_SOLVED = (0, 0, 255, 255) HOST = '127.0.0.1' # Standard loopback interface address (localhost) PORT = 65432 # Port to listen on (non-privileged ports are > 1023) try: image = Image.open(map_file) imagePixels = image.load() except: print("Could not load file", map_file) exit() # Saving the imagePixels in a 2D array to refer to this whenever resetting pixels defaultPixels = [[None for _ in range(image.height)] for __ in range(image.width)] for x in range(image.width): for y in range(image.height): defaultPixels[x][y] = imagePixels[x, y] f = open(items_file) data = json.load(f) destinations = dict() distances = dict() graphs = dict() for k, v in data.items(): destinations[k] = tuple(v) distances[k] = float("inf") graphs[k] = None f = open(labels_file) data = json.load(f) labels = dict() for k, v in data.items(): labels[k] = tuple([tuple(v[0]), v[1]]) # # access points of items # destinations = { # "apple": (1.1, 0), # "shampoo": (2.2, 1.4), # "deodorant": (1.7, 0.5), # } # # Distances to reach the items from varying starting points # # Every time we reach an item, we remove it from the distances & graphs dictionary and set visited flag in destinations as false # distances = { # "apple": float("inf"), # "shampoo": float("inf"), # "deodorant": float("inf") # } # graphs = { # "apple": None, # "shampoo": None, # "deodorant": None # } # # Label with its centre and rotation # labels = { # "1": ((1.4, 1.7), 0), # located in pixel (4,5) facing downward # "2": ((1.7, 2.2), -90), # located in pixel (5,7) facing the right # "3": ((2.3, 1.3), -90) # located in pixel (7,4) facing the right # } # Initial point that is replaced at the end with whatever destination we reach initialX = entry_point[0] initialY = entry_point[1] # Establishing socket and listening with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) print("Waiting for connection...") s.listen() conn, addr = s.accept() print("Connected") with conn: while len(distances) > 0: nodes = [[None for _ in range(image.width)] for __ in range(image.height)] for k, v in destinations.items(): # Resetting pixels to default pixel values every iteration pixels = [[None for _ in range(image.height)] for __ in range(image.width)] for x in range(image.width): for y in range(image.height): pixels[x][y] = defaultPixels[x][y] pixels[convertRealToMap(scale, initialX)][convertRealToMap( scale, initialY)] = COLOR_START pixels[convertRealToMap(scale, v[0])][convertRealToMap( scale, v[1])] = COLOR_END for x in range(image.width): for y in range(image.height): pixel = pixels[x][y] if pixel == COLOR_WALL: nodes[y][x] = None else: nodes[y][x] = d.Node(x, y) if pixel == COLOR_START: initial_coords = (x, y) if pixel == COLOR_END: destination_coords = (x, y) graph = d.Graph(nodes, initial_coords, destination_coords) # Saving destination graph graphs[k] = graph # Saving destination distance distances[k] = d.dijkstra(graph) # Retrieving item with minimum distance and plotting its path item = min(distances, key=distances.get) print("Item that we are going to retrieve: " + item) graph = graphs[item] initial_node = graph.graph[convertRealToMap( scale, initialY)][convertRealToMap(scale, initialX)] destination_node = graph.graph[convertRealToMap( scale, destinations[item][1])][convertRealToMap( scale, destinations[item][0])] nodes = graph.get_nodes() for node in nodes: if node: node.visited = False current_node = destination_node smallest_tentative_distance = distances[item] # Go from destination node to initial node to find path while current_node is not initial_node: neighbors = graph.get_neighbors(current_node) for neighbor in neighbors: if not neighbor or neighbor.visited: continue if neighbor.tentative_distance < smallest_tentative_distance: smallest_tentative_distance = neighbor.tentative_distance neighbor.visited = True current_node = neighbor imagePixels[current_node.x, current_node.y] = COLOR_SOLVED imagePixels[destination_node.x, destination_node.y] = COLOR_END image.save(item + "_" + output_file, "PNG") # Resetting the image pixels that were coloured for the next item's path for x in range(image.width): for y in range(image.height): if imagePixels[x, y] == COLOR_SOLVED: imagePixels[x, y] = COLOR_PATH currentRealX = currentRealY = -1 # Giving directions until destination is reached while convertRealToMap( scale, currentRealX) != convertRealToMap( scale, destinations[item][0]) or convertRealToMap( scale, currentRealY) != convertRealToMap( scale, destinations[item][1]): # Receiving coordinates from received from another process through socket data = conn.recv(1024) if not data: raise Exception("Disconnected from client") # Function that converts camera plane coordinates to map plane coordinates labelNo, cameraRealX, cameraRealY = data.decode().split() # Handling invalid label received try: currentRealX, currentRealY = rotate_around_point( (float(cameraRealX), float(cameraRealY)), labels[labelNo][1], labels[labelNo][0]) except KeyError: continue currentMapX = convertRealToMap(scale, currentRealX) currentMapY = convertRealToMap(scale, currentRealY) for node in nodes: if node: node.visited = False current_node = destination_node smallest_tentative_distance = distances[item] # Flag if directions are sent directions_sent = False # Go from destination node to initial node to find path while current_node is not initial_node: neighbors = graph.get_neighbors(current_node) for neighbor in neighbors: if not neighbor or neighbor.visited: continue if neighbor.tentative_distance < smallest_tentative_distance: smallest_tentative_distance = neighbor.tentative_distance neighbor.visited = True # Printing the instructions on how to move to reach destination if neighbor.x == currentMapX and neighbor.y == currentMapY: # Printing directions # print("Heading towards " + item + ": Move by " + str(current_node.x - neighbor.x) + " x blocks & " + str(current_node.y - neighbor.y) + " y blocks") string_to_send = "Heading towards " + item + ": Move by " + str( current_node.x - neighbor.x) + " x blocks & " + str( current_node.y - neighbor.y) + " y blocks" conn.sendall(string_to_send.encode()) directions_sent = True current_node = neighbor if not directions_sent: # Do nothing is sent when either an item has just been retrieved or location received is invalid conn.sendall(b"Do nothing") # Change initial point at the end to the destination point initialX = currentRealX initialY = currentRealY # Remove the item from the destinations, distances and graphs dictionaries del destinations[item] del distances[item] del graphs[item]
def __init__(self, *data_centers): self._graph = dijkstra.Graph() self._graph.read_from_file(NetworkInfo._path) self._data_centers = set(data_centers) self._user_nodes = self._graph.nodes - self._data_centers
print("\nNot a valid number for distance, please try again.") else: x[2] = int(x[2]) # make distance into an int edges.append(tuple(x)) # append tuple to edge list print("\nEdge " + str(x) + " added!") answer = input( "\nAre these all the edges you want? Input Y/y for yes, anything else for no: " ) if answer == "y" or answer == "Y": # make sure they want to calculate this expression break elif answer == "exit": # if user wants to quit, break from loop sentence = "exit" break if sentence == "exit": # if you broke from the previous loop, break from big loop break graph = dijkstra.Graph(edges) # add edges and create the graph while True: # ask to calculate path sentence = input( "\nPlease input the shortest path you want to calculate in the form-> NODE1 NODE2: " ) x = sentence.split(' ', 1) if len(x) != 2: # make sure length is 2 nodes long print("\nInvalid input form, please try again.") elif x[0] not in graph.nodes or x[ 1] not in graph.nodes: # make sure both of the nodes are actually in the graph print( "\nOne or more of the nodes is invalid, please try again.") else: # perform dijkstra's algorithm
#!/usr/bin/env pypy3 import dijkstra as dij import math if __name__ == '__main__': graph = dij.Graph() # fin = open('test.txt', 'r') # graph.vexnum = int(fin.readline()) # start, end = [int(i) for i in fin.readline().split()] # fin = open('t()est.txt', 'r') # fin.close graph.vexnum = int(input()) start, end = [int(i) for i in input().split()] for i in range(graph.vexnum): graph.arcs.append( [int(j) if int(j) != -1 else math.inf for j in input().split()]) # graph.arcs.append([int(j) if int(j) != -1 else math.inf for j in fin.readline().split()]) for j in range(i): graph.arcs[i][j] = graph.arcs[j][i] # print(graph.arcs) short, path = graph.shortestpath(start, end) print("Min=%f" % short) print("Path ", end='') for i in path: print(i, end=' ') print() pass
import ProbabilityFunction import dijkstra src = int(input("Enter node of packet Src : ")) dest = int(input("Enter node of packet destination : ")) matrix = [] edgeslist = ProbabilityFunction.matrixEdges(matrix, ProbabilityFunction.n) # print(edgeslist) graph = dijkstra.Graph(ProbabilityFunction.n * ProbabilityFunction.n) # graph = Graph() print("The Graph is (Src , Destination , weight)") for i in edgeslist: # graph.add_edge(i) u = i["pt1"] v = i["pt2"] w = i["weight"] print(u, v, w) graph.addEdge(u, v, w) print("Shortest Path between %d and %d is " % (src, dest)), l = graph.findShortestPath(src, dest) print("\nShortest Distance between %d and %d is %d " % (src, dest, l)),
data = {"address": get_router_address_for_host(num)} requests.post(url=make_router_url(num), json=data) if exist_link(num, i): data = {"address": get_router_address(num, i, prefix=True)} requests.post(url=make_router_url(num), json=data) def router_add_route(src, by, dst): data = { "gateway": get_router_address(by, src), "destination": get_router_host_address(dst) } requests.post(url=make_router_url(src), json=data) graph = dijkstra.Graph() for i in node_list: router_add_address(i) for i in distance_list: graph.add_edge(i[0], i[1], i[2]) graph.add_edge(i[1], i[0], i[2]) for i in node_list: dij = dijkstra.DijkstraSPF(graph, i) for j in network_list: path = dij.get_path(j) if len(path) >= 2: router_add_route(i, path[1], j)