Package 'glt'

Title: Bayesian Factor Modelling via Generalized Lower Triangular Priors
Description: Sparse Bayesian factor models for multivariate data, built around a flexible Generalized Lower Triangular (GLT) process prior on the loading matrix by Canale and Frühwirth-Schnatter (2026) <doi:10.48550/arXiv.2610.09762>. The number of active factors, their sparsity pattern, and the loadings themselves are learned jointly via a Markov chain Monte Carlo sampler implemented in C++ with 'Rcpp' and 'RcppArmadillo'.
Authors: Antonio Canale [aut, cre]
Maintainer: Antonio Canale <[email protected]>
License: GPL-2
Version: 1.0
Built: 2026-10-29 17:17:46 UTC
Source: https://github.com/cran/glt

Help Index


gltfactor: Bayesian Factor Models with GLT Process Priors

Description

Fits a Bayesian Gaussian factor model under a Generalized Lower Triangular (GLT) process prior using an MCMC sampler implemented in C++ via Rcpp. The package provides tools for model fitting, posterior summarisation, identification post-processing, and visualisation of loading matrices and variance decompositions.

Details

The main entry point is gltfa(), which accepts a data matrix y (T x m) and returns a "gltfit" object containing posterior draws and metadata.

Main functions

gltfa()

Fit a GLT factor model via MCMC.

get_variance()

Compute posterior draws of the factor and total covariance matrices.

get_pivots()

Extract pivot row indices from a binary allocation matrix Delta.

plot_real_matrix()

Visualise a numeric matrix as a colour image using a diverging palette.

Author(s)

Maintainer: Antonio Canale [email protected]

Authors:

References

Canale, A. and Frühwirth-Schnatter, S. (2026). "The generalized lower triangular process prior." Technical Report,


Construct a "facmatrix" object

Description

A thin wrapper that tags a numeric matrix with class "facmatrix" so that it is plotted via plot.facmatrix() (a colour-image raster) rather than via the default matrix print/plot methods.

Usage

facmatrix(mat)

Arguments

mat

A numeric matrix.

Value

mat with class "facmatrix" prepended.


Extract pivot row indices from a Delta matrix

Description

For each column of Delta, returns the row index of the first 1, which defines the pivot row for that factor.

Usage

get_pivots(Delta)

Arguments

Delta

An ⁠m x H⁠ integer matrix with entries in ⁠{0, 1}⁠. Each column must contain at least one 1.

Value

An integer vector of length H.


Posterior draws of variance decomposition

Description

For each saved MCMC draw, computes the m×mm \times m matrices ΛΛ⊤\Lambda\Lambda^\top (factor covariance) and ΛΛ⊤+Σ\Lambda\Lambda^\top + \Sigma (total marginal covariance), where Σ=diag(σ12,…,σm2)\Sigma = \mathrm{diag}(\sigma^2_1, \ldots, \sigma^2_m).

Usage

get_variance(fit)

Arguments

fit

A gltfit object returned by gltfa().

Value

A named list with two elements:

LLt

An m×m×Sm \times m \times S array of ΛsΛs⊤\Lambda_s \Lambda_s^\top draws.

total

An m×m×Sm \times m \times S array of ΛsΛs⊤+Σs\Lambda_s \Lambda_s^\top + \Sigma_s draws.


Fit a Bayesian factor model with GLT process prior

Description

Fits a Bayesian Gaussian factor model under a Generalized Lower Triangular (GLT) process prior using an MCMC sampler implemented in C++ via Rcpp. This is the main user-facing entry point of the package.

Usage

gltfa(
  y,
  mcmc = list(),
  Hmax = ncol(y),
  prior = list(),
  init = list(),
  control = list(),
  fixed = list(),
  verbose = interactive()
)

Arguments

y

A numeric T×mT \times m data matrix with observations in rows and variables in columns. Missing values are not supported.

mcmc

A named list of MCMC settings. Recognised fields:

niter

Positive integer. Total number of MCMC iterations. Default 5000.

nburn

Non-negative integer. Number of burn-in iterations to discard. Must be strictly less than niter. Default 2500.

thin

Positive integer. Thinning interval. Default 1.

Hmax

A positive integer giving a conservative upper bound for the number of active factors. Default ncol(y).

prior

A named list of prior hyperparameters. Recognised fields:

a_nu

Positive numeric. First shape of the Beta prior on the global inclusion probability ν\nu. Default 1.

b_nu

Positive numeric. Second shape of the Beta prior on ν\nu. Default 1.

alpha

Positive numeric. Shape of the Gamma prior on pivot loadings. Default 1.

