コード例 #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)
コード例 #2
0
ファイル: test_osmnx.py プロジェクト: rvpanchani/osmnx
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)

    # test multiple origins-destinations
    n = 5
    nodes = np.array(G.nodes)
    origs = np.random.choice(nodes, size=n, replace=True)
    dests = np.random.choice(nodes, size=n, replace=True)
    paths1 = ox.shortest_path(G, origs, dests, weight="length", cpus=1)
    paths2 = ox.shortest_path(G, origs, dests, weight="length", cpus=2)
    paths3 = ox.shortest_path(G, origs, dests, weight="length", cpus=None)
    assert paths1 == paths2 == paths3

    # test k shortest paths
    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)
コード例 #3
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)
コード例 #4
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)
コード例 #5
0
ファイル: test_osmnx.py プロジェクト: zhuang-hao-ming/osmnx
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)
コード例 #6
0
ファイル: test_osmnx.py プロジェクト: sephib/osmnx
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)
コード例 #7
0
def draw_map(G, highlight = None , zoom = 16):
    """ draws ipyleaflet map with location as center of the map """
    
    if len(G) >= 1000:
        print(f"The graph has {len(G)} which is a lot, we will use basic faster folium instead")
        if highlight:
            center_osmid = ox.stats.extended_stats(G,ecc=True)['center'][0]
            G_gdfs = ox.graph_to_gdfs(G)
            nodes_frame = G_gdfs[0]
            ways_frame = G_gdfs[1]
            m = ox.plot_graph_folium(G = G)
            for node_osmid in highlight:
                node = nodes_frame.loc[node_osmid]
                node_xy = [node['y'], node['x']]
                fl.Marker(node_xy).add_to(m)
        else: 
            m = ox.plot_graph_folium(G = G)
        return m
        
    center_osmid = ox.stats.extended_stats(G,ecc=True)['center'][0]
    G_gdfs = ox.graph_to_gdfs(G)
    nodes_frame = G_gdfs[0]
    ways_frame = G_gdfs[1]
    center_node = nodes_frame.loc[center_osmid]
    location = (center_node['y'], center_node['x'])
    m = lf.Map(center = location, zoom = zoom)

    for _, row in ways_frame.iterrows():
        lines = lf.Polyline(
            locations = [list(elem)[::-1] for elem in [*row['geometry'].coords]],
            color = "black",
            fill = False,
            weight = 1
        )
        m.add_layer(lines)

    # if we want to mark some specific nodes
    if highlight:
        for node_osmid in highlight:
            node = nodes_frame.loc[node_osmid]
            node_xy = (node['y'], node['x'])
            marker = lf.Marker(location = node_xy, draggable = False)
            m.add_layer(marker)

    return m
コード例 #8
0
def buildHTMLWithNetworkx(G):
    try:
        graphMap = ox.plot_graph_folium(G, edge_width=2)
    except (ValueError, KeyError):
        raise OsmnxException(
            "Probably there are elements without all its nodes or the response is empty. "
            "It is not possible to show the results but you can use the option 'Open netedit'."
        )
    graphMap.save(tilePath)

    logging.info("Html built.")

    return graphMap.get_root().render()
コード例 #9
0
def get_plot(address):
    orig_results, true_results, to_remove, best_improvement, G = get_removable_streets(
        address)
    cols = vals_to_colors([(orig_results[node_str(node_a, node_b)] if node_str(
        node_a, node_b) in orig_results else 0)
                           for (node_a, node_b) in G.edges()])

    for i, (node_a, node_b) in enumerate(G.edges()):
        if node_str(node_a, node_b) in to_remove:
            cols[i] = '#73db67'

    gdf_edges = ox.graph_to_gdfs(G, nodes=False, fill_edge_geometry=True)
    gdf_edges['edge_color'] = cols
    return ox.plot_graph_folium(gdf_edges), best_improvement
コード例 #10
0
def make_updated_graph_model():
    ox.config(log_console=True, use_cache=True)

    G_2 = ox.load_graphml('osmnx_graph.graphml')

    # plot the street network with folium
    graph_map = ox.plot_graph_folium(G_2, edge_width=2)

    filepath = 'templates/graph.html'
    graph_map.save(filepath)
    IFrame(filepath, width=600, height=500)

    soup = BeautifulSoup(open('templates/graph.html'), 'html.parser')

    js_tag = soup.find_all("script")
    js_tag[5].append('{% block script %} {% endblock %}')

    with open("templates/graph.html", "w") as file:
        file.write(str(soup))

    soup.find("div")
    div = soup.find("div")
    div = str(div).split()
    map_id = div[2][4:-8]

    fin = open("templates/graph.html", "rt")
    # output file to write the result to
    fout = open("templates/final_graph.html", "wt")
    # for each line in the input file
    for line in fin:
        # read replace the string and write to output file
        fout.write(line.replace(map_id, 'map_id'))
    # close input and output files
    fin.close()
    fout.close()

    soup = BeautifulSoup(open('templates/final_graph.html'), 'html.parser')

    data_body = '{% block body %} {% endblock %}'
    data_script = '{% block script %} {% endblock %}'
    data_style = '{% block style %} {% endblock %}'

    soup.body.append(data_body)

    soup.style.append(data_style)
    with open("templates/final_graph.html", "w") as file:
        file.write(str(soup))
