【问题标题】:Save and re-load a weighted graph from OSMnx for NetworKX从 OSMnx for NetworKX 保存并重新加载加权图
【发布时间】:2020-12-16 21:35:29
【问题描述】:

我正在使用 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, node_start, node_stop, weight = 'w3')

现在我想将 G 保存到磁盘并重新打开它,以便稍后执行更多导航任务。但保存后:

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

然后重新打开它:

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

我的自定义属性 w3 消失了。我在文档中关注了instructions,但没有运气。感觉好像我错过了一些非常明显的东西,但我不明白它是什么..

【问题讨论】:

  • 尝试使用edge_attrs参数

标签: networkx osmnx


【解决方案1】:

使用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')

【讨论】:

  • 是的,属性就在那里!但是我的字典的值现在被视为字符串,而在将它们保存在浮动之前。我围绕提取字典并将字符串转换为浮点数进行了工作,但我在徘徊这种变化的原因是什么。
  • OSMnx 必须做出一些让步,才能优雅地将所有内容序列化为 graphml 格式。字符串化就是其中之一。
猜你喜欢
  • 2020-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多