Package {normalblockr}


Type: Package
Title: Gaussian Models with Latent Clustering of Variables
Version: 1.0.0
Description: Implements two families of Gaussian models with a latent clustering of the variables, for multivariate data whose variables co-vary, or respond to covariates, in groups. In the Normal-Block-Var model, the clusters structure the covariance through latent variables, and a network is inferred between the clusters rather than between the variables, which reduces its dimension and eases its interpretation (Tous and Chiquet (2026) <doi:10.1016/j.csda.2026.108347>). In the Normal-Block-Mean model, the variables of a cluster share the same regression profile, and a network between the variables can be inferred from their residual covariance. In both families, the clustering is either known or inferred, the network can be sparse (graphical lasso), and zero-inflated variants handle data with an excess of zeros. The parameters are estimated by expectation-maximization or variational expectation-maximization algorithms, accelerated by squared extrapolation, and a split and merge procedure improves the fits of a collection of models. The number of clusters, the sparsity of the network and the shape of the covariance are chosen with penalized criteria, cross-validation or stability selection.
License: GPL (≥ 3)
URL: https://github.com/jchiquet/normalblockr, https://jchiquet.github.io/normalblockr/
BugReports: https://github.com/jchiquet/normalblockr/issues
Encoding: UTF-8
LazyData: true
Depends: R (≥ 4.1.0)
Imports: Matrix, purrr, R6, ggplot2, igraph, sbm, corrplot, MASS, stats, Rcpp
LinkingTo: Rcpp, RcppArmadillo
Suggests: testthat (≥ 3.0.0), aricode, covr, rmarkdown, pheatmap, paletteer, ggthemes, knitr
Config/testthat/edition: 3
VignetteBuilder: knitr
Config/roxygen2/version: 8.1.0
NeedsCompilation: yes
Packaged: 2026-11-23 15:12:20 UTC; jchiquet
Author: Jeanne Tous [aut], Julien Chiquet ORCID iD [aut, cre], Nestor Ngalala Manguitini [aut]
Maintainer: Julien Chiquet <julien.chiquet@inrae.fr>
Repository: CRAN
Date/Publication: 2026-11-23 17:30:03 UTC

normalblockr: Gaussian Models with Latent Clustering of Variables

Description

Implements two families of Gaussian models with a latent clustering of the variables, for multivariate data whose variables co-vary, or respond to covariates, in groups. In the Normal-Block-Var model, the clusters structure the covariance through latent variables, and a network is inferred between the clusters rather than between the variables, which reduces its dimension and eases its interpretation (Tous and Chiquet (2026) doi:10.1016/j.csda.2026.108347). In the Normal-Block-Mean model, the variables of a cluster share the same regression profile, and a network between the variables can be inferred from their residual covariance. In both families, the clustering is either known or inferred, the network can be sparse (graphical lasso), and zero-inflated variants handle data with an excess of zeros. The parameters are estimated by expectation-maximization or variational expectation-maximization algorithms, accelerated by squared extrapolation, and a split and merge procedure improves the fits of a collection of models. The number of clusters, the sparsity of the network and the shape of the covariance are chosen with penalized criteria, cross-validation or stability selection.

Author(s)

Maintainer: Julien Chiquet julien.chiquet@inrae.fr (ORCID)

Authors:

See Also

Useful links:


Bayesian Information Criterion for a Normal-Block Model

Description

Extracts the (variational) BIC of a fitted normal-block model, computed as deviance + penalty (lower is better). The penalty charges each group of parameters the log of the number of observations informing it (see the penalty_terms field of NormalBlockBase), so it differs from stats::BIC()'s default log(nobs) * df computed from logLik().

Usage

## S3 method for class 'NormalBlockBase'
BIC(object, ...)

Arguments

object

An object of class NormalBlockBase.

...

not used, only here for S3 compatibility

Value

A scalar: the (variational) BIC.

Examples

ex_data <- generate_normal_block_var_data(n = 50, p = 20, d = 1, q = 3)
data <- NormalBlockData$new(ex_data$Y, ex_data$X)
model <- normal_block(data, blocks = 3, control = NB_control(verbose = FALSE))
BIC(model)

Bayesian Information Criterion for a Collection of Normal-Block Models

Description

Returns the (variational) BIC of every model in a collection of normal-block models.

Usage

## S3 method for class 'NormalBlockCollection'
BIC(object, ...)

Arguments

object

An object inheriting from NormalBlockCollection.

...

not used, only here for S3 compatibility

Value

A numeric vector of BIC values, one per model in the collection.

Examples

ex_data <- generate_normal_block_var_data(n = 50, p = 20, d = 1, q = 3)
data <- NormalBlockData$new(ex_data$Y, ex_data$X)
models <- normal_block(data, blocks = 2:5, control = NB_control(verbose = FALSE))
BIC(models)

Control Parameters for Normal-Block Models

Description

Control the model settings and various optimization parameters

Usage

NB_control(
  niter = 500,
  threshold = 1e-04,
  fixed_point_niter = 5,
  sparsity_weights = NULL,
  sparsity_penalties = NULL,
  n_sparsity_penalties = 30,
  min_ratio = 0.01,
  fixed_tau = FALSE,
  clustering_init = NULL,
  verbose = TRUE,
  heuristic = FALSE,
  noise_covariance = NULL,
  refine = TRUE,
  acceleration = NULL
)

Arguments

niter

maximal number of (V)EM iterations.

threshold

the (V)EM stops when the objective (log-likelihood or ELBO) increases by less than this. A negative value runs exactly niter iterations, without the warning issued when niter is reached.

fixed_point_niter

number of sweeps of the tau update for Normal-Block-Mean models with unknown clusters. Each sweep visits the rows of tau sequentially and maximizes the ELBO exactly in each, so it can never decrease the ELBO.

sparsity_weights

a symmetric matrix of weights applied to the penalty, entry by entry: q x q (variance-block) or p x p (mean-block). By default, 1 off the diagonal and 0 on it (the diagonal is not penalized).

sparsity_penalties

the penalties of a sparsity path (sparsity = TRUE). By default, n_sparsity_penalties values from the smallest penalty that removes every edge down to min_ratio times it, on a log scale.

n_sparsity_penalties

number of penalties of the default path.

min_ratio

ratio between the smallest and the largest penalty of the default path.

fixed_tau

whether the posterior cluster probabilities stay at their initial value (clustering_init) during the optimization; used to refit a sparsity path with its clustering held fixed (stability selection).

clustering_init