コード例 #11
0
ファイル: TSP.py プロジェクト: royanc/TSP
def mergeNplot(optimal_path, locations):
    lat = lon = 0
    # Finding the center of all locations, it's purpose is for generating the map
    for location in locations:
        lat += location[0]
        lon += location[1]
    lat = lat / len(locations)
    lon = lon / len(locations)
    mid_point = (lat, lon)

    # Calculating the distace from each location to mid_point
    distances = [distance.distance(x, mid_point).meters for x in locations]
    dist = max(distances) + 200

    #Generating the graph
    graph = ox.graph_from_point(mid_point, dist)
    graph_map = ox.plot_graph_folium(graph,
                                     popup_attribute='name',
                                     edge_width=0)

    # Generating the route according to the optimal order of the locations
    routes = []
    for i in range(len(optimal_path) - 1):
        l1 = locations[optimal_path[i]]
        l2 = locations[optimal_path[i + 1]]

        orig_node = ox.get_nearest_node(graph, l1)
        dest_node = ox.get_nearest_node(graph, l2)
        route = nx.shortest_path(graph,
                                 source=orig_node,
                                 target=dest_node,
                                 weight='length')
        route_graph_map = ox.plot_route_folium(graph,
                                               route,
                                               route_map=graph_map)
        routes.append(route)

    # Markers addition on the places locations.
    i = 0
    for location in optimal_path:
        folium.Marker(location=locations[location],
                      popup=i,
                      icon=folium.Icon(color='blue')).add_to(graph_map)
        i += 1

    graph_map.save('tsp_graph.html')
コード例 #12
0
    def make_folium(self, **kwargs):
        # filename = kwargs.get('filename','folium_output_.html')

        mapboxtoken = 'pk.eyJ1Ijoid2FsdGVyOTM4OCIsImEiOiJjazhzbmhocGUwMWEyM25uZDd1Z3hwYjA4In0.5JWjuw2ZyuHVzxnvNx1cfQ'
        # username_id='walter9388.ck8snlelx2cep1intbso64rza'
        username_id = 'mapbox.dark'

        self.G.graph = {
            'crs': 'WGS84',
            'name': 'unnamed',
        }

        map = folium.Map(
            location=[0, 0],
            zoom_start=12,
            tiles=None,
        )
        folium.TileLayer(
            'http://api.mapbox.com/v4/' + username_id +
            '/{z}/{x}/{y}.png?access_token=' + mapboxtoken,
            attr=
            'Mapbox | Source: InfraSense Labs | Written by Alex Waldron, 2020',
            name='Base Map',
        ).add_to(map)

        network_fg = folium.FeatureGroup(name='Distribution Mains')
        map.add_child(network_fg)
        graph_map = ox.plot_graph_folium(
            self.G,
            edge_width=1,
            edge_color='#FFFFFF',
            popup_attribute='name',
            # graph_map=map,
        )

        temp = list(graph_map._children.keys())[1:-1]
        [
            graph_map._children[temp[i]].add_to(network_fg)
            for i in range(len(temp))
        ]
        map.fit_bounds(map.get_bounds())
        folium.LayerControl().add_to(map)

        self.folium_map = map