beta

Positive numeric. Rate of the Gamma prior on pivot loadings. Default 1.

kappa

Positive numeric. Precision of the normal prior on non-pivot loadings. Default 1.

a_sigma

Positive numeric. Shape of the inverse-Gamma prior on idiosyncratic variances σi2\sigma^2_i. Default 2.

b_sigma

Positive numeric. Scale of the inverse-Gamma prior on σi2\sigma^2_i. Default 2.

init

A named list of initial values for the sampler. Recognised fields:

H

Single non-negative integer. Initial number of active factors.

Lambda

Numeric m×Hm \times H loading matrix.

Delta

Integer m×Hm \times H binary allocation matrix with entries in {0,1}\{0,1\}.

Eta

Numeric H×TH \times T factor score matrix.

ell

Integer vector of length HH with pivot row indices.

tau

Numeric vector of length HH with initial column-specific inclusion probabilities.

nu

Single numeric in (0,1)(0,1). Initial global sparsity parameter.

sigma2

Positive numeric vector of length mm. Initial idiosyncratic variances.

control

A named list of algorithmic and storage options. Recognised fields:

store_draws

Logical. Whether to store posterior draws of Lambda, Delta, sigma2, and H. Default TRUE.

store_eta

Logical. Whether to additionally store draws of the factor score matrix Eta. Default FALSE.

print_every

Positive integer. Print progress every this many iterations (only when verbose = TRUE). Default 100.

seed

Single integer or NULL. Random seed for the C++ sampler. Default NULL.

fixed

A named list of logical flags indicating which MCMC updates to skip. For example, list(H = TRUE) keeps the number of factors fixed at its initial value throughout sampling.

verbose

Logical. Whether to print sampling progress to the console. Defaults to interactive().

Details

The model is:

yt=Ληt+ϵt,ϵt∼Nm(0,Σ)y_t = \Lambda \eta_t + \epsilon_t, \quad \epsilon_t \sim N_m(0, \Sigma)

where Λ\Lambda is a sparse lower-triangular loading matrix controlled by a binary allocation matrix Δ\Delta, and Σ=diag(σ12,…,σm2)\Sigma = \mathrm{diag}(\sigma^2_1, \ldots, \sigma^2_m).

Notation and dimensions:

  • y is a numeric matrix of dimension T×mT \times m.

  • Lambda is a loading matrix of dimension m×Hm \times H.

  • Delta is a binary allocation matrix of dimension m×Hm \times H.

  • Eta is a factor score matrix of dimension H×TH \times T.

Value

An object of class "gltfit", a named list with components:

draws

A named list of posterior draws (if control$store_draws = TRUE): Lambda (m×Hmax⁡×nsavem \times H_{\max} \times n_{\text{save}}), Delta (m×Hmax⁡×nsavem \times H_{\max} \times n_{\text{save}}), sigma2 (m×nsavem \times n_{\text{save}}), H (nsaven_{\text{save}}), and optionally Eta (Hmax⁡×T×nsaveH_{\max} \times T \times n_{\text{save}}).

meta

A named list with nsave, Hmax, T, m.

input

A named list echoing the processed mcmc, prior, control, and fixed arguments.

call

The matched call.

References

Canale, A. and Frühwirth-Schnatter, S. (2026). "The generalized lower triangular process prior." arXiv preprint arXiv:2610.09762.

See Also

get_variance(), get_pivots(), plot_real_matrix()

Examples

set.seed(42)
Y <- matrix(rnorm(200 * 10), nrow = 200, ncol = 10)

fit <- gltfa(
  y       = Y,
  mcmc    = list(niter = 2000, nburn = 1000, thin = 1),
  Hmax    = 5,
  prior   = list(a_sigma = 2, b_sigma = 1),
  init    = list(H = 2),
  control = list(store_draws = TRUE, seed = 1L, random_scan = TRUE),
  verbose = FALSE
)

Fit a STAR-extended GLT factor model for discrete/mixed-scale data

Description

Fits the Kowal & Canale (2020) simultaneous transformation and rounding (STAR) extension of gltfa() to discrete-valued (e.g. counts, ordinal) observed data. A continuous latent matrix z is linked to the observed matrix y via a column-specific monotone transform G_j and a column-specific threshold sequence, and modelled with a regression mean plus the same sparse GLT factor model used by gltfa():

Usage

gltfa_star(
  y,
  X = NULL,
  thresholds = NULL,
  g_type = "exp",
  mcmc = list(),
  Hmax = ncol(y),
  prior = list(),
  init = list(),
  control = list(),
  fixed = list(),
  verbose = interactive()
)

