def run(self, start, end, ele_mode, cost_percentage): start = ox.geocode(start) target = ox.geocode(end) graph_origin_file = "data/Amherst_city_graph.pkl" graph_project_file = "data/Amherst_city_graph_projected.pkl" # "Amherst_city_graph_projected.pkl" graph_project, graph_orig = controller_obj.read_map_data(False, graph_origin_file, graph_project_file) source = ox.get_nearest_node(graph_orig, (start)) destination = ox.get_nearest_node(graph_orig, (target)) shortest_path_length = self.get_ground_truth_shorest_length(graph_orig, source, destination) # self.get_total_length(graph_projection, shortest_path) overhead = cost_percentage allowed_cost = ((100.0 + overhead) * shortest_path_length) / 100.0 elevation_mode = ele_mode route2 = self.get_dijkstra_evelation_shorest_perentage_route(graph_orig, source, destination, allowed_cost, elevation_mode=elevation_mode) x = ox.plot_route_folium(graph_orig, route2, route_color='green') folium.Marker(location=start, icon=folium.Icon(color='red')).add_to(x) folium.Marker(location=target, icon=folium.Icon(color='blue')).add_to(x) filepath = "output/example.html" x.save(filepath)
def recommendation_output(): [os.remove(file) for file in glob.glob('/Users/niall/insight_project/projectname/static/map_out_*.png')] rightnow = dt.now() picname = "map_out_%i%i%i%i%i" % (rightnow.month, rightnow.day, rightnow.hour, rightnow.minute, rightnow.second) filename_out = '/Users/niall/insight_project/projectname/static/%s' % (picname) # Pull input input1 =request.args.get('user_input1') input2 =request.args.get('user_input2') print(input1) origin = [] destination = [] try: origin = list(ox.geocode(input1)) destination = list(ox.geocode(input2)) except: pass # Case if empty if input1 =="" or input2 =="": return render_template("index.html", my_input = input1, my_form_result="Empty") elif not origin: return render_template("index.html", my_input = input1, my_form_result="Empty_origin") elif not destination: return render_template("index.html", my_input = input2, my_form_result="Empty_destination") else: # origin = list(ox.geocode(input1)) # destination = list(ox.geocode(input2)) # get the weather data current_weather = CF.get_current_weather_toronto() # add the weather data to the unique roads roads_with_weather = CF.add_current_weather_to_unique_roads(current_weather) # run the unique roads through the classifier and save locally roads_with_weather = CF.get_collision_probs(roads_with_weather) # save the graph as the name used by the return statement below CF.plot_map_with_probs_routes(roads_with_weather, origin, destination, filename=filename_out) # CF.plot_map_with_probs_routes(roads_with_weather) some_output = "yeay!" some_number = 0 some_image = '%s%s' % (picname, '.png') return render_template("index.html", my_input=input1, my_output=some_output, my_number=some_number, my_img_name=some_image, my_form_result="NotEmpty")
def generate(self): # main code # creating variable to store punggol boundary punggol = (1.403948, 103.909048) distance = 2000 # user input startpoint = ox.geocode(self.src) endpoint = ox.geocode(self.des) startosmid = ox.get_nearest_node(self.G_walk, startpoint, method='euclidean', return_dist=True) endosmid = ox.get_nearest_node(self.G_walk, endpoint, method='euclidean', return_dist=True) # calculating heuristic distance from start to end point main_h = self.heuristic(self.latlon(startosmid[0]), self.latlon(endosmid[0])) # recording down algorithmn speed start_time = time.time() # running A* algorithm with start osmid, end osmid and heuristic distance of start and end point # total A* algorithm complexity: Log(E + V) final = self.walk_astar(startosmid[0], endosmid[0], main_h) end_time = round((time.time() - start_time), 2) print("--- %s seconds ---" % end_time) # calculations for Time taken and distance travelled totaldist = final[1] + (startosmid[1] * 1000) + (endosmid[1] * 1000) # calculating estimated time to reach the destination taking avg human walking speed of 1.4m/s estwalk = totaldist / (1.4 * 60) print("Time: " + str(round(estwalk)) + " minutes" + "\nDistance: " + str(round((totaldist / 1000), 2)) + " km") # storing the calculations into variables to pass over to flask to print out for user self.walkvariable = ("Time taken for run the algorithm: %s seconds" % end_time) self.walkvariable1 = ("Time taken: " + str(round(estwalk)) + " minutes") self.walkvariable2 = ("Distance travelled: " + str(round((totaldist / 1000), 2)) + " km") # converting osm ids to coords final[0] = self.convertRoute(ox.plot.node_list_to_coordinate_lines(self.G_walk, final[0])) # plotting map to folium m = folium.Map(location=punggol, distance=distance, zoom_start=15, tiles="OpenStreetMap") folium.Marker(startpoint, popup=self.src, icon=folium.Icon(color='red', icon='record')).add_to(m) folium.Marker(endpoint, popup=self.des, icon=folium.Icon(color='red', icon='record')).add_to(m) folium.PolyLine(([startpoint] + final[0] + [endpoint]), color="blue", weight=2, opacity=1).add_to(m) # saving the plotted coordinates to an html file m.save("templates/default.html") print("Successfully overwrite default.html!!!")
def plot_route_to_html(home_address, track, ref, operator): """Given a starting and destination point, create and plot route""" #Starting point is inputted byt he user, so we simply convert it to a point starting_point = osmnx.geocode(home_address) #Destination point is the last member of the track that is a way (there are also node in the track and they are usually not ordered) track_members = track.members() destination_node = None destination_point = None while destination_point is None: #found the first way of the relation, getting the first node if track_members[0].nodes(): #checking if we want the first or last node of the way if len(track_members) > 1: first_way_first_last = [track_members[0].nodes()[0].id(), track_members[0].nodes()[-1].id()] second_way_first_last = [track_members[1].nodes()[0].id(), track_members[1].nodes()[-1].id()] if first_way_first_last[0] in second_way_first_last: destination_node = track_members[0].nodes()[-1] else: destination_node = track_members[0].nodes()[0] else: destination_node = track_members[0].nodes()[0] destination_point = (destination_node.lat(), destination_node.lon()) else: del track_members[0] time_needed = Map.print_path(starting_point, destination_point, ref, operator) directions_link = "https://www.openstreetmap.org/directions?engine=graphhopper_car&route={}%2C{}%3B{}%2C{}".format(starting_point[0], starting_point[1], destination_point[0], destination_point[1]) data_route = '<iframe src="./home_to_destination/{}/home_to_CAI_{}.html"></iframe><br><a href="{}">Directions on OSM</a>'.format(operator, ref, directions_link) data_time = int(time_needed/1000/60) #time returned in milliseconds return [data_route, data_time, destination_point]
def get_node_from_address(graph, address): """ Converts a string address to the closest node on a graph. Parameters: ----------- graph: networkx Graph The graph to perform the look up. address: String The address to convert to a node. Returns: -------- node: The closest node to the address given. """ try: latlng = ox.geocode(address) node, dist = ox.get_nearest_node(graph, latlng, return_dist=True) if dist > 10000: raise Exception( "{} is not currently included in Routing Capabilities".format( address)) return node except: raise Exception("Could not find location '{}'".format(address))
def get_path(origin, destination, weight, graph=None): """Returns a path from origin to destination taking elevation into account per the parameter 'weight' after generating model. Parameters ---------- origin : string String pertaining to origin's address destination: string String pertaining to destination's address weight: int value that pertains to how much we want to weigh elevation Returns ------- graph: NetworkX graph Returns a grapy representing the route. Notes ----- """ graph = ox.load_graphml( "boston-elevation-graph") if graph is None else graph opoint = ox.geocode(origin) dpoint = ox.geocode(destination) o_node = ox.get_nearest_node(graph, tuple(reversed(opoint))) d_node = ox.get_nearest_node(graph, tuple(reversed(dpoint))) weight_choice = "elev{weight}".format(weight=weight) route = nx.shortest_path(graph, source=o_node, target=d_node, weight=weight_choice) print(route) fig, ax = ox.plot_graph_route(graph, route, node_size=0) return route
def geocode(self, address): """Geocode a single address with OSM.""" try: result = ox.geocode(address) return { 'address': address, 'latitude': result[0], 'longitude': result[1], } # Note - Ox raises general exceptions Exception. except Exception as error: logger.error(error.__class__.__name__ + ' - ' + str(error)) return None
def graph_from_circle(query, radius=1000, network_type='all_private', dual=False, return_igraph=False, save_pickle=False, fname='graphs\\city_graph', osmnx_query_kws={}): """ Like fetching a graph with osmnx but with a circle instead of a square. Parameters ---------- query : string or dict Location to query Nominatim. radius: float Radius of the circle. network_type: string see osmnx network types dual: bool if true converts graph to its dual form return_igraph: bool if true retruns the graph as iGraph save_pickle: bool if True saves file as a pickle in fname directory fname: string Directory to save. osmnx_query_kws: dict options for osmnx query. See osmnx properties at https://osmnx.readthedocs.io/en/stable/osmnx.html. Returns ------- iGraph or NetworkX graph """ pt = ox.geocode(query) poly = circle_from_lat_lon(*pt, radius) G = ox.graph_from_polygon(poly, network_type=network_type, **osmnx_query_kws) G.graph['kind'] = 'primal' if dual: G = get_dual(G) if return_igraph: G = get_full_igraph(G) if save_pickle and return_igraph: _save_pickle_file(G, fname, extention='ig') elif save_pickle and not return_igraph: _save_pickle_file(G, fname, extention='nx') return G
def __init__(self, api_key, run_distance, address, difficulty='hard', graph=None): self.api_key = api_key self.difficulty = difficulty self.run_distance = run_distance self.address = address self.address_lat_lon = ox.geocode(address) if graph is None: self.G = self.render_graph() self.add_alt_grades() else: self.G = graph self.add_alt_grades() self.home_node = ox.get_nearest_node(self.G, self.address_lat_lon)
def PointList(a): for i in range (0, len(a)): points.append(ox.geocode(a[i]))
import osmnx as ox import networkx as nx import folium import matplotlib.pyplot as plt from sklearn.neighbors import KDTree get_ipython().run_line_magic('matplotlib', 'inline') # creating a graph by using a point in downtown Omaha old_market = (40.704620, -73.876030) G = ox.graph_from_point(old_market, distance=5000) #banks bank1 = ox.geocode('8000 Cooper Ave, Glendale, NY 11385') bank2 = ox.geocode('9030 Metropolitan Ave, Rego Park, NY 11374') bank3 = ox.geocode('7011 Myrtle Ave, Glendale, NY 11385') fig, ax = ox.plot_graph(G, fig_height=10, fig_width=10, show=False, close=False, edge_color='black') ax.scatter(bank1[1], bank1[0], c='red', s=100) ax.scatter(bank2[1], bank2[0], c='blue', s=100) ax.scatter(bank3[1], bank3[0], c ='yellow', s = 100) plt.savefig('firstnodes.png') # In[44]:
radius = None if use_coordinates: if len(arguments) < 2: print("You need to specify a longitude and latitude.") sys.exit(1) if len(arguments) > 2: radius = arguments[2] latitude = arguments[0] longitude = arguments[1] else: if len(arguments) < 1: print("You need to specify an address or place.") sys.exit(1) if len(arguments) > 1: radius = arguments[1] latitude, longitude = ox.geocode(arguments[0]) data = util.load_json_from_dgraph(latitude, longitude, radius) else: data = json.load(sys.stdin) G = util.reconstruct_network_from_dgraph_json(data) if do_simplification: G = util.simplify_network(G) print("Network has {} nodes and {} edges. Clustering coefficient is {}.". format( sum(1 for _ in G.nodes()), sum(1 for _ in G.edges()), nx.average_clustering( util.to_simple_edge_network(G).to_undirected( reciprocal=False)))) fig, ax = ox.plot_graph(G, edge_linewidth=2) if save_render:
def geo_address(address): return ox.geocode(address)
def generate_route(start_address, end_address): # read in api key api_file = open("api_key.txt", "r") api_key = api_file.read() api_file.close() url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&" # get distance google maps finds for path res = requests.get(url + "origins=" + start_address + "&destinations=" + end_address + "&key=" + api_key) google_dist = res.json()['rows'][0]['elements'][0]['distance']['value'] start_geocode = ox.geocode(start_address) end_geocode = ox.geocode(end_address) # get bounding box coordinates N, S, E, W = calc_box_points(start_geocode, end_geocode) print(f"\n{Fore.BLUE}Creating osm graph...{Style.RESET_ALL}") # generate multi digraph from osm data start = time.time() osm_graph = ox.graph_from_bbox(north=N, south=S, east=E, west=W, truncate_by_edge=True) end = time.time() print( f"{Fore.GREEN}Osm graph created in {round(end - start, 2)} seconds!{Style.RESET_ALL}\n" ) # get nodes from osm_graph nodes, _ = ox.graph_to_gdfs(osm_graph) # convert nodes into KDTree, uses euclidean distance by default kd_tree = KDTree(nodes[['y', 'x']]) # use tree structure to quickly find nearest node start_index = kd_tree.query([start_geocode], return_distance=False)[0] end_index = kd_tree.query([end_geocode], return_distance=False)[0] start_node = nodes.iloc[start_index].index.values[0] end_node = nodes.iloc[end_index].index.values[0] # display route on graph print(f"{Fore.BLUE}Calculating route...{Style.RESET_ALL}") start = time.time() route, distance = dijkstras(osm_graph, start_node, end_node) end = time.time() print( f"{Fore.GREEN}Route calculated in {round((end - start) * 1000, 2)} ms!{Style.RESET_ALL}" ) print() print(f"Distance: {distance}m") print(f"Google distance: {google_dist}") # calculate accuracy of pathing accuracy = 100 - abs(((distance - google_dist) / (google_dist)) * 100) if accuracy >= 90.0: print(f"{Fore.GREEN}Accuracy: {round(accuracy, 2)}% {Style.RESET_ALL}") else: print(f"{Fore.RED}Accuracy: {round(accuracy, 2)}% {Style.RESET_ALL}") print() # overlay route onto map and set icons to show start and end route_map = ox.plot_route_folium(osm_graph, route) folium.Marker(location=start_geocode, icon=folium.Icon(color='red')).add_to(route_map) folium.Marker(location=end_geocode, icon=folium.Icon(color='green')).add_to(route_map) route_map.save('templates/route.html')
def plot( # Address query, # Figure parameters figsize=(10, 10), ax=None, title=None, # Whether to plot a circle centered around the address; circle params circle=False, radius=1000, streets_radius=1000, # Street params dilate_streets=5, draw_streets=True, # Color params background_color='white', background_alpha=1., palette=None, perimeter_lw=1, perimeter_ec='black', water_ec='black', land_ec='black', buildings_ec='black', # Which layers to plot layers=['perimeter', 'landuse', 'water', 'building', 'streets'], # Layer ordering params zorder_perimeter=None, zorder_landuse=None, zorder_water=None, zorder_streets=None, zorder_building=None, # Whether to fetch data using OSM Id by_osmid=False, by_coordinates=False, ): ############# ### Fetch ### ############# # Geocode central point if by_coordinates: point = (float(query.split(",")[0].strip()), float(query.split(",")[1].strip())) elif not by_osmid: point = ox.geocode(query) # Fetch perimeter perimeter = get_perimeter(query, by_osmid=by_osmid) if not circle else None # Fetch buildings, land, water, streets layers_dict = {} for layer in layers: if layer == 'perimeter': pass elif layer == 'streets': layers_dict[layer], _ = get_streets(**({ 'point': point, 'radius': streets_radius } if circle else { 'perimeter': perimeter }), dilate=dilate_streets) else: layers_dict[layer], perimeter_ = get_footprints(**({ 'point': point, 'radius': radius } if circle else { 'perimeter': perimeter }), footprint=layer) # Project perimeter if 'perimeter' in layers: layers_dict['perimeter'] = perimeter_ if circle else union( ox.project_gdf(perimeter).geometry) ############ ### Plot ### ############ if ax is None: # if ax is none, create figure fig, ax = plt.subplots(figsize=figsize) # Ajust axis ax.axis('off') ax.axis('equal') ax.autoscale() # Setup parameters for drawing layers layer_kwargs = { 'perimeter': { 'lw': perimeter_lw, 'ec': perimeter_ec, 'fc': background_color, 'alpha': background_alpha, 'zorder': zorder_perimeter }, 'landuse': { 'ec': land_ec, 'fc': '#53bd53', 'zorder': zorder_landuse }, 'water': { 'ec': water_ec, 'fc': '#a1e3ff', 'zorder': zorder_water }, 'streets': { 'fc': '#f5da9f', 'zorder': zorder_streets }, 'building': { 'ec': buildings_ec, 'palette': palette, 'zorder': zorder_building }, } # Draw layers for layer in ['perimeter', 'landuse', 'water', 'streets', 'building']: if layer in layers_dict: plot_shapes(layers_dict[layer], ax, **layer_kwargs[layer]) # Return perimeter return layers_dict['perimeter']
def plotShortestWalkBus(startLocation, endLocation): startTime = time.time() startLocation = ox.geocode(startLocation) endLocation = ox.geocode(endLocation) startLocation = (str(startLocation[0]), str(startLocation[1])) endLocation = (str(endLocation[0]), str(endLocation[1])) api = overpy.Overpass() punggol = (1.4041070, 103.9025242) distance = 3000 W = ox.graph_from_point(punggol, distance=distance, network_type='walk') D = ox.graph_from_point(punggol, distance=distance, network_type='drive_service') startBusStopNode = None endBusStopNode = None radius = 100 # Find busstop to walk to, retrieve its busstopCode, latlon while (startBusStopNode == None): startBusStopNode = api.query( "node(around:" + str(radius) + "," + startLocation[0] + "," + startLocation[ 1] + ")[highway=bus_stop];out;") if len(startBusStopNode.nodes) > 0: startBusStopNode = startBusStopNode.nodes[0] startBusStopLatLon = (startBusStopNode.lat, startBusStopNode.lon) startBusStopCode = startBusStopNode.tags['asset_ref'] else: startBusStopNode = None radius += 50 # Find path of INITIAL WALK to BUS STOP try: initialWalkToBusStop = plotShortestWalkRoute.plotWalk(startLocation, startBusStopLatLon) except: print("Cannot find walk route.") # Find destination busstop, retrieve its busStopCode, latlon while (endBusStopNode == None): endBusStopNode = api.query( "node(around:" + str(radius) + "," + endLocation[0] + "," + endLocation[ 1] + ")[highway=bus_stop];out;") if len(endBusStopNode.nodes) > 0: endBusStopNode = endBusStopNode.nodes[0] endBusStopLatLon = (endBusStopNode.lat, endBusStopNode.lon) endBusStopCode = endBusStopNode.tags['asset_ref'] else: endBusStopNode = None radius += 50 # Find path of FINAL WALK from BUS STOP to DESTINATION try: finalWalkFromBusStopToDestination = plotShortestWalkRoute.plotWalk(endBusStopLatLon, endLocation) except: print("Cannot find walk route.") # Find path of BUS ROUTE try: paths = findShortestBusRoute.findShortestBusRoute(int(startBusStopCode), int(endBusStopCode)) busRouteToPlot = plotShortestBusRoute.findPath(paths) forPlotNode = busRouteToPlot[1] busRouteToPlot = busRouteToPlot[0] except: print("Cannot find bus route. Missing Map Data") # Convert Path(List of Nodes) to Path(List of coords) to draw PolyLines try: initialWalkToBusStop = convertRoute(ox.plot.node_list_to_coordinate_lines(W, initialWalkToBusStop)) busRouteToPlot = convertRoute(ox.plot.node_list_to_coordinate_lines(D, busRouteToPlot)) finalWalkFromBusStopToDestination = convertRoute( ox.plot.node_list_to_coordinate_lines(W, finalWalkFromBusStopToDestination)) except: print("Unable to find route. Missing Map Data") plotTime = time.time() # Plot Final Graph m = folium.Map(location=punggol, distance=distance, zoom_start=15) if len(initialWalkToBusStop) > 0: folium.PolyLine(initialWalkToBusStop, color="green", weight=4, opacity=1).add_to(m) folium.PolyLine(busRouteToPlot, color="blue", weight=4, opacity=1).add_to(m) if len(finalWalkFromBusStopToDestination) > 0: folium.PolyLine(finalWalkFromBusStopToDestination, color="green", weight=4, opacity=1).add_to(m) # For creating the Markers on the map with: BUS STOP DATA, BUS SERVICES TO TAKE AT THAT STOP, BUSSTOP NAME with open('../../bus_data/all_bus_stops.json') as bus_stop: data = json.load(bus_stop) count = 0 counter2 = 0 tupleOfPairs = [] tupleProcessed = [] busServices = [] for i in range(len(paths) - 1): tupleOfPairs.append((paths[i], paths[i + 1])) df = pd.read_csv("../../bus_data/Bus_Edge_Direction_1.csv", usecols=['BusStop A', 'BusStop B', 'Service(s)']) for x in df.values: if math.isnan(x[0]): pass else: for i in tupleOfPairs: if i[0] == x[0] and i[1] == x[1]: tupleProcessed.append((x[0], x[1], x[2])) break # To get bus services for i in paths: busServices.append([]) for z in tupleProcessed: if i in z: busServices[counter2].extend(z[2].split(',')) counter2 = counter2 + 1 for i in range(len(busServices)): busServices[i] = plotShortestBusRoute.removeDupes(busServices[i]) # Get long and lat of all the individual busstops/nodes nodesLatLongs = [] for i in range(len(forPlotNode)): nodesLatLongs.append((forPlotNode[i][0][0], forPlotNode[i][0][1])) nodesLatLongs.append((forPlotNode[-1][1][0], forPlotNode[-1][1][1])) # Create the node with the datas for i in nodesLatLongs: for z in data['value']: if int(z['BusStopCode']) == paths[count]: folium.Marker(location=[i[0], i[1]], popup=folium.Popup (("<div>" + z['Description'] + "</div>" + "Buses: " + str(busServices[count]).strip( "[]").replace("'", '')), max_width=450), icon=folium.Icon(color='red', icon='bus', prefix='fa')).add_to(m) count = count + 1 # Add Start and End Destination Markers folium.Marker(location=startLocation, icon=folium.Icon(color='green', icon='play', prefix='fa')).add_to(m) folium.Marker(location=endLocation, icon=folium.Icon(color='green', icon='stop', prefix='fa')).add_to(m) # Save as html file m.save('../templates/dijkstra_walk_bus.html') endTime = time.time() print("Plotting of Map takes: ", round(endTime - plotTime, 2)) print("Time taken: ", round(endTime - startTime, 2))
def index(request): try: if request.method == 'POST': retrieveForm = AddressForm(request.POST) if retrieveForm.is_valid(): # punggol, singapore org_var = retrieveForm.cleaned_data['var_org'] # blk 128B, punggol, singapore dst_var = retrieveForm.cleaned_data['var_dst'] type_var = retrieveForm.cleaned_data['var_type'] geolocator = Nominatim(user_agent="test") org_addr = geolocator.geocode(org_var) dst_addr = geolocator.geocode(dst_var) org = (org_addr.latitude, org_addr.longitude) dest = (dst_addr.latitude, dst_addr.longitude) if type_var == 'Bus': graph = ox.graph_from_file(JSON_FOLDER + "punggol.osm", bidirectional=True, simplify=True, retain_all=False) start = ox.geocode(org_var) end = ox.geocode(dst_var) print("Found a starting node", start) print("Found a ending node", end) start_node = ox.get_nearest_node(graph, start) end_node = ox.get_nearest_node(graph, end) nodes, edges = ox.graph_to_gdfs(graph) # TO CREATE BUS ROUTING pathcheck = bus(busGraph, graph, start, end, start_node, end_node) # IF BUS ROUTE IS AVAILABLE if pathcheck[1] == 0: startStopCoords = pathcheck[2] endStopCoords = pathcheck[3] print(startStopCoords) print(endStopCoords) start_Bus = ox.get_nearest_node(graph, startStopCoords) end_Bus = ox.get_nearest_node(graph, endStopCoords) pathToBusstop = astar_path(graph, start_node, start_Bus) pathFromBusstop = astar_path(graph, end_Bus, end_node) latlontobus = [] latlonfrombus = [] # walk from start to bus start startbuscoord = (graph.nodes[start_Bus]['y'], graph.nodes[start_Bus]['x']) prev = None splice = None ptr = 0 temp = float("Infinity") for item in pathToBusstop: if prev is None: prev = item else: try: line = graph[prev][item][0]["geometry"] for point in list(line.coords): if splice is None: splice = ptr temp = geopy.distance.distance( startbuscoord, (point[1], point[0])).km elif geopy.distance.distance( startbuscoord, (point[1], point[0])).km < temp: splice = ptr temp = geopy.distance.distance( startbuscoord, (point[1], point[0])).km latlontobus.append( (point[1], point[0])) ptr += 1 except: pass finally: prev = item latlontobus = latlontobus[:splice + 1] # walk for bus end to dst endbuscoord = (graph.nodes[end_Bus]['y'], graph.nodes[end_Bus]['x']) prev = None splice = None ptr = 0 temp = float("Infinity") for item in pathFromBusstop: if prev is None: prev = item else: try: line = graph[prev][item][0]["geometry"] for point in list(line.coords): if splice is None: splice = ptr temp = geopy.distance.distance( endbuscoord, (point[1], point[0])).km elif geopy.distance.distance( endbuscoord, (point[1], point[0])).km < temp: splice = ptr temp = geopy.distance.distance( endbuscoord, (point[1], point[0])).km latlonfrombus.append( (point[1], point[0])) ptr += 1 except: pass finally: prev = item latlonfrombus = latlonfrombus[:splice + 1] path = pathcheck[0] indexing = 0 line = [] prevService = None prevIndex = None i = 0 markers = [] routing = None while i < len(path): stopCode, service = path[i] # in the case of first stop, no bus service stated, take next if service is None: service = path[i + 1][1] if service != prevService: indexing = 0 prevIndex = 0 qlat = bus_stop_code_map[stopCode]["Latitude"] qlon = bus_stop_code_map[stopCode]["Longitude"] # get routes for respective direction if service[1] == 1: routing = busRoute0[service[0]]["coordinates"] else: routing = busRoute1[service[0]]["coordinates"] while indexing < len(routing): clon, clat = routing[indexing] u = (qlat, qlon) v = (clat, clon) # stop found in range of 30 meters, latlong accuracy difference from # two sources if geopy.distance.distance(u, v).km < 0.03: # first bus stop if prevService is None: line.append(v) else: if prevService == service: print("ALWAYS COME HERE?", prevIndex, indexing) for x, y in routing[ prevIndex:indexing + 1]: line.append((y, x)) else: print( "ENTER ELSE ---------------------------------" ) prevLatLong = line[-1] tempIndex = 0 while tempIndex < len(routing): plon, plat = routing[tempIndex] p = (plat, plon) if geopy.distance.distance( prevLatLong, p).km < 0.03: for x, y in routing[ tempIndex: indexing + 1]: line.append((y, x)) break tempIndex += 1 prevIndex = indexing prevService = service markers.append((v, stopCode)) break indexing += 1 i += 1 # TO CREATE ROUTING WITH BUS nodepath = astar_path(graph, start_node, end_node) m = ox.plot_route_folium(graph, nodepath, tiles='openstreetmap', route_color='green', route_opacity=0) folium.Marker(location=(start[0], start[1]), popup='START', icon=folium.Icon(color='red', icon='flag')).add_to(m) folium.Marker(location=(end[0], end[1]), popup='END', icon=folium.Icon(color='blue', icon='flag')).add_to(m) for loc, code in markers: folium.Marker(location=loc, popup='Bus stop number:' + str(code), icon=folium.Icon( color='green', icon='bus', prefix='fa')).add_to(m) folium.PolyLine(line, color="red", weight=2.5, opacity=1).add_to(m) # start point to start busstop folium.PolyLine([start, latlontobus[0]], color="blue", weight=2.5, opacity=1, dasharray="4").add_to(m) folium.PolyLine(latlontobus, color="green", weight=2.5, opacity=1).add_to(m) folium.PolyLine([latlontobus[-1], line[0]], color="blue", weight=2.5, opacity=1, dasharray="4").add_to(m) # End bus stop to end point folium.PolyLine([line[-1], latlonfrombus[0]], color="blue", weight=2.5, opacity=1, dasharray="4").add_to(m) folium.PolyLine(latlonfrombus, color="green", weight=2.5, opacity=1, dasharray="4").add_to(m) folium.PolyLine([latlonfrombus[-1], end], color="blue", weight=2.5, opacity=1, dasharray="4").add_to(m) m.save(ROUTE_FOLDER + 'bus_routing.html') # IF BUS ROUTE NOT FOUND, RUN WALK ROUTE if pathcheck[1] == 1: nodepath = pathcheck[0] m = ox.plot_route_folium(graph, nodepath, tiles='openstreetmap', route_color='green') folium.Marker(location=(start[0], start[1]), popup='START', icon=folium.Icon(color='red', icon='flag')).add_to(m) folium.Marker(location=(end[0], end[1]), popup='END', icon=folium.Icon(color='blue', icon='flag')).add_to(m) m.save(ROUTE_FOLDER + 'bus_routing.html') print("bus_routing.html created!") speedBus = 40 stopsBus = getStops() distanceBus = round(getDistance(), 3) timeBus = math.ceil((getDistance() / speedBus) * 60) timeBus = timeBus + stopsBus if distanceBus <= 3.2: costBus = 0.92 elif distanceBus <= 4.2: costBus = 1.02 elif distanceBus <= 5.2: costBus = 1.12 elif distanceBus <= 6.2: costBus = 1.22 elif distanceBus <= 7.2: costBus = 1.31 elif distanceBus <= 8.2: costBus = 1.38 elif distanceBus <= 9.2: costBus = 1.44 else: costBus = 2 busRoute = getBus().split(',') contentDict = { "org_addr": org_addr.address, "dst_addr": dst_addr.address, "mode_var": type_var, "distance": distanceBus, "stops": getStops(), "bus": busRoute, "time": timeBus, "cost": costBus } return render(request, "bus.html", contentDict) elif type_var == 'LRT': print("Loading OSM") graph = ox.graph_from_file(JSON_FOLDER + "punggol.osm", bidirectional=True, simplify=True, retain_all=False) start = ox.geocode(org_var) end = ox.geocode(dst_var) print("Found a starting node", start) print("Found a ending node", end) start_node = ox.get_nearest_node(graph, start) end_node = ox.get_nearest_node(graph, end) nodes, edges = ox.graph_to_gdfs(graph) # TO CREATE ROUTE TO AND FROM LRT path_to_Lrt = findNearestLrt(graph, start, end, start_node, end_node) # LRT ROUTING lrtline = [] lrtMarkers = [] if path_to_Lrt is not None: # if LRT path is found if path_to_Lrt[1] == 0: pathDict = path_to_Lrt[0] for path in pathDict: indexing = 0 prevService = None prevIndex = None i = 0 for item in path: direction = item[0][4] stationName = item[0][1] loop = item[0][-1] if direction == 1: print("D 1 \n") routing = LrtRoute0[loop]["coordinates"] else: print("D 2 \n") routing = LrtRoute1[loop]["coordinates"] while i < len(path[item]): qlat = path[item][i][2] qlon = path[item][i][3] while indexing < len(routing): clon, clat = routing[indexing] u = (qlat, qlon) v = (clat, clon) if geopy.distance.distance( u, v).km < 0.03: if prevService is None: lrtline.append(v) else: prevLatLong = lrtline[-1] tempIndex = 0 while tempIndex < len(routing): plon, plat = routing[ tempIndex] p = (plat, plon) if geopy.distance.distance( prevLatLong, p).km < 0.01: for x, y in routing[ tempIndex: indexing + 1]: lrtline.append( (y, x)) break tempIndex += 1 prevIndex = indexing prevService = path[item] lrtMarkers.append( (v, path[item][i][1], path[item][i][-1], path[item][i][-2])) break indexing += 1 i += 1 nearestStartStop = path_to_Lrt[2] nearestEndStop = path_to_Lrt[3] start_Lrt = ox.get_nearest_node( graph, nearestStartStop) end_Lrt = ox.get_nearest_node( graph, nearestEndStop) pathToLrtStop = astar_path(graph, start_node, start_Lrt) pathFromLrtStop = astar_path( graph, end_Lrt, end_node) latlontolrt = [] latlonfromlrt = [] # walk from start to lrt start startlrtcoord = (graph.nodes[start_Lrt]['y'], graph.nodes[start_Lrt]['x']) prev = None splice = None ptr = 0 temp = float("Infinity") for item in pathToLrtStop: if prev is None: prev = item else: try: line = graph[prev][item][0]["geometry"] for point in list(line.coords): if splice is None: splice = ptr temp = geopy.distance.distance( startlrtcoord, (point[1], point[0])).km elif geopy.distance.distance( startlrtcoord, (point[1], point[0])).km < temp: splice = ptr temp = geopy.distance.distance( startlrtcoord, (point[1], point[0])).km latlontolrt.append( (point[1], point[0])) ptr += 1 except: pass finally: prev = item if splice is not None: latlontolrt = latlontolrt[:splice + 1] # walk from lrt end to end endlrtcoord = (graph.nodes[end_Lrt]['y'], graph.nodes[end_Lrt]['x']) prev = None splice = None ptr = 0 temp = float("Infinity") for item in pathFromLrtStop: if prev is None: prev = item else: try: line = graph[prev][item][0]["geometry"] for point in list(line.coords): if splice is None: splice = ptr temp = geopy.distance.distance( endlrtcoord, (point[1], point[0])).km elif geopy.distance.distance( endlrtcoord, (point[1], point[0])).km < temp: splice = ptr temp = geopy.distance.distance( endlrtcoord, (point[1], point[0])).km latlonfromlrt.append( (point[1], point[0])) ptr += 1 except: pass finally: prev = item if splice is not None: latlonfromlrt = latlonfromlrt[:splice + 1] else: print("LRT route unable to be established") # default route nodepath = astar_path(graph, start_node, end_node) if path_to_Lrt[1] == 0: # INIT m = ox.plot_route_folium(graph, nodepath, tiles='openstreetmap', route_color='green', route_opacity=0) # LRT LINE folium.PolyLine(lrtline, color="black", weight=2.5, opacity=1).add_to(m) # Variables for Display strStation = '' stationCount = 0 # LRT Markers for loc, station, loop, direction in lrtMarkers: folium.Marker( location=loc, popup='<b>Station Name:</b> ' + str(station) + '<br><b>Lat:</b> ' + str(loc[0]) + '<br><b>Lon:</b> ' + str(loc[1]) + '<br><b>Loop:</b> ' + str(loop) + '<br><b>Direction: </b>' + str(direction), icon=folium.Icon(color='black', icon='train', prefix='fa')).add_to(m) strStation = strStation + str(station) + ',' stationCount = stationCount + 1 strStation = strStation + 'End' # START AND END MARKERS folium.Marker(location=(start[0], start[1]), popup='START', icon=folium.Icon(color='red', icon='flag')).add_to(m) folium.Marker(location=(end[0], end[1]), popup='END', icon=folium.Icon(color='blue', icon='flag')).add_to(m) if len(latlontolrt) > 0: # start point to start lRT folium.PolyLine([start, latlontolrt[0]], color="blue", weight=2.5, opacity=1, dasharray="4").add_to(m) folium.PolyLine(latlontolrt, color="green", weight=2.5, opacity=1).add_to(m) folium.PolyLine([latlontolrt[-1], lrtline[0]], color="blue", weight=2.5, opacity=1, dasharray="4").add_to(m) if len(latlonfromlrt) > 0: # End LRT stop to end point folium.PolyLine([lrtline[-1], latlonfromlrt[0]], color="blue", weight=2.5, opacity=1, dasharray="4").add_to(m) folium.PolyLine(latlonfromlrt, color="green", weight=2.5, opacity=1, dasharray="4").add_to(m) folium.PolyLine([latlonfromlrt[-1], end], color="blue", weight=2.5, opacity=1, dasharray="4").add_to(m) m.save(ROUTE_FOLDER + 'lrt_routing.html') print("LRT_Routing.html created!") # IF LRT ROUTE NOT FOUND, RUN WALK ROUTE if path_to_Lrt[1] == 1: # INIT m = ox.plot_route_folium(graph, nodepath, tiles='openstreetmap', route_color='green') folium.Marker(location=(start[0], start[1]), popup='START', icon=folium.Icon(color='red', icon='flag')).add_to(m) folium.Marker(location=(end[0], end[1]), popup='END', icon=folium.Icon(color='blue', icon='flag')).add_to(m) m.save(ROUTE_FOLDER + 'lrt_routing.html') print("LRT_Routing.html created!") strStation = strStation.split(',') timeTrain = 2 * stationCount if getDistanceLRT() <= 3.2: costLRT = 0.92 elif getDistanceLRT() <= 4.2: costLRT = 1.02 elif getDistanceLRT() <= 5.2: costLRT = 1.12 elif getDistanceLRT() <= 6.2: costLRT = 1.22 elif getDistanceLRT() <= 7.2: costLRT = 1.31 elif getDistanceLRT() <= 8.2: costLRT = 1.38 elif getDistanceLRT() <= 9.2: costLRT = 1.44 else: costLRT = 2 contentDict = { "org_addr": org_addr.address, "dst_addr": dst_addr.address, "mode_var": type_var, "count": stationCount, "route": strStation, "time": timeTrain, "cost": costLRT } return render(request, "lrt.html", contentDict) else: if type_var == 'Walk': if org: graph = ox.graph_from_point(org, distance=2000, network_type='walk') else: (graph, org) = ox.graph_from_address(address, distance=5000, network_type='walk', return_coords=True) elif type_var == 'Drive': if org: graph = ox.graph_from_point(org, distance=2000, network_type='drive') else: graph = ox.graph_from_address(address, distance=5000, network_type='drive') # get cloest node to the point of search global target_node orig_node = ox.get_nearest_node(graph, org) target_node = ox.get_nearest_node(graph, dest) nodes, edges = ox.graph_to_gdfs(graph) node_data = get_nodes(edges) ourRoute3 = list( creator3(nodes, node_data, orig_node, target_node)) # usage of folium to create interactive web map astar_map = ox.plot_route_folium(graph, ourRoute3, popup_attribute='name', tiles='openstreetmap', route_color='blue') folium.Marker( location=org, popup=org_addr.address, icon=folium.Icon(color='red')).add_to(astar_map) folium.Marker( location=dest, popup=dst_addr.address, icon=folium.Icon(color='blue')).add_to(astar_map) filepath3 = ROUTE_FOLDER + 'astar_route.html' astar_map.save(filepath3) distanceAstar = round( getDistanceTravelled(nodes, node_data, ourRoute3), 3) if type_var == 'Walk': estSpeed = 5 else: estSpeed = 50 timeAstar = math.ceil((distanceAstar / estSpeed) * 60) contentDict = { "org_addr": org_addr.address, "dst_addr": dst_addr.address, "dist_astar": distanceAstar, "mode_var": type_var, "time": timeAstar, "estSpeed": estSpeed } return render(request, "main.html", contentDict) else: inputForm = AddressForm() return render(request, "index.html", {'form': inputForm}) except: inputForm = AddressForm() return render(request, "error.html", {'form': inputForm})
# -*- coding: utf-8 -*- """ Created on Wed Jan 15 10:52:52 2020 @author: niall This is a function that can be run to test whether the toold needed to run SafeRoute are accessable. The local path in 'custom_func.py' must be edited """ #import pandas as pd ##from datetime import datetime as dt #from darksky import forecast #import pickle #from datetime import datetime as dt import osmnx as ox import custom_funcs as CF input1 = '253 merton street, toronto' input2 = '22 epsom avenue, toronto' origin = list(ox.geocode(input1)) destination = list(ox.geocode(input2)) filename_out = 'custom_functions_test_output' current_weather = CF.get_current_weather_toronto() # add the weather data to the unique roads roads_with_weather = CF.add_current_weather_to_unique_roads(current_weather) # run the unique roads through the classifier and save locally roads_with_weather = CF.get_collision_probs(roads_with_weather) # save the graph as the name used by the return statement below CF.plot_map_with_probs_routes(roads_with_weather, origin, destination, filename=filename_out)
dist1 = 100000 G = create_graph(loc= loc1, dist= dist1, transport_mode= transport_mode1, ) # fig, ax = ox.plot_graph(G); # plt.tight_layout() # Create nodes geodataframe from Graph network (G) gdf_nodes = ox.graph_to_gdfs(G, edges=False) user_point = ox.geocode(loc1) # Specify where you want to start and get nearest nodes. point_of_interest = ox.get_nearest_node(G, point=user_point) # Project a graph from lat-long to the UTM zone appropriate for its geographic location. G = ox.project_graph(G) # Trip time in Minutes trip_times = [5, 15, 25, 40, 60] # add an edge attribute for time in minutes required to traverse each edge meters_per_minute = travel_speed * 1000 / 60 #km per hour to m per minute for u, v, k, data in G.edges(data=True, keys=True): data['time'] = data['length'] / meters_per_minute
# In[2]: umass = (42.38, -72.52) G = ox.graph_from_point(umass, distance=1000) # quick pflot ox.plot_graph(G, fig_height=10, fig_width=10, edge_color='black') # In[3]: route = nx.shortest_path(G, np.random.choice(G.nodes), np.random.choice(G.nodes)) ox.plot_graph_route(G, route, fig_height=10, fig_width=10) # In[11]: library = ox.geocode('154 Hicks Way, Amherst, MA 01003') dining = ox.geocode('141 Southwest Cir, Amherst, MA 01003') # In[12]: fig, ax = ox.plot_graph(G, fig_height=10, fig_width=10, show=False, close=False, edge_color='black') ax.scatter(library[1], library[0], c='red', s=100) ax.scatter(dining[1], dining[0], c='blue', s=100) plt.show() # In[13]:
######################################## # Folium HTML generator ######################################## import osmnx as ox import folium # ask user for a location location = input("Hello. What city do you want to go to? ") try: # get the lat/lon by geocoding the location latlon = ox.geocode(location) # create a folium map m = folium.Map(location=[latlon[0], latlon[1]]) # save it as an html file m.save(location + '.html') # leave a message print('Bon voyage! Look for your travel file "' + location + '.html"') except: print('Could not geocode your location')
for k in mrtNodeList: # check for nodes which are stations try: if "PE" in k.get('ref'): pe.append(k.get('osmid')) if "PW" in k.get('ref'): pw.append(k.get('osmid')) except: # to catch and skip noneType iterations continue # testing algorithmn speed start_time = time.time() # user input (GUI TEAM, user input in text area will be stored here) src = "Block 130, Edgedale Plains, Punggol" # 406B, Northshore Drive, Punggol - Nibong, Punggol # punggol will return punggol mrt coordinates 406B, Northshore Drive, Punggol - 220A Sumang Lane, Singapore 821220 - Blk 126A, Punggol Field, Punggol - Waterway Cascadia, 314A, Punggol Way, Punggol des = "406B, Northshore Drive, Punggol" # random hdb 60 Punggol East, Singapore 828825 startpoint = ox.geocode(src) endpoint = ox.geocode(des) # finding nearest nodes required strtpt = ox.get_nearest_node(G_walk, startpoint, method='euclidean', return_dist=True) endpt = ox.get_nearest_node(G_walk, endpoint, method='euclidean', return_dist=True) # locateStrtLrt and lcoateEndLrt is only used to locate the location of both mrt locateStrtLrt = ox.get_nearest_node(G_lrt, startpoint,
def plotShortestWalkBus(W, D, startLocation, endLocation): startTime = time.time() # Converts address to coords startLocation = ox.geocode(startLocation) endLocation = ox.geocode(endLocation) #Convert coords to tuple of string lat and lon startLocation = (str(startLocation[0]), str(startLocation[1])) endLocation = (str(endLocation[0]), str(endLocation[1])) api = overpy.Overpass() punggol = (1.403948, 103.909048) distance = 2000 startBusStopNode = None endBusStopNode = None radius = 100 # Find busstop to walk to (starts from range 50m, increases till find a busstop) , retrieve its busstopCode, latlon # Uses overpass api # Complexity of O(n) Run n times until startBusStopNode is not none while (startBusStopNode == None): startBusStopNode = api.query( "node(around:" + str(radius) + "," + startLocation[0] + "," + startLocation[ 1] + ")[highway=bus_stop];out;") if len(startBusStopNode.nodes) > 0: startBusStopNode = startBusStopNode.nodes[0] startBusStopLatLon = (startBusStopNode.lat, startBusStopNode.lon) startBusStopCode = startBusStopNode.tags['asset_ref'] else: startBusStopNode = None radius += 50 # Find path of INITIAL WALK to BUS STOP # Complexity of should be O(n) try: initialWalkToBusStop = plotShortestWalkRoute.plotWalk(W, startLocation, startBusStopLatLon) except: print("Cannot find walk route.") radius = 100 # Find Dest busstop from final dest (starts from range 50m, increases till find a busstop) , retrieve its busstopCode, latlon # Uses overpass api # Complexity of O(n) Run n times until endBusStopNode is not none while (endBusStopNode == None): endBusStopNode = api.query( "node(around:" + str(radius) + "," + endLocation[0] + "," + endLocation[ 1] + ")[highway=bus_stop];out;") if len(endBusStopNode.nodes) > 0: endBusStopNode = endBusStopNode.nodes[0] endBusStopLatLon = (endBusStopNode.lat, endBusStopNode.lon) endBusStopCode = endBusStopNode.tags['asset_ref'] else: endBusStopNode = None radius += 100 # Find path of FINAL WALK from Dest BUS STOP to DESTINATION # Complexity of should be O(n) try: finalWalkFromBusStopToDestination = plotShortestWalkRoute.plotWalk(W, endBusStopLatLon, endLocation) except: print("Cannot find walk route.") # Find path of BUS ROUTE # Complexity of O(n^2) try: paths = findShortestBusRoute.findShortestBusRoute(int(startBusStopCode), int(endBusStopCode)) busRouteToPlot = plotShortestBusRoute.findPath(D, paths) except: print("Cannot find bus route. Missing Map Data") # Convert Path(List of Nodes) to Path(List of coords) to draw PolyLines try: initialWalkToBusStop = convertRoute(ox.plot.node_list_to_coordinate_lines(W, initialWalkToBusStop)) busRouteToPlot = convertRoute(ox.plot.node_list_to_coordinate_lines(D, busRouteToPlot)) finalWalkFromBusStopToDestination = convertRoute( ox.plot.node_list_to_coordinate_lines(W, finalWalkFromBusStopToDestination)) except: print("Unable to find route. Missing Map Data") plotTime = time.time() # Plot Final Graph m = folium.Map(location=punggol, distance=distance, zoom_start=15) # Don't plot if no path if len(initialWalkToBusStop) > 0: folium.PolyLine(initialWalkToBusStop, color="blue", weight=4, opacity=1).add_to(m) folium.PolyLine(busRouteToPlot, color="purple", weight=4, opacity=1).add_to(m) # Don't plot if no path if len(finalWalkFromBusStopToDestination) > 0: folium.PolyLine(finalWalkFromBusStopToDestination, color="blue", weight=4, opacity=1).add_to(m) # For creating the Markers on the map with: BUS STOP DATA, BUS SERVICES TO TAKE AT THAT STOP, BUSSTOP NAME with open('data/all_bus_stops.json') as bus_stop: data = json.load(bus_stop) count = 0 counter2 = 0 tupleOfPairs = [] tupleProcessed = [] busServices = [] # Complexity of O(n) n number of paths-1 for i in range(len(paths) - 1): tupleOfPairs.append((paths[i], paths[i + 1])) df = pd.read_csv("data/Bus_Edge_Direction_1.csv", usecols=['BusStop A', 'BusStop B', 'Service(s)']) # Complexity of O(n) number of values in direction csv file for x in df.values: if math.isnan(x[0]): pass else: for i in tupleOfPairs: if i[0] == x[0] and i[1] == x[1]: tupleProcessed.append((x[0], x[1], x[2])) break # To get bus services # Complexity of O(n^2) n number of paths, n number of values in tupleProcessed for i in paths: busServices.append([]) for z in tupleProcessed: if i in z: busServices[counter2].extend(z[2].split(',')) counter2 = counter2 + 1 # Complexity of O(n) n number of bus services for i in range(len(busServices)): busServices[i] = plotShortestBusRoute.removeDupes(busServices[i]) # Create the marker nodes with the bus services to visualize on map # Complexity of O(n) number of paths for i in paths: for z in data['value']: if int(z['BusStopCode']) == paths[count]: folium.Marker(location=[z['Latitude'], z['Longitude']], popup=folium.Popup (("<div>" + z['Description'] + "</div>" + "Buses: " + str(busServices[count]).strip( "[]").replace("'", '')), max_width=450), icon=folium.Icon(color='green', icon='bus', prefix='fa')).add_to(m) count = count + 1 # Add Start and End Destination Markers folium.Marker(location=startLocation, icon=folium.Icon(color='red', icon='record')).add_to(m) folium.Marker(location=endLocation, icon=folium.Icon(color='red', icon='record')).add_to(m) # Save as html file m.save('templates/default.html') endTime = time.time() totalTime = ["Total calculation time: {first} seconds.".format(first=round(endTime - startTime, 2)), "Plotting of Map takes: {second}.".format(second=round(endTime - plotTime, 2)), "Time taken: {third}".format(third=round(endTime - startTime, 2))] totalTime.append("Click each node for bus information") return totalTime
# quick plot ox.plot_graph(G, fig_height=10, fig_width=10, edge_color='black') # In[28]: route = nx.shortest_path(G, np.random.choice(G.nodes), np.random.choice(G.nodes)) ox.plot_graph_route(G, route, fig_height=10, fig_width=10) # In[29]: library = ox.geocode('154 Hicks Way, Amherst, MA 01003') museum = ox.geocode('141 Southwest Cir, Amherst, MA 01003') # In[30]: fig, ax = ox.plot_graph(G, fig_height=10, fig_width=10, show=False, close=False, edge_color='black') ax.scatter(library[1], library[0], c='red', s=100) ax.scatter(museum[1], museum[0], c='blue',s=100) plt.show() # In[31]:
def nearest_node_to_address(self): ll = ox.geocode(self.address) begin_lat, begin_lon = ll[0], ll[1] return ox.get_nearest_node(self.G, (begin_lat, begin_lon))
def generate(self): # main code punggol = (1.403948, 103.909048) distance = 2000 api = overpy.Overpass() pe = [] pw = [] for k in self.mrtNodeList: # check for nodes which are stations try: if "PE" in k.get('ref'): pe.append(k.get('osmid')) if "PW" in k.get('ref'): pw.append(k.get('osmid')) except: # to catch and skip noneType iterations continue # testing algorithmn speed start_time = time.time() # user input (GUI TEAM, user input in text area will be stored here) # src = "Block 130, Edgedale Plains, Punggol" # 406B, Northshore Drive, Punggol - Nibong, Punggol # punggol will return punggol mrt coordinates 406B, Northshore Drive, Punggol - 220A Sumang Lane, Singapore 821220 - Blk 126A, Punggol Field, Punggol - Waterway Cascadia, 314A, Punggol Way, Punggol # des = "406B, Northshore Drive, Punggol" # random hdb 60 Punggol East, Singapore 828825 startpoint = ox.geocode(self.src) endpoint = ox.geocode(self.des) # finding nearest nodes required strtpt = ox.get_nearest_node(self.G_walk, startpoint, method='euclidean', return_dist=True) endpt = ox.get_nearest_node(self.G_walk, endpoint, method='euclidean', return_dist=True) # locateStrtLrt and lcoateEndLrt is only used to locate the location of both mrt locateStrtLrt = ox.get_nearest_node(self.G_lrt, startpoint, method='euclidean', return_dist=True) lcoateEndLrt = ox.get_nearest_node(self.G_lrt, endpoint, method='euclidean', return_dist=True) lrtstart = self.lrt_nearnode(locateStrtLrt[0])[1] lrtend = self.lrt_nearnode(lcoateEndLrt[0])[1] if (lrtstart == lrtend or (lrtstart == 6587709456 and lrtend == 6587709457) or (lrtstart == 6587709457 and lrtend == 6587709456) ): # and (start point bus stop node is same as end point): final = self.walk_astar(strtpt[0], endpt[0]) # plotting map to folium final[0] = self.convertRoute( ox.plot.node_list_to_coordinate_lines(self.G_walk, final[0])) m = folium.Map(location=punggol, distance=distance, zoom_start=15, tiles="OpenStreetMap") folium.Marker(startpoint, popup="start", icon=folium.Icon(color='red', icon='record')).add_to(m) folium.Marker(endpoint, popup="end", icon=folium.Icon(color='red', icon='record')).add_to(m) folium.PolyLine( ([startpoint] + final[0] + [endpoint]), color="blue", weight=2, opacity=1, tooltip= "There is no LRT to bring you to your destination, please walk." ).add_to(m) m.save('templates/default.html') else: reachLRT = ox.get_nearest_node(self.G_walk, self.mrtn_latlon(lrtstart), method='euclidean', return_dist=True) leaveLRT = ox.get_nearest_node(self.G_walk, self.mrtn_latlon(lrtend), method='euclidean', return_dist=True) eastlrt = 0 westlrt = 0 for i in self.mrtNodeList: mrtid = i.get('osmid') if mrtid == lrtstart and lrtstart in pe: eastlrt += 1 # print("scenario1") elif mrtid == lrtstart and lrtstart in pw: # print("scenario2") westlrt += 1 elif mrtid == lrtend and lrtend in pe: # print("scenario3") eastlrt += 1 elif mrtid == lrtend and lrtend in pw: # print("scenario4") westlrt += 1 elif westlrt == 2 or eastlrt == 2: # both lrt station in the same lrt loop break elif westlrt == 1 and eastlrt == 1: # both lrt station in different lrt loop # print("break") break m = folium.Map(location=punggol, distance=distance, zoom_start=15, tiles="OpenStreetMap") folium.Marker(startpoint, popup="start", icon=folium.Icon(color='red', icon='record')).add_to(m) folium.Marker(endpoint, popup="end", icon=folium.Icon(color='red', icon='record')).add_to(m) if westlrt == 1 and eastlrt == 1: # if both stations are found on both loop (west loop and east loop) if lrtstart in pw: lrtfirst = self.lrt_astar( self.lrt_nearnode(lrtstart)[1], 6587709456, "no") lrtsecond = self.lrt_astar(6587709457, self.lrt_nearnode(lrtend)[1], "yes") elif lrtstart in pe: lrtfirst = self.lrt_astar( self.lrt_nearnode(lrtstart)[1], 6587709457, "no") lrtsecond = self.lrt_astar(6587709456, self.lrt_nearnode(lrtend)[1], "yes") radius = 100 endBusStopNode = None endLRTBusStopNode = None while endBusStopNode is None: endBusStopNode = api.query("node(around:" + str(radius) + "," + str(endpoint[0]) + "," + str(endpoint[1]) + ")[highway=bus_stop];out;") if len(endBusStopNode.nodes) > 0: endBusStopNode = endBusStopNode.nodes[0] endBusStopLatLon = (endBusStopNode.lat, endBusStopNode.lon) endBusStopCode = endBusStopNode.tags['asset_ref'] else: endBusStopNode = None radius += 50 endLRTLatLon = self.mrtn_latlon(lcoateEndLrt[0]) while endLRTBusStopNode is None: endLRTBusStopNode = api.query("node(around:" + str(radius) + "," + str(endLRTLatLon[0]) + "," + str(endLRTLatLon[1]) + ")[highway=bus_stop];out;") if len(endLRTBusStopNode.nodes) > 0: endLRTBusStopNode = endLRTBusStopNode.nodes[0] endLRTBusStopLatLon = (endLRTBusStopNode.lat, endLRTBusStopNode.lon) endLRTBusStopCode = endLRTBusStopNode.tags['asset_ref'] else: endLRTBusStopNode = None radius += 50 if endBusStopNode.id == endLRTBusStopNode.id: # algo testing walk and lrt walkToStation = self.walk_astar(strtpt[0], reachLRT[0]) walkFromStation = self.walk_astar(leaveLRT[0], endpt[0]) # converting all osmnx nodes to coordinates walkToStation[0] = self.convertRoute( ox.plot.node_list_to_coordinate_lines( self.G_walk, walkToStation[0])) walkFromStation[0] = self.convertRoute( ox.plot.node_list_to_coordinate_lines( self.G_walk, walkFromStation[0])) lrtfirst[0] = self.convertRoute( ox.plot.node_list_to_coordinate_lines( self.G_lrt, lrtfirst[0])) lrtsecond[0] = self.convertRoute( ox.plot.node_list_to_coordinate_lines( self.G_lrt, lrtsecond[0])) # calculating estimated time, cost, distance to reach the destination statDist = 10300 / 14 totalDistLRT = (lrtfirst[1] + lrtsecond[1] ) / 1000 # convert to meters to km now = datetime.now() timenow = now.strftime("%H") waitTime = 0 if "10" > timenow > "6": print("--- PEAK HOUR ---") waitTime = 3 self.wlbvariable = "--- PEAK HOUR ---" else: print("--- NON-PEAK HOUR ---") waitTime = 7 self.wlbvariable = "--- NON-PEAK HOUR ---" self.lrtFareCal(totalDistLRT) # call fare function numStation = math.floor(totalDistLRT / statDist + 2) totatTimeLRT = numStation + ( (totalDistLRT * 1000) / (45000 / 60) ) + waitTime # avg mrt speed 45km/hr - 750m per minute totalDistWalk = (walkToStation[1] + walkFromStation[1] ) / 1000 # convert to meters to km estwalk = (totalDistWalk * 1000) / ( 5000 / 60) # avg walking speed 1.4m/min - 5km/hr # print("Time: " + str(round(totatTimeLRT + estwalk)) + " minutes" + "\nDistance: " + # str(round((totalDistWalk + totalDistLRT), 2)) + " km\nTransfer: 1, Punggol Station") self.wlbvariable4 = ("\nTime taken : " + str(round(totatTimeLRT + estwalk)) + " minutes") self.wlbvariable5 = ( "\nDistance travelled: " + str(round( (totalDistWalk + totalDistLRT), 2)) + " km\n") self.wlbvariable6 = ("Transfer: 1, Punggol Station") # plotting on folium map folium.PolyLine( lrtfirst[0], color="red", weight=2, opacity=1, tooltip="Change LRT at Punggol Station.").add_to(m) folium.PolyLine( lrtsecond[0], color="red", weight=2, opacity=1, tooltip="Continue here to your destination.").add_to(m) folium.PolyLine(([lrtfirst[0][-1]] + [lrtsecond[0][0]]), color="blue", weight=2, opacity=1, tooltip="Transit LRT here!").add_to(m) folium.PolyLine( ([startpoint] + walkToStation[0] + [lrtfirst[0][0]]), color="blue", weight=2, opacity=1).add_to(m) folium.PolyLine( ([lrtsecond[0][-1]] + walkFromStation[0] + [endpoint]), color="blue", weight=2, opacity=1).add_to(m) m.save('templates/default.html') else: # algo testing walk and lrt walkToStation = self.walk_astar(strtpt[0], reachLRT[0]) paths = findShortestBusRoute.findShortestBusRoute( int(endLRTBusStopCode), int(endBusStopCode)) # bus = plotShortestBusRoute.findPath(G_bus, paths) bus = plotShortestBusRoute.findPath(self.G_bus, paths) walkFromBusStop = self.walk_astar(endLRTBusStopNode.id, endpt[0]) # converting all osmnx nodes to coordinates walkToStation[0] = self.convertRoute( ox.plot.node_list_to_coordinate_lines( self.G_walk, walkToStation[0])) walkFromBusStop[0] = self.convertRoute( ox.plot.node_list_to_coordinate_lines( self.G_walk, walkFromBusStop[0])) bus[0] = self.convertRoute( ox.plot.node_list_to_coordinate_lines( self.G_bus, bus[0])) lrtfirst[0] = self.convertRoute( ox.plot.node_list_to_coordinate_lines( self.G_lrt, lrtfirst[0])) lrtsecond[0] = self.convertRoute( ox.plot.node_list_to_coordinate_lines( self.G_lrt, lrtsecond[0])) # calculating estimated time, cost, distance to reach the destination statDist = 10300 / 14 totalDistLRT = (lrtfirst[1] + lrtsecond[1] ) / 1000 # convert to meters to km now = datetime.now() timenow = now.strftime("%H") waitTime = 0 if "10" > timenow > "6": print("--- PEAK HOUR ---") waitTime = 3 self.wlbvariable = "--- PEAK HOUR ---" else: print("--- NON-PEAK HOUR ---") waitTime = 7 self.wlbvariable = "--- NON-PEAK HOUR ---" self.lrtFareCal(totalDistLRT) # call fare function numStation = math.floor(totalDistLRT / statDist + 2) totatTimeLRT = numStation + ( (totalDistLRT * 1000) / (45000 / 60) ) + waitTime # avg mrt speed 45km/hr - 750m per minute totalDistWalk = (walkToStation[1] + walkFromBusStop[1] ) / 1000 # convert to meters to km estwalk = (totalDistWalk * 1000) / ( 5000 / 60) # avg walking speed 1.4m/min - 5km/hr # print("Time: " + str(round(totatTimeLRT + estwalk)) + " minutes" + "\nDistance: " + # str(round((totalDistWalk + totalDistLRT), 2)) + " km\nTransfer: 1, Punggol Station") self.wlbvariable4 = ("\nTime taken : " + str(round(totatTimeLRT + estwalk)) + " minutes") self.wlbvariable5 = ( "\nDistance travelled: " + str(round( (totalDistWalk + totalDistLRT), 2)) + " km\n") self.wlbvariable6 = ("Transfer: 1, Punggol Station") # plotting on folium map folium.PolyLine( lrtfirst[0], color="red", weight=2, opacity=1, tooltip="Change LRT at Punggol Station.").add_to(m) folium.PolyLine( lrtsecond[0], color="red", weight=2, opacity=1, tooltip="Continue here to your destination.").add_to(m) folium.PolyLine( bus[0], color="green", weight=2, opacity=1, tooltip="Change from Lrt to Bus.").add_to(m) folium.PolyLine(([lrtfirst[0][-1]] + [lrtsecond[0][0]]), color="blue", weight=2, opacity=1, tooltip="Transit LRT here!").add_to(m) folium.PolyLine( ([startpoint] + walkToStation[0] + [lrtfirst[0][0]]), color="blue", weight=2, opacity=1, tooltip="Walk to Bus stop").add_to(m) folium.PolyLine(([lrtsecond[0][-1]] + [bus[0][0]]), color="blue", weight=2, opacity=1).add_to(m) folium.PolyLine( ([bus[0][-1]] + walkFromBusStop[0] + [endpoint]), color="blue", weight=2, opacity=1).add_to(m) m.save('templates/default.html') else: # if both stations are found on the same lrt loop # algo testing walk and lrt lrtfinal = self.lrt_astar( self.lrt_nearnode(lrtstart)[1], self.lrt_nearnode(lrtend)[1], "no") radius = 100 endBusStopNode = None endLRTBusStopNode = None while endBusStopNode is None: endBusStopNode = api.query("node(around:" + str(radius) + "," + str(endpoint[0]) + "," + str(endpoint[1]) + ")[highway=bus_stop];out;") if len(endBusStopNode.nodes) > 0: endBusStopNode = endBusStopNode.nodes[0] endBusStopLatLon = (endBusStopNode.lat, endBusStopNode.lon) endBusStopCode = endBusStopNode.tags['asset_ref'] else: endBusStopNode = None radius += 50 endLRTLatLon = self.mrtn_latlon(lcoateEndLrt[0]) radius = 100 while endLRTBusStopNode is None: endLRTBusStopNode = api.query("node(around:" + str(radius) + "," + str(endLRTLatLon[0]) + "," + str(endLRTLatLon[1]) + ")[highway=bus_stop];out;") if len(endLRTBusStopNode.nodes) > 0: endLRTBusStopNode = endLRTBusStopNode.nodes[0] endLRTBusStopLatLon = (endLRTBusStopNode.lat, endLRTBusStopNode.lon) endLRTBusStopCode = endLRTBusStopNode.tags['asset_ref'] else: endLRTBusStopNode = None radius += 50 if endBusStopNode.id == endLRTBusStopNode.id: walkToStation = self.walk_astar(strtpt[0], reachLRT[0]) walkFromStation = self.walk_astar(leaveLRT[0], endpt[0]) # converting all osmnx nodes to coordinates walkToStation[0] = self.convertRoute( ox.plot.node_list_to_coordinate_lines( self.G_walk, walkToStation[0])) walkFromStation[0] = self.convertRoute( ox.plot.node_list_to_coordinate_lines( self.G_walk, walkFromStation[0])) lrtfinal[0] = self.convertRoute( ox.plot.node_list_to_coordinate_lines( self.G_lrt, lrtfinal[0])) # calculating estimated time, cost, distance to reach the destination statDist = 10300 / 14 totalDistLRT = ( lrtfinal[1]) / 1000 # convert to meters to km now = datetime.now() timenow = now.strftime("%H") waitTime = 0 if "10" > timenow > "6": print("--- PEAK HOUR ---") waitTime = 3 self.wlbvariable = "--- PEAK HOUR ---" else: print("--- NON-PEAK HOUR ---") waitTime = 7 self.wlbvariable = "--- NON-PEAK HOUR ---" self.lrtFareCal(totalDistLRT) # call fare function numStation = math.floor(totalDistLRT / statDist + 2) totatTimeLRT = numStation + ( (totalDistLRT * 1000) / (45000 / 60) ) + waitTime # avg mrt speed 45km/hr - 750m per minute totalDistWalk = (walkToStation[1] + walkFromStation[1] ) / 1000 # convert to meters to km estwalk = (totalDistWalk * 1000) / ( 5000 / 60) # avg walking speed 1.4m/min - 5km/hr # print("Time: " + str(round(totatTimeLRT + estwalk)) + " minutes" + "\nDistance: " + # str(round((totalDistWalk + totalDistLRT), 2)) + " km\nTransfer: None.") self.wlbvariable4 = ("\nTime taken : " + str(round(totatTimeLRT + estwalk)) + " minutes") self.wlbvariable5 = ( "\nDistance travelled: " + str(round( (totalDistWalk + totalDistLRT), 2)) + " km\n") self.wlbvariable6 = ("Transfer: None.") # plotting map to folium folium.PolyLine(lrtfinal[0], color="red", weight=2, opacity=1).add_to(m) folium.PolyLine( ([startpoint] + walkToStation[0] + [lrtfinal[0][0]]), color="blue", weight=2, opacity=1).add_to(m) folium.PolyLine( ([lrtfinal[0][-1]] + walkFromStation[0] + [endpoint]), color="blue", weight=2, opacity=1).add_to(m) # m.save('templates/astaralgo_walklrtbus.html') m.save('templates/default.html') else: walkToStation = self.walk_astar(strtpt[0], reachLRT[0]) paths = findShortestBusRoute.findShortestBusRoute( int(endLRTBusStopCode), int(endBusStopCode)) # bus = plotShortestBusRoute.findPath(G_bus, paths) bus = plotShortestBusRoute.findPath(self.G_bus, paths) walkFromBusStop = self.walk_astar(endBusStopNode.id, endpt[0]) # converting all osmnx nodes to coordinates walkToStation[0] = self.convertRoute( ox.plot.node_list_to_coordinate_lines( self.G_walk, walkToStation[0])) walkFromBusStop[0] = self.convertRoute( ox.plot.node_list_to_coordinate_lines( self.G_walk, walkFromBusStop[0])) bus[0] = self.convertRoute( ox.plot.node_list_to_coordinate_lines( self.G_bus, bus[0])) lrtfinal[0] = self.convertRoute( ox.plot.node_list_to_coordinate_lines( self.G_lrt, lrtfinal[0])) # calculating estimated time, cost, distance to reach the destination statDist = 10300 / 14 totalDistLRT = ( lrtfinal[1]) / 1000 # convert to meters to km now = datetime.now() timenow = now.strftime("%H") if "10" > timenow > "6": print("--- PEAK HOUR ---") waitTime = 3 self.wlbvariable = "--- PEAK HOUR ---" else: print("--- NON-PEAK HOUR ---") waitTime = 7 self.wlbvariable = "--- NON-PEAK HOUR ---" self.lrtFareCal(totalDistLRT) # call fare function numStation = math.floor(totalDistLRT / statDist + 2) totatTimeLRT = numStation + ( (totalDistLRT * 1000) / (45000 / 60) ) + waitTime # avg mrt speed 45km/hr - 750m per minute totalDistWalk = (walkToStation[1] + walkFromBusStop[1] ) / 1000 # convert to meters to km estwalk = (totalDistWalk * 1000) / ( 5000 / 60) # avg walking speed 1.4m/min - 5km/hr # print("Time: " + str(round(totatTimeLRT + estwalk)) + " minutes" + "\nDistance: " + # str(round((totalDistWalk + totalDistLRT), 2)) + " km\nTransfer: None.") self.wlbvariable4 = ("\nTime taken : " + str(round(totatTimeLRT + estwalk)) + " minutes") self.wlbvariable5 = ( "\nDistance travelled: " + str(round( (totalDistWalk + totalDistLRT), 2)) + " km\n") self.wlbvariable6 = ("Transfer: None.") # plotting map to folium folium.PolyLine(lrtfinal[0], color="red", weight=2, opacity=1).add_to(m) folium.PolyLine(bus[0], color="green", weight=2, opacity=1).add_to(m) folium.PolyLine( ([startpoint] + walkToStation[0] + [lrtfinal[0][0]]), color="blue", weight=2, opacity=1).add_to(m) folium.PolyLine(([lrtfinal[0][-1]] + [bus[0][0]]), color="blue", weight=2, opacity=1).add_to(m) folium.PolyLine( ([bus[0][-1]] + walkFromBusStop[0] + [endpoint]), color="blue", weight=2, opacity=1).add_to(m) # m.save('templates/astaralgo_walklrtbus.html') m.save('templates/default.html') # print("--- %s seconds to run all calculations ---" % round((time.time() - start_time), 2)) self.wlbvariable7 = ("Seconds to run all calculations: %s seconds" % round((time.time() - start_time), 2))
route_by_weight = nx.shortest_path(G, source=nearest_nodes[0], target=nearest_nodes[1], weight='impedance') route_by_length = nx.shortest_path(G, source=nearest_nodes[0], target=nearest_nodes[1], weight='length') routes = [route_by_weight, route_by_length] # create route colors rc1 = ['green'] * (len(route_by_weight)) rc2 = ['blue'] * len(route_by_length) route_colours = rc1 + rc2 filename_save = '/Users/niall/insight_project/projectname/static/map_with_routes' fig, ax = ox.plot_graph_routes(G, routes, node_size=0, route_color=route_colours, orig_dest_node_color='green', edge_color=edges.colour, fig_height=12, fig_width=12, margin=0, axis_off=False, show=True, save=True, file_format='png', filename=filename_save) routes = route_by_length route_colours = rc2 #fig, ax = ox.plot_graph_route(G, routes, node_size=0, route_color=route_colours, # orig_dest_node_color='green', edge_color=edges.colour, # fig_height=12, fig_width=12, margin=0, axis_off=False, # show=True, save=True, file_format='png', # filename=filename_save) y = ox.geocode('22, epsom avenue, toronto') ox.plot_route_folium(G, routes, route_map=None, popup_attribute=None, tiles='cartodbpositron', zoom=1, fit_bounds=True, route_color='#cc0000', route_width=5, route_opacity=1) #fig.savefig('/Users/niall/insight_project/data/map_output/map_with_routes.png') plt.show() #END