tests/testthat/test-model_invgaussian.R

context("Inv-Gaussian (Shifted Wald)")

test_that("rcogmod_invgaussian matches theoretical moments", {
  n_samples <- 15000
  set.seed(123)
  drift_values <- c(0.5, 1, 3, 5)
  boundary_values <- c(0.1, 0.5, 1, 2)
  ndt_values <- c(0, 0.1, 0.3, 0.5) # Keep ndt
  tol_mean <- 0.05
  tol_sd_abs <- 0.05 # Base absolute tolerance
  tol_sd_rel <- 0.15 # Relaxed relative tolerance component to 15%

  for (drift in drift_values) {
    for (boundary in boundary_values) {
      for (ndt in ndt_values) { # Keep ndt
        label <- sprintf("params(drift=%.1f, boundary=%.1f, ndt=%.1f)", drift, boundary, ndt) # Keep ndt
        rts <- rcogmod_invgaussian(n_samples, drift = drift, boundary = boundary, ndt = ndt) # Keep ndt

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

        theo_mean <- boundary / drift + ndt # Keep ndt
        theo_var <- boundary / (drift^3)
        theo_sd <- sqrt(theo_var)
        emp_mean <- mean(rts)
        emp_sd <- sd(rts)

        expect_equal(emp_mean, theo_mean, tolerance = tol_mean,
                     label = paste(label, "- Mean: Empirical vs Theoretical"))

        # Use a combined absolute and relaxed relative tolerance for SD
        current_tol_sd <- max(tol_sd_abs, theo_sd * tol_sd_rel)
        expect_equal(emp_sd, theo_sd, tolerance = current_tol_sd,
                     label = paste(label, "- SD: Empirical vs Theoretical"))
      }
    }
  }
})

