Extension API

ERGM.Extension is the stable API for packages that build estimators or term families on ERGM.jl. TERGM.jl, ERGMCount.jl, ERGMRank.jl, ERGMEgo.jl, ERGMMulti.jl and ERGMUserterms.jl are written against it, and so can a third-party package.

using ERGM
using ERGM.Extension          # the names below, unqualified
# or, qualified:
using ERGM: Extension
Extension.n_observed_dyads(load_dataset(:florentine_marriage))   # 120

The contract

  • Stability. The names of ERGM.Extension, their documented signatures, keywords and return values are covered by semantic versioning from ERGM.jl 0.2.0, like the exported API. A breaking change to one of them is a breaking release.
  • Nothing else is. No underscore name of ERGM.jl is public. Everything with a leading underscore is internal and may change in any release, so a package built on ERGM.jl must not call one. If it needs a building block that is not here, the block belongs here: ask for it.
  • Every name has a consumer. A name is in the extension API because one of the six ERGM-family packages calls it, or because it is an extension point a package adds methods to. The test suite pins the inventory and checks that each name has a consumer.
  • Extension points. attainable_range and materialize are generic functions owned by ERGM.Extension. A package adds methods for its own term or network types to them (Extension.attainable_range(t::MyTerm, net) = …); ERGM.jl's own estimators then see those methods.
  • ERGM exports nothing from here. Extension itself is a public (not exported) name of ERGM, so using ERGM leaves a user's namespace unchanged.
ERGM.Extension — Module
ERGM.Extension

The stable API for packages that build estimators or term families on ERGM.jl. TERGM.jl, ERGMCount.jl, ERGMRank.jl, ERGMEgo.jl, ERGMMulti.jl and ERGMUserterms.jl are written against it, and a third-party package can be too. The names are covered by semantic versioning from ERGM.jl 0.2.0. They are not exported by ERGM itself: bring them in with using ERGM.Extension, or call them qualified (Extension.mple_fit_design(...) after using ERGM: Extension).

Building blockNames
Formula pipelinecollect_terms, validate_formula, materialize, expand_terms, require_supported_network, n_observed_dyads
Boundary of the parameter spaceattainable_range, extreme_statistics, boundary_columns, warn_boundary
Pseudo-likelihoodmple_fit_design
Monte-Carlo MLEmcmc_defaults, mcmle_solve, confidence_test, mcmle_covariance, ess_sample, mcmle_sampler, bridge_integrate

