Network Simulation

ERGM.jl provides tools to simulate networks from fitted ERGM models using Markov Chain Monte Carlo (MCMC). Simulated networks are essential for assessing model fit, making predictions, and understanding the structural implications of estimated parameters.

Why Simulate?

Network simulation serves several purposes:

  • Goodness of fit: Compare observed network properties to properties of networks generated by the model
  • Model exploration: Understand what kinds of networks a given model specification produces
  • Prediction: Generate plausible networks given estimated parameters
  • Hypothesis testing: Use simulation-based tests for network hypotheses

Simulating from a Fitted Model

The simplest approach is to simulate from an ERGMResult:

using NetworkCore, ERGM
using Random

Random.seed!(42)

# Example network: Florentine marriage ties with a categorical attribute
net = load_dataset(:florentine_marriage)
set_vertex_attribute!(net, :gender,
    Dict(v => (isodd(v) ? "F" : "M") for v in 1:nv(net)))

# Fit a model
terms = [Edges(), Triangle(), NodeMatch(:gender)]
result = ergm(net, terms; method=:mple)

# Simulate 100 networks from the fitted model
sim_nets = simulate_ergm(result; n_sim=100)

println("Generated $(length(sim_nets)) networks")
println("Each with $(nv(sim_nets[1])) nodes")

Parameters

ParameterDescriptionDefault
n_simNumber of networks to simulate1
burninMCMC burn-in steps (per chain)20 × n_dyads
intervalSteps between saved samplesmax(100, n_dyads ÷ 10)
rngRandom number generator all draws flow fromRandom.default_rng()
n_chainsIndependent chains run in parallelmin(n_sim, 4)

Reproducibility and Threading

Every sampling function takes an rng::AbstractRNG keyword, and all random draws flow from it — two calls with the same rng state return identical networks. The n_sim draws are split over n_chains independent chains, run in parallel when Julia has multiple threads; each chain's RNG is seeded deterministically from the caller's rng, so results do not depend on the thread count:

sims_a = simulate_ergm(result; n_sim=20, rng=Xoshiro(1))
sims_b = simulate_ergm(result; n_sim=20, rng=Xoshiro(1))
# sims_a and sims_b are identical, at any JULIA_NUM_THREADS

Choosing Burn-in and Interval

The burn-in ensures the MCMC chain has reached stationarity before sampling. The interval (thinning) reduces autocorrelation between samples.

Every sampler in ERGM.jl — simulate_ergm, sample_networks, mh_sample, gof, mcmle and the MPLE bootstrap — resolves an omitted burnin/interval through one dyad-scaled rule (ERGM.Extension.mcmc_defaults): a chain that proposes one dyad per step needs a number of steps proportional to the number of dyads to move every dyad a bounded number of times.

NetworkDyadsDefault burn-in (20 × n_dyads)Default interval (max(100, n_dyads ÷ 10))
16 nodes, undirected1202,400100
50 nodes, undirected1,22524,500122
200 nodes, undirected19,900398,0001,990
500 nodes, directed249,5004,990,00024,950
ERGM.Extension.mcmc_defaults(ERGMModel(ERGMFormula(terms), net))   # (burnin = 2400, interval = 100)

# Override explicitly when the chain mixes slowly (check `mcmc_diagnostics`)
sim_nets = simulate_ergm(result;
    n_sim = 100,
    burnin = 50000,
    interval = 5000
)

Simulating from a Model Specification

You can also simulate directly from an ERGM model and coefficient vector, without a fitted result:

# Define model
formula = ERGMFormula(terms)
model = ERGMModel(formula, net)

# Specify coefficients
θ = [-2.0, 0.5, 0.8]  # edges, triangle, nodematch

# Sample networks
sim_nets = sample_networks(model, θ; n_sim=50)

Low-Level Single-Chain Sampling

mh_sample runs one parameterized Metropolis–Hastings chain and returns the sampled sufficient statistics (and, optionally, the sampled networks). It is the primitive that the estimation routines and downstream packages (e.g. ERGMEgo.jl) build on:

