我有一个多维图形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)。networkx或osmnx中是否已经存在某些内容
谢谢
发布于 2021-04-07 17:32:19
我的建议是创建你的路径的导出子图,即,
shortest_path_graph = G.subgraph(best_path) #.copy()如果您想要执行更改,则可以创建一个副本,而这些更改不应反映在原始图形中。
然后,您可以应用任何更改并向shortest_path_graph添加任何更改,例如,添加节点属性或删除现有的不需要的信息。之后,您可以使用任何networkx save methods保存您的结果,例如GraphML或YAML,以遵循您的建议。如果您想在不同的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修改节点ids。
编辑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)) https://stackoverflow.com/questions/66982521
复制相似问题