Types

MultilayerNetwork{D}, MultiERGMModel{D} and MultiERGMResult{D} carry the directedness of the layers as a type parameter, exactly as Network{T,D} and ERGM.ERGMModel{T,D} do; is_directed reads it.

ERGMMulti.MultilayerNetwork — Type
MultilayerNetwork{D}
MultilayerNetwork(n::Int; directed::Bool=true) -> MultilayerNetwork{directed}

Several relations ("layers") on the same actor set. All layers share the number of actors and the directedness D, which is a type parameter (as it is for Network{T,D}): layers is a concretely typed Vector{Network{Int,D}}, is_directed(m) reads D, and a layer of the other directedness is refused by add_layer!.

Fields

  • n::Int: Number of actors
  • layers::Vector{Network{Int,D}}: One network per layer
  • layer_names::Vector{Symbol}

Example

using ERGMMulti, NetworkCore
m = MultilayerNetwork(4; directed=true)
add_layer!(m, :friendship)
add_layer!(m, :advice)
add_layer_edge!(m, :friendship, 1, 2)
is_directed(m)                       # true
m isa MultilayerNetwork{true}        # true
eltype(m.layers) === Network{Int,true}   # true
layer_names(m)                       # [:friendship, :advice]
source
ERGMMulti.MultiNetwork — Type
MultiNetwork(networks::Vector{<:Network}, names::Vector{Symbol})

A collection of independent networks (possibly of different sizes and directedness), for descriptive pooling with CrossNetEdges. It never enters a fit: ergm.multi's covariate-driven Networks() models (N(~edges, ~x)) are not implemented, and ergm_multi accepts a MultilayerNetwork only.

Example

using ERGMMulti, ERGM, NetworkCore
a = network(4; directed=false); add_edge!(a, 1, 2)
b = network(6; directed=false); add_edge!(b, 1, 2); add_edge!(b, 3, 4)
mn = MultiNetwork([a, b], [:school1, :school2])
length(mn)                                    # 2
compute(CrossNetEdges(), mn)                  # 3.0 — edges pooled over the networks
source
ERGMMulti.MultilevelNetwork — Type
MultilevelNetwork

A hierarchical design: one network per level plus membership maps and explicit cross-level edges. The associated statistics (Nestedness, CrossLevelEdge, LevelHomophily) are descriptive.

Fields

  • level_nets::Vector{Network{Int}}: One network per level
  • membership::Vector{Dict{Int,Int}}: membership[l][node] = group, the level-(l+1) unit that level-l node node belongs to
  • cross_level_edges::Vector{NTuple{4,Int}}: (level_from, node_from, level_to, node_to) ties added via add_cross_level_edge!

Example

using ERGMMulti, ERGM, NetworkCore
people = network(5; directed=false)
add_edge!(people, 1, 2); add_edge!(people, 2, 3); add_edge!(people, 3, 4)
orgs = network(2; directed=false)
membership = [Dict(1 => 1, 2 => 1, 3 => 2, 4 => 2, 5 => 2)]   # person => organisation
ml = MultilevelNetwork([people, orgs], membership)
compute(LevelHomophily(1), ml)      # 2.0 — (1,2) and (3,4) stay inside one organisation
compute(Nestedness(1), ml)          # 0.666… — 2 of the 3 person ties
source
ERGMMulti.MultiERGMModel — Type
MultiERGMModel{D}
MultiERGMModel(terms, m::MultilayerNetwork{D}; offsets=Dict{Int,Float64}())

Multilayer ERGM specification: terms, data, and any per-term offsets. D is the directedness of the network (is_directed(model)), as for ERGM.ERGMModel{T,D}.

