Shared Inference Utilities
Machinery that more than one model package needs, defined once here so that it cannot drift into several subtly different copies: the one Newton optimizer and logistic-likelihood kernel, the one bootstrap loop and se= validator, the one statistic protocol, and the golden-fixture harness that pins numerical agreement with the R reference implementations.
Shared Newton Optimizer
newton_fit is the Newton–Raphson-with-step-halving optimizer of the ecosystem and logistic_derivatives the logistic log-likelihood kernel behind every dyad-independent pseudo-likelihood (ERGM's MPLE, ERGMMulti, TERGM's CMPLE, ERGMRank's swap MPLE). They live here rather than in ERGM.jl because REM.jl and Revel.jl, which fit their models with the same optimizer, deliberately do not depend on ERGM.jl; ERGM.jl re-exports them, so using ERGM keeps working unchanged.
Both names are public but not exported from NetworkCore.jl: refer to them as NetworkCore.newton_fit / NetworkCore.logistic_derivatives, or import NetworkCore: newton_fit, logistic_derivatives (ERGM.jl's test suite calls newton_fit unqualified after using ERGM, NetworkCore, and a second export of a different binding would make that name ambiguous there until ERGM.jl aliases its copy).
Two things distinguish this optimizer from the copies it replaces:
- A step at which the objective is not finite is never taken. It is halved like a decrease; if every halving is non-finite the iteration stops at the last finite iterate with
converged == false, instead of stepping ontoNaN. - An indefinite Hessian gives
NaNstandard errors and a warning, never a finite number. Before Cholesky, information is scaled to unit diagonal; its smallest eigenvalue must exceedp * eps(Float64)times its largest. This rejects numerical non-identification without depending on individual coefficient units. Failed identification also setsconverged=false. The covariance is unscaled back to the original coefficient units.
logistic_derivatives takes binary rows (y, optionally weights= for collapsed dyad classes) or binomial rows (n_tot, n_one), through ONE kernel whose workspaces are allocated once; an evaluation allocates exactly the gradient and Hessian it returns.
using NetworkCore
# Edges-only MPLE of a 16-actor undirected network with 20 ties, in closed
# form: 120 dyads, so θ̂ = logit(20/120) and se = 1/sqrt(120 p (1 − p)).
d = NetworkCore.logistic_derivatives(ones(1, 1), [120.0], [20.0])
fit = NetworkCore.newton_fit(d, [0.0])
fit.θ[1] ≈ log(20 / 100) # true
fit.se[1] ≈ sqrt(1 / (120 * (1 / 6) * (5 / 6))) # true
fit.converged # true
# A Poisson log-mean from k = 7 events: ll(θ) = kθ − e^θ, maximum at log k
k = 7.0
pfit = NetworkCore.newton_fit(θ -> (k * θ[1] - exp(θ[1]), [k - exp(θ[1])], hcat(-exp(θ[1]))),
[0.0])
pfit.θ[1] ≈ log(k) && pfit.se[1] ≈ 1 / sqrt(k) # trueNetworkCore.newton_fit — Function
newton_fit(loglik_grad_hess, θ0::AbstractVector;
maxiter=100, tol=1e-8, max_halvings=30,
information_rtol=length(θ0)*eps(Float64)) -> NamedTupleMaximize a smooth objective (typically a log-likelihood) by Newton–Raphson with step halving.
loglik_grad_hess(θ) must return a tuple (ll, grad, hess): the objective value, its gradient vector, and its Hessian matrix at θ (the Hessian of the objective itself, i.e. negative-definite near a maximum). Each Newton step −hess \ grad is halved up to max_halvings times until the objective is finite and does not decrease (a decrease within a few ulps of |ll| counts as "does not decrease" when the gradient norm shrinks with it: rounding noise at the optimum is not a descent). Convergence is declared when the Newton decrement ½ ∇ℓᵀ(−H)⁻¹∇ℓ — the objective gain the full Newton step could still deliver, scale-free in the parameters and in the same units as tol — is below tol (the full step is then taken, as the polish that lands on the maximum), or when the objective change is below tol and the gradient norm below sqrt(tol).
This is the ONE Newton optimizer of the ecosystem, hosted in NetworkCore.jl so that packages which do not depend on ERGM.jl (REM.jl, Revel.jl) share it too; ERGM.jl re-exports it. Pair it with logistic_derivatives for any logistic (pseudo-)likelihood.
Arguments
loglik_grad_hess: Functionθ -> (ll, grad, hess)θ0::AbstractVector: Starting values (copied, not mutated). The objective must be finite there (ArgumentErrorotherwise).
Keywords
maxiter::Int=100: Maximum Newton iterationstol::Float64=1e-8: Convergence tolerance on the objective changemax_halvings::Int=30: Maximum step halvings per iteration, i.e. the smallest step tried is2^-(max_halvings-1)of the Newton step. Far from the maximum a likelihood with a rare indicator covariate proposes steps hundreds of times too long (a participation shift in a relational event model needed2^-10); the limit was 10 before 0.2.0, which stopped such fits one halving short.information_rtol::Float64=length(θ0)*eps(Float64): Relative eigenvalue threshold for the final observed-information rank check, in[0, 1). Objectives whose Hessians accumulate longer floating-point sums can supply a larger threshold reflecting their evaluation precision.
Returns
NamedTuple (θ, se, vcov, loglik, converged, iterations, stop):
vcovisinv(-hess)at the final iterate, computed through a Cholesky factorization of diagonally equilibrated-hess— the usual observed-information covariance when the objective is a log-likelihood — andse = sqrt.(diag(vcov)).- If
-hessis not positive definite at the solution (a saddle, a flat direction, a non-identified coefficient), the covariance is undefined:seandvcovare filled withNaN,convergedis false, and a warning is emitted. Numerical identification requires the smallest eigenvalue of the information scaled to unit diagonal to exceedinformation_rtoltimes its largest (by default,p * eps(Float64)). This criterion is invariant to changes of individual coefficient units; it detects singular information that roundoff can let Cholesky accept. The oldsqrt.(abs.(diag(pinv(-hess))))would have returned finite, meaningless numbers here. stopsays why the iteration ended, so a caller can name the reason instead of guessing it fromiterations::converged;:maxiter—maxiteriterations were taken;:singular_start— there is no Newton direction at the starting value: the information (-hess) is singular there, so the step cannot be formed or is useless (typically collinear statistics). Raisingmaxiterdoes not help;:singular— the same at a later iterate;:no_ascent— no step halving found a finite, non-decreasing objective;:singular_information— the iteration settled, but the information at the solution is singular, so the covariance is undefined.
converged == falsewhenmaxiteris exhausted, when the Newton step cannot be formed (singular Hessian), or when no step halving finds a finite, non-decreasing objective. Only a failed factorisation of the Hessian is treated as "no Newton direction"; any other error raised while forming the step — a gradient of the wrong length (DimensionMismatch), a Hessian that is not a matrix (MethodError), an interrupt — is a bug inloglik_grad_hessand propagates instead of being reported as non-convergence. A step at which the objective is not finite (NaN,±Inf) is never taken: it is halved like a decrease, and if every halving is non-finite the iteration stops at the last finite iterate. When the halvings only find finite decreasing objectives,θis left where it is andconvergedreports whether the gradient is already belowsqrt(tol). Before any halving, an iterate whose Newton decrement is belowtoltakes the full step — provided it is finite and loses no more thanmax(tol, 8·eps(|ll|)), which the quadratic model bounds — and is converged there: this is the polish R'sglmreports as converged at the same point, and it is what makes the verdict scale-free.
The decrement criterion is what makes the verdict independent of the scale of the design: on a pseudo-likelihood over thousands of rows with a statistic running to ~30 the gradient's own units put sqrt(tol) below the rounding floor of the objective, so Newton stalled one ulp short of the maximum with ‖∇ℓ‖ ≈ 1e-4 and reported a converged fit as unconverged — and BLAS rounding then decided which bootstrap replicates counted as converged.
Callers should surface converged == false to the user (an unconverged fit is a loud result in this ecosystem, never a silent one).
converged does not certify a finite maximiser
On (quasi-)separated logistic data, a zero-count Poisson, or any objective whose supremum is approached only as θ → ±∞ along some direction, the Newton decrement decays along that asymptote and the fit stops at a large, finite θ (typically 20–40 for a logistic model) with enormous standard errors and converged == true, exactly as R's glm does. converged says the iteration settled, not that a finite maximum exists. Whether one exists is a property of the data, decided by the separation verdict: logistic_separation, poisson_separation or clogit_separation. Every fitting function calls one of them and applies the shared policy (warn_separation).
Example
# Poisson mean via the log-likelihood of k events: ll(θ) = kθ − exp(θ)
import NetworkCore: newton_fit, logistic_derivatives # public, not exported
k = 7.0
fit = newton_fit(θ -> (k*θ[1] - exp(θ[1]), [k - exp(θ[1])], hcat(-exp(θ[1]))),
[0.0])
fit.θ[1] ≈ log(k) # true
fit.se[1] ≈ 1 / sqrt(k) # true: observed information is k at the MLE
fit.converged # true
fit.stop # :converged
# Collinear columns: the information is singular at the start, which is not
# an iteration limit
X = hcat(ones(6), [1.0, 2, 3, 1, 2, 3], [2.0, 4, 6, 2, 4, 6])
col = newton_fit(logistic_derivatives(X, Bool[1, 0, 1, 0, 1, 1]), zeros(3))
(col.converged, col.stop) # (false, :singular_start)
# Complete separation: "converged", yet the estimate sits on an asymptote;
# the separation verdict says so
x = collect(-5.0:5.0)
sep = newton_fit(logistic_derivatives(hcat(ones(11), x), x .> 0), zeros(2))
sep.converged # true
NetworkCore.logistic_separation(hcat(ones(11), x), x .> 0).separated # trueNetworkCore.logistic_derivatives — Function
logistic_derivatives(X, y::AbstractVector{Bool};
offset=nothing, weights=nothing) -> Function
logistic_derivatives(X, n_tot::AbstractVector{<:Real},
n_one::AbstractVector{<:Real}; offset=nothing) -> FunctionThe (ll, grad, hess) closure of a logistic log-likelihood on design matrix X (n × p), ready for newton_fit.
Binary rows (y, optionally with non-negative weights, e.g. the multiplicity of a collapsed dyad class):
ℓ(β) = Σ_r w_r [ y_r η_r − log(1 + e^{η_r}) ], η = Xβ + offset
∇ℓ = X' w (y − p), ∇²ℓ = −X' diag(w p(1−p)) X.Binomial rows (n_tot trials of which n_one are successes, so that a row stands for a whole class of identical dyads — the form ERGM's MPLE uses after collapsing dyads with identical change statistics):
ℓ(β) = Σ_r [ n_one,r η_r − n_tot,r log(1 + e^{η_r}) ]
∇ℓ = X'(n_one − n_tot ⊙ p), ∇²ℓ = −X' diag(n_tot ⊙ p(1−p)) X.Both forms run through ONE kernel: the binary form is the binomial one with n_tot = weights (or 1) and n_one = n_tot ⋅ y, so a weighted binary fit and the equivalent duplicated-row fit give identical ll, grad and hess to rounding. log(1 + e^η) is evaluated on its numerically stable branch on both sides of zero.
Every ERGM-family pseudo-likelihood over dyad-independent rows is this likelihood — ERGM.mple's logistic regression on the change statistics, ERGMMulti's MPLE over the within-layer dyads, TERGM's CMPLE over the free dyads of the auxiliary networks, ERGMRank's swap MPLE over the (ego, alter-pair) comparisons (with y ≡ true: the observed order is always the "success") — so it lives here, next to newton_fit, rather than pasted into four packages. offset (a fixed per-row addition to the linear predictor) is ergm's offset mechanism: ERGMMulti uses it for terms whose coefficients are held fixed.
Allocation : the workspaces are allocated ONCE, when the closure is built. Each evaluation allocates only the length-p gradient and p×p Hessian it returns — never the n×p weighted design or a per-row x * x' outer product. The "Shared Newton optimizer" testset pins this with @allocated, and the downstream packages mirror it.
Throws ArgumentError on a length mismatch, a negative or non-finite weight, or a binomial row with n_one outside [0, n_tot].
Example
# Edges-only MPLE of the Florentine marriage network in closed form: 120
# dyads, 20 ties, so θ̂ = logit(20/120) and se = 1/sqrt(120 p (1 − p)).
import NetworkCore: newton_fit, logistic_derivatives # public, not exported
d = logistic_derivatives(ones(1, 1), [120.0], [20.0])
fit = newton_fit(d, [0.0])
fit.θ[1] ≈ log(20 / 100) # true
fit.se[1] ≈ sqrt(1 / (120 * (1 / 6) * (5 / 6))) # true
# The same fit from 120 binary rows, and from one weighted row
X = ones(120, 1); y = [i <= 20 for i in 1:120]
newton_fit(logistic_derivatives(X, y), [0.0]).θ[1] ≈ log(20 / 100) # trueconverged == true does not mean that a finite maximum exists. On separated data the optimizer settles on an asymptote. Whether that happened is answered by the Separation Contract.
Threaded Loops
Threaded samplers and refits run their tasks through spawn_all, which waits for every task and rethrows the first failure as the task's own exception, never wrapped in a TaskFailedException. A caller that catches an ArgumentError therefore catches it on the threaded path as well as on the serial one. unwrap_task_exception is the unwrapping step on its own, for loops written with Threads.@threads (as bootstrap_cov is). Both are public, not exported.
NetworkCore.spawn_all — Function
spawn_all(f, n::Integer) -> nothingRun f(1), f(2), …, f(n) on separate tasks (Threads.@spawn) and wait for all of them. If any task fails, the first failure in task order is rethrown as the task's own exception (through unwrap_task_exception), never as a TaskFailedException, and only after every task has finished, so none is left running behind the error.
The failing task's backtrace is not lost: the TaskFailedException is kept on the exception stack as the cause of the rethrown error. In a catch block, current_exceptions() returns both, and the first entry's task.backtrace holds the frames inside the task; an uncaught error prints them under "caused by: TaskFailedException … nested task error".
The order in which tasks run is up to the scheduler, so f(c) must write only to its own slot of any shared output (out[c] = …). Seeding is the caller's job: draw one seed per task from the caller's rng before calling, so the result does not depend on the thread count.
Example
import NetworkCore: spawn_all
out = zeros(4)
spawn_all(c -> (out[c] = c^2), 4)
out # [1.0, 4.0, 9.0, 16.0]
try
spawn_all(c -> c == 3 ? throw(ArgumentError("task 3")) : nothing, 4)
catch e
e # ArgumentError("task 3")
cause = first(current_exceptions()).exception # the TaskFailedException
cause.task.backtrace # frames inside task 3
endNetworkCore.unwrap_task_exception — Function
unwrap_task_exception(e) -> ExceptionThe first underlying exception of a TaskFailedException / CompositeException nest (what wait, fetch, @sync and Threads.@threads raise when a task fails), or e itself when it is neither. Peels any depth of nesting, taking the first exception of a CompositeException.
Example
import NetworkCore: unwrap_task_exception
t = Threads.@spawn throw(ArgumentError("bad input"))
e = try wait(t) catch err; err end
e isa TaskFailedException # true
unwrap_task_exception(e) # ArgumentError("bad input")
unwrap_task_exception(ErrorException("x")) # returned unchangedBootstrap Covariance
bootstrap_cov is the resampling loop of the ecosystem. It backs the parametric bootstrap of every pseudo-likelihood estimator (ERGM.mple, ERGMCount.count_mple, ERGMRank.fit_ergm_rank, ERGMMulti.ergm_multi with se=:bootstrap) and, with a different simulate callback, the repeated draw of the case-control risk set in REM.fit_rem.
All randomness flows through the caller's rng and the refits are deterministic given their replicate, so a fixed rng reproduces the standard errors exactly and the threaded refits are thread-count-independent.
The se= keyword every such fitter exposes — a subset of (:hessian, :sandwich, :bootstrap) — is validated by the one helper check_se, so a wrong symbol produces the same message shape everywhere:
using NetworkCore
check_se(:hessian, (:hessian, :bootstrap); context="mple") # :hessian
try
check_se(:sandwich, (:hessian, :bootstrap); context="mple")
catch err
println(err.msg) # mple: se must be one of (:hessian, :bootstrap) (got :sandwich)
endNetworkCore.bootstrap_cov — Function
bootstrap_cov(refit, simulate, θ̂; n_boot=100, rng=Random.default_rng(),
threaded=true) -> NamedTupleResampling covariance of an estimator: draw n_boot replicate datasets, refit on each, and return the empirical covariance of the refitted coefficients.
This is the ONE shared bootstrap loop of the ecosystem. It is used for the parametric bootstrap of a pseudo-likelihood estimator (simulate from the model at θ̂, refit, empirical covariance — ERGM.mple, ERGMCount.count_mple, ERGMRank.fit_ergm_rank, ERGMMulti.ergm_multi, TERGM.stergm with se=:bootstrap) and, with a different simulate, for repeated draws of a sampling design rather than of the model: REM.control_draw_cov redraws the case-control risk set and reports the between-draw covariance of the refits as a control-draw sensitivity diagnostic, not as a standard error (REM's former se=:bootstrap, which combined it with the within-draw covariance, was withdrawn as double-counting — the sampled likelihood's own information is already consistent under nested case-control sampling).
A refit that has no finite answer on its replicate (a boundary statistic in a simulated network, a separated design) should return a NaN row: the loop keeps every replicate as returned, and the caller decides what a non-finite row means for its estimator — every ERGM-family se=:bootstrap excludes such rows from the covariance, warns once with the count in its own words, and records the exclusion in approximations(fit).
Its sibling for the point estimate is newton_fit, the shared Newton–Raphson optimizer also hosted in NetworkCore.jl (a fitter's se=:hessian is the se that newton_fit returns; se=:bootstrap replaces it with the covariance computed here). Validate the se= keyword itself with check_se.
Replicates are opaque to this function: simulate may return anything refit understands (a simulated network, an observations DataFrame, an (index, data) pair — REM uses the last so each threaded refit can stash its within-draw covariance).
The point estimate is not touched. Only the covariance is replaced: callers keep θ̂ and swap in the returned vcov/se. The bootstrap centres on the replicate mean, not on θ̂, so it estimates the sampling variability of the estimator, not its bias.
Arguments
refit:replicate -> AbstractVector{<:Real}— refits the estimator on one replicate dataset and returns its coefficient vector (lengthlength(θ̂)). Must be pure and thread-safe: it is called from a threaded loop.simulate:(rng, n_boot) -> AbstractVector— draws alln_bootreplicate datasets in ONE call, so that a package with its own chain-splitting or seeding discipline (e.g.ERGM.sample_networks) keeps it. All randomness must flow through therngit is handed, so a fixedrngreproduces the standard errors exactly.θ̂::AbstractVector: the point estimate — used for its length and returned unchanged by the caller; the covariance does not depend on it.
Keyword Arguments
n_boot::Int=100: number of replicates (at least 2; a covariance needs two)rng::AbstractRNG=Random.default_rng(): source of the replicate randomnessthreaded::Bool=true: refit the replicates on all available threads. The refits are deterministic given their replicate, so this is thread-count-independent (all the randomness lives insimulate).
Returns
NamedTuple (vcov, se, replicates):
vcov::Matrix{Float64}—n × nempirical covariance of the refitsse::Vector{Float64}— its square-rooted diagonal (negative-zero-guarded)replicates::Matrix{Float64}— then_boot × pmatrix of refitted coefficients, so callers can report percentile intervals or diagnose a refit that failed to converge
An exception thrown by refit propagates as itself in both modes: the threaded loop unwraps the CompositeException/TaskFailedException the task machinery adds and rethrows the first underlying exception.
Example
# Bootstrap of a sample mean: the "model" is the fitted normal, the "refit" is
# the mean of a replicate.
using Random, Statistics
θ̂ = [3.0]
boot = bootstrap_cov(x -> [mean(x)],
(rng, B) -> [randn(rng, 50) .+ 3.0 for _ in 1:B],
θ̂; n_boot=200, rng=MersenneTwister(1))
boot.se[1] # ≈ 1/sqrt(50)NetworkCore.check_se — Function
check_se(se::Symbol, allowed; context::AbstractString) -> SymbolValidate the se= keyword of a fitter: return se unchanged when it is one of allowed (a tuple or vector of Symbols), otherwise throw an ArgumentError whose message names context (the fitter), the allowed vocabulary and the offending symbol:
<context>: se must be one of (:hessian, :bootstrap) (got :sandwich)This is the ONE se= validator of the ecosystem: ERGM.mple, ERGMCount.count_mple, ERGMRank.fit_ergm_rank, ERGMMulti.ergm_multi, TERGM.stergm and REM.fit_rem (both its EventSequence and DataFrame methods take (:hessian, :sandwich); REM refuses :bootstrap first, with a pointer to control_draw_cov) each accept a different subset of (:hessian, :sandwich, :bootstrap), and each used to carry its own copy of the se in (...) || throw(...) line with its own wording. One helper, one message shape, one place to extend the vocabulary.
Example
check_se(:hessian, (:hessian, :bootstrap); context="mple") # :hessian
try check_se(:sandwich, (:hessian, :bootstrap); context="mple") catch err; err end
# ArgumentError("mple: se must be one of (:hessian, :bootstrap) (got :sandwich)")The StatsAPI Surface
Every fitted-model type in the ecosystem is expected to implement the StatsAPI verbs wherever the quantity exists — coef, stderror, vcov, confint, loglikelihood, nobs, dof, aic, bic, coeftable, coefnames — on its own type, with coeftable returning a CoefficientTable whose names are coefnames(fit). NetworkCore.jl defines no method on any of them; it re-exports coeftable and coefnames (one binding each for the whole ecosystem) and provides check_statsapi, which turns the claim into a testset line. It reports, verb by verb, whether hasmethod finds an implementation, checks that the ones found agree with each other (coef, stderror, vcov, coeftable and coefnames have matching sizes, and coefnames equals the table's names; a method that throws on its own fit counts as absent), and with strict=true throws an error that names exactly what is missing. coefnames is checked whenever a fit defines it, but is not yet required by default; list it in required= to require it:
using NetworkCore
using LinearAlgebra: diag
import StatsAPI
struct TinyFit
θ::Vector{Float64}
V::Matrix{Float64}
end
StatsAPI.coef(f::TinyFit) = f.θ
StatsAPI.vcov(f::TinyFit) = f.V
StatsAPI.stderror(f::TinyFit) = sqrt.(diag(f.V))
StatsAPI.coeftable(f::TinyFit) =
CoefficientTable(StatsAPI.coefnames(f), StatsAPI.coef(f), StatsAPI.stderror(f))
StatsAPI.coefnames(::TinyFit) = ["a", "b"]
fit = TinyFit([1.0, -0.5], [0.04 0.0; 0.0 0.09])
check_statsapi(fit; required=(:coef, :stderror, :vcov, :coeftable, :coefnames))
# (coef = true, stderror = true, vcov = true, coeftable = true, coefnames = true)
r = check_statsapi(fit) # the ten verbs required by default
r.coef, r.aic # (true, false): no StatsAPI.aic(::TinyFit)
try
check_statsapi(fit; strict=true)
catch err
println(err.msg) # "... missing or inconsistent: confint, loglikelihood, nobs, dof, aic, bic. ..."
endA package's testset pins its surface with @test check_statsapi(fit; strict=true) !== nothing (or a required= subset naming the verbs the model legitimately has — a model without a likelihood has no aic).
NetworkCore.check_statsapi — Function
check_statsapi(fit; required=(:coef, :stderror, :vcov, :confint,
:loglikelihood, :nobs, :dof, :aic, :bic,
:coeftable),
strict::Bool=false) -> NamedTupleReport which verbs of the ecosystem's StatsAPI surface a fitted-model object implements: for each name in required, whether hasmethod(StatsAPI.<verb>, Tuple{typeof(fit)}) holds. When the methods exist their results are also checked for consistency — length(coef(fit)) == length(stderror(fit)) == size(vcov(fit), 1) == size(vcov(fit), 2), coeftable(fit) must be a CoefficientTable with one row per coefficient, and coefnames(fit) must be a vector of strings, one per coefficient, equal to coeftable(fit).names — and a verb whose method exists but throws or disagrees is reported false too.
The surface has an eleventh verb, coefnames, which is not in the default required list yet: list it (required=(..., :coefnames)) to require it. A fit that defines coefnames has it checked for consistency even when it is not listed, and with strict=true an inconsistent coefnames throws.
Returns a NamedTuple keyed by required with Bool values, so a package's testset can read @test all(check_statsapi(fit)) or inspect the gaps. With strict=true an incomplete surface throws an ArgumentError naming every missing or inconsistent verb, so the idiom @test check_statsapi(fit; strict=true) !== nothing pins the full surface in one line and the failure message says exactly what is absent.
required may be any subset of the eleven verbs (a model with no likelihood legitimately omits loglikelihood/aic/bic; pass the verbs it should have). A name that is not a StatsAPI function is an ArgumentError.
Example
using NetworkCore
using LinearAlgebra: diag
import StatsAPI
struct TinyFit
θ::Vector{Float64}
V::Matrix{Float64}
end
StatsAPI.coef(f::TinyFit) = f.θ
StatsAPI.vcov(f::TinyFit) = f.V
StatsAPI.stderror(f::TinyFit) = sqrt.(diag(f.V))
StatsAPI.coeftable(f::TinyFit) =
CoefficientTable(StatsAPI.coefnames(f), StatsAPI.coef(f), StatsAPI.stderror(f))
StatsAPI.coefnames(::TinyFit) = ["a", "b"]
fit = TinyFit([1.0, -0.5], [0.04 0.0; 0.0 0.09])
check_statsapi(fit; required=(:coef, :stderror, :vcov, :coeftable, :coefnames))
# (coef = true, stderror = true, vcov = true, coeftable = true, coefnames = true)
check_statsapi(fit).aic # false — no method StatsAPI.aic(::TinyFit)See also CoefficientTable, coeftable, coefnames.
Statistic Protocol
Three empty generics — compute, name and compute_all. NetworkCore.jl defines no methods and knows nothing about what a statistic is; every model package extends these with methods for its own statistic types (compute(term, net) in ERGM.jl, compute(term, net, prev_net) in TERGM.jl, compute(stat, state, sender, receiver) in REM.jl). The signatures differ, so the methods coexist on one function.
This exists because ERGM.jl and REM.jl each used to define and export their own compute and name — two different functions with one name — so using ERGM, REM left the unqualified verbs undefined, which is Julia's rule for conflicting exports. One generic cannot collide with itself.
The rule: a verb that more than one package needs is defined once, here, and imported by name (import NetworkCore: compute, name) wherever methods are added — never redefined locally.
NetworkCore.compute — Function
compute(stat, args...) -> Float64Evaluate a network statistic. The ecosystem-wide generic for the "value of this statistic" verb; every model package adds methods for its own statistic types:
| package | signature |
|---|---|
| ERGM.jl | compute(term::AbstractERGMTerm, net) |
| TERGM.jl | compute(term::TemporalTerm, net, prev_net) |
| REM.jl | compute(stat::AbstractStatistic, state, sender, receiver) |
The methods have different signatures, so they coexist on one generic without ambiguity — which is the point: using ERGM, REM leaves compute usable unqualified, instead of undefined by Julia's conflicting-export rule.
Extend it for your own statistic with import NetworkCore: compute.
Example
import NetworkCore: compute, name
struct EdgeCount end
compute(::EdgeCount, net::Network) = Float64(ne(net))
name(::EdgeCount) = "edges"
net = network(3); add_edges!(net, [(1, 2), (2, 3)])
compute(EdgeCount(), net) # 2.0See also name, compute_all.
NetworkCore.name — Function
name(stat) -> StringThe display label of a network statistic — the string that identifies it in a coefficient table. The ecosystem-wide generic; every model package adds methods for its own statistic types (see compute).
Extend it for your own statistic with import NetworkCore: name.
Example
import NetworkCore: name
struct EdgeCount end
name(::EdgeCount) = "edges"
name(EdgeCount()) # "edges"NetworkCore.compute_all — Function
compute_all(set, args...) -> Vector{Float64}Evaluate every statistic in a set, returning the vector of values in set order. The ecosystem-wide generic; model packages add methods for their own set types (ERGM.jl's TermSet, REM.jl's StatisticSet, ...).
Example
import NetworkCore: compute, compute_all
struct EdgeCount end
struct VertexCount end
compute(::EdgeCount, net::Network) = Float64(ne(net))
compute(::VertexCount, net::Network) = Float64(nv(net))
compute_all(stats::Vector, net::Network) = [compute(s, net) for s in stats]
net = network(3); add_edge!(net, 1, 2)
compute_all(Any[EdgeCount(), VertexCount()], net) # [1.0, 3.0]See also compute.
Golden Fixtures
The harness behind the ecosystem's numerical-agreement tests: a fixture is a stored set of reference values (typically produced by the corresponding R statnet/RSiena routine) plus a per-key tolerance, and a test checks a computed value against it.
A fixture only loads when it can be audited and regenerated: the [provenance] block must name r_version, seed and script, and the script must exist on disk. load_golden resolves provenance.script by walking up the ancestors of the fixture's directory (or of root=, when given) until joinpath(dir, script) is a file — so the conventional script = "test/fixtures/r/<name>.R", relative to the package root, resolves from any working directory, and an ad-hoc fixture may keep r/<name>.R beside itself. The resolved absolute path is the fixture's script_path field, printed by show and by golden_report, so a maintainer facing a red test sees not only which R and seed produced the reference but which script to re-run. A fixture whose script cannot be found throws an ArgumentError naming the fixture, the script string and every directory searched.
using NetworkCore
g = load_golden(joinpath(pkgdir(NetworkCore), "test", "fixtures", "florentine_sna.toml"))
g.provenance["sna_version"] # "2.8"
endswith(g.script_path, "harness_selftest.R") # true, an absolute path
check_golden(g, "density", 1 / 6) # trueNetworkCore.GoldenFixture — Type
GoldenFixtureFrozen output from a reference implementation (R statnet / RSiena / relevent), with the provenance needed to regenerate and audit it.
Fields
name— the fixture's identifiervalues::Dict{String,Any}— the frozen numbers (coefficients, SEs, targets…)tolerance::Dict{String,Any}— the agreed tolerances, per value or globalprovenance::Dict{String,Any}— R version, package versions, seed, script, datescript_path::String— the absolute path of the generating script named byprovenance["script"], resolved on disk byload_golden(a fixture whose script cannot be found does not load)
Load with load_golden; compare with check_golden. The struct has no external constructor: a GoldenFixture only ever comes from a provenanced file on disk.
Example
g = load_golden(joinpath(pkgdir(NetworkCore), "test", "fixtures", "network_density.toml"))
g isa GoldenFixture # true
g.provenance["network_version"] # the R `network` version the values came from
isfile(g.script_path) # true — the generating R script, resolved on diskNetworkCore.load_golden — Function
load_golden(path::AbstractString; root=nothing) -> GoldenFixtureLoad a golden fixture from a TOML file and refuse to load one that cannot be audited. A fixture missing its [provenance] block — the R version, the package versions, the seed, and the generating script — throws, because an unprovenanced golden value is not a check on anything: it cannot be regenerated when the reference implementation changes, and a future maintainer cannot tell whether a mismatch means their code broke or R moved.
The named provenance.script must also exist. It is resolved by walking up the ancestors of the fixture's directory — the directory itself, its parent, and so on to the filesystem root — until joinpath(dir, script) is a file, so the conventional script = "test/fixtures/r/<name>.R" (relative to the package root) resolves from any working directory, and an ad-hoc fixture can keep its script beside it as r/<name>.R. Pass root= to start the walk from a different directory (a fixture copied out of its package, say). An absolute script is used as given. Relative paths are normalized to the platform's path separators. The resolved absolute path is stored in the returned fixture's script_path field and printed by show and golden_report. A fixture whose script cannot be found throws an ArgumentError naming the fixture, the script string and every directory searched, for the same reason an unprovenanced one does.
Example
using NetworkCore
g = load_golden(joinpath(pkgdir(NetworkCore), "test", "fixtures", "florentine_sna.toml"))
g.provenance["sna_version"] # "2.8"
g.values["density"] # the frozen sna::gden value
isfile(g.script_path) # true — test/fixtures/r/harness_selftest.RNetworkCore.check_golden — Function
check_golden(g::GoldenFixture, key::AbstractString, actual) -> BoolWhether actual agrees with the frozen value g.values[key] within the tolerance the fixture declares for it (see golden_tolerance). Element-wise for vectors; lengths must match.
Returns a Bool so it drops straight into @test. Use golden_report to see why a comparison failed.
Example
g = load_golden(joinpath(pkgdir(NetworkCore), "test", "fixtures", "network_density.toml"))
check_golden(g, "directed_noloops", 0.25) # true
check_golden(g, "directed_noloops", 0.25 + 1e-6) # false — outside the declared toleranceNetworkCore.golden_report — Function
golden_report(g::GoldenFixture, key::AbstractString, actual) -> StringA human-readable comparison of actual against the frozen value: the reference, the observed value, the discrepancy, and the tolerance — plus the provenance, so a maintainer facing a red test knows which R version and seed produced the number they are being measured against.
Example
g = load_golden(joinpath(pkgdir(NetworkCore), "test", "fixtures", "network_density.toml"))
println(golden_report(g, "directed_noloops", 0.3))
# golden fixture network_density [directed_noloops] (atol = 1.0e-12)
# reference (R): 0.25
# observed (jl): 0.3
# |difference| : 0.04999999999999999
# provenance : date=2026-09-09, ..., r_version=4.6.1, ...
# script : /.../test/fixtures/r/network_density.RNetworkCore.golden_tolerance — Function
golden_tolerance(g::GoldenFixture, key::AbstractString) -> Float64The tolerance agreed for key, falling back to the fixture's default and then to 0.0. Comparing a Monte-Carlo estimator to a reference at machine precision is meaningless, so the tolerance is stated in the fixture rather than invented at the call site — which makes it auditable.
Example
g = load_golden(joinpath(pkgdir(NetworkCore), "test", "fixtures", "network_density.toml"))
golden_tolerance(g, "directed_noloops") # 1.0e-12 — the fixture's `default`