Skip to content

Fix is_aperiodic - #8021

Closed
fei0319 wants to merge 16 commits into
networkx:mainfrom
fei0319:fix-is-aperiodic
Closed

fei0319 wants to merge 16 commits into
networkx:mainfrom
fei0319:fix-is-aperiodic

Conversation

@fei0319

@fei0319 fei0319 commented May 3, 2025

Copy link
Copy Markdown
Contributor

The current implementation of is_aperiodic (link) is incorrect. It short-circuits when g != 1 with return value False. However, g != 1 for the currently explored nodes doesn't necessarily mean the graph is not aperiodic.

One of the current tests is incorrect (G contains a self-loop and is therefore aperiodic. But the test claims that it is not aperiodic):

def test_is_aperiodic_disconnected2():
    G = nx.DiGraph()
    nx.add_cycle(G, [0, 1, 2])
    G.add_edge(3, 3)
    assert not nx.is_aperiodic(G)

Several tests that fail with the current implementation are added. Preview:

def test_is_aperiodic_cycle5():
    G = nx.DiGraph()
    nx.add_cycle(G, [1, 2, 3, 4])
    nx.add_cycle(G, [5, 6, 7])
    G.add_edge(5, 1)
    assert nx.is_aperiodic(G)


def test_is_aperiodic_acyclic_component():
    G = nx.DiGraph()
    G.add_node(0)
    G.add_edge(1, 1)
    assert nx.is_aperiodic(G)


def test_is_aperiodic_acyclic_component2():
    G = nx.DiGraph()
    G.add_node(0)
    nx.add_cycle(G, [1, 2, 3])
    nx.add_cycle(G, [2, 3, 4, 5])
    assert nx.is_aperiodic(G)

The fixed new implementation works in the same manner as the original one, but is no longer recursive.

@Peiffap Peiffap left a comment

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 new behavior makes sense to me, though I'm curious to see the reasoning behind why the current algorithm is what it is. Some comments below. Thanks!

Comment thread networkx/algorithms/dag.py Resolved
Comment thread networkx/algorithms/dag.py Resolved
Comment thread networkx/algorithms/dag.py Resolved
Comment thread networkx/algorithms/tests/test_dag.py Resolved
fei0319 and others added 2 commits May 3, 2025 22:43
@fei0319

fei0319 commented May 3, 2025

Copy link
Copy Markdown
Contributor Author

I found a counterexample to the algorithm: DiGraph([(1, 2), (1, 3), (1, 4), (4, 2)]). There are no cycles in the graph, but the algorithm would count a cycle of length 2. This is because that only a back edge can form a cycle, but we counted cross edges. So neither the original implementation nor the proposed implementation is correct.

g

Fortunately the paper ([1] Jarvis, J. P.; Shier, D. R. (1996), "Graph-theoretic analysis of finite Markov chains," in Shier, D. R.; Wallenius, K. T., Applied Mathematical Modeling: A Multidisciplinary Approach, CRC Press.) pointed out that the algorithm works for SCCs (Strongly Connected Components). We should divide the input graph into strongly connected subgraphs and perform the algorithm on them. Only need a few extra lines.

@Peiffap This answers your question about why the original implementation is what it is. I believe it tries to use recursion to naturally process the graph in SCCs. It is not guaranteed to identify and process SCC though.

@Peiffap

Peiffap commented May 3, 2025

Copy link
Copy Markdown
Member

The test failure is my bad; I didn't realize you were using the built-in Python random module and thought it was the NumPy equivalent. Since this is the only place NumPy is used, let's go back to what it was before.

@dschult dschult left a comment

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 docs should talk about self-loops and whether they are included in the definition of cycles. Look at the paper to see how they handle self-loops. It may be that this implementation does not work for self-loops. And that's ok so long ast the docs state it and we check that appropriate results occur when selfloops are present. It looks like there is a test for this already, so someone has already thought about that. Let's make it clear in the docs how we handle it.

Comment thread networkx/algorithms/dag.py Resolved
Comment thread networkx/algorithms/dag.py Resolved
Comment thread networkx/algorithms/dag.py Resolved
Comment on lines -658 to +668
assert not nx.is_aperiodic(G)
assert nx.is_aperiodic(G)

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.

I'm not sure this is correct. selfloops provide a cycle on length 1. That length isn't evenly divided by any integer > 1.

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.

If there is a self-loop (assuming we treat those as cycles of length 1, as you mention in your general comment), then there cannot be any k > 1 that divides the length of every cycle in the graph. This means the graph is aperiodic.

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 think we should make sure we get the semantics right here. AIUI, what we're saying is that any graph with a self-loop is by definition aperiodic, right? This doesn't seem to align with the current behavior.

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.

Yes -- Thanks for the correction! I got the double-negative switched. :P

It looks like the original implementation ignores self-loops completely -- which is an alternative approach that is appropriate if documented well. Is there an external source that discusses what to do with self-loops for aperiodic?
If not, I have a slight preference (maybe 0+) for leaving the original behavior, but stating in the docs that self-loops are ignored for this calculation. We have other ways to check for them is a user wants.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The original implementation doesn't mean to ignore self-loops. The following code shows that the original is_aperiodic determines a graph G with a single self-loop to be aperiodic. The ignorance of self-loops in this test is purely a bug.

