R/model_sdm.R

Defines functions sdm_stanvar_int_array .sdm_wide_rule sdm_run_metadata posterior_predict_sdm_simple log_lik_sdm_simple revert_postprocess_brm.sdm postprocess_brm.sdm configure_model.sdm check_data.sdm sdmSimple sdm settable_links.sdm .model_sdm

Documented in sdm sdmSimple

############################################################################# !
# MODELS                                                                 ####
############################################################################# !

.model_sdm <- function(resp_error = NULL, links = NULL, version = "simple", call = NULL, ...) {
  out <- structure(
    list(
      resp_vars = nlist(resp_error),
      other_vars = nlist(),
      domain = "Visual working memory",
      task = "Continuous reproduction",
      name = "Signal Discrimination Model (SDM) by Oberauer (2023)",
      citation = glue(
        "Oberauer, K. (2023). Measurement models for visual working \\
        memory\u2014A factorial model comparison. Psychological Review, \\
        130(3), 841-852. https://doi.org/10.1037/rev0000328"
      ),
      version = version,
      requirements = glue(
        "- The response variable should be in radians and represent the angular \\
        error relative to the target"
      ),
      parameters = list(
        mu = glue("Location parameter of the SDM distribution (in radians; \\
                  by default fixed internally to 0)"),
        c = "Memory strength parameter of the SDM distribution",
        kappa = "Precision parameter of the SDM distribution"
      ),
      links = list(
        mu = "tan_half",
        c = "log",
        kappa = "log"
      ),
      fixed_parameters = list(mu = 0),
      default_priors = list(
        mu = list(main = "normal(0, 0.5)", effects = "normal(0, 0.25)", sd = "exponential(4)"),
        kappa = list(main = "student_t(5, 1.75, 0.75)", effects = "normal(0, 1)", sd = "exponential(1)"),
        c = list(main = "student_t(5, 2, 0.75)", effects = "normal(0, 1)", sd = "exponential(1)")
      ),
      init_ranges = list(
        mu = c(-0.5,0.5),
        kappa = c(2.5,3.5),
        c = c(4,6)
      )
    ),
    class = c("bmmodel", "circular", "sdm", paste0("sdm_", version)),
    call = call
  )
  out <- set_links(out, links)
  out
}

# configure_model.sdm declares the family links itself, and the log link of `c`
# is written into the Stan chunk as exp(c), so none of the three can be set
#' @exportS3Method
settable_links.sdm <- function(model) {
  character(0)
}

# user facing alias
# information in the title and details sections will be filled in
# automatically based on the information in the .model_sdm_simple(NA)$info

#' @title `r .model_sdm()$name`
#' @name sdm
#' @details see [the online article](https://venpopov.com/bmm/articles/bmm_sdm_simple.html) for a detailed description of the model
#'   and how to use it. `r model_docs(.model_sdm())`
#' @param resp_error The name of the variable in the dataset containing the
#'   response error. The response error should code the response relative to the
#'   to-be-recalled target in radians. You can transform the response error in
#'   degrees to radians using the `deg2rad` function.
#' @param version Character. The version of the model to use. Currently only
#'   "simple" is supported.
#' @param ... used internally for testing, ignore it
#' @return An object of class `bmmodel`
#' @export
#' @keywords bmmodel
#' @examplesIf identical(Sys.getenv("BMM_EXAMPLES"), "true")
#' # simulate data from the model
#' dat <- data.frame(y = rsdm(n = 1000, c = 4, kappa = 3))
#'
#' # specify formula
#' ff <- bmf(
#'   c ~ 1,
#'   kappa ~ 1
#' )
#'
#' # specify the model
#' fit <- bmm(
#'   formula = ff,
#'   data = dat,
#'   model = sdm(resp_error = "y"),
#'   cores = 4,
#'   backend = "cmdstanr"
#' )
sdm <- function(resp_error, version = "simple", ...) {
  call <- match.call()
  .check_constructor_dots(list(...), known = "links")
  stop_missing_args()
  version <- match.arg(version)
  .model_sdm(resp_error = resp_error, version = version, call = call, ...)
}

