Exemplo n.º 1
0
def test_routing_folium():

    G = ox.graph_from_address(address=address,
                              dist=500,
                              dist_type="bbox",
                              network_type="bike")

    # give each node a random elevation then calculate edge grades
    randm = np.random.random(size=len(G))
    elevs = {n: e for n, e in zip(G.nodes(), randm)}
    nx.set_node_attributes(G, name="elevation", values=elevs)
    G = ox.add_edge_grades(G, add_absolute=True)

    # give each edge speed and travel time attributes
    G = ox.add_edge_speeds(G)
    G = ox.add_edge_travel_times(G)

    orig_node = list(G.nodes())[5]
    dest_node = list(G.nodes())[-5]
    orig_pt = (G.nodes[orig_node]["y"], G.nodes[orig_node]["x"])
    dest_pt = (G.nodes[dest_node]["y"], G.nodes[dest_node]["x"])
    route = nx.shortest_path(G, orig_node, dest_node, weight="travel_time")

    attributes = ox.utils_graph.get_route_edge_attributes(
        G, route, "travel_time")

    fig, ax = ox.plot_graph_route(G,
                                  route,
                                  save=True,
                                  filename="route",
                                  file_format="png")

    fig, ax = ox.plot_graph_route(
        G,
        route,
        origin_point=orig_pt,
        destination_point=dest_pt,
        save=True,
        filename="route",
        file_format="png",
    )

    # test multiple routes
    fig, ax = ox.plot_graph_routes(G, [route, route])

    # test folium
    gm = ox.plot_graph_folium(G, popup_attribute="name")
    rm = ox.plot_route_folium(G, route)

    # test calling folium plotters with FeatureGroup instead of Map, and extra kwargs
    fg = folium.FeatureGroup(name="legend name", show=True)
    gm = ox.plot_graph_folium(G, graph_map=fg)
    assert isinstance(gm, folium.FeatureGroup)

    rm = ox.plot_route_folium(G,
                              route,
                              route_color="g",
                              route_map=fg,
                              tooltip="x")
    assert isinstance(rm, folium.FeatureGroup)
Exemplo n.º 2
0
def test_routing_folium():

    # calculate shortest path and plot as static image and leaflet web map
    import networkx as nx
    G = ox.graph_from_address('398 N. Sicily Pl., Chandler, Arizona',
                              distance=800,
                              network_type='drive')
    origin = (33.307792, -111.894940)
    destination = (33.312994, -111.894998)
    origin_node = ox.get_nearest_node(G, origin)
    destination_node = ox.get_nearest_node(G, destination, method='euclidean')
    route = nx.shortest_path(G, origin_node, destination_node)

    attributes = ox.get_route_edge_attributes(G, route, 'length')

    fig, ax = ox.plot_graph_route(G,
                                  route,
                                  save=True,
                                  filename='route',
                                  file_format='png')
    fig, ax = ox.plot_graph_route(G,
                                  route,
                                  origin_point=origin,
                                  destination_point=destination,
                                  save=True,
                                  filename='route',
                                  file_format='png')

    graph_map = ox.plot_graph_folium(G, popup_attribute='name')
    route_map = ox.plot_route_folium(G, route)
Exemplo n.º 3
0
def create_route(coords, dist_goal, name):
    """
    Creates list of routes
    Parameters:
        coords (tuple): (latitude,longitude)
        dist_goal (int): desired length in km
    Returns:
        paths (list): list of lists, each sublist is a path (list of osmid's)
    """

    graph = ox.core.graph_from_point(coords,
                                     distance=dist_goal * 700,
                                     simplify=False)
    start = ox.get_nearest_node(graph, coords)
    nodes, _ = ox.graph_to_gdfs(graph)
    pivots = get_pivots(graph, start, dist_goal)

    #print(start)

    paths = []
    for piv in pivots:
        try:
            test = make_loop(graph, piv, start, dist_goal)
            paths.append(test)
            ox.plot_graph_route(graph, test)
        except Exception as exception:
            print("Error in loop generation")
            print(exception)

    return paths, nodes