G = nx.DiGraph()
G.add_edge(1, 1)
# Prints True
print(nx.is_aperiodic(G))

In a strongly connected graph, if one defines a Markov chain on the vertices, in which the probability of transitioning from v to w is nonzero if and only if there is an edge from v to w, then this chain is aperiodic if and only if the graph is aperiodic.

Wikipedia shows the strong connection between aperiodicity in graphs and MCs (Markov Chains). And self-loops are ubiquitous in MCs.

Yes, the Markov chain you gave is aperiodic. To see this, you can try proving that whenever the underlying graph is strongly connected (or, in other words, the MC is irreducible) and contains at least one self-loop, then the Markov chain is aperiodic.

This is another discussion at https://math.stackexchange.com/a/1234284 that says self-loops are valid in aperiodicity of MCs (not graphs though).

It makes sense to keep the self-loops.

Comment thread networkx/algorithms/tests/test_dag.py Resolved
fei0319 and others added 2 commits May 4, 2025 02:04

@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.

LGTM, left a comments wrt test cases.

cycle_nodes = [rng.randint(0, 10) for _ in range(cycle)]
nx.add_cycle(G, cycle_nodes)

assert nx.is_aperiodic(G)

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.

Can you generate cases where G is not aperiodic?

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.

And add the test case you found where the current implementation fails?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The tests should be fine now.

this_level = [s]

scc = nx.strongly_connected_components(G)
sg = (G.subgraph(c) for c in scc)

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.

These subgraph views can be slow. I wonder if it's better to just work with the set of elements. Anyhow, that's out of the scope of this PR

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

It is possible to work without subgraph views, but I cannot figure out a way to fit nx.bfs_labeled_edges with it.

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.

Maybe by doing continue once you see a node outside the component set and breaking once you have seen them all in that component.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, this absolutely works with a custom BFS. But with nx.bfs_labeled_edges, we have no control of continuing or breaking. This is a trade-off between readability and efficiency.

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.

I think in this case it makes sense to quantify the trade-off by benchmarking. Note that the current implementation also uses subgraph views (in a way I think is slower than what this PR does) - this change does not necessarily need to address that part yet.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I have carried out a benchmark. Results:

Graph With subgraphs Without subgraphs
Aperiodic 0.001187 0.001072
Periodic 0.005958 0.003403

Benchmark code (The graph generators are available in test_dag.py):

def benchmark(Gs, title, result):
    t = 0
    for G in Gs:
        t1 = time.perf_counter()
        assert nx.is_aperiodic(G) == result
        t2 = time.perf_counter()
        t += t2 - t1
    return print(f"{title}: {t / len(Gs):.6f} seconds")

if __name__ == "__main__":
    Gs = [random_aperiodic_graph(seed, 1000, 100, 3, 20) for seed in range(1000)]
    benchmark(Gs, "aperiodic", True)

    Gs = list(map(lambda G: to_periodic_graph(G, 2), Gs))
    benchmark(Gs, "periodic", False)

Optimized code:

    g = 0
    for c in scc:
        s = nx.utils.arbitrary_element(c)

        level = {s: 0}
        seen = {s}
        current_layer = [s]
        l = 1

        while current_layer:
            next_layer = []
            for u in current_layer:
                for v in G[u]:
                    if v not in c:
                        continue
                    if v not in seen:
                        seen.add(v)
                        level[v] = l
                        next_layer.append(v)
                    else:
                        g = gcd(g, level[u] - level[v] + 1)
                        if g == 1:
                            return True

            current_layer = next_layer
            l += 1

    return False

It makes sense to optimize the algorithm. It won't be part of this PR anyway.

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.

I agree -- this PR does not need to address whether to use subgraph here or not. If speed is an issue, we can use G.subgraph(...).copy(). But memory may be the limiting factor in which case the subgraph view is what we want.

@Peiffap Peiffap left a comment

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.

Some more comments.

this_level = [s]

scc = nx.strongly_connected_components(G)
sg = (G.subgraph(c) for c in scc)

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.

I think in this case it makes sense to quantify the trade-off by benchmarking. Note that the current implementation also uses subgraph views (in a way I think is slower than what this PR does) - this change does not necessarily need to address that part yet.

Comment thread networkx/algorithms/dag.py Resolved
cycle_nodes = [rng.randint(0, 10) for _ in range(cycle)]
nx.add_cycle(G, cycle_nodes)

assert nx.is_aperiodic(G)

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.

And add the test case you found where the current implementation fails?

@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.

Great job!

Comment on lines -658 to +668
assert not nx.is_aperiodic(G)
assert nx.is_aperiodic(G)

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 think we should make sure we get the semantics right here. AIUI, what we're saying is that any graph with a self-loop is by definition aperiodic, right? This doesn't seem to align with the current behavior.

assert nx.is_aperiodic(G)


