Estimation and Simulation

Fitting

fit_ergm_rank (= ergm_rank) takes method=:mcmle (the MCMC maximum likelihood estimate of R ergm.rank, the default) or method=:mple (the swap pseudo-likelihood). The MCMLE keywords — n_samples, burnin, interval, n_chains, init, gamma0, max_step_norm, termination, conv_precision, conv_confidence, max_n_samples, conv_threshold, hotelling_alpha, bridge_rungs, bridge_samples, verbose — are ERGM.mcmle's vocabulary, spelled the same, and maxiter caps the MCMLE iterations (default 60) or the swap-MPLE's Newton iterations (default 100). se resolves per method: :fisher under :mcmle; under :mple, not given (pseudo-Hessian standard errors, with z, p and intervals withheld), :hessian (the naive Wald table, opted into) or :bootstrap. The convergence report of an MCMLE fit is an ERGM.MCMLEConvergence in fit.mcmc_convergence. A single term or a tuple of terms is accepted in place of the vector; a Network or a rank matrix in place of the RankNetwork, and a binary ERGM.jl term in the term list, are refused with an ArgumentError naming the fix.

ERGMRank.fit_ergm_rank — Function
fit_ergm_rank(rnet::RankNetwork, terms; method=:mcmle, kwargs...) -> RankERGMResult

Fit a rank-order ERGM P(y) ∝ exp(θ'g(y)) on the complete-ordering space (the CompleteOrderReference), by one of two estimators:

  • method=:mcmle (default) — the MCMC maximum likelihood estimate, the estimator of R ergm.rank: starting from the swap-MPLE (or init), each iteration samples the model statistics along an AlterSwap Metropolis chain at the current θ and takes a Hummel-style partial Newton step toward the observed statistics; convergence is declared by R ergm 4's confidence stopping rule (the iteration is ERGM.jl's ERGM.Extension.mcmle_solve, the one ERGM.mcmle runs). Standard errors are the inverse Fisher information of the final sample plus the Monte-Carlo component; the log-likelihood is a path-sampling bridge estimate. See the "MCMC MLE" section below. On Newcomb's fraternity ranks it reproduces ergm.rank's coefficients within ergm.rank's own Monte-Carlo spread (asserted by the provenanced golden fixtures, for a two-term and a three-term model), in 10–30 s at the default budget.
  • method=:mple — swap-based maximum pseudo-likelihood, an estimator of this package that ergm.rank does not have: for each ego i and each unordered alter pair {j, k}, the conditional probability of the observed ranking y against the single alternative y_swapped (ego's ranks of j and k exchanged) — P(y | {y, y_swapped}), the two-state conditional, not "the order of j and k given the rest of the rankings": a non-adjacent swap also reorders j and k relative to the alters ranked between them — is logistic in θ'[g(y) − g(y_swapped)], and the product of these conditionals is maximized by Newton-Raphson with step-halving. Fast (milliseconds) and deterministic; a different estimator from the MLE (see the warning below). It is the MCMLE's starting point, and useful for screening models.

How far the swap-MPLE is from the MLE depends on the model. On Newcomb week 1, rank.deference + rank.nonconformity("all"): MCMLE (R) [-0.1531, -0.00659], swap-MPLE [-0.1409, -0.00585] — 16× and 13× R's own seed-to-seed spread apart, i.e. a systematic (not Monte-Carlo) difference, 0.30 and 0.43 of an MLE standard error. On week 2 with rank.deference + rank.nonconformity("localAND") + rank.inconsistency(week 1): MCMLE (R) [-0.2053, -0.0044, -0.1377], swap-MPLE [-0.1636, -0.0100, -0.1263] — 0.89, 0.83 and 0.76 of an MLE standard error, the nonconformity coefficient 2.3× the MLE's. In both, the pseudo-Hessian standard errors are 2–3.9× too small.

What is and is not claimed for the swap-MPLE

No consistency result is established here. The swap pseudo-likelihood never equals the likelihood — there is no rank analogue of dyad independence under which the product of two-state swap conditionals is the likelihood: the comparisons within one ego's row must form a total order, so they are never independent, even for a term that decomposes over egos. On the 4-actor example network with RankNodeICov([1, 2, 3, 4]), exact enumeration of all 1296 orderings gives the MLE θ = −0.0767 (log-likelihood −7.015) while the swap-MPLE is −0.0880 (pseudo-log-likelihood −8.057); method=:mcmle lands on the MLE up to Monte-Carlo error (pinned by the test suite). The estimator's large-sample behaviour in this setting has not been characterized, and MPLE for dependent ERGMs is known to be biased in finite samples.

ergm_rank is the statnet-style name (after the ergm.rank package) of the same function.

Standard errors and inference of the swap-MPLE

The inverse negative pseudo-Hessian treats the overlapping swap comparisons as independent, so the standard errors it gives are too small. Under method=:mple:

  • default (se not given) — the point estimates and the pseudo-Hessian standard errors are reported, but no inference built on them: the z values and p-values of coeftable/show are NaN (with a note saying why), confint refuses with an ArgumentError, and approximations(fit) records it (fit.inference_withheld).
  • se=:hessian passed explicitly — the written opt-in to the naive Wald table (z, p and intervals from the pseudo-Hessian), printed with the anticonservatism warning.
  • se=:bootstrap — parametric bootstrap: simulate n_boot rank networks from the fitted model at θ̂ with simulate_rank_ergm (AlterSwap Metropolis), refit the swap MPLE on each, and report the empirical covariance of the refits, with z, p and intervals. The point estimates are unchanged; only the covariance is replaced. It measures the sampling variability of the swap-MPLE — in simulation its 95 % intervals covered the true coefficients at close to the nominal rate where the Hessian ones did not (see the estimation guide) — but it does not remove the swap-MPLE's bias relative to the MLE. This is the same option, with the same keywords and the same semantics, as ERGM.mple's, and it runs on the ONE shared NetworkCore.bootstrap_cov loop. The replicates are successive draws of one chain: at the default boot_interval the thinning is ESS-aware (draws whose model statistics have an effective sample size below n_boot/2 are taken again, once, at an interval up to 8× longer; see gof). A replicate on which the swap MPLE does not exist (a statistic at the boundary of its attainable range in the simulated ranking) is excluded from the covariance: it is a NaN row of fit.boot_replicates, the exclusion is warned about once and recorded in approximations(fit), and fewer than 2 finite refits is an ArgumentError. se=:bootstrap is refused (an ArgumentError) when a coefficient of the fit itself is fixed at ±Inf, because no ranking can be simulated at an infinite coefficient.

When the pseudo-Hessian at the solution is not negative definite (a coefficient the swap comparisons do not identify) the standard errors are NaN, with a warning from newton_fit and an entry in approximations — never a finite number from an indefinite matrix.

The swap pseudo-likelihood is a logistic likelihood on the swap-difference rows with the response identically true, so it is maximized with the ecosystem's shared NetworkCore.logistic_derivatives kernel and NetworkCore.newton_fit Newton–Raphson-with-step-halving optimizer (the same bindings ERGM.jl's MPLE runs on).