how to obtain the initial clustering of the q unknown blocks: a heuristic name ("ward2", "kmeans", "sbm" or "spectral"), an actual clustering (a vector of labels or a p x q indicator matrix, or a list of either per q for a collection), or "best_of_inits" to try several heuristics per model and keep the best-ELBO fit (see NormalBlockBase's best_of_inits(); not supported with sparsity = TRUE). Default NULL, i.e. "kmeans" for both model families; "ward2" can work better on zero-inflated abundance data.

verbose

whether to print the progress of the optimization.

heuristic

whether to use the heuristic approach (moment-based, no (V)EM recursion) instead of the full (V)EM. Default is FALSE. In heuristic mode, no likelihood/ELBO is computed, so entropy, loglik, BIC, ICL and EBIC are all NA on the resulting model.

noise_covariance

shape of the residual covariance. Variance-block models accept "diagonal" (variable-specific) or "spherical" (common); mean-block models, whose Sigma is the full p x p residual covariance, also accept "full". Default NULL, resolved per model family at fit time to "diagonal" – except for a mean-block model with sparsity > 0, which implies "full" since a penalty on a diagonal precision matrix would have nothing to act on (explicitly asking for both is an error). A full Sigma has many parameters and needs n > p; use it when the residual associations between variables are of interest.

refine

for collections over a range of cluster counts (both families): whether optimize() automatically calls refine() afterwards. Default TRUE: the split and merge search repairs the poor local optima that independent fits can leave, at a few times the cost of the collection. With FALSE, collection$refine() can be called later.

acceleration

whether the (V)EM is accelerated by SQUAREM (Varadhan & Roland, 2008), an extrapolation built on two successive (V)EM steps and accepted only if it does not lower the objective. Default NULL: on, except for mean-block models with a diagonal or spherical Sigma, whose EM is exact and fast. TRUE or FALSE forces it. Never used when sparsity > 0.

Value

A named list of parameters to pass to normal_block()'s control argument.

Examples

ex_data <- generate_normal_block_var_data(n = 50, p = 20, d = 1, q = 3)
data <- NormalBlockData$new(ex_data$Y, ex_data$X)
## silent fits, without the split and merge search
ctrl <- NB_control(verbose = FALSE, refine = FALSE)
collection <- normal_block(data, blocks = 2:4, control = ctrl)
summary(collection)

Root Base Class for Normal-Block Models

Description

R6 abstract class shared by the variance-block (NormalBlockVarBase) and mean-block (NormalBlockMeanBase) model families.

Public fields

data

object of NormalBlockData class, with responses and design matrix

Active bindings

inference_method

inference procedure used (heuristic or integrated with EM)

n

number of samples

p

number of responses per sample

d

number of variables (dimensions in X)

d0

number of zero-inflation covariates (dimensions in X0)

who_am_I

a description of the model

q

number of blocks

n_edges

number of edges of the network (non null coefficient of the sparse precision matrix Omega)

objective

evolution of the objective function during (V)EM algorithm

loglik

(or its variational lower bound)

deviance

(or its variational lower bound)

entropy

entropy of the (variational) posterior distribution of the clustering, -sum(tau * log(tau)): 0 when the clustering is known. Only the discrete partition is completed, as in the ICL of Biernacki, Celeux and Govaert (2000); the latent vectors W of the variance-block family are integrated out, not completed.

penalty_terms

data frame with one row per group of parameters: its name (group), its number of free parameters (nu) and the number of independent observations informing it (N), so that the group costs nu * log(N) in the BIC. As in the ICL of Daudin, Picard and Robin (2008) for SBMs and Keribin et al. (2015) for latent block models, the cluster proportions are charged log(p) (the variables are the units being clustered), parameters shared by every cell of a block log(n * p), and the remaining ones log(n).

nb_param

number of free parameters in the model, sum(penalty_terms$nu)

penalty

BIC penalty, sum(nu * log(N)) over penalty_terms

BIC

Bayesian information criterion, deviance + penalty (lower is better); built on the ELBO when the clustering is unknown and the likelihood is not available in closed form.

ICL

integrated completed likelihood criterion, BIC + 2 * entropy (lower is better); equal to the BIC when the clustering is known.

EBIC

extended BIC of Foygel and Drton (2010) with gamma = 1/2, BIC + 2 * n_edges * log(dim), where dim is the dimension of the network: q for the variance-block family (network between clusters), p for the mean-block family (network between variables).

criteria

a vector with loglik, BIC and number of parameters

sparsity

(overall sparsity parameter)

sparsity_term

(sparsity_term term in log-likelihood due to sparsity)

memberships

the p x q matrix of cluster memberships: indicators for a known clustering, posterior probabilities (tau) otherwise

clustering

the cluster label of each variable (MAP for an unknown clustering), named after the columns of Y

cluster_sizes

given as a vector of cluster sizes

elements_per_cluster

given as the list of elements contained in each cluster

Methods

Public methods


NormalBlockBase$new()

Create a new NormalBlockBase object.

Usage
NormalBlockBase$new(data, q, sparsity = 0, control, zero_inflation = FALSE)
Arguments
data

object of NormalBlockData class, with responses and design matrix

q

number of block/cluster

sparsity

sparsity penalty on the network density

control

structured list of more specific parameters, to generate with NB_control

zero_inflation

whether the concrete subclass models zero-inflation; set by the ZI subclasses themselves, not meant to be set by the end user. When FALSE, the (costly) zero-inflation probability fit (kappa/B0) is skipped entirely, since it would otherwise never be used downstream.

Returns

A new NormalBlockBase object


NormalBlockBase$update()

Update the parameters of a model in place. Each argument applies to the families or variants named in parentheses; NA (the default) leaves the parameter unchanged.

Usage
NormalBlockBase$update(
  B = NA,
  dm1 = NA,
  C = NA,
  Omega = NA,
  gamma = NA,
  mu = NA,
  alpha = NA,
  M = NA,
  S = NA,
  ll_list = NA,
  warm_started = NA,
  clustering_init = NA
)
Arguments
B

regression coefficients (all models)

dm1

inverse noise variances of the variables (variance-block)

C

cluster memberships: indicators, or posterior probabilities (all models)

Omega

precision matrix: between clusters (variance-block) or between variables (mean-block)

gamma

posterior variance of W (variance-block, known clusters)

mu

posterior mean of W (variance-block, known clusters)

alpha

cluster proportions (unknown clusters)

M

variational means of W (variance-block, unknown clusters)

S

variational variances of W (variance-block, unknown clusters)

ll_list

list of log-lik (elbo) values

warm_started

whether optim_initialize() should treat the model as already initialized (reuse B/Omega/dm1/C/alpha/M/S as they stand) rather than recomputing a fresh heuristic initialization. Set by ⁠$warm_start_from()⁠ and by ⁠$split()⁠/⁠$merge()⁠.

clustering_init

initial clustering

Returns

Update the current object in place


NormalBlockBase$optimize()

calls optimization (EM or heuristic) and updates relevant fields

Usage
NormalBlockBase$optimize(
  control = list(niter = 500, threshold = 1e-04, fixed_point_niter = 5),
  warn = TRUE
)
Arguments
control

a list for controlling the optimization process

warn

whether to warn when the (V)EM stops at the niter cap without reaching threshold (see private$warn_if_not_converged()). Set to FALSE for deliberately-truncated trial fits (cheap candidate scoring in candidates_split()/candidates_merge(), the sparsity-path warm-start probe in NormalBlockCollectionSparsity) where stopping at the cap is expected and not a sign of trouble.

Returns

optimizes the model and updates its parameters


NormalBlockBase$best_of_inits()

Try several clustering-initialization heuristics and keep the best-ELBO converged fit (see NB_control()'s clustering_init for the heuristics and the rationale behind the default). Every candidate is first screened with a short trial_niter run (same idea as candidates_split()/candidates_merge()), and only the max_training best-screened ones are fully retrained with control.

Usage
NormalBlockBase$best_of_inits(
  inits = private$default_inits,
  trial_niter = 10,
  max_training = 2,
  control = list(niter = 500, threshold = 1e-04, fixed_point_niter = 5)
)
Arguments
inits

vector of clustering-heuristic names to try; defaults to the model family's own preferred order (private$default_inits)

trial_niter

number of (V)EM iterations used to cheaply screen every candidate in inits before fully retraining the best few

max_training

how many of the screened candidates (best loglik after trial_niter iterations) get fully retrained with control

control

optimize() control list (niter/threshold) used for the final full retraining of the max_training best candidates

Returns

a new, already-optimized model. Does not mutate the current object; reassign the result (model <- model$best_of_inits()).


NormalBlockBase$warm_start_from()

Seed this model's starting parameters from another, already-optimized model of the same family and q, instead of a fresh heuristic clustering. Used by the sparsity paths to warm-start each penalty from the previous one's solution.

Usage
NormalBlockBase$warm_start_from(other)
Arguments
other

a model of the same class, already optimized

Returns

Update the current object in place with other's parameters


NormalBlockBase$candidates_split()

generate and select a set of candidate models by splitting the clusters of the current model

Usage
NormalBlockBase$candidates_split(trial_niter = 5, split_rule = NULL)
Arguments
trial_niter

number of (V)EM iterations used to cheaply score each candidate before the caller fully re-optimizes the best few – kept short on purpose.

split_rule

passed to split() as its rule: "kmeans", "noise", or NULL for the family's default


NormalBlockBase$candidates_merge()

generate and select a set of candidate models by merging the clusters of the current model

Usage
NormalBlockBase$candidates_merge(max_candidates = 30, trial_niter = 2)
Arguments
max_candidates

merge candidates are, unlike split's, quadratic in q (choose(q, q-2) pairs): beyond max_candidates pairs, only the most promising ones are actually built and trial-optimized, ranked by the family's own private$merge_score(). Set to Inf to always try every pair.

trial_niter

see ⁠$candidates_split()⁠


NormalBlockBase$heldout_loglik()

Log-likelihood of new observations at the fitted parameters and, for an unknown clustering, at the MAP partition (see normal_block_cv()). It is exact, computed for variance-block models with q x q matrices only (Woodbury identity), and given on Y's original scale.

Usage
NormalBlockBase$heldout_loglik(newdata, per_observation = FALSE)
Arguments
newdata

a NormalBlockData object with the same variables and covariates (and zero-inflation covariates) as the training data.

per_observation

whether to return one value per observation rather than their sum.

Returns

the held-out log-likelihood, or a vector of newdata$n values


NormalBlockBase$predict()

Predicts the mean of Y for new covariates X, in Y's original units. For the variance-block family, ⁠X B⁠: the latent block signals average out, so that on the training X it differs from fitted(), which adds their posterior mean. The mean-block family overrides it.

Usage
NormalBlockBase$predict(new_X)
Arguments
new_X

new set of covariates.

Returns

A n*p prediction matrix for new observations


NormalBlockBase$latent_network()

Extract the network encoded by Omega, as a matrix rather than a plot (see ⁠$plot_network()⁠): between clusters for the variance-block family, between variables for the mean-block family.

Usage
NormalBlockBase$latent_network(type = c("partial_cor", "support", "precision"))
Arguments
type

edge value in the network: "support" (binary edges), "precision" (entries of the precision matrix, on the scale of the fit) or "partial_cor" (partial correlations)

Returns

a sparse square matrix, q x q (variance-block) or p x p (mean-block), with named rows and columns


NormalBlockBase$plot_loglik()

plots the evolution of the objective (log-likelihood or ELBO) across the (V)EM iterations of the last call to optimize().

Usage
NormalBlockBase$plot_loglik(show_increment = TRUE)
Arguments
show_increment

whether to add a second panel with the (log10) absolute increment between iterations and the convergence threshold (distinguishes true convergence from a flat-looking objective trace).

Returns

a ggplot2::ggplot graph


NormalBlockBase$plot_network()

Plot the network encoded by Omega (see ⁠$latent_network()⁠ to extract it as a matrix).

Usage
NormalBlockBase$plot_network(
  type = c("partial_cor", "support"),
  output = c("igraph", "corrplot"),
  edge.color = c("#F8766D", "#00BFC4"),
  remove.isolated = FALSE,
  node.labels = NULL,
  layout = igraph::layout_in_circle,
  plot = TRUE
)
Arguments
type

edge value in the network: "partial_cor" (partial correlations) or "support" (binary edges).

output

Output type. Either igraph (for the network) or corrplot (for the adjacency matrix)

edge.color

Length 2 color vector. Color for positive/negative edges. Default is c("#F8766D", "#00BFC4"). Only relevant for igraph output.

remove.isolated

if TRUE, isolated node are remove before plotting. Only relevant for igraph output.

node.labels

vector of character. The labels of the nodes. By default, the cluster names (variance-block) or the variable names (mean-block), as in ⁠$latent_network()⁠.

layout

an igraph layout function, applied to the graph without its edge weights, or a matrix of node coordinates. Only relevant for igraph output.

plot

logical. Should the final network be displayed or only sent back to the user. Default is TRUE.


NormalBlockBase$plot()

plots the evolution of the objective during model optimization (see plot_loglik())

Usage
NormalBlockBase$plot()

NormalBlockBase$print()

User friendly print method

Usage
NormalBlockBase$print(model = paste0("A ", self$who_am_I, ".\n"))
Arguments
model

First line of the print output


NormalBlockBase$clone()

The objects of this class are cloneable with this method.

Usage
NormalBlockBase$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples

# An internal abstract base class, never instantiated directly -- see
# normal_block() for how concrete models are created and fitted.

Base Class for a Collection of Normal-Block Models

Description

Shared scaffolding for the collections explored by get_model()/ normal_block(): a sweep over sparsity penalties (NormalBlockVarCollectionSparsity), over the number of clusters (NormalBlockVarCollectionClusters), or over both (NormalBlockVarCollectionClustersSparsity). Concrete subclasses set private$progress_field/private$progress_label in their initialize() and provide their own get_best_model(), delegating the (row of self$criteria minimizing a criterion) lookup to private$best_id().

Public fields

models

list of models (or sub-collections) explored by the collection

control

store the list of user-defined model settings and optimization parameters

Active bindings

who_am_I

a description of the collection: the kind of models it holds and what varies across them

criteria

a data frame with the values of some criteria for the collection of models

loglik

not defined for a collection: accessing it raises an informative error. Use logLik() for every model's log-likelihood, or ⁠$get_best_model()$loglik⁠ for a single one.

Methods

Public methods


NormalBlockCollection$optimize()

optimizes every model (or sub-collection) in the collection

Usage
NormalBlockCollection$optimize(
  control = list(niter = 500, threshold = 1e-04, verbose = TRUE)
)
Arguments
control

optimization parameters (niter and threshold). When control$clustering_init is "best_of_inits", each leaf model is fit via its own best_of_inits() instead of a plain optimize().


NormalBlockCollection$print()

User-friendly print method: model type and the range of q/sparsity explored. See summary() for the full criteria table.

Usage
NormalBlockCollection$print()

NormalBlockCollection$summary()

Summarize the collection: model type, full criteria table, and the range of q/sparsity explored.

Usage
NormalBlockCollection$summary()
Returns

An object of class summary.NormalBlockCollection, printed with a dedicated print.summary.NormalBlockCollection() method.


NormalBlockCollection$clone()

The objects of this class are cloneable with this method.

Usage
NormalBlockCollection$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples

# An internal abstract base class, never instantiated directly -- see
# normal_block() for how collections (NormalBlockVarCollectionClusters,
# NormalBlockVarCollectionSparsity, NormalBlockVarCollectionClustersSparsity)
# are actually created and fitted.

Base Class for a Collection of Models over a Range of Cluster Counts

Description

Shared scaffolding for NormalBlockVarCollectionClusters and NormalBlockMeanCollectionClusters: the models of the collection, one per q in increasing order, model lookup and selection, the criteria plot and the split/merge refine() search. Concrete subclasses only name the model family.

Super class

NormalBlockCollection -> NormalBlockCollectionClusters

Active bindings

q_list

number of blocks

deviance_violations

the values of q whose deviance is higher than at the previous q of the collection. The models being nested, each one signals a poor local optimum, which refine() can repair.

Methods

Public methods

Inherited methods

NormalBlockCollectionClusters$new()

Create a collection over a range of q, sorted increasingly.

Usage
NormalBlockCollectionClusters$new(
  mydata,
  q_list,
  zero_inflation = FALSE,
  sparsity = 0,
  control = NB_control()
)
Arguments
mydata

object of NormalBlockData class, with responses and design matrix

q_list

values of q (number of clusters) in the collection

zero_inflation

whether the models of the collection are zero-inflated

sparsity

sparsity penalty on the network density

control

structured list of more specific parameters, to generate with NB_control

Returns

A new collection object


NormalBlockCollectionClusters$get_model()

The model of the collection with q clusters.

Usage
NormalBlockCollectionClusters$get_model(q)
Arguments
q

a number of clusters among those of the collection (⁠$q_list⁠)

Returns

a fitted model, of the class of the collection's models


NormalBlockCollectionClusters$get_best_model()

The best model of the collection for a criterion.

Usage
NormalBlockCollectionClusters$get_best_model(
  crit = c("ICL", "BIC", "EBIC", "deviance")
)
Arguments
crit

the criterion minimized: "ICL" (the default), "BIC", "EBIC", or "deviance" (which always selects the largest q)

Returns

a copy of the selected fitted model


NormalBlockCollectionClusters$plot()

Plot the criteria of the models of the collection against q, with a dashed line at the q selected by each criterion (see also plot.NormalBlockCollection()).

Usage
NormalBlockCollectionClusters$plot(
  criteria = c("deviance", "ICL", "BIC", "EBIC")
)
Arguments
criteria

the criteria to plot, among "deviance", "ICL", "BIC" and "EBIC"; all of them by default.

Returns

a ggplot2::ggplot graph


NormalBlockCollectionClusters$optimize()

optimizes every model in the collection, then – if control$refine is TRUE (see NB_control(), the default) – calls ⁠$refine()⁠ automatically, reporting in one line how many models it improved.

Usage
NormalBlockCollectionClusters$optimize(
  control = list(niter = 500, threshold = 1e-04, verbose = TRUE)
)
Arguments
control

optimization parameters (niter, threshold, verbose)


NormalBlockCollectionClusters$refine()

Tries to improve every model in the collection with a short split-and-reoptimize trial seeded from its smaller-q neighbor ("split"), a short merge-and-reoptimize trial seeded from its larger-q neighbor ("merge"), or both (the default); a candidate replaces the original only if it strictly lowers the deviance, so this can only improve (or leave unchanged) each model it touches. Only contiguous q pairs (q and ⁠q -/+ 1⁠, both present in the collection) are refined. Run by default after fitting a collection, see NB_control()'s refine for the rationale.

Usage
NormalBlockCollectionClusters$refine(
  trial_niter = 2,
  max_candidates = 30,
  directions = c("split", "merge"),
  verbose = self$control$verbose,
  split_rule = NULL
)
Arguments
trial_niter

number of EM iterations used for the cheap trial candidates (passed to candidates_split()/candidates_merge()) before fully re-optimizing only the best one.

max_candidates

passed to candidates_merge() (ignored for "split", which is never combinatorial in q) – see its documentation.

directions

which neighbor(s) to seed refinement candidates from: "split" (smaller-q neighbor), "merge" (larger-q neighbor), or both (the default).

verbose

whether to print, for each q attempted, whether the candidate from that neighbor improved on it. Defaults to control$verbose (the value set at construction, see NB_control()).

split_rule

how a cluster is split to seed the q + 1 model, see the rule argument of the models' split(): "kmeans", "noise", or NULL (default) for the family's own default ("kmeans" for the variance-block family, "noise" for the mean-block one).

Returns

invisibly returns self; improved models replace the originals in ⁠$models⁠ in place.


NormalBlockCollectionClusters$print()

User-friendly print method: as for any collection, plus a warning line when the deviance increases with q somewhere (see deviance_violations).

Usage
NormalBlockCollectionClusters$print()

NormalBlockCollectionClusters$clone()

The objects of this class are cloneable with this method.

Usage
NormalBlockCollectionClusters$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples

# An internal abstract base class, never instantiated directly -- see
# normal_block() for how collections are created and fitted.

Base Class for a Collection over Cluster Counts and Sparsity Levels

Description

Shared scaffolding for NormalBlockVarCollectionClustersSparsity and NormalBlockMeanCollectionClustersSparsity: a collection of sparsity sub-collections, one per q in increasing order. Everything lives here (two-key model lookup, model selection over both axes, the criteria heatmap); subclasses only name the model family.

Super class

NormalBlockCollection -> NormalBlockCollectionClustersSparsity

Active bindings

q_list

number of blocks

sparsity

list of penalties used for each q

Methods

Public methods

Inherited methods

NormalBlockCollectionClustersSparsity$new()

Create a collection over a range of q, sorted increasingly, with a sparsity path for each q.

Usage
NormalBlockCollectionClustersSparsity$new(
  mydata,
  q_list,
  zero_inflation = FALSE,
  control = NB_control()
)
Arguments
mydata

object of NormalBlockData class, with responses and design matrix

q_list

values of q (number of clusters) in the collection

zero_inflation

whether the models of the collection are zero-inflated

control

structured list of parameters to handle sparsity control

Returns

A new collection object


NormalBlockCollectionClustersSparsity$get_model()

returns a collection of models corresponding to given q or one single model if penalty is also given

Usage
NormalBlockCollectionClustersSparsity$get_model(q, sparsity = NA)
Arguments
q

number of blocks asked by user.

sparsity

sparsity penalty asked by user

Returns

either a sparsity sub-collection or a single model object


NormalBlockCollectionClustersSparsity$get_best_model()

Extract best model in the collection

Usage
NormalBlockCollectionClustersSparsity$get_best_model(
  crit = c("ICL", "BIC", "EBIC")
)
Arguments
crit

a character for the criterion used to performed the selection. Either "BIC", "EBIC" or "ICL". "ICL" is the default criterion

Returns

a single fitted model object


NormalBlockCollectionClustersSparsity$plot()

Plot one criterion as a heatmap over q and the penalty (see also plot.NormalBlockCollection()).

Usage
NormalBlockCollectionClustersSparsity$plot(
  criterion = c("deviance", "ICL", "BIC", "EBIC"),
  n_intervals = NULL
)
Arguments
criterion

the criterion to plot, among "deviance" (the default), "ICL", "BIC" and "EBIC".

n_intervals

number of intervals into which the range of the penalties is split

Returns

a ggplot2::ggplot heatmap


NormalBlockCollectionClustersSparsity$clone()

The objects of this class are cloneable with this method.

Usage
NormalBlockCollectionClustersSparsity$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples

# An internal abstract base class, never instantiated directly -- see
# normal_block() for how collections are created and fitted.

Base Class for a Collection of Models over a Sparsity Path

Description

Shared scaffolding for NormalBlockVarCollectionSparsity and NormalBlockMeanCollectionSparsity: the penalty grid, the warm-started path traversal, the penalty lookup and the criteria plot. Model selection, StARS included (stability selection, Liu et al. 2010), is shared: a family only says on which covariance estimate the default penalty grid is read (private$penalty_scale()), how to refit its path on a subsample with the clustering held fixed (private$subsample_path()) and how to name the nodes of its network (private$network_nodes()).

Super class

NormalBlockCollection -> NormalBlockCollectionSparsity

Public fields

data

object of NormalBlockData class, with responses and design matrix

Active bindings

sparsity_details

number, range and ratio of the penalties of the path

q

number of blocks

blocks

group matrix or number of blocks

sparsity

list of sparsity penalties

criteria

a data frame with the criteria of every model of the path, plus its StARS stability once stability_selection() has run

stability_path

selection probability of every edge at every penalty (StARS), NULL until stability_selection() has run

stability

mean edge stability along the penalty path, ⁠1 - mean(4 p (1 - p))⁠ over the edges; NA until stability_selection() has run

Methods

Public methods

Inherited methods

NormalBlockCollectionSparsity$new()

Create a collection over a path of sparsity penalties. By default, control$n_sparsity_penalties values on a log scale, from the largest absolute (weighted) entry of a covariance estimate, which removes every edge, down to control$min_ratio times it.

Usage
NormalBlockCollectionSparsity$new(
  mydata,
  blocks,
  zero_inflation = FALSE,
  control = NB_control()
)
Arguments
mydata

object of NormalBlockData class, with responses and design matrix

blocks

either a clustering matrix (known, fixed clustering) or a single integer (number of blocks to infer)

zero_inflation

whether the models of the path are zero-inflated

control

structured list of parameters to handle sparsity control

Returns

A new collection object


NormalBlockCollectionSparsity$optimize()

optimizes every model in the sparsity path, warm-starting each one (after the first) from the previous, adjacent penalty's converged parameters (see the family's base class's warm_start_from()) instead of re-deriving everything from the heuristic clustering, the way the generic NormalBlockCollection optimize() would. blocks (hence q) is fixed across the whole path, only the sparsity penalty changes, so the warm start is always between models of matching shape.

Usage
NormalBlockCollectionSparsity$optimize(
  control = list(niter = 500, threshold = 1e-04, verbose = TRUE)
)
Arguments
control

optimization parameters (niter and threshold)


NormalBlockCollectionSparsity$get_model()

returns the NormalBlockVarKnownClusters model corresponding to given penalty

Usage
NormalBlockCollectionSparsity$get_model(sparsity)
Arguments
sparsity

sparsity penalty asked by user

Returns

A NormalBlockVarKnownClusters (sparse) object with given value penalty


NormalBlockCollectionSparsity$get_best_model()

Extract best model in the collection

Usage
NormalBlockCollectionSparsity$get_best_model(
  crit = c("BIC", "EBIC", "ICL", "StARS"),
  stability = 0.9
)
Arguments
crit

a character for the criterion used to perform the selection: "BIC" (default), "EBIC", "ICL" or "StARS".

stability

if crit = "StARS", the level of stability required.

Returns

a model of the collection's family


NormalBlockCollectionSparsity$stability_selection()

Computes the stability path (StARS, Liu et al. 2010): the penalty path is refitted on subsamples of the observations, with the clustering held fixed, and the selection frequency of each edge is recorded at every penalty.

Usage
NormalBlockCollectionSparsity$stability_selection(
  subsamples = NULL,
  n_subsamples = 10
)
Arguments
subsamples

a list of vectors describing the subsamples. The number of vectors (or list length) determines the number of subsamples used in the stability selection. Automatically set to 10 subsamples with size 10*sqrt(n) if n >= 144 and 0.8*n otherwise following Liu et al. (2010) recommendations.

n_subsamples

number of subsamples to create if the subsamples are not given


NormalBlockCollectionSparsity$plot()

Plot the criteria of the models of the path against the penalty, with a dashed line at the penalty selected by each criterion (see also plot.NormalBlockCollection()).

Usage
NormalBlockCollectionSparsity$plot(
  criteria = c("deviance", "BIC", "EBIC", "ICL"),
  log.x = TRUE
)
Arguments
criteria

the criteria to plot, among "deviance", "BIC", "EBIC" and "ICL"; all of them by default.

log.x

logical: should the x-axis be represented in log-scale? Default is TRUE.

Returns

a ggplot2::ggplot graph


NormalBlockCollectionSparsity$clone()

The objects of this class are cloneable with this method.

Usage
NormalBlockCollectionSparsity$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples

# An internal abstract base class, never instantiated directly -- see
# normal_block() for how collections are created and fitted.

Data Container for Normal-Block Models

Description

R6 class holding the responses and design matrix used to fit a normal-block model.

Rescaling Y (scale)

Each column of Y can be divided by its own standard deviation before fitting. scale = NULL (the default) leaves the choice to the model family, resolved when a model is fitted: rescaled for variance-block models, raw for mean-block ones; TRUE or FALSE forces it for both. Columns are never centered: the model's own intercept already absorbs each variable's mean.

The two families need opposite defaults. A variance-block model loads every variable of a block on the same latent signal with the same weight, while on real data the variables of a block may carry that signal with different amplitudes; rescaling evens them out. A mean-block model shares a mean profile within a block, which a division by variable-specific standard deviations would break.

The resulting B, Omega and clustering are properties of the data the model was fitted on; with rescaled data, use ⁠$B_original⁠, ⁠$dm1_original⁠ and fitted() for quantities in Y's original units (a shared block covariance has no unique original-scale counterpart, since the scaling factors differ within a block).

Public fields

Y

the matrix of responses (rescaled column-wise if scale = TRUE)

Y_scale

the per-column standard deviation Y was divided by (all 1's if Y was not rescaled)

scale

the scale argument as given: TRUE, FALSE, or NULL for the family default (see for_family())

X

the matrix of covariates

X0

the matrix of zero-inflation covariates, if applicable

formula

describes the relationship between Y and X, and X0 if applicable, useful if not all of X's or X0's covariates should be used, should be formatted ~ X1 + X2... | Z1 + Z2... with the Normal formula before the | and the ZI formula after the |

n

sample size

d

number of covariates

d0

number of zero-inflation covariates, if applicable

p

number of variables

XtX

useful for inference in some cases

XtXm1

inverse of XtX, useful for inference

XtY

useful for inference

npY

total number of non zeros in Y

nY

total number of non zeros for each column/variable in Y

zeros

where are the zero in Y

zeros_bar

where are the non-zeros in Y

Active bindings

Y_original

the matrix of responses as given, before any rescaling

Methods

Public methods


NormalBlockData$new()

Create a new NormalBlockData object.

Usage
NormalBlockData$new(
  Y,
  X,
  X0 = NULL,
  formula = NULL,
  scale = NULL,
  zeros = NULL,
  check_constant = TRUE
)
Arguments
Y

the matrix of responses (called Y in the model).

X

design matrix (called X in the model).

X0

zero-inflation design matrix, if applicable.

formula

describes the relationship between Y and X, useful if not all of X's covariates should be used.

scale

whether to rescale each column of Y by its own standard deviation (no centering): NULL (default) for the model family's default, see the section "Rescaling Y" below and for_family().

zeros

an optional 0/1 matrix of structural zeros, overriding the default Y == 0.

check_constant

whether to refuse constant columns of Y, which carry no information to cluster on. FALSE for data only used to evaluate a fitted model (see heldout_loglik()).


NormalBlockData$for_family()

The data a model of the given family is fitted on. When scale was given explicitly, the object itself. Otherwise (scale = NULL) the family decides: the object itself, unscaled, for the mean-block family; a rescaled copy for the variance-block family, built once and shared by every model fitted on it.

Usage
NormalBlockData$for_family(model = c("var", "mean"))
Arguments
model

the model family, "var" or "mean"

Returns

a NormalBlockData object


NormalBlockData$subset()

The data restricted to some observations, with the same covariates, formula, zeros and scale request (a rescaled Y is rescaled again on these rows).

Usage
NormalBlockData$subset(rows, check_constant = TRUE)
Arguments
rows

the observations to keep (indices or a logical vector)

check_constant

as in new()

Returns

a NormalBlockData object


NormalBlockData$ols_fit()

Ordinary-least-squares fit of Y on X, with its residuals and their covariance. Computed once and memoized.

Usage
NormalBlockData$ols_fit()
Returns

a list with B (d x p), R (n x p residuals) and Sigma (p x p residual covariance)


NormalBlockData$zi_ols_fit()

Masked counterpart of ols_fit(): a per-variable weighted least-squares fit of B under the zero-inflation mask, with its inverse residual variances and residuals (see zi_weighted_fit()). Computed once and memoized.

Usage
NormalBlockData$zi_ols_fit()
Returns

a list with B (d x p), dm1 (p) and R (n x p masked residuals)


NormalBlockData$zi_fit()

Zero-inflation component: p independent logistic regressions of each variable's zero pattern on X0, and the fixed contribution they make to the log-likelihood. The (V)EM never revisits these, so they are a property of the data rather than of a model.

Usage
NormalBlockData$zi_fit()
Returns

a list with B0 (d0 x p), kappa (n x p zero-inflation probabilities) and ZI_cond_mean (a scalar)


NormalBlockData$clone()

The objects of this class are cloneable with this method.

Usage
NormalBlockData$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples

ex <- generate_normal_block_var_data(n = 50, p = 20, d = 1, q = 3)
data <- NormalBlockData$new(ex$Y, ex$X)
c(n = data$n, p = data$p, d = data$d)

Base Class for Normal-Block-Mean Models

Description

R6 abstract class for the Normal-Block models where the clustering structures the mean (mu_i = C B' X_i).

Super class

NormalBlockBase -> NormalBlockMeanBase

Active bindings

model_par

a list with the model parameters: B (d x q, one profile per cluster) and Omega (p x p precision matrix of the residuals), on the scale of the fit (see coef() and sigma()).

fitted

Y values predicted by the model, in Y's original units: ⁠X B C'⁠ (with the posterior cluster probabilities as C when the clustering is unknown), with the observed zeros of zero-inflated models set to 0

sparsity_weights

(weights associated to each pair of groups)

Methods

Public methods

Inherited methods

NormalBlockMeanBase$new()

Create a new NormalBlockMeanBase object.

Usage
NormalBlockMeanBase$new(
  data,
  q,
  sparsity = 0,
  control = NB_control(),
  zero_inflation = FALSE
)
Arguments
data

object of NormalBlockData class, with responses and design matrix

q

number of block/cluster

sparsity

sparsity penalty on the network density

control

structured list of more specific parameters, to generate with NB_control

zero_inflation

whether the concrete subclass models zero-inflation; set by the ZI subclasses themselves, not meant to be set by the end user.

Returns

A new NormalBlockMeanBase object


NormalBlockMeanBase$predict()

Predicts the mean of Y for new covariates X, in Y's original units: mu_i = C B' X_i, with the posterior cluster probabilities as C when the clustering is unknown (as in fitted()).

Usage
NormalBlockMeanBase$predict(new_X)
Arguments
new_X

new set of covariates.

Returns

A n*p prediction matrix for new observations


NormalBlockMeanBase$split()

Create a clone of the current NormalBlockMeanBase object after splitting cluster index. Unlike the variance-block family, Omega and the sparsity weights are p x p here and do not depend on q, so they carry over unchanged; only C (tau) and B (one column per cluster) are affected.

Usage
NormalBlockMeanBase$split(index, in_place = FALSE, rule = NULL)
Arguments
index

index (integer) of the cluster to split

in_place

should the split be applied to the object itself, or should a copy be sent? Default FALSE (send a copy)

rule

how the members of the cluster are divided: "kmeans" runs a 2-means on their fitted mean trajectories ⁠X B_ols⁠; "noise" cuts them at the median of their noise variance 1 / diag(Omega). Default NULL, i.e. "noise" for this family.

Returns

A new NormalBlockMeanBase object


NormalBlockMeanBase$merge()

Create a clone of the current NormalBlockMeanBase object after merging clusters indices

Usage
NormalBlockMeanBase$merge(indices, in_place = FALSE)
Arguments
indices

indices (couple of integer) of the clusters to merge

in_place

should the merge be applied to the object itself, or should a copy be sent? Default FALSE (send a copy)

Returns

A new NormalBlockMeanBase object


NormalBlockMeanBase$clone()

The objects of this class are cloneable with this method.

Usage
NormalBlockMeanBase$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples

# An internal abstract base class, never instantiated directly -- use
# NormalBlockMeanKnownClusters / NormalBlockMeanUnknownClusters.

Collection of Normal-Block-Mean Models over a Range of Cluster Counts

Description

R6 class for a collection of mean-block models (NormalBlockMeanBase) with different numbers of clusters (q). As for NormalBlockVarCollectionClusters, the q-independent part of the initial clustering heuristic is computed once for the whole collection.

Super classes

NormalBlockCollection -> NormalBlockCollectionClusters -> NormalBlockMeanCollectionClusters

Methods

Public methods

Inherited methods

NormalBlockMeanCollectionClusters$clone()

The objects of this class are cloneable with this method.

Usage
NormalBlockMeanCollectionClusters$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples

ex <- generate_normal_block_mean_data(n = 50, p = 20, d = 1, q = 3)
data <- NormalBlockData$new(ex$Y, ex$X)
models <- normal_block(data, blocks = 2:5, model = "mean")
plot(models, criteria = c("BIC", "ICL"))
models$get_best_model()

Collection of Normal-Block-Mean Models over Cluster Counts and Sparsity Levels

Description

R6 class for a collection of mean-block models (NormalBlockMeanBase) over both a range of cluster counts (q) and a sparsity path, i.e. one NormalBlockMeanCollectionSparsity per q. Mirrors NormalBlockVarCollectionClustersSparsity.

Super classes

NormalBlockCollection -> NormalBlockCollectionClustersSparsity -> NormalBlockMeanCollectionClustersSparsity

Methods

Public methods

Inherited methods

NormalBlockMeanCollectionClustersSparsity$clone()

The objects of this class are cloneable with this method.

Usage
NormalBlockMeanCollectionClustersSparsity$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples

ex <- generate_normal_block_mean_data(n = 60, p = 20, d = 1, q = 3)
data <- NormalBlockData$new(ex$Y, ex$X)
models <- normal_block(data, blocks = 2:4, sparsity = TRUE, model = "mean",
                       control = NB_control(n_sparsity_penalties = 4))
plot(models, criterion = "BIC")
models$get_best_model("BIC")

Collection of Normal-Block-Mean Models over a Sparsity Path

Description

R6 class for a collection of mean-block models (NormalBlockMeanBase) with a fixed clustering (or a fixed number of blocks) and different sparsity levels applied to the p x p precision matrix of the variables. Mirrors NormalBlockVarCollectionSparsity, StARS included; the default penalty grid is read off the covariance of the least-squares residuals.

Super classes

NormalBlockCollection -> NormalBlockCollectionSparsity -> NormalBlockMeanCollectionSparsity

Methods

Public methods

Inherited methods

NormalBlockMeanCollectionSparsity$new()

Create a new NormalBlockMeanCollectionSparsity object.

Usage
NormalBlockMeanCollectionSparsity$new(
  mydata,
  blocks,
  zero_inflation = FALSE,
  control = NB_control()
)
Arguments
mydata

object of NormalBlockData class, with responses and design matrix

blocks

either a clustering matrix (known, fixed clustering) or a single integer (number of blocks to infer)

zero_inflation

must be FALSE: the path penalizes a full Sigma, which zero-inflated mean-block models do not carry

control

structured list of parameters to handle sparsity control

Returns

A new NormalBlockMeanCollectionSparsity object


NormalBlockMeanCollectionSparsity$clone()

The objects of this class are cloneable with this method.

Usage
NormalBlockMeanCollectionSparsity$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples

ex <- generate_normal_block_mean_data(n = 60, p = 20, d = 1, q = 3)
data <- NormalBlockData$new(ex$Y, ex$X)
models <- normal_block(data, blocks = 3, sparsity = TRUE, model = "mean",
                       control = NB_control(n_sparsity_penalties = 5))
plot(models, criteria = c("BIC", "EBIC"))

Normal-Block-Mean Model with Known Clustering

Description

R6 class for a Normal-Block-Mean model with a known clustering.

Super classes

NormalBlockBase -> NormalBlockMeanBase -> NormalBlockMeanKnownClusters

Methods

Public methods

Inherited methods

NormalBlockMeanKnownClusters$new()

Create a new NormalBlockMeanKnownClusters object.

Usage
NormalBlockMeanKnownClusters$new(data, C, sparsity = 0, control = NB_control())
Arguments
data

object of NormalBlockData class, with responses and design matrix

C

p x q clustering matrix, C_jk = 1 if variable j belongs to cluster k

sparsity

to apply on variance matrix when calling GLASSO

control

structured list of more specific parameters, to generate with NB_control

Returns

A new NormalBlockMeanKnownClusters object


NormalBlockMeanKnownClusters$clone()

The objects of this class are cloneable with this method.

Usage
NormalBlockMeanKnownClusters$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples

ex <- generate_normal_block_mean_data(n = 50, p = 20, d = 1, q = 3)
data <- NormalBlockData$new(ex$Y, ex$X)
model <- normal_block(data, blocks = ex$parameters$C, model = "mean")
plot(model)

Normal-Block-Mean Model with Unknown Clustering

Description

R6 class for a Normal-Block-Mean model with a fixed number of clusters (but unknown clustering), inferred by variational EM.

Super classes

NormalBlockBase -> NormalBlockMeanBase -> NormalBlockMeanUnknownClusters

Active bindings

model_par

the parameters of NormalBlockMeanBase (B, Omega), plus alpha (cluster proportions)

var_par

a list with the variational parameter: tau (posterior group probabilities)

Methods

Public methods

Inherited methods

NormalBlockMeanUnknownClusters$new()

Create a new NormalBlockMeanUnknownClusters object.

Usage
NormalBlockMeanUnknownClusters$new(
  data,
  q,
  sparsity = 0,
  control = NB_control()
)
Arguments
data

object of NormalBlockData class, with responses and design matrix

q

number of clusters

sparsity

to apply on variance matrix when calling GLASSO

control

structured list of more specific parameters, to generate with NB_control

Returns

A new NormalBlockMeanUnknownClusters object


NormalBlockMeanUnknownClusters$clone()

The objects of this class are cloneable with this method.

Usage
NormalBlockMeanUnknownClusters$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples

ex <- generate_normal_block_mean_data(n = 50, p = 20, d = 1, q = 3)
data <- NormalBlockData$new(ex$Y, ex$X)
model <- normal_block(data, blocks = 3, model = "mean")
model$clustering

Base Class for Normal-Block-Var Models

Description

R6 abstract class for the sparse Normal-Block models, where the clustering structures the latent covariance.

Super class

NormalBlockBase -> NormalBlockVarBase

Active bindings

B_original

regression coefficients (d x p), converted back to Y's original units (undoing NormalBlockData(scale = TRUE)'s column-wise rescaling, if any). Use model_par$B instead for the coefficients on the internal fitting scale.

fitted

Y values predicted by the model, in Y's original units: ⁠X B⁠, plus the posterior mean of the latent block signals for (V)EM fits, with the observed zeros of zero-inflated models set to 0

model_par

a list with the model parameters: B (d x p regression coefficients), B0 (zero-inflation coefficients, if any), dm1 (inverse noise variances of the variables) and Omega (q x q precision matrix of the latent block signals), on the scale of the fit. Use ⁠$B_original⁠/⁠$dm1_original⁠ for B and dm1 on Y's original scale.

sparsity_weights

(weights associated to each pair of groups)

dm1_original

inverse residual variance per variable (1 / Var(Y_j)), converted back to Y's original units. Use model_par$dm1 instead for the internal fitting scale. With noise_covariance = "spherical", model_par$dm1 is a single value repeated p times; once converted back per-variable, the p values returned here generally differ from one another whenever Y's columns were rescaled by different factors.

Methods

Public methods

Inherited methods

NormalBlockVarBase$new()

Create a new NormalBlockVarBase object.

Usage
NormalBlockVarBase$new(
  data,
  q,
  sparsity = 0,
  control = NB_control(),
  zero_inflation = FALSE
)
Arguments
data

object of NormalBlockData class, with responses and design matrix

q

number of block/cluster

sparsity

sparsity penalty on the network density

control

structured list of more specific parameters, to generate with NB_control

zero_inflation

whether the concrete subclass models zero-inflation; set by the ZI subclasses themselves, not meant to be set by the end user. When FALSE, the (costly) zero-inflation probability fit (kappa/B0) is skipped entirely, since it would otherwise never be used downstream.

Returns

A new NormalBlockVarBase object


NormalBlockVarBase$within_block_correlations()

Checks that the blocks gather positively co-varying variables, as the model requires (two variables of a block have a positive correlation). Compares, for each block, the empirical correlations of the residuals Y - XB with those implied by the model.

Usage
NormalBlockVarBase$within_block_correlations()
Returns

a data frame with one row per block: block, size, the mean and minimum of the empirical within-block correlations (mean_cor, min_cor), the proportion of negative ones (prop_negative), and the mean correlation implied by the model (model_cor). NA for blocks with fewer than two variables.


NormalBlockVarBase$split()

Create a clone of the current NormalBlockVarBase object after splitting cluster index

Usage
NormalBlockVarBase$split(index, in_place = FALSE, rule = NULL)
Arguments
index

index (integer) of the cluster to split

in_place

should the split applied to the object itself, or should a copy be sent? default FALSE (send a copy)

rule

how the members of the cluster are divided: "kmeans" runs a 2-means on their columns of residuals Y - XB; "noise" cuts them at the median of their noise variance. Default NULL, i.e. "kmeans" for this family.

Returns

A new NormalBlockVarBase object


NormalBlockVarBase$merge()

Create a clone of the current NormalBlockVarBase object after merging clusters cl1 and cl2

Usage
NormalBlockVarBase$merge(indices, in_place = FALSE)
Arguments
indices

indices (couple of integer) of the clusters to merge

in_place

should the split applied to the object itself, or should a copy be sent? default FALSE (send a copy)

Returns

A new NormalBlockVarBase object


NormalBlockVarBase$clone()

The objects of this class are cloneable with this method.

Usage
NormalBlockVarBase$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples

# An internal abstract base class, never instantiated directly. See
# normal_block() for how concrete models (NormalBlockVarKnownClusters,
# NormalBlockVarUnknownClusters, and their zero-inflated variants) are
# actually created and fitted.

Collection of Normal-Block-Var Models over a Range of Cluster Counts

Description

R6 class for a collection of normal-block models with different number of clusters (q) and a fixed sparsity level. The q-independent part of the initial clustering heuristic is computed once for the whole collection.

Super classes

NormalBlockCollection -> NormalBlockCollectionClusters -> NormalBlockVarCollectionClusters

Methods

Public methods

Inherited methods

NormalBlockVarCollectionClusters$clone()

The objects of this class are cloneable with this method.

Usage
NormalBlockVarCollectionClusters$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples

ex <- generate_normal_block_var_data(n = 50, p = 20, d = 1, q = 3)
data <- NormalBlockData$new(ex$Y, ex$X)
models <- normal_block(data, blocks = 2:4, control = NB_control(verbose = FALSE))
models$get_best_model("ICL")$q

Collection of Normal-Block-Var Models over Cluster Counts and Sparsity Levels

Description

R6 class for a collection of normal-block models with different number of clusters (q) and different sparsity levels, i.e. one NormalBlockVarCollectionSparsity per q.

Super classes

NormalBlockCollection -> NormalBlockCollectionClustersSparsity -> NormalBlockVarCollectionClustersSparsity

Methods

Public methods

Inherited methods

NormalBlockVarCollectionClustersSparsity$clone()

The objects of this class are cloneable with this method.

Usage
NormalBlockVarCollectionClustersSparsity$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples

ex <- generate_normal_block_var_data(n = 50, p = 20, d = 1, q = 3)
data <- NormalBlockData$new(ex$Y, ex$X)
models <- normal_block(data, blocks = 2:3, sparsity = TRUE,
                       control = NB_control(verbose = FALSE, n_sparsity_penalties = 3))
models$get_best_model("BIC")$q

Collection of Normal-Block-Var Models over a Sparsity Path

Description

R6 class for a collection of normal-block models with a fixed clustering (blocks) and different sparsity levels. The default penalty grid is read off the latent block covariance of a short unpenalized fit.

Super classes

NormalBlockCollection -> NormalBlockCollectionSparsity -> NormalBlockVarCollectionSparsity

Methods

Public methods

Inherited methods

NormalBlockVarCollectionSparsity$clone()

The objects of this class are cloneable with this method.

Usage
NormalBlockVarCollectionSparsity$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples

ex <- generate_normal_block_var_data(n = 50, p = 20, d = 1, q = 3)
data <- NormalBlockData$new(ex$Y, ex$X)
models <- normal_block(data, blocks = ex$parameters$C, sparsity = TRUE,
                       control = NB_control(verbose = FALSE, n_sparsity_penalties = 5))
models$get_best_model("BIC")$sparsity

Normal-Block-Var Model with Known Clustering

Description

R6 class for a normal-block model with known clustering.

Super classes

NormalBlockBase -> NormalBlockVarBase -> NormalBlockVarKnownClusters

Active bindings

posterior_par

a list with the parameters of posterior distribution W | Y

Methods

Public methods

Inherited methods

NormalBlockVarKnownClusters$new()

Create a new NormalBlockVarKnownClusters object.

Usage
NormalBlockVarKnownClusters$new(data, C, sparsity = 0, control = NB_control())
Arguments
data

object of NormalBlockVarData class, with responses and design matrix

C

p x q clustering matrix, C_jk = 1 if variable j belongs to cluster k

sparsity

to apply on variance matrix when calling GLASSO

control

structured list of more specific parameters, to generate with NB_control

Returns

A new NormalBlockVarKnownClusters object


NormalBlockVarKnownClusters$clone()

The objects of this class are cloneable with this method.

Usage
NormalBlockVarKnownClusters$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples

ex <- generate_normal_block_var_data(n = 50, p = 20, d = 1, q = 3)
data <- NormalBlockData$new(ex$Y, ex$X)
model <- normal_block(data, blocks = ex$parameters$C, control = NB_control(verbose = FALSE))
model$clustering

Normal-Block-Var Model with Unknown Clustering

Description

R6 class for a normal-block model with a fixed number of clusters (but unknown clustering).

Super classes

NormalBlockBase -> NormalBlockVarBase -> NormalBlockVarUnknownClusters

Active bindings

model_par

the parameters of NormalBlockVarBase (B, B0, dm1, Omega), plus alpha (cluster proportions)

var_par

a list with the matrices of the variational parameters: M (means), S (variances), tau (posterior group probabilities)

Methods

Public methods

Inherited methods

NormalBlockVarUnknownClusters$new()

Create a new NormalBlockVarUnknownClusters object.

Usage
NormalBlockVarUnknownClusters$new(
  data,
  q,
  sparsity = 0,
  control = NB_control()
)
Arguments
data

contains the matrix of responses (Y) and the design matrix (X).

q

required number of groups

sparsity

sparsity penalty to add on blocks precision matrix for sparsity

control

structured list for specific parameters

Returns

A new NormalBlockVarUnknownClusters object


NormalBlockVarUnknownClusters$clone()

The objects of this class are cloneable with this method.

Usage
NormalBlockVarUnknownClusters$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples

ex <- generate_normal_block_var_data(n = 50, p = 20, d = 1, q = 3)
data <- NormalBlockData$new(ex$Y, ex$X)
model <- normal_block(data, blocks = 3, control = NB_control(verbose = FALSE))
model$clustering

Zero-Inflated Normal-Block-Mean Model with Known Clustering

Description

R6 class for a zero-inflated Normal-Block-Mean model with a known clustering. Sigma is diagonal or spherical here. See NormalBlockMeanBase for why a full one is out of reach under a mask.

Super classes

NormalBlockBase -> NormalBlockMeanBase -> ZINormalBlockMeanKnownClusters

Active bindings

model_par

the parameters of NormalBlockMeanBase (B, Omega), plus B0 (zero-inflation coefficients) and kappa (zero-inflation probabilities)

Methods

Public methods

Inherited methods

ZINormalBlockMeanKnownClusters$new()

Create a new ZINormalBlockMeanKnownClusters object.

Usage
ZINormalBlockMeanKnownClusters$new(
  data,
  C,
  sparsity = 0,
  control = NB_control()
)
Arguments
data

object of NormalBlockData class, with responses and design matrix

C

p x q clustering matrix, C_jk = 1 if variable j belongs to cluster k

sparsity

unused here, kept for signature symmetry (must be 0)

control

structured list of more specific parameters, to generate with NB_control

Returns

A new ZINormalBlockMeanKnownClusters object


ZINormalBlockMeanKnownClusters$clone()

The objects of this class are cloneable with this method.

Usage
ZINormalBlockMeanKnownClusters$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples

ex <- generate_normal_block_mean_data(n = 50, p = 20, d = 1, q = 3)
Y <- ex$Y; Y[runif(length(Y)) < 0.2] <- 0
data <- NormalBlockData$new(Y, ex$X)
model <- normal_block(data, blocks = ex$parameters$C, model = "mean",
                      zero_inflation = TRUE)
model$clustering

Zero-Inflated Normal-Block-Mean Model with Unknown Clustering

Description

R6 class for a zero-inflated Normal-Block-Mean model with a fixed number of clusters (but unknown clustering), inferred by variational EM. Sigma is diagonal or spherical here. See NormalBlockMeanBase for why a full one is out of reach under a mask.

Super classes

NormalBlockBase -> NormalBlockMeanBase -> ZINormalBlockMeanUnknownClusters

Active bindings

var_par

a list with the variational parameter: tau (posterior group probabilities)

model_par

the parameters of NormalBlockMeanBase (B, Omega), plus B0 (zero-inflation coefficients), kappa (zero-inflation probabilities) and alpha (cluster proportions)

Methods

Public methods

Inherited methods

ZINormalBlockMeanUnknownClusters$new()

Create a new ZINormalBlockMeanUnknownClusters object.

Usage
ZINormalBlockMeanUnknownClusters$new(
  data,
  q,
  sparsity = 0,
  control = NB_control()
)
Arguments
data

object of NormalBlockData class, with responses and design matrix

q

number of clusters

sparsity

unused here, kept for signature symmetry (must be 0)

control

structured list of more specific parameters, to generate with NB_control

Returns

A new ZINormalBlockMeanUnknownClusters object


ZINormalBlockMeanUnknownClusters$clone()

The objects of this class are cloneable with this method.

Usage
ZINormalBlockMeanUnknownClusters$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples

ex <- generate_normal_block_mean_data(n = 50, p = 20, d = 1, q = 3)
Y <- ex$Y; Y[runif(length(Y)) < 0.2] <- 0
data <- NormalBlockData$new(Y, ex$X)
model <- normal_block(data, blocks = 3, model = "mean", zero_inflation = TRUE)
model$clustering

Zero-Inflated Normal-Block-Var Model with Known Clustering

Description

R6 class for a zero-inflated normal-block model with a known clustering.

Super classes

NormalBlockBase -> NormalBlockVarBase -> ZINormalBlockVarKnownClusters

Active bindings

posterior_par

a list with the parameters of posterior distribution W | Y

model_par

the parameters of NormalBlockVarBase (B, B0, dm1, Omega), plus kappa (zero-inflation probabilities)

Methods

Public methods

Inherited methods

ZINormalBlockVarKnownClusters$new()

Create a new ZINormalBlockVarKnownClusters object.

Usage
ZINormalBlockVarKnownClusters$new(
  data,
  C,
  sparsity = 0,
  control = NB_control()
)
Arguments
data

object of NormalBlockData class, with responses and design matrix

C

p x q clustering matrix, C_jk = 1 if variable j belongs to cluster k

sparsity

to apply on variance matrix when calling GLASSO

control

structured list of more specific parameters, to generate with NB_control

Returns

A new ZINormalBlockVarKnownClusters object


ZINormalBlockVarKnownClusters$clone()

The objects of this class are cloneable with this method.

Usage
ZINormalBlockVarKnownClusters$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples

ex <- generate_normal_block_var_data(n = 50, p = 20, d = 1, q = 3, kappa = rep(0.3, 20))
data <- NormalBlockData$new(ex$Y, ex$X)
model <- normal_block(data, blocks = ex$parameters$C, zero_inflation = TRUE,
                      control = NB_control(verbose = FALSE))
model$clustering

Zero-Inflated Normal-Block-Var Model with Unknown Clustering

Description

R6 class for a zero-inflated normal-block model with a fixed number of clusters (but unknown clustering).

Super classes

NormalBlockBase -> NormalBlockVarBase -> ZINormalBlockVarUnknownClusters

Active bindings

var_par

a list with variational parameters

model_par

the parameters of NormalBlockVarBase (B, B0, dm1, Omega), plus kappa (zero-inflation probabilities) and alpha (cluster proportions)

Methods

Public methods

Inherited methods

ZINormalBlockVarUnknownClusters$new()

Create a new ZINormalBlockVarUnknownClusters object.

Usage
ZINormalBlockVarUnknownClusters$new(
  data,
  q,
  sparsity = 0,
  control = NB_control()
)
Arguments
data

object of NormalBlockVarData class, with responses and design matrix

q

required number of groups

sparsity

to apply on variance matrix when calling GLASSO

control

structured list of more specific parameters

Returns

A new ZINormalBlockVarUnknownClusters object


ZINormalBlockVarUnknownClusters$clone()

The objects of this class are cloneable with this method.

Usage
ZINormalBlockVarUnknownClusters$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.

Examples

ex <- generate_normal_block_var_data(n = 50, p = 20, d = 1, q = 3, kappa = rep(0.3, 20))
data <- NormalBlockData$new(ex$Y, ex$X)
model <- normal_block(data, blocks = 3, zero_inflation = TRUE,
                      control = NB_control(verbose = FALSE))
model$clustering

Breast Cancer Proteomics Data (TCGA, RPPA)

Description

Reverse-phase protein array (RPPA) measurements of 163 proteins across 346 breast cancer tumor samples from The Cancer Genome Atlas (TCGA), along with the PAM50 molecular subtype of each sample. Used as the running example in Tous & Chiquet (2026).

Usage

brca_rppa

Format

A list with 3 elements:

expr

a 346 x 163 numeric matrix of protein expression levels (normalized log-ratios), samples in rows (named by TCGA sample identifier), proteins in columns.

covariates

a data frame with one row per sample, in the same order as the rows of expr: sampleId (matches rownames(expr)) and 11 clinical variables, factors unless noted otherwise – CN_CLUSTER (copy-number cluster, 5 levels), CONVERTED_STAGE (tumor stage), ER_STATUS (estrogen receptor status), FRACTION_GENOME_ALTERED (numeric, in [0, 1]), HER2_STATUS, METASTASIS_CODED, METHYLATION_CLUSTER (5 levels), MUTATION_COUNT (numeric), PAM50_SUBTYPE (5 levels: Basal-like, HER2-enriched, Luminal A, Luminal B, Normal-like), RPPA_CLUSTER (7 levels) and AGE (numeric, in years). A few of these have missing values for a handful of samples (FRACTION_GENOME_ALTERED, HER2_STATUS, METASTASIS_CODED).

gene_annotation

a data frame with one row per protein, in the same order as the columns of expr: protein (matches colnames(expr)), entrezGeneId, hugoGeneSymbol, type ("protein-coding" or "phosphoprotein") and go_bp_term (a Gene Ontology Biological Process classification, one term per protein, or "unknown" if none could be found – see Details).

Details

go_bp_term is derived from org.Hs.eg.db, queried by entrezGeneId for "protein-coding" rows. Phospho-site antibodies (type == "phosphoprotein", e.g. "EGFR_PY1068") carry a placeholder, negative entrezGeneId (there is no separate gene for a specific phosphorylation site, only the underlying gene) and are instead queried by gene symbol (the part of protein before the first "_"). Each protein typically has dozens of GO Biological Process terms; go_bp_term keeps, for each protein, the one term shared by the most other proteins in this dataset – giving a handful of non-trivial groups rather than one near-singleton group per protein, more useful for comparing against an inferred clustering. See data-raw/brca_rppa_go_annotation.R for the full extraction code.

Source

TCGA breast cancer cohort (Cancer Genome Atlas Network, 2012, doi:10.1038/nature11412), downloaded via cBioPortal (brca_tcga_pub study, https://www.cbioportal.org). go_bp_term (see Details) was added afterwards from org.Hs.eg.db.

Examples

expr <- brca_rppa$expr
X <- model.matrix(~ 0 + PAM50_SUBTYPE, data = brca_rppa$covariates)
nb_data <- NormalBlockData$new(expr, X)
table(brca_rppa$gene_annotation$go_bp_term)

Extract Model Coefficients

Description

Extract the regression coefficients B of a normal-block model. For the variance-block models, one column per variable, on the original scale of Y even when the variables were rescaled for the fit. For the mean-block models, one column per cluster, on the scale of the fit (the original one by default), since a profile is shared by variables of different scales.

Usage

## S3 method for class 'NormalBlockBase'
coef(object, ...)

Arguments

object

An object of class NormalBlockBase.

...

not used, only here for S3 compatibility

Value

A d x p (variance-block) or d x q (mean-block) matrix.

Examples

ex_data <- generate_normal_block_var_data(n = 50, p = 20, d = 1, q = 3)
data <- NormalBlockData$new(ex_data$Y, ex_data$X)
model <- normal_block(data, blocks = 3, control = NB_control(verbose = FALSE))
coef(model)[, 1:5]

Extract Fitted Values

Description

Extract the fitted values of a normal-block model, on the original scale of Y. For the variance-block models, they include the posterior mean of the latent block signals, ⁠X B + E[W] C'⁠; for the mean-block models, they are ⁠X B C'⁠ (with the posterior cluster probabilities when the clustering is unknown). Zero-inflated models set the observed zeros to 0.

Usage

## S3 method for class 'NormalBlockBase'
fitted(object, ...)

Arguments

object

An object of class NormalBlockBase.

...

not used, only here for S3 compatibility

Value

A matrix of fitted values extracted from the object.

Examples

ex_data <- generate_normal_block_var_data(n = 50, p = 20, d = 1, q = 3)
data <- NormalBlockData$new(ex_data$Y, ex_data$X)
model <- normal_block(data, blocks = 3, control = NB_control(verbose = FALSE))
head(fitted(model)[, 1:5])

Simulate Data from a Normal-Block-Mean Model

Description

A function to draw data from the normal block model (see details). The function returns both the generated data and the corresponding model parameters, in a list.

Usage

generate_normal_block_mean_data(
  n = 100,
  p = 40,
  d = 1,
  q = 3,
  kappa = 0,
  omega_structure = "erdos-renyi",
  u_v = c(0.3, 0.1),
  SNR = 5,
  alpha = rep(1/q, q),
  range_X = c(0, 10)
)

Arguments

n

number of individuals. Default to 100.

p

number of variables. Default to 40.

d

number of covariates. Default to 1.

q

number of groups. Default to 3.

kappa

vector (or scalar) of variable-wise probability of zero inflation. Default to 0.

omega_structure

the structure of the graph on which the precision matrix between variables is built. Can be a symmetric matrix with p rows/columns or a character picked in "erdos-renyi", "preferential_attachment", "community" in which case a graph is drawn with sensible generation parameters. See generate_precision_matrix for details.

u_v

two-size vector of positive numbers v and u controlling the generation of the precision matrix Omega: v scales the off-diagonal elements of the precision matrix (magnitude of partial correlations), and u is a positive number added to the diagonal elements to ensure positive-definiteness. The default value is c(0.3, 0.1).

SNR

signal-to-noise ratio: the residual covariance Sigma is rescaled so that the squared norm of the signal X B C' is SNR times the expected squared norm of the noise, n tr(Sigma).

alpha

the q-size vector of group proportion. Default to rep(1/q, q)

range_X

A 2-size vector defining the range of the uniform distribution used to draw values in X, the regressor matrix. Default is c(0, 10)

Value

A named list with the following element

Examples

ex <- generate_normal_block_mean_data(n = 50, p = 20, d = 2, q = 3)
dim(ex$Y)
ex$parameters$B # one regression profile per cluster

Simulate Data from a Normal-Block-Var Model

Description

A function to draw data from the normal block model (see details). The function returns both the generated data and the corresponding model parameters, in a list.

Usage

generate_normal_block_var_data(
  n = 100,
  p = 40,
  d = 1,
  q = 3,
  kappa = 0,
  omega_structure = "erdos-renyi",
  u_v = c(0.3, 0.1),
  SNR = 0.75,
  alpha = rep(1/q, q),
  range_X = c(0, 10),
  range_D = c(0.5, 1.5)
)

Arguments

n

number of individuals. Default to 100.

p

number of variables. Default to 40.

d

number of covariates. Default to 1.

q

number of groups. Default to 3.

kappa

vector (or scalar) of variable-wise probability of zero inflation. Default to 0.

omega_structure

the structure of the graph on which the precision matrix between groups is built. Can be a symmetric matrix with q rows/columns or a character picked in "erdos-renyi", "preferential_attachment", "community" in which case a graph is drawn with sensible generation parameters. See generate_precision_matrix for details.

u_v

two-size vector of positive numbers v and u controlling the generation of the precision matrix Omega: v scales the off-diagonal elements of the precision matrix (magnitude of partial correlations), and u is a positive number added to the diagonal elements to ensure positive-definiteness. The default value is c(0.3, 0.1).

SNR

signal-to-noise ratio: the regression coefficients B are rescaled so that the variance of the entries of X B is SNR times the variance of the entries of the latent block covariance Sigma.

alpha

the q-size vector of group proportion. Default to rep(1/q, q)

range_X

A 2-size vector defining the range of the uniform distribution used to draw values in X, the regressor matrix. Default is c(0, 10)

range_D

A 2-size vector defining the range of the uniform distribution used to draw values in D, the diagonal matrix of variances of variables. Default is c(0.5, 1.5)

Value

A named list with the following element

Examples

ex <- generate_normal_block_var_data(n = 50, p = 20, d = 1, q = 3)
dim(ex$Y)
colSums(ex$parameters$C) # sizes of the clusters

Create a Normal-Block Model Object

Description

Creates, without fitting it, the model (or collection of models) that normal_block() would fit for the same arguments.

Usage

get_model(
  data,
  blocks,
  sparsity = 0,
  zero_inflation = FALSE,
  control = NB_control(),
  model = c("var", "mean")
)

Arguments

data

a NormalBlockData object, holding the responses (Y, n x p) and the covariates (X, n x d).

blocks

the clustering of the variables: a p x q indicator matrix for a known clustering (e.g. model.matrix(~ 0 + factor(labels))), a single integer q for an unknown clustering into q clusters, or a vector of distinct integers for a collection over these values of q.

sparsity

the graphical-lasso penalty on Omega: 0 (the default) for none, a positive number for a single penalty, or TRUE for a collection along a path of penalties (see NB_control()).

zero_inflation

whether to model an excess of exact zeros in Y.

control

a list of settings, built with NB_control().

model

the model family: "var" (the default) clusters the variables by how they covary, and infers a network between clusters (see NormalBlockVarBase); "mean" clusters them by how they respond to the covariates, ⁠mu_i = C B' X_i⁠ (see NormalBlockMeanBase). Every combination of the other arguments is available for both families, except a penalty together with zero-inflation for the mean-block family, whose zero-inflated models have a diagonal or spherical Sigma.

Value

an R6 object: a model or a collection of models, not optimized yet.

Examples

ex_data <- generate_normal_block_var_data(n = 50, p = 20, d = 1, q = 3)
data <- NormalBlockData$new(ex_data$Y, ex_data$X)
## the model is created but not fitted, unlike with normal_block()
model <- get_model(data, blocks = 3, control = NB_control(verbose = FALSE))
class(model)

Check if an Object is a Normal-Block Model

Description

Checks if a model is of class NormalBlockBase(), i.e. any normal-block model (variance-block or mean-block family).

Usage

isNB(object)

Arguments

object

An R object.

Value

A boolean telling whether object inherits from the NormalBlockBase class.

Examples

ex_data <- generate_normal_block_var_data(n = 50, p = 20, d = 1, q = 3)
data <- NormalBlockData$new(ex_data$Y, ex_data$X)
model <- normal_block(data, blocks = 3, control = NB_control(verbose = FALSE))
isNB(model)

Extract Log-Likelihood of a Normal-Block Model

Description

Returns the (variational) log-likelihood of a fitted normal-block model as a "logLik" object, compatible with stats::AIC() and stats::BIC().

Usage

## S3 method for class 'NormalBlockBase'
logLik(object, ...)

Arguments

object

An object of class NormalBlockBase.

...

not used, only here for S3 compatibility

Value

An object of class "logLik". The numeric value is the log-likelihood or its variational lower bound (ELBO), on the scale of the data the model was fitted on (rescaled or not, see NormalBlockData); use the heldout_loglik() method for a log-likelihood on Y's original scale. Attributes df and nobs hold the number of parameters and observations.

Examples

ex_data <- generate_normal_block_var_data(n = 50, p = 20, d = 1, q = 3)
data <- NormalBlockData$new(ex_data$Y, ex_data$X)
model <- normal_block(data, blocks = 3, control = NB_control(verbose = FALSE))
logLik(model)

Extract Log-Likelihood of a Collection of Normal-Block Models

Description

Returns the log-likelihood of every model in a collection of normal-block models (see NormalBlockVarCollectionClusters, NormalBlockVarCollectionSparsity, NormalBlockVarCollectionClustersSparsity).

Usage

## S3 method for class 'NormalBlockCollection'
logLik(object, ...)

Arguments

object

An object inheriting from NormalBlockCollection.

...

not used, only here for S3 compatibility

Value

A numeric vector of log-likelihood values, one per model in the collection.

Examples

ex_data <- generate_normal_block_var_data(n = 50, p = 20, d = 1, q = 3)
data <- NormalBlockData$new(ex_data$Y, ex_data$X)
models <- normal_block(data, blocks = 2:5, control = NB_control(verbose = FALSE))
logLik(models)

Fit Normal-Block Models

Description

Fits a Normal-Block model, or a collection of them, by (variational) EM. The arguments select the model: the family (model), whether the clustering is known (blocks), whether the network is penalized (sparsity) and whether Y is zero-inflated (zero_inflation).

Usage

normal_block(
  data,
  blocks,
  sparsity = 0,
  zero_inflation = FALSE,
  control = NB_control(),
  model = c("var", "mean")
)

Arguments

data

a NormalBlockData object, holding the responses (Y, n x p) and the covariates (X, n x d).

blocks

the clustering of the variables: a p x q indicator matrix for a known clustering (e.g. model.matrix(~ 0 + factor(labels))), a single integer q for an unknown clustering into q clusters, or a vector of distinct integers for a collection over these values of q.

sparsity

the graphical-lasso penalty on Omega: 0 (the default) for none, a positive number for a single penalty, or TRUE for a collection along a path of penalties (see NB_control()).

zero_inflation

whether to model an excess of exact zeros in Y.

control

a list of settings, built with NB_control().

model

the model family: "var" (the default) clusters the variables by how they covary, and infers a network between clusters (see NormalBlockVarBase); "mean" clusters them by how they respond to the covariates, ⁠mu_i = C B' X_i⁠ (see NormalBlockMeanBase). Every combination of the other arguments is available for both families, except a penalty together with zero-inflation for the mean-block family, whose zero-inflated models have a diagonal or spherical Sigma.

Value

a fitted model (an R6 object, see the classes listed in the reference index), or a collection of fitted models.

Examples

## Variance-block models over a range of q
ex_data <- generate_normal_block_var_data(n = 100, p = 30, d = 1, q = 3)
data <- NormalBlockData$new(ex_data$Y, ex_data$X)
my_normal_block <- normal_block(data, blocks = 1:5)
plot(my_normal_block)
best <- my_normal_block$get_best_model("ICL")
plot(ex_data$Y, fitted(best)); abline(0, 1)
## the same with zero-inflation
ex_data_zi <- generate_normal_block_var_data(n = 50, p = 30, d = 1, q = 3,
                                             kappa = rep(0.5, 30))
zidata <- NormalBlockData$new(ex_data_zi$Y, ex_data_zi$X)
my_zi_block <- normal_block(zidata, blocks = 3, zero_inflation = TRUE)
## a mean-block model (clustering in the mean rather than the covariance)
ex_mean <- generate_normal_block_mean_data(n = 50, p = 20, d = 1, q = 3)
mean_data <- NormalBlockData$new(ex_mean$Y, ex_mean$X)
my_mean_block <- normal_block(mean_data, blocks = 3, model = "mean")
coef(my_mean_block)

Cross-Validated Log-Likelihood of Normal-Block Models

Description

Splits the observations into folds, fits normal_block() on all but one fold and evaluates the held-out log-likelihood of the left-out fold (see heldout_loglik() in NormalBlockBase), for every model of the collection. It selects the number of clusters without a penalty, and compares models of different families, shapes of Sigma or scalings.

Usage

normal_block_cv(
  data,
  blocks,
  model = c("var", "mean"),
  zero_inflation = FALSE,
  sparsity = 0,
  folds = 5,
  control = NB_control(verbose = FALSE)
)

Arguments

data

a NormalBlockData object

blocks

as in normal_block(): a range of numbers of clusters, a single one, or a known clustering (p x q indicator matrix)

model, zero_inflation, sparsity

as in normal_block(). A sparsity path (sparsity = TRUE) is not supported: its penalty grid depends on the data, hence on the fold; pick the penalty with StARS instead (see NormalBlockVarCollectionSparsity).

folds

the number of folds, or a vector of data$n fold labels. With a number, the folds are drawn at random, stratified on the distinct rows of the design X when it is categorical (e.g. a factor coded by model.matrix()), so that every training set sees every category.

control

a list of controls, see NB_control()

Value

an object of class normal_block_cv: a data frame with one row per model (q), the total held-out log-likelihood over the n observations (loglik, larger is better) and its standard error (se, from the spread of the per-observation values); the per-observation values are kept in the per_observation attribute (n x number of models) and the folds in folds. Its best attribute is the q chosen by the one-standard-error rule, the smallest q within one standard error of the maximum; best_max is the maximum itself, which tends to over-select.

Examples

ex   <- generate_normal_block_var_data(n = 60, p = 15, d = 1, q = 3)
data <- NormalBlockData$new(ex$Y, ex$X)
set.seed(1)
cv <- normal_block_cv(data, blocks = 2:4, folds = 3)
cv

Cluster Variables in the Mean, then in the Residual Covariance

Description

Fits the two model families one after the other: a mean-block model (NormalBlockMeanBase) groups the variables by how they respond to the covariates, then a variance-block model (NormalBlockVarBase) groups the residuals of that fit by how they co-vary. The two answer different questions and generally return unrelated partitions, so running both is often more informative than choosing one.

Usage

normal_block_sequential(
  data,
  blocks_mean,
  blocks_var,
  crit = c("ICL", "BIC"),
  zero_inflation = FALSE,
  control_mean = NB_control(verbose = FALSE),
  control_var = NB_control(verbose = FALSE)
)

Arguments

data

a NormalBlockData object

blocks_mean

number of clusters for the mean-block stage: an integer, a vector of integers to explore, or a p x q indicator matrix. It can also be a mean-block model or collection already fitted on data (by normal_block(data, ..., model = "mean")), in which case the first stage is not refitted: a collection is reduced to its best model by crit.

blocks_var

idem for the variance-block stage, run on the residuals

crit

criterion used to pick a model when a range is explored, "ICL" (the default) or "BIC"

zero_inflation

whether Y carries structural zeros. Both stages are then zero-inflated, sharing the same mask: the second one would otherwise re-derive it from residuals, which are never exactly zero.

control_mean

control list for the mean-block stage, see NB_control()

control_var

control list for the variance-block stage

Details

The second stage uses an intercept-only design on purpose: the covariate effects have already been removed by the first stage.

This is a heuristic two-stage estimator, not a joint model.

Value

an object of class normal_block_sequential, a list with the fitted mean and var models and the residual matrix residuals handed from one stage to the other.

Examples

ex   <- generate_normal_block_mean_data(n = 80, p = 20, d = 1, q = 3)
data <- NormalBlockData$new(ex$Y, ex$X)
fit  <- normal_block_sequential(data, blocks_mean = 3, blocks_var = 2)
fit

French Stream Fish Community Data (ONEMA / OFB Electrofishing Surveys)

Description

Fish biomass per species, aggregated by sampling station, together with environmental covariates for each station. Derived from the fish community monitoring of stream sections across metropolitan France (1995-2018) by the French Office for Biodiversity (formerly ONEMA, "Office National de l'Eau et des Milieux Aquatiques"), using electrofishing.

Usage

onema

Format

A list with 2 elements:

biomass

a 399 x 46 numeric matrix of total biomass (grams) per species (3-letter species code, columns) and station (row names).

covariates

a data frame with one row per station, in the same order as the rows of biomass: station (matches rownames(biomass)) and 14 environmental variables – slope, alt (altitude), d_source (distance to source), strahler (Strahler stream order), width_river_mean/width_river_cv, avg_depth_station_mean/ avg_depth_station_cv, DBO_med/DBO_cv (biological oxygen demand), flow_med/flow_cv and temperature_med/temperature_cv (⁠_med⁠ = median, ⁠_cv⁠ = coefficient of variation, over the monitoring period).

Details

The source data is organized around fishing operations (opcod): several electrofishing operations can be carried out at the same station over time. onema aggregates this to one row per station: every operation is first mapped to its station (fishing_protocol.csv), then biomass (in grams) is summed over every operation recorded at a given station, separately for each species (i.e. biomass[s, ] is the total biomass of each species ever caught at station s, not a single operation's catch). Stations without environmental data are dropped. Species observed at fewer than 10 stations are also dropped: at that level of rarity, a zero-inflated fit's iterative initialization can fit a species' handful of non-zero observations exactly, driving its estimated noise precision to infinity (these species also carry essentially no information for clustering anyway).

Source

Danet, A., Mouchet, M., Bonnaffe, W., Thebault, E., Fontaine, C. (2021) "Species richness and food-web structure jointly drive community biomass and its temporal stability in fish communities", data set, Zenodo, doi:10.5281/zenodo.5095656.

Examples

Y <- log(1 + onema$biomass)
X <- model.matrix(~ 1, data = onema$covariates)
nb_data <- NormalBlockData$new(Y, X)

## zero-inflated fits; ward2 initializations suit abundance data
out <- normal_block(nb_data, 2:6, zero_inflation = TRUE,
                    control = NB_control(clustering_init = "ward2", verbose = FALSE))
out$get_best_model("ICL")


Plot a Normal-Block Model

Description

Plots the evolution of the objective (log-likelihood or ELBO) across the (V)EM iterations of the last call to optimize(), see ⁠$plot_loglik()⁠.

Usage

## S3 method for class 'NormalBlockBase'
plot(x, ...)

Arguments

x

An object of class NormalBlockBase.

...

not used, only here for S3 compatibility

Value

Invisibly returns the ggplot2::ggplot object; called for its side effect of plotting.

Examples

ex_data <- generate_normal_block_var_data(n = 50, p = 20, d = 1, q = 3)
data <- NormalBlockData$new(ex_data$Y, ex_data$X)
model <- normal_block(data, blocks = 3, control = NB_control(verbose = FALSE))
plot(model)

Plot a Collection of Normal-Block Models

Description

Plots the model-selection criteria of a collection of normal-block models: against the number of clusters q for a collection over q (NormalBlockVarCollectionClusters, NormalBlockMeanCollectionClusters), against the penalty for a sparsity path (NormalBlockVarCollectionSparsity, NormalBlockMeanCollectionSparsity), with a dashed line at the model selected by each criterion; as a heatmap over q and the penalty for a collection over both (NormalBlockVarCollectionClustersSparsity, NormalBlockMeanCollectionClustersSparsity).

Usage

## S3 method for class 'NormalBlockCollection'
plot(x, ...)

Arguments

x

An object inheriting from NormalBlockCollection.

...

passed to the collection's ⁠$plot()⁠ method: criteria (the criteria to plot, among "deviance", "ICL", "BIC" and "EBIC") for a collection over q or a sparsity path, plus log.x for the latter; criterion (a single one) and n_intervals for a collection over both.

Value

Invisibly returns the ggplot2::ggplot object; called for its side effect of plotting.

Examples

ex_data <- generate_normal_block_var_data(n = 50, p = 20, d = 1, q = 3)
data <- NormalBlockData$new(ex_data$Y, ex_data$X)
models <- normal_block(data, blocks = 2:5, control = NB_control(verbose = FALSE))
plot(models)
plot(models, criteria = c("BIC", "ICL"))

Plot a Cross-Validated Log-Likelihood

Description

The held-out log-likelihood against the number of clusters, with one standard error on either side.

Usage

## S3 method for class 'normal_block_cv'
plot(x, ...)

Arguments

x

an object of class normal_block_cv, from normal_block_cv()

...

not used, only here for S3 compatibility

Value

a ggplot2::ggplot graph

Examples

ex   <- generate_normal_block_var_data(n = 60, p = 15, d = 1, q = 3)
data <- NormalBlockData$new(ex$Y, ex$X)
set.seed(1)
cv <- normal_block_cv(data, blocks = 2:4, folds = 3)
plot(cv)

Predict Method for Normal-Block Models

Description

Predicts the mean of the observations Y for new covariates X, on the original scale of Y: ⁠B' X⁠ for the variance-block models (the latent block signals, centered, average out; unlike fitted(), which adds their posterior mean for the training observations), ⁠C B' X⁠ for the mean-block models. For zero-inflated models, the mean of the Gaussian component.

Usage

## S3 method for class 'NormalBlockBase'
predict(object, new_X, ...)

Arguments

object

An object of class NormalBlockBase.

new_X

New set of covariates.

...

not used, only here for S3 compatibility

Value

A n*p prediction matrix for new observations

Examples

ex_data <- generate_normal_block_var_data(n = 50, p = 20, d = 1, q = 3)
data <- NormalBlockData$new(ex_data$Y, ex_data$X)
model <- normal_block(data, blocks = 3, control = NB_control(verbose = FALSE))
predict(model, ex_data$X[1:3, , drop = FALSE])[, 1:5]

Print a Normal-Block Model

Description

Print a short summary of a fitted normal-block model: model type, goodness-of-fit criteria, and the useful fields/methods to explore it further.

Usage

## S3 method for class 'NormalBlockBase'
print(x, ...)

Arguments

x

An object of class NormalBlockBase.

...

not used, only here for S3 compatibility

Value

Invisibly returns x.

Examples

ex_data <- generate_normal_block_var_data(n = 50, p = 20, d = 1, q = 3)
data <- NormalBlockData$new(ex_data$Y, ex_data$X)
model <- normal_block(data, blocks = 3, control = NB_control(verbose = FALSE))
print(model)

Print a Collection of Normal-Block Models

Description

Print a short summary of a collection of normal-block models: model type and the range of q/sparsity explored. See summary.NormalBlockCollection() for the full criteria table.

Usage

## S3 method for class 'NormalBlockCollection'
print(x, ...)

Arguments

x

An object inheriting from NormalBlockCollection.

...

not used, only here for S3 compatibility

Value

Invisibly returns x.

Examples

ex_data <- generate_normal_block_var_data(n = 50, p = 20, d = 1, q = 3)
data <- NormalBlockData$new(ex_data$Y, ex_data$X)
models <- normal_block(data, blocks = 2:5, control = NB_control(verbose = FALSE))
print(models)

Print a Cross-Validated Log-Likelihood

Description

Print a Cross-Validated Log-Likelihood

Usage

## S3 method for class 'normal_block_cv'
print(x, ...)

Arguments

x

an object of class normal_block_cv, from normal_block_cv()

...

not used, only here for S3 compatibility

Value

Invisibly returns x.

Examples

ex   <- generate_normal_block_var_data(n = 60, p = 15, d = 1, q = 3)
data <- NormalBlockData$new(ex$Y, ex$X)
set.seed(1)
cv <- normal_block_cv(data, blocks = 2:4, folds = 3)
print(cv)

Print a Sequential Mean-then-Variance Fit

Description

Reports both stages and, when aricode is available, how related the two partitions are.

Usage

## S3 method for class 'normal_block_sequential'
print(x, ...)

Arguments

x

an object of class normal_block_sequential

...

not used, only here for S3 compatibility

Value

Invisibly returns x.

Examples

ex   <- generate_normal_block_mean_data(n = 80, p = 20, d = 1, q = 3)
data <- NormalBlockData$new(ex$Y, ex$X)
fit  <- normal_block_sequential(data, blocks_mean = 3, blocks_var = 2)
print(fit)

Print a Normal-Block Model Summary

Description

Print method for objects returned by summary.NormalBlockBase().

Usage

## S3 method for class 'summary.NormalBlockBase'
print(x, ...)

Arguments

x

An object of class summary.NormalBlockBase.

...

not used, only here for S3 compatibility

Value

Invisibly returns x.

Examples

ex_data <- generate_normal_block_var_data(n = 50, p = 20, d = 1, q = 3)
data <- NormalBlockData$new(ex_data$Y, ex_data$X)
model <- normal_block(data, blocks = 3, control = NB_control(verbose = FALSE))
print(summary(model))

Print a Collection Summary

Description

Print method for objects returned by summary.NormalBlockCollection().

Usage

## S3 method for class 'summary.NormalBlockCollection'
print(x, ...)

Arguments

x

An object of class summary.NormalBlockCollection.

...

not used, only here for S3 compatibility

Value

Invisibly returns x.

Examples

ex_data <- generate_normal_block_var_data(n = 50, p = 20, d = 1, q = 3)
data <- NormalBlockData$new(ex_data$Y, ex_data$X)
collection <- normal_block(data, blocks = 2:4, control = NB_control(verbose = FALSE))
print(summary(collection))

Extract the Covariance Matrix

Description

Extract the covariance matrix Omega^-1. For the variance-block models, the q x q covariance of the latent block signals, on the scale of the fit (it has no original-scale counterpart when the variables of a block were rescaled by different factors). For the mean-block models, the p x p residual covariance between variables, on the original scale of Y.

Usage

## S3 method for class 'NormalBlockBase'
sigma(object, ...)

Arguments

object

An object of class NormalBlockBase.

...

not used, only here for S3 compatibility

Value

The covariance matrix, of size q x q or p x p depending on the model.

Examples

ex_data <- generate_normal_block_var_data(n = 50, p = 20, d = 1, q = 3)
data <- NormalBlockData$new(ex_data$Y, ex_data$X)
model <- normal_block(data, blocks = 3, control = NB_control(verbose = FALSE))
sigma(model)

Summarize a Normal-Block Model

Description

Summarizes a fitted normal-block model: model type, goodness-of-fit criteria, cluster sizes, and the density of the inferred network between blocks.

Usage

## S3 method for class 'NormalBlockBase'
summary(object, ...)

Arguments

object

An object of class NormalBlockBase.

...

not used, only here for S3 compatibility

Value

An object of class summary.NormalBlockBase (a list with the model's who_am_I, criteria, cluster_sizes and network density), printed with a dedicated print.summary.NormalBlockBase() method.

Examples

ex_data <- generate_normal_block_var_data(n = 50, p = 20, d = 1, q = 3)
data <- NormalBlockData$new(ex_data$Y, ex_data$X)
model <- normal_block(data, blocks = 3, control = NB_control(verbose = FALSE))
summary(model)

Summarize a Collection of Normal-Block Models

Description

Summarizes a collection of normal-block models: model type, the full criteria table, and the range of q/sparsity explored.

Usage

## S3 method for class 'NormalBlockCollection'
summary(object, ...)

Arguments

object

An object inheriting from NormalBlockCollection.

...

not used, only here for S3 compatibility

Value

An object of class summary.NormalBlockCollection (a list with the collection's who_am_I, criteria, q_range and sparsity_range), printed with a dedicated print.summary.NormalBlockCollection() method.

Examples

ex_data <- generate_normal_block_var_data(n = 50, p = 20, d = 1, q = 3)
data <- NormalBlockData$new(ex_data$Y, ex_data$X)
models <- normal_block(data, blocks = 2:5, control = NB_control(verbose = FALSE))
summary(models)

University Webpages Text Data (CMU "4 Universities" / WebKB)

Description

Term-frequency data derived from the student personal webpages of the CMU "World Wide Knowledge Base" (WebKB) project's "4 Universities" dataset (Cornell, Texas, Washington, Wisconsin computer science departments, collected January 1997). Used as one of the running examples in Tous & Chiquet (2026).

Usage

university

Format

A list with 3 elements:

frequencies

a 504 x 1867 numeric matrix of term frequencies (row sums to 1): for each document (row, named by its original file path) and term (column), the fraction of that document's (post-preprocessing) word count made up of that term.

entropies

a named numeric vector of length 1867 (one value per column of frequencies, same names/order), the normalized Shannon entropy of each term's distribution across documents.

terms

a character vector of the 100 column names of frequencies with the highest entropies, ordered by decreasing entropy.

Details

Each of the 504 pages (rows) is a document; each of the 1867 columns is a term retained after lower-casing, stripping URLs/HTML tags/control characters/punctuation/numbers, removing English stopwords and dropping terms occurring in fewer than 2 documents. entropies ranks every term by how evenly it is spread across documents (Shannon entropy of each term's normalized document distribution, in [0, 1], 1 = perfectly uniform); terms is the 100 highest-entropy terms, i.e. the terms that are the most informative for distinguishing documents from one another rather than just reflecting a few documents' idiosyncratic vocabulary – the transformation used by Tan et al. (2015).

Source

CMU Text Learning Group, "World Wide Knowledge Base (Web->KB) project", http://www.cs.cmu.edu/~webkb/; "4 Universities" subset, https://www.cs.cmu.edu/afs/cs/project/theo-20/www/data/. Tan, P.-N., Steinbach, M., Kumar, V. (2015) "Introduction to Data Mining" (transform used to derive entropies/terms).

Examples

Y <- log(1 + university$frequencies[, university$terms])
nb_data <- NormalBlockData$new(Y, X = matrix(1, nrow(Y), 1))

out <- normal_block(nb_data, 2:6, control = NB_control(verbose = FALSE))
out$get_best_model("ICL")