def random_aperiodic_graph(seed, n, n_cycle, l, r):

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'm generally not a fan of this style of testing, i.e. blitzing the algorithm with randomly-generated examples. Now, I think this is a valuable exercise for exploring the space for counter examples, I just don't think we should have that exploration part of the test suite.

A pattern that I think is better would be something like:

  • Run the tested function with randomly generated inputs
  • If failures are identified, then focus on that test input and reduce it to a minimal example that (hopefully) highlights the mechanism that causes the failure
  • Add that reduced example to the test suite.

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'm generally not a fan of this style of testing, i.e. blitzing the algorithm with randomly-generated examples. Now, I think this is a valuable exercise for exploring the space for counter examples, I just don't think we should have that exploration part of the test suite.

A pattern that I think is better would be something like:

  • Run the tested function with randomly generated inputs
  • If failures are identified, then focus on that test input and reduce it to a minimal example that (hopefully) highlights the mechanism that causes the failure
  • Add that reduced example to the test suite.

I see the point here. But even if you don't find bugs now doesn't mean that you are not covering future bugs. As the code evolves bugs might be introduced and the random examples might be able to catch them. Of course, the developer could re-build the random tests every time a change is made but that would be easy to overlook.

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.

I'm somewhere in the middle of these opinions. I think the "randomized blitzing" is a valuable tool to have in a test suite, but it's a better fit for property-based testing, not unit testing.

fei0319 added 2 commits May 6, 2025 14:18
The algorithm only supports strongly connected graphs. Other graphs
must be divided into SCCs before checking.

@dschult dschult left a comment

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.

I feel like I've responded to this PR in short bursts and not gone through the whole question/problem that it is trying to solve. So I spent some time today and hope I can contribute in a more helpful way now.

IIUC the current implementation does not treat graphs with more than one SCC correctly. It basically checks whether all SCC are aperiodic (in isolation from the others) instead of checking whether any SCC is aperiodic. It seems like changing the and in original line 665 to or should fix this problem.

It looks like one of the tests in the test file is incorrect: test_aperiodic_disconnected2 as reported above. This is due to the and vs or issue.

I think the other issues here -- recursive, splitting into SCCs, using existing NX tools like bfs_labeled_edges, etc. are efficiency or ease of reading/documenting issues. Is that correct?

I would like to entertain a first PR that just changes "and" to "or" and corrects the broken test (and adds more tests -- though not test_is_aperiodic_random). That will hopefully lead to expedited review and inclusion in the v3.5 release (coming in the next week or two). It's always good to fix bugs! :)

While that is progressing we can work on this one to get the wrinkles out of the many concepts being discussed here. I can put together a quick fix PR if time till release gets tight. But @fei0319 would you like to make a new branch and add this? Either way is fine with me -- I don't want to get in your way or steal your credit. But if you'd rather focus on this stuff, I'm fine with putting together the quick-fix version.

@rossbar

rossbar commented May 7, 2025

Copy link
Copy Markdown
Contributor

I would like to entertain a first PR that just changes "and" to "or" and corrects the broken test (and adds more tests -- though not test_is_aperiodic_random). That will hopefully lead to expedited review and inclusion in the v3.5 release (coming in the next week or two). It's always good to fix bugs! :)

I agree - the discussion here has generally had wider scope than the set of changes. IMO the bug-fix is unobjectionable and should go in before 3.5, so breaking just that part out into a separate PR might be helpful!

@fei0319

fei0319 commented May 7, 2025

Copy link
Copy Markdown
Contributor Author

Yes -- many of this PR are not about correctness! We can concentrate on correctness and have a fast fix, but I am afraid there are more problems beyond the use of and/or with the original implementation.

  • We can't tell whether a graph is aperiodic by the periodicities of its SCCs. We must know the periods of them. All SCCs being periodic doesn't imply the graph is periodic, i.e. a graph with a length-2 cycle (periodic) and a length-3 cycle (periodic) is actually aperiodic.
  • We intend to process one SCC at a time. But we are actually searching all nodes reachable from the source, not just the SCC.

The following test can illustrate both problems well (it was added yesterday). The current algorithm (with and/or fixed) would say the first subgraph has a length-2 cycle (levels[4] - levels[2] + 1 is 2), but it is actually acyclic. Even if the first subgraph becomes a length-2 cycle, the current algorithm would still mistake the new graph for a periodic graph.

def test_is_aperiodic_scc_division():
    """Tests that `is_aperiodic` correctly divides the graph into
    SCCs (Strongly Connected Components) before checking for aperiodicity.
    """
    G = nx.DiGraph()

    # Would detect a length-2 cycle if not divided into SCCs
    # The subgraph is actually acyclic
    nx.add_path(G, [1, 2])
    nx.add_path(G, [1, 3, 4])
    G.add_edge(4, 2)

    # A length-3 cycle
    nx.add_cycle(G, [5, 6, 7])

    assert not nx.is_aperiodic(G)

A minimal bug fix considering these has been implemented at #8029 . It should be correct and as minimal!

@dschult

dschult commented May 8, 2025 •

Copy link
Copy Markdown
Member

