R/wrapper_fa.R

Defines functions rtmb_fa

Documented in rtmb_fa

#' RTMB-based Factor Analysis Wrapper
#'
#' @description
#' Performs exploratory factor analysis (EFA) using RTMB. It supports standard
#' rotation methods (e.g., varimax, promax) as well as regularized factor analysis
#' using a Spike-and-Slab Prior (SSP) for estimating sparse loading matrices.
#'
#' @param data Observation data frame or matrix (N x J).
#' @param nfactors Number of factors (K).
#' @param rotate String specifying the rotation method (e.g., "varimax", "promax", "ssp"). If NULL, no rotation is applied. Specifying "ssp" performs regularized factor analysis.
#' @param score Logical; if TRUE, factor scores are calculated in the generate block (default is FALSE).
#' @param prior Prior configuration: `prior_flat()`, `prior_normal()`, or
#'   `prior_weak()`. `prior_ssp()` is accepted when `rotate = "ssp"`.
#'   Hyperparameters can be specified within these functions (e.g.,
#'   `prior_normal(mean_sd = 10, sd_rate = 1 / 5, loadings_sd = 10)`).
#'   Available FA aliases are `mean_sd`, `sd_rate`, and `loadings_sd`; they
#'   override the corresponding common arguments `mu_sd`, `sigma_rate`, and
#'   `b_sd`. `sd_rate` is an exponential rate, so `1 / 5` gives a prior mean
#'   of 5. `ssp_ratio` is available when `rotate = "ssp"`.
#' @param y_range A numeric vector of length 2 specifying the theoretical min and max values of the items.
#'   Used to construct weakly informative priors when `prior = prior_weak()`.
#' @param init List of initial values.
#' @param fixed A named list of parameter values to fix (optional).
#' @param missing Missing value handling strategy: "listwise" (default) or "fiml" (Full Information Maximum Likelihood).
#' @param WAIC Logical; if TRUE, add pointwise `log_lik` to the generate block for WAIC.
#' @example inst/examples/ex_fa.R
#' @export
rtmb_fa <- function(data, nfactors = 1, rotate = NULL, score = FALSE,
                    prior = prior_flat(),
                    y_range = NULL,
                    init = NULL, fixed = NULL,
                    missing = c("listwise", "fiml"), WAIC = FALSE) {
  missing <- match.arg(missing)
  if (isTRUE(WAIC) && missing != "listwise") {
    stop("WAIC = TRUE is currently supported for rtmb_fa() only with missing = 'listwise'.", call. = FALSE)
  }
  if (!is.numeric(nfactors) || length(nfactors) != 1L || is.na(nfactors) ||
      nfactors < 1 || nfactors != as.integer(nfactors)) {
    stop("'nfactors' must be a positive integer.", call. = FALSE)
  }

  if (is.data.frame(data)) {
    if (!all(sapply(data, is.numeric))) {
      stop("All variables in the data must be numeric. Character or factor variables are not supported.", call. = FALSE)
    }
  } else if (!is.numeric(data) && !is.logical(data)) {
    stop("The data matrix must be numeric.", call. = FALSE)
  }
  Y <- as.matrix(data)
  if (missing == "listwise") {
    Y <- na.omit(Y)
  }
  K <- as.integer(nfactors)
  J <- ncol(Y)
  N <- nrow(Y)

  if (is.null(J) || J < 2L) {
    stop("Factor analysis requires at least two observed variables.", call. = FALSE)
  }
  if (is.null(N) || N < 2L) {
    stop("Factor analysis requires at least two complete observations.", call. = FALSE)
  }
  if (K >= J) stop("The number of factors (K) must be less than the number of observed variables (J).")

  var_names <- colnames(data)
  if (is.null(var_names)) var_names <- paste0("V", 1:J)
  factor_names <- paste0("Factor", 1:K)
  colnames(Y) <- var_names

  # --- 1. Pre-calculate Sufficient Statistics in R (Handling NAs) ---
  if (any(is.na(Y))) {
    Y_bar <- apply(Y, 2, mean, na.rm = TRUE)
    S_Y <- cov(Y, use = "pairwise.complete.obs") * (N - 1)
  } else {
    Y_bar <- apply(Y, 2, mean)
    S_Y <- cov(Y) * (N - 1)
  }

  # --- 2. Prior Handling (Extracting from prior object) ---
  if (is.null(prior)) prior <- prior_flat()
  is_ssp <- !is.null(rotate) && rotate == "ssp"

  # Automatically switch to prior_weak() if y_range is provided and prior is default flat
  if (!is.null(y_range) && inherits(prior, "rtmb_prior") && identical(prior$type, "flat")) {
    prior <- prior_weak()
  }

  prior <- .validate_prior_type(
    prior,
    allowed = if (is_ssp) c("flat", "normal", "weak", "ssp") else c("flat", "normal", "weak"),
    context = "rtmb_fa()"
  )

  prior_type <- prior$type
  
  # Error handling: if weak is requested but y_range is missing
  if (prior_type == "weak" && is.null(y_range)) {
    stop("When using 'prior_weak()', you must specify 'y_range' (e.g., y_range = c(1, 5)) to define the scaling of the priors.", call. = FALSE)
  }

  # Default/Initial settings
  prior_mean_center <- 0
  if (prior_type == "normal") {
    prior_mean_sd <- if ("mean_sd" %in% names(prior)) prior$mean_sd else prior$mu_sd
    prior_sd_rate <- if ("sd_rate" %in% names(prior)) prior$sd_rate else prior$sigma_rate
    prior_loadings_sd <- if ("loadings_sd" %in% names(prior)) prior$loadings_sd else prior$b_sd
  } else {
    prior_mean_sd <- prior$mean_sd
    prior_sd_rate <- prior$sd_rate
    prior_loadings_sd <- prior$loadings_sd
  }
  ssp_ratio <- if (!is.null(prior$ssp_ratio)) prior$ssp_ratio else 0.25

  # Weak Information Prior Logic (GLMER style)
  if (prior_type == "weak") {
    sd_ratio <- if (!is.null(prior$sd_ratio)) prior$sd_ratio else 0.5
    half_d_y <- diff(y_range) / 2
    base_scale <- half_d_y * sd_ratio
    
    prior_mean_center <- mean(y_range)
    prior_mean_sd <- half_d_y
    prior_sd_rate <- 1.0 / base_scale
    prior_loadings_sd <- base_scale
  }

  # --- 3. Simplified Setup AST ---
  setup_exprs <- list(
    "# Observed data",
    quote(Y <- as.matrix(.data))
  )
  if (missing == "listwise") {
    setup_exprs[[length(setup_exprs) + 1L]] <- quote(Y <- na.omit(Y))
  }
  setup_exprs <- c(setup_exprs, list(
    "# Number of factors (nfactors)",
    bquote(K <- .(K)),
    quote(N <- nrow(Y)),
    quote(J <- ncol(Y))
  ))
  if (missing == "listwise") {
    setup_exprs[[length(setup_exprs) + 1L]] <- quote(Y_bar <- colMeans(Y))
    setup_exprs[[length(setup_exprs) + 1L]] <- quote(S_Y <- cov(Y) * (N - 1))
  }
  if (prior_type == "weak") {
    setup_exprs <- c(setup_exprs, list(
      "# Prior scales",
      bquote(prior_mean_center <- .(prior_mean_center)),
      bquote(prior_mean_sd <- .(prior_mean_sd)),
      bquote(prior_sd_rate <- .(prior_sd_rate)),
      bquote(prior_loadings_sd <- .(prior_loadings_sd))
    ))
  }
  if (is_ssp) {
    setup_exprs[[length(setup_exprs) + 1L]] <- bquote(ssp_ratio <- .(ssp_ratio))
  }
  setup_ast <- as.call(c(list(as.name("{")), setup_exprs))

  if (is_ssp) {
    # Automatic generation of initial values for SSP
    if (is.null(init)) {
      tryCatch({
        eig <- eigen(S_Y / (N - 1))
        L_pca <- eig$vectors[, 1:K, drop = FALSE] %*% diag(sqrt(pmax(eig$values[1:K], 0.01)), nrow = K, ncol = K)
        var_Y <- diag(S_Y / (N - 1))

        if (K > 1) {
          pm <- stats::promax(L_pca, m = 4)
          init_Lambda <- unclass(pm$loadings)
          T_mat <- pm$rotmat
          Phi <- cov2cor(solve(t(T_mat) %*% T_mat))
          init_CF_Omega <- t(chol(Phi))
        } else {
          init_Lambda <- L_pca
          init_CF_Omega <- matrix(1, nrow = 1, ncol = 1)
          Phi <- matrix(1, nrow = 1, ncol = 1)
        }
        h2_raw <- rowSums(init_Lambda * (init_Lambda %*% Phi))
        init_sd <- sqrt(pmax(var_Y - h2_raw, 0.01 * var_Y))
        L_std <- init_Lambda / sqrt(var_Y)
        init_r <- ifelse(abs(L_std) > 0.2, 0.9, 0.1)

        init <- list(mean = Y_bar, Lambda_star = init_Lambda, sd = init_sd, CF_Omega = init_CF_Omega, r = init_r, tau = matrix(1.0, nrow = J, ncol = K))
      }, error = function(e) { init <- NULL })
    }

    param_ast <- quote({
      mean = Dim(dim = J)
      Lambda_star = Dim(c(J, K))
      r = Dim(c(J, K), lower = 0.001, upper = 0.999)
      tau = Dim(c(J, K), lower = 0)
      sd = Dim(J, lower = 0)
      CF_Omega = Dim(c(K, K), type = "CF_corr")
    })

    tran_ast <- quote({
      Lambda <- Lambda_star * r * tau
      Lambda_CF <- Lambda %*% CF_Omega
      h2 <- rtmb_vector(0, J, seed = sd[1])
      for (j in 1:J) {
        for (k in 1:K) {
          h2[j] <- h2[j] + Lambda[j, k] * Lambda_CF[j, k]
        }
      }
      var_Y <- h2 + sd^2
      sd_Y <- sqrt(var_Y)
      L <- rtmb_array(0, dim = c(J, K), seed = sd[1])
      for (j in 1:J) {
        for (k in 1:K) {
          L[j, k] <- Lambda[j, k] / sd_Y[j]
        }
      }
      fa_cor <- CF_Omega %*% t(CF_Omega)
    })

    model_exprs <- list()
    # In SSP case, Lambda is a transformed variable. 
    # S_Y ~ sufficient_multi_normal_fa(N, Y_bar, mean, sd, Lambda %*% CF_Omega)
    # Note: Lambda here is the loadings *before* correlation matrix rotation.
    if (missing == "listwise") {
      model_exprs[[1]] <- quote(S_Y ~ sufficient_multi_normal_fa(N, Y_bar, mean, sd, Lambda %*% CF_Omega))
    } else {
      model_exprs[[1]] <- quote(Y ~ fiml_multi_normal_fa(mean, Lambda %*% CF_Omega, sd))
    }
    if (prior_type == "normal") {
       if (!is.null(prior_mean_sd)) model_exprs[[length(model_exprs) + 1]] <- bquote(mean ~ normal(0, .(prior_mean_sd)))
       if (!is.null(prior_sd_rate)) model_exprs[[length(model_exprs) + 1]] <- bquote(sd ~ exponential(.(prior_sd_rate)))
    } else if (prior_type == "weak") {
       if (!is.null(prior_mean_sd)) model_exprs[[length(model_exprs) + 1]] <- bquote(mean ~ normal(prior_mean_center, prior_mean_sd))
       if (!is.null(prior_sd_rate)) model_exprs[[length(model_exprs) + 1]] <- bquote(sd ~ exponential(prior_sd_rate))
    }
    model_exprs[[length(model_exprs) + 1]] <- quote(CF_Omega ~ lkj_CF_corr(1))
    model_exprs[[length(model_exprs) + 1]] <- bquote(mu_r <- log(ssp_ratio / (1 - ssp_ratio)))
    model_exprs[[length(model_exprs) + 1]] <- quote(r ~ logit_normal(mu_r, 3))
    model_exprs[[length(model_exprs) + 1]] <- quote(tau ~ exponential(1))
    model_exprs[[length(model_exprs) + 1]] <- quote(Lambda_star ~ laplace(0, 1))
    model_ast <- as.call(c(list(as.name("{")), model_exprs))

    base_gq <- quote({
      Lambda_CF <- Lambda %*% CF_Omega
      Sigma <- Lambda %*% fa_cor %*% t(Lambda) + diag(sd^2)
      var_total <- rtmb_vector(0, J, seed = sd[1])
      var_common <- rtmb_vector(0, J, seed = sd[1])
      for (j in 1:J) {
        var_total[j] <- Sigma[j, j]
        for (k in 1:K) {
          var_common[j] <- var_common[j] + Lambda[j, k] * Lambda_CF[j, k]
        }
      }
      communality <- var_common / var_total
    })
    waic_expr <- if (isTRUE(WAIC)) {
      quote({ log_lik <- multi_normal_lpdf(Y, mean, Sigma, sum = FALSE) })
    } else {
      quote({})
    }
    score_expr <- if (score) {
      quote({
        # Use explicit matrix creation to ensure AD type is preserved
        Y_c <- Y - matrix(mean, nrow = N, ncol = J, byrow = TRUE)
        score <- Y_c %*% solve(Sigma, Lambda %*% fa_cor)
      })
    } else quote({})
    report_vars <- c("communality", if (isTRUE(WAIC)) "log_lik", if (score) "score")
    gq_ast <- as.call(c(list(as.name("{")), as.list(base_gq)[-1], as.list(waic_expr)[-1], as.list(score_expr)[-1], list(.rtmb_report_call(report_vars))))
    
    code_obj <- list(setup = setup_ast, parameters = param_ast, transform = tran_ast, model = model_ast, generate = gq_ast, env = parent.frame())
    code_obj$setup_env <- .rtmb_setup_env(environment(), setup_ast, exclude = names(data))
    p_names <- list(
      mean = var_names,
      Lambda_star = list(var_names, factor_names),
      r = list(var_names, factor_names),
      tau = list(var_names, factor_names),
      sd = var_names,
      CF_Omega = factor_names,
      Lambda = list(var_names, factor_names),
      L = list(var_names, factor_names),
      fa_cor = factor_names,
      communality = var_names
    )
    if (score) {
      ind_names <- rownames(Y); if (is.null(ind_names)) ind_names <- paste0("Id", 1:N)
      p_names[["score"]] <- list(ind_names, factor_names)
    }
    obj <- rtmb_model(data = data, code = code_obj, par_names = p_names, init = init, view = c("L", "sd", "fa_cor"), fixed = fixed)
    obj$type <- "fa"
    obj$extra <- list(
      source = "wrapper",
      prior_type = if (is_ssp) "ssp" else prior$type,
      marginal = "mean"
    )
    return(obj)

  } else {
    # --- Standard rotation logic ---
    if (is.null(init)) {
      tryCatch({
        eig <- eigen(S_Y / (N - 1))
        L_pca <- eig$vectors[, 1:K, drop = FALSE] %*% diag(sqrt(pmax(eig$values[1:K], 0.01)), nrow=K, ncol=K)
        L_top <- L_pca[1:K, , drop = FALSE]; qr_res <- qr(t(L_top)); Q_mat <- qr.Q(qr_res)
        init_loadings <- L_pca %*% Q_mat
        init_sd <- pmax(diag(S_Y / (N - 1)) - rowSums(init_loadings^2), 0.01)^0.5
        for (j in 1:J) for (k in 1:K) if (j < k) init_loadings[j, k] <- 0
        init <- list(mean = Y_bar, L_raw = init_loadings, sd = init_sd)
      }, error = function(e) { init <- NULL })
    }

    param_ast <- quote({
      mean <- Dim(dim = J)
      L_raw <- Dim(dim = c(J, K), type = "lower_tri")
      sd <- Dim(dim = J, lower = 0)
    })

    tran_ast <- quote({
      h2 <- rtmb_vector(0, J, seed = sd[1])
      for (j in 1:J) {
        for (k in 1:min(j, K)) {
          h2[j] <- h2[j] + L_raw[j, k]^2
        }
      }
      var_Y <- h2 + sd^2
      sd_Y <- sqrt(var_Y)
      L <- rtmb_array(0, dim = c(J, K), seed = sd[1])
      for (j in 1:J) {
        for (k in 1:min(j, K)) {
          L[j, k] <- L_raw[j, k] / sd_Y[j]
        }
      }
    })

    model_exprs <- list()
    # Standard FA case: L_raw is a parameter (lower triangular matrix)
    if (missing == "listwise") {
      model_exprs[[1]] <- quote(S_Y ~ sufficient_multi_normal_fa(N, Y_bar, mean, sd, L_raw))
    } else {
      model_exprs[[1]] <- quote(Y ~ fiml_multi_normal_fa(mean, L_raw, sd))
    }
    if (prior_type == "normal") {
       if (!is.null(prior_mean_sd)) model_exprs[[length(model_exprs) + 1]] <- bquote(mean ~ normal(0, .(prior_mean_sd)))
       if (!is.null(prior_sd_rate)) model_exprs[[length(model_exprs) + 1]] <- bquote(sd ~ exponential(.(prior_sd_rate)))
       if (!is.null(prior_loadings_sd)) model_exprs[[length(model_exprs) + 1]] <- bquote(L_raw ~ lower_tri_normal(0, .(prior_loadings_sd)))
    } else if (prior_type == "weak") {
       if (!is.null(prior_mean_sd)) model_exprs[[length(model_exprs) + 1]] <- bquote(mean ~ normal(0, prior_mean_sd))
       if (!is.null(prior_sd_rate)) model_exprs[[length(model_exprs) + 1]] <- bquote(sd ~ exponential(prior_sd_rate))
       if (!is.null(prior_loadings_sd)) model_exprs[[length(model_exprs) + 1]] <- bquote(L_raw ~ lower_tri_normal(0, prior_loadings_sd))
    }
    model_ast <- as.call(c(list(as.name("{")), model_exprs))

    base_gq <- quote({
      Sigma <- rtmb_array(0, dim = c(J, J), seed = sd[1])
      var_common <- rtmb_vector(0, J, seed = sd[1])
      for (j1 in 1:J) {
        for (j2 in 1:J) {
          for (k in 1:min(j1, j2, K)) {
            Sigma[j1, j2] <- Sigma[j1, j2] + L_raw[j1, k] * L_raw[j2, k]
          }
        }
      }
      for (j in 1:J) {
        Sigma[j, j] <- Sigma[j, j] + sd[j]^2
        for (k in 1:min(j, K)) {
          var_common[j] <- var_common[j] + L_raw[j, k]^2
        }
      }
      var_total <- rtmb_vector(0, J, seed = sd[1])
      for (j in 1:J) {
        var_total[j] <- Sigma[j, j]
      }
      communality <- var_common / var_total
    })
    waic_expr <- if (isTRUE(WAIC)) {
      quote({ log_lik <- multi_normal_lpdf(Y, mean, Sigma, sum = FALSE) })
    } else {
      quote({})
    }

    if (!is.null(rotate)) {
      rot_loadings_name <- paste0("L_", rotate)
      if (exists(rotate, where = asNamespace("stats"), mode = "function")) {
        rot_fn <- get(rotate, envir = asNamespace("stats"), mode = "function")
        fn_call <- call("::", as.name("stats"), as.name(rotate))
      }
      else if (exists(rotate, mode = "function")) { rot_fn <- match.fun(rotate); fn_call <- as.name(rotate) }
      else if (requireNamespace("GPArotation", quietly = TRUE) && exists(rotate, where = asNamespace("GPArotation"), mode = "function")) {
        rot_fn <- getFromNamespace(rotate, "GPArotation"); fn_call <- call("::", as.name("GPArotation"), as.name(rotate))
      } else stop("Rotation function not found: ", rotate)
      
      dummy_L <- matrix(rnorm(J * K), J, K); test_rot <- rot_fn(dummy_L)
      is_matrix_rot <- is.matrix(test_rot); has_phi <- !is_matrix_rot && !is.null(test_rot$Phi)
      if (is_matrix_rot) {
        rot_expr <- bquote({
          rot_obj <- .(fn_call)(L)
          .(as.name(rot_loadings_name)) <- unclass(rot_obj)
          dimnames(.(as.name(rot_loadings_name))) <- list(.(var_names), .(factor_names))
          class(.(as.name(rot_loadings_name))) <- c("rtmb_estimate_matrix", "matrix", "array")
        })
        score_expr <- if (score) bquote({
          Y_c <- Y - matrix(mean, nrow = N, ncol = J, byrow = TRUE)
          rot_raw <- unclass(.(fn_call)(L_raw)); if (!is.matrix(rot_raw)) rot_raw <- unclass(rot_raw$loadings)
          score <- Y_c %*% solve(Sigma, rot_raw)
        }) else quote({})
      } else {
        if (has_phi) {
          rot_expr <- bquote({
            rot_obj <- .(fn_call)(L)
            fa_cor <- rot_obj$Phi
            .(as.name(rot_loadings_name)) <- unclass(rot_obj$loadings)
            dimnames(.(as.name(rot_loadings_name))) <- list(.(var_names), .(factor_names))
            class(.(as.name(rot_loadings_name))) <- c("rtmb_estimate_matrix", "matrix", "array")
          })
          score_expr <- if (score) bquote({
            Y_c <- Y - matrix(mean, nrow = N, ncol = J, byrow = TRUE)
            rot_raw_obj <- .(fn_call)(L_raw); score <- Y_c %*% solve(Sigma, unclass(rot_raw_obj$loadings) %*% rot_raw_obj$Phi)
          }) else quote({})
        } else {
          rot_expr <- bquote({
            rot_obj <- .(fn_call)(L)
            .(as.name(rot_loadings_name)) <- unclass(rot_obj$loadings)
            dimnames(.(as.name(rot_loadings_name))) <- list(.(var_names), .(factor_names))
            class(.(as.name(rot_loadings_name))) <- c("rtmb_estimate_matrix", "matrix", "array")
          })
          score_expr <- if (score) bquote({
            Y_c <- Y - matrix(mean, nrow = N, ncol = J, byrow = TRUE)
            score <- Y_c %*% solve(Sigma, unclass(.(fn_call)(L_raw)$loadings))
          }) else quote({})
        }
      }
    } else { has_phi <- FALSE; rot_expr <- quote({}); score_expr <- if (score) quote({ Y_c <- Y - matrix(mean, nrow = N, ncol = J, byrow = TRUE); score <- Y_c %*% solve(Sigma, L_raw) }) else quote({}) }

    report_vars <- c(
      "communality",
      if (isTRUE(WAIC)) "log_lik",
      if (!is.null(rotate)) rot_loadings_name,
      if (isTRUE(has_phi)) "fa_cor",
      if (score) "score"
    )
    gq_ast <- as.call(c(list(as.name("{")), as.list(base_gq)[-1], as.list(waic_expr)[-1], as.list(rot_expr)[-1], as.list(score_expr)[-1], list(.rtmb_report_call(report_vars))))
    
    code_obj <- list(setup = setup_ast, parameters = param_ast, transform = tran_ast, model = model_ast, generate = gq_ast, env = parent.frame())
    code_obj$setup_env <- .rtmb_setup_env(environment(), setup_ast, exclude = names(data))
    p_names <- list(
      mean = var_names,
      L_raw = list(var_names, factor_names),
      sd = var_names,
      L = list(var_names, factor_names),
      communality = var_names
    )
    if (!is.null(rotate)) {
      p_names[[paste0("L_", rotate)]] <- list(var_names, factor_names)
      if (has_phi) p_names[["fa_cor"]] <- factor_names
    }
    if (score) { ind_names <- rownames(Y); if (is.null(ind_names)) ind_names <- paste0("Id", 1:N); p_names[["score"]] <- list(ind_names, factor_names) }

    target_view <- if (!is.null(rotate)) c(paste0("L_", rotate), "sd", "fa_cor") else c("L", "sd", "fa_cor")
    obj <- rtmb_model(data = data, code = code_obj, par_names = p_names, init = init, view = target_view, fixed = fixed)
    obj$type <- "fa"
    obj$extra <- list(
      source = "wrapper",
      prior_type = prior$type,
      marginal = "mean"
    )
    return(obj)
  }
}

Try the BayesRTMB package in your browser

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

BayesRTMB documentation built on Nov. 24, 2026, 9:06 a.m.