Manuscript Offprint
arXiv:2611.07925Efficiently Estimating Cycle Statistics on Graphs via Spanning Trees
Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.
Josef Hoppe and Michael T. Schaub*
RWTH Aachen University
(Dated: November 6, 2026)
Simple cycles encode feedback and alternative routes in networks and are important for routing problems, the convergence of dynamical processes on networks, message passing and belief propagation, or even static network characterizations such as structural balance in signed networks. Being able to assess and sample from the cycle structure of a graph is thus of interest in many analysis contexts. However, due to the combinatorial growth of the cycle space with graph size, the computational cost for such sampling is high. Therefore, we here introduce a sampling framework that enables us to sample from the cycle structure without enumerating all cycles. Specifically, the method draws uniform spanning trees and collects the fundamental cycles created by their non-tree edges, such that each tree provides an informative subset of simple cycles. Because cycles are included with unequal probabilities and are dependent within each subset, we formulate an inclusion-probability-based Horvitz-Thompson estimator, which we average over random subsets, a procedure we call Monte Carlo Horvitz-Thompson. For this, we sample multiple Horvitz-Thompson estimators and introduce a method to further subsample the individual estimators for increased computational performance. For sampling cycles, the estimator is unbiased if exact cycle inclusion probabilities are known. To extend the method to larger networks, we derive an efficient mean-field approximation for the inclusion probabilities and characterize the graph regimes in which it remains accurate. Experiments on synthetic and real-world networks demonstrate the computational scaling and statistical performance of the framework. We then illustrate the utility of Monte Carlo Horvitz-Thompson estimation by estimating cycle counts and cycle-level frustration statistics in signed spin systems. An implementation is available in the py-raccoon package.
Keywords: Simple cycles, uniform spanning trees, inclusion-probability estimation, cycle counting, signed networks
I. INTRODUCTION
Simple cycles, i.e., closed paths with no repeated vertices other than the initial and terminal vertex, are among the most basic nonlinear structures in a graph. They identify alternative routes, feedback, topological holes, and local redundancy, and their abundance across different lengths provides information that is not accounted for by degrees or pairwise distances alone. Cycle structure consequently appears in a broad range of network-analysis problems. In graph classification, cycle counts can provide features that increase the expressive power of graph neural networks [1] beyond the Weisfelter-Leman limit [2, 3]. In signed social networks, the parity of negative edges around cycles is central to structural balance and polarization [4–6]. Cycles also describe circular exchange opportunities in financial networks [7] and can be used to reconstruct cyclic structure from observed flows [8]. In cellular pathway analysis, elementary flux modes are directed cycles that form positive feedback loops [9, 10] and are widely studied. In ecological network analysis, the relevance of cycles compared to non-cyclical paths is described by different cycle-based metrics [11–13].
However, computing simple-cycle statistics presents a computational bottleneck. The number of simple cycles can grow exponentially with graph size, and exact counting is computationally hard in general [14, 15]. Exact
enumeration is therefore most practical for graphs with manageable numbers of cycles or analyses restricted to short cycles [15, 16]; enumerating longer cycles is typically expensive even with strong algorithmic optimizations [5, 17].
This limitation is noted and dealt with differently in a wide variety of works. For some applications, researchers limit their analysis to graphs where an exhaustive enumeration or exact computation is possible [13, 18]. In research on elementary flux modes, many different task-specific optimizations exist, but do not fully meet the need for scalability yet and research is ongoing [10]. Another alternative is to replace simple cycles by closed walks, which are more amenable to methods from linear algebra [6]. This substitution is always possible, but a closed walk may revisit vertices and edges and therefore need not represent the same structural object as a simple cycle.
Moreover, counting is only one of several relevant tasks associated with cycles. Applications may require the computation of the distribution of a cycle statistic, an average over all cycles of a given length, or the fraction of cycles satisfying a property. Examples include the fraction of unbalanced cycles in a signed network, the distribution of gains over circular exchanges, and cycle-based anomaly or feedback scores. These tasks motivate sampling methods that expose individual simple cycles without first enumerating the full population. Ideally, we would draw cycles uniformly at random from all cycles of a chosen length. In practice, direct uniform sampling is difficult because this population can be too large to enumerate and its size is generally unknown.
- {hoppe, schaub}@rwth-aachen.de

