tests/testthat/test-model_lba1.R

context("Single-Accumulator LBA")

test_that("rcogmod_lba1 produces valid reaction times and responds to parameters", {
  skip_on_cran()
  set.seed(123)
  n <- 10000  # Large sample size for reliable means

  # Parameter combinations for basic property tests
  param_combinations <- expand.grid(
    drift = c(1, 3),
    sigma = 1,
    sigmabias = 0.5,
    boundary = 0.5,
    ndt = 0.3
  )

  # 1. Basic property tests
  for (i in 1:nrow(param_combinations)) {
    params <- param_combinations[i, ]
    label <- sprintf("params(drift=%.1f, sigma=%.1f, sigmabias=%.1f, boundary=%.1f, ndt=%.1f)",
                     params$drift, params$sigma, params$sigmabias, params$boundary, params$ndt)
    rts <- rcogmod_lba1(n, drift = params$drift, sigma = params$sigma,
                   sigmabias = params$sigmabias, boundary = params$boundary, ndt = params$ndt)

    # Check for NA values
    if (any(is.na(rts))) {
      warning("NA values generated by rcogmod_lba1 for ", label)
      next
    }

    # All RTs should be >= ndt
    expect_true(all(rts >= params$ndt),
                label = paste(label, "- All RTs >= ndt"))

    # All RTs should be finite
    expect_true(all(is.finite(rts)),
                label = paste(label, "- All RTs are finite"))
  }

  # 2. Parameter sensitivity tests
  # Effect of drift: higher drift should decrease mean RT
  params_low_drift <- list(drift = 1, sigma = 1, sigmabias = 0.5, boundary = 0.5, ndt = 0.3)
  params_high_drift <- list(drift = 3, sigma = 1, sigmabias = 0.5, boundary = 0.5, ndt = 0.3)

  rts_low_drift <- rcogmod_lba1(n, drift = params_low_drift$drift, sigma = params_low_drift$sigma,
                           sigmabias = params_low_drift$sigmabias, boundary = params_low_drift$boundary,
                           ndt = params_low_drift$ndt)
  rts_high_drift <- rcogmod_lba1(n, drift = params_high_drift$drift, sigma = params_high_drift$sigma,
                            sigmabias = params_high_drift$sigmabias, boundary = params_high_drift$boundary,
                            ndt = params_high_drift$ndt)

  mean_low_drift <- mean(rts_low_drift)
  mean_high_drift <- mean(rts_high_drift)

  expect_true(mean_high_drift < mean_low_drift,
              label = "Mean RT decreases with increasing drift")

  # Effect of boundary: higher boundary should increase mean RT
  params_low_boundary <- list(drift = 3, sigma = 1, sigmabias = 0.5, boundary = 0.5, ndt = 0.3)
  params_high_boundary <- list(drift = 3, sigma = 1, sigmabias = 0.5, boundary = 1, ndt = 0.3)

  rts_low_boundary <- rcogmod_lba1(n, drift = params_low_boundary$drift, sigma = params_low_boundary$sigma,
                        sigmabias = params_low_boundary$sigmabias, boundary = params_low_boundary$boundary,
                        ndt = params_low_boundary$ndt)
  rts_high_boundary <- rcogmod_lba1(n, drift = params_high_boundary$drift, sigma = params_high_boundary$sigma,
                         sigmabias = params_high_boundary$sigmabias, boundary = params_high_boundary$boundary,
                         ndt = params_high_boundary$ndt)

  mean_low_boundary <- mean(rts_low_boundary)
  mean_high_boundary <- mean(rts_high_boundary)

  expect_true(mean_high_boundary > mean_low_boundary,
              label = "Mean RT increases with increasing boundary")
})



