Estimation API Reference

This page documents the functions for model estimation, simulation, and goodness of fit.

Model Estimation

fit_siena

The primary estimation entry point.

Siena.fit_siena — Function
fit_siena(data::SienaData, effects::SienaEffects;
          algorithm::SienaAlgorithm=SienaAlgorithm(), rng=algorithm.rng)

Estimate SAOM parameters by the Method of Moments with Robbins-Monro stochastic approximation (Snijders 2001) — the estimator RSiena's siena07() uses by default.

Relation to RSiena's siena07()

siena07 is an alias of this function. The estimand is RSiena's: the same moment equations (targets pinned against RSiena:::getTargets for every effect offered under an RSiena name), conditional estimation by default when one dependent variable is simulated (RSiena's cond = NA), the score-function derivative for the standard errors, and the publication convergence standard. It is not a drop-in numerical copy of siena07():

  • only the Method of Moments is implemented (no Maximum Likelihood, Bayesian or GMoM estimation, no multi-group data, no siena08 meta-analysis);
  • the Robbins-Monro schedule is simpler (fixed subphase length, no diagonalisation or Dolby option, finite-difference preconditioner in phases 1-2) and is followed by capped Newton refinement, so Monte-Carlo paths differ;
  • the effects whose formula only approximates RSiena's carry a Simple suffix (e.g. BalanceSimpleEffect); interactions are not implemented;
  • dyads whose structural status changes between waves do not get RSiena's correction (see DependentNetwork), missing (NA) tie values are refused, and composition change is wave-integer only (see add_composition_change!).

The checked-in golden fixtures compare the estimates and standard errors with RSiena 1.6.6 for an unconditional and a conditional s50 network model, a co-evolution model and an undirected model, within multiples of RSiena's own seed-to-seed spread.

Phases

  1. A finite-difference derivative matrix at the initial values (the preconditioner), plus phase1_iterations Robbins-Monro updates.
  2. n_subphases subphases of Robbins-Monro updates with halving gain; each returns the Polyak-Ruppert average of its iterates.
  3. Up to refine_max capped Newton updates, each from 2 * phase3_iterations simulations with the score-function derivative, until the moment deviations are below half the convergence thresholds.
  4. Phase 3: phase3_iterations fresh simulations at the final estimate give the convergence t-ratios, tconv.max, and the standard errors $D^{-1} Σ D^{-T}$ ($D$ by the score function, algorithm.derivative_method = :score, or by central finite differences). If this independent batch fails the convergence standard, it drives one more Newton step and a fresh batch validates again, up to revalidate_max times; the reported diagnostics always come from a batch that was not used to choose the estimate.

Convergence follows the RSiena publication standard: all per-parameter |t-ratios| below algorithm.convergence_threshold (0.1) and tconv.max below algorithm.overall_convergence_threshold (0.25). An unconverged fit is returned with a warning (allow_unconverged=true, the default, as RSiena does) — show and approximations(fit) flag it and its estimates should not be reported — or throws SienaConvergenceError with allow_unconverged=false.

Restricted models (algorithm.model_type)

With model_type = :networkonly (or :behavioronly) only the network (behavior) dependent variables take ministeps; the others are frozen at their period-start values for the whole simulated period. A frozen variable stays in the simulation state and is still read by the effects of the simulated variables, but it never changes — so its own rate and objective effects have constant moments, are not identified, and are dropped from the estimated parameter vector (see simulated_variables and restrict_effects). algorithm.condvar must be one of the simulated variables. This is not RSiena's modelType (see the warning in SienaAlgorithm).

Conditional estimation

Conditional estimation (RSiena's cond=TRUE, and the default when one dependent variable is simulated and the data have no composition change) conditions on the observed amount of change of one dependent variable (algorithm.condvar, defaulting to the only one, RSiena's condvarno=1): every simulated period runs until that variable's distance from the period-start observation reaches the observed distance, instead of until time 1. The conditioned variable's basic rates leave the parameter vector and are estimated afterwards from the phase-3 stopping times (simulation rate × mean stopping time), with RSiena's standard error (simulation rate × standard deviation of the stopping time); both are reported in rate_estimates and rate_standard_errors. The basic rates of the other dependent variables are rescaled to the same time unit, as RSiena does. The derivative matrix is the score-function estimator in this case too (the conditional stopping rule is a stopping time of the simulated chain).

Score-type tests

Effects included with fix=true, test=true are held at their initial value and tested with the generalised score-type test of Schweinberger (2012), RSiena's test=TRUE: their statistics are simulated in phase 3 alongside the estimated ones, and result.score_test (a SienaScoreTest) holds the joint and per-effect chi-square tests, the signed one-df statistics and one-step estimates.

Example

using Siena, NetworkCore, Random
s50 = load_dataset(:s50)
data = siena_data()
add_nodeset!(data, NodeSet(50))
add_dependent!(data, DependentNetwork(:friendship, s50.friendship))
effects = get_effects(data)
include_effects!(effects, :friendship, [:outdegree, :recip])
result = fit_siena(data, effects; rng=MersenneTwister(1),
                   algorithm=SienaAlgorithm(verbose=false, phase3_iterations=200))
result.conditional        # true: one dependent network, RSiena's default

Returns

  • SienaResult: estimates (rate parameters first, then objective parameters)
source
fit_siena(algorithm::SienaAlgorithm, data::SienaData, effects::SienaEffects; rng)
fit_siena(algorithm::SienaAlgorithm; data::SienaData, effects::SienaEffects, rng)

RSiena's argument order: siena07(myalgorithm, data = mydata, effects = myeff) puts the algorithm first, and both spellings of it are accepted (with siena07 too). The fit is exactly fit_siena(data, effects; algorithm=algorithm, rng=rng). Passing the algorithm both positionally and as algorithm= is an ArgumentError, as is any other argument order (the message names the accepted ones).

Example

using Siena, NetworkCore, Random
s50 = load_dataset(:s50)
data = siena_data()
add_dependent!(data, DependentNetwork(:friendship, s50.friendship))
effects = get_effects(data)
alg = SienaAlgorithm(verbose=false, phase3_iterations=200)
fit = siena07(alg, data, effects; rng=MersenneTwister(1))           # RSiena's order
fit2 = siena07(alg; data=data, effects=effects, rng=MersenneTwister(1))
fit.estimates == fit2.estimates                                      # true
source

