Skip to content

fix: add suggestions from #8021 and #8029 to is_aperiodic - #8148

Merged
dschult merged 7 commits into
networkx:mainfrom
Peiffap:refactor/is_aperiodic
Jan 18, 2026
Merged

dschult merged 7 commits into
networkx:mainfrom
Peiffap:refactor/is_aperiodic

Conversation

@Peiffap

@Peiffap Peiffap commented Jul 14, 2025 •

Copy link
Copy Markdown
Member

This PR combines some of the changes suggested in #8021 and #8029. CC @fei0319.

Changelist:

  • Some docstring changes.
  • Use not_implemented_for instead of checking manually (this changes the exception type but everyone seemed to agree no deprecation was necessary in the original PRs).
  • Switch to an approach based on bfs_labeled_edges. I originally tried to get a working solution using dfs_labeled_edges, without using nx.strongly_connected_components, but kept finding edge cases that it wouldn't work for. I kept the BFS because it's slightly more readable; both versions are ~30% faster over 100 runs for G = nx.complete_graph(300, create_using=nx.DiGraph):
dfs 2.1416163529793266
bfs 2.1179135239799507
old 2.9861131829966325
  • Several changes to tests: removed a duplicate test for the null graph, used with pytest.raises instead of pytest.raises, and added the edge cases I came up with to the "not strongly connected" tests. These should be purely incremental, i.e. no previously tested behavior is now untested.

One point raised in the discussions on previous PRs remains: it's strange to have a function in dag.py that raises for DAGs... We should find a new home for it. :) How about cycles.py?

@Peiffap Peiffap changed the title fix: add suggestions from gh-8021 and gh-8029 to is_aperiodic fix: add suggestions from #8021 and #8029 to is_aperiodic Jul 14, 2025

@amcandio amcandio left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice

Comment thread networkx/algorithms/tests/test_dag.py Resolved
Comment thread networkx/algorithms/dag.py Outdated
for u, v, d in nx.bfs_labeled_edges(G, s):
if d == "tree":
levels[v] = levels[u] + 1
elif (g := gcd(g, levels[u] - levels[v] + 1)) == 1:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think it has any real implications for performance reasons, but I'm curious whether I'm understanding the algorithm correctly...

AIUI the gcd check is only necessary when a cycle is detected, correct? And a cycle can only come about from a "reverse" edge? In other words, could this statement be:

elif (d == "reverse") and (g := gcd(g, levels[u] - levels[v] + 1)) == 1

FWIW I've had to stare at this for a while for it to make sense to me. That's not a knock on the implementation - the use of bfs_labeled_edges is definitely more clear IMO, but I realized I didn't really have a great handle on the original logic either!

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Admittedly, I've had to think about this too... I believe your suggestion will break for self-loops, i.e. cycles of length 1. These get reported as "level" edges. I can't think of an example where a "forward" edge creates a cycle, and I'm reasonably confident it's not possible: creating a cycle requires that lvls[u] >= lvls[v] for some edge, and "forward" edges must have lvls[u] < lvls[v] by definition.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Admittedly, I've had to think about this too... I believe your suggestion will break for self-loops, i.e. cycles of length 1. These get reported as "level" edges.

More than just self-loop edges it turns out. I went ahead and just tried it to see what breaks and there's an example of a non-selfloop level edge creating a cycle in the test suite:

G = nx.cycle_graph(4, create_using=nx.DiGraph)
G.add_edge(1, 3)

So I'm convinced now that both "reverse" and "level" edges are relevant for cycle detection.

IMO there's enough going on here to warrant additional code or at least comments to aid readers in understanding how this works with the different bfs_labeled edge types. Here's a rough proposal:

# There are four categories of edges from bfs_labeled_edges:
# "tree", "reverse", "level" and "forward".
for u, v, d in nx.bfs_labeled_edges(G, s):
    # "tree" edges indicate a new level in the bfs tree
    if d == "tree":
        levels[v] = levels[u] + 1
    # Only "reverse" or "level" edges are involved in cycles
    elif (d == "reverse") or (d == "level"):
        # When a new potential cycle is encountered, check whether it's
        # length is divisible by a common factor with all other
        # encountered cycles
        if (g := math.gcd(g, levels[u] - levels[v] + 1)) == 1:
            return True
    # "forward" edges are not involved in either cycles nor expanding
    # tree depth and are therefore ignored
    elif d == "forward":
        continue
    else:
        raise NetworkXError(f"Unrecognized edge label '{d}' from bfs_labeled_edges")

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've added some comments inspired by your example. I also switched from using bfs_labeled_edges to dfs_labeled_edges because the edge types are slightly more intuitive IMO.