Are you sure we need to find the gcd between two SSCs? That implies the gcd between periods of two SCCs is the period of the combined graph. But I think that is incorrect. I argue here that an aperiodic graph must have all nodes being aperiodic. Said another way, a graph has period 1 (is aperiodic) when no recurrent nodes have period greater than 1.

I believe the original algorithm was correct. We have to have g==1 for every SCC to have an aperiodic graph.
TL;DR

I am having a hard time finding a reference that considers aperiodicity with multiple SCCs. The period of individual states/nodes seems to agree across sources. But most sources only consider a graph with a single SCC. And it is quite rare for the sources to define the period of a graph when there are multiple SCCs.

The most clearly stated definition I have seen comes from lectures at Brown University and describes it for markov chains as: A Markov Chain in which no recurrent states are periodic is called aperiodic. A state is periodic when its period is > 1. A state is aperiodic when its period is 1. The whole chain is aperiodic only when all of its states have period 1.

Note that recurrent states translate to graphs as nodes that lie on cycles -- that is the nodes are in an SCC. Translating the markov chain term aperiodic to transition graphs, we get a Graph is aperiodic when the period is 1 for each node that lies on a cycle. Let me stress that all nodes must be aperiodic (have period 1) for a graph to be aperiodic. If any nodes have period > 1 then the graph is not aperiodic.

Viewing the term "aperiodic" from an ergodic theory perspective, we want aperiodic and irreducible to imply ergodic (well mixed -- single long term probability distribution, etc). The irreducible condition rules out more than one SCC. That is probably why almost nobody seems to care about aperiodic with multiple SCCs. But looking at it from ergodic theory perspective, aperiodic means we don't have structures that bind the probability into non-constant patterns over time. That needs to be true everywhere -- not anywhere. So one SCC that is aperiodic and another that is periodic will not make the graph aperiodic. There is still a place (the other SCC) where probability has patterns over time.

Example to show why we need gcd between cycle-lengths within a SCC:
We need the gcd of the periods of two cycles within an SCC to find the period of the nodes in that SCC. The nodes in the SCC interact and add their cycle lengths, so the resulting times when a node can return to itself are multiples of the gcd. For example, a 8-cycle and a 10-cycle can allow a node to return to itself after 8, 10, 16, 18, 20, 24 and any even number above 24. So the even numbers includes all times at which the states can return to themselves. Thus those nodes have period 2. (See the only reference from the periodic graphs wikipedia article that discusses multiple SCCs though it is very brief.) That is because the cycles are interacting.

But cycles in different SCCs don't interact. We can't travel along one cycle and then the other cycle to find the possible return times. The possible return times for nodes in the two SCCs are just different. If you want to try to define return times by looking at two particles starting at two nodes and see when they return (which is what ergodic theory would be interested in I think) then it seems that the period of a graph with two SCCs of relatively prime periods would be the product of the periods. That is how long it would take for the "system" (of two particles) to return to its original state.

So, a graph with two SCCs, one with period 2 and the other with period 3, have some states/nodes with period 2 and also other states/nodes with period 3. So the graph is not aperiodic!! It has some periodic recurrent nodes. Not all nodes are aperiodic.

To show a graph is aperiodic, we need g==1 for every SCC. To show a graph is not aperiodic we only need one SCC to have g>1.