Exemplo n.º 4
0
def test_routing_folium():

    import networkx as nx
    G = ox.graph_from_address('N. Sicily Pl., Chandler, Arizona',
                              distance=800,
                              network_type='drive')
    origin = (33.307792, -111.894940)
    destination = (33.312994, -111.894998)
    origin_node = ox.get_nearest_node(G, origin)
    destination_node = ox.get_nearest_node(G, destination)
    route = nx.shortest_path(G, origin_node, destination_node)
    fig, ax = ox.plot_graph_route(G,
                                  route,
                                  save=True,
                                  filename='route',
                                  file_format='png')
    fig, ax = ox.plot_graph_route(G,
                                  route,
                                  origin_point=origin,
                                  destination_point=destination,
                                  save=True,
                                  filename='route',
                                  file_format='png')

    graph_map = ox.plot_graph_folium(G, popup_attribute='name')
    route_map = ox.plot_route_folium(G, route)
Exemplo n.º 5
0
def task6(to_show):

	marks_for_part = 0

	G_iit, origin_node, final_node = get_problem('iit')
	actual_route = [668478124, 668672699, 4348259295, 668672574, 245674992, 668672700, 3215340463, 667357325, 5366445105]
	problem = MapSearchProblem(G_iit, origin_node, final_node)
	route_astar_iit = AStar_search(problem, heuristic)

	if route_astar_iit == actual_route and problem.nodes_expanded < 25:
		marks_for_part += 1 
	print "Number of nodes expanded for IIT: %d" % problem.nodes_expanded

	G_mumbai, origin_node, final_node = get_problem('mumbai')
	actual_route = [5280438428, 4348259324, 5280437314, 5280437313, 668672574, 245674992, 668672700, 3215340463, 667357325, 668699249, 667357311, 668660552, 1879817556, 245673500, 3708892000, 667395479, 667395482, 667395474, 667395468, 2246662857, 2246662767, 1855812188, 667395460, 2055634531, 4759328799, 4759328802, 1366901332, 4759328760, 5456498950, 5456509646, 5456509636, 5456509634, 2245075822, 1366901213, 1366901212, 2245075777, 1366901170, 5456500624, 5456509624, 2245075731, 1366901143, 2245075698, 1366901132, 2244962270, 2244962262, 2244962226, 2244962231, 2244962200, 2244962171, 1366900900, 4366100155, 2246661216, 2246661194, 3245621937, 2246661136, 2246661130, 2246661132, 2246661074, 623889405, 5477703669, 5477703667, 5477703671, 5758624138, 2622177356, 2244961487, 1644086520, 623889400, 4264598038, 4264598040, 4264598033, 4264598029, 4264598395, 1640287824, 1640287806, 1454672572, 245668721, 1454673995, 1643047708, 245668490, 2246472636, 1643047703, 2246472590, 2246472543, 2246472486, 2246472465, 1643035298, 1643035294, 2246472375, 1643031073, 245667692, 2146269450, 2163935132, 2146273510, 1232644012, 4264598321, 2146273513, 5913464524, 2439252028, 5865538271, 1366938254, 5865538272, 1232644986, 1642951891, 1642951846, 1642951818, 245664866, 1642951755, 1642951748, 1642954393, 1179340118, 1179340221, 245664141, 245663296, 1179314459, 245663089, 4362786418, 1643134423, 2258304514, 2258304493, 2258304484, 1179089888, 1179257896, 1179273129, 245660324, 2258304455, 245660183, 1179221113, 1179221116, 1179221118, 5921458181, 2258304438, 245659911, 245659814, 1165320838, 5848596597, 245659701, 2258304421, 245659569, 245659514, 245659478, 245659392, 2258304411, 674906578, 2258304349, 2258304338, 5637109060, 1375482657, 245657044, 245657005, 620382315, 2258304310, 245656839, 4443807473, 861155618, 861155314, 861155306, 2246157812, 245656050, 861155655, 861190736, 620393213, 245655857, 245655720, 245655652, 2246157809, 245655525, 245655412, 245655339, 620403338, 245655305, 2184321321, 245655223, 5510030709, 245655072, 620408597, 620404556, 245654969, 245654863, 2248513091, 2244632754, 1643210517, 245654715, 1643210514, 485953796, 485953814, 485953784, 356168287, 1643210508, 6215526121, 1127766407, 4568979756, 4568979754]
	problem = MapSearchProblem(G_mumbai, origin_node, final_node)
	route_astar_mumbai = AStar_search(problem, heuristic)

	if route_astar_mumbai == actual_route and problem.nodes_expanded < 15000:
		marks_for_part += 1
	print "Number of nodes expanded for Mumbai: %d" % problem.nodes_expanded

	if to_show:
		try:
			ox.plot_graph_route(G_iit, route_astar_iit, node_size=1)
		except:
			print "The route returned is not possible for IIT"
		try:
			ox.plot_graph_route(G_mumbai, route_astar_mumbai, node_size=1)
		except:
			print "The route returned is not possible for Mumbai"	
	
	return marks_for_part, 2
