【发布时间】:2022-01-06 13:55:27
【问题描述】:
在追求 python 的快速图形库的过程中,我偶然发现了retworkx, 我正在尝试达到与使用networkx 相同的(期望的)结果。
在我的 networkx 代码中,我用一组加权边实例化了一个有向图对象, 激活它的内置 shortest_path(基于 dijkstra),并接收该路径。我通过使用以下代码来做到这一点:
graph = nx.DiGraph()
in_out_weight_triplets = np.concatenate((in_node_indices, out_node_indices,
np.abs(weights_matrix)), axis=1)
graph.add_weighted_edges_from(in_out_weight_triplets)
shortest_path = nx.algorithms.shortest_path(graph, source=n_nodes, target=n_nodes + 1,
weight='weight')
当尝试使用 reworkx 重现相同的最短路径时:
graph = rx.PyDiGraph(multigraph=False)
in_out_weight_triplets = np.concatenate((in_node_indices.astype(int),
out_node_indices.astype(int),
np.abs(weights_matrix)), axis=1)
unique_nodes = np.unique([in_node_indices.astype(int), out_node_indices.astype(int)])
graph.add_nodes_from(unique_nodes)
graph.extend_from_weighted_edge_list(list(map(tuple, in_out_weight_triplets)))
shortest_path = rx.digraph_dijkstra_shortest_paths(graph, source=n_nodes,
target=n_nodes + 1)
但是对于使用带有浮动权重的三元组,我得到了错误:
"C:\Users\tomer.d\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3437, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-23-752a42ce79d7>", line 1, in <module> graph.extend_from_weighted_edge_list(list(map(tuple, in_out_weight_triplets))) TypeError: argument 'edge_list': 'numpy.float64' object cannot be interpreted as an integer ```
当我尝试将权重乘以 10^4 并将它们转换为整数的解决方法时:
np.concatenate((in_node_indices.astype(int), out_node_indices.astype(int),
(np.abs(weights_matrix) * 10000).astype(int), axis=1)
所以我应该不会减轻体重的微妙之处 - 不会引发错误, 但是最短路径的输出与我使用networkx时得到的不同。
我知道权重不一定是这里的问题, 但他们目前是我的主要嫌疑人。
任何其他建议都会被接受。
【问题讨论】:
标签: python python-3.x networkx shortest-path digraphs