Boundary statistics under method=:mple (R's drop)

A statistic whose observed value no single swap can lower (or raise) has no finite swap-MPLE: the pseudo-log-likelihood increases monotonically as its coefficient goes to -Inf (or +Inf). RankInconsistency(rnet) fitted to rnet itself is the textbook case (the observed ranking is at zero inconsistency). As R ergm does under its default drop=TRUE, such a coefficient is fixed at ∓Inf with standard error 0 (z = ∓Inf, p = 0), a warning quotes R's sentence ("observed statistic(s) … are at their smallest attainable values"), and the remaining coefficients are estimated on the swap comparisons the dropped statistics do not change — the exact limit of the pseudo-likelihood. A statistic observed at an end of its attainable range (a count observed at 0) is dropped too, even when no swap changes it. dof(fit) counts only the finite coefficients and approximations records the drop. A statistic that no swap changes, or that is a linear combination of the preceding statistics on the comparisons fitted, has no identifiable coefficient: it is reported as NaN (R's NA), with a warning, and the others are estimated without it.

Non-convergence

A swap-MPLE fit that exhausts maxiter is returned with converged == false, a warning at fit time, a caveat printed directly under Converged: false, and an entry in approximations: the coefficients are the last Newton iterate and the standard errors are unreliable.

MCMC MLE (method=:mcmle, the default)

