Data Preparation
This guide covers how to prepare data for SAOM analysis in Siena.jl. The data layer mirrors the RSiena API with Julia-idiomatic types.
Overview
A SAOM analysis requires:
- A node set defining the actors
- One or more dependent variables (networks and/or behaviors) observed at multiple waves
- Optionally, covariates (actor-level or dyadic, constant or varying)
All data is assembled into a SienaData container.
Node Sets
A NodeSet defines the set of actors in the analysis:
using Siena
# Basic: 50 actors with auto-generated names ("1", "2", ...)
nodes = NodeSet(50)
# With custom names
nodes = NodeSet(5; names=["Alice", "Bob", "Carol", "David", "Eve"])
# With a custom identifier (useful for two-mode networks)
students = NodeSet(30; id=:students)
teachers = NodeSet(10; id=:teachers)Node Set Properties
nodes = NodeSet(50)
length(nodes) # 50
nodes.n # 50
nodes.id # :actors (default)
nodes.names # ["1", "2", ..., "50"]A two-mode Network panel (network(n; bipartite=n₁) or BipartiteNetwork, stored directed or undirected) converts the same way, with the incidence matrices as the waves and the ties running from the mode-1 actors to the mode-2 nodes; a directed two-mode network with an arc from mode 2 to mode 1 is refused, since the variable cannot hold it:
using NetworkCore
waves = [network(30; bipartite=20, directed=false) for _ in 1:2]
add_edge!(waves[1], 1, 21); add_edge!(waves[2], 1, 21); add_edge!(waves[2], 2, 25)
membership = DependentNetwork(:membership, waves; nodeset1=:students, nodeset2=:clubs)
size(membership.networks[1]) # (20, 10)Using the Convenience Constructor
nodes = siena_nodeset(50; id=:actors)Dependent Network Variables
A DependentNetwork represents a network observed at multiple time points. Each observation is an adjacency matrix where entry (i, j) = 1 indicates a tie from actor i to actor j.
Creating from Adjacency Matrices
n = 30
# Create adjacency matrices for 3 waves
wave1 = zeros(Int, n, n)
wave2 = zeros(Int, n, n)
wave3 = zeros(Int, n, n)
# Populate with observed data
# (In practice, load from files or DataFrames)
wave1[1, 2] = 1 # Actor 1 -> Actor 2 at wave 1
wave1[2, 1] = 1 # Actor 2 -> Actor 1 at wave 1
wave1[1, 3] = 1 # Actor 1 -> Actor 3 at wave 1
# Create the dependent network
friendship = DependentNetwork(:friendship, [wave1, wave2, wave3])Network Properties
n_waves(friendship) # 3
n_actors(friendship) # 30
friendship.name # :friendship
friendship.directed # true (default)
friendship.type # :onemode (default)Network Options
| Parameter | Type | Default | Description |
|---|---|---|---|
name | Symbol | Required | Variable name |
networks | Vector{Matrix{Int}} | Required | Adjacency matrices |
type | Symbol | :onemode | :onemode, :twomode, or :bipartite |
directed | Bool | true | Whether the network is directed; false declares a symmetric network (see below) |
allow_self_loops | Bool | false | Whether self-ties are allowed |
nodeset1 | Symbol | :actors | ID of the row node set |
nodeset2 | Symbol | nothing | ID of the column node set (bipartite) |
structural_zero | Int | 10 | Code marking a structurally absent tie |
structural_one | Int | 11 | Code marking a structurally present tie |
allow_only | Bool | true | Restrict up-only/down-only periods, as RSiena's allowOnly (see below) |
Up-only and down-only periods
As in RSiena (sienaDependent(allowOnly = TRUE)), a period in which the observed network only gains ties is up-only, and actors can then only create ties in the simulation; a period that only loses ties is down-only, and actors can only drop ties. The same holds for a behaviour whose values only rise or only fall. When every period is up-only (or every period down-only), get_effects offers no outdegree (density) effect, or no linear effect for a behaviour, because RSiena's getEffects does not. The classification is on dep.uponly and dep.downonly. Pass allow_only=false to simulate such periods without the restriction:
w1 = [0 1 0; 0 0 1; 1 0 0]
w2 = [0 1 1; 0 0 1; 1 0 0] # only a tie added: up-only
DependentNetwork(:advice, [w1, w2]).uponly # [true]
DependentNetwork(:advice, [w1, w2]; allow_only=false).uponly # [false]Structural Zeros and Ones (10/11 Coding)
As in RSiena, adjacency matrices may contain the codes 10 (structural zero — the tie is impossible, e.g. between actors who never overlapped) and 11 (structural one — the tie is forced, e.g. a formal relationship). The codes are configurable via structural_zero / structural_one and are validated: any entry other than 0, 1, or the two codes throws an ArgumentError.
w1 = [0 1 11;
0 0 0;
10 0 0] # tie 1->3 forced present, tie 3->1 impossible
w2 = [0 0 11;
1 0 0;
10 0 0]
dep = DependentNetwork(:net, [w1, w2])
has_structural(dep) # true
is_structural_dyad(dep, 1, 1, 3) # true
dep.networks[1] # decoded 0/1 face values (10 -> 0, 11 -> 1)Semantics (first-order port of RSiena's treatment):
- Simulation: during the period starting at wave
m, dyads structurally determined at wavemare excluded from the ministep candidate sets — an actor can never toggle them, so simulated networks keep the determined values. - Estimation: structurally determined entries are excluded from the target and simulated moment statistics (zeroed under the period-start mask on both sides of the moment equation), and observed changes at those entries do not count toward rate statistics.
Limitations vs RSiena: no correction is applied when a dyad's structural status changes between waves beyond using the period-start mask, and siena_gof statistics include structurally determined ties at their face values (identically for observed and simulated networks). Missing data (NA ties) remains unsupported in estimation; composition change is supported per whole period (see below).
Undirected Networks
Pass directed=false for a non-directed relation. Every wave must be symmetric (an asymmetric wave is an ArgumentError). The network evolves under RSiena's default model for symmetric networks, model type 2 (unilateral initiative and reciprocal confirmation): the actor with the opportunity chooses an alter with its objective function and the edge is created or dissolved in both directions. get_effects then offers RSiena's symmetric-network effects (transTriads, degPlus, gwesp, …) and refuses the directed ones (recip, transTrip, …).
undirected = DependentNetwork(:contact, [max.(w, w') for w in (wave1, wave2, wave3)];
directed=false)Two-Mode Networks
For bipartite networks connecting two different types of nodes:
# 20 students connected to 10 clubs
n_students = 20
n_clubs = 10
# Affiliation matrices (student x club)
aff1 = rand(0:1, n_students, n_clubs)
aff2 = rand(0:1, n_students, n_clubs)
membership = DependentNetwork(:membership, [aff1, aff2];
type=:twomode,
nodeset1=:students,
nodeset2=:clubs
)Using the Convenience Constructor
net = siena_dependent(:friendship, [wave1, wave2, wave3])Dependent Behavior Variables
A DependentBehavior represents an ordinal or integer-valued behavior observed across waves. Each observation is a vector of values for all actors.
Creating Behavior Variables
n = 30
# Behavior values at each wave (e.g., substance use on 1-5 scale)
beh_wave1 = rand(1:5, n)
beh_wave2 = rand(1:5, n)
beh_wave3 = rand(1:5, n)
drinking = DependentBehavior(:drinking, [beh_wave1, beh_wave2, beh_wave3])Behavior Properties
n_waves(drinking) # 3
n_actors(drinking) # 30
drinking.name # :drinking
drinking.min_val # 1 (automatically detected)
drinking.max_val # 5 (automatically detected)Specifying Range Explicitly
# Override auto-detected range
exercise = DependentBehavior(:exercise, [beh_wave1, beh_wave2, beh_wave3];
min_val=0, max_val=7
)allow_only=true (the default) restricts a period in which the behaviour only rises to increases, and one in which it only falls to decreases, as for networks (see above).
Using the Convenience Constructor
beh = siena_dependent(:drinking, [beh_wave1, beh_wave2, beh_wave3])Covariates
Covariates are predictor variables that are not modeled as dependent. They can be actor-level or dyadic, and constant or varying across waves.
Constant Covariates
A ConstantCovariate has the same value for each actor across all waves:
# Gender (binary)
gender = constant_covariate(:gender, [0, 1, 0, 1, 1, 0, 0, 1, 1, 0])
# Age (continuous)
age = constant_covariate(:age, [15.2, 16.1, 15.8, 14.9, 16.3, 15.5, 14.7, 15.9, 16.0, 15.1])By default, covariates are centered (mean-subtracted). To disable centering:
# Uncentered
gender_raw = ConstantCovariate(:gender_raw, [0, 1, 0, 1, 1]; center=false)Varying Covariates
A VaryingCovariate has different values at each wave:
# GPA changing over 3 waves
gpa = varying_covariate(:gpa, [
[3.5, 3.2, 3.8, 3.1, 3.6], # Wave 1
[3.6, 3.1, 3.9, 3.3, 3.5], # Wave 2
[3.4, 3.3, 3.7, 3.2, 3.7], # Wave 3
])Constant Dyadic Covariates
A ConstantDyadCovariate is a matrix of values for each pair of actors:
n = 10
# Geographical distance between actors
distances = rand(n, n)
distances = (distances + distances') / 2 # Symmetrize
geo = constant_dyad_covariate(:distance, distances)Varying Dyadic Covariates
A VaryingDyadCovariate changes across waves:
n = 10
# Shared class membership at each wave
shared1 = rand(0:1, n, n)
shared2 = rand(0:1, n, n)
shared3 = rand(0:1, n, n)
shared_class = varying_dyad_covariate(:shared_class, [shared1, shared2, shared3])Covariate Properties
| Type | Fields | Centering |
|---|---|---|
ConstantCovariate | values::Vector{Float64} | Mean-centered by default |
VaryingCovariate | values::Vector{Vector{Float64}} | Overall mean-centered |
ConstantDyadCovariate | values::Matrix{Float64} | Mean of the off-diagonal entries (one-mode), as RSiena |
VaryingDyadCovariate | values::Vector{Matrix{Float64}} | Overall off-diagonal mean |
All covariates store:
name::Symbol– Covariate identifiercentered::Bool– Whether centering was appliedmean::Float64– The mean used for centeringn_imputed::Int– How many missing values were imputed
Missing Covariate Values
A covariate with a missing value (missing or NaN) is refused with an ArgumentError: before 0.2 a single NaN turned the whole centred covariate into NaN and the fit failed deep inside LAPACK. Pass missing=:mean to impute the mean of the observed values, RSiena's default rule. The fit then lists the imputation in approximations(fit); unlike RSiena, the imputed actors still enter the target statistics.
gpa = ConstantCovariate(:gpa, [3.1, NaN, 2.7, 3.9, 3.3]; missing=:mean)
gpa.n_imputed # 1A covariate and a dependent variable cannot share a name: a dependent behaviour is itself available to the covariate effects of the networks (network selection on the behaviour).
Assembling the SienaData Object
The SienaData container holds all data components:
# Create empty container
data = siena_data()
# Add node set (required)
add_nodeset!(data, NodeSet(30))
# Add dependent variables (at least one required)
add_dependent!(data, friendship)
add_dependent!(data, drinking) # Optional second dependent
# Add covariates (optional)
add_covariate!(data, gender)
add_covariate!(data, age)
add_covariate!(data, geo)
println(data)
# SienaData(nodesets=1, dependents=2, covariates=3, waves=3)Validation
The SienaData object validates consistency:
# All dependent variables must have the same number of waves
net_2wave = DependentNetwork(:net2, [wave1, wave2]) # 2 waves
beh_3wave = DependentBehavior(:beh3, [beh_wave1, beh_wave2, beh_wave3]) # 3 waves
data = siena_data()
add_nodeset!(data, NodeSet(30))
add_dependent!(data, net_2wave)
# add_dependent!(data, beh_3wave) # ERROR: Number of waves must be consistentAccessing Data Components
data.nodesets # Dict{Symbol, NodeSet}
data.dependents # Dict{Symbol, AbstractDependent}
data.covariates # Dict{Symbol, AbstractCovariate}
data.n_waves # Number of observation wavesNetwork State
The NetworkState represents the current state of networks and behaviors during simulation. It is primarily used internally but can be useful for inspection:
# Rebuild the full data object (the validation demo above replaced it)
data = siena_data()
add_nodeset!(data, NodeSet(30))
add_dependent!(data, friendship)
add_dependent!(data, drinking)
state = NetworkState()
initialize!(state, data, 1) # Initialize from wave 1
# Access current network
net = state.networks[:friendship] # Matrix{Int}
# Access current behavior
beh = state.behaviors[:drinking] # Vector{Int}
# Current simulation time
state.time # Float64Initializing from Different Waves
# Start from wave 1 (for forward simulation)
initialize!(state, data, 1)
# Start from wave 2 (for period 2 simulation)
initialize!(state, data, 2)Composition Change
If actors join or leave the network between waves, use CompositionChange (RSiena's sienaCompositionChange):
cc = CompositionChange()
# Actor 5 leaves at wave 2 (present at wave 1 only)
add_change!(cc, 5, 2, :leave)
# Actor 3 joins at wave 2 (absent at wave 1)
add_change!(cc, 3, 2, :join)
# Attach to data
add_composition_change!(data, cc)
is_present(cc, 5, 1) # true
is_present(cc, 5, 2) # falseDuring estimation an actor contributes to a period only when present at both of its endpoint waves. Absent actors get no ministep opportunities, their dyads are excluded from the candidate sets, and their rows/columns are excluded from the target and simulated moment statistics and from the observed change (rate) distances.
This is a listwise, whole-period approximation, not RSiena's treatment: RSiena (Huisman & Snijders 2003) places joining and leaving at times within the period and lets an actor take part until it leaves (or from when it joins). Here joining and leaving are wave events, and an actor who leaves during a period is dropped from the whole period, also as an alter of the others. Fits with composition change say so in approximations(fit).
Data Validation Tips
Network Data
- Square matrices: One-mode networks must have square adjacency matrices
- No self-loops: Diagonal entries should be 0 (unless
allow_self_loops=true) - Binary values: Entries should be 0 or 1
- Consistent size: All wave matrices must have the same dimensions
using LinearAlgebra: diagind
waves = friendship.networks # the wave matrices of the dependent above
beh_waves = drinking.values # the behavior waves
# Validate network data
for (w, net) in enumerate(waves)
@assert size(net, 1) == size(net, 2) "Wave $w: matrix not square"
@assert all(net[diagind(net)] .== 0) "Wave $w: self-loops present"
@assert all(x -> x in (0, 1), net) "Wave $w: non-binary values"
endBehavior Data
- Integer values: Behavior values must be integers
- Consistent range: Values should span a reasonable range (typically 1-5 or 1-7)
- Sufficient variation: At least some change between waves is needed
# Check behavior variation
for w in 2:length(beh_waves)
changes = sum(beh_waves[w] .!= beh_waves[w-1])
println("Wave $w: $changes actors changed behavior")
endCovariate Data
- Matching dimensions: Covariate vector length must equal number of actors
- No excessive missing data: NaN values may cause issues
- Centering: Covariates are centered by default for numerical stability
# Check for NaN values
@assert !any(isnan, gender.values) "Covariate has NaN values"
# Verify dimensions match the dependent's actor set (the toy `gender`
# above was built for a 10-actor example, so build a matching one here)
gender_full = constant_covariate(:gender, rand(0:1, n_actors(friendship)))
@assert length(gender_full.values) == n_actors(friendship)Complete Data Setup Example
using Siena
using Random
Random.seed!(42)
# Parameters
n = 40
n_waves_total = 3
# === Generate synthetic data ===
# Network waves with some structure
function generate_network(n, density)
net = zeros(Int, n, n)
for i in 1:n, j in 1:n
if i != j && rand() < density
net[i, j] = 1
end
end
return net
end
waves = [generate_network(n, 0.1) for _ in 1:n_waves_total]
# Behavior waves (ordinal 1-5)
beh_waves = [rand(1:5, n) for _ in 1:n_waves_total]
# Covariates
gender_vals = rand(0:1, n)
age_vals = randn(n) .* 2 .+ 16
# === Assemble ===
data = siena_data()
add_nodeset!(data, NodeSet(n))
add_dependent!(data, DependentNetwork(:net, waves))
add_dependent!(data, DependentBehavior(:beh, beh_waves))
add_covariate!(data, constant_covariate(:gender, gender_vals))
add_covariate!(data, constant_covariate(:age, age_vals))
println(data)
println("Network density wave 1: ", sum(waves[1]) / (n * (n-1)))
println("Behavior range: ", minimum(vcat(beh_waves...)), "-", maximum(vcat(beh_waves...)))