test_that("dcogmod_lba1 integrates correctly and returns valid densities", {
  skip_on_cran()
  set.seed(456)
  n_samples_for_range <- 5000
  tol_integration <- 1e-3  # Tolerance for integration

  # Parameter combinations
  param_combinations <- expand.grid(
    drift = c(1, 3),
    sigma = c(0.5, 1),
    sigmabias = c(0.2, 0.5),
    boundary = 0.5,
    ndt = 0.3
  )

  # 1. Integration test
  for (i in 1:nrow(param_combinations)) {
    params <- param_combinations[i, ]
    label <- sprintf("params(drift=%.1f, sigma=%.1f, sigmabias=%.1f, boundary=%.1f, ndt=%.1f)",
                     params$drift, params$sigma, params$sigmabias, params$boundary, params$ndt)

    # Define the integrand
    integrand <- function(x) {
      dcogmod_lba1(x, drift = params$drift, sigma = params$sigma,
              sigmabias = params$sigmabias, boundary = params$boundary, ndt = params$ndt)
    }

    # Determine integration upper limit using simulated RTs
    x_sample_range <- rcogmod_lba1(n_samples_for_range, drift = params$drift,
                              sigma = params$sigma, sigmabias = params$sigmabias,
                              boundary = params$boundary, ndt = params$ndt)
    if (any(is.na(x_sample_range)) || length(x_sample_range) < 2) {
      warning("Skipping integration test for ", label, " due to invalid sample range.")
      next
    }
    upper_limit <- quantile(x_sample_range, 0.9999, na.rm = TRUE) +
      10 * sd(x_sample_range, na.rm = TRUE)
    if (!is.finite(upper_limit) || upper_limit < params$ndt + 10) {
      upper_limit <- params$ndt + 100
    }

    # Compute the integral
    integral_result <- tryCatch(
      stats::integrate(integrand, lower = params$ndt + .Machine$double.eps,
                       upper = upper_limit, subdivisions = 1000,
                       rel.tol = tol_integration / 10, abs.tol = tol_integration / 10)$value,
      error = function(e) {
        warning("Integration failed for ", label, ": ", e$message)
        NA
      }
    )

    if (!is.na(integral_result)) {
      expect_equal(integral_result, 1, tolerance = tol_integration,
                   label = paste(label, "- Density integrates to 1"))
    }
  }

  # 2. Density value tests with a single parameter set
  params <- list(drift = 3, sigma = 1, sigmabias = 0.5, boundary = 0.5, ndt = 0.3)
  rt_below_ndt <- params$ndt - 0.1
  rt_at_ndt <- params$ndt
  rt_above_ndt <- params$ndt + 0.5

  # Density should be 0 for RT < ndt
  expect_equal(dcogmod_lba1(rt_below_ndt, drift = params$drift, sigma = params$sigma,
                       sigmabias = params$sigmabias, boundary = params$boundary, ndt = params$ndt),
               0, label = "Density is 0 for RT < ndt")

  # Density should be non-negative at RT = ndt
  density_at_ndt <- dcogmod_lba1(rt_at_ndt, drift = params$drift, sigma = params$sigma,
                            sigmabias = params$sigmabias, boundary = params$boundary, ndt = params$ndt)
  expect_true(density_at_ndt >= 0,
              label = "Density is non-negative at RT = ndt")

  # Density should be non-negative for RT > ndt
  density_above_ndt <- dcogmod_lba1(rt_above_ndt, drift = params$drift, sigma = params$sigma,
                               sigmabias = params$sigmabias, boundary = params$boundary, ndt = params$ndt)
  expect_true(density_above_ndt >= 0,
              label = "Density is non-negative for RT > ndt")
})



context("Single-Accumulator LBA - brms")

test_that("cogmod_lba2 model can recover parameters with brms", {
  skip_if_not_slow()
  skip_on_cran()
  skip_if_not_installed("brms")
  skip_if_not_installed("cmdstanr")

  set.seed(1234)
  n <- 4000
  true_drift <- 4
  true_sigma <- 1
  true_sigmabias <- 0.5
  true_boundary <- 0.3
  true_ndt <- 0.16
  true_poutlier <- 0.02

  df <- data.frame(rt = rcogmod_lba1(n, drift = true_drift, sigma = true_sigma,
                                sigmabias = true_sigmabias, boundary = true_boundary,
                                ndt = true_ndt, poutlier = true_poutlier))
  df <- df[df$rt < 1, , drop = FALSE]

  # sigma is fixed to 1: the evidence scale is arbitrary, so drift, sigmabias
  # and boundary are only identified relative to it. ndt is now estimated directly.
  f <- brms::bf(
    rt ~ 1,
    sigma = 1,
    sigmabias ~ 1,
    boundary ~ 1,
    ndt ~ 1,
    poutlier ~ 1,
    family = cogmod_lba1()
  )

  # Only the drift is helped along here; cogmod_priors() now supplies the
  # sigmabias and boundary rows itself, which is what the block below pins.
  priors <- c(
    cogmod_priors(f, df),
    brms::set_prior("normal(3, 1)", class = "Intercept", dpar = ""),
    replace = TRUE
  )

  fit <- brms::brm(
    formula = f,
    data = df,
    prior = priors,
    stanvars = cogmod_lba1_stanvars(),
    backend = "cmdstanr",
    algorithm = "pathfinder",
    init = 0,
    refresh = 0
  )

  fixed <- summary(fit)$fixed
  # ndt is on a log link and is the parameter the reparameterization is about
  expect_equal(exp(fixed["ndt_Intercept", "Estimate"]), true_ndt,
               tolerance = 0.08, label = "ndt recovery")
  expect_true(is.finite(fixed["Intercept", "Estimate"]))
})


