Estimation API Reference

This page documents the functions for model fitting, simulation, and diagnostics.

Model Fitting

ergm / fit_ergm

ergm is a const alias of fit_ergm (ergm === fit_ergm): one method table, one keyword vocabulary.

ERGM.fit_ergm — Function
fit_ergm(net, terms; method=:auto, kwargs...) -> ERGMResult
ergm(net, terms; method=:auto, kwargs...) -> ERGMResult

Fit an ERGM to the observed network net with the model terms — R ergm's ergm(net ~ edges + triangle + ...). ergm is a const alias of fit_ergm (ergm === fit_ergm): the statnet name and the ecosystem's fit_<model> name are one function.

Builds ERGMModel(ERGMFormula(terms), net) (validating every term against the network — a missing attribute, a directed-only term on an undirected network, or a two-mode network throws an ArgumentError before any fitting) and dispatches on method:

  • method=:auto (default) — R's rule (ERGM.resolve_method): the MPLE when no term is dyad-dependent, where the pseudo-likelihood is the likelihood and the MPLE is the exact MLE, and the MCMLE otherwise, as R's ergm() does.
  • method=:mple — maximum pseudo-likelihood, mple. Exact for dyad-independent formulas; fast but approximate under dyadic dependence (see the caveat show prints), where z values, p-values and intervals are withheld unless se=:bootstrap or se=:hessian is asked for.
  • method=:mcmle — Monte-Carlo maximum likelihood, mcmle.

Every other keyword is forwarded unchanged to the chosen estimator. A keyword that estimator does not take is an ArgumentError saying which estimator does — e.g. se=:bootstrap on a dyad-dependent formula, which method=:auto fits by MCMLE, asks for method=:mple:

