R/model_ddm.R

Defines functions posterior_epred_cogmod_ddm posterior_predict_cogmod_ddm log_lik_cogmod_ddm cogmod_ddm_stanvars cogmod_ddm_lpdf_expose .cogmod_ddm_lpdf .ddm_rng .ddm_fpt_rng .ddm_solve_series .ddm_cdf_lower .ddm_series .ddm_tmin .ddm_nterms .ddm_tfloor .ddm_plower .ddm_ldens .cogmod_ddm_to_rtdists .ddm_ldens_var .ddm_lfpt_resp .ddm_lfpt .ddm_lfpt0 .ddm_fpt_kl .ddm_fpt_ks .gauss_legendre .cogmod_ddm_draw_trialwise .cogmod_ddm_has_variability cogmod_ddm pcogmod_ddm dcogmod_ddm rcogmod_ddm

Documented in cogmod_ddm cogmod_ddm_lpdf_expose cogmod_ddm_stanvars dcogmod_ddm log_lik_cogmod_ddm pcogmod_ddm posterior_epred_cogmod_ddm posterior_predict_cogmod_ddm rcogmod_ddm

#' @title Drift Diffusion Model (DDM)
#'
#' @description
#' The Drift Diffusion Model (DDM) describes a two-choice decision as noisy
#' evidence accumulating between two boundaries until one of them is reached.
#' The boundary reached is the choice and the time taken is the decision time.
#' The observed RT is that decision time shifted by a non-decision time `ndt`,
#' and a fixed proportion `poutlier` of responses is generated by an outlier
#' process instead of by the diffusion.
#'
#' Functions:
#' - `rcogmod_ddm()`: Simulates random draws from the DDM.
#' - `dcogmod_ddm()`: Computes the density (likelihood).
#' - `pcogmod_ddm()`: Computes the cumulative distribution function.
#' - `cogmod_ddm()`: Creates a `brms::custom_family()` for use in `brms` models.
#' - `cogmod_ddm_stanvars()`: Generates the `stanvars` to pass to `brm()`.
#' - `p_outlier()`: Per-trial posterior probability of being an outlier.
#'
#' @details
#' # Response coding
#'
#' The response coded `1` (`response` here, `dec()` in a `brms` formula) is the
#' **upper** boundary and the response coded `0` is the **lower** one, following
#' `brms`'s own `wiener()` family. Two consequences are worth keeping in mind
#' when reading a fitted model:
#'
#' * `bias` is measured *from the lower boundary*, so `bias > 0.5` places the
#'   starting point closer to the response coded `1`, and `bias < 0.5` closer to
#'   the response coded `0`. Since first-passage times are shorter for the nearer
#'   boundary, `bias > 0.5` makes responses coded `1` *faster* than responses
#'   coded `0`, and `bias < 0.5` makes them slower. At exactly `bias = 0.5` the
#'   two conditional RT distributions are identical, whatever the drift rate.
#' * A positive `drift` pushes the accumulator towards the response coded `1`.
#'   When `0` codes correct responses and `1` codes errors (a common choice when
#'   the task has no natural stimulus-to-boundary mapping), good performance
#'   therefore corresponds to a *negative* drift rate.
#'
#' # Parameterization
#'
#' `ndt` is expressed **directly, in seconds** (through a log link in the `brms`
#' family). Nothing about it is taken from the data: it is not bounded by the
#' fastest observed response, so a non-decision time that varies by condition or
#' by participant can exceed the sample minimum wherever the data support it.
#'
#' Tying `ndt` to the fastest observed response would cap it at an order
#' statistic of the sample, so any condition or participant whose true `ndt`
#' exceeded that response would be inexpressible, and the misfit would surface
#' as spurious effects on the other parameters. Expressing it directly is what
#' avoids that.
#'
#' `sigmandt` is the between-trial *range* of the non-decision time (`st0` in
#' the usual notation), expressed directly in the same unit as the data, with
#' `ndt` the lower bound of the resulting Uniform.
#'
#' # Between-trial variability
#'
#' `sigmadrift`, `sigmabias` and `sigmandt` extend the classic 4-parameter
#' process to the full 7-parameter one. Each is legitimately **zero**, and
#' setting all three to zero in the formula recovers the classic model:
#'
#' ```r
#' brms::bf(RT | dec(Error) ~ Condition, sigmadrift = 0, sigmabias = 0,
#'          sigmandt = 0, ndt ~ 1, poutlier ~ 1, family = cogmod_ddm())
#' ```
#'
#' Writing `sigmadrift = 0` **fixes** the parameter; leaving it out of `bf()`
#' altogether *estimates* it, which is not the same thing. All three are hard to
#' recover even from a lot of data, and each has a flat direction at its own
#' floor - the link only reaches zero at minus infinity, and the likelihood stops
#' changing well before then - so [cogmod_priors()] gives all three deliberately
#' tight priors. Fixing the ones a design cannot identify is usually better than
#' estimating them behind a prior.
#'
#' `boundary` and `bias` have no such direction, but `brms` would leave them
#' flat, so [cogmod_priors()] fills those too: `normal(1, 1)` on the `boundary`
#' intercept, on its `softplus` link - a median separation of 1.31, with 95%
#' between 0.32 and 3.0 - and `normal(0, 0.5)` on the slopes of both. The
#' `bias` intercept keeps `brms`'s `logistic(0, 1)`, uniform on the probability
#' scale.
#'
#' There is a cost argument too, and it is a cliff rather than a slope. The
#' density has a closed form in `sigmadrift`, so estimating it costs about 1.2
#' to 1.6 times the classic model per gradient evaluation, depending on the data
#' (it was 3.5 before 0.3.6). `sigmabias` and `sigmandt` have no closed form:
#' Stan integrates them out numerically, once for the density and once more for
#' each partial derivative, at every observation and every leapfrog step.
#' Measured against the `sigmadrift`-only model on 300 trials, estimating *one*
#' of them costs about 60 to 70 times as much per gradient and estimating *both*
#' about 250 times. The multiples move with the data and the parameter values,
#' since the integration adapts to them. Nothing in between exists: the fast
#' path is a test for exactly zero, so a tight prior does not buy it back - a
#' `sigmandt` estimated at 1e-5 costs the same as one at 0.05 s. Only
#' `sigmandt = 0` in `bf()` does. On a few thousand trials this is the
#' difference between minutes and hours; on a few hundred thousand, between a
#' day and weeks.
#'
#' # The outlier component
#'
#' A shifted distribution assigns exactly zero density to any response faster
#' than `ndt`, which puts a hard boundary in the likelihood at the fastest
#' observed RT. Mixing in a component with support over the whole positive line
#' removes it: every response keeps positive density whatever `ndt` is, so the
#' boundary becomes a finite cost rather than a wall and the log-density stays
#' smooth and differentiable.
#'
#' Because this model produces a **choice as well as a time**, the contaminant
#' has to produce both. It is a guess: the choice is uniform over the two
#' options, and the RT is a **half Normal** with scale `0.2` seconds.
#'
#' \deqn{f(t, k) = p \frac{1}{K} g(t) + (1 - p) f_k(t - ndt)}
#'
#' The `1 / K` is what keeps the total summing to one over the response options;
#' without it it would come to `1 + poutlier`.
#'
#' `poutlier` is a *rate*, not a classification: the model never labels
#' individual trials, it estimates what share of them came from elsewhere. Use
#' [p_outlier()] for per-trial posterior probabilities.
#'
#' # Reaction times must be in seconds
#'
#' The outlier component's scale is a constant in seconds, and so are the
#' priors [cogmod_priors()] supplies. There is no argument for changing the
#' unit. Millisecond data fails silently rather than loudly - the outlier
#' component contributes nothing and the min-RT boundary comes back. See the
#' corresponding section of [cogmod_lognormal()] for the full account, which
#' applies unchanged here.
#'
#' # Implementation
#'
#' The 4-parameter density is the Navarro and Fuss (2009) series, evaluated in
#' log space and vectorised over parameter sets, so a response in the far tail
#' has a finite log-density rather than `log(0)`. It agrees with
#' [brms::dwiener()] and with `rtdists` to about `1e-10` wherever those return a
#' number, and is about eight times cheaper per element than the former. Draws are
#' taken by inverting the first-passage CDF, which - unlike [brms::rwiener()],
#' and unlike `rtdists` - vectorises over parameter sets, so the per-call setup
#' is paid once rather than once per posterior draw. That matters for
#' [posterior_predict()], where every draw carries its own parameters; it is
#' several times faster there and agrees with both packages' samplers to within
#' sampling error.
#'
#' The full 7-parameter model is built on top of these rather than delegated to
#' another package: between-trial variability is simulated by drawing the
#' per-trial parameters, and evaluated by combining a closed-form drift
#' correction with Gauss-Legendre quadrature over the starting point and
#' non-decision time, also in log space.
#'
#' In Stan, whenever `sigmabias` and `sigmandt` are both zero, the decision
#' component is the same series written in the Stan language, with `sigmadrift`
#' in closed form. The two sides agree to about `1e-11`, so the density a model
#' is fitted with is the one `log_lik()` and `loo()` score it by, on every
#' version of Stan and every backend. Stan's own `wiener_lpdf()` is used only for
#' the 7-parameter form, called with its own non-decision time set to zero
#' because the shift is applied by the mixture around it. Its 5-parameter form,
#' which the package used before 0.3.6, controls its error in absolute terms, so
#' it was off by up to a log unit per trial in the tails, and it computes the
#' density and each derivative as separate series, which made a model with
#' `sigmadrift` about 3.4 times as costly per gradient as it is now
#' (`benchmarks/wiener_stan/` in the source repository).
#'
#' # Fitting
#'
#' ```r
#' f <- brms::bf(RT | dec(Error) ~ Condition, boundary ~ Condition, bias ~ 1,
#'               sigmadrift = 0, sigmabias = 0, sigmandt = 0,
#'               ndt ~ 1, poutlier ~ 1, family = cogmod_ddm())
#' brms::brm(f, data = df,
#'           prior    = cogmod_priors(f, df),
#'           init     = cogmod_inits(f, df),
#'           stanvars = cogmod_stanvars(f))
#' ```
#'
#' Use [cogmod_inits()] rather than `init = 0`. `brms` initialises on the
#' unconstrained scale, so `init = 0` puts `ndt` at `exp(0) = 1` second - above
#' nearly every sub-second RT, which leaves every response attributed to the
#' outlier component and the diffusion parameters with no gradient at all.
#'
#' # Predictions exclude the outlier component
#'
#' `posterior_predict()` and `posterior_epred()` describe the **diffusion
#' alone** by default, as if `poutlier` were zero, because the outlier component
#' is a fixed regularizer rather than a claim about how guesses are distributed.
#' Use [with_outliers()] for the fitted mixture - chiefly for
#' `brms::pp_check()` - and [without_outliers()] to go back. `log_lik()` is
#' always the full mixture.
#'
#' @param n Number of simulated trials. If `length(n) > 1`, the length is taken
#'   to be the number required.
#' @param drift Drift rate. Any real value; positive pushes the accumulator
#'   towards the boundary coded `1`.
#' @param boundary Boundary separation. Must be positive.
#' @param bias Starting point, as a proportion of the boundary separation
#'   *measured from the boundary coded `0`*. Must be in `(0, 1)`.
#' @param ndt Non-decision time (shift parameter), in seconds. Must be
#'   non-negative. With `sigmandt > 0` it is the **lower bound** of the
#'   between-trial distribution rather than its midpoint.
#' @param sigmadrift Between-trial SD of the drift rate (`sv`). Must be
#'   non-negative. Default `0`.
#' @param sigmabias Between-trial start-point range, as a fraction in `[0, 1)`
#'   of the widest range that keeps the start point inside the boundaries:
#'   `sw = sigmabias * min(2 * bias, 2 * (1 - bias))`. Default `0`.
#' @param sigmandt Between-trial range of the non-decision time (`st0`), in the
#'   same unit as the data, with `ndt` its lower bound. Default `0`.
#' @param poutlier Proportion of responses generated by the outlier process
#'   rather than by the diffusion. Range: `[0, 1]`.
#'
#' @return `rcogmod_ddm()` returns a data frame with `n` rows and two columns:
#'   \item{rt}{The simulated reaction time.}
#'   \item{response}{The boundary reached, `1` for upper and `0` for lower,
#'     matching the `dec()` coding used by the `brms` families.}
#'
#'   `dcogmod_ddm()` returns the defective density at each element of `x` - the
#'   log density if `log = TRUE` - and `pcogmod_ddm()` the defective cumulative
#'   probability at each element of `q`, both for the response given in
#'   `response` and recycled to the length of the longest argument.
#'   `cogmod_ddm()` returns a `brms::custom_family` object, to put on a
#'   `brms::bf()` formula. `cogmod_ddm_stanvars()` returns a `brms::stanvars`
#'   object holding the family's Stan `functions` block, to pass to
#'   `brms::brm()`, and `cogmod_ddm_lpdf_expose()` compiles that Stan code and
#'   returns it as an R function, for checking the density outside of a model.
#'   The remaining functions are `brms` post-processing methods, called by
#'   `brms` rather than directly: `log_lik_cogmod_ddm()` returns a numeric
#'   vector holding one log-likelihood value per posterior draw for observation
#'   `i`, `posterior_predict_cogmod_ddm()` a draws x 2 matrix of reaction times
#'   and choices simulated for observation `i` - or, given a vector of
#'   observation indices, a `(draws * length(i))` x 2 matrix with the draws for
#'   `i[1]` first, which is how to predict many observations in one vectorised
#'   call rather than through `brms`'s one-observation-at-a-time loop (see
#'   Details) - and
#'   `posterior_epred_cogmod_ddm()` a draws x observations matrix of expected
#'   reaction times (marginal over the two responses, and only approximate once
#'   the between-trial variability parameters are non-zero).
#'
#' @references
#' - Ratcliff, R., & McKoon, G. (2008). The diffusion decision model: Theory and
#'     data for two-choice decision tasks. *Neural Computation*, *20*(4),
#'     873-922. \doi{10.1162/neco.2008.12-06-420}
#' - Navarro, D. J., & Fuss, I. G. (2009). Fast and accurate calculations for
#'     first-passage times in Wiener diffusion models. *Journal of Mathematical
#'     Psychology*, *53*(4), 222-230. \doi{10.1016/j.jmp.2009.02.003}
#'
#' @seealso [rcogmod_rdm()], [rcogmod_lba2()], [rcogmod_lnr()]
#'
#' @examples
#' # Simulate data, with 2% of trials from the outlier process
#' data <- rcogmod_ddm(1000,
#'   drift = 0.5, boundary = 1, bias = 0.5, ndt = 0.2, poutlier = 0.02
#' )
#' head(data)
#'
#' # Responses faster than ndt keep positive density, unlike the unmixed model
#' dcogmod_ddm(0.1, ndt = 0.2, response = 1, poutlier = 0.02)
#' dcogmod_ddm(0.1, ndt = 0.2, response = 1, poutlier = 0)
#'
#' @export
rcogmod_ddm <- function(n, drift = 0, boundary = 1, bias = 0.5, ndt = 0.2,
                        sigmadrift = 0, sigmabias = 0, sigmandt = 0,
                        poutlier = 0) {
  .rchoice("cogmod_ddm", n = n, ndt = ndt, poutlier = poutlier, mu = drift, boundary = boundary, bias = bias,
           sigmadrift = sigmadrift, sigmabias = sigmabias, sigmandt = sigmandt)
}


