An R package providing fast estimation, simulation, and model selection routines for discrete-time Dynamic Stochastic Block Models (DSBM). The package features an accelerated Classification Expectation-Maximization (CEM) algorithm, an asymmetric M-step, high-performance C++ subroutines powered by Rcpp and Armadillo, and an innovative Perturbed SVD Multi-Start Initialization Strategy.
Developed as part of a Masterβs Thesis in Statistics by Gianfilippo Tito, extending the hybrid estimation methodology of Marino & Pandolfi (2022) to dynamic temporal graph architectures.
π Theoretical Framework
Dynamic Stochastic Block Models extend static stochastic block models to temporal graph structures, allowing the latent block memberships of nodes to transition across discrete time snapshots governed by a first-order Markov chain.
Let denote a binary temporal adjacency tensor observed over vertices across discrete observation horizons. Let be the latent community membership of node at time .
The model parameters are parameterised by :
- Initial class proportions: , where .
- First-order Markov transition matrix: , where and .
- Dyadic connection probability matrix: , where .
The Hybrid Inference Extension
Due to the combinatorial explosion of latent trajectory paths and the multi-modal topography of the complete-data log-likelihood surface, standard local search heuristics frequently get trapped in sub-optimal local extrema.
hdsbm tackles this problem by generalizing the Hybrid Maximum Likelihood approach developed by Marino & Pandolfi (2022) for static SBMs into a dynamic, time-varying paradigm:
- Hybrid Classification EM: Combining continuous posterior probabilities (E-step) with discrete partition adjustments to preserve sharp community boundaries.
- Dynamic Greedy Reallocation Passes: Extending node-by-node greedy swaps across temporal slices, accelerated via C++ subroutines.
- Structured Multi-Start: Coupling deterministic spectral graph embeddings (Truncated SVD) with controlled stochastic perturbations to ensure global likelihood exploration.
π¬ Perturbed SVD Multi-Start Strategy
A key contribution of the package is the Perturbed SVD Multi-Start scheme, combining the asymptotic properties of spectral graph clustering with controlled stochastic exploration of the likelihood landscape.
Temporal Network Tensor Y (n x n x T)
β
βΌ
Time-Averaged Adjacency Matrix Y_mean
β
βΌ
Truncated SVD Decomposition
β
βΌ
K-Means Base Partition (cl_base)
β
βββββββββββββββββββ΄ββββββββββββββββββ
βΌ βΌ
[Base Start] [h = 1, ..., nrep Perturbations]
Tau ~ K-means Perturbation intensity Ξ± ~ U(0.05, 0.35)
Stochastic class reassignment from cl_base
Column-wise normalization -> Taur
β
βΌ
Hybrid CEM Fit with Taur
β
βββββββββββββββββββ¬ββββββββββββββββββ
βΌ
Select Optimal Estimate Based on
Complete-Data Log-Likelihood
Algorithmic Workflow
-
Spectral Base Partitioning:
- Compute the time-averaged network matrix:
- Extract the Singular Value Decomposition (SVD) of and retain the top left singular vectors :
- Run -means on the rows of to construct the deterministic baseline partition .
-
Controlled Stochastic Perturbations:
- For each restart :
- Sample a random perturbation fraction .
- For each node and snapshot , retain with probability , or reassign it to a uniformly chosen alternative block with probability .
- Construct a regularized posterior tensor ( mass on the selected cluster, distributed uniformly across remainder), followed by column normalization:
- For each restart :
-
Global Model Selection:
- Execute the Hybrid CEM engine starting from the baseline and each perturbed state .
- Retain the solution maximizing the complete-data log-likelihood:
β‘ Core Engine Highlights
- Forward-Backward Recursions (E-step): Computes soft responsibilities over hidden temporal transitions via numerically stabilized Hidden Markov Model forward-backward routines.
- Asymmetric M-step: Simultaneously integrates soft continuous responsibilities and hard categorical assignments to update , , and .
-
C++ Accelerated Combinatorial Greedy Search: Accelerates dyadic reallocation passes through compiled C++ subroutines (
src/Core_hyb.cpp) usingRcppArmadillo. -
Dual-Path Decoding: Delivers both pointwise greedy classifications (
cl) and globally optimal Viterbi state trajectories (clv). - Integrated Completed Likelihood (ICL): Tailored penalization criterion separating structural connectivity parameters from Markov chain dynamic parameters.
π Repository Structure
The package follows standard CRAN directory conventions:
hdsbm/
βββ DESCRIPTION # Package metadata, dependencies, and licensing
βββ NAMESPACE # Exported functions and C++ symbol registration
βββ LICENSE / LICENSE.md # MIT License terms
βββ _pkgdown.yml # Documentation website configuration
βββ .Rbuildignore # Rules for packaging and build exclusion
βββ .gitignore # Git ignore configuration for Rcpp binaries and caches
βββ data/
β βββ toy_hdsbm.rda # Built-in synthetic sample dataset
βββ data-raw/
β βββ toy_hdsbm.R # Reproducible data-generation script
βββ inst/
β βββ CITATION # BibTeX and formal academic citation metadata
βββ man/ # Roxygen2 Rd documentation files
βββ R/
β βββ best_perm.R # Hungarian-style label alignment for ARI evaluation
β βββ data.R # Dataset documentation
β βββ draw_sn_dyn.R # Dynamic network generative simulator
β βββ est_hyb_sbm_dyn_dec.R # CEM algorithm with forward-backward & Viterbi passes
β βββ hdsbm_fit.R # Top-level API with SVD multi-start and S3 print methods
β βββ hdsbm-package.R # Package-level documentation and Rcpp registration
β βββ icl_dyn_hyb.R # Standalone ICL functions (icl, ICL, icl_dyn_hyb)
β βββ RcppExports.R # Automatically generated Rcpp wrappers
βββ src/
β βββ Core_hyb.cpp # High-performance C++ likelihood & greedy search functions
β βββ RcppExports.cpp # Compiled Rcpp registration routines
βββ tests/
β βββ testthat.R # Testthat test runner
β βββ testthat/ # Unit tests
βββ Simulation.R # Benchmarking and Monte Carlo simulation script
βοΈ Requirements & Installation
Prerequisites
- R (>= 3.5.0) (R >= 4.0 recommended).
- A functional C++ compiler with C++11 support:
-
macOS: Xcode Command Line Tools (
xcode-select --install). - Windows: Rtools matching your R version.
-
Linux:
g++orclang++(build-essentialon Debian/Ubuntu).
-
macOS: Xcode Command Line Tools (
Install via remotes / devtools
You can install hdsbm directly from GitHub:
# If not already installed:
install.packages("remotes")
# Install hdsbm directly from GitHub:
remotes::install_github("Titolise/Hybrid-DSBMs")Or clone the repository and build locally:
π Quick Start Guide
1. Using the Included Dataset (toy_hdsbm)
The package includes a ready-to-use temporal network dataset toy_hdsbm ( nodes, latent classes, snapshots):
library(hdsbm)
library(mclust)
# 1. Load the dataset (available lazily)
data(toy_hdsbm)
# 2. Fit the model with 5 perturbed spectral restarts
model <- hdsbm_fit(
Y = toy_hdsbm$Y,
k = 3,
nrep = 5,
seed = 123
)
# 3. Print summary results (S3 method)
print(model)
# 4. Evaluate clustering accuracy vs. ground truth
ari_greedy <- adjustedRandIndex(model$best_fit$cl, toy_hdsbm$U_true)
ari_viterbi <- adjustedRandIndex(model$best_fit$clv, toy_hdsbm$U_true)
cat(sprintf("Adjusted Rand Index (Pointwise Greedy): %.4f\n", ari_greedy))
cat(sprintf("Adjusted Rand Index (Global Viterbi): %.4f\n", ari_viterbi))
# 5. Extract Model Selection Criterion (ICL)
icl(model)2. Simulating and Estimating a Dynamic Network
Generate synthetic dynamic networks and test different persistent Markov regimes:
library(hdsbm)
# Dimensional parameters
n <- 30 # Nodes
k <- 3 # Communities
TT <- 5 # Time windows
# Ground-truth parameters
piv0 <- rep(1 / k, k)
# High persistence Markov transition matrix
rho <- 0.1
Pi0 <- rho^abs(outer(seq_len(k), seq_len(k), "-"))
Pi0 <- sweep(Pi0, 1, rowSums(Pi0), "/")
# Assortative connectivity matrix (high within-group, low between-group)
Psi0 <- matrix(0.04, nrow = k, ncol = k)
diag(Psi0) <- c(0.35, 0.40, 0.45)
# Simulate dynamic network
sim <- draw_sn_dyn(n = n, k = k, TT = TT, piv = piv0, Pi = Pi0, Psi = Psi0)
# Estimate with SVD multi-start
fit <- hdsbm_fit(
Y = sim$Y,
k = k,
nrep = 10,
maxit = 150,
seed = 42,
verbose = TRUE
)
# Access estimated parameters
print(fit)
# Compute numeric ICL or inspect penalty decomposition
icl(fit)
icl(fit, detailed = TRUE)3. Model Selection across different
# Fit models for candidate block counts k in 2:4
k_candidates <- 2:4
fits <- lapply(k_candidates, function(k_val) {
hdsbm_fit(toy_hdsbm$Y, k = k_val, nrep = 5, verbose = FALSE)
})
# Compare ICL scores (higher is better)
scores <- sapply(fits, icl)
names(scores) <- paste0("k=", k_candidates)
print(scores)
best_k <- k_candidates[which.max(scores)]
cat(sprintf("Optimal number of communities selected by ICL: k = %d\n", best_k))π Function Reference
| Function | Description |
|---|---|
hdsbm_fit(Y, k, nrep, ...) |
Main API function. Runs the Hybrid CEM engine using the Perturbed SVD multi-start strategy and returns an S3 hdsbm object. |
icl(object, detailed = FALSE, ...) |
Computes the Integrated Completed Likelihood (ICL) criterion (returns a scalar or detailed penalty list). Also aliased as ICL(). |
draw_sn_dyn(n, k, TT, piv, Pi, Psi) |
Generates synthetic dynamic network tensors and true latent paths under the DSBM framework. |
best_perm(Utrue, Uprop) |
Finds the optimal permutation of class labels to match estimated clusters to ground truth. |
est_pred_sbm_dyn_decoding(Y, k, ...) |
Low-level estimation routine executing the Hybrid CEM algorithm with Viterbi decoding. |
icl_dyn_hyb(out_pred, ...) |
Legacy interface for computing the ICL with detailed breakdown. |
π Evaluation & Model Selection
- Adjusted Rand Index (ARI): Evaluates partition recovery accuracy against ground-truth community trajectories, invariant to label switching.
- Integrated Completed Likelihood (ICL): Penalizes connection probabilities, transition matrices, and initial distributions separately to guarantee consistent model selection.
π Citation & References
Methodological Foundation
The hybrid inference framework implemented in this package builds upon and extends the hybrid maximum likelihood estimation strategy for static stochastic block models proposed by:
- Marino, M. F., & Pandolfi, S. (2022). Hybrid maximum likelihood inference for stochastic block models. Computational Statistics & Data Analysis, 171, 107452. https://doi.org/10.1016/j.csda.2022.107452
BibTeX:
@article{marino2022hybrid,
title = {Hybrid maximum likelihood inference for stochastic block models},
author = {Marino, Maria Francesca and Pandolfi, Silvia},
journal = {Computational Statistics \& Data Analysis},
volume = {171},
pages = {107452},
year = {2022},
publisher = {Elsevier},
doi = {10.1016/j.csda.2022.107452}
}π License & Author
- Author: Gianfilippo Tito (gianfilippotito@gmail.com)
- License: Released under the MIT License.