The constructor validates the formula against the data before anything is fitted, throwing an ArgumentError that names the fix:

  • every layer a term refers to (LayerEdges(3), InterlayerDependence(1, 3), WithinLayer(t, 3)) must exist — the message lists layer_names(m);
  • every WithinLayer(t, l) is checked against layer l with ERGM.jl's own formula validator (ERGM.Extension.validate_formula): a missing or partial vertex attribute, an EdgeCov of the wrong size, and an undirected-only term (Kstar, GWDegree, Degree) on a directed layer or a directed-only one (Mutual, OStar, ...) on an undirected layer are refused;
  • LayerMutual and MultiplexMutual are directed-only (requires_directed) and are refused on a MultilayerNetwork{false};
  • a bare ERGM.jl term (Mutual() where WithinLayer(Mutual(), l) was meant — ergm.multi's L(~mutual, ~A)) or a multilevel descriptive (Nestedness) has no multilayer change statistic and is refused with the WithinLayer fix spelled out (it used to fail at fit time with a MethodError);
  • no layer may contain a self-loop (a loops=true layer with none is fine): the statistics would count it but the within-layer design, nobs, the sampler and gof never touch the diagonal — the same refusal as ERGM.ERGMModel's ("R ergm warns "This network contains loops" here");
  • the network must have at least one layer and at least two actors — a MultilayerNetwork(0) or MultilayerNetwork(1) has no within-layer dyad, so there is nothing to estimate or simulate (it used to run Newton on an empty design and return coef = [0.0], NaN standard errors and two misleading non-convergence warnings);
  • offsets must index terms (1:length(terms)), an offset term must not expand into several statistics (pin each level/degree with its own single-statistic term instead), and at least one coefficient must be free.

(A layer selected by name inside a term — LayerEdges(:advice) — is an ArgumentError at the term's construction, before the model: terms carry indices, and the message gives findfirst(==(:advice), layer_names(m)).)

Attribute terms inside WithinLayer are then materialized (ERGM.Extension.materialize), so the stored terms — an ERGM.TermSet whose names are the direction-aware coefficient labels (name(term, m)) — may hold more statistics than terms were given (a multi-level NodeFactor, a Degree(0:2)); offsets keys are remapped to the expanded positions.

Fields

  • terms::ERGM.TermSet: the (materialized, expanded) statistics and their labels
  • network::MultilayerNetwork{D}
  • offsets::Dict{Int,Float64}: fixed coefficients, keyed by statistic index

Example

using ERGMMulti, ERGM, NetworkCore
m = MultilayerNetwork(4; directed=true)
add_layer!(m, :friendship); add_layer!(m, :advice)
model = MultiERGMModel([LayerEdges(1), WithinLayer(GWESP(0.5), 2)], m)
model.terms.names          # ["L(friendship)~edges", "L(advice)~gwesp.OTP.fixed.0.5"]
is_directed(model)         # true
try
    MultiERGMModel([LayerEdges(3)], m)
catch e
    occursin("layer 3", e.msg) && occursin(":advice", e.msg)   # true
end
source
ERGMMulti.MultiERGMResult — Type
MultiERGMResult{D}

Results from ergm_multi on a MultilayerNetwork{D}. Offset terms report their fixed coefficient with NaN standard error (and NaN rows/columns of vcov); loglik is the maximized pseudo-log-likelihood over the within-layer dyads.

se_type records how std_errors/vcov were ACTUALLY obtained — :hessian (the inverse negative pseudo-Hessian, which under-covers under dependence) or :bootstrap (the parametric bootstrap of ergm_multi(...; se=:bootstrap)) or :mcmc (a method=:mcmle fit; reported as :fisher). It is what NetworkCore.se_method(fit) reports, and what show reads before deciding whether the anticonservatism caveat still applies. Offset rows stay NaN under either option: a fixed coefficient carries no uncertainty.

boot_replicates is the n_boot × p_free matrix of refitted free coefficients under se=:bootstrap (a replicate whose refit did not converge is a NaN row, excluded from the covariance), nothing otherwise.

inference_withheld is true for an MPLE fit (method=:mple, se not given) of a dyad-dependent formula: the naive pseudo-likelihood standard errors under-cover, so coeftable/show report NaN z and p-values and confint refuses (see ergm_multi, "Standard errors"). An explicit se=:hessian or se=:bootstrap sets it to false.

method is :mple or :mcmle. For a method=:mcmle fit of a dyad-dependent formula loglik is the log-likelihood itself (path sampling), se_type is :mcmc, and mcmc holds the Monte-Carlo record: convergence (an ERGM.MCMLEConvergence), mc_std_errors and the final samples of the estimated statistics (estimated: their indices — the free ones, less any fixed at ∓Inf by a boundary statistic or held because not identifiable), n_samples, burnin, interval, loglik_mc_se, the start (MPLE) coefficients, the stopping rule (termination, termination_p, conv_confidence, conv_precision) and loglik_note (why the log-likelihood is NaN, or nothing); mcmc is nothing otherwise. The final sample is the one drawn at the last iterate, before the final step to the returned coefficients (as in R), so the t-ratios and Hotelling p-value in convergence describe that sample, not the returned coefficients: the convergence verdict is the stopping rule, which show, approximations and the non-convergence warning quote (under the default termination=:confidence, the equivalence test's p-value and the step length γ).

converged is false when the Newton iteration did not meet its tolerance or when the pseudo-likelihood has no finite maximum by separation (separated == true, R's "The MPLE does not exist!"): the coefficients are then the point where Newton stopped on its flat asymptote and are unreliable. separated_terms names the coefficients that carry the direction along which the pseudo-likelihood keeps increasing (NetworkCore's separation verdict); it is empty exactly when separated is false. A separated fit reports NaN z values, p-values and confidence intervals. A statistic at the boundary of its attainable range is handled differently — its coefficient is fixed at ∓Inf (see ergm_multi).

The full StatsAPI surface is implemented: coef, stderror, vcov, confint, loglikelihood, nobs, dof, aic, bic and coeftable (a NetworkCore.CoefficientTable — the table show prints). The shared result-metadata accessors (is_exact, se_method, approximations, ...) read the same fields.

Example

using ERGMMulti, ERGM, NetworkCore, Random
rng = Xoshiro(2)
m = MultilayerNetwork(12; directed=true)
add_layer!(m, :a); add_layer!(m, :b)
for l in 1:2, i in 1:12, j in 1:12
    i != j && rand(rng) < 0.25 && add_layer_edge!(m, l, i, j)
end
fit = fit_ergm_multi(m, [LayerEdges(1), LayerEdges(2)])
fit isa MultiERGMResult{true}      # true
fit.converged, fit.separated       # (true, false)
fit.separated_terms                # String[]
se_method(fit)                     # :hessian
is_exact(fit)                      # true — every term is dyad-independent
fit.boot_replicates === nothing    # true — no bootstrap was run
fit.inference_withheld             # false — dyad-independent: the Wald table is exact
approximations(fit)                # String[] — nothing to disclose
source

Construction and conversion

ERGMMulti.add_layer! — Function
add_layer!(m::MultilayerNetwork, name::Symbol;
           net::Union{Network,Nothing}=nothing) -> MultilayerNetwork

Add a layer, either empty or from an existing Network with matching size and directedness. A network of the other directedness is refused with an ArgumentError naming both (a MultilayerNetwork{true} holds directed layers only, and vice versa), and so is a two-mode (bipartite) network: ERGMMulti models one-mode layers only, and a bipartite layer would have its impossible within-mode pairs enumerated as observed non-ties by the within-layer MPLE (statnet's bipartite layer terms b1dspL, ... are not implemented). A layer that allows self-loops (loops=true) is accepted here; a layer that contains one is refused by MultiERGMModel.

Example

using ERGMMulti, NetworkCore
m = MultilayerNetwork(3; directed=false)
add_layer!(m, :a)                                    # empty undirected layer
net = network(3; directed=false); add_edge!(net, 1, 2)
add_layer!(m, :b; net=net)                           # from an existing network
try
    add_layer!(m, :c; net=network(3; directed=true))
catch e
    occursin("undirected", e.msg)                    # true
end
source
ERGMMulti.add_layer_edge! — Function
add_layer_edge!(m::MultilayerNetwork, layer, i, j) -> MultilayerNetwork

Add the edge (i, j) in the given layer (an index or a name) — add_edge! on that layer's Network, so on an undirected MultilayerNetwork{false} the pair is unordered and a repeated edge is a no-op.

An actor id outside 1:n (a mistyped id, a 0-based id from Python data) and a self-loop (i, i) on a layer built without loops=true are refused with an ArgumentError naming the ids and the range — never silently dropped, which is what add_edge!'s false return used to become. An unknown layer name or an out-of-range layer index is an ArgumentError too (layer_network).

Example

using ERGMMulti, NetworkCore
m = MultilayerNetwork(3; directed=true)
add_layer!(m, :friendship); add_layer!(m, :advice)
add_layer_edge!(m, :friendship, 1, 2)          # by name
add_layer_edge!(m, 2, 2, 3)                    # by index
ne(layer_network(m, :friendship)), ne(layer_network(m, :advice))   # (1, 1)
has_edge(layer_network(m, :advice), 3, 2)      # false — directed
try
    add_layer_edge!(m, :advice, 0, 2)          # 0-based id
catch e
    occursin("actor ids must lie in 1:3", e.msg)   # true
end
source
ERGMMulti.layer_network — Function
layer_network(m::MultilayerNetwork, layer) -> Network

The Network{Int,D} of a layer, by index or by name — the object itself, not a copy, so attributes and missing-dyad masks set on it are seen by the model. An unknown name, or an index outside 1:n_layers, is an ArgumentError naming the layers the network has (never a raw BoundsError).

Example

using ERGMMulti, NetworkCore
m = MultilayerNetwork(3; directed=false)
add_layer!(m, :friendship); add_layer!(m, :advice)
add_layer_edge!(m, :advice, 1, 3)
layer_network(m, 2) === layer_network(m, :advice)     # true — the same Network
has_edge(layer_network(m, :advice), 3, 1)              # true — undirected
try
    layer_network(m, :trust)
catch e
    occursin("no layer named :trust", e.msg)           # true
end
try
    layer_network(m, 5)
catch e
    occursin("layer index 5 out of range", e.msg)      # true
end
source
ERGMMulti.layer_names — Function
layer_names(m::MultilayerNetwork) -> Vector{Symbol}

The layer names in index order — the mapping behind every integer layer selector (LayerEdges(2) is the layer layer_names(m)[2], and the validation errors quote this list). Returns a copy; the network's own vector is not exposed.

Example

using ERGMMulti
m = MultilayerNetwork(3; directed=true)
add_layer!(m, :friendship); add_layer!(m, :advice)
layer_names(m)                                # [:friendship, :advice]
findfirst(==(:advice), layer_names(m))        # 2 — the index `LayerEdges(2)` selects
source
ERGMMulti.as_multilayer — Function
as_multilayer(nets::Vector{<:Network}, names::Vector{Symbol};
              report=false) -> MultilayerNetwork

Build a multilayer network from same-sized networks. The directedness of the first network sets the type parameter; every other layer must match (add_layer! refuses a mismatch). The layer networks are stored as given — not copied — so their vertex/edge/network attributes and their missing-dyad masks survive inside the MultilayerNetwork unchanged: the conversion is lossless, and with report=true it returns (m, ::ConversionReport) whose is_lossless is true.

Example

using ERGMMulti, NetworkCore
a = network(4; directed=true); add_edge!(a, 1, 2); set_missing_dyad!(a, 3, 4)
b = network(4; directed=true); add_edge!(b, 2, 3)
m, rep = as_multilayer([a, b], [:friendship, :advice]; report=true)
is_lossless(rep)                                   # true
n_missing_dyads(layer_network(m, :friendship))     # 1 — the mask is kept
source
ERGMMulti.combine_networks — Function
combine_networks(m::MultilayerNetwork; report=false) -> Network
combine_networks(m; report=true) -> (Network, ConversionReport)

The block-diagonal combined network of ergm.multi's Layer() construct: one network with n × L vertices, where vertex (l-1)·n + a is actor a's copy in layer l. Each vertex carries the :layer (layer index) and :actor (original actor ID) attributes, and every layer's edges are placed within its own block. Cross-block dyads are structurally empty — the model's dyad universe is the within-block dyads only.

The missing-dyad mask is preserved: a masked (unobserved) dyad (i, j) of layer l is masked at (off + i, off + j) of the combined network (off = (l-1)·n), so n_missing_dyads(combined) is the sum over the layers and split_by_layer restores every mask. An unobserved within-layer tie never becomes an observed absent one on the way through. The loops flag is carried when any layer allows self-loops.

What a block-diagonal network cannot hold is dropped and reported: the layers' own vertex attributes (only :layer/:actor are carried), edge attributes and network attributes. (A two-mode layer never gets this far: add_layer! refuses it.) With report=true the function returns (combined, ::ConversionReport) whose dropped_fields name each dropped attribute (and the layer it came from, in the reason), so a covariate that vanished is never silent.

Example

using ERGMMulti, NetworkCore
m = MultilayerNetwork(4; directed=true)
add_layer!(m, :friendship); add_layer!(m, :advice)
add_layer_edge!(m, :friendship, 1, 2)
set_missing_dyad!(layer_network(m, :advice), 2, 3)          # unobserved in layer 2
set_vertex_attribute!(layer_network(m, :friendship), :grp,
                      Dict(1 => "A", 2 => "A", 3 => "B", 4 => "B"))
c, rep = combine_networks(m; report=true)
nv(c), ne(c)                              # (8, 1)
is_missing_dyad(c, 6, 7)                  # true — actor 2→3 in block 2
n_missing_dyads(c)                        # 1
dropped_fields(rep)                       # [:grp]
source
ERGMMulti.split_by_layer — Function
split_by_layer(combined::Network, n::Int, L::Int;
               names=Symbol[], report=false) -> MultilayerNetwork

Inverse of combine_networks: recover the L layers of n actors from a block-diagonal combined network. Every edge must lie within a block (a cross-block edge is an ArgumentError), and so must every masked dyad: the mask of block l is remapped onto layer l (is_missing_dyad(layer_l, i, j) for a masked (off + i, off + j)), and a masked cross-block dyad is refused with the same ArgumentError as a cross-block edge — a dyad the block-diagonal model declares structurally empty cannot also be unobserved. The loops flag is carried to every layer.

With report=true returns (m, ::ConversionReport): the combined network's vertex attributes other than :layer/:actor, its edge attributes and its network attributes cannot be attributed to a layer and are dropped and named.

Example

using ERGMMulti, NetworkCore
m = MultilayerNetwork(4; directed=true)
add_layer!(m, :friendship); add_layer!(m, :advice)
add_layer_edge!(m, :advice, 4, 3)
set_missing_dyad!(layer_network(m, :advice), 2, 3)
c = combine_networks(m)
m2 = split_by_layer(c, 4, 2; names=[:friendship, :advice])
has_edge(layer_network(m2, :advice), 4, 3)              # true
is_missing_dyad(layer_network(m2, :advice), 2, 3)       # true — round trip
source
ERGMMulti.add_cross_level_edge! — Function
add_cross_level_edge!(m::MultilevelNetwork, level_from, node_from,
                      level_to, node_to)

Record a cross-level tie (e.g. a person–organization affiliation beyond the nesting structure); counted by CrossLevelEdge. A level the network does not have is an ArgumentError.

Example

using ERGMMulti, ERGM, NetworkCore
people = network(3; directed=false)
orgs = network(2; directed=false)
ml = MultilevelNetwork([people, orgs], [Dict(1 => 1, 2 => 1, 3 => 2)])
add_cross_level_edge!(ml, 1, 3, 2, 1)     # person 3 is also affiliated with organisation 1
compute(CrossLevelEdge(), ml)             # 1.0
try
    add_cross_level_edge!(ml, 1, 1, 3, 1) # there is no level 3
catch e
    occursin("level out of range", e.msg) # true
end
source