コード例 #13
0
def plot_graph(trajectories):
    # 求出所有gps点的中心点坐标,获取中心点坐标周围的地图数据
    # TODO 利用所有点之间的最大距离作为dist
    position_list = [v['positions'] for v in list(trajectories.values())]
    all_points = np.concatenate(position_list)
    G = ox.graph_from_point(all_points[0], dist=1000)

    # ox.plot_graph(G)
    # plt.show()

    m1 = ox.plot_graph_folium(G, opacity=0)

    # 所有轨迹绘制,坐标点,轨迹线路,终点起点等
    for track_id, track_values in trajectories.items():
        # 去掉异常轨迹点
        drop_anormal_points_result = drop_anormal_point(
            track_id, track_values, max_speed_threshold=150)
        # 去掉停驻轨迹点
        remove_stop_points_result, stop_points_info, around_points_info = remove_stop_points(
            track_id,
            drop_anormal_points_result[track_id],
            min_distance_threshold=1e-5,
            min_delta_dist=0.5,
            min_delta_time=0.8)
        # 绘制停留点
        # plot_stop_marker(stop_points_info, around_points_info, m1)

        # 进行轨迹分段
        segments_result = get_trajectory_segments(
            remove_stop_points_result[track_id],
            segment_angle=90,
            segment_distance=0.5)
        segments, segments_time = segments_result["segments"], segments_result[
            "segments_time"]

        # 绘制分段结果
        plot_segments(segments, m1, track_id)

        # 绘制完整轨迹
        # plot_trajectory(remove_stop_points_result[track_id]['positions'], m1, track_id)

    filepath = "gps_data_visualize.html"
    m1.save(filepath)
コード例 #14
0
ファイル: test_osmnx.py プロジェクト: gboeing/osmnx
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)
コード例 #15
0
def plot_corner():
    """
    可视化预测可能存在路口的网格点。
    :return: None
    """
    file_name = "./cache/grid_point_struct_with_labels.pkl"

    if not os.path.exists(file_name):
        raise IOError('File %s is not found!' % file_name)

    with open(file_name, 'rb') as f:
        grid_point_struct_with_labels = pickle.load(f)

    left_up_point, right_down_point, grid_size = (-10.899355, -37.096252), (
        -10.927514, -37.043267), 100
    G = ox.graph_from_point(left_up_point, dist=1000)
    m1 = ox.plot_graph_folium(G, opacity=0)

    plot_points_with_cluster_label(grid_point_struct_with_labels, m1,
                                   left_up_point, grid_size)

    filepath = "test.html"
    m1.save(filepath)
コード例 #16
0
def test_routing_folium():

    # calculate shortest path and plot as static image and leaflet web map
    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.nodes()))
    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)

    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)

    attributes = ox.utils_graph.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=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])

    graph_map = ox.plot_graph_folium(G, popup_attribute="name")
    route_map = ox.plot_route_folium(G, route)
コード例 #17
0
ファイル: backend.py プロジェクト: omrakn/satrap
def degreeCentrality(G, outPath, *args):
    """
    Compute degree centrality of a node and save the output and road network
    data in shapefile format.

    Parameters
    ----------
    G: graph
        A networkx graph
    outpath: string
        absolute path to save the output of analysis
    *args: string
        path to save the output of analysis in html webmap format

    Returns
    -------
    ################################################################
    """

    G_proj = nx.MultiGraph(ox.project_graph(G))
    nodes, edges = ox.graph_to_gdfs(G_proj)
    nodes["x"] = nodes["x"].astype(float)

    degree_centrality = nx.degree_centrality(G_proj)
    degree = gpd.GeoDataFrame(pd.Series(degree_centrality), columns=["degree"])
    nodes_dgr = nodes.merge(degree, left_index=True, right_index=True)

    argument = [i for i in args]
    if any(argument):
        linear = cm.LinearColormap(["blue", "yellow", "red"], vmin=0, vmax=5)
        nodes_dgr['geoid'] = nodes_dgr.index.astype(str)
        lat = list(nodes_dgr["lat"])
        lon = list(nodes_dgr["lon"])
        dgr = list(nodes_dgr["degree"])
        name = list(nodes_dgr["osmid"])

        m = ox.plot_graph_folium(G, edge_width=1.5)
        fgdgr = folium.FeatureGroup(name="Degrees of Nodes")

        classifier = pysal.viz.mapclassify.NaturalBreaks.make(k=5)
        classifications = nodes_dgr[["degree"]].apply(classifier)
        classifications.columns = ["class"]
        nodes_dgr = nodes_dgr.join(classifications)

        for lt, ln, dg, nm, cl in zip(lat, lon, dgr, name,
                                      list(nodes_dgr["class"])):
            fgdgr.add_child(
                folium.CircleMarker(location=[lt, ln],
                                    popup='Degree Centrality of the {}. \
node is {:.5f}'.format(str(nm), dg),
                                    radius=4,
                                    fill_color=linear(cl),
                                    color="grey",
                                    fill_opacity=1,
                                    weight=0.5))

        # fgavg.add_child(marker_cluster)
        m.add_child(fgdgr)
        # m.add_child(linear)
        m.save(argument[0])

        ox.save_graph_shapefile(G_proj, filename="network", folder=outPath)
        nodes_dgr.to_file(outPath + "/degree_centrality.shp")
        return "I"
    else:
        ox.save_graph_shapefile(G_proj, filename="network", folder=outPath)
        nodes_dgr.to_file(outPath + "/degree_centrality.shp")
        return "G"
