Types
ERGMEgo.EgoNetwork — Type
EgoNetwork{T}An ego-centric network observation.
Fields
ego::T: Ego IDalters::Vector{T}: Alter IDs (original IDs are preserved so that cross-ego alter overlap remains meaningful)alter_ties::Matrix{Bool}: Symmetric adjacency among alters (ego not included)ego_attrs::Dict{Symbol, Any}: Ego attributesalter_attrs::Dict{Symbol, Vector}: Alter attributes (column per attribute)
alter_ties must be square (n_alters × n_alters) and symmetric (ego networks are undirected); an asymmetric matrix is an ArgumentError. So is an alter listed twice (a duplicated ego–alter row in a survey's wide-to-long reshape, which would double the ego's degree and its homophily count in every target) and a true on the diagonal of alter_ties (an alter tied to itself, which n_alter_ties would silently drop by integer division): each is refused naming the ego and the alter. So are an ego listed as its own alter and an alter attribute whose length is not the number of alters. The constructor EgoNetwork(ego, alters, alter_ties; ego_attrs, alter_attrs) infers T from ego.
Example
using ERGMEgo
e = EgoNetwork(1, [10, 11, 12], Bool[0 1 0; 1 0 0; 0 0 0];
ego_attrs=Dict{Symbol,Any}(:group => "A"),
alter_attrs=Dict{Symbol,Vector}(:group => ["A", "B", "A"]))
n_alters(e), n_alter_ties(e) # (3, 1)
e # EgoNetwork{Int64}: ego 1, 3 alters, 1 alter–alter tie; ...
try EgoNetwork(2, [10, 11], Bool[0 1; 0 0]) catch e; e isa ArgumentError end # true — ArgumentError: alter_ties must be symmetric
try EgoNetwork(3, [10, 10], zeros(Bool, 2, 2)) catch e; e isa ArgumentError end # true — ArgumentError: ego 3 lists alter 10 twice
try EgoNetwork(4, [10, 11], Bool[1 0; 0 0]) catch e; e isa ArgumentError end # true — ArgumentError: self-tie on the diagonal
try EgoNetwork(5, [5, 11], zeros(Bool, 2, 2)) catch e; e isa ArgumentError end # true — ArgumentError: ego 5 is listed as its own alterERGMEgo.EgoData — Type
EgoDataCollection of ego networks with sampling information.
Fields
egos::Vector{EgoNetwork}: Individual ego network observationspopulation_size::Union{Int, Nothing}: Known or estimated population sizesampling_weights::Vector{Float64}: Per-ego sampling weights (design weights, ideally inverse inclusion probabilities)design::Dict{Symbol, Any}: Survey design information
EgoData(egos; population_size, sampling_weights, design) defaults to unit weights (one per ego; a weight vector of another length is an ArgumentError). Every weight must be a finite, non-negative number and the weights must sum to a positive number: a NaN, Inf or negative case weight (an NA inclusion probability, a 1/0), or an all-zero vector, is an ArgumentError naming the ego and the value — as ergm.ego/survey refuse — never a NaN target or a coefficient computed from a negative-weight Hájek mean. An EgoData iterates and indexes as its vector of egos.
design[:alter_ties_observed] == false records that the ties among alters were not collected (as_egodata sets it when no aatie_df is given). An uncollected tie is unobserved, not absent: every statistic that reads alter–alter ties (EgoTriangle, the shared-partner panel of gof) then refuses with an ArgumentError instead of counting zero triangles, and summary_stats(ed).mean_alter_ties is NaN. The design the weights describe is independent egos with case weights — there is no field for strata, clusters, a finite-population correction or replicate weights, and the design variance of a fit encodes none (see fit_ergm_ego).
Example
using ERGMEgo
e1 = EgoNetwork(1, [10, 11], zeros(Bool, 2, 2))
e2 = EgoNetwork(2, [11], zeros(Bool, 1, 1))
ed = EgoData([e1, e2]; population_size=50, sampling_weights=[2.0, 1.0])
length(ed), ed[2].ego # (2, 2)
[ego_degree(e) for e in ed] # [2, 1]
summary_stats(ed).mean_degree # 1.6667 — the weighted mean (2·2 + 1·1)/3
try EgoData([e1, e2]; sampling_weights=[1.0, -1.0]) catch e; e isa ArgumentError end # true — ArgumentError naming ego 2 and the weightERGMEgo.EgoERGMModel — Type
EgoERGMModel{T}Specification of an egocentric ERGM fit: ego terms, their ERGM counterparts, the ego data, the pseudo-population and population sizes, and the target statistics. The type parameter T is the vertex-ID type of the ego data, so data::EgoData{T} is concretely typed (fit.model.data is an EgoData{Int} for data built by as_egodata or simulate_ego_sample).
Fields
ego_terms::Vector{EgoTerm}: the ego terms of the model, in orderergm_terms::Vector{AbstractERGMTerm}: the terms of the ERGM simulated on the pseudo-population — the ERGM.jl term each ego term estimates, in order, followed byOffset(GWESP(0.0), …)when the network-size offset carries the triangle adjustment (seefit_ergm_ego)data::EgoData{T}: the ego data the fit was made onppopsize::Int: the realised pseudo-population sizepopsize::Int: the population size;1when it is unknown (ergm.ego's default — the coefficients are then per capita)targets::Vector{Float64}: target statistics on the pseudo-population scale (ego_target_stats)ppop_counts::Vector{Int}: how many pseudo-population vertices replicate each ego (round(ppopsize · wᵢ/Σw); they sum toppopsize)
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))
fit.model isa EgoERGMModel{Int} # true
fit.model.targets # [203.0, 163.0] — the census reproduces the network's ownERGMEgo.EgoERGMResult — Type
EgoERGMResult{T}Results from fit_ergm_ego; T is the vertex-ID type of the ego data (EgoERGMModel{T}).
Fields
model::EgoERGMModel{T}: the fitted specificationcoefficients: the coefficients for a population ofmodel.popsizemembers — per capita when the population size is unknown (popsize = 1). They are the free coefficients ofergm.ego's offset model, the numbersergm.egoprints below itsnetsize.adjrowstd_errors: standard errors,sqrt.(diag(vcov))vcov: the covariance of the coefficients,vcov_design + vcov_estimation—ergm.ego's decomposition (vcov(fit, sources="all"))vcov_design: the survey-design componentI⁻¹ Σ_design I⁻¹(times1 + n_egos/popsizewhense_type == :superpopulation), whereΣ_designis the design variance of the target statistics andIthe information (covariance of the statistics on the final MCMC sample) —ergm.ego'ssources="model"vcov_estimation: the Monte-Carlo estimation componentI⁻¹ / n_eff(= I⁻¹ Σ_mc I⁻¹withΣ_mc = I / n_effthe variance of the sampled mean,n_effthe Geyer effective sample size of the final sample) —ergm.ego'ssources="estimation". There is deliberately no standaloneI⁻¹term: the estimand is a population parameter estimated from a sample of egos, and the population network is not modelled as a draw from the ERGM (Krivitsky & Morris 2017, §4).netsize_adjustment: the coefficient of the network-size offset,-log(ppopsize/popsize)— R'snetsize.adjrow. The edges coefficient of the simulated pseudo-population iscoefficients[edges] + netsize_adjustment. (Before 0.2 this field held the negative of R's value.)converged: whether the termination rule passed (termination.rule): R ergm's confidence test by defaulttermination:(rule, p_value, precision, confidence, n_samples)— the rule, its p-value on the final sample (:confidencepasses when it is below1 − confidence;:hotellingwhen it is abovehotelling_alphaand every t-ratio is belowconv_threshold), the size of that sample, and the coefficient step the equivalence test was evaluated at (step: the full Newton step taken from a sample that passed in the loop; zeros for a fresh sample drawn at the returned coefficients aftermaxiter, and under:hotelling, which tests the sample at its own coefficients)mcmc_convergence::ERGM.MCMLEConvergence: the diagnostics of the same sample —(iterations, step_length, t_ratios, hotelling_p, n_eff): the iterations run, the last Hummel step length (1.0 for a full step), the per-statistic t-ratios, the Hotelling T² p-value and the Geyer effective sample sizesim_stats: that sample (pseudo-population scale, one column per ego term) — the oneconverged,termination,mcmc_convergenceandvcovdescribe. It is the sample that passed the test, from which the last step was taken (R'sergmdesign: no fresh draw after convergence), or, whenmaxiterwas exhausted, a fresh sample at the returned coefficients that decidedconvergedse_type::design(ergm.ego's standard errors),:superpopulation(the design component multiplied by1 + n_egos/popsize) or:bootstrap(a bootstrap over egos;vcov_designis then the bootstrap covariance lessvcov_estimation); seefit_ergm_egofor what each does and does not coverboot_replicates: then_boot × prefitted coefficients underse=:bootstrap(aNaNrow for a refit that did not converge),0 × potherwise
StatsAPI
coef, stderror, vcov, confint, coeftable, nobs (the number of egos — the independent units the design variance divides by; R's nobs() on the underlying ergm object counts pseudo-population dyads instead) and dof (the number of finite coefficients) are defined. loglikelihood, aic and bic are deliberately not: the fit is moment matching (objective(fit) == :moment) and no likelihood is ever evaluated, so there is no number to return.
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))
fit.converged # true
fit.mcmc_convergence.n_eff > 100 # true
coeftable(fit)["edges"].estimate == coef(fit)[1] # true — R's label
nobs(fit) # 205 egosHelpers
ERGMEgo.n_alters — Function
n_alters(ego_net::EgoNetwork) -> IntNumber of alters in an ego network.
Example
using ERGMEgo
e = EgoNetwork(1, [10, 11, 12], zeros(Bool, 3, 3))
n_alters(e) # 3ERGMEgo.ego_degree — Function
ego_degree(ego_net::EgoNetwork) -> IntThe ego's degree (number of alters) — the same number as n_alters, under the name the ERGM literature uses.
Example
using ERGMEgo
e = EgoNetwork(1, [10, 11], zeros(Bool, 2, 2))
ego_degree(e) # 2
ego_degree(EgoNetwork(2, Int[], Matrix{Bool}(undef, 0, 0))) # 0 — an isolate egoERGMEgo.alter_degree — Function
alter_degree(ego_net::EgoNetwork) -> Vector{Int}Degree of each alter within the ego network (not counting ego): the row sums of alter_ties, in the order of alters.
Example
using ERGMEgo
e = EgoNetwork(1, [10, 11, 12, 13], Bool[0 1 1 0; 1 0 0 0; 1 0 0 0; 0 0 0 0])
alter_degree(e) # [2, 1, 1, 0] — alter 10 is tied to 11 and 12ERGMEgo.n_alter_ties — Function
n_alter_ties(ego_net::EgoNetwork) -> IntNumber of (undirected) ties among alters — half the number of true entries of the symmetric alter_ties matrix.
Example
using ERGMEgo
e = EgoNetwork(1, [10, 11, 12], Bool[0 1 1; 1 0 0; 1 0 0])
n_alter_ties(e) # 2 — the ties 10–11 and 10–12ERGM.summary_stats — Function
summary_stats(ed::EgoData) -> NamedTupleDesign-weighted summary statistics for ego data: n_egos, the weighted mean_degree and weighted median_degree (the 0.5 quantile of the weight-estimated degree distribution with the midpoint convention, so it reduces to Statistics.median under unit weights and both centre statistics honour the same sampling weights), min_degree, max_degree, the weighted mean_alter_ties (NaN when the alter–alter ties were not collected), the unweighted total_alters (the number of ego–alter rows) and population_size. An EgoData with no egos (an as_egodata whose ego frame filtered down to zero rows, say) is an ArgumentError that says so, not a bare "reducing over an empty collection".
Example
using ERGMEgo
e1 = EgoNetwork(1, [10, 11, 12], Bool[0 1 0; 1 0 0; 0 0 0])
e2 = EgoNetwork(2, [10, 13], Bool[0 0; 0 0])
e3 = EgoNetwork(3, [11, 14, 15, 16], zeros(Bool, 4, 4))
ed = ego_design(EgoData([e1, e2, e3]); weights=[1.0, 1.0, 4.0])
summary_stats(ed).mean_degree # 3.5 — (3 + 2 + 4·4)/6
summary_stats(ed).median_degree # 4.0 — the design-weighted median; the unweighted one is 3.0ERGMEgo.as_egodata — Function
as_egodata(ego_df::DataFrame, alter_df::DataFrame;
aatie_df=nothing, kwargs...) -> EgoDataCreate EgoData from ergm.ego-style data frames:
ego_df: one row per ego (ego_idcolumn plus ego attributes)alter_df: one row per ego–alter pair (ego_id,alter_idplus alter attributes)aatie_df: optional alter–alter ties, one row per tie with columnsego_id,source_col,target_col(alter IDs). Without it the ties among alters are recorded as not collected (ed.design[:alter_ties_observed] == false):EgoTriangleand the shared-partner goodness-of-fit panel refuse such data rather than read "no triangles" from it. Pass an empty frame (with the three columns) when the ties were collected and there are none.
Keyword Arguments
ego_id::Symbol=:ego_id,alter_id::Symbol=:alter_idego_attrs::Vector{Symbol}=Symbol[]: Ego attribute columns fromego_dfalter_attrs::Vector{Symbol}=Symbol[]: Alter attribute columns fromalter_dfweight_col::Union{Symbol,Nothing}=nothing: Ego sampling-weight column inego_dfsource_col::Symbol=:src,target_col::Symbol=:dst: Alter-tie columnspopulation_size::Union{Int,Nothing}=nothing
Alter IDs are preserved (not relabeled), so cross-ego alter overlap remains available to estimate_popsize.
Every column the keywords name must exist in its frame: a missing ego_id/alter_id, ego or alter attribute, weight, or alter-tie column is an ArgumentError naming the column, the frame (ego_df, alter_df, aatie_df) and the columns that frame does have, instead of a KeyError from deep inside the row loop. A duplicated (ego, alter) row in alter_df (the wide-to-long reshape mistake, which would double that ego's degree in every statistic) and an aatie_df row tying an alter to itself are likewise ArgumentErrors naming the ego and the alter; so is a weight column holding a NaN, Inf or negative entry (see EgoData).
Example
using ERGMEgo, DataFrames
ego_df = DataFrame(ego_id=[1, 2], group=["A", "B"], w=[2.0, 1.0])
alter_df = DataFrame(ego_id=[1, 1, 2], alter_id=[10, 11, 10], group=["A", "B", "B"])
aatie_df = DataFrame(ego_id=[1], src=[10], dst=[11])
ed = as_egodata(ego_df, alter_df; aatie_df=aatie_df, ego_attrs=[:group],
alter_attrs=[:group], weight_col=:w)
ed.sampling_weights # [2.0, 1.0]
n_alter_ties(ed[1]) # 1
try as_egodata(ego_df, alter_df; ego_attrs=[:nope]) catch e; e isa ArgumentError end # true — ArgumentError: column :nope not found in ego_dfERGMEgo.ego_design — Function
ego_design(ed::EgoData; popsize=nothing, weights=nothing) -> EgoDataAttach survey-design information (population size and/or per-ego weights) to ego data, returning a new EgoData (the egos are shared, the weights replaced when given, the population size replaced when given). This is the whole of the design an EgoData can express: independent egos with case weights — there is no strata/cluster/finite-population-correction input.
popsize is the size of the population the egos were sampled from (ergm.ego's popsize), stored as ed.population_size. It is not the pseudo-population size, which is the ppopsize keyword of fit_ergm_ego.
Example
using ERGMEgo
e1 = EgoNetwork(1, [10, 11], zeros(Bool, 2, 2))
e2 = EgoNetwork(2, [11], zeros(Bool, 1, 1))
ed = ego_design(EgoData([e1, e2]); popsize=1000, weights=[3.0, 1.0])
ed.population_size, ed.sampling_weights # (1000, [3.0, 1.0])
estimate_popsize(ed) # 4.0 — Horvitz–Thompson: the weight sum