#' @rdname sdm
#' @keywords deprecated
#' @export
sdmSimple <- function(resp_error, version = "simple", ...) {
  warning2("The function `sdmSimple()` is deprecated. Please use `sdm()` instead.")
  call <- match.call()
  .check_constructor_dots(list(...), known = "links")
  stop_missing_args()
  .model_sdm(resp_error = resp_error, version = version, call = call, ...)
}

############################################################################# !
# CHECK_DATA S3 METHODS                                                  ####
############################################################################# !

#' @export
check_data.sdm <- function(model, data, formula) {
  # data sorted by predictors is necessary for speedy computation of normalizing constant
  data <- order_data_query(model, data, formula)
  attr(data, "sdm_run_metadata") <- sdm_run_metadata(data, formula, model)
  NextMethod("check_data")
}

############################################################################# !
# CONFIGURE_MODEL S3 METHODS                                             ####
############################################################################# !
# Each model should have a corresponding configure_model.* function. See
# ?configure_model for more information.

#' @export
configure_model.sdm <- function(model, data, formula) {
  # note - c has a log link, but I've coded it manually for computational efficiency
  sdm_simple <- brms::custom_family(
    name = "sdm_simple",
    dpars = c("mu", "c", "kappa"),
    links = c("tan_half", "identity", "log"),
    lb = c(NA, NA, NA),
    ub = c(NA, NA, NA),
    type = "real", loop = FALSE,
    log_lik = log_lik_sdm_simple,
    posterior_predict = posterior_predict_sdm_simple,
    posterior_epred = posterior_epred_sdm_simple
  )

  # prepare initial stanvars to pass to brms, model formula and priors
  sc_path <- system.file("stan_chunks", package = "bmm")
  stan_funs <- read_lines2(paste0(sc_path, "/sdm_simple_funs.stan"))
  stan_tdata <- read_lines2(paste0(sc_path, "/sdm_simple_tdata.stan"))
  likelihood_file <- if (brms_slices_likelihood()) {
    "sdm_simple_likelihood_threaded.stan"
  } else {
    "sdm_simple_likelihood.stan"
  }
  stan_likelihood <- read_lines2(paste0(sc_path, "/", likelihood_file))
  run_metadata <- attr(data, "sdm_run_metadata")
  if (is.null(run_metadata)) {
    # Guard direct configure_model.sdm() calls that bypass check_data.sdm().
    run_metadata <- sdm_run_metadata(data, formula, model)
  }
  # 16 nodes per panel and the 32-node wide rule keep log Z within 4e-12
  # where it is below 1e4 and, above it, within 5e-10 to log c = 12 and
  # kappa = 3000 and within 3 ulps beyond; where sdm_simple_ldenom()
  # switches between them they differ by 4e-14 (#615).
  # test-model_sdm-stan.R holds the bar
  gl <- .gl_rule(16L)
  wide <- .sdm_wide_rule()
  stanvars <- brms::stanvar(scode = stan_funs, block = "functions") +
    brms::stanvar(scode = stan_tdata, block = "tdata") +
    brms::stanvar(x = gl$nodes, name = "sdm_gl_x") +
    brms::stanvar(x = gl$weights, name = "sdm_gl_w") +
    brms::stanvar(x = wide$cosm1, name = "sdm_wide_cosm1") +
    brms::stanvar(x = wide$weights, name = "sdm_wide_w") +
    brms::stanvar(x = run_metadata$G_sdm_runs, name = "G_sdm_runs") +
    sdm_stanvar_int_array(run_metadata$sdm_run_start, "sdm_run_start", "G_sdm_runs") +
    sdm_stanvar_int_array(run_metadata$sdm_run_count, "sdm_run_count", "G_sdm_runs") +
    brms::stanvar(scode = stan_likelihood, block = "likelihood", position = "end")

  # construct main brms formula from the bmm formula
  formula <- bmf2bf(model, formula)
  formula$family <- sdm_simple

  nlist(formula, data, stanvars)
}