コード例 #18
0
import osmnx as ox
import folium
import pickle
G = ox.graph_from_address('Inner Harbor, Baltimore, Maryland, USA', network_type='drive')
pickle.dump(G, open('harbor.pkl', 'wb'))

graph_map = ox.plot_graph_folium(G, popup_attribute='name', edge_width=2)

graph_map.save('harbor.html')
コード例 #19
0
import folium

from api_keys import here_app_id, here_app_code, google_api_key

%load_ext autoreload
%autoreload


streets_w = get_streets('Lörrach, Germany', 'walk')
city_name = 'Lörrach, Germany'
street_type = 'drive'
city_boundary = ox.gdf_from_place(city_name).geometry.iloc[0]
drive_net = ox.graph_from_polygon(city_boundary, network_type=street_type)

# plot strees on folium
graph_folium = ox.plot_graph_folium(drive_net, popup_attribute='highway')
graph_folium.save('map.html')


drive_gpd = ox.graph_to_gdfs(drive_net, nodes=True, edges=False,
                             fill_edge_geometry=False, node_geometry=True)
drive_gpd_sub = drive_gpd
roads_json = drive_gpd_sub.to_json()
points = folium.features.GeoJson(roads_json)
m = folium.Map([47.6120896, 7.6607218])
m.add_children(points)
m.save('map.html')

streets_w.plot()

streets_w.size
コード例 #20
0
def graphRoute(route, ax=None):
    """check route displaying a graph"""
    G = nx.MultiDiGraph()
    G.graph['crs'] = {'init': 'epsg:4326'}
    G.graph['name'] = "local network"
    colorL = [
        'black', 'blue', 'red', 'green', 'brown', 'orange', 'purple',
        'magenta', 'olive', 'maroon', 'steelblue', 'midnightblue',
        'darkslategrey', 'crimson', 'teal', 'darkolivegreen'
    ]
    colorL = colorL + colorL
    for i, g in route.iterrows():
        G.add_node(i,
                   pos=(g[['x', 'y']]),
                   x=g['x'],
                   y=g['y'],
                   key=0,
                   potential=g['potential'],
                   active=g['active'],
                   n=g['occupancy'])
    for k, g in route.groupby("agent"):
        if k == 0: continue
        idx = list(g.index)
        if len(idx) < 2: continue
        pair_idx = [(i, j) for i, j in zip(idx[:-1], idx[1:])]
        for i, j in pair_idx:
            g1, g2 = route.loc[i], route.loc[j]
            i1, i2 = g1['geohash'], g2['geohash']
            dist = math.hypot(g1['x'] - g2['x'], g1['y'] - g2['y'])
            G.add_edge(i,
                       j,
                       key=k,
                       origin=i1,
                       destination=i2,
                       length=dist,
                       width=1,
                       speed=1,
                       color=colorL[k])
    G = ox.project_graph(G)
    colorL = [cm.get_cmap('plasma')(x) for x in np.linspace(0, 1, 6)]
    nc = ['blue' if G.nodes()[x]['active'] else 'red' for x in G.nodes()]
    nbins = min(20, len(set(route['potential'])))
    cmap = matplotlib.cm.get_cmap('plasma')
    max_pot = np.percentile(route['potential'], 95)
    nc = [cmap(x['potential'] / max_pot) for i, x in G.nodes(data=True)]
    # nc = ox.get_node_colors_by_attr(G,'potential',cmap='plasma',num_bins=nbins-2)
    ns = [20. * x['n'] for i, x in G.nodes(data=True)]
    # ec = ox.get_edge_colors_by_attr(G, attr='length')
    ec = [o['color'] for u, v, k, o in G.edges(data=True, keys=True)]
    # if len(ec) == 0: return plt.subplots(1,1)
    ew = [200. * o['length'] for u, v, k, o in G.edges(data=True, keys=True)]
    pos, lab = {}, {}
    for i, x in G.nodes(data=True):
        pos[i] = [x['lon'], x['lat']]
    for i, x in G.nodes(data=True):
        lab[i] = i
    # nx.draw_networkx_edge_labels(G,pos,edge_colors=ec)
    if ax == None:
        fig, ax = plt.subplots(1, 1)
        fig.set_size_inches(10, 6)
    # nx.draw(G,pos,node_color=nc,node_size=ns,edge_color=ec,edge_cmap=plt.cm.Reds)
    nx.draw_networkx_nodes(G,
                           pos,
                           node_color=nc,
                           node_size=ns,
                           alpha=0.1,
                           ax=ax)
    # nx.draw_networkx_labels(G,pos,lab,font_size=8,ax=ax,alpha=0.3)
    nx.draw_networkx_edges(G,
                           pos,
                           width=ew,
                           alpha=0.5,
                           edge_color=ec,
                           ax=ax,
                           edge_cmap=plt.cm.Reds)
    ax.set_axis_off()
    ax.set_xlim(np.percentile(route['x'], [1, 99]))
    ax.set_ylim(np.percentile(route['y'], [1, 99]))
    return ax
    if False:
        gdf_edges = ox.graph_to_gdfs(G, nodes=False, fill_edge_geometry=True)
        graph_map = ox.plot_graph_folium(G,
                                         tiles='stamenterrain',
                                         edge_color=ec,
                                         edge_width=2)
        origin_node = list(G.nodes())[0]
        destination_node = list(G.nodes())[-1]
        route = nx.shortest_path(G, origin_node, destination_node)
        route_map = ox.plot_route_folium(G, route)
        graph_map.save(baseDir + "www/gis/folium.html")

        ox.make_folium_polyline(gdf_edges, ew, ew, popup_attribute=None)
        plot_graph_folium(gdf_edges,
                          graph_map=None,
                          popup_attribute=None,
                          tiles='cartodbpositron',
                          zoom=1,
                          fit_bounds=True,
                          edge_width=5,
                          edge_opacity=1)
    return fig, ax