The estimator of R ergm.rank. Each iteration draws n_samples statistics vectors along the AlterSwap Metropolis chain at the current θ (the ONE ERGM.mh_toggle! kernel, the running statistics kept current from the accepted swaps' change statistics — never a recomputation per draw), then takes the Hummel partial Newton step θ += γ · Σ̂⁻¹ (g_obs − ḡ): the step length γ starts at gamma0 and grows (at most doubling per iteration) while the observed statistics lie outside the sampled cloud (the 95 % Mahalanobis radius), reaching 1 once the cloud covers them, and each step is capped at Euclidean norm max_step_norm. Convergence is declared only at γ = 1 and by the stopping rule termination: :confidence (default) is R ergm 4's equivalence test — the estimating equations at the updated coefficients (this sample importance-reweighted to them) lie with conv_confidence confidence inside the tolerance ellipsoid x'(conv_precision·Σ̂)⁻¹x ≤ 1, and a test that fails near the solution enlarges the next sample (at most doubling, up to max_n_samples); :hotelling is the fixed-sample-size rule of ERGM.mcmc_convergence (every t-ratio |g_obs − ḡ| / sd(g) below conv_threshold and a Hotelling T² test non-significant at hotelling_alpha). The step, the stopping rule, the boost, the final sample and the covariance are ERGM.jl's ERGM.Extension.mcmle_solve — the iteration ERGM.mcmle runs — with the AlterSwap chain as the sampler.

A Monte-Carlo Newton step is taken at every iteration, the first included (statnet's order, and ERGM.mcmle's): a fit whose start already passes the tests is still refined by one step from that sample, so the swap-MPLE start is never returned as the MCMLE. The returned θ̂ is the update from the sample that passed, and that sample is the final sample: the standard errors, fit.mcmc_samples and fit.mcmc_convergence come from it. fit.termination records the rule, its p-value and the size of that sample. A fit that ends unconverged draws a fresh sample at the returned coefficients for them instead.

Non-convergence is loud: a fit that exhausts maxiter MCMLE iterations warns with the last max t-ratio, Hotelling p-value and step length, approximations(fit) lists the caveat with those numbers, and show prints it under Converged: false. Continue such a fit with init=coef(fit).

Standard errors (se=:fisher, the only option under :mcmle) are vcov = V + V·Σ_mc·V with V = Σ̂⁻¹ the inverse covariance of the final sample (the Fisher information) and Σ_mc the Geyer initial-sequence covariance of the sampled mean — the Monte-Carlo component of the estimating equation (Hunter & Handcock 2006 §3.3), exactly as ERGM.mcmle reports and as R's summary.ergm "MCMC %" column quotes. fit.vcov_fisher is V alone.

Log-likelihood. loglik = θ̂'g_obs − log Z(θ̂) with `log Z(θ̂) = log Z(0)

  • ∫₀¹ E{uθ̂}[g]'θ̂ du— path sampling alongθu = u·θ̂` from the uniform

ordering model, whose normalizer is exact, log Z(0) = n · log((n − 1)!). The integral is composite Simpson's rule over bridge_rungs segments (an odd number is raised by one), each grid point one seeded chain of bridge_samples draws (the ERGM.Extension.bridge_integrate estimator, with the uniform ranking model as the exact reference). It is run only after the final sample, so coefficients and standard errors are bit-identical with and without it; bridge_rungs=0 skips it and loglik, aic, bic are NaN, show prints "not estimated" and approximations records it.

Boundary statistics (R's drop). A statistic whose observed value is an end of its attainable range — a count (nonconformity, the unweighted inconsistency, deference) observed at 0 — has no finite MLE. R ergm's drop=TRUE would fix its coefficient at ∓Inf and estimate the rest by MCMC on the rankings that share the observed value, but the AlterSwap sampler cannot be held there: those rankings are not connected by single swaps (on 4 actors the 138 rankings with local nonconformity 0 fall into 22 swap classes), so the held chain would fit a smaller model. The MCMLE therefore refuses such a model with an ArgumentError that says so and points at method=:mple, whose pseudo-likelihood applies the drop exactly. (ergm.rank's terms declare no bound, so R does not drop here either: its sampler stops moving.) drop=false refuses the same models with the strict-mode message.

Boundary and separated starts. A statistic at the boundary of its range only under single swaps of the observed ranking (the swap-MPLE start would be ∓Inf, but the observed value is not an end of the attainable range) is a local extremum, which does not show that no MLE exists: refused with an ArgumentError unless init= is supplied, in which case a warning says so and the convergence tests decide. A separated swap-MPLE (R: "The MPLE does not exist!") and a coefficient the swap-MPLE cannot identify (NaN: no swap changes its statistic, or the statistic is a linear combination of the preceding ones) are refused the same way, pointing at init=.

Reproducibility. All randomness flows through rng; with n_chains > 1 the n_samples draws are split over chains seeded from rng in order and run on separate tasks, so a fit depends only on rng and n_chains, never on the thread count (n_chains never defaults to Threads.nthreads()).

Keyword Arguments

Common:

  • method::Symbol=:mcmle: :mcmle or :mple (anything else is an ArgumentError naming both)
  • maxiter::Int: the iteration cap — MCMLE iterations (default 60, R ergm's MCMLE.maxit) or Newton iterations of the swap-MPLE (default 100)
  • se: :fisher (default, and the only option) under :mcmle; under :mple, not given (pseudo-Hessian standard errors, inference withheld), :hessian (the naive Wald table, opted into) or :bootstrap; anything else is an ArgumentError from the shared NetworkCore.check_se naming the method's vocabulary
  • rng::AbstractRNG=Random.default_rng(): source of all randomness (the bootstrap, the MCMC chains, the bridge) — a fixed rng reproduces the fit exactly, on any thread count
  • verbose::Bool=false: print MCMLE progress
  • drop::Bool=true: R's control.ergm(drop=). Under :mple a statistic at the boundary of its attainable range is fixed at ∓Inf and the rest estimated (above); drop=false refuses the model with an ArgumentError naming the statistics, before any fitting. Under :mcmle such a model is refused either way (above); drop=false gives the strict-mode message

Swap-MPLE (method=:mple):

  • tol::Float64=1e-8 (passed to newton_fit)
  • n_boot::Int=100: number of bootstrap replicates (se=:bootstrap only; at least 2)
  • boot_burnin=nothing, boot_interval=nothing: MCMC controls for the bootstrap simulations; nothing resolves to the swap-scaled defaults of simulate_rank_ergm — burnin = 20 n_swaps, interval = max(100, n_swaps ÷ 10) with n_swaps = n (n − 1)(n − 2) / 2 (ERGM.jl's dyad-scaled rule applied to the swap count); with the default boot_interval the thinning is ESS-aware (above), an explicit integer is honoured as given

MCMC MLE (method=:mcmle; the vocabulary of ERGM.mcmle):

  • n_samples::Int=1024: MCMC draws per iteration, in total over the chains (the confidence rule may boost it, up to max_n_samples, default 16·n_samples)
  • termination::Symbol=:confidence: the stopping rule — R ergm 4's equivalence test (conv_precision=0.1, conv_confidence=0.99: the estimating equations at the updated coefficients lie, with 99 % confidence, inside the tolerance ellipsoid x'(0.1·Σ)⁻¹x ≤ 1; a failed test near the solution enlarges the next sample), or :hotelling, the t-ratio + Hotelling rule at a fixed sample size (conv_threshold, hotelling_alpha)
  • burnin=nothing, interval=nothing: steps discarded per chain and steps between draws; nothing resolves to the swap-scaled rule above
  • n_chains::Int=1: independent chains per iteration (and for the final sample), each burned in from the observed ranking, seeded from rng
  • init=nothing: starting coefficients (default: the swap-MPLE)
  • gamma0::Float64=0.1: initial Hummel step length
  • max_step_norm::Float64=5.0: cap on the norm of each Newton step
  • conv_threshold::Float64=0.1, hotelling_alpha::Float64=0.05: the :hotelling rule's tests (also what fit.mcmc_convergence reports on the final sample under either rule)
  • bridge_rungs::Int=16, bridge_samples=nothing (default n_samples): the log-likelihood bridge; bridge_rungs=0 skips it

Errors

An empty term list, a network with fewer than 3 actors (no ego has two alters to compare) and an invalid ranking are refused with an ArgumentError that says so. So are a term that is not a rank term — ERGM.jl's binary Edges(), Mutual(), … have no rank statistic; the message lists the five rank terms — and a Network or a rank matrix in place of the RankNetwork (the message says to call as_rank_network first). A single term, or a tuple of terms, is accepted in place of the vector: fit_ergm_rank(rnet, RankDeference()).

Example

using ERGMRank, Random
m = [0 3 2 1;
     3 0 1 2;
     1 3 0 2;
     2 1 3 0]
rnet = as_rank_network(m)
x = [1.0, 2.0, 3.0, 4.0]
mle = fit_ergm_rank(rnet, [RankNodeICov(x)]; n_samples=512, rng=Xoshiro(1))
mle.method                        # :mcmle — the default, R ergm.rank's estimator
mle.mcmc_convergence.step_length  # 1.0 at convergence
isfinite(loglikelihood(mle))      # true: the bridge estimate (bridge_rungs=16)
coeftable(mle)                    # the table `show(mle)` prints
approximations(mle)               # what the estimator did NOT do exactly

# The swap pseudo-likelihood: fast and deterministic, a different estimator.
# (RankDeference() + RankNonconformity() on these 4 actors is perfectly
# separated — the swap-MPLE does not exist, and the fit says so)
pl = fit_ergm_rank(rnet, [RankDeference(), RankNodeICov([10, 20, 30, 40])]; method=:mple)
pl.converged                      # true
round.(coef(pl); digits=4)        # [-0.0658, -0.0082]: two swap-MPLE coefficients
pl.inference_withheld             # true: z, p and confint are not reported by default
source
ERGMRank.ergm_rank — Function
ergm_rank(rnet::RankNetwork, terms; kwargs...) -> RankERGMResult

The statnet-style name of fit_ergm_rank (the same function, ===), after the R ergm.rank package — the ecosystem convention of one fit_<model> name and one statnet-style name per model package. Like R's ergm(..., response=, reference=~CompleteOrder), it fits the MCMC MLE by default.

Example

using ERGMRank
m = [0 3 2 1;
     3 0 1 2;
     1 3 0 2;
     2 1 3 0]
rnet = as_rank_network(m)
ergm_rank === fit_ergm_rank            # true
fit = ergm_rank(rnet, [RankNodeICov([1, 2, 3, 4])]; n_samples=256, bridge_rungs=0)
fit.method                             # :mcmle — the MCMC MLE, R ergm.rank's estimator
source

Data

ERGMRank.newcomb_week1 — Function
newcomb_week1() -> RankNetwork

Newcomb's fraternity (Newcomb 1961), week 1: 17 men who had just moved into a University of Michigan fraternity house, each ranking the other 16 by liking — the newcomb[[1]] network of R ergm.rank, read with as.matrix(newcomb[[1]], attrname = "rank"), with greater value = higher standing (ergm.rank's convention: y[i,j] > y[i,k] means i ranks j over k). It is the dataset every ergm.rank example fits, and the one the golden fixture test/fixtures/newcomb_rank.toml (generated by test/fixtures/r/newcomb_rank.R from ergm.rank 4.1.2) freezes: the matrix below is that frozen ranking, verbatim, and the test suite asserts the two are identical. Every Newcomb number quoted in the README and the estimation guide — the swap-MPLE [-0.1409, -0.00585], the MCMLE [-0.1531, -0.00659], the observed statistics (844, 12748) — is reproducible from it.

Weeks 2–15 are not bundled; NetworkCore.load_dataset does not carry Newcomb yet, so this is the one loader.

Example

using ERGMRank
rnet = newcomb_week1()
rnet.n                                            # 17
is_valid_ranking(rnet)                            # true
compute(RankDeference(), rnet) == 844             # true: ergm.rank's summary()
compute(RankNonconformity(:all), rnet) == 12748   # true
pl = fit_ergm_rank(rnet, [RankDeference(), RankNonconformity()]; method=:mple)   # swap-MPLE, ~15 ms
round.(coef(pl); digits=4) == [-0.1409, -0.0059]                    # true
# fit_ergm_rank(rnet, [RankDeference(), RankNonconformity()]) is the MCMC MLE,
# ergm.rank's estimator: ≈ [-0.153, -0.0066] in 10–30 s

Reference

Newcomb, T. M. (1961). The Acquaintance Process. New York: Holt, Rinehart & Winston. Distributed as newcomb in R ergm.rank (Krivitsky & Butts).

source

Result metadata

The shared result-metadata protocol of NetworkCore.jl (fit_metadata, approximations, estimand, objective, is_exact, se_method, missing_method) is exported by ERGMRank, so approximations(fit) works with just using ERGMRank. estimand(fit) is :rank_ergm, missing_method(fit) is :none (a RankNetwork has no dyad mask) and approximations(fit) lists, per method, what the estimator did not do exactly (the Monte-Carlo approximation of the likelihood and the bridge, or the swap pseudo-likelihood, its anticonservative pseudo-Hessian errors and the inference withheld from them), plus any non-convergence, dropped boundary statistic, undefined standard error or excluded bootstrap replicate. The three below carry rank-specific answers.

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

:likelihood for a method=:mcmle fit — the MCMC maximum likelihood estimate solves E_θ[g(Y)] = g(y_obs) on the complete-ordering space, the estimator of R ergm.rank. :pseudolikelihood for a method=:mple fit — the swap pseudo-likelihood: the product, over every (ego, unordered alter pair {j, k}), of the conditional probability of the observed ranking y against the single alternative y_swapped (ego's ranks of j and k exchanged), i.e. P(y | {y, y_swapped}), the AlterSwap move taking the role of the edge toggle in dyadwise MPLE. That product is never the likelihood — not even for a term that decomposes over egos, such as RankNodeICov (see fit_ergm_rank).

Example

using ERGMRank
m = [0 3 2 1;
     3 0 1 2;
     1 3 0 2;
     2 1 3 0]
fit = fit_ergm_rank(as_rank_network(m), [RankDeference()]; method=:mple)
objective(fit)                         # :pseudolikelihood
fit_metadata(fit).objective            # the same, through the shared protocol
source
NetworkCore.is_exact — Method
is_exact(::RankERGMResult) -> Bool

Always false, for one of two reasons. A method=:mple fit maximizes the swap pseudo-likelihood: the swap comparisons overlap — each ranking enters n − 2 of the pairwise conditionals — so their product is not the likelihood, and no consistency result is claimed for that estimator (the earlier "consistent approximation" claim has been withdrawn; see fit_ergm_rank). A method=:mcmle fit targets the likelihood, but it is a Monte-Carlo estimate of the MLE: the estimating equation is solved against a finite MCMC sample (the Monte-Carlo error is included in the standard errors) and the log-likelihood is a path-sampling bridge estimate, so the numbers change with the rng and the MCMC budget.

Example

using ERGMRank
m = [0 3 2 1;
     3 0 1 2;
     1 3 0 2;
     2 1 3 0]
fit = fit_ergm_rank(as_rank_network(m), [RankDeference()]; method=:mple)
is_exact(fit)                          # false: a swap pseudo-likelihood
approximations(fit)[1]                 # says so in words
source
NetworkCore.se_method — Method
se_method(result::RankERGMResult) -> Symbol

What the reported standard errors ACTUALLY are: :fisher (the default method=:mcmle: the inverse Fisher information from the final MCMC sample plus the Monte-Carlo component), :hessian (method=:mple: the inverse negative Hessian of the swap pseudo-likelihood) or :bootstrap (the parametric bootstrap of fit_ergm_rank(...; method=:mple, se=:bootstrap)). Read straight off the fit.

Example

using ERGMRank, Random
m = [0 3 2 1;
     3 0 1 2;
     1 3 0 2;
     2 1 3 0]
rnet = as_rank_network(m)
se_method(fit_ergm_rank(rnet, [RankDeference()]; method=:mple))      # :hessian
se_method(fit_ergm_rank(rnet, [RankDeference()]; method=:mple, se=:bootstrap,
                        n_boot=10, rng=Xoshiro(1)))                   # :bootstrap
se_method(fit_ergm_rank(rnet, [RankNodeICov([1, 2, 3, 4])]; n_samples=256,
                        bridge_rungs=0, rng=Xoshiro(1)))              # :fisher (the default MCMC MLE)
source

StatsAPI

The full ecosystem StatsAPI surface (coef, stderror, vcov, confint, loglikelihood, nobs, dof, aic, bic, coeftable) is defined on RankERGMResult and pinned by NetworkCore.check_statsapi in the test suite. coef, stderror, vcov, loglikelihood read the result's fields; nobs is the number of (ego, unordered alter pair) swap comparisons of a :mple fit and the n(n−1) ordered dyads of a :mcmle fit (R's nobs.ergm); dof counts the finite coefficients. loglikelihood is the maximized swap pseudo-log-likelihood of a :mple fit (NaN when no comparison is left after a boundary drop) and the bridge estimate of the absolute log-likelihood of a :mcmle fit (NaN under bridge_rungs=0) — R's logLik is relative to θ = 0, n·log((n−1)!) higher. coefnames returns the term names, the labels coeftable prints. The five below carry rank-specific caveats; coefnames is listed with them.

StatsAPI.nobs — Method
nobs(result::RankERGMResult) -> Int

The sample size the estimator's information criteria are computed on, which differs between the two estimators (a method of StatsAPI.nobs):

  • method=:mple — the number of swap comparisons, n(n−1)(n−2)/2 (one per ego and unordered alter pair): the observations of the swap pseudo-likelihood, each a logistic conditional. After a boundary statistic was dropped, result.n_kept (the comparisons the dropped statistics do not change) is what bic uses, as R's logLik nobs attribute does.
  • method=:mcmle — the number of ordered dyads, n(n−1): R ergm.rank's convention (nobs.ergm is network.dyadcount), so bic of an MCMLE fit is on R's scale (log(272) on Newcomb's 17 actors, not log(2040)). result.n_kept equals it.

Example

using ERGMRank, Random
m = [0 3 2 1;
     3 0 1 2;
     1 3 0 2;
     2 1 3 0]
rnet = as_rank_network(m)
nobs(fit_ergm_rank(rnet, [RankDeference()]; method=:mple)) == 12   # true: 4·3·2/2 swap comparisons
mle = fit_ergm_rank(rnet, [RankNodeICov([1, 2, 3, 4])]; method=:mcmle,
                    n_samples=64, bridge_rungs=0, rng=Xoshiro(1))
nobs(mle) == 12                                                 # true: 4·3 dyads (R's nobs)
source
StatsAPI.aic — Method
aic(result::RankERGMResult) -> Float64
bic(result::RankERGMResult) -> Float64

-2 loglikelihood + 2 dof and -2 loglikelihood + dof · log(n_kept), where dof counts the finite coefficients and n_kept is the sample size of the estimator — nobs(result): the swap comparisons of a :mple fit (or fewer after a boundary statistic was dropped, R's logLik nobs attribute) and the n(n−1) ordered dyads of a :mcmle fit (R's nobs.ergm).

For a method=:mcmle fit loglikelihood is the path-sampling (bridge) estimate of the absolute log-likelihood θ̂'g(y) − log Z(θ̂), with its own Monte-Carlo error, so these are the AIC/BIC of the MCMC MLE; they are NaN when the fit was run with bridge_rungs=0 (the estimate skipped on request, recorded in approximations).

R's `logLik` is relative to the uniform-ordering model

R ergm.rank's logLik(fit) is not the absolute log-likelihood: for a valued ERGM ergm defines the null (θ = 0) model's likelihood as 0 ("Null model likelihood calculation is not implemented for valued ERGMs"), so logLik(fit) is the bridge-sampled ratio log L(θ̂) − log L(0). ERGMRank reports the absolute value, using the exact normalizer of the uniform ordering model, log Z(0) = n·log((n−1)!). The two are related by a constant of the ranking size alone:

R's logLik = loglikelihood(fit) + n·log((n−1)!) and R's AIC/BIC are aic(fit)/bic(fit) shifted by −2n·log((n−1)!) (log(1296) ≈ 7.17 on 4 actors; 17·log(16!) ≈ 521 on Newcomb's 17, so AIC/BIC differ by ≈ 1042 there). Differences between models fitted to the same ranking — the only comparison either convention licenses — are unaffected. The golden fixture asserts the identity against ergm.rank's logLik within both bridges' Monte-Carlo error.

For a method=:mple fit they are the pseudo-AIC and pseudo-BIC of the swap pseudo-likelihood — the product of overlapping swap conditionals, not the likelihood — so they rank swap-MPLE fits against each other on the same network and nothing else, and are not comparable to the :mcmle values or to R's. When no swap comparison is left to estimate on (every one changes a statistic dropped at the boundary of its attainable range, n_kept == 0) the pseudo-log-likelihood is undefined and all three are NaN.

Example

using ERGMRank
m = [0 3 2 1;
     3 0 1 2;
     1 3 0 2;
     2 1 3 0]
fit = fit_ergm_rank(as_rank_network(m), [RankDeference()]; method=:mple)
aic(fit) == -2 * loglikelihood(fit) + 2 * dof(fit)              # true
bic(fit) == -2 * loglikelihood(fit) + dof(fit) * log(nobs(fit))  # true
ERGMRank._log_n_orderings(4) ≈ 4 * log(6)    # true: R's logLik − loglikelihood(mle) on 4 actors
source
StatsAPI.bic — Method
aic(result::RankERGMResult) -> Float64
bic(result::RankERGMResult) -> Float64

-2 loglikelihood + 2 dof and -2 loglikelihood + dof · log(n_kept), where dof counts the finite coefficients and n_kept is the sample size of the estimator — nobs(result): the swap comparisons of a :mple fit (or fewer after a boundary statistic was dropped, R's logLik nobs attribute) and the n(n−1) ordered dyads of a :mcmle fit (R's nobs.ergm).

For a method=:mcmle fit loglikelihood is the path-sampling (bridge) estimate of the absolute log-likelihood θ̂'g(y) − log Z(θ̂), with its own Monte-Carlo error, so these are the AIC/BIC of the MCMC MLE; they are NaN when the fit was run with bridge_rungs=0 (the estimate skipped on request, recorded in approximations).

R's `logLik` is relative to the uniform-ordering model

R ergm.rank's logLik(fit) is not the absolute log-likelihood: for a valued ERGM ergm defines the null (θ = 0) model's likelihood as 0 ("Null model likelihood calculation is not implemented for valued ERGMs"), so logLik(fit) is the bridge-sampled ratio log L(θ̂) − log L(0). ERGMRank reports the absolute value, using the exact normalizer of the uniform ordering model, log Z(0) = n·log((n−1)!). The two are related by a constant of the ranking size alone:

R's logLik = loglikelihood(fit) + n·log((n−1)!) and R's AIC/BIC are aic(fit)/bic(fit) shifted by −2n·log((n−1)!) (log(1296) ≈ 7.17 on 4 actors; 17·log(16!) ≈ 521 on Newcomb's 17, so AIC/BIC differ by ≈ 1042 there). Differences between models fitted to the same ranking — the only comparison either convention licenses — are unaffected. The golden fixture asserts the identity against ergm.rank's logLik within both bridges' Monte-Carlo error.

For a method=:mple fit they are the pseudo-AIC and pseudo-BIC of the swap pseudo-likelihood — the product of overlapping swap conditionals, not the likelihood — so they rank swap-MPLE fits against each other on the same network and nothing else, and are not comparable to the :mcmle values or to R's. When no swap comparison is left to estimate on (every one changes a statistic dropped at the boundary of its attainable range, n_kept == 0) the pseudo-log-likelihood is undefined and all three are NaN.

Example

using ERGMRank
m = [0 3 2 1;
     3 0 1 2;
     1 3 0 2;
     2 1 3 0]
fit = fit_ergm_rank(as_rank_network(m), [RankDeference()]; method=:mple)
aic(fit) == -2 * loglikelihood(fit) + 2 * dof(fit)              # true
bic(fit) == -2 * loglikelihood(fit) + dof(fit) * log(nobs(fit))  # true
ERGMRank._log_n_orderings(4) ≈ 4 * log(6)    # true: R's logLik − loglikelihood(mle) on 4 actors
source
StatsAPI.confint — Method
confint(result::RankERGMResult; level=0.95) -> Matrix{Float64}

Normal-theory (Wald) confidence limits θ̂ ± z_{(1+level)/2} · se, one row per coefficient with the lower limit in column 1 and the upper in column 2 (a method of StatsAPI.confint). The standard errors are the ones the fit reports — se_method(result) says whether they are the MCMC MLE's (:fisher), the parametric bootstrap of se=:bootstrap, or the inverse pseudo-Hessian of a swap-MPLE fit. For the default swap-MPLE fit (method=:mple without se=), whose pseudo-Hessian standard errors are too small, confint refuses with an ArgumentError (see fit_ergm_rank); with an explicit se=:hessian the naive, over-narrow intervals are returned.

Example

using ERGMRank, Random
m = [0 3 2 1;
     3 0 1 2;
     1 3 0 2;
     2 1 3 0]
rnet = as_rank_network(m)
fit = fit_ergm_rank(rnet, [RankNodeICov([1, 2, 3, 4])]; n_samples=256,
                    bridge_rungs=0, rng=Xoshiro(1))
ci = confint(fit)                             # 1×2
ci[1, 1] < coef(fit)[1] < ci[1, 2]            # true
size(confint(fit; level=0.9)) == (1, 2)       # true
pl = fit_ergm_rank(rnet, [RankDeference()]; method=:mple)
try
    confint(pl)
catch err
    err isa ArgumentError                     # true: withheld for a swap-MPLE fit with the default `se`
end
source
StatsAPI.coeftable — Method
coeftable(result::RankERGMResult) -> NetworkCore.CoefficientTable

The R-style coefficient table (Estimate, Std.Error, z value, Pr(>|z|)) as an inspectable NetworkCore.CoefficientTable — exactly the table show(result) prints, built from the same vectors (a method of StatsAPI.coeftable). The p-values come from NetworkCore.z_pvalues (two-sided normal, floored at floatmin(Float64) so a finite z never prints as 0.0); a coefficient fixed at ∓Inf by a boundary statistic has z = ∓Inf and p = 0, as R prints it. For a swap-MPLE fit with the default se (method=:mple without se=) the z and p columns are NaN: no test is built on its pseudo-Hessian standard errors (see fit_ergm_rank). Rows can be read by index or by term name.

Example

using ERGMRank
m = [0 3 2 1;
     3 0 1 2;
     1 3 0 2;
     2 1 3 0]
fit = fit_ergm_rank(as_rank_network(m), [RankDeference(), RankNodeICov([10, 20, 30, 40])];
                    method=:mple)
fit.converged                                       # true
tbl = coeftable(fit)
tbl["rank.deference"].estimate == coef(fit)[1]     # true
tbl[2].std_error == stderror(fit)[2]                # true
source
StatsAPI.coefnames — Method
coefnames(result::RankERGMResult) -> Vector{String}

The coefficient labels, in coef(result) order: the term names (rank.deference, rank.nonconformity.localAND, …), the labels coeftable and show print. A method of StatsAPI.coefnames (R's names(coef(fit))); ERGMRank's labels are rank.-prefixed where ergm.rank prints deference, nonconformity, … (see the README). A fresh vector on every call, so changing it leaves the fit alone.

Example

using ERGMRank
m = [0 3 2 1;
     3 0 1 2;
     1 3 0 2;
     2 1 3 0]
fit = fit_ergm_rank(as_rank_network(m),
                    [RankDeference(), RankNodeICov([10, 20, 30, 40]; label="age")];
                    method=:mple)
coefnames(fit) == ["rank.deference", "rank.nodeicov.age"]   # true
coefnames(fit) == coeftable(fit).names                      # true
source

Simulation

ERGMRank.simulate_rank_ergm — Function
simulate_rank_ergm(rnet, terms, θ; n_sim=1, burnin=nothing, interval=nothing,
                   rng=Random.default_rng()) -> Vector{RankNetwork}

Simulate rank networks from a rank-order ERGM by Metropolis sampling with the AlterSwap proposal (as in ergm.rank): pick a random ego and two random alters, propose swapping their ranks, and accept with probability min(1, exp(θ'Δg)). Every state visited is a valid complete ranking, and the chain targets P(y) ∝ exp(θ'g(y)) on the complete-ordering space (the proposal is symmetric, so the CompleteOrder reference cancels).

The loop is the ecosystem's shared Metropolis kernel ERGM.mh_toggle! (accept/reject arithmetic, burn-in, thinning), fed the AlterSwap move (ego, j, k), its change statistics and swap_ranks! as callables. Δg is the per-term swap_change — evaluated from the comparisons the swap touches, O(n) per term (O(n²) for nonconformity), never a recomputation of the full statistics — written in place into the kernel's workspace, so a step allocates nothing. A swap has no "removal" direction (Δg is already the signed difference), so the kernel never negates the log-ratio. The sampled sequence for a given rng is bit-identical to the hand-written loop this kernel replaced.

Burn-in and thinning defaults

burnin and interval default to nothing, resolved by the ecosystem's one dyad-scaled rule (ERGM.jl's, burnin = 20 n, interval = max(100, n ÷ 10)) applied to the size of the swap proposal space n_swaps = n (n − 1)(n − 2) / 2: burnin = 20 n_swaps steps and interval = max(100, n_swaps ÷ 10) steps between recorded draws. A chain that proposes one swap per step needs a number of steps proportional to the number of swaps to move every comparison a bounded number of times, so a fixed budget was wrong at both ends: for 4 actors (12 swaps) the defaults are (240, 100); for 17 (2,040 swaps) they are (40800, 204). An explicit integer is honoured as given.

All randomness flows through rng: a fixed rng reproduces the draws. θ is any real vector ([0], a range) of one coefficient per term; terms may also be a single term or a tuple. n_sim < 1, fewer than 3 actors, an invalid starting ranking, a θ whose length differs from terms, a term that is not a rank term (ERGM.jl's binary terms) and a Network/matrix in place of the RankNetwork are refused with an ArgumentError that names the fix.

Example

using ERGMRank, Random
rnet = RankNetwork(5)
draws = simulate_rank_ergm(rnet, [RankDeference()], [-0.5];
                           n_sim=20, burnin=200, interval=10, rng=Xoshiro(1))
length(draws)                     # 20
all(is_valid_ranking, draws)      # true
scaled = simulate_rank_ergm(rnet, [RankDeference()], [-0.5]; n_sim=2, rng=Xoshiro(1))
length(scaled)                    # 2, after burnin = 20 · 30 = 600 steps
source
simulate_rank_ergm(result::RankERGMResult; kwargs...) -> Vector{RankNetwork}

Simulate from a fitted rank-order ERGM (the fitted coefficients, terms and observed ranking as the starting state); keywords as above.

Errors

A fit with a non-finite coefficient — one fixed at ±Inf by a statistic at the boundary of its attainable range, or NaN (not identified, converged == false) — is refused with an ArgumentError naming the term(s): the sampler would reject every swap and return copies of the observed ranking. Remove the term (R's drop=TRUE) and refit.

source

Goodness of fit

NetworkCore.gof — Method
gof(result::RankERGMResult; n_sim=100, burnin=nothing, interval=nothing,
    rng=Random.default_rng()) -> GOFResult

Goodness-of-fit assessment of a fitted rank-order ERGM: rank networks are simulated from the fitted model with simulate_rank_ergm (AlterSwap Metropolis sampling) and features of the observed ranking are compared with their simulated distributions.

This is a method of the shared NetworkCore.gof generic; it returns the shared NetworkCore.GOFResult (observed value, simulation envelope, and two-sided Monte-Carlo p-value per statistic), with these panels:

  • "model statistics" — the model's own terms. For a method=:mcmle fit these are matched in expectation by construction (the MLE solves E[g(Y)] = g(y)), so their p-values only check that the fit converged and say nothing about how well the model describes the ranking; for a method=:mple fit they show how far the swap pseudo-likelihood estimate is from reproducing them. The fit of the model is judged on the auxiliary panels below, none of which is a model statistic:
  • "structural statistics (not in the model)" — those of rank.deference, rank.nonconformity and rank.nonconformity.localAND the model does not contain (absent when it contains all three).
  • "mean received rank (sorted)" — each actor's mean received rank, sorted ascending (labels 1…n): the popularity profile, the rank analogue of a degree distribution.
  • "dyadic rank difference" — the number of dyads {i, j} with |y_ij − y_ji| = d, d = 0, …, n − 2: reciprocity of standing.
  • "ego agreement (Kendall tau)" — the number of ego pairs by Kendall's τ between their rankings of the alters they share, in five bins (needs at least 4 actors).

Keyword Arguments

  • n_sim::Int=100: Number of simulated rank networks (at least 1)
  • burnin, interval, rng: passed to simulate_rank_ergm; nothing (the default) resolves to its swap-scaled rule — burnin = 20 n_swaps, interval = max(100, n_swaps ÷ 10) with n_swaps = n (n − 1)(n − 2) / 2 — and an explicit integer is honoured. With the default interval the thinning is ESS-aware (as in ERGM.gof): the envelopes and p-values treat the draws as independent, so when the effective sample size of the model statistics over the n_sim draws (at least 20) is below n_sim/2 the draws are taken again, once, at an interval scaled up by n_sim/ESS (at most 8×); an effective sample size still below n_sim/4 is warned about.

Errors

n_sim < 1 is refused. So is a fit with a non-finite coefficient — one fixed at ±Inf by a statistic at the boundary of its attainable range, or NaN (not identified, converged == false): the sampler would reject every swap, the "simulations" would all equal the observed ranking, and the table would show a perfect fit (every simulated statistic equal to the observed one, MC p-value 1). The ArgumentError names the term(s) and says to remove them, as R's drop=TRUE does, and refit.

Example

using ERGMRank, Random
m = [0 3 2 1;
     3 0 1 2;
     1 3 0 2;
     2 1 3 0]
fit = fit_ergm_rank(as_rank_network(m), [RankDeference()]; method=:mple)
g = gof(fit; n_sim=50, burnin=100, interval=10, rng=Xoshiro(1))
g.statistics[1].labels            # ["rank.deference"]
[s.name for s in g.statistics]    # the model statistics and four auxiliary panels
source