Repository navigation
Fix double counting in undirected expected_edges() and expected_density() - #58
Merged
Merged
Conversation
…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>
alexpghayes
marked this pull request as ready for review
November 17, 2026 22:48
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
For undirected models,
expected_edges()andexpected_density()have returned twice the true value since 0.4.0. Because theexpected_densityargument rescalesSto hitexpected_density(), every undirected model built withexpected_density = dsamples graphs of density aboutd / 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, asA[i, j]andA[j, i]; a self-loop appears once, asA[i, i]. Sosum(P) = E[sum(A)]is about twice the expected number of edges.expected_edges()sum(P)E[sum(A)], about 2 × the number of edgesexpected_degree()sum(P) / nE[A], which is the mean degree (correct)expected_density()sum(P) / choose(n, 2)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 halvedSat 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)) / 2expected_density()is the mean edge rate between distinct nodes, so the expected number of non-loop edges isexpected_density() * choose(n, 2):mean_{i ≠ j} P[i, j] = (sum(P) - tr(P)) / (n (n - 1))expected_degree()is unchanged atsum(P) / n. It is now computed directly instead of throughexpected_edges().Both use
sum(P) = c' S cwithc = colSums(X), andtr(P) = sum((X S) ∘ X), soPis 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 to1e-10for twelve models: an asymmetricS, sparseX, rank one,expected_degreeandexpected_densityscaling,erdos_renyi,sbm,dcsbm,planted_partition,chung_lu,mmsbmandoverlapping_sbm.Step 2: counting. In every sampled graph:
(sum(A) + tr(A)) / 2(sum(A) - tr(A)) / 2This is checked on 5 seeds × 12 models × self-loops on/off × Poisson/Bernoulli. For each, the edgelist,
sample_sparse()andsample_igraph()all come from the same seed. The check also confirms that edgelist rows, igraph edges,Aand 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():m ~ Poisson(sum(X (S/2) Xᵀ)), whereS/2is passed in by the undirected method.medges independently, with probability proportional toP[i, j]: a block pair is chosen in proportion toS̃, then nodes in proportion to the columns ofX.By Poisson splitting:
(i, j)gets an independentPoisson(P[i, j] / 2)count.from ≤ to, so the unordered pair {i, j}, i < j, getsPoisson(P[i, j] / 2 + P[j, i] / 2) = Poisson(P[i, j]).(i, i)getsPoisson(P[i, i] / 2)from the sampler, plus an independentPoisson(P[i, i] / 2)top-up from Undirected samplers draw self-loops (diagonal of A) at half the intended rate #46, forPoisson(P[i, i])in total.So, exactly:
Poisson(Σ_{i ≤ j} P[i, j]) = Poisson(expected_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
RindependentPoisson(μ)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 = drealizes densitydfor all eight undirected constructors (undirected_factor_model,erdos_renyi,sbm,dcsbm,planted_partition,chung_lu,mmsbm,overlapping_sbm), by z-test and directly.Poisson(expected_density() * choose(n, 2)).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 onmain, 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" ismain, "new" is this PR.Σ_{i≤j} P[i,j]expected_edges()expected_edges()mean_{i≠j} P[i,j]expected_density()expected_density()expected_degree()gives the same values before and after, and matches the brute-force mean row sum ofPfor all five models. For example, thechung_lumodel was built withexpected_degree = 6and returns 6.0000.Requested vs realized density, n = 1,000,
expected_density = 0.01, 100 replicates:mainConventions and caveats
expected_edges()includes expected self-loops even whenallow_self_loops = FALSE, matching howexpected_degree()and the directed functions treat the diagonal.expected_density()excludes the diagonal by definition, so it is the same either way. Self-loops contributetr(P), which is aboutdegreein total versus aboutn × degree / 2for all edges.poisson_edges = FALSE,Sis 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.Other changes
erdos_renyi()anddirected_erdos_renyi()checkedis.null(expected_degree)(andexpected_in_degree/expected_out_degree), but those names aren't arguments of the functions. R found the package's generic functions instead, which are neverNULL, so the "must specify" error never fired, and calling the function with neither argument silently usedp = 0.5. The functions now look for the scaling arguments in..., andexpected_densityalso 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)) / 2withexpected_edges().expected_edges()example comparedmean(rowSums(triu(A))), which is half the mean degree, with the analytic mean degree. It now usesrowSums(A).skip_on_cran(); the exact algebra and identity tests always run.Effects elsewhere
expected_densitynow samples twice as many edges, so seeded graphs change. NEWS calls this a breaking change.README.Rmdonce more.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