コード例 #21
0
def plot_corner_by_cluster(trajectories):
    """
    根据轨迹信息挖掘出路口点。
    :param trajectories: 轨迹信息
    :return: None
    """
    position_list = [v['positions'] for v in list(trajectories.values())]
    all_points = np.concatenate(position_list)
    G = ox.graph_from_point(all_points[0], dist=1000)
    m1 = ox.plot_graph_folium(G, opacity=0)

    all_segments, all_segments_time = [], []
    # 得到所有轨迹的分段结果
    for track_id, track_values in trajectories.items():
        # 去掉异常轨迹点
        drop_anormal_points_result = drop_anormal_point(
            track_id, track_values, max_speed_threshold=150)
        # 去掉停驻轨迹点
        remove_stop_points_result, stop_points_info, around_points_info = remove_stop_points(
            track_id,
            drop_anormal_points_result[track_id],
            min_distance_threshold=1e-5,
            min_delta_dist=0.5,
            min_delta_time=0.8)
        # 进行轨迹分段
        segments_result = get_trajectory_segments(
            remove_stop_points_result[track_id],
            segment_angle=90,
            segment_distance=0.5)
        segments, segments_time = segments_result["segments"], segments_result[
            "segments_time"]
        all_segments.extend(segments)
        all_segments_time.extend(segments_time)

        # 绘制分段结果
        # plot_segments(segments, m1, track_id)

    # 得到带有速度矢量的点集
    points_with_velocity = get_points_with_velocity(all_segments,
                                                    all_segments_time)
    # plot_points_with_velocity(points_with_velocity, m1)

    # 绘制指定区域网格
    left_up_point, right_down_point, grid_size = (-10.899355, -37.096252), (
        -10.927514, -37.043267), 100
    plot_grid(left_up_point, right_down_point, grid_size, m1)

    # 按每个网格一个颜色绘制路径点
    grid_point_struct = get_grid_point_struct(
        left_up_point,
        right_down_point,
        grid_size=grid_size,
        points_with_velocity=points_with_velocity)

    if not os.path.exists('./cache/grid_point_struct.pkl'):
        with open('./cache/grid_point_struct.pkl', 'wb') as f:
            pickle.dump(grid_point_struct, f)

    # plot_points_in_which_grid(grid_point_struct, m1)

    # 按照轨迹点聚类结果进行绘制
    grid_points_struct_with_labels = cluster_grid_points(grid_point_struct)

    if not os.path.exists('./cache/grid_point_struct_with_labels.pkl'):
        with open('./cache/grid_point_struct_with_labels.pkl', 'wb') as f:
            pickle.dump(grid_points_struct_with_labels, f)

    plot_points_with_cluster_label(grid_points_struct_with_labels, m1,
                                   left_up_point, grid_size)

    filepath = "find_corner.html"
    m1.save(filepath)
