Types API Reference

This page documents the core data types in NetworkCore.jl.

Abstract Types

AbstractNetwork

NetworkCore.AbstractNetwork — Type
AbstractNetwork{T} <: Graphs.AbstractGraph{T}

Abstract base type for all network types. Extends Graphs.jl's AbstractGraph to provide StatNet-compatible network functionality. Network and BipartiteNetwork are its two concrete subtypes; write a method against AbstractNetwork to accept either.

Example

Network(3) isa AbstractNetwork              # true
BipartiteNetwork(2, 3) isa AbstractNetwork  # true
n_dyads(net::AbstractNetwork) = nv(net) * (nv(net) - 1)
n_dyads(Network(4))                         # 12
source

Network Types

Network

The module is NetworkCore; the type it exports is Network. So using NetworkCore; Network(5) works.

NetworkCore.Network — Type
Network{T,D}

Core network data structure representing a network with optional vertex and edge attributes.

Mirrors R's network class from the statnet network package, while implementing Graphs.jl's AbstractGraph interface for interoperability with the Julia graph ecosystem.

Type Parameters

  • T: Vertex ID type (typically Int)
  • D::Bool: Compile-time directedness. Network{T,true} is directed, Network{T,false} undirected, so Graphs.is_directed is truthful at the type level and Graphs.jl trait-dispatched generics use the correct (un)directed semantics. In user code you rarely need to spell out D: Network{Int} matches both, and network(n; directed=...) / Network{Int}(; directed=...) pick D from the keyword.

Storage design

The backing store is always a SimpleDiGraph{T} (field graph), regardless of D. Undirected networks store each edge in both arc directions (self-loops once); all Graphs.jl interface methods (ne, edges, degree, has_edge, …) account for this so each undirected edge is reported exactly once. This design was chosen over splitting the storage into SimpleGraph/SimpleDiGraph because downstream packages (SNA.jl, NDTV.jl, …) access net.graph directly and rely on it being a symmetric SimpleDiGraph for undirected networks; keeping the storage uniform makes the directedness change purely a type-level (trait) fix with no data-layout fallout.

Directedness is not a mutable runtime field: net.directed is a read-only property returning D, and attempting net.directed = x throws.

Fields

  • graph::SimpleDiGraph{T}: Underlying graph storage (symmetric when D == false)
  • bipartite::Union{Nothing, Int}: Number of vertices in first mode if two-mode, nothing otherwise
  • loops::Bool: Whether self-loops are allowed
  • multiple::Bool: Whether multiple edges between same vertices are allowed. NOT supported by the simple-graph backing store; passing true throws.
  • hyper::Bool: Whether hyperedges are allowed. NOT supported; passing true throws.
  • vertex_attrs::Dict{Symbol, Dict{T, Any}}: Vertex attributes by name
  • edge_attrs::Dict{Symbol, Dict{Tuple{T,T}, Any}}: Edge attributes by vertex pair
  • network_attrs::Dict{Symbol, Any}: Network-level attributes
  • missing_dyads::Set{Tuple{T,T}}: Dyads whose tie status is UNOBSERVED (statnet-style NA ties). See set_missing_dyad! for the semantics; manipulate through the missing-dyad API, not directly.
  • n_self_loops::Int: Number of self-loops stored (internal cache that makes ne O(1) on undirected networks with loops); maintained by the mutators.
Call Graphs.jl on the `Network`, never on `net.graph`

For an undirected network net.graph is a SimpleDiGraph holding both arcs of every edge, so a Graphs.jl algorithm run on it treats each tie as two directed arcs: Graphs.core_number(net.graph) doubles every core number, degree(net.graph) doubles every degree, betweenness and clustering are wrong the same way, and undirected-only algorithms (maximal_cliques, …) throw. Pass the Network itself (Graphs.core_number(net)), which reports the correct undirected semantics, or convert explicitly with Graphs.SimpleGraph(net) (an undirected copy) when an algorithm needs a concrete Graphs.jl type. Never mutate net.graph directly either: the mutators keep edge attributes, the missing-dyad mask, the two-mode partition and the self-loop count in step with it.

Example

# Create an empty directed network with 5 vertices
net = Network(5)

# `network(5)` is the equivalent statnet-style alias
net = network(5)