Exemplo n.º 6
0
def test_routing_folium():

    import networkx as nx
    with httmock.HTTMock(
            get_mock_response_content('overpass-response-3.json.gz')):
        G = ox.graph_from_address('398 N. Sicily Pl., Chandler, Arizona',
                                  distance=800,
                                  network_type='drive')
    origin = (33.307792, -111.894940)
    destination = (33.312994, -111.894998)
    origin_node = ox.get_nearest_node(G, origin)
    destination_node = ox.get_nearest_node(G, destination)
    route = nx.shortest_path(G, origin_node, destination_node)

    attributes = ox.get_route_edge_attributes(G, route, 'length')

    fig, ax = ox.plot_graph_route(G,
                                  route,
                                  save=True,
                                  filename='route',
                                  file_format='png')
    fig, ax = ox.plot_graph_route(G,
                                  route,
                                  origin_point=origin,
                                  destination_point=destination,
                                  save=True,
                                  filename='route',
                                  file_format='png')

    graph_map = ox.plot_graph_folium(G, popup_attribute='name')
    route_map = ox.plot_route_folium(G, route)
Exemplo n.º 7
0
 def plot_graph_route_over_cost(self, path_converted, filename=None):
     ec = ox.get_edge_colors_by_attr(self.planner.graph, 'cost', cmap='plasma', num_bins=100)
     fig, ax = ox.plot_graph(self.kalman.env.graph, fig_height=6, edge_color=ec, node_zorder=2,
                              use_geom=True)
     if filename:
         fig, ax = ox.plot_graph_route(self.planner.graph, path_converted, edge_color=ec, route_alpha=0.3, save=True, filename=filename, )
     else:
         fig, ax = ox.plot_graph_route(self.planner.graph, path_converted, edge_color=ec, route_alpha=0.3)
Exemplo n.º 8
0
    def plot_path (self, route):
        """
        This method plot the path found.

        :param route: The list of visited nodes
        :return: None
        """
        ox.plot_graph_route(self.graph, route)
Exemplo n.º 9
0
def lab_2():
    np.random.seed(int(time()))
    G = ox.load_graphml('data/BUPT.graphml')
    print(len(G.nodes))  # 2164
    print(len(G.edges))  # 5226
    src = np.random.choice(G.nodes)
    dst = np.random.choice(G.nodes)
    route = nx.dijkstra_path(G, src, dst, weight='length')
    ox.plot_graph_route(G, route, figsize=(20, 20))
Exemplo n.º 10
0
def test_routing():

    G = ox.graph_from_address(address=address,
                              dist=500,
                              dist_type="bbox",
                              network_type="bike")

    # give each node a random elevation then calculate edge grades
    randm = np.random.random(size=len(G))
    elevs = {n: e for n, e in zip(G.nodes(), randm)}
    nx.set_node_attributes(G, name="elevation", values=elevs)
    G = ox.add_edge_grades(G, add_absolute=True)

    # give each edge speed and travel time attributes
    G = ox.add_edge_speeds(G)
    G = ox.add_edge_speeds(G, hwy_speeds={"motorway": 100})
    G = ox.add_edge_travel_times(G)

    orig_node = list(G.nodes())[5]
    dest_node = list(G.nodes())[-5]
    orig_pt = (G.nodes[orig_node]["y"], G.nodes[orig_node]["x"])
    dest_pt = (G.nodes[dest_node]["y"], G.nodes[dest_node]["x"])
    route = ox.shortest_path(G, orig_node, dest_node, weight="travel_time")

    attributes = ox.utils_graph.get_route_edge_attributes(G, route)
    attributes = ox.utils_graph.get_route_edge_attributes(
        G, route, "travel_time")

    fig, ax = ox.plot_graph_route(G, route, save=True)

    fig, ax = ox.plot_graph_route(G, route, save=True)

    # test multiple routes
    routes = ox.k_shortest_paths(G,
                                 orig_node,
                                 dest_node,
                                 k=2,
                                 weight="travel_time")
    fig, ax = ox.plot_graph_routes(G, list(routes))

    # test folium with keyword arguments to pass to folium.PolyLine
    gm = ox.plot_graph_folium(G,
                              popup_attribute="name",
                              color="#333333",
                              weight=5,
                              opacity=0.7)
    rm = ox.plot_route_folium(G, route, color="#cc0000", weight=5, opacity=0.7)

    # test calling folium plotters with FeatureGroup instead of Map, and extra kwargs
    fg = folium.FeatureGroup(name="legend name", show=True)
    gm = ox.plot_graph_folium(G, graph_map=fg)
    assert isinstance(gm, folium.FeatureGroup)

    rm = ox.plot_route_folium(G, route, route_map=fg, tooltip="x")
    assert isinstance(rm, folium.FeatureGroup)