#' @rdname rcogmod_ddm
#' @param x The observed reaction time (RT).
#' @param response The boundary reached: `1` for the upper boundary, `0` for the
#'   lower one. This gives the *defective* density that boundary carries, mixed
#'   with the outlier component.
#' @param log Logical; if TRUE, returns the log-density. Default: FALSE.
#' @export
dcogmod_ddm <- function(x, drift = 0, boundary = 1, bias = 0.5, ndt = 0.2,
                        response, sigmadrift = 0, sigmabias = 0, sigmandt = 0,
                        poutlier = 0, log = FALSE) {
  .dchoice("cogmod_ddm", x = x, response = response, ndt = ndt,
           poutlier = poutlier, log = log,
           mu = drift, boundary = boundary, bias = bias,
           sigmadrift = sigmadrift, sigmabias = sigmabias, sigmandt = sigmandt)
}


#' @rdname rcogmod_ddm
#'
#' @description
#' `pcogmod_ddm()` is the cumulative distribution function: the probability that
#' a response has been made by time `q`. With `response = NULL` it is the RT
#' distribution marginally over the choice; with `response` set it is the
#' *defective* CDF that boundary carries, rising to the probability of that
#' boundary rather than to one.
#'
#' @details
#' # Accuracy of `pcogmod_ddm()`
#'
#' This CDF is more accurate than the one in `rtdists`, which is the usual
#' reference implementation. Deviation from numerical integration of the
#' density, at `drift = -4`, `boundary = 0.6`, `bias = 0.25`, by decision time:
#'
#' | decision time | this function | `rtdists::pdiffusion()` |
#' | --- | --- | --- |
#' | 0.02 | `+2.8e-16` | `+5.5e-04` |
#' | 0.05 | `-1.1e-16` | `+4.0e-04` |
#' | 0.30 | `-1.1e-16` | `+1.5e-04` |
#'
#' Over a grid of 360 (drift, boundary, bias, boundary-reached, time) cells the
#' worst deviation from integrating [dcogmod_ddm()] is 1e-15, i.e. rounding. The
#' choice probabilities are exact to the same order, where
#' `rtdists::pdiffusion(Inf, ...)` is out by up to 1.4e-04. The difference is
#' not academic: this function exists because [rcogmod_ddm()] inverts it to draw
#' from, so any error in it would land directly in the draws.
#'
#' `pcogmod_ddm()` covers the classic **4-parameter** DDM plus the outlier
#' component. The between-trial variability parameters would each need their own
#' quadrature layer on top - and `sigmadrift`, which the density handles with a
#' closed-form correction, has no such form here - so they are not arguments at
#' all: passing one is an error rather than a silently wrong number. Integrate
#' [dcogmod_ddm()] over `q` if you need them.
#'
#' With a `response`, `pcogmod_ddm()` returns the **defective** CDF
#' `P(RT <= q, choice = response)`, which does not reach one: its limit is the
#' probability of that boundary, given by `pcogmod_ddm(Inf, response = k)`. The
#' upper tail is then the matching defective survival
#' `P(RT > q, choice = response)`, so the two add to that response's own
#' probability rather than to one. Marginally (`response = NULL`) they add to
#' one as usual. [pcogmod_rdm()] follows the same convention.
#'
#' @param q Vector of quantiles (reaction times, in seconds).
#' @param lower.tail Logical; if TRUE (default) the probability is
#'   `P(RT <= q)`, otherwise `P(RT > q)`. With a `response`, both are defective
#'   - see Details.
#' @param log.p Logical; if TRUE, probabilities are returned on the log scale.
#' @export
pcogmod_ddm <- function(q, drift = 0, boundary = 1, bias = 0.5, ndt = 0.2,
                        response = NULL, poutlier = 0,
                        lower.tail = TRUE, log.p = FALSE) {
  # `response` is optional here but required by the shared preparation, so a
  # placeholder goes in when the marginal is wanted and is never read.
  params <- .prepare_choice("cogmod_ddm", x = q,
                            response = if (is.null(response)) 0 else response,
                            ndt = ndt, poutlier = poutlier,
                            mu = drift, boundary = boundary, bias = bias,
                            sigmadrift = 0, sigmabias = 0, sigmandt = 0)

  t_adj <- params$x - params$ndt
  # Response 1 is the upper boundary and `bias` is measured from the lower one,
  # following brms::wiener(). The upper boundary is the lower boundary of the
  # reflected process, so one lower-boundary routine serves both.
  f_lo <- .ddm_cdf_lower(t_adj, params$mu, params$boundary, params$bias)
  f_up <- .ddm_cdf_lower(t_adj, -params$mu, params$boundary, 1 - params$bias)

  # The outlier component is a half Normal, and its 1 / K sums back to one over
  # the response options - so the marginal carries all of it and a single
  # defective CDF carries its share.
  g_out <- 2 * stats::pnorm(pmax(params$x, 0) / .POUTLIER_SCALE) - 1
  if (is.null(response)) {
    dec <- f_lo + f_up
  } else {
    dec <- ifelse(params$response == 1, f_up, f_lo)
    g_out <- g_out / 2
  }

  # The attainable mass, which is what the two tails have to add back up to.
  # Marginally that is one; for a defective CDF it is the probability of that
  # response, so `lower.tail = FALSE` gives the defective survival
  # `P(RT > q, choice = response)` rather than `1 - P(RT <= q, choice =
  # response)`. The latter is `P(RT > q OR choice != response)`, which is not a
  # quantity anyone asks for - at `q = Inf` it returned the probability of the
  # *other* response instead of zero. Same convention as `pcogmod_rdm()`.
  #
  # `.ddm_plower()` is the limit `.ddm_cdf_lower()` itself takes at infinite
  # time, so the total is built the same way as the two defective CDFs above.
  if (is.null(response)) {
    total <- 1
  } else {
    p_lo <- .ddm_plower(params$mu, params$boundary, params$bias)
    p_up <- .ddm_plower(-params$mu, params$boundary, 1 - params$bias)
    total <- params$poutlier / 2 +
      (1 - params$poutlier) * ifelse(params$response == 1, p_up, p_lo)
  }

  out <- params$poutlier * g_out + (1 - params$poutlier) * dec
  out <- pmin(pmax(out, 0), total)
  if (!lower.tail) out <- total - out
  if (log.p) log(out) else out
}


# Family ------------------------------------------------------------------