g should be recalculated for each SCC independent of the other SCCs (because the cycles can't add to each other across SCCs). And we should test each for g==1. They all need to be g==1 to have an aperiodic graph.

Can you see any holes in this story? Can you justify another treatment of "aperiodic" when there are multiple SCCs? What am I missing?

@dschult

dschult commented May 8, 2025 •

Copy link
Copy Markdown
Member

I'm looking at the test of multiple SCCs from above. I think the two add_path calls should be add_cycle to make the example work -- right? Then we have a 2-cycle and a 3-cycle with an edge allowing probability from the 3-cycle to leak over into the 2-cycle and never come back.

So the long term behavior of the Markov Chain is to end up on the 2-cycle with probability sloshing back and forth between nodes 1 and 2. That is dependent on initial conditions, and it not a stationary probability distribution... Thus not ergodic. Importantly, the existence of two nodes with period 2 is sufficient to show that the whole graph is not aperiodic. The random walk will have a time dependent pattern that in general depends on the initial conditions.

Hmmmm... this could get even messier! In some sense the period of the other SCC doesn't matter much in the long run. So if the first SCC was aperiodic and the second was period 3, and the direction of flow is into the aperiodic SCC, then should we call the whole graph aperiodic because with probability 1 we end up in the aperiodic SCC? Now we've got aperiodic depending on flow other than cycles. And maybe the whole idea of aperiodic is not easily defined with multiple SCCs. Perhaps we should be raising an exception for graphs that have multiple SCCs. Thoughts?

@fei0319

fei0319 commented May 8, 2025

Copy link
Copy Markdown
Contributor Author

Happy to involved in an in-depth discussion like this. We both agree with what graphs of a single SCC are aperiodic, but there is a divergence on graphs with multiple SCCs. First thing first, we can find a good definition of aperiodicity for multiple-SCCs graphs so we shouldn't simply disable multiple SCCs. I will elaborate on the reasons later.

Let's talk about the correctness of the current implementation first. I believe the current implementation is incorrect if we intend to keep the multiple SCCs cases and a bug fix is necessary anyway. Say we agree that all SCCs should be aperiodic for an aperiodic graph, then we have a counterexample where the original implementation fails:

def test():
    G = nx.DiGraph()

    # The SCC of {1, 2, 3, 4} is aperiodic
    nx.add_cycle(G, [1, 2, 3, 4])
    G.add_edge(2, 4)

    # The SCC of {5, 6, 7, 8} is periodic
    nx.add_cycle(G, [5, 6, 7, 8])
    G.add_edge(4, 5)

    # Hence G is not aperiodic
    # But the current implementation fails
    assert not nx.is_aperiodic(G)

Then we have to determine which definition to base the fix on:

  1. The greatest common divisor of periods of all SCCs equals 1, or
  2. All SCCs are aperiodic

There are arguments on both sides. The first definition is what "A directed graph is aperiodic if there is no integer k > 1 that divides the length of every cycle in the graph" literally means, which complies with Wikipedia and the original docstring. The second definition keeps consistency with Markov chains aperiodicity, and I suppose is_aperiodic is used with MCs in most cases so the second definition would be more practical.

I also tried to find references for aperiodicity definition on directed graphs with multiple SCCs. But the only one I see is the one on Wikipedia you mentioned (it happens to be in the is_aperiodic docstring as well). Most time people talk about aperiodicity under the premise of irreducibility.

I am in favor of "All SCCs must be aperiodic" now, since it makes more senses mathematically based on your analysis. However, this raises a new issue: should we ignore those SCCs that are not attracting components, according to your mentioned definition "A Markov Chain in which no recurrent states are periodic is called aperiodic" from the Brown University lecture? Note that a recurrent node is a node in an attracting component, not just in a SCC; this is very confusing.

Yes, ignoring transient (non-reccurent) nodes makes sense to me, since all transient nodes does not contribute to $n \to \infty$ distribution generally. As the paper says:

$\textit{Theorem 3}$: Suppose that the condensed graph $\hat G$ for $G$ has a single supernode $K$ with no leaving edges and that all states of $K$ are aperiodic.

Then limiting probabilities exist and are independent of the initial probability vector $\alpha$. Moreover, these limiting probabilities coincide with the (unique) stationary distribution for the chain.

So a directed graph with a single attracting component can have a unique stationary distribution that can be approached by sampling if the attracting component is aperiodic, and the periodicities of other SCCs are ignored. We only care about the attracting components. (If a graph has multiple attracting components, though a unique stationary distribution is not guaranteed, the asymptotic law is still well-defined: it converges to the convex combination of the per-component stationary distributions, with weights equal to the probabilities of falling into each component. Aperiodicity guarantees the convergence inside every component; only the random choice of component prevents uniqueness.) This may answer your considerations about the multiple SCCs mess! Luckily aperiodicities make senses for multiple-SCCs graphs!

BTW, the time complexity of the implementation is incorrect. After the minimal fix is_aperiodic will still requires $O(n^2)$ (quadratic, since we calculate G.subgraph(set(G) - set(levels)) for every attracting components) instead of linear time of $n$ or $m$. I am not sure whether we should warn about that in docstring, since the whole logic will be superseded in a short time with the full fix.

Here is what I plan to include in the minimal fix:

  • Test fixes
  • Implement: A graph is aperiodic if all its attracting components are aperiodic
  • Update the definition of aperiodicity in docstring

and full fix:

  • No longer recursive
  • Reduce the time complexity from quadratic to linear
  • Use not_implemented_for
  • More readable with nx.bfs_labeled_edges

What do you think?

@dschult

dschult commented May 10, 2025

Copy link
Copy Markdown
Member

Once again, this is too long...
In summary:
I think we need to enforce (through checking or through documentation) that this function only be run on a strongly connected digraph. That is the only case we have a clear definition of aperiodic graph. And that is the only case where any of the definitions I have found have a performant algorithm.

TL;DR

Definitions:
I have found three definitions of an "aperiodic graph" used in the literature. They agree on the important case that is relevant to theorems involving ergodicity of the Markov processes described by these graphs. So there doesn't seem to be one that is "better" than the other.

  1. An aperiodic graph has the gcd of all cycle-lengths equal to 1.
  2. An aperiodic graph has every node being an aperiodic node. A node is aperiodic when the gcd of all cycles-lengths through that node is 1.
  3. A digraph is aperiodic if and only if a globally reachable node is aperiodic. A globally reachable node n has a directed path from each node to n. The node's period d is the gcd of all cycle lengths from n to n. The node n is d-periodic if d>1 and aperiodic if d=1.

The definitions differ for the example described above with cycles (1, 2, 3, 4) (1, 2, 4) and (5, 6, 7, 8) and edge (4, 5). Nodes 5, 6, 7, & 8 have period 4, so are not aperiodic. Thus definitions 2) and 3) say the graph is not aperiodic, while definition 1) says the graph is aperiodic since gcd(3, 4, 4)=1. Definition 3) means disconnected graphs cannot be aperiodic because they have no globally reachable nodes. While 2) allows disconnected graphs so long as each connected part has every node aperiodic. There are many other examples where the definitions differ.

