Skip to content

Commit d9f3dd8

Browse files
petercorkeclaude
andcommitted
Implement iscyclic()
For an undirected graph this is an O(1) check: a forest (acyclic) has exactly n - nc edges, one per component-connecting edge with no redundancy, so any excess indicates a cycle -- using n/ne/nc, which are already cached. For a directed graph this runs Kahn's algorithm (repeatedly remove vertices with no remaining incoming edges; if every vertex can eventually be removed the graph is a DAG, otherwise the ones never freed form a cycle), O(V+E), using the same iterative-frontier style already used by path_BFS/path_UCS/path_Astar. Does not mutate the graph -- "removal" is simulated via a local indegree dict. A matrix-based test (digraph acyclic iff its adjacency matrix is nilpotent) was considered and rejected: it needs an O(N^3) eigendecomposition plus a floating-point zero-tolerance judgement call to answer a question Kahn's algorithm answers exactly with integers in O(V+E). Verified against 7 hand-checked scenarios including a DAG "diamond" (shared descendant, no cycle -- a classic false-positive trap for a naive cycle detector). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
1 parent 6a1607a commit d9f3dd8

2 files changed

Lines changed: 105 additions & 3 deletions

File tree

‎src/pgraph/PGraph.py‎

Lines changed: 50 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -728,7 +728,7 @@ def __iter__(self) -> Iterator[BaseVertex]:
728728
729729
.. runblock:: pycon
730730
731-
731+
732732
>>> from pgraph import UGraph
733733
>>> g = UGraph()
734734
>>> v1 = g.add_vertex(coord=[0,0], name='v1')
@@ -1076,8 +1076,55 @@ def showgraph(self, **kwargs: Any) -> None:
10761076
# time.sleep(1)
10771077
# os.remove(pdffile.name)
10781078

1079-
def iscyclic(self):
1080-
pass
1079+
def iscyclic(self) -> bool:
1080+
"""
1081+
Test if graph is cyclic
1082+
1083+
:return: true if the graph contains at least one cycle
1084+
:rtype: bool
1085+
1086+
For an undirected graph this is a simple count: a forest (acyclic)
1087+
has exactly ``n - nc`` edges, one per component-connecting edge with
1088+
no redundancy, so any excess indicates a cycle. This is O(1) given
1089+
:meth:`n`, :meth:`ne` and :meth:`nc`, which are already cached.
1090+
1091+
For a directed graph this runs `Kahn's algorithm
1092+
<https://en.wikipedia.org/wiki/Topological_sorting#Kahn's_algorithm>`_:
1093+
repeatedly remove vertices with no remaining incoming edges. If every
1094+
vertex can eventually be removed, the graph is a DAG (acyclic); if
1095+
some are never freed, they form a cycle. This is O(V+E), using
1096+
vertices' outgoing edges via :meth:`BaseVertex.neighbours` the same
1097+
way :meth:`path_BFS` and friends do.
1098+
1099+
.. note:: A matrix-based test also exists in theory -- a digraph is
1100+
acyclic iff its adjacency matrix is nilpotent (all eigenvalues
1101+
zero) -- but that needs an O(N^3) eigendecomposition plus a
1102+
floating-point zero-tolerance judgement call, to answer a
1103+
question Kahn's algorithm answers exactly with integers in
1104+
O(V+E). Not used here for that reason.
1105+
1106+
:seealso: :meth:`adjacency`
1107+
"""
1108+
if isinstance(self, UGraph):
1109+
return self.ne > self.n - self.nc
1110+
1111+
# DGraph: Kahn's algorithm
1112+
indegree = {vertex: 0 for vertex in self}
1113+
for e in self.edges():
1114+
assert e.v2 is not None
1115+
indegree[e.v2] += 1
1116+
1117+
frontier = [vertex for vertex in self if indegree[vertex] == 0]
1118+
removed = 0
1119+
while frontier:
1120+
vertex = frontier.pop()
1121+
removed += 1
1122+
for n in vertex.neighbours():
1123+
indegree[n] -= 1
1124+
if indegree[n] == 0:
1125+
frontier.append(n)
1126+
1127+
return removed != self.n
10811128

10821129
def average_degree(self) -> float:
10831130
r"""

‎tests/test_graph.py‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -525,6 +525,29 @@ def test_components(self):
525525
v1.connect(v3)
526526
self.assertEqual(g.nc, 1)
527527

528+
def test_iscyclic(self):
529+
530+
# tree: acyclic
531+
g = UGraph()
532+
v = [g.add_vertex(name=str(i)) for i in range(4)]
533+
g.add_edge(v[0], v[1])
534+
g.add_edge(v[1], v[2])
535+
g.add_edge(v[2], v[3])
536+
self.assertFalse(g.iscyclic())
537+
538+
# one extra edge closes a cycle
539+
g.add_edge(v[3], v[0])
540+
self.assertTrue(g.iscyclic())
541+
542+
# two disconnected trees: still acyclic
543+
g2 = UGraph()
544+
a = [g2.add_vertex(name=f'a{i}') for i in range(3)]
545+
b = [g2.add_vertex(name=f'b{i}') for i in range(2)]
546+
g2.add_edge(a[0], a[1])
547+
g2.add_edge(a[1], a[2])
548+
g2.add_edge(b[0], b[1])
549+
self.assertFalse(g2.iscyclic())
550+
528551
def test_matrices(self):
529552
g = UGraph()
530553
# coordinates are needed so edge cost auto-computes, otherwise
@@ -796,6 +819,38 @@ def test_Dict(self):
796819
for v in g:
797820
self.assertIsInstance(v, DVertex)
798821

822+
def test_iscyclic(self):
823+
824+
# diamond DAG: shared descendant, but acyclic -- a classic false
825+
# positive for a naive/buggy cycle detector
826+
g = DGraph()
827+
v = [g.add_vertex(name=str(i)) for i in range(4)]
828+
g.add_edge(v[0], v[1])
829+
g.add_edge(v[0], v[2])
830+
g.add_edge(v[1], v[3])
831+
g.add_edge(v[2], v[3])
832+
self.assertFalse(g.iscyclic())
833+
834+
# a back-edge closes an actual directed cycle
835+
g.add_edge(v[3], v[0])
836+
self.assertTrue(g.iscyclic())
837+
838+
# disconnected DAG components: still acyclic
839+
g2 = DGraph()
840+
x = [g2.add_vertex(name=f'x{i}') for i in range(2)]
841+
y = [g2.add_vertex(name=f'y{i}') for i in range(2)]
842+
g2.add_edge(x[0], x[1])
843+
g2.add_edge(y[0], y[1])
844+
self.assertFalse(g2.iscyclic())
845+
846+
# pure 3-cycle, no self-loops
847+
g3 = DGraph()
848+
t = [g3.add_vertex(name=str(i)) for i in range(3)]
849+
g3.add_edge(t[0], t[1])
850+
g3.add_edge(t[1], t[2])
851+
g3.add_edge(t[2], t[0])
852+
self.assertTrue(g3.iscyclic())
853+
799854
def test_matrices(self):
800855
# 3-4-5 triangle, directed 0->1, 0->2, 1->2 -- deliberately
801856
# asymmetric so directed-specific behaviour (out-degree only,

0 commit comments

Comments
 (0)