test_that("Stan cogmod_lba1_lpdf matches R dcogmod_lba1", {
  skip_on_cran()
  skip_if_not_installed("cmdstanr")

  cogmod_lba1_lpdf_stan <- stan_fun("cogmod_lba1")

  grid <- expand.grid(
    Y = c(0.3, 0.5, 0.8, 1.2, 2.0),
    drift = c(1, 3),
    sigma = c(0.5, 1),
    # the small start-point ranges are the ones that used to break: both
    # differences in the LBA bracket cancel as sigmabias -> 0. Zero itself is
    # the recinormal (LATER), a supported model rather than a boundary to
    # avoid, and Stan has to agree with R there too.
    sigmabias = c(0, 1e-6, 1e-3, 0.5, 1.0),
    boundary = c(0.2, 0.5),
    ndt = c(0, 0.1, 0.25),
    poutlier = c(0, 0.03)
  )

  for (k in seq_len(nrow(grid))) {
    g <- grid[k, ]
    stan_lpdf <- cogmod_lba1_lpdf_stan(g$Y, g$drift, g$sigma, g$sigmabias, g$boundary,
                                  g$ndt, g$poutlier)
    r_lpdf <- dcogmod_lba1(g$Y, drift = g$drift, sigma = g$sigma,
                      sigmabias = g$sigmabias, boundary = g$boundary, ndt = g$ndt,
                      poutlier = g$poutlier, log = TRUE)
    label <- sprintf("Y=%.2f, drift=%.1f, sigma=%.1f, A=%g, boundary=%.1f, ndt=%.2f, p=%.2f",
                     g$Y, g$drift, g$sigma, g$sigmabias, g$boundary, g$ndt, g$poutlier)
    expect_equal(stan_lpdf, r_lpdf, tolerance = 1e-8,
                 label = paste("Density mismatch:", label))
  }
})


test_that("the density stays normalised as the start-point range shrinks", {
  skip_on_cran()
  # Regression test. The bracket
  #   drift * (Phi(z2) - Phi(z1)) + sigma * (phi(z1) - phi(z2))
  # is divided by the start-point range A, and both differences vanish linearly
  # in A. Evaluating them directly (and flooring the result at 1e-10, as the
  # previous implementation did) made the density stop integrating to one below
  # about A = 0.1, and diverge outright below A = 0.01.
  for (A in c(2, 0.5, 0.1, 1e-2, 1e-4, 1e-6, 1e-8)) {
    total <- integrate(
      function(z) dcogmod_lba1(z, drift = 3, sigma = 1, sigmabias = A, boundary = 0.5,
                          ndt = 0.3),
      lower = 0.3, upper = Inf, rel.tol = 1e-10
    )$value
    expect_equal(total, 1, tolerance = 1e-5,
                 label = sprintf("integral at sigmabias = %g", A))
  }

  # As the start-point range vanishes the model becomes the recinormal (LATER),
  # in which 1 / (RT - ndt) is normally distributed. Convergence is O(A), with
  # the relative error settling at about 9 * A for these parameters.
  recinormal <- function(t, drift = 3, s = 1, b = 0.5, ndt = 0.3) {
    dnorm(b / (t - ndt), drift, s) / (1 - pnorm(0, drift, s)) * b / (t - ndt)^2
  }
  x <- c(0.4, 0.5, 0.8)
  prev <- Inf
  for (A in c(1e-2, 1e-4, 1e-6)) {
    rel <- max(abs(dcogmod_lba1(x, sigmabias = A, ndt = 0.3) / recinormal(x) - 1))
    expect_lt(rel, 12 * A)
    expect_lt(rel, prev)
    prev <- rel
  }
})