using Statistics

out = mh_sample(model, θ; n_samples=200, burnin=5000, interval=100,
                rng=Xoshiro(7))
size(out.stats)          # (200, 3): one row of g(y) per sample
mean(out.stats, dims=1)  # E[g] estimate at θ

with_nets = mh_sample(model, θ; n_samples=10, return_networks=true)
with_nets.networks       # the 10 sampled networks themselves

Starting Network

By default, sample_networks initializes from a random network matching the observed density. You can provide a custom starting network:

# Start from the observed network
sim_nets = sample_networks(model, θ;
    n_sim = 50,
    start_net = net
)

# Start from an empty network
empty_net = network(nv(net); directed=is_directed(net))
sim_nets = sample_networks(model, θ;
    n_sim = 50,
    start_net = empty_net
)

The MCMC Algorithm

Each simulation step:

  1. Propose with statnet's tie/no-tie (TNT) proposal, the default (proposal=:tnt): with probability ½ a uniformly chosen existing tie, otherwise a uniformly chosen dyad
  2. Compute: Calculate change statistics $\delta(y)_{ij}$ for all terms
  3. Accept/Reject: Toggle the dyad with probability

\[\alpha = \min\left(1, \exp\left(\pm\theta^\top \delta(y)_{ij}\right) \cdot H\right)\]

with the sign negative for a removal, and $H$ the proposal's Hastings ratio. With $E$ toggleable ties among $N$ toggleable dyads, TNT proposes a tie with probability $\tfrac12/E + \tfrac12/N$ and a non-tie with $\tfrac12/N$ (every dyad with $1/N$ when there is no tie at all), so $H$ is the ratio of the reverse and forward proposal probabilities — statnet's MH_TNT correction, including the $E = 0 \leftrightarrow 1$ boundary.

Why TNT: on a sparse network almost every uniformly random dyad is an absent tie whose addition the model rejects, so a uniform random toggle (proposal=:random, the sampler of ERGM.jl 0.1, kept bit-identical) barely moves; TNT spends half its proposals on removals and mixes several times faster per toggle. Both proposals are exact: the test suite compares their stationary distribution with exhaustive enumeration and checks TNT's detailed balance exactly. proposal=:spdyad is R ergm ≥ 4.6's SPDyad (R's default for every one-mode network, and mcmle's; the samplers here default to :tnt): with probability ¼ the dyad is drawn uniformly from those with at least one shared partner, otherwise by TNT, with the mixture's Hastings ratio — several times more effective draws per toggle on clustered models.

The kernel: mh_toggle!

Steps 1–3, the burn-in and the thinning are one exported function, mh_toggle!, that knows nothing about networks: the proposal, the change statistics and the state mutation are supplied as callables. ERGM.jl's own samplers are a thin adapter over it (a move is a free dyad (i, j), change! fills change_stat_all! and reports whether the tie is present, apply! toggles it), and the ERGM variants adopt the same kernel with their own moves — TERGM's constrained formation/dissolution toggles, ERGMMulti's (layer, i, j), ERGMRank's rank swaps. An asymmetric proposal passes its log Hastings ratio as the optional hastings= callable (TNT does); a symmetric one omits it. The kernel allocates nothing per step and draws from rng in a fixed order, so a chain is bit-identical for a given seed. A state need not be a network at all:

using Statistics
state = Ref(false)                      # one "tie", statistic g(y) = y
draws = Float64[]
mh_toggle!(Xoshiro(1), [log(3.0)], [0.0],
           rng -> 1,                                        # propose: the only move
           (delta, move) -> (delta[1] = 1.0; state[]),      # change!: Δ = 1, removal if present
           (move, removal) -> (state[] = !removal),         # apply!
           k -> push!(draws, state[]);                      # on_sample
           burnin=100, interval=1, n_samples=20_000)
round(mean(draws), digits=2)            # ≈ 0.75 = P(y = 1) at θ = log 3

Random Initialization

When no starting network is provided, a random network is created with edge probability matching the observed network density:

