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

是否可以通过路径中包含的属性在 networkx 中获取唯一路径?

如何解决是否可以通过路径中包含的属性在 networkx 中获取唯一路径?

我有以下图表,我希望能够发现我可以从“ip”到“name”的所有方式,在 networkx 中使用以下图表显示我可以从“ip”到“name”如果我遵循这条路径 [['ip','address','name']],问题是我还定义了 addressname 可以从两个不同的边缘经过,一个具有属性 through=isptool,另一个通过属性 through=phyonebook 是否可以让 networkx 将这两条路径列为单独的路径,并在路径中包含 through 属性?类似的东西

ip -sometool-> address -isptool-> name

ip -sometool-> address -phonebook-> name
import networkx as nx
g = nx.DiGraph()
g.add_node('email')
g.add_node('ip')
g.add_node('address')
g.add_node('name')
g.add_edges_from([('address','name')],through='isptool')
g.add_edges_from([('address',through='phonebook')
g.add_edge('email','address')
g.add_edge('ip',through='sometool')
list(nx.all_simple_paths(g,'ip','name'))
>>>[['ip','name']] # should have 2 paths one using isptool and one using phonebook edge
list(nx.all_simple_paths(g,'email','name'))
>>>[['email','name']] # same here,should have 2 paths

解决方法

问题在于您尝试使用 DiGraph,它只能处理从一个节点到另一个节点的一条有向边。如果我们切换到使用 MultiDiGraphnx.all_simple_paths() 会返回预期结果:

>>> import networkx as nx
    g = nx.MultiDiGraph()
    g.add_nodes_from(['email','ip','address','name'])
    
    g.add_edges_from([('address','name')],through='isptool')
    g.add_edges_from([('address',through='phonebook')
    g.add_edge('email','address')
    g.add_edge('ip',through='sometool')
>>> list(nx.all_simple_paths(g,'name'))
[['ip','name'],['ip','name']]
>>> list(nx.all_simple_paths(g,'email','name'))
[['email',['email','name']]

然而,虽然我们现在得到了两条路径,但是我们看不到边属性。我们可以使用 nx.all_simple_edge_paths() 代替:

>>> list(nx.all_simple_edge_paths(g,'name'))
[[('email',0),('address','name',0)],[('email',1)]]

借助一些 f-string 魔法,我们可以使用边缘数据来生成您想要的输出:

>>> for path in nx.all_simple_edge_paths(g,'name'):
        a,b,e = path[0]
        print(f'{a} -{g[a][b][e].get("through","sometool")}-> {b}',end='')
        for a,e in path[1:]:
            print(f' -{g[a][b][e].get("through",end='')
        print('\n')
email -sometool-> address -isptool-> name

email -sometool-> address -phonebook-> name

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