test_that("sigmabias = 0 is exactly the recinormal (LATER) model", {
  skip_on_cran()
  # The end of that sequence is not merely approached, it is reachable: zero is
  # an admissible value of `sigmabias`, and there the density IS the recinormal,
  # in which 1 / (RT - ndt) is normally distributed. delta = sigmabias / st is
  # then 0, which takes the Taylor branch of .lba_ldens(), and there
  # drift + sigma * z1 = b / t identically - so what comes out is the closed
  # form below rather than an approximation to it.
  recinormal <- function(t, drift, s, b, ndt) {
    d <- t - ndt
    dnorm(b / d, drift, s) * b / d^2 / pnorm(drift / s)
  }

  grid <- covering_grid(
    x = c(0.35, 0.5, 0.9, 1.6, 3.0),
    drift = c(1, 3, 6),
    sigma = c(0.5, 1, 2),
    boundary = c(0.2, 0.5, 1),
    ndt = c(0, 0.1, 0.3)
  )
  for (k in seq_len(nrow(grid))) {
    g <- grid[k, ]
    got <- dcogmod_lba1(g$x, drift = g$drift, sigma = g$sigma, sigmabias = 0,
                        boundary = g$boundary, ndt = g$ndt)
    want <- recinormal(g$x, g$drift, g$sigma, g$boundary, g$ndt)
    expect_equal(got, want, tolerance = 1e-12,
                 label = sprintf("x=%.2f drift=%g sigma=%g b=%g ndt=%g",
                                 g$x, g$drift, g$sigma, g$boundary, g$ndt))
  }

  # Proper, not defective: truncating the drift at zero is what the 1 / Phi
  # normalisation in the closed form above pays for.
  total <- integrate(
    function(z) dcogmod_lba1(z, drift = 3, sigma = 1, sigmabias = 0,
                             boundary = 0.5, ndt = 0.3),
    lower = 0.3, upper = Inf, rel.tol = 1e-10
  )$value
  expect_equal(total, 1, tolerance = 1e-6)

  # Continuous into the pinned value from above, so the free and the fixed model
  # really are the same likelihood at the same point.
  approach <- vapply(
    c(1e-2, 1e-4, 1e-6, 1e-8),
    function(A) dcogmod_lba1(0.5, sigmabias = A, ndt = 0.3), numeric(1)
  )
  at_zero <- dcogmod_lba1(0.5, sigmabias = 0, ndt = 0.3)
  expect_equal(approach[length(approach)], at_zero, tolerance = 1e-7)
  expect_true(all(diff(abs(approach - at_zero)) < 0))

  # The RNG follows: every trial starts at zero, so RT = ndt + b / drift.
  set.seed(11)
  rts <- rcogmod_lba1(20000, drift = 3, sigma = 1, sigmabias = 0,
                      boundary = 0.5, ndt = 0.3)
  expect_true(all(rts > 0.3))
  expect_true(all(is.finite(rts)))
  # promptness is the truncated normal it is supposed to be
  promptness <- 0.5 / (rts - 0.3)
  expect_equal(mean(promptness), 3, tolerance = 0.05)
  expect_equal(sd(promptness), 1, tolerance = 0.05)

  # The bound is closed, not open: zero is admissible and only negatives are not.
  expect_silent(dcogmod_lba1(0.5, sigmabias = 0, ndt = 0.2))
  expect_warning(dcogmod_lba1(0.5, sigmabias = -1e-8, ndt = 0.2),
                 "must be at least 0")
})