siena07

siena07 === fit_siena; both names refer to the same function.

Siena.siena07 — Function
siena07(data::SienaData, effects::SienaEffects;
        algorithm::SienaAlgorithm=SienaAlgorithm())

Alias for fit_siena, keeping the RSiena function name for the same step of the workflow. See fit_siena for how far the correspondence with RSiena's siena07() goes — the estimation method is the same, but the two are not numerically interchangeable in general.

Example

using Siena, NetworkCore, Random
s50 = load_dataset(:s50)
data = siena_data()
add_dependent!(data, DependentNetwork(:friendship, s50.friendship))
effects = get_effects(data)
include_effects!(effects, :friendship, [:outdegree, :recip])
fit = siena07(data, effects; rng=MersenneTwister(1),
                algorithm=SienaAlgorithm(verbose=false, phase3_iterations=200))
fit.converged
source

Internal update helpers

Siena.update_parameters! — Function
update_parameters!(θ::Vector{Float64}, score::AbstractVector{<:Real},
                  D::AbstractMatrix{<:Real}, gain::Real; max_step::Real=2.0)

Robbins-Monro update $θ \leftarrow θ - \text{gain} \cdot D^{-1} (\bar s - s_{obs})$, with the step capped at max_step in Euclidean norm. Falls back to the pseudoinverse if D is singular. D may be any matrix type, dense or structured (a Diagonal, for example): which container LinearAlgebra returns for a mixed broadcast is an implementation detail that changes between Julia versions.

source

Parameters and Targets

buildparammap

Siena.build_param_map — Function
build_param_map(effects::SienaEffects)

Build the ParameterMap for the included effects.

Example

using Siena
w1 = [0 1 0; 0 0 1; 1 0 0]
w2 = [0 1 1; 0 0 1; 0 0 0]
data = siena_data()
add_dependent!(data, DependentNetwork(:advice, [w1, w2]))
effects = get_effects(data)
include_effects!(effects, :advice, [:outdegree, :recip])
pm = build_param_map(effects)
length(pm.free)          # 3
source
Siena.ParameterMap — Type
ParameterMap

Mapping between the full free-parameter vector θ and the included effect entries.

The canonical θ layout is: free rate parameters first (in effects-table order, basic rates parameterized as the rate $\rho_m$ itself), then free objective parameters (in effects-table order). Fixed included effects keep their initial_value and are not part of θ.

Example

using Siena
w1 = [0 1 0; 0 0 1; 1 0 0]
w2 = [0 1 1; 0 0 1; 0 0 0]
data = siena_data()
add_dependent!(data, DependentNetwork(:advice, [w1, w2]))
effects = get_effects(data)
include_effects!(effects, :advice, [:outdegree, :recip])
pm = build_param_map(effects)
Siena.n_free_parameters(pm)      # 1 rate + 2 objective parameters
source

parameter_names

Siena.parameter_names — Function
parameter_names(effects::SienaEffects)

Display names of the free parameters, aligned with the θ vector.

Example

using Siena
w1 = [0 1 0; 0 0 1; 1 0 0]
w2 = [0 1 1; 0 0 1; 0 0 0]
data = siena_data()
add_dependent!(data, DependentNetwork(:advice, [w1, w2]))
effects = get_effects(data)
include_effects!(effects, :advice, [:outdegree, :recip])
parameter_names(effects)       # ["Rate advice (period 1)", "outdegree", "recip"]
source

objective_theta

Siena.objective_theta — Function
objective_theta(pm::ParameterMap, θ::Vector{Float64})

The objective-function part of the full parameter vector.

Example

using Siena
w1 = [0 1 0; 0 0 1; 1 0 0]
w2 = [0 1 1; 0 0 1; 0 0 0]
data = siena_data()
add_dependent!(data, DependentNetwork(:advice, [w1, w2]))
effects = get_effects(data)
include_effects!(effects, :advice, [:outdegree, :recip])
objective_theta(build_param_map(effects), [2.5, -1.0, 0.5])     # [-1.0, 0.5]
source

basic_rate

Siena.basic_rate — Function
basic_rate(pm::ParameterMap, θ::Vector{Float64}, variable::Symbol, period::Int)

Basic rate parameter $\rho_m$ for a dependent variable and period (1.0 if the model has no basic rate entry for it).

Example

using Siena
w1 = [0 1 0; 0 0 1; 1 0 0]
w2 = [0 1 1; 0 0 1; 0 0 0]
data = siena_data()
add_dependent!(data, DependentNetwork(:advice, [w1, w2]))
effects = get_effects(data)
include_effects!(effects, :advice, [:outdegree, :recip])
pm = build_param_map(effects)
basic_rate(pm, [2.5, -1.0, 0.5], :advice, 1)      # 2.5
source
Siena.default_basic_rate — Function
default_basic_rate(data::SienaData, variable::Symbol, period::Int) -> Float64

Data-based starting value of a basic rate parameter: the observed amount of change of variable in period per actor, inflated by 1.5 for cancelling ministeps (at least 0.5). get_effects uses it as the initial value of the basic rates, and conditional estimation as the simulation rate of the conditioning variable.

Example

using Siena
w1 = [0 1 0; 0 0 1; 1 0 0]; w2 = [0 1 1; 0 0 1; 0 0 0]
data = siena_data()
add_dependent!(data, DependentNetwork(:advice, [w1, w2]))
default_basic_rate(data, :advice, 1)        # 1.5 * 2 changes / 3 actors = 1.0
source

Restricted models (model_type)

SienaAlgorithm's model_type selects which dependent variables co-evolve. The frozen variables stay in the state (and readable by the effects of the simulated ones), but they take no ministeps and their own effects leave the parameter vector.

Siena.simulated_variables — Function
simulated_variables(data::SienaData, model_type::Symbol)
simulated_variables(data::SienaData, algorithm::SienaAlgorithm)

The dependent variables that take ministeps under model_type (see SienaAlgorithm), in the order of data.dependents:

The variables that are not returned stay in the NetworkState fixed at their period-start values: they never change, but they remain readable by the effects of the simulated variables (a network effect may depend on a frozen behavior, and vice versa).

Throws if the restriction leaves no variable to simulate.

Example