コード例 #22
0
def plot_html(track,
              track_corr=[],
              track_color="black",
              track_corr_color="#CD473E",
              track_size=2,
              track_corr_size=2,
              route_corr=[],
              route_size=2,
              route_corr_size=2,
              route_color="black",
              route_corr_color="#CD473E",
              route_opacity=.7,
              route_corr_opacity=.7,
              proj=False,
              proj_color="#CD473E",
              proj_size=1,
              proj_alpha=.5,
              show_graph=False,
              graph=None,
              file_name="my_map.html",
              save=True):
    """
    

    Parameters
    ----------
    track : TYPE
        DESCRIPTION.
    track_corr : TYPE, optional
        DESCRIPTION. The default is [].
    track_color : TYPE, optional
        DESCRIPTION. The default is "black".
    track_corr_color : TYPE, optional
        DESCRIPTION. The default is "darkcyan".
    track_size : TYPE, optional
        DESCRIPTION. The default is 2.
    track_corr_size : TYPE, optional
        DESCRIPTION. The default is 2.
    route_corr : TYPE, optional
        DESCRIPTION. The default is [].
    route_size : TYPE, optional
        DESCRIPTION. The default is 2.
    route_corr_size : TYPE, optional
        DESCRIPTION. The default is 2.
    route_color : TYPE, optional
        DESCRIPTION. The default is "black".
    route_corr_color : TYPE, optional
        DESCRIPTION. The default is "darkcyan".
    route_opacity : TYPE, optional
        DESCRIPTION. The default is .6.
    route_corr_opacity : TYPE, optional
        DESCRIPTION. The default is .6.
    proj : TYPE, optional
        DESCRIPTION. The default is False.
    proj_color : TYPE, optional
        DESCRIPTION. The default is "skyblue".
    proj_size : TYPE, optional
        DESCRIPTION. The default is 1.
    proj_alpha : TYPE, optional
        DESCRIPTION. The default is 1.
    show_graph : TYPE, optional
        DESCRIPTION. The default is False.
    graph : TYPE, optional
        DESCRIPTION. The default is None.
    file_name : TYPE, optional
        DESCRIPTION. The default is "my_map.html".
    save : TYPE, optional
        DESCRIPTION. The default is True.

    Returns
    -------
    my_map : TYPE
        DESCRIPTION.

    """

    med_lat = track[len(track) // 2][0]
    med_lon = track[len(track) // 2][1]

    # Load map centred on central coordinates
    my_map = folium.Map(location=[med_lat, med_lon], zoom_start=20)

    if show_graph or graph is not None:
        if graph is None:
            graph = matching.graph_from_track(track, network='drive')
        my_map = ox.plot_graph_folium(graph,
                                      popup_attribute='name',
                                      edge_width=1,
                                      edge_color='darkgrey')

    if proj:
        for i in range(len(track)):
            folium.PolyLine([(track[i][0], track[i][1]),
                             (track_corr[i][0], track_corr[i][1])],
                            color=proj_color,
                            weight=proj_size,
                            opacity=proj_alpha).add_to(my_map)
    # If the route is given in input, plot both (original and corrected)
    if len(route_corr) > 0:
        # add lines
        folium.PolyLine(track,
                        color=route_color,
                        weight=route_size,
                        opacity=route_opacity).add_to(my_map)
        folium.PolyLine(route_corr,
                        color=route_corr_color,
                        weight=route_corr_size,
                        opacity=route_corr_opacity).add_to(my_map)

    # add dots
    for i in range(len(track)):
        folium.CircleMarker(location=[track[i][0], track[i][1]],
                            radius=track_size,
                            weight=1,
                            color=track_color,
                            fill=True,
                            fill_opacity=1).add_to(my_map)
    for i in range(len(track_corr)):
        folium.CircleMarker(location=[track_corr[i][0], track_corr[i][1]],
                            radius=track_corr_size,
                            weight=1,
                            color=track_corr_color,
                            fill=True,
                            fill_opacity=1).add_to(my_map)

    # add the OSM light grey background
    folium.TileLayer('cartodbpositron').add_to(my_map)

    # plot the legend in the HTML page
    legend_html = """
    <div style="position: fixed;
                width: 210px;
                top: 10px; right: 10px;
                border: 2px solid lightgrey;
                border-radius: 4px;
                background-color: rgba(255, 255, 255, 0.85);
                z-index:9999;
                font-size: 15px; color: slategrey;
     ">
         &nbsp; <span style="font-weight: bold">Legend</span>
         <br>
             &nbsp; Original Point &nbsp;
             <i class="fa fa-circle"
                 style="float: right;
                         margin-right: 19px; margin-top: 4px;
                         color: black">
             </i>
         <br>
             &nbsp; Projected Point &nbsp;
             <i class="fa fa-circle"
                 style="float: right;
                         margin-right: 19px; margin-top: 4px;
                         color: #CD473E">
             </i>
         <br>
             &nbsp; Projection &nbsp;
             <div class="line"
                 style="float: right;
                         margin-right: 10px; margin-top: 10px;
                         width: 30px; height: 2px;
                         background-color: #CD473E">
             </div>
    </div>
    """
    my_map.get_root().html.add_child(folium.Element(legend_html))

    if save:
        my_map.save(file_name)
        # Plot in new tab
        webbrowser.open(file_name, new=2)  # open in new tab

    return my_map
コード例 #23
0
    def submit(self):

        city = str(self.ui.comboCity.currentText())
        month = str(self.ui.comboMonth.currentText())
        day = str(self.ui.comboDay.currentText())
        city1, month1 = get_filters(city, month)
        global df, df5, df6, gender_mean, female_mean, male_mean, user_subs, user_cust, user
        global ut_subs, ut_cust, ut_subs_fem, ut_subs_male, ut_cust_fem, ut_cust_male
        df, df5 = load_data(city1, month1, day)

        try:
            now = datetime.datetime.now()
            df['age'] = now.year - df['Birth Year']
        except:
            df['age'] = 0
            pass
        try:
            female_mean = df[df['Gender'] == 'Female'].groupby(
                'Start Station').mean()
            female_mean['count'] = df[df['Gender'] == 'Female'].groupby(
                'Start Station')['Id'].count()
            female_mean.drop(columns=[
                'latitude_start', 'longitude_start', 'latitude_end',
                'longitude_end'
            ],
                             inplace=True)
            male_mean = df[df['Gender'] == 'Male'].groupby(
                'Start Station').mean()
            male_mean['count'] = df[df['Gender'] == 'Male'].groupby(
                'Start Station')['Id'].count()
            gender_mean = male_mean.merge(female_mean,
                                          how='outer',
                                          left_index=True,
                                          right_index=True,
                                          suffixes=(' male', ' female'))
            gender_mean['count total'] = gender_mean[
                'count female'] + gender_mean['count male']
            gender_mean['female percent'] = (gender_mean['count female'] /
                                             gender_mean['count total']) * 100
        except:
            pass

        try:
            user_subs = df[df['User Type'] == 'Subscriber'].groupby(
                'Start Station').mean()
            user_subs['count'] = df[df['User Type'] == 'Subscriber'].groupby(
                'Start Station')['Id'].count()
            user_cust = df[df['User Type'] == 'Customer'].groupby(
                'Start Station').mean()
            user_cust['count'] = df[df['User Type'] == 'Customer'].groupby(
                'Start Station')['Id'].count()

            user_cust.drop(columns=[
                'latitude_start', 'longitude_start', 'latitude_end',
                'longitude_end'
            ],
                           inplace=True)
            user = user_subs.merge(user_cust,
                                   how='outer',
                                   left_index=True,
                                   right_index=True,
                                   suffixes=(' subs', ' cust'))
            user.dropna(subset=['latitude_start'], inplace=True)
            user['count subs'] = user['count subs'].fillna(0)
            user['count cust'] = user['count cust'].fillna(0)
            user['count total'] = user['count subs'] + user['count cust']
            user['subs percent'] = (user['count subs'] /
                                    user['count total']) * 100
        except:
            pass

        # Statistics
        commonMonth, commonDay, commonHour = time_stats(df, city1, month1, day)
        commonStartStation, commonEndStation, G, route, dataFr, distRec = station_stats(
            df)
        ttt, ttm = trip_duration_stats(df)
        ut_subs, ut_cust, ut_subs_fem, ut_subs_male, ut_cust_fem, ut_cust_male = user_stats(
            df)
        df6 = dfStats(df, df5, dataFr)

        tstat = []
        tstat.append('Statistics on the most frequent times of travel')
        tstat.append('The Most Common Month : ' + str(commonMonth))
        tstat.append('The Most Common Day : ' + str(commonDay))
        tstat.append('The Most Common Hour : ' + str(commonHour))

        tstat.append('\nStatistics on the most popular stations and trip')
        tstat.append('The Most Common Used Start Station : ' +
                     str(commonStartStation))
        tstat.append('The Most Common Used End Station : ' +
                     str(commonEndStation))

        tstat.append('\nStatistics on the most popular combination stations')
        tstat.append('The Most Common Combination of Start-End Station : ' +
                     str(dataFr['Start Station'].iloc[0]) + ' and ' +
                     str(dataFr['End Station'].iloc[0]))
        tstat.append(
            'The Most Common Combination of Start-End Station Track (km): ' +
            str(distRec[0]))
        tstat.append(
            'The Most Common Combination of Start-End Station Lineal Distance (km): '
            + str(dataFr['Dist_lin_km'].iloc[0]))

        tstat.append('\nStatistics on the total and average trip duration')
        tstat.append('The total travel time : ' + str(ttt))
        tstat.append('The mean travel time : ' + str(ttm))

        tstat.append('\nDisplays statistics on bikeshare users and gender')
        tstat.append('The counts of user types "Subscriber" : ' +
                     str(len(ut_subs)))
        tstat.append('The counts of user types "Customer" : ' +
                     str(len(ut_cust)))
        try:
            tstat.append(
                'The counts of user types "Subscriber" and Gender "Female": ' +
                str(len(ut_subs_fem)))
            tstat.append(
                'The counts of user types "Subscriber" and Gender "Male": ' +
                str(len(ut_subs_male)))
            tstat.append(
                'The counts of user types "Customer" and Gender "Female": ' +
                str(len(ut_cust_fem)))
            tstat.append(
                'The counts of user types "Customer" and Gender "Male": ' +
                str(len(ut_cust_male)))
        except:
            pass
        try:
            tstat.append(
                '\nDisplay earliest, most recent, and most common year of birth'
            )
            tstat.append('The earliest year of birt: ' +
                         str(int(df['Birth Year'].min())))
            tstat.append('The most recent year of birt: ' +
                         str(int(df['Birth Year'].max())))
            tstat.append('The most common year of birt: ' +
                         str(int(df['Birth Year'].mode())))
        except:
            pass

        self.ui.textEdit.setText("\n".join(tstat))

        # Route Map
        graph_map = ox.plot_graph_folium(G,
                                         popup_attribute='name',
                                         edge_width=2,
                                         edge_color="#85d3de",
                                         zoom=8)
        try:
            route_graph_map = ox.plot_route_folium(G,
                                                   route,
                                                   route_map=graph_map,
                                                   popup_attribute='length',
                                                   zoom=8)
        except:
            route_graph_map = graph_map

        locations = df6[['latitude', 'longitude']]
        locationlist = locations.values.tolist()
        for point in range(0, len(df6)):
            Marker(locationlist[point],
                   popup=df6[['Station', 'name'
                              ]].iloc[point].values).add_to(route_graph_map)
        filepath = 'CommonStation_ShortestPath.html'
        route_graph_map.save(filepath)
        w = self.ui.webEngineView_1
        w.resize(740, 540)
        self.url = QtCore.QUrl.fromLocalFile(str(pathname) + '/' + filepath)
        w.load(self.url)
        w.show()

        ##Bike Stations
        maps = Map([df5['latitude'].mean(), df5['longitude'].mean()],
                   zoom_start=10,
                   control_scale=True,
                   tiles="OpenStreetMap")
        locations2 = df5[['latitude', 'longitude']]
        locationlist2 = locations2.values.tolist()
        group2 = FeatureGroup(name="Bike Stations")
        for point in range(0, len(locationlist2)):
            Marker(locationlist2[point],
                   popup=df5[['Station', 'latitude',
                              'longitude']].iloc[point].values).add_to(group2)
        group2.add_to(maps)
        LayerControl().add_to(maps)
        data = io.BytesIO()
        maps.save(data, close_file=False)
        m = self.ui.webEngineView_2
        m.setHtml(data.getvalue().decode())
        m.resize(740, 540)
        maps.save("BikeStations.html")
        m.show()
        maps.save(data, close_file=True)

        # initial map tab
        maps = Map([df5['latitude'].mean(), df5['longitude'].mean()],
                   zoom_start=10,
                   control_scale=True,
                   tiles="OpenStreetMap")
        LayerControl().add_to(maps)
        data = io.BytesIO()
        maps.save(data, close_file=False)
        m = self.ui.webEngineView_3
        m.setHtml(data.getvalue().decode())
        m.resize(740, 520)
        m.show()
        maps.save(data, close_file=True)

        try:
            # initial Graphics
            self.figure.clear()
            labels = 'Male', 'Female'
            sizes = [
                len(df[df['Gender'] == 'Male']),
                len(df[df['Gender'] == 'Female'])
            ]
            explode = (0, 0.1)
            ax1 = self.figure.add_subplot(111)
            ax1.pie(sizes,
                    explode=explode,
                    labels=labels,
                    autopct='%1.1f%%',
                    startangle=90)
            ax1.axis('equal')
            self.canvas.draw()
            self.show
        except:
            pass

        # setting value to progress bar
        for i in range(101):
            time.sleep(0.04)
            self.ui.progressBar.setValue(i)