#' @rdname rcogmod_ddm
#' @param link_mu,link_boundary,link_bias Link functions for the drift rate, the
#'   boundary separation and the starting point. `mu` is the drift: `brms`
#'   requires the first distributional parameter of a custom family to be called
#'   `mu`.
#' @param link_sigmadrift,link_sigmabias,link_sigmandt Link functions for the
#'   between-trial variability parameters. Fix them in the `brms::bf()` formula
#'   (e.g. `sigmadrift = 0`) to recover the classic 4-parameter DDM.
#' @param link_ndt,link_poutlier Link functions for the non-decision time and
#'   the outlier rate.
#' @param predict_outliers Logical; whether `posterior_predict()` and
#'   `posterior_epred()` should include the outlier component. `FALSE` (the
#'   default) fixes `poutlier` to zero for prediction, so predictions describe
#'   the diffusion alone; the likelihood is always the full mixture either way.
#'   On the prediction methods themselves the default is `NULL`, which defers to
#'   the flag carried on the model - see [with_outliers()]. See Details.
#' @export
cogmod_ddm <- function(
  link_mu = "identity",
  link_boundary = "softplus",
  link_bias = "logit",
  link_sigmadrift = "softplus",
  link_sigmabias = "logit",
  link_sigmandt = "log",
  link_ndt = "log",
  link_poutlier = "logit",
  predict_outliers = FALSE
) {
  .choice_family(
    "cogmod_ddm",
    links = c(link_mu, link_boundary, link_bias, link_sigmadrift,
              link_sigmabias, link_sigmandt),
    predict_outliers = predict_outliers
  )
}


# Internals ---------------------------------------------------------------

# Internal helpers for the extended (7-parameter) DDM ------------------------

#' @keywords internal
#' @noRd
.cogmod_ddm_has_variability <- function(params) {
  any(params$sigmadrift != 0, na.rm = TRUE) ||
    any(params$sigmabias != 0, na.rm = TRUE) ||
    any(params$sigmandt != 0, na.rm = TRUE)
}

#' Draw per-trial DDM parameters from their between-trial distributions
#'
#' Between-trial variability is, by definition, a hierarchical draw: the drift
#' is Normal, the starting point Uniform and the non-decision time Uniform
#' across trials. Drawing them and then running the plain 4-parameter process
#' reproduces the 7-parameter model exactly, so no dedicated sampler is needed.
#'
#' The parameterization matches the Stan likelihood in [cogmod_ddm_stanvars()]:
#' `sw = sigmabias * min(2*bias, 2*(1-bias))` with the starting point centred
#' on `bias`, and `st0 = sigmandt` directly, with `ndt` the *lower bound* of
#' the non-decision time (not its midpoint).
#'
#' @keywords internal
#' @noRd
.cogmod_ddm_draw_trialwise <- function(params) {
  n <- params$n

  params$drift <- stats::rnorm(n, params$drift, params$sigmadrift)

  sw <- params$sigmabias * pmin(2 * params$bias, 2 * (1 - params$bias))
  params$bias <- stats::runif(n, params$bias - sw / 2, params$bias + sw / 2)

  st0 <- params$sigmandt
  params$ndt <- pmax(stats::runif(n, params$ndt, params$ndt + st0), 0)

  params
}


#' Gauss-Legendre nodes and weights on `[-1, 1]`
#'
#' Computed with the Golub-Welsch algorithm (eigendecomposition of the Jacobi
#' matrix), so that no additional dependency is needed.
#'
#' @keywords internal
#' @noRd
.gauss_legendre <- function(n) {
  i <- seq_len(n - 1)
  b <- i / sqrt(4 * i^2 - 1)
  j <- matrix(0, n, n)
  j[cbind(i, i + 1)] <- b
  j[cbind(i + 1, i)] <- b
  e <- eigen(j, symmetric = TRUE)
  list(nodes = rev(e$values), weights = rev(2 * e$vectors[1, ]^2))
}


# The first-passage density -----------------------------------------------
#
# Navarro & Fuss (2009), written out here rather than delegated to
# `brms::dwiener()`. That call was 6 us per element, and it was the whole cost
# of `log_lik()` and hence of `loo()` - tolerable for the 4-parameter model,
# where it is paid once per draw-observation, and not for the 7-parameter one,
# where the quadrature below paid it 625 times per draw-observation: 5 ms each,
# or hours for a LOO over a few thousand draws of a few hundred trials. The
# series here is about 1 us per element vectorised - the remaining cost is R
# overhead, not arithmetic, so the next step would be C - and it works in log space
# throughout, so a response in the far tail comes back as a large negative
# number rather than as `log(0)`, which matters to `p_outlier()` and to LOO on
# exactly the trials they are most interested in. The Stan side is untouched:
# it calls Stan's own `wiener_lpdf()` (see .DDM_STAN_PRELUDE), and the two are
# checked against each other in test-model_ddm.R.

# Absolute accuracy demanded of the rescaled density f0 below. The series
# lengths grow only as sqrt(log(1 / eps)), so asking for a lot is cheap: at
# 1e-12 the longer of the two series is under ten terms everywhere the two
# meet, and the tails need fewer still.
.DDM_FPT_EPS <- 1e-12
# Terms per series, each way from the centre for the small-time one. Only an
# extreme rescaled time could reach it, and there the answer is `-Inf` anyway.
.DDM_FPT_CAP <- 200L

# Navarro & Fuss's term counts (their eqs 10-13) for an absolute error `eps`
# on the rescaled density at rescaled time `u`: the small-time series' count,
# across both sides of k = 0, and the large-time series' count.
#' @keywords internal
.ddm_fpt_ks <- function(u, eps = .DDM_FPT_EPS) {
  pmax(sqrt(u) + 1,
       ifelse(2 * sqrt(2 * pi * u) * eps < 1,
              2 + sqrt(pmax(-2 * u * log(2 * sqrt(2 * pi * u) * eps), 0)),
              2))
}
#' @keywords internal
.ddm_fpt_kl <- function(u, eps = .DDM_FPT_EPS) {
  pmax(1 / (pi * sqrt(u)),
       ifelse(pi * u * eps < 1,
              sqrt(pmax(-2 * log(pi * u * eps), 0) / (pi^2 * u)), 0))
}

# The rescaled time at which those two counts cross at .DDM_FPT_EPS: below it
# the small-time series is the shorter one, above it the large-time series.
# Written out rather than solved for at load, so that the Stan code built from
# it (.WFPT_STAN) is the same text on every machine; test-model_ddm.R checks
# it against the counts.
.DDM_FPT_SWITCH <- 0.20276100128382937

# Log first-passage density at the LOWER boundary of the driftless, unit-
# boundary diffusion started at `w`, at rescaled time `u = t / boundary^2`.
# `wc` is `1 - w`, which a caller that has it exactly should pass: near the
# far boundary `1 - w` rounds away the start point's distance from it.
#
# Navarro & Fuss give two series that are each exact and each converge only in
# their own regime - the small-time one in powers of exp(-1/u), the large-time
# one in powers of exp(-u) - and a rule (their eqs 10-13) for how many terms
# each needs for a given absolute error, so the cheaper one is taken for every
# element (below .DDM_FPT_SWITCH, the small-time one). Each series is then
# summed with its leading term factored out: for
# the small-time series that is the k = 0 term's exponent, `-w^2 / 2u`, and for
# the large-time series the k = 1 term's, `-pi^2 u / 2`. That is what makes the
# result accurate in the tails, where the density itself is far below `eps`:
# the leading term carries the magnitude exactly and the sum inside the log is
# an O(1) correction to it. Without the factoring, every term would underflow
# to zero together and the log would be `-Inf` at densities a long way above
# the smallest representable number.
#
# Elements are grouped by series and each group is evaluated as one terms x
# elements matrix, sized by the element in the group that needs the most terms.
# The extra terms the others get are exact zeros to double precision, so the
# grouping costs time and never accuracy.
#
# Two sums are arranged so that they do not cancel as the start point nears
# the far boundary (`wc` -> 0). The small-time k = 0 and k = -1 terms,
# `w + (w - 2) exp(-2 wc / u)`, are both near 1 there with a sum near
# `2 wc / u`, so they are taken together through expm1() - but only when `wc`
# is the smaller: near the boundary being hit (`w` -> 0) that form cancels
# instead, and the two terms as written are exact. And the large-time
# `sin(k pi w)` is taken as `(-1)^(k + 1) sin(k pi wc)` when `wc` is the
# smaller. The Stan code (.WFPT_STAN) does the same.
#' @keywords internal
.ddm_lfpt0 <- function(u, w, wc = 1 - w) {
  n <- max(length(u), length(w), length(wc))
  u <- rep_len(u, n)
  w <- rep_len(w, n)
  wc <- rep_len(wc, n)
  out <- rep(-Inf, n)
  ok <- is.finite(u) & u > 0 & is.finite(w) & w > 0 & w < 1
  if (!any(ok)) return(out)
  u <- u[ok]
  w <- w[ok]
  wc <- wc[ok]

  small <- u < .DDM_FPT_SWITCH
  res <- rep(-Inf, length(u))

  if (any(small)) {
    us <- u[small]
    ws <- w[small]
    wcs <- wc[small]
    m <- min(.DDM_FPT_CAP,
             max(2L, as.integer(ceiling(max(.ddm_fpt_ks(us)) / 2))))
    kk <- c(seq.int(-m, -2), seq_len(m))
    K <- length(kk)
    ne <- length(us)
    W <- matrix(ws, K, ne, byrow = TRUE) + 2 * kk
    U <- matrix(us, K, ne, byrow = TRUE)
    W0 <- matrix(ws, K, ne, byrow = TRUE)
    x <- -2 * wcs / us
    e1 <- exp(x)
    s <- ifelse(wcs < 0.5, -expm1(x) - wcs * (1 + e1), ws + (ws - 2) * e1) +
      .colSums(W * exp(-(W^2 - W0^2) / (2 * U)), K, ne)
    res[small] <- ifelse(s > 0,
                         log(s) - ws^2 / (2 * us) - 0.5 * log(2 * pi * us^3),
                         -Inf)
  }
  if (any(!small)) {
    ul <- u[!small]
    flip <- w[!small] > 0.5
    th <- pi * ifelse(flip, wc[!small], w[!small])
    K <- min(.DDM_FPT_CAP,
             max(2L, as.integer(ceiling(max(.ddm_fpt_kl(ul))))))
    ne <- length(ul)
    Kk <- matrix(seq_len(K), K, ne)
    U <- matrix(ul, K, ne, byrow = TRUE)
    TH <- matrix(th, K, ne, byrow = TRUE)
    sg <- ifelse(matrix(flip, K, ne, byrow = TRUE) & Kk %% 2 == 0, -1, 1)
    s <- .colSums(sg * Kk * exp(-(Kk^2 - 1) * pi^2 * U / 2) * sin(Kk * TH),
                  K, ne)
    res[!small] <- ifelse(s > 0, log(pi) + log(s) - pi^2 * ul / 2, -Inf)
  }
  out[ok] <- res
  out
}


