当您想要对大型研究区域(例如整个地区或整个国家)进行建模时,存在固有的权衡:1) 模型精度 vs 2) 区域大小 vs 3) 内存/速度。您需要权衡这三者之一。
首先,您可以对较粗粒度的网络进行建模,例如仅对该地区/国家/地区的主要道路进行建模,而不是对数百万条细粒度的住宅街道和路径进行建模。对于第二个,您可以研究较小的区域。对于第三种,您可以配置一台具有大量内存的计算机,然后让脚本运行一段时间以完成该过程。您权衡什么将取决于您自己的分析需求。
在下面的示例代码中,我选择权衡#1:我通过高速公路和主干道对该地区(西米德兰兹)进行了建模。考虑到不同的分析目标,您可能会权衡其他事情。创建模型后,我随机sample https://osmnx.readthedocs.io/en/stable/osmnx.html#osmnx.utils_geo.sample_points1000 个出发点和目的地经纬度点,将它们捕捉到最近的节点 https://osmnx.readthedocs.io/en/stable/osmnx.html#osmnx.distance.nearest_nodes并求解图中的最短路径 https://osmnx.readthedocs.io/en/stable/osmnx.html#osmnx.distance.shortest_path by 旅行时间 https://osmnx.readthedocs.io/en/stable/osmnx.html#osmnx.speed.add_edge_travel_times(占speed https://osmnx.readthedocs.io/en/stable/osmnx.html#osmnx.speed.add_edge_speeds限制)与多处理。
import osmnx as ox
# get boundaries of West Midlands region by its OSM ID
gdf = ox.geocode_to_gdf('R151283', by_osmid=True)
polygon = gdf.iloc[0]['geometry']
# get network of motorways and trunk roads, with speed and travel time
cf = '["highway"~"motorway|motorway_link|trunk|trunk_link"]'
G = ox.graph_from_polygon(polygon, network_type='drive', custom_filter=cf)
G = ox.add_edge_speeds(G)
G = ox.add_edge_travel_times(G)
# randomly sample lat-lng points across the graph
origin_points = ox.utils_geo.sample_points(ox.get_undirected(G), 1000)
origin_nodes = ox.nearest_nodes(G, origin_points.x, origin_points.y)
dest_points = ox.utils_geo.sample_points(ox.get_undirected(G), 1000)
dest_nodes = ox.nearest_nodes(G, dest_points.x, dest_points.y)
%%time
# solve 1000 shortest paths between origins and destinations
# minimizing travel time, using all available CPUs
paths = ox.shortest_path(G, origin_nodes, dest_nodes, weight='travel_time', cpus=None)
# elapsed time: 9.8 seconds
为了更快地建模,您可以从 .osm XML 加载网络数据file https://osmnx.readthedocs.io/en/stable/osmnx.html#osmnx.graph.graph_from_xml而不必多次调用 Overpass API。默认情况下,OSMnx 将您的查询区域划分为 50km x 50km 的块,然后每次对每个块查询 Overpass,以免超出服务器的每次查询内存限制。你可以配置 https://osmnx.readthedocs.io/en/stable/osmnx.html#osmnx.utils.config this max_query_area_size
参数以及服务器内存分配(如果您更喜欢使用 OSMnx 的 API 查询函数而不是其来自文件的功能)。