Types API Reference

This page documents the core types in ERGMUserterms.jl.

Package

ERGMUserterms — Module
ERGMUserterms.jl - Custom ERGM Term Development

Provides templates, utilities, and validation tools for developing custom ERGM terms. Includes example terms and a comprehensive testing framework.

Port of the R ergm.userterms package from the StatNet collection. What is ported is the role of that package — a validated, copyable starting point for third-party terms — not its contents: R's C-level changestats.users template and its mindegree example term are not ported (the Julia counterpart of the C template is examples/MyTermPackage/; a Julia term is plain Julia, so there is no C skeleton to fill in).

The interface generics a term extends — name, compute, change_stat — are ERGM.jl's (compute/name are really NetworkCore.jl's shared statistic protocol); this package imports and re-exports them, so import ERGM: … and import ERGMUserterms: … name the same functions. Edge endpoints src/dst are Graphs.src/Graphs.dst, which neither NetworkCore.jl nor ERGM.jl re-exports: a term iterating edges(net) needs using Graphs: src, dst.

source

Term Base Types

ERGMUserterms.AbstractUserTerm — Type
AbstractUserTerm <: AbstractERGMTerm

Base type for user-defined ERGM terms. A subtype is a full ERGM.jl term — it can go into an ERGMFormula, be fitted with fit_ergm/ergm and simulated from — once it has name, compute and change_stat methods (the add-direction convention) and declares the traits that differ from the defaults (ERGM.required_vertex_attributes, ERGM.requires_directed, ERGM.is_dyad_dependent, NetworkCore.supports_missing, …). The fallback ERGM.is_dyad_dependent(::AbstractUserTerm) is true, the conservative answer; ERGM's own NodalTerm/DyadicTerm supertypes imply false, so subtype those only for covariate-only terms.

Example

using ERGM, ERGMUserterms, NetworkCore, Random
import ERGM: name, compute, change_stat
struct EdgeCount <: AbstractUserTerm end
name(::EdgeCount) = "edgecount"
compute(::EdgeCount, net) = Float64(ne(net))
change_stat(::EdgeCount, net, i::Int, j::Int) = 1.0
ERGM.is_dyad_dependent(::EdgeCount) = false          # covariate-only: exact MPLE
EdgeCount() isa AbstractERGMTerm                     # true — a first-class ERGM term
net = network(6; directed=true)
add_edge!(net, 1, 2); add_edge!(net, 2, 3)
validate_term(EdgeCount(), net; verbose=false, rng=Xoshiro(1))   # true
ERGMModel(ERGMFormula([EdgeCount()]), net) isa ERGMModel         # true
source

Example Terms

ERGMUserterms.ExampleTerm — Type
ExampleTerm <: AbstractUserTerm

Example custom term that counts edges weighted by vertex ID sum. Use this as a template for creating your own terms.

All change_stat methods must return the add-direction change statistic g(y⁺ij) − g(y⁻ij) — the statistic with edge (i,j) present minus with it absent — independent of whether the edge currently exists. ERGM.jl's MPLE design matrix and MH sampler both require this convention.

Identical to statnet's nodecov("id") with id = vertex index; the golden fixture test/fixtures/userterms_examples.toml pins it against ergm on every dyad. Covariate-only, so it declares ERGM.is_dyad_dependent = false.

Example

using ERGM, ERGMUserterms, NetworkCore
net = network(5; directed=true)
add_edge!(net, 1, 2); add_edge!(net, 3, 4)
compute(ExampleTerm(), net)              # 10.0 — (1 + 2) + (3 + 4)
change_stat(ExampleTerm(), net, 2, 3)    # 5.0
change_stat(ExampleTerm(), net, 1, 2)    # 3.0 — edge present: same add-direction value
name(ExampleTerm())                      # "example"
source
ERGMUserterms.TemplateTerm — Type
TemplateTerm{T} <: AbstractUserTerm

A parameterized template term — param times the number of edges. Copy and modify this for your own terms. TemplateTerm(1.0) is statnet's edges (pinned by the golden fixture).

