使用 NetworkX all_simple_paths 给出 AttributeError
Using NetworkX all_simple_paths gives AttributeError
我有一个具有以下形式的邻接矩阵的图(一个 6 节点图,其中自边为 0,no_connections 标记为 Inf,其他边为 1):
{1: {1: 0, 2: 1, 3: inf, 4: inf, 5: inf, 6: inf}, 2: {1: 1, 2: 0, 3: inf, 4: 1, 5: 1, 6: inf}, 3: {1: inf, 2: inf, 3: 0, 4: 1, 5: inf, 6: inf}, 4: {1: inf, 2: 1, 3: 1, 4: 0, 5: 1, 6: 1}, 5: {1: inf, 2: 1, 3: inf, 4: 1, 5: 0, 6: inf}, 6: {1: inf, 2: inf, 3: inf, 4: 1, 5: inf, 6: 0}}
我想使用 networkx 包的 all_simple_paths 函数来查找从源到目的地的所有简单路径,但是当我调用
nx.all_simple_paths(graph, src, dst)
它给出:
AttributeError: 'dict' 对象没有属性 'is_multigraph'
我目前没有任何其他格式的图表。我该如何解决这个问题?
谢谢。
您的图表当前存储为字典。期望 networkx 在您选择的任何数据结构上自动工作有点不公平。即使它被设置为按照您完成的方式处理字典,它怎么知道如何解释 0 或 inf
?
要使用 networkx 命令,您的图形需要采用 networkx 图形格式。
import networkx as nx
D = {1: {1: 0, 2: 1, 3: float('inf'), 4: float('inf'), 5: float('inf'), 6: float('inf')}, 2: {1: 1, 2: 0, 3: float('inf'), 4: 1, 5: 1, 6: float('inf')}, 3: {1: float('inf'), 2: float('inf'), 3: 0, 4: 1, 5: float('inf'), 6: float('inf')}, 4: {1: float('inf'), 2: 1, 3: 1, 4: 0, 5: 1, 6: 1}, 5: {1: float('inf'), 2: 1, 3: float('inf'), 4: 1, 5: 0, 6: float('inf')}, 6: {1: float('inf'), 2: float('inf'), 3: float('inf'), 4: 1, 5: float('inf'), 6: 0}}
G=nx.Graph()
for node, neighbor_dict in D.items():
G.add_node(node)
for neighbor, val in neighbor_dict.items():
if val !=0 and val <float('inf'):
G.add_edge(node, neighbor, weight=val)
for path in nx.all_simple_paths(G,1,3):
print path
>[1, 2, 4, 3]
>[1, 2, 5, 4, 3]
我有一个具有以下形式的邻接矩阵的图(一个 6 节点图,其中自边为 0,no_connections 标记为 Inf,其他边为 1):
{1: {1: 0, 2: 1, 3: inf, 4: inf, 5: inf, 6: inf}, 2: {1: 1, 2: 0, 3: inf, 4: 1, 5: 1, 6: inf}, 3: {1: inf, 2: inf, 3: 0, 4: 1, 5: inf, 6: inf}, 4: {1: inf, 2: 1, 3: 1, 4: 0, 5: 1, 6: 1}, 5: {1: inf, 2: 1, 3: inf, 4: 1, 5: 0, 6: inf}, 6: {1: inf, 2: inf, 3: inf, 4: 1, 5: inf, 6: 0}}
我想使用 networkx 包的 all_simple_paths 函数来查找从源到目的地的所有简单路径,但是当我调用
nx.all_simple_paths(graph, src, dst)
它给出: AttributeError: 'dict' 对象没有属性 'is_multigraph'
我目前没有任何其他格式的图表。我该如何解决这个问题?
谢谢。
您的图表当前存储为字典。期望 networkx 在您选择的任何数据结构上自动工作有点不公平。即使它被设置为按照您完成的方式处理字典,它怎么知道如何解释 0 或 inf
?
要使用 networkx 命令,您的图形需要采用 networkx 图形格式。
import networkx as nx
D = {1: {1: 0, 2: 1, 3: float('inf'), 4: float('inf'), 5: float('inf'), 6: float('inf')}, 2: {1: 1, 2: 0, 3: float('inf'), 4: 1, 5: 1, 6: float('inf')}, 3: {1: float('inf'), 2: float('inf'), 3: 0, 4: 1, 5: float('inf'), 6: float('inf')}, 4: {1: float('inf'), 2: 1, 3: 1, 4: 0, 5: 1, 6: 1}, 5: {1: float('inf'), 2: 1, 3: float('inf'), 4: 1, 5: 0, 6: float('inf')}, 6: {1: float('inf'), 2: float('inf'), 3: float('inf'), 4: 1, 5: float('inf'), 6: 0}}
G=nx.Graph()
for node, neighbor_dict in D.items():
G.add_node(node)
for neighbor, val in neighbor_dict.items():
if val !=0 and val <float('inf'):
G.add_edge(node, neighbor, weight=val)
for path in nx.all_simple_paths(G,1,3):
print path
>[1, 2, 4, 3]
>[1, 2, 5, 4, 3]