Python Networkx 检测 loops/circles

Python Networkx detecting loops/circles

给定以下示例:

是否有可能检测到网络中的环路(I1, I2,I3, C6, C7, I5)

我试过:simple_cycles → 它在 3 个节点上工作正常,但不能超过 3 个。

我需要检测包含所有节点和 "input" 节点 ("I1") 和 "output" ("I3").

的圆

是的,如果您使用 nx.simple_cycles(G) 方法,您将在图中得到循环作为循环中的一组节点(正如我所了解的那样)。有关详细信息,请查看 this

我重新创建了你的图表:

import networkx as nx

g = nx.DiGraph([('P', 'I0'), ('I0', 'I1'), ('I1', 'I2'),
                ('I2', 'I3'), ('I1', 'I5'), ('I5', 'C7'),
                ('C7', 'C6'), ('C6', 'I3'), ('I3', 'C9')])

您正在搜索简单循环,但上图中有 none:

>>> list(nx.simple_cycles(g))
[]

所以你必须在无向图中搜索循环。您必须将图形转换为无向图。对于无向图,cycle_basis 函数似乎是您所需要的:

>>> nx.cycle_basis(g.to_undirected())
[['I5', 'C7', 'C6', 'I3', 'I2', 'I1']]