# Log first-passage density at the LOWER boundary, with drift `v`, boundary
# separation `a`, relative start point `w` and - optionally - a Normal
# between-trial spread `sv` on the drift.
#
# The drift enters the density only through a factor, and integrating that
# factor against a Normal drift is closed form, so `sv` costs nothing: at
# `sv = 0` the exponent below is the familiar `-v a w - v^2 t / 2` and the
# `sqrt(1 + sv^2 t)` is one.
#' @keywords internal
.ddm_lfpt <- function(t, v, a, w, sv = 0, wc = 1 - w) {
  n <- max(length(t), length(v), length(a), length(w), length(sv), length(wc))
  t <- rep_len(t, n)
  v <- rep_len(v, n)
  a <- rep_len(a, n)
  w <- rep_len(w, n)
  sv <- rep_len(sv, n)
  s2t <- 1 + sv^2 * t
  num <- -v^2 * t - 2 * v * a * w + sv^2 * a^2 * w^2
  .ddm_lfpt0(t / a^2, w, wc) - 2 * log(a) + num / (2 * s2t) - 0.5 * log(s2t)
}


# The same for the boundary named by `k`: 1 is upper, 0 lower. The upper
# boundary is the lower boundary of the reflected process, so one routine
# serves both with the drift and the start point flipped - and the start
# point's complement is then `w` itself, exactly.
#' @keywords internal
.ddm_lfpt_resp <- function(t, v, a, w, k, sv = 0) {
  up <- k == 1
  .ddm_lfpt(t, ifelse(up, -v, v), a, ifelse(up, 1 - w, w), sv,
            wc = ifelse(up, w, 1 - w))
}