The Javis and Shier paper defines when a state is aperiodic. It does not talk about when a graph is aperiodic (other than a strongly connected digraph).

It does give (in Theorem 3) a statement that when a single strongly connected component with no outgoing edges has all nodes aperiodic then the usual nice properties for ergodic cases holds. It then immediately states that from that point on it will only consider the "important" case of a graph that is a strongly connected digraph -- and that such a graph is called aperiodic if the gcd of all cycles is 1.

The care with which the paper avoids defining "aperiodic graph" for anything other than an irreducible system is subtle but telling.

After much search for a "best" definition, I noticed that the definitions agree on every statement that requires both aperiodic and irreducible (or not decomposable, or strongly connected, or having a single communicating class). Until people start finding a use for looking at periodicity in a larger sense, I don't think there will be a definitive answer as to which definition is more useful. And, importantly, I should stop looking for a way to restrict the definitions to a single closed strongly connected component. The definition are all fine and agree in the case of a single closed strongly connected component.

Algorithms:
A closer look at the whole of the paper by Jarvis and Shier (linked here and above and cited both in our current docs as well as the wikipedia article) describes two algorithms. The first uses a depth-first-search in section 17.2.3 to order the nodes and (with other stored information from the DFS that is not described in this paper) can be used to identify the strongly connected components. This is essentially Tarjan's algorithm for finding strongly connected components (and we get them in their reverse topological sort order as a biproduct). The second uses a breadth-first-search and is intended to find the period of a strongly connected digraph. The paper states parenthetically that the graph must be strongly connected: A breadth-first search of the (strongly connected) digraph G visits all nodes of G in order of non-decreasing level. The paper then proceeds to describe how to find d during this BFS process.

The breadth-first-search approach presented in 17.3.2 is implemented in our code, though our code adds a check at the end and recursively calls if a condition is met. The result is that our code provides answers that contradict each definition of aperiodic graph given above. It doesn't make sense -- and that is because it was written and presented as only working for strongly connected digraphs. Our code should ensure that we are working with a strongly connected digraph G. It currently does not -- leading to surprising results and thus, this discussion.

Also note that the recursive part of our function is not part of the BFS algorithm from this article. (It is part of the description for the DFS algorithm though.) The recursive part will never be called with a strongly connected digraph. The authors must have added it as a way to extend the algorithm to more than just strongly connected digraphs. It was merged before we had pull requests and discussions, so there is no record. and there are no references. It seems to me to be incorrect.

Implementing algorithms for definitions 2 or 3 will be non-performant because they will require finding which cycles go through each node. We would need to find all cycles. And that approach will perform much worse on the important case of a strongly connected digraph than our current algorithm with the recursive part removed.

Other sources:
The definition from the Brown Univ lecture notes (linked above) is more generous in that it defines an aperiodic graph as a graph where every state is an aperiodic state. That can apply to a much larger class of digraphs. And the notes build on this definition to get theorems about ergodic features such as unique steady state probability distributions, etc. But the definition is only used in tandem with a restriction of a graph with a single connected component (where the two definitions agree).

A thesis from University of Toronto by Zhiyun Lin defines a stochastic, indecomposable and aperiodic (SIA) square matrix to be one that has the nice ergodic properties. It then provides and proves its Theroem 2.8: A stochastic matrix E is SIA if and only if its graph G(E) has a globally reachable node which is aperiodic. Notice that it doesn't call the graph aperiodic. It defines aperiodic nodes and uses them in this theorem. (The thesis also defines aperiodic graphs in the same way our docs do, but does not use that definition to prove anything -- so it is not clear that they considered it very thoughtfully.) The key wording that has changed here is that we need a globally reachable node to be aperiodic and we get SIA. That along with our Brown lecture notes leads me to believe that the correct way to extend our current function beyond strongly connected digraphs is to use the definition:

But we don't have an algorithm to find whether such a condition holds!! We could make one up like:

  • do an all-pairs-shortest-path sp on the reverse of the graph. Then check sp[node]==len(G) for each node and keep the nodes for which is it true. These are globally reachable nodes.
  • find the period for each of these nodes by performing BFS starting from that node. Any back edge coming back to the root node forms a cycle, and we track the gcd of all those cycle lengths. If the gcd is 1 for any globally reachable node, the graph is aperiodic.

But that algorithm is not performant. Applied to a strongly connected digraph it would require n BFS traversals instead of the 1 BFS traversal used in the current algorithm. And we have no reason to look for this definition of aperiodic

@fei0319

fei0319 commented May 10, 2025

Copy link
Copy Markdown
Contributor Author

Your definition that "a globally reachable node shoule be aperiodic" makes a lot of senses. We do have a performant algorithm for it actually, which runs at $O(n + m)$ time complexity.

Theorem:

If $G$ has exactly one attracting component, all nodes in that attracting component are globally reachable, and no other nodes are globally reachable.

If $G$ has more than one attracting components, all nodes in $G$ are not globally reachable.

So we only need to find attracting components of $G$ using nx.attracting_components, which runs at $O(n + m)$. If $G$ has more than one attracting components, we simply return False. Otherwise we perform the current algorithm on that attracting component.

Do you think we should use this algorithm? It is quite simple and performant!

Another consideration: the Brown University lecture says if there are multiple attracting components, as long as they are all aperiodic, the graph can still be aperiodic. It makes sense to me. What do you think? We have a performant algorithm for this as well.

@dschult

dschult commented May 10, 2025

Copy link
Copy Markdown
Member

Niiice... :)
What is the source for your theorem? It makes a lot of sense!

I had forgotten we have an attracting_components function. That helps a lot because we can just start the current algorithm with an arbitrary node from the attracting component. No need to worry about leaving the component.

And I think your idea of approaching multiple attracting components could work too. But definition 2) (Brown Univ lect notes) wants every node to be aperiodic, while definition 3) (Univ Toronto thesis) only needs any globally reachable node to be aperiodic.

To understand the difference, consider a graph consisting of two disconnected strongly connected components. One with period 1 and the other with period 2. So the Markov chain could end up being period 2. Or it could end up period 1 (aperiodic). Which of these happens depends on initial conditions. The ergodic results of a unique steady state probability distribution do not hold. (And they wouldn't even hold if both components were aperiodic (period 1)). The ergodic results must have a single attracting component. So what about the definition of aperiodic?

So, what should our homemade definition of an aperiodic graph give for this case? The graph as a whole has periodic nodes of period 2, so it should not be aperiodic, but it has some globally reachable nodes that are aperiodic so it should be aperiodic.

@fei0319

fei0319 commented May 10, 2025

Copy link
Copy Markdown
Contributor Author

I came up with the theorem myself. I have a simple proof attached.

It seems the confusing concept of "recurrence" brought some misunderstanding to us.

A state $i$ is said to be transient if, starting from $i$, there is a non-zero probability that the chain will never return to $i$. It is called recurrent (or persistent) otherwise.

This words from Wikipedia show that state $i$ is transient if it could leave and never return to $i$, i.e. it is not in an attracting component. Hence a state $i$ is recurrent if it is in an attracting component.

So the Brown University lecture notes (A Markov chain in which no recurrent states are periodic) basically means that a MC is aperiodic iff all its attracting components are aperiodic.

We have three options then:

  1. Raises an error for non-strongly-connected graphs (the easy way)
  2. Graphs with all attracting components being aperiodic are aperiodic (definition from the Brown University lecture notes)
  3. Graphs with the only attracting component being aperiodic are aperiodic (holds some ergodic features)

I am ok with all of them, maybe slightly biased towards [2] since it has an explicit endorsement and can also be mathematically justified. Others also make a lot of sense.

TL; DR:

These lines fix [2] (complexity will be $O(nm)$ in this minimal fix; it can be reduced to $O(n + m)$ in the full fix):

sinks = list(nx.attracting_components(G))
G = G.subgraph(nx.utils.flatten(sinks))

These lines fix [3] (complexity will be $O(n + m)$ in this minimal fix):

sinks = list(nx.attracting_components(G))
if len(sinks) > 1:
    return False
s = nx.utils.arbitrary_element(sinks[0])

A brief proof for the theorem:

It is evident that nodes in the same SCC are either all globally reachable or all not globally reachable. Then we can have each SCC contracted to a single node, and the resulting graph $\hat G$ is called the condensation of $G$. We only need to determine what nodes in $\hat G$ are globally reachable.

Because $\hat G$ is a directed acyclic graph, every maximal path starting at any node eventually ends at a sink (a node with zero out-degree), which corresponds to a attracting component in the original graph $G$.

If $\hat G$ has only one sink, then the maximal paths starting at any nodes end at that sink, which means there is a path from any nodes to that sink. Therefore the sink is globally reachable. Any other nodes are not reachable from the sink, so they are not globally reachable.

If $\hat G$ has multiple sinks, then the sinks are not reachable from each other, and they are therefore not globally reachable. Other nodes are not reachable from the sinks, so they are not globally reachable neither.

@fei0319

fei0319 commented May 11, 2025

Copy link
Copy Markdown
Contributor Author

After going through many references without finding one involves aperiodicity of reducible Markov chains, raising an error for non-strongly-connected graphs now makes much more sense for me.

I also read some textbooks. Most of them simply do not have a definition of aperiodicity for Markov chains; others mostly define a aperiodic Markov chain as one with all states aperiodic (Understanding Markov Chains, page 168; Dynamics of Markov Chains for Undergraduates, page 86). But we know all states being aperiodic doesn't make much sense.

We have some reasonable definitions for reducible MCs, but they disagree with each other.

Seems like we can never find a universal aperiodic definition for reducible Markov chains that everybody accepts. We should probably just raise an error for multiple-SCCs graphs, and those who want to research aperiodicity on reducible MCs can go with their own definitions with the help of nx.attracting_components. It reduces many complicated corner cases and can help with a reasonable and fast bug fix.

@Peiffap

Peiffap commented May 11, 2025

Copy link
Copy Markdown
Member

Both the docstring and the Wikipedia article mention DAGs in the context of periodicity, so I'm not sure we can just disregard all graphs that aren't strongly connected...

@dschult

dschult commented May 11, 2025

Copy link
Copy Markdown
Member

This sounds like a good approach to me -- and we could include an example in the doc-string of how to use attracting components for the simple two SCC/one attracting SCC example.

@dschult

dschult commented May 11, 2025

Copy link
Copy Markdown
Member

How can a DAG have periodicity? Acyclic is in the name. :)