@Peiffap

Peiffap commented Jul 31, 2025

Copy link
Copy Markdown
Member Author

Running benchmarks locally, I get this

| Change   | Before [01705c4a] <main>   | After [4c1d13a6] <refactor/is_aperiodic>   |   Ratio | Benchmark (Parameter)                                                     |
|----------|----------------------------|--------------------------------------------|---------|---------------------------------------------------------------------------|
| -        | 2.46±0.04ms                | 1.93±0.02ms                                |    0.79 | benchmark_dag.DAGBenchmarks.time_is_aperiodic('Erdos Renyi (100, 0.9)')   |
| -        | 25.7±0.3ms                 | 20.2±0.3ms                                 |    0.79 | benchmark_dag.DAGBenchmarks.time_is_aperiodic('Erdos Renyi (1000, 0.09)') |
| -        | 363±7μs                    | 282±3μs                                    |    0.78 | benchmark_dag.DAGBenchmarks.time_is_aperiodic('Erdos Renyi (100, 0.1)')   |
| -        | 1.42±0.04ms                | 1.10±0.02ms                                |    0.78 | benchmark_dag.DAGBenchmarks.time_is_aperiodic('Erdos Renyi (100, 0.5)')   |
| -        | 219±3μs                    | 168±0.5μs                                  |    0.77 | benchmark_dag.DAGBenchmarks.time_is_aperiodic('Erdos Renyi (100, 0.05)')  |
| -        | 2.74±0.02ms                | 2.09±0.03ms                                |    0.76 | benchmark_dag.DAGBenchmarks.time_is_aperiodic('Complete (100)')           |
| -        | 277±0.9ms                  | 210±3ms                                    |    0.76 | benchmark_dag.DAGBenchmarks.time_is_aperiodic('Complete (1000)')          |
| -        | 14.8±0.3ms                 | 11.2±0.1ms                                 |    0.76 | benchmark_dag.DAGBenchmarks.time_is_aperiodic('Erdos Renyi (1000, 0.05)') |
| -        | 3.93±0.02ms                | 2.92±0.01ms                                |    0.74 | benchmark_dag.DAGBenchmarks.time_is_aperiodic('Erdos Renyi (1000, 0.01)') |

SOME BENCHMARKS HAVE CHANGED SIGNIFICANTLY.
PERFORMANCE INCREASED.

@rossbar rossbar left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The performance gains are nice, but the real win here is the readability improvement - this is much more clear about how/why the traversal relates to the length of detected cycles. Thanks @Peiffap !

Comment thread benchmarks/benchmarks/benchmark_dag.py Outdated
import networkx as nx


class DAGBenchmarks:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The naming here reflects the module naming scheme - I'd vote to instead call this (and rename the filename BenchmarkAperiodic or similar.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, I've updated the names.
Somewhat related: should this function really be in dag.py given that it raises for DAG inputs?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The is_aperiodic function doesn't raised for all DAGs right?
My interpretation of the dag.py module name is that these functions are relevant for DAG graphs. It does not imply that they don't raise for all DAGs. But maybe I'm missing something.

aperiodic is a subset of DAG right?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With the updates in #8029, is_aperiodic raises if the graph is not strongly connected, which excludes all DAGs except for the single-node empty graph IIUC. Can we really say is_aperiodic is relevant for DAGs in that case? To me, the two concepts seem orthogonal.

Thinking about this some more, I also have a suggestion for how we might be able to make the API more clear with the changes discussed in #8021 and #8029. Since the decision was made to restrict aperiodicity to single SCC graphs, with several ways of extending it to graphs with multiple SCCs (using aperiodicity for each SCC or even attracting component), how would you feel about creating an is_aperiodic_component(G, component) function in a new module algorithms/components/aperiodic.py, and moving is_aperiodic to it as well?

Co-authored-by: Ross Barnowski <[email protected]>
@dschult

dschult commented Jan 18, 2026

Copy link
Copy Markdown
Member

I think the only leftover discussion from this PR is whether to move is_aperiodic out of dag.py because DAGs and aperiodic graphs do not overlap (one precludes the other, except for very small cases). I'm going to merge this as it has two approvals. We can take up the idea of moving the function in a different PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Development

Successfully merging this pull request may close these issues.

4 participants