Arguments

y

An integer (or coercible) T×mT \times m matrix of observed, 0-indexed levels (0,1,…,Kj−10, 1, \ldots, K_j - 1 for column j). Missing values are not supported.

X

A numeric T×pT \times p covariate matrix, or NULL (default) for a zero-mean latent process (p=0p = 0).

thresholds

A list of length ncol(y). Element j is either NULL (use the default integer-spaced cutpoints 1,2,…,max⁡(y⋅j)+11, 2, \ldots, \max(y_{\cdot j}) + 1, reproducing floor rounding) or a strictly increasing numeric vector of max⁡(y⋅j)+1\max(y_{\cdot j}) + 1 interior cutpoints (aj,1,…,aj,Kj−1)(a_{j,1}, \ldots, a_{j,K_j - 1}). Columns may have different numbers of levels KjK_j. Default NULL uses the default for every column.

g_type

Character vector of length 1 or ncol(y), each entry one of "identity" or "exp", giving the column-specific monotone transform GjG_j. Default "exp" for every column (count-data STAR).

mcmc, Hmax, control, fixed, verbose

As in gltfa().

prior

A named list of prior hyperparameters; see gltfa() for the factor-model hyperparameters (a_nu, b_nu, alpha, beta, kappa, a_sigma, b_sigma, ...), plus regression hyperparameters:

b0_beta

Numeric vector of length ncol(X). Prior mean for every column's regression coefficients. Default 0.

V_beta_inv

⁠p x p⁠ prior precision matrix (common across columns), i.e. beta_j ~ N(b0_beta, sigma2_j * V_beta_inv^{-1}). Default NULL, in which case V_beta_inv = I_p / c0_beta.

c0_beta

Positive numeric. Prior variance scale used when V_beta_inv is not supplied. Default 100.

init

A named list of initial values; see gltfa() for the factor-model fields, plus:

Beta

Numeric p×mp \times m matrix. Default all zero.

z

Numeric T×mT \times m matrix. Default a bound-consistent midpoint initialisation.

Details

yij=ℓ  ⟺  Gj(zij)∈[aj,ℓ,aj,ℓ+1)y_{ij} = \ell \iff G_j(z_{ij}) \in [a_{j,\ell}, a_{j,\ell+1})

zij=xi′βj+ϵij,ϵt∼Nm(0,ΛΛ′-structured Σ)z_{ij} = x_i'\beta_j + \epsilon_{ij}, \quad \epsilon_t \sim N_m(0, \Lambda\Lambda' \text{-structured } \Sigma)

Two extra Gibbs steps run before the original 8-step sampler on each iteration: imputing z from its truncated-normal full conditional (Step 0a), and updating the regression coefficients Beta (Step 0b, conjugate normal). The residual ⁠epsilon = z - X Beta⁠ is then fed into the unchanged Delta/pivots/H/Lambda/sigma2/Eta updates.

Value

An object of class c("gltfit_star", "gltfit"). In addition to the components documented in gltfa(), draws$Beta holds ⁠p x m⁠ draws of the regression coefficients (always stored), and last$z / last$epsilon hold the final latent-z / residual draws (not stored across iterations).

References

Canale, A. and Frühwirth-Schnatter, S. (2026). "The generalized lower triangular process prior." arXiv preprint arXiv:2610.09762,

Kowal, D. and Canale, A. (2020). "Simultaneous transformation and rounding (STAR) models for integer-valued data." Electronic Journal of Statistics, 14(1), 1744-1772.

See Also

gltfa()

Examples

set.seed(42)
Ycounts <- matrix(rpois(100 * 6, lambda = 3), nrow = 100, ncol = 6)

fit <- gltfa_star(
  y       = Ycounts,
  Hmax    = 3,
  mcmc    = list(niter = 500, nburn = 250, thin = 1),
  init    = list(H = 1),
  control = list(store_draws = TRUE, seed = 1L),
  verbose = FALSE
)

Plot a real-valued matrix as a colour image

Description

Renders a numeric matrix as a raster image using a diverging colour palette (via signed_palette() by default), with optional grid lines and axis labels. Rows increase downward (matrix convention).

Usage

plot_real_matrix(
  mat,
  palette_fun = signed_palette,
  draw_grid = TRUE,
  grid_col = "grey80",
  axes = TRUE,
  xlab = "column",
  ylab = "row",
  asp = 1,
  main = "",
  legend = FALSE,
  legend_n = 100,
  legend_width = 1.4,
  legend_digits = 2,
  v_lines = NULL,
  h_lines = NULL,
  ...
)