Exemplo n.º 11
0
    def plot_route(self, graph, route):
        if self._ax is None:
            raise Exception('Need to plot the map first before the route.')

        ox.plot_graph_route(graph,
                            route,
                            ax=self._ax,
                            route_colors=self.COLOR_ROUTE,
                            alpha=1,
                            orig_dest_size=250,
                            route_linewidth=4,
                            show=False,
                            close=False)
Exemplo n.º 12
0
def test_routing():

    G = ox.graph_from_address(address=address,
                              dist=500,
                              dist_type="bbox",
                              network_type="bike")

    # give each edge speed and travel time attributes
    G = ox.add_edge_speeds(G)
    G = ox.add_edge_speeds(G, hwy_speeds={"motorway": 100})
    G = ox.add_edge_travel_times(G)

    orig_x = np.array([-122.404771])
    dest_x = np.array([-122.401429])
    orig_y = np.array([37.794302])
    dest_y = np.array([37.794987])
    orig_node = ox.distance.nearest_nodes(G, orig_x, orig_y)[0]
    dest_node = ox.distance.nearest_nodes(G, dest_x, dest_y)[0]

    route = ox.shortest_path(G, orig_node, dest_node, weight="travel_time")
    attributes = ox.utils_graph.get_route_edge_attributes(G, route)
    attributes = ox.utils_graph.get_route_edge_attributes(
        G, route, "travel_time")

    fig, ax = ox.plot_graph_route(G, route, save=True)

    fig, ax = ox.plot_graph_route(G, route, save=True)

    # test multiple routes
    routes = ox.k_shortest_paths(G,
                                 orig_node,
                                 dest_node,
                                 k=2,
                                 weight="travel_time")
    fig, ax = ox.plot_graph_routes(G, list(routes))

    # test folium with keyword arguments to pass to folium.PolyLine
    gm = ox.plot_graph_folium(G,
                              popup_attribute="name",
                              color="#333333",
                              weight=5,
                              opacity=0.7)
    rm = ox.plot_route_folium(G, route, color="#cc0000", weight=5, opacity=0.7)

    # test calling folium plotters with FeatureGroup instead of Map, and extra kwargs
    fg = folium.FeatureGroup(name="legend name", show=True)
    gm = ox.plot_graph_folium(G, graph_map=fg)
    assert isinstance(gm, folium.FeatureGroup)

    rm = ox.plot_route_folium(G, route, route_map=fg, tooltip="x")
    assert isinstance(rm, folium.FeatureGroup)
Exemplo n.º 13
0
 def plot_graph_route(self, path, filename=None):
     fig, ax = ox.plot_graph(self.kalman.env.graph,
                             fig_height=6,
                             node_zorder=2,
                             use_geom=True)
     if filename:
         fig, ax = ox.plot_graph_route(self.planner.graph,
                                       path,
                                       route_alpha=0.3,
                                       save=True,
                                       filename=filename)
     else:
         fig, ax = ox.plot_graph_route(self.planner.graph,
                                       path,
                                       route_alpha=0.3)
def carrinheiro(id_user, date):
    user_carrinheiro = User.get_user(id_user, DATABASE_DIRECTORY)
    path = Path.Path(user_carrinheiro, date, DATABASE_DIRECTORY)

    stop_points = scenario_stop_points(path)

    # download the osm file (scenario)
    file_name_osm = OpenSteetMap.file_osm(MAPS_DIRECTORY, stop_points)

    # download the GeoTiff file (scenario)
    geotiff_name = GeoTiff.geotiff(MAPS_DIRECTORY, stop_points)

    G, nodes_coordinates, nodes_mass_increment = graph_scenario(
        stop_points, geotiff_name, path.material_weights, file_name_osm)

    H = Graph_Collect.create_graph_route(nodes_coordinates,
                                         nodes_mass_increment)

    index_coordinate_start = list(nodes_coordinates.values()).index(
        path.start_point)
    node_source = list(nodes_coordinates.keys())[index_coordinate_start]
    index_coordinate_end = list(nodes_coordinates.values()).index(
        path.end_point)
    node_target = list(nodes_coordinates.keys())[index_coordinate_end]

    cost_total, paths = closest_insertion_path(G, H, node_source, node_target)

    for i in paths:
        fig, ax = ox.plot_graph_route(G,
                                      i,
                                      route_linewidth=6,
                                      node_size=0,
                                      bgcolor='w')

    return paths
Exemplo n.º 15
0
def showShortest(G, start_node=246539610, end_node=59768831):
    edge_color = "black"  # colorEdges(G)
    route = nx.shortest_path(G, start_node, end_node, weight='weight')
    fig, ax = ox.plot_graph_route(G,
                                  route=route,
                                  edge_color=edge_color,
                                  node_color='none')
Exemplo n.º 16
0
def get_robo_route(start=(41.814884, -87.664603), chicago_path="chicago.xml", pothole_path="potholes.xml"):

	"""
	This function will compute the optimal route for
	a robot to take to fill potholes.
	
	Input:
		start: The location where the robot starts and ends at (the facility)
		chicago_path: The location of the graph of Chicago located locally
		pothole_path: The location of the graph of the pothole data located locally
	Return:
		An ordered list of nodes representing the route the robot will take
	"""

	#Acquire the graph of Chicago
	print("Opening Chicago")
	Chicago = open_chicago_graph(chicago_path)
	Cpp = CppGraph(Chicago)
	Cpp.set_start(start)
	
	#Acquire the set of all potholes that need to be filled
	print("Opening Potholes")
	potholes = open_potholes(pothole_path)
	
	#Get the shortest paths connecting the potholes and the robot facility
	print("Adding potholes to Chicago")
	short_pathN(Chicago, Cpp, potholes)
	
	#Find the optimal way to traverse the graph starting from the robot's facility
	print("Finding the route")
	route = Cpp.solve()
	
	#Save the route the robot will take as an image
	fig, ax = ox.plot_graph_route(G, route, save=True, filename="graph")
	return route
Exemplo n.º 17
0
def type_transport(transport):
    """This function plot the shortest path for different type of transport from La Maison du Lez, Montpellier, France 
    to Place to Eugène Bataillon, Montpellier, France.
    
    Parameters
    ----------
    transport : string, type of transport to choose to plot his path.
    
    Returns
    -------
    a map showing the shortest path.
    """ 
    # download the map as a graph object 
    G = ox.graph_from_place(
        'Montpellier, Hérault, France', network_type=transport)
    # define origin and desination locations 
    origin_point = ox.geo_utils.geocode('Maison du Lez, Montpellier, France')
    destination_point = ox.geo_utils.geocode(
        'Place Eugène Bataillon, Montpellier, France')
    # get the nearest nodes to the locations 
    origin_node = ox.get_nearest_node(G, origin_point)
    destination_node = ox.get_nearest_node(G, destination_point)
    # finding the shortest path
    route = nx.shortest_path(G, origin_node, destination_node)
    # plot the map graph
    fig, ax = ox.plot_graph_route(G, route, origin_point=origin_point, destination_point=destination_point, route_linewidth=2)
    plt.show
    return()
Exemplo n.º 18
0
def shortestPathNavigation(userLoc, destinLoc):
    """
    :type userLoc:     List[float] of size 2
    :type destinLoc:   List[float] of size 2
    """
    G = ox.graph_from_point(userLoc, distance = 2000, distance_type = 'network', network_type = 'walk')
    Gnodes = G.nodes()
    
    # Get the nearest node in the system of the given location
    origin_node = ox.get_nearest_node(G, userLoc)
    destin_node = ox.get_nearest_node(G, destinLoc)
    
    # Get the lat&lng of the approximated location
    origin_point, destin_point = [[Gnodes[i]['y'],Gnodes[i]['x']] for i in [origin_node, destin_node]]
    
    # Get the shortest route's nodes' indices
    route = nx.shortest_path(G, origin_node,destin_node, weight = 'length')
    fig,ax = ox.plot_graph_route(G,route,origin_point = origin_point, destination_point = destin_point)
    
    # Get the shortest route's lat&lng
    the_route = [[G.nodes()[i]['y'],G.nodes()[i]['x']] for i in route]
    
    # Create map and add markers of origin&destin to the map
    m = folium.Map(location = userLoc, zoom_start = 13)
    marker_cluster = folium.MarkerCluster().add_to(m)
    folium.Marker(origin_point, popup = 'Origin').add_to(marker_cluster)
    folium.Marker(destin_point, popup = 'Dest').add_to(marker_cluster)
    
    # Add the shortest path to the map
    shortest_path = folium.PolyLine(the_route).add_to(m) # More parameters: #weight=15,#color='#8EE9FF'
    
    # Show the map
    return m
