R/NormalBlockData.R

## %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
##  CLASS NormalBlockData ##################################
## %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

#' Data Container for Normal-Block Models
#'
#' R6 class holding the responses and design matrix used to fit a
#' normal-block model.
#' @param Y the matrix of responses.
#' @param X design matrix.
#' @param X0 zero-inflation design matrix, if applicable.
#' @param 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 |
#' @param zeros an optional n x p 0/1 matrix marking the structural zeros of
#' Y. By default they are read off Y itself (`Y == 0`). Pass it explicitly
#' when the matrix handed to the model is no longer the one carrying the zeros
#' (typically the residuals of a first stage, see [normal_block_sequential()]).
#' @section 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).
#' @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)
#' @export
NormalBlockData <- R6::R6Class(
  classname = "NormalBlockData",
  ## %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  ## PUBLIC MEMBERS ----
  ## %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  public = list(
    #' @field Y the matrix of responses (rescaled column-wise if `scale = TRUE`)
    Y  = NULL,
    #' @field Y_scale the per-column standard deviation Y was divided by (all
    #' 1's if Y was not rescaled)
    Y_scale = NULL,
    #' @field scale the `scale` argument as given: `TRUE`, `FALSE`, or `NULL`
    #' for the family default (see `for_family()`)
    scale = NULL,
    #' @field X the matrix of covariates
    X = NULL,
    #' @field X0 the matrix of zero-inflation covariates, if applicable
    X0 = NULL,
    #' @field 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 |
    formula = NULL,
    #' @field n sample size
    n  = NULL,
    #' @field d number of covariates
    d = NULL,
    #' @field d0 number of zero-inflation covariates, if applicable
    d0 = NULL,
    #' @field p number of variables
    p = NULL,
    #' @field XtX useful for inference in some cases
    XtX = NULL,
    #' @field XtXm1 inverse of XtX, useful for inference
    XtXm1 = NULL,
    #' @field XtY useful for inference
    XtY = NULL,
    #' @field npY total number of non zeros in Y
    npY = NULL,
    #' @field nY total number of non zeros for each column/variable in Y
    nY = NULL,
    #' @field zeros where are the zero in Y
    zeros = NULL,
    #' @field zeros_bar where are the non-zeros in Y
    zeros_bar = NULL,

    #' @description Create a new [`NormalBlockData`] object.
    #' @param Y the matrix of responses (called Y in the model).
    #' @param X design matrix (called X in the model).
    #' @param X0 zero-inflation design matrix, if applicable.
    #' @param formula describes the relationship between Y and X, useful if not all of X's covariates should be used.
    #' @param 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()`.
    #' @param zeros an optional 0/1 matrix of structural zeros, overriding the
    #' default `Y == 0`.
    #' @param 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()`).
    initialize = function(Y, X, X0 = NULL, formula = NULL, scale = NULL,
                          zeros = NULL, check_constant = TRUE) {
      stopifnot("Y and X must be matrices" = all(is.matrix(Y), is.matrix(X)))
      stopifnot("Y and X must have the same number of rows" = (nrow(Y) == nrow(X)))
      stopifnot("scale must be NULL, TRUE or FALSE" =
                  is.null(scale) || (is.logical(scale) && length(scale) == 1 && !is.na(scale)))
      constant <- if (check_constant) which(apply(Y, 2, function(y) all(y == y[1]))) else integer(0)
      if (length(constant) > 0) {
        names_Y <- colnames(Y)
        stop("Y has constant columns, which carry no information to cluster on: ",
             paste(if (is.null(names_Y)) constant else names_Y[constant], collapse = ", "),
             ". Remove them before fitting.", call. = FALSE)
      }
      self$scale <- scale
      ## the constructor's arguments, kept for for_family(), subset() and
      ## Y_original
      private$args <- list(Y = Y, X = X, X0 = X0, formula = formula, zeros = zeros)
      if (isTRUE(scale)) {
        self$Y_scale <- pmax(apply(Y, 2, sd), .Machine$double.eps)
        self$Y <- Y / matrix(self$Y_scale, nrow(Y), ncol(Y), byrow = TRUE)
      } else {
        self$Y_scale <- rep(1, ncol(Y))
        self$Y <- Y
      }
      self$n <- nrow(Y)
      self$p <- ncol(Y)
      self$formula <- formula
      fm_zi <- NULL
      if(is.null(formula)){self$X <- X
      }else{
        stopifnot("The formula should start with ~" = (formula[[1]] == "~"))
        if(formula[[2]][[1]] == "|"){
          fm <- as.formula(paste0("~", formula[[2]][2]))
          fm_zi <- as.formula(paste0("~", formula[[2]][3]))
        }else{
          fm <- formula}
        stopifnot("Covariates given in formula must be present in X" = (length(setdiff(all.vars(terms(fm)), colnames(X))) ==0))
        self$X <- model.matrix(fm, as.data.frame(X))
      }
      if(is.null(X0)){X0 <- matrix(rep(1, self$n))}
      if(is.null(fm_zi)){
        self$X0 <- X0
      }else{
        self$X0 <- model.matrix(fm_zi, as.data.frame(X0))
        stopifnot("Zero-inflation covariates given in the formula must be present in X0" = (length(setdiff(all.vars(terms(fm_zi)), colnames(X0))) ==0))
      }
      self$d0        <- ncol(self$X0)
      self$d         <- ncol(self$X)
      self$XtX       <- crossprod(self$X)
      ## a rank-deficient design (e.g. a category absent from a cross-validation
      ## fold) falls back on the pseudo-inverse, i.e. minimum-norm least squares
      self$XtXm1     <- tryCatch(chol2inv(chol(self$XtX)), error = function(e) MASS::ginv(self$XtX))
      self$XtY       <- crossprod(self$X, self$Y)
      if (is.null(zeros)) {
        self$zeros <- 1 * (self$Y == 0)
      } else {
        stopifnot("zeros must be a matrix with the same dimensions as Y" =
          is.matrix(zeros) && all(dim(zeros) == dim(self$Y)))
        self$zeros <- 1 * (zeros != 0)
      }
      self$zeros_bar <- 1 - self$zeros
      self$npY       <- sum(self$zeros_bar)
      self$nY        <- colSums(self$zeros_bar)
    },

    #' @description 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.
    #' @param model the model family, `"var"` or `"mean"`
    #' @return a [`NormalBlockData`] object
    for_family = function(model = c("var", "mean")) {
      model <- match.arg(model)
      if (!is.null(self$scale) || model == "mean") return(self)
      if (is.null(private$scaled_copy))
        private$scaled_copy <- NormalBlockData$new(private$args$Y, private$args$X, private$args$X0,
                                                   private$args$formula, scale = TRUE,
                                                   zeros = private$args$zeros, check_constant = FALSE)
      private$scaled_copy
    },

    #' @description The data restricted to some observations, with the same
    #' covariates, formula, zeros and scale request (a rescaled Y is rescaled
    #' again on these rows).
    #' @param rows the observations to keep (indices or a logical vector)
    #' @param check_constant as in `new()`
    #' @return a [`NormalBlockData`] object
    subset = function(rows, check_constant = TRUE) {
      a <- private$args
      NormalBlockData$new(a$Y[rows, , drop = FALSE], a$X[rows, , drop = FALSE],
                          X0 = if (!is.null(a$X0)) a$X0[rows, , drop = FALSE],
                          formula = a$formula, scale = self$scale,
                          zeros = self$zeros[rows, , drop = FALSE],
                          check_constant = check_constant)
    },

    #' @description Ordinary-least-squares fit of Y on X, with its residuals
    #' and their covariance. Computed once and memoized.
    #' @return a list with `B` (d x p), `R` (n x p residuals) and `Sigma`
    #' (p x p residual covariance)
    ols_fit = function() {
      if (is.null(private$ols_cache)) {
        B <- self$XtXm1 %*% self$XtY
        R <- self$Y - self$X %*% B
        private$ols_cache <- list(B = B, R = R, Sigma = cov(R))
      }
      private$ols_cache
    },

    #' @description 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.
    #' @return a list with `B` (d x p), `dm1` (p) and `R` (n x p masked residuals)
    zi_ols_fit = function() {
      if (is.null(private$zi_ols_cache)) private$zi_ols_cache <- zi_weighted_fit(self)
      private$zi_ols_cache
    },

    #' @description 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.
    #' @return a list with `B0` (d0 x p), `kappa` (n x p zero-inflation
    #' probabilities) and `ZI_cond_mean` (a scalar)
    zi_fit = function() {
      if (is.null(private$zi_cache)) {
        ## d0 x p, one column of coefficients per variable.
        no_zeros <- self$npY == self$n * self$p
        B0 <- if (!no_zeros) {
          coefs <- lapply(1:self$p, function(j) {
            df <- data.frame("zeros" = self$zeros[, j], self$X0)
            glm(zeros ~ 0 + ., family = binomial(link = "logit"), data = df)$coefficients
          })
          matrix(unlist(coefs), nrow = self$d0, ncol = self$p)
        } else {
          matrix(rep(-Inf, self$p * self$d0), nrow = self$d0)
        }
        ## With no zeros to model, kappa is 0 by construction. Taking it from
        ## the -Inf sentinel instead only works when d0 == 1: a second
        ## covariate contributes x * -Inf, which is +Inf wherever x < 0, and
        ## the linear predictor collapses to NaN.
        kappa <- if (no_zeros) matrix(0, self$n, self$p)
                 else stats::plogis(self$X0 %*% B0)
        private$zi_cache <- list(
          B0 = B0, kappa = kappa,
          ZI_cond_mean = sum(xlogy(self$zeros, kappa)) +
                         sum(xlogy(self$zeros_bar, 1 - kappa)))
      }
      private$zi_cache
    }
  ),

  ## %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  ## PRIVATE MEMBERS ----
  ## %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  private = list(
    ## memoized by ols_fit()/zi_fit(); both are pure functions of the fields
    ## set in initialize(), none of which change afterwards
    ols_cache     = NULL,
    zi_ols_cache  = NULL,
    zi_cache      = NULL,
    ## the constructor's arguments, and the rescaled copy built from them for
    ## the variance-block family when scale = NULL (see for_family())
    args          = NULL,
    scaled_copy   = NULL
  ),

  ## %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  ##  ACTIVE BINDINGS ----
  ## %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  active = list(
    #' @field Y_original the matrix of responses as given, before any rescaling
    Y_original = function() private$args$Y
  )
)

Try the normalblockr package in your browser

Any scripts or data that you put into this service are public.

normalblockr documentation built on Nov. 24, 2026, 1:06 a.m.