Types API Reference
This page documents the core data types in ERGM.jl.
Abstract Term Types
AbstractERGMTerm
ERGM.AbstractERGMTerm — Type
AbstractERGMTermAbstract base type for all ERGM terms.
All terms must implement:
compute(term, net) -> Float64: Compute the term statistic for the networkchange_stat(term, net, i, j) -> Float64: The add-direction change statisticg(y⁺ᵢⱼ) − g(y⁻ᵢⱼ), independent of the dyad's current statename(term) -> String: Return the term name
and may declare the term-trait protocol (required_vertex_attributes, requires_directed, is_dyad_dependent, ...; see src/terms/traits.jl).
Example
using ERGM
struct NonEdges <: AbstractERGMTerm end # a third-party term
ERGM.name(::NonEdges) = "nonedges"
ERGM.compute(::NonEdges, net) = nv(net) * (nv(net) - 1) / 2 - ne(net)
ERGM.change_stat(::NonEdges, net, i, j) = -1.0 # i, j need no annotation
ERGM.is_dyad_dependent(::NonEdges) = false
net = load_dataset(:florentine_marriage)
compute(NonEdges(), net) # 100.0
NonEdges() isa AbstractERGMTerm # trueStructuralTerm
ERGM.StructuralTerm — Type
StructuralTerm <: AbstractERGMTermTerms based purely on network structure (edges, triangles, etc.).
NodalTerm
ERGM.NodalTerm — Type
NodalTerm <: AbstractERGMTermTerms based on vertex attributes (nodefactor, nodecov, etc.).
DyadicTerm
ERGM.DyadicTerm — Type
DyadicTerm <: AbstractERGMTermTerms based on dyad-level attributes or combinations of vertex attributes.
ConstraintTerm
ERGM.ConstraintTerm — Type
ConstraintTerm <: AbstractERGMTermTerms that represent constraints rather than model terms.
Term Collections
TermSet
ERGM.TermSet — Type
TermSetA collection of ERGM terms.
Terms are stored as a tuple so that compute_all/change_stat_all compile to statically dispatched calls per term instead of dynamic dispatch through an abstractly-typed vector (which would dominate the MCMC inner loop). TermSet(::AbstractVector) accepts a vector of terms (nested vectors are spliced, as fit_ergm does).
Example
using ERGM
ts = TermSet([Edges(), Triangle()])
length(ts) # 2
ts.names # ["edges", "triangle"]
compute_all(ts, load_dataset(:florentine_marriage)) # [20.0, 3.0]Model Specification
ERGMFormula
ERGM.ERGMFormula — Type
ERGMFormula(terms; constraints=ConstraintTerm[])Represents an ERGM model specification: the right-hand side of R ergm's net ~ edges + triangle + nodematch("attr").
terms is a TermSet or any vector of terms (the shapes fit_ergm accepts, including [Edges(), Degree(0:2)]).
Constraints are not implemented. ERGM.jl fits unconstrained models only: passing a non-empty constraints= vector (here, or to fit_ergm) throws an ArgumentError rather than storing constraints that no sampler or estimator would honour (statnet's constraints= — edges, degrees, blockdiag, observed, … — has no counterpart yet). The abstract type ERGM.ConstraintTerm is a reserved, unexported placeholder.
Fields
terms::TermSet: Model termsconstraints::Vector{ConstraintTerm}: always empty (see above)
Example
using ERGM
formula = ERGMFormula([Edges(), Triangle()])
length(formula.terms) # 2ERGMModel
ERGM.ERGMModel — Type
ERGMModel{T,D}
ERGMModel(formula::ERGMFormula, net::Network{T,D}; reference=:bernoulli)An ERGM model specification with observed network. T is the network's vertex-index type and D its directedness (Graphs.is_directed(model) == D, known at the type level, so every hot loop reading model.network is statically typed).
Construction validates the formula against the network — every attribute-based term's vertex attribute must exist on the network, and intrinsically directed terms (e.g. Mutual) are rejected on undirected networks — throwing an ArgumentError otherwise. Attribute-based nodal terms are then materialized: their attribute values are snapshotted into dense typed vectors (see src/terms/materialize.jl) so that change statistics in the estimation and sampling hot loops avoid the untyped attribute storage. Materialized terms keep the original term names and semantics.
One-mode networks only. A two-mode (bipartite-flagged) network — created with network(n; bipartite=k), or a BipartiteNetwork — is refused with an ArgumentError: the bipartite ERGM terms of statnet (b1degree, b2degree, b1factor, b1nodematch, …) and the two-mode proposal kernel are not implemented, and fitting the one-mode terms would silently count the structurally impossible within-mode dyads as observations. See the README's "Not implemented" section.
No self-loops. A network that contains a self-loop (has_edge(net, v, v); only possible with network(n; loops=true)) is refused with an ArgumentError too: the term statistics would count the loop, but the pseudo-likelihood, nobs, the MH proposal and every simulation range over the n(n−1) (or n(n−1)/2) off-diagonal dyads only, so a loop would inflate the observed statistics against a model that can never reproduce it (R ergm warns "This network contains loops" and fits regardless). A loops=true network with no loop present is accepted and modelled as the loop-free network it is — the diagonal is structurally absent.
show(model) prints the network's size and directedness and the formula (`ERGMModel{Int64,false}: 16 vertices, 20 edges (undirected); terms: edges
- nodecov.wealth`), never the materialized attribute vectors.
Fields
formula::ERGMFormula: Model formula (with materialized terms)network::Network{T,D}: Observed networkreference::Symbol: Reference measure (:bernoulli by default)
Example
using ERGM
net = load_dataset(:florentine_marriage)
model = ERGMModel(ERGMFormula([Edges(), Triangle()]), net)
is_directed(model) # false
model.formula.terms.names # ["edges", "triangle"]Results
ERGMResult
ERGM.ERGMResult — Type
ERGMResult{T,D}Results from fitting an ERGM. The type parameters are those of the fitted ERGMModel (vertex-index type and directedness).
Fields
model::ERGMModel{T,D}: The fitted modelcoefficients::Vector{Float64}: Estimated coefficientsstd_errors::Vector{Float64}: Standard errorsz_values::Vector{Float64}: Z-statisticsp_values::Vector{Float64}: Two-sided p-valuesvcov::Matrix{Float64}: Estimated covariance matrix of the coefficientsloglik::Float64: Log-likelihood (or pseudo-log-likelihood)aic::Float64: AICbic::Float64: BICmethod::Symbol: Estimation method (:mple or :mcmle)converged::Bool: Convergence statusmcmc_samples::Union{Nothing, Matrix{Float64}}: Statistics sampled at the final coefficient values (for MCMLE)se_type::Symbol: How the standard errors were obtained (:hessianfor inverse observed information,:bootstrapfor parametric bootstrap,:mcmcfor the inverse Fisher information estimated from MCMC samples)missing_method::Symbol: How masked (unobserved) dyads were treated —:noneif the network had none,:available_caseif they were dropped from the pseudo-likelihood (MPLE),:mleif they were integrated out of the likelihood by the constrained chain of the missing-data MCMLE (missing=:mle),:condition_on_faceif they were held fixed at their stored face value throughout MCMC (missing=:condition_on_face). Seesrc/missing.jl.vcov_fisher::Matrix{Float64}: For an MCMLE fit, the inverse Fisher informationΣ̂⁻¹from the final MCMC sample alone —vcovis this plus the Monte-Carlo componentV·Σ_mc·V(seemcmle). For an MPLE fit it isvcovitself.mcmc_se::Vector{Float64}: The Monte-Carlo standard error of each coefficient,sqrt(diag(V·Σ_mc·V))— the part ofstd_errorsthat comes from the finite MCMC sample rather than from the data (R's "MCMC %"). Zeros for an MPLE fit. Accessor:mcmc_se.mcmc_convergence::Union{Nothing, MCMLEConvergence}: For an MCMLE fit, the classical diagnostics of the final MCMC sample — a NamedTuple(iterations, step_length, t_ratios, hotelling_p, n_eff): per-statistic t-ratios|g_obs − ḡ|/sd(g)and the Hotelling T² p-value of that sample (drawn at the last iterate; the returned estimate is one Newton step from it when the fit converged, as in statnet), and its effective sample size.convergedis the verdict of the stopping rule recorded intermination, and the warning,showandapproximationsof an unconverged fit quote that rule only (seeMCMLEConvergence).nothingfor an MPLE fit.chain_lengths::Vector{Int}: For an MCMLE fit, the number of rows ofmcmc_sampleseach of then_chainsindependent chains contributed, in order (the sample is their concatenation), somcmc_diagnosticscan work chain by chain instead of across the seams. Empty for MPLE.boot_replicates::Union{Nothing, Matrix{Float64}}: Forse=:bootstrap, then_boot × pmatrix of refitted coefficients the covariance was taken over; a replicate on which the MPLE did not exist (a boundary statistic or a separated design in the simulated network) is a row ofNaNs and was excluded.nothingotherwise.separated_terms::Vector{String}: For an MPLE fit whose pseudo-likelihood has no finite maximum (separation, decided by the sharedNetworkCore.logistic_separationverdict — an exact linear programme, like R ergm'smple.existence), the coefficients that carry the separating direction; the fit then hasconverged == falseand no z values, p-values or intervals. Empty otherwise.termination::Union{Nothing, NamedTuple}: For an MCMLE fit, the verdict of the stopping rule behindconverged— a NamedTuple(rule, p_value, precision, confidence, n_samples):ruleis:confidence(R ergm's default equivalence test;p_valueis its Hotelling-T² p-value, which must fall below1 − confidence) or:hotelling(the pre-0.2 rule;p_valueis the Hotelling p), andn_samplesthe size of the final (possibly boosted) MCMC sample.nothingfor an MPLE fit.
The full ecosystem StatsAPI surface is available on a result: coef, stderror, vcov, confint, loglikelihood, nobs, dof, aic, bic and coeftable (a NetworkCore.CoefficientTable), plus the result-metadata protocol (NetworkCore.fit_metadata).
Example
using ERGM
net = load_dataset(:florentine_marriage)
fit = fit_ergm(net, [Edges(), NodeCov(:wealth)])
coef(fit) # 2-vector
confint(fit) # 2×2 matrix of normal-theory 95% limits
coeftable(fit) # the R-style table `show(fit)` printsMCMLEConvergence
ERGM.MCMLEConvergence — Type
MCMLEConvergenceThe convergence report an MCMLE fit carries in fit.mcmc_convergence (nothing for MPLE): a NamedTuple with
iterations::Int: MCMLE iterations run (≤maxiter);step_length::Float64: the last Hummel step length γ (1.0 at convergence);t_ratios::Vector{Float64}: per-statistic t-ratios|g_obs − ḡ| / sd(g)of the final MCMC sample;hotelling_p::Float64: p-value of the Hotelling T² test on that sample;n_eff::Float64: the effective sample size behind it (Geyer, summed over chains).
Which sample. For a converged fit the final sample is the one drawn at the LAST ITERATE, before the final Newton step: the returned coefficients are that iterate plus one step, as in statnet, so these numbers describe the pre-step sample, not the returned coefficients, and a converged fit can carry t-ratios of 0.1–0.2. For an unconverged fit they come from a fresh sample drawn at the returned coefficients. They are classical diagnostics, not the verdict: fit.converged is the stopping rule recorded in fit.termination (R ergm's confidence test by default), and show and approximations report only that rule.
See mcmc_convergence, which computes the last three.
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))
fit.mcmc_convergence isa ERGM.MCMLEConvergence # true
fit.mcmc_convergence.step_length # 1.0 at convergenceMCMCDiagnostics
ERGM.MCMCDiagnostics — Type
MCMCDiagnosticsWhat mcmc_diagnostics returns: one row of chain diagnostics per model statistic, computed chain by chain when the fit ran n_chains > 1 (the sample is the chains' concatenation; chain_lengths says where the seams are) and printed as a table by show. Fields:
term_names::Vector{String}: statistic namesautocorrelation::Vector{Float64}: lag-1 autocorrelation (within chains, length-weighted over chains)effective_sample_size::Vector{Float64}: ESS from the lag-1 autocorrelation,Σ_c L_c (1−ρ_c)/(1+ρ_c)— the most optimistic columness_geyer::Vector{Float64}: Geyer initial-sequence ESS summed over chains — all lags, the preferred column, and the same estimator the MCMLE's own convergence test uses (fit.mcmc_convergence.n_eff)geweke_z::Vector{Float64},geweke_p::Vector{Float64}: Geweke stationarity z-scores (first 10 % vs last 50 % of a chain) — with several chains the z of largest magnitude, and its two-sided p-value (the smallest); a small p flags a chain that had not reached stationarityn_samples::Int,chain_lengths::Vector{Int}: total draws and the per-chain counts
Example
using ERGM, Random
net = load_dataset(:florentine_marriage)
fit = mcmle(ERGMModel(ERGMFormula([Edges(), GWESP(0.5)]), net);
n_samples=400, n_chains=2, bridge_rungs=0, rng=Xoshiro(1))
d = mcmc_diagnostics(fit)
d isa MCMCDiagnostics # true
length(d.chain_lengths) # 2 — one count per chain
sum(d.chain_lengths) == d.n_samples # true (the ESS-adaptive sampler sets the counts)
println(d) # the per-term tableInterface Functions
compute
NetworkCore.compute — Function
compute(term::AbstractERGMTerm, net) -> Float64Compute the term statistic g(y) for the given network — the statnet summary(net ~ term) value. compute is the shared NetworkCore.jl statistic generic (NetworkCore.compute); ERGM adds one method per term type.
A masked (missing) dyad is read at its stored face value: the term layer knows nothing about the mask (see supports_missing(::AbstractERGMTerm)), the estimators do.
Example
using ERGM
net = load_dataset(:florentine_marriage)
compute(Edges(), net) # 20.0
compute(Triangle(), net) # 3.0
compute(NodeCov(:wealth), net) # 2168.0change_stat
ERGM.change_stat — Function
change_stat(term::AbstractERGMTerm, net, i, j) -> Float64Compute the add-direction change statistic for dyad (i,j): g(y⁺ᵢⱼ) − g(y⁻ᵢⱼ), i.e. the statistic with edge (i,j) present minus the statistic with it absent, holding all other dyads at their current values.
The result must not depend on whether edge (i,j) currently exists — this is the convention required by both the MPLE design matrix and the Metropolis–Hastings sampler (which negates it for removal proposals).
Example
using ERGM
net = load_dataset(:florentine_marriage)
change_stat(Edges(), net, 1, 2) # 1.0 — always, present or absent
change_stat(Triangle(), net, 2, 9) # 0.0 — 2 and 9 share no neighbour
change_stat(Triangle(), net, 6, 7) # 1.0 — 2 is tied to both 6 and 7
has_edge(net, 2, 9) # true; the values above do not depend on itA term's own method may annotate the dyad (i::Int, j::Int) or not (change_stat(t::MyTerm, net, i, j)): the fallback below is typed on the abstract term only, so any method for a concrete term type is strictly more specific and never ambiguous with it.
name
NetworkCore.name — Function
name(term::AbstractERGMTerm) -> StringThe R ergm-style coefficient name of the term ("edges", "nodematch.sex", "gwesp.fixed.0.5", ...), as printed in the coefficient table. name is the shared NetworkCore.jl statistic generic.
Example
using ERGM
name(Edges()) # "edges"
name(GWESP(0.5)) # "gwesp.fixed.0.5"
name(NodeMatch(:sex)) # "nodematch.sex"name(term::AbstractERGMTerm, net) -> StringThe coefficient name term carries in a model built on net — the label R ergm prints for that term on that network. For most terms this is name(term); the geometrically weighted shared-partner terms (GWESP, GWDSP) are the exception, because R's label depends on the network's directedness (gwesp.fixed.0.5 on an undirected network, gwesp.OTP.fixed.0.5 on a directed one). ERGMModel and summary_stats name their statistics with this method, so fit.model.formula.terms.names matches names(coef(fit)) of a statnet fit of the same formula on either kind of network.
Example
using ERGM
net = load_dataset(:florentine_marriage)
name(GWESP(0.5), net) # "gwesp.fixed.0.5"
dnet = network(3; directed=true)
name(GWESP(0.5), dnet) # "gwesp.OTP.fixed.0.5"
name(Edges(), dnet) # "edges"Batch Operations
NetworkCore.compute_all — Function
compute_all(ts::TermSet, net) -> Vector{Float64}Compute all term statistics for the network — the vector g(y) of the model's sufficient statistics, in term order. compute_all is the shared NetworkCore.jl statistic generic.
Example
using ERGM
net = load_dataset(:florentine_marriage)
compute_all(TermSet([Edges(), NodeCov(:wealth)]), net) # [20.0, 2168.0]ERGM.change_stat_all — Function
change_stat_all(ts::TermSet, net, i::Int, j::Int) -> Vector{Float64}Compute add-direction change statistics for all terms for dyad (i,j) — one row of the MPLE design matrix.
Example
using ERGM
net = load_dataset(:florentine_marriage)
change_stat_all(TermSet([Edges(), NodeCov(:wealth)]), net, 1, 2) # [1.0, 46.0]ERGM.summary_stats — Function
summary_stats(net, terms; missing=:error) -> NamedTupleCompute the observed value of every term on net without fitting anything — R ergm's summary(net ~ edges + triangle). Returns a NamedTuple keyed by the terms' names as they appear in a model on net (see name(term, net): a directed network's GWESP(0.5) is gwesp.OTP.fixed.0.5, as in R); terms is a vector of terms, in the same shapes fit_ergm accepts. The formula is validated and expanded exactly as a model on net would be: a term undefined on the network (Mutual on an undirected network, Degree on a directed one, a missing or incomplete vertex attribute) is an ArgumentError, as in R, never a silent 0; a multi-degree term (Degree(0:2)), a multi-level NodeFactor and a multi-cell NodeMix expand into one entry per statistic, under R's labels. A network containing a self-loop is refused with the model's ArgumentError (see ERGM.Extension.require_supported_network): ERGM.jl's terms are defined on the off-diagonal dyads, and R counts a loop differently in some of them (kstar(2) of a looped triangle is 7 in R, 5 when the loop is read as an edge), so no number is returned for a statistic neither package of the model would reproduce.
Masked dyads (set_missing_dyad!) are refused by default — a statistic is a number computed from every dyad, and an unobserved dyad has no value to contribute (the ecosystem missing-data contract, NetworkCore.require_observed). missing=:face is the explicit opt-in: every masked dyad is read at its stored face value (a masked tie counts as a tie). This is a descriptive statistic, so the opt-in is legitimate — but note that R's summary() treats an NA dyad as absent, so to reproduce R's number remove the masked ties first (the provenanced masked-flomarriage fixture does exactly that). missing_policies(summary_stats) == (:error, :face). The protocol-level compute/compute_all are raw evaluations with no policy of their own (they are what the estimators, which handle the mask themselves, call).
Example
using ERGM
net = load_dataset(:florentine_marriage)
summary_stats(net, [Edges(), Triangle()]) # (edges = 20.0, triangle = 3.0)
summary_stats(net, [Degree(0:1)]) # (degree0 = 1.0, degree1 = 4.0)
try summary_stats(net, [Mutual()]) catch e; e isa ArgumentError end # true: undirected
loopy = network(3; directed=false, loops=true)
add_edge!(loopy, 1, 2); add_edge!(loopy, 1, 1)
try summary_stats(loopy, [Edges()]) catch e; occursin("self-loop", e.msg) end # true
masked = copy(net); set_missing_dyad!(masked, 1, 9) # a masked tie
try summary_stats(masked, [Edges()]) catch e; e isa ArgumentError end # true
summary_stats(masked, [Edges()]; missing=:face) # (edges = 20.0,)Result Accessors
The full ecosystem StatsAPI surface (coef, stderror, vcov, confint, loglikelihood, nobs, dof, aic, bic, coeftable, coefnames) is defined on ERGMResult; NetworkCore.check_statsapi(fit; strict=true) passes with coefnames required.
StatsAPI.coef — Method
coef(result::ERGMResult) -> Vector{Float64}Estimated coefficients of the fitted model (a method of StatsAPI.coef), in the order of result.model.formula.terms.names.
Example
using ERGM
fit = fit_ergm(load_dataset(:florentine_marriage), [Edges(), NodeCov(:wealth)])
round.(coef(fit); digits=3) # [-2.595, 0.011]StatsAPI.stderror — Method
stderror(result::ERGMResult) -> Vector{Float64}Standard errors of the coefficient estimates (a method of StatsAPI.stderror); their type is recorded in result.se_type (:hessian, :bootstrap, or :mcmc — the last includes the Monte-Carlo component mcmc_se).
Example
using ERGM
fit = fit_ergm(load_dataset(:florentine_marriage), [Edges(), NodeCov(:wealth)])
round.(stderror(fit); digits=3) # [0.536, 0.005]StatsAPI.vcov — Method
vcov(result::ERGMResult) -> Matrix{Float64}Variance-covariance matrix of the coefficient estimates (a method of StatsAPI.vcov); sqrt.(diag(vcov(fit))) == stderror(fit).
Example
using ERGM, LinearAlgebra
fit = fit_ergm(load_dataset(:florentine_marriage), [Edges(), NodeCov(:wealth)])
size(vcov(fit)) # (2, 2)
sqrt.(diag(vcov(fit))) ≈ stderror(fit) # trueStatsAPI.confint — Method
confint(result::ERGMResult; 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 — result.se_type says whether they are inverse-Hessian, parametric-bootstrap or MCMC-based. For an MPLE fit (method=:mple) of a dyad-dependent model with the default se, whose naive pseudo-likelihood SEs under-cover, confint refuses with an ArgumentError (see mple, "Inference under dyadic dependence"); with an explicit se=:hessian the naive intervals are returned. A separated MPLE (result.separated_terms not empty) has no finite maximum, and every limit is NaN.
Example
using ERGM
fit = fit_ergm(load_dataset(:florentine_marriage), [Edges(), NodeCov(:wealth)])
ci = confint(fit) # 2×2
all(ci[:, 1] .< coef(fit) .< ci[:, 2]) # true
confint(fit; level=0.9) # narrowerStatsAPI.coeftable — Method
coeftable(result::ERGMResult) -> NetworkCore.CoefficientTableThe 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). Rows can be read by index or by term name.
Example
using ERGM
fit = fit_ergm(load_dataset(:florentine_marriage), [Edges(), NodeCov(:wealth)])
tbl = coeftable(fit)
tbl["edges"].estimate == coef(fit)[1] # true
tbl[2].p_value == fit.p_values[2] # trueStatsAPI.coefnames — Method
coefnames(result::ERGMResult) -> Vector{String}The coefficient labels, in coef(result) order — R's names(coef(fit)), under R's labels ("edges", "nodematch.Race.Hisp", "gwesp.fixed.0.25", …) and identical to coeftable(result).names (a method of StatsAPI.coefnames). A copy: changing it does not change the fit.
Example
using ERGM
fit = fit_ergm(load_dataset(:florentine_marriage), [Edges(), NodeCov(:wealth)])
coefnames(fit) # ["edges", "nodecov.wealth"]
coefnames(fit) == coeftable(fit).names # true