test_that("dcogmod_invgaussian integrates correctly", {
  n_samples_for_range <- 5000
  set.seed(456)
  tol_integration <- 1e-3 # Relaxed tolerance

  drift_values <- c(0.8, 2, 4)
  boundary_values <- c(0.2, 0.7, 1.5)
  ndt_values <- c(0.05, 0.2, 0.4)

  for (drift in drift_values) {
    for (boundary in boundary_values) {
      for (ndt in ndt_values) {
        label <- sprintf("params(drift=%.1f, boundary=%.1f, ndt=%.1f)", drift, boundary, ndt)
        integrand <- function(x_int) {
          dcogmod_invgaussian(x_int, drift = drift, boundary = boundary, ndt = ndt)
        }
        x_sample_range <- rcogmod_invgaussian(n_samples_for_range, drift = drift, boundary = boundary, ndt = ndt)
        # Ensure sample range is valid before calculating quantiles/sd
         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) # Increased range capture
        if (!is.finite(upper_limit) || upper_limit < ndt + 10) upper_limit <- ndt + 100

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

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


test_that("pcogmod_invgaussian matches rcogmod_invgaussian and has correct properties", {
  n_samples <- 20000 # More samples for better ECDF accuracy
  set.seed(789)
  tol_cdf <- 0.05 # Tolerance for comparing pcogmod_invgaussian to ECDF

  drift_values <- c(0.8, 3)
  boundary_values <- c(0.3, 1.0)
  ndt_values <- c(0.1, 0.4)

  for (drift in drift_values) {
    for (boundary in boundary_values) {
      for (ndt in ndt_values) {
        label <- sprintf("params(drift=%.1f, boundary=%.1f, ndt=%.1f)", drift, boundary, ndt)

        # Generate samples
        rts <- rcogmod_invgaussian(n_samples, drift = drift, boundary = boundary, ndt = ndt)
        if(any(is.na(rts))) {
            warning("NA values generated by rcogmod_invgaussian for ", label)
            next
        }

        # Calculate empirical CDF
        ecdf_rts <- stats::ecdf(rts)

        # Test points (quantiles from empirical distribution)
        test_quantiles <- quantile(rts, probs = c(0.01, 0.1, 0.25, 0.5, 0.75, 0.9, 0.99), na.rm = TRUE)
        # Add edge cases near ndt
        test_quantiles <- c(ndt + 1e-6, ndt + 0.01, test_quantiles)
        test_quantiles <- unique(test_quantiles[is.finite(test_quantiles) & test_quantiles > ndt])

        # 1. Compare pcogmod_invgaussian with empirical CDF
        p_values <- pcogmod_invgaussian(test_quantiles, drift = drift, boundary = boundary, ndt = ndt)
        ecdf_values <- ecdf_rts(test_quantiles)
        expect_equal(p_values, ecdf_values, tolerance = tol_cdf,
                     label = paste(label, "- CDF: pcogmod_invgaussian vs Empirical"))

        # 2. Check boundary conditions
        expect_equal(pcogmod_invgaussian(ndt, drift = drift, boundary = boundary, ndt = ndt), 0,
                     label = paste(label, "- CDF at ndt is 0"))
        expect_equal(pcogmod_invgaussian(ndt - 1e-6, drift = drift, boundary = boundary, ndt = ndt), 0,
                     label = paste(label, "- CDF below ndt is 0"))
        expect_equal(pcogmod_invgaussian(Inf, drift = drift, boundary = boundary, ndt = ndt), 1,
                     label = paste(label, "- CDF at Inf is 1"))

        # 3. Check lower.tail argument
        p_upper <- pcogmod_invgaussian(test_quantiles, drift = drift, boundary = boundary, ndt = ndt, lower.tail = FALSE)
        expect_equal(p_upper, 1 - p_values, tolerance = 1e-7,
                     label = paste(label, "- CDF lower.tail=FALSE"))

        # 4. Check log.p argument
        p_log <- pcogmod_invgaussian(test_quantiles, drift = drift, boundary = boundary, ndt = ndt, log.p = TRUE)
        # Avoid log(0) issues for comparison by filtering p_values > 0
        valid_idx <- p_values > 0
        expect_equal(p_log[valid_idx], log(p_values[valid_idx]), tolerance = 1e-7,
                     label = paste(label, "- CDF log.p=TRUE"))
        # Where the probability underflows to 0, the log-scale answer is not
        # -Inf but the actual log-probability: just above the shift the Wald CDF
        # is of order exp(-boundary^2 / (2 t)), and log.p = TRUE exists precisely
        # so that a number like -500 survives. Below the log of the smallest
        # double is the only thing to require of it.
        expect_true(all(p_log[!valid_idx] < log(.Machine$double.xmin)),
                    label = paste(label, "- CDF log.p=TRUE stays on the log scale for p=0"))

      }
    }
  }
})



test_that("the Wald density, CDF and survival agree with statmod", {
  # Everything else in this file holds the package to itself: R against Stan,
  # the CDF against the integrated density, the sampler against both. Those
  # catch the two implementations drifting apart, not an error they share.
  # statmod's inverse Gaussian (Giner & Smyth, 2016) is a separate lineage,
  # written on the log scale for the same reason ours is, and rtdists holds its
  # own Wald to it (rtdists/rtdists#26, #27). Its parameterisation is the
  # inverse Gaussian's: mean = boundary / drift, shape = boundary^2.
  skip_if_not_installed("statmod")

  g <- expand.grid(t = c(0.02, 0.05, 0.2, 0.5, 1, 2, 5, 20),
                   drift = c(0.1, 0.5, 1, 3, 8, 20),
                   boundary = c(0.1, 0.5, 1, 2, 5, 20))
  m <- g$boundary / g$drift
  s <- g$boundary^2

  # Density, natural and log scale. The log scale is compared where statmod's
  # own answer is finite: below about exp(-745) it has nothing to compare to.
  expect_equal(
    dcogmod_invgaussian(g$t, drift = g$drift, boundary = g$boundary, ndt = 0),
    statmod::dinvgauss(g$t, mean = m, shape = s),
    tolerance = 1e-12
  )
  ld <- dcogmod_invgaussian(g$t, drift = g$drift, boundary = g$boundary,
                            ndt = 0, log = TRUE)
  ref <- statmod::dinvgauss(g$t, mean = m, shape = s, log = TRUE)
  ok <- is.finite(ref)
  expect_true(all(abs(ld[ok] - ref[ok]) <= 1e-11 * pmax(1, abs(ref[ok]))))

  # CDF and survival, both tails, both scales. On the log scale a survival of
  # -600 is an ordinary number for both implementations, so it is compared as
  # one rather than through exp().
  expect_equal(
    pcogmod_invgaussian(g$t, drift = g$drift, boundary = g$boundary, ndt = 0),
    statmod::pinvgauss(g$t, mean = m, shape = s),
    tolerance = 1e-14
  )
  for (lower in c(TRUE, FALSE)) {
    lp <- pcogmod_invgaussian(g$t, drift = g$drift, boundary = g$boundary,
                              ndt = 0, lower.tail = lower, log.p = TRUE)
    ref <- statmod::pinvgauss(g$t, mean = m, shape = s, lower.tail = lower,
                              log.p = TRUE)
    ok <- is.finite(ref) & ref > -700
    expect_true(all(abs(lp[ok] - ref[ok]) <= 1e-10 * pmax(1, abs(ref[ok]))),
                info = sprintf("lower.tail = %s", lower))
  }

  # The regime rtdists/rtdists#27 was about: 2 * boundary * drift = 800 here,
  # so exp(2 a v) overflows and Phi(-(a + v t) / sqrt(t)) underflows, and the
  # CDF is only right if their product is kept as one exponent. A natural-scale
  # `exp(2 a v) * Phi(.)` - or `log(Phi(.))` inside the exponent, which is
  # what rtdists had - loses the whole second term.
  t <- c(0.9, 0.99, 1, 1.05, 1.2)
  expect_equal(pcogmod_invgaussian(t, drift = 20, boundary = 20, ndt = 0),
               statmod::pinvgauss(t, mean = 1, shape = 400),
               tolerance = 1e-12)
  expect_equal(pcogmod_invgaussian(Inf, drift = 20, boundary = 20, ndt = 0), 1)

  # ndt is a shift and nothing else.
  expect_equal(
    pcogmod_invgaussian(g$t + 0.25, drift = g$drift, boundary = g$boundary,
                        ndt = 0.25),
    statmod::pinvgauss(g$t, mean = m, shape = s),
    tolerance = 1e-14
  )
})


context("Inv-Gaussian (Shifted Wald) - brms")



test_that("Shifted Wald model can recover parameters with brms", {
  skip_if_not_slow()

  skip_if_not_installed("brms")
  skip_if_not_installed("cmdstanr")

  set.seed(555)
  n_obs <- 400

  # True parameters
  true_mu <- 2.5
  true_boundary <- 0.8
  true_ndt <- 0.16
  true_poutlier <- 0.03

  # Simulate data
  df <- data.frame(rt = rcogmod_invgaussian(n_obs, drift = true_mu, boundary = true_boundary,
                                        ndt = true_ndt,
                                        poutlier = true_poutlier))

  # ndt is estimated directly now, on a log link, alongside poutlier
  f <- brms::bf(rt ~ 1, boundary ~ 1, ndt ~ 1, poutlier ~ 1,
                family = cogmod_invgaussian())

  fit <- brms::brm(f,
              data = df,
              prior = cogmod_priors(f, df),
              stanvars = cogmod_invgaussian_stanvars(),
              backend = "cmdstanr",
              algorithm = "pathfinder", # VI
              refresh = 0)

  fixed_effects <- summary(fit)$fixed

  # Intercepts are on their link scales: softplus for mu/boundary, log for ndt
  expect_equal(log1p(exp(fixed_effects["Intercept", "Estimate"])), true_mu,
               tolerance = 0.3, label = "mu recovery")
  expect_equal(log1p(exp(fixed_effects["boundary_Intercept", "Estimate"])), true_boundary,
               tolerance = 0.5, label = "boundary recovery")
  expect_equal(exp(fixed_effects["ndt_Intercept", "Estimate"]), true_ndt,
               tolerance = 0.1, label = "ndt recovery")
})


test_that("Stan cogmod_invgaussian_lpdf matches R dcogmod_invgaussian function", {
  skip_if_not_installed("cmdstanr")

  cogmod_invgaussian_lpdf <- stan_fun("cogmod_invgaussian")

  mu_values <- c(1.0, 3.0, 5.0)
  boundary_values <- c(0.3, 0.8, 1.5)
  # 0 is the plain-Wald branch of the Stan function; the rest go through the
  # drift-variability one, including a value small enough to be within rounding
  # distance of the branch it does not take.
  sigmadrift_values <- c(0, 0.05, 0.5, 2.0)
  ndt_values <- c(0, 0.1, 0.25)
  pout_values <- c(0, 0.03, 0.4)
  y_offsets <- c(0.05, 0.2, 1.0)

  for (mu_val in mu_values) {
    for (boundary in boundary_values) {
      for (sigmadrift in sigmadrift_values) {
        for (ndt_val in ndt_values) {
          for (pout in pout_values) {
            for (y_offset in y_offsets) {
              y_val <- ndt_val + y_offset

              label <- sprintf(
                paste("mu=%.1f, boundary=%.1f, sigmadrift=%.2f, ndt=%.2f,",
                      "poutlier=%.2f, Y=%.3f"),
                mu_val, boundary, sigmadrift, ndt_val, pout, y_val)

              r_loglik <- dcogmod_invgaussian(y_val, drift = mu_val, boundary = boundary,
                                          ndt = ndt_val, sigmadrift = sigmadrift,
                                          poutlier = pout, log = TRUE)
              stan_loglik <- cogmod_invgaussian_lpdf(Y = y_val, mu = mu_val, boundary = boundary,
                                                 sigmadrift = sigmadrift, sigmandt = 0,
                                                 ndt = ndt_val, poutlier = pout)
              expect_equal(stan_loglik, r_loglik, tolerance = 1e-8, label = label)
            }
          }
        }
      }
    }
  }

  mu_val <- 3.0
  alpha_val <- 0.5
  ndt_val <- 0.2

  # Below ndt: with no outlier component the response is impossible...
  y_below <- 0.15
  expect_equal(
    cogmod_invgaussian_lpdf(Y = y_below, mu = mu_val, boundary = alpha_val,
                        sigmadrift = 0, sigmandt = 0, ndt = ndt_val, poutlier = 0),
    -Inf, label = "Y < ndt, poutlier = 0")

  # ...but with one it keeps positive density, which is the whole point
  lp <- cogmod_invgaussian_lpdf(Y = y_below, mu = mu_val, boundary = alpha_val,
                            sigmadrift = 0, sigmandt = 0, ndt = ndt_val, poutlier = 0.02)
  expect_true(is.finite(lp))
  expect_equal(lp, dcogmod_invgaussian(y_below, drift = mu_val, boundary = alpha_val,
                                   ndt = ndt_val, poutlier = 0.02, log = TRUE),
               tolerance = 1e-10, label = "Y < ndt, poutlier > 0")

  # Y exactly at ndt behaves the same way
  expect_equal(
    cogmod_invgaussian_lpdf(Y = ndt_val, mu = mu_val, boundary = alpha_val,
                        sigmadrift = 0, sigmandt = 0, ndt = ndt_val, poutlier = 0),
    -Inf, label = "Y == ndt")

  # Invalid parameters
  expect_equal(cogmod_invgaussian_lpdf(Y = 0.3, mu = -1.0, boundary = alpha_val,
                                   sigmadrift = 0, sigmandt = 0, ndt = ndt_val, poutlier = 0.02), -Inf)
  expect_equal(cogmod_invgaussian_lpdf(Y = 0.3, mu = mu_val, boundary = 0.0,
                                   sigmadrift = 0, sigmandt = 0, ndt = ndt_val, poutlier = 0.02), -Inf)
  expect_equal(cogmod_invgaussian_lpdf(Y = 0.3, mu = mu_val, boundary = alpha_val,
                                   sigmadrift = -1, sigmandt = 0, ndt = ndt_val, poutlier = 0.02), -Inf)
  expect_equal(cogmod_invgaussian_lpdf(Y = 0.3, mu = mu_val, boundary = alpha_val,
                                   sigmadrift = 0, sigmandt = -0.1, ndt = ndt_val, poutlier = 0.02), -Inf)
  expect_equal(cogmod_invgaussian_lpdf(Y = 0.3, mu = mu_val, boundary = alpha_val,
                                   sigmadrift = 0, sigmandt = 0, ndt = -0.1, poutlier = 0.02), -Inf)
  expect_equal(cogmod_invgaussian_lpdf(Y = 0.3, mu = mu_val, boundary = alpha_val,
                                   sigmadrift = 0, sigmandt = 0, ndt = ndt_val, poutlier = 1.1), -Inf)

  # ndt = 0 is now an ordinary interior value, not a boundary
  expect_equal(
    cogmod_invgaussian_lpdf(Y = 0.1, mu = mu_val, boundary = alpha_val,
                        sigmadrift = 0, sigmandt = 0, ndt = 0, poutlier = 0),
    dcogmod_invgaussian(0.1, drift = mu_val, boundary = alpha_val, ndt = 0, log = TRUE),
    tolerance = 1e-8, label = "ndt = 0")
})


context("Inv-Gaussian (Shifted Wald) - across-trial drift variability")

test_that("sigmadrift = 0 is exactly the fixed-drift Wald", {
  # Not "close to": the D = 1 + sigmadrift^2 * t factor and the two normal CDFs
  # of the truncation have to cancel outright, or the default model would have
  # silently changed.
  t <- c(0.02, 0.1, 0.3, 1, 3, 10)
  for (drift in c(0.8, 3, 6)) {
    for (boundary in c(0.2, 0.7, 2)) {
      ig_mu <- boundary / drift
      lambda <- boundary^2
      wald <- 0.5 * (log(lambda) - log(2 * pi) - 3 * log(t)) -
        lambda * (t - ig_mu)^2 / (2 * ig_mu^2 * t)
      expect_equal(
        dcogmod_invgaussian(t + 0.2, drift = drift, boundary = boundary,
                            ndt = 0.2, sigmadrift = 0, log = TRUE),
        wald, tolerance = 1e-12,
        label = sprintf("drift=%.1f, boundary=%.1f", drift, boundary))
    }
  }

  # And it is the default, so leaving sigmadrift out has to give the same thing
  expect_identical(
    dcogmod_invgaussian(c(0.3, 0.5, 1), drift = 3, boundary = 0.5, ndt = 0.2),
    dcogmod_invgaussian(c(0.3, 0.5, 1), drift = 3, boundary = 0.5, ndt = 0.2,
                        sigmadrift = 0))
})


test_that("sigmadrift is continuous into zero", {
  # The Stan and R densities both branch at sigmadrift == 0, so the two sides of
  # the branch have to meet. They do, linearly in sigmadrift^2.
  t <- c(0.05, 0.2, 0.8, 3)
  ref <- dcogmod_invgaussian(t + 0.2, drift = 3, boundary = 0.5, ndt = 0.2,
                             sigmadrift = 0, log = TRUE)
  prev <- Inf
  for (s in c(1e-2, 1e-4, 1e-6, 1e-8)) {
    gap <- max(abs(dcogmod_invgaussian(t + 0.2, drift = 3, boundary = 0.5,
                                       ndt = 0.2, sigmadrift = s,
                                       log = TRUE) - ref))
    expect_lt(gap, prev)
    prev <- gap
  }
  expect_lt(prev, 1e-10)
})


test_that("dcogmod_invgaussian integrates to 1 with a variable drift", {
  # The truncation at zero is what makes this hold: with an untruncated Normal
  # drift the mass would leak away with sigmadrift, since a negative drift never
  # reaches the boundary at all.
  for (drift in c(0.5, 3)) {
    for (boundary in c(0.3, 1.5)) {
      for (sigmadrift in c(0.1, 0.8, 2, 4)) {
        label <- sprintf("drift=%.1f, boundary=%.1f, sigmadrift=%.1f",
                         drift, boundary, sigmadrift)
        integral <- stats::integrate(
          function(x) {
            dcogmod_invgaussian(x, drift = drift, boundary = boundary,
                                ndt = 0.2, sigmadrift = sigmadrift)
          },
          lower = 0, upper = Inf, rel.tol = 1e-9)$value
        expect_equal(integral, 1, tolerance = 1e-6, label = label)
      }
    }
  }
})


test_that("pcogmod_invgaussian matches the integrated density with a variable drift", {
  # The CDF is quadrature over the drift rather than a closed form (see
  # .pwald_raw), so it is worth checking against the density it belongs to
  # rather than only against an ECDF.
  q <- c(0.21, 0.25, 0.4, 0.7, 1.5, 4, 12)
  for (drift in c(0.5, 3)) {
    for (boundary in c(0.3, 1.5)) {
      for (sigmadrift in c(0.05, 0.8, 3)) {
        label <- sprintf("drift=%.1f, boundary=%.1f, sigmadrift=%.2f",
                         drift, boundary, sigmadrift)
        cdf <- pcogmod_invgaussian(q, drift = drift, boundary = boundary,
                                   ndt = 0.2, sigmadrift = sigmadrift)
        ref <- vapply(q, function(u) {
          stats::integrate(function(x) {
            dcogmod_invgaussian(x, drift = drift, boundary = boundary,
                                ndt = 0.2, sigmadrift = sigmadrift)
          }, lower = 0, upper = u, rel.tol = 1e-10)$value
        }, numeric(1))
        expect_equal(cdf, ref, tolerance = 1e-8, label = label)

        expect_equal(
          pcogmod_invgaussian(Inf, drift = drift, boundary = boundary,
                              ndt = 0.2, sigmadrift = sigmadrift),
          1, tolerance = 1e-10, label = paste(label, "- CDF at Inf"))
      }
    }
  }
})


test_that("rcogmod_invgaussian follows the variable-drift density", {
  set.seed(2024)
  n <- 50000
  for (sigmadrift in c(0.3, 1, 2.5)) {
    rts <- rcogmod_invgaussian(n, drift = 3, boundary = 0.5, ndt = 0.2,
                               sigmadrift = sigmadrift)
    probs <- c(0.05, 0.25, 0.5, 0.75, 0.9)
    emp <- stats::quantile(rts, probs)
    # The quantiles the CDF says those probabilities sit at, found by bisection
    theo <- vapply(probs, function(p) {
      stats::uniroot(function(x) {
        pcogmod_invgaussian(x, drift = 3, boundary = 0.5, ndt = 0.2,
                            sigmadrift = sigmadrift) - p
      }, interval = c(0.2 + 1e-9, 1e4), tol = 1e-10)$root
    }, numeric(1))
    expect_equal(unname(emp), theo, tolerance = 0.02,
                 label = sprintf("sigmadrift=%.1f - quantiles", sigmadrift))
  }

  # A longer right tail is the whole point of the parameter
  set.seed(11)
  fixed <- rcogmod_invgaussian(n, drift = 3, boundary = 0.5, ndt = 0.2)
  varied <- rcogmod_invgaussian(n, drift = 3, boundary = 0.5, ndt = 0.2,
                                sigmadrift = 1)
  expect_gt(stats::quantile(varied, 0.99), stats::quantile(fixed, 0.99))
})


test_that("a zero drift SD is legal but a negative one is not", {
  expect_silent(dcogmod_invgaussian(0.5, ndt = 0.2, sigmadrift = 0))
  expect_silent(rcogmod_invgaussian(5, ndt = 0.2, sigmadrift = 0))
  # d*() downgrades the error to a warning and returns zero density
  expect_warning(d <- dcogmod_invgaussian(0.5, ndt = 0.2, sigmadrift = -0.1))
  expect_equal(d, 0)
  expect_error(rcogmod_invgaussian(5, ndt = 0.2, sigmadrift = -0.1),
               "at least 0")
  # the drift and the threshold keep their open bounds
  expect_error(rcogmod_invgaussian(5, drift = 0, ndt = 0.2), "greater than 0")
  expect_error(rcogmod_invgaussian(5, boundary = 0, ndt = 0.2), "greater than 0")
})


test_that("the family carries sigmadrift and it can be fixed in the formula", {
  fam <- cogmod_invgaussian()
  expect_equal(fam$dpars,
               c("mu", "boundary", "sigmadrift", "sigmandt", "ndt", "poutlier"))
  expect_equal(fam$lb$sigmadrift, "0")
  expect_equal(fam$link_sigmadrift, "softplus")

  skip_if_not_installed("brms")
  d <- data.frame(RT = rcogmod_invgaussian(100, ndt = 0.2, poutlier = 0.02))

  # Left out of bf(), it is estimated, and cogmod_priors() has to fence it: a
  # softplus link reaches zero only at minus infinity, so a flat prior there is
  # an improper posterior.
  f_free <- brms::bf(RT ~ 1, boundary ~ 1, ndt ~ 1, poutlier ~ 1,
                     family = cogmod_invgaussian())
  pr <- cogmod_priors(f_free, d)
  expect_true(any(pr$class == "sigmadrift" & nzchar(pr$prior)))

  # Fixed at zero, it is not a parameter at all and needs no prior
  f_fixed <- brms::bf(RT ~ 1, boundary ~ 1, sigmadrift = 0, ndt ~ 1,
                      poutlier ~ 1, family = cogmod_invgaussian())
  expect_false(any(cogmod_priors(f_fixed, d)$dpar == "sigmadrift"))

  # `boundary` is identified, but brms would leave it flat - an improper
  # prior on a softplus link - so it is filled in both forms
  raw <- brms::get_prior(f_free, d, family = cogmod_invgaussian())
  expect_true(all(!nzchar(raw$prior[raw$dpar == "boundary"])))
  expect_equal(pr$prior[pr$class == "Intercept" & pr$dpar == "boundary"],
               "normal(0.5, 1)")
  p_omit <- cogmod_priors(brms::bf(RT ~ 1, sigmadrift = 0, sigmandt = 0,
                                   family = cogmod_invgaussian()), d)
  expect_equal(p_omit$prior[p_omit$class == "boundary"], "lognormal(0, 0.6)")
})


test_that("Shifted Wald with drift variability recovers its parameters", {
  skip_if_not_slow()

  skip_if_not_installed("brms")
  skip_if_not_installed("cmdstanr")

  set.seed(555)
  true_mu <- 2.5
  true_boundary <- 0.8
  true_sigmadrift <- 0.9
  true_ndt <- 0.16
  true_poutlier <- 0.03

  df <- data.frame(rt = rcogmod_invgaussian(1500, drift = true_mu,
                                            boundary = true_boundary,
                                            ndt = true_ndt,
                                            sigmadrift = true_sigmadrift,
                                            poutlier = true_poutlier))

  f <- brms::bf(rt ~ 1, boundary ~ 1, sigmadrift ~ 1, ndt ~ 1, poutlier ~ 1,
                family = cogmod_invgaussian())

  # Sampled rather than approximated: sigmadrift is the parameter this test is
  # about, and it is the one a variational fit is least likely to pin down.
  fit <- brms::brm(f,
              data = df,
              prior = cogmod_priors(f, df),
              init = cogmod_inits(f, df),
              stanvars = cogmod_invgaussian_stanvars(),
              backend = "cmdstanr",
              chains = 2, iter = 1000, refresh = 0, seed = 1)

  fixed_effects <- summary(fit)$fixed

  expect_equal(log1p(exp(fixed_effects["Intercept", "Estimate"])), true_mu,
               tolerance = 0.4, label = "mu recovery")
  expect_equal(log1p(exp(fixed_effects["boundary_Intercept", "Estimate"])),
               true_boundary, tolerance = 0.3, label = "boundary recovery")
  expect_equal(log1p(exp(fixed_effects["sigmadrift_Intercept", "Estimate"])),
               true_sigmadrift, tolerance = 0.4, label = "sigmadrift recovery")
  expect_equal(exp(fixed_effects["ndt_Intercept", "Estimate"]), true_ndt,
               tolerance = 0.05, label = "ndt recovery")

  # posterior_epred() has nothing to return here, but the other two methods do
  expect_true(all(is.finite(brms::posterior_predict(fit, ndraws = 20))))
  expect_true(all(is.infinite(brms::posterior_epred(fit, ndraws = 5))))
})


test_that("posterior_epred has no mean to return once the drift varies", {
  # E[T] diverges for sigmadrift > 0: the density decays as t^-2, because a
  # drift arbitrarily close to zero takes arbitrarily long.
  spec <- cogmod:::.shifted_spec("cogmod_invgaussian")
  expect_equal(spec$mean(list(mu = 3, boundary = 0.5, sigmadrift = 0, sigmandt = 0)),
               0.5 / 3)
  expect_equal(spec$mean(list(mu = 3, boundary = 0.5, sigmadrift = 0.01, sigmandt = 0)),
               Inf)

  # and the tail really is t^-2, so the constant below settles rather than the
  # density decaying faster. Its limit is
  # boundary * exp(-mu^2 / (2 sigmadrift^2)) / (2 sigmadrift sqrt(2 pi) Phi(mu / sigmadrift)),
  # the 1/2 being what the truncation's numerator tends to as t grows.
  t <- 10^(5:8)
  const <- exp(cogmod:::.dwald_raw(t, 3, 0.5, 0.5)) * t^2
  expect_equal(const[4], const[3], tolerance = 0.01)
  expect_equal(const[4],
               0.5 * exp(-3^2 / (2 * 0.5^2)) /
                 (2 * 0.5 * sqrt(2 * pi) * stats::pnorm(3 / 0.5)),
               tolerance = 0.01)
})


# sigmandt: a non-decision time spread over a range ------------------------

test_that("sigmandt = 0 changes nothing, to the bit", {
  # The parameter is routed around for exactly the elements with a positive
  # range, so a zero range - the default, and what every pre-existing formula
  # fixes - returns what the family returned before the parameter existed.
  t <- c(0.21, 0.3, 0.5, 1, 3)
  for (sv in c(0, 0.8)) {
    expect_identical(
      dcogmod_invgaussian(t, 3, 0.5, 0.2, sigmadrift = sv, sigmandt = 0, log = TRUE),
      dcogmod_invgaussian(t, 3, 0.5, 0.2, sigmadrift = sv, log = TRUE)
    )
    for (lower in c(TRUE, FALSE)) {
      expect_identical(
        pcogmod_invgaussian(t, 3, 0.5, 0.2, sigmadrift = sv, sigmandt = 0,
                            lower.tail = lower, log.p = TRUE),
        pcogmod_invgaussian(t, 3, 0.5, 0.2, sigmadrift = sv,
                            lower.tail = lower, log.p = TRUE)
      )
    }
  }
  # Including the random stream: the uniform offset is drawn only when some
  # trial has a range.
  set.seed(1); a <- rcogmod_invgaussian(50, sigmandt = 0)
  set.seed(1); b <- rcogmod_invgaussian(50)
  expect_identical(a, b)
  # And in a mixed vector the zero-range elements are still the closed form.
  st0 <- c(0, 0.05, 0, 0.1, 0)
  expect_identical(
    dcogmod_invgaussian(t, sigmandt = st0, log = TRUE)[st0 == 0],
    dcogmod_invgaussian(t, log = TRUE)[st0 == 0]
  )
})


test_that("the smeared Wald is the fixed-shift one averaged over the range", {
  # Brute force: (1 / st0) * INT_0^st0 f(y | ndt + u) du, at times that put the
  # interval [y - ndt - st0, y - ndt] entirely above the shift and straddling
  # it, with and without the drift quadrature underneath.
  for (sv in c(0, 0.7)) {
    for (st0 in c(0.03, 0.15)) {
      y <- 0.2 + c(0.005, 0.02, st0 * 0.9, st0 * 1.1, 0.2, 0.6, 1.5, 3)
      info <- sprintf("sigmadrift %.1f sigmandt %.2f", sv, st0)
      ref <- vapply(y, function(yy) {
        stats::integrate(function(u) {
          dcogmod_invgaussian(yy, 3, 0.5, 0.2 + u, sigmadrift = sv)
        }, 0, st0, rel.tol = 1e-12)$value / st0
      }, numeric(1))
      got <- dcogmod_invgaussian(y, 3, 0.5, 0.2, sigmadrift = sv, sigmandt = st0)
      expect_equal(got, ref, tolerance = 1e-8, info = info)

      # The CDF integrates that density and the survival completes it - the
      # survival computed AS a survival, since that is what cens() scores.
      dens <- function(s) dcogmod_invgaussian(s, 3, 0.5, 0.2, sigmadrift = sv,
                                              sigmandt = st0)
      cdf <- vapply(y, function(yy) {
        stats::integrate(dens, 0, yy, rel.tol = 1e-12)$value
      }, numeric(1))
      surv <- vapply(y, function(yy) {
        stats::integrate(dens, yy, Inf, rel.tol = 1e-12)$value
      }, numeric(1))
      pF <- pcogmod_invgaussian(y, 3, 0.5, 0.2, sigmadrift = sv, sigmandt = st0)
      pS <- pcogmod_invgaussian(y, 3, 0.5, 0.2, sigmadrift = sv, sigmandt = st0,
                                lower.tail = FALSE)
      expect_equal(pF, cdf, tolerance = 1e-10, info = info)
      expect_equal(pS / surv, rep(1, length(y)), tolerance = 1e-8, info = info)
      expect_equal(pF + pS, rep(1, length(y)), tolerance = 1e-12, info = info)
    }
  }
})


test_that("the integrated Wald CDF and survival are the ones written down", {
  # I(t) = INT_0^t F and R(t) = INT_t^Inf S, each checked against adaptive
  # integration of the fixed-drift CDF and survival they integrate. These two
  # are what make the smeared CDF closed form.
  Fw <- function(s) exp(cogmod:::.log_pwald_fixed(s, 3, 0.5))
  Sw <- function(s) exp(cogmod:::.lswald_fixed(s, 3, 0.5))
  for (t in c(0.05, 0.1, 0.2, 0.5, 1, 3)) {
    expect_equal(exp(cogmod:::.lwald_liF_fixed(t, 3, 0.5)),
                 stats::integrate(Fw, 0, t, rel.tol = 1e-12)$value,
                 tolerance = 1e-10, info = t)
    expect_equal(exp(cogmod:::.lwald_liS_fixed(t, 3, 0.5)),
                 stats::integrate(Sw, t, Inf, rel.tol = 1e-12)$value,
                 tolerance = 1e-10, info = t)
  }
  # R(0) is the mean, and below the shift the survival is 1.
  expect_equal(exp(cogmod:::.lwald_liS_fixed(1e-300, 3, 0.5)), 0.5 / 3,
               tolerance = 1e-8)
})


test_that("the smeared density is continuous across its branches and into zero", {
  # The kernel has a midpoint branch below st0 / t = 1e-5, where the difference
  # quotient has lost its digits, and a tail choice at F(midpoint) = 1/2. A log
  # link never reaches zero, so the sampler visits small ranges routinely and
  # the branches have to meet.
  t <- c(0.21, 0.3, 1, 3)
  for (what in c("dens", "cdf", "surv")) {
    f <- function(st0) cogmod:::.lwald_raw(t, 3, 0.5, 0, st0, what)
    base <- f(0)
    prev <- Inf
    for (st0 in c(1e-3, 1e-5, 1e-7, 1e-9)) {
      gap <- max(abs(f(rep(st0, 4)) - base))
      expect_lt(gap, prev, label = sprintf("%s sigmandt = %g", what, st0))
      prev <- gap
    }
    expect_lt(prev, 1e-7)
    # Either side of the switch.
    above <- f(1e-5 * t * (1 + 1e-6))
    below <- f(1e-5 * t * (1 - 1e-6))
    expect_lt(max(abs(above - below)), 1e-7, label = what)
  }
  # And across the tail choice: a range wide enough that the midpoint's CDF
  # passes 1/2 somewhere inside a fine grid of times.
  y <- seq(0.25, 1.2, by = 0.0005)
  ld <- dcogmod_invgaussian(y, 3, 0.5, 0.2, sigmandt = 0.1, log = TRUE)
  expect_true(all(is.finite(ld)))
  expect_lt(max(abs(diff(ld, differences = 2))), 1e-3)
})


test_that("the smeared Wald stays on the log scale at both ends", {
  # Just above the shift the CDF is of order exp(-boundary^2 / (2 t)); far out
  # the survival is exp(-drift^2 t / 2). Both have to come back as numbers,
  # not as -Inf or NaN, with a range as without one.
  lF <- pcogmod_invgaussian(0.2 + c(1e-4, 1e-6), 3, 0.5, 0.2, sigmandt = 0.05,
                            log.p = TRUE)
  expect_true(all(is.finite(lF) & lF < -1000))
  lS <- pcogmod_invgaussian(c(3, 6, 20), 3, 0.5, 0.2, sigmandt = 0.05,
                            lower.tail = FALSE, log.p = TRUE)
  expect_true(all(is.finite(lS)) && all(diff(lS) < 0))
  # Roughly the fixed-shift decay rate.
  expect_equal((lS[3] - lS[2]) / 14, -3^2 / 2, tolerance = 0.05)
  ld <- dcogmod_invgaussian(c(0.2001, 20), 3, 0.5, 0.2, sigmandt = 0.05,
                            log = TRUE)
  expect_true(all(is.finite(ld)))
})


test_that("a mixed vector of ranges and drift SDs takes each branch it needs", {
  # Zero and positive ranges, fixed and variable drifts, in one call: four
  # code paths, each subsetting by its own mask.
  st0 <- c(0, 0.05, 1e-8, 0.1, 0)
  sv <- c(0, 0, 0.5, 0.5, 0.5)
  t <- c(0.25, 0.4, 0.6, 0.9, 2)
  each <- function(f, ...) {
    vapply(1:5, function(i) f(t[i], 3, 0.5, 0.2, sv[i], st0[i], ...), numeric(1))
  }
  expect_identical(dcogmod_invgaussian(t, 3, 0.5, 0.2, sv, st0, log = TRUE),
                   each(dcogmod_invgaussian, log = TRUE))
  expect_identical(pcogmod_invgaussian(t, 3, 0.5, 0.2, sv, st0, log.p = TRUE),
                   each(pcogmod_invgaussian, log.p = TRUE))
  expect_identical(
    pcogmod_invgaussian(t, 3, 0.5, 0.2, sv, st0, lower.tail = FALSE, log.p = TRUE),
    each(pcogmod_invgaussian, lower.tail = FALSE, log.p = TRUE)
  )
})


test_that("rcogmod_invgaussian spreads the non-decision time over the range", {
  set.seed(3)
  r <- rcogmod_invgaussian(2e5, 3, 0.5, 0.2, sigmandt = 0.1, poutlier = 0)
  expect_gte(min(r), 0.2)
  # E[RT] = ndt + boundary / drift + sigmandt / 2
  expect_equal(mean(r), 0.2 + 0.5 / 3 + 0.05, tolerance = 0.01)
  qs <- quantile(r, c(0.01, 0.1, 0.5, 0.9, 0.99))
  expect_equal(unname(ecdf(r)(qs)),
               pcogmod_invgaussian(unname(qs), 3, 0.5, 0.2, sigmandt = 0.1),
               tolerance = 0.005)
  # A negative range is rejected like every other bad parameter.
  expect_warning(expect_equal(dcogmod_invgaussian(0.5, sigmandt = -0.1), 0),
                 "sigmandt")
  expect_error(rcogmod_invgaussian(5, sigmandt = -0.1), "sigmandt")
})


test_that("the family carries sigmandt on a log link with the DDM's prior", {
  fam <- cogmod_invgaussian()
  expect_equal(fam$link_sigmandt, "log")
  expect_equal(fam$lb$sigmandt, "0")
  spec <- cogmod:::.shifted_spec("cogmod_invgaussian")
  expect_equal(spec$mean(list(mu = 3, boundary = 0.5, sigmadrift = 0, sigmandt = 0.1)),
               0.5 / 3 + 0.05)
  expect_equal(spec$mean(list(mu = 3, boundary = 0.5, sigmadrift = 0.1, sigmandt = 0.1)),
               Inf)

  skip_if_not_installed("brms")
  d <- data.frame(RT = rcogmod_invgaussian(100, ndt = 0.2, poutlier = 0.02))
  # Omitted: estimated on the natural scale, and fenced with the DDM's prior.
  f_free <- brms::bf(RT ~ 1, boundary ~ 1, sigmadrift = 0, ndt ~ 1,
                     poutlier ~ 1, family = cogmod_invgaussian())
  pr <- as.data.frame(cogmod_priors(f_free, d))
  expect_equal(pr$prior[pr$class == "sigmandt"], "lognormal(-3, 1)")
  # Modelled: on the link scale.
  f_mod <- brms::bf(RT ~ 1, boundary ~ 1, sigmadrift = 0, sigmandt ~ 1,
                    ndt ~ 1, poutlier ~ 1, family = cogmod_invgaussian())
  pr <- as.data.frame(cogmod_priors(f_mod, d))
  expect_equal(pr$prior[pr$dpar == "sigmandt" & pr$class == "Intercept"],
               "normal(-3, 1)")
  # Fixed: gone.
  f_fixed <- brms::bf(RT ~ 1, boundary ~ 1, sigmadrift = 0, sigmandt = 0,
                      ndt ~ 1, poutlier ~ 1, family = cogmod_invgaussian())
  expect_false(any(as.data.frame(cogmod_priors(f_fixed, d))$dpar == "sigmandt"))
  # Inits follow the same two forms.
  expect_equal(cogmod_inits(f_free, d)()$sigmandt, 0.05, tolerance = 0.3)
  expect_equal(exp(cogmod_inits(f_mod, d)()$Intercept_sigmandt), 0.05,
               tolerance = 0.3)
})


test_that("the smeared Wald agrees with rtdists's st0, where rtdists has one", {
  # rtdists/rtdists#26 gives its shifted Wald a closed-form st0 at A = 0, the
  # same model under the same convention (t0 the lower bound). Until it merges
  # and ships, the installed rtdists has no dwald() with an st0 argument.
  skip_if_not_installed("rtdists")
  dw <- tryCatch(get("dwald", envir = asNamespace("rtdists")),
                 error = function(e) NULL)
  skip_if(is.null(dw) || !"st0" %in% names(formals(dw)),
          "installed rtdists has no st0 for the Wald")
  rt <- seq(0.22, 1.5, length.out = 20)
  expect_equal(
    dcogmod_invgaussian(rt, 3, 0.5, 0.2, sigmandt = 0.1),
    dw(rt, A = 0, b = 0.5, t0 = 0.2, v = 3, st0 = 0.1),
    tolerance = 1e-8
  )
})

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.