Exemplo n.º 19
0
def show_route(edges):
    route = []
    route.append(edges[0][0])
    previous_node = edges[0][1]
    for edge in edges[1:]:
        go_node = edge[0]
        r = nx.shortest_path(G_lisbon, previous_node, go_node, weight='length')
        if False and len(r) <= 1:
            print 'strange... => previus_node:' + str(
                previous_node) + ' go_node:' + str(go_node)
            print r
        route.extend(r)
        previous_node = edge[1]

    print 'route with ' + str(len(route)) + ' nodes'
    ox.plot_graph_route(G_lisbon, route, route_linewidth=2)
Exemplo n.º 20
0
    def test_mocked_path_creation(self):
        mongo_resource = MongoResourceImpl()
        track_statistics_repository = TrackStatisticsRepositoryImpl(
            mongo_resource)
        graph_information = GraphInformationRepositoryImpl(mongo_resource)
        bellver_graph = Graph(39.5713, 39.5573, 2.6257, 2.6023)
        gpx_resource = GPXResourceImpl()
        pyplot_resource = PyplotResourceImpl()
        try:
            k.start()
            data = graph_information.read_graph_information_dataframe(
                os.environ.get('LAST_VERSION_GRAPH'))
            k.stop()
        except IndexError:
            logging.warning("NOT found in MongoDB")
            return
        simulate_track = SimulateTrackImpl(bellver_graph, 4, gpx_resource,
                                           pyplot_resource,
                                           track_statistics_repository)
        # Graph information load
        bellver_graph.load_graph_analysis_statistics(data)
        simulator = TrackSimulatorPipeline(simulate_track)

        path = simulator.run(1248507104, 10000)
        a = [x[0] for x in path]
        print(path)
        fig, ax = osmnx.plot_graph_route(bellver_graph.graph,
                                         a,
                                         bgcolor='k',
                                         node_color='black',
                                         edge_linewidth=1.5,
                                         edge_alpha=1,
                                         node_zorder=3)
        plt.show()
def main():
    map_graph = ox.graph_from_place('Berkley, California',
                                    network_type='drive')
    origin = ox.get_nearest_node(map_graph, (37.8743, -122.277))
    destination = list(map_graph.nodes())[-1]

    shortest_path = nx.shortest_path(map_graph,
                                     origin,
                                     destination,
                                     weight='length')
    fig, ax = ox.plot_graph_route(map_graph, shortest_path)

    path = dijkstras_search(origin, destination, map_graph)
    fig, ax = ox.plot_graph_route(map_graph, path)

    path = a_star_search(origin, destination, map_graph)
    fig, ax = ox.plot_graph_route(map_graph, path)
Exemplo n.º 22
0
    def show_route(self, end_node):
        """
        Show map and render route from start to end_node
        :param end_node: Node id of current location
        :return: Matplotlib figure
        """
        route = nx.shortest_path(self.G, end_node, end_node, weight='length')

        ox.plot_graph_route(self.G,
                            route,
                            node_size=0,
                            show=False,
                            save=True,
                            filename="output",
                            file_format="png")
        fig = cv2.imread("data/plot/output.png")

        return fig
