ouddm 0.4.4__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ouddm-0.4.4/CHANGELOG.md +104 -0
- ouddm-0.4.4/LICENSE +21 -0
- ouddm-0.4.4/MANIFEST.in +4 -0
- ouddm-0.4.4/PKG-INFO +142 -0
- ouddm-0.4.4/README.md +118 -0
- ouddm-0.4.4/examples/color_shapes_application.py +111 -0
- ouddm-0.4.4/examples/color_shapes_counts.py +20 -0
- ouddm-0.4.4/examples/color_shapes_descriptives.py +18 -0
- ouddm-0.4.4/examples/color_shapes_ou_bound.py +48 -0
- ouddm-0.4.4/examples/color_shapes_revision.py +100 -0
- ouddm-0.4.4/examples/color_shapes_s1_noou.py +24 -0
- ouddm-0.4.4/examples/condition_study.py +99 -0
- ouddm-0.4.4/examples/design_study.py +82 -0
- ouddm-0.4.4/examples/main_study.py +106 -0
- ouddm-0.4.4/examples/paper_figures.py +150 -0
- ouddm-0.4.4/examples/stage1_error_diagnostic.py +44 -0
- ouddm-0.4.4/examples/step1_bias_study.py +95 -0
- ouddm-0.4.4/examples/step1_figure.py +63 -0
- ouddm-0.4.4/pyproject.toml +32 -0
- ouddm-0.4.4/setup.cfg +4 -0
- ouddm-0.4.4/src/ouddm/__init__.py +40 -0
- ouddm-0.4.4/src/ouddm/collapsed.py +78 -0
- ouddm-0.4.4/src/ouddm/design.py +102 -0
- ouddm-0.4.4/src/ouddm/design_model.py +390 -0
- ouddm-0.4.4/src/ouddm/estimate.py +311 -0
- ouddm-0.4.4/src/ouddm/ez.py +56 -0
- ouddm-0.4.4/src/ouddm/ou.py +152 -0
- ouddm-0.4.4/src/ouddm/simulate.py +194 -0
- ouddm-0.4.4/src/ouddm/twostage.py +27 -0
- ouddm-0.4.4/src/ouddm/wiener.py +89 -0
- ouddm-0.4.4/src/ouddm.egg-info/PKG-INFO +142 -0
- ouddm-0.4.4/src/ouddm.egg-info/SOURCES.txt +37 -0
- ouddm-0.4.4/src/ouddm.egg-info/dependency_links.txt +1 -0
- ouddm-0.4.4/src/ouddm.egg-info/requires.txt +7 -0
- ouddm-0.4.4/src/ouddm.egg-info/top_level.txt +1 -0
- ouddm-0.4.4/tests/test_core.py +61 -0
- ouddm-0.4.4/tests/test_design_model.py +160 -0
- ouddm-0.4.4/tests/test_estimate_design.py +133 -0
- ouddm-0.4.4/tests/test_exact.py +137 -0
ouddm-0.4.4/CHANGELOG.md
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.4.4
|
|
4
|
+
|
|
5
|
+
- No change to the package code (identical to 0.4.2 and 0.4.3).
|
|
6
|
+
- The manuscript build files (`paper/`) are no longer shipped in the source
|
|
7
|
+
distribution. They are in the replication archive that accompanies the
|
|
8
|
+
article. A `.gitignore` keeps them out of the public repository.
|
|
9
|
+
|
|
10
|
+
## 0.4.3
|
|
11
|
+
|
|
12
|
+
- No change to the package code (identical to 0.4.2).
|
|
13
|
+
- Manuscript: abstract shortened to under 250 words for the Journal of
|
|
14
|
+
Mathematical Psychology; the build now checks the abstract length and
|
|
15
|
+
writes a separate highlights file (3–5 bullets, at most 85 characters each).
|
|
16
|
+
- Software and data availability section names the PyPI release.
|
|
17
|
+
|
|
18
|
+
## 0.4.2
|
|
19
|
+
|
|
20
|
+
- `profile_interval` no longer returns the best grid point as a one-point
|
|
21
|
+
range when no grid point lies within the cut-off. It reports an empty set
|
|
22
|
+
(`regions == []`, `empty=True`, `needs_refinement=True`, NaN ends) and gives
|
|
23
|
+
`best_grid_halflife` as the place to refine. New test.
|
|
24
|
+
- Manuscript: Section 9.1 no longer says that joint OU models for drift and
|
|
25
|
+
boundary keep the Gaussian reduction. The drift states integrate out
|
|
26
|
+
exactly given the boundary trajectory; the boundary needs a separate
|
|
27
|
+
integration step.
|
|
28
|
+
|
|
29
|
+
## 0.4.1
|
|
30
|
+
|
|
31
|
+
- `profile_interval` now detects a disconnected supported set. It returns
|
|
32
|
+
each connected range in `regions` and sets `disconnected=True`; the outer
|
|
33
|
+
ends `halflife_lo`/`halflife_hi` are kept but should not be read as one
|
|
34
|
+
interval in that case. New helper `supported_regions`; new test.
|
|
35
|
+
- New example `color_shapes_s1_noou.py`: the practice-slope model without an
|
|
36
|
+
OU part, reported in Table 6.
|
|
37
|
+
- The manuscript build checks that every archived profile has one connected
|
|
38
|
+
supported region.
|
|
39
|
+
|
|
40
|
+
## 0.4.0
|
|
41
|
+
|
|
42
|
+
- New: person-specific random slope on a session predictor in `design_model`
|
|
43
|
+
(`DesignData.from_trials(..., slope="day_c")`), correlated with the person
|
|
44
|
+
mean. The likelihood stays exact; checked against quadrature.
|
|
45
|
+
- New: `ou=False` fits the no-OU limit model (random person intercept plus
|
|
46
|
+
session deviations). With tau and omega free, both ends of the theta range
|
|
47
|
+
reduce to this model; a test checks this.
|
|
48
|
+
- `profile_interval` takes the fitted maximum as the reference and finds the
|
|
49
|
+
interval ends by root-finding; it reports whether either end is open.
|
|
50
|
+
- New examples: `color_shapes_revision.py` (refined profile from theta = 1e-5
|
|
51
|
+
to 1e5 per day, practice-slope, long-window, and interaction sensitivity
|
|
52
|
+
analyses), `color_shapes_ou_bound.py`, `color_shapes_counts.py`.
|
|
53
|
+
`color_shapes_profile.py` is removed; its results are superseded.
|
|
54
|
+
|
|
55
|
+
## 0.3.0
|
|
56
|
+
|
|
57
|
+
- New: `design_model` for real task designs, with the exact likelihood kept:
|
|
58
|
+
stimulus coding (drift sign by stimulus), start point depending on bias
|
|
59
|
+
predictors, boundary depending on boundary predictors, person-specific
|
|
60
|
+
non-decision time (kappa x fastest RT), drift predictors, and independent
|
|
61
|
+
session-level drift deviations (nugget). `fit_design`, `profile_theta`,
|
|
62
|
+
`profile_interval`.
|
|
63
|
+
- The OU part of `design_model` is parameterized by its stationary SD, so the
|
|
64
|
+
white-noise limit (theta -> infinity) is reachable; starts span theta from
|
|
65
|
+
0.3 to 2000 per day, because real data can have separate slow and fast optima.
|
|
66
|
+
- `_log_g` accepts a start point per trial.
|
|
67
|
+
- New tests: extended likelihood (with and without session deviations) against
|
|
68
|
+
3-D quadrature; vector start points.
|
|
69
|
+
- New example: reanalysis of the Color Shapes data (Kim et al., 2025;
|
|
70
|
+
https://osf.io/ty4uf/), with a profile-likelihood script.
|
|
71
|
+
|
|
72
|
+
## 0.2.0
|
|
73
|
+
|
|
74
|
+
- Fix: the zero-drift Wiener density is now summed on the log scale (signed
|
|
75
|
+
log-sum-exp). Before, very short decision times hit a numerical floor
|
|
76
|
+
(log density about -678 instead of -1788 at 0.1 ms with a = 1.2), which
|
|
77
|
+
could make a large non-decision time look too plausible.
|
|
78
|
+
- Fix: `fit_exact` and `fit_ou` add starting values for the person-level SD
|
|
79
|
+
tau. With a common practice trend, a single start could end in a second
|
|
80
|
+
optimum with tau near 0 and a slow OU process standing in for it.
|
|
81
|
+
- New: drift predictors. `fit_exact(trials, covariates=[...])` fits trial
|
|
82
|
+
drift = OU state + x'beta with the exact likelihood (Proposition 4).
|
|
83
|
+
- New: `simulate_study(..., x_session=, beta=)` for session-level predictors.
|
|
84
|
+
- New: fits report which optimizer bound (if any) theta reached; study
|
|
85
|
+
scripts count both bounds, optimizer status, and interval denominators.
|
|
86
|
+
- Faster density evaluation (trimmed series, cached zero-drift term).
|
|
87
|
+
- New tests: density near zero decision time, series continuity, the bias
|
|
88
|
+
identity E[m|v] = v E[S] E[1/S], covariate likelihood against quadrature,
|
|
89
|
+
and recovery with a practice trend.
|
|
90
|
+
|
|
91
|
+
## 0.1.0
|
|
92
|
+
|
|
93
|
+
- Exact collapsed marginal likelihood for the DDM with OU drift dynamics
|
|
94
|
+
(`fit_exact`): all session drifts and person home bases integrated out in
|
|
95
|
+
closed form; boundary separation and non-decision time estimated jointly;
|
|
96
|
+
Wald intervals for the drift half-life.
|
|
97
|
+
- Shared-nuisance two-stage comparator (`fit_two_stage_ml`), with or without
|
|
98
|
+
propagation of session drift variance.
|
|
99
|
+
- EZ-diffusion two-stage estimators (naive and constant measurement error).
|
|
100
|
+
- Design calculator (`design_information`, `compare_designs`): expected SE
|
|
101
|
+
of the log half-life for a session schedule, with or without RTs.
|
|
102
|
+
- Exact Wiener first-passage density and CDF; information ratio x / sinh(x).
|
|
103
|
+
- Simulator with exact OU transitions at irregular or fixed times and a
|
|
104
|
+
bridge-corrected Wiener sampler.
|
ouddm-0.4.4/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Subir Hait
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
ouddm-0.4.4/MANIFEST.in
ADDED
ouddm-0.4.4/PKG-INFO
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ouddm
|
|
3
|
+
Version: 0.4.4
|
|
4
|
+
Summary: Exact likelihood and study design for drift diffusion models with Ornstein-Uhlenbeck drift dynamics
|
|
5
|
+
Author-email: Subir Hait <haitsubi@msu.edu>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/subirhait/ouddm
|
|
8
|
+
Project-URL: Issues, https://github.com/subirhait/ouddm/issues
|
|
9
|
+
Keywords: drift diffusion model,Ornstein-Uhlenbeck,intensive longitudinal data,ambulatory assessment,cognitive modeling,study design
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Intended Audience :: Science/Research
|
|
13
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
14
|
+
Requires-Python: >=3.10
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
Requires-Dist: numpy>=1.24
|
|
18
|
+
Requires-Dist: scipy>=1.10
|
|
19
|
+
Requires-Dist: pandas>=2.0
|
|
20
|
+
Provides-Extra: dev
|
|
21
|
+
Requires-Dist: pytest; extra == "dev"
|
|
22
|
+
Requires-Dist: matplotlib; extra == "dev"
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# ouddm
|
|
26
|
+
|
|
27
|
+
Exact likelihood and study design for drift diffusion models (DDMs) whose drift
|
|
28
|
+
rate follows an Ornstein–Uhlenbeck (OU) process across repeated sessions. It is
|
|
29
|
+
built for intensive longitudinal cognitive data such as smartphone-based
|
|
30
|
+
ambulatory assessments.
|
|
31
|
+
|
|
32
|
+
Author: Subir Hait, Michigan State University · License: MIT
|
|
33
|
+
|
|
34
|
+
## What it does
|
|
35
|
+
|
|
36
|
+
Person *i* completes short two-choice sessions at times *t_ij* (days, irregular
|
|
37
|
+
spacing allowed). Within a session, trials follow a Wiener diffusion with drift
|
|
38
|
+
`v_ij`, boundary `a`, start `w·a`, diffusion scale 1, and non-decision time `ter`.
|
|
39
|
+
Across sessions, the drift follows an OU process:
|
|
40
|
+
|
|
41
|
+
dv = θ (μ_i − v) dt + σ dW, μ_i ~ N(μ0, τ²), half-life = ln 2 / θ
|
|
42
|
+
|
|
43
|
+
**Key result.** A session-constant drift enters the Wiener likelihood only through
|
|
44
|
+
a quadratic term, so as a function of the drift each session's likelihood is an
|
|
45
|
+
exact Gaussian kernel:
|
|
46
|
+
|
|
47
|
+
l_j(v) − l_j(0) = b_j v − S_j v² / 2,
|
|
48
|
+
b_j = a[(1−w) N_jU − w N_jL], S_j = Σ decision times
|
|
49
|
+
|
|
50
|
+
The kernel is centered at `m_j = b_j / S_j` with curvature `S_j`. (This is a
|
|
51
|
+
statement about the likelihood; `m_j` itself is biased upward in short sessions:
|
|
52
|
+
`E[m|v] = v E[S] E[1/S]`.) All latent drifts and person means integrate out in
|
|
53
|
+
closed form, giving the exact likelihood of all choices and RTs. No MCMC and no
|
|
54
|
+
stage-one approximation are needed. The reduction stays exact when observed trial
|
|
55
|
+
or session predictors (task condition, practice) shift the drift.
|
|
56
|
+
|
|
57
|
+
## Install
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
pip install ouddm # once released on PyPI
|
|
61
|
+
pip install -e ".[dev]" # from a clone, with test dependencies
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## Quick start
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
import numpy as np
|
|
68
|
+
import ouddm
|
|
69
|
+
|
|
70
|
+
# data: one row per trial with columns person, occasion, time (days),
|
|
71
|
+
# rt (seconds), correct (1 = upper boundary, 0 = lower boundary)
|
|
72
|
+
sim = ouddm.simulate_study(ouddm.OUDDMParams(),
|
|
73
|
+
ouddm.DesignParams(n_persons=50, n_occasions=10, n_trials=40),
|
|
74
|
+
np.random.default_rng(1))
|
|
75
|
+
trials = sim["trials"]
|
|
76
|
+
|
|
77
|
+
fit = ouddm.fit_exact(trials) # joint ML: a, ter, mu0, tau, theta, sigma
|
|
78
|
+
print(fit.halflife, fit.halflife_ci()) # half-life (days) with 95% Wald interval
|
|
79
|
+
print(fit.a, fit.ter)
|
|
80
|
+
|
|
81
|
+
# task condition and practice as drift predictors (trial drift = OU state + x'beta)
|
|
82
|
+
# trials["cond"] = ...; trials["day_c"] = ...
|
|
83
|
+
# fit = ouddm.fit_exact(trials, covariates=["cond", "day_c"]); print(fit.beta, fit.se_beta)
|
|
84
|
+
|
|
85
|
+
# plan a study: plug-in SE of log half-life for a schedule
|
|
86
|
+
sched = ouddm.schedule(n_sessions=20, window=14.0, spacing="even")
|
|
87
|
+
print(ouddm.design_information(sched, n_trials=20, a=1.2, mu0=1.5, tau=0.3,
|
|
88
|
+
theta=0.5, sigma=0.35, n_persons=50))
|
|
89
|
+
print(ouddm.compare_designs(budget=400, sessions=[4, 10, 20, 40], window=14.0, halflife=1.4))
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## Main functions
|
|
93
|
+
|
|
94
|
+
| Function | Purpose |
|
|
95
|
+
|---|---|
|
|
96
|
+
| `fit_exact` | Joint ML from the exact collapsed likelihood, with half-life interval and optional drift predictors |
|
|
97
|
+
| `fit_two_stage_ml` | Two-stage comparator with shared `a`, `ter`; optional variance propagation |
|
|
98
|
+
| `DesignData`, `fit_design` | Exact likelihood for real task designs: stimulus coding, condition-specific boundary and start point, person-specific non-decision time, drift predictors, session deviations |
|
|
99
|
+
| `profile_theta`, `profile_interval` | Profile-likelihood interval for the half-life (use when θ is near a bound) |
|
|
100
|
+
| `two_stage`, `ez_by_occasion` | EZ-diffusion two-stage estimators (naive, constant error) |
|
|
101
|
+
| `design_information`, `compare_designs`, `schedule` | Design calculator for the half-life |
|
|
102
|
+
| `information_ratio_choice` | Share of per-trial drift information kept by choices alone, x / sinh(x) |
|
|
103
|
+
| `wiener_logpdf`, `wiener_cdf` | Exact Wiener first-passage density and CDF |
|
|
104
|
+
| `simulate_study` | Simulator with exact OU transitions and a bridge-corrected Wiener sampler |
|
|
105
|
+
|
|
106
|
+
## Assumptions
|
|
107
|
+
|
|
108
|
+
- Diffusion scale fixed at 1. Drift constant within a session apart from observed predictors.
|
|
109
|
+
- `a`, `w`, and `ter` are shared across sessions and persons. In the current
|
|
110
|
+
version, `w = 1/2` is fixed during estimation.
|
|
111
|
+
- No across-trial variability in non-decision time or starting point, and no
|
|
112
|
+
contaminant responses.
|
|
113
|
+
|
|
114
|
+
## Reproducing the paper
|
|
115
|
+
|
|
116
|
+
```bash
|
|
117
|
+
pytest -q
|
|
118
|
+
python examples/main_study.py 100 results # Simulation study 1 (~45 min, 2 cores)
|
|
119
|
+
python examples/design_study.py 40 results # Simulation study 2 (~60 min, 2 cores)
|
|
120
|
+
python examples/condition_study.py 40 results # Simulation study 3 (~25 min, 2 cores)
|
|
121
|
+
# Application: download data_merged.csv and ColorShapesTrialData_n69.csv from https://osf.io/ty4uf/
|
|
122
|
+
python -I examples/color_shapes_application.py <path>/data_merged.csv results # ~12 min
|
|
123
|
+
python -I examples/color_shapes_revision.py <path>/data_merged.csv A results # M3n + S1, ~56 min
|
|
124
|
+
python -I examples/color_shapes_revision.py <path>/data_merged.csv B results # S2 + S3, ~39 min
|
|
125
|
+
python -I examples/color_shapes_revision.py <path>/data_merged.csv C results # M2n, ~20 min
|
|
126
|
+
python -I examples/color_shapes_ou_bound.py <path>/data_merged.csv results # OU SD bounds under S1
|
|
127
|
+
python -I examples/color_shapes_s1_noou.py <path>/data_merged.csv results # S1 without OU, Table 6
|
|
128
|
+
python -I examples/color_shapes_counts.py <path>/data_merged.csv results
|
|
129
|
+
python -I examples/color_shapes_descriptives.py <path>/ColorShapesTrialData_n69.csv results
|
|
130
|
+
python examples/stage1_error_diagnostic.py 20 results
|
|
131
|
+
python examples/paper_figures.py results figures
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
The manuscript build files (`paper/`) are not part of the package. They are in
|
|
135
|
+
the replication archive that accompanies the article, with instructions in
|
|
136
|
+
`REPLICATION.md`.
|
|
137
|
+
|
|
138
|
+
## Citation
|
|
139
|
+
|
|
140
|
+
Hait, S. (2026). *Estimating the half-life of cognitive fluctuations from short
|
|
141
|
+
repeated tasks: An exact likelihood for diffusion models with Ornstein–Uhlenbeck
|
|
142
|
+
drift.* Manuscript in preparation.
|
ouddm-0.4.4/README.md
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
# ouddm
|
|
2
|
+
|
|
3
|
+
Exact likelihood and study design for drift diffusion models (DDMs) whose drift
|
|
4
|
+
rate follows an Ornstein–Uhlenbeck (OU) process across repeated sessions. It is
|
|
5
|
+
built for intensive longitudinal cognitive data such as smartphone-based
|
|
6
|
+
ambulatory assessments.
|
|
7
|
+
|
|
8
|
+
Author: Subir Hait, Michigan State University · License: MIT
|
|
9
|
+
|
|
10
|
+
## What it does
|
|
11
|
+
|
|
12
|
+
Person *i* completes short two-choice sessions at times *t_ij* (days, irregular
|
|
13
|
+
spacing allowed). Within a session, trials follow a Wiener diffusion with drift
|
|
14
|
+
`v_ij`, boundary `a`, start `w·a`, diffusion scale 1, and non-decision time `ter`.
|
|
15
|
+
Across sessions, the drift follows an OU process:
|
|
16
|
+
|
|
17
|
+
dv = θ (μ_i − v) dt + σ dW, μ_i ~ N(μ0, τ²), half-life = ln 2 / θ
|
|
18
|
+
|
|
19
|
+
**Key result.** A session-constant drift enters the Wiener likelihood only through
|
|
20
|
+
a quadratic term, so as a function of the drift each session's likelihood is an
|
|
21
|
+
exact Gaussian kernel:
|
|
22
|
+
|
|
23
|
+
l_j(v) − l_j(0) = b_j v − S_j v² / 2,
|
|
24
|
+
b_j = a[(1−w) N_jU − w N_jL], S_j = Σ decision times
|
|
25
|
+
|
|
26
|
+
The kernel is centered at `m_j = b_j / S_j` with curvature `S_j`. (This is a
|
|
27
|
+
statement about the likelihood; `m_j` itself is biased upward in short sessions:
|
|
28
|
+
`E[m|v] = v E[S] E[1/S]`.) All latent drifts and person means integrate out in
|
|
29
|
+
closed form, giving the exact likelihood of all choices and RTs. No MCMC and no
|
|
30
|
+
stage-one approximation are needed. The reduction stays exact when observed trial
|
|
31
|
+
or session predictors (task condition, practice) shift the drift.
|
|
32
|
+
|
|
33
|
+
## Install
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
pip install ouddm # once released on PyPI
|
|
37
|
+
pip install -e ".[dev]" # from a clone, with test dependencies
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Quick start
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
import numpy as np
|
|
44
|
+
import ouddm
|
|
45
|
+
|
|
46
|
+
# data: one row per trial with columns person, occasion, time (days),
|
|
47
|
+
# rt (seconds), correct (1 = upper boundary, 0 = lower boundary)
|
|
48
|
+
sim = ouddm.simulate_study(ouddm.OUDDMParams(),
|
|
49
|
+
ouddm.DesignParams(n_persons=50, n_occasions=10, n_trials=40),
|
|
50
|
+
np.random.default_rng(1))
|
|
51
|
+
trials = sim["trials"]
|
|
52
|
+
|
|
53
|
+
fit = ouddm.fit_exact(trials) # joint ML: a, ter, mu0, tau, theta, sigma
|
|
54
|
+
print(fit.halflife, fit.halflife_ci()) # half-life (days) with 95% Wald interval
|
|
55
|
+
print(fit.a, fit.ter)
|
|
56
|
+
|
|
57
|
+
# task condition and practice as drift predictors (trial drift = OU state + x'beta)
|
|
58
|
+
# trials["cond"] = ...; trials["day_c"] = ...
|
|
59
|
+
# fit = ouddm.fit_exact(trials, covariates=["cond", "day_c"]); print(fit.beta, fit.se_beta)
|
|
60
|
+
|
|
61
|
+
# plan a study: plug-in SE of log half-life for a schedule
|
|
62
|
+
sched = ouddm.schedule(n_sessions=20, window=14.0, spacing="even")
|
|
63
|
+
print(ouddm.design_information(sched, n_trials=20, a=1.2, mu0=1.5, tau=0.3,
|
|
64
|
+
theta=0.5, sigma=0.35, n_persons=50))
|
|
65
|
+
print(ouddm.compare_designs(budget=400, sessions=[4, 10, 20, 40], window=14.0, halflife=1.4))
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## Main functions
|
|
69
|
+
|
|
70
|
+
| Function | Purpose |
|
|
71
|
+
|---|---|
|
|
72
|
+
| `fit_exact` | Joint ML from the exact collapsed likelihood, with half-life interval and optional drift predictors |
|
|
73
|
+
| `fit_two_stage_ml` | Two-stage comparator with shared `a`, `ter`; optional variance propagation |
|
|
74
|
+
| `DesignData`, `fit_design` | Exact likelihood for real task designs: stimulus coding, condition-specific boundary and start point, person-specific non-decision time, drift predictors, session deviations |
|
|
75
|
+
| `profile_theta`, `profile_interval` | Profile-likelihood interval for the half-life (use when θ is near a bound) |
|
|
76
|
+
| `two_stage`, `ez_by_occasion` | EZ-diffusion two-stage estimators (naive, constant error) |
|
|
77
|
+
| `design_information`, `compare_designs`, `schedule` | Design calculator for the half-life |
|
|
78
|
+
| `information_ratio_choice` | Share of per-trial drift information kept by choices alone, x / sinh(x) |
|
|
79
|
+
| `wiener_logpdf`, `wiener_cdf` | Exact Wiener first-passage density and CDF |
|
|
80
|
+
| `simulate_study` | Simulator with exact OU transitions and a bridge-corrected Wiener sampler |
|
|
81
|
+
|
|
82
|
+
## Assumptions
|
|
83
|
+
|
|
84
|
+
- Diffusion scale fixed at 1. Drift constant within a session apart from observed predictors.
|
|
85
|
+
- `a`, `w`, and `ter` are shared across sessions and persons. In the current
|
|
86
|
+
version, `w = 1/2` is fixed during estimation.
|
|
87
|
+
- No across-trial variability in non-decision time or starting point, and no
|
|
88
|
+
contaminant responses.
|
|
89
|
+
|
|
90
|
+
## Reproducing the paper
|
|
91
|
+
|
|
92
|
+
```bash
|
|
93
|
+
pytest -q
|
|
94
|
+
python examples/main_study.py 100 results # Simulation study 1 (~45 min, 2 cores)
|
|
95
|
+
python examples/design_study.py 40 results # Simulation study 2 (~60 min, 2 cores)
|
|
96
|
+
python examples/condition_study.py 40 results # Simulation study 3 (~25 min, 2 cores)
|
|
97
|
+
# Application: download data_merged.csv and ColorShapesTrialData_n69.csv from https://osf.io/ty4uf/
|
|
98
|
+
python -I examples/color_shapes_application.py <path>/data_merged.csv results # ~12 min
|
|
99
|
+
python -I examples/color_shapes_revision.py <path>/data_merged.csv A results # M3n + S1, ~56 min
|
|
100
|
+
python -I examples/color_shapes_revision.py <path>/data_merged.csv B results # S2 + S3, ~39 min
|
|
101
|
+
python -I examples/color_shapes_revision.py <path>/data_merged.csv C results # M2n, ~20 min
|
|
102
|
+
python -I examples/color_shapes_ou_bound.py <path>/data_merged.csv results # OU SD bounds under S1
|
|
103
|
+
python -I examples/color_shapes_s1_noou.py <path>/data_merged.csv results # S1 without OU, Table 6
|
|
104
|
+
python -I examples/color_shapes_counts.py <path>/data_merged.csv results
|
|
105
|
+
python -I examples/color_shapes_descriptives.py <path>/ColorShapesTrialData_n69.csv results
|
|
106
|
+
python examples/stage1_error_diagnostic.py 20 results
|
|
107
|
+
python examples/paper_figures.py results figures
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
The manuscript build files (`paper/`) are not part of the package. They are in
|
|
111
|
+
the replication archive that accompanies the article, with instructions in
|
|
112
|
+
`REPLICATION.md`.
|
|
113
|
+
|
|
114
|
+
## Citation
|
|
115
|
+
|
|
116
|
+
Hait, S. (2026). *Estimating the half-life of cognitive fluctuations from short
|
|
117
|
+
repeated tasks: An exact likelihood for diffusion models with Ornstein–Uhlenbeck
|
|
118
|
+
drift.* Manuscript in preparation.
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Empirical application: Color Shapes smartphone study (Kim et al., 2025).
|
|
2
|
+
|
|
3
|
+
Data: data_merged.csv from the authors' OSF repository (https://osf.io/ty4uf/,
|
|
4
|
+
"Files for June 11 2025 submission/2_processing/"), which already excludes
|
|
5
|
+
trials without a response and RTs < 200 ms or > 7000 ms.
|
|
6
|
+
|
|
7
|
+
Coding
|
|
8
|
+
upper boundary = "different" response (button_pressed = 1); stimulus sign
|
|
9
|
+
s = +1 for "different" trials, -1 for "same" trials (stimulus coding, as
|
|
10
|
+
in the authors' JAGS model). Session = one task version (60 trials); two
|
|
11
|
+
versions per day, done back to back. Session time = day - 1, plus the
|
|
12
|
+
duration of the first version (task_time, minutes) for the second version.
|
|
13
|
+
|
|
14
|
+
Models (all fitted with the exact likelihood, design_model.fit_design)
|
|
15
|
+
M0 no design: one boundary, one start point, no drift predictors
|
|
16
|
+
M1 nuisance design: boundary by choice urgency, start point by
|
|
17
|
+
probability of change, no drift predictors
|
|
18
|
+
M2 M1 + the four task manipulations as drift predictors
|
|
19
|
+
M3 M2 + practice (day, centered) as a drift predictor
|
|
20
|
+
M2n, M3n M2 and M3 plus independent session-level drift deviations
|
|
21
|
+
(variance omega^2). Each person completes each of the 16 task
|
|
22
|
+
versions once, so person-specific version effects appear as
|
|
23
|
+
session-specific deviations; the nugget absorbs them.
|
|
24
|
+
Also: two-stage EZ-diffusion, naive (accuracy coding), for reference.
|
|
25
|
+
|
|
26
|
+
Usage: python -I color_shapes_application.py <data_merged.csv> [outdir]
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
import sys
|
|
30
|
+
import time
|
|
31
|
+
from pathlib import Path
|
|
32
|
+
|
|
33
|
+
import numpy as np
|
|
34
|
+
import pandas as pd
|
|
35
|
+
|
|
36
|
+
from ouddm import ez_by_occasion, fit_ou
|
|
37
|
+
from ouddm.design_model import DesignData, fit_design
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def load(path):
|
|
41
|
+
d = pd.read_csv(path, low_memory=False)
|
|
42
|
+
d = d.rename(columns={"participant_id": "person"})
|
|
43
|
+
d["task2"] = (d["sequential_task_order"] == "task2").astype(int)
|
|
44
|
+
d["occasion"] = d["day"] * 2 + d["task2"]
|
|
45
|
+
first = (d[d.task2 == 0].groupby(["person", "day"])["task_time"].first().rename("t1_dur"))
|
|
46
|
+
d = d.merge(first, on=["person", "day"], how="left")
|
|
47
|
+
d["t1_dur"] = d["t1_dur"].fillna(d["task_time"].median())
|
|
48
|
+
d["time"] = (d["day"] - 1) + d["task2"] * d["t1_dur"] / 1440.0
|
|
49
|
+
d["rt"] = d["response_time"] / 1000.0
|
|
50
|
+
d["upper"] = d["button_pressed"].astype(int)
|
|
51
|
+
d["stim"] = np.where(d["trial_type"] == 1, 1.0, -1.0)
|
|
52
|
+
d["correct"] = d["accuracy"].astype(int)
|
|
53
|
+
for c in ["StudyTimeCoded", "ChoiceUrgencyCoded", "ProbOfChangeCoded", "ProbeTypeCoded"]:
|
|
54
|
+
d[c + "_c"] = d[c] - 0.5
|
|
55
|
+
d["day_c"] = d["day"] - 4.5
|
|
56
|
+
return d
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
MANIP = ["StudyTimeCoded_c", "ChoiceUrgencyCoded_c", "ProbOfChangeCoded_c", "ProbeTypeCoded_c"]
|
|
60
|
+
MODELS = {
|
|
61
|
+
"M0 no design": dict(boundary=(), bias=(), drift=()),
|
|
62
|
+
"M1 nuisance design": dict(boundary=("ChoiceUrgencyCoded",), bias=("ProbOfChangeCoded",), drift=()),
|
|
63
|
+
"M2 + manipulations on drift": dict(boundary=("ChoiceUrgencyCoded",), bias=("ProbOfChangeCoded",), drift=tuple(MANIP)),
|
|
64
|
+
"M3 + practice on drift": dict(boundary=("ChoiceUrgencyCoded",), bias=("ProbOfChangeCoded",), drift=tuple(MANIP) + ("day_c",)),
|
|
65
|
+
"M2n M2 + session deviations": dict(boundary=("ChoiceUrgencyCoded",), bias=("ProbOfChangeCoded",), drift=tuple(MANIP), nugget=True),
|
|
66
|
+
"M3n M3 + session deviations": dict(boundary=("ChoiceUrgencyCoded",), bias=("ProbOfChangeCoded",), drift=tuple(MANIP) + ("day_c",), nugget=True),
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def main():
|
|
71
|
+
path = Path(sys.argv[1])
|
|
72
|
+
outdir = Path(sys.argv[2]) if len(sys.argv) > 2 else Path("results")
|
|
73
|
+
outdir.mkdir(parents=True, exist_ok=True)
|
|
74
|
+
d = load(path)
|
|
75
|
+
desc = {"persons": d.person.nunique(), "sessions": d.groupby(["person", "occasion"]).ngroups,
|
|
76
|
+
"trials": len(d), "accuracy": d.correct.mean(), "median_rt": d.rt.median()}
|
|
77
|
+
print(desc)
|
|
78
|
+
rows, coefs = [], []
|
|
79
|
+
for name, spec in MODELS.items():
|
|
80
|
+
t0 = time.time()
|
|
81
|
+
data = DesignData.from_trials(d, "stim", **spec)
|
|
82
|
+
f = fit_design(data)
|
|
83
|
+
lo, hi = f.halflife_ci
|
|
84
|
+
rows.append({"model": name, "halflife_days": f.halflife, "hl_lo": lo, "hl_hi": hi,
|
|
85
|
+
"theta": f.params["theta"], "tau": f.params["tau"], "sigma": f.params["sigma"],
|
|
86
|
+
"stationary_sd": f.params["sd_stat"], "omega": f.params["omega"],
|
|
87
|
+
"kappa": f.params["kappa"], "loglik": f.loglik, "n_params": f.n_params, "aic": f.aic,
|
|
88
|
+
"converged": f.converged, "theta_at_bound": f.theta_at_bound,
|
|
89
|
+
"seconds": time.time() - t0})
|
|
90
|
+
for k, v in f.params.items():
|
|
91
|
+
coefs.append({"model": name, "param": k, "estimate": v, "se": f.se.get(k, np.nan)})
|
|
92
|
+
print(rows[-1])
|
|
93
|
+
# two-stage EZ, naive (accuracy coding)
|
|
94
|
+
tr = d[["person", "occasion", "time", "rt", "correct"]]
|
|
95
|
+
est = ez_by_occasion(tr)
|
|
96
|
+
ez = fit_ou(est.person, est.time, est.v_hat, se=True)
|
|
97
|
+
lo, hi = ez.halflife_ci()
|
|
98
|
+
rows.append({"model": "EZ two-stage, naive", "halflife_days": ez.halflife, "hl_lo": lo, "hl_hi": hi,
|
|
99
|
+
"theta": ez.theta, "tau": ez.tau, "sigma": ez.sigma,
|
|
100
|
+
"stationary_sd": ez.sigma / np.sqrt(2 * ez.theta), "converged": ez.converged,
|
|
101
|
+
"theta_at_bound": "upper" if np.log(ez.theta) >= 3 - 1e-6 else ""})
|
|
102
|
+
res = pd.DataFrame(rows)
|
|
103
|
+
res.to_csv(outdir / "colorshapes_models.csv", index=False)
|
|
104
|
+
pd.DataFrame(coefs).to_csv(outdir / "colorshapes_coefficients.csv", index=False)
|
|
105
|
+
pd.DataFrame([desc]).to_csv(outdir / "colorshapes_descriptives.csv", index=False)
|
|
106
|
+
with pd.option_context("display.width", 250, "display.precision", 3, "display.max_columns", 30):
|
|
107
|
+
print(res.to_string(index=False))
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
if __name__ == "__main__":
|
|
111
|
+
main()
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Trial, session, and person counts for the Color Shapes analysis subsets.
|
|
2
|
+
|
|
3
|
+
Usage: python -I color_shapes_counts.py <data_merged.csv> [outdir]
|
|
4
|
+
"""
|
|
5
|
+
import sys
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import pandas as pd
|
|
9
|
+
|
|
10
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
11
|
+
import color_shapes_application as app # noqa: E402
|
|
12
|
+
|
|
13
|
+
d = app.load(Path(sys.argv[1]))
|
|
14
|
+
outdir = Path(sys.argv[2]) if len(sys.argv) > 2 else Path("results")
|
|
15
|
+
rows = []
|
|
16
|
+
for name, sub in (("all", d), ("long deadline only", d[d.ChoiceUrgencyCoded == 0])):
|
|
17
|
+
rows.append({"subset": name, "trials": len(sub), "persons": sub["person"].nunique(),
|
|
18
|
+
"sessions": sub.groupby(["person", "time"]).ngroups})
|
|
19
|
+
pd.DataFrame(rows).to_csv(outdir / "colorshapes_counts.csv", index=False)
|
|
20
|
+
print(pd.DataFrame(rows))
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""Missing-response (timeout) rates in the raw Color Shapes trial file, by choice
|
|
2
|
+
urgency. Usage: python -I color_shapes_descriptives.py <ColorShapesTrialData_n69.csv> [outdir]"""
|
|
3
|
+
import sys
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
import pandas as pd
|
|
7
|
+
|
|
8
|
+
raw = pd.read_csv(sys.argv[1])
|
|
9
|
+
outdir = Path(sys.argv[2]) if len(sys.argv) > 2 else Path("results")
|
|
10
|
+
raw = raw[raw.participant_id != 4039] # excluded by the original authors
|
|
11
|
+
raw["urgent"] = raw.task_version.str.contains("RT-")
|
|
12
|
+
rows = []
|
|
13
|
+
for u, g in raw.groupby("urgent"):
|
|
14
|
+
rows.append({"window": "3000 ms" if u else "10000 ms", "trials": len(g),
|
|
15
|
+
"no_response_rate": (g.response_time == -999).mean()})
|
|
16
|
+
rows.append({"window": "all", "trials": len(raw), "no_response_rate": (raw.response_time == -999).mean()})
|
|
17
|
+
pd.DataFrame(rows).to_csv(outdir / "colorshapes_timeouts.csv", index=False)
|
|
18
|
+
print(pd.DataFrame(rows))
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Upper 95% profile bound on the SD of an OU component with a given half-life,
|
|
2
|
+
under the person-specific practice-slope model (S1). The half-life is fixed;
|
|
3
|
+
the OU stationary SD is profiled; all other parameters are re-maximized.
|
|
4
|
+
|
|
5
|
+
Usage: python -I color_shapes_ou_bound.py <data_merged.csv> [outdir]
|
|
6
|
+
"""
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
import pandas as pd
|
|
12
|
+
from scipy.optimize import brentq, minimize
|
|
13
|
+
|
|
14
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
15
|
+
import color_shapes_application as app # noqa: E402
|
|
16
|
+
from color_shapes_revision import BASE # noqa: E402
|
|
17
|
+
from ouddm.design_model import DesignData, _bounds, _names, _starts, design_loglik, fit_design # noqa: E402
|
|
18
|
+
|
|
19
|
+
d = app.load(Path(sys.argv[1]))
|
|
20
|
+
outdir = Path(sys.argv[2]) if len(sys.argv) > 2 else Path("results")
|
|
21
|
+
data = DesignData.from_trials(d, "stim", **BASE, slope="day_c")
|
|
22
|
+
names = _names(data)
|
|
23
|
+
ilt, isd = names.index("log_theta"), names.index("log_sd_stat")
|
|
24
|
+
fit = fit_design(data, se=False)
|
|
25
|
+
ref = fit.loglik
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def prof(log_theta, log_sd):
|
|
29
|
+
b = _bounds(data, fix_theta=log_theta)
|
|
30
|
+
b[isd] = (log_sd, log_sd)
|
|
31
|
+
best = None
|
|
32
|
+
for z in [fit.x] + _starts(data, thetas=(np.exp(log_theta),)):
|
|
33
|
+
z = z.copy(); z[ilt] = log_theta; z[isd] = log_sd
|
|
34
|
+
r = minimize(lambda x: -design_loglik(x, data), z, method="L-BFGS-B", bounds=b)
|
|
35
|
+
if best is None or r.fun < best.fun:
|
|
36
|
+
best = r
|
|
37
|
+
return -best.fun
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
rows = []
|
|
41
|
+
for hl in (1.0, 2.0):
|
|
42
|
+
lt = np.log(np.log(2) / hl)
|
|
43
|
+
g = lambda lsd: 2 * (ref - prof(lt, lsd)) - 3.841
|
|
44
|
+
lo, hi = np.log(0.01), np.log(0.6)
|
|
45
|
+
sd_up = float(np.exp(brentq(g, lo, hi, xtol=0.005)))
|
|
46
|
+
rows.append({"halflife_days": hl, "ou_sd_upper95": sd_up, "ref_loglik": ref})
|
|
47
|
+
print(rows[-1], flush=True)
|
|
48
|
+
pd.DataFrame(rows).to_csv(outdir / "colorshapes_ou_sd_bounds.csv", index=False)
|