Skip to content

Fix double counting in undirected expected_edges() and expected_density() - #58

Merged
alexpghayes merged 3 commits into
mainfrom
fix/undirected-expected-edges-density
Nov 17, 2026
Merged

alexpghayes merged 3 commits into
mainfrom
fix/undirected-expected-edges-density

Conversation

@alexpghayes

Copy link
Copy Markdown
Collaborator

Summary

For undirected models, expected_edges() and expected_density() have returned twice the true value since 0.4.0. Because the expected_density argument rescales S to hit expected_density(), every undirected model built with expected_density = d samples graphs of density about d / 2. The README example shows it: sbm(n = 1000, k = 5, expected_density = 0.01) should give about 4,995 edges, and its printed output has 2,447.

This PR redefines both functions. It does not change expected_degree(), expected_degrees(), sampling, population spectra or any directed model. Those were already correct, and the tests here confirm it.

Where the factor of 2 came from

Write P = E[A | X, S] = X S Xᵀ. Each undirected edge {i, j} with i ≠ j appears in the symmetric adjacency matrix twice, as A[i, j] and A[j, i]; a self-loop appears once, as A[i, i]. So sum(P) = E[sum(A)] is about twice the expected number of edges.

Old definition What it actually measured
expected_edges() sum(P) E[sum(A)], about 2 × the number of edges
expected_degree() sum(P) / n mean row sum of E[A], which is the mean degree (correct)
expected_density() sum(P) / choose(n, 2) 2 × the number of edges ÷ the number of pairs