Exemplo n.º 23
0
def ShortestPath(orig_address, dest_address):
    """
    This function takes a two addresses in as an input (origin and destination). The addresses should be strings. Then it calculates he quickest route from origin to destination by driving and presents  that on a map. Please note that the function only works in Helsinki because the network data is heavy, that's why it might be slow. 
    """
    #retrieve the driving network from Helsinki. I first did this with bike network data but none of the nodes I tried were connected to biking network so I changed that to driving for the sake of convenience.
    place_name = "Helsinki, Finland"
    graph = ox.graph_from_place(place_name, network_type="drive")

    #project the graph
    graph_proj = ox.project_graph(graph)

    #access projected nodes and edges
    nodes_proj, edges_proj = ox.graph_to_gdfs(graph_proj,
                                              nodes=True,
                                              edges=True)

    #create a dataframe with the addresses as an input
    d = {"id": [1, 2], "addr": [orig_address, dest_address]}
    data = pd.DataFrame(data=d)

    #geocode addresses so the dataframe becomes a geodataframe (with location information extracted by geocoding)
    geo = geocode(data["addr"],
                  provider="nominatim",
                  user_agent="SK",
                  timeout=4)

    #check CRS systems, they are different
    CRS(geo.crs).to_epsg()
    CRS(edges_proj.crs).to_epsg()

    #convert geo to same CRS system with projected network
    geo = geo.to_crs(epsg=32635)

    #make a tuple of the x and y coordinates by retrieving them from dataframe. Y is first because it is latitude infomation
    orig_xy = [geo["geometry"][0].y, geo["geometry"][0].x]
    dest_xy = [geo["geometry"][1].y, geo["geometry"][1].x]

    #find the nearest node to the origin and target point coordinates with euclidean distance
    orig_node = ox.get_nearest_node(graph_proj, orig_xy, method='euclidean')
    target_node = ox.get_nearest_node(graph_proj, dest_xy, method='euclidean')

    # Calculate the shortest path (using Djikstra's algorithm)
    route = nx.shortest_path(G=graph_proj,
                             source=orig_node,
                             target=target_node,
                             weight='time')

    # Plot the shortest path
    fig, ax = ox.plot_graph_route(graph_proj,
                                  route,
                                  origin_point=orig_xy,
                                  destination_point=dest_xy)

    #save and return figure
    output_fig = "outputs/shortest_path_from_" + orig_address + "_to_" + dest_address + ".png"
    plt.savefig(output_fig)
    return fig
Exemplo n.º 24
0
 def show_route(self, graph_projection, route, bbox):
     print("Showing route")
     # lat_long_list = []
     # gmap = gmplot.GoogleMapPlotter(37.7749295, -122.4194155, 13)
     # #gmap = self.from_geocode("San Francisco", apikey = 'AIzaSyDU_zAP8D2D9c54N9G5nMPYF52H5VZ_T4o')
     # for i in range(0, len(route)):
     # 	sum += route[i]
     # 	lat_long_list.append(tuple((graph_projection.node[route[i]]['y'], graph_projection.node[route[i]]['x'])))
     # top_attraction_lats, top_attraction_lons = zip(*lat_long_list)
     # gmap.scatter(top_attraction_lats, top_attraction_lons, '#3B0B39', size = 40, marker = False)
     # # Marker
     # hidden_gem_lat, hidden_gem_lon = 37.77, -122.426
     # gmap.marker(hidden_gem_lat, hidden_gem_lon, 'cornflowerblue')
     # hidden_gem_lat_2, hidden_gem_lon_2 = 37.773, -122.441
     # gmap.marker(hidden_gem_lat_2, hidden_gem_lon_2, 'cornflowerblue')
     # # Draw
     # gmap.draw("my_map1.html")
     ox.plot_graph_route(graph_projection, route, bbox=bbox, node_size=0)
Exemplo n.º 25
0
def plot_route(G, route_list, color):
    return ox.plot_graph_route(G,
                               bgcolor='white',
                               node_size=1.0,
                               node_color='gray',
                               edge_color='gray',
                               route=route_list,
                               route_color=color,
                               dpi=300,
                               figsize=(15, 15))
Exemplo n.º 26
0
 def plot_shortest_route(self):
     # Calculates the shortest route from start point to end point taking only the length of the edges as the weight
     # and plots the route on the reduced graph using the boundary box
     orig_node = ox.get_nearest_node(self.G, self.start)
     dest_node = ox.get_nearest_node(self.G, self.end)
     route = nx.shortest_path(self.G, orig_node, dest_node, weight='length')
     #print('Path Length:',nx.shortest_path_length(self.G, orig_node, dest_node, weight='length'))
     fig, ax = ox.plot_graph_route(self.G,
                                   route,
                                   bbox=self.bbox,
                                   node_size=0,
                                   fig_height=15)
     plt.show()
Exemplo n.º 27
0
def short_path(graph, origin, destination):  
    """This function plot the shortest path in the graph and calculate his length.
    
    Returns
    -------
    a networkx graph showing the shortest path.
    """  
    origin_node = ox.get_nearest_node(graph, origin)
    destination_node = ox.get_nearest_node(graph, destination)
    route = nx.shortest_path(graph, origin_node, destination_node)
    route_lentgh = nx.shortest_path_length(graph, origin_node, destination_node)
    chemin = ox.plot_graph_route(graph, route)
    return chemin, route_lentgh
Exemplo n.º 28
0
def test_routing_folium():

    # calculate shortest path and plot as static image and leaflet web map
    import networkx as nx
    G = ox.graph_from_address('398 N. Sicily Pl., Chandler, Arizona', distance=800, network_type='drive')
    origin = (33.307792, -111.894940)
    destination = (33.312994, -111.894998)
    origin_node = ox.get_nearest_node(G, origin)
    destination_node = ox.get_nearest_node(G, destination, method='euclidean')
    route = nx.shortest_path(G, origin_node, destination_node)

    attributes = ox.get_route_edge_attributes(G, route, 'length')

    fig, ax = ox.plot_graph_route(G, route, save=True, filename='route', file_format='png')
    fig, ax = ox.plot_graph_route(G, route, origin_point=origin, destination_point=destination,
                                  save=True, filename='route', file_format='png')

    # test multiple routes
    fig, ax = ox.plot_graph_routes(G, [route, route])

    graph_map = ox.plot_graph_folium(G, popup_attribute='name')
    route_map = ox.plot_route_folium(G, route)
Exemplo n.º 29
0
def safest_way(origin, destination):  # select safest route
    route = ox.shortest_path(G, origin, destination, weight='danger_weight')
    fig, ax = ox.plot_graph_route(G,
                                  route,
                                  route_color='y',
                                  route_linewidth=6,
                                  node_size=0)  # plot the safest road
    route_risk = int(
        sum(ox.utils_graph.get_route_edge_attributes(
            G, route, 'danger_weight')))  # print the risk on this road
    txt1 = 'The risk on this Route is '
    txt2 = ' accidents per year'
    return fig, txt1, txt2, route_risk
Exemplo n.º 30
0
        def plot_shortest_path(self, destination_id, truncate=True):
            """
            Plots shortest path between two stations as determined by osmnx
            :param destination_id: int
                destination id for destination station
            :param truncate: boolean, optional, default True
                whether to truncate the graph to the smallest box enclosing the path or keep the path
                embedded in the entire location_graph
            :return: None
            """
            path = self.shortest_path(destination_id)

            if truncate:
                path_coords_x = [self.bike_service_instance.location_graph.node[node]['x'] for node in path]
                path_coords_y = [self.bike_service_instance.location_graph.node[node]['y'] for node in path]

                north = max(path_coords_y)
                south = min(path_coords_y)
                east = max(path_coords_x)
                west = min(path_coords_x)

                temp_graph = ox.truncate_graph_bbox(
                    G=self.bike_service_instance.location_graph,
                    north=north,
                    south=south,
                    east=east,
                    west=west)

            else:
                temp_graph = self.bike_service_instance.location_graph

            ox.plot_graph_route(
                temp_graph,
                path,
                fig_height=30,
                node_size=0)

            return None
Exemplo n.º 31
0
def run_optimality_evaluation(G):
    start_node_id = np.random.choice(G.nodes)
    goal_node_id = np.random.choice(G.nodes)

    truth_route = nx.shortest_path(G,
                                   start_node_id,
                                   goal_node_id,
                                   weight='best_travel_time')

    curr_node_id = start_node_id
    ml_route = []
    visited = collections.deque(maxlen=7)

    # Start node
    ml_route.append(curr_node_id)
    use_random_actions = False

    history = collections.deque(maxlen=5)
    while curr_node_id != goal_node_id:
        curr_node_id = predict_next_node_id(G,
                                            curr_node_id,
                                            goal_node_id,
                                            model,
                                            randomness=0.1)
        ml_route.append(curr_node_id)

    gt_duration = get_route_duration(truth_route, G)
    ml_duration = get_route_duration(ml_route, G)

    print("------ METRICS ------")
    print("GT duration: ", gt_duration, ". ML duration: ", ml_duration,
          ". Abs Diff: ", ml_duration - gt_duration, ". Ratio: ",
          gt_duration / ml_duration)
    print("---------------------")

    ###### PLOT GT AND ML PATHS ######
    ox.plot_graph_route(G, truth_route)
    ox.plot_graph_route(G, ml_route)