############################################################################# !
# POSTPROCESS METHODS                                                    ####
############################################################################# !

#' @export
postprocess_brm.sdm <- function(model, fit, ...) {
  # manually set link_c to "log" since I coded it manually
  fit$family$link_c <- "log"
  fit$formula$family$link_c <- "log"
  fit
}

#' @export
revert_postprocess_brm.sdm <- function(model, fit, ...) {
  fit$family$link_c <- "identity"
  fit$formula$family$link_c <- "identity"
  fit
}

log_lik_sdm_simple <- function(i, prep) {
  mu <- brms::get_dpar(prep, "mu", i = i)
  c <- brms::get_dpar(prep, "c", i = i)
  kappa <- brms::get_dpar(prep, "kappa", i = i)
  y <- prep$data$Y[i]
  dsdm(y, mu, c, kappa, log = T)
}

posterior_epred_sdm_simple <- posterior_epred_undefined("sdm")

posterior_predict_sdm_simple <- function(i, prep, ...) {
  mu <- brms::get_dpar(prep, "mu", i = i)
  c <- brms::get_dpar(prep, "c", i = i)
  kappa <- brms::get_dpar(prep, "kappa", i = i)
  rsdm(length(mu), mu, c, kappa)
}

sdm_run_metadata <- function(data, formula, model) {
  predictors <- data_predictor_vars(data, formula)
  # brms excludes rows with missing values in any model variable before
  # fitting, so run boundaries must be computed on the rows brms will keep
  model_vars <- unique(c(unlist(model$resp_vars), predictors))
  model_vars <- model_vars[model_vars %in% colnames(data)]
  if (length(model_vars) > 0L) {
    data <- data[stats::complete.cases(data[model_vars]), , drop = FALSE]
  }
  if (length(predictors) == 0L) {
    return(list(
      G_sdm_runs = 1L,
      sdm_run_start = 1L,
      sdm_run_count = nrow(data)
    ))
  }

  # values, not interaction() labels: pasted with ".", the cells (1, 5.2) and
  # (1.5, 2) would share one run and its first row's normalising constant.
  # The rows are complete cases here, so no comparison is NA
  changed <- Reduce(`|`, lapply(data[predictors], function(x) x[-1] != x[-length(x)]))
  run_start <- c(1L, which(changed) + 1L)
  run_count <- diff(c(run_start, nrow(data) + 1L))
  list(
    G_sdm_runs = length(run_start),
    sdm_run_start = as.integer(run_start),
    sdm_run_count = as.integer(run_count)
  )
}

# The midpoint rule on [0, pi] after mapping t to t - 0.55 sin(t) three times.
# The map fixes 0 and pi and keeps the integrand smooth and periodic, so the
# rule keeps converging geometrically, and it crowds the nodes toward the
# spike at u = 0, where they are 11 times denser than without it. cos(u) - 1
# is formed as -2 sin(u / 2)^2, which does not cancel near the spike.
.sdm_wide_rule <- function() {
  n <- 32L
  u <- (seq_len(n) - 0.5) * pi / n
  weights <- rep(pi / n, n)
  for (i in 1:3) {
    weights <- weights * (1 - 0.55 * cos(u))
    u <- u - 0.55 * sin(u)
  }
  list(cosm1 = -2 * sin(u / 2)^2, weights = weights)
}

sdm_stanvar_int_array <- function(x, name, size) {
  x <- array(as.integer(x), dim = length(x))
  out <- brms::stanvar(x = x, name = name)
  out[[name]]$scode <- paste0("array[", size, "] int ", name, ";")
  out[[name]]$pll_args <- paste("data array[] int", name)
  out
}

Try the bmm package in your browser

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

bmm documentation built on Nov. 6, 2026, 5:06 p.m.