Ahh -- I see... you are saying we should return False if it is acyclic.

But be careful with using the definition in wikipedia and in our docs. They are both mistaken in the same way -- . They are coming from the same article and that article includes quite clearly that this is defined for strongly connected graphs. So the definition doesn't apply to acyclic graphs even if both wikipedia and our docs give that as an example. We can fix both our docs and the wikipedia article.

Can you find anywhere else that aperiodic is discussed alongside acyclic graphs?

@Peiffap

Peiffap commented May 12, 2025 •

Copy link
Copy Markdown
Member

Yes, my comment was not particularly clear! I meant to say that the docstring and Wikipedia article mention that DAGs are not aperiodic. It seems to me like everywhere the two are mentioned together, someone is citing either the Wikipedia page, or the NetworkX docstring, and everyone seems to just accept it without questioning.

I have a hard time deciding whether definition (2) makes more sense than (3) or the other way around, which tells me the simplest approach (raising an error for graphs that aren't strongly connected) is probably the easiest to justify. I'd also be in favor of adding examples where we show how the alternative definitions can be implemented.

Note that given these discussions, I believe we ought to move the function to a different home in the codebase - it would make very little sense to keep a function in dag.py that... doesn't work for DAGs. :)

EDIT: I haven't had time to read about it in detail, but this seems like it might be of interest, if someone wants to dig deeper into it: https://en.wikipedia.org/wiki/Aperiodic_finite-state_automaton.

@fei0319

fei0319 commented May 12, 2025

Copy link
Copy Markdown
Contributor Author

Your suggestion about moving the code makes a lot of sense. I think "cycle" section can be a better place than "DAG" for is_aperiodic. It doesn't change the API.

I did a brief study on the aperiodic finite-state automaton you mentioned. To summarize:

  • Aperiodic monoid: a monoid in which for each element $x$ there exists a positive integer $n$ such that $x^n = x^{n+1}$.
  • Transition monoid: a monoid in which each element $f$ is a function from a node to itself or another node. The product of two element $f$ and $g$ is defined as $(fg)(x) = f(g(x))$. In a determistic finite automaton, such an element $f$ means a directed graph where each node has exactly one outgoing edge, representing a mapping in $f$.
  • Aperiodic transition monoid: a monoid in which for each element $f$ and each node $x$ there exists a positive integer $n$ such that in the accordant graph of $f$, the walk of $n$ and $n + 1$ steps starting from $x$ end at the same node. This means every weakly connected components in every $f$ must have a self-loop.
  • Aperiodic finite-state automaton: A finite-state automaton whose transition monoid is aperiodic.

So aperiodicity in this context means a self-loop for every weakly connected components. It is a different concept with a same name.

@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.

@fei0319 any thoughts about what to do with this one now that #8029 is in? It may be easiest to start with a fresh PR now that the fact that aperiodicity isn't considered for graphs with multiple components is merged. Whatever you think!

@fei0319

fei0319 commented May 24, 2025

Copy link
Copy Markdown
Contributor Author

@rossbar thanks for keeping an eye on this issue! I will close this PR now and, once I am ready, cleanly continue our work on a new PR.

@fei0319 fei0319 closed this May 24, 2025
@Peiffap

Peiffap commented Jul 10, 2025

Copy link
Copy Markdown
Member

There was some interesting discussion in this PR! @fei0319 are you still interested in working on some of these changes?

@fei0319

fei0319 commented Jul 11, 2025

Copy link
Copy Markdown
Contributor Author

@Peiffap thank you for your concern on this topic! I am sorry that I have been busy lately and can't work here in the near future. Feel free to work on the changes if you are interested!

Peiffap added a commit to Peiffap/networkx that referenced this pull request Jul 14, 2025
Peiffap added a commit to Peiffap/networkx that referenced this pull request Jul 14, 2025
Peiffap added a commit to Peiffap/networkx that referenced this pull request Jul 14, 2025
Peiffap added a commit to Peiffap/networkx that referenced this pull request Jul 14, 2025
Peiffap added a commit to Peiffap/networkx that referenced this pull request Jul 14, 2025
dschult pushed a commit that referenced this pull request Jan 18, 2026
* fix: add suggestions from gh-8021 and gh-8029 to `is_aperiodic`

Co-authored-by: Fei Pan <[email protected]>

* clarify null graph test for

* Don't compute gcd for forward edges

* Add test with multiedges

* add benchmark for

* switch to dfs and add comments

* rename benchmark

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

---------

Co-authored-by: Fei Pan <[email protected]>
Co-authored-by: Ross Barnowski <[email protected]>
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.

5 participants