根据地理参考多边形裁剪 networkx 图

Clipping a networkx graph according to georeferenced polygon

我是 运行 一个循环,它为 GeoDataFrames(城市)列表的每一行(社区)计算 networkx.classes.multidigraph.MultiDiGraph。然后它为每一行计算一些统计数据并将文件写出到磁盘。问题是循环计算起来非常长,因为图形是为每一行计算的。

我想加快循环的方法是计算整个 GeoDataFrame 的图形,然后将图形裁剪到每一行(每一行都有一个多边形)。您可以使用 geopandas.clip 为 GeoSeries 执行此操作。然而,对于 networkx 图,似乎不存在等同于 geopandas.clip 的东西。

这是我的初始代码:

import osmnx as ox
import pandas as pd
import geopandas as gpd
import os

path="C:/folder/"
files=[os.path.join(path, f) for f in os.listdir(path)]

for i in range(0,2):
    city=gpd.read_file(files[i])
    circ=[]

    for i in range(0,181):
        graph_for_row=ox.graph_from_polygon(city.geometry[i])
        #above is the long command
        stat = ox.basic_stats(graph_for_row)
        circ.append(stat['circuity_avg'])

    circ=pd.Series(circ)
    merged.append(pd.concat([city, circ], axis=1))

for i in (range(0,len(merged))):
    with open(geofiles[i], 'w') as f:
        f.write(merged[i].to_json())

这是我的目标新循环:

clipped_graph=[]

for i in range(0,2):
    city=gpd.read_file(files[i])
    whole_city=city.unary_union
    graph=ox.graph_from_polygon(whole_city)
    clipped_graph.append(gpd.clip(graph, city.geometry))#this line 
    #does not work since 'graph' is a networkx object, not
    #a GeoDataFrame or GeoSeries
    circ=[]

    for i in range(0,181)
        stat = ox.basic_stats(clipped_graph[i])
        circ.append(stat['circuity_avg'])

    circ=pd.Series(circ)
    merged.append(pd.concat([city, circ], axis=1))

for i in (range(0,len(merged))):
    with open(geofiles[i], 'w') as f:
        f.write(merged[i].to_json())

您可以使用您的个人多边形(在空间上)与图形节点相交,然后使用这些节点产生 subgraph。 MWE:

import osmnx as ox
ox.config(use_cache=True, log_console=True)

# load a shapefile of polygons as geodataframe using geopandas
# here i just get 3 cities from OSM to make example reproducible without a shapefile
places = ['Cudahy, CA, USA', 'Bell, CA, USA', 'Maywood, CA, USA']
gdf = ox.gdf_from_places(places)

# get a graph of the union of their boundaries, then extract nodes as geodataframe
G = ox.graph_from_polygon(gdf.unary_union, network_type='drive')
nodes = ox.graph_to_gdfs(G, edges=False)

# for each city polygon, find intersecting nodes then induce subgraph
for polygon in gdf['geometry']:
    intersecting_nodes = nodes[nodes.intersects(polygon)].index
    G_sub = G.subgraph(intersecting_nodes)
    fig, ax = ox.plot_graph(G_sub)