# The same density in Stan, for the likelihood (pasted into .DDM_STAN_PRELUDE).
# The switch is generated from .DDM_FPT_SWITCH, so the two sides cannot pick
# different series.
#' @keywords internal
.WFPT_STAN <- sprintf("
// The decision density whenever the start-point and non-decision-time ranges
// are both zero: .ddm_lfpt0() and .ddm_lfpt() of the R side, in Stan. Stan's
// own wiener_lpdf() serves the 7-parameter form only. Against Stan's, this is
// one series for the value and every partial (its 5-parameter form runs four),
// accurate in both tails where that form is off by up to a log unit, the
// number log_lik() computes in R, and the same on every Stan version and on
// stanli. To go back to Stan's - once a release carries stan-dev/math#3481 and
// #3442 - rerun benchmarks/wiener_stan/grid.R and program_ab.R on it: if
// Stan's is as accurate and no slower on both engines, the call in
// cogmod_ddm_decision_lpdf() is the only thing to change.
//
// Log first-passage density of the driftless, unit-boundary diffusion at its
// lower boundary, started at wl, at rescaled time u (Navarro & Fuss 2009, at
// 1e-12 absolute on the density, each series with its leading exponent
// factored out). w = 1 - wl is passed alongside because the caller has it
// exactly, where 1 - wl would round.
//
// Both series are written out at fixed length, m = 3 (k = -3..3) and K = 6:
// the most either needs at 1e-12 on its side of the switch (test-model_ddm.R
// checks this against .DDM_FPT_EPS). Do not fold them back into loops. A loop
// whose trip count depends on a parameter keeps the trial loop out of
// stanli's region map, which then records it afresh at every new point: 15 to
// 24 times slower per gradient (benchmarks/wiener_stan/README.md).
real cogmod_wfpt0(real u, real wl, real w) {
  if (u < %s) {
    // Small time: sum_k (wl + 2k) exp(-2k(k + wl) / u). Every term is a
    // product of e1 (the k = -1 factor), a1 (k = 1) and q = exp(-4 / u). The
    // k = 0 and k = -1 terms, wl + (wl - 2) e1, are taken by side. As w -> 0
    // both are near 1 with a sum near 2w / u, so there they go through
    // expm1(). As wl -> 0 that form would cancel instead (1 - w is wl), at
    // 2e-16 / wl on the log density, and the two terms as written are exact.
    real r = 2 / u;
    real x = -w * r;
    real e1 = exp(x);
    real a1 = exp(-(1 + wl) * r);
    real q = a1 * e1;
    real q2 = square(q);
    real b2 = square(e1) * q;
    real a2 = square(a1) * q;
    real s = (w < 0.5 ? -expm1(x) - w * (1 + e1) : wl + (wl - 2) * e1)
             + (wl + 2) * a1 + (wl - 4) * b2 + (wl + 4) * a2
             + (wl - 6) * (b2 * e1 * q2) + (wl + 6) * (a2 * a1 * q2);
    if (!(s > 0)) return negative_infinity();
    return log(s) - square(wl) / (2 * u) - 0.5 * log(2 * pi()) - 1.5 * log(u);
  }
  // Large time: sum_k k E^(k^2 - 1) sin(k pi wl), k = 1..6, with
  // E = exp(-pi^2 u / 2). The sines come by rotation from one sin() and one
  // cos(), at whichever of wl and w is nearer 0, using
  // sin(k pi wl) = (-1)^(k + 1) sin(k pi w), so that a start point near
  // either boundary keeps its relative precision.
  real E = exp(-square(pi()) * u / 2);
  real E2 = square(E);
  real g2 = E2 * E;
  real g3 = g2 * g2 * E2;
  real g4 = g3 * g2 * E2 * E2;
  real g5 = g4 * g3 * E;
  real g6 = g5 * g3 * E2 * E;
  int flip = wl > 0.5;
  int f = flip ? -1 : 1;
  real theta = pi() * (flip ? w : wl);
  real s1 = sin(theta);
  real c1 = cos(theta);
  real s2 = 2 * s1 * c1;
  real c2 = 1 - 2 * square(s1);
  real s3 = s2 * c1 + c2 * s1;
  real s4 = 2 * s2 * c2;
  real c4 = 1 - 2 * square(s2);
  real s5 = s4 * c1 + c4 * s1;
  real c5 = c4 * c1 - s4 * s1;
  real s6 = s5 * c1 + c5 * s1;
  real s = s1 + f * 2 * g2 * s2 + 3 * g3 * s3 + f * 4 * g4 * s4
           + 5 * g5 * s5 + f * 6 * g6 * s6;
  if (!(s > 0)) return negative_infinity();
  return log(pi()) + log(s) - square(pi()) * u / 2;
}

// The density at the upper boundary with w measured from the lower one, as
// Stan's wiener_lpdf(): the lower boundary of the reflected process, started
// at 1 - w with drift -v. sv integrates out in closed form.
//
// Outside 1e-140 < t / a^2 < 1e140 the log density is below -1e100 or so,
// and the partials of t / a^2 itself overflow (u / a^2 = 4e380 at a = 8e-96)
// while the value is still finite: reverse mode multiplies a zero adjoint
// into the infinite partial, and the gradient of the whole model is NaN under
// any mixture weight. So the answer there is the -inf it rounds to, as a
// constant, tested on products whose partials cannot overflow.
real cogmod_wfpt_lpdf(real t, real a, real w, real v, real sv) {
  real a2 = square(a);
  if (t > 1e140 * a2 || t < 1e-140 * a2) return negative_infinity();
  real wl = 1 - w;
  real lf = cogmod_wfpt0(t / a2, wl, w) - 2 * log(a);
  if (sv == 0) return lf + v * a * wl - square(v) * t / 2;
  real s2 = square(sv);
  return lf + (s2 * square(a * wl) + 2 * v * a * wl - square(v) * t)
              / (2 * (1 + s2 * t))
         - 0.5 * log1p(s2 * t);
}
", formatC(.DDM_FPT_SWITCH, format = "g", digits = 17, width = 1))


# Full (7-parameter) log-density at decision time `t`.
#
# Drift variability is closed form (see `.ddm_lfpt()`); the starting point and
# the non-decision time are integrated out by Gauss-Legendre quadrature over
# their Uniform distributions, on the log scale. The non-decision time is
# integrated only up to `t` - a later start leaves no time to decide in and
# contributes nothing - so the per-trial decision time `u` runs over
# `[t - st0, t]`, floored at zero.
#
# The st0 integral is taken over LOG decision time, `u = exp(s)`, and from a
# lower end where the density is dead rather than from zero. A fixed rule on
# the plain time scale fails whenever the st0 range reaches down to fast
# decision times: the first-passage density then rises from nothing to its
# peak - near `a^2 w^2 / 3` for a start point `a w` from the responding
# boundary - inside a sliver of the range, and 25 nodes spread over the whole
# of it cannot resolve that. It is the defect reported against
# `rtdists::ddiffusion()` in rtdists issue #28, and it was here too: against a
# converged rule the plain-scale 25-node rule was out by 5e-4 on the issue's
# own example (`a = 0.5`, `v = 0.5`, `w = 0.3`, `st0 = 0.16`, `t = 0.16`), by
# 3% at `w = 0.1`, `st0 = 0.2`, `t = 0.2`, and by 50% with the start point
# almost on the boundary. In `s` the peak is about one log unit wide wherever
# it sits, so the same 25 nodes see it at the same resolution at any time
# scale, and the density's two tails - `exp(-c / u)` on the left,
# `exp(-lambda u)` on the right - both become double exponentials, which is as
# gentle as an integrand gets.
#
# The lower end: the small-time series is dominated by `exp(-c / u)` with
# `c = a^2 w^2 / 2`, whose exponent is `1.5` at the peak of the leading term,
# or `c / t` if `t` itself is earlier than that peak. The integral starts where
# that exponent has grown by `.DDM_ST0_DEAD` more - where the integrand is
# `e^-25` below its peak - or at `t - st0` if that is later. Without the
# cutoff the log range would run to `-Inf`; with it the range is three log
# units to the left of the peak plus `log(t / peak)` to its right, and no node
# is spent where nothing is. The cutoff depends on the start point, so the st0
# nodes are laid out afresh for each start-point node: a few length-n
# operations and one `exp()` per node, against the series evaluation itself,
# which is where the time goes.
#
# How many nodes the log range then needs is nearly a matter of its length
# alone, since the peak's width in `s` does not change: against the rule at
# 1600 nodes, 25 nodes hold 1e-9 up to six log units, 5e-7 up to ten, and
# 1e-5 at fourteen - a 10 s response under a 10 s st0 range with the start
# point 5% of a 0.5 boundary from the response - where 40 nodes hold 3e-8. So
# the st0 rule gets `.DDM_ST0_NODES_PER_LOG` nodes per log unit of the widest
# range in the call, and never fewer than `nodes`. That is a no-op below eight
# log units, and a range that stops short of zero only exceeds them if it
# reaches within a 3000th of the decision time of it; so in practice the rule
# grows only for responses faster than the st0 range itself, and then only with
# the start point near the boundary or a long response - which is exactly
# where the plain-scale rule failed.
#
# The st0 nodes are evaluated in one call per start-point node, as a nodes x
# observations block, and combined with a log-sum-exp down the columns. The
# density's cost is R overhead rather than arithmetic, so 25 calls on long
# vectors are several times cheaper than 625 calls on short ones - and the
# block is only 25 x draws, so memory is not a concern.
#
# `sw` is the start-point range as a fraction of `[0, 1]` and `st0` the
# non-decision-time range in seconds, both as `.cogmod_ddm_draw_trialwise()`
# and the Stan code define them, with `ndt` the LOWER end of the st0 range.
#
# Validated against this same rule at 800 and 1600 nodes, which agree with each
# other to 1e-13: on the issue-28 sweep (`a = 0.5`, `v = 0.5`, `w` from 0.1,
# `st0` up to 0.2, `t` from 0.02 to 0.5, with and without start-point
# variability) the result is within 1e-9 everywhere, within 4e-12 over a grid
# of 800 cells that also has 4 s responses under a 5 s st0 range, drifts of 3,
# and the start point 2.5% of the boundary from the response, and within 4e-12
# on the 10 s cases above - the last two with the rule sized to the widest
# range in the call, as it would be in use. Where the st0 range stays inside
# the response time the values agree with the plain-scale rule's to 1e-13 - it
# was right there - for no measurable difference in cost: on 4000 draws of a
# typical observation the two land within a tenth of each other either way
# between runs, the series evaluation being where the time goes. The Stan
# likelihood in [cogmod_ddm_stanvars()] agrees to 1e-5 (test-model_ddm.R);
# the worst cells sit at 2e-6, which is Stan's own stopping tolerance.
#
# `nodes` is the least number of quadrature nodes per integrated dimension.
#' @keywords internal
.ddm_ldens_var <- function(pars, nodes = 25) {
  t <- pars$t
  n <- length(t)
  # The upper boundary is the lower one of the reflected process. The reflection
  # is applied here, once, rather than at every node: `sw` is symmetric in the
  # start point, and the nodes are symmetric about it, so the quadrature over
  # the reflected start point is the same sum.
  up <- pars$response == 1
  v <- ifelse(up, -pars$drift, pars$drift)
  w <- ifelse(up, 1 - pars$bias, pars$bias)
  wc <- ifelse(up, pars$bias, 1 - pars$bias)  # 1 - w, exactly
  a <- pars$boundary
  sv <- pars$sigmadrift
  sw <- pars$sigmabias * pmin(2 * w, 2 * (1 - w))
  st0 <- pars$sigmandt

  # A degenerate "node" of weight 2 reproduces the point value once the 1/2
  # factor of the uniform average is applied.
  degenerate <- list(nodes = 0, weights = 2)
  quad <- .gauss_legendre(nodes)
  w_quad <- if (any(sw > 0)) quad else degenerate

  spread <- st0 > 0
  u_lo <- pmax(t - st0, 0)
  log_t <- log(t)

  # The st0 rule, sized to the widest log range any start-point node will
  # face: the node nearest the boundary has the smallest `c` and hence the
  # lowest cutoff (see above). `w - sw / 2` is just beyond the outermost node,
  # so the range is if anything overstated.
  if (any(spread)) {
    cc <- a^2 * (w - sw / 2)^2 / 2
    lrange <- log_t - log(pmax(u_lo, cc / (pmax(1.5, cc / t) + .DDM_ST0_DEAD)))
    nodes_t <- ceiling(.DDM_ST0_NODES_PER_LOG * max(lrange[spread]))
    nodes_t <- min(max(nodes, nodes_t), .DDM_ST0_NODES_MAX)
    t_quad <- if (nodes_t == nodes) quad else .gauss_legendre(nodes_t)
  } else {
    t_quad <- degenerate
  }
  nb <- length(t_quad$nodes)
  lw <- log(t_quad$weights)

  # Everything the st0 dimension needs, laid out node-fastest: element
  # (b, i) of the block sits at position (i - 1) * nb + b, so a vector
  # repeated `each = nb` pairs with the node vector recycled `n` times.
  each <- function(x) rep(x, each = nb)
  v_b <- each(v)
  a_b <- each(a)
  sv_b <- each(sv)

  out <- rep(-Inf, n)
  for (ia in seq_along(w_quad$nodes)) {
    w_a <- w + (sw / 2) * w_quad$nodes[ia]
    wc_a <- wc - (sw / 2) * w_quad$nodes[ia]
    # The log range: from where the density is dead (see above), or from
    # `t - st0` if that is later, up to `t`.
    cc <- a^2 * w_a^2 / 2
    lo <- log(pmax(u_lo, cc / (pmax(1.5, cc / t) + .DDM_ST0_DEAD)))
    half <- pmax(log_t - lo, 0) / 2
    # The Jacobian of the nodes onto that range, the `1 / st0` of the uniform
    # density, and the `du = u ds` of the substitution, which is `s_b` itself
    # and is added below. Where st0 is zero the range has collapsed onto `t`,
    # every node sits at `log(t)`, and the `-log(t)` here cancels that term so
    # the weights - two of them, or a full rule's when other elements have an
    # st0 - average back to the point value.
    lscale <- ifelse(spread, log(half) - log(st0), -log(2) - log_t)
    s_b <- each(log_t - half) + each(half) * t_quad$nodes
    lt <- matrix(each(lscale) + lw + s_b +
                   .ddm_lfpt(exp(s_b), v_b, a_b, each(w_a), sv_b,
                             wc = each(wc_a)), nb, n)
    # log-sum-exp down the columns; a column of -Inf stays -Inf rather than NaN
    mx <- lt[1, ]
    for (b in seq_len(nb)[-1]) mx <- pmax(mx, lt[b, ])
    fin <- is.finite(mx)
    inner <- rep(-Inf, n)
    if (any(fin)) {
      inner[fin] <- mx[fin] +
        log(.colSums(exp(lt[, fin, drop = FALSE] - rep(mx[fin], each = nb)),
                     nb, sum(fin)))
    }
    out <- .log_add_exp(out, log(w_quad$weights[ia] / 2) + inner)
  }
  out
}

# How far below its peak, in log units, the first-passage density is taken as
# dead when `.ddm_ldens_var()` places the lower end of its st0 quadrature.
# `e^-25` is 1e-11: the mass dropped is far below the rule's own error, and
# each extra unit here would only stretch the log range the nodes have to
# cover.
#' @keywords internal
.DDM_ST0_DEAD <- 25

# Nodes per log unit of decision time for the st0 rule of `.ddm_ldens_var()`,
# and the most it will use. Three per unit hold 3e-8 at fourteen log units; the
# cap is reached only by an absurd range - a start point within 1e-6 of the
# boundary, say - and keeps one such element from sizing the block for all.
#' @keywords internal
.DDM_ST0_NODES_PER_LOG <- 3
#' @keywords internal
.DDM_ST0_NODES_MAX <- 100L


#' Translate `cogmod`'s parameterization into `rtdists`' one
#'
#' Not used by the package itself - the 7-parameter model is implemented
#' natively - but kept as the reference mapping for cross-checking against
#' [rtdists::ddiffusion()]/[rtdists::rdiffusion()]. Note that `rtdists` takes
#' the starting point and its variability on the absolute (`a`-scaled) scale,
#' and treats `t0` as the *lower* bound of the non-decision time distribution.
#'
#' @keywords internal
#' @noRd
.cogmod_ddm_to_rtdists <- function(params) {
  sw <- params$sigmabias * pmin(2 * params$bias, 2 * (1 - params$bias))
  list(
    a = params$boundary,
    v = params$drift,
    t0 = params$ndt,
    z = params$bias * params$boundary,
    sv = params$sigmadrift,
    sz = sw * params$boundary,
    st0 = params$sigmandt
  )
}

# CODE to BENCHMARK the backends

# # Load required packages
# library(brms)
# library(microbenchmark)

# # Function to randomly generate parameters
# generate_random_params <- function() {
#   list(
#     boundary = runif(1, 0.5, 2),  # Boundary separation: [0.5, 2]
#     bias = runif(1, 0.3, 0.7), # Starting point bias: [0.3, 0.7]
#     drift = runif(1, -1, 1),      # Drift rate: [-1, 1]
#     ndt = runif(1, 0.1, 0.5)   # Non-decision time: [0.1, 0.5]
#   )
# }

# # Benchmark settings
# n <- 5000  # Number of trials for simulation
# x <- seq(0.05, 2.5, length.out = 1000)  # Reaction times for density computation
# resp <- sample(c(1, 2), size = length(x), replace = TRUE)  # Random responses

# # Function to set backend and run rwiener with random parameters
# benchmark_rwiener <- function(backend) {
#   options(wiener_backend = backend)
#   params <- generate_random_params()
#   rwiener(n, boundary = params$boundary, bias = params$bias, delta = params$drift, tau = params$ndt)
# }

# # Function to set backend and run dwiener with random parameters
# benchmark_dwiener <- function(backend) {
#   options(wiener_backend = backend)
#   params <- generate_random_params()
#   dwiener(x, boundary = params$boundary, bias = params$bias, delta = params$drift, tau = params$ndt, resp = resp)
# }

# # Benchmark rwiener for both backends
# rwiener_benchmark <- microbenchmark(
#   Rwiener = benchmark_rwiener("Rwiener"),
#   rtdists = benchmark_rwiener("rtdists"),
#   times = 100
# )
# print("rwiener Benchmark:")
# print(rwiener_benchmark)
# autoplot(rwiener_benchmark) + ggtitle("rwiener Benchmark")

# # Benchmark dwiener for both backends
# dwiener_benchmark <- microbenchmark(
#   Rwiener = benchmark_dwiener("Rwiener"),
#   rtdists = benchmark_dwiener("rtdists"),
#   times = 100
# )

# # Print results
# print("dwiener Benchmark:")
# print(dwiener_benchmark)
# autoplot(dwiener_benchmark) + ggtitle("dwiener Benchmark")


# The decision component, as the registry wants it ------------------------

# Stan's `wiener_lpdf()` insists on a strictly positive non-decision time, but
# the density depends on the time and the non-decision time only through their
# difference, so the Stan code evaluates it at `(t + tau0, tau0)` and gets the
# decision density at `t` exactly. The value is far below any RT resolution and
# cancels to the last bit at every magnitude the density is ever asked about,
# so it is a workaround for an argument check rather than an approximation. It
# is written into the generated Stan code from here (see .DDM_STAN_PRELUDE);
# the R density has no such check to appease and does not use it.
#' @keywords internal
.DDM_TAU0 <- 1e-10

# The tolerance handed to Stan's 7-parameter `wiener_lpdf()`, the form the Stan
# code falls through to when `sigmabias` or `sigmandt` is estimated. Stan
# integrates the start point and the non-decision time out numerically
# (adaptive cubature), and not once but eight times per observation: the
# density, then each partial derivative in an integral of its own. This number
# is the relative tolerance of every one of those integrals; Stan's default is
# 1e-4.
#
# Measured 2026-09-18 (CmdStan 2.38.0, per observation and gradient, on the
# benchmark of the report that prompted this): with only one of the two ranges
# open the tolerance changes nothing - 102 us at 1e-4, 100 at 1e-3, 97 at 1e-2 -
# because a one-dimensional integral is already settled by cubature's first
# 15-point pass, so that cost is a floor. With both open, 274 us at 1e-4 falls
# to 223 at 2e-4, 182 at 5e-4, 163 at 1e-3 and 153 at 1e-2: a 1.7x saving by
# 1e-3 and nothing much after it, which is why this stops there. The
# 5-parameter form, for comparison, is 5.4 us; the fast paths are untouched by
# this. On the brms program benchmarks/gradient_cost.R emits - 5000 trials,
# every dpar estimated - the gradient went from 3.25 s to 1.50 s, ratio 0.46
# over 21 alternating blocks: more than the 1.7x above, the operating point
# being a different one.
#
# What it costs in accuracy (benchmarks/gradient_check.R, cogmod_ddm, 22
# points): the value still agrees with the R density to 1e-5 across
# test-model_ddm.R's grid, but the gradient's relative error against central
# differences is about 2e-5 at a typical point where Stan's default gave 2e-6,
# and 1.2e-4 at the one tail point that now exceeds the check's 1e-4 gate -
# `ndt` 2.5 log units above its start, where nearly every trial has fallen to
# the outlier component. The step happens at the first loosening: 3e-4, 5e-4
# and 1e-3 measure the same error at every one of those points, so there is no
# intermediate value that keeps the default's accuracy and any of the saving.
# The known-bad point (`sigmandt` pushed wide, see .GP_KNOWN in the check) is
# unrelated to this number and moves around with it - 13 at 1e-4, 5e-4 at
# 5e-4, 0.06 at 1e-3.
#
# And in a fit (benchmarks/ddm_precision/, same day): the intercept-only
# 7-parameter model on 100 simulated trials, 4 chains, both tolerances from
# the same start, metric and seed. End to end (100 warmup + 200 draws) and
# again with adaptation off from one shared adapted state (200 draws), the
# sampler did not notice the looser gradient - 24 leapfrog steps per iteration
# either way, the same step size, acceptance 0.90 -> 0.92, divergences 10 -> 7
# and 11 -> 7, min bulk ESS 206 -> 248 and 224 -> 261 (noise at 800 draws,
# but not lower) - while a gradient cost 883 -> 445 ms and 830 -> 435 ms. Min
# ESS per CPU second: x2.4 and x2.2. The same fit says the report's 274 us
# per observation is a benign point: here it was 8.3 ms at the default
# tolerance, thirty times that, with the posterior at sigmandt ~ 0.03 s and
# sigmadrift ~ 0.7 - and Laplace draws in the tails cost seconds per
# evaluation, which is cubature's 6000-evaluation cap times eight integrals.
# If the trade ever looks wrong in a fit, this constant is the one line to
# change back.
#' @keywords internal
.DDM_WIENER_PRECISION <- 1e-3


# Log-density of the diffusion finishing at decision time `t` (already net of
# the non-decision time) at the boundary named by `k`: 1 is upper, 0 lower.
#
# `.ldec_choice()` masks out `t <= 0` and restores the shape afterwards, so this
# only has to work elementwise. Everything is flattened first because
# `p_outlier()` passes draws x observations matrices.
#' @keywords internal
.ddm_ldens <- function(t, k, p) {
  tv <- as.vector(t)
  n <- length(tv)
  if (n == 0) return(numeric(0))
  rec <- function(v) rep_len(as.vector(v), n)

  pars <- list(
    t = tv,
    drift = rec(p$mu),
    boundary = rec(p$boundary),
    bias = rec(p$bias),
    response = rec(k),
    sigmadrift = rec(p$sigmadrift),
    sigmabias = rec(p$sigmabias),
    sigmandt = rec(p$sigmandt)
  )

  if (.cogmod_ddm_has_variability(pars)) {
    return(.ddm_ldens_var(pars))
  }
  .ddm_lfpt_resp(pars$t, pars$drift, pars$boundary, pars$bias, pars$response)
}


# Vectorised first-passage sampler ----------------------------------------
#
# `brms::rwiener()` samples one parameter set per call, so `posterior_predict()`
# - which brms drives one observation at a time, with every posterior draw
# carrying its own parameters - pays the sampler's fixed setup cost once per
# draw. Measured, that setup was about 85% of the cost: rtdists' marginal cost
# per draw is 1.4 us against a 772 us fixed cost, and RWiener's sampler does not
# amortise at all (55-90 us per draw at any n).
#
# So the draws are taken by inverting the CDF instead, which vectorises across
# parameter sets because every step acts on the whole vector at once. Three
# things make it cheap enough to be worth it:
#
#  * The large-time series for the defective lower-boundary CDF splits into a
#    part that depends on t and a part that does not. The root-finder varies
#    only t, so the rest is built once and each evaluation is a single exp()
#    and a column sum.
#  * The density falls out of the same exp(), because C_k * R_k reduces to
#    k sin(k pi w) / 2. A Newton step therefore costs exactly what a bisection
#    step costs.
#  * The series is solved in stages of growing length (see `.ddm_fpt_rng()`):
#    the number of terms a draw needs falls as 1 / sqrt(t), so the bulk of the
#    draws are settled with a short series and only the fastest responses pay
#    for a long one. Sizing the series for the worst case instead cost 4-7x
#    on the inner loop - and 18x when the parameters vary across draws, as
#    they do in `posterior_predict()`, since one extreme draw then sets the
#    length for all of them.
#
# Accurate to 1e-13 in log RT against a 60-step bisection, and the underlying
# CDF agrees with numerical integration to 1e-9 - where `rtdists::pdiffusion()`
# is out by up to 5e-4. Every draw checked against `.ddm_cdf_lower()` lands
# within 1e-13 of its target probability.

# Terms are kept until the last one is below this at the earliest time evaluated.
.DDM_SERIES_TOL <- 1e-13
# The series length grows as 1/sqrt(t), so an extreme starting point makes it
# long. The cap trades accuracy for time only in that corner.
.DDM_SERIES_CAP <- 400L
# Terms in the first stage, and the factor the count grows by per stage. At the
# default start point 16 terms settle about 98% of the draws; measured over a
# grid of drifts, boundaries and start points, 16 x 4 beat every alternative
# from 8 x 2 to 24 x 4.
.DDM_SERIES_K0 <- 16L
.DDM_SERIES_GROW <- 4L
# Newton passes before the stragglers are handed to bisection. Converged draws
# leave the active set, so late passes run on a handful of draws and cost next
# to nothing; twelve leaves about 0.1% for the cleanup.
.DDM_NEWTON <- 12L
.DDM_EPS_V <- 1e-8

# P(the lower boundary is hit first), for a process starting at z = w * a.
#' @keywords internal
.ddm_plower <- function(v, a, w) {
  # A driftless walk hits 0 first with probability (a - z) / a: the start point
  # divides the interval and nothing biases it either way.
  out <- 1 - w
  g <- abs(v) >= .DDM_EPS_V
  if (any(g)) {
    x <- -2 * v[g] * a[g]
    y <- x * w[g]
    # Both exponents share the sign of -v, so writing it this way keeps whichever
    # one could overflow out of the expression entirely.
    r <- (1 - exp(y - x)) / (1 - exp(-x))
    neg <- x < 0
    if (any(neg)) r[neg] <- (exp(x[neg]) - exp(y[neg])) / expm1(x[neg])
    out[g] <- r
  }
  pmin(pmax(out, 0), 1)
}

# Below this the lower-boundary CDF is under about 1e-15, so it is taken as
# zero. It doubles as the lower end of the root-finder's bracket, which is what
# bounds the series length: the number of terms needed grows as 1 / sqrt(t).
#' @keywords internal
.ddm_tfloor <- function(a, w) (a * w)^2 / 69

#' @keywords internal
.ddm_nterms <- function(a, tmin) {
  k <- a * sqrt(-2 * log(.DDM_SERIES_TOL) / (pi^2 * pmax(tmin, 1e-12)))
  as.integer(min(.DDM_SERIES_CAP, max(4L, ceiling(max(k)))))
}

# The inverse of `.ddm_nterms()`: the earliest time at which K terms meet the
# tolerance, for boundary separation a. A series of K terms is trusted from
# here on and not below.
#' @keywords internal
.ddm_tmin <- function(a, K) {
  a^2 * (-2 * log(.DDM_SERIES_TOL)) / (pi^2 * K^2)
}

# The t-independent half of the series, as K x n matrices.
#
#   S(t) = P_lo - F_lo(t) = pref * sum_k C_k exp(-R_k t)
#   f(t) = -dS/dt         = pref * sum_k C_k R_k exp(-R_k t)
#
# The survival is the series itself, formed with no cancellation, where the CDF
# is a difference that saturates. That is why the inversion below solves for the
# survival: on the CDF side the gradient vanishes in the right tail and Newton
# stalls.
#' @keywords internal
.ddm_series <- function(v, a, w, K) {
  n <- length(v)
  k <- seq_len(K)
  # outer() and recycling in place of four K x n copies of the parameters: the
  # setup was a quarter of the sampler's time at long series lengths.
  kpa <- outer(k^2 * pi^2, 1 / a^2)
  v2 <- kpa + rep(v^2, each = K)
  list(C = matrix(k, K, n) * sin(outer(k * pi, w)) / v2,
       R = v2 / 2,
       pref = (2 * pi / a^2) * exp(-v * a * w),
       K = K, n = n)
}

# Defective CDF of the lower boundary: P(absorbed at 0, by time t).
#
# The same series the sampler inverts, evaluated once instead of repeatedly.
# Accurate to about 1e-9 against numerical integration of the density, where
# `rtdists::pdiffusion()` is out by up to 5e-4 - which is the reason this exists
# rather than delegating: `.ddm_fpt_rng()` inverts it, so its error would end up
# in the draws.
#' @keywords internal
.ddm_cdf_lower <- function(t, v, a, w) {
  out <- numeric(length(t))
  if (!length(t)) return(out)
  plo <- .ddm_plower(v, a, w)
  # At infinite time the process has been absorbed with certainty, so the
  # defective CDF has reached the choice probability of its own boundary. The
  # series cannot reach it - every term is exp(-R t), so the survival there is
  # exactly zero rather than small - and it is taken from `.ddm_plower()`
  # instead. Without this the branch below leaves the pre-allocated zero, which
  # is the value at t = 0, not at t = Inf.
  absorbed <- is.infinite(t) & t > 0
  out[absorbed] <- plo[absorbed]
  # Below the floor the CDF is under about 1e-15, and the series would need a
  # prohibitive number of terms to say so. Returning zero there is both cheaper
  # and, to double precision, right.
  live <- is.finite(t) & t > .ddm_tfloor(a, w)
  if (!any(live)) return(out)
  tl <- t[live]
  pre <- .ddm_series(v[live], a[live], w[live], .ddm_nterms(max(a[live]), min(tl)))
  s <- pre$pref * .colSums(pre$C * exp(-pre$R * rep(tl, each = pre$K)),
                           pre$K, pre$n)
  out[live] <- pmin(pmax(plo[live] - s, 0), plo[live])
  out
}


# Solve log S(t) = ltarget for every column of a prepared series, given the
# log of a floor the root is known to sit above. Returns log t. The bracket
# starts at [floor, 60 s] and is widened at the top where the one-term
# inversion says the root is out that far; a near-driftless process behind a
# wide boundary can finish well past 60 s.
#
# Indexed assignment rather than ifelse() throughout, and no column subsetting
# while every draw is still active: brms calls the sampler once per observation
# with a few dozen draws, and at that size the cost is the number of R-level
# operations, not the arithmetic.
#' @keywords internal
.ddm_solve_series <- function(pre, ltarget, llo, guess) {
  C <- pre$C; R <- pre$R; pref <- pre$pref; K <- pre$K; m <- pre$n
  ev <- function(x, idx = NULL) {
    if (is.null(idx)) {
      ce <- C * exp(-R * rep(exp(x), each = K))
      list(S = pref * .colSums(ce, K, m), f = pref * .colSums(ce * R, K, m))
    } else {
      mm <- length(idx)
      Ri <- R[, idx, drop = FALSE]
      ce <- C[, idx, drop = FALSE] * exp(-Ri * rep(exp(x), each = K))
      list(S = pref[idx] * .colSums(ce, K, mm),
           f = pref[idx] * .colSums(ce * Ri, K, mm))
    }
  }

  # The one-term inversion: exact in the tail, where a single term carries the
  # series, and meaningless (negative, or below the floor) for a fast response,
  # which starts from the small-time guess instead.
  t1 <- (log(pref * C[1, ]) - ltarget) / R[1, ]
  tail <- is.finite(t1) & t1 > exp(llo)
  x <- guess
  x[tail] <- log(t1[tail])

  # Only a root the one-term inversion already puts past 15 s can lie beyond
  # 60 s: by then every other term is down by exp(-3 pi^2 t / (2 a^2)) or more
  # on the first, which is negligible for any boundary under 10. So the
  # extension check runs on those draws alone rather than on all of them.
  lhi <- rep(log(60), m)
  far <- which(is.finite(t1) & t1 > 15)
  if (length(far)) {
    lf <- lhi[far]
    for (i in 1:8) {
      short <- log(ev(lf, far)$S) > ltarget[far]
      short[is.na(short)] <- FALSE
      if (!any(short)) break
      lf[short] <- lf[short] + log(16)
    }
    lhi[far] <- lf
  }
  x <- pmin(pmax(x, llo + 1e-9), lhi - 1e-9)

  out <- x
  act <- NULL                        # NULL: every draw is still active
  tg <- ltarget
  for (i in seq_len(.DDM_NEWTON)) {
    sf <- ev(x, act)
    h <- log(sf$S) - tg               # > 0: too much mass left, so t is too small
    dx <- h * sf$S / pmax(sf$f * exp(x), 1e-300)
    # S can only come back non-positive far in the tail, from rounding on a
    # sum that should be ~0, so that side of the bracket moves down.
    up <- h > 0
    up[is.na(up)] <- FALSE
    llo[up] <- x[up]
    lhi[!up] <- x[!up]
    # Converged means a tiny step AND a tiny residual. The step alone is not
    # enough: a pass that lands deep in the tail finds S and f both denormal,
    # and their ratio makes dx look like 1e-13 while the residual is still
    # hundreds of log units off. That was a genuine (rare) failure mode, and it
    # returned a 30 s response for a 3 ms one.
    conv <- is.finite(dx) & abs(dx) < 1e-10 & is.finite(h) & abs(h) < 1e-8
    xn <- x + dx
    # A step out of the bracket falls back to its midpoint, so every pass
    # makes progress even where Newton is wild.
    wild <- (!is.finite(xn) | xn <= llo | xn >= lhi) & !conv
    xn[wild] <- (llo[wild] + lhi[wild]) / 2
    x <- xn
    # Converged draws leave the active set, so the late passes cost almost
    # nothing and there is no reason to skimp on them.
    if (any(conv)) {
      if (is.null(act)) act <- seq_len(m)
      out[act[conv]] <- x[conv]
      keep <- !conv
      act <- act[keep]; x <- x[keep]; llo <- llo[keep]; lhi <- lhi[keep]
      tg <- tg[keep]
      if (!length(act)) break
    }
  }

  # Whatever Newton has not settled is bisected. The bracket is valid by
  # construction, so this cannot fail to converge.
  if (is.null(act)) act <- seq_len(m)
  if (length(act)) {
    C <- C[, act, drop = FALSE]; R <- R[, act, drop = FALSE]
    pref <- pref[act]; mm <- length(act)
    for (i in 1:50) {
      mid <- (llo + lhi) / 2
      s <- pref * .colSums(C * exp(-R * rep(exp(mid), each = K)), K, mm)
      up <- log(s) > tg
      up[is.na(up)] <- FALSE
      llo[up] <- mid[up]
      lhi[!up] <- mid[!up]
    }
    out[act] <- (llo + lhi) / 2
  }
  out
}


# Draw first-passage times for a Wiener process with drift `v`, boundary
# separation `a` and relative start point `w`, one parameter set per draw.
# Returns response 1 for the upper boundary, matching brms::rwiener().
#
# The series is solved in stages. A series of K terms is exact (to the
# tolerance) from `.ddm_tmin(a, K)` onwards and unusable below it, so each stage
# brackets its draws from that time, settles those whose root is comfortably
# inside the bracket, and hands the rest - the draws that turn out to be faster
# than this many terms can describe - to the next stage with four times as
# many terms. The last stage uses the true floor and the full series, exactly
# as a single-stage solve would, so nothing is ever approximated: a draw is
# only accepted from a stage whose series is exact at its root. The number of
# terms a draw needs falls as 1 / sqrt(t), and at the default start point the
# first stage settles about 98% of them with 16 terms where the full series
# has 41; at a start point of 0.1 it is 205.
#' @keywords internal
.ddm_fpt_rng <- function(n, v, a, w) {
  if (n == 0) return(list(rt = numeric(0), response = numeric(0)))
  v <- rep_len(v, n); a <- rep_len(a, n); w <- rep_len(w, n)

  resp_lower <- stats::runif(n) < .ddm_plower(v, a, w)
  q <- stats::runif(n)
  # The upper boundary is the lower one of the reflected process, so flipping
  # those draws leaves a single lower-boundary problem to solve.
  upper <- !resp_lower
  vf <- v; vf[upper] <- -v[upper]
  wf <- w; wf[upper] <- 1 - w[upper]
  pf <- .ddm_plower(vf, a, wf)
  ltarget <- log1p(-q) + log(pf)

  lo <- .ddm_tfloor(a, wf)
  Kmax <- .ddm_nterms(max(a), min(lo))
  # Starting guess for the fast responses, where the one-term inversion has
  # nothing to say: near t = 0 the far boundary is out of reach and the process
  # is a single-barrier hit at distance a w, driftless to first order, whose CDF
  # is 2 Phi(-a w / sqrt(t)). Inverting that puts Newton within a pass or two of
  # the root instead of the four to six it took from the floor.
  guess <- 2 * log((a * wf) / stats::qnorm(1 - pmin(q * pf, 0.999) / 2))

  rt <- numeric(n)
  todo <- seq_len(n)
  K <- min(.DDM_SERIES_K0, Kmax)
  repeat {
    final <- K >= Kmax
    m <- length(todo)
    tlo <- if (final) lo[todo] else pmax(lo[todo], .ddm_tmin(a[todo], K))
    llo <- log(tlo)
    pre <- .ddm_series(vf[todo], a[todo], wf[todo], K)
    if (final) {
      deep <- rep(FALSE, m)
    } else {
      # A root below this stage's floor needs more terms: those draws skip the
      # solve here rather than grind against the bracket edge. The final stage
      # has the true floor, below which the CDF is zero, so nothing is deep.
      s0 <- pre$pref * .colSums(pre$C * exp(-pre$R * rep(tlo, each = K)), K, m)
      deep <- !(log(s0) > ltarget[todo])
    }
    act <- which(!deep)
    if (length(act)) {
      sub <- if (length(act) < m) {
        list(C = pre$C[, act, drop = FALSE], R = pre$R[, act, drop = FALSE],
             pref = pre$pref[act], K = K, n = length(act))
      } else {
        pre
      }
      x <- .ddm_solve_series(sub, ltarget[todo[act]], llo[act], guess[todo[act]])
      if (final) {
        rt[todo[act]] <- exp(x)
      } else {
        # A root hugging the stage floor is only known to be at or below it -
        # the series is not trusted underneath - so it goes round again.
        ok <- x > llo[act] + log(1.5)
        rt[todo[act[ok]]] <- exp(x[ok])
        deep[act[!ok]] <- TRUE
      }
    }
    if (final || !any(deep)) break
    todo <- todo[deep]
    K <- min(K * .DDM_SERIES_GROW, Kmax)
  }
  list(rt = rt, response = as.numeric(upper))
}


# Decision-component sampler. Between-trial variability needs no special
# sampler: it *is* a hierarchical draw, so the per-trial drift, starting point
# and non-decision time are drawn and the ordinary 4-parameter process is run on
# top. The shift the mixture applies is added by `.rchoice()`, so the process
# here starts at zero.
#' @keywords internal
.ddm_rng <- function(n, p) {
  pars <- list(
    n = n,
    drift = p$mu,
    boundary = p$boundary,
    bias = p$bias,
    # Zero rather than `.DDM_TAU0`, unlike the density: that placeholder exists
    # only to get past rwiener()'s and dwiener()'s rejection of a zero
    # non-decision time, and this sampler has no such check to appease. Starting
    # at zero also leaves `draw_trialwise()` drawing the st0 offset on its own
    # scale, which is what gets added back below.
    ndt = numeric(n),
    sigmadrift = p$sigmadrift,
    sigmabias = p$sigmabias,
    sigmandt = p$sigmandt
  )
  if (.cogmod_ddm_has_variability(pars)) {
    pars <- .cogmod_ddm_draw_trialwise(pars)
  }
  sim <- .ddm_fpt_rng(n, v = pars$drift, a = pars$boundary, w = pars$bias)
  # `pars$ndt` carries the between-trial st0 offset and nothing else - the
  # family's own `ndt` is added by `.rchoice()`. It is exactly zero unless
  # `sigmandt` is free, so this costs nothing in the common case.
  list(rt = sim$rt + pars$ndt, response = sim$response)
}


# Stanvars ----------------------------------------------------------------

# The Stan literals are generated from `.DDM_TAU0` and `.DDM_WIENER_PRECISION`
# rather than written out, so the two implementations cannot end up shifted by
# different amounts. One sprintf() template per function, because R refuses a
# format string longer than 8192 characters; the 4- and 5-parameter density,
# .WFPT_STAN, is its own.
#' @keywords internal
.DDM_STAN_PRELUDE <- paste0(sprintf("
// The decision component: the Wiener density at the decision time. `w` is
// the starting point of whichever boundary is being scored, so the caller flips
// both it and the drift for the lower one.
//
// With the start-point and non-decision-time ranges both zero, that density is
// cogmod_wfpt_lpdf(), whether or not sigmadrift is estimated. Otherwise it is
// Stan's 7-parameter wiener_lpdf(), which integrates the ranges out by adaptive
// quadrature: 100 us per observation and gradient with one of them nonzero,
// about 160 with both at the tolerance .DDM_WIENER_PRECISION passes it
// (2026-09-18). The test is for *exact* zero, so an estimated sigmabias or
// sigmandt never takes the cheap path however small it gets; only fixing it in
// bf() does.
//
// The shift is applied by the mixture around this, so the diffusion's own
// non-decision time should be zero - but wiener_lpdf() rejects that outright,
// and the density depends on the time and the non-decision time only through
// their difference. So both are offset by the same %s, exactly as the R side
// offsets them (see .DDM_TAU0). It is a workaround for an argument check rather
// than an approximation: at that magnitude the offset cancels to the last bit.
//
// sigmabias is a fraction of the widest start-point range that keeps the start
// point inside the boundaries, so sw = sigmabias * fmin(2w, 2(1-w)) - which is
// the same number for w and 1 - w, as it must be. sigmandt is st0 itself, in
// the same unit as Y, with the shift as its lower bound.

// A cheap estimate of the log first-passage density, used only to keep Stan's
// 7-parameter wiener_lpdf() out of the region where its density underflows -
// never as the density itself. There that function returns -inf with NaN
// partial derivatives, and a NaN partial is not made harmless by the mixture
// weight on it being zero: reverse-mode multiplies the (zero) adjoint into the
// stored partial, and 0 * NaN is NaN, so a single such trial turns the gradient
// of the whole model to NaN. That is what \"Error evaluating model log
// probability: Non-finite gradient\" reports during a Pathfinder search, and
// it is also why such a fit collects divergent transitions - a proposal whose
// gradient is not finite is rejected as one.
//
// The two series Navarro & Fuss give for the driftless, unit-boundary density
// at rescaled time tau = t / boundary^2 are each exact in their own tail and a
// wild extrapolation outside it, so the smaller of the two leading terms is the
// one to believe. Integrating a normal drift out of the density is closed-form,
// so sv enters as a factor rather than as another series. The 7-parameter
// density averages over a start point spread across sw and a non-decision time
// spread across st0, so what matters there is whether *any* point of those
// ranges has a representable density. Each term is therefore taken at
// whichever end of each range makes it largest.
real cogmod_ddm_log_density_scale(real t, real v, real boundary, real w,
                                  real sv, real sw, real st0) {
  real w_lo = fmax(w - sw / 2, 1e-12);
  real w_hi = fmin(w + sw / 2, 1 - 1e-12);
  real t_lo = fmax(t - st0, 1e-12);
  real tau_hi = t / square(boundary);
  real tau_lo = t_lo / square(boundary);

  // The small-time term rises with the decision time and peaks at a start
  // point of sqrt(tau); the large-time term falls with the decision time and
  // peaks at the start point nearest the midpoint.
  real ws = fmin(fmax(sqrt(tau_hi), w_lo), w_hi);
  real small = log(ws) - square(ws) / (2 * tau_hi)
               - 0.5 * log(2 * pi() * tau_hi^3);
  real wl = fmin(fmax(0.5, w_lo), w_hi);
  real large = log(pi()) - square(pi()) * tau_lo / 2 + log(sin(pi() * wl));

  // The drift factor, which at sv = 0 is just exp(-v * boundary * w -
  // v^2 * t / 2). Dropping the -log(sqrt(1 + sv^2 t)) that goes with it only
  // makes the estimate larger, which is the harmless direction.
  real num = -square(v) * t_lo - 2 * v * boundary * (v > 0 ? w_lo : w_hi)
             + square(sv * boundary * w_hi);
  real drift = num / (2 * (1 + square(sv) * (num > 0 ? t_lo : t)));

  return -2 * log(boundary) + fmin(small, large) + drift;
}
", formatC(.DDM_TAU0, format = "g", digits = 17, width = 1)), .WFPT_STAN, sprintf("
real cogmod_ddm_decision_lpdf(real t, real v, real boundary, real w,
                              real sigmadrift, real sigmabias, real sigmandt) {
  real tau0 = %s;
  // Below the offset the Wiener density has underflowed to zero anyway, so
  // -inf is the answer to double precision as well as the safe one.
  if (t <= tau0) return negative_infinity();
  real sw = sigmabias * fmin(2 * w, 2 * (1 - w));

  // The 4- and 5-parameter forms: cogmod_wfpt_lpdf() is sound everywhere, so
  // nothing routes around it.
  if (sw == 0 && sigmandt == 0) {
    return cogmod_wfpt_lpdf(t | boundary, w, v, sigmadrift);
  }

  // The 7-parameter form returns -inf with NaN partials where its density
  // underflows. Where the estimate puts it below -600, the answer is that
  // -inf - only as a constant, which carries no partial derivatives to poison
  // the gradient with. The threshold stops over 100 log units short of
  // underflow (-745), far more slack than the estimate's error.
  if (cogmod_ddm_log_density_scale(t, v, boundary, w, sigmadrift, sw,
                                   sigmandt) < -600) {
    return negative_infinity();
  }
  real y = t + tau0;
  return wiener_lpdf(y | boundary, tau0, w, v, sigmadrift, sw, sigmandt, %s);
}
",
  formatC(.DDM_TAU0, format = "g", digits = 17, width = 1),
  formatC(.DDM_WIENER_PRECISION, format = "g", digits = 17, width = 1)
))


#' @keywords internal
.cogmod_ddm_lpdf <- function() {
  .choice_lpdf("cogmod_ddm")
}


#' @rdname rcogmod_ddm
#' @examples
#' \dontrun{
#' # Needs cmdstanr and a CmdStan toolchain, which live outside CRAN - see the
#' # package website to install them. Not run under R CMD check, which executes
#' # every example in one R session: once brms has fitted a model there (the
#' # cogmod_inits() and p_outlier() examples do), rstan is live in the process
#' # and loading an exposed Stan function next to it segfaults on Linux.
#' lpdf <- cogmod_ddm_lpdf_expose()
#' lpdf(
#'   Y = 0.5, mu = 0.5, boundary = 1, bias = 0.5, sigmadrift = 0,
#'   sigmabias = 0, sigmandt = 0, ndt = 0.2, poutlier = 0.02, dec = 1
#' )
#' }
#'
#' @export
cogmod_ddm_lpdf_expose <- function() {
  .choice_expose("cogmod_ddm")
}


#' @rdname rcogmod_ddm
#' @export
cogmod_ddm_stanvars <- function() {
  brms::stanvar(
    scode = .cogmod_ddm_lpdf(),
    block = "functions"
  )
}


# brms methods ------------------------------------------------------------

#' @rdname rcogmod_ddm
#' @inheritParams rcogmod_betagate
#' @export
log_lik_cogmod_ddm <- function(i, prep) {
  .log_lik_choice("cogmod_ddm", i, prep)
}


#' @rdname rcogmod_ddm
#' @inheritParams rcogmod_betagate
#' @importFrom brms get_dpar
#'
#' @details
#' # Predicting many observations at once
#'
#' `brms::posterior_predict()` calls `posterior_predict_cogmod_ddm()` once per
#' observation, each time with every draw's parameters, so a data set of a few
#' thousand trials means a few thousand calls of a sampler that is vectorised
#' across parameter sets and would rather take them all at once. About half of
#' each call is fixed cost, and the loop itself adds as much again. The method
#' therefore also accepts a *vector* of observation indices and returns their
#' draws stacked, the draws for `i[1]` first, so a posterior predictive check
#' can be built in a handful of calls instead:
#'
#' ```r
#' prep <- brms::prepare_predictions(fit, newdata = data, ndraws = 50)
#' # as brms::posterior_predict() does before its loop: linear predictors once
#' for (dp in names(prep$dpars)) prep$dpars[[dp]] <- brms::get_dpar(prep, dp)
#' chunks <- split(seq_len(prep$nobs), ceiling(seq_len(prep$nobs) / 50))
#' pp <- do.call(rbind, lapply(chunks, posterior_predict_cogmod_ddm, prep = prep))
#' pp[, 1]  # reaction times; pp[, 2] the choices
#' ```
#'
#' Chunks of about 50 observations are the sweet spot: the sampler sizes its
#' series for the fastest response it might have to describe, and the more
#' heterogeneous the parameters in a call, the longer that series. On 2,500
#' trials by 50 draws this runs in about a third of the time of
#' `posterior_predict()`. The other choice families' methods accept a vector
#' `i` in the same way.
#' @export
posterior_predict_cogmod_ddm <- function(i, prep, predict_outliers = NULL,
                                         ...) {
  .posterior_predict_choice("cogmod_ddm", i, prep, predict_outliers)
}


#' @rdname rcogmod_ddm
#' @inheritParams rcogmod_betagate
#' @export
posterior_epred_cogmod_ddm <- function(prep, predict_outliers = NULL) {
  mu <- brms::get_dpar(prep, "mu")
  boundary <- brms::get_dpar(prep, "boundary")
  bias <- brms::get_dpar(prep, "bias")
  ndt <- brms::get_dpar(prep, "ndt")
  sigmadrift <- brms::get_dpar(prep, "sigmadrift")
  sigmabias <- brms::get_dpar(prep, "sigmabias")
  sigmandt <- brms::get_dpar(prep, "sigmandt")

  # The closed form below is exact only for the classic 4-parameter DDM. There
  # is no simple one once the between-trial variability is switched on, so say
  # so rather than return an approximation silently. (`sigmandt` is the one
  # exception in principle - it shifts the mean by st0 / 2 - but the other two
  # do not, and warning about some of them and not others would be worse.)
  if (any(sigmadrift != 0) || any(sigmabias != 0) || any(sigmandt != 0)) {
    warning(
      "posterior_epred() for cogmod_ddm() uses a closed form that is exact ",
      "only for the classic 4-parameter DDM (sigmadrift = sigmabias = ",
      "sigmandt = 0). The between-trial variability parameters are non-zero ",
      "here, so these expected RTs are approximate. Use posterior_predict() ",
      "and summarise the draws for exact ones.",
      call. = FALSE
    )
  }

  # Unconditional mean first-passage time plus the non-decision time. Formula
  # adapted from https://doi.org/10.1016/j.jmp.2009.01.006, which takes the
  # starting point on the absolute scale: `bias` is a proportion of `boundary`,
  # so the quantity entering it is z = bias * boundary, not `bias` itself.
  z <- bias * boundary
  epred <- ndt - z / mu +
    boundary / mu * (exp(-2 * mu * z) - 1) / (exp(-2 * mu * boundary) - 1)

  # The expression has a removable singularity at mu = 0 (and loses precision to
  # cancellation near it). The limit is ndt + z * (boundary - z).
  near_zero <- abs(mu) < 1e-6
  if (any(near_zero)) {
    # `+ 0 * mu` recycles the limit to the shape of the draws x observations
    # matrix, whatever mix of scalar and matrix dpars was supplied.
    lim <- ndt + z * (boundary - z) + 0 * mu
    epred[near_zero] <- lim[near_zero]
  }

  if (!.predict_outliers(predict_outliers, prep)) {
    return(epred)
  }
  poutlier <- brms::get_dpar(prep, "poutlier")
  (1 - poutlier) * epred + poutlier * .mcontam()
}

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.