test_that("cogmod_priors fences off the sigmabias = 0 flat direction", {
  # As the start-point range approaches zero the LBA converges to the
  # recinormal, so the likelihood stops depending on `sigmabias` altogether -
  # and softplus reaches zero only at minus infinity. Left flat, that is an
  # improper posterior of exactly the kind cogmod_priors() exists to prevent for
  # `ndt` and `poutlier`; fitted without it on the 4285-trial data in
  # vignette("rt_models"), `sigmabias` ran to softplus(-10.4) with Rhat 1.69 and
  # an effective sample size of 6.
  set.seed(3)
  d <- data.frame(
    rt = rcogmod_lba1(200, ndt = 0.25, poutlier = 0.02),
    Condition = rep(c("a", "b"), 100)
  )
  f <- brms::bf(rt ~ Condition, sigma = 1, sigmabias ~ Condition,
                boundary ~ Condition, ndt ~ 1, family = cogmod_lba1())

  # brms leaves both flat on its own
  raw <- brms::get_prior(f, data = d, family = cogmod_lba1())
  expect_true(all(raw$prior[raw$dpar %in% c("sigmabias", "boundary")] == ""))

  p <- cogmod_priors(f, d)
  for (dp in c("sigmabias", "boundary")) {
    # brms reports a blanket row plus one per coefficient; cogmod_priors fills
    # the blanket and leaves the per-coefficient row to inherit from it, so it
    # is the rows carrying a prior that are the ones to check
    rows <- p[p$dpar == dp & nzchar(p$prior), ]
    expect_equal(rows$prior[rows$class == "Intercept"], "normal(0, 1)",
                 label = paste(dp, "intercept"))
    # slopes get a wider prior than the blanket normal(0, 0.2) the other dpars
    # take: a condition difference in the start-point range is a real effect of
    # ordinary size, and the job here is to fence off zero, not to shrink it
    expect_equal(rows$prior[rows$class == "b"], "normal(0, 0.5)",
                 label = paste(dp, "slope"))
  }

  # a dpar omitted from bf() is declared on the natural scale instead, and needs
  # a prior that lives there
  f2 <- brms::bf(rt ~ 1, family = cogmod_lba1())
  p2 <- cogmod_priors(f2, d)
  expect_equal(p2$prior[p2$class == "sigmabias"], "lognormal(-0.7, 0.75)")
  expect_equal(p2$prior[p2$class == "boundary"], "lognormal(-0.7, 0.75)")

  # and brms accepts both without complaining that a row goes unused
  for (form in list(f, f2)) {
    expect_silent(
      brms::make_stancode(form, data = d, family = cogmod_lba1(),
                          prior = cogmod_priors(form, d),
                          stanvars = cogmod_lba1_stanvars())
    )
  }
})


test_that("a mixed vector of start-point ranges takes each branch it needs", {
  # .lba_ldens() switches to its Taylor branch below delta = 1e-4, so one
  # vectorised call can send some elements one way and the rest the other.
  # rtdists's lognormal and gamma LBAs have the same structure and, until
  # rtdists/rtdists#24, indexed one branch's parameters by the other branch's
  # mask - so a small A gave the right answer only when every A in the call
  # was small, and the tests, which swept one value at a time, never noticed.
  # The sweep above is the same shape; this is the check it lacks.
  A <- c(0, 1e-9, 1e-6, 1e-5, 0.2, 0.7)
  t <- c(0.45, 0.6, 0.9, 0.5, 0.7, 1.1)
  ndt <- c(0.2, 0.3, 0.1, 0.25, 0.2, 0.15)
  mixed <- dcogmod_lba1(t, drift = 3, sigma = 1, sigmabias = A, boundary = 0.5,
                        ndt = ndt, poutlier = 0.02)
  each <- vapply(seq_along(A), function(i) {
    dcogmod_lba1(t[i], drift = 3, sigma = 1, sigmabias = A[i], boundary = 0.5,
                 ndt = ndt[i], poutlier = 0.02)
  }, numeric(1))
  expect_identical(mixed, each)
  expect_true(all(is.finite(mixed) & mixed > 0))

  # The other half of the rtdists bug: the small branch forgot to subtract t0.
  # Without the outlier component the density is a pure shift in ndt.
  expect_equal(
    dcogmod_lba1(t + 0.1, drift = 3, sigma = 1, sigmabias = A, boundary = 0.5,
                 ndt = ndt + 0.1, poutlier = 0),
    dcogmod_lba1(t, drift = 3, sigma = 1, sigmabias = A, boundary = 0.5,
                 ndt = ndt, poutlier = 0),
    tolerance = 1e-12
  )
})

Try the cogmod package in your browser

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

cogmod documentation built on Nov. 28, 2026, 1:08 a.m.