use argmin::core::{CostFunction, Error as ArgminError, Executor, State};
use argmin::solver::neldermead::NelderMead;
use rand::{Rng, SeedableRng};
use rand_chacha::ChaCha8Rng;
use rand_distr::StandardNormal;
use rayon::prelude::*;
pub const DT: f64 = 0.001;
pub const MAX_SIM_TIME: f64 = 10.0;
#[derive(Debug, Clone, PartialEq)]
pub struct Params {
pub drift_rate: f64,
pub boundary_separation: f64,
pub starting_point: f64,
pub non_decision_time: f64,
pub noise_sd: f64,
}
impl Default for Params {
fn default() -> Self {
Self {
drift_rate: 0.0,
boundary_separation: 1.0,
starting_point: 0.5,
non_decision_time: 0.0,
noise_sd: 1.0,
}
}
}
impl Params {
pub fn new(
drift_rate: f64,
boundary_separation: f64,
starting_point: f64,
non_decision_time: f64,
) -> Self {
Self {
drift_rate,
boundary_separation,
starting_point,
non_decision_time,
noise_sd: 1.0,
}
}
#[must_use]
pub fn with_noise_sd(mut self, noise_sd: f64) -> Self {
self.noise_sd = noise_sd;
self
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Trial {
pub upper_boundary: bool,
pub rt: f64,
pub timed_out: bool,
}
pub fn simulate_trial(params: &Params, rng: &mut impl Rng) -> Trial {
let sqrt_dt = DT.sqrt();
let boundary = params.boundary_separation;
let mut x = params.starting_point * boundary;
let mut t = 0.0_f64;
while x > 0.0 && x < boundary && t < MAX_SIM_TIME {
let z: f64 = rng.sample(StandardNormal);
x += params.drift_rate * DT + params.noise_sd * sqrt_dt * z;
t += DT;
}
let timed_out = x > 0.0 && x < boundary;
Trial {
upper_boundary: x >= 0.5 * boundary,
rt: t + params.non_decision_time,
timed_out,
}
}
pub fn simulate_n(params: &Params, n: usize, seed: u64) -> Vec<Trial> {
(0..n as u64)
.into_par_iter()
.map(|i| {
let mut rng = ChaCha8Rng::seed_from_u64(seed);
rng.set_stream(i);
simulate_trial(params, &mut rng)
})
.collect()
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SummaryStats {
pub accuracy: f64,
pub mean_rt: f64,
pub var_rt: f64,
pub n_usable: usize,
pub n_correct: usize,
}
pub fn summary_stats(trials: &[Trial]) -> Option<SummaryStats> {
let n_usable = trials.iter().filter(|t| !t.timed_out).count();
if n_usable == 0 {
return None;
}
let correct_rts: Vec<f64> = trials
.iter()
.filter(|t| !t.timed_out && t.upper_boundary)
.map(|t| t.rt)
.collect();
let n_correct = correct_rts.len();
if n_correct < 2 {
return None;
}
let m = n_correct as f64;
let mean_rt = correct_rts.iter().sum::<f64>() / m;
let var_rt = correct_rts
.iter()
.map(|rt| (rt - mean_rt).powi(2))
.sum::<f64>()
/ (m - 1.0);
Some(SummaryStats {
accuracy: n_correct as f64 / n_usable as f64,
mean_rt,
var_rt,
n_usable,
n_correct,
})
}
pub const EZ_SCALING_S: f64 = 1.0;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EzError {
NotEnoughTrials(usize),
NotEnoughCorrect(usize),
ChancePerformance,
NonPositiveVariance,
NoRealSolution,
}
impl std::fmt::Display for EzError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
EzError::NotEnoughTrials(n) => {
write!(f, "need >= 2 non-timed-out trials, got {n}")
}
EzError::NotEnoughCorrect(n) => {
write!(
f,
"need >= 2 upper-boundary trials for RT statistics, got {n}"
)
}
EzError::ChancePerformance => {
write!(f, "accuracy is exactly 0.5; drift rate is not identifiable")
}
EzError::NonPositiveVariance => {
write!(f, "variance of correct RT is not positive")
}
EzError::NoRealSolution => {
write!(
f,
"EZ drift equation has no real solution for these statistics"
)
}
}
}
}
impl std::error::Error for EzError {}
pub fn ez_diffusion(trials: &[Trial]) -> Result<Params, EzError> {
let n_usable = trials.iter().filter(|t| !t.timed_out).count();
if n_usable < 2 {
return Err(EzError::NotEnoughTrials(n_usable));
}
let stats = summary_stats(trials).ok_or_else(|| {
let n_correct = trials
.iter()
.filter(|t| !t.timed_out && t.upper_boundary)
.count();
EzError::NotEnoughCorrect(n_correct)
})?;
let mut pc = stats.accuracy;
if pc == 1.0 {
pc = 1.0 - 1.0 / (2.0 * n_usable as f64);
} else if pc == 0.5 {
return Err(EzError::ChancePerformance);
}
let mrt = stats.mean_rt;
let vrt = stats.var_rt;
if vrt.is_nan() || vrt <= 0.0 {
return Err(EzError::NonPositiveVariance);
}
let s = EZ_SCALING_S;
let s2 = s * s;
let l = (pc / (1.0 - pc)).ln();
let bracket = l * (l * pc * pc - l * pc + pc - 0.5) / vrt;
if bracket.is_nan() || bracket < 0.0 {
return Err(EzError::NoRealSolution);
}
let v = (pc - 0.5).signum() * s * bracket.powf(0.25);
let a = s2 * l / v;
let y = -v * a / s2;
let mdt = (a / (2.0 * v)) * ((1.0 - y.exp()) / (1.0 + y.exp()));
let ter = mrt - mdt;
Ok(Params {
drift_rate: v,
boundary_separation: a,
starting_point: 0.5,
non_decision_time: ter,
noise_sd: s,
})
}
pub const FIT_N_PER_EVAL: usize = 5_000;
fn fit_eval_seed(stats: &SummaryStats) -> u64 {
let mut h: u64 = 0x9E37_79B9_7F4A_7C15;
for x in [
stats.accuracy.to_bits(),
stats.mean_rt.to_bits(),
stats.var_rt.to_bits(),
stats.n_usable as u64,
stats.n_correct as u64,
] {
h = (h ^ x).wrapping_mul(0xFF51_AFD7_ED55_8CCD);
h ^= h >> 33;
}
h.wrapping_mul(0xC4CE_B9FE_1A85_EC53)
}
const FIT_WEIGHTS: [f64; 3] = [1.0, 1.0, 0.5];
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FitError {
NoData,
NoSolution,
Solver(String),
}
impl std::fmt::Display for FitError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
FitError::NoData => write!(
f,
"target data has no usable trials or fewer than two upper-boundary trials"
),
FitError::NoSolution => write!(f, "optimizer produced no solution"),
FitError::Solver(msg) => write!(f, "optimizer error: {msg}"),
}
}
}
impl std::error::Error for FitError {}
#[derive(Clone)]
struct SimFitCost {
target: SummaryStats,
n_per_eval: usize,
seed: u64,
}
impl CostFunction for SimFitCost {
type Param = Vec<f64>;
type Output = f64;
fn cost(&self, p: &Self::Param) -> Result<Self::Output, ArgminError> {
let (v, a, t0) = (p[0], p[1], p[2]);
if !v.is_finite() || !a.is_finite() || !t0.is_finite() || a <= 1e-6 || t0 < 0.0 {
return Ok(1e9);
}
let params = Params {
drift_rate: v,
boundary_separation: a,
starting_point: 0.5,
non_decision_time: t0,
noise_sd: EZ_SCALING_S,
};
let trials = simulate_n(¶ms, self.n_per_eval, self.seed);
let Some(cand) = summary_stats(&trials) else {
return Ok(1e9);
};
let sq_rel = |c: f64, t: f64| {
let d = (c - t) / t;
d * d
};
let cost = FIT_WEIGHTS[0] * sq_rel(cand.accuracy, self.target.accuracy)
+ FIT_WEIGHTS[1] * sq_rel(cand.mean_rt, self.target.mean_rt)
+ FIT_WEIGHTS[2] * sq_rel(cand.var_rt, self.target.var_rt);
Ok(cost)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct SimFit {
pub params: Params,
pub iterations: u64,
pub final_cost: f64,
}
pub fn default_fit_guess(trials: &[Trial]) -> Params {
ez_diffusion(trials).unwrap_or_else(|_| Params::new(1.0, 1.0, 0.5, 0.2))
}
pub fn fit_simulation(
trials: &[Trial],
initial_guess: Params,
max_iters: usize,
) -> Result<SimFit, FitError> {
let target = summary_stats(trials).ok_or(FitError::NoData)?;
let cost = SimFitCost {
target,
n_per_eval: FIT_N_PER_EVAL,
seed: fit_eval_seed(&target),
};
let g = [
initial_guess.drift_rate,
initial_guess.boundary_separation,
initial_guess.non_decision_time,
];
let round1_iters = (max_iters * 55 / 100).max(1) as u64;
let (mut best, mut best_cost, mut iters) =
run_neldermead(cost.clone(), simplex_around(&g, 0.15, 0.05), round1_iters)?;
let round2_iters = (max_iters as u64).saturating_sub(iters).max(1);
let (b2, c2, i2) = run_neldermead(cost, simplex_around(&best, 0.05, 0.02), round2_iters)?;
iters += i2;
if c2 < best_cost {
best = b2;
best_cost = c2;
}
Ok(SimFit {
params: Params {
drift_rate: best[0],
boundary_separation: best[1],
starting_point: 0.5,
non_decision_time: best[2],
noise_sd: EZ_SCALING_S,
},
iterations: iters,
final_cost: best_cost,
})
}
fn simplex_around(center: &[f64; 3], frac: f64, floor: f64) -> Vec<Vec<f64>> {
let step = |v: f64| (v.abs() * frac).max(floor);
vec![
center.to_vec(),
vec![center[0] + step(center[0]), center[1], center[2]],
vec![center[0], center[1] + step(center[1]), center[2]],
vec![center[0], center[1], center[2] + floor.max(0.05)],
]
}
fn run_neldermead(
cost: SimFitCost,
simplex: Vec<Vec<f64>>,
max_iters: u64,
) -> Result<([f64; 3], f64, u64), FitError> {
let solver = NelderMead::new(simplex)
.with_sd_tolerance(1e-10)
.map_err(|e| FitError::Solver(e.to_string()))?;
let result = Executor::new(cost, solver)
.configure(|state| state.max_iters(max_iters))
.run()
.map_err(|e| FitError::Solver(e.to_string()))?;
let state = result.state();
let best = state.get_best_param().ok_or(FitError::NoSolution)?;
Ok((
[best[0], best[1], best[2]],
state.get_best_cost(),
state.get_iter(),
))
}
#[cfg(test)]
mod tests {
use super::*;
fn prop_upper(trials: &[Trial]) -> f64 {
trials.iter().filter(|t| t.upper_boundary).count() as f64 / trials.len() as f64
}
fn mean_rt(trials: &[Trial]) -> f64 {
trials.iter().map(|t| t.rt).sum::<f64>() / trials.len() as f64
}
fn analytic_p_upper(v: f64, a: f64, z_frac: f64, s: f64) -> f64 {
let z = z_frac * a;
if v.abs() < 1e-12 {
return z / a;
}
let k = -2.0 * v / (s * s);
(k * z).exp_m1() / (k * a).exp_m1()
}
#[test]
fn zero_drift_centered_start_is_balanced() {
let params = Params::new(0.0, 1.0, 0.5, 0.0);
let trials = simulate_n(¶ms, 40_000, 0xC0FFEE);
let p = prop_upper(&trials);
assert!((p - 0.5).abs() < 0.02, "expected ~0.5 split, got {p}");
}
#[test]
fn choice_probability_matches_closed_form() {
for &(v, a, z) in &[
(1.0, 1.0, 0.5),
(2.5, 1.0, 0.5),
(-2.0, 1.0, 0.5),
(0.0, 1.0, 0.8),
(0.8, 1.4, 0.3),
] {
let params = Params::new(v, a, z, 0.0);
let p = prop_upper(&simulate_n(¶ms, 60_000, 17));
let expected = analytic_p_upper(v, a, z, params.noise_sd);
assert!(
(p - expected).abs() < 0.03,
"v={v} a={a} z={z}: empirical {p:.3} vs analytic {expected:.3}"
);
}
}
#[test]
fn stronger_drift_favors_boundary_and_speeds_decisions() {
let weak = Params::new(0.5, 1.0, 0.5, 0.0);
let strong = Params::new(2.5, 1.0, 0.5, 0.0);
let weak_trials = simulate_n(&weak, 40_000, 7);
let strong_trials = simulate_n(&strong, 40_000, 7);
let (p_weak, p_strong) = (prop_upper(&weak_trials), prop_upper(&strong_trials));
let (rt_weak, rt_strong) = (mean_rt(&weak_trials), mean_rt(&strong_trials));
assert!(
p_strong > p_weak,
"stronger drift should favor the boundary more: {p_weak} -> {p_strong}"
);
assert!(
rt_strong < rt_weak,
"stronger drift should be faster: {rt_weak} -> {rt_strong}"
);
}
#[test]
fn negative_drift_favors_lower_boundary() {
let params = Params::new(-2.0, 1.0, 0.5, 0.0);
let trials = simulate_n(¶ms, 40_000, 42);
assert!(
prop_upper(&trials) < 0.2,
"negative drift should favor the lower boundary, got {}",
prop_upper(&trials)
);
}
#[test]
fn seeding_is_reproducible_and_seed_sensitive() {
let params = Params::new(0.8, 1.2, 0.4, 0.2);
let a = simulate_n(¶ms, 5_000, 2024);
let b = simulate_n(¶ms, 5_000, 2024);
let c = simulate_n(¶ms, 5_000, 2025);
assert_eq!(a, b, "identical seed must reproduce identical trials");
assert_ne!(a, c, "different seed should produce different trials");
}
#[test]
fn determinism_is_independent_of_thread_count() {
let params = Params::new(1.0, 1.0, 0.5, 0.0);
let reference = simulate_n(¶ms, 8_000, 99);
let one_thread = rayon::ThreadPoolBuilder::new()
.num_threads(1)
.build()
.unwrap()
.install(|| simulate_n(¶ms, 8_000, 99));
assert_eq!(reference, one_thread);
}
#[test]
fn non_decision_time_is_an_additive_shift() {
let base = Params::new(1.0, 1.0, 0.5, 0.0);
let shifted = Params::new(1.0, 1.0, 0.5, 0.3);
let a = simulate_n(&base, 3_000, 1);
let b = simulate_n(&shifted, 3_000, 1);
for (x, y) in a.iter().zip(b.iter()) {
assert_eq!(x.upper_boundary, y.upper_boundary);
assert!((y.rt - x.rt - 0.3).abs() < 1e-9);
}
}
#[test]
fn biased_start_favors_near_boundary() {
let params = Params::new(0.0, 1.0, 0.8, 0.0);
let trials = simulate_n(¶ms, 40_000, 5);
assert!(
prop_upper(&trials) > 0.7,
"start near the upper boundary should favor upper responses"
);
}
#[test]
fn ez_diffusion_recovers_known_parameters() {
let truths = [
Params::new(1.0, 1.0, 0.5, 0.20),
Params::new(2.0, 1.2, 0.5, 0.30),
Params::new(0.5, 1.5, 0.5, 0.15),
Params::new(3.0, 0.8, 0.5, 0.25),
];
for (k, truth) in truths.iter().enumerate() {
let trials = simulate_n(truth, 200_000, 1000 + k as u64);
let est = ez_diffusion(&trials).expect("recovery should succeed");
let rel = |got: f64, want: f64| (got - want).abs() / want;
assert!(
rel(est.drift_rate, truth.drift_rate) < 0.08,
"case {k}: drift {:.4} vs true {:.4} ({:.1}%)",
est.drift_rate,
truth.drift_rate,
100.0 * rel(est.drift_rate, truth.drift_rate),
);
assert!(
rel(est.boundary_separation, truth.boundary_separation) < 0.08,
"case {k}: boundary {:.4} vs true {:.4} ({:.1}%)",
est.boundary_separation,
truth.boundary_separation,
100.0 * rel(est.boundary_separation, truth.boundary_separation),
);
assert!(
(est.non_decision_time - truth.non_decision_time).abs() < 0.020,
"case {k}: Ter {:.4} vs true {:.4}",
est.non_decision_time,
truth.non_decision_time,
);
}
}
#[test]
fn ez_diffusion_edge_corrects_perfect_accuracy() {
let mut rng = ChaCha8Rng::seed_from_u64(3);
let trials: Vec<Trial> = (0..5_000)
.map(|_| Trial {
upper_boundary: true,
rt: 0.4 + 0.05 * rng.sample::<f64, _>(StandardNormal),
timed_out: false,
})
.collect();
assert!(trials.iter().all(|t| t.upper_boundary));
let est = ez_diffusion(&trials).expect("edge correction should apply");
assert!(est.drift_rate.is_finite() && est.drift_rate > 0.0);
assert!(est.boundary_separation.is_finite() && est.boundary_separation > 0.0);
assert!(est.non_decision_time.is_finite());
}
#[test]
fn ez_diffusion_excludes_timed_out_trials() {
let mut trials = simulate_n(&Params::new(1.0, 1.0, 0.5, 0.2), 5_000, 9);
let clean = ez_diffusion(&trials).unwrap();
for i in 0..2_000 {
trials.push(Trial {
upper_boundary: i % 2 == 0,
rt: 10.0 + i as f64,
timed_out: true,
});
}
let with_junk = ez_diffusion(&trials).unwrap();
assert!((clean.drift_rate - with_junk.drift_rate).abs() < 1e-12);
assert!((clean.boundary_separation - with_junk.boundary_separation).abs() < 1e-12);
assert!((clean.non_decision_time - with_junk.non_decision_time).abs() < 1e-12);
}
#[test]
fn summary_stats_are_correct_and_exclude_timeouts() {
let trials = vec![
Trial {
upper_boundary: true,
rt: 0.5,
timed_out: false,
},
Trial {
upper_boundary: true,
rt: 0.7,
timed_out: false,
},
Trial {
upper_boundary: true,
rt: 0.9,
timed_out: false,
},
Trial {
upper_boundary: false,
rt: 0.6,
timed_out: false,
},
Trial {
upper_boundary: true,
rt: 10.1,
timed_out: true,
},
Trial {
upper_boundary: false,
rt: 10.1,
timed_out: true,
},
];
let s = summary_stats(&trials).unwrap();
assert_eq!(s.n_usable, 4);
assert_eq!(s.n_correct, 3);
assert!((s.accuracy - 0.75).abs() < 1e-12);
assert!((s.mean_rt - 0.7).abs() < 1e-12);
assert!((s.var_rt - 0.04).abs() < 1e-12);
assert!(summary_stats(&[]).is_none());
}
#[test]
fn ez_diffusion_and_summary_stats_agree() {
let trials = simulate_n(&Params::new(1.3, 1.1, 0.5, 0.2), 20_000, 4);
let s = summary_stats(&trials).unwrap();
let est = ez_diffusion(&trials).unwrap();
let (v, a) = (est.drift_rate, est.boundary_separation);
let y = -v * a / (EZ_SCALING_S * EZ_SCALING_S);
let mdt = (a / (2.0 * v)) * ((1.0 - y.exp()) / (1.0 + y.exp()));
assert!((est.non_decision_time - (s.mean_rt - mdt)).abs() < 1e-9);
}
#[test]
fn fit_simulation_is_deterministic() {
let trials = simulate_n(&Params::new(1.2, 1.0, 0.5, 0.25), 20_000, 11);
let guess = default_fit_guess(&trials);
let a = fit_simulation(&trials, guess.clone(), 80).unwrap();
let b = fit_simulation(&trials, guess, 80).unwrap();
assert_eq!(a, b);
}
#[test]
fn fit_simulation_recovers_known_parameters() {
let truths = [
Params::new(1.0, 1.0, 0.5, 0.20),
Params::new(2.0, 1.2, 0.5, 0.30),
Params::new(0.5, 1.5, 0.5, 0.15),
Params::new(3.0, 0.8, 0.5, 0.25),
];
for (k, truth) in truths.iter().enumerate() {
let trials = simulate_n(truth, 150_000, 2000 + k as u64);
let guess = default_fit_guess(&trials);
let fit = fit_simulation(&trials, guess, 150).expect("fit should succeed");
let est = fit.params;
let rel = |got: f64, want: f64| (got - want).abs() / want;
assert!(
rel(est.drift_rate, truth.drift_rate) < 0.08,
"case {k}: drift {:.4} vs true {:.4} ({:.1}%), cost {:.2e}",
est.drift_rate,
truth.drift_rate,
100.0 * rel(est.drift_rate, truth.drift_rate),
fit.final_cost,
);
assert!(
rel(est.boundary_separation, truth.boundary_separation) < 0.05,
"case {k}: boundary {:.4} vs true {:.4} ({:.1}%), cost {:.2e}",
est.boundary_separation,
truth.boundary_separation,
100.0 * rel(est.boundary_separation, truth.boundary_separation),
fit.final_cost,
);
assert!(
(est.non_decision_time - truth.non_decision_time).abs() < 0.018,
"case {k}: Ter {:.4} vs true {:.4}, cost {:.2e}",
est.non_decision_time,
truth.non_decision_time,
fit.final_cost,
);
}
}
}