using Siena
data = siena_data()
add_dependent!(data, DependentNetwork(:net, [[0 1; 0 0], [0 1; 1 0]]))
add_dependent!(data, DependentBehavior(:mood, [[1, 2], [2, 2]]))
simulated_variables(data, :networkonly)       # [:net]
source
Siena.restrict_effects — Function
restrict_effects(effects::SienaEffects, variables::Vector{Symbol})

The effects of variables only: an effects object holding the entries whose target variable is simulated, sharing the EffectEntry objects with effects (so fix/include flags and estimated values stay in sync). Returns effects itself when nothing has to be dropped.

This is the seam through which SienaAlgorithm's model_type reaches the parameter vector: the rate and objective effects of a frozen dependent variable are not identified (the variable never changes, so its moments are constant), and are therefore removed from the model rather than estimated. Effects of a simulated variable that merely read a frozen one (e.g. a network rate effect depending on a behavior) are kept.

Example

using Siena
data = siena_data()
add_dependent!(data, DependentNetwork(:net, [[0 1 0; 0 0 1; 1 0 0], [0 1 1; 0 0 1; 0 0 0]]))
add_dependent!(data, DependentBehavior(:mood, [[1, 2, 3], [2, 2, 3]]))
effects = get_effects(data)
length(restrict_effects(effects, [:net])) < length(effects)       # true: :mood's effects dropped
source

computetargetstatistics

Siena.compute_target_statistics — Function
compute_target_statistics(data::SienaData, effects::SienaEffects)

Observed target statistics for all free parameters (θ order): objective statistics are evaluated at the end wave of each period and summed over periods; rate statistics are the observed amounts of change.

Example

using Siena
w1 = [0 1 0; 0 0 1; 1 0 0]
w2 = [0 1 1; 0 0 1; 0 0 0]
data = siena_data()
add_dependent!(data, DependentNetwork(:advice, [w1, w2]))
effects = get_effects(data)
include_effects!(effects, :advice, [:outdegree, :recip])
compute_target_statistics(data, effects)      # [rate distance, outdegree, recip]
source

computesimulatedstatistics

Siena.compute_simulated_statistics — Function
compute_simulated_statistics(data::SienaData, effects::SienaEffects,
                            results::Vector{SimulationResult})

Simulated moment statistics for all free parameters, from the per-period results of simulate_saom.

Example

using Siena
w1 = [0 1 0; 0 0 1; 1 0 0]
w2 = [0 1 1; 0 0 1; 0 0 0]
data = siena_data()
add_dependent!(data, DependentNetwork(:advice, [w1, w2]))
effects = get_effects(data)
include_effects!(effects, :advice, [:outdegree, :recip])
_, periods = simulate_saom(data, effects, [2.0, -1.0, 0.5]; rng=Siena.Random.Xoshiro(1))
compute_simulated_statistics(data, effects, periods)    # distance, outdegree, recip
source

Derivative Matrix Estimators

Siena.estimate_derivative_matrix — Function
estimate_derivative_matrix(data::SienaData, effects::SienaEffects,
                          θ::Vector{Float64}, n_sims::Int, rng::AbstractRNG;
                          central=true, step=0.1, ...)

Estimate $D = \partial E[s]/\partial θ$ ($D_{kj} = \partial E[s_k]/\partial θ_j$) by finite differences with common random numbers: every perturbed run reuses the base run's simulation seeds, so the Monte-Carlo noise largely cancels in the difference.

central=true (the default) takes central differences with step $ε_j =$ step $\cdot \max(1, |θ_j|)$; the first-order curvature bias cancels. Before 0.2 this was a forward difference, whose bias inflated $D$ by up to a third and made standard errors 15–25 % too small. A much smaller step does not help: with common random numbers the difference of two discrete trajectories has a variance of order $1/ε$, so the default step = 0.1 balances bias against noise. central=false keeps the cheaper forward difference, which the estimator uses only as a phase-1/phase-2 preconditioner under derivative_method = :finite_difference, where its bias changes step sizes but not the solution of the moment equations.

The simulations are independent (each is driven by its own seeded RNG) and run multi-threaded unless threaded=false; every simulation writes to its own slot and the results are reduced in a fixed order, so the estimate is identical to a single-threaded run regardless of the number of threads.

Example

using Siena, Random
w1 = [0 1 0 0; 0 0 1 0; 1 0 0 1; 0 1 0 0]; w2 = [0 1 1 0; 0 0 1 0; 0 0 0 1; 1 1 0 0]
data = siena_data()
add_dependent!(data, DependentNetwork(:advice, [w1, w2]))
effects = get_effects(data)
include_effects!(effects, :advice, [:outdegree, :recip])
D = estimate_derivative_matrix(data, effects, [2.0, -1.0, 0.5], 20, MersenneTwister(1))
size(D)            # (3, 3)
source
Siena.estimate_derivative_matrix_score — Function
estimate_derivative_matrix_score(data::SienaData, effects::SienaEffects,
                                θ::Vector{Float64}, n_sims::Int, rng::AbstractRNG)

