Nothing
#' @title Two-Accumulator Racing Diffusion Model (RDM)
#'
#' @description
#' The Racing Diffusion Model (RDM) treats a choice as a race between two
#' diffusion processes, one per response option, each accumulating evidence at
#' its own rate until it reaches a common threshold. The winner determines both
#' the observed reaction time and the choice. 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 race.
#'
#' Functions:
#' - `rcogmod_rdm()`: Simulates random draws from the RDM.
#' - `dcogmod_rdm()`: Computes the density (likelihood).
#' - `pcogmod_rdm()`: Computes the CDF of the reaction time, marginally over the
#' choice or defectively for one response.
#' - `qcogmod_rdm()`: Computes the corresponding quantiles.
#' - `cogmod_rdm()`: Creates a `brms::custom_family()` for use in `brms` models.
#' - `cogmod_rdm_stanvars()`: Generates the `stanvars` to pass to `brm()`.
#' - `p_outlier()`: Per-trial posterior probability of being an outlier.
#'
#' @details
#' # Parameterization
#'
#' Each accumulator is a diffusion with drift rate `v` and unit diffusion
#' coefficient, starting from a point `z ~ Uniform(0, bias)` drawn afresh on
#' every trial and finishing when it reaches the threshold `b = boundary + bias`.
#' The distance it has to cover is therefore `b - z = boundary + bias - z`,
#' which is what makes `boundary` the threshold *offset*: the distance from the
#' highest possible starting point to the threshold. Its first passage time is
#' Wald (inverse Gaussian) with the start point integrated out. The observed
#' reaction time is `ndt + min(T_0, T_1)` and the observed choice is whichever
#' accumulator got there first.
#'
#' This is the `B` parameterization of `DMC` and `EMC2`, where `b = B + A` with
#' `A` the start-point range (`bias` here). It is used for a reason rather than for taste: the
#' threshold has to sit above the highest possible starting point, and writing
#' the *offset* makes `b > A` hold automatically for any positive value. The
#' alternative - estimating the absolute threshold, as `rtdists` does - needs an
#' order constraint between two estimated parameters, which has to hold in every
#' cell of the design once either of them carries a predictor. The cost is that
#' `boundary` alone is not the quantity to read off a fitted model; `boundary +
#' bias` is.
#'
#' A drift rate of **exactly zero is allowed**, and is not the same as an
#' accumulator that never responds: driftless Brownian motion still reaches any
#' positive level with probability one, so a zero-drift accumulator is slow but
#' still finishes, and can still win the race.
#'
#' A start-point range of **exactly zero is allowed** too, and is a model rather
#' than a degenerate parameter: both accumulators then start at `0` on every
#' trial and the race is between two plain Walds - equation 2 of Tillman et al.
#' (2020), which is the limit the density already takes. [cogmod_lba1()] and
#' [cogmod_lba2()] have always allowed it. Note that this does not make the
#' `sigmabias` direction any better identified - see Fitting below.
#'
#' `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 race parameters. Expressing it directly is what
#' avoids that.
#'
#' # 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. That is what makes the direct parameterization of
#' `ndt` workable without taking a bound from the data.
#'
#' 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`. The half Normal is used for the
#' timing because it is **flat at the origin** (zero derivative), so the very
#' fastest responses - the ones least plausibly decisions - are not starved of
#' density, and because it dies fast enough above that range to leave the slow
#' tail to the race itself rather than claiming it.
#'
#' `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.
#'
#' # Fitting
#'
#' ```r
#' f <- brms::bf(RT | dec(Error) ~ Condition, driftone ~ Condition,
#' sigmabias ~ 1, boundary ~ 1, ndt ~ 1, poutlier ~ 1,
#' family = cogmod_rdm())
#' brms::brm(f, data = df,
#' prior = cogmod_priors(f, df),
#' init = cogmod_inits(f, df),
#' stanvars = cogmod_stanvars(f))
#' ```
#'
#' The `brms` family names the drift of the first accumulator `mu` (as `brms`
#' requires) and that of the second `driftone`, and calls the start-point range
#' `sigmabias` to match [cogmod_lba2()], where it denotes the same quantity. Note
#' that this is *not* the same thing as `bias` in [cogmod_ddm()], which is a
#' relative starting point in `[0, 1]`. Both drifts use a `softplus` link with a
#' lower bound of zero, following [cogmod_invgaussian()]: a Wald drift must be
#' non-negative for the accumulator to be a proper first passage time.
#'
#' 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 race parameters with no gradient at all. It also
#' starts `driftone` at a third of `mu`'s drift rather than equal to it: a
#' Wald density is thin on the fast side and flat on the slow side, so an
#' error accumulator started too fast sits hundreds of log-density units above
#' the posterior, and a cold chain's first trajectory can convert that into a
#' run down the flat `driftone` direction from which it never returns. On the
#' benchmark data of the [performance article](https://dominiquemakowski.com/cogmod/articles/performance.html) that froze one chain in four;
#' the slower start removed it.
#'
#' [cogmod_priors()] is not a convenience here either. Beyond `ndt` and
#' `poutlier`, `sigmabias` and `boundary` are only weakly identified from each
#' other, because they enter the threshold only through the sum
#' `b = boundary + sigmabias` and trade off almost freely: on simulated data with
#' 4000 trials the profile log-likelihood varies by only about 3 units as
#' `sigmabias` ranges from 0 to half the threshold, while `boundary` slides to
#' compensate. With flat priors the sampler tends to wander down the
#' `sigmabias -> 0` ridge (the plain Wald race) and produce divergent
#' transitions, and a `softplus` link reaches zero only at minus infinity - a
#' flat prior over an unbounded flat region, which is an improper posterior.
#' That the endpoint is now a legal parameter value does not help: the link
#' never reaches it, so the flat direction is as long as it ever was.
#' [cogmod_priors()] fences both off, exactly as it does for [cogmod_lba1()],
#' which shares this parameterisation.
#'
#' The sum `boundary + sigmabias` is well identified either way, so it is the
#' more trustworthy quantity to interpret and to compare across conditions. The
#' same caveat applies to [cogmod_lba2()].
#'
#' The error accumulator's drift has a flat direction of its own. A drift of
#' zero is legitimate - driftless Brownian motion still finishes, and still
#' wins sometimes - but once `driftone` is a few hundredths the likelihood stops
#' changing, while the `softplus` link puts that whole region at minus
#' infinity. Left flat, the two-participant data of the
#' [decision-making article](https://dominiquemakowski.com/cogmod/articles/decision_making.html),
#' whose Accuracy condition carries about 75 errors, ran it down to 0.0001 with
#' half of the transitions divergent. [cogmod_priors()] fences it with
#' `normal(3, 2)`, and `normal(0, 2)` on its slopes. That prior sits well above
#' the floor on purpose. Under `dec(Error)`, the coding every example here
#' uses, `driftone` is the *error* accumulator, and wherever errors are rare
#' its posterior will land in the prior's lower tail. That is the fence
#' working, not a prior at odds with the data: nothing the model predicts
#' depends on where on the plateau the drift sits, and priors centred lower
#' were measured to cost sampling efficiency without changing the fit. If the
#' *rarely* chosen option is the one on `mu`, mirror that prior onto `mu` by
#' hand.
#'
#' # Predictions exclude the outlier component
#'
#' `posterior_predict()` describes the **race 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.
#'
#' `posterior_epred()` is not provided: for a race model the expectation needs
#' numerical integration per draw and per observation, and users are better off
#' summarising `posterior_predict()` draws.
#'
#' @param n Number of simulated trials. If `length(n) > 1`, the length is taken
#' to be the number required.
#' @param vzero,vone Drift rates of the two accumulators (choice 0 and 1). Must
#' be non-negative; larger means faster. Zero is allowed - such an accumulator
#' is slow, but it still finishes, and can still win. Range: `[0, Inf)`.
#' @param boundary Threshold offset, `boundary = b - bias`, where `b` is the
#' decision threshold and `bias` the maximum starting point. Must be positive.
#' @param bias Maximum starting point. The starting point of each accumulator on
#' each trial is drawn from `Uniform(0, bias)`. Must be non-negative; zero is
#' allowed and gives the plain Wald race, in which both accumulators start at
#' `0` on every trial. Range: `[0, Inf)`. Called `sigmabias` in the `brms`
#' family, to match [cogmod_lba2()].
#' @param ndt Non-decision time (shift parameter), in seconds. Represents the
#' time taken for processes unrelated to the decision (e.g., encoding, motor
#' response). Must be non-negative. Range: `[0, Inf)`.
#' @param poutlier Proportion of responses generated by the outlier process
#' rather than by the race. Range: `[0, 1]`. At `poutlier = 0` the
#' distribution reduces to the plain shifted RDM.
#'
#' @return `rcogmod_rdm()` returns a data frame with `n` rows and two columns:
#' \item{rt}{The simulated reaction time.}
#' \item{response}{The winning accumulator, coded `0` for `vzero` and `1` for
#' `vone`, matching the `dec()` coding used by the `brms` families.}
#'
#' `dcogmod_rdm()` returns the density at each element of `x` - the log
#' density if `log = TRUE` - `pcogmod_rdm()` the cumulative probability at
#' each element of `q`, and `qcogmod_rdm()` the quantile at each element of
#' `p`, in seconds. With a `response` the latter two are defective, i.e.
#' scaled to that response's own probability rather than to one. All are
#' numeric vectors, recycled to the length of the longest argument.
#' `cogmod_rdm()` returns a `brms::custom_family` object, to put on a
#' `brms::bf()` formula. `cogmod_rdm_stanvars()` returns a `brms::stanvars`
#' object holding the family's Stan `functions` block, to pass to
#' `brms::brm()`, and `cogmod_rdm_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_rdm()` returns a numeric
#' vector holding one log-likelihood value per posterior draw for observation
#' `i`, and `posterior_predict_cogmod_rdm()` a draws x 2 matrix of reaction
#' times and choices simulated for observation `i`.
#' `posterior_epred_cogmod_rdm()` returns nothing: the expected reaction time
#' of a race has no closed form, so it errors rather than report one -
#' summarise `posterior_predict()` draws instead.
#'
#' @references
#' - Michael, J. R., Schucany, W. R., & Haas, R. W. (1976). Generating Random Variates Using
#' Transformations with Multiple Roots. *The American Statistician*, *30*(2), 88-90. \doi{10.2307/2683801}
#' - Tillman, G., Van Zandt, T., & Logan, G. D. (2020). Sequential sampling models
#' without random between-trial variability: The racing diffusion model of
#' speeded decision making. *Psychonomic Bulletin & Review*, *27*, 911-936.
#' \doi{10.3758/s13423-020-01719-6}
#' - Folks, J. L., & Chhikara, R. S. (1978). The inverse Gaussian distribution and its
#' statistical application-a review. *Journal of the Royal Statistical Society Series B:
#' Statistical Methodology*, *40*(3), 263-275.
#'
#' @seealso [rcogmod_invgaussian()], [rcogmod_lnr()]
#'
#' @examples
#' # Simulate data, with 2% of trials from the outlier process
#' data <- rcogmod_rdm(1000,
#' vzero = 2.5, vone = 1.6, boundary = 0.5, bias = 0.2,
#' ndt = 0.2, poutlier = 0.02
#' )
#' head(data)
#'
#' # Responses faster than ndt keep positive density, unlike the unmixed model
#' dcogmod_rdm(0.1, ndt = 0.2, response = 0, poutlier = 0.02)
#' dcogmod_rdm(0.1, ndt = 0.2, response = 0, poutlier = 0)
#'
#' # Defective CDF of one response: at q = Inf it is that response's probability
#' pcogmod_rdm(c(0.4, 0.6, Inf), vzero = 2.5, vone = 1.6, response = 0)
#'
#' # The RT quantiles of each response, for a quantile-probability plot
#' sapply(0:1, function(k) {
#' qcogmod_rdm(c(0.1, 0.3, 0.5, 0.7, 0.9),
#' vzero = 2.5, vone = 1.6, response = k, scale_p = TRUE
#' )
#' })
#'
#' @export
rcogmod_rdm <- function(n, vzero = 3, vone = 2, boundary = 0.5, bias = 0.2,
ndt = 0.2, poutlier = 0) {
.rchoice("cogmod_rdm", n = n, ndt = ndt, poutlier = poutlier, mu = vzero, driftone = vone, sigmabias = bias, boundary = boundary)
}
#' @rdname rcogmod_rdm
#' @param x The observed reaction time (RT).
#' @param response Accumulator whose finishing time is being scored: `0` for the
#' `vzero` accumulator, `1` for the `vone` accumulator. This gives the
#' *defective* density `f_response(x) * S_other(x)`, mixed with the outlier
#' component, which is what a race likelihood needs. The default `NULL`
#' instead returns the *marginal* density of the RT, ignoring which
#' accumulator won - the sum of the two.
#' @param log Logical; if TRUE, returns the log-density. Default: FALSE.
#' @export
dcogmod_rdm <- function(x, vzero = 3, vone = 2, boundary = 0.5, bias = 0.2,
ndt = 0.2, response = NULL, poutlier = 0, log = FALSE) {
if (is.null(response)) {
# The marginal is the sum of the two defective densities. The outlier
# component's 1 / K sums back to 1 over the options, so what comes out is
# the plain mixture of the half Normal with the marginal race density.
per_k <- lapply(c(0, 1), function(k) {
dcogmod_rdm(x, vzero = vzero, vone = vone, boundary = boundary,
bias = bias, ndt = ndt, response = k, poutlier = poutlier,
log = TRUE)
})
out <- .log_add_exp(per_k[[1]], per_k[[2]])
return(if (log) out else exp(out))
}
.dchoice("cogmod_rdm", x = x, response = response, ndt = ndt,
poutlier = poutlier, log = log,
mu = vzero, driftone = vone, sigmabias = bias, boundary = boundary)
}
#' @rdname rcogmod_rdm
#' @param q Vector of quantiles (reaction times).
#' @param lower.tail If `TRUE` (default) return `P(RT <= q)`, otherwise the
#' survival `P(RT > q)`. With a `response`, both are defective - see Details.
#' @param log.p If `TRUE`, probabilities are returned on the log scale.
#' @details
#' `pcogmod_rdm()` with `response = NULL` (the default) describes the RT of the
#' trial as a whole - whichever accumulator wins, and whether or not the trial
#' came from the outlier component - since `P(min(T0, T1) > q) = S0(q) * S1(q)`.
#' That is a closed form and is exact.
#'
#' With a `response`, it returns the **defective** CDF
#' `P(RT <= q, choice = response)`, which is what a defective-CDF or
#' quantile-probability plot needs. It does not reach one: its limit is the
#' probability of that response, which `pcogmod_rdm(Inf, response = k)` gives.
#' There is no closed form for it, so it is obtained by quadrature over the
#' defective density: accurate to about `1e-8` rather than to machine precision,
#' and about ten times slower per element (roughly 3 ms against 0.3 ms), since
#' the marginal is a vectorised closed form and this is a loop.
#' `lower.tail = FALSE` integrates the upper side directly rather than
#' subtracting, so the defective survival stays accurate into the tail.
#' @export
pcogmod_rdm <- function(q, vzero = 3, vone = 2, boundary = 0.5, bias = 0.2,
ndt = 0.2, poutlier = 0, response = NULL,
lower.tail = TRUE, log.p = FALSE) {
# `response` is required alongside `x` by `.prepare_choice()`, but plays no
# part in the RT distribution marginally over the choice, so a placeholder
# goes in and is never read.
params <- .prepare_choice("cogmod_rdm", x = q,
response = if (is.null(response)) 0 else response,
ndt = ndt, poutlier = poutlier,
mu = vzero, driftone = vone,
sigmabias = bias, boundary = boundary)
if (!is.null(response)) {
pr <- .rdm_pdefective(params, lower.tail = lower.tail)
return(if (log.p) log(pr) else pr)
}
# Survival of the race: P(min(T0, T1) > q) = S0(q) * S1(q), carried in log
# space because each factor underflows to exactly zero long before the product
# is genuinely negligible.
logS_dec <- .swald(params$x, params$mu, params$boundary, params$sigmabias,
params$ndt, log.p = TRUE) +
.swald(params$x, params$driftone, params$boundary, params$sigmabias,
params$ndt, log.p = TRUE)
# Survival of the half-Normal outlier component, on the same scale. Which
# choice the contaminant makes is irrelevant here: the 1 / K sums back to 1
# over the response options.
logS_out <- log(2) + stats::pnorm(params$x / .POUTLIER_SCALE,
lower.tail = FALSE, log.p = TRUE)
logS_out[params$x <= 0] <- 0
# Clamped because a survival cannot exceed one: at `q <= 0` both components
# are exactly log(1), and `.log_mix()` lands 2e-17 above zero there rather
# than on it, which turns `.log1m_exp()` into NaN instead of the -Inf it
# should be.
logS <- pmin(.log_mix(params$poutlier, logS_out, logS_dec), 0)
out <- if (lower.tail) .log1m_exp(logS) else logS
# `.log_mix()` sends a missing value to -Inf, which would surface here as a
# CDF of exactly 1 - the one answer a missing input must not give. The
# defective branch above propagates NA, so this one has to as well.
out[is.na(params$x)] <- NA_real_
if (log.p) out else exp(out)
}
#' @rdname rcogmod_rdm
#' @param p Vector of probabilities. With `response = NULL` these are ordinary
#' probabilities of the marginal RT distribution. With a `response` they are
#' read off the *defective* CDF unless `scale_p = TRUE`, so they must be below
#' the probability of that response; anything above it has no quantile and
#' comes back `NA` with a warning.
#' @param scale_p Logical. If `TRUE`, `p` is taken as a fraction of the chosen
#' response's own probability rather than of the whole distribution, so that
#' `p = 0.5` is that response's median. This is what a quantile-probability
#' plot wants. Ignored when `response` is `NULL`. Default `FALSE`.
#' @param interval Length-2 numeric giving the initial bracket, in seconds, for
#' the root search. The upper end is doubled until it covers the requested
#' probability, so this only affects speed.
#' @details
#' `qcogmod_rdm()` inverts `pcogmod_rdm()` by root-finding, and so inherits its
#' quadrature error where a `response` is given. It is the natural way to get
#' the RT quantiles of each response for a quantile-probability plot: ask for
#' `p = c(0.1, 0.3, 0.5, 0.7, 0.9)` with `scale_p = TRUE`, once per response.
#' @export
qcogmod_rdm <- function(p, vzero = 3, vone = 2, boundary = 0.5, bias = 0.2,
ndt = 0.2, poutlier = 0, response = NULL,
scale_p = FALSE, lower.tail = TRUE, log.p = FALSE,
interval = c(0, 10)) {
if (log.p) p <- exp(p)
if (!lower.tail) p <- 1 - p
params <- .prepare_choice("cogmod_rdm", x = p,
response = if (is.null(response)) 0 else response,
ndt = ndt, poutlier = poutlier,
mu = vzero, driftone = vone,
sigmabias = bias, boundary = boundary)
if (!is.numeric(interval) || length(interval) != 2 || anyNA(interval) ||
interval[1] < 0 || interval[2] <= interval[1]) {
stop("`interval` must be two increasing non-negative numbers.",
call. = FALSE)
}
cdf <- function(q, i) {
one <- lapply(params[.RDM_PAR_NAMES], function(v) v[i])
one$x <- q
if (is.null(response)) {
# The closed form, reached through the same argument path users take.
do.call(pcogmod_rdm, list(q = q, vzero = one$mu, vone = one$driftone,
boundary = one$boundary, bias = one$sigmabias,
ndt = one$ndt, poutlier = one$poutlier))
} else {
.rdm_pdefective(one, lower.tail = TRUE)
}
}
m <- params$ndraws
out <- rep(NA_real_, m)
if (m == 0) return(out)
target <- params$x
# The attainable mass. One is exact for the marginal; for a defective CDF it
# is that response's probability, and it costs one more quadrature call.
pmax_i <- if (is.null(response)) rep(1, m) else vapply(seq_len(m), function(i)
cdf(Inf, i), numeric(1))
if (scale_p && !is.null(response)) target <- target * pmax_i
bad <- is.na(target) | target < 0 | target > 1
over <- !bad & target > pmax_i
if (any(over)) {
warning("`p` exceeds the attainable probability for ",
if (is.null(response)) "the distribution" else "this response",
"; returning NA.", call. = FALSE)
}
out[!bad & target <= 0] <- 0
# The supremum is only reached in the limit, so ask for it and get Inf back
# rather than whatever finite number the root search happened to stop at.
out[!bad & !over & target >= pmax_i] <- Inf
todo <- which(!bad & !over & target > 0 & target < pmax_i)
for (i in todo) {
lo <- interval[1]
hi <- interval[2]
# Double the bracket rather than trusting the default: `ndt` alone can sit
# above it, and a slow accumulator's upper quantiles run well past 10 s.
tries <- 0L
while (cdf(hi, i) < target[i] && tries < 40L) {
lo <- hi
hi <- hi * 2
tries <- tries + 1L
}
if (cdf(hi, i) < target[i]) next # left as NA; unreachable in practice
out[i] <- stats::uniroot(function(z) cdf(z, i) - target[i],
lower = lo, upper = hi,
tol = .Machine$double.eps^0.5)$root
}
out
}
# Family ------------------------------------------------------------------
#' @rdname rcogmod_rdm
#' @param link_mu,link_driftone Link functions for the two drift rates. `mu` is
#' `vzero`: `brms` requires the first distributional parameter of a custom
#' family to be called `mu`, so that is the name the formula and this argument
#' use, and the drift of accumulator 0 is what it means.
#' @param link_sigmabias,link_boundary Link functions for the start-point range
#' and the threshold offset.
#' @param link_ndt,link_poutlier Link functions for the non-decision time and
#' the outlier rate.
#' @param predict_outliers Logical; whether `posterior_predict()` should include
#' the outlier component. `FALSE` (the default) fixes `poutlier` to zero for
#' prediction, so predictions describe the race alone; the likelihood is
#' always the full mixture either way. On the prediction method itself the
#' default is `NULL`, which defers to the flag carried on the model - see
#' [with_outliers()] to change it after fitting. See Details.
#' @export
cogmod_rdm <- function(
link_mu = "softplus",
link_driftone = "softplus",
link_sigmabias = "softplus",
link_boundary = "softplus",
link_ndt = "log",
link_poutlier = "logit",
predict_outliers = FALSE
) {
.choice_family(
"cogmod_rdm",
links = c(link_mu, link_driftone, link_sigmabias, link_boundary),
predict_outliers = predict_outliers
)
}
# Internals ---------------------------------------------------------------
# Log-space building blocks -----------------------------------------------
#
# The Wald-with-uniform-start-point density and survival are both *difference
# quotients in the threshold* `b`: writing `b = boundary + bias`, the start point
# `z ~ U(0, bias)` means
#
# f_A(t) = (1/bias) * Integral_{boundary}^{boundary+bias} f_Wald(t; b) db
# S_A(t) = (1/bias) * Integral_{boundary}^{boundary+bias} S_Wald(t; b) db
#
# so both take the form `[G(boundary + bias) - G(boundary)] / bias`. That structure drives
# every numerical choice below:
#
# * the whole computation is carried in log space, because for moderate drift
# the individual terms underflow to zero long before the answer does (at
# drift 3 the survival hits exactly 0 by t = 12, while its true value is
# 4e-26);
# * `exp(2 * drift * b) * Phi(.)` is evaluated as `exp(2 * drift * b + lcdf)`,
# since the product is representable when neither factor is;
# * as `bias / sqrt(t)` shrinks the difference quotient cancels, so we fall
# back to the plain Wald evaluated at the *midpoint* threshold
# `b = boundary + bias / 2`, which is second-order accurate and therefore exact to
# double precision well before cancellation sets in.
# Smallest `bias / sqrt(t)` handled by the exact difference; below this the
# midpoint (plain Wald) limit is both cheaper and more accurate.
.RDM_EPS_A <- 1e-4
# Below this |drift| the survival's 1 / (2 * drift) factor is replaced by its
# driftless limit. Measured crossover between the two errors is near 3e-8.
.RDM_EPS_V <- 1e-7
#' log(exp(x) + exp(y)), stable
#' @noRd
.log_add_exp <- function(x, y) {
m <- pmax(x, y)
out <- m + log(exp(x - m) + exp(y - m))
out[is.infinite(m) & m < 0] <- -Inf
out
}
#' log(exp(x) - exp(y)) for x >= y, stable (reuses `.log1m_exp`)
#'
#' `y >= x` collapses to `-Inf` rather than `NaN`; the guard is applied *before*
#' evaluating `.log1m_exp()` so a masked-out element cannot raise a warning.
#'
#' @noRd
.log_sub_exp <- function(x, y) {
n <- max(length(x), length(y))
x <- rep_len(x, n)
y <- rep_len(y, n)
out <- rep(-Inf, n)
bad <- is.na(x) | is.na(y)
ok <- !bad & (y < x)
if (any(ok)) {
out[ok] <- x[ok] + .log1m_exp(y[ok] - x[ok])
}
out[bad] <- NA_real_
out
}
#' Signed log-domain sum
#'
#' Given terms as (log-magnitude, sign) pairs, returns the log-magnitude and
#' sign of their sum. Used to assemble the density (2 terms) and survival
#' (6 terms), each of which mixes signs but is known to be positive overall.
#'
#' @noRd
.log_sum_signed <- function(logs, signs) {
n <- length(logs[[1]])
acc_l <- rep(-Inf, n)
acc_s <- rep(0, n)
for (i in seq_along(logs)) {
li <- logs[[i]]
si <- signs[[i]]
li[si == 0 | is.na(li)] <- -Inf
si[is.na(si)] <- 0
new_l <- rep(-Inf, n)
new_s <- numeric(n)
# Same sign (or either term vanishing): magnitudes add.
same <- (acc_s == si) | (acc_s == 0) | (si == 0)
if (any(same)) {
new_l[same] <- .log_add_exp(acc_l[same], li[same])
new_s[same] <- ifelse(acc_s[same] != 0, acc_s[same], si[same])
}
# Opposite signs: subtract the smaller magnitude, keep the larger's sign.
op <- !same
if (any(op)) {
keep_acc <- acc_l[op] >= li[op]
new_l[op] <- .log_sub_exp(
pmax(acc_l[op], li[op]),
pmin(acc_l[op], li[op])
)
new_s[op] <- ifelse(keep_acc, acc_s[op], si[op])
}
new_s[is.infinite(new_l) & new_l < 0] <- 0
acc_l <- new_l
acc_s <- new_s
}
list(log = acc_l, sign = acc_s)
}
#' Stable `log(u * Phi(u) + phi(u))`
#'
#' This is `log Integral_{-Inf}^{u} Phi(s) ds`, the antiderivative that appears
#' when integrating the Wald survival over the threshold. For very negative `u`
#' both terms underflow *and* they cancel to order `u^-2`, so we factor out
#' `phi(u)` and expand `1 - |u| * MillsRatio(|u|)` asymptotically.
#'
#' @noRd
.log_gfun <- function(u) {
out <- numeric(length(u))
# Seam at -10: the direct form still cancels only ~100-fold there, while the
# series has converged to ~1e-12, so the two agree to well past what the
# likelihood needs.
hi <- u > -10
if (any(hi)) {
uh <- u[hi]
out[hi] <- log(uh * stats::pnorm(uh) + stats::dnorm(uh))
}
lo <- !hi
if (any(lo)) {
x2 <- u[lo]^2
s <- 0
term <- rep(1, length(x2))
for (j in seq_len(12)) {
term <- term * (2 * j - 1) / x2
s <- if (j %% 2 == 1) s + term else s - term
}
out[lo] <- stats::dnorm(u[lo], log = TRUE) + log(s)
}
out
}
#' Stable `log(Phi(b) - Phi(a))` for `b >= a`
#'
#' Picks whichever tail keeps both arguments away from a saturating normal CDF.
#'
#' @noRd
.log_diff_pnorm <- function(a, b) {
out <- numeric(length(a))
up <- a >= 0
if (any(up)) {
out[up] <- .log_sub_exp(
stats::pnorm(a[up], lower.tail = FALSE, log.p = TRUE),
stats::pnorm(b[up], lower.tail = FALSE, log.p = TRUE)
)
}
dn <- b <= 0
if (any(dn)) {
out[dn] <- .log_sub_exp(
stats::pnorm(b[dn], log.p = TRUE),
stats::pnorm(a[dn], log.p = TRUE)
)
}
mid <- !up & !dn # straddles zero: both probabilities are O(1)
if (any(mid)) {
out[mid] <- log(stats::pnorm(b[mid]) - stats::pnorm(a[mid]))
}
out
}
# Wald with uniform start point: log density and log survival --------------
#' Log density of the first passage time `t` (already net of non-decision time)
#'
#' @param t Decision time, `> 0`.
#' @param nu Drift rate.
#' @param k Threshold offset `boundary`.
#' @param A Start point range `bias` (`>= 0`).
#' @noRd
.wald_lpdf_core <- function(t, nu, k, A) {
st <- sqrt(t)
# Small start-point range (or large t): plain Wald at the midpoint threshold.
small <- (A / st) < .RDM_EPS_A
out <- numeric(length(t))
if (any(small)) {
b <- k[small] + A[small] / 2
ts <- t[small]
out[small] <- log(b) -
0.5 * (log(2 * pi) + 3 * log(ts)) -
(b - nu[small] * ts)^2 / (2 * ts)
}
gen <- !small
if (any(gen)) {
tg <- t[gen]
stg <- st[gen]
nug <- nu[gen]
kg <- k[gen]
Ag <- A[gen]
alpha <- (kg - nug * tg) / stg
beta <- (kg + Ag - nug * tg) / stg
# T1 = drift * (Phi(beta) - Phi(alpha))
l1 <- log(abs(nug)) + .log_diff_pnorm(alpha, beta)
s1 <- sign(nug)
# T2 = (phi(alpha) - phi(beta)) / sqrt(t); phi is even, so the sign is
# decided by which argument is closer to zero.
lpa <- stats::dnorm(alpha, log = TRUE)
lpb <- stats::dnorm(beta, log = TRUE)
s2 <- ifelse(abs(alpha) <= abs(beta), 1, -1)
l2 <- ifelse(
s2 > 0,
.log_sub_exp(lpa, lpb),
.log_sub_exp(lpb, lpa)
) -
log(stg)
res <- .log_sum_signed(list(l1, l2), list(s1, s2))
out[gen] <- res$log - log(Ag)
}
out
}
#' Log survival of the first passage time `t` (already net of non-decision time)
#'
#' Uses the closed-form antiderivative of the Wald survival in the threshold,
#' rather than `log(1 - CDF)`, which underflows to `-Inf` at ordinary parameter
#' values and would stall the sampler with a zero gradient.
#'
#' @inheritParams .wald_lpdf_core
#' @noRd
.wald_lccdf_core <- function(t, nu, k, A) {
st <- sqrt(t)
out <- numeric(length(t))
# --- Small start-point range: plain Wald survival at the midpoint. ---
small <- (A / st) < .RDM_EPS_A
if (any(small)) {
b <- k[small] + A[small] / 2
ts <- t[small]
sts <- st[small]
nus <- nu[small]
l1 <- stats::pnorm((b - nus * ts) / sts, log.p = TRUE)
l2 <- 2 * nus * b + stats::pnorm(-(b + nus * ts) / sts, log.p = TRUE)
out[small] <- .log_sub_exp(l1, l2)
}
gen <- !small
if (any(gen)) {
tg <- t[gen]
stg <- st[gen]
nug <- nu[gen]
kg <- k[gen]
Ag <- A[gen]
bg <- kg + Ag
alpha <- (kg - nug * tg) / stg
beta <- (bg - nug * tg) / stg
# `res` accumulates log(S * A); the shared 1 / A is divided out at the end.
res <- rep(NA_real_, length(tg))
# --- Driftless limit: S = 1 + (2 sqrt(t) / A) * (g(beta0) - g(alpha0)). ---
# This form already carries its own 1 / A, so log(A) is added back to keep
# it on the same `log(S * A)` footing as the general branch below.
z <- abs(nug) < .RDM_EPS_V
if (any(z)) {
a0 <- -kg[z] / stg[z]
b0 <- -bg[z] / stg[z]
lgap <- .log_sub_exp(.log_gfun(a0), .log_gfun(b0))
res[z] <- .log_sum_signed(
list(rep(0, sum(z)), log(2) + log(stg[z]) - log(Ag[z]) + lgap),
list(rep(1, sum(z)), rep(-1, sum(z)))
)$log +
log(Ag[z])
}
# --- General case: six signed terms, positive overall. ---
g <- !z
if (any(g)) {
tt <- tg[g]
stt <- stg[g]
nn <- nug[g]
kk <- kg[g]
AA <- Ag[g]
bb <- bg[g]
al <- alpha[g]
be <- beta[g]
sv <- sign(nn)
linv <- -log(2 * abs(nn)) # log(1 / (2 |drift|))
wa <- -(kk + nn * tt) / stt
wb <- -(bb + nn * tt) / stt
logs <- list(
0.5 * log(tt) + .log_gfun(be), # + sqrt(t) g(beta)
0.5 * log(tt) + .log_gfun(al), # - sqrt(t) g(alpha)
linv + 2 * nn * bb + stats::pnorm(wb, log.p = TRUE),
linv + 2 * nn * kk + stats::pnorm(wa, log.p = TRUE),
linv + stats::pnorm(be, log.p = TRUE),
linv + stats::pnorm(al, log.p = TRUE)
)
m <- length(tt)
signs <- list(
rep(1, m),
rep(-1, m),
-sv,
sv,
-sv,
sv
)
res[g] <- .log_sum_signed(logs, signs)$log
}
out[gen] <- res - log(Ag)
}
pmin(out, 0)
}
#' Analytical PDF for Wald with Uniform Start Point Variability
#'
#' Calculates the probability density function (PDF) for the time it takes a
#' diffusion process with drift `drift`, starting point `z ~ U(0, bias)`, to reach
#' threshold `b = boundary + bias`, shifted by `ndt`. Based on Tillman et al. (2020).
#' This function calculates the density for the *unadjusted* time `x`.
#'
#' @noRd
.dwald <- function(x, drift, boundary, bias, ndt, log = FALSE) {
n <- length(x)
if (!all(lengths(list(drift, boundary, bias, ndt)) == n)) {
stop("All inputs must be numeric vectors of the same length.")
}
out <- rep(NA_real_, n)
invalid <- is.na(x) |
is.na(drift) |
is.na(boundary) |
is.na(bias) |
is.na(ndt) |
(boundary <= 0) |
(bias < 0) |
(ndt < 0)
ok <- !invalid
if (any(ok)) {
t_adj <- x[ok] - ndt[ok]
res <- rep(-Inf, sum(ok)) # zero density at or before the non-decision time
live <- t_adj > 0
if (any(live)) {
res[live] <- .wald_lpdf_core(
t_adj[live],
drift[ok][live],
boundary[ok][live],
bias[ok][live]
)
}
out[ok] <- res
}
if (log) out else exp(out)
}
#' Analytical survival function for Wald with Uniform Start Point Variability
#'
#' Complement of `.pwald()`, computed directly rather than as `1 - CDF`. See the
#' note above `.wald_lccdf_core()` for why that distinction matters.
#'
#' @noRd
.swald <- function(x, drift, boundary, bias, ndt, log.p = FALSE) {
n <- length(x)
if (!all(lengths(list(drift, boundary, bias, ndt)) == n)) {
stop("All inputs must be numeric vectors of the same length.")
}
out <- rep(NA_real_, n)
invalid <- is.na(x) |
is.na(drift) |
is.na(boundary) |
is.na(bias) |
is.na(ndt) |
(boundary <= 0) |
(bias < 0) |
(ndt < 0)
ok <- !invalid
if (any(ok)) {
t_adj <- x[ok] - ndt[ok]
res <- numeric(sum(ok)) # log(1): nothing can finish before the ndt
live <- t_adj > 0
if (any(live)) {
res[live] <- .wald_lccdf_core(
t_adj[live],
drift[ok][live],
boundary[ok][live],
bias[ok][live]
)
}
out[ok] <- res
}
if (log.p) out else exp(out)
}
#' Analytical CDF for Wald with Uniform Start Point Variability
#'
#' Calculates the cumulative distribution function (CDF) for the time it takes a
#' diffusion process with drift `drift`, starting point `z ~ U(0, bias)`, to reach
#' threshold `b = boundary + bias`, shifted by `ndt`. Based on Tillman et al. (2020).
#' This function calculates the CDF for the *unadjusted* time `x`.
#'
#' @noRd
.pwald <- function(
x,
drift,
boundary,
bias,
ndt,
lower.tail = TRUE,
log.p = FALSE
) {
n <- length(x)
if (!all(lengths(list(drift, boundary, bias, ndt)) == n)) {
stop("All inputs must be numeric vectors of the same length.")
}
# The survival is the primitive: it is the quantity the race likelihood
# needs, and it is the one that stays accurate far into the upper tail.
logS <- .swald(x, drift, boundary, bias, ndt, log.p = TRUE)
if (!lower.tail) {
return(if (log.p) logS else exp(logS))
}
# Lower tail. Near t = 0 the CDF is astronomically small and `1 - S` cannot
# resolve it, so use the direct series there; elsewhere `1 - S` is fine.
out <- .log1m_exp(logS)
tiny <- !is.na(logS) & logS > -1e-3
if (any(tiny)) {
out[tiny] <- .wald_lcdf_direct(
x[tiny],
drift[tiny],
boundary[tiny],
bias[tiny],
ndt[tiny]
)
}
out[is.na(logS)] <- NA_real_
if (log.p) out else exp(out)
}
#' Direct log-CDF, used only in the lower tail where `log(1 - S)` cancels
#'
#' Same closed form as Tillman et al. (2020), with `exp(2 * drift * b) * Phi(.)`
#' folded into a single exponent so it stays finite when the factors separately
#' overflow and underflow.
#'
#' @noRd
.wald_lcdf_direct <- function(x, drift, boundary, bias, ndt) {
t <- x - ndt
out <- rep(-Inf, length(t))
live <- !is.na(t) & t > 0
if (!any(live)) {
return(out)
}
tt <- t[live]
stt <- sqrt(tt)
nn <- drift[live]
kk <- boundary[live]
AA <- bias[live]
bb <- kk + AA
res <- rep(NA_real_, length(tt))
# Small start-point range: the difference quotient in the threshold cancels,
# so use the plain Wald CDF at the midpoint threshold, exactly as the density
# and the survival do. At `bias = 0` the midpoint *is* the threshold and this
# is the plain Wald, which is the only branch that can serve that case - the
# two below both divide by `A`.
small <- (AA / stt) < .RDM_EPS_A
if (any(small)) {
bm <- kk[small] + AA[small] / 2
ts <- tt[small]
sts <- stt[small]
ns <- nn[small]
res[small] <- .log_add_exp(
stats::pnorm((ns * ts - bm) / sts, log.p = TRUE),
2 * ns * bm + stats::pnorm(-(bm + ns * ts) / sts, log.p = TRUE)
)
}
# Driftless limit: C = (2 sqrt(t) / A) * (g(-k/sqrt(t)) - g(-b/sqrt(t))).
# NOTE: the factor of 2 here was missing before. Nothing in the package
# reaches this branch except `.pwald()` itself - the race likelihood goes
# through `.swald()`, which has a driftless branch of its own - so it went
# unnoticed, but the Stan version reaches it whenever drift approaches 0.
z <- !small & abs(nn) < .RDM_EPS_V
if (any(z)) {
lgap <- .log_sub_exp(
.log_gfun(-kk[z] / stt[z]),
.log_gfun(-bb[z] / stt[z])
)
res[z] <- log(2) + log(stt[z]) - log(AA[z]) + lgap
}
g <- !small & !z
if (any(g)) {
tg <- tt[g]
sg <- stt[g]
ng <- nn[g]
kg <- kk[g]
Ag <- AA[g]
bg <- bb[g]
sv <- sign(ng)
linv <- -log(2 * abs(ng))
a1 <- (ng * tg - bg) / sg
a2 <- (ng * tg - kg) / sg
w1 <- (-ng * tg - bg) / sg
w2 <- (-ng * tg - kg) / sg
m <- length(tg)
logs <- list(
linv + .log_diff_pnorm(a1, a2), # (1/2vA)(Phi(a2) - Phi(a1))
log(sg) + .log_gfun(a2), # +sqrt(t)/A * g(a2)
log(sg) + .log_gfun(a1), # -sqrt(t)/A * g(a1)
linv + 2 * ng * kg + stats::pnorm(w2, log.p = TRUE),
linv + 2 * ng * bg + stats::pnorm(w1, log.p = TRUE)
)
signs <- list(sv, rep(1, m), rep(-1, m), -sv, sv)
res[g] <- .log_sum_signed(logs, signs)$log - log(Ag)
}
out[live] <- res
pmin(out, 0)
}
# The decision component, as the registry wants it ------------------------
# Log-density of the winner's finishing time at `t` - already net of the
# non-decision time - for the accumulator named by `k`: that accumulator's
# density times the other one's survival, which is the defective density a race
# likelihood needs.
#
# `.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, and the core helpers index
# with logical subsetting.
#' @keywords internal
.rdm_ldens <- function(t, k, p) {
win <- as.vector(ifelse(k == 0, p$mu, p$driftone))
los <- as.vector(ifelse(k == 0, p$driftone, p$mu))
tv <- as.vector(t)
kk <- as.vector(p$boundary)
aa <- as.vector(p$sigmabias)
.wald_lpdf_core(tv, win, kk, aa) + .wald_lccdf_core(tv, los, kk, aa)
}
# Names `.prepare_choice()` puts on the recycled parameter vectors, in the order
# `qcogmod_rdm()` needs to slice one trial out of them.
.RDM_PAR_NAMES <- c("mu", "driftone", "sigmabias", "boundary", "ndt",
"poutlier", "response")
# Quadrature over one sub-divided range, so that a density concentrated far
# from either endpoint cannot be stepped over. `stats::integrate()` is adaptive
# but starts from a single 15-point rule on the whole interval, and a race with
# a fast accumulator puts essentially all of its mass in the first tenth of a
# second of a range that may run to infinity.
#' @noRd
.rdm_quad <- function(f, lo, hi, brk) {
cuts <- sort(unique(c(lo, brk[brk > lo & brk < hi], hi)))
total <- 0
for (j in seq_len(length(cuts) - 1L)) {
total <- total + stats::integrate(
f, cuts[j], cuts[j + 1L],
rel.tol = .Machine$double.eps^0.5, subdivisions = 200L
)$value
}
total
}
# Defective CDF `P(RT <= q, choice = k)` (or its upper-tail complement
# `P(RT > q, choice = k)`), including the outlier component.
#
# The decision half has no closed form - unlike the *marginal* CDF, where the
# race survival factorises as S0 * S1 - so it is integrated numerically. That
# also settles the scale: quadrature cannot deliver a log-space answer in the
# far tail, so this works on the natural scale throughout and `pcogmod_rdm()`
# takes the log of it afterwards rather than pretending otherwise.
#
# `lower.tail = FALSE` integrates from `q` upwards rather than subtracting from
# the total, which keeps the defective survival accurate where the two would
# cancel.
#' @noRd
.rdm_pdefective <- function(p, lower.tail = TRUE) {
n <- length(p$x)
out <- numeric(n)
if (n == 0) return(out)
K <- 2 # .choice_spec("cogmod_rdm")$K, fixed for this family
win <- ifelse(p$response == 0, p$mu, p$driftone)
los <- ifelse(p$response == 0, p$driftone, p$mu)
for (i in seq_len(n)) {
q <- p$x[i]
if (is.na(q)) {
out[i] <- NA_real_
next
}
kk <- p$boundary[i]
aa <- p$sigmabias[i]
vw <- win[i]
vl <- los[i]
# Defective density of the decision component in decision time `u`: the
# winner's density times the loser's survival, the same product the
# likelihood uses.
dens <- function(u) {
m <- length(u)
exp(.wald_lpdf_core(u, rep(vw, m), rep(kk, m), rep(aa, m)) +
.wald_lccdf_core(u, rep(vl, m), rep(kk, m), rep(aa, m)))
}
# Where the winner's mass sits, used only to place the breakpoints. With a
# drift it is the mean first passage time; without one the finishing time is
# Levy and has no mean, so its scale parameter stands in.
bm <- kk + aa / 2
tau <- if (vw > .RDM_EPS_V) bm / vw else bm^2
brk <- tau * c(0.05, 0.1, 0.25, 0.5, 1, 2, 4, 8, 16, 32)
tdec <- q - p$ndt[i] # decision time available at `q`
dec <- if (lower.tail) {
if (tdec <= 0) 0 else .rdm_quad(dens, 0, tdec, brk)
} else {
.rdm_quad(dens, max(tdec, 0), Inf, brk)
}
# The outlier component, on the same footing. The half Normal carries no
# shift, and the 1 / K is the uniform guess over the response options.
con <- if (q <= 0) {
if (lower.tail) 0 else 1
} else {
z <- q / .POUTLIER_SCALE
if (lower.tail) 2 * stats::pnorm(z) - 1 else 2 * stats::pnorm(-z)
}
out[i] <- p$poutlier[i] * con / K + (1 - p$poutlier[i]) * dec
}
# Quadrature can overshoot by a few ulps; a probability cannot.
pmin(pmax(out, 0), 1)
}
# Decision-component sampler: two accumulators, each with its own start point
# drawn from Uniform(0, sigmabias), and the first to finish takes the trial.
#
# A positive drift gives an inverse Gaussian first passage time (Michael et al.,
# 1976). A drift of exactly zero gives the driftless one, which is Levy
# distributed and drawn as `alpha^2 / Z^2` with `Z ~ Normal(0, 1)`: zero drift
# means the accumulator is slow, not that it never finishes.
#' @keywords internal
.rdm_rng <- function(n, p) {
# Interleaved as (trial 1 acc 0, trial 1 acc 1, trial 2 acc 0, ...), which is
# what `rep(each = 2)` and the `rbind()` below both produce.
aa <- rep(p$sigmabias, each = 2)
kk <- rep(p$boundary, each = 2)
z <- stats::runif(2 * n, min = 0, max = aa)
alpha <- kk + aa - z # distance left to travel, b - z
v <- as.vector(rbind(p$mu, p$driftone))
ft <- numeric(2 * n)
pos <- v > 0
if (any(pos)) ft[pos] <- .rwald_raw(sum(pos), v[pos], alpha[pos])
if (any(!pos)) ft[!pos] <- (alpha[!pos] / stats::rnorm(sum(!pos)))^2
m <- matrix(ft, nrow = n, ncol = 2, byrow = TRUE)
list(rt = pmin(m[, 1], m[, 2]),
response = as.numeric(m[, 1] >= m[, 2]))
}
# Stanvars ----------------------------------------------------------------
# The Stan side of the decision component. Pulled out of the lpdf as a
# prelude, like the LBA's and the Log-Gamma's, because the density itself is
# one expression in the registry and the arithmetic that keeps it stable does
# not fit in one. Every normal tail below goes through cogmod_log_Phi(), which
# comes in with .LOG_PHI_STAN_PRELUDE (core_shifted.R): Stan's
# std_normal_lcdf() has the right value but approximate partial derivatives,
# and here those partials are the gradient of the drifts and the boundary.
# Measured against central differences of the log probability over the
# gradient check's grid (benchmarks/gradient_check.R): 2e-4 relative at the
# start and up to 7e-2 with a small drift through std_normal_lcdf(), 2e-7
# through cogmod_log_Phi(), at about 14% more per gradient
# (benchmarks/gradient_cost.R, 5000 trials).
#' @keywords internal
.RDM_STAN_PRELUDE <- paste0(.LOG_PHI_STAN_PRELUDE, "
// ---------------------------------------------------------------------------
// Two-accumulator Racing Diffusion Model (Tillman, Van Zandt & Logan, 2020).
//
// Two Wald accumulators race to a common threshold b = boundary + sigmabias, each
// starting from z ~ Uniform(0, sigmabias). The observed trial contributes the
// winner's density times the loser's survival.
//
// Everything is carried in log space. That is not stylistic: for moderate
// drift the survival underflows to exactly zero (at drift 6 it does so by
// t = 4), and `log(0)` hands the sampler a zero gradient, which stalls it
// silently rather than erroring. The same applies to the density, whose
// individual terms underflow long before the density itself does.
//
// This is the most expensive likelihood in the package, so two things are
// deliberate and worth keeping when editing it. The normal CDF dominates the
// cost, and each one is evaluated exactly once: `log_g` takes log Phi(u) from
// its caller instead of recomputing Phi(u) internally. And nothing on the hot
// path returns a vector - Stan allocates on the autodiff stack for that, and
// here it would be per term, per observation, per leapfrog step. Together the
// two are worth about 1.5x on the gradient, measured against the term-by-term
// signed-accumulator form this replaced.
// ---------------------------------------------------------------------------
// Below this ratio of start-point range to sqrt(t), the threshold difference
// quotient cancels; the midpoint (plain Wald) limit is then both cheaper and
// more accurate, being second-order in the range.
// Below RDM_EPS_V the survival's 1 / (2 * drift) factor takes its driftless
// limit instead.
// log(u * Phi(u) + phi(u)) = log of the antiderivative of Phi, given
// lPhi = log Phi(u) that the caller already has.
//
// Taking lPhi as an argument rather than computing Phi(u) here is what keeps
// the survival down to four normal-CDF evaluations instead of six: the caller
// needs log Phi(alpha) and log Phi(beta) for its own terms anyway, and the
// normal CDF is by far the most expensive thing in this file.
real cogmod_rdm_log_g_lphi(real u, real lPhi) {
// For u < -10 both terms underflow *and* they cancel to order u^-2, so factor
// out phi(u) and expand 1 - |u| * MillsRatio(|u|) asymptotically. lPhi is not
// touched on this branch.
if (u <= -10) {
real x2 = square(u);
real s = 0;
real term = 1;
for (j in 1:12) {
term *= (2.0 * j - 1) / x2;
s += (j % 2 == 1) ? term : -term;
}
return -0.5 * x2 - 0.9189385332046727 + log(s);
}
real lphi = -0.5 * square(u) - 0.9189385332046727;
// g(u) > 0 throughout. Below zero the two terms cancel, so take the
// difference in log space rather than forming u * Phi(u) + phi(u) directly.
if (u >= 0) return log_sum_exp(log(u) + lPhi, lphi);
return log_diff_exp(lphi, log(-u) + lPhi);
}
// Standalone form, for the one caller that has no log Phi(u) to hand.
real cogmod_rdm_log_g(real u) {
if (u <= -10) return cogmod_rdm_log_g_lphi(u, 0); // lPhi unused there
return cogmod_rdm_log_g_lphi(u, cogmod_log_Phi(u));
}
// log(Phi(b) - Phi(a)) for b >= a, using whichever tail keeps both arguments
// away from a saturating normal CDF.
//
// The upper tail is written as cogmod_log_Phi(-a) rather than as a Stan
// upper-tail function: std_normal_lccdf() collapses to -inf once its argument
// passes about 8.3 (and is already wrong in the 3rd decimal at 8), and the
// distinction is not academic here -- alpha reaches 10 for a reaction time only
// a few milliseconds above the non-decision time. cogmod_log_Phi() of the
// negated argument is the same quantity, finite and differentiable however far
// out.
real cogmod_rdm_log_diff_Phi(real a, real b) {
if (b <= a) return negative_infinity();
if (a >= 0) return log_diff_exp(cogmod_log_Phi(-a), cogmod_log_Phi(-b));
if (b <= 0) return log_diff_exp(cogmod_log_Phi(b), cogmod_log_Phi(a));
return log(Phi(b) - Phi(a));
}
// log density of the first passage time t (net of non-decision time) for a
// diffusion with drift nu, threshold offset k, start-point range A.
real cogmod_rdm_wald_ldens(real t, real nu, real k, real A) {
if (t <= 0) return negative_infinity();
real st = sqrt(t);
if (A / st < 1e-4) { // midpoint plain Wald
real bm = k + 0.5 * A;
return log(bm) - 0.5 * (1.8378770664093453 + 3 * log(t))
- square(bm - nu * t) / (2 * t);
}
real alpha = (k - nu * t) / st;
real beta = (k + A - nu * t) / st;
// T1 = drift * (Phi(beta) - Phi(alpha))
real l1 = log(abs(nu)) + cogmod_rdm_log_diff_Phi(alpha, beta);
real s1 = nu > 0 ? 1 : (nu < 0 ? -1 : 0);
// T2 = (phi(alpha) - phi(beta)) / sqrt(t); phi is even, so the closer
// argument to zero wins and decides the sign.
real lpa = -0.5 * square(alpha) - 0.9189385332046727;
real lpb = -0.5 * square(beta) - 0.9189385332046727;
real s2; real l2;
if (abs(alpha) <= abs(beta)) {
s2 = 1; l2 = log_diff_exp(lpa, lpb) - log(st);
} else {
s2 = -1; l2 = log_diff_exp(lpb, lpa) - log(st);
}
// The density is positive, so the two terms add when they agree in sign and
// otherwise reduce to (larger - smaller). Deciding that here rather than
// through the signed accumulator keeps everything scalar: a vector-returning
// helper allocates on Stan's autodiff stack on every call, on every leapfrog
// step, for every observation. A zero drift leaves l1 at -inf and falls
// through the same branch.
real lnum;
if (s1 == s2) {
lnum = log_sum_exp(l1, l2);
} else if (l1 > l2) {
lnum = log_diff_exp(l1, l2);
} else if (l2 > l1) {
lnum = log_diff_exp(l2, l1);
} else {
lnum = negative_infinity();
}
return lnum - log(A);
}
// log survival of the first passage time t. Computed from the closed-form
// antiderivative of the Wald survival in the threshold, NOT as log(1 - CDF):
// the latter underflows to -inf at ordinary parameter values.
//
// Writing G for that antiderivative, S * A = G(k + A) - G(k), and G splits into
// two pieces that are each monotone in the threshold. Grouping the six terms
// into those two differences - rather than accumulating them one at a time with
// signs - makes each group's sign known in advance, which removes every signed
// accumulator from the hot path and, as a side effect, cancels less: measured
// against the R implementation the grouped form is accurate to 6e-11 where the
// term-by-term one reached 5e-9. (The second group is itself assembled from
// three signed pieces, for the reason given at D2 below, but with its sign
// still known in advance.)
real cogmod_rdm_wald_lsurv(real t, real nu, real k, real A) {
if (t <= 0) return 0; // log(1): nothing finishes before the ndt
real st = sqrt(t);
real b = k + A;
if (A / st < 1e-4) { // midpoint plain Wald survival
real bm = k + 0.5 * A;
real m1 = cogmod_log_Phi((bm - nu * t) / st);
real m2 = 2 * nu * bm + cogmod_log_Phi(-(bm + nu * t) / st);
return m1 > m2 ? log_diff_exp(m1, m2) : negative_infinity();
}
real alpha = (k - nu * t) / st;
real beta = (b - nu * t) / st;
if (abs(nu) < 1e-7) { // driftless limit
// S = 1 - (2 sqrt(t) / A) * (g(-k/st) - g(-b/st)); already carries its 1/A.
real lsub = 0.6931471805599453 + log(st) - log(A)
+ log_diff_exp(cogmod_rdm_log_g(-k / st),
cogmod_rdm_log_g(-b / st));
return lsub < 0 ? log1m_exp(lsub) : negative_infinity();
}
real linv = -log(2 * abs(nu));
// The two shared normal CDFs: log_g needs them, and so does D2 below.
real lPa = cogmod_log_Phi(alpha);
real lPb = cogmod_log_Phi(beta);
// S * A = D1 - D2, both pieces positive.
//
// D1 = sqrt(t) * (g(beta) - g(alpha)), positive because g is increasing.
real lD1 = 0.5 * log(t) + log_diff_exp(cogmod_rdm_log_g_lphi(beta, lPb),
cogmod_rdm_log_g_lphi(alpha, lPa));
// D2 = |R(k + A) - R(k)| / (2 |nu|), for
// R(x) = exp(2 nu x) Phi(-(x + nu t) / st) + Phi((x - nu t) / st)
// = E(x) + Phi(alpha_x),
// which increases with the threshold when nu > 0 and decreases when nu < 0
// (dR/dx = 2 nu E(x): the other two derivative terms cancel by the Wald
// reflection identity exp(2 nu x) phi((x + nu t) / st) = phi((x - nu t) / st)).
// Dividing by 2 nu flips the second case back, so D2 is positive either way.
//
// It is NOT formed as log_diff_exp(log R(b), log R(k)). Just above the
// non-decision time alpha and beta run past 37, Phi(alpha) and Phi(beta) both
// round to exactly 1 and the E terms underflow next to them, so the two logs
// are exactly 0 and log_diff_exp(0, 0) is evaluated. Its value, -inf, is
// harmless - D2 really is negligible there - but its reverse-mode adjoint is
// 0 / expm1(0) = 0 / 0, and that NaN propagates to the gradient of every
// parameter. Stan treats a NaN gradient as a divergent transition, and with
// `ndt` sitting a few milliseconds below the fastest responses the sampler
// crossed that half-millisecond window under most trajectories: 60% of
// transitions divergent on the lexical decision data of the decision-making
// article, with the posterior itself perfectly healthy.
//
// So the difference is taken term by term instead:
// R(b) - R(k) = [Phi(beta) - Phi(alpha)] + E(b) - E(k) = P + E_b - E_k,
// every piece of which is a log of something small and stays away from the
// saturated end of the normal CDF. P comes from whichever tail is small; the
// lower tail reuses lPa and lPb, which are exact there, and the upper one
// costs two more normal CDFs but only where alpha is large. E_b and E_k stay
// single exponents so that they survive the range where exp(2 nu x) and
// Phi(w) separately overflow and underflow. The sign of E_b - E_k is
// genuinely either (E alone is not monotone in the threshold), so it is
// resolved explicitly; the sum is positive for nu > 0 and negative for
// nu < 0. The guards below only ever fire when the difference is under one
// ulp of its terms, where D2 / D1 is far below double precision anyway.
// Measured against quadrature this form is as accurate as the grouped one;
// what it buys is a gradient that stays finite as t -> 0.
real lEb = 2 * nu * b + cogmod_log_Phi(-(b + nu * t) / st);
real lEk = 2 * nu * k + cogmod_log_Phi(-(k + nu * t) / st);
real lP = alpha < 3
? log_diff_exp(lPb, lPa)
: log_diff_exp(cogmod_log_Phi(-alpha), cogmod_log_Phi(-beta));
real lD2;
if (nu > 0) {
if (lEb >= lEk) {
lD2 = log_sum_exp(lP, lEb > lEk ? log_diff_exp(lEb, lEk) : negative_infinity());
} else {
real lx = log_sum_exp(lP, lEb);
lD2 = lx > lEk ? log_diff_exp(lx, lEk) : negative_infinity();
}
} else {
real lx = log_sum_exp(lP, lEb);
lD2 = lEk > lx ? log_diff_exp(lEk, lx) : negative_infinity();
}
lD2 += linv;
real ls = lD1 > lD2 ? log_diff_exp(lD1, lD2) : negative_infinity();
return fmin(ls - log(A), 0);
}
")
#' @keywords internal
.cogmod_rdm_lpdf <- function() {
.choice_lpdf("cogmod_rdm")
}
#' @rdname rcogmod_rdm
#' @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_rdm_lpdf_expose()
#' lpdf(
#' Y = 0.5, mu = 2, driftone = 1.5, sigmabias = 0.2, boundary = 0.5,
#' ndt = 0.2, poutlier = 0.02, dec = 0
#' )
#' }
#'
#' @export
cogmod_rdm_lpdf_expose <- function() {
.choice_expose("cogmod_rdm")
}
#' @rdname rcogmod_rdm
#' @export
cogmod_rdm_stanvars <- function() {
brms::stanvar(
scode = .cogmod_rdm_lpdf(),
block = "functions"
)
}
# brms methods ------------------------------------------------------------
#' @rdname rcogmod_rdm
#' @inheritParams rcogmod_betagate
#' @export
log_lik_cogmod_rdm <- function(i, prep) {
.log_lik_choice("cogmod_rdm", i, prep)
}
#' @rdname rcogmod_rdm
#' @inheritParams rcogmod_betagate
#' @importFrom brms get_dpar
#' @export
posterior_predict_cogmod_rdm <- function(i, prep, predict_outliers = NULL,
...) {
.posterior_predict_choice("cogmod_rdm", i, prep, predict_outliers)
}
#' @rdname rcogmod_rdm
#' @export
posterior_epred_cogmod_rdm <- function(prep) {
stop(
"Computing posterior_epred for a race model needs numerical integration ",
"per draw and per observation, which is prohibitive here. Use ",
"posterior_predict() and summarise the draws instead.",
call. = FALSE
)
}
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.