# Create an undirected network
net = network(5; directed=false)

# Add edges
add_edge!(net, 1, 2)
add_edge!(net, 2, 3)

# Set vertex attributes
set_vertex_attribute!(net, :name, Dict(1 => "Alice", 2 => "Bob", 3 => "Carol"))

# Set edge attributes
set_edge_attribute!(net, :weight, Dict((1,2) => 1.5, (2,3) => 2.0))
source

BipartiteNetwork

NetworkCore.BipartiteNetwork — Type
BipartiteNetwork{T,D}

A bipartite (two-mode) network with distinct vertex sets. D is the directedness of the wrapped network, carried in the type exactly as in Network{T,D}, so the network field is concretely typed; in user code BipartiteNetwork{T} (or plain BipartiteNetwork) matches both and the directed keyword picks D.

Fields

  • network::Network{T,D}: Underlying network
  • n_mode1::Int: Number of vertices in the first mode
  • n_mode2::Int: Number of vertices in the second mode

Vertices 1:nmode1 are in the first mode, (nmode1+1):(nmode1+nmode2) are in the second mode.

BipartiteNetwork(n₁, n₂; directed=true, loops=false) wraps network(n₁ + n₂; bipartite=n₁): the same two-mode semantics (within-mode edges are rejected by add_edge!, as_matrix returns the n₁ × n₂ incidence matrix, network_density takes discount_bipartite=), with the mode sizes carried as fields.

Example

b = BipartiteNetwork(2, 3; directed=false)
add_edge!(b, 1, 3)          # mode 1 → mode 2: true
add_edge!(b, 1, 2)          # within mode 1: false
b.n_mode1, b.n_mode2        # (2, 3)
size(as_matrix(b))          # (2, 3)
source

Constructors

network

NetworkCore.network — Function
network(n::Int; kwargs...) -> Network

Create a new network with n vertices. Alias for Network constructor to match R's network() function.

Keyword Arguments

  • directed::Bool=true: Whether the network is directed
  • bipartite::Union{Nothing,Int}=nothing: Number of vertices in first mode if bipartite
  • loops::Bool=false: Whether self-loops are allowed
  • multiple::Bool=false: Must be false; parallel edges are not supported
  • hyper::Bool=false: Must be false; hyperedges are not supported

Example

net = network(10; directed=false)
source

network_initialize

NetworkCore.network_initialize — Function
network_initialize(n::Int; kwargs...) -> Network

Initialize an empty network with n vertices. Alias matching R's network.initialize(); takes the same keywords as network.

Example

net = network_initialize(10; directed=false)
nv(net), ne(net)    # (10, 0)
source

Missing-Dyad Mask

Dyads whose tie status is unobserved (statnet-style NA ties). A masked dyad is not the same as an absent edge: structural queries keep reporting the stored face value, while statistical packages consult the mask to exclude the dyad from estimation. See the Missing Data guide.

NetworkCore.set_missing_dyad! — Function
set_missing_dyad!(net::Network, i, j) -> Network

Mark the dyad (i, j) as missing (unobserved): the analyst does not know whether the tie exists. This does not add or remove an edge — the network keeps a "face value" for the dyad (edge present or absent), which structural queries continue to report. Statistical packages built on NetworkCore.jl use the mask to exclude unobserved dyads from estimation (e.g. ERGM.jl drops masked dyads from the MPLE design matrix and never toggles them during MCMC).

For undirected networks the mask is symmetric: marking (i, j) also masks (j, i). For directed networks each ordered pair (arc) is masked independently. Marking an already-masked dyad is a no-op.

Throws ArgumentError if either vertex does not exist, or for a self-dyad (i, i) when the network does not allow loops.

See also is_missing_dyad, delete_missing_dyad!, clear_missing_dyads!, missing_dyads, n_missing_dyads.

Example

net = network(4)
add_edge!(net, 1, 2)
set_missing_dyad!(net, 3, 4)   # tie 3→4 is unobserved
is_missing_dyad(net, 3, 4)     # true
has_edge(net, 3, 4)            # false — the face value, NOT an observation
source
NetworkCore.is_missing_dyad — Function
is_missing_dyad(net::Network, i, j) -> Bool

Return whether the tie status of dyad (i, j) is missing (unobserved); see set_missing_dyad!. O(1). For undirected networks the check is symmetric in i and j.

