def plot_edge_grades(): files_map = '../data/maps/m43.96267779776494_m19.944747838679202_m43.929659815391865_m19.905049264605925.graphml' G = ox.load_graphml(files_map) max_lat = -12.934333867695516 min_lat = -12.961083555974895 max_lon = -38.473331269107426 min_lon = -38.49996781691653 name_geotiff = '../data/maps/19S45_ZN.tif' G = ox.graph_from_bbox(max_lat, min_lat, max_lon, min_lon, network_type='all') G = Graph.set_node_elevation(G, name_geotiff) # deadends = [(u, v) for u, v, k, data in G.edges(keys=True, data=True) if data['highway'] == ''] # print(deadends) # G2.remove_nodes_from(deadends) G = Graph.edge_grades(G) G_proj = ox.project_graph(G) ec = ox.plot.get_edge_colors_by_attr(G_proj, "grade", cmap="plasma", num_bins=5, equal_size=True) fig, ax = ox.plot_graph(G_proj, edge_color=ec, edge_linewidth=0.5, node_size=0, bgcolor="w")
def nodes_data(file_name, stop_points, material_weights, file_osm, geotiff): G = ox.load_graphml(file_name) lats = [a_tuple[0] for a_tuple in stop_points] lons = [a_tuple[1] for a_tuple in stop_points] nodes_coordinates = {} nodes_mass_increment = {} [nodes_coordinates.update([(list(G.neighbors(n))[0], (d['y'], d['x']))]) \ for n, d in G.nodes(data=True) if d['y'] in lats and d['x'] in lons and len(list(G.neighbors(n))) == 1] [nodes_mass_increment.update([(list(G.neighbors(n))[0], material_weights.get((d['y'], d['x']))[0])]) \ for n, d in G.nodes(data=True) if d['y'] in lats and d['x'] in lons and len(list(G.neighbors(n))) == 1] if len(list(nodes_coordinates.keys())) != len(stop_points): [nodes_coordinates.update([(n, (d['y'], d['x']))]) for n, d in G.nodes(data=True) if d['y'] in lats and d['x'] in lons] [nodes_mass_increment.update([(n, material_weights.get((d['y'], d['x']))[0])]) \ for n, d in G.nodes(data=True) if d['y'] in lats and d['x'] in lons] Scenario.simulation_edit_graph(G, file_osm) G = Graph.set_node_elevation(G, geotiff) G = Graph.edge_grades(G) #G = Graph.update_weight(G, VEHICLE_MASS) Graph.save_graph_file(G, file_name) return G, nodes_coordinates, nodes_mass_increment
def nodes_data(file_name, stop_points, material_weights, file_osm, geotiff, file): G = ox.load_graphml(file_name) nodes_coordinates = {} nodes_mass_increment = {} try: f = open(file + '.json', "r") dados = json.loads(f.read()) f.close() except: dados = 0 pass dados = dict(dados) tam = len(list(dados.values())) dados = list(dados.values())[:tam-2] [nodes_coordinates.update([(int(d[0][2]), (d[0][0], d[0][1]))]) \ for d in list(dados)] [nodes_mass_increment.update([(int(d[0][2]), int(d[0][3]))]) \ for d in list(dados)] Scenario.simulation_edit_graph(G, file_osm) G = Graph.set_node_elevation(G, geotiff) G = Graph.edge_grades(G) #G = Graph.update_weight(G, VEHICLE_MASS) Graph.save_graph_file(G, file_name) return G, nodes_coordinates, nodes_mass_increment
def cost_path(G, source, target, vehicle_mass, impedance): """ This function calculates the path between source and target nodes, and returns it. Besides, calculates the sum of all edges weight of the path, and returns it. :param G: NetworkX graph. Geographic scenario :param source: :param target: :param vehicle_mass: :return: """ # updates the weight of all edges of the scenario according # to the current weight of the vehicle G = Graph.update_weight(G, vehicle_mass) # finds the shortest path to the destination in the scenario graph path = Heuristics.shortest_path_faster(G, source, target, weight=impedance) # cost to get to the destination: # the sum of the weight of all the edges from the path sum_path_costs = sum_costs(G, path, impedance) # updates the weight of all edges of the scenario according # to the current weight of the vehicle G = Graph.update_weight(G, VEHICLE_MASS) return sum_path_costs, path
def plot_elevation_belem(): files_map = '../data/maps/m48.488877797764935_m1.484547838679201_m48.45585981539186_m1.4448492646059234.graphml' G = ox.load_graphml(files_map) max_lat = -1.449 min_lat = -1.479 max_lon = -48.462 min_lon = -48.488 name_geotiff = '../data/maps/01S495ZN.tif' G = ox.graph_from_bbox(max_lat, min_lat, max_lon, min_lon, network_type='all') G = Graph.set_node_elevation(G, name_geotiff) G = Graph.edge_grades(G) # G_proj = ox.project_graph(G) nc = ox.plot.get_node_colors_by_attr(G, 'elevation', cmap='plasma', num_bins=10) # , start=0, stop=1 cmap = plt.cm.get_cmap('plasma') print( "belem", max(list(nx.get_node_attributes(G, 'elevation').values())) - min(list(nx.get_node_attributes(G, 'elevation').values()))) norm = plt.Normalize( vmin=min(list(nx.get_node_attributes(G, 'elevation').values())), vmax=max(list(nx.get_node_attributes(G, 'elevation').values()))) sm = mpl.cm.ScalarMappable(norm=norm, cmap=cmap) sm.set_array([]) fig, ax = ox.plot_graph(G, node_color=nc, node_size=45, edge_linewidth=0.7, bgcolor='w', show=False) # pad: position of colorbar, shrink=.92: colorbar size cb = fig.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax, orientation='vertical', shrink=.94, fraction=0.15, pad=-0.0001) cb.ax.tick_params(labelsize=25) cb.set_label('Elevação (m)', fontsize=25, labelpad=23, fontweight='bold') plt.show()
def sum_costs(G, path, impedance): """ This function calculates the sum of the costs of a path created according to the geographic scenario graph. :param G: NetworkX graph. Geographic scenario :param path: list The list must contains the id of nodes of the path. :param weight: String or function :return: float The sum of all cost (weight) edges of the path. """ weight = Graph._weight(G, impedance) sum_costs = 0 for i in range(len(path) - 1): e = G.adj[path[i]].get(path[i + 1]) weight_edge = weight(path[i], path[i + 1], e) sum_costs += weight_edge return sum_costs
def graph_scenario(stop_points, geotiff_name, ad_weights, file_name_osm): max_lat, min_lat, max_lon, min_lon = Coordinates.create_osmnx(stop_points) # Scenario graph (paths are edges and junctions are nodes) G = ox.graph_from_bbox(max_lat, min_lat, max_lon, min_lon, network_type='all') G, nodes_coordinates, nodes_mass_increment = Graph.configure_graph(G, geotiff_name, stop_points, ad_weights, file_name_osm) return G, nodes_coordinates, nodes_mass_increment
def cost_path(G, source, target, vehicle_mass, impedance, heuristic): """ This function calculates the path between source and target nodes, and returns it. Besides, calculates the sum of all edges weight of the path, and returns it. :param G: NetworkX graph. Geographic scenario :param source: :param target: :param vehicle_mass: :return: """ # updates the weight of all edges of the scenario according # to the current weight of the vehicle if impedance == 'weight': G = Graph.update_weight(G, vehicle_mass) # finds the shortest path to the destination in the scenario graph if heuristic == 'SPFA': distance, path = Heuristics.bellman_ford(G, source, target, weight=impedance) #path = Heuristics.shortest_path_faster(G, source, target, impedance) elif heuristic == 'dijkstra': distance, path = Heuristics.bidirectional_dijkstra(G, source, target, weight=impedance) elif heuristic == 'astar': path = nx.astar_path(G, source, target, weight=impedance) else: distance, path = Heuristics.bellman_ford(G, source, target, weight=impedance) # cost to get to the destination: # the sum of the weight of all the edges from the path sum_path_costs = sum_costs(G, path, impedance) # updates the weight of all edges of the scenario according # to the current weight of the vehicle #if impedance == 'weight': # G = Graph.update_weight(G, VEHICLE_MASS) return sum_path_costs, path
def calculate_power(G, dict_edges_net, id_edge, vehicle_mass, speed): nodes = Map_Simulation.edges_to_nodes(id_edge, dict_edges_net) data_edge = G.get_edge_data(nodes[0], nodes[1]) slope = data_edge.get(0).get('grade') surface_floor = data_edge.get(0).get('surface') current_force = Graph.force(vehicle_mass, surface_floor, slope) power = current_force * speed return power
def _shortest_path_faster(G, source, weight): """ This function returns the single-source shortest path in weighted directed graph based on Shortest Path Faster Algorithm (SPFA). It is an improvement of the Bellman– Ford algorithm. The pseudocode of the SPFA: https://en.wikipedia.org/wiki/Shortest_Path_Faster_Algorithm :param G: NetworkX graph. input graph :param source: Float Id of the start node :param target: Float Id of the goal node :param weight: Function :return: List List with all nodes of the shortest path """ weight = Graph._weight(G, weight) last_edge = {source: (None, None)} pred_edge = {source: None} source = [source] q = deque(source) G_adjacents = G.succ if G.is_directed() else G.adj n_G = len(G_adjacents) count = {} dist = {} parent = {} inf = float("inf") # Initialization for i in G.nodes: dist.update([(i, inf)]) parent.update([(i, None)]) dist.update([(source[0], 0)]) while q: u = q.popleft() # for each edge between the node u and their adjacent nodes for v, e in G_adjacents[u].items(): # Relaxing new_dist_v = dist.get(u) + weight(u, v, e) if new_dist_v < dist.get(v): if v in last_edge[u]: print("Error: Negative cost cycle.") return False if v in pred_edge and pred_edge[v] == u: last_edge[v] = last_edge[u] else: last_edge[v] = (u, v) dist.update([(v, new_dist_v)]) parent.update([(v, u)]) if v not in q: q.append(v) count_v = count.get(v, 0) + 1 if count_v == n_G: print("Error: Negative cost cycle") return False count[v] = count_v pred_edge[v] = u return dist, parent
def nearest_neighbor(G, H, source, target, impedance, heuristic): """ :param G: NetworkX graph. input graph :param source: Float Id of the start node :param target: Float Id of the goal node :param weight: Function :return: List List with all nodes of the shortest path """ if source not in H: print("Error") return False open = [source] closed = [] current_vehicle_mass = VEHICLE_MASS nodes_graph = list(H.nodes) nodes_graph.remove(target) route = [] route1 = [] cost_total = 0 edges_update_mass = [] while len(open) > 0: dist = {} node = open.pop(0) closed.append(node) missing = verifying_nodes(closed, nodes_graph) # if current node is the target (objective) and # there is not nodes missing to be visited if node == target and missing is False: if impedance == 'weight': G = Graph.update_weight(G, VEHICLE_MASS) fig, ax = ox.plot_graph_route(G, route1[-1], route_linewidth=6, node_size=0, bgcolor='w') return cost_total, route, edges_update_mass else: # checks nodes that have not yet been added in closed possibilities = set(H.adj[node]) - set(closed) for u in possibilities: # checks the edge weight according to the vehicle's mass + # mass increase at the current vertex edge_cost, path = Graph_Collect.cost_path( G, node, u, current_vehicle_mass, impedance, heuristic) dist.update([(u, [edge_cost, path])]) # sorting the dict according to edge weights dist = dict(sorted(dist.items(), key=lambda item: item[1][0])) # if starting and arrival point is the same node if len(dist) < 1 and source == target: new_node = target else: new_node = list(dist.keys())[0] # if there are more than one not visited node # and the nearest node is the arrival point if len(dist) > 1 and new_node == target: new_node = list(dist.keys())[1] route.extend(list(dist.values())[1][1][:-1]) route1.append(list(dist.values())[1][1][:-1]) cost_total += float(list(dist.values())[1][0]) edges_update_mass.append(list(dist.values())[0][1][:2]) elif new_node == target: route.extend(list(dist.values())[0][1]) route1.append(list(dist.values())[0][1]) cost_total += float(list(dist.values())[0][0]) edges_update_mass.append(list(dist.values())[0][1][:2]) else: route.extend(list(dist.values())[0][1][:-1]) route1.append(list(dist.values())[0][1][:-1]) cost_total += float(list(dist.values())[0][0]) edges_update_mass.append(list(dist.values())[0][1][:2]) open.append(new_node) current_vehicle_mass += H.nodes[new_node]['mass']
def create_route(stop_points, material_weights, json_files, n = None, n_points=10): # the desired geotiff name to the mosaic mosaic_geotiff_name = 'out.tif' geotiff_name_out = MAPS_DIRECTORY + mosaic_geotiff_name # creates the geographic rectangular area based on stop points coordinates # downloads the Open Street Map (osm) file of the area osm_file = OpenSteetMap.file_osm(MAPS_DIRECTORY, stop_points) # downloads the GeoTiff file(s) of the area from the Topodata site # it returns the geotiff name of the Topodata database geotiff_name = GeoTiff.geotiff(MAPS_DIRECTORY, stop_points) geotiff_name = MAPS_DIRECTORY + geotiff_name + '.tif' # gdal translate of the geotiff file geotiff_transformation(geotiff_name, geotiff_name_out) # creates a rectangular area based on stop points coordinates max_lat, min_lat, max_lon, min_lon = Coordinates.create_osmnx(stop_points) # G_file is the name of the graph file (.graphml extension) G_file = Saves.def_file_name(MAPS_DIRECTORY, stop_points, '.graphml') # defines the json file name of the simulation results file_name_json = Saves.def_file_name(RESULTS_DIRECTORY, stop_points, '') + '_' + str(n) + '_' + str(n_points) json_files.append(file_name_json) # the coordinates of the area is used to verify if the graph exists coordinates_list = Coordinates.coordinates_list_bbox(stop_points) """ # if the graph exists, it is not necessary to do all configurations on the graph if verify_graph_exists(G_file, stop_points, coordinates_list) is True: # creates the .net.xml file (SUMO simulator file) netconvert_geotiff(osm_file, geotiff_name_out, NET) # configure the elevation and edge weights # creates dictionaries with coordinates and mass increment data G, nodes_coordinates, nodes_mass_increment = nodes_data(G_file, stop_points, material_weights, osm_file, geotiff_name) else: """ # delete collect points added before in the osm file Map_Simulation.delete_osm_items(osm_file) # if there are ways that can be bidirectional to 'carrinheiro' if BIDIRECTIONAL is True: Map_Simulation.edit_map(osm_file) # creates the osmnx graph based on the geographic area # Scenario graph (paths are edges and junctions are nodes) G = ox.graph_from_bbox(max_lat, min_lat, max_lon, min_lon, network_type='all') # configure the graph G, nodes_coordinates, nodes_mass_increment = Graph.configure_graph_simulation(G, geotiff_name, stop_points, material_weights, osm_file, G_file) ########### # the starting point is the first collect point of the vector index_source = list(nodes_coordinates.values()).index(stop_points[0]) node_source = list(nodes_coordinates.keys())[index_source] # the arrival point is the last collect point of the vector index_target = list(nodes_coordinates.values()).index(stop_points[-1]) node_target = list(nodes_coordinates.keys())[index_target] # creates the ordering graph # it is a complete graph with the number of nodes equivalent to number of collect points H = Graph_Collect.create_graph_route(nodes_coordinates, nodes_mass_increment) # dictionary with adjacent edges information dict_edges_net = Map_Simulation.edges_net(NET) # it is necessary configure the edges on simulator to allow the carrinheiro's type of vehicle Map_Simulation.allow_vehicle(NET) politics = ['weight', 'length'] heuristics = ['SPFA', 'dijkstra', 'astar'] """ # Nearest heuristic_combination(nn, G, H, node_source, node_target, politics[0], heuristics[0], stop_points, dict_edges_net, nodes_mass_increment, file_name_json) heuristic_combination(nn, G, H, node_source, node_target, politics[0], heuristics[1], stop_points, dict_edges_net, nodes_mass_increment, file_name_json) heuristic_combination(nn, G, H, node_source, node_target, politics[0], heuristics[2], stop_points, dict_edges_net, nodes_mass_increment, file_name_json) heuristic_combination(nn, G, H, node_source, node_target, politics[1], heuristics[0], stop_points, dict_edges_net, nodes_mass_increment, file_name_json) heuristic_combination(nn, G, H, node_source, node_target, politics[1], heuristics[1], stop_points, dict_edges_net, nodes_mass_increment, file_name_json) heuristic_combination(nn, G, H, node_source, node_target, politics[1], heuristics[2], stop_points, dict_edges_net, nodes_mass_increment, file_name_json) # Closest heuristic_combination(ci, G, H, node_source, node_target, politics[0], heuristics[0], stop_points, dict_edges_net, nodes_mass_increment, file_name_json) heuristic_combination(ci, G, H, node_source, node_target, politics[0], heuristics[1], stop_points, dict_edges_net, nodes_mass_increment, file_name_json) heuristic_combination(ci, G, H, node_source, node_target, politics[0], heuristics[2], stop_points, dict_edges_net, nodes_mass_increment, file_name_json) heuristic_combination(ci, G, H, node_source, node_target, politics[1], heuristics[0], stop_points, dict_edges_net, nodes_mass_increment, file_name_json) heuristic_combination(ci, G, H, node_source, node_target, politics[1], heuristics[1], stop_points, dict_edges_net, nodes_mass_increment, file_name_json) heuristic_combination(ci, G, H, node_source, node_target, politics[1], heuristics[2], stop_points, dict_edges_net, nodes_mass_increment, file_name_json) """ # Further heuristic_combination(fi, G, H, node_source, node_target, politics[0], heuristics[0], stop_points, dict_edges_net, nodes_mass_increment, file_name_json) heuristic_combination(fi, G, H, node_source, node_target, politics[0], heuristics[1], stop_points, dict_edges_net, nodes_mass_increment, file_name_json) heuristic_combination(fi, G, H, node_source, node_target, politics[0], heuristics[2], stop_points, dict_edges_net, nodes_mass_increment, file_name_json) heuristic_combination(fi, G, H, node_source, node_target, politics[1], heuristics[0], stop_points, dict_edges_net, nodes_mass_increment, file_name_json) heuristic_combination(fi, G, H, node_source, node_target, politics[1], heuristics[1], stop_points, dict_edges_net, nodes_mass_increment, file_name_json) heuristic_combination(fi, G, H, node_source, node_target, politics[1], heuristics[2], stop_points, dict_edges_net, nodes_mass_increment, file_name_json) return json_files
def further_insertion(G, H, source, target, impedance, heuristic): current_vehicle_mass = VEHICLE_MASS path = [source] costs_to_source = {} # create a dictionary with the nodes and respective mass increments of the vehicle mass = {} for i in H.nodes: mass.update([(i, H.nodes[i]['mass'])]) # verify the cost of the source to the nodes for u in H.adj[source]: edge_cost, _ = Graph_Collect.cost_path(G, source, u, current_vehicle_mass, impedance, heuristic) costs_to_source.update([(u, edge_cost)]) # sorting the dict according to edge weights costs_to_source = dict( sorted(costs_to_source.items(), key=lambda item: item[1], reverse=True)) # add the closest node of the source path.append(list(costs_to_source.keys())[0]) # updates the vehicle mass according to current path current_vehicle_mass = updates_vehicle_mass(path, mass) nodes = list(H.nodes) nodes.remove(target) possibilities = set(nodes) - set(path) # all nodes must be visited while len(possibilities) > 0: # len(path) < len(nodes): # get the closest node of any node inside the path max_cost = float('-inf') k_node = float('inf') for a in path: for b in possibilities: cost, _ = Graph_Collect.cost_path(G, a, b, current_vehicle_mass, impedance, heuristic) if cost > max_cost: max_cost = cost k_node = b # the k node must be inserted in a position of the path # where the cost (cost_IK + cost_KJ - cost_IJ) is minimum max_cost = float('-inf') position = 0 for i in range(len(path) - 1): current_vehicle_mass = updates_vehicle_mass(path[:i], mass) cost_IK, _ = Graph_Collect.cost_path(G, path[i], k_node, current_vehicle_mass, impedance, heuristic) cost_KJ, _ = Graph_Collect.cost_path(G, k_node, path[i + 1], current_vehicle_mass, impedance, heuristic) cost_IJ, _ = Graph_Collect.cost_path(G, path[i], path[i + 1], current_vehicle_mass, impedance, heuristic) total_cost = cost_IK + cost_KJ - cost_IJ # print('costs', cost_IK, cost_KJ, cost_IJ, total_cost) if total_cost > max_cost: a_1 = path[i] a_2 = path[i + 1] max_cost = total_cost position = i + 1 path.insert(position, k_node) current_vehicle_mass = updates_vehicle_mass(path, mass) # nodes not yet visited possibilities = set(nodes) - set(path) path.append(target) # get all paths cost_total, paths, edges_update = Graph_Collect.sum_costs_route( G, H, path, VEHICLE_MASS, impedance, heuristic) if impedance == 'weight': G = Graph.update_weight(G, VEHICLE_MASS) return cost_total, paths, edges_update
def plot_elevation(): files_map = '../data/maps/m38.49905230272549_m12.960541036813272_m38.47398437502447_m12.935229804750517.graphml' G = ox.load_graphml(files_map) max_lat = -12.934333867695516 min_lat = -12.961083555974895 max_lon = -38.473331269107426 min_lon = -38.49996781691653 name_geotiff = '../data/maps/12S39_ZN.tif' G = ox.graph_from_bbox(max_lat, min_lat, max_lon, min_lon, network_type='all') G = Graph.set_node_elevation(G, name_geotiff) G = Graph.edge_grades(G) # G_proj = ox.project_graph(G) nc = ox.plot.get_node_colors_by_attr(G, 'elevation', cmap='plasma', num_bins=10) # , start=0, stop=1 cmap = plt.cm.get_cmap('plasma') #norm = plt.Normalize(vmin= 0, vmax=max(list(nx.get_node_attributes(G, 'elevation').values())) - min(list(nx.get_node_attributes(G, 'elevation').values()))) print( "Salvador", max(list(nx.get_node_attributes(G, 'elevation').values())) - min(list(nx.get_node_attributes(G, 'elevation').values()))) norm = plt.Normalize( vmin=min(list(nx.get_node_attributes(G, 'elevation').values())), vmax=max(list(nx.get_node_attributes(G, 'elevation').values()))) sm = mpl.cm.ScalarMappable(norm=norm, cmap=cmap) sm.set_array([ min(list(nx.get_node_attributes(G, 'elevation').values())), 10, 20, 30, 40, 50, 60, 70, 80, 85 ]) figsize = (20, 20) fig, ax = ox.plot_graph(G, node_color=nc, node_size=35, edge_linewidth=0.7, bgcolor='w', show=False) fig, ax = ox.plot_graph(G, ax=ax, node_color=nc, node_size=35, edge_linewidth=0.7, bgcolor='w', show=False) #plt.axis([-38.49996781691653, -38.473331269107426, -12.961083555974895, -12.934333867695516],option='on') #ax.axis('on') #ax.set(xlim=(-38.49996781691653, -38.473331269107426), ylim=(-12.961083555974895, -12.934333867695516), option='on') # pad: position of colorbar, shrink=.92: colorbar size cb = fig.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax, orientation='vertical', shrink=.94, fraction=0.15, pad=-0.0001) cb.ax.tick_params(labelsize=25) cb.set_label('Altitude [m]', fontsize=25, labelpad=23, fontweight='bold') #ax.set_xticks(x) plt.show()
if __name__ == '__main__': G = ox.graph_from_bbox(-22.796008, -22.843953, -47.054891, -47.107718000000006, network_type='all') stop_points = [(-22.820204, -47.085525), (-22.825029, -47.068495), (-22.824376, -47.070952), (-22.82503, -47.07410), (-22.82504, -47.07730), (-24.992554, -47.069115)] # (-22.816008, -47.075614)] # fig1, ax1 = ox.plot_graph(G, node_size=5, edge_color='#333333', bgcolor='k') # Graph.save_graph_file(G, '../' + MAPS_DIRECTORY, 'test1') weigths = { (-22.816639, -47.074891): (50, 'Kg'), (-22.818317, -47.083415): (30, 'Kg'), (-22.820244, -47.085422): (15, 'Kg'), (-22.823953, -47.087718): (12, 'Kg') } G, nodes_collect_and_coordinates, nodes_collect_and_weights = add_collect_points( G, stop_points, weigths) G = Graph.set_node_elevation(G, '../' + MAPS_DIRECTORY + '22S48_ZN.tif') G = Graph.edge_grades(G) Graph.save_graph_file(G, '../' + MAPS_DIRECTORY, 'test.graphml') # Graph.plot_graph(G) weight = Graph._weight(G, 'weight') distance, route = nx.bidirectional_dijkstra(G, 1000000002, 1000000011, weight) print(route)
for v in g.get_vertex(p[len(p)-1]).get_connections(): if(v.visited=='yes'): continue elif(v.get_id() in p ): continue else: v.visited='yes' a=1 route[start+'->'+v.get_id()]=route[start]+g.get_vertex(p[len(p)-1]).get_weight(v) PQ1.push(start+'->'+v.get_id(), g.get_vertex('lafayette').distance1(v)) if a==1: GBFS1(g, stop, PQ1, route, rslt) return 0 if __name__ == '__main__': g = Graph() PQ=PriorityQueue() results=[] route={} f=open('input.txt', 'r') f.readline() k=f.readline() while (k!= 'Edges:\n'): p=k.split(', ') g.add_vertex(p[0], p[1], p[2]) k=f.readline() while(k !=None): if(k==''): break elif(k!= 'Edges:\n'): p=k.split(', ')
for x in range(0, len(vetc)): if vetc[x].visited!='yes': stk.push(vetc[x]) vetc[x].visited='yes' path.append(vetc[x].get_id()) distance+=start.get_weight(vetc[x]) if vetc[x].get_id()==stop.get_id(): print'The path for Depth-First Search for the graph is %s and the distance taken is %d' %(path, distance) return 0 DFS(vetc[x], stop, stk, path, distance) if stk.isEmpty()!=True: stk.pop() return 0 if __name__ == '__main__': g = Graph() distance=0 stack= Stack() path=[] f=open('input.txt', 'r') f.readline() k=f.readline() p=k.split(', ') for name in p: g.add_vertex(name) print name k=f.readline() while(k !=None): if(k==''): break
for v in g.get_vertex(p[len(p)-1]).get_connections(): if(v.get_id() in p ): continue else: a=1 route[start+'->'+v.get_id()]=route[start] + g.get_vertex(p[len(p)-1]).get_weight(v) if b==1: PQ.push(start+'->'+v.get_id(), g.get_vertex('houston').distance(v)+g.get_vertex('lafayette').distance(v)) else: PQ.push(start+'->'+v.get_id(), g.get_vertex('houston').distance1(v)+g.get_vertex('lafayette').distance1(v)) if a==1: AS(g, stop, PQ, route, rslt, b) return 0 if __name__ == '__main__': g = Graph() PQ=PriorityQueue() results=[] route={} f=open('input.txt', 'r') f.readline() k=f.readline() while (k!= 'Edges:\n'): p=k.split(', ') g.add_vertex(p[0], p[1], p[2]) k=f.readline() while(k !=None): if(k==''): break elif(k!= 'Edges:\n'): p=k.split(', ')
def bidirectional_dijkstra(G, initial_node, target_node, weight): weight = Graph._weight(G, weight) print("dij", initial_node, target_node) distance, route = nx.bidirectional_dijkstra(G, initial_node, target_node, weight) return distance, route
def bellman_ford(G, initial_node, target_node, weight): weight = Graph._weight(G, weight) distance, route = nx.single_source_bellman_ford(G, initial_node, target_node, weight) return distance, route
for x in range(0, len(vetc)): Q.push(vetc[x]) currentnode=Q.pop() path.append(currentnode.get_id()) if currentnode in start.adjacent.keys(): distance+=start.get_weight(currentnode) if currentnode.get_id()==stop.get_id(): print'The path for Breadth-First Search for the graph is %s and the distance taken is %d' %(path, distance) return 0 BFS(currentnode,stop, Q, path, distance) return 0 if __name__ == '__main__': g = Graph() distance=0 Q=Queue() path=[] f=open('input.txt', 'r') f.readline() k=f.readline() p=k.split(', ') for name in p: g.add_vertex(name) print name k=f.readline() while(k !=None): if(k==''): break