| rcogmod_ddm | R Documentation |
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.
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.
rcogmod_ddm(
n,
drift = 0,
boundary = 1,
bias = 0.5,
ndt = 0.2,
sigmadrift = 0,
sigmabias = 0,
sigmandt = 0,
poutlier = 0
)
dcogmod_ddm(
x,
drift = 0,
boundary = 1,
bias = 0.5,
ndt = 0.2,
response,
sigmadrift = 0,
sigmabias = 0,
sigmandt = 0,
poutlier = 0,
log = FALSE
)
pcogmod_ddm(
q,
drift = 0,
boundary = 1,
bias = 0.5,
ndt = 0.2,
response = NULL,
poutlier = 0,
lower.tail = TRUE,
log.p = FALSE
)
cogmod_ddm(
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
)
cogmod_ddm_lpdf_expose()
cogmod_ddm_stanvars()
log_lik_cogmod_ddm(i, prep)
posterior_predict_cogmod_ddm(i, prep, predict_outliers = NULL, ...)
posterior_epred_cogmod_ddm(prep, predict_outliers = NULL)
n |
Number of simulated trials. If |
drift |
Drift rate. Any real value; positive pushes the accumulator
towards the boundary coded |
boundary |
Boundary separation. Must be positive. |
bias |
Starting point, as a proportion of the boundary separation
measured from the boundary coded |
ndt |
Non-decision time (shift parameter), in seconds. Must be
non-negative. With |
sigmadrift |
Between-trial SD of the drift rate ( |
sigmabias |
Between-trial start-point range, as a fraction in |
sigmandt |
Between-trial range of the non-decision time ( |
poutlier |
Proportion of responses generated by the outlier process
rather than by the diffusion. Range: |
x |
The observed reaction time (RT). |
response |
The boundary reached: |
log |
Logical; if TRUE, returns the log-density. Default: FALSE. |
q |
Vector of quantiles (reaction times, in seconds). |
lower.tail |
Logical; if TRUE (default) the probability is
|
log.p |
Logical; if TRUE, probabilities are returned on the log scale. |
link_mu, link_boundary, link_bias |
Link functions for the drift rate, the
boundary separation and the starting point. |
link_sigmadrift, link_sigmabias, link_sigmandt |
Link functions for the
between-trial variability parameters. Fix them in the |
link_ndt, link_poutlier |
Link functions for the non-decision time and the outlier rate. |
predict_outliers |
Logical; whether |
i, prep |
For brms' functions to run: index of the observation and a |
... |
Additional arguments. |
rcogmod_ddm() returns a data frame with n rows and two columns:
rt |
The simulated reaction time. |
response |
The boundary reached, |
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).
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.
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.
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:
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.
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.
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.
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.
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
rstantools::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).
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.
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.
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.
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:
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.
Ratcliff, R., & McKoon, G. (2008). The diffusion decision model: Theory and data for two-choice decision tasks. Neural Computation, 20(4), 873-922. \Sexpr[results=rd]{tools:::Rd_expr_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. \Sexpr[results=rd]{tools:::Rd_expr_doi("10.1016/j.jmp.2009.02.003")}
rcogmod_rdm(), rcogmod_lba2(), rcogmod_lnr()
# 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)
## Not run:
# 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
)
## End(Not run)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.