# The density of the observed network
density = ne(net) / (nv(net) * (nv(net) - 1) / 2)  # undirected

Missing (Unobserved) Dyads

A simulated network has a value at every dyad, so the samplers refuse a network with dyads masked as missing (set_missing_dyad!) by default and offer one opt-in, missing=:condition_on_face (warned): masked dyads are then never proposed for toggling — every sampled network keeps the stored face value at those dyads, and random starting networks (start_net=nothing) preserve them instead of randomizing — so the sampler draws from the model conditional on the face values. missing=:mle is an estimation policy of mcmle and is refused here with a message saying so.

mh_sample additionally takes toggleable=:all (every dyad, masked ones included — the unconditional model, the free chain of the missing-data MCMLE) and toggleable=:masked (only the masked dyads, observed dyads held fixed — the constrained chain whose mean is E[g(Y) | Y_obs]); neither reads an unobserved value as an observation, so neither takes an opt-in. If the chain has no dyad to toggle, sampling throws an ArgumentError.

Analyzing Simulated Networks

Comparing Observed vs. Simulated Properties

# Edge count comparison
obs_edges = ne(net)
sim_edges = [ne(s) for s in sim_nets]

println("Observed edges: ", obs_edges)
println("Simulated edges: ",
    round(mean(sim_edges), digits=1), " ± ",
    round(std(sim_edges), digits=1))

Checking Model Statistics

# Compute model statistics for each simulated network
ts = TermSet(terms)

for (i, snet) in enumerate(sim_nets[1:5])
    stats = compute_all(ts, snet)
    println("Simulation $i: ", round.(stats, digits=2))
end

# Compare to observed
obs_stats = compute_all(ts, net)
println("Observed:      ", round.(obs_stats, digits=2))

Network-Level Summaries

using Statistics

# Density
sim_densities = [ne(s) / (nv(s) * (nv(s) - 1) / 2) for s in sim_nets]
println("Simulated density: ",
    round(mean(sim_densities), digits=4), " ± ",
    round(std(sim_densities), digits=4))

# Global clustering coefficient (transitivity): 3 × triangles / two-paths,
# computed from the networks themselves with ERGM's own statistics
clustering(s) = 3 * compute(Triangle(), s) / compute(Kstar(2), s)
sim_clustering = [clustering(s) for s in sim_nets]
println("Simulated clustering: ",
    round(mean(sim_clustering), digits=4), " ± ",
    round(std(sim_clustering), digits=4))

Exploring Parameter Effects

Use simulation to understand how parameters affect network structure:

# Vary the triangle coefficient
formula = ERGMFormula([Edges(), Triangle()])
model = ERGMModel(formula, net)

for tri_coef in [0.0, 0.5, 1.0, 1.5]
    θ = [-2.0, tri_coef]
    sims = sample_networks(model, θ; n_sim=20)
    avg_triangles = mean(compute(Triangle(), s) for s in sims)
    avg_edges = mean(ne(s) for s in sims)
    println("θ_triangle = $tri_coef → ",
        "edges: $(round(avg_edges, digits=1)), ",
        "triangles: $(round(avg_triangles, digits=1))")
end

Computational Notes

  • Simulation time scales with burnin + n_sim × interval MCMC steps per chain; independent chains run in parallel when Julia has multiple threads (n_chains keyword)
  • Each step involves computing change statistics for all terms
  • For large networks, consider reducing n_sim or increasing interval
  • Simulated networks share the same node count and directedness as the observed network
  • Vertex and network attributes (and the observed network's settings) are inherited by simulated networks, so attribute-based terms evaluate against the same covariates

Best Practices

  1. Set random seeds: Pass an explicit rng (e.g. rng=Xoshiro(42)) for reproducible simulations
  2. Adequate burn-in: Ensure the chain has reached stationarity
  3. Sufficient thinning: Reduce autocorrelation between samples
  4. Compare statistics: Always compare model statistics between observed and simulated networks
  5. Multiple simulations: Use at least 50–100 simulated networks for stable estimates
  6. Check mixing: If simulated networks are very similar, increase the interval