Before 0.4.0, undirected sampling drew every edge twice (#19), so the realized edge count really was about sum(P). The 0.4.0 fix halved S at sampling time but left these functions alone. That fixed degrees and spectra, and moved the factor of 2 onto edges and density.

New definitions

  • expected_edges() is the expected number of undirected edges, counting self-loops once:

    Σ_{i ≤ j} P[i, j] = (sum(P) + tr(P)) / 2

  • expected_density() is the mean edge rate between distinct nodes, so the expected number of non-loop edges is expected_density() * choose(n, 2):

    mean_{i ≠ j} P[i, j] = (sum(P) - tr(P)) / (n (n - 1))

  • expected_degree() is unchanged at sum(P) / n. It is now computed directly instead of through expected_edges().

Both use sum(P) = c' S c with c = colSums(X), and tr(P) = sum((X S) ∘ X), so P is never formed and the cost is still O(nk²).

Why these are correct

The argument has three steps. Each one is tested on its own in tests/testthat/test-expected-edges-density.R.

Step 1: the algebra. The closed forms equal the definitions written as explicit sums over a dense P. This is checked to 1e-10 for twelve models: an asymmetric S, sparse X, rank one, expected_degree and expected_density scaling, erdos_renyi, sbm, dcsbm, planted_partition, chung_lu, mmsbm and overlapping_sbm.

Step 2: counting. In every sampled graph:

  • number of edges = (sum(A) + tr(A)) / 2
  • edges between distinct nodes = (sum(A) - tr(A)) / 2

This is checked on 5 seeds × 12 models × self-loops on/off × Poisson/Bernoulli. For each, the edgelist, sample_sparse() and sample_igraph() all come from the same seed. The check also confirms that edgelist rows, igraph edges, A and the self-loop counts all agree. These are deterministic identities, not statistical checks.

Step 3: the distribution of the edge count is exactly Poisson. This follows from the sampler's code, sample_edgelist.matrix():

  • It draws m ~ Poisson(sum(X (S/2) Xᵀ)), where S/2 is passed in by the undirected method.
  • It then places each of the m edges independently, with probability proportional to P[i, j]: a block pair is chosen in proportion to S̃, then nodes in proportion to the columns of X.

By Poisson splitting:

  • Each ordered pair (i, j) gets an independent Poisson(P[i, j] / 2) count.
  • The undirected edgelist stores from ≤ to, so the unordered pair {i, j}, i < j, gets Poisson(P[i, j] / 2 + P[j, i] / 2) = Poisson(P[i, j]).
  • Self-loop (i, i) gets Poisson(P[i, i] / 2) from the sampler, plus an independent Poisson(P[i, i] / 2) top-up from Undirected samplers draw self-loops (diagonal of A) at half the intended rate #46, for Poisson(P[i, i]) in total.

So, exactly:

  • number of edges ~ Poisson(Σ_{i ≤ j} P[i, j]) = Poisson(expected_edges())
  • non-loop edges ~ Poisson(Σ_{i < j} P[i, j]) = Poisson(expected_density() * choose(n, 2))

That allows proper z-tests instead of ad hoc tolerances. Over 400 replicates, the total of R independent Poisson(μ) counts has z = (total − Rμ) / sqrt(Rμ). The tests require |z| < 4.5 (each check has about a 7e-6 chance of a false alarm). They also check that the variance-to-mean ratio is near 1, which is a direct check of the Poisson claim.

Further tests check the user-facing guarantees:

  • expected_density = d realizes density d for all eight undirected constructors (undirected_factor_model, erdos_renyi, sbm, dcsbm, planted_partition, chung_lu, mmsbm, overlapping_sbm), by z-test and directly.
  • Bernoulli SBMs realize the requested density.
  • Without self-loops, non-loop edges are still Poisson(expected_density() * choose(n, 2)).
  • Directed expectations equal explicit sums over P = X S Yᵀ and are exactly Poisson, which shows directed models are unchanged.

The tests distinguish old from new. Run against main, the formula-dependent tests fail (step 1: 36 failures, step 3: 24, density round trip: 8, Bernoulli: 2, no self-loops: 3). The step 2 identities and the directed tests pass on main, which confirms they test the sampler independently of the formulas.

Numbers

n = 300, 1,000 Monte Carlo replicates per model. "Brute force" means sums over an explicitly formed dense P; "old" is main, "new" is this PR.

Model Brute-force edges, Σ_{i≤j} P[i,j] Old expected_edges() New expected_edges() Monte Carlo mean edges z
factor model, asymmetric S 8,491.5 16,909.0 8,491.5 8,495.8 1.47
sbm, unequal blocks 1,609.0 3,200.0 1,609.0 1,608.6 −0.32
dcsbm 4,831.3 9,573.7 4,831.3 4,832.2 0.44
chung_lu 904.0 1,800.0 904.0 904.4 0.40
erdos_renyi(p = 0.02) 903.0 1,800.0 903.0 903.4 0.37
Model Brute-force density, mean_{i≠j} P[i,j] Old expected_density() New expected_density() Monte Carlo density
factor model, asymmetric S 0.18768 0.37701 0.18768 0.18776
sbm, unequal blocks 0.03547 0.07135 0.03547 0.03547
dcsbm 0.10574 0.21346 0.10574 0.10576
chung_lu 0.01998 0.04013 0.01998 0.01999
erdos_renyi(p = 0.02) 0.02000 0.04013 0.02000 0.02001

expected_degree() gives the same values before and after, and matches the brute-force mean row sum of P for all five models. For example, the chung_lu model was built with expected_degree = 6 and returns 6.0000.

Requested vs realized density, n = 1,000, expected_density = 0.01, 100 replicates:

Model Realized density on main Realized density with this PR
sbm 0.00499 0.01000
dcsbm 0.00500 0.01000
erdos_renyi 0.00498 0.01002

Conventions and caveats

  • Self-loops. expected_edges() includes expected self-loops even when allow_self_loops = FALSE, matching how expected_degree() and the directed functions treat the diagonal. expected_density() excludes the diagonal by definition, so it is the same either way. Self-loops contribute tr(P), which is about degree in total versus about n × degree / 2 for all edges.
  • Bernoulli graphs. These are Poisson expectations. With poisson_edges = FALSE, S is rescaled to the requested value first and only then transformed to -log(1 - S), so the requested density or degree is realized as an edge probability. Afterwards, expected_*() reports the Poisson-scale value, which slightly overestimates when probabilities are large. This is unchanged and is now documented.
  • Densities above 0.5. Undirected models can now request them; previously the argument effectively capped out at 0.5.

Other changes

  • erdos_renyi() and directed_erdos_renyi() checked is.null(expected_degree) (and expected_in_degree / expected_out_degree), but those names aren't arguments of the functions. R found the package's generic functions instead, which are never NULL, so the "must specify" error never fired, and calling the function with neither argument silently used p = 0.5. The functions now look for the scaling arguments in ..., and expected_density also counts.
  • test-degree-scaling.R: the "undirected density computed consistently" test had the doubled value built into its analytic formula. It now uses the exact density (2 choose(pop, 2) a + pop² b) / choose(n, 2).
  • test-diagonal-sampling.R: now compares (sum(A) + tr(A)) / 2 with expected_edges().
  • The expected_edges() example compared mean(rowSums(triu(A))), which is half the mean degree, with the analytic mean degree. It now uses rowSums(A).
  • The Monte Carlo tests (about 20 s) use skip_on_cran(); the exact algebra and identity tests always run.

Effects elsewhere

Full suite: 1,865 passed, 0 failed. In CRAN mode, 1,626 passed and the 5 Monte Carlo tests are skipped. Examples run.

🤖 Generated with Claude Code

alexpghayes and others added 3 commits November 17, 2026 14:29
…ty()

Each undirected edge appears twice in the symmetric adjacency matrix,
so sum(X S X') is twice the expected number of edges. Since the #19 fix
halved undirected sampling, expected_edges() and expected_density()
have reported twice the true values, and expected_density = d produced
graphs of density about d / 2.

- expected_edges(): (sum(P) + tr(P)) / 2, the expected number of
  undirected edges counting self-loops once
- expected_density(): (sum(P) - tr(P)) / (n (n - 1)), the mean edge
  rate between distinct nodes
- expected_degree() is unchanged (sum(P) / n) and now computed directly

Add verification tests: closed forms vs explicit sums over a dense P,
exact edge-counting identities on sampled graphs, and exact Poisson
z-tests of sampled edge counts. Fix the erdos_renyi() and
directed_erdos_renyi() argument checks, which looked up the generic
functions instead of the arguments and never fired.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Resolve the NEWS.md conflict with #57's bullets by keeping both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
main now has the directed stack, the overlapping SBM changes, #49, #51
and #53. Resolve the NEWS.md conflict by keeping both sides.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@alexpghayes
alexpghayes marked this pull request as ready for review November 17, 2026 22:48
@alexpghayes
alexpghayes merged commit 6f50321 into main Nov 17, 2026
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant