Estimation

fit_ergm_ego is the primary entry point; ergm_ego is the same function under ergm.ego's name.

ERGMEgo.fit_ergm_ego — Function
fit_ergm_ego(ed::EgoData, terms::Vector{<:EgoTerm}; kwargs...) -> EgoERGMResult

Fit an ERGM to egocentrically sampled data, following ergm.ego:

  1. Build a pseudo-population network: each ego's attributes replicated round(ppopsize · wᵢ/Σw) times (ergm.ego's ppop.wt = "round"). The realised size m is the sum of those counts; it can differ from the requested ppopsize (an @info says so) and is what the fit uses and reports. The composition depends on each ego's own weight only, never on the order of the egos.
  2. Compute design-weighted target statistics scaled to m.
  3. Move the pseudo-population toward the targets by simulated annealing and take the pseudo-likelihood estimate on it as the start (what R's ergm(target.stats=) does with san), then fit by MCMC moment matching with ERGM.jl's MCMLE machinery: at every iteration a sample is drawn at the current coefficients and a Hummel-style partial Newton step γ·Σ⁻¹(targets − ḡ) is taken, with the step length γ growing to 1 as the sampled cloud comes to cover the targets. The sampler is ERGM.mcmle's (ERGM.Extension.mcmle_sampler), with R ergm 4's defaults, which ergm.ego runs underneath: the SPDyad proposal, and ESS-adaptive sampling on one chain continued from iteration to iteration — each sample is extended, its thinning interval doubling, until its effective sample size reaches effective_size (R's MCMLE.effectiveSize = 64).
  4. Stop by R ergm's confidence rule (termination=:confidence, as ERGM.mcmle): the moment equation at the updated coefficients must lie, with conv_confidence confidence, inside the tolerance region x'(conv_precision·Σ)⁻¹x ≤ 1; while it does not, the target effective sample size is raised (a fixed-size sample is enlarged), up to max_n_samples draws. termination=:hotelling is the pre-0.2 rule (every t-ratio below conv_threshold and a Hotelling T² test not rejected at hotelling_alpha). The sample that passes is the final sample: converged, termination, mcmc_convergence, sim_stats and the standard errors describe that one sample. When maxiter is exhausted, one more sample is drawn at the returned coefficients and that sample decides converged.
  5. Report the coefficients with ergm.ego's network-size adjustment (below).

Network size: popsize, ppopsize and the offset

As in ergm.ego, the pseudo-population model carries the offset netsize.adj with coefficient -log(m/popsize), so the reported coefficients are those of a population of popsize members:

  • popsize unknown (not given, and ed.population_size is nothing): popsize = 1, R's default. The edges coefficient is then per capita (network-size invariant, Krivitsky, Handcock & Morris 2011): it does not depend on ppopsize, and the edges coefficient for a population of N members is coef − log(N). (Before 0.2 an unknown population size was silently set to ppopsize, which put the coefficient on an arbitrary scale.)
  • popsize = N: the coefficients are on the scale of a network of N vertices. fit.netsize_adjustment is the offset coefficient -log(m/N) (R's netsize.adj row), and the edges coefficient of the simulated pseudo-population is coef(fit)[edges] + fit.netsize_adjustment.
  • A triangle or gwesp term (an order-3 statistic) makes the offset statistic edges − transitiveties/3 (R's offset(netsize.adj(edges=1, transitiveties=-1/3))) whenever m ≠ popsize: the pseudo-population model gains Offset(GWESP(0.0), netsize_adjustment · (−1/3)) (the last entry of fit.model.ergm_terms; gwesp at decay 0 counts the ties with at least one shared partner). With popsize = 1 the triangle coefficient is therefore R's per-capita one, not the triangle coefficient of a plain ERGM on a network of size m.

Targets at a bound

A target at an end of the attainable range of its statistic — degree0 when no ego is an isolate, triangle or gwesp when no alter–alter tie is reported, a nodefactor level no ego or alter has — has no finite coefficient. As ergm.ego does (ergm's check of target.stats under its default drop=TRUE), its coefficient is fixed at -Inf (+Inf at the top), with a warning in ergm's words; the sampler holds the statistic at its bound, and the other coefficients are estimated given that. The fixed coefficient has standard error 0 (p-value 0); show and approximations(fit) name it, dof does not count it, and sim_stats and termination.step hold the estimated statistics only. drop=false refuses such a model with an ArgumentError instead, and se=:bootstrap refuses it (the bootstrap needs finite point estimates).

Standard errors

The standard errors are a sandwich, V(θ̂) = I⁻¹ Σ I⁻¹ + I⁻¹/n_eff: the variance Σ of the targets sandwiched by the inverse information, plus the Monte-Carlo estimation term (see EgoERGMResult). Two choices of Σ are offered, and fit.se_type records which one a fit used:

  • se=:design is ergm.ego's: Σ = Σ_design, the survey-design variance of the targets, which treats the egos as independent. They are not: a tie between two sampled egos is reported by both. Against the model (superpopulation) parameter, nominal 95 % intervals therefore cover less often as the sampling fraction f = n_egos/popsize grows — 80–85 % at a census in simulation — and at a census they are not zero either, so they are not finite-population intervals. Use it to reproduce R.

  • se=:superpopulation uses Σ = (1 + f)·Σ_design. For a statistic that is a sum over ties (edges, nodematch) under equal-probability sampling this is the exact variance of the targets under the model: each tie of a sampled ego is reported a second time with probability f. It is approximate for unequal weights and for triangle and degree statistics, and it needs a known popsize (an ArgumentError otherwise).

  • se=:bootstrap resamples the egos with replacement (each drawn ego keeps its sampling weight), rebuilds the pseudo-population and the targets, and refits, n_boot times, through the shared NetworkCore.bootstrap_cov loop. The spread of the refits carries what no sandwich does — the sampling error of the pseudo-population's attribute composition — besides the design variance and the Monte-Carlo error of a fit; f times the design sandwich is added for the double-counted ties when popsize is known. The standard errors are the normalised interquartile ranges of the replicates (IQR/1.349, with the replicates' correlations): resamples with an extreme composition are outliers that inflate the plain standard deviation. It costs n_boot fits (refits run on the available threads; every resample and refit seed is drawn from rng up front, so the result does not depend on the thread count). A refit that does not converge is a NaN row of fit.boot_replicates, excluded, warned about once and listed by approximations(fit); the standard errors are then conditional on a finite refit and biased downward (the excluded replicates are the extreme ones), which the warning, show and approximations say.

The default (se=nothing) is :superpopulation when the population size is known and :design when it is not (then f is unknown; for a small sampling fraction the two agree). Measured coverage of nominal 95 % intervals for edges / nodematch on a 200-actor population, 300 replicates each:

egos (f):design:superpopulation
200 (1.0)0.80 / 0.830.94 / 0.95
100 (0.5)0.86 / 0.850.92 / 0.92
50 (0.25)0.91 / 0.870.93 / 0.91
20 (0.1)0.85 / 0.780.87 / 0.78
100 of 1000 (0.1), mean degree 700.93 / 0.840.94 / 0.85

The correction removes the under-coverage that comes from the double-counted ties. What remains affects attribute terms: the attribute composition of the pseudo-population is itself estimated from the sample, a second-order effect no sandwich captures. It matters with few egos (where nodematch is also biased downward) and when the egos have many ties, so that the targets are precise relative to the composition. (With the composition held at its population value the 20-ego intervals cover 0.94 / 0.93.) se=:bootstrap captures it: on the hard cases it covers 0.94–0.97 / 0.98 (20 of 200 egos, mean degree 14, two runs of 150 and 100 replicates; default 0.85 / 0.80–0.84) and 0.98 / 0.99 (50 of 200 egos, mean degree 56, 80 replicates; default 0.89 / 0.84) — conservatively, its standard errors running 10–35 % above the sampling standard deviation. It costs n_boot fits, so it is not the default; show recommends it below 50 egos. show and approximations(fit) say what the reported standard errors are.

A fit that does not converge is loud: a warning quoting the termination test, the max t-ratio, the Hotelling p-value and the iteration count is emitted, converged is false, show prints the caveat under Converged: false, and approximations(fit) lists it. A singular covariance of the sampled statistics (collinear terms, a degenerate model) makes the fit step back toward the last coefficients that gave a regular sample; if that fails too the iterations stop with a warning and the standard errors are NaN.

ergm_ego is the same function under ergm.ego's name. The estimator and the network-size handling are ergm.ego's; the default standard errors are not when the population size is known (see "Standard errors": pass se=:design for ergm.ego's).

Keyword Arguments

  • popsize::Union{Int,Nothing}: population size (default: ed.population_size; when that is unknown too, 1 — per-capita coefficients)
  • ppopsize::Int: requested pseudo-population size. The default is ergm.ego's when the population size is unknown — the number of egos (with R's warning when the sampling weights are unequal: rounding n·wᵢ/Σw then drops or merges egos; pass a multiple of the number of egos) — and popsize when it is known and at most 1000. Above 1000 the default is ten times the number of egos, where R uses popsize itself (a pseudo-population of that size is slow to simulate; pass ppopsize=popsize for R's choice); show says so when this applies
  • n_samples, burnin, interval: MCMC controls; nothing (the default) selects the package's dyad-scaled budget rule. Under ESS-adaptive sampling n_samples sets the cap max_n_samples, burnin the first burn-in and interval the starting interval (an eighth of it)
  • maxiter::Int=60: maximum number of iterations
  • termination::Symbol=:confidence, conv_precision::Float64=0.1, conv_confidence::Float64=0.99, max_n_samples (default 4·n_samples): the stopping rule, as in ERGM.mcmle, and the cap on a sample's size (under ESS-adaptive sampling the target effective size is capped at a quarter of it)
  • conv_threshold::Float64=0.1, hotelling_alpha::Float64=0.05: the t-ratio and Hotelling tests reported in mcmc_convergence (and the stopping rule under termination=:hotelling)
  • gamma0::Float64=0.1, max_step_norm::Float64=5.0: initial step length and the cap on the Euclidean norm of a step
  • proposal::Symbol=:spdyad: the Metropolis proposal, R ergm 4's default (MCMC.prop = ~sparse + .triadic): tie/no-tie mixed with a shared-partner-focused proposal. :tnt (tie/no-tie) and :random (uniform dyad toggles) are available
  • effective_size=64: ESS-adaptive sampling (R's MCMLE.effectiveSize); nothing draws a fixed n_samples per iteration, each sample started afresh from the annealed pseudo-population (the pre-0.2 design; proposal=:tnt, effective_size=nothing reproduces it)
  • se=nothing: :design (ergm.ego's), :superpopulation or :bootstrap; the default is :superpopulation when the population size is known, else :design (see "Standard errors")
  • n_boot::Int=100: bootstrap replicates under se=:bootstrap
  • drop::Bool=true: fix a coefficient whose target is at a bound of its statistic at ∓Inf, as ergm.ego does; false refuses such a model (see "Targets at a bound")
  • rng::AbstractRNG=Random.default_rng(): source of every random draw (pseudo-population seeding, annealing and the MCMC chain); the same rng state gives a bit-identical fit whatever the global RNG holds

Example

using ERGMEgo, NetworkCore, Random
net = load_dataset(:faux_mesa_high)                 # 205 students, 203 ties
ed = simulate_ego_sample(net, 205; ego_attrs=[:Grade], rng=Xoshiro(1))   # a census, population_size = 205
fit = fit_ergm_ego(ed, [EgoEdges(), EgoNodeMatch(:Grade)]; rng=Xoshiro(1))
fit.converged                     # true
coef(fit)                         # ≈ [-6.03, 2.83] — ergm.ego with popsize = 205
stderror(fit)                     # ≈ [0.22, 0.25]: se=:superpopulation, the default when popsize is known
design = fit_ergm_ego(ed, [EgoEdges(), EgoNodeMatch(:Grade)]; se=:design, rng=Xoshiro(1))
stderror(design)                  # ≈ [0.16, 0.18] — ergm.ego's (0.178, 0.196)
percap = fit_ergm_ego(ed, [EgoEdges(), EgoNodeMatch(:Grade)]; popsize=1, ppopsize=205, rng=Xoshiro(1))
coef(percap)[1]                   # ≈ -0.71 = -6.03 + log(205): R's default output
percap.netsize_adjustment         # -5.323 = -log(205), R's netsize.adj
source
ERGMEgo.ergm_ego — Function
ergm_ego(ed::EgoData, terms; kwargs...)

R-faithful alias for fit_ergm_ego (the same function, so ergm_ego === fit_ergm_ego), matching the R ergm.ego package name — the ecosystem convention of one fit_<model> name and one statnet-style name.

Example

using ERGMEgo, NetworkCore, Random
ergm_ego === fit_ergm_ego            # true
net = load_dataset(:faux_mesa_high)
ed = simulate_ego_sample(net, 205; ego_attrs=[:Grade], rng=Xoshiro(1))
fit = ergm_ego(ed, [EgoEdges(), EgoNodeMatch(:Grade)]; rng=Xoshiro(1))   # R: ergm.ego(egor ~ edges + nodematch("Grade"))
fit.converged                        # true
source
ERGMEgo.estimate_popsize — Function
estimate_popsize(ed::EgoData; method=:horvitz_thompson) -> Float64

Estimate the population size from an ego sample.

  • :horvitz_thompson: The sum of the sampling weights. Only meaningful when the weights are inverse inclusion probabilities; with unit weights this is just the number of egos.

  • :capture_recapture: Lincoln–Petersen (Chapman's form) on nominated alters who are themselves sampled egos. The egos are the first capture — an equal-probability sample, so every member of the population, isolates included, is in it with the same probability — and the R ego–alter nominations are the second. A nominated alter is one of the other n − 1 sampled egos with probability (n − 1)/(N − 1), whatever its degree, so with M the nominations whose alter is a sampled ego, N̂ = 1 + (n − 1)(R + 2)/(M + 2) (the +2 is Chapman's small-sample correction: a tie between two sampled egos is two nominations). It requires ego and alter IDs in one ID space (as simulate_ego_sample and as_egodata keep them) and an equal-probability sample: unequal sampling weights are an ArgumentError, as is M = 0 (no nominated alter is a sampled ego). The estimate is noisy when M is small (its relative standard error is about √(2/M)).

    Before 0.2 this method split the egos into halves by input order and compared the two halves' alter sets; alters are a degree-biased sample and isolates are never named, so it estimated the number of non-isolates (about 25 % low on faux.mesa.high). The present estimator is within about 1 % of the truth on average there for 40 or more egos.

An unknown method is an ArgumentError naming it and listing the two methods above (:horvitz_thompson, :capture_recapture).

Example

using ERGMEgo
e1 = EgoNetwork(1, [2, 11, 12], zeros(Bool, 3, 3))    # names ego 2
e2 = EgoNetwork(2, [1, 13], zeros(Bool, 2, 2))        # names ego 1
e3 = EgoNetwork(3, [10, 14], zeros(Bool, 2, 2))
e4 = EgoNetwork(4, [12, 15], zeros(Bool, 2, 2))
ed = ego_design(EgoData([e1, e2, e3, e4]); weights=[10.0, 10.0, 5.0, 5.0])
estimate_popsize(ed)                                  # 30.0 — the weight sum
estimate_popsize(EgoData([e1, e2, e3, e4]); method=:capture_recapture)   # 9.25 — 4 egos, 9 nominations, 2 of them of sampled egos: 1 + 3·11/4
try estimate_popsize(ed; method=:capture_recapture) catch e; e isa ArgumentError end   # true — unequal weights
try estimate_popsize(ed; method=:lincoln_petersen) catch e; e isa ArgumentError end   # true — ArgumentError: unknown method :lincoln_petersen; expected :horvitz_thompson ... or :capture_recapture ...
source
ERGMEgo.simulate_ego_sample — Function
simulate_ego_sample(net::Network, n_egos::Int;
                    ego_attrs=Symbol[], missing=:error, report=false,
                    rng=Random.default_rng()) -> EgoData
simulate_ego_sample(net, n_egos; report=true) -> (EgoData, ConversionReport)

Draw an egocentric sample from a complete undirected, one-mode network: sample n_egos egos uniformly without replacement (rng) and record each ego's alters, the ties among those alters, and the vertex attributes named in ego_attrs for ego and alters. Alter IDs are the network's vertex IDs, so cross-ego overlap is preserved; population_size is nv(net).

This is the ecosystem's Network → EgoData conversion adapter and follows the conversion contract (NetworkCore.ConversionReport) and the missing-data contract (NetworkCore.require_observed):

  • Refused (ArgumentError naming the fix): a network with masked (unobserved) dyads under the default missing=:error — a masked dyad is unobserved, not absent, and the sample would read its face value as an observed ego–alter or alter–alter tie; a directed network (ego networks are undirected; neighbors would be read as out-neighbours only — symmetrise first, e.g. A = as_matrix(net); network_from_matrix(A .| A'; directed=false)); a two-mode network; an entry of ego_attrs the network does not carry, or carries for only some vertices (the pre-0.2 code silently filled missing, which a homophily term then miscounted).
  • missing=:face reads the stored face value of every masked dyad — an explicit, auditable opt-in, recorded in the report as :missing_dyads. supports_missing(simulate_ego_sample) == true, missing_policies(simulate_ego_sample) == (:error, :face).
  • Reported with report=true, which returns (ed, report): :edges (ties between unsampled vertices, whenever n_egos < nv(net)), :vertex_attrs (each attribute not in ego_attrs), :edge_attrs, :network_attrs, :loops (a network allowing self-loops: an ego's own loop is never read and alter self-loops are not recorded) and :missing_dyads (under missing=:face). A census of an undirected network with every vertex attribute requested and no edge/network attributes is lossless (is_lossless(report)).

Example

using ERGMEgo, NetworkCore, Random
net = load_dataset(:faux_mesa_high)                       # undirected, :Grade/:Race/:Sex
ed, rep = simulate_ego_sample(net, 205; ego_attrs=[:Grade, :Race, :Sex],
                              rng=Xoshiro(1), report=true)
is_lossless(rep)                                          # true — a census, every attribute kept
ed30, rep30 = simulate_ego_sample(net, 30; ego_attrs=[:Grade], rng=Xoshiro(1), report=true)
dropped_fields(rep30)                                     # [:edges, :vertex_attrs, :vertex_attrs]
try simulate_ego_sample(net, 30; ego_attrs=[:nope]) catch e; e isa ArgumentError end   # true — ArgumentError naming :nope and the attributes it has

masked = copy(net)
set_missing_dyad!(masked, 1, 2)
try simulate_ego_sample(masked, 30) catch e; e isa ArgumentError end   # true — ArgumentError: ... pass `missing=:face` ...
edf, repf = simulate_ego_sample(masked, 30; missing=:face, report=true)
:missing_dyads in dropped_fields(repf)                    # true
source

Every sampler of the package draws on one MCMC budget, scaled by the pseudo-population of m vertices: n_samples = max(400, min(3000, 20m)) draws per sample, and burnin/interval from ERGM.jl's dyad-scaled rule (ERGM.Extension.mcmc_defaults: 20·n_dyads and max(100, n_dyads ÷ 10) toggles over the m(m−1)/2 dyads). Pass n_samples, burnin or interval to override it. Under fit_ergm_ego's default ESS-adaptive sampling (effective_size = 64, through ERGM.Extension.mcmle_sampler) the chain is burned in once, its interval starts at an eighth of interval and adapts, each sample grows until it reaches the target effective size, and n_samples sets the cap max_n_samples = 4·n_samples.

simulate_ego_sample is the one routine of the package that can meet a masked dyad, and it declares its missing-data policy through the shared NetworkCore.jl traits: supports_missing(simulate_ego_sample) == true and missing_policies(simulate_ego_sample) == (:error, :face). fit_ergm_ego takes EgoData — a sample of reported local networks, not a sociomatrix — so no missing= keyword exists on it.

StatsAPI

coef, coefnames, stderror, vcov, confint, coeftable, nobs and dof are the surface the fit can honestly answer; coefnames and the rows of coeftable are ergm.ego's labels. loglikelihood, aic and bic deliberately have no methods (the fit is moment matching; no likelihood is evaluated).

StatsAPI.coef — Method
coef(result::EgoERGMResult) -> Vector{Float64}

The coefficients for a population of result.model.popsize members, in the order of the model's ego terms (per capita when the population size is unknown) — a method of StatsAPI.coef.

Example

using ERGMEgo, NetworkCore, Random
net = load_dataset(:faux_mesa_high)
ed = simulate_ego_sample(net, 205; ego_attrs=[:Grade], rng=Xoshiro(1))
fit = fit_ergm_ego(ed, [EgoEdges(), EgoNodeMatch(:Grade)]; rng=Xoshiro(1))
coef(fit) == fit.coefficients        # true
coef(fit)[1] + fit.netsize_adjustment    # the edges coefficient of the simulated pseudo-population
source
StatsAPI.coefnames — Method
coefnames(result::EgoERGMResult) -> Vector{String}

The coefficient labels, in coef(result) order — ergm.ego's labels (names(coef(fit)) in R without its offset(netsize.adj) row, which is result.netsize_adjustment here): edges, degree0, nodefactor.Race.Hisp, gwesp.fixed.0, … They are the row labels of coeftable(result). A method of StatsAPI.coefnames; the vector is a fresh copy.

Example

using ERGMEgo, NetworkCore, Random
net = load_dataset(:faux_mesa_high)
ed = simulate_ego_sample(net, 205; ego_attrs=[:Grade], rng=Xoshiro(1))
fit = fit_ergm_ego(ed, [EgoEdges(), EgoNodeMatch(:Grade)]; rng=Xoshiro(1))
coefnames(fit)                              # ["edges", "nodematch.Grade"]
coefnames(fit) == coeftable(fit).names      # true
source
StatsAPI.stderror — Method
stderror(result::EgoERGMResult) -> Vector{Float64}

The standard errors sqrt.(diag(vcov(result))): ergm.ego's design + MCMC-estimation decomposition (see EgoERGMResult) — a method of StatsAPI.stderror. NaN when the information matrix was singular.

Example

using ERGMEgo, NetworkCore, Random, LinearAlgebra
net = load_dataset(:faux_mesa_high)
ed = simulate_ego_sample(net, 205; ego_attrs=[:Grade], rng=Xoshiro(1))
fit = fit_ergm_ego(ed, [EgoEdges(), EgoNodeMatch(:Grade)]; rng=Xoshiro(1))
stderror(fit) ≈ sqrt.(diag(vcov(fit)))                    # true
all(stderror(fit) .> sqrt.(diag(fit.vcov_design)))        # true — the estimation term adds to the design part
source
StatsAPI.vcov — Method
vcov(result::EgoERGMResult) -> Matrix{Float64}

The covariance of the coefficients, vcov_design + vcov_estimation (ergm.ego's vcov(fit, sources="all")) — a method of StatsAPI.vcov.

Example

using ERGMEgo, NetworkCore, Random
net = load_dataset(:faux_mesa_high)
ed = simulate_ego_sample(net, 205; ego_attrs=[:Grade], rng=Xoshiro(1))
fit = fit_ergm_ego(ed, [EgoEdges(), EgoNodeMatch(:Grade)]; rng=Xoshiro(1))
vcov(fit) == fit.vcov_design .+ fit.vcov_estimation       # true
size(vcov(fit))                                           # (2, 2)
source
StatsAPI.coeftable — Method
coeftable(result::EgoERGMResult) -> NetworkCore.CoefficientTable

The 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); p-values come from the shared NetworkCore.z_pvalues, except for a coefficient fixed at ∓Inf (its target at a bound of its statistic: standard error 0, z = ∓Inf, p = 0, as R prints it). Rows can be read by index or by their label (coefnames, ergm.ego's).

Example

using ERGMEgo, NetworkCore, Random
net = load_dataset(:faux_mesa_high)
ed = simulate_ego_sample(net, 205; ego_attrs=[:Grade], rng=Xoshiro(1))
fit = fit_ergm_ego(ed, [EgoEdges(), EgoNodeMatch(:Grade)]; rng=Xoshiro(1))
tbl = coeftable(fit)
tbl["edges"].estimate == coef(fit)[1]          # true
tbl[2].p_value == z_pvalues(coef(fit), stderror(fit)).p[2]   # true
source
StatsAPI.confint — Method
confint(result::EgoERGMResult; level=0.95) -> Matrix{Float64}

Normal-theory confidence intervals θ̂ ± z_{1−α/2} · se, one row per coefficient (lower, upper) — a method of StatsAPI.confint. The standard errors are the design + MCMC-estimation decomposition of EgoERGMResult; see fit_ergm_ego, "Standard errors", for their measured coverage (se=:design, ergm.ego's, covers the model parameter less often than level as the sampling fraction grows).

Example

using ERGMEgo, NetworkCore, Random
net = load_dataset(:faux_mesa_high)
ed = simulate_ego_sample(net, 205; ego_attrs=[:Grade], rng=Xoshiro(1))
fit = fit_ergm_ego(ed, [EgoEdges(), EgoNodeMatch(:Grade)]; rng=Xoshiro(1))
ci = confint(fit)                            # 2×2
all(ci[:, 1] .< coef(fit) .< ci[:, 2])       # true
confint(fit; level=0.9)                      # narrower
source
StatsAPI.nobs — Method
nobs(result::EgoERGMResult) -> Int

The number of egos — the independent sampling units the design variance divides by. Note that R's nobs() on the ergm object underlying an ergm.ego fit counts the pseudo-population's dyads, not egos; this method reports the egocentric sample size.

Example

using ERGMEgo, NetworkCore, Random
net = load_dataset(:faux_mesa_high)
ed = simulate_ego_sample(net, 30; ego_attrs=[:Grade], rng=Xoshiro(1))
fit = fit_ergm_ego(ed, [EgoEdges()]; ppopsize=100, popsize=205, rng=Xoshiro(1))
nobs(fit)                            # 30 — egos, not the 4950 pseudo-population dyads
source
StatsAPI.dof — Method
dof(result::EgoERGMResult) -> Int

The number of estimated (finite) coefficients — a method of StatsAPI.dof.

Example

using ERGMEgo, NetworkCore, Random
net = load_dataset(:faux_mesa_high)
ed = simulate_ego_sample(net, 205; ego_attrs=[:Grade], rng=Xoshiro(1))
fit = fit_ergm_ego(ed, [EgoEdges(), EgoNodeMatch(:Grade)]; rng=Xoshiro(1))
dof(fit)                             # 2
source

Result metadata

The shared NetworkCore.fit_metadata protocol: what the fit actually did.

NetworkCore.objective — Method
objective(::EgoERGMResult) -> Symbol

:moment — the fit is MCMC moment matching (Newton iterations on targets − E_θ[g]), not a likelihood maximization: no likelihood, exact or approximate, is ever evaluated (which is why loglikelihood/aic/bic have no methods for an egocentric fit).

source
NetworkCore.is_exact — Method
is_exact(::EgoERGMResult) -> Bool

Always false. The estimator matches design-weighted target statistics against Monte-Carlo means simulated on a pseudo-population network of size ppopsize — two distinct approximations to the population likelihood, neither of which collapses to it for any formula.

source
NetworkCore.se_method — Method
se_method(::EgoERGMResult) -> Symbol

:bootstrap for a fit made with se=:bootstrap (a bootstrap over egos); otherwise :sandwich: V(θ̂) = I⁻¹ Σ_design I⁻¹ + I⁻¹/n_eff — the survey-design covariance of the target statistics sandwiched by the inverse MCMC information, plus the Monte-Carlo estimation term of the moment equations (ergm.ego's sources="model" and sources="estimation"). fit.se_type says whether Σ_design is ergm.ego's (:design) or carries the 1 + n_egos/popsize factor (:superpopulation). See approximations for what that design covariance does and does not encode.

source
NetworkCore.approximations — Method
approximations(result::EgoERGMResult) -> Vector{String}

What the reported numbers do and do not account for, as one sentence per item (the shared NetworkCore.approximations protocol, collected by fit_metadata): the Monte-Carlo nature of the moment-matching fit with the final sample's size, effective size, max t-ratio and Hotelling p; the pseudo-population construction and the network-size offset; the independent-egos assumption behind the design variance (no strata, clusters, finite-population correction, replicate weights or without-replacement inclusion probabilities) and the under-coverage that follows from ignoring that a tie between two sampled egos is reported twice (under se=:bootstrap: the resampling, the excluded refits and the robust scale); and the design + MCMC-estimation composition of the standard errors. A fit that did not converge lists the non-convergence caveat first — the same sentence show prints and the @warn quoted.

Example

using ERGMEgo, NetworkCore, Random
net = load_dataset(:faux_mesa_high)
ed = simulate_ego_sample(net, 205; ego_attrs=[:Grade], rng=Xoshiro(1))
fit = fit_ergm_ego(ed, [EgoEdges(), EgoNodeMatch(:Grade)]; rng=Xoshiro(1))
length(approximations(fit))                                   # 4
any(occursin("no strata, clusters", a) for a in approximations(fit))   # true
source

Diagnostics

gof is a method of the shared NetworkCore.gof generic and returns the shared NetworkCore.GOFResult; ego_gof is the legacy NamedTuple-returning form.

NetworkCore.gof — Method
gof(result::EgoERGMResult; n_sim=50, rng=Random.default_rng(),
    burnin=nothing, interval=nothing, n_chains=min(n_sim, 4),
    proposal=:tnt) -> GOFResult

Goodness-of-fit assessment of a fitted egocentric ERGM: pseudo-population networks are simulated at the fitted coefficients, an ego sample mirroring the observed design is drawn from each, and the observed design-weighted statistics are compared with their simulated distributions. The statistics are gof.ergm.ego's three diagnostics, plus two descriptive means:

  1. "model statistics" — every statistic of the model, per capita (GOF = "model"), labelled by the ego terms. These are the fitted targets: their p-values say whether the simulation reproduces what was fitted (a small one means the fit did not converge, or the chain does not mix), not whether the model fits.
  2. "degree distribution" — the proportion of egos at each degree, over gof.ergm.ego's bins (GOF = "degree"): degree 0 … degree maxdeg−1 plus an upper tail degree ≥ maxdeg, with maxdeg = 2·max(K, 3) and K the largest observed ego degree — R's degree(0:(maxdeg−1)) + degrange(maxdeg) — so every simulated ego falls in exactly one row. When maxdeg ≥ ppopsize − 1 every attainable degree is its own bin and there is no tail, as in R. An edges-only model matches the mean degree by construction but not the distribution around it.
  3. "edgewise shared partners" — the per-capita number of ties whose ends have k shared partners, k = 0 … 2·(max(K, 3) − 1) (GOF = "espartners", R's esp(0:maxesp)): where a model without a triangle term shows its lack of clustering. Present only when the ties among alters were collected (ed.design[:alter_ties_observed]).
  4. "ego summary statistics" — the mean degree and, when the ties among alters were collected, the mean number of alter–alter ties per ego (what ego_gof reads).

The simulated ego samples respect the design. From each simulated network one vertex is drawn for each observed ego, uniformly among the pseudo-population vertices that replicate it, and it carries that ego's sampling weight. The simulated column is therefore the same design-weighted estimator as the observed one, from a sample of the same size and weight distribution. (gof.ergm.ego compares the observed estimates with the statistics of the whole simulated network instead, which leaves the sampling variation of the observed column out of the reference distribution.)

This is a method of the shared NetworkCore.gof generic; it returns the shared NetworkCore.GOFResult (observed value, simulation envelope, and two-sided Monte-Carlo p-value per level from NetworkCore.mc_pvalue, the (1 + k)/(N + 1) estimator, so it is never exactly zero).

Every random draw — the pseudo-population, the MCMC chains and the ego samples — flows through rng, so two calls from the same rng state give identical simulated statistics, and the multi-chain sampler is seeded per chain from rng so the result does not depend on the thread count.

Keyword Arguments

  • n_sim::Int=50: number of simulated networks
  • rng::AbstractRNG=Random.default_rng(): source of every random draw
  • burnin, interval: MCMC controls of the network sampler; nothing (the default) selects the dyad-scaled rule the fit uses (the package's budget rule, ERGM.jl's 20·n_dyads and max(100, n_dyads ÷ 10))
  • n_chains::Int=min(n_sim, 4): chains the n_sim networks are split over (ERGM.sample_networks, one seed per chain drawn from rng); for a given n_chains and rng state the result is bit-identical whatever the thread count (changing n_chains changes the chain seeding, hence the draws)
  • proposal::Symbol=:tnt: the Metropolis proposal (:tnt or :random)

Example

using ERGMEgo, NetworkCore, Random
net = load_dataset(:faux_mesa_high)
ed = simulate_ego_sample(net, 205; ego_attrs=[:Grade], rng=Xoshiro(1))
fit = fit_ergm_ego(ed, [EgoEdges(), EgoNodeMatch(:Grade)]; rng=Xoshiro(1))
g = gof(fit; n_sim=20, rng=Xoshiro(5))
[s.name for s in g.statistics]                  # ["model statistics", "degree distribution", "edgewise shared partners", "ego summary statistics"]
g.statistics[1].labels                          # ["edges", "nodematch.Grade"]
g.statistics[1].observed ≈ fit.model.targets ./ 205   # true — the per-capita targets
g.statistics[2].labels[end]                     # "degree ≥ 26" — the tail bin, maxdeg = 2·max(13, 3); K = 13 observed
all(sum(g.statistics[2].simulated; dims=2) .≈ 1) # true — every simulated ego lands in one row
g.statistics[3].labels[1:2]                     # ["esp 0", "esp 1"]
g.statistics[1].simulated == gof(fit; n_sim=20, rng=Xoshiro(5)).statistics[1].simulated   # true
g.statistics[1].p_values[1] == mc_pvalue(g.statistics[1].simulated[:, 1], g.statistics[1].observed[1])   # true
source
ERGMEgo.ego_gof — Function
ego_gof(result::EgoERGMResult; n_sim=50, rng=Random.default_rng(),
        burnin=nothing, interval=nothing, n_chains=min(n_sim, 4),
        proposal=:tnt) -> NamedTuple

Goodness of fit for an egocentric ERGM as a NamedTuple (observed, simulated, p_values, n_sim) keyed by mean_degree / mean_alter_ties: observed the design-weighted sample statistics, simulated the means over the simulated ego samples, p_values the two-sided Monte-Carlo p-values (NetworkCore.mc_pvalue). mean_alter_ties is NaN throughout when the ties among alters were not collected.

A thin wrapper over gof — the same simulations, the same keywords, the same p-value estimator, read out of the GOFResult's "ego summary statistics" — so the two cannot disagree. Prefer gof, which returns the shared NetworkCore.GOFResult and also carries every model statistic, the degree distribution and the shared-partner distribution.

Example

using ERGMEgo, NetworkCore, Random
net = load_dataset(:faux_mesa_high)
ed = simulate_ego_sample(net, 205; ego_attrs=[:Grade], rng=Xoshiro(1))
fit = fit_ergm_ego(ed, [EgoEdges(), EgoNodeMatch(:Grade)]; rng=Xoshiro(1))
e = ego_gof(fit; n_sim=20, rng=Xoshiro(5))
g = gof(fit; n_sim=20, rng=Xoshiro(5))
e.p_values.mean_degree == g.statistics[end].p_values[1]   # true
e.observed.mean_degree == summary_stats(ed).mean_degree   # true
source

Renamed and removed names

Names and keywords of the development versions that 0.2.0 does not carry. Each is gone, not deprecated: the old spelling is an error.

OldNow
fit_ego_ergm(ed, terms)fit_ergm_ego(ed, terms) or ergm_ego(ed, terms)
fit_ergm_ego(…; max_iter=k)fit_ergm_ego(…; maxiter=k)
fit_ergm_ego(…; tol=x)removed (it was ignored): convergence is the termination rule, tuned by conv_precision and conv_confidence
ego_design(ed; ppopsize=N)ego_design(ed; popsize=N) — it sets the population size; the pseudo-population size is fit_ergm_ego's ppopsize