ouddm 0.4.4__py3-none-any.whl
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/__init__.py +40 -0
- ouddm/collapsed.py +78 -0
- ouddm/design.py +102 -0
- ouddm/design_model.py +390 -0
- ouddm/estimate.py +311 -0
- ouddm/ez.py +56 -0
- ouddm/ou.py +152 -0
- ouddm/simulate.py +194 -0
- ouddm/twostage.py +27 -0
- ouddm/wiener.py +89 -0
- ouddm-0.4.4.dist-info/METADATA +142 -0
- ouddm-0.4.4.dist-info/RECORD +15 -0
- ouddm-0.4.4.dist-info/WHEEL +5 -0
- ouddm-0.4.4.dist-info/licenses/LICENSE +21 -0
- ouddm-0.4.4.dist-info/top_level.txt +1 -0
ouddm/__init__.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""ouddm: drift diffusion models with Ornstein-Uhlenbeck dynamics in drift rate.
|
|
2
|
+
|
|
3
|
+
Main entry points
|
|
4
|
+
-----------------
|
|
5
|
+
fit_exact(trials, covariates=()) joint ML from the exact collapsed likelihood,
|
|
6
|
+
optionally with drift predictors (task condition, practice)
|
|
7
|
+
fit_two_stage_ml(trials) shared-nuisance two-stage comparator
|
|
8
|
+
fit_design(DesignData...) exact likelihood for real task designs: stimulus coding,
|
|
9
|
+
condition-specific boundary and start point, person-specific
|
|
10
|
+
non-decision time, drift predictors, session deviations
|
|
11
|
+
profile_theta(...) profile likelihood of the half-life
|
|
12
|
+
design_information(...) plug-in SE of the drift half-life for a schedule
|
|
13
|
+
compare_designs(...) fixed-budget comparison of session schedules
|
|
14
|
+
simulate_study(...) simulate OU-drift DDM data
|
|
15
|
+
|
|
16
|
+
Input data: one row per trial with columns person, occasion, time (days),
|
|
17
|
+
rt (seconds), correct (1 = upper boundary, 0 = lower boundary).
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from .collapsed import collapsed_loglik, fit_collapsed, session_summaries
|
|
21
|
+
from .design import compare_designs, design_information, schedule, trial_information
|
|
22
|
+
from .design_model import DesignData, DesignFit, fit_design, profile_interval, profile_theta, supported_regions
|
|
23
|
+
from .estimate import JointFit, SessionData, fit_exact, fit_two_stage_ml
|
|
24
|
+
from .ez import ez_by_occasion, ez_diffusion
|
|
25
|
+
from .ou import OUFit, fit_ou
|
|
26
|
+
from .simulate import DesignParams, OUDDMParams, simulate_ou, simulate_study, simulate_wiener
|
|
27
|
+
from .twostage import oracle, two_stage
|
|
28
|
+
from .wiener import information_ratio_choice, wiener_cdf, wiener_logpdf
|
|
29
|
+
|
|
30
|
+
__version__ = "0.4.4"
|
|
31
|
+
|
|
32
|
+
__all__ = [
|
|
33
|
+
"fit_exact", "fit_two_stage_ml", "JointFit", "SessionData",
|
|
34
|
+
"DesignData", "DesignFit", "fit_design", "profile_theta", "profile_interval", "supported_regions",
|
|
35
|
+
"design_information", "compare_designs", "schedule", "trial_information",
|
|
36
|
+
"collapsed_loglik", "fit_collapsed", "session_summaries",
|
|
37
|
+
"DesignParams", "OUDDMParams", "simulate_ou", "simulate_study", "simulate_wiener",
|
|
38
|
+
"ez_by_occasion", "ez_diffusion", "two_stage", "oracle", "fit_ou", "OUFit",
|
|
39
|
+
"information_ratio_choice", "wiener_cdf", "wiener_logpdf",
|
|
40
|
+
]
|
ouddm/collapsed.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""Exact collapsed (marginal) likelihood for the OU-drift DDM.
|
|
2
|
+
|
|
3
|
+
With s = 1, a centered start (w = 1/2), and drift v_j constant within
|
|
4
|
+
session j, the session log-likelihood is exactly quadratic in v_j:
|
|
5
|
+
|
|
6
|
+
l_j(v) - l_j(0) = b_j v - S_j v^2 / 2,
|
|
7
|
+
b_j = (a / 2) (N_j+ - N_j-), S_j = sum_r T_jr (decision times).
|
|
8
|
+
|
|
9
|
+
So, up to a factor free of v, session j contributes a Gaussian
|
|
10
|
+
'observation' m_j = b_j / S_j of v_j with known variance 1 / S_j.
|
|
11
|
+
Because the OU states and person means are Gaussian, all of them
|
|
12
|
+
integrate out exactly:
|
|
13
|
+
|
|
14
|
+
log L = sum_j l_j(0) + sum_j [ b_j^2 / (2 S_j) + 0.5 log(2 pi / S_j) ]
|
|
15
|
+
+ sum_i log N( m_i | mu0 1, tau^2 11' + K_i(theta, sigma) + diag(1/S_i) ).
|
|
16
|
+
|
|
17
|
+
The first two sums depend on (a, ter) and the data only. For fixed
|
|
18
|
+
(a, ter) the OU parameters are estimated from the last term, which is
|
|
19
|
+
the hierarchical OU model with known heteroskedastic noise. The noise
|
|
20
|
+
variance 1/S_j is exact and session-specific: it shrinks with more
|
|
21
|
+
trials and with longer decision times.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import numpy as np
|
|
27
|
+
import pandas as pd
|
|
28
|
+
from scipy.stats import multivariate_normal
|
|
29
|
+
|
|
30
|
+
from .ou import OUFit, fit_ou
|
|
31
|
+
from .wiener import wiener_logpdf
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def session_summaries(trials: pd.DataFrame, a: float, ter: float) -> pd.DataFrame:
|
|
35
|
+
"""Per person-session sufficient statistics for the drift.
|
|
36
|
+
|
|
37
|
+
Returns person, occasion, time, n, b, S, m (= b/S), var (= 1/S).
|
|
38
|
+
Trials with rt <= ter are invalid under the model and raise.
|
|
39
|
+
"""
|
|
40
|
+
T = trials["rt"].to_numpy() - ter
|
|
41
|
+
if np.any(T <= 0):
|
|
42
|
+
raise ValueError("some rt <= ter; decision times must be positive")
|
|
43
|
+
df = trials.assign(T=T, sgn=np.where(trials["correct"].to_numpy() == 1, 1.0, -1.0))
|
|
44
|
+
g = df.groupby(["person", "occasion"], sort=True)
|
|
45
|
+
out = g.agg(time=("time", "first"), n=("T", "size"), S=("T", "sum"), d=("sgn", "sum")).reset_index()
|
|
46
|
+
out["b"] = 0.5 * a * out["d"]
|
|
47
|
+
out["m"] = out["b"] / out["S"]
|
|
48
|
+
out["var"] = 1.0 / out["S"]
|
|
49
|
+
return out.drop(columns="d")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def collapsed_constant(trials: pd.DataFrame, summ: pd.DataFrame, a: float, ter: float) -> float:
|
|
53
|
+
"""sum_j l_j(0) + sum_j [b_j^2/(2 S_j) + 0.5 log(2 pi / S_j)]: the part of the
|
|
54
|
+
log marginal likelihood free of the OU parameters (needed to estimate a, ter)."""
|
|
55
|
+
l0 = wiener_logpdf(trials["rt"].to_numpy() - ter, trials["correct"].to_numpy(), 0.0, a).sum()
|
|
56
|
+
return float(l0 + np.sum(summ["b"] ** 2 / (2 * summ["S"]) + 0.5 * np.log(2 * np.pi / summ["S"])))
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def collapsed_loglik(trials: pd.DataFrame, a: float, ter: float, mu0: float, tau: float,
|
|
60
|
+
theta: float, sigma: float) -> float:
|
|
61
|
+
"""Exact log marginal likelihood of all choices and RTs, with every session
|
|
62
|
+
drift and person home base integrated out."""
|
|
63
|
+
summ = session_summaries(trials, a, ter)
|
|
64
|
+
ll = collapsed_constant(trials, summ, a, ter)
|
|
65
|
+
for _, g in summ.groupby("person"):
|
|
66
|
+
t = g["time"].to_numpy()
|
|
67
|
+
d = np.abs(t[:, None] - t[None, :])
|
|
68
|
+
C = tau ** 2 + sigma ** 2 / (2 * theta) * np.exp(-theta * d) + np.diag(g["var"].to_numpy())
|
|
69
|
+
ll += multivariate_normal(mean=np.full(t.size, mu0), cov=C).logpdf(g["m"].to_numpy())
|
|
70
|
+
return float(ll)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def fit_collapsed(trials: pd.DataFrame, a: float, ter: float) -> tuple[OUFit, pd.DataFrame]:
|
|
74
|
+
"""ML estimates of (mu0, tau, theta, sigma) from the exact collapsed
|
|
75
|
+
likelihood, for known boundary separation a and non-decision time ter."""
|
|
76
|
+
summ = session_summaries(trials, a, ter)
|
|
77
|
+
fit = fit_ou(summ["person"], summ["time"], summ["m"], obs_var=summ["var"])
|
|
78
|
+
return fit, summ
|
ouddm/design.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Design calculator: expected precision of the drift half-life for a study
|
|
2
|
+
schedule, before data are collected.
|
|
3
|
+
|
|
4
|
+
Under the exact collapsed likelihood, session j contributes a Gaussian
|
|
5
|
+
observation of its drift with variance 1/S_j, S_j = total decision time.
|
|
6
|
+
The calculator replaces 1/S_j by its plug-in expectation 1/(n I_trial),
|
|
7
|
+
where I_trial is the per-trial Fisher information about drift:
|
|
8
|
+
|
|
9
|
+
choice + RT : I_trial = E[T | v] = (a / (2v)) tanh(a v / 2)
|
|
10
|
+
choice only : I_trial = a^2 p (1 - p), p = 1 / (1 + exp(-a v))
|
|
11
|
+
|
|
12
|
+
evaluated at the population home base v = mu0. The expected Fisher
|
|
13
|
+
information of the hierarchical Gaussian OU model then follows in closed
|
|
14
|
+
form, giving the standard error of log half-life (= SE of log theta).
|
|
15
|
+
The oracle (session drifts observed without error) sets the variance to 0.
|
|
16
|
+
|
|
17
|
+
This is an approximation (plug-in session variance, a and ter treated as
|
|
18
|
+
known). Rankings of designs should be checked by simulation; see
|
|
19
|
+
examples/design_study.py.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import numpy as np
|
|
25
|
+
import pandas as pd
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def trial_information(v: float, a: float, rt: bool = True) -> float:
|
|
29
|
+
if rt:
|
|
30
|
+
return (a / (2.0 * v)) * np.tanh(a * v / 2.0) if v != 0 else a ** 2 / 4.0
|
|
31
|
+
p = 1.0 / (1.0 + np.exp(-a * v))
|
|
32
|
+
return a ** 2 * p * (1.0 - p)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def schedule(n_sessions: int, window: float, spacing: str = "even", burst_gap: float = 0.1) -> np.ndarray:
|
|
36
|
+
"""Session times (days) over [0, window].
|
|
37
|
+
|
|
38
|
+
even : equally spaced.
|
|
39
|
+
burst : sessions in pairs, pair starts equally spaced, sessions within a
|
|
40
|
+
pair burst_gap days apart (a mix of short and long gaps).
|
|
41
|
+
"""
|
|
42
|
+
if spacing == "even":
|
|
43
|
+
return np.linspace(0.0, window, n_sessions)
|
|
44
|
+
if spacing == "burst":
|
|
45
|
+
if n_sessions % 2:
|
|
46
|
+
raise ValueError("burst spacing needs an even number of sessions")
|
|
47
|
+
starts = np.linspace(0.0, window - burst_gap, n_sessions // 2)
|
|
48
|
+
return np.sort(np.concatenate([starts, starts + burst_gap]))
|
|
49
|
+
raise ValueError("spacing must be 'even' or 'burst'")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _person_information(times, obs_var, tau, theta, sigma):
|
|
53
|
+
t = np.asarray(times, float)
|
|
54
|
+
D = np.abs(t[:, None] - t[None, :])
|
|
55
|
+
E = np.exp(-theta * D)
|
|
56
|
+
c = sigma ** 2 / (2 * theta)
|
|
57
|
+
S = tau ** 2 + c * E + np.diag(np.broadcast_to(obs_var, t.shape))
|
|
58
|
+
Si = np.linalg.inv(S)
|
|
59
|
+
dS = [2 * tau ** 2 * np.ones_like(S), # d / d log tau
|
|
60
|
+
-c * E - 0.5 * sigma ** 2 * D * E, # d / d log theta
|
|
61
|
+
2 * c * E] # d / d log sigma
|
|
62
|
+
I = np.empty((3, 3))
|
|
63
|
+
for k in range(3):
|
|
64
|
+
for l in range(k, 3):
|
|
65
|
+
I[k, l] = I[l, k] = 0.5 * np.trace(Si @ dS[k] @ Si @ dS[l])
|
|
66
|
+
return I
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def design_information(times, n_trials: int, a: float, mu0: float, tau: float, theta: float,
|
|
70
|
+
sigma: float, n_persons: int = 1, rt: bool = True) -> dict:
|
|
71
|
+
"""Expected SE of log half-life for a common schedule given to n_persons.
|
|
72
|
+
|
|
73
|
+
Returns se_log_halflife, se_oracle, relative_efficiency (oracle variance /
|
|
74
|
+
design variance; 1 = as good as observing the true session drifts), and
|
|
75
|
+
the plug-in session variance.
|
|
76
|
+
"""
|
|
77
|
+
v_obs = 1.0 / (n_trials * trial_information(mu0, a, rt))
|
|
78
|
+
I = n_persons * _person_information(times, v_obs, tau, theta, sigma)
|
|
79
|
+
I0 = n_persons * _person_information(times, 0.0, tau, theta, sigma)
|
|
80
|
+
se = float(np.sqrt(np.linalg.inv(I)[1, 1]))
|
|
81
|
+
se0 = float(np.sqrt(np.linalg.inv(I0)[1, 1]))
|
|
82
|
+
return {"se_log_halflife": se, "se_oracle": se0, "relative_efficiency": (se0 / se) ** 2,
|
|
83
|
+
"session_var": v_obs}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def compare_designs(budget: int, sessions: list[int], window: float, halflife: float,
|
|
87
|
+
a: float = 1.2, mu0: float = 1.5, tau: float = 0.3, stationary_sd: float = 0.35,
|
|
88
|
+
n_persons: int = 50, spacings=("even", "burst"), rt: bool = True) -> pd.DataFrame:
|
|
89
|
+
"""Fixed per-person trial budget split into K sessions of budget/K trials."""
|
|
90
|
+
theta = np.log(2) / halflife
|
|
91
|
+
sigma = stationary_sd * np.sqrt(2 * theta)
|
|
92
|
+
rows = []
|
|
93
|
+
for K in sessions:
|
|
94
|
+
n = budget // K
|
|
95
|
+
for sp in spacings:
|
|
96
|
+
try:
|
|
97
|
+
t = schedule(K, window, sp)
|
|
98
|
+
except ValueError:
|
|
99
|
+
continue
|
|
100
|
+
r = design_information(t, n, a, mu0, tau, theta, sigma, n_persons, rt)
|
|
101
|
+
rows.append({"sessions": K, "trials_per_session": n, "spacing": sp, "halflife": halflife, **r})
|
|
102
|
+
return pd.DataFrame(rows)
|
ouddm/design_model.py
ADDED
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
"""Exact likelihood for the OU-drift DDM with a full trial-level design.
|
|
2
|
+
|
|
3
|
+
This generalizes fit_exact() to the structure of real ambulatory tasks:
|
|
4
|
+
|
|
5
|
+
* stimulus coding: the upper boundary is one response option (e.g.
|
|
6
|
+
"different"), and the trial drift is s_r * eta_r, where s_r = +1 or -1
|
|
7
|
+
is the stimulus type (+1 when the upper response is correct);
|
|
8
|
+
* eta_r = u_i(t_ij) + x_r' beta: the OU state plus drift predictors;
|
|
9
|
+
* boundary a_r = exp(alpha' z_r) depends on boundary predictors z_r;
|
|
10
|
+
* start point w_r = logistic(gamma' q_r) depends on bias predictors q_r;
|
|
11
|
+
* person-specific non-decision time ter_i = kappa * min RT_i, 0 < kappa < 1;
|
|
12
|
+
* session-level OU state (optional), independent session deviations
|
|
13
|
+
(optional, variance omega^2), and a person-specific random slope on a
|
|
14
|
+
session-level variable such as practice (optional, correlated with the
|
|
15
|
+
random intercept).
|
|
16
|
+
|
|
17
|
+
For any a, w, s the trial log density in eta is exactly
|
|
18
|
+
log f(T | 0, a_r, w_r) + c_r eta - T eta^2 / 2,
|
|
19
|
+
c_r = s_r * a_r (1 - w_r) (upper response)
|
|
20
|
+
c_r = -s_r * a_r w_r (lower response),
|
|
21
|
+
so each session is still a Gaussian kernel in u with curvature S_j = sum T,
|
|
22
|
+
and Proposition 2 (all latent states integrate out) applies unchanged.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
from dataclasses import dataclass, field
|
|
28
|
+
|
|
29
|
+
import numpy as np
|
|
30
|
+
import pandas as pd
|
|
31
|
+
from scipy.optimize import minimize
|
|
32
|
+
|
|
33
|
+
from scipy.linalg import cho_factor, cho_solve
|
|
34
|
+
from scipy.optimize import brentq
|
|
35
|
+
|
|
36
|
+
from .estimate import LOG2PI, _num_hessian
|
|
37
|
+
from .wiener import _log_g
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _logistic(x):
|
|
41
|
+
return 1.0 / (1.0 + np.exp(-x))
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass
|
|
45
|
+
class DesignData:
|
|
46
|
+
rt: np.ndarray # RT (s) per trial
|
|
47
|
+
upper: np.ndarray # 1 = upper-boundary response
|
|
48
|
+
stim: np.ndarray # +1 / -1 stimulus sign
|
|
49
|
+
sess: np.ndarray # session index per trial (0..J-1)
|
|
50
|
+
minrt_trial: np.ndarray # min RT of the trial's person
|
|
51
|
+
Z: np.ndarray # boundary design (n, pa), first column = 1
|
|
52
|
+
Q: np.ndarray # bias design (n, pw), first column = 1
|
|
53
|
+
X: np.ndarray # drift predictors (n, k), no intercept
|
|
54
|
+
time: np.ndarray # session time
|
|
55
|
+
person: np.ndarray # person id per session
|
|
56
|
+
person_slices: list
|
|
57
|
+
J: int
|
|
58
|
+
names: dict = field(default_factory=dict)
|
|
59
|
+
zcache: dict = field(default_factory=dict)
|
|
60
|
+
nugget: bool = False # independent session-level drift deviations (variance omega^2)
|
|
61
|
+
ou: bool = True # OU state across sessions
|
|
62
|
+
slope_z: np.ndarray | None = None # session-level variable with a person-specific random slope
|
|
63
|
+
|
|
64
|
+
@classmethod
|
|
65
|
+
def from_trials(cls, trials: pd.DataFrame, stim_col: str, boundary=(), bias=(), drift=(),
|
|
66
|
+
nugget=False, ou=True, slope=None):
|
|
67
|
+
need = {"person", "occasion", "time", "rt", "upper", stim_col, *boundary, *bias, *drift}
|
|
68
|
+
if slope:
|
|
69
|
+
need.add(slope)
|
|
70
|
+
miss = need - set(trials.columns)
|
|
71
|
+
if miss:
|
|
72
|
+
raise ValueError(f"missing columns: {sorted(miss)}")
|
|
73
|
+
tr = trials.dropna(subset=list(need)).sort_values(["person", "time", "occasion"]).reset_index(drop=True)
|
|
74
|
+
agg = {"time": ("time", "first")}
|
|
75
|
+
if slope:
|
|
76
|
+
agg["slope_z"] = (slope, "first")
|
|
77
|
+
s = (tr.groupby(["person", "occasion"], sort=False).agg(**agg).reset_index()
|
|
78
|
+
.sort_values(["person", "time"]).reset_index(drop=True))
|
|
79
|
+
key = {(p, o): i for i, (p, o) in enumerate(zip(s.person, s.occasion))}
|
|
80
|
+
sess = np.array([key[(p, o)] for p, o in zip(tr.person, tr.occasion)])
|
|
81
|
+
slices, start = [], 0
|
|
82
|
+
for _, cnt in s.groupby("person", sort=False).size().items():
|
|
83
|
+
slices.append(slice(start, start + cnt)); start += cnt
|
|
84
|
+
minrt = tr.groupby("person")["rt"].transform("min").to_numpy(float)
|
|
85
|
+
n = len(tr)
|
|
86
|
+
Z = np.column_stack([np.ones(n)] + [tr[c].to_numpy(float) for c in boundary])
|
|
87
|
+
Q = np.column_stack([np.ones(n)] + [tr[c].to_numpy(float) for c in bias])
|
|
88
|
+
X = np.column_stack([tr[c].to_numpy(float) for c in drift]) if drift else np.zeros((n, 0))
|
|
89
|
+
return cls(rt=tr.rt.to_numpy(float), upper=tr.upper.to_numpy(int), stim=np.sign(tr[stim_col].to_numpy(float)),
|
|
90
|
+
sess=sess, minrt_trial=minrt, Z=Z, Q=Q, X=X, time=s.time.to_numpy(float),
|
|
91
|
+
person=s.person.to_numpy(), person_slices=slices, J=len(s),
|
|
92
|
+
names={"boundary": ["intercept", *boundary], "bias": ["intercept", *bias], "drift": list(drift),
|
|
93
|
+
"slope": slope},
|
|
94
|
+
nugget=nugget, ou=ou, slope_z=(s.slope_z.to_numpy(float) if slope else None))
|
|
95
|
+
|
|
96
|
+
@property
|
|
97
|
+
def sizes(self):
|
|
98
|
+
return self.Z.shape[1], self.Q.shape[1], self.X.shape[1]
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _names(d: DesignData):
|
|
102
|
+
return ([f"log_a:{n}" for n in d.names["boundary"]] + [f"logit_w:{n}" for n in d.names["bias"]]
|
|
103
|
+
+ ["logit_kappa", "log_tau"]
|
|
104
|
+
+ (["log_theta", "log_sd_stat"] if d.ou else [])
|
|
105
|
+
+ (["log_omega"] if d.nugget else [])
|
|
106
|
+
+ (["log_slope_sd", "atanh_rho"] if d.slope_z is not None else [])
|
|
107
|
+
+ [f"beta:{n}" for n in d.names["drift"]])
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _unpack(x, d: DesignData):
|
|
111
|
+
"""Parameters by name. The OU is parameterized by its stationary SD,
|
|
112
|
+
sd_stat = sigma / sqrt(2 theta), so both limits theta -> 0 (a person-level
|
|
113
|
+
constant) and theta -> infinity (independent session deviations) are reachable."""
|
|
114
|
+
names = _names(d)
|
|
115
|
+
v = dict(zip(names, x))
|
|
116
|
+
pa, pw, k = d.sizes
|
|
117
|
+
out = {"alpha": np.asarray(x[:pa]), "gamma": np.asarray(x[pa:pa + pw]),
|
|
118
|
+
"kappa": _logistic(v["logit_kappa"]), "tau": float(np.exp(v["log_tau"])),
|
|
119
|
+
"theta": float(np.exp(v["log_theta"])) if d.ou else np.inf,
|
|
120
|
+
"sd_stat": float(np.exp(v["log_sd_stat"])) if d.ou else 0.0,
|
|
121
|
+
"omega": float(np.exp(v["log_omega"])) if d.nugget else 0.0,
|
|
122
|
+
"slope_sd": float(np.exp(v["log_slope_sd"])) if d.slope_z is not None else 0.0,
|
|
123
|
+
"rho": float(np.tanh(v["atanh_rho"])) if d.slope_z is not None else 0.0,
|
|
124
|
+
"beta": np.asarray(x[len(names) - k:]) if k else np.zeros(0)}
|
|
125
|
+
out["sigma"] = out["sd_stat"] * np.sqrt(2 * out["theta"]) if d.ou else 0.0
|
|
126
|
+
return out
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _cov_profile(m, var, d: DesignData, p):
|
|
130
|
+
"""Gaussian log-likelihood of the session statistics with mu0 profiled out.
|
|
131
|
+
Person covariance: [1 z] G [1 z]' + K(theta, sd_stat) + diag(var + omega^2)."""
|
|
132
|
+
num = den = 0.0
|
|
133
|
+
facs = []
|
|
134
|
+
tau, sd, th, om = p["tau"], p["sd_stat"], p["theta"], p["omega"]
|
|
135
|
+
s_sd, rho = p["slope_sd"], p["rho"]
|
|
136
|
+
for sl in d.person_slices:
|
|
137
|
+
t = d.time[sl]
|
|
138
|
+
C = np.full((t.size, t.size), tau ** 2)
|
|
139
|
+
if d.ou:
|
|
140
|
+
C += sd ** 2 * np.exp(-th * np.abs(t[:, None] - t[None, :]))
|
|
141
|
+
if d.slope_z is not None:
|
|
142
|
+
z = d.slope_z[sl]
|
|
143
|
+
C += rho * tau * s_sd * (z[:, None] + z[None, :]) + s_sd ** 2 * np.outer(z, z)
|
|
144
|
+
C[np.diag_indices_from(C)] += var[sl] + om ** 2 + 1e-10
|
|
145
|
+
try:
|
|
146
|
+
c = cho_factor(C, lower=True, check_finite=False)
|
|
147
|
+
except np.linalg.LinAlgError:
|
|
148
|
+
return -np.inf, np.nan
|
|
149
|
+
one = np.ones(t.size)
|
|
150
|
+
Si1 = cho_solve(c, one, check_finite=False)
|
|
151
|
+
num += Si1 @ m[sl]; den += Si1.sum()
|
|
152
|
+
facs.append(c)
|
|
153
|
+
mu0 = num / den
|
|
154
|
+
ll = 0.0
|
|
155
|
+
for sl, c in zip(d.person_slices, facs):
|
|
156
|
+
r = m[sl] - mu0
|
|
157
|
+
ll -= 0.5 * (2 * np.sum(np.log(np.diag(c[0]))) + r @ cho_solve(c, r, check_finite=False) + r.size * LOG2PI)
|
|
158
|
+
return ll, mu0
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def design_loglik(x, d: DesignData, return_mu0=False):
|
|
162
|
+
p = _unpack(x, d)
|
|
163
|
+
alpha, gamma, kappa, beta = p["alpha"], p["gamma"], p["kappa"], p["beta"]
|
|
164
|
+
a = np.exp(d.Z @ alpha)
|
|
165
|
+
w = _logistic(d.Q @ gamma)
|
|
166
|
+
T = d.rt - kappa * d.minrt_trial
|
|
167
|
+
key = (tuple(alpha), tuple(gamma), float(kappa))
|
|
168
|
+
if d.zcache.get("key") == key:
|
|
169
|
+
zero = d.zcache["val"]
|
|
170
|
+
else:
|
|
171
|
+
wb = np.where(d.upper == 1, 1.0 - w, w) # zero-drift density: lower uses w, upper 1 - w
|
|
172
|
+
zero = float(np.sum(-2.0 * np.log(a) + _log_g(T / a ** 2, wb)))
|
|
173
|
+
d.zcache.update(key=key, val=zero)
|
|
174
|
+
c = d.stim * np.where(d.upper == 1, a * (1.0 - w), -a * w)
|
|
175
|
+
S = np.bincount(d.sess, weights=T, minlength=d.J)
|
|
176
|
+
b = np.bincount(d.sess, weights=c, minlength=d.J)
|
|
177
|
+
extra = 0.0
|
|
178
|
+
if beta.size:
|
|
179
|
+
xb = d.X @ beta
|
|
180
|
+
b = b - np.bincount(d.sess, weights=T * xb, minlength=d.J)
|
|
181
|
+
extra = float(np.sum(c * xb) - 0.5 * np.sum(T * xb ** 2))
|
|
182
|
+
ll = zero + extra + np.sum(b ** 2 / (2 * S) + 0.5 * (LOG2PI - np.log(S)))
|
|
183
|
+
cov, mu0 = _cov_profile(b / S, 1.0 / S, d, p)
|
|
184
|
+
return (ll + cov, mu0) if return_mu0 else ll + cov
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
DESIGN_LOG_THETA = (-6.0, 9.0) # fitting range; profiles may go beyond
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
@dataclass
|
|
191
|
+
class DesignFit:
|
|
192
|
+
params: dict
|
|
193
|
+
se: dict
|
|
194
|
+
x: np.ndarray
|
|
195
|
+
halflife: float
|
|
196
|
+
halflife_ci: tuple
|
|
197
|
+
loglik: float
|
|
198
|
+
n_params: int
|
|
199
|
+
converged: bool
|
|
200
|
+
theta_at_bound: str
|
|
201
|
+
|
|
202
|
+
@property
|
|
203
|
+
def aic(self):
|
|
204
|
+
return -2 * self.loglik + 2 * self.n_params
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _bounds(d: DesignData, fix_theta=None):
|
|
208
|
+
b = []
|
|
209
|
+
for n in _names(d):
|
|
210
|
+
if n.startswith("log_a:"):
|
|
211
|
+
b.append((-3, 3))
|
|
212
|
+
elif n.startswith("logit_w:"):
|
|
213
|
+
b.append((-4, 4))
|
|
214
|
+
elif n == "logit_kappa":
|
|
215
|
+
b.append((-8, 8))
|
|
216
|
+
elif n == "log_theta":
|
|
217
|
+
b.append(DESIGN_LOG_THETA if fix_theta is None else (fix_theta, fix_theta))
|
|
218
|
+
elif n == "atanh_rho":
|
|
219
|
+
b.append((-3, 3))
|
|
220
|
+
elif n.startswith("beta:"):
|
|
221
|
+
b.append((-10, 10))
|
|
222
|
+
else:
|
|
223
|
+
b.append((-8, 2))
|
|
224
|
+
return b
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _starts(d: DesignData, thetas=(0.3, 2.0, 50.0, 2000.0), taus=(0.3, 0.03)):
|
|
228
|
+
names = _names(d)
|
|
229
|
+
out = []
|
|
230
|
+
for th0 in (thetas if d.ou else (None,)):
|
|
231
|
+
for tau0 in taus:
|
|
232
|
+
z = np.zeros(len(names))
|
|
233
|
+
z[0] = np.log(1.5)
|
|
234
|
+
z[names.index("logit_kappa")] = 2.0
|
|
235
|
+
z[names.index("log_tau")] = np.log(tau0)
|
|
236
|
+
if d.ou:
|
|
237
|
+
z[names.index("log_theta")] = np.log(th0)
|
|
238
|
+
z[names.index("log_sd_stat")] = np.log(0.3)
|
|
239
|
+
if d.nugget:
|
|
240
|
+
z[names.index("log_omega")] = np.log(0.2)
|
|
241
|
+
if d.slope_z is not None:
|
|
242
|
+
z[names.index("log_slope_sd")] = np.log(0.05)
|
|
243
|
+
out.append(z)
|
|
244
|
+
return out
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def fit_design(d: DesignData, se: bool = True, x0: np.ndarray | None = None) -> DesignFit:
|
|
248
|
+
"""Joint ML for the design model. The likelihood in theta can have separate
|
|
249
|
+
optima at slow and at very fast reversion, so starts span theta from 0.3
|
|
250
|
+
to 2000 per day and two values of tau."""
|
|
251
|
+
names = _names(d)
|
|
252
|
+
f = lambda x: -design_loglik(x, d)
|
|
253
|
+
bounds = _bounds(d)
|
|
254
|
+
starts = _starts(d)
|
|
255
|
+
if x0 is not None:
|
|
256
|
+
starts.insert(0, np.asarray(x0, float))
|
|
257
|
+
best = None
|
|
258
|
+
for z in starts:
|
|
259
|
+
r = minimize(f, z, method="L-BFGS-B", bounds=bounds)
|
|
260
|
+
if best is None or r.fun < best.fun:
|
|
261
|
+
best = r
|
|
262
|
+
x = best.x
|
|
263
|
+
ll, mu0 = design_loglik(x, d, return_mu0=True)
|
|
264
|
+
p = _unpack(x, d)
|
|
265
|
+
sev = np.full(len(names), np.nan)
|
|
266
|
+
if se:
|
|
267
|
+
try:
|
|
268
|
+
cov = np.linalg.inv(_num_hessian(f, x))
|
|
269
|
+
sev = np.sqrt(np.where(np.diag(cov) > 0, np.diag(cov), np.nan))
|
|
270
|
+
except np.linalg.LinAlgError:
|
|
271
|
+
pass
|
|
272
|
+
params = dict(zip(names, x)); params["mu0"] = mu0
|
|
273
|
+
params.update({k: p[k] for k in ("kappa", "tau", "theta", "sigma", "omega", "sd_stat", "slope_sd", "rho")})
|
|
274
|
+
sed = dict(zip(names, sev))
|
|
275
|
+
hl, ci, atb = np.nan, (np.nan, np.nan), ""
|
|
276
|
+
if d.ou:
|
|
277
|
+
ilt = names.index("log_theta")
|
|
278
|
+
hl = np.log(2) / p["theta"]
|
|
279
|
+
ci = (float(np.exp(np.log(hl) - 1.96 * sev[ilt])), float(np.exp(np.log(hl) + 1.96 * sev[ilt])))
|
|
280
|
+
lt = x[ilt]
|
|
281
|
+
atb = ("upper" if lt >= DESIGN_LOG_THETA[1] - 1e-6 else
|
|
282
|
+
("lower" if lt <= DESIGN_LOG_THETA[0] + 1e-6 else ""))
|
|
283
|
+
return DesignFit(params=params, se=sed, x=x, halflife=float(hl), halflife_ci=ci,
|
|
284
|
+
loglik=float(ll), n_params=len(names) + 1, converged=bool(best.success), theta_at_bound=atb)
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def profile_point(d: DesignData, log_theta: float, warm=()) -> tuple[float, np.ndarray]:
|
|
288
|
+
"""Maximized log-likelihood with log theta fixed; starts from the warm
|
|
289
|
+
vectors given and from the default starts at this theta."""
|
|
290
|
+
names = _names(d)
|
|
291
|
+
ilt = names.index("log_theta")
|
|
292
|
+
f = lambda x: -design_loglik(x, d)
|
|
293
|
+
bounds = _bounds(d, fix_theta=log_theta)
|
|
294
|
+
cands = [np.asarray(w, float).copy() for w in warm] + _starts(d, thetas=(np.exp(log_theta),))
|
|
295
|
+
best = None
|
|
296
|
+
for z in cands:
|
|
297
|
+
z = z.copy(); z[ilt] = log_theta
|
|
298
|
+
r = minimize(f, z, method="L-BFGS-B", bounds=bounds)
|
|
299
|
+
if best is None or r.fun < best.fun:
|
|
300
|
+
best = r
|
|
301
|
+
return -float(best.fun), best.x
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def profile_theta(d: DesignData, log_thetas, x_start=None) -> pd.DataFrame:
|
|
305
|
+
"""Profile log-likelihood over a grid of log theta (warm-started along the grid)."""
|
|
306
|
+
out, prev = [], None
|
|
307
|
+
for lt in log_thetas:
|
|
308
|
+
warm = [w for w in (prev, x_start) if w is not None]
|
|
309
|
+
ll, x = profile_point(d, lt, warm)
|
|
310
|
+
prev = x
|
|
311
|
+
p = _unpack(x, d)
|
|
312
|
+
out.append({"log_theta": lt, "theta": np.exp(lt), "halflife_days": np.log(2) / np.exp(lt), "loglik": ll,
|
|
313
|
+
"tau": p["tau"], "sd_stat": p["sd_stat"], "omega": p["omega"], "slope_sd": p["slope_sd"]})
|
|
314
|
+
return pd.DataFrame(out)
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def supported_regions(dev: np.ndarray, cut: float = 3.841) -> list:
|
|
318
|
+
"""Index ranges (start, end), inclusive, of the connected runs of grid
|
|
319
|
+
points whose deviance is at or below the cut-off."""
|
|
320
|
+
inside = np.asarray(dev) <= cut
|
|
321
|
+
runs, start = [], None
|
|
322
|
+
for k, v in enumerate(inside):
|
|
323
|
+
if v and start is None:
|
|
324
|
+
start = k
|
|
325
|
+
if not v and start is not None:
|
|
326
|
+
runs.append((start, k - 1)); start = None
|
|
327
|
+
if start is not None:
|
|
328
|
+
runs.append((start, len(inside) - 1))
|
|
329
|
+
return runs
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def profile_interval(prof: pd.DataFrame, ref_loglik: float | None = None, d: DesignData | None = None,
|
|
333
|
+
fit: DesignFit | None = None, cut: float = 3.841) -> dict:
|
|
334
|
+
"""Approximate profile-likelihood interval for the half-life.
|
|
335
|
+
|
|
336
|
+
The deviance is measured from ref_loglik (the full maximum; defaults to the
|
|
337
|
+
grid maximum). If d and fit are given, each crossing bracketed by the grid
|
|
338
|
+
is located by root-finding on the profile; otherwise by linear
|
|
339
|
+
interpolation.
|
|
340
|
+
|
|
341
|
+
The supported set {deviance <= cut} need not be connected. Each connected
|
|
342
|
+
run of grid points gives one range in ``regions`` (half-lives, shortest
|
|
343
|
+
range first), and ``disconnected`` is True when there is more than one.
|
|
344
|
+
``halflife_lo`` and ``halflife_hi`` are the outer ends; when the set is
|
|
345
|
+
disconnected they span points outside it, so use ``regions`` instead.
|
|
346
|
+
The open-end flags refer to the outer ends.
|
|
347
|
+
|
|
348
|
+
If no grid point lies within the cut-off, the supported set is reported
|
|
349
|
+
as empty (``regions == []``, ``empty`` and ``needs_refinement`` True, the
|
|
350
|
+
ends NaN). This happens when ref_loglik is above every grid point by more
|
|
351
|
+
than cut/2; add the fitted maximum to the profile or refine the grid near
|
|
352
|
+
``best_grid_halflife``.
|
|
353
|
+
"""
|
|
354
|
+
p = prof.sort_values("log_theta").reset_index(drop=True)
|
|
355
|
+
ref = p.loglik.max() if ref_loglik is None else max(ref_loglik, p.loglik.max())
|
|
356
|
+
dev = 2 * (ref - p.loglik.to_numpy())
|
|
357
|
+
lt = p.log_theta.to_numpy()
|
|
358
|
+
n = len(lt)
|
|
359
|
+
runs = supported_regions(dev, cut)
|
|
360
|
+
if not runs:
|
|
361
|
+
# No grid point lies within the cut-off of the reference: the grid
|
|
362
|
+
# misses the supported set (e.g. the fitted maximum was not added and
|
|
363
|
+
# the grid is too coarse). Report an empty set rather than guess.
|
|
364
|
+
imin = int(np.argmin(dev))
|
|
365
|
+
nan = float("nan")
|
|
366
|
+
return {"theta_lo": nan, "theta_hi": nan, "halflife_lo": nan, "halflife_hi": nan,
|
|
367
|
+
"long_end_open": False, "short_end_open": False,
|
|
368
|
+
"disconnected": False, "regions": [], "empty": True,
|
|
369
|
+
"needs_refinement": True, "best_grid_halflife": float(np.log(2) / np.exp(lt[imin])),
|
|
370
|
+
"ref_loglik": float(ref), "max_dev_on_grid": float(dev.max())}
|
|
371
|
+
|
|
372
|
+
def cross(a, b, warm):
|
|
373
|
+
if d is None or fit is None:
|
|
374
|
+
return float(np.interp(cut, sorted([dev[a], dev[b]]), [lt[a], lt[b]] if dev[a] < dev[b] else [lt[b], lt[a]]))
|
|
375
|
+
g = lambda x: 2 * (ref - profile_point(d, x, warm)[0]) - cut
|
|
376
|
+
return float(brentq(g, lt[a], lt[b], xtol=0.01))
|
|
377
|
+
|
|
378
|
+
warm = [fit.x] if fit is not None else []
|
|
379
|
+
bounds = [] # (lo log-theta, hi log-theta) per run
|
|
380
|
+
for a, b in runs:
|
|
381
|
+
lo_lt = lt[a] if a == 0 else cross(a - 1, a, warm)
|
|
382
|
+
hi_lt = lt[b] if b == n - 1 else cross(b, b + 1, warm)
|
|
383
|
+
bounds.append((lo_lt, hi_lt))
|
|
384
|
+
lo_lt, hi_lt = bounds[0][0], bounds[-1][1]
|
|
385
|
+
regions = [(float(np.log(2) / np.exp(h)), float(np.log(2) / np.exp(l))) for l, h in reversed(bounds)]
|
|
386
|
+
return {"theta_lo": float(np.exp(lo_lt)), "theta_hi": float(np.exp(hi_lt)),
|
|
387
|
+
"halflife_lo": float(np.log(2) / np.exp(hi_lt)), "halflife_hi": float(np.log(2) / np.exp(lo_lt)),
|
|
388
|
+
"long_end_open": bool(runs[0][0] == 0), "short_end_open": bool(runs[-1][1] == n - 1),
|
|
389
|
+
"disconnected": len(runs) > 1, "regions": regions, "empty": False, "needs_refinement": False,
|
|
390
|
+
"ref_loglik": float(ref), "max_dev_on_grid": float(dev.max())}
|