从OSMnx中为NetworKX保存并重新加载加权图

问题描述

我正在使用OSMnx获取图形并添加一个新的边缘属性(w3),以表示每个边缘的自定义权重。然后,我可以使用NetworkX和'length','w2'成功找到2个点之间的2条不同的最短路径。一切正常,这是我的代码

G = ox.graph_from_place(PLACE,network_type='all_private',retain_all = True,simplify=True,truncate_by_edge=False) ``` 
w3_dict = dict((zip(zip(lu,lv,lk),lw3)))
nx.set_edge_attributes(G,w3_dict,"w3") 
route_1 = nx.shortest_path(G,node_start,node_stop,weight = 'length')
route_2 = nx.shortest_path(G,weight = 'w3')

现在,我想将G保存到磁盘并重新打开,以在以后执行更多导航任务。但是,使用以下命令保存后:

ox.save_graph_xml(G,filepath='DATA/network.osm')

并使用以下命令重新打开它:

G = ox.graph_from_xml('DATA/network.osm')

我的自定义属性w3已消失。我遵循了文档中的instructions,但是没有运气。感觉好像我在漏掉一些确实很明显的东西,但是我不明白它是什么。

解决方法

使用ox.save_graphmlox.load_graphml函数将功能齐全的OSMnx / NetworkX图形保存到磁盘或从磁盘加载以供以后使用。保存xml函数仅用于允许序列化为需要.osm的应用程序的应用程序,并且存在很多约束条件。

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

# get a graph,set 'w3' edge attribute
G = ox.graph_from_place('Piedmont,CA,USA',network_type='drive')
nx.set_edge_attributes(G,100,'w3')

# save graph to disk
ox.save_graphml(G,'./data/graph.graphml')

# load graph from disk and confirm 'w3' edge attribute is there
G2 = ox.load_graphml('./data/graph.graphml')
nx.get_edge_attributes(G2,'w3')