Score-function (likelihood-ratio) estimator of $D = \partial E[s]/\partial θ$ (Schweinberger & Snijders 2007), as used by RSiena: simulate n_sims trajectories at θ, accumulate the score of each trajectory period by period (see ScoreAccumulator), and estimate $D = \sum_m \widehat{\mathrm{cov}}(s_m, S_m)$ across the simulations, pairing each period's statistics with that period's score only (RSiena's derivativeFromScoresAndDeviations; the cross-period terms are zero in expectation, and before 0.2 their noise was included).

Unlike estimate_derivative_matrix it needs no parameter perturbations, so the cost is n_sims simulations regardless of the number of parameters. Pass condvar/cond_targets for the conditional estimator's derivative (see ScoreAccumulator for why the score function stays valid there).

Example

using Siena, Random
w1 = [0 1 0 0; 0 0 1 0; 1 0 0 1; 0 1 0 0]; w2 = [0 1 1 0; 0 0 1 0; 0 0 0 1; 1 1 0 0]
data = siena_data()
add_dependent!(data, DependentNetwork(:advice, [w1, w2]))
effects = get_effects(data)
include_effects!(effects, :advice, [:outdegree, :recip])
D = estimate_derivative_matrix_score(data, effects, [2.0, -1.0, 0.5], 200,
                                     MersenneTwister(1))
size(D)            # (3, 3)

The simulations are independent (one seeded RNG per simulation) and run multi-threaded unless threaded=false; results are identical to a single-threaded run regardless of the number of threads.

source

Simulation

simulate_saom

Siena.simulate_saom — Function
simulate_saom(data::SienaData, effects::SienaEffects, θ::Vector{Float64};
             rng::AbstractRNG=Random.default_rng())

Simulate the SAOM across all periods. θ is the full free-parameter vector (rate parameters first, then objective parameters — see build_param_map).

Each period starts from the corresponding observed wave (as in unconditional Method-of-Moments estimation), so per-period results are conditionally independent given the data.

Returns (final_state, results::Vector{SimulationResult}) with one result per period.

If scores is given, the score function of the simulated trajectory is accumulated across all periods (see ScoreAccumulator).

If condvar is given, every period is simulated conditionally on the observed amount of change of that dependent variable (RSiena's conditional simulation): the period runs until the variable's distance from the period-start observation reaches cond_targets[period] instead of until time 1. Scores can be accumulated in either mode (see ScoreAccumulator).

The model is checked against the data first (validate_effects); the estimator, which simulates thousands of times, passes validate=false after checking once.

Example

using Siena, Random
w1 = [0 1 0; 0 0 1; 1 0 0]; w2 = [0 1 1; 0 0 1; 0 0 0]
data = siena_data()
add_dependent!(data, DependentNetwork(:advice, [w1, w2]))
effects = get_effects(data)
include_effects!(effects, :advice, [:outdegree, :recip])
state, periods = simulate_saom(data, effects, [2.0, -1.0, 0.5]; rng=MersenneTwister(1))
size(state.networks[:advice])          # (3, 3)

variables restricts the ministeps to a subset of the dependent variables (the model_type restriction, see simulated_variables); the others are frozen at their period-start values but stay readable. θ must then be the parameter vector of the restricted effects (see restrict_effects).

source

Objective effect sets

The simulation hot path snapshots the included objective effects into a tuple-backed ObjectiveEffectSet (built once per simulation), so the per-candidate contribution loop is statically dispatched. All simulation functions accept either a SienaEffects table or a prebuilt set; results are identical.

Siena.ObjectiveEffectSet — Type
ObjectiveEffectSet

The included objective effects of a model, stored as a tuple of ObjectiveEffectSpecs (mirroring ERGM.TermSet) so that the per-candidate contribution loop compiles to statically dispatched calls instead of dynamic dispatch through an abstractly-typed effects table.

Build one with build_objective_set and pass it to simulate_period!, compute_objective, or the choice-probability functions in place of the SienaEffects argument; results are identical, evaluation is just faster.

Example

using Siena
w1 = [0 1 0; 0 0 1; 1 0 0]
w2 = [0 1 1; 0 0 1; 0 0 0]
data = siena_data()
add_dependent!(data, DependentNetwork(:advice, [w1, w2]))
effects = get_effects(data)
include_effects!(effects, :advice, [:outdegree, :recip])
oset = build_objective_set(effects)
length(oset)        # 2 included objective effects
source
Siena.build_objective_set — Function
build_objective_set(effects::SienaEffects)

Snapshot the included objective effects (network and behavior effects, in effects-table order) into an ObjectiveEffectSet. The spec's param_idx follows the layout of objective_theta: consecutive indices over the non-fixed objective entries.

The set is a snapshot: rebuild it after changing inclusion/fix flags or initial values.

Example

using Siena
w1 = [0 1 0; 0 0 1; 1 0 0]
w2 = [0 1 1; 0 0 1; 0 0 0]
data = siena_data()
add_dependent!(data, DependentNetwork(:advice, [w1, w2]))
effects = get_effects(data)
include_effects!(effects, :advice, [:outdegree, :recip])
build_objective_set(effects).specs isa Tuple       # true
source
Siena.ObjectiveEffectSpec — Type
ObjectiveEffectSpec

One included objective effect with the entry metadata the simulation hot loop needs (target variable, effect type, fix status, θ-index). The effect field is concretely typed, so compute_contribution calls through a spec are statically dispatched.

source
Siena.entry_value — Function
entry_value(pm::ParameterMap, θ::Vector{Float64}, entry::EffectEntry)

Current parameter value of an included entry: its θ component if free, its initial_value if fixed.

source

Score accumulation

Siena.ScoreAccumulator — Type
ScoreAccumulator(pm::ParameterMap)

Accumulator for the score function $S = \partial \log P(\text{path}; θ)/\partial θ$ of a simulated trajectory, aligned with the full free-parameter vector θ.

Passed to simulate_saom via the scores keyword. Every ministep adds its multinomial-choice score $s_{\text{chosen}} - \sum_a P(a)\, s_a$ over the candidate set, and every waiting time adds the rate-parameter exposure terms of the time-truncated CTMC likelihood. The accumulated scores drive the score-function (Schweinberger–Snijders) derivative estimator $D = \mathrm{cov}(s, S)$ used for standard errors.

Valid for unconditional simulation (the exposure of the last, unfinished waiting time is censored at the end of the unit period) and for conditional simulation: a conditional period ends at the ministep that reaches the observed distance, a stopping time of the simulated chain, so the score of the path up to that point is still the derivative of its log-probability and $D = \mathrm{cov}(s, S)$ remains unbiased (Schweinberger & Snijders 2007). The conditioning variable's basic rate is not a free parameter then and gets no score.

Example

using Siena, Random
w1 = [0 1 0; 0 0 1; 1 0 0]; w2 = [0 1 1; 0 0 1; 0 0 0]
data = siena_data()
add_dependent!(data, DependentNetwork(:advice, [w1, w2]))
effects = get_effects(data)
include_effects!(effects, :advice, [:outdegree, :recip])
sacc = ScoreAccumulator(build_param_map(effects))
simulate_saom(data, effects, [2.0, -1.0, 0.5]; rng=MersenneTwister(1), scores=sacc)
length(sacc.scores)        # 3: one score per free parameter
source
Siena.reset_scores! — Function
reset_scores!(sacc::ScoreAccumulator)

Zero the accumulated scores (for reuse across simulations).

Example

using Siena
data = siena_data()
add_dependent!(data, DependentNetwork(:advice, [[0 1; 0 0], [0 0; 1 0]]))
effects = get_effects(data)                                  # rate, outdegree, recip
include_effects!(effects, :advice, [:recip]; include=false)
sacc = ScoreAccumulator(build_param_map(effects))
reset_scores!(sacc).scores           # [0.0, 0.0]
source
Siena.MinistepWorkspace — Type
MinistepWorkspace(n_alters::Int, n_parameters::Int=0)

Reusable network-choice buffers. n_parameters is the full free-parameter count when collecting trajectory scores, or zero for probabilities only. Allocate one per concurrent simulation. Reuse it with compute_network_choice_probs!. The buffers are overwritten by each call; only the first n_candidates entries are active (remaining probabilities are zero).

Example

using Siena
w1 = [0 1 0; 0 0 1; 1 0 0]
w2 = [0 1 1; 0 0 1; 0 0 0]
data = siena_data()
add_dependent!(data, DependentNetwork(:advice, [w1, w2]))
effects = get_effects(data)
include_effects!(effects, :advice, [:outdegree, :recip])
oset = build_objective_set(effects)
state = initialize!(NetworkState(), data, 1)
work = MinistepWorkspace(3)
compute_network_choice_probs!(work, oset, [-1.0, 0.5], state, data, 1, :advice)
work.probabilities[1:work.n_candidates]      # no change, then alters 2 and 3
source
Siena.compute_network_choice_probs! — Function
compute_network_choice_probs!(workspace::MinistepWorkspace, effects::ObjectiveEffectSet,
                              theta, state, data, actor, variable; param_map=nothing)

Write network-choice probabilities and alter indices into reusable buffers and return workspace. Pass the full param_map to also compute objective gradients for trajectory scores. This method allocates no choice buffers; the allocating compute_network_choice_probs remains available when owned outputs are needed.

Example

using Siena
w1 = [0 1 0; 0 0 1; 1 0 0]
w2 = [0 1 1; 0 0 1; 0 0 0]
data = siena_data()
add_dependent!(data, DependentNetwork(:advice, [w1, w2]))
effects = get_effects(data)
include_effects!(effects, :advice, [:outdegree, :recip])
oset = build_objective_set(effects)
state = initialize!(NetworkState(), data, 1)
work = MinistepWorkspace(3)
compute_network_choice_probs!(work, oset, [-1.0, 0.5], state, data, 1, :advice).n_candidates   # 3
source

simulate_period!

Siena.simulate_period! — Function
simulate_period!(state::NetworkState, effects,
                θ_obj::Vector{Float64}, rate_params::Dict{Symbol, Float64},
                data::SienaData, rng::AbstractRNG; kwargs...)

Simulate one period of network/behavior dynamics over the unit time interval.

Arguments

  • effects: a SienaEffects table or a prebuilt ObjectiveEffectSet (simulate_saom builds the set once and reuses it across periods)
  • θ_obj: objective-function parameters (see objective_theta)
  • rate_params: basic rate $\rho$ per dependent variable for this period
  • nonbasic_rates: optional Dict(variable => (entries, values)) of non-basic rate effect entries and their parameters
  • conditional/target_changes: if conditional=true, simulate until each variable in target_changes has reached the target distance from its period-start state (network: Hamming distance; behavior: L1 distance), instead of until time 1 — RSiena's conditional simulation
  • variables: the dependent variables that take ministeps (nothing, the default: all of them). Variables left out are frozen: they keep their period-start values for the whole period, but stay in state and remain readable by the effects of the simulated variables. This is how SienaAlgorithm's model_type restricts the model (see simulated_variables)
  • max_steps: safety cap on the number of ministeps
  • scores: optional ScoreAccumulator collecting the score function of the simulated trajectory (unconditional simulation only)

Per-actor rates are cached between ministeps: a variable's rates are recomputed only after a ministep actually changed the state, and only for variables whose rate function is state-dependent (i.e. with non-basic rate effects). Variables with only a basic rate have constant rates that are computed once per period.

Example

using Siena
w1 = [0 1 0; 0 0 1; 1 0 0]
w2 = [0 1 1; 0 0 1; 0 0 0]
data = siena_data()
add_dependent!(data, DependentNetwork(:advice, [w1, w2]))
effects = get_effects(data)
include_effects!(effects, :advice, [:outdegree, :recip])
state = initialize!(NetworkState(), data, 1)
oset = build_objective_set(effects)
res = simulate_period!(state, oset, [-1.0, 0.5], Dict(:advice => 2.0), data,
                       Siena.Random.Xoshiro(3))
res.n_network_changes[:advice]
source

Internal ministep machinery

One iteration of the continuous-time Markov chain: an actor is selected via the rate function, waits an exponential time, and executes a network or behavior ministep.

Siena.actor_rate — Function
actor_rate(λ_basic::Float64, effects::Vector{EffectEntry}, θ::Vector{Float64},
          state::NetworkState, data::SienaData, actor::Int)

Compute the rate $\lambda_i = \lambda \prod_k \exp(\theta_k r_{ki})$ for an actor, given the basic rate and the non-basic rate effect entries with their parameters.

source
Siena.sample_waiting_time — Function
sample_waiting_time(rate::Float64, rng::AbstractRNG)

Sample waiting time from exponential distribution with given rate.

source
Siena.execute_network_ministep! — Function
execute_network_ministep!(state::NetworkState, effects,
                         θ::Vector{Float64}, data::SienaData,
                         actor::Int, variable::Symbol, rng::AbstractRNG;
                         scores::Union{Nothing, ScoreAccumulator}=nothing)

Execute a network mini-step for the given actor. Returns the chosen alter (0 for no change). If scores is given, the choice score of the ministep is accumulated.

For an undirected network the chosen tie is toggled in both directions (RSiena's default model type 2 for symmetric networks): the choice probabilities are those of the standard actor-oriented model computed on the symmetric state, and the change is imposed on the alter. effects may be a SienaEffects table or a prebuilt ObjectiveEffectSet.

source
Siena.execute_behavior_ministep! — Function
execute_behavior_ministep!(state::NetworkState, effects,
                          θ::Vector{Float64}, data::SienaData,
                          actor::Int, variable::Symbol, rng::AbstractRNG;
                          scores::Union{Nothing, ScoreAccumulator}=nothing)

Execute a behavior mini-step for the given actor. Returns the chosen direction. If scores is given, the choice score of the ministep is accumulated. effects may be a SienaEffects table or a prebuilt ObjectiveEffectSet.

source

compute_objective

Siena.compute_objective — Function
compute_objective(effects, θ::Vector{Float64},
                 state::NetworkState, data::SienaData,
                 actor::Int, alter::Int, variable::Symbol)

Objective-function change for a potential ministep, using the objective part of the parameter vector (see objective_theta). effects may be a SienaEffects table or a prebuilt ObjectiveEffectSet (the simulation hot path builds the set once per simulation and reuses it for every candidate alter).

For networks the change is a toggle of the tie actor -> alter; since compute_contribution returns the add-direction change statistic, deletions get the sign flip $(1 - 2 x_{ij})$. For behavior, alter encodes the direction (±1) and the contributions are already directional differences. Creation effects only enter for additions/increases, endowment effects only for deletions/decreases.

Example

using Siena
w1 = [0 1 0; 0 0 1; 1 0 0]
w2 = [0 1 1; 0 0 1; 0 0 0]
data = siena_data()
add_dependent!(data, DependentNetwork(:advice, [w1, w2]))
effects = get_effects(data)
include_effects!(effects, :advice, [:outdegree, :recip])
state = initialize!(NetworkState(), data, 1)
compute_objective(effects, [-1.0, 0.5], state, data, 2, 1, :advice)   # -1.0 + 0.5
source

computenetworkchoice_probs

Siena.compute_network_choice_probs — Function
compute_network_choice_probs(effects, θ::Vector{Float64},
                            state::NetworkState, data::SienaData,
                            actor::Int, variable::Symbol)

Compute multinomial-logit probabilities for all possible tie toggles of an actor (plus the no-change option). Returns (probabilities, alters) where alter 0 is the no-change option. For two-mode networks the alters are the events (columns).

Structurally determined dyads (structural zeros/ones of the period-start wave; see DependentNetwork) are excluded from the candidate set: an actor can never toggle them. Likewise, when the data have composition changes, dyads involving actors absent in the current period are excluded (an inactive ego gets only the no-change option). In an up-only period of the observed network only absent ties are candidates, and in a down-only period only present ones (RSiena's allowOnly; see DependentNetwork).

effects may be a SienaEffects table or a prebuilt ObjectiveEffectSet; with a SienaEffects argument the set is built once (hoisted out of the alter loop).

Example

using Siena
w1 = [0 1 0; 0 0 1; 1 0 0]
w2 = [0 1 1; 0 0 1; 0 0 0]
data = siena_data()
add_dependent!(data, DependentNetwork(:advice, [w1, w2]))
effects = get_effects(data)
include_effects!(effects, :advice, [:outdegree, :recip])
state = initialize!(NetworkState(), data, 1)
probs, alters = compute_network_choice_probs(effects, [-1.0, 0.5], state, data, 1, :advice)
alters          # [0, 2, 3]: no change, or toggle a tie to 2 or 3
source

computebehaviorchoice_probs

Siena.compute_behavior_choice_probs — Function
compute_behavior_choice_probs(effects, θ::Vector{Float64},
                             state::NetworkState, data::SienaData,
                             actor::Int, variable::Symbol)

Compute probabilities for behavior changes (-1, 0, +1) for an actor. Returns (probabilities, directions). A step outside the observed range is not a candidate, and neither is a decrease in an up-only period or an increase in a down-only period (RSiena's allowOnly; see DependentBehavior).

effects may be a SienaEffects table or a prebuilt ObjectiveEffectSet.

Example

using Siena
data = siena_data()
add_dependent!(data, DependentNetwork(:net, [[0 1 0; 0 0 1; 1 0 0], [0 1 1; 0 0 1; 0 0 0]]))
add_dependent!(data, DependentBehavior(:mood, [[1, 2, 3], [2, 2, 2]]))
effects = get_effects(data)       # net: outdegree, recip; mood: linear, quad (RSiena)
state = initialize!(NetworkState(), data, 1)
θ = [-1.0, 0.5, 0.3, -0.1]          # the four included objective parameters, in order
compute_behavior_choice_probs(effects, θ, state, data, 2, :mood)   # (probs, [-1, 0, 1])
source

Result Accessors

coef

StatsAPI.coef — Function
coef(result::SienaResult)

Return the parameter estimates (rate parameters first, then objective parameters). Extends StatsAPI.coef.

Example

using Siena, NetworkCore, Random
s50 = load_dataset(:s50)
data = siena_data()
add_dependent!(data, DependentNetwork(:friendship, s50.friendship))
effects = get_effects(data)
include_effects!(effects, :friendship, [:outdegree, :recip])
fit = fit_siena(data, effects; rng=MersenneTwister(1),
                algorithm=SienaAlgorithm(verbose=false, phase3_iterations=200))
coef(fit)          # objective parameters (a conditional fit has no rate in θ)
source

coefnames

StatsAPI.coefnames — Function
coefnames(result::SienaResult) -> Vector{String}

The parameter labels, in coef(result) order (R's names(coef(fit))): the same labels as coeftable(result).names and result.parameter_names (a copy, so changing it leaves the fit alone). Extends StatsAPI.coefnames.

Example

using Siena, NetworkCore, Random
s50 = load_dataset(:s50)
data = siena_data()
add_dependent!(data, DependentNetwork(:friendship, s50.friendship))
effects = get_effects(data)
include_effects!(effects, :friendship, [:outdegree, :recip])
fit = fit_siena(data, effects; rng=MersenneTwister(1),
                algorithm=SienaAlgorithm(verbose=false, phase3_iterations=200))
coefnames(fit)                          # ["outdegree", "recip"]
coefnames(fit) == coeftable(fit).names  # true
source

stderror

StatsAPI.stderror — Function
stderror(result::SienaResult)

Return standard errors. Extends StatsAPI.stderror.

Example

using Siena, NetworkCore, Random
s50 = load_dataset(:s50)
data = siena_data()
add_dependent!(data, DependentNetwork(:friendship, s50.friendship))
effects = get_effects(data)
include_effects!(effects, :friendship, [:outdegree, :recip])
fit = fit_siena(data, effects; rng=MersenneTwister(1),
                algorithm=SienaAlgorithm(verbose=false, phase3_iterations=200))
stderror(fit)
source

vcov

StatsAPI.vcov — Function
vcov(result::SienaResult)

Return covariance matrix. Extends StatsAPI.vcov.

Example

using Siena, NetworkCore, Random
s50 = load_dataset(:s50)
data = siena_data()
add_dependent!(data, DependentNetwork(:friendship, s50.friendship))
effects = get_effects(data)
include_effects!(effects, :friendship, [:outdegree, :recip])
fit = fit_siena(data, effects; rng=MersenneTwister(1),
                algorithm=SienaAlgorithm(verbose=false, phase3_iterations=200))
vcov(fit)
source

confint

StatsAPI.confint — Function
confint(result::SienaResult; level::Float64=0.95)

Compute confidence intervals. Extends StatsAPI.confint.

Example

using Siena, NetworkCore, Random
s50 = load_dataset(:s50)
data = siena_data()
add_dependent!(data, DependentNetwork(:friendship, s50.friendship))
effects = get_effects(data)
include_effects!(effects, :friendship, [:outdegree, :recip])
fit = fit_siena(data, effects; rng=MersenneTwister(1),
                algorithm=SienaAlgorithm(verbose=false, phase3_iterations=200))
confint(fit; level=0.9)
source
StatsAPI.coeftable — Method
coeftable(result::SienaResult)

Return the shared coefficient table in fitted parameter order. Rate parameters are positive waiting-rate parameters; their normal Wald tests against zero are generally not appropriate, so their z and p entries are undefined. Convergence t-ratios remain available separately as result.t_ratios.

Example

using Siena, NetworkCore, Random
s50 = load_dataset(:s50)
data = siena_data()
add_dependent!(data, DependentNetwork(:friendship, s50.friendship))
effects = get_effects(data)
include_effects!(effects, :friendship, [:outdegree, :recip])
fit = fit_siena(data, effects; rng=MersenneTwister(1),
                algorithm=SienaAlgorithm(verbose=false, phase3_iterations=200))
coeftable(fit)
source

Time heterogeneity

Siena.siena_time_test — Function
siena_time_test(result::SienaResult; effects=nothing, condition=false)

Test the fitted model for time heterogeneity — RSiena's sienaTimeTest (Lospinoso, Schweinberger, Snijders & Ripley 2011). For every estimated objective or non-basic rate effect and every period after the first, the model is extended by the interaction of the effect with a dummy for that period; the dummies are not estimated but tested at zero with the score-type test of Schweinberger (2012), from the per-period statistics and scores of the fit's phase-3 simulations (no new simulations are run). Basic rate parameters are already period-specific and are not tested.

effects restricts the tested effects (short names, e.g. ["recip"], or positions in result.parameter_names). With condition=true each individual dummy test also conditions on the other dummies, as RSiena's condition=TRUE. Effects whose dummies are linearly dependent on the model are excluded (and listed in excluded).

Needs at least two periods (three waves). A significant joint test says that some parameter differs between periods; RSiena's remedy, period-dummy effects (sienaTimeFix), is not implemented — fit the periods separately instead.

Example

using Siena, NetworkCore, Random
s50 = load_dataset(:s50)
data = siena_data()
add_dependent!(data, DependentNetwork(:friendship, s50.friendship))
effects = get_effects(data)
include_effects!(effects, :friendship, [:outdegree, :recip, :transTrip])
fit = fit_siena(data, effects; rng=MersenneTwister(1),
                algorithm=SienaAlgorithm(verbose=false, phase3_iterations=300))
tt = siena_time_test(fit)
tt.p_value               # joint test of time heterogeneity
tt.effect_p_values       # one test per effect
source
Siena.SienaTimeTest — Type
SienaTimeTest

Result of siena_time_test: score-type tests of time heterogeneity.

Fields

  • effects::Vector{String}: The tested (base) effects
  • periods::Vector{Int}: The periods with a dummy (all but the first)
  • chisq::Float64, df::Int, p_value::Float64: Joint test of all dummies
  • effect_chisq, effect_df, effect_p_values: Per effect, the joint test of its dummies (given the estimated parameters)
  • period_chisq, period_df, period_p_values: Per period, the joint test of that period's dummies; for period 1 (the reference) the test of the summed dummies of every effect, as in RSiena
  • dummy_names::Vector{String}: "(*)Dummy<period>:<effect>", effect by effect
  • dummy_z, dummy_p_values: One-sided score statistics (approximately standard normal under homogeneity) of each dummy and their two-sided p-values
  • one_step::Vector{Float64}: One-step estimates of the dummy parameters
  • excluded::Vector{String}: Effects left out because their dummies are collinear with the model (e.g. an effect that is itself period-specific)

Example

using Siena, NetworkCore, Random
s50 = load_dataset(:s50)
data = siena_data()
add_dependent!(data, DependentNetwork(:friendship, s50.friendship))
effects = get_effects(data)
include_effects!(effects, :friendship, [:outdegree, :recip, :transTrip])
fit = fit_siena(data, effects; rng=MersenneTwister(1),
                algorithm=SienaAlgorithm(verbose=false, phase3_iterations=300))
tt = siena_time_test(fit)
tt.df                    # 3 effects x 1 dummy (period 2)
source

Goodness of Fit

gof

Method of the shared NetworkCore.gof generic; returns the ecosystem-wide GOFResult.

NetworkCore.gof — Method
gof(result::SienaResult; statistics=nothing, n_sim=100, rng=Random.default_rng(), period=nothing)
gof(result::SienaResult, statistic_or_statistics; kwargs...)
gof(result::SienaResult, data::SienaData, statistic_or_statistics; kwargs...)

Goodness-of-fit assessment of an estimated SAOM — the preferred GOF entry point, a method of the shared NetworkCore.gof generic returning the ecosystem-wide GOFResult (one table per statistic). It runs siena_gof (which returns the RSiena-style detail) for each statistic.

Without statistics, every network is assessed on its in- and outdegree distributions (RSiena's default levels 0:8, cumulative) and every behaviour on its value distribution, using the data stored on the fit. With a single statistic the overall p-value is the Monte-Carlo p-value of the Mahalanobis distance.

Example

using Siena, NetworkCore, Random
s50 = load_dataset(:s50)
data = siena_data()
add_dependent!(data, DependentNetwork(:friendship, s50.friendship))
effects = get_effects(data)
include_effects!(effects, :friendship, [:outdegree, :recip, :transTrip])
fit = fit_siena(data, effects; rng=MersenneTwister(1),
                algorithm=SienaAlgorithm(verbose=false, phase3_iterations=200))
report = gof(fit; n_sim=50, rng=Xoshiro(2))                 # in- and outdegrees
triads = gof(fit, TriadCensus(:friendship); n_sim=50, rng=Xoshiro(3))
source

siena_gof

The RSiena-style entry point; returns the detailed SienaGOFResult.

Siena.siena_gof — Function
siena_gof(result::SienaResult, data::SienaData, statistic::AbstractGOFStatistic;
         n_sim::Int=100, rng::AbstractRNG=Random.default_rng(), period=nothing)

Goodness of fit of an estimated model on one auxiliary statistic — RSiena's sienaGOF. n_sim trajectories are simulated from the estimates (each period starting from its observed wave, conditionally on the observed amount of change when the fit was conditional, and with the fit's model_type restriction), the statistic is evaluated at the end of every period, and — RSiena's join=TRUE — summed over the periods; pass period=m to compare period m only.

The overall p-value is a Monte-Carlo test of the Mahalanobis distance. Unlike sienaGOF, which centres and scales the distances with the mean and covariance of the simulations alone, the observed vector is pooled with the simulated ones, so under the fitted model the observed distance is exchangeable with the simulated ones and $p = (1 + \#\{d_s \ge d_{obs}\})/(N + 1)$ is an exact Monte-Carlo p-value (a pseudo-inverse handles the linear constraints of the counts). With the default fixed cumulative degree levels the test holds its size: a correct model is rejected about 5 % of the time at the 5 % level (pinned by a simulation testset). The estimation uncertainty of the parameters is not accounted for, which makes the test slightly conservative, as RSiena's.

Example

using Siena, NetworkCore, Random
s50 = load_dataset(:s50)
data = siena_data()
add_dependent!(data, DependentNetwork(:friendship, s50.friendship))
effects = get_effects(data)
include_effects!(effects, :friendship, [:outdegree, :recip, :transTrip])
fit = fit_siena(data, effects; rng=MersenneTwister(1),
                algorithm=SienaAlgorithm(verbose=false, phase3_iterations=200))
detail = siena_gof(fit, data, IndegreeDistribution(:friendship); n_sim=50,
                   rng=Xoshiro(2))
0 < detail.p_overall <= 1
source

computegofstatistic

Siena.compute_gof_statistic — Function
compute_gof_statistic(stat::AbstractGOFStatistic, state::NetworkState,
                      data::SienaData) -> (labels, counts)

Evaluate an auxiliary GOF statistic on one network/behaviour state: the labels of its components and the integer count of each.

Example

using Siena
w = [0 1 1; 0 0 1; 0 0 0]
data = siena_data()
add_dependent!(data, DependentNetwork(:advice, [w, w]))
state = initialize!(NetworkState(), data, 1)
compute_gof_statistic(IndegreeDistribution(:advice; levls=0:2, cumulative=false),
                      state, data)            # (["0", "1", "2"], [1, 1, 1])
source

Convenience Functions

Siena.siena_gof_indegree — Function
siena_gof_indegree(result::SienaResult, data::SienaData, variable::Symbol;
                  kwargs...)

Shorthand for siena_gof(result, data, IndegreeDistribution(variable); kwargs...) (prefer gof).

Example

using Siena, NetworkCore, Random
s50 = load_dataset(:s50)
data = siena_data()
add_dependent!(data, DependentNetwork(:friendship, s50.friendship))
effects = get_effects(data)
include_effects!(effects, :friendship, [:outdegree, :recip])
fit = fit_siena(data, effects; rng=MersenneTwister(1),
                algorithm=SienaAlgorithm(verbose=false, phase3_iterations=200))
siena_gof_indegree(fit, data, :friendship; n_sim=20, rng=Xoshiro(1)).p_overall
source
Siena.siena_gof_outdegree — Function
siena_gof_outdegree(result::SienaResult, data::SienaData, variable::Symbol;
                   kwargs...)

Shorthand for siena_gof(result, data, OutdegreeDistribution(variable); kwargs...) (prefer gof).

Example

using Siena, NetworkCore, Random
s50 = load_dataset(:s50)
data = siena_data()
add_dependent!(data, DependentNetwork(:friendship, s50.friendship))
effects = get_effects(data)
include_effects!(effects, :friendship, [:outdegree, :recip])
fit = fit_siena(data, effects; rng=MersenneTwister(1),
                algorithm=SienaAlgorithm(verbose=false, phase3_iterations=200))
siena_gof_outdegree(fit, data, :friendship; n_sim=20, rng=Xoshiro(1)).p_overall
source
Siena.siena_gof_triad — Function
siena_gof_triad(result::SienaResult, data::SienaData, variable::Symbol;
               kwargs...)

Shorthand for siena_gof(result, data, TriadCensus(variable); kwargs...) (prefer gof).

Example

using Siena, NetworkCore, Random
s50 = load_dataset(:s50)
data = siena_data()
add_dependent!(data, DependentNetwork(:friendship, s50.friendship))
effects = get_effects(data)
include_effects!(effects, :friendship, [:outdegree, :recip])
fit = fit_siena(data, effects; rng=MersenneTwister(1),
                algorithm=SienaAlgorithm(verbose=false, phase3_iterations=200))
siena_gof_triad(fit, data, :friendship; n_sim=20, rng=Xoshiro(1)).p_overall
source
Siena.siena_gof_behavior — Function
siena_gof_behavior(result::SienaResult, data::SienaData, variable::Symbol;
                  kwargs...)

Shorthand for siena_gof(result, data, BehaviorDistribution(variable); kwargs...) (prefer gof).

Example

using Siena, NetworkCore, Random
s50 = load_dataset(:s50)
data = siena_data()
add_dependent!(data, DependentNetwork(:friendship, s50.friendship))
add_dependent!(data, DependentBehavior(:alcohol, [s50.alcohol[:, w] for w in 1:3]))
effects = get_effects(data)
include_effects!(effects, :friendship, [:outdegree, :recip])
include_effects!(effects, :alcohol, [:linear, :quad])
fit = fit_siena(data, effects; rng=MersenneTwister(1),
                algorithm=SienaAlgorithm(verbose=false, phase3_iterations=200))
siena_gof_behavior(fit, data, :alcohol; n_sim=20, rng=Xoshiro(1)).p_overall
source