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...) -> EgoERGMResultFit an ERGM to egocentrically sampled data, following ergm.ego:
- Build a pseudo-population network: each ego's attributes replicated
round(ppopsize · wᵢ/Σw)times (ergm.ego'sppop.wt = "round"). The realised sizemis the sum of those counts; it can differ from the requestedppopsize(an@infosays 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. - Compute design-weighted target statistics scaled to
m. - 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 withsan), 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 isERGM.mcmle's (ERGM.Extension.mcmle_sampler), with R ergm 4's defaults, whichergm.egoruns 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 reacheseffective_size(R'sMCMLE.effectiveSize = 64). - Stop by R ergm's confidence rule (
termination=:confidence, asERGM.mcmle): the moment equation at the updated coefficients must lie, withconv_confidenceconfidence, inside the tolerance regionx'(conv_precision·Σ)⁻¹x ≤ 1; while it does not, the target effective sample size is raised (a fixed-size sample is enlarged), up tomax_n_samplesdraws.termination=:hotellingis the pre-0.2 rule (every t-ratio belowconv_thresholdand a Hotelling T² test not rejected athotelling_alpha). The sample that passes is the final sample:converged,termination,mcmc_convergence,sim_statsand the standard errors describe that one sample. Whenmaxiteris exhausted, one more sample is drawn at the returned coefficients and that sample decidesconverged. - 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:
popsizeunknown (not given, anded.population_sizeisnothing):popsize = 1, R's default. The edges coefficient is then per capita (network-size invariant, Krivitsky, Handcock & Morris 2011): it does not depend onppopsize, and the edges coefficient for a population ofNmembers iscoef − log(N). (Before 0.2 an unknown population size was silently set toppopsize, which put the coefficient on an arbitrary scale.)popsize = N: the coefficients are on the scale of a network ofNvertices.fit.netsize_adjustmentis the offset coefficient-log(m/N)(R'snetsize.adjrow), and the edges coefficient of the simulated pseudo-population iscoef(fit)[edges] + fit.netsize_adjustment.- A triangle or gwesp term (an order-3 statistic) makes the offset statistic
edges − transitiveties/3(R'soffset(netsize.adj(edges=1, transitiveties=-1/3))) wheneverm ≠ popsize: the pseudo-population model gainsOffset(GWESP(0.0), netsize_adjustment · (−1/3))(the last entry offit.model.ergm_terms;gwespat decay 0 counts the ties with at least one shared partner). Withpopsize = 1the triangle coefficient is therefore R's per-capita one, not the triangle coefficient of a plain ERGM on a network of sizem.
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=:designisergm.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 fractionf = n_egos/popsizegrows — 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=:superpopulationusesΣ = (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 probabilityf. It is approximate for unequal weights and for triangle and degree statistics, and it needs a knownpopsize(anArgumentErrorotherwise).se=:bootstrapresamples the egos with replacement (each drawn ego keeps its sampling weight), rebuilds the pseudo-population and the targets, and refits,n_boottimes, through the sharedNetworkCore.bootstrap_covloop. 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;ftimes the design sandwich is added for the double-counted ties whenpopsizeis 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 costsn_bootfits (refits run on the available threads; every resample and refit seed is drawn fromrngup front, so the result does not depend on the thread count). A refit that does not converge is aNaNrow offit.boot_replicates, excluded, warned about once and listed byapproximations(fit); the standard errors are then conditional on a finite refit and biased downward (the excluded replicates are the extreme ones), which the warning,showandapproximationssay.
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.83 | 0.94 / 0.95 |
| 100 (0.5) | 0.86 / 0.85 | 0.92 / 0.92 |
| 50 (0.25) | 0.91 / 0.87 | 0.93 / 0.91 |
| 20 (0.1) | 0.85 / 0.78 | 0.87 / 0.78 |
| 100 of 1000 (0.1), mean degree 70 | 0.93 / 0.84 | 0.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 isergm.ego's when the population size is unknown — the number of egos (with R's warning when the sampling weights are unequal: roundingn·wᵢ/Σwthen drops or merges egos; pass a multiple of the number of egos) — andpopsizewhen it is known and at most 1000. Above 1000 the default is ten times the number of egos, where R usespopsizeitself (a pseudo-population of that size is slow to simulate; passppopsize=popsizefor R's choice);showsays so when this appliesn_samples,burnin,interval: MCMC controls;nothing(the default) selects the package's dyad-scaled budget rule. Under ESS-adaptive samplingn_samplessets the capmax_n_samples,burninthe first burn-in andintervalthe starting interval (an eighth of it)maxiter::Int=60: maximum number of iterationstermination::Symbol=:confidence,conv_precision::Float64=0.1,conv_confidence::Float64=0.99,max_n_samples(default4·n_samples): the stopping rule, as inERGM.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 inmcmc_convergence(and the stopping rule undertermination=:hotelling)gamma0::Float64=0.1,max_step_norm::Float64=5.0: initial step length and the cap on the Euclidean norm of a stepproposal::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 availableeffective_size=64: ESS-adaptive sampling (R'sMCMLE.effectiveSize);nothingdraws a fixedn_samplesper iteration, each sample started afresh from the annealed pseudo-population (the pre-0.2 design;proposal=:tnt, effective_size=nothingreproduces it)se=nothing::design(ergm.ego's),:superpopulationor:bootstrap; the default is:superpopulationwhen the population size is known, else:design(see "Standard errors")n_boot::Int=100: bootstrap replicates underse=:bootstrapdrop::Bool=true: fix a coefficient whose target is at a bound of its statistic at∓Inf, asergm.egodoes;falserefuses 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 samerngstate 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.adjERGMEgo.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 # trueERGMEgo.estimate_popsize — Function
estimate_popsize(ed::EgoData; method=:horvitz_thompson) -> Float64Estimate 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 theRego–alter nominations are the second. A nominated alter is one of the othern − 1sampled egos with probability(n − 1)/(N − 1), whatever its degree, so withMthe nominations whose alter is a sampled ego,N̂ = 1 + (n − 1)(R + 2)/(M + 2)(the+2is Chapman's small-sample correction: a tie between two sampled egos is two nominations). It requires ego and alter IDs in one ID space (assimulate_ego_sampleandas_egodatakeep them) and an equal-probability sample: unequal sampling weights are anArgumentError, as isM = 0(no nominated alter is a sampled ego). The estimate is noisy whenMis 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 ...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 (
ArgumentErrornaming the fix): a network with masked (unobserved) dyads under the defaultmissing=: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;neighborswould 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 ofego_attrsthe network does not carry, or carries for only some vertices (the pre-0.2 code silently filledmissing, which a homophily term then miscounted). missing=:facereads 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, whenevern_egos < nv(net)),:vertex_attrs(each attribute not inego_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(undermissing=: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) # trueEvery 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-populationStatsAPI.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 # trueStatsAPI.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 partStatsAPI.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)StatsAPI.coeftable — Method
coeftable(result::EgoERGMResult) -> NetworkCore.CoefficientTableThe R-style coefficient table (Estimate, Std.Error, z value, Pr(>|z|)) as an inspectable NetworkCore.CoefficientTable — exactly the table show(result) prints, built from the same vectors (a method of StatsAPI.coeftable); 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] # trueStatsAPI.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) # narrowerStatsAPI.nobs — Method
nobs(result::EgoERGMResult) -> IntThe 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 dyadsStatsAPI.dof — Method
dof(result::EgoERGMResult) -> IntThe 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) # 2Result 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).
NetworkCore.is_exact — Method
is_exact(::EgoERGMResult) -> BoolAlways 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.
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.
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)) # trueDiagnostics
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) -> GOFResultGoodness-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:
"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."degree distribution"— the proportion of egos at each degree, overgof.ergm.ego's bins (GOF = "degree"):degree 0 … degree maxdeg−1plus an upper taildegree ≥ maxdeg, withmaxdeg = 2·max(K, 3)andKthe largest observed ego degree — R'sdegree(0:(maxdeg−1)) + degrange(maxdeg)— so every simulated ego falls in exactly one row. Whenmaxdeg ≥ ppopsize − 1every 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."edgewise shared partners"— the per-capita number of ties whose ends havekshared partners,k = 0 … 2·(max(K, 3) − 1)(GOF = "espartners", R'sesp(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])."ego summary statistics"— the mean degree and, when the ties among alters were collected, the mean number of alter–alter ties per ego (whatego_gofreads).
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 networksrng::AbstractRNG=Random.default_rng(): source of every random drawburnin,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's20·n_dyadsandmax(100, n_dyads ÷ 10))n_chains::Int=min(n_sim, 4): chains then_simnetworks are split over (ERGM.sample_networks, one seed per chain drawn fromrng); for a givenn_chainsandrngstate the result is bit-identical whatever the thread count (changingn_chainschanges the chain seeding, hence the draws)proposal::Symbol=:tnt: the Metropolis proposal (:tntor: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]) # trueERGMEgo.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) -> NamedTupleGoodness 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 # trueRenamed 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.
| Old | Now |
|---|---|
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 |