FIG. 1: Overview of Monte-Carlo Horvitz-Thompson with spanning trees to estimate cycle statistics.
We address this problem by indirectly sampling simple cycles through their association with uniform spanning trees. Every spanning tree provides a compact view of the graph's cycle structure: adding any non-tree edge to the tree creates one fundamental simple cycle. Sampling a uniform spanning tree therefore produces an entire subset of cycles in one iteration, and efficient algorithms such as Wilson's algorithm make the tree draw itself tractable. This construction has two important consequences. First, the cycles within a sampled subset are dependent, since they share the same tree. Second, different cycles need not have the same probability of appearing: a cycle is included exactly when the sampled tree contains all but one of its edges. Treating the observed cycles as uniform individual samples would consequently lead to biased estimates.
The appropriate correction for a single uniform spanning tree can be naturally accounted for in terms of inclusion probabilities via a Horvitz-Thompson [19] estimator. It needs only the marginal probability that each object is included and does not require independence among objects within a subset or an explicit probability distribution over all possible subsets. Thus, cycles may share edges or vertices without compromising unbiasedness, although this dependence affects the variance. Using Monte Carlo averages over multiple such uniform spanning trees, we can then estimate the desired cycle statistics, closing the methodological gap we identified.
Here, the inclusion probabilities are determined by the spanning-tree sampling process, which contrasts with the standard usage of HT estimators, in which the sampling design can typically be chosen. To further reduce the cost of evaluating these inclusion probabilities, we also consider an estimator that subsamples one cycle of the chosen length from each nonempty subset. This additional sampling step preserves unbiasedness for totals when exact inclusion probabilities are used, with potentially higher variance than using the full subset. We refer to Monte Carlo averaging of the per-tree HT estimates as Monte Carlo Horvitz-Thompson (MCHT) estimation.
Contributions. Our main contributions are as follows. First, we develop Monte Carlo Horvitz-Thompson estimat-
tors for arbitrary object populations and apply them to compute cycle statistics as seen in Figure 1. We clarify the relation of our estimators to importance sampling and compare the full-subset estimator with one that selects one cycle from each nonempty sampled subset.
Second, we derive an exact expression for the inclusion probability of each fundamental cycle induced by a uniform spanning tree.
Third, we derive a mean-field approximation that permits near-linear evaluation of the inclusion probabilities for cycles of a fixed length induced by each sampled tree, in addition to the cost of generating the tree. Using this approximation can introduce bias into the estimates.
Fourth, we characterize the limitations on sampled cycle lengths arising from uniform spanning tree diameters and empirically study runtime, probability-approximation error, and estimator convergence on synthetic and real-world graphs.
Finally, we demonstrate the framework for two tasks: estimating cycle counts and estimating frustration statistics in signed spin systems.
Outline. Section II introduces notation and preliminaries. Section III describes the spanning-tree construction and exact inclusion probabilities, and Section IV develops Monte Carlo Horvitz-Thompson estimation. Section V presents the scalable inclusion-probability approximation, Section VI discusses the lengths of cycles that can be sampled, and Section VII evaluates runtime and the probability approximation. We then apply the estimators to cycle counting in Section VIII and cycle-level frustration in Section IX.
For finite-population totals, ordinary importance sampling is closely related to Hansen–Hurwitz [20] estimation. We use the importance-sampling terminology here.
letters for their realizations (e.g., ). For simplicity, given a set , we denote sampling from the uniform distribution over as instead of .
A. Graphs and Simple Cycles
We consider undirected graphs with vertices and edges. We denote the degree of a vertex by , the mean degree by , and the graph Laplacian by , where is the adjacency matrix and the degree matrix of . We write for an Erdős-Rényi (ER) random graph [21, 22]: for each unordered pair of distinct vertices, the corresponding edge is present independently with probability . In our mean-field calculations we will consider a graph as a realization of to simplify calculations.
A cycle is a closed simple path on ; its length equals the number of vertices (or edges) in . We denote the set of all cycles in by . We use to denote the set of all cycles with length and to denote the number of cycles of length on a graph. If vertex or edge is part of the cycle , we write or , respectively. Without loss of generality, we assume that all graphs are connected. Indeed, on a graph with multiple connected components, cycles are contained within connected components, so counting and sampling can be performed independently on each component.
B. Importance Sampling
Importance sampling (IS) is a Monte Carlo technique to estimate expectations under a probability distribution when direct sampling from or direct evaluation of the expectation is difficult. For a full introduction to importance sampling, we refer the reader to [23–25]. Let be a random element of with probability distribution , that is, . Given a function , we are now interested in estimating the quantity:
where the expectation is taken with respect to . The idea of importance sampling is to draw samples from an easier-to-sample proposal distribution and reweight the samples by
The ratio compensates for over- and undersampling: objects that are more common under the proposal receive less weight, while rare objects receive more weight. If whenever (support condition), then
Thus, let us consider random objects and denote their realized values by . The importance-sampling estimate computed from these realizations is
In many applications, is known only up to a normalization constant (partition function), i.e., with unknown . Then we can use the self-normalized importance sampling estimator
As the constant Z cancels in the ratio, only unnormalized densities are needed. In Section IV, we use the symbol for inclusion probabilities under subset sampling; unlike , is not a normalized probability mass function over cycles.
C. Horvitz-Thompson Estimators
Horvitz-Thompson (HT) [19] (see also [26]) estimation is a method for estimating totals of a finite universe where each sample consists of a random subset . The subset is characterized by unequal inclusion probabilities for , which are not necessarily independent. To unify notation with importance sampling and our method, we denote the inclusion probability by and represent the quantity to estimate as a function . The HT estimator now estimates the population total for an element-wise quantity from a concrete subset as follows:
Like importance sampling, this estimator weights individual objects inversely to their inclusion probability. For the same reason, this estimator is unbiased as long as whenever , i.e., .
Many applications use HT to design a single estimator, often for stratified sampling, or combine multiple different designs. In contrast, we are considering a sampler of subsets that are defined by inclusion probabilities, which we cannot control. Because we have no direct control of the inclusion probabilities, we adjust the effective sample size by combining multiple HT estimates into a Monte Carlo average instead.
There are also other methods in the literature that can be seen as HT sampling with identical inclusion probabilities. For instance, the number of occurrences of treewidth-limited subgraphs can be estimated using random node colorings, considering only subgraphs that contain one node of each color [27]. Similarly, one can estimate the total number of triangles by only considering monochromatic edges and counting the triangles on these [28]. Alternatively, edges can directly be removed with a certain probability, which leads to an efficient estimator for the number of triangles [29]. If applied or extended to cycles, all three approaches take exponential time in the length of the cycles to estimate the cycle count.
III. TAMING THE CYCLE SPACE WITH SPANNING TREES
The set of simple cycles in a general graph is difficult to characterize directly. In this section, we use spanning trees to obtain a structured, but biased, view of that set. By quantifying this bias, we can apply importance sampling to estimate cycle-level quantities.
A. Cycle Space, Cycle Bases, and Uniform Spanning Trees
Every spanning tree on a graph induces a set of (simple) cycles (which is also a cycle basis [30]): each additional edge that is not part of creates a cycle consisting of the path from to on and the edge . The set of all such induced cycles is denoted by . It contains exactly cycles, one for each non-tree edge. For fixed cycle length , we use .
A uniform spanning tree (UST) is a spanning tree picked uniformly at random from all spanning trees on a given graph. Uniform spanning trees can be efficiently obtained, e.g., by Wilson's algorithm [31]. We denote the set of spanning trees by , abbreviate it as when the graph is fixed, and write for a random uniform spanning tree. By Kirchhoff's matrix-tree theorem, the number of spanning trees in a graph is the determinant of the graph Laplacian with one row and the corresponding column removed [32]:
Here is the submatrix obtained by deleting the row and column of an arbitrarily chosen vertex ; the resulting determinant (3) does not depend on that choice. We adopt the standard convention when consists of a single vertex, so that the determinant of the corresponding empty matrix is one.
Let denote a simple path, with vertex set and edge set . The probability that all edges of this path are included in a uniform spanning tree is
Besides certain random walk formulations [33, 34], this path-inclusion probability can be computed by spanning-tree counting: if all edges of the path are contracted, then the spanning trees of the contracted graph are in bijection with the spanning trees of that contain . Hence,
where denotes the graph obtained by contracting all edges of , and both terms can be obtained from their respective Laplacian cofactors (3).
Note that as path contraction may create parallel edges (the contraction may be a multigraph), for the validity of the formula the multiplicities of the edges must be retained as edge weights in the contracted Laplacian. As the Laplacian is invariant to the addition of self-loops, these loops do not contribute to the matrix-tree cofactor.
B. Induced Cycle Inclusion Probabilities
For our cycle sampling procedure, we need the inclusion probability of a cycle in the set of induced cycles of a tree, rather than the inclusion probability of a path. How can we calculate this from the path inclusion probability? First, we can write as a proportion of trees:
Each cycle c can be induced by any of the paths that are missing one edge e in c:
While we could compute this equation for in practice, we can further simplify it by looking at the different graphs we obtain by contracting the path in . When contracting a path , all nodes in the path will be merged into one node and all edges between these nodes become self-loops. Figure 2 illustrates this on a small toy graph. The contracted node will thus have the same number of edges to every node (including itself), irrespective of the selection and order of edges that are contracted. Thus, , i.e., the number of spanning trees only depends on the contracted nodes. In other words, all paths have the same probability. We simplify by multiplying the probability of any of the paths by the length of the cycle:

FIG. 2: Top: A simple cycle on a toy graph. Middle: Two paths that, if included in a spanning tree, induce the cycle; and their edge contractions. Bottom: The cycle contraction. All three contractions result in the same multigraph (after deleting self-loops).
C. Importance Sampling of Simple Cycles with Uniform Spanning Trees
The construction of cycles via spanning trees also leads to a simple single-cycle sampling procedure for cycles of length . The idea is to first sample a tree and then a random non-tree edge, retrieving one cycle. The probability of obtaining this cycle is then
In practice, we often have to set for cycles that do not have the correct length. This is mathematically similar to rejecting the sampled cycle. We could also explicitly implement rejection sampling by rescaling the inclusion probability by the inverse of the (empirical) probability to obtain a desired cycle. For normalized expectations, this common factor cancels in a self-normalized estimator. For unnormalized totals such as a cycle count, it must instead be known or estimated.
Depending on the graph, and especially in the limit for large graphs, this will lead to many estimates of 0 or many rejections, respectively, leading to an increased variance of the estimator. This makes it necessary to sample a large number of trees to obtain an accurate estimate,
making the strategy impractical for many applications. The core issue is the usage of only one cycle per tree in IS. In the next section, we will introduce an alternative approach that samples multiple trees and averages over the Horvitz–Thompson estimators of the resulting cycle sets.
IV. MONTE CARLO HORVITZ–THOMPSON WITH UNIFORM SPANNING TREES
The importance sampling construction in the previous section discards most of the cycles induced by a sampled tree. In this section, we will discuss a per-tree HT estimator, using all induced cycles of the desired length. Then, we derive an estimator more similar to standard importance sampling by subsampling the Horvitz–Thompson estimator. This reduces the number of cycle inclusion probabilities we need to calculate, which speeds up computation at the cost of a higher variance in the estimator. Finally, we show that both estimators have a substantially lower variance than the importance sampling approach introduced in the previous section.
The cycle sampling procedure directly lends itself to HT estimation: Usually, we want to sample over the universe of cycles of a certain length . The random set can be identified with the set of cycles from a uniform spanning tree , and we know the inclusion probability from Equation (4). To get a more accurate estimate, we apply a Monte Carlo approach, i.e., we sample USTs and average over the HT estimators:
The different spanning trees are independent, and the individual HT estimates are unbiased. Thus, the Monte Carlo estimate is unbiased and its standard error is smaller than that of a single HT estimator by a factor of .
For a task estimating the average over a population (like in IS), we can use a self-normalized version.
The current estimator has one drawback: Unlike standard importance sampling, it requires the calculation of a large number of inclusion probabilities. Section V introduces an approximation of the inclusion probability that can be efficiently calculated. However, we can also use the Horvitz–Thompson estimator from above to derive a single-cycle estimator that is strictly better than the importance sampling introduced in Section III.
For this, we use an unbiased sampler for the HT estimator:
Thus, the Monte Carlo one-cycle (MCOC) estimator is also unbiased (but may have a higher variance than Monte Carlo Horvitz–Thompson):
Retrieving a random cycle from the set of induced cycles with the desired length is tempting, but since this set does not have a fixed size, the resulting inclusion probability is infeasible to compute.

FIG. 3: Mean-field treatment of the Laplacian-random-walk transitions. Red vertices have fixed potential one, blue vertices are current, and black vertices have already been visited. The first and final two transitions receive separate corrections because adjacency to the target is known. Appendix A gives the formulas.
Algorithm 1 MCHT cycle estimation from USTs
Require: connected graph , length , tree count , contribution , probability mode
1:
2: for do
3: sample a uniform spanning tree
4: for each non-tree edge do
5: let be plus the unique path in
6: if then
7: compute or
8:
9: end if
10: end for
11: end for
12: return
We can compare this to IS as described in Equation (5): If at least one cycle of the desired length is induced by a tree , the standard importance sampling approach returns one with probability
Remark 1 (Effective sample sizes of MCOC and IS). With growing graph size, we find longer cycles induced by almost all spanning trees. For these cycles, MCOC provides one independent sample per sampled tree, whereas IS only provides a sample with probability . This smaller effective sample size translates to a larger variance in the estimator.
This transitively implies that MCHT sampling leads to an even smaller variance.
A. End-to-End Cycle Estimation
Algorithm 1 summarizes the overall procedure to estimate for one cycle length . In practice, we can estimate this total for all occurring lengths at the same time; the pseudocode only omits that for simplicity.
V. IMPROVED SCALING BY APPROXIMATING THE CYCLE INCLUSION PROBABILITY
The exact inclusion probability based on the determinant is useful for moderate problem sizes, but can become a computational bottleneck on larger graphs. To avoid this, we design a mean-field approximation of that, using the sampled spanning tree, can be calculated in near-constant time per cycle. The full derivation can be found in Appendix A. Here, we will only give an intuitive overview.
To achieve this, we replace the calculation of based on counting spanning trees by a calculation based on a loop-erased random walk, which is also how USTs are usually sampled [31]. The probability of a loop-erased random walk choosing a path is the same as the probability of a Laplacian random walk [33, 34]. The Laplacian random walk allows us to calculate step-wise transition probabilities. Finally, we design a mean-field approximation of the individual steps that can be calculated efficiently over a spanning tree, i.e., decomposed into a multiplicative node-wise and additive edge-wise component.
A loop-erased random walk can be obtained by performing a random walk from a source until it hits a target , erasing loops whenever a vertex is visited twice. Wilson's algorithm [31] samples uniform spanning trees by starting with a root node that is part of the tree, and then performing a loop-erased random walk from each vertex until it hits the tree, adding the walk to the tree. Since USTs can be constructed this way, it is intuitive that loop-erased random walks between two points have the same probability distribution as taking the path between the same points from a UST (proven in [35]). However, the probability of obtaining a loop-erased random walk is infeasible to describe directly due to the loop erasure.
Instead, we use the Laplacian random walk, which shares the same probability distribution [33, 34]. Intuitively, the Laplacian random walk biases the transition, weighting it by the probability that a loop-erased random walk taking that transition will reach the target without erasing a loop. Trivially, this means that the target node has weight 1, and visited nodes (including the current

FIG. 4: Path aggregation on a rooted spanning tree. Prefix sums and products from the root, together with lowest-common-ancestor queries, give the aggregates on every induced simple cycle.
node) have weight 0. All other nodes have a weight that is the average of their neighbors' weights (since the loop-erased random walk chooses from all neighbors uniformly). The resulting path probability is exact and equivalent to the one obtained using the determinant.
To speed up computation, we apply a mean-field approximation, as illustrated in Figure 3. This approximation can only use limited information in order to still fit the efficient calculation over the spanning tree. First, we approximate the weight of all unvisited nodes with the mean-field approximation, i.e., based on the number of target nodes and visited nodes. We can divide the steps into the first, last, second-to-last, and intermediate steps. In the first step, one of our neighbors is the target node, and all other neighbors are unvisited. In intermediate steps, we know that one neighbor (the next node) is unvisited and one neighbor (the previous node) is visited; for all remaining neighbors, we assume mean-field connectivity to all other nodes (visited, unvisited, target). In the penultimate step, we have additional information about the next node, namely that it has the target node as a neighbor. In the final step, the next node is the target node, and we assume mean-field connectivity to visited and unvisited nodes.
For and , these factors can be combined into functions only depending on global properties and local node degrees as
This mean-field approximation consists of a global correction factor , a per-edge factor that needs to be summed over the path, and a per-node factor that needs to be multiplied over the path. Instead of iterating over the induced cycles, we can decompose the sum and product components into paths from the root to different nodes. The following subsection discusses how we can efficiently calculate the mean-field approximation.
A. Algorithmic Complexity
After introducing our approximation , we now analyze the computational complexity of calculating it for all cycles induced by one spanning tree.
Theorem 1. Let be a connected graph with , fix a length , and let denote the expected number of random-walk steps required by one run of Wilson's algorithm for the chosen root and vertex order. For independent trees, computing our cycle inclusion probability approximation for every induced cycle of length has expected runtime
Apart from the graph-dependent cost of drawing the tree, one sample requires essentially linear work in the graph size; the inverse Ackermann factor grows so slowly that it is below five for all practical input sizes.
Proof. Wilson's algorithm [31] takes time linear in the number of random-walk steps it performs; its expected contribution is therefore . This quantity depends on the graph, root, and vertex order and should not be identified with a single pairwise hitting time. Hitting-time results nevertheless explain why Wilson sampling is fast on many dense random graphs and can be much slower on worst-case graphs [36, 37].
For each occurring length , the global factor is computed once. Each cycle is induced by a non-tree edge and consists of the edge and the path from to in the tree. We split the calculation of Equation (9) into , where denotes a sum and a product over the path . Defining and recovers , because is the union of the non-tree edge and the tree path .
To calculate and for the required vertex pairs, we start at the root and traverse the tree (cf. Figure 4). From the definitions, and . For a vertex with parent , we calculate and . We can then obtain and in constant time from the lowest common ancestor of and :
We can calculate and for all vertices in by traversing the tree from the root downwards. Equations (10) and (11) have to be calculated only once for each edge that is not part of the tree, i.e., . To compute the lowest common ancestor (lca) of all required pairs, we use Tarjan's off-line lca algorithm [38], which runs in per tree, where is the inverse Ackermann function.
By multiplying with the number of sampled spanning trees s, the theorem follows.
Remark 2 (Complexity of calculating cycle lengths). The length of the cycle induced by is depth depthdepth(lca. Calculating the depth of all vertices in a tree requires a traversal in ; for each cycle, the calculation takes constant time.
B. Limits of the Probability Approximation
The approximate probability of sampling a cycle only depends on the length and the degrees of the vertices. As an example, consider k-regular graphs, where all vertices have the same degree. Therefore, the approximated inclusion probability cannot distinguish cycles of the same length and gives the same estimate for them. However, different cycles may have different sampling probabilities. The approximate probability fails to capture this. In physical terms, the approximation retains local coordination numbers but discards where those vertices sit in the global geometry. Similar effects can happen on non-regular graphs, especially with strong structure.
In practice, this may or may not have a relevant impact depending on the metric considered. If it is potentially relevant, the magnitude can be estimated by choosing a small number of cycles to calculate the probability exactly and comparing the probabilities to the approximate probability. In Section VII, we will empirically analyze the accuracy on different real-world and synthetic graphs.
VI. ON THE LENGTHS OF SAMPLED CYCLES
Counting the number of cycles of an arbitrary length is #P-hard [14]. Like any approach, the spanning-tree-based method is limited by this, but it is interesting to see when and especially how the limitation manifests. In this section, we discuss the behavior of spanning trees and how this limits the length of efficiently sampleable cycles.
Trivially, every cycle on a graph can be induced by at least one spanning tree. However, the length of induced cycles is at most one plus the diameter of the spanning tree. The diameter of uniform spanning trees has been extensively studied. For sufficiently high-dimensional graphs, the diameter is in [39–41], including the complete graph , dense Erdős-Rényi graphs, and integer lattices of dimension . In special cases, the expected diameter is larger. For example, for 2D grid graphs, this is [42, 43].
This does not make it impossible to obtain cycles of arbitrary length using spanning trees. However, it requires sampling an ever-increasing number of trees to do so, limiting computational feasibility.
As a worst-case illustration, we consider Hamiltonian cycles (i.e., cycles of length ) on the complete graph . A Hamiltonian cycle is only induced by a Hamiltonian path (viewed as a spanning tree), of which exist in . Thus, the probability of finding a cycle of length is
(13)
In other words, to find cycles of length , in the worst case we need to sample a number of spanning trees that is exponential in the size of the graph. In practice, we see an exponential decrease in the probability of finding a cycle between and .
While there is no directly comparable approach in the literature, Giscard et al. [5] introduced an efficient cycle-based sampling algorithm that is still exponential in the length of sampled cycles. Thus, our approach provides a relevant improvement in the length of cycles that can be efficiently sampled, even though the theoretical limitation makes the sampling of arbitrary cycles infeasible.
VII. EMPIRICAL EVALUATION
Analogously to the theoretical considerations, we first evaluate the runtime of different approaches, then investigate the lengths of sampled cycles and the accuracy of the probability approximation. Finally, we look at the accuracy and convergence in two application examples and use the results to discuss when to use which configuration.
The evaluation code is available at github.com/josefhoppe/cycle-statistics.
A. Empirical Runtime
For the analysis of the runtime, we also compare to the current state-of-the-art Monte Carlo method for estimating balance by Giscard et al. [5]. The Giscard Monte

FIG. 5: Runtime on Erdős–Rényi graphs for sampled trees and 10 subgraphs of size (Giscard); mean and standard deviation over 10 graphs (5 for Giscard). MCOC evaluates one exact inclusion probability for every length observed more than once per tree on average. Exact probability unless noted as MF.
Carlo method samples connected node-induced subgraphs of fixed size, uses an exact algorithm with exponential runtime to calculate the balance of the subgraph, and takes the average degree of balance as its overall estimate.
In their paper, Giscard et al. show measures for maximum cycle lengths between 15 and 18; they note that they obtained the best results for subgraph sizes between 20 and 30. Thus, for our comparison, we also set . Note that with a constant number of sampled induced subgraphs and growing graph size, Giscard's algorithm cannot cover all nodes in the graph, whereas the spanning-tree-based approaches do. Additionally, the spanning-tree-based approaches cover increasingly longer cycles. In other words, the comparison is somewhat biased in favor of Giscard's algorithm.
Figure 5 compares the runtime of the MCHT estimator with exact and approximated probabilities, the MCOC estimator with the exact probability, and the Giscard method. Empirically, the runtimes for the approach are in line with our analysis as it takes approximately , which is consistent with since for a fixed . The MCHT estimator with approximated probabilities scales much better than any approach with exact probabilities, but the one-cycle estimator with exact probabilities is viable for larger graphs than MCHT with exact probabilities. Giscard's estimator exhibits the longest runtime by a large margin. We also evaluated the runtime on real-world networks (cf. Figure 13), which qualitatively lines up with the synthetic experiments. Here, approximated MCHT is practical to use even for networks with more than edges.
All algorithms considered are highly parallelizable as each spanning tree or subgraph can be sampled independently (which is not currently implemented for the spanning-tree-based ones, but easy to achieve with the PyPI package). Still, for practical applications, the size of the graph will determine which approaches are feasible, potentially excluding the slower ones altogether.
B. Lengths of Efficiently Sampleable Cycles
As mentioned in Section VI, for the dense random-graph regime considered here, the diameter of a uniform spanning tree is of order . Figure 6 confirms the corresponding scale for the length of cycles that are frequently observed, and shows that, for ER graphs, this length grows from about at over at to at , with only a small dependence on . With a decreasing number of cycles, MCHT and MCOC converge to the same estimator.
With increasing lengths, there is a steep decline in the number of cycles found. In other words, finding cycles with a length of order of is feasible, but finding longer cycles leads to an exponential number of samples required.
C. Approximation Accuracy
First, we compare the mean-field cycle inclusion probability with the exact value on different Erdős–Rényi configurations. Given a graph, we sample multiple spanning trees and calculate and for every cycle induced by those trees. Then, we repeat the procedure on other synthetic and real-world graphs to investigate the broader applicability of our approach to cycle sampling. Because validation cycles are themselves obtained from uniform spanning trees, these plots weight cycle in proportion to its inclusion probability . They therefore describe approximation accuracy under the sampling distribution, not uniformly over all cycles. Rare cycles, whose inverse weights can dominate estimator variance, are underrepresented.
Figure 7(a) shows close agreement between exact and approximate probabilities in the denser graph. A baseline using cycle length alone has visibly larger errors (Figure 14), showing that local degree information improves the accuracy significantly.
However, as Figure 7 (b) shows, for graphs that are relatively sparse, the accuracy drops. This is likely a result of graphs with smaller edge probabilities behaving more differently from the expected graph: Our approximation implicitly assumes a relatively densely and evenly connected graph. Sparse configurations of ER are more likely to deviate from this expectation than dense configurations: The degree distribution is less uniform and a (partial) path is more likely to 'cut off' parts of the graph due to the lower connectivity.
For graphs that are not sampled from the Erdős–Rényi model, the accuracy strongly depends on the structure. If the graph is globally and relatively evenly connected, the approximation is still accurate. We verified this with a number of synthetic examples in Figure 15 (a)–(e), where our approximation is fairly accurate on most graphs.
On graphs with a macro structure that is uneven, the accuracy drops dramatically. In a barbell graph (Figure 15 (f)), all cycles are contained in one of the complete subgraphs. However, the other vertices are still treated

a

b
FIG. 6: Lengths of cycles exposed by uniform spanning trees. (a) Number of induced cycles (by length) over spanning trees on Erdős-Rényi graphs with ; one line for each of 50 runs on different graphs, the red line marks (one cycle per tree on average). The most common length is near the scale, while cycles with still appear about once per tree on average. (b) Largest for which more than 1000 cycles were induced by spanning trees; means and standard deviations are over 50 runs on different graphs for each and . The largest well-observed length is empirically consistent with scaling in this dense random-graph regime.

a

b
FIG. 7: Exact versus mean-field cycle inclusion probabilities for cycles exposed by ten USTs on Erdős-Rényi graphs with and (a) (209 edges) or (b) (63 edges); the right panels show the relative error . The approximation is more accurate on the denser Erdős-Rényi graph.
as unvisited and potentially reachable, leading to an overestimate of the cycle inclusion probability. The most notable deviations occur in Delaunay triangulations of the plane and two-dimensional grid graphs (Figure 15 (g) and (h)). Here, we see a systematic underestimation of the cycle inclusion probability for long cycles. This stems from the fact that the graph, while well-connected, has a large diameter and in nearly all steps, the target vertex is a neighbor with probability 0 instead of . More generally, this mechanism arises when different vertices are much easier or harder to reach, especially with a greater shortest path length (or diameter). To a lesser degree, this can also be observed on the stochastic block model (SBM;
Figure 15 (c)), and likely many real-world networks.
Our experiments on real-world networks in Figure 16 support these observations, with most graphs producing fairly small approximation errors. Graphs that have a comparatively large diameter or are (globally and nearly) planar show a systematic error, as indicated by our synthetic experiments.
VIII. APPLICATION: APPROXIMATE CYCLE COUNTING
Counting the cycles of a given length is #P-hard [14]. However, we can easily design a Horvitz-Thompson estimator for the number of cycles of a certain length by
The mean-field model underestimates connectivity to the target: within the clique the target is adjacent at every step, whereas the approximation averages over possible target adjacency.
TABLE I: Relative standard error of the mean (SEM/) and multiplicative bias (where statistically significant) of the cycle count estimation for , each sampled from 1000 spanning trees. Note that the bias of all approximated approaches is the same in expectation, but due to differences in the variance, some biases are not statistically significant. 'Count' derived from exact MCHT sampling. 'er' is a graph, 'grid' a grid, and 'delaunay' the Delaunay triangulation of 50 uniformly random points. Real-world datasets retrieved from Netzschleuder, https://networks.skewed.de, same naming convention.
| Graph | n | l | Count | mean | MCHT | MCOC | IS | |||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| exact | approx | exact | approx | exact | approx | |||||||||
| polbooks | 105 | 11 | 14.8 | 0.03 | - | 0.03 1.29 | 0.06 | - | 0.06 1.26 | 0.29 | - | 0.30 | - | |
| contact | 274 | 17 | 56.6 | 0.06 | - | 0.06 1.75 | 0.09 | - | 0.10 1.66 | 0.43 | - | 0.44 | - | |
| grid | 100 | 10 | 6.0 | 0.01 | - | 0.01 2.18 | 0.02 | - | 0.02 2.18 | 0.12 | - | 0.13 2.05 | ||
| er | 100 | 10 | 25.4 | 0.02 | - | 0.02 1.20 | 0.03 | - | 0.04 1.22 | 0.16 | - | 0.17 | - | |
| delaunay | 50 | 8 | 3.8 | 0.02 | - | 0.02 1.77 | 0.02 | - | 0.03 1.78 | 0.16 | - | 0.18 | - | |
| karate | 34 | 6 | 5.1 | 0.02 | - | 0.03 2.08 | 0.03 | - | 0.04 2.09 | 0.11 | - | 0.14 2.16 | ||
| football | 115 | 11 | 20.0 | 0.01 | - | 0.01 1.48 | 0.02 | - | 0.02 1.50 | 0.19 | - | 0.18 | - | |
setting :
A cycle observed with probability represents, on average, cycles in the full population. From this definition of , we can directly derive MCHT and MCOC as unbiased estimators and substitute the mean-field approximation for a faster but potentially biased estimator.
This also works as an importance sampling estimator:
Table I shows a comparison of results obtained using all of the aforementioned approaches in both exact and approximated variants. As expected, the most accurate (lowest variance) approach is MCHT, followed by MCOC, and importance sampling is the least accurate by a large margin. Using the approximated probability leads to a bias that depends on the graph's structure. The error depends on the length of cycles considered, and is generally smaller for shorter cycles.
This error makes the approach a bad fit in some cases, e.g., where an unbiased estimate for the cycle count is required. However, in many cases the error is actually tolerable for practical applications. Different graphs often have cycle counts that vary by multiple orders of magnitude, far more than the systematic bias in many cases. Furthermore, graphs with similar connectivity structures have similar biases. Thus, a comparison or usage as an input feature for a downstream learning task may still work well even with this error.
In conclusion, for tasks such as cycle counting (where the end result directly relates to the bias in the probability approximation), it is sometimes required to use the exact version of an estimator. The choice between MCHT and MCOC for the estimator is straightforward once we also consider the computational requirements for sampling a spanning tree and calculating the exact inclusion probability . The runtime of sampling a spanning tree is essentially negligible compared to calculating the exact inclusion probability . MCHT has a higher correlation between its sampled cycles, and thus MCOC with a bigger number of samples is preferable in the exact setting. For the approximated version, MCHT and MCOC have practically the same runtime per tree, making MCHT a clearly preferable choice.
IX. APPLICATION: SPIN GLASSES AND CYCLE FRUSTRATION
In this section, we consider how to apply cycle sampling to the area of spin glasses [44, 45] and investigate its performance. A spin glass can be modeled as a graph where each vertex has a spin value of , and two vertices can be positively or negatively coupled (i.e., have edges with value ). Here, positively coupled means that the coupling has a low-energy state when the two spins have the same orientation, and a high-energy state when they have opposite orientations. Negative coupling is defined analogously. The couplings are collected in a symmetric matrix . The Hamiltonian (energy function) of a state is . On the level of individual edges, we call an edge frustrated if it is in the high-energy state, i.e., . Equivalently, the spin assignment fails to satisfy the preferred relation encoded by that coupling.
For general interaction graphs, finding a ground state (a state with minimum energy) and its energy is NP-hard [46]. However, by simulating random changes to the spins, one can obtain a low-energy state. Given a low-energy spin configuration obtained from this sampling process, it is interesting to see how close this spin configuration is


a

b

FIG. 8: Energy and cycle-level frustration for two spin systems: (a) an Erdős-Rényi graph with , , and (for additional lengths, see Figure 10) and (b) a grid graph with (for additional lengths, see Figure 9). Edges are selected to be negative couplings independently at random with probability . Cycle-level frustration is estimated with MCHT using the exact and trees. Dots represent spin configurations obtained with temperature (x-axis), and red squares represent configurations obtained uniformly at random (). The left plot shows energy and the fraction of frustrated edges; the other plots show the proportion of edge-frustrated cycles for selected lengths. Horizontal lines show values for a non-unique optimal configuration (green), the corresponding spectral or cycle-level lower bound (orange dashed), and zero frustration (red dashed). The energy and cycle-level quantities have different units and their bound tightness is not directly comparable.
to the ground state.
As an efficient approximation, there is a well-known spectral bound for the energy. The largest eigenvalue of J gives the lower bound .
As an alternative, we will now study frustration on the cycles. We call a cycle edge-frustrated under h if at least one of its edges is frustrated. If there is an even number of negative couplings in the cycle, there is a spin configuration that leads to a non-frustrated cycle; for an odd number of negative couplings, such a configuration cannot exist. Borrowing terminology from structural balance theory [4], we call a cycle balanced if it has an even number of negative couplings, and unbalanced if it does not. There is a spin configuration without frustrated edges if and only if every cycle is balanced.
The number of unbalanced cycles for a certain length is a lower bound for the number of edge-frustrated cycles (given any spin configuration ) of that length. In some cases and for relatively short cycles, this cycle-level bound is quite tight. Figure 8 shows two cases where the cycle-level bound is tighter to the optimal count of balanced
cycles than the spectral bound is to the energy. For longer cycles, the balance bound becomes uninformative in all instances we investigated. In other cases (cf. Figures 11 and 12), it is loose even at short lengths.
The number of unbalanced cycles is therefore a rigorous lower bound on the number of edge-frustrated cycles, but it is not by itself a bound on energy or on the ground-state optimality gap: one frustrated edge may belong to many cycles. We consequently use it as a cycle-level diagnostic and do not compare its numerical tightness directly with the spectral energy bound.
To estimate the fraction of balanced cycles , we need to obtain an estimate for the number of balanced cycles and for the number of all cycles. Trivially, the former can be achieved by setting for balanced and for unbalanced cycles:
A. Comparison of Approaches
For this task, there is a previous Monte Carlo approach [5]. In their approach, Giscard et al. sample connected node-induced subgraphs and calculate the balance ratio on them. As the authors note, this works as an estimator for the balance, but does not generalize to the cycle count.
Since the height of the spanning tree scales as and the number of induced cycles often drops off after , we show evaluation results for length . Furthermore, we set the number of sampled subgraphs and spanning trees to 100 and the size of subgraphs (called in [5]) to .
Table II shows the results. We observe much smaller biases in the approximated versions of the estimators, to the point that the bias is only statistically significant for MCHT and only on half of the tested graphs. In practical applications, this bias is likely negligible. Since the estimator can only be biased by a correlation between the approximation error and , the average approximation error is not relevant here; and since the variance in the approximation error is comparatively low, a negligible bias is generally very likely. Giscard's algorithm is not only the slowest in our experiments, but also less accurate than MCHT and comparable to MCOC. Standard importance sampling is, again, the least accurate approach.
In practice, this means that the accuracy of MCHT-approx is almost as good as that of MCHT-exact with the same number of trees. However, since MCHT-approx is much more computationally efficient, it provides a better cost/accuracy trade-off in these cases. This confirms that the selected estimation task is highly relevant for the selection of the most practically useful estimator.
X. CONCLUSION
In this paper, we have introduced Monte Carlo methods based on uniform spanning trees and Horvitz-Thompson estimators to estimate properties of the cycle space on graphs from cycles induced by spanning trees. While inherently limited by the theoretical complexity of the problem, our methods push the boundaries of computational feasibility to cycles that have a length on the order of , which is considerably further than the current state of the art that was exponential in the length of the cycles considered. Furthermore, our approach is more general and may be used for a wide variety of cycle-based metrics and features.
For this, we need to adjust the estimator using the inclusion probability of individual cycles. The exact estimators
we introduced are already more computationally efficient than any current approach, but for maximum scalability, we have introduced a degree-based approximation of the inclusion probability such that the runtime of the overall estimator is almost linear in the number of edges.
The accuracy and runtime trade-off needs to be considered based on the estimation target and the underlying graph structure. On some graphs, there is a significant approximation bias that increases for longer cycles and leads to inaccuracies for non-normalized estimates (e.g., cycle counting). While the error may still be acceptable for some applications, it can make the approximated version infeasible for others, and usually using the exact one-cycle estimator leads to the best results in these cases. On the other hand, when considering normalized estimates (e.g., the fraction of cycles fulfilling a certain property), this systematic bias is not a problem. Theoretically, a correlation between the variance in the approximation and the estimation target could still lead to a bias in the overall result. However, since this variance is much smaller than the bias in all graphs that we investigated, it is unlikely to lead to a large error in practice even if it is strongly correlated. Thus, in these cases, it is usually preferable to use the full MCHT estimator with approximated probabilities.
Most importantly, this groundwork closes a gap in the methodological toolkit for multiple existing applications in different subject areas, enabling the scalability of unbiased analysis to larger networks. In addition to enabling or extending existing methods, analogues to other global properties on the graph may be defined over the cycles. Thus, there are applications in many fields, such as computational social science, biology, economics, and physics.
Beyond applying and analyzing the practical performance of the method, future work could further optimize the method. Currently, we either calculate a full Horvitz-Thompson estimate or subsample it with a single cycle. Subsampling a set number per length may lead to comparable variances, without the full computational cost.
CODE AND DATA AVAILABILITY
The implementation, experiment scripts, and graph-processing pipeline are available in the project repository. The cycle-sampling implementation is also distributed as the py-raccoon package on the Python Package Index. The real-world networks used in the experiments are identified by their Netzschleuder dataset names in the appendix figures.
ACKNOWLEDGMENTS
Funded by the European Union (ERC, HIGH-HOPeS, 101039827). Views and opinions expressed are however those of the author(s) only and do not necessarily reflect those of the European Union or the European Research Council Executive Agency. Neither the European Union
Giscard et al. note that it is beneficial to set the maximum length bigger than the length that we are interested in and report using lengths between 20 and 30 while reporting results for lengths up to 18, but with increasing uncertainties.
TABLE II: Comparison of all balance estimation approaches on selected graphs, with 100 samples (spanning trees / subgraphs of size , respectively). The ER graphs are (the same graph in the first two rows) and ; negative couplings are drawn independently with probability (top to bottom). Columns show the graph type, total size, number of positive and negative edges, balance as determined by MCHT-exact, and standard deviations over 100 runs. The length shown is . All approaches have the same mean value for the balance (up to uncertainty). The entries highlighted in red indicate a statistically significant bias; all biases are smaller than . Theoretically, MCOC and IS should have the same bias for the approximated variant, but it is too small to be statistically significant.
| Graph | MCHT | MCOC | IS | Giscard | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| n | l | exact | approx | exact | approx | exact | ||||
| ER | 60 | 8 | 152 | 16 | 0.56 | 0.02 | 0.02 | 0.07 | 0.08 | 0.23 |
| ER | 60 | 8 | 119 | 49 | 0.50 | 0.02 | 0.02 | 0.07 | 0.07 | 0.22 |
| ER | 100 | 10 | 453 | 21 | 0.70 | 0.02 | 0.02 | 0.06 | 0.06 | 0.25 |
| Grid | 64 | 8 | 138 | 6 | 0.68 | 0.02 | 0.02 | 0.05 | 0.05 | 0.16 |
| Grid | 64 | 8 | 113 | 31 | 0.49 | 0.02 | 0.02 | 0.06 | 0.07 | 0.19 |
| Grid | 100 | 10 | 169 | 11 | 0.62 | 0.03 | 0.03 | 0.05 | 0.06 | 0.22 |
nor the granting authority can be held responsible for them.
[1] G. Bouritsas, F. Frasca, S. Zafeiriou, and M. M. Bronstein, IEEE Transactions on Pattern Analysis and Machine Intelligence 45, 657 (2022).
[2] C. Morris, M. Ritzert, M. Fey, W. L. Hamilton, J. E. Lenssen, G. Rattan, and M. Grohe, in Proceedings of the AAAI conference on artificial intelligence, Vol. 33 (2019) pp. 4602–4609.
[3] K. Xu, W. Hu, J. Leskovec, and S. Jegelka, in International Conference on Learning Representations (2019).
[4] D. Cartwright and F. Harary, Psychological review 63, 277 (1956).
[5] P.-L. Giscard, P. Rochet, and R. C. Wilson, Journal of Complex Networks 5, 750 (2017).
[6] S. Talaga, M. Stella, T. J. Swanson, and A. S. Teixeira, Communications Physics 6, 349 (2023).
[7] Z. Cui and S. M. Taylor, Stevens Institute of Technology School of Business Research Paper (2018).
[8] J. Hoppe and M. T. Schaub, in The Second Learning on Graphs Conference (2023).
[9] J. Zanghellini, D. E. Ruckerbauer, M. Hanscho, and C. Jungreuthmayer, Biotechnology journal 8, 1009 (2013).
[10] E. Ullah, M. Yosafshahi, and S. Hassoun, Briefings in bioinformatics 21, 1875 (2020).
[11] J. T. Finn, Journal of theoretical Biology 56, 363 (1976).
[12] B.-P. Han, Ecological Modelling 104, 289 (1997).
[13] S. Allesina and R. E. Ulanowicz, Computational biology and chemistry 28, 227 (2004).
[14] L. G. Valiant, SIAM Journal on Computing 8, 410 (1979).
[15] F. Harary and B. Manvel, Matematicky časopis 21, 55 (1971).
[16] N. Alon, R. Yuster, and U. Zwick, Algorithmica 17, 209 (1997).
[17] P.-L. Giscard, N. Kriege, and R. C. Wilson, Algorithmica 81, 2716 (2019).
[18] V. Domínguez-García, S. Pigolotti, and M. A. Munoz, Scientific reports 4, 7497 (2014).
[19] D. G. Horvitz and D. J. Thompson, Journal of the American Statistical Association 47, 663 (1952).
[20] M. H. Hansen and W. N. Hurwitz, The Annals of Mathematical Statistics 14, 333 (1943).
[21] P. Erdős and A. Rényi, Publ. math. debrecen 6, 18 (1959).
[22] E. N. Gilbert, The Annals of Mathematical Statistics 30, 1141 (1959).
[23] S. T. Tokdar and R. E. Kass, Wiley Interdisciplinary Reviews: Computational Statistics 2, 54 (2010).
[24] A. B. Owen, Monte Carlo theory, methods and examples (https://artowen.su.domains/mc/, 2013).
[25] S. Agapiou, O. Papaspiliopoulos, D. Sanz-Alonso, and A. M. Stuart, Statistical Science, 405 (2017).
[26] D. J. MacKay, Information theory, inference and learning algorithms (Cambridge university press, 2003).
[27] N. Alon, P. Dao, I. Hajirasouliha, F. Hormozdiari, and S. C. Sahinalp, Bioinformatics 24, i241 (2008).
[28] R. Pagh and C. E. Tsourakakis, Information Processing Letters 112, 277 (2012).
[29] C. E. Tsourakakis, U. Kang, G. L. Miller, and C. Faloutsos, in Proceedings of the 15th ACM SIGKDD international conference on Knowledge discovery and data mining (2009) pp. 837–846.
[30] M. M. Syslo, Networks 9, 123 (1979).
[31] D. B. Wilson, in Proceedings of the twenty-eighth annual ACM symposium on Theory of computing (1996) pp. 296–303.
[32] S. Chaiken and D. Kleitman, Journal of Combinatorial Theory, Series A 24, 377 (1978).
[33] J. Lyklema, C. Evertsz, and L. Pietronero, Europhysics Letters 2, 77 (1986).
[34] G. F. Lawler, Journal of Physics A: Mathematical and General 20, 4565 (1987).
[35] R. Pemantle, The Annals of Probability, 1559 (1991).
[36] G. Brightwell and P. Winkler, Random Structures & Algorithms 1, 263 (1990).
[37] M. Löwe and F. Torres, Statistics & Probability Letters 89, 81 (2014).
[38] R. E. Tarjan, Journal of the ACM (JACM) 26, 690 (1979).
[39] P. Michaeli, A. Nachmias, and M. Shalev, Probability Theory and Related Fields 179, 261 (2021).
[40] D. J. Aldous, SIAM Journal on Discrete Mathematics 3, 450 (1990).
[41] N. Alon, A. Nachmias, and M. Shalev, Combinatorics, Probability and Computing 31, 1010 (2022).
[42] G. F. Lawler, O. Schramm, and W. Werner, in Selected Works of Oded Schramm (Springer, 2011) pp. 931–987.
[43] V. Beffara, The Annals of Probability, 1421 (2008).
[44] K. Binder and A. P. Young, Reviews of Modern physics 58, 801 (1986).
[45] G. Toulouse et al., Spin Glass Theory and Beyond: An Introduction to the Replica Method and Its Applications 9, 99 (1987).
[46] F. Barahona, Journal of Physics A: Mathematical and General 15, 3241 (1982).
[47] P. W. Holland, K. B. Laskey, and S. Leinhardt, Social networks 5, 109 (1983).
[48] A.-L. Barabási and R. Albert, science 286, 509 (1999).
[49] W. W. Zachary, Journal of Anthropological Research 33, 452 (1977).
Appendix A: Approximation of the Cycle Inclusion Probability
A cycle is induced by a spanning tree if and only if all but one of its edges are part of the spanning tree. Each path formed by removing an edge from the cycle has a certain probability of being part of the spanning tree. By summing these probabilities, we can obtain the overall cycle inclusion probability .
To approximate this, we briefly outline the loop-erased random walk that is also used to sample uniform spanning trees. We then present the Laplacian random walk [33], an equivalent formulation with the same path distribution [34]. This gives an exact equation for the cycle inclusion probability . Finally, we introduce an approximation of that equation that can be calculated efficiently on spanning trees.
1. The Loop-Erased Random Walk
On a graph , a loop-erased random walk from vertex to vertex is obtained by performing a random walk and chronologically erasing loops whenever the walk self-intersects. Wilson's algorithm [31] constructs a uniform spanning tree from a sequence of such walks. The loop-erased-walk path from to has the same distribution as the unique path in a uniformly sampled spanning tree [35]. This also implies that the loop-erased random walk from to has the same distribution as performing the loop-erased random walk from to .
2. The Laplacian Random Walk
The Laplacian random walk (LRW) [33] from to has the same path distribution as the loop-erased random walk from to . The LRW achieves the same probability distribution as the loop-erased random walk by avoiding loops in the first place. To do this, the transition probabilities are adjusted to account for the possibility of creating a loop before reaching the target vertex . Previously visited vertices always lead to a loop, and are thus never chosen. Choosing the target terminates the walk and can thus never create a loop. For all other vertices, the probability of closing a loop depends on the following steps. Since the loop-erased random walk chooses neighbors uniformly, their probability is the average of the probabilities of their neighbors.
Formally, in step , each vertex is assigned a weight depending on its relation to the random walk. The probability to transition from to is then . For the target, . For visited nodes (including the current one) , . The weight of every other vertex is harmonic in the Laplacian , i.e., it satisfies . Since the set of visited nodes changes after each step, this weight has to be recalculated after each step and each transition probability depends on the previous transitions.
3. Calculating the Cycle Inclusion Probability and Approximating the Laplacian Random Walk
As discussed, a spanning tree induces a cycle if and only if all but one edge of belong to the tree. Thus, each edge corresponds to a potential path in a spanning tree. For each edge , choose an orientation of the open path , where . At step , let be the harmonic potential with target and visited set . With the previous definition,
The exact cycle inclusion probability is then
Since the probability of the loop-erased random walk does not depend on the direction, neither does the LRW, making the orientation arbitrary.
Since the LRW requires calculating for every step of the walk, it is too computationally expensive for our purpose. Instead, we derive a mean-field approximation that assumes equal (weighted) connectivity for most edges in the graph but integrates local connectivity where possible. To enable efficient computation over a spanning tree, we can only consider exact degrees on one edge (two adjacent vertices) in the path at the same time. Additionally, depending on the step, we integrate structural information from the complete path.
The mean-field approximation assumes that unobserved nodes have mean degree and are connected to all other nodes with weight . For an Erdős-Rényi graph, this is equivalent to the weights in the expected graph. All vertices that have not been visited and are not the target are symmetric, and their potential only depends on the number of visited nodes. This gives the mean-field estimate
However, this first approximation ignores the local structure of the LRW. For vertices adjacent to the current vertex, we can give a more accurate approximation. The current vertex is adjacent and, by definition, has value zero, reducing the mean-field value of . While this is symmetric for unvisited neighbors, the target may also be a neighbor. Thus, the transition probability to the prescribed next vertex is smaller than the global approximation alone would suggest. Instead, we can derive a mean-field approximation specifically for neighbors :
Furthermore, for the penultimate vertex, one of the neighbors is the target vertex v. Thus, its is bigger, increasing the probability for this step. We denote the corrected value by :
With these considerations, we approximate the transition probabilities of individual LRW steps. For the first step, no other vertex has been visited and all neighbors are either unvisited or v. The first-step approximation depends on , , and the degree of the initial vertex. The target vertex is a neighbor because the edge closes the cycle. The remaining neighbors, including the next vertex, are unvisited.
For an intermediate step , we can obtain a similar expression. One neighbor was visited in the previous step, so only the remaining neighbors must be considered; one is the prescribed next vertex. Among the possible vertices in the mean-field calculation, have already been visited, one is the target , and are unvisited. The corresponding fractions therefore have denominator .
(A12)
However, this expression depends on the current step , which would make it impossible to compute from path-wise aggregates over spanning trees. Instead, we will approximate intermediate steps further by using :
Due to the cancellation in the last step, no longer depends on i. Since , this introduces a bias. We will correct for this afterwards using expected values.
At step l-2, the next vertex is known to be adjacent to the target, which gives the refined factor
For the final transition to (step ), we know that is a neighbor. Therefore, there is one neighbor that was certainly visited, one that has value 1, and of the remaining neighbors, have not been visited and have value :
We now assemble the approximation for a cycle of length without relying on an implicit indexing of the cycle vertices. For every omitted edge , choose one orientation of the resulting open path and write
Let denote the reverse orientation. For the forward orientation, define
and define analogously on the reverse path. To improve the overall accuracy, we thus get a first approximation
The average removes the small orientation dependence introduced by the mean-field substitutions.
For fast path aggregation, we require most factors to be independent of both and . We approximate these probabilities further by to obtain a multiplicative aggregator and an additive aggregator . We correct the (expected) bias of this approximation with a global correction factor :
(A18)
This approximation for the one-way path inclusion probability consists of the (final) general correction factor , a part depending on the degrees of the first and last vertex in the cycle, and the cycle-dependent (but not path-dependent) product of over all vertices. The approximation for the reversed path is identical except in the fraction depending on the two vertices, which are reversed. We can now insert this approximation into Equation (A17) to obtain the final approximation :
The aggregated factors are functions that only depend on their parameters:
As discussed in Section V A, this approximation can be efficiently calculated using a spanning tree.
Appendix B: Example Run on Toy Graph
This section provides an example run to give a better intuition on how the algorithm and its optimizations work. We will be using the following graph drawn from Erdős-Rényi ():

First, we sample a uniform spanning tree (left: highlighted on graph, right: displayed as rooted spanning tree).

As explained in Section V A, we can calculate for all cycles efficiently. For this, we calculate for all :

Then, we calculate all lowest common ancestors using Tarjan's off-line lca algorithm [38]. In our example, we will look at the edge with . The corresponding cycle is ; we can compute its length without iterating over it from the depths of , and their lowest common ancestor in the tree.
From this information, we can calculate by evaluating Equations (10) and (11):
For comparison, the exact cycle inclusion probability is .
Appendix C: Additional Plots
Evaluation code to generate these plots is available at github.com/josefhoppe/cycle-statistics. The full spin-system results corresponding to Figure 8 are shown in Figures 9 to 12. Figure 13 extends the runtime comparison to real-world networks. The probability-approximation diagnostics are collected in Figures 14 to 16.


Cycle frust. I=8
Cycle frust. I=10
Cycle frust. I=12
Cycle frust. I=14
Cycle frust. I=16
Cycle frust. I=18

Cycle frust. I=20
Cycle frust. I=22
Cycle frust. I=24
FIG. 9: Energy and cycle-level frustration on a grid graph with . Cycle-level frustration is estimated with MCHT using the exact and trees. Dots represent temperature-indexed spin configurations and red squares uniformly random configurations. Horizontal lines show values for a non-unique optimum, the relevant energy or cycle-level lower bound, and zero frustration. The cycle-level bound is informative for short lengths and becomes loose for longer cycles; it is not directly comparable in magnitude with the spectral energy bound.


Cycle frust. l=5
Cycle frust. l=6
Cycle frust. l=7
Cycle frust. l=8
Cycle frust. l=9
Cycle frust. l=10
Cycle frust. l=11
Cycle frust. l=12
Cycle frust. l=13
FIG. 10: Energy and cycle-level frustration on an Erdős–Rényi graph with , , and . Plot elements and estimation are as in Figure 9. The cycle-level bound is informative for short lengths and becomes loose for longer cycles; it is not directly comparable in magnitude with the spectral energy bound.


FIG. 11: Energy and cycle-level frustration on a grid graph with . Plot elements and estimation are as in Figure 9. In this regime the cycle-level lower bound is loose.


Cycle frust. l=5
Cycle frust. l=6
Cycle frust. l=7
Cycle frust. l=8
Cycle frust. l=9
Cycle frust. l=10
Cycle frust. l=11
Cycle frust. l=12
Cycle frust. l=13
FIG. 12: Energy and cycle-level frustration on the same Erdős–Rényi graph as in Figure 10 (n = 60, p = 0.1) with . Plot elements and estimation are as in Figure 9. In this regime the cycle-level lower bound is loose.

dataset
• karate/78
• ceo_club
• high_tech_company
• student_cooperation
• game_thrones
• cs_department
• polbooks
• football
• crime
• facebook_friends
• contact
• sp_infectious
• sp_high_school/proximity
• wiki_science
• sp_primary_school
• dnc
• chicago_road
• escorts
• sp_colocation/Thiers13
• cofe
• marvel_universe
• email_enron
• us_agencies/aggregate
• dblp_coauthor_snap
• roadnet/PA
• roadnet/CA
• hyves
• wikitree
• fixster
• dblp_coauthor
• as_skitter
FIG. 13: Runtime on selected real-world datasets (retrieved from Netzschleuder, https://networks.skewed.de, same naming convention), ordered by number of edges (m); estimation run from 100 sampled trees (Giscard: 100 subgraphs of size ); ten runs per graph; exact probability unless noted as MF. For disconnected networks, we used the largest connected component. The sample includes some of the largest networks available on Netzschleuder. This shows that our algorithm is performant enough for practical applications on a large number of real-world datasets.

(a) Evaluation on the same cycles and graph sampled from ER with n = 30, p = 0.5 as Figure 7 (a).

(b) Evaluation on the same cycles and graph sampled from ER with n = 30, p = 0.15 as Figure 7 (b).
FIG. 14: The approximation error of a hypothetical approximation that assigns each cycle the mean probability of all cycles with the same length, for a moderate configuration (a) and a sparse configuration (b). The estimation error is significantly larger than that of our approach, i.e., our approach detects significantly more than just the cycle length.

(a) Complete graph .
(b) Complete bipartite graph .

(c) Homophilic SBM [47] (two blocks, n = 30, p = 0.4, q = 0.2).
(d) Heterophilic SBM (two blocks, n = 50, p = 0.2, q = 0.4).

(e) Barabási–Albert [48] graph with 30 vertices, each new vertex attaching with 7 edges.

(f) Barbell graph consisting of two 10-vertex cliques connected by a path through three additional vertices.

(g) Delaunay triangulation of 50 uniformly random points in two-dimensional Euclidean space.
(h) 10 by 10 grid graph.
FIG. 15: Approximation error on synthetic graphs, for cycles exposed by ten USTs (as in Figure 7). The approximation is exact on the complete graph and remains accurate on several well-mixed models. Its systematic error grows when local connectivity is a poor description of global geometry. The barbell graph introduces a bottleneck, while the Delaunay triangulation and grid have strong low-dimensional structure and large diameter. In these cases, vertices with the same degree can have different harmonic relationships to the target, which the mean-field approximation cannot represent.

(a) High Tech Company.


(b) New Guinea Tribes.
(c) November 17 Terror Cell Network.


(d) Dutch Criticism.
(e) CEO Club.


(f) Montreal.
(g) Zachary's Karate Club [49].


(i) Florentine Families.
(h) Game [of] Thrones.

(j) Student Cooperation.
FIG. 16: Accuracy of the approximate cycle inclusion probability for cycles exposed by ten USTs on real-world networks from Netzschleuder (https://networks.skewed.de), unless noted otherwise; largest connected component. The approximation generally has small bias and moderate variance. The more systematic errors in (g)–(i) coincide with comparatively large graph diameter; (j), a nearly planar network, is a notable exception.