微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 networkx 和 osmnx 在“结构化文件”中保存最短路径 编辑编辑 2 - 来自 @lhoupert

如何解决使用 networkx 和 osmnx 在“结构化文件”中保存最短路径 编辑编辑 2 - 来自 @lhoupert

我有一个多维图 G一个使用 nx.shortest_path 方法计算的列表 best_path

多亏了这个 stackexchange post,我使用 json.dumps 将路线的 x 和 y 坐标导出到一个简单的 ascii 文件中:

parts = []
for i in best_path:
    node = G.nodes[i]
    parts.append([float(node["y"]),float(node["x"])])
json_route = json.dumps(parts)

with open(current_dir + "test_best_path.json","w",encoding="utf-8") as f:
    f.write(json.dumps(parts,ensure_ascii=False))

现在我正在寻找一种解决方案,我可以将这条最佳路线保存到一个更“结构化”的文件中,我还可以在其中添加更多节点属性(例如 yaml 或 graphml)。 networkxosmnx 中是否已存在某些内容

谢谢

解决方法

我的建议是创建路径的诱导子图,即

shortest_path_graph = G.subgraph(best_path) #.copy()

并且可能会创建一个副本,如果您要执行更改,则不应反映在原始图表中。

然后您可以应用任何更改并将任何更改添加到 shortest_path_graph,例如,添加节点属性,或删除现有的不需要的信息。之后,您可以使用 networkx save methods 中的任何一个保存您的结果,例如 GraphMLYAML 以遵循您的建议。如果您想在不同的 PC 之间共享文件,我强烈建议您避免使用 pickle。

编辑

由于上述过程会丢失有关路径中节点顺序的信息,或者换句话说,我希望上述过程返回一行,即在有向情况下,一个节点没有度数为 1,度数为 0,另一个入度为 1,出度为 0 的节点,度数 = 1 = 出度的所有其他节点。

为了保存路径中节点的顺序,您可以创建一个新的属性

for i,node in enumerate(best_path):
    shortest_path_graph.nodes[node]["path counter"] = i

或使用 nx.relabel_nodes 修改节点 ID。

编辑 2 - 来自 @lhoupert

我喜欢 nx.relabel_nodes 的解决方案,它不会创建新属性。 下面是一个实现示例:

# Relabel nodes id to sort them according to the path orientation 
mapping_dict = {num: x for x,num in enumerate(best_path)} 
H = nx.relabel_nodes(G_shortest_path,mapping_dict) 

# Sort the graph nodes and edges according to new ID  
H2 = nx.Graph()  # or nx.MultiDiGraph()
H2.add_nodes_from(sorted(H.nodes(data=True)))  
H2.add_edges_from(H.edges(data=True))   

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。