Two of them are extension points that a package adds methods to for its own types: attainable_range (the minval/maxval of R ergm's terms, which drives R's drop=TRUE) and materialize (the snapshot a term takes of the network's attributes when a model is built). The boundary convention every ERGM-family estimator follows is described on the documentation page "Extension API".

Example

using ERGM
using ERGM.Extension
net = load_dataset(:florentine_marriage)
ts = TermSet([Edges(), Triangle()])
validate_formula(ts, net) === nothing                  # true
extreme_statistics(materialize(ts, net), net)          # Tuple{Int, Symbol}[]: nothing at a bound
attainable_range(Edges(), net)                         # (0.0, 120.0)
source

Formula pipeline

What ERGMModel does to a term list, as separate steps, so that a model evaluated on several networks (TERGM's panels, ERGMMulti's layers) runs the same checks and expansion on each.

ERGM.Extension.collect_terms — Function
collect_terms(terms) -> Vector{AbstractERGMTerm}

Normalize a user-supplied term collection into a flat Vector{AbstractERGMTerm}.

Accepts a single term, a vector of terms, and — for callers that build term lists programmatically — a vector that mixes terms with vectors of terms ([Edges(), [NodeMatch(:g; diff=true, level=l) for l in levels]]); such nested vectors are spliced in place instead of raising a raw MethodError. (Degree(0:2) is a single expanding term since 0.2 and needs no splicing.)

Anything else throws an ArgumentError naming the offending element, its position and its type — with a hint when it is a term type rather than an instance (Edges instead of Edges()), the most common slip. Part of ERGM.Extension: the variants (TERGM's stergm) accept exactly what fit_ergm accepts by running their term lists through it.

Example

using ERGM
ERGM.Extension.collect_terms(Edges())                                        # [Edges()]
length(ERGM.Extension.collect_terms(Any[Edges(), [NodeMatch(:g), Triangle()]]))   # 3: spliced
try ERGM.Extension.collect_terms([Edges, Triangle()]) catch e; e isa ArgumentError end   # true: a term TYPE
source
ERGM.Extension.validate_formula — Function
validate_formula(terms::TermSet, net) -> nothing

Validate every term of a formula against the observed network, through the term-trait protocol alone: a declared vertex/edge attribute must exist (and a vertex attribute must have a value on every vertex — statnet refuses NA), and a direction requirement must be met. Throws an ArgumentError naming the term, the attribute/direction and the fix; called by the ERGMModel constructor so user errors surface before any fitting. Part of ERGM.Extension: TERGM.jl and the other variants validate their panels and layers with it rather than re-implementing the checks.

Example

using ERGM
net = load_dataset(:florentine_marriage)
ERGM.Extension.validate_formula(TermSet([Edges(), NodeCov(:wealth)]), net)   # nothing
try
    ERGM.Extension.validate_formula(TermSet([NodeCov(:welth)]), net)
catch e
    occursin(":welth", e.msg)   # true — names the missing attribute
end
source
ERGM.Extension.materialize — Function
materialize(term, net) -> term or Vector of terms
materialize(terms::TermSet, net) -> TermSet

Turn a term into its model-construction form: attribute terms snapshot the vertex attribute into typed vectors (MaterializedNodeCov, ...) so the hot loops never touch the attribute Dicts; multi-level NodeFactor/NodeMix and multi-degree Degree/IDegree/ODegree expand into one statistic per level/cell/degree (a Vector); every other term is returned unchanged. Names and values are preserved (verified against the raw terms in the test suite).

Part of ERGM.Extension, and an extension point: a term whose change statistic reads a vertex or edge attribute adds a method for its own type that returns a twin holding a snapshot of it (ERGMUserterms' WeightedEdges), because the samplers delete a tie's attributes when they remove it. The variants materialize their own layers and panels with it.

Example

using ERGM
net = load_dataset(:florentine_marriage)
ERGM.Extension.materialize(Edges(), net) === Edges()                       # true
m = ERGM.Extension.materialize(NodeCov(:wealth), net)
compute(m, net) == compute(NodeCov(:wealth), net)                 # true
length(ERGM.Extension.materialize(Degree(0:2), net))                       # 3
source
ERGM.Extension.expand_terms — Function
expand_terms(terms, net) -> Vector{AbstractERGMTerm}

The specification of a term list against net: the same expansion materialize performs — a multi-level NodeFactor / multi-cell NodeMix into one term per level or cell, a multi-degree Degree / IDegree / ODegree into one per degree, levels resolved from net — but as plain single-statistic terms (NodeFactor(:g; level=l), NodeMix(:g, a, b), Degree(d), every other term unchanged), WITHOUT the attribute snapshot a materialized twin carries. terms may be a TermSet or anything collect_terms accepts.

This is what a model that evaluates its terms on several networks needs: a STERGM scores T−1 auxiliary networks (TERGM), a multilayer model each layer (ERGMMulti). One snapshot taken at construction would freeze the first network's attribute onto every other, so such a model stores the specification and materializes per network. Part of ERGM.Extension for exactly those callers; the twin's base field is ERGM's own layout, read here and nowhere else.

Example

using ERGM
net = load_dataset(:faux_mesa_high)          # :Grade has six levels
spec = ERGM.Extension.expand_terms([Edges(), NodeFactor(:Grade), Degree(0:2)], net)
length(spec)                                   # 9: 1 + 5 non-base levels + 3 degrees
all(t -> !startswith(string(nameof(typeof(t))), "Materialized"), spec)   # true: no snapshot
spec[2] isa NodeFactor && spec[2].level !== nothing   # true: one level each
[name(t) for t in ERGM.Extension.expand_terms(ERGM.TermSet([Degree(0:1)]), net)]   # ["degree0", "degree1"]
source
ERGM.Extension.require_supported_network — Function
require_supported_network(net) -> net

The refusals ERGMModel gives a network ERGM.jl cannot model, in ERGM.jl's own words; returns net unchanged when it passes. Part of ERGM.Extension: a package that builds its own models on ERGM.jl's terms (ERGMUserterms' harness) refuses up front with these sentences rather than a mirrored copy, and picks up any refusal added later.

  • A two-mode (bipartite) network: bipartite terms and the two-mode proposal kernel are not implemented, and fitting the one-mode terms would count the impossible within-mode dyads as observations.
  • A self-loop: the statistics would count it while the estimators and samplers (which range over the off-diagonal dyads only) ignore it, so the two halves of the package would disagree about the data (R ergm warns "This network contains loops"). The looped vertices are named. A loops=true network with no loop passes.

Example

using ERGM
ERGM.Extension.require_supported_network(Network(4)) isa Network         # true
try ERGM.Extension.require_supported_network(network(5; bipartite=2)) catch e; occursin("two-mode", e.msg) end   # true
loopy = network(3; loops=true); add_edge!(loopy, 2, 2)
try ERGM.Extension.require_supported_network(loopy) catch e; occursin("at vertex 2", e.msg) end   # true
source
ERGM.Extension.n_observed_dyads — Function
n_observed_dyads(model::ERGMModel) -> Int
n_observed_dyads(net::Network) -> Int

Number of observed free dyads in the model's network (ordered pairs for directed networks, unordered pairs otherwise), excluding dyads masked as missing via NetworkCore.set_missing_dyad! — their tie status is unobserved, so they are not observations. It is what nobs(fit) returns. Part of ERGM.Extension: the variants size their samplers and probes with it (ERGMUserterms' term validation, ERGMCount's sweeps).

Example

using ERGM
net = load_dataset(:florentine_marriage)
model = ERGMModel(ERGMFormula([Edges()]), net)
ERGM.Extension.n_observed_dyads(model)          # 120
set_missing_dyad!(net, 3, 4)
ERGM.Extension.n_observed_dyads(model)          # 119
ERGM.Extension.n_observed_dyads(net)            # 119
source

The boundary convention

A statistic whose observed value sits at an end of its attainable range has no finite maximum-likelihood or pseudo-likelihood estimate. R ergm's default (control.ergm(drop=TRUE)) fixes its coefficient at -Inf (at the smallest value) or +Inf (at the largest) and estimates the rest. Every ERGM-family estimator follows the same convention:

  1. Detection. The boundary is extreme_statistics(terms, net) (R's ergm.checkextreme.model: the observed statistic equals an end of its attainable_range) together with boundary_columns(X, n_tot, n_one; fixed=extreme) (the design test, iterated). The first catches statistics whose change statistics are all zero, which the design cannot show; the second catches statistics the range does not bound, such as a perfectly separated nodematch.
  2. Pseudo-likelihood. A pseudo-likelihood fitter calls mple_fit_design(X, n_tot, n_one, names; context, extreme). That one function does the drop (∓Inf, standard error 0, p-value 0, the other coefficients fitted on the rows the dropped columns do not touch, n_kept for the BIC), the aliasing (a statistic that does not vary, or a linear combination of the ones before it, is NaN, R's NA), Newton and NetworkCore's separation verdict. It returns the verdict, so the caller never runs it again. Its note keyword replaces R ergm's closing sentences when the package's own R counterpart behaves differently.
  3. Monte-Carlo MLE. An MCMC estimator applies the drop instead of refusing:
    • the dropped columns become fixed ∓Inf coordinates, excluded from the step, the stopping rule and the covariance, and held at ±1e300 in the sampler, so the statistic never leaves its bound;
    • it warns R ergm's sentence (warn_boundary);
    • drop=false is the strict mode, an ArgumentError raised before any start;
    • the log-likelihood is NaN when a dropped statistic is dyad-dependent, because such a constraint has no dyad-independent reference to bridge from;
    • a dyad-independent aliased column is held at 0 (any value gives the same model) and reported NaN; a dyad-dependent one is refused unless init= is given.
  4. Reporting. Fixed coefficients are ∓Inf with standard error 0 and p-value 0; aliased ones are NaN. dof counts the finite coefficients. show and approximations carry a note naming them, and the parametric bootstraps refuse a point estimate that is not finite.
  5. Term types of other packages. A package declares the range of its own term types by adding attainable_range methods, never by keeping a separate range table. ERGMMulti declares its layer terms' ranges on a MultilayerNetwork, ERGMRank its rank terms' on a RankNetwork, and ERGMEgo maps each ego term to the ERGM term whose statistic it estimates.

A package may depart from point 3 where its sampler cannot hold a statistic at a bound, and must say why. ERGMRank's MCMLE refuses a boundary statistic, because single swaps do not connect the rankings that share an extreme value; its swap MPLE follows the convention.

ERGM.Extension.attainable_range — Function
attainable_range(term, net) -> (lo::Float64, hi::Float64)

The smallest and largest values the statistic of term can take on networks like net (the same vertex count and directedness): the minval/maxval that R ergm's terms declare. R's ergm.checkextreme.model compares the observed statistics with them. An observed value equal to lo fixes the coefficient at -Inf and one equal to hi at +Inf (R's default drop=TRUE); extreme_statistics makes that comparison. A side with no bound is -Inf or Inf, and (-Inf, Inf) declares nothing.

ERGM.jl's values are R's (read off ergm_model(...)$minval/maxval for ergm 4.12). Count statistics start at 0, degree-type counts end at the number of vertices, and edges and mutual end at the number of dyads. nodecov, absdiff, edgecov and any term without a method have no bound. One deliberate difference: R declares no lower bound for gwesp, gwdsp and gwnsp, but with a decay ≥ 0 (the only decays ERGM.jl accepts) they are weighted counts and cannot go below 0, so they get (0, Inf). On a network with no shared partner R fits a finite, unidentified coefficient (−0.31 on a 30-node perfect matching, after warning that the statistic is "not varying"); here it is fixed at -Inf, as a boundary found in the design already is.

The range matters where the pseudo-likelihood design cannot show the bound: a statistic whose change statistics are all zero on the observed network (a NodeMix cell of a singleton level, a Triangle on a network with no two-path) gives the design a flat direction, not a one-signed gradient.

Part of ERGM.Extension, and an extension point: a package adds a method for its own term type, or for its own network type, instead of keeping a separate range table. ERGMMulti declares its layer terms' ranges on a MultilayerNetwork, and ERGMRank its rank terms' ranges on a RankNetwork. ERGM.jl's own methods take an AbstractNetwork, so they never claim a bound on another package's network type.

Example

using ERGM
net = load_dataset(:florentine_marriage)             # 16 vertices, undirected
ERGM.Extension.attainable_range(Edges(), net)        # (0.0, 120.0)
ERGM.Extension.attainable_range(Degree(2), net)      # (0.0, 16.0)
ERGM.Extension.attainable_range(NodeCov(:wealth), net)   # (-Inf, Inf)
# A third-party term declares its own range
struct Isolates <: AbstractERGMTerm end
ERGM.Extension.attainable_range(::Isolates, net::AbstractNetwork) = (0.0, Float64(nv(net)))
ERGM.Extension.attainable_range(Isolates(), net)     # (0.0, 16.0)
source
ERGM.Extension.extreme_statistics — Function
extreme_statistics(terms, net) -> Vector{Tuple{Int,Symbol}}

The statistics whose observed value on net sits at an end of their attainable_range, as (position, :min) or (position, :max): R ergm's ergm.checkextreme.model. terms is a TermSet or a vector of terms, normally as materialized for net; the observed values are compute(term, net) at face value. Offset terms are fixed already and never listed.

This is the extreme seed that boundary_columns and mple_fit_design take. It dispatches through attainable_range and compute alone, so it works for any term and network type that has methods for both.

Part of ERGM.Extension.

Example

using ERGM
# A perfect matching on 10 vertices: five ties and no two-path, so the
# triangle count is at its minimum although no single dyad shows it
net = network(10; directed=false)
for i in 1:2:9
    add_edge!(net, i, i + 1)
end
ERGM.Extension.extreme_statistics([Edges(), Triangle()], net)   # [(2, :min)]
source
ERGM.Extension.boundary_columns — Function
boundary_columns(X, n_tot, n_one; fixed=[]) -> Vector{Tuple{Int,Symbol}}

The columns of a compressed pseudo-likelihood design whose statistic is at the boundary of its attainable range, as (column, :min) or (column, :max) sorted by column — R ergm's drop test, iterated to the exact limit of the pseudo-likelihood. X[r, :] holds the change statistics of a class of n_tot[r] identical dyads (or comparisons) of which n_one[r] are ties.

A column is at its minimum when every row with a positive change statistic is a non-tie and every row with a negative one is a tie (the mirror for the maximum); the sign pattern of the column does not matter. Its pseudo-log-likelihood then increases monotonically as the coefficient goes to -Inf (:min) or +Inf (:max), so no finite estimate exists. A perfectly separated nodematch (no within-group tie) is the textbook case.

Dropping a boundary column restricts the pseudo-likelihood to the rows it does not touch, and on that design another column can sit at its boundary (a mixed-sign nodecov: once it is fixed at -Inf the untouched dyads are all ties, so edges is at its largest value). The test is therefore repeated on the reduced design until nothing more is at a boundary.

fixed seeds the iteration with columns known to be at a boundary beforehand, normally extreme_statistics: a statistic whose observed value equals an end of its attainable_range. The design cannot show such a column when its change statistics are all zero (a Triangle on a network with no two-path). Seeds are included in the result.

Part of ERGM.Extension: every ERGM-family pseudo-likelihood runs this test, directly or through mple_fit_design.

Example

using ERGM
X = [1.0 0.0; 1.0 2.0]
# Column 2 is at its minimum (its only row is empty); once it is dropped the
# untouched row is all ties, so column 1 is at its maximum on the reduced design
ERGM.Extension.boundary_columns(X, [3.0, 2.0], [3.0, 0.0])   # [(1, :max), (2, :min)]
ERGM.Extension.boundary_columns(X, [3.0, 2.0], [1.0, 1.0])   # empty
# A column of zeros sits at no design boundary; seeded as one, it is listed
Z = [1.0 0.0; 1.0 0.0]
ERGM.Extension.boundary_columns(Z, [3.0, 2.0], [1.0, 1.0]; fixed=[(2, :min)])  # [(2, :min)]
source
ERGM.Extension.warn_boundary — Function
warn_boundary(names, boundary; context, note="R ergm reports the same",
              noun="dyads") -> nothing

R ergm's warning (ergm.checkextreme.model) for the statistics at the boundary of their attainable range, one warning per side, prefixed with context (the fitter's name). boundary is what boundary_columns returns, and names labels its columns.

  • note is the parenthesis after "no finite maximum pseudo-likelihood estimate exists". A package whose R counterpart does not drop (ergm.multi returns a finite value) says so here instead of restating the sentence.
  • noun names the rows the remaining coefficients are fitted on (ERGMRank's are "swap comparisons").

Part of ERGM.Extension: every ERGM-family estimator emits this one sentence. A fitter that runs on mple_fit_design gets it from that function, worded through its context, noun and note keywords.

Example

using ERGM
ERGM.Extension.warn_boundary(["edges", "nodematch.g"], [(2, :min)]; context="mple") === nothing  # true; warns
ERGM.Extension.warn_boundary(["edges"], [(1, :max)]; context="fit_ergm_rank",
                             noun="swap comparisons", note="ergm.rank has no drop")
source

Declaring the range of a new term

using ERGM
using ERGM: Extension

# A count of isolated vertices: between 0 and the number of vertices
struct Isolates <: AbstractERGMTerm end
ERGM.name(::Isolates) = "isolates"
ERGM.compute(::Isolates, net) = Float64(count(v -> degree(net, v) == 0, vertices(net)))
Extension.attainable_range(::Isolates, net::AbstractNetwork) = (0.0, Float64(nv(net)))

net = network(6; directed=false)
add_edge!(net, 1, 2); add_edge!(net, 3, 4); add_edge!(net, 5, 6)
Extension.extreme_statistics([Edges(), Isolates()], net)   # [(2, :min)]: no isolate

Pseudo-likelihood

ERGM.Extension.mple_fit_design — Function
mple_fit_design(X, n_tot, n_one, names; context="mple", estimate="MPLE",
                noun="dyads", note=(;), warn=true, extreme=[], offset=nothing,
                maxiter=100, tol=1e-8, verbose=false) -> NamedTuple

The pseudo-likelihood fit of a compressed binomial-row design, with R ergm's boundary and separation semantics. Row r of X holds the change statistics of a class of n_tot[r] identical dyads (or comparisons), of which n_one[r] are ties; names labels the columns. The steps are:

  1. Drop. A statistic at the boundary of its attainable range (boundary_columns, seeded with extreme) is fixed at ∓Inf with standard error 0. The other coefficients are fitted on the rows the dropped columns do not touch, which is R's drop=TRUE and the exact limit of the pseudo-likelihood. Pass the statistics whose observed value is at an end of their range as extreme (extreme_statistics): the design cannot show them when their change statistics are all zero.
  2. Aliasing. A statistic that does not vary on the rows fitted, or is a linear combination of the statistics before it, has no identifiable coefficient. It is reported as NaN (standard error NaN; R's glm gives NA) and the rest is fitted without it.
  3. Newton and separation. NetworkCore's newton_fit on logistic_derivatives fits the remaining columns from zero (or from a continuation start when there is an offset). NetworkCore's logistic_separation verdict is computed on the design actually fitted; a separated fit returns converged = false with its separated terms named, per the ecosystem's separation policy.

Warnings and their wording

Each step that finds something warns, unless warn=false (a bootstrap replicate's boundary is not a fact about the data). Every warning starts with context, the fitter's name. estimate names the estimator ("CMPLE", "swap-MPLE"), and noun the rows ("swap comparisons").

Each warning closes with R ergm's own sentence for the same design. note replaces it for a package whose R counterpart behaves differently. It is a NamedTuple with any of these keys:

  • boundary: the drop (R ergm: "R ergm reports the same");
  • not_varying: a statistic whose change statistics are all 0;
  • linear_dependence: a statistic in the span of the ones before it;
  • separation: the separation warning.

A key that is not given keeps R ergm's sentence; an unknown key is an ArgumentError.

Result

A NamedTuple with:

  • coefficients, std_errors, var_cov over all columns, with ∓Inf and SE 0 for the dropped ones and NaN for the aliased ones;
  • loglik (the maximised pseudo-log-likelihood), converged;
  • boundary, the dropped (column, :min | :max), and aliased, the NaN columns;
  • fitted, the columns Newton estimated, and kept_rows, the rows they were fitted on;
  • verdict, NetworkCore's SeparationVerdict on X[kept_rows, fitted] (its terms index fitted), or nothing when no column was left to fit;
  • separated and separated_terms (the names of the separated columns), read from verdict;
  • n_dyads, the sum of n_tot, and n_kept, the dyads the finite coefficients were estimated on (R's logLik nobs, the BIC sample size).

A caller that issues its own warnings passes warn=false and reads boundary, aliased and verdict from the result; it never needs to run the separation verdict a second time.

offset is a fixed per-row addition to the linear predictor (the contribution of terms whose coefficients are not estimated).

Part of ERGM.Extension: ERGM's own MPLE and MCMLE start, TERGM's CMPLE, ERGMMulti's MPLE and ERGMRank's swap MPLE are all this one fit.

Example

using ERGM
X = [1.0 0.0; 1.0 1.0]          # two dyad classes: edges only / edges + x
r = ERGM.Extension.mple_fit_design(X, [100.0, 50.0], [20.0, 25.0], ["edges", "x"]; context="my_fit")
r.converged                     # true
r.coefficients[1] ≈ log(20 / 80)            # true: a saturated design, closed-form logits
r.coefficients[2] ≈ log(25 / 25) - log(20 / 80)   # true
r.n_kept == 150                 # true: nothing dropped
r.verdict.separated             # false
# A statistic at the bottom of its range with all-zero change statistics
# (`extreme`), and one that never varies (aliased: NaN)
Z = [1.0 0.0 0.0; 1.0 0.0 0.0]
z = ERGM.Extension.mple_fit_design(Z, [100.0, 50.0], [20.0, 25.0], ["edges", "triangle", "x"];
                                   extreme=[(2, :min)], warn=false)
z.coefficients[2] == -Inf && isnan(z.coefficients[3])   # true
z.coefficients[1] ≈ log(45 / 105)                       # true
z.boundary                      # [(2, :min)]
z.aliased                       # [3]
# A package whose R counterpart does not drop words the warning itself
ERGM.Extension.mple_fit_design([1.0 0.0; 1.0 1.0], [3.0, 2.0], [1.0, 0.0], ["edges", "x"];
    context="my_fit", note=(boundary="my R package returns a finite value instead",))
source

Monte-Carlo MLE

The drivers behind mcmle, each written against a closure so that it knows nothing about networks. mcmle itself is mcmle_solve plus a sampler, and that sampler is mcmle_sampler: an estimator that solves moment equations on an ERGMModel (ERGMEgo's moment matching, the curved MCMLE) samples exactly as mcmle does — R ergm 4's SPDyad proposal and ESS-adaptive, continued chains — by passing its draw and resize to mcmle_solve or to its own iteration.

ERGM.Extension.mcmc_defaults — Function
mcmc_defaults(model::ERGMModel) -> (burnin, interval)
mcmc_defaults(n_dyads::Int) -> (burnin, interval)

THE dyad-scaled rule behind every sampler default in ERGM.jl: burnin = 20 × n_dyads toggles and interval = max(100, n_dyads ÷ 10) toggles between recorded draws, where n_dyads is the number of free (unmasked) dyads (n_observed_dyads). A Metropolis chain that proposes one dyad per step needs a number of steps proportional to the number of dyads to move every dyad a bounded number of times, so a fixed budget (the pre-0.2 10000/1000) was both far too small for a 500-node network and wastefully large for a 16-node one.

mcmle, the MPLE parametric bootstrap, mh_sample, sample_networks, simulate_ergm and gof all resolve a burnin=nothing/interval=nothing keyword through this one function, so the budgets cannot drift apart. Part of ERGM.Extension: every variant's sampler resolves its defaults through it too (ERGMCount converts the toggles to sweeps, ERGMRank counts swaps), so the family burns in alike.

Example

using ERGM
model = ERGMModel(ERGMFormula([Edges()]), load_dataset(:florentine_marriage))
ERGM.Extension.mcmc_defaults(model)     # (burnin = 2400, interval = 100): 120 dyads
ERGM.Extension.mcmc_defaults(124750)    # (burnin = 2495000, interval = 12475): n = 500
source
ERGM.Extension.mcmle_solve — Function
mcmle_solve(draw, θ0; labels, n_samples, maxiter=60, termination=:confidence,
             conv_precision=0.1, conv_confidence=0.99, conv_threshold=0.1,
             hotelling_alpha=0.05, gamma0=0.1, max_step_norm=5.0,
             max_n_samples=16 * n_samples, resize=nothing, take_step=true,
             adjust=nothing, target=nothing, verbose=false,
             context="MCMLE") -> NamedTuple

The Monte-Carlo MLE iteration, as mcmle runs it, written against a sampling callback so that it knows nothing about networks. Part of ERGM.Extension, for every estimator of the family that solves E_θ[g] = target by MCMC (TERGM's CMLE over constrained sample spaces and pooled transitions, ERGMEgo's moment matching, the rank and count MCMLEs). mcmle(::ERGMModel) itself is this function plus a sampler.

draw(θ, n) samples at coefficients θ with size request n and returns either an n × p matrix of statistics (one chain; the target is then the target keyword, default zeros — statistics measured relative to the observed ones), or a NamedTuple (samples, chain_lengths, target, obs_samples, obs_chain_lengths, aux) — of which only samples is required — for several chains, a per-draw target (the missing-data MCMLE's constrained chain, given as obs_samples) or anything the caller wants back (aux).

Every iteration draws, takes the Hummel-stepped Newton update (_hummel_step (internal); skipped when take_step == false, the iterations then only test), and — at full step length — applies the stopping rule: termination=:confidence is R ergm 4's equivalence test on the updated coefficients (confidence_test), :hotelling the t-ratio + Hotelling rule (mcmc_convergence). When the confidence test fails near the solution, or the estimating equations stop approaching the tolerance region, the next request is resize(n, boost) (default: min(max_n_samples, ceil(n·boost))). A singular sampled covariance stops the iteration with a warning prefixed context. adjust(θ, δ, iter) -> (δ′, allowed, stop), when given, is a family's own step rule, applied to the Hummel step before the stopping rule tests it: δ′ is the step taken, allowed == false forbids declaring convergence on it, and stop == true ends the iteration, unconverged, after it (the curved MCMLE's trust region on its decays).

Returns (coef, converged, iterations, step_length, termination_p, final, tests, vcov_fisher, vcov, se, mcmc_se): final is the draw the returned coefficients were stepped from when converged (the one whose test passed), otherwise a fresh draw at them; tests is mcmc_convergence on it; the covariance is mcmle_covariance's (Fisher + Monte-Carlo).

Example

using ERGM, Random, Statistics
# A toy exponential family: g ~ N(θ, I₂); solve E_θ[g] = (1, −2)
rng = Xoshiro(1)
draw(θ, n) = randn(rng, n, 2) .+ θ'
sol = ERGM.Extension.mcmle_solve(draw, [0.0, 0.0]; labels=["a", "b"], n_samples=2000,
                        target=[1.0, -2.0])
sol.converged                                   # true
isapprox(sol.coef, [1.0, -2.0]; atol=0.1)       # true
isapprox(sol.se, [1.0, 1.0]; atol=0.1)          # true: Σ = I, so the Fisher SEs are 1
source
ERGM.Extension.confidence_test — Function
confidence_test(samples, chain_lengths, target, δ; obs_samples=nothing,
                 obs_chain_lengths=nothing, precision=0.1, confidence=0.99)
    -> (converged, p_value, d2, boost)

R ergm's confidence MCMLE termination test for the estimate θ + δ, from statistics samples drawn at θ (importance-reweighted to θ + δ with weights ∝ exp(δ'g), the Monte-Carlo covariance of the mean inflated by the weights' Kish factor n·Σw²). d2 is the gate distance of the unweighted equation at θ on the tolerance scale (R tests only when d2 < 2); converged requires the reweighted equation inside the tolerance region and the Hotelling-T² equivalence p-value below 1 − confidence; boost is the factor by which R would enlarge the next sample when the test fails near the solution (min(critval/T², 2)).

Part of ERGM.Extension: an estimator that solves moment equations by MCMC (ERGMEgo, a TERGM CMLE) stops on the same rule as mcmle — pass the step it is about to take as δ (zeros to test the current coefficients), and multiply its next sample size by boost when the test fails. With obs_samples (a constrained chain whose mean is the target) the test is the two-sample one of the missing-data MCMLE.

Example

using ERGM, Random, Statistics
rng = Xoshiro(11)
draws = randn(rng, 4000, 2)                               # statistics sampled at θ
on = ERGM.Extension.confidence_test(draws, [4000], vec(mean(draws, dims=1)), zeros(2))
on.converged                                              # true: solved, with 99 % confidence
off = ERGM.Extension.confidence_test(draws, [4000], [0.5, 0.0], zeros(2))
off.converged                                             # false: 0.5 sd off target
few = ERGM.Extension.confidence_test(draws[1:40, :], [40], vec(mean(draws[1:40, :], dims=1)), zeros(2))
few.converged, few.boost > 1                              # (false, true): too few draws to be sure
source
ERGM.Extension.mcmle_covariance — Function
mcmle_covariance(samples, chain_lengths, obs_samples, obs_chain_lengths, p)
    -> (vcov_fisher, vcov, std_errors, mcmc_se)

The MCMLE covariance from the final sample(s). V = Σ̂⁻¹ with Σ̂ = cov(samples), or — under missing-data ML, when obs_samples (the constrained chain) is given — V = (Σ̂_free − Σ̂_obs)⁻¹, the Fisher information of the observed-data likelihood (Handcock & Gile 2010, Eq. 9), which is checked for positive definiteness first: a difference that is not PD (too few draws for the two chains to separate, or a degenerate model) yields NaN standard errors with a warning rather than a nonsense covariance. The Monte-Carlo term is V·Σ_mc·V with Σ_mc the Geyer covariance of the free chain's mean plus that of the constrained chain's mean (_mc_cov_of_mean). Any failure to invert yields NaNs with a warning.

Part of ERGM.Extension: a variant with its own MCMC MLE (ERGMRank's method=:mcmle) gets the same Fisher + Monte-Carlo covariance as mcmle, so its standard errors include the MCMC-error component rather than a locally re-derived Geyer covariance.

Example

using ERGM, Random
rng = Xoshiro(1)
samples = randn(rng, 2000, 2)             # statistics sampled at θ̂, one chain of 2000
V, Vtot, se, mcse = ERGM.Extension.mcmle_covariance(samples, [2000], nothing, nothing, 2)
isapprox(V, [1.0 0.0; 0.0 1.0]; atol=0.15)  # true: Σ̂⁻¹ of unit-variance draws
all(mcse .< se)                             # true: `se` includes the MC component
source
ERGM.Extension.ess_sample — Function
ess_sample(extend, target, m; interval, n_chains=1, maxruns=16)
    -> (samples, chain_lengths, interval)

The ESS-adaptive sample-size / interval chooser (R ergm's adaptive MCMC, MCMC.effectiveSize), written against a chain callback. Part of ERGM.Extension, so a variant's sampler adapts the way mcmle(...; effective_size=) does.

extend(c, n, interval) continues chain c (1 … n_chains) by n draws interval steps apart and returns their n × p statistics. Each chain first contributes m / n_chains draws at interval; while the effective sample size of the pooled draws (the smallest over statistics of the Geyer ESS, summed over chains) is below target, every chain drops every other draw, the interval doubles, and each chain draws the missing half at the new interval — so every round doubles the chain length at a constant stored size — at most maxruns times. Chains are extended on separate tasks. Returns the pooled m × p sample, the per-chain row counts and the final interval (start the next call at half of it, as R does).

Example

using ERGM, Random
# A strongly autocorrelated AR(1) "chain": thinning is what buys ESS
rng = Xoshiro(1); state = Ref(0.0)
function extend(c, n, interval)
    out = zeros(n, 1)
    for k in 1:n
        for _ in 1:interval; state[] = 0.95 * state[] + randn(rng); end
        out[k, 1] = state[]
    end
    return out
end
S, counts, interval = ERGM.Extension.ess_sample(extend, 150.0, 256; interval=1)
size(S), counts            # ((256, 1), [256])
interval >= 8              # true: the interval was doubled until ESS ≥ 150
source
ERGM.Extension.mcmle_sampler — Function
mcmle_sampler(model; effective_size=64, n_samples=1000,
              max_n_samples=16 * n_samples, n_free=length(model.formula.terms),
              burnin=nothing, interval=nothing, n_chains=1, proposal=:spdyad,
              toggleable=:free, missing=:error, rng=Random.default_rng(),
              verbose=false) -> (draw, resize, n_samples)

The sampler of mcmle, packaged as the draw/resize pair that mcmle_solve takes. Part of ERGM.Extension: an estimator that solves moment equations by MCMC on an ERGMModel (ERGMEgo's moment matching, the curved MCMLE) samples exactly as mcmle does, R ergm 4's design, by calling it.

  • ESS-adaptive (effective_size=64, R's MCMLE.effectiveSize; the default): the chains are continued from one call to the next (R's MCMLE.sequential): burned in for burnin toggles on the first call and 16 × interval afterwards, their thinning interval starting at interval ÷ 8 and halved from the last call's, then doubled until the effective sample size of the draws reaches the target (ess_sample). resize(n, boost) — the stopping rule's sample-size boost — multiplies the TARGET (capped at max_n_samples / 4) and returns the number of draws to store, min(max_n_samples, max(256, 32·n_free, 4·target)).
  • Fixed-size (effective_size=nothing): every call draws n statistics interval toggles apart after burnin toggles from model.network, split over n_chains chains as mcmle splits them; resize multiplies n by the boost, up to max_n_samples.

draw(θ, n; model=model) returns the NamedTuple (samples, chain_lengths) — a valid mcmle_solve draw, with the target given by its target= — at the full coefficient vector θ (an infinite entry holds its statistic at its bound). model= lets a family change the statistics between calls (the curved MCMLE's working statistics at the current decays); the chains always run on networks over model.network's vertex set. n_samples is the first request to pass to mcmle_solve. One seed per chain is drawn from rng at each call (a single chain uses rng itself), so the result does not depend on the thread count.

Example

using ERGM, Random
net = load_dataset(:florentine_marriage)
model = ERGMModel(ERGMFormula([Edges(), GWESP(0.5)]), net)
s = ERGM.Extension.mcmle_sampler(model; rng=Xoshiro(1))
S, chain_lengths = s.draw([-1.7, 0.4], s.n_samples)
size(S), chain_lengths                             # ((256, 2), [256]): one chain
sol = ERGM.Extension.mcmle_solve(s.draw, [-1.7, 0.4]; labels=["edges", "gwesp"],
        n_samples=s.n_samples, resize=s.resize, target=compute_all(model.formula.terms, net))
sol.converged                                      # true: mcmle's fit, by hand
s.resize(256, 2.0) >= 256                          # true: a boost raises the target ESS
source
ERGM.Extension.bridge_integrate — Function
bridge_integrate(mean_stats, θ_ref, θ; rungs=16, threaded=false) -> Float64

The path-sampling (bridge) integral log Z(θ) − log Z(θ_ref) of an exponential family, by the thermodynamic identity d/du log Z(θ(u)) = E_{θ(u)}[g]'(θ − θ_ref) along θ(u) = θ_ref + u·(θ − θ_ref), integrated by composite Simpson's rule (_bridge_quadrature (internal)) over rungs equal segments (an odd rungs is raised by one). mean_stats(θu, k) returns the (Monte-Carlo) mean of the statistics at the k-th grid point θu, k = 1, …, rungs + 1 — k lets the caller seed each rung deterministically. With threaded=true the rungs run on separate tasks (the callback must then be thread-safe; an error in a rung is rethrown as itself). Coordinates equal in θ and θ_ref — an infinite offset included — do not move.

Part of ERGM.Extension: mcmle's log-likelihood is θ'g_obs − (log Z(θ_ref) + this) with the exact dyad-independent log Z(θ_ref); a variant supplies its own sampler and its own exact reference (TERGM: the conditional logistic likelihood of a side's dyad-independent terms).

Example

using ERGM
# One Bernoulli dyad with statistic y ∈ {0, 1}: E_θ[y] = logistic(θ), and
# log Z(θ) = log(1 + e^θ), so the integral from 0 to 2 is known
exact = log1p(exp(2.0)) - log(2.0)
est = ERGM.Extension.bridge_integrate((θu, k) -> [1 / (1 + exp(-θu[1]))], [0.0], [2.0]; rungs=8)
isapprox(est, exact; atol=1e-5)        # true
source

The convergence tests a moment-matching estimator reports, ERGM.mcmc_convergence and its result type ERGM.MCMLEConvergence, and R's default-estimator rule ERGM.resolve_method are public names of ERGM itself.

Name map

Development versions declared these building blocks public under underscore names. They are no longer public; each is replaced by an ERGM.Extension name, with no deprecation alias (0.2.0 is the first release).

Development nameERGM.Extension nameNote
ERGM._collect_termscollect_terms
ERGM._validate_formulavalidate_formula
ERGM._materializematerializean extension point: add methods to Extension.materialize
ERGM._expand_termsexpand_terms
ERGM._refuse_two_mode, ERGM._refuse_self_loopsrequire_supported_networkmerged: the one check ERGMModel runs on a network; the two refusals stay internal
ERGM._n_dyadsn_observed_dyadsrenamed: REM.jl exports an unrelated n_dyads
ERGM._attainable_range (internal)attainable_rangenow a documented extension point
ERGM._extreme_statistics (internal)extreme_statisticsalso takes a vector of terms
ERGM._boundary_columns_iteratedboundary_columnsthe one-pass test is internal
ERGM._warn_boundarywarn_boundary
ERGM._mple_fit_designmple_fit_designadds note= and noun=; returns boundary, aliased, fitted, kept_rows and the separation verdict
ERGM._mcmc_defaultsmcmc_defaults
ERGM._mcmle_solvemcmle_solve
ERGM._confidence_testconfidence_test
ERGM._mcmle_covariancemcmle_covariance
ERGM._ess_sampleess_sample
ERGM._bridge_integratebridge_integrate
ERGM._separated, ERGM._warn_separatedremovedhad no caller; NetworkCore's logistic_separation and warn_separation