Example

net = network(3)
set_missing_dyad!(net, 1, 2)
is_missing_dyad(net, 1, 2)    # true
is_missing_dyad(net, 2, 1)    # false — directed: each arc is masked separately
source
NetworkCore.delete_missing_dyad! — Function
delete_missing_dyad!(net::Network, i, j) -> Bool

Remove the missing-dyad mark from dyad (i, j), declaring its tie status observed again (at its current face value). Returns true if the dyad was masked, false if it was not.

Example

net = network(3)
set_missing_dyad!(net, 1, 2)
delete_missing_dyad!(net, 1, 2)    # true
delete_missing_dyad!(net, 1, 2)    # false — no longer masked
n_missing_dyads(net)               # 0
source
NetworkCore.clear_missing_dyads! — Function
clear_missing_dyads!(net::Network) -> Network

Remove every missing-dyad mark, declaring all dyads observed. This is the route a routine that refuses masked data (missing=:error) points at when the analyst has decided the face values are the data.

Example

net = network(3)
set_missing_dyad!(net, 1, 2)
set_missing_dyad!(net, 2, 3)
clear_missing_dyads!(net)
n_missing_dyads(net)    # 0
source
NetworkCore.missing_dyads — Function
missing_dyads(net::Network{T}) -> iterator of Tuple{T,T}

Iterator over the masked (unobserved) dyads of the network, in canonical form: (i, j) as marked for directed networks, minmax(i, j) for undirected. Iteration order is unspecified. The iterator reflects the live mask; do not add or delete marks while iterating. The Julia counterpart of R's is.na(net) / as.matrix(net) |> is.na.

Example

net = network(3; directed=false)
set_missing_dyad!(net, 3, 1)
collect(missing_dyads(net))    # [(1, 3)] — canonical minmax form
source
NetworkCore.n_missing_dyads — Function
n_missing_dyads(net::Network) -> Int