Arguments

mat

A numeric matrix to plot.

palette_fun

A function with signature f(x, ...) that maps a numeric vector to a character vector of hex colour codes. Defaults to signed_palette().

draw_grid

Logical. Whether to draw cell grid lines. Default TRUE.

grid_col

Character. Colour of the grid lines. Default "grey80".

axes

Logical. Whether to draw row and column axes. Default TRUE.

xlab

Character. Label for the horizontal axis. Default "column".

ylab

Character. Label for the vertical axis. Default "row".

asp

Numeric. Aspect ratio passed to plot(). Default 1.

main

Character. Plot title. Default "".

legend

Logical. Whether to draw a colour-scale legend to the right of the matrix image. Default FALSE.

legend_n

Integer. Number of colour steps used to build the legend gradient. Default 100.

legend_width

Numeric. Width of the legend panel in inches. Default 1.4.

legend_digits

Integer. Number of decimal digits shown on the legend axis labels. Default 2.

v_lines

Numeric vector or NULL. Column positions (on the data scale) at which to draw dashed vertical reference lines. Default NULL (no lines).

h_lines

Numeric vector or NULL. Row positions (on the data scale) at which to draw dashed horizontal reference lines. Default NULL (no lines).

...

Additional arguments forwarded to palette_fun.

Details

This is the internal workhorse used by plot.facmatrix(); it remains available for plotting plain numeric matrices directly.

Value

Invisibly NULL; called for its side effect of producing a plot.

See Also

signed_palette()


Plot a "facmatrix" object

Description

S3 plot method for objects of class "facmatrix". Renders the matrix as a colour-image raster using signed_palette() by default; see plot_real_matrix() for the full set of supported arguments.

Usage

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

Arguments

x

A "facmatrix" object (a numeric matrix with that class).

...

Additional arguments passed on to plot_real_matrix().

Value

Invisibly x; called for its side effect of producing a plot.

See Also

plot_real_matrix(), facmatrix()


Print a "summary.gltfit" object

Description

Print a "summary.gltfit" object

Usage

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

Arguments

x

A "summary.gltfit" object, as returned by summary.gltfit().

...

Currently unused.

Value

Invisibly x.


Summarize a "gltfit" object

Description

Computes posterior averages (across admissible saved MCMC draws) of Lambda, Delta, sigma2, and H, along with the posterior average of Ω=ΛΛ⊤+Σ\Omega = \Lambda \Lambda^\top + \Sigma, where Σ=diag(σ2)\Sigma = \mathrm{diag}(\sigma^2). The posterior-mean Lambda, Delta, and Omega matrices are returned with class "facmatrix" so they inherit plot.facmatrix().

Usage

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

Arguments

object

An object of class "gltfit", as returned by gltfa().

...

Currently unused.

Details

Before averaging, draws are filtered using admissible_draws(): a draw is dropped when, after removing spurious columns (loadings on a single variable) and any resulting all-zero rows, the allocation matrix fails sparvaride::counting_rule_holds(). This mirrors the usual post-processing step for GLT-type factor models, where unidentified draws (e.g. those with too few active variables per factor) should not contribute to posterior summaries of Lambda/Delta.

object$draws$Lambda and object$draws$Delta are stored as ragged lists of length nsaven_{\text{save}}, each element an m×Hsm \times H_s matrix (HsH_s is the active number of factors for that draw, see object$draws$H). Kept draws are zero-padded to m×Hmax⁡m \times H_{\max} before elementwise averaging. sigma2 draws are stored as an nsave×mn_{\text{save}} \times m matrix, averaged over kept rows. Ω\Omega is computed per kept draw as ΛsΛs⊤+diag(σs2)\Lambda_s \Lambda_s^\top + \mathrm{diag}(\sigma^2_s) (using the draw's own, unpadded Λs\Lambda_s) and then averaged.

Value

A named list with class "summary.gltfit" containing:

Lambda

Posterior mean loading matrix (m×Hmax⁡m \times H_{\max}), class "facmatrix".

Delta

Posterior mean allocation matrix (m×Hmax⁡m \times H_{\max}), class "facmatrix".

sigma2

Posterior mean idiosyncratic variances (length mm).

H

Posterior mean number of active factors (scalar).

Omega

Posterior mean of ΛΛ⊤+Σ\Lambda \Lambda^\top + \Sigma (m×mm \times m), class "facmatrix".

n_admissible

Number of draws retained after filtering.

n_total

Total number of saved draws before filtering.

See Also

gltfa(), plot.facmatrix(), sparvaride::counting_rule_holds()