Fields

  • param::T: A parameter value
  • attr::Symbol: An attribute name (optional; unused by the template's statistic — a placeholder for the attribute your term reads)

Example

using ERGM, ERGMUserterms, NetworkCore, Random
net = network(5; directed=true)
add_edge!(net, 1, 2); add_edge!(net, 2, 3)
t = TemplateTerm(2.5)
name(t)                                  # "template.2.5"
compute(t, net)                          # 5.0 — 2 edges × 2.5
change_stat(t, net, 3, 4)                # 2.5
TemplateTerm(3; attr=:x).attr            # :x
validate_term(t, net; verbose=false, rng=Xoshiro(1))   # true
source
ERGMUserterms.WeightedEdges — Type
WeightedEdges <: AbstractUserTerm

Sum of edge weights, with default (1.0) for dyads lacking the weight attribute. Demonstrates accessing edge attributes — and the one thing a term reading them must get right.

The weights are exogenous dyadic data, snapshotted at model construction. ERGM.jl's samplers toggle dyads with rem_edge! / add_edge!, and rem_edge! deletes the dyad's edge attributes: a term that read the attribute live would lose every stored weight as the chain runs, and MCMLE, simulate_ergm and gof would silently target the all-default model. So WeightedEdges defines ERGM.Extension.materialize(term, net), the step ERGMModel runs on every term: it returns a twin holding the weights as an n × n matrix W (the stored attribute where a dyad has one, default elsewhere), and inside a model the term is statnet's edgecov(W) — in MPLE, MCMLE, simulation and goodness of fit alike (pinned against R and against the exact MLE). validate_traits checks exactly this for any term on a network with edge attributes.

Called directly on a network (outside a model), compute sums over the network's edges, reading each edge's weight with the per-edge getter get_edge_attribute(net, attr, i, j) (which returns nothing for an edge — or a network — without the attribute) and falling back to default. The term declares no required edge attribute: it is well defined on a network that has never heard of attr. On an undirected network the getter reads the canonical (min, max) key itself.

The read is asserted ::Float64, so compute/change_stat infer Float64 and allocate nothing per call (the attribute store is untyped, Dict{…,Any}; without the assertion the term would infer Any and box on every MPLE row and MH step of any model containing it).

Example

using ERGM, ERGMUserterms, NetworkCore, Random
net = network(4; directed=true)
add_edge!(net, 1, 2); add_edge!(net, 2, 3)
set_edge_attribute!(net, :weight, 1, 2, 3.0)
t = WeightedEdges()                      # attr = :weight, default = 1.0
compute(t, net)                          # 4.0 — 3.0 + the default 1.0
change_stat(t, net, 1, 2)                # 3.0
change_stat(t, net, 3, 4)                # 1.0 — a fresh edge gets the default
ERGM.required_edge_attributes(t)         # () — deliberately undeclared
validate_term(t, net; verbose=false)     # true
# Inside a model the weights are a snapshot: they survive the edge being
# removed and re-added, which deletes the stored attribute
m = ERGM.Extension.materialize(t, net)
rem_edge!(net, 1, 2); add_edge!(net, 1, 2)
(change_stat(t, net, 1, 2), change_stat(m, net, 1, 2))   # (1.0, 3.0)
source
ERGMUserterms.DyadCovTerm — Type
DyadCovTerm <: AbstractUserTerm

Dyadic covariate term: sum over edges of covariate[i, j]. Demonstrates using a matrix covariate. Identical to statnet's edgecov(covariate); on an undirected network the entry is read at the canonical (min, max) position, so pass a symmetric matrix (or accept that only its upper triangle counts).

The matrix must be n × n for the network it is used on, in vertex order: a non-square matrix is refused at construction, and a matrix of the wrong size is an ArgumentError from compute, change_stat, validate_term and ERGMModel construction — never a silent 0 for the dyads it does not cover (a 4 × 4 matrix on 16 vertices used to fit to -Inf).

Example

using ERGM, ERGMUserterms, NetworkCore, Random
distance = [0.0 1.0 2.0 3.0
            1.0 0.0 1.5 2.5
            2.0 1.5 0.0 1.0
            3.0 2.5 1.0 0.0]
net = network(4; directed=true)
add_edge!(net, 1, 2); add_edge!(net, 3, 4)
t = DyadCovTerm(distance)
compute(t, net)                          # 2.0 — distance[1,2] + distance[3,4]
change_stat(t, net, 1, 3)                # 2.0
validate_term(t, net; verbose=false)     # true
try; ERGMModel(ERGMFormula([t]), network(6; directed=true)); catch e; e isa ArgumentError; end   # true — wrong size
source
ERGMUserterms.InteractionTerm — Type
InteractionTerm <: AbstractUserTerm

Interaction between two vertex attributes: the sum over edges (i, j) of a_i b_j + a_j b_i. Identical to statnet's edgecov(M) with M = a bᵀ + b aᵀ. It declares both attributes (ERGM.required_vertex_attributes), so ERGMModel construction refuses a network on which either is absent or set on only some vertices — the statnet NA rule — instead of fitting a silent all-zero column. Values are read per vertex with get_vertex_attribute(net, attr, v) and asserted ::Float64, so compute/change_stat infer Float64 and allocate nothing.

Example

using ERGM, ERGMUserterms, NetworkCore, Random
net = network(4; directed=true)
add_edge!(net, 1, 2)
set_vertex_attribute!(net, :age, Dict(1 => 25.0, 2 => 30.0, 3 => 40.0, 4 => 50.0))
set_vertex_attribute!(net, :income, Dict(1 => 5.0, 2 => 6.0, 3 => 7.0, 4 => 8.0))
t = InteractionTerm(:age, :income)
compute(t, net)                          # 300.0 — 25·6 + 30·5
ERGM.required_vertex_attributes(t)       # (:age, :income)
validate_term(t, net; verbose=false, rng=Xoshiro(1))   # true
try; ERGMModel(ERGMFormula([InteractionTerm(:age, :height)]), net); catch e; e isa ArgumentError; end   # true
source

Term Interface

All terms (both user-defined and built-in) must implement these methods. The generics are owned by ERGM.jl and re-exported by ERGMUserterms.jl.

NetworkCore.name — Function
name(term::AbstractERGMTerm) -> String

Return the term's descriptive, lowercase name, including any parameters (e.g. "template.2.0", "weightedges.weight").

This generic is owned by ERGM.jl (it is NetworkCore.name, the ecosystem's shared statistic protocol) and re-exported here: ERGMUserterms.name === ERGM.name === NetworkCore.name. Add a method for your term type after importing it by name — import ERGM: name or import ERGMUserterms: name, the same function; a bare using followed by name(::MyTerm) = … defines a local name that ERGM.jl never calls. Without a method, ERGM.jl falls back to string(typeof(term)).

Use R ergm's label where one exists ("gwdeg.fixed.0.5", "nodematch.group") so coefficient tables line up with statnet output. ERGM.jl also has a two-argument name(term, net) for labels that depend on the network's direction ("gwesp.OTP.fixed.0.5" on a digraph); it falls back to name(term), so a user term needs only the one-argument method.

Example

using ERGM, ERGMUserterms, NetworkCore, Random
import ERGM: name, compute, change_stat     # extend the shared generics
struct OneEdge <: AbstractUserTerm end
name(::OneEdge) = "oneedge"
compute(::OneEdge, net) = Float64(ne(net))
change_stat(::OneEdge, net, i::Int, j::Int) = 1.0
name(OneEdge())                                   # "oneedge"
name(OneEdge()) == ERGM.name(OneEdge())           # true — one generic, not a local copy
validate_term(OneEdge(), network(4; directed=true); verbose=false, rng=Xoshiro(1))   # true
source
NetworkCore.compute — Function
compute(term::AbstractERGMTerm, net) -> Float64

Compute the term's full network statistic g(y) on net.

This generic is owned by ERGM.jl (it is NetworkCore.compute, the ecosystem's shared statistic protocol) and re-exported here: ERGMUserterms.compute === ERGM.compute === NetworkCore.compute. Add a method for your term type after import ERGM: compute (or import ERGMUserterms: compute — the same function). It must be deterministic, must not modify the network, and should handle empty and complete networks.

Edge endpoints are Graphs.src/Graphs.dst, which NetworkCore.jl does not re-export — a compute that iterates edges(net) needs using Graphs: src, dst. A vertex attribute the term declares (ERGM.required_vertex_attributes) is guaranteed complete inside an ERGMModel (ERGM refuses a partial one, as statnet refuses NA), so get(attrs, v, default) fallbacks only ever fire on raw compute calls.

Example

using ERGM, ERGMUserterms, NetworkCore, Random
using Graphs: src, dst
import ERGM: name, compute, change_stat
struct Descending <: AbstractUserTerm end      # arcs i -> j with i > j
name(::Descending) = "descending"
compute(::Descending, net) = Float64(count(src(e) > dst(e) for e in edges(net)))
change_stat(::Descending, net, i::Int, j::Int) = i > j ? 1.0 : 0.0
net = network(4; directed=true)
add_edge!(net, 3, 1); add_edge!(net, 1, 2)
compute(Descending(), net)                                            # 1.0
validate_term(Descending(), net; verbose=false, rng=Xoshiro(1))       # true
source
ERGM.change_stat — Function
change_stat(term::AbstractERGMTerm, net, i::Int, j::Int) -> Float64

Compute 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 fixed.

The value must not depend on whether the edge currently exists: ERGM.jl's MPLE design matrix uses it directly, and the Metropolis–Hastings sampler negates it for removal proposals. The toggle-direction idiom has_edge(net, i, j) ? -delta : delta is wrong under this contract and is rejected by change_stat_check / validate_term.

This generic is owned by ERGM.jl and re-exported here (ERGMUserterms.change_stat === ERGM.change_stat); add a method for your term type after import ERGM: change_stat. For performance it should be O(degree), not O(edges).

Example

using ERGM, ERGMUserterms, NetworkCore, Random
import ERGM: name, compute, change_stat
struct Mutuals <: AbstractUserTerm end          # mutual dyads, counted once
name(::Mutuals) = "mutuals"
compute(::Mutuals, net) =
    Float64(count(has_edge(net, i, j) && has_edge(net, j, i)
                  for i in 1:nv(net) for j in 1:nv(net) if i < j))
# Adding i -> j completes a mutual dyad iff j -> i is there; the value does
# not consult has_edge(net, i, j) itself
change_stat(::Mutuals, net, i::Int, j::Int) = has_edge(net, j, i) ? 1.0 : 0.0
net = network(4; directed=true)
add_edge!(net, 1, 2); add_edge!(net, 2, 1); add_edge!(net, 3, 4)
change_stat(Mutuals(), net, 4, 3)                                    # 1.0
change_stat(Mutuals(), net, 1, 2)                                    # 1.0 — edge present, same value
change_stat_check(Mutuals(), net; n_tests=8, rng=Xoshiro(1))         # true
source