Skip to content

Commit

Permalink
Switch is_directed_acyclic_graph to use toposort internally (Qiskit#217)
Browse files Browse the repository at this point in the history
Previously the retworkx.is_directed_acyclic_graph() function was
internally using the petgraph::algo::is_cyclic_directed function to look
for a potential cycle in the graph. However, as noted in the docs[1]
this function is recursive and as reported in Qiskit/qiskit#5502
with very large graphs this is causing segfaults. To avoid this
potential issue this commit changes the internal implementation to use
petgraph::algo::toposort which isn't recursive and should be more
reliable.

Fixes: Qiskit/qiskit#5502

[1] https://docs.rs/petgraph/0.5.1/petgraph/algo/fn.is_cyclic_directed.html
  • Loading branch information
mtreinish authored Dec 11, 2020
1 parent 7ebd64b commit d735c76
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
fixes:
- |
Fixed a potential segfault that could occur when calling
:func:`~retworkx.is_directed_acyclic_graph` with a a very deep
:class:`~retworkx.PyDiGraph` object as reported in
`Qiskit/qiskit-terra#5502 <https://github.com/Qiskit/qiskit-terra/issues/5502>`__.
6 changes: 4 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -231,8 +231,10 @@ pub fn is_weakly_connected(graph: &digraph::PyDiGraph) -> PyResult<bool> {
#[pyfunction]
#[text_signature = "(graph, /)"]
fn is_directed_acyclic_graph(graph: &digraph::PyDiGraph) -> bool {
let cycle_detected = algo::is_cyclic_directed(graph);
!cycle_detected
match algo::toposort(graph, None) {
Ok(_nodes) => true,
Err(_err) => false,
}
}

/// Determine if 2 graphs are structurally isomorphic
Expand Down
9 changes: 9 additions & 0 deletions tests/test_edges.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,15 @@ def test_cycle_checking_at_init_nodes_from(self):
with self.assertRaises(retworkx.DAGWouldCycle):
dag.add_edges_from([(node_a, node_c, {}), (node_c, node_b, {})])

def test_is_directed_acyclic_graph(self):
dag = retworkx.generators.directed_path_graph(1000)
res = retworkx.is_directed_acyclic_graph(dag)
self.assertTrue(res)

def test_is_directed_acyclic_graph_false(self):
digraph = retworkx.generators.directed_cycle_graph(1000)
self.assertFalse(retworkx.is_directed_acyclic_graph(digraph))

def test_add_edge_from_no_data(self):
dag = retworkx.PyDAG()
nodes = list(range(4))
Expand Down

0 comments on commit d735c76

Please sign in to comment.