Validation API Reference
This page documents the validation, testing, and consistency checking functions.
Term Validation
ERGMUserterms.validate_term — Function
validate_term(term::AbstractERGMTerm, net::Network; verbose=true, traits=true,
n_tests=nothing, rng=Random.default_rng()) -> BoolValidate that a term is correctly implemented.
Checks the method interface:
name()returns a non-empty stringcompute()returns a Realchange_stat()returns a Real on every checked dyad- Change statistics are consistent with compute differences (the add-direction convention,
change_stat_check) — by default on every dyad ofnet - The statistic of the empty network and the path to
net:computeon the empty network,g(∅), plus the change statistics summed while the edges ofnetare added one at a time, must equalcompute(term, net).g(∅)need not be 0 (a count of isolates isnthere) — ERGM.jl's likelihood includesθ'g(∅)— but it must be the right number: acomputethat special-cases the empty network (ne(net) == 0 && return 0.0) fails here.
and, unless traits=false, the term's trait declarations — see validate_traits for exactly what is asserted about ERGM.required_vertex_attributes, ERGM.required_edge_attributes, ERGM.requires_directed/requires_undirected, ERGM.is_dyad_dependent and NetworkCore.supports_missing, and about edge attributes surviving the sampler. The trait checks also assert that the term is accepted by ERGMModel construction on net, so a term that passes validate_term is a term ERGM.jl will fit.
net must carry every vertex/edge attribute the term declares (validate against a network the term is meant for), with a value on every vertex — ERGM.jl refuses partial attributes at model construction, and so does this — and with values that vary across vertices (a constant declared attribute cannot be shown to be read, and the run fails). A network ERGM.jl cannot fit is refused up front with an ArgumentError rather than validated: fewer than 2 vertices (no dyad to check), a two-mode network, or one containing a self-loop. A verdict is never returned without evidence: an integer n_tests must be at least 1.
Keywords
verbose=true: log each check (@info) and each failure (@warn). The consistency line reports how many of the network's dyads were checked.traits=true: runvalidate_traitsafter the interface checks.n_tests=nothing: which dyads thechange_statchecks visit.nothing(the default) checks every dyad of a network with up to 5000 dyads, and a stratified sample of 5000 on a larger one. An integerk ≥ 1is the opt-in to a cheaper, weaker run: a stratified sample ofmin(k, number of dyads)distinct dyads. The strata are the dyad's own state, the state of the reverse arc (directed networks) and whether its endpoints share a partner; they are filled in turn, so every non-empty stratum is visited and a small one (e.g. the reciprocated dyads of a sparse network) is exhausted before a large one is sampled further.rng=Random.default_rng(): the source of every random draw (none in an exhaustive run). Two calls with equal rngs visit the same dyads. Every failure message of a sampled run ends withreproduce with rng=Xoshiro(0x…, 0x…, 0x…, 0x…), the rng state on entry — pass it back to replay the run.
Example
using ERGM, ERGMUserterms, NetworkCore, Random
net = network(10; directed=true)
for (i, j) in [(1, 2), (2, 3), (3, 1), (1, 4), (4, 5)]
add_edge!(net, i, j)
end
validate_term(ExampleTerm(), net; verbose=false) # true — all 90 dyads checked
validate_term(ExampleTerm(), net; verbose=false, n_tests=20, rng=Xoshiro(1)) # true — 20 sampled dyadsERGMUserterms.validate_traits — Function
validate_traits(term::AbstractERGMTerm, net::Network; verbose=true,
rng=Random.default_rng()) -> BoolExercise a term's declarations under ERGM.jl's public term-trait protocol (ERGM.required_vertex_attributes, ERGM.required_edge_attributes, ERGM.requires_directed, ERGM.requires_undirected, ERGM.is_dyad_dependent, NetworkCore.supports_missing) against net.
Checked, in order:
- Attributes are the ones it reads. Every attribute the term declares must exist on
net— a declared vertex attribute with a value on every vertex, since ERGM.jl refuses a partial attribute at model construction the way statnet refuses NA — and must actually move the term's statistic when its values are perturbed (otherwise the declaration is a warning: an over-declaration needlessly narrows the networks the term can be fitted to). Conversely, a term whose statistic moves when an undeclared vertex attribute is perturbed fails: it reads an attribute ERGM.jl will not validate, so on a network lacking that attribute it would silently become an all-zero design column instead of an error. (An undeclared edge attribute is only warned about — terms likeWeightedEdgesread one but fall back to a default, so they genuinely do not require it.) An attribute that is constant onnetcannot be perturbed, so whether the term reads it is undecidable there: the check is reported as not run (never as ✓), and for a declared attribute the run fails — validate on a network where the attribute varies. - Direction requirements are honoured. A term declaring
requires_directedmust be rejected byERGMModelconstruction on the undirected twin ofnet(and symmetrically forrequires_undirected). - Dyad-independence claims hold. A term declaring
is_dyad_dependent(term) == falsemust return the same change statistic for a dyad whatever the state of the other dyads: every dyad's change statistic is compared on the empty, the observed and the complete network, and then every other dyad is toggled in turn for every source dyad (all pairs on a network of up to ~500 ordered dyads; beyond that the reverse arc and the dyads sharing an endpoint first, then a random remainder). A violation fails the run — ERGM.jl trusts the declaration foris_exactand for the exact log-normaliser. (true, the conservative default, asserts nothing.)
3b. Edge attributes survive the sampler. ERGM.jl's samplers toggle with rem_edge!/add_edge!, and rem_edge! deletes the dyad's edge attributes. On a network carrying edge attributes, the term as ERGMModel holds it (ERGM.Extension.materialize(term, net)) must give the same statistic and change statistics after every edge has been removed and re-added without its attributes: a term that reads an edge attribute live fails (snapshot it at model construction, as WeightedEdges does).
- Missing-data claims hold. A term declaring
NetworkCore.supports_missing(term) == truemust return the same statistic however the face value of a masked dyad is flipped — that is what it means to honour the mask. (false, the default, asserts nothing: the statistic then counts masked dyads at face value, and the missing-data treatment lives in the estimator.)
Finally, ERGMModel construction with the term on net must succeed (ERGM.Extension.validate_formula is what runs there; its message is reported verbatim on failure).
Keywords
verbose=true: log each check (@info) and each failure (@warn).rng=Random.default_rng(): the source of every random draw (the sampled pairs of check 3 on a big network and the masked dyads of check 4). Every failure message ends withreproduce with rng=Xoshiro(0x…, …), the rng state on entry.
Example
using ERGM, ERGMUserterms, NetworkCore, Random
net = network(6; directed=true)
set_vertex_attribute!(net, :a, Dict(v => Float64(v) for v in 1:6))
add_edge!(net, 1, 2); add_edge!(net, 2, 3)
validate_traits(InteractionTerm(:a, :a), net; verbose=false, rng=Xoshiro(1)) # trueERGMUserterms.test_term — Function
test_term(term::AbstractERGMTerm; n_vertices=20, density=0.1, n_tests=nothing,
directed=true, vertex_attributes=Dict{Symbol,Any}(),
rng=Random.default_rng()) -> BoolComprehensive test suite for an ERGM term: builds a random network of n_vertices vertices at edge density (directed unless directed=false; edges drawn from rng), gives it the vertex attributes in vertex_attributes, runs validate_term on it (every dyad by default; n_tests sampled dyads if given) with the same rng, then checks compute on an empty and on a complete network of the same kind (same directedness and attributes). Prints a report (including the rng=Xoshiro(0x…, …) literal that replays the whole run) and returns whether everything passed.
The generated networks carry no vertex attributes unless you ask, and are directed unless you ask: a term that declares ERGM.required_vertex_attributes needs vertex_attributes, one that declares ERGM.requires_undirected needs directed=false — otherwise validate_term (correctly) reports the mismatch and the run FAILS.
Keywords
n_vertices=20,density=0.1: size (at least 2) and edge density (in[0, 1]) of the random network; anything else is anArgumentError, not a report on a network with no dyad to check.n_tests=nothing: every dyad of the generated network is checked; an integer (at least 1) checks a stratified sample of that many instead.directed=true: build a directed (true) or undirected (false) network.vertex_attributes=Dict{Symbol,Any}():attr => specpairs set on every generated network;specis either a function of the vertex index (v -> value) or a vector with one value per vertex (length ≥n_vertices).rng=Random.default_rng(): the source of every random draw — the network and the dyads.
Example
using ERGM, ERGMUserterms, Random
test_term(ExampleTerm(); n_vertices=8, density=0.2, n_tests=5, rng=Xoshiro(2)) # true
# A term declaring vertex attributes needs the generated network to carry them
test_term(InteractionTerm(:a, :b); n_vertices=8, n_tests=5, rng=Xoshiro(2),
vertex_attributes=Dict(:a => (v -> Float64(v)), :b => (v -> Float64(9 - v)))) # true
# A term defined on undirected networks only (ERGM.requires_undirected) is
# tested on one
test_term(TemplateTerm(2.0); n_vertices=8, n_tests=5, directed=false, rng=Xoshiro(2)) # trueConsistency Checking
ERGMUserterms.change_stat_check — Function
change_stat_check(term::AbstractERGMTerm, net::Network; n_tests=nothing,
verbose=true, tol=1e-10, rng=Random.default_rng()) -> BoolVerify that change_stat returns the add-direction change statistic required by ERGM.jl: compute with edge (i,j) present minus compute with it absent, independent of the dyad's current state. By default (n_tests=nothing) every dyad of net is checked (a stratified sample of 5000 on a network with more dyads than that); an integer n_tests ≥ 1 checks a stratified sample of that many distinct dyads drawn with rng (see validate_term for the strata). Each dyad is toggled on a copy of net and restored, and is checked twice — as-is, and with its state flipped — so a toggle-direction term fails the second check. All failing dyads are reported, not only the first. A network with fewer than 2 vertices, a two-mode one, or one containing a self-loop is refused with an ArgumentError (ERGM.jl cannot fit it; see validate_term).
Every failure message (verbose=true) names the dyad and ends with reproduce with rng=Xoshiro(0x…, …), the rng state on entry; pass it back to replay the same dyad sequence.
Example
using ERGM, ERGMUserterms, NetworkCore, Random
net = network(8; directed=true)
add_edge!(net, 1, 2); add_edge!(net, 2, 3); add_edge!(net, 3, 1)
change_stat_check(ExampleTerm(), net) # true — all 56 dyads
change_stat_check(ExampleTerm(), net; n_tests=5, rng=Xoshiro(1)) # true — 5 sampled dyads
change_stat_check(ExampleTerm(), net; n_tests=5, rng=Xoshiro(1)) ==
change_stat_check(ExampleTerm(), net; n_tests=5, rng=Xoshiro(1)) # trueERGMUserterms.consistency_check — Function
consistency_check(term::AbstractERGMTerm, net::Network; exhaustive=true,
tol=1e-10, verbose=false, rng=Random.default_rng()) -> BoolFull consistency check between compute and the add-direction change_stat (see change_stat_check); stops at the first inconsistent dyad. By default (exhaustive=true) every dyad of net is checked once, whatever its size — each ordered pair on a directed network, each unordered pair (i < j) on an undirected one (can be slow for large networks). exhaustive=false is the opt-in to a cheaper, weaker run: up to min(100, number of dyads) distinct random dyads drawn from rng (never i == j; canonicalised to (min, max) on an undirected network). verbose=true reports the failing dyad, with the rng=Xoshiro(0x…, …) replay literal. A network with fewer than 2 vertices, a two-mode one, or one containing a self-loop is refused with an ArgumentError.
Example
using ERGM, ERGMUserterms, NetworkCore, Random
net = network(6; directed=true)
add_edge!(net, 1, 2); add_edge!(net, 2, 3)
consistency_check(TemplateTerm(2.0), net) # true — all 30 dyads
consistency_check(TemplateTerm(2.0), net; exhaustive=false, rng=Xoshiro(3)) # trueBenchmarking
ERGMUserterms.benchmark_term — Function
benchmark_term(term::AbstractERGMTerm, net::Network; n_iter=1000,
rng=Random.default_rng()) -> NamedTupleBenchmark compute() and change_stat() performance: n_iter timed calls of each (at least 1), the change_stat calls on random dyads drawn from rng. Returns (compute_mean, compute_std, change_stat_mean, change_stat_std, speedup) in seconds; speedup = compute_mean / change_stat_mean. A network with fewer than 2 vertices, a two-mode one, or one containing a self-loop is refused with an ArgumentError, as by every validator.
Example
using ERGM, ERGMUserterms, NetworkCore, Random
net = network(10; directed=true)
add_edge!(net, 1, 2); add_edge!(net, 2, 3)
b = benchmark_term(ExampleTerm(), net; n_iter=100, rng=Xoshiro(1))
b.speedup > 0 # trueERGMUserterms.profile_term — Function
profile_term(term::AbstractERGMTerm; sizes=[10, 20, 40], density=0.1,
n_iter=200, directed=true, vertex_attributes=Dict{Symbol,Any}(),
rng=Random.default_rng()) -> Vector{NamedTuple}Profile a term's compute/change_stat cost across network sizes. Returns one benchmark_term result per size (with n_vertices and the realized edge count ne added), useful for spotting change statistics that do not scale (e.g. O(edges) instead of O(degree)). The random networks and the benchmarked dyads are all drawn from rng.
The generated networks are built exactly as test_term builds them: directed unless directed=false, and carrying the vertex attributes in vertex_attributes (attr => v -> value or attr => vector). Without them a term declaring ERGM.requires_undirected cannot be profiled at all, and an attribute-declaring term is timed on its attribute-absent fallback branch rather than its real cost.
Keywords
sizes=[10, 20, 40]: vertex counts (each at least 2) of the random networks.density=0.1: edge density of each random network, in[0, 1].n_iter=200: timed calls per size (at least 1), passed tobenchmark_term.directed=true: build directed (true) or undirected (false) networks.vertex_attributes=Dict{Symbol,Any}():attr => specpairs set on every generated network;specis a function of the vertex index or a vector with one value per vertex (length ≥ the largest size).rng=Random.default_rng(): the source of every random draw.
Example
using ERGM, ERGMUserterms, Random
prof = profile_term(ExampleTerm(); sizes=[5, 10], n_iter=5, rng=Xoshiro(1))
[r.n_vertices for r in prof] # [5, 10]
# An attribute-declaring term is timed on networks that carry its attributes
prof = profile_term(InteractionTerm(:a, :b); sizes=[5, 10], n_iter=5, rng=Xoshiro(1),
vertex_attributes=Dict(:a => (v -> Float64(v)), :b => (v -> 1.0)))
length(prof) # 2
# ... and an undirected-only term on undirected networks
profile_term(TemplateTerm(1.0); sizes=[6], n_iter=5, directed=false, rng=Xoshiro(1))[1].ne <= 15 # trueTerm Macro
ERGMUserterms.@ergm_term — Macro
@ergm_term name bodyMacro for defining custom ERGM terms. After evaluating body, it verifies that the named type exists and that compute, change_stat, and name methods are defined for it, warning about anything missing. (Numeric consistency is checked separately with validate_term / change_stat_check, which need a term instance and a network.)
The generics must be imported by name before the macro is used (import ERGM: name, compute, change_stat); with a bare using, the body defines local functions of those names and the macro reports them as missing.
Example
using ERGM, ERGMUserterms, NetworkCore, Random
import ERGM: name, compute, change_stat
@ergm_term ScaledEdges begin
struct ScaledEdges <: AbstractUserTerm
scale::Float64
end
name(t::ScaledEdges) = "scalededges.$(t.scale)"
compute(t::ScaledEdges, net) = t.scale * ne(net)
# Add-direction: one more edge adds `scale`, whatever the dyad's state
change_stat(t::ScaledEdges, net, i::Int, j::Int) = t.scale
end
net = network(6; directed=true)
add_edge!(net, 1, 2); add_edge!(net, 2, 3)
compute(ScaledEdges(2.0), net) # 4.0
change_stat(ScaledEdges(2.0), net, 1, 2) # 2.0
validate_term(ScaledEdges(2.0), net; verbose=false, rng=Xoshiro(1)) # true