keywordestimatormeaning
verbosebothprogress output
se, n_boot, boot_burnin, boot_intervalmple:hessian or :bootstrap standard errors and the bootstrap's controls (replicates without a finite MPLE are excluded, warned once); the default withholds z/p/intervals for a dyad-dependent formula (see mple)
maxiter, tolmpleNewton iteration cap / tolerance of the logistic fit
n_samples, burnin, interval, maxiter, initmcmleMCMC sample size per iteration, dyad-scaled burn-in / thinning, iteration cap, starting coefficients
termination, conv_precision, conv_confidence, max_n_samplesmcmlethe stopping rule (R ergm's confidence equivalence test by default) and the sample-size boost cap
conv_threshold, hotelling_alpha, gamma0, max_step_normmcmlethe legacy termination=:hotelling rule and Hummel step control
dropbothR's drop=TRUE (default): a statistic at the boundary of its attainable range is fixed at ∓Inf and the rest estimated, with R's message; drop=false refuses such a model
proposalbothMH proposal of every simulation: :spdyad (R ergm 4's SPDyad, the mcmle default), :tnt (tie/no-tie, the default of the mple bootstrap) or :random
effective_sizemcmleESS-adaptive sampling target (R's MCMLE.effectiveSize, 64 by default; nothing = fixed n_samples draws per iteration)
bridge_rungs, bridge_samplesmcmlepath-sampling log-likelihood controls
missingmcmle:error (default), :mle (missing-data maximum likelihood) or :condition_on_face for masked dyads
obs_burnin, obs_intervalmcmlecontrols of the constrained chain under missing=:mle
rngboththe AbstractRNG every Monte-Carlo draw flows from
constraints—statnet's sample-space constraints are not implemented: any non-empty value is an ArgumentError

Arguments

  • net::Network: the observed (one-mode) network
  • terms: a single term, a vector of terms, or a vector mixing terms with vectors of terms — [Edges(), Degree(0:2)] is spliced into one term per degree, as statnet's degree(0:2). Anything else is an ArgumentError naming the offending element; swapping the two positional arguments (fit_ergm(terms, net)) is an ArgumentError too, not a MethodError.
  • method::Symbol=:auto: :auto, :mple or :mcmle

Example

using ERGM, Random
net = load_dataset(:florentine_marriage)
fit = ergm(net, [Edges(), NodeCov(:wealth)])            # dyad-independent: MPLE = MLE
fit.method                                               # :mple
round.(coef(fit); digits=3)                              # [-2.595, 0.011]
fit_dep = fit_ergm(net, [Edges(), GWESP(0.5)]; rng=Xoshiro(1))   # dyad-dependent: MCMLE
fit_dep.method                                           # :mcmle
fit_dep.converged                                        # true
source
ERGM.ergm — Function
ergm(net, terms; method=:auto, kwargs...) -> ERGMResult

The statnet-style name of fit_ergm — a const alias, so ergm === fit_ergm and the two names share one method table, one docstring of keywords and one set of error messages. See fit_ergm for the full keyword vocabulary.

Example

using ERGM
net = load_dataset(:florentine_marriage)
ergm(net, [Edges(), NodeCov(:wealth)]) === nothing   # false — a fitted ERGMResult
ergm === fit_ergm                                     # true
source

resolve_method

The default method=:auto follows R: the MPLE (exact) when no term is dyad-dependent, the MCMLE otherwise. The rule is public (not exported) so the ERGM variants resolve :auto the same way.

ERGM.resolve_method — Function
resolve_method(method::Symbol, model; exact=:mple, mcmc=:mcmle,
               methods=(exact, mcmc), context="fit_ergm") -> Symbol

The estimator a method= keyword selects, with R's default rule for method=:auto: the pseudo-likelihood estimator exact when no term of the model is dyad-dependent (there the pseudo-likelihood IS the likelihood, so the MPLE is the exact MLE), and the Monte-Carlo MLE mcmc otherwise — what R's ergm() does (estimate = "MLE", which for a dyad-independent formula is computed by the logistic regression). Any other method must be one of methods and is returned unchanged; anything else is an ArgumentError naming the choices.

model is anything has_dyad_dependent has a method for (an ERGMModel, a variant's own model type), or a Bool that already says whether the formula is dyad-dependent. The ERGM variants reuse this rule with their own estimator names, e.g. exact=:cmple, mcmc=:cmle for TERGM's conditional estimators, so :auto means the same thing across the family.

Example

using ERGM
net = load_dataset(:florentine_marriage)
ERGM.resolve_method(:auto, ERGMModel(ERGMFormula([Edges(), NodeCov(:wealth)]), net))  # :mple
ERGM.resolve_method(:auto, ERGMModel(ERGMFormula([Edges(), Triangle()]), net))        # :mcmle
ERGM.resolve_method(:mple, true)                                     # :mple (explicit choice kept)
ERGM.resolve_method(:auto, true; exact=:cmple, mcmc=:cmle)           # :cmle
source

mple

ERGM.mple — Function
mple(model::ERGMModel; verbose=false, se=nothing, n_boot=100,
     boot_burnin=nothing, boot_interval=nothing, maxiter=100, tol=1e-8,
     rng=Random.default_rng(), proposal=:tnt, drop=true) -> ERGMResult

Fit an ERGM using Maximum Pseudo-Likelihood Estimation: a logistic regression of the dyad indicators on the change statistics, solved by Newton–Raphson on the ecosystem's shared kernel (NetworkCore.logistic_derivatives + NetworkCore.newton_fit) to a tolerance of tol on the pseudo-log-likelihood. On the Florentine marriage network the dyad-independent fit agrees with R ergm to 1e-12 on the coefficients and 5e-8 on the standard errors (provenanced fixture, asserted at 1e-6).

Arguments

  • model::ERGMModel: The ERGM model specification
  • verbose::Bool=false: Print progress information
  • maxiter::Int=100, tol::Float64=1e-8: Newton iteration cap and convergence tolerance (see NetworkCore.newton_fit). A fit that exhausts maxiter is returned with converged = false and a warning
  • se: How to compute standard errors. The default (nothing) is :hessian, with the inference it supports decided by the formula — see "Inference under dyadic dependence" below:
    • :hessian — inverse of the observed pseudo-likelihood information. For dyad-independent models the pseudo-likelihood is the true likelihood and these are the exact ML standard errors. For models with dyad-dependent terms they are the naive pseudo-likelihood errors — typically anticonservative (too small), because the pseudo-likelihood treats dependent dyads as independent observations.
    • :bootstrap — parametric bootstrap: simulate n_boot networks from the model at the MPLE estimate (via the MCMC sampler), refit the MPLE on each, and use the empirical covariance of the refitted coefficients. Honest under dyad dependence (though the MPLE point estimate itself may still be biased; consider method=:mcmle). A replicate on which the MPLE does not exist — a simulated network with no triangle under Triangle(), no shared-partner edge under GWESP, or a separated design — is excluded from the covariance (its refit is -Inf/NaN, which would make every standard error NaN). The standard errors are then conditional on a finite refit: the excluded replicates are the extreme ones, so the standard errors are biased downward. ONE warning names how many of n_boot were excluded, fit.boot_replicates holds every refit (the excluded ones as NaN rows) and approximations(fit) records it. At least two finite refits are required (ArgumentError otherwise). A point estimate that itself carries a ±Inf coefficient (see below) cannot be simulated from, so se=:bootstrap is refused for it.
  • n_boot::Int=100: Number of bootstrap replicates (only for se=:bootstrap)
  • boot_burnin, boot_interval: MCMC controls for the bootstrap simulations; default to the dyad-scaled mcmle defaults (20 * n_dyads and max(100, n_dyads ÷ 10))
  • proposal::Symbol=:tnt: MH proposal of the bootstrap simulations (see mh_sample)
  • drop::Bool=true: R's control.ergm(drop=TRUE): a statistic at the boundary of its attainable range is fixed at ∓Inf (below); drop=false refuses such a model
  • rng::AbstractRNG=Random.default_rng(): Source of the bootstrap simulation randomness (reproducible seeding)

Returns

  • ERGMResult: Fitted model results (se_type records :hessian or :bootstrap)

Inference under dyadic dependence

For a formula with a dyad-dependent term (has_dyad_dependent(model)), the naive pseudo-likelihood standard errors are not calibrated: in simulation (n = 30, edges + gwesp(0.5)) 95 % Wald intervals built from them covered the truth 0.85 and 0.71 of the time, against 0.945 and 0.970 for the parametric bootstrap. So, by default, a dyad-dependent MPLE fit reports its point estimates and naive standard errors but no inference built on them: z_values and p_values are NaN (the coefficient table shows NaN in those columns, with a note saying why), confint refuses with an ArgumentError, and approximations(fit) records the suppression. For calibrated inference use se=:bootstrap (z, p and intervals are then reported) or method=:mcmle. Passing se=:hessian explicitly is the written opt-in to R's naive Wald table (z and p from the inverse Hessian), printed with the pseudo-likelihood caveat. Dyad-independent formulas are unaffected: there the MPLE is the MLE and its z, p and intervals are exact.

Note: the reported log-likelihood is the maximized pseudo-log-likelihood; AIC/BIC derived from it are only heuristics for dependence models. dof(fit) counts the finite coefficients and the BIC sample size is the number of dyads they were estimated on (R's logLik df and nobs attributes), so after a drop (below) AIC/BIC are R's numbers too.

Separation that _boundary_columns_once cannot see — a combination of statistics that predicts every tie — leaves the pseudo-likelihood without a maximum. R warns "The MPLE does not exist!". mple decides it with the shared NetworkCore.logistic_separation verdict, an exact linear programme on the design (as R's mple.existence), and follows the ecosystem's separation policy: it warns, naming the coefficients that carry the separating direction; returns the fit with converged == false and those names in fit.separated_terms; and withholds inference — z values and p-values are NaN and confint returns NaN limits — while keeping the coefficients and standard errors where Newton stopped, for diagnosis. show and approximations carry the caveat, and is_exact(fit) is false. se=:bootstrap is refused on such a fit (there is no estimate to simulate from).

A statistic at the boundary of its attainable range — a NodeMatch with no within-group tie, a NodeMix cell of a singleton level, a Triangle on a network with no two-path, … — has no finite MPLE. It is detected as R does — the observed statistic against the term's attainable range (ergm.checkextreme.model), which also catches a statistic whose change statistics are all zero — and by the pseudo-likelihood design. As R ergm does (its default drop=TRUE), mple warns "observed statistic(s) … are at their smallest attainable values. Their coefficients will be fixed at -Inf", returns that coefficient as -Inf (+Inf at the largest value) with standard error 0 and p-value 0, and fits the remaining coefficients on the dyads the dropped statistic does not touch — the exact limit of the pseudo-likelihood, and R's numbers. NetworkCore.approximations(fit) lists the fixed coefficients; show prints a note under the table. mcmle does the same (see there). drop=false refuses such a model with an ArgumentError (R's drop=FALSE is not implemented).

A statistic that does not vary on the dyads fitted (every change statistic 0, with no attainable bound reached), or that is a linear combination of the statistics before it, has no identifiable coefficient. Newton would stop at its start on the singular information and return 0 for every coefficient; instead, as R's glm does, the coefficient is reported as NaN (standard error NaN; R: NA), with R's warning, and the other coefficients are estimated without it.

Dyads masked as missing (NetworkCore.set_missing_dyad!) are excluded from the pseudo-likelihood: an unobserved tie status is not a response, so those dyads contribute no logistic-regression row and nobs decreases accordingly. Their face values still condition the change statistics of the observed dyads. This is the standard available-case pseudo-likelihood — a principled treatment of missing data — so mple declares NetworkCore.supports_missing(mple) == true and needs no missing keyword; the fit records missing_method = :available_case (:none when nothing is masked).

Caveat for se=:bootstrap on a masked network: the bootstrap simulates from the fitted model, and a simulated network has a value at every dyad, so the MH sampler conditions the masked dyads on their face value. The point estimate is available-case, but the bootstrap SEs around it are not; a warning is emitted. For maximum likelihood under missing data use mcmle(model; missing=:mle).

Example

using ERGM
net = load_dataset(:florentine_marriage)
fit = mple(ERGMModel(ERGMFormula([Edges(), NodeCov(:wealth)]), net))
fit.converged            # true
round.(coef(fit); digits=3)   # [-2.595, 0.011]  (R ergm: -2.594929, 0.010546)
source

mcmle

ERGM.mcmle — Function
mcmle(model::ERGMModel; n_samples::Int=1000, burnin=nothing,
      interval=nothing, maxiter::Int=60, n_chains::Int=1,
      termination::Symbol=:confidence, conv_precision=0.1,
      conv_confidence=0.99, max_n_samples=nothing,
      proposal::Symbol=:spdyad, effective_size=64, drop=true,
      gamma0::Float64=0.1, max_step_norm::Float64=5.0,
      init=nothing, missing::Symbol=:error,
      obs_burnin=nothing, obs_interval=nothing,
      rng=Random.default_rng(), bridge_rungs::Int=16,
      bridge_samples=nothing, verbose::Bool=false) -> ERGMResult

Fit an ERGM using Monte Carlo Maximum Likelihood Estimation.

Starting from the MPLE estimates (or init), every iteration — the first included, as in statnet — samples networks at the current coefficients and takes a Hummel-style partial Newton step toward the pseudo-target γ·g(y_obs) + (1−γ)·ḡ (_hummel_step (internal)). The step length γ ∈ (0, 1] starts at gamma0 and adapts upward (at most doubling per iteration) while the observed statistics lie outside the sampled statistic cloud; it reaches γ = 1 once the cloud covers them. Each Newton step is capped at Euclidean norm max_step_norm. (A dyad-independent formula started from its MPLE is already at the exact MLE: no step is taken, the iterations only confirm the moment equation.)

Convergence is declared only at full step length (γ = 1), by R ergm 4's confidence rule (termination=:confidence, confidence_test): the estimating equation at the updated coefficients must lie, with conv_confidence (99 %) Monte-Carlo confidence, inside a tolerance region of conv_precision (0.1) of the statistics' variance. When the test fails near the solution the next iteration's sample is enlarged (up to max_n_samples, default 16 × n_samples), so the rule is attainable under Monte-Carlo noise. The estimate returned by a converged fit is the update from the sample that passed, and that sample is the one the standard errors, mcmc_samples, fit.mcmc_convergence and fit.termination describe. termination=:hotelling is the pre-0.2 rule: every per-statistic t-ratio below conv_threshold and a non-significant Hotelling T² test at hotelling_alpha (mcmc_convergence).

Arguments

  • model::ERGMModel: The ERGM model specification
  • n_samples::Int=1000: Number of MCMC samples per iteration (in total, over all chains)
  • burnin::Int: Burn-in steps per chain. Defaults to 20 * n_dyads (mcmc_defaults, the one dyad-scaled rule shared with every sampler), so mixing scales with network size
  • interval::Int: Thinning interval. Defaults to max(100, n_dyads ÷ 10)
  • maxiter::Int=60: Maximum MCMLE iterations (R's MCMLE.maxit; the ecosystem's iteration-cap keyword)
  • n_chains::Int=1: Independent MH chains per iteration (and for the final sample). The n_samples draws are split over the chains, each burned in separately from the observed network and seeded deterministically from rng exactly as sample_networks does, then concatenated; the effective sample size behind the Hotelling test is the sum of the per-chain Geyer ESSs. With several Julia threads the chains run in parallel — the result is identical at any thread count, which is why n_chains never defaults to Threads.nthreads(). n_chains=1 is bit-for-bit the single-chain sampler.
  • termination::Symbol=:confidence, conv_precision=0.1, conv_confidence=0.99, max_n_samples=16·n_samples: the stopping rule (above) and the cap on the boosted sample size
  • conv_threshold::Float64=0.1, hotelling_alpha::Float64=0.05: the t-ratio threshold and Hotelling level of termination=:hotelling
  • proposal::Symbol=:spdyad: the MH proposal of every chain. The default is R ergm 4's: its MCMC.prop = ~sparse + .triadic selects the SPDyad proposal (TNT mixed with a shared-partner-focused proposal) for every one-mode network, whatever the terms — and ERGM.jl's models are one-mode (R falls back to TNT only for bipartite networks, which ERGM.jl refuses). :tnt (tie/no-tie) and :random (see mh_sample) remain available. Both :spdyad and :tnt are exact samplers of the model; SPDyad mixes several times faster on models with triadic terms at about twice the cost per toggle.
  • effective_size=64: ESS-adaptive sampling (R's MCMLE.effectiveSize, 64 in R, the default). An iteration's sample is not a fixed n_samples draws: the chain is continued from the previous iteration and extended — its thinning interval doubling — until the effective sample size of the sampled statistics reaches the target, and the stopping rule's boost raises that target. n_samples then only sets the constrained chain's and the bridge's sample sizes, and interval the starting interval (an eighth of it). effective_size=nothing restores fixed-size sampling: n_samples draws interval toggles apart per iteration, boosted up to max_n_samples. mcmle(model; proposal=:tnt, effective_size=nothing) is the fixed-size tie/no-tie design
  • drop::Bool=true: R's control.ergm(drop=TRUE) — a statistic at the boundary of its attainable range is fixed at ∓Inf and the rest estimated (see "Boundary statistics" below); drop=false refuses such a model
  • gamma0::Float64=0.1: Initial Hummel step length
  • max_step_norm::Float64=5.0: Cap on the Euclidean norm of each Newton step
  • init::Vector{Float64}: Starting coefficients (statnet's control.ergm(init=)). Default: the MPLE. Pass coef(previous_fit) to continue an unconverged fit from where it stopped.
  • missing::Symbol=:error: Treatment of dyads masked as missing (NetworkCore.set_missing_dyad!): :error, :mle or :condition_on_face — see the missing-data section below
  • obs_burnin::Int, obs_interval::Int: Burn-in and thinning of the constrained chain under missing=:mle (statnet's obs.MCMC.burnin / obs.MCMC.interval). Default to the dyad-scaled rule applied to the number of masked dyads — the only dyads that chain moves
  • rng::AbstractRNG=Random.default_rng(): Source of all random draws; runs with the same rng state are exactly reproducible
  • bridge_rungs::Int=16: Number of path-sampling segments used for the final log-likelihood estimate (see _bridge_loglik). bridge_rungs=0 skips the estimate: loglik, aic and bic are NaN, show prints "not estimated", and approximations(fit) records it. The bridge draws bridge_rungs + 1 further MCMC samples of bridge_samples draws each after the fit is finished — on a single thread it was ~70 % of the total mcmle time on the Florentine and Faux Mesa High fits — and it consumes randomness only after the final sample, so coefficients and standard errors are bit-identical with and without it.
  • bridge_samples::Int: MCMC samples per bridge rung (default n_samples)
  • verbose::Bool=false: Print progress

Non-convergence is loud

A fit that exhausts maxiter without passing the stopping rule is returned with converged == false and a warning quoting the rule's p-value, the last max t-ratio, the Hotelling p-value and the step length; NetworkCore.approximations(fit) lists the non-convergence too, show prints the caveat under Converged: false, and fit.mcmc_convergence carries the t-ratios, Hotelling p, effective sample size, iteration count and step length recomputed on the final sample at the returned coefficients. Continue such a fit with mcmle(model; init=coef(fit), ...).

Standard errors

vcov(fit) is the inverse Fisher information estimated from the final MCMC sample, V = Σ̂⁻¹, plus the Monte-Carlo component of the estimate (Hunter & Handcock 2006, §3.3): the estimating equation ḡ(θ) = g_obs is itself Monte Carlo, with Var(ḡ) = Σ_mc — the Geyer initial-sequence asymptotic covariance of the sampled statistics, per-statistic on the diagonal with the lag-0 correlations off-diagonal, divided by the number of draws — so vcov = V + V·Σ_mc·V. The Fisher part alone is fit.vcov_fisher, the Monte-Carlo standard error sqrt(diag(V·Σ_mc·V)) is mcmc_se(fit), and show prints R's summary.ergm "MCMC %" column: round(100 · (se − se_fisher) / se) per coefficient — the share of the standard error (not of its variance) that the Monte-Carlo term adds, R's 100 * (tot.se - mod.se) / tot.se. At the default n_samples=1000 it rounds to 0 on a well-mixing chain; a large share says the sample, not the data, is limiting the precision — raise n_samples or n_chains.

Boundary statistics

A statistic at the boundary of its attainable range has no finite MLE: a NodeMatch level with no within-group tie, a NodeMix cell of a singleton level (no dyad at all), a Triangle on a triangle-free network, a Degree(1) that no vertex has. As R's ergm() does under its default drop=TRUE, mcmle fixes such a coefficient at -Inf (+Inf at the largest value), warns with R's sentence, and estimates the rest with the statistic held at its bound — an infinite offset, which the samplers honour as a constraint (no move off the bound is accepted). The fixed coefficient is reported with standard error 0 and p-value 0, dof/AIC/BIC count only the estimated coefficients, and show and NetworkCore.approximations(fit) say which coefficients were fixed. When a fixed statistic is dyad-dependent (Triangle), the log-likelihood is not estimated (NaN), as for an infinite dyad-dependent Offset. Detection is R's ergm.checkextreme.model test (the observed statistic against the term's attainable range) together with the pseudo-likelihood design's boundary test, which also sees, e.g., a NodeCov whose positive-change dyads are all empty. drop=false refuses such a model with an ArgumentError instead (R's drop=FALSE, which keeps the term in a model whose "MLE is poorly defined", is not implemented).

A dyad-independent statistic that does not vary at all, or is a linear combination of the statistics before it, has no identifiable coefficient: it is held at 0 (any value gives the same model) and reported as NaN, with R's warning, as R's MPLE reports NA. A dyad-dependent one leaves the MPLE start undefined and is refused unless init= is given.

Missing data

A network with dyads masked as missing (set_missing_dyad!) is rejected by default: missing=:error throws the shared NetworkCore.require_observed error, whose last bullets name the two policies mcmle accepts (missing_policies(mcmle) == (:error, :condition_on_face, :mle)).

  • missing=:mle — missing-data maximum likelihood (Handcock & Gile 2010; what R ergm() does with NA ties). The likelihood is Z_obs(θ) / Z(θ), the masked dyads integrated out. Each iteration runs two chains: the free chain toggles every dyad (masked ones included — the unconditional model) and gives ḡ = Ê[g(Y)] and Σ_free; the constrained chain toggles only the masked dyads, the observed dyads fixed at their observed values, and gives ĝ_obs = Ê[g(Y) | Y_obs] and Σ_obs. ĝ_obs replaces the observed statistics as the Newton target (θ += γ Σ_free⁻¹ (ĝ_obs − ḡ)), the convergence tests compare the two chains (the difference's variance is Σ_free/n_eff_free + Σ_obs/n_eff_obs), the Fisher information is Σ_free − Σ_obs (Eq. 9 there; standard errors are NaN, with a warning, when it is not positive definite), and both chains contribute Monte-Carlo error to the standard errors. The log-likelihood log Z_obs(θ) − log Z(θ) is two path-sampling bridges (a toggleable=:all one from the exact dyad-independent normalizer over all dyads, a toggleable=:masked one from the exact normalizer over the masked dyads with the observed dyads fixed). The fit records missing_method = :mle; nobs is the number of observed dyads. Under dyad independence the estimate coincides with the available-case MPLE (the exact MLE of the observed dyads).
  • missing=:condition_on_face — hold each masked dyad fixed at its stored face value: never toggled, and scored as recorded in the observed sufficient statistics. That is the model conditional on the face values — a different estimand from the missing-data MLE, right only when the stored values are true by construction (structural zeros, ties fixed by design). Explicit and warned; the fit records missing_method = :condition_on_face.

mple (which declares NetworkCore.supports_missing(mple) == true) drops the masked dyads from the pseudo-likelihood instead. The provenanced flomarriage_missing_ergm.toml fixture pins missing=:mle against R ergm on a masked flomarriage.

The reported log-likelihood (and hence AIC/BIC) is estimated by path sampling along a bridge_rungs-segment ladder from a dyad-independent reference distribution to the fitted coefficients — the standard ergm-style bridge estimator — rather than a one-jump importance-sampling estimate, which has unusably high variance when θ̂ is far from the reference.

Returns

  • ERGMResult: Fitted model results. mcmc_samples holds the statistics sampled at the final coefficients (all chains concatenated; the free chain under missing=:mle; suitable for mcmc_diagnostics); samples from earlier iterations are discarded since they target different coefficient values.

Example

using ERGM, Random
net = load_dataset(:florentine_marriage)
model = ERGMModel(ERGMFormula([Edges(), GWESP(0.5)]), net)
fit = mcmle(model; n_samples=500, rng=Xoshiro(1))
fit.converged                     # true
se_method(fit)                    # :fisher — inverse Fisher information (+ MC term) from the MCMC sample
maximum(mcmc_se(fit) ./ stderror(fit)) < 0.2   # true: the MC share is small
fast = mcmle(model; n_samples=500, rng=Xoshiro(1), bridge_rungs=0)
coef(fast) == coef(fit)           # true: the bridge only runs after the fit
isnan(loglikelihood(fast))        # true

# Missing-data MLE on a copy with two unobserved dyads
masked = copy(net); set_missing_dyad!(masked, 3, 4); set_missing_dyad!(masked, 1, 9)
fit_na = mcmle(ERGMModel(ERGMFormula([Edges(), GWESP(0.5)]), masked);
               n_samples=500, missing=:mle, rng=Xoshiro(2))
missing_method(fit_na)            # :mle
nobs(fit_na)                      # 118
source

mcmc_se

ERGM.mcmc_se — Function
mcmc_se(result::ERGMResult) -> Vector{Float64}

The Monte-Carlo component of each coefficient's standard error: for an MCMLE fit, sqrt(diag(V·Σ_mc·V)) where V = vcov_fisher is the inverse Fisher information and Σ_mc the Geyer initial-sequence covariance of the sampled statistics' mean (Hunter & Handcock 2006 §3.3) — the uncertainty that comes from the finite MCMC sample rather than from the data. stderror(result) already includes it (se² = se_fisher² + mcmc_se²); show prints R's summary.ergm "MCMC %" column, which is the share of the standard error (not of its variance) that the Monte-Carlo term adds: round(100 · (se − se_fisher) / se) with se_fisher = sqrt.(diag(result.vcov_fisher)) — R's 100 * (tot.se - mod.se) / tot.se. A large share says the sample, not the data, limits the precision: raise n_samples/n_chains. Zeros for an MPLE fit (no MCMC sample).

Example

using ERGM, Random
net = load_dataset(:florentine_marriage)
fit = fit_ergm(net, [Edges(), GWESP(0.5)]; method=:mcmle, n_samples=1000, rng=Xoshiro(1))
all(mcmc_se(fit) .< stderror(fit))            # true
all(mcmc_se(fit_ergm(net, [Edges()])) .== 0)  # true: MPLE has no MC term
source

mcmc_convergence

The MCMLE convergence tests as one public (not exported) function, so a variant that solves its own moment equations uses the same rule.

ERGM.mcmc_convergence — Function
mcmc_convergence(samples::AbstractMatrix, targets::AbstractVector;
                 conv_threshold=0.1, hotelling_alpha=0.05,
                 chain_lengths=[size(samples, 1)],
                 target_samples=nothing, target_chain_lengths=nothing)
    -> (converged, t_ratios, hotelling_p, n_eff)

The classical MCMLE convergence tests, as one public (not exported) function: given an n × p matrix of statistics sampled at the current coefficients and the p target (observed) statistics, compute

  • t_ratios: the per-statistic convergence t-ratios |target_j − mean_j| / sd_j (Inf for a statistic with zero sampled variance — a collapsed sampler cannot confirm convergence);
  • n_eff: the effective sample size — the smallest over statistics of the Geyer initial-sequence ESS, summed over chains when chain_lengths says the rows are several independent chains concatenated;
  • hotelling_p: the p-value of the Hotelling T² test that the sampled mean equals the targets, using the sampled covariance and n_eff (0.0 when the covariance is singular or n_eff ≤ p, where the test is undefined);
  • converged: maximum(t_ratios) < conv_threshold && hotelling_p > hotelling_alpha.

When the targets are themselves a Monte-Carlo mean — the constrained chain of the missing-data MCMLE — pass its draws as target_samples (with target_chain_lengths): targets must then equal their column means, the per-draw sd behind the t-ratios becomes sqrt(var_j + var_target_j), and the Hotelling test uses the variance of the difference of the two means, Σ/n_eff + Σ_target/n_eff_target.

Under termination=:hotelling (the pre-0.2 rule) converged is mcmle's stopping verdict. Under the default termination=:confidence the verdict is R ergm's equivalence test (confidence_test) and this function only supplies the classical diagnostics recorded in fit.mcmc_convergence, computed on the final sample — which, for a converged fit, is the sample drawn at the last iterate, before the final Newton step (see MCMLEConvergence). ERGMEgo's moment matching and any other equation-solving estimator can use it instead of an ad-hoc relative-change rule.

Example

using ERGM, Random, Statistics
rng = Xoshiro(1)
draws = randn(rng, 2000, 2) .+ [1.0 5.0]           # a stationary sample around (1, 5)
ok = ERGM.mcmc_convergence(draws, [1.0, 5.0])
ok.converged                                        # true
off = ERGM.mcmc_convergence(draws, [3.0, 5.0])      # 2 sd away on statistic 1
off.converged, off.t_ratios[1] > 1.5                # (false, true)
two = ERGM.mcmc_convergence(draws, [1.0, 5.0]; chain_lengths=[1000, 1000])
two.n_eff > 1000                                    # true: ESS adds over chains
source

The MCMLE iteration's building blocks

mcmle is built from drivers that know nothing about networks: the iteration, R ergm 4's confidence stopping rule, the covariance, the ESS-adaptive sample-size chooser and the bridge integral behind the log-likelihood. They are part of the Extension API, so a variant's own MCMC estimator (ERGMEgo's moment matching, TERGM's CMLE, ERGMRank's and ERGMCount's MCMLEs) runs on the same ones: mcmle_solve, confidence_test, mcmle_covariance, ess_sample, mcmle_sampler (mcmle's own sampler, for an estimator that samples an ERGMModel) and bridge_integrate.

newtonfit / logisticderivatives

The shared optimizer and logistic kernel are NetworkCore.jl's (public there) and re-exported by ERGM.jl, so using ERGM provides them unchanged and ERGM.newton_fit === NetworkCore.newton_fit. They are documented on NetworkCore.jl's inference page; ERGM's MPLE is newton_fit applied to the binomial-row form of logistic_derivatives:

using ERGM
# Edges-only MPLE of the Florentine marriage network in closed form: 120
# dyads, 20 ties, so θ̂ = logit(20/120)
d = logistic_derivatives(ones(1, 1), [120.0], [20.0])
fit = newton_fit(d, [0.0])
fit.θ[1] ≈ log(20 / 100)     # true
fit.converged                # true

Simulation

mh_toggle!

The Metropolis toggle kernel every ERGM-family sampler is built on: the accept/reject arithmetic, burn-in and thinning, with the proposal, the change statistics and the state mutation supplied as callables.

ERGM.mh_toggle! — Function
mh_toggle!(rng::AbstractRNG, θ::AbstractVector, delta::Vector{Float64},
           propose, change!, apply!, on_sample;
           burnin::Int, interval::Int, n_samples::Int,
           hastings=nothing) -> Int

The Metropolis toggle kernel every ERGM-family sampler is built on. It owns exactly three things — the accept/reject arithmetic, the burn-in and the thinning — and knows nothing about networks: what a move is, how it changes the sufficient statistics and how it is applied to the state are supplied as callables, so the same loop samples binary networks (ERGM.jl's _mh_run!), formation/dissolution networks (TERGM), multilayer networks (ERGMMulti) and rankings (ERGMRank).

For burnin + n_samples × interval steps the kernel does

move    = propose(rng)                 # a proposal, drawn from `rng`
removal = change!(delta, move)         # fills Δ, says whether the move removes
accept  = log(rand(rng)) < (removal ? -1 : 1) * θ'Δ + hastings(move, removal)
accept && apply!(move, removal)        # mutate the state

and after burn-in calls on_sample(k) at every interval-th step, k running from 1 to n_samples. Returns the number of samples recorded.

Callables

  • propose(rng) -> move: draw the next proposal, consuming only rng. For ERGM it is a free dyad (i, j) — never a masked one, never a loop, i < j on undirected networks. Any immutable value can be a move (a tuple, a struct); the kernel only passes it on.
  • change!(delta, move) -> Bool: fill delta with the add-direction change statistics g(y⁺) − g(y⁻) of the move (the state-independent convention every change_stat method follows) and return true when the move is a removal (the tie is currently present), so that the kernel negates the log-ratio. A sampler whose moves have no removal direction — ERGMRank's rank swaps, whose delta is already the signed difference — returns false always.
  • apply!(move, removal::Bool): mutate the state for an accepted move (toggle the tie, and keep any running statistics current).
  • on_sample(k): record sample number k (write a row of a statistics matrix, push a copy of the network, ...).
  • hastings(move, removal) -> Float64 (keyword, optional): the log Hastings ratio log q(y | y*) − log q(y* | y) of an asymmetric proposal, evaluated on the current state before the move is applied. Omitted (nothing, the default) for a symmetric proposal — a uniformly random dyad, a rank swap — and then compiled out entirely. ERGM.jl's tie/no-tie (TNT) proposal passes its correction here (see mh_sample).

Keywords

  • burnin::Int: steps discarded before the first sample (≥ 0).
  • interval::Int: steps between recorded samples (≥ 1).
  • n_samples::Int: number of samples to record (≥ 0).

Contract

θ and delta must have the same length; delta is the caller's workspace and is overwritten at every step. The kernel draws from rng in a fixed order — the proposal first (through propose), then one uniform for the acceptance test — so for the same rng state, propose and change! the sampled sequence is bit-identical to ERGM.jl's pre-0.2 hand-written loop (pinned by the "MH kernel" testset). It allocates nothing per step when the callables do not (@allocated is pinned to grow by 0 bytes between burnin=10_000 and burnin=20_000): keep the move a stack value and the closures free of reassigned captured variables.

Adopting the kernel in a variant

TERGM _sample_constrained — moves are dyads drawn from the free list (non-edges of the previous network for formation, its edges for dissolution), the change statistics are the temporal _tchange, no samples are recorded (the state after steps toggles is the draw):

propose = rng -> free[rand(rng, 1:length(free))]
change! = (delta, move) -> begin
    i, j = move
    for (k, t) in enumerate(terms); delta[k] = _tchange(t, net, i, j, prev); end
    has_edge(net, i, j)
end
apply! = (move, removal) -> begin
    i, j = move
    removal ? rem_edge!(net, i, j) : add_edge!(net, i, j)
    nothing
end
mh_toggle!(rng, θ, delta, propose, change!, apply!, _ -> nothing;
           burnin=steps, interval=1, n_samples=0)

(A sketch in TERGM's own names — free, net, prev, _tchange — not a standalone program, hence the jl fence; the runnable example is below.)

ERGMMulti — a move is (layer, i, j); change! calls change_stat_layer(t, current, l, i, j) and returns has_edge(current.layers[l], i, j); apply! toggles that layer's edge; on_sample pushes a copy of the multilayer network. This is real code now — ERGMMulti._multi_mh_run, pinned bit-identical to a hand-written mh_toggle! call in ERGMMulti's tests.

ERGMRank — a move is a swap (ego, j, k); change! fills delta with _swap_delta(terms, current, ego, j, k) and returns false (a swap has no removal direction); apply! is swap_ranks!(current, ego, j, k); on_sample pushes copy(current).

ERGMCount does not adopt it: its sampler is a Gibbs sweep that redraws each dyad's count from its full conditional, not a Metropolis toggle.

Example

A two-state toy chain — a single "tie" with statistic g = y, sampled at θ = log(3), so P(y = 1) = 3/4:

using ERGM, Random, Statistics
state = Ref(false)
draws = Float64[]
mh_toggle!(Xoshiro(1), [log(3.0)], [0.0],
           rng -> 1,                              # the only move
           (delta, move) -> (delta[1] = 1.0; state[]),
           (move, removal) -> (state[] = !removal),
           k -> push!(draws, state[]);
           burnin=100, interval=1, n_samples=20_000)
abs(mean(draws) - 0.75) < 0.02    # true
source

mh_sample

ERGM.mh_sample — Function
mh_sample(model::ERGMModel, θ::Vector{Float64};
          n_samples::Int=100, burnin=nothing, interval=nothing,
          rng::AbstractRNG=Random.default_rng(),
          start_net::Union{Nothing,Network}=nothing,
          return_networks::Bool=false, missing::Symbol=:error,
          toggleable::Symbol=:free, proposal::Symbol=:tnt)
    -> (stats::Matrix{Float64}, networks::Union{Nothing,Vector{<:Network}})

Run one Metropolis–Hastings edge-toggle chain of the ERGM exp(θ'g(y)) defined by model's terms, and return the sampled sufficient statistics (and optionally the sampled networks).

This is the public single-chain sampling primitive that the estimation routines (and downstream packages such as ERGMEgo.jl) build on. Each MH step proposes toggling one dyad and accepts with probability min(1, exp(±θ'Δ) · H), where Δ is the add-direction change statistic vector of the dyad and H the proposal's Hastings ratio.

The proposal (proposal=) is statnet's default tie/no-tie (:tnt): with probability ½ a uniformly chosen existing tie is proposed for removal, otherwise a uniformly chosen dyad is toggled, and the acceptance ratio carries the exact Hastings correction (R ergm's MH_TNT). On sparse networks — the usual case — a uniformly random dyad is nearly always an absent tie whose addition the model rejects, so TNT mixes several times faster per toggle (about 7× in effective sample size on faux.mesa.high). proposal=:random is the uniformly random dyad toggle (symmetric, no correction), the pre-0.2 sampler, kept for reproducing earlier results. Both are exact: their stationary distribution is exp(θ'g(y))/Z(θ) (verified against enumeration in the test suite). The :masked chain always proposes uniformly among the masked dyads.

Which dyads the chain may toggle is toggleable:

  • :free (default) — every dyad that is not masked as missing (NetworkCore.set_missing_dyad!). A masked dyad is then frozen at its stored face value (edge present/absent as recorded), never proposed, so the chain conditions on it. Reinterpreting an unobserved tie as an observed one is never silent, so with :free a masked network is rejected unless the caller opts in with missing=:condition_on_face. Throws ArgumentError if every dyad is masked.
  • :all — every dyad, masked ones included: the chain samples the unconditional model exp(θ'g(y)) over the whole dyad set, as the free chain of the missing-data MCMLE (mcmle with missing=:mle) does. No unobserved value is read as an observation (the face values only seed the starting state, which burn-in washes out), so no missing= opt-in is needed; missing must be left at :error.
  • :masked — only the masked dyads, every observed dyad held fixed at its observed value: the constrained chain of the missing-data MCMLE, whose mean estimates E[g(Y) | Y_obs] (Handcock & Gile 2010). Requires n_missing_dyads(model.network) > 0; missing must be left at :error.

Arguments

  • model::ERGMModel: Model specification (terms + network template). The chain runs on a copy; model.network is never mutated.
  • θ::Vector{Float64}: Natural-parameter vector, one entry per term.

Keywords

  • n_samples::Int=100: Number of recorded samples.
  • burnin::Int: MH steps discarded before the first sample. Defaults to 20 × n_dyads (the shared dyad-scaled rule, mcmc_defaults), where n_dyads is the number of dyads the chain may toggle.
  • interval::Int: MH steps between recorded samples (thinning). Defaults to max(100, n_dyads ÷ 10).
  • rng::AbstractRNG=Random.default_rng(): Source of all random draws; same rng state ⇒ identical output.
  • start_net=nothing: Starting network. Defaults to a copy of the observed model.network (attributes are preserved either way).
  • return_networks::Bool=false: Also collect a copy of the network at every sampling point.
  • missing::Symbol=:error: :error rejects a network with masked dyads (under toggleable=:free); :condition_on_face explicitly holds them at their face value.
  • toggleable::Symbol=:free: :free, :all or :masked — see above.
  • proposal::Symbol=:tnt: :tnt (tie/no-tie) or :random — see above.

Returns

A NamedTuple (stats, networks):

  • stats: n_samples × p matrix; row k holds g(y⁽ᵏ⁾).
  • networks: Vector of the sampled networks if return_networks=true, otherwise nothing.

Example

using ERGM, Random, Statistics
net = load_dataset(:florentine_marriage)
model = ERGMModel(ERGMFormula([Edges(), Triangle()]), net)
out = mh_sample(model, [-1.5, 0.3]; n_samples=500, rng=Xoshiro(1))
size(out.stats)            # (500, 2)
mean(out.stats, dims=1)    # E[g] estimate at θ

# The two chains of the missing-data MCMLE on a masked copy
masked = copy(net); set_missing_dyad!(masked, 3, 4); set_missing_dyad!(masked, 1, 9)
mm = ERGMModel(ERGMFormula([Edges(), Triangle()]), masked)
free = mh_sample(mm, [-1.5, 0.3]; n_samples=200, toggleable=:all, rng=Xoshiro(2))
cons = mh_sample(mm, [-1.5, 0.3]; n_samples=200, toggleable=:masked, rng=Xoshiro(3),
                 return_networks=true)
all(has_edge(s, 2, 6) for s in cons.networks)   # true: observed ties never move
source

Sampler defaults

Every sampler resolves an omitted burnin/interval through one dyad-scaled rule, mcmc_defaults (part of the Extension API): burnin = 20 × n_dyads and interval = max(100, n_dyads ÷ 10).

simulate_ergm

ERGM.simulate_ergm — Function
simulate_ergm(result::ERGMResult; n_sim::Int=1, burnin=nothing,
              interval=nothing, rng::AbstractRNG=Random.default_rng(),
              n_chains::Int=min(n_sim, 4),
              missing::Symbol=:error, proposal::Symbol=:tnt) -> Vector{Network}

Simulate networks from a fitted ERGM (at result.coefficients).

If the fitted network has dyads masked as missing, the simulation cannot reinterpret them: the sampler would silently freeze each unobserved tie at its stored face value and report it as a simulated tie. That requires the explicit missing=:condition_on_face opt-in (a warning is emitted); the default missing=:error refuses. This holds even for an MPLE fit, whose point estimate excluded the masked dyads: simulation is a separate act.

Arguments

  • result::ERGMResult: Fitted ERGM result
  • n_sim::Int=1: Number of networks to simulate
  • burnin::Int: MCMC burn-in steps (per chain). Defaults to 20 × n_dyads (the shared dyad-scaled rule, mcmc_defaults)
  • interval::Int: Steps between samples. Defaults to max(100, n_dyads ÷ 10)
  • rng::AbstractRNG: Source of all random draws (reproducible seeding)
  • n_chains::Int: Number of independent chains (see sample_networks)
  • missing::Symbol=:error: Missing-dyad policy (:error or :condition_on_face)
  • proposal::Symbol=:tnt: MH proposal, :tnt (tie/no-tie, statnet's default) or :random (see mh_sample)

Returns

  • Vector of simulated Network objects

Example

using ERGM, Random
net = load_dataset(:florentine_marriage)
fit = fit_ergm(net, [Edges(), NodeCov(:wealth)])
sims = simulate_ergm(fit; n_sim=10, rng=Xoshiro(1))
length(sims)                       # 10
all(nv(s) == 16 for s in sims)     # true
source

sample_networks

ERGM.sample_networks — Function
sample_networks(model::ERGMModel, θ::Vector{Float64};
                n_sim::Int=1, burnin=nothing, interval=nothing,
                start_net::Union{Nothing,Network}=nothing,
                rng::AbstractRNG=Random.default_rng(),
                n_chains::Int=min(n_sim, 4),
                missing::Symbol=:error,
                proposal::Symbol=:tnt) -> Vector{Network{T,D}}

Sample networks from an ERGM specification. The returned vector is concretely typed (Vector{Network{T,D}}, the model's own network type).

The n_sim draws are split over n_chains independent MH chains run in parallel (Threads.@spawn), each burned in separately and seeded deterministically from rng — so for a fixed rng state and n_chains the result is identical regardless of the number of threads. n_chains deliberately does not default to Threads.nthreads(), precisely to keep results thread-count-independent.

Arguments

  • model::ERGMModel: ERGM model specification
  • θ::Vector{Float64}: Model coefficients
  • n_sim::Int=1: Number of networks to sample
  • burnin::Int: MCMC burn-in steps (per chain). Defaults to 20 × n_dyads (the shared dyad-scaled rule, mcmc_defaults)
  • interval::Int: Steps between samples. Defaults to max(100, n_dyads ÷ 10)
  • start_net: Starting network for every chain (default: an independent Bernoulli(density) random network per chain, with the observed network's attributes)
  • rng::AbstractRNG: Source of all random draws
  • n_chains::Int: Number of independent chains
  • missing::Symbol=:error: Missing-dyad policy. :error refuses a network with masked dyads; :condition_on_face explicitly freezes each masked dyad at its stored face value in every chain (_random_network starting states preserve them too).
  • proposal::Symbol=:tnt: MH proposal, :tnt (tie/no-tie, statnet's default) or :random (see mh_sample)

Example

using ERGM, Random
net = load_dataset(:florentine_marriage)
model = ERGMModel(ERGMFormula([Edges(), Triangle()]), net)
sims = sample_networks(model, [-1.6, 0.2]; n_sim=8, n_chains=2, rng=Xoshiro(1))
length(sims)                        # 8
sims isa Vector{Network{Int,false}} # true
source

Utilities

isdyaddependent / hasdyaddependent

ERGM.is_dyad_dependent — Function
is_dyad_dependent(term::AbstractERGMTerm) -> Bool

Whether the term's change statistic depends on the state of other dyads (true for e.g. Mutual, Triangle, Kstar, TwoPath, GWESP, GWDegree) or only on exogenous covariates of the dyad itself (false for Edges and all nodal/dyadic covariate terms).

For dyad-independent models the pseudo-likelihood is the likelihood, so MPLE is exact; for models with any dyad-dependent term MPLE point estimates can be biased and its inverse-Hessian standard errors are typically anticonservative (see mple).

The fallback for term types this package does not know about is true (the conservative answer). Packages defining their own dyad-independent terms should add a method returning false.

Example

using ERGM
is_dyad_dependent(Edges())          # false
is_dyad_dependent(NodeCov(:x))      # false
is_dyad_dependent(GWESP(0.5))       # true
source
ERGM.has_dyad_dependent — Function
has_dyad_dependent(model::ERGMModel) -> Bool

Whether the model's formula contains any dyad-dependent term (see is_dyad_dependent; unknown term types count as dependent).

This is THE predicate that decides whether a pseudo-likelihood fit is an approximation: for a dyad-independent formula the MPLE is the MLE and the inverse-Hessian standard errors are the exact ML ones. It is defined once and used by both show(::ERGMResult) (which prints the prose caveat) and is_exact(::ERGMResult) (which reports the same fact to a machine), so the two can never disagree. The ERGM variants (ERGMCount, ERGMMulti, TERGM) add methods for their own model types rather than defining same-named privates.

Example

using ERGM
net = load_dataset(:florentine_marriage)
has_dyad_dependent(ERGMModel(ERGMFormula([Edges(), NodeCov(:wealth)]), net))  # false
has_dyad_dependent(ERGMModel(ERGMFormula([Edges(), Triangle()]), net))        # true
source

Result Metadata

ERGM.jl implements the ecosystem's result-metadata protocol, so what a fit actually did is programmatically inspectable rather than buried in a show method. NetworkCore.fit_metadata(result) collects these accessors.

The key one is is_exact: an MPLE fit of a dyad-independent formula is the exact MLE, while the same estimator on a formula containing any dyad-dependent term (Triangle, GWESP, Mutual, ...) is an approximation with anticonservative standard errors. That distinction is exactly what a user needs and cannot otherwise see.

NetworkCore.objective — Method
objective(result::ERGMResult) -> Symbol

:pseudolikelihood for an MPLE fit (dyadwise conditionals multiplied as if independent) and :mc_likelihood for MCMLE (a Monte-Carlo approximation to the likelihood). Part of the shared result-metadata protocol.

Example

using ERGM
fit = fit_ergm(load_dataset(:florentine_marriage), [Edges()])
objective(fit)      # :pseudolikelihood
source
NetworkCore.is_exact — Method
is_exact(result::ERGMResult) -> Bool

true only for a converged MPLE fit of a dyad-independent formula: there the dyadwise conditionals are the model's conditionals, so the pseudo-likelihood is the likelihood and the MPLE is the exact MLE. The very same estimator applied to a formula containing any dyad-dependent term (Triangle, GWESP, Mutual, ...) reports false, and so does a fit whose pseudo-likelihood has no finite maximum — perfect separation (converged == false: the coefficients are a point on an asymptote, not an estimate) or a coefficient fixed at ±Inf by a boundary statistic (R's drop): an extended-value estimate is not the exact MLE. MCMLE is always false — it maximizes a Monte-Carlo approximation to the likelihood.

Example

using ERGM
net = load_dataset(:florentine_marriage)
is_exact(fit_ergm(net, [Edges(), NodeCov(:wealth)]))   # true — MPLE is the MLE here
is_exact(fit_ergm(net, [Edges(), Triangle()]; method=:mple))   # false — MPLE of a dyad-dependent formula
source
NetworkCore.se_method — Method
se_method(result::ERGMResult) -> Symbol

:hessian (inverse observed information of the objective), :bootstrap (parametric bootstrap), or :fisher — the se_type == :mcmc case, where the covariance is the inverse Fisher information estimated from the MCMC sample plus the Monte-Carlo component of the estimate (V + V·Σ_mc·V, Hunter & Handcock 2006 §3.3; the pure Fisher part is result.vcov_fisher, the added standard error is mcmc_se).

Example

using ERGM
fit = fit_ergm(load_dataset(:florentine_marriage), [Edges()])
se_method(fit)      # :hessian
source

The missing-data trait a term opts into (see the ecosystem missing-data contract):

NetworkCore.supports_missing — Method
supports_missing(term::AbstractERGMTerm) -> Bool

Whether the term's statistic honours the missing-dyad mask: that is, whether compute(term, net) is invariant to the face value of any dyad marked with NetworkCore.set_missing_dyad!.

This is the term-level method of the ecosystem missing-data trait (NetworkCore.supports_missing; see src/missing.jl for how ERGM's estimators declare it). It is false for every built-in term, and that is the honest answer: compute(Edges(), net) counts a masked dyad's stored edge at face value. The estimators are where ERGM's principled treatment lives — MPLE drops masked dyads from the pseudo-likelihood — so a false declaration here is not a defect, merely a statement of fact.

A term declares true only if it consults the mask itself. ERGMUserterms.validate_term tests the declaration by masking a dyad, flipping its face value, and requiring the statistic not to move.

Example

using ERGM
supports_missing(Edges())             # false — counts a masked tie at face value
supports_missing(mple)                # true  — the estimator drops masked dyads
struct ObservedEdges <: AbstractERGMTerm end
function ERGM.compute(::ObservedEdges, net)
    total = 0.0
    for e in edges(net)
        is_missing_dyad(net, e.src, e.dst) && continue
        total += 1.0
    end
    return total
end
ERGM.supports_missing(::ObservedEdges) = true
net = load_dataset(:florentine_marriage); set_missing_dyad!(net, 1, 9)
compute(ObservedEdges(), net)         # 19.0
supports_missing(ObservedEdges())     # true
source

Diagnostics

gof

NetworkCore.gof — Function
gof(result::ERGMResult; n_sim::Int=100,
    stats::Vector{Symbol}=[:degree, :esp, :distance],
    burnin=nothing, interval=nothing,
    rng::AbstractRNG=Random.default_rng(),
    n_chains::Int=min(n_sim, 4), esp_type::Symbol=:OTP,
    missing::Symbol=:error, proposal::Symbol=:tnt) -> GOFResult

Goodness-of-fit assessment for a fitted ERGM.

Compares observed network statistics to distributions from simulated networks. The simulations are split over n_chains independent MCMC chains run in parallel and seeded deterministically from rng, so results are reproducible and independent of the thread count (see sample_networks).

For directed networks the :degree statistic is split into separate in- and out-degree distributions, reported under the keys :idegree and :odegree (as R ergm's GOF does); :idegree/:odegree may also be requested individually. The :esp distribution for directed networks uses the esp_type shared-partner definition (default :OTP, statnet's directed default — the same types as GWESP, including :union for the either-direction count).

Arguments

  • result::ERGMResult: Fitted ERGM result
  • n_sim::Int=100: Number of networks to simulate
  • stats::Vector{Symbol}: Statistics to evaluate (:degree, :idegree, :odegree, :esp, :distance); any other symbol is an ArgumentError raised before a single network is simulated
  • burnin::Int, interval::Int: MCMC controls for the simulations. Default to the dyad-scaled rule every sampler shares (mcmc_defaults): 20 × n_dyads and max(100, n_dyads ÷ 10). With the default interval the thinning is ESS-aware: the effective sample size of the model's statistics over the simulated networks is measured, and when it is below n_sim/2 the networks are drawn again at an interval of twice the integrated autocorrelation time of the model's statistics, measured on a statistics-only pilot chain (at most 64× the default interval). An effective sample size still below n_sim/4 is warned about (also with an explicit interval). Chains shorter than ten draws are too short to measure and are left as drawn.
  • rng::AbstractRNG: Source of all random draws
  • n_chains::Int: Number of independent simulation chains
  • esp_type::Symbol=:OTP: Directed shared-partner type for :esp (ignored for undirected networks)
  • missing::Symbol=:error: Missing-dyad policy. GOF reads the observed network's degree/ESP/geodesic distributions at face value and simulates from the model, so a masked dyad would be silently reinterpreted as an observed tie on both sides of the comparison. :error (the default) refuses; :condition_on_face is the explicit, warned opt-in.
  • proposal::Symbol=:tnt: MH proposal of the simulations, :tnt (tie/no-tie, statnet's default) or :random (see mh_sample)

Returns

A NetworkCore.GOFResult with one GOFStatistic panel per requested statistic (named "degree", "idegree", "odegree", "esp", "distance"). Per-level p-values are two-sided Monte-Carlo p-values computed with the shared (1 + k)/(N + 1) estimator (NetworkCore.mc_pvalue), so they are never exactly zero. show renders the observed value, simulation envelope, and p-value per level.

Example

using ERGM, Random
net = load_dataset(:florentine_marriage)
fit = fit_ergm(net, [Edges(), NodeCov(:wealth)])
g = gof(fit; n_sim=20, stats=[:degree, :esp], rng=Xoshiro(1))
n_simulations(g)                         # 20
[s.name for s in g.statistics]           # ["degree", "esp"]
source

mcmc_diagnostics

ERGM.mcmc_diagnostics — Function
mcmc_diagnostics(result::ERGMResult) -> MCMCDiagnostics

MCMC diagnostics for MCMLE results: per statistic, the lag-1 autocorrelation, two effective sample sizes and the Geweke stationarity test, as an MCMCDiagnostics whose show prints the table R's mcmc.diagnostics prints.

Throws an ArgumentError if the fit has no MCMC samples (i.e. it was estimated by MPLE): there is no chain to diagnose. Refit with method=:mcmle to obtain a result this function accepts.

With n_chains > 1 every quantity is computed within each chain and combined — the lag-1 autocorrelation length-weighted, both effective sample sizes summed (the Geyer column is then exactly the MCMLE's own fit.mcmc_convergence.n_eff estimator), the Geweke test reported for the chain of largest |z| — never across the seams of the concatenated sample, where the first 10 % of chain 1 would otherwise be compared with the tail of the last chain.

Returns

An MCMCDiagnostics with fields term_names, autocorrelation, effective_sample_size (lag-1 estimate, Σ_c L_c(1−ρ_c)/(1+ρ_c), the most optimistic column), ess_geyer (Geyer initial-sequence ESS, all lags, summed over chains — preferred), geweke_z/geweke_p (first 10 % vs last 50 % of a chain; small p flags a chain that had not reached stationarity), n_samples and chain_lengths.

Example

using ERGM, Random
net = load_dataset(:florentine_marriage)
fit = mcmle(ERGMModel(ERGMFormula([Edges(), GWESP(0.5)]), net);
            n_samples=300, bridge_rungs=0, rng=Xoshiro(1))
d = mcmc_diagnostics(fit)
d.term_names                       # ["edges", "gwesp.fixed.0.5"]
all(d.ess_geyer .> 20)             # true on a mixing chain
all(d.geweke_p .> 0.001)           # true
println(d)                         # one row per term: AC, ESS (lag-1), ESS (Geyer), Geweke z, p
source

Renamed and removed names

0.2.0 is the first public release. Names that existed only in development versions were renamed or removed outright, without deprecation shims:

Development name0.2.0Note
using Networksusing NetworkCorethe foundation package was renamed; types and functions keep their names
mcmle(...; max_iter=)mcmle(...; maxiter=)the ecosystem's iteration-cap keyword
mcmle(...; tol=)removedit was ignored: convergence is the stopping rule termination= (R's confidence test by default)
ERGM._requires_directed, ERGM._requires_undirectedrequires_directed, requires_undirectedthe exported term traits
ERGM._vertex_attribute(t)required_vertex_attributes(t)a tuple of every attribute the term reads
ERGM._has_dyad_dependenthas_dyad_dependentexported
ERGM._z_pvaluesNetworkCore.z_pvaluesthe one z → p helper
ERGM._hummel_step, ERGM._bridge_quadrature, ERGM._bridge_logZ, ERGM._warn_degenerate_statsinternal (no longer public)use the drivers ERGM.Extension.mcmle_solve and ERGM.Extension.bridge_integrate
ERGM._separated, ERGM._warn_separatedremovedNetworkCore's logistic_separation / warn_separation, or the verdict that ERGM.Extension.mple_fit_design returns
the public underscore names of the extension surface (ERGM._mple_fit_design, ERGM._mcmle_solve, …)ERGM.Extensionno longer public; the name map gives each one's replacement

One default changed meaning rather than name: fit_ergm/ergm take method=:auto (R's rule, ERGM.resolve_method) instead of method=:mple. A dyad-independent formula is fitted exactly as before; a dyad-dependent one is now fitted by MCMLE, as R's ergm() does. Pass method=:mple for the pseudo-likelihood fit.