从 OSMnx 为 NetworKX 生成加权图

Generate weighted graph from OSMnx for NetworKX

我想生成一个带有加权边的 NetworKX 图,这样每条边的权重将是它的 distance * driving speed on this road(if it exists) 或者如果行驶速度未知,高速公路 100*distance60*distance适用于城市道路。

除了 之外,我找不到与我的需求相似的 post,但必须有一种方法可以自动完成。

我的目标是找到从 A 点到 B 点之间行驶时间最短(使用 Dijkstra)的路径,这是我到现在所做的:

l1 = (A_lat,A_lon)
G = ox.graph_from_point(l1,distance= 100)
l1_node_id = ox.get_nearest_node(G,l1)   # Find closest node ID    

l2 = (B_lat,B_lon)
G = ox.graph_from_point(l2,distance = 100)
l2_node_id = ox.get_nearest_node(G,l2)   # Find closest node ID

dist = vincenty(l1, l2).meters    # The distance between l1 and l2


p1 = ((l1[0] + l2[0])/2,(l1[1]+l2[1])/2)    #The mid point between l1 and l2
dist = vincenty(l1, l2).meters              #The distance between l1 and l2
G = ox.graph_from_point(p1,distance = dist)
path = nx.shortest_path(G, l1_node_id, l2_node_id)   #Find the shortest path for cutoff

for path in nx.all_simple_paths(G, source=l1_node_id, target=l2_node_id,cutoff = len(path)):
    #Here I want to checke if "path" is the shortest path but right now it is without weight

documentation 他们写的 weight 应该是一个字符串,但我该怎么做?

TIA

fast=['motorway','trunk','primary','secondary','motorway_link','trunk_link','primary_link','secondary_link','escape','track']
slow = ['tertiary', 'residential','tertiary_link','living_street']
other = ['unclassified','road','service']

def find_speed(row):
    if row['highway'] in fast:
        return 100/3.6
    elif row['highway'] in slow:
        return 50/3.6
    elif row['highway'] in other:
        return 70/3.6
    else:
        return 5/3.6


nodes, edges = ox.graph_to_gdfs(G)
edges = edges.assign(speed=edges.apply(find_speed, axis=1))
edges['wgt'] = edges['length']/edges['speed']

UG = ox.gdfs_to_graph(nodes, edges)


for path in nx.all_shortest_paths(UG, source=l1_node_id, target=l2_node_id,weight = 'wgt'):

calculate edge travel times 的功能从 OSMnx v0.13.0 开始可用。然后,您可以使用这些边行驶时间属性按行驶时间而不是距离求解网络最短路径。默认情况下,它会估算缺少来自 OSM 的 maxspeed 数据的边缘的速度,然后将行程时间计算为长度和速度的函数。但是你可以为不同的道路类型传递你自己的自定义速度:

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

G = ox.graph_from_place('Piedmont, CA, USA', network_type='drive')

# Impute speeds on edges missing data.
G = ox.add_edge_speeds(G)

# Or assign speeds to edges missing data based on dict values.
# For edges with highway type not in dict, impute speeds.
hwy_speeds = {'motorway': 100,
              'trunk': 100,
              'residential': 60,
              'tertiary': 60} #etc
G = ox.add_edge_speeds(G, hwy_speeds)

# Calculate shortest path by travel time.
G = ox.add_edge_travel_times(G)
orig, dest = list(G)[0], list(G)[-1]
route = nx.shortest_path(G, orig, dest, weight='travel_time')