Number of masked (unobserved) dyads: ordered pairs for directed networks, unordered pairs for undirected (R's network.naedgecount).

Example

net = network(4)
set_missing_dyad!(net, 1, 2)
set_missing_dyad!(net, 3, 4)
n_missing_dyads(net)    # 2
source

Shared Result Presentation

The presentation layer used by every model package in the ecosystem: coefficient tables, the z → p-value step, p-value formatting, Monte-Carlo p-values, and the goodness-of-fit containers behind the single gof generic.

z_pvalues is the ONE z → two-sided-normal-p helper: it uses erfc(|z|/√2) so the tail stays accurate where the naive 2(1 − Φ(|z|)) cancels to a false 0.0, floors the result at floatmin(Float64) for finite z (a finite statistic never has a p-value of exactly zero), and keeps a NaN z — an undefined standard error — as a NaN p-value. The two-argument form builds the z statistics from estimates and standard errors first (NaN where the standard error is not strictly positive), so a show method is one call away from a coefficient table:

using NetworkCore

est = [1.20, -0.30, 0.80]
se  = [0.40,  0.10, 0.00]          # the third SE is undefined
zp  = z_pvalues(est, se)           # (z = [3.0, -3.0, NaN], p = [0.0027, 0.0027, NaN])
print_coeftable(stdout, ["a", "b", "c"], est, se, zp.p; z_values=zp.z)

z_pvalues([50.0])[1] == floatmin(Float64)   # true: floored, never 0.0

print_coeftable also renders a table without a standard-error column (std_errors=nothing, z_values mandatory, a three-title header) for a statistic that has none — a permutation test — and takes the display floor p_floor=, so a Monte-Carlo p-value with resolution 1/reps prints as "<0.001" rather than 0.0.

CoefficientTable is the inspectable form of the same table: the value every model package returns from coeftable(fit) — the StatsAPI verb, re-exported here so that all packages extend the ONE binding. It stores exactly the vectors print_coeftable consumes, fills z/p from z_pvalues when they are omitted, and its show is print_coeftable, so what a user inspects is what the fit prints:

using NetworkCore

tbl = CoefficientTable(["edges", "mutual"], [-2.1, 1.3], [0.2, 0.4])
tbl.p_values == z_pvalues([-2.1, 1.3], [0.2, 0.4]).p   # true
tbl["mutual"].estimate                               # 1.3
length(tbl)                                          # 2
[r.name for r in tbl]                                # ["edges", "mutual"]
tbl                                                  # prints the R-style table

# A permutation test: no Std.Error column, a t statistic, resolution 1/1000
CoefficientTable(["intercept", "x"], [0.12, 0.85], nothing;
                 z_values=[1.02, 6.7], p_values=[0.31, 0.0],
                 header=("Estimate", "t value", "Pr(>=|t|)"), p_floor=1/1000)
NetworkCore.print_coeftable — Function
print_coeftable(io::IO, names, estimates, std_errors, p_values;
                z_values=nothing, digits::Int=4,
                signif_codes::Bool=true, legend::Bool=signif_codes,
                header=nothing, p_floor::Real=1e-16)

Print an R-style coefficient table with aligned columns and significance codes. This is the shared presentation layer for every model package built on NetworkCore.jl — call it from a result type's Base.show method, passing the coefficient names and vectors (or show a CoefficientTable, which delegates here).

All vectors must have equal length. Column widths adapt to the widest entry, so long term names and large coefficients stay aligned. p-values are rendered with format_pvalue (so an underflowed p-value prints as "<1e-16", never 0.0).

Arguments

  • names: coefficient names (strings or symbols), left-aligned first column
  • estimates, p_values: equal-length numeric vectors
  • std_errors: standard errors, or nothing for a table without a Std.Error column (a permutation test such as SNA.netlm has a test statistic and a p-value but no standard error). With nothing, z_values must be given explicitly (there is nothing to divide by) and the table has three numeric columns.

Keyword Arguments

  • z_values: test statistics; defaults to estimates ./ std_errors (required when std_errors === nothing)
  • digits::Int=4: decimal places for the numeric columns
  • signif_codes::Bool=true: append ***/**/*/. per row
  • legend::Bool=signif_codes: print the significance-code legend below the table (pass legend=false when printing several tables in one report)
  • header: the column titles — a 4-tuple ("Estimate", "Std.Error", "z value", "Pr(>|z|)") (the default) with standard errors, a 3-tuple ("Estimate", "z value", "Pr(>|z|)") without; override e.g. to label the statistic "t value" / "Pr(>|t|)" for a t-based model. A tuple of the wrong length is an ArgumentError.
  • p_floor::Real=1e-16: the display floor forwarded to format_pvalue. A Monte-Carlo or permutation p-value has a resolution of 1/reps and is never exactly zero in truth, so pass p_floor=1/reps and a zero count prints as "<0.001" (for 1000 replicates), never 0.0.

A method without io prints to stdout.

Examples

print_coeftable(stdout,
                ["edges", "gwesp.fixed.0.5"],
                [-3.2145, 0.8113],
                [0.1936, 0.2854],
                [1.2e-62, 0.0045])

# A permutation test: no Std.Error column, a t statistic, resolution 1/1000
print_coeftable(stdout, ["intercept", "x"], [0.12, 0.85], nothing, [0.31, 0.0];
                z_values=[1.02, 6.7],
                header=("Estimate", "t value", "Pr(>=|t|)"), p_floor=1/1000)
source
NetworkCore.CoefficientTable — Type
CoefficientTable(names, estimates, std_errors;
                 z_values=nothing, p_values=nothing, header=nothing,
                 p_floor=1e-16)

The ecosystem's generic coefficient table: the value every model package returns from StatsAPI.coeftable(fit). It holds exactly the vectors print_coeftable consumes — names, estimates, standard errors (or nothing for a statistic without one, e.g. a permutation test), test statistics, p-values — plus the column titles and the p-value display floor, so show renders it through print_coeftable and prints identically to the fit's own show method.

When z_values/p_values are omitted they are filled from z_pvalues(estimates, std_errors) — z = NaN where the standard error is not strictly positive, p floored at floatmin, never 0.0. With std_errors === nothing, z_values is required and p_values defaults to z_pvalues(z_values). header defaults to the four R-style titles (three without standard errors) and must have the matching length. All vectors must have the same length (ArgumentError otherwise).

The name is CoefficientTable, not CoefTable: StatsBase.CoefTable exists, and using NetworkCore, StatsBase must never leave the name ambiguous. This one carries no StatsBase dependency and is a plain struct any package can build.

Fields

  • names::Vector{String}, estimates::Vector{Float64}, std_errors::Union{Nothing, Vector{Float64}}, z_values::Vector{Float64}, p_values::Vector{Float64}
  • header::Tuple{Vararg{String}}: column titles (length 4, or 3 without SEs)
  • p_floor::Float64: the floor show passes to format_pvalue

Interface

  • length(tbl): number of coefficients
  • tbl[i]: row i as a NamedTuple (name, estimate, std_error, z_value, p_value) (std_error === nothing in a table without SEs)
  • tbl["edges"] / tbl[:edges]: the row with that name (KeyError if absent)
  • iteration yields the rows in order
  • show(io, tbl): print_coeftable with the stored header and floor

Examples

using NetworkCore

tbl = CoefficientTable(["edges", "mutual"], [-2.1, 1.3], [0.2, 0.4])
tbl.p_values == z_pvalues([-2.1, 1.3], [0.2, 0.4]).p   # true
tbl["mutual"].estimate                               # 1.3
length(tbl)                                          # 2
tbl                                                  # prints the R-style table

# A permutation test: no standard errors, a t statistic, resolution 1/1000
CoefficientTable(["intercept", "x"], [0.12, 0.85], nothing;
                 z_values=[1.02, 6.7], p_values=[0.31, 0.0],
                 header=("Estimate", "t value", "Pr(>=|t|)"), p_floor=1/1000)

See also coeftable, check_statsapi.

source
StatsAPI.coeftable — Function
coeftable(fit) -> CoefficientTable

The StatsAPI.coeftable generic, re-exported by NetworkCore.jl so that every model package in the ecosystem extends the ONE binding (NetworkCore.coeftable === StatsAPI.coeftable) and using NetworkCore, REM — or any other pair — leaves the verb defined. NetworkCore.jl adds no method: each package defines StatsAPI.coeftable(fit::ItsOwnResult) = CoefficientTable(...) on its own result type, feeding it the same vectors its show method passes to print_coeftable, so the table a user inspects is the table they see printed.

This is one verb of the ecosystem's StatsAPI surface: coef, stderror, vcov, confint, loglikelihood, nobs, dof, aic, bic, coeftable and coefnames, all defined on the fitted-model type wherever the quantity exists. check_statsapi reports which of them a result type implements.

Example

using NetworkCore
import StatsAPI

struct MyFit
    est::Vector{Float64}
    se::Vector{Float64}
end
StatsAPI.coeftable(f::MyFit) = CoefficientTable(["a", "b"], f.est, f.se)

tbl = coeftable(MyFit([1.2, -0.3], [0.4, 0.1]))
tbl["a"].p_value ≈ z_pvalues([3.0])[1]   # true
source
StatsAPI.coefnames — Function
coefnames(fit) -> Vector{String}

The StatsAPI.coefnames generic: the coefficient labels of a fitted model, in coef(fit) order, as R's names(coef(fit)). Re-exported by NetworkCore.jl for the same reason as coeftable: every model package extends the ONE binding (NetworkCore.coefnames === StatsAPI.coefnames, also the binding StatsBase and GLM export), so using NetworkCore, ERGM, REM leaves the verb defined. NetworkCore.jl adds no method. A package defines StatsAPI.coefnames(fit::ItsOwnResult) returning the same labels its coeftable(fit).names holds; check_statsapi checks that they agree.

Example

using NetworkCore
import StatsAPI

struct MyFit
    est::Vector{Float64}
    se::Vector{Float64}
end
StatsAPI.coefnames(::MyFit) = ["edges", "mutual"]
StatsAPI.coef(f::MyFit) = f.est
StatsAPI.coeftable(f::MyFit) = CoefficientTable(coefnames(f), f.est, f.se)

fit = MyFit([-1.2, 0.8], [0.3, 0.2])
coefnames(fit)                                  # ["edges", "mutual"]
coefnames(fit) == coeftable(fit).names          # true
check_statsapi(fit; required=(:coef, :coeftable, :coefnames))
source
NetworkCore.z_pvalues — Function
z_pvalues(z::AbstractVector{<:Real}) -> Vector{Float64}
z_pvalues(estimates::AbstractVector{<:Real},
          std_errors::AbstractVector{<:Real}) -> NamedTuple{(:z, :p)}

Two-sided normal (Wald) p-values 2 · P(Z ≥ |z|) for a vector of z statistics, computed as erfc(|z| / √2) so that the tail is accurate far beyond where the naive 2 · (1 − Φ(|z|)) cancels to a false 0.0 (around |z| ≈ 8.3). The result is floored at floatmin(Float64) for finite z (max(p, floatmin), so it is also monotone through the subnormal range) — a finite statistic never has a p-value of exactly zero — while ±Inf gives 0.0 and a NaN z (an undefined standard error) stays NaN.

The two-argument form first forms z = estimate / std_error, with z = NaN wherever the standard error is not strictly positive (zero, negative or NaN — the coefficient's uncertainty is undefined, so its test is too), and returns the NamedTuple (z = ..., p = ...) ready for print_coeftable.

This is the ONE z → p helper of the ecosystem: every model package's Base.show and coeftable builds its Pr(>|z|) column through it, so a p-value cannot mean two things in two packages (floored in one, underflowing in another). Throws ArgumentError when the two vectors differ in length.

See also format_pvalue, signif_code, print_coeftable.

Examples

z_pvalues([0.0, 1.96, -2.5758])            # [1.0, 0.04999579029644087, 0.009999713929143034]
z_pvalues([50.0])[1] == floatmin(Float64)  # true — floored, never 0.0

zp = z_pvalues([1.2, -0.3, 0.8], [0.4, 0.1, 0.0])
zp.z                                       # [3.0, -3.0, NaN]
isnan(zp.p[3])                             # true — an undefined SE gives an undefined p-value
source
z_pvalues(estimates, std_errors, verdict::SeparationVerdict) -> NamedTuple{(:z, :p)}

z_pvalues under the separation policy: the usual Wald z values and two-sided p-values when the verdict is not separated, and NaN for every coefficient when it is (a fit with no finite maximum supports no Wald inference on any coefficient, since the others are estimated conditionally on the separated ones being infinite).

Example

using NetworkCore
x = collect(-3.0:3.0)
v = NetworkCore.logistic_separation(hcat(ones(7), x), x .> 0)
z_pvalues([1.0, 20.0], [0.5, 900.0], v).p          # [NaN, NaN]
source
NetworkCore.format_pvalue — Function
format_pvalue(p::Real; digits::Int=4, floor::Real=1e-16) -> String

Format a p-value for display. Never prints 0.0: values below floor render as "<1e-16" (R's format.pval convention), values too small for digits decimal places switch to scientific notation, and everything else is printed with digits decimal places. NaN renders as "NaN" (e.g. a coefficient with an undefined standard error).

Throws ArgumentError if p is outside [0, 1] (and not NaN), or if digits < 1.

See also signif_code, print_coeftable.

Example

format_pvalue(0.03511)    # "0.0351"
format_pvalue(3.2e-7)     # "3.2e-07"
format_pvalue(0.0)        # "<1e-16"
format_pvalue(1e-300)     # "<1e-16"
source
NetworkCore.signif_code — Function
signif_code(p::Real) -> String

R-style significance code for a p-value: "***" for p < 0.001, "**" for p < 0.01, "*" for p < 0.05, "." for p < 0.1, and "" otherwise (including NaN).

The legend, printed by print_coeftable:

Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Example

signif_code(0.0004)    # "***"
signif_code(0.03)      # "*"
signif_code(0.2)       # ""
source
NetworkCore.SIGNIF_LEGEND — Constant
SIGNIF_LEGEND

The significance-code legend line printed beneath every coefficient table in the ecosystem, matching R's convention. Paired with signif_code, which maps a p-value to one of the codes.

Example

SIGNIF_LEGEND    # "Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1"
println(SIGNIF_LEGEND)
source
NetworkCore.mc_pvalue — Function
mc_pvalue(sim::AbstractVector{<:Real}, obs::Real) -> Float64

Two-sided Monte-Carlo p-value of an observed statistic relative to a vector of simulated values, using the (1 + k)/(N + 1) estimator (the observed value counts as one draw from its null distribution), so the result is never exactly zero. This is the shared p-value used by goodness-of-fit assessments across the ecosystem.

Undefined statistics give NaN, never a small p-value. A NaN observed value (a statistic undefined on the observed network) returns NaN. Simulated values that are NaN (undefined on that draw) are dropped and N is the number of defined draws; if none is defined the result is NaN. (Comparing NaN counts no draw as extreme, so before 0.2.0 both cases returned the "significant" 2/(N+1).)

Throws ArgumentError if sim is empty.

Example

mc_pvalue([1.0, 2.0, 3.0, 4.0], 5.0)        # 0.4 — 2 * (1 + 0)/(4 + 1)
mc_pvalue([1.0, NaN, 3.0, 4.0], 5.0)        # 0.5 — 2 * (1 + 0)/(3 + 1), the NaN draw dropped
mc_pvalue([1.0, 2.0], NaN)                  # NaN — undefined observed statistic
source
NetworkCore.GOFStatistic — Type
GOFStatistic(name, labels, observed, simulated; p_values=nothing)

Goodness-of-fit comparison for ONE statistic category (e.g. the degree distribution, the edgewise-shared-partner distribution, a triad census): observed values versus a matrix of simulated values, one column per level of the statistic.

Arguments

  • name: statistic name shown as the table heading (e.g. "degree")
  • labels: one label per level (e.g. ["0", "1", "2", ...])
  • observed: observed value per level (length k)
  • simulated: n_sim × k matrix of the statistic in simulated networks

Keyword Arguments

  • p_values: per-level p-values; when omitted they are computed with mc_pvalue (two-sided, (1 + k)/(N + 1) estimator)

Collect one or more GOFStatistics in a GOFResult for formatted display.

Example

sims = [rand(0:5) for _ in 1:100, _ in 1:3]        # 100 simulations × 3 levels
stat = GOFStatistic("degree", ["0", "1", "2"], [2, 3, 1], sims)
stat.p_values                                      # Monte-Carlo p-value per level
stat                                               # prints the observed / envelope / p table
source
NetworkCore.GOFResult — Type
GOFResult(statistics; model="", p_overall=nothing)
GOFResult(statistic::GOFStatistic; kwargs...)

Goodness-of-fit assessment of a fitted model: one GOFStatistic per statistic category, displayed as observed value, simulation envelope (2.5% / mean / 97.5% quantiles of the simulated distribution), and Monte-Carlo p-value per level.

This is the common return type for gof methods across the model packages, so every model's goodness of fit prints the same way.

Keyword Arguments

  • model: description shown in the heading (e.g. "ERGM", "SAOM")
  • p_overall: optional overall p-value (e.g. the Monte-Carlo p-value of a Mahalanobis distance, as in RSiena's sienaGOF)

Example

sims = [rand(0:5) for _ in 1:100, _ in 1:3]
stat = GOFStatistic("degree", ["0", "1", "2"], [2, 3, 1], sims)
GOFResult([stat]; model="ERGM")
source
NetworkCore.n_simulations — Function
n_simulations(result::GOFResult) -> Int

Number of simulated networks the goodness-of-fit assessment is based on (the number of rows of the first statistic's simulated matrix).

Example

sims = [rand(0:5) for _ in 1:100, _ in 1:3]
res = GOFResult(GOFStatistic("degree", ["0", "1", "2"], [2, 3, 1], sims))
n_simulations(res)    # 100
source
NetworkCore.gof — Function
gof(result; kwargs...) -> GOFResult

Goodness-of-fit assessment of a fitted statistical network model.

This is an empty generic function: NetworkCore.jl defines no methods. Each model package (ERGM.jl, TERGM.jl, Siena.jl, REM.jl, ...) adds methods for its own result types to this ONE shared generic, so gof(fit) works uniformly across the ecosystem and loading several model packages together never produces colliding gof exports. Methods should return a GOFResult.

Example

using Random
import NetworkCore: gof                      # extend the ONE generic, never define a new `gof`
struct ToyFit end
function gof(::ToyFit; n_sim=100, rng=Random.default_rng())
    sims = [rand(rng, 0:5) for _ in 1:n_sim, _ in 1:3]
    GOFResult(GOFStatistic("degree", ["0", "1", "2"], [2, 3, 1], sims); model="toy")
end
n_simulations(gof(ToyFit(); n_sim=50))    # 50
source

For what a fit did — the objective it maximised, whether that objective is exact, how the standard errors were computed — see the Result-Metadata Protocol.