From 4a2f43f9105b6f151abf3b0bc87935fa86b7fbfb Mon Sep 17 00:00:00 2001 From: Gilles de Hollander Date: Sun, 25 Oct 2026 13:33:52 +0100 Subject: [PATCH 01/20] MagnitudeEstimationModel: hierarchical Bayesian observer for estimation on a bounded integer scale Weber / constant / power-law encoding noise; true, fitted or empirical prior; posterior mean or median readout; censored discretised motor noise; free lapse; optional leakage of an uncued magnitude (mixture or average). Observed Categorical likelihood, so LOO and posterior-predictive draws come from PyMC. Tests: builds + finite gradients for every option, analytic checks, MAP and hierarchical NUTS parameter recovery. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 19 ++ bauer/magnitude_estimation.py | 526 +++++++++++++++++++++++++++++ tests/test_magnitude_estimation.py | 158 +++++++++ 3 files changed, 703 insertions(+) create mode 100644 bauer/magnitude_estimation.py create mode 100644 tests/test_magnitude_estimation.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 74eb644..7a2fd0e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,25 @@ All notable changes to **bauer** are documented here. This project loosely follows [Keep a Changelog](https://keepachangelog.com/) and semantic versioning. +## Unreleased (branch `estimation-model`) + +### Added +- `bauer.magnitude_estimation.MagnitudeEstimationModel`: hierarchical Bayesian + observer for magnitude estimation on a bounded, discrete (integer) response + scale. Options: Weber (log-normal), constant or power-law (`flexible`) + encoding noise; true (uniform), fitted (Gaussian / log-normal) or per-subject + empirical prior; posterior-mean or posterior-median readout; motor noise + discretised and censored at the scale ends; free per-subject lapse rate; and + optional leakage of a second, uncued magnitude (`mixture` = swap, + `average` = weighted report). The likelihood is an observed + `pm.Categorical`, so `pm.compute_log_likelihood` (LOO) and + `pm.sample_posterior_predictive` (simulated datasets) work directly. + `predict`, `predict_response_distribution`, `simulate` and `ppc` return + integer responses with lapses, censoring and leakage included. +- `tests/test_magnitude_estimation.py`: build/gradient tests for every option, + analytic checks, single-subject MAP recovery and a hierarchical NUTS + recovery test (`slow`). + ## 0.5.0 (2026-10-18) The headline of this release is a much-extended `bauer.efficient_coding` diff --git a/bauer/magnitude_estimation.py b/bauer/magnitude_estimation.py new file mode 100644 index 0000000..47db798 --- /dev/null +++ b/bauer/magnitude_estimation.py @@ -0,0 +1,526 @@ +""" +Bayesian-observer models of magnitude estimation on a bounded, discrete scale. + +The task: on each trial a magnitude ``n`` is shown (e.g. a dot array) and the +participant reports it on a bounded response scale (e.g. an integer slider from +5 to 25). The generative model is + +1. **Encoding.** A noisy internal measurement ``m``: + + * ``encoding='weber'`` m ~ N(log n, nu^2) (log-normal noise) + * ``encoding='constant'`` m ~ N(n, nu^2) (constant, items) + * ``encoding='flexible'`` m ~ N(n, (nu * (n / n_ref)^beta)^2) (power law; beta = 0 + is ``constant``, beta = 1 is scalar variability) + +2. **Prior.** The observer's prior over ``n``: + + * ``prior='true'`` uniform on the presented range (the task distribution) + * ``prior='fitted'`` Gaussian with free mean and width, in the encoding + space (log-normal for ``weber``, Gaussian in items otherwise) + * ``prior='empirical'`` each participant's own histogram of presented ``n`` + +3. **Readout.** The posterior mean (``readout='mean'``, squared-error loss) or + the posterior median (``readout='median'``, absolute-error loss) of ``n`` + given ``m``, in the units of the response scale. + +4. **Response.** Motor noise ``r ~ N(n_hat, sigma_r^2)``, discretised to the + integer response options and **censored** at the scale ends (all mass below + the lowest option goes to that option, likewise at the top). With + ``lapse=True`` a free per-participant lapse rate ``p_lapse`` mixes in a + uniform distribution over the response options. + +5. **Leakage of a second, uncued magnitude** (optional; needs ``n_uncued``): + + * ``leakage='mixture'`` with probability ``leak`` the participant reports the + *other* array (a swap), else the cued one. + * ``leakage='average'`` the report is ``(1 - leak) * n_hat(m_cued) + + leak * n_hat(m_uncued)``. The uncued term is integrated with a Gaussian + approximation (its mean and variance given ``n_uncued``), exact in the + limit of small ``leak``. + +Implementation: everything is computed on fixed grids. For each participant +the estimate ``n_hat(m)`` is precomputed on a measurement grid (posterior over a +hypothesis grid), the response distribution of every presented ``n`` is the +measurement density integrated against the discretised motor kernel (one +batched matmul), and the per-trial likelihood is a ``pm.Categorical`` over the +response options. Because the likelihood is an *observed* RV, pointwise +log-likelihoods (``pm.compute_log_likelihood`` -> LOO) and posterior-predictive +draws (``pm.sample_posterior_predictive``) work out of the box. + +Data conventions: ``n`` (presented, integer), ``response`` (integer on the +response scale), optional ``n_uncued``; a ``subject`` index level for +hierarchical fits. +""" + +import numpy as np +import pandas as pd +import pymc as pm +import pytensor.tensor as pt + +from .estimation import EstimationBaseModel + + +ENCODINGS = ('weber', 'constant', 'flexible') +PRIORS = ('true', 'fitted', 'empirical') +READOUTS = ('mean', 'median') +LEAKAGES = (None, 'mixture', 'average') + + +def _norm_cdf(x): + return 0.5 * pt.erfc(-x / np.sqrt(2.0)) + + +class MagnitudeEstimationModel(EstimationBaseModel): + """Hierarchical Bayesian observer for continuous magnitude estimation. + + Parameters + ---------- + paradigm : pd.DataFrame + Columns ``n`` and ``response`` (integers), optionally ``n_uncued``; + a ``subject`` index level for hierarchical fits. + encoding : {'weber', 'constant', 'flexible'} + prior : {'true', 'fitted', 'empirical'} + readout : {'mean', 'median'} + lapse : bool + Free per-participant lapse rate (uniform over response options). + leakage : {None, 'mixture', 'average'} + Influence of the uncued magnitude ``n_uncued`` (see module docstring). + stimulus_range : (int, int) + Smallest and largest presented magnitude (inclusive integers). The + ``'true'`` prior is uniform on ``[lo - .5, hi + .5]``. + response_range : (int, int) + Smallest and largest response option (inclusive integers). + n_ref : float + Reference magnitude of the ``flexible`` noise power law; ``nu`` is the + encoding s.d. (items) at ``n_ref``. + n_measurement_grid, n_hypothesis_grid : int + Grid sizes (measurement axis; observer's hypothesis axis). + hypothesis_range : (float, float) + Support of the observer's hypothesis grid (must contain the prior's mass). + """ + + paradigm_keys = ['n'] + + def __init__(self, paradigm=None, encoding='weber', prior='true', readout='mean', + lapse=True, leakage=None, stimulus_range=(5, 24), + response_range=(5, 25), n_ref=12.0, n_measurement_grid=150, + n_hypothesis_grid=246, hypothesis_range=(1.0, 50.0), **kwargs): + if encoding not in ENCODINGS: + raise ValueError(f'encoding must be one of {ENCODINGS}') + if prior not in PRIORS: + raise ValueError(f'prior must be one of {PRIORS}') + if readout not in READOUTS: + raise ValueError(f'readout must be one of {READOUTS}') + if leakage not in LEAKAGES: + raise ValueError(f'leakage must be one of {LEAKAGES}') + self.encoding = encoding + self.prior = prior + self.readout = readout + self.lapse = lapse + self.leakage = leakage + self.stimulus_range = tuple(int(x) for x in stimulus_range) + self.response_range = tuple(int(x) for x in response_range) + self.n_ref = float(n_ref) + self.n_measurement_grid = int(n_measurement_grid) + self.n_hypothesis_grid = int(n_hypothesis_grid) + self.hypothesis_range = tuple(float(x) for x in hypothesis_range) + if leakage is not None: + self.paradigm_keys = ['n', 'n_uncued'] + super().__init__(paradigm, lapse_rate=0.0, **kwargs) + self._setup_grids(paradigm) + + # ------------------------------------------------------------------ + # Parameters + # ------------------------------------------------------------------ + + @property + def log_space(self): + return self.encoding == 'weber' + + def get_free_parameters(self): + pars = {} + if self.encoding == 'weber': + # nu in log units; softplus(-1) = .31 + pars['nu'] = dict(mu_intercept=-1.0, sigma_intercept=0.75, + cauchy_sigma_intercept=0.5, transform='softplus') + else: + # nu in items (at n_ref for 'flexible'); softplus(5) ~ 5 + pars['nu'] = dict(mu_intercept=5.0, sigma_intercept=2.5, + cauchy_sigma_intercept=1.5, transform='softplus') + if self.encoding == 'flexible': + pars['nu_exponent'] = dict(mu_intercept=0.5, sigma_intercept=1.0, + cauchy_sigma_intercept=0.5, transform='identity') + if self.prior == 'fitted': + lo, hi = self.stimulus_range + if self.log_space: + mid = 0.5 * (np.log(lo) + np.log(hi)) + pars['prior_mu'] = dict(mu_intercept=mid, sigma_intercept=0.3, + cauchy_sigma_intercept=0.2, transform='identity') + pars['prior_sd'] = dict(mu_intercept=-0.5, sigma_intercept=0.75, + cauchy_sigma_intercept=0.5, transform='softplus') + else: + pars['prior_mu'] = dict(mu_intercept=0.5 * (lo + hi), sigma_intercept=3.0, + cauchy_sigma_intercept=2.0, transform='identity') + pars['prior_sd'] = dict(mu_intercept=(hi - lo + 1) / np.sqrt(12), + sigma_intercept=2.5, cauchy_sigma_intercept=1.5, + transform='softplus') + # motor noise in items; softplus(1) = 1.31 + pars['sigma_r'] = dict(mu_intercept=1.0, sigma_intercept=1.0, + cauchy_sigma_intercept=0.75, transform='softplus') + if self.lapse: + pars['p_lapse'] = dict(transform='beta', beta_mu_mean=0.05, beta_mu_kappa=8.0) + if self.leakage is not None: + pars['leak'] = dict(transform='beta', beta_mu_mean=0.05, beta_mu_kappa=8.0) + return pars + + def get_model_inputs(self, parameters): + return {key: self.subjectwise(key) for key in self.free_parameters} + + # ------------------------------------------------------------------ + # Grids and paradigm + # ------------------------------------------------------------------ + + def _setup_grids(self, paradigm): + lo, hi = self.stimulus_range + self.stimuli = np.arange(lo, hi + 1, dtype=float) # (K,) + rlo, rhi = self.response_range + self.response_options = np.arange(rlo, rhi + 1, dtype=float) # (R,) + # Category edges, censored at the scale ends + # (finite outer edges: an infinite edge makes d/d(sd) = inf * 0 = NaN) + self.response_edges = np.concatenate( + [[-1e4], self.response_options[:-1] + 0.5, [1e4]]) + + h0, h1 = self.hypothesis_range + self.hyp_grid = np.linspace(h0, h1, self.n_hypothesis_grid) # (H,) + self.d_hyp = self.hyp_grid[1] - self.hyp_grid[0] + + if self.log_space: + self.meas_grid = np.linspace(np.log(h0) - 0.5, np.log(h1) + 0.5, + self.n_measurement_grid) + else: + self.meas_grid = np.linspace(h0 - 20.0, h1 + 10.0, self.n_measurement_grid) + self.d_meas = self.meas_grid[1] - self.meas_grid[0] + + # True prior: uniform on [lo - .5, hi + .5]; cell-overlap weights. + a, b = lo - 0.5, hi + 0.5 + left = np.clip(self.hyp_grid - self.d_hyp / 2, a, b) + right = np.clip(self.hyp_grid + self.d_hyp / 2, a, b) + w = right - left + self.true_prior = w / w.sum() + + self.subject_ids = None + self.empirical_prior = None + if paradigm is not None: + if 'subject' in paradigm.index.names: + subj = paradigm.index.get_level_values('subject') + elif 'subject' in paradigm.columns: + subj = paradigm['subject'].values + else: + subj = np.zeros(len(paradigm), dtype=int) + codes, uniques = pd.factorize(subj) + self.subject_ids = uniques + if self.prior == 'empirical': + n = paradigm['n'].values.astype(int) + counts = np.zeros((len(uniques), len(self.stimuli))) + np.add.at(counts, (codes, n - lo), 1.0) + # Spread each integer's mass over its [k - .5, k + .5] cell + cell = np.zeros((len(self.stimuli), len(self.hyp_grid))) + for k, nk in enumerate(self.stimuli): + l_ = np.clip(self.hyp_grid - self.d_hyp / 2, nk - .5, nk + .5) + r_ = np.clip(self.hyp_grid + self.d_hyp / 2, nk - .5, nk + .5) + cell[k] = (r_ - l_) + emp = counts @ cell + self.empirical_prior = emp / emp.sum(1, keepdims=True) + + def _get_paradigm(self, paradigm=None, subject_mapping=None): + if paradigm is None: + paradigm = self.paradigm + lo, hi = self.stimulus_range + rlo, rhi = self.response_range + n = paradigm['n'].values + if np.any(n != np.round(n)) or n.min() < lo or n.max() > hi: + raise ValueError(f'n must be integers in {self.stimulus_range}') + + paradigm_ = {'_data_n': len(paradigm)} + if subject_mapping is None: + if 'subject' in paradigm.index.names: + paradigm_['subject_ix'], _ = pd.factorize(paradigm.index.get_level_values('subject')) + elif 'subject' in paradigm.columns: + paradigm_['subject_ix'], _ = pd.factorize(paradigm['subject']) + else: + paradigm_['subject_ix'] = np.zeros(len(paradigm), dtype=int) + else: + s = (paradigm.index.get_level_values('subject') if 'subject' in paradigm.index.names + else paradigm['subject']) + paradigm_['subject_ix'] = np.array([subject_mapping[x] for x in s]) + + paradigm_['stimulus_ix'] = (n - lo).astype(int) + if self.leakage is not None: + u = paradigm['n_uncued'].values + paradigm_['uncued_ix'] = (u - lo).astype(int) + + if 'response' in paradigm.columns: + r = paradigm['response'].values.astype(float) + if np.any(np.isnan(r)): + raise ValueError('response has NaNs; drop no-response trials first') + r = np.clip(np.round(r), rlo, rhi) + paradigm_['response_ix'] = (r - rlo).astype(int) + else: + paradigm_['response_ix'] = np.zeros(len(paradigm), dtype=int) + return paradigm_ + + # ------------------------------------------------------------------ + # The observer + # ------------------------------------------------------------------ + + def _encoding_sd(self, nu, nu_exponent, x): + """Encoding s.d. at magnitudes x. nu: (S,), x: (..., P) -> (S, P).""" + if self.encoding == 'flexible': + return nu[:, None] * (x[None, :] / self.n_ref) ** nu_exponent[:, None] + return pt.ones((1, x.shape[0])) * nu[:, None] + + def _encode(self, x): + return np.log(x) if self.log_space else x + + def _prior_on_grid(self, inputs): + """(S, H) normalised prior mass on the hypothesis grid.""" + h = pt.as_tensor_variable(self.hyp_grid) + if self.prior == 'true': + return pt.as_tensor_variable(self.true_prior)[None, :] + if self.prior == 'empirical': + return pt.as_tensor_variable(self.empirical_prior) + mu = inputs['prior_mu'][:, None] + sd = inputs['prior_sd'][:, None] + if self.log_space: + logdens = -0.5 * ((pt.log(h)[None, :] - mu) / sd) ** 2 - pt.log(h)[None, :] + else: + logdens = -0.5 * ((h[None, :] - mu) / sd) ** 2 + logdens = logdens - pt.max(logdens, axis=1, keepdims=True) + dens = pt.exp(logdens) + return dens / pt.sum(dens, axis=1, keepdims=True) + + def _estimate_on_measurement_grid(self, inputs): + """n_hat(m): (S, M) estimate for every measurement on the grid.""" + nu = inputs['nu'] + beta = inputs.get('nu_exponent', None) + h = self.hyp_grid + m = pt.as_tensor_variable(self.meas_grid) + sd_h = self._encoding_sd(nu, beta, pt.as_tensor_variable(h)) # (S|1, H) + mu_h = pt.as_tensor_variable(self._encode(h)) # (H,) + # log p(m | h): (S, M, H) + loglik = (-0.5 * ((m[None, :, None] - mu_h[None, None, :]) / sd_h[:, None, :]) ** 2 + - pt.log(sd_h)[:, None, :]) + logprior = pt.log(self._prior_on_grid(inputs) + 1e-300) # (S|1, H) + logpost = loglik + logprior[:, None, :] + logpost = logpost - pt.max(logpost, axis=2, keepdims=True) + post = pt.exp(logpost) + post = post / pt.sum(post, axis=2, keepdims=True) # (S, M, H) + hh = pt.as_tensor_variable(h) + if self.readout == 'mean': + return pt.sum(post * hh[None, None, :], axis=2) + # Median: posterior mass is piecewise constant over cells of width d_hyp + # centred on the grid; the median is the point where the cumulative mass + # crosses .5, linearly interpolated within its cell (continuous in the + # parameters, so NUTS sees a usable gradient). + cum = pt.cumsum(post, axis=2) + before = cum - post + frac = pt.clip((0.5 - before) / (post + 1e-30), 0.0, 1.0) + return (h[0] - self.d_hyp / 2) + self.d_hyp * pt.sum(frac, axis=2) + + def _measurement_density(self, inputs): + """p(m | n_k) * dm for every presented magnitude: (S, K, M).""" + nu = inputs['nu'] + beta = inputs.get('nu_exponent', None) + x = pt.as_tensor_variable(self.stimuli) + sd = self._encoding_sd(nu, beta, x) # (S|1, K) + mu = pt.as_tensor_variable(self._encode(self.stimuli)) + m = pt.as_tensor_variable(self.meas_grid) + logd = -0.5 * ((m[None, None, :] - mu[None, :, None]) / sd[:, :, None]) ** 2 + logd = logd - pt.max(logd, axis=2, keepdims=True) + d = pt.exp(logd) + return d / pt.sum(d, axis=2, keepdims=True) + + def _motor_kernel(self, centre, sd): + """P(response option | centre) for centre (..., M), sd broadcastable.""" + edges = pt.as_tensor_variable(self.response_edges) + z = (edges - centre[..., None]) / sd[..., None] + cdf = _norm_cdf(z) + return cdf[..., 1:] - cdf[..., :-1] # (..., R) + + def response_table(self, inputs): + """Response distribution per participant and presented magnitude. + + Returns (S, K, R), or (S, K, K, R) indexed [s, cued, uncued, r] for + ``leakage='average'``. Lapses are mixed in, mixtures are not (the + mixture is formed per trial in ``trial_probabilities``). + """ + n_hat = self._estimate_on_measurement_grid(inputs) # (S, M) + p_m = self._measurement_density(inputs) # (S, K, M) + sigma_r = inputs['sigma_r'] + R = len(self.response_options) + + if self.leakage == 'average': + leak = inputs['leak'] + mu_u = pt.sum(p_m * n_hat[:, None, :], axis=2) # (S, K) + var_u = pt.sum(p_m * (n_hat[:, None, :] - mu_u[:, :, None]) ** 2, axis=2) + centre = ((1 - leak)[:, None, None] * n_hat[:, None, :] + + leak[:, None, None] * mu_u[:, :, None]) # (S, U, M) + sd = pt.sqrt(sigma_r[:, None] ** 2 + leak[:, None] ** 2 * var_u) # (S, U) + kern = self._motor_kernel(centre, pt.repeat(sd[:, :, None], centre.shape[2], axis=2)) + # (S, K_c, M) x (S, U, M, R) -> (S, K_c, U, R), as one batched matmul + # over M (no 5-D intermediate in the gradient graph) + S_, U_ = kern.shape[0], kern.shape[1] + kern_m = kern.dimshuffle(0, 2, 1, 3).reshape((S_, kern.shape[2], U_ * R)) + table = pt.batched_dot(p_m, kern_m).reshape((S_, p_m.shape[1], U_, R)) + else: + kern = self._motor_kernel(n_hat, sigma_r[:, None] * pt.ones_like(n_hat)) # (S, M, R) + table = pt.batched_dot(p_m, kern) # (S, K, R) + + if self.lapse: + lam = inputs['p_lapse'] + lam = lam.reshape((-1,) + (1,) * (table.ndim - 1)) + table = (1 - lam) * table + lam / R + return table + + def trial_probabilities(self, inputs, subject_ix, stimulus_ix, uncued_ix=None): + table = self.response_table(inputs) + if self.leakage == 'average': + p = table[subject_ix, stimulus_ix, uncued_ix] + elif self.leakage == 'mixture': + leak = inputs['leak'][subject_ix][:, None] + p = (1 - leak) * table[subject_ix, stimulus_ix] + leak * table[subject_ix, uncued_ix] + else: + p = table[subject_ix, stimulus_ix] + p = pt.clip(p, 1e-10, 1.0) + return p / pt.sum(p, axis=1, keepdims=True) + + # ------------------------------------------------------------------ + # PyMC graph + # ------------------------------------------------------------------ + + def build_estimation_model(self, data=None, coords=None, hierarchical=True, + save_p_choice=False, flat_prior=False, paradigm=None): + if data is None: + data = paradigm if paradigm is not None else self.paradigm + self._setup_grids(data) + if hierarchical and coords is None: + coords = {'subject': data.index.unique(level='subject')} + with pm.Model(coords=coords) as self.estimation_model: + paradigm_ = self._get_paradigm(paradigm=data) + self.set_paradigm(paradigm_) + self.build_priors(hierarchical=hierarchical, flat_prior=flat_prior) + self.build_likelihood(None, save_p_choice=save_p_choice) + + def build_likelihood(self, parameters, save_p_choice=False): + model = pm.Model.get_context() + inputs = self.get_model_inputs(parameters) + p = self.trial_probabilities( + inputs, model['subject_ix'], model['stimulus_ix'], + model['uncued_ix'] if self.leakage is not None else None) + if save_p_choice: + p = pm.Deterministic('p_response', p) + pm.Categorical('response', p=p, observed=model['response_ix']) + + # ------------------------------------------------------------------ + # Prediction / simulation + # ------------------------------------------------------------------ + + def _parameter_arrays(self, parameters, subject_ids): + """dict name -> (S,) float array, aligned to ``subject_ids``.""" + if isinstance(parameters, pd.DataFrame): + pars = parameters.loc[list(subject_ids)] + return {k: pars[k].values.astype(float) for k in self.free_parameters} + out = {} + for k in self.free_parameters: + v = np.atleast_1d(np.asarray(parameters[k], dtype=float)) + out[k] = np.broadcast_to(v, (len(subject_ids),)).copy() + return out + + def predict_response_distribution(self, paradigm, parameters): + """Per-trial probabilities over the response options. + + Returns a DataFrame (index = paradigm.index, columns = response options). + ``parameters``: DataFrame indexed by subject, or a dict of scalars/arrays. + """ + if self.prior == 'empirical': + self._setup_grids(paradigm) + if 'subject' in paradigm.index.names: + subj = paradigm.index.get_level_values('subject') + elif 'subject' in paradigm.columns: + subj = paradigm['subject'].values + else: + subj = np.zeros(len(paradigm), dtype=int) + codes, uniques = pd.factorize(subj) + pars = self._parameter_arrays(parameters, uniques) + inputs = {k: pt.as_tensor_variable(v) for k, v in pars.items()} + par_ = self._get_paradigm(paradigm) + par_['subject_ix'] = codes + p = self.trial_probabilities( + inputs, pt.as_tensor_variable(par_['subject_ix']), + pt.as_tensor_variable(par_['stimulus_ix']), + pt.as_tensor_variable(par_['uncued_ix']) if self.leakage is not None else None).eval() + return pd.DataFrame(p, index=paradigm.index, + columns=pd.Index(self.response_options.astype(int), name='response')) + + def predict(self, paradigm, parameters): + """Predicted mean and s.d. of the response per trial.""" + p = self.predict_response_distribution(paradigm, parameters) + r = self.response_options + mean = p.values @ r + sd = np.sqrt(np.maximum(p.values @ r ** 2 - mean ** 2, 0)) + out = paradigm.copy() + out['predicted_mean'] = mean + out['predicted_sd'] = sd + return out + + def simulate(self, paradigm, parameters, n_samples=1, rng=None): + """Simulate integer responses (lapses, censoring and leakage included). + + Returns a long DataFrame with a ``sample`` index level and a + ``simulated_response`` column (the observed ``response`` column, if + any, is dropped to avoid collisions). + """ + rng = np.random.default_rng(rng) + p = self.predict_response_distribution(paradigm, parameters).values + cdf = np.cumsum(p, axis=1) + u = rng.random((n_samples, len(p), 1)) + ix = (u > cdf[None]).sum(-1) + ix = np.minimum(ix, p.shape[1] - 1) + sim = self.response_options[ix].T # (n_trials, n_samples) + # Built by position, not by index join: a paradigm index need not be unique. + par = paradigm.drop(columns=['response'], errors='ignore') + out = pd.concat([par.assign(sample=k + 1, simulated_response=sim[:, k]) + for k in range(n_samples)]) + return out.set_index('sample', append=True) + + def ppc(self, paradigm=None, idata=None, n_posterior_samples=200, random_seed=None, + progressbar=False): + """Posterior-predictive simulated datasets for the fitted trials. + + Draws ``n_posterior_samples`` posterior draws and simulates one full + dataset (same trials) from each. Returns a long DataFrame with index + ``paradigm.index + ppc_sample`` and a ``simulated_response`` column. + """ + idata = self._get_idata(idata) + if paradigm is None: + paradigm = self.paradigm + post = idata.posterior.stack(sample=('chain', 'draw')) + rng = np.random.default_rng(random_seed) + sel = rng.choice(post.sizes['sample'], size=min(n_posterior_samples, post.sizes['sample']), + replace=False) + thinned = post.isel(sample=sel) + thinned = thinned.assign_coords(sample=np.arange(len(sel))).rename(sample='draw') + thinned = thinned.expand_dims('chain').transpose('chain', 'draw', ...) + import arviz as az + id_thin = az.InferenceData(posterior=thinned) + with self.estimation_model: + pp = pm.sample_posterior_predictive(id_thin, var_names=['response'], + random_seed=random_seed, progressbar=progressbar) + arr = pp.posterior_predictive['response'].values[0] # (draw, trial) + sim = self.response_options[arr].T + out = pd.DataFrame(sim, index=paradigm.index, + columns=pd.Index(np.arange(len(sel)), name='ppc_sample')) + return out.stack().rename('simulated_response').to_frame() + + def sample_parameters_from_prior(self, n_subjects=None): + return super().sample_parameters_from_prior(n_subjects=n_subjects) diff --git a/tests/test_magnitude_estimation.py b/tests/test_magnitude_estimation.py new file mode 100644 index 0000000..6ffda32 --- /dev/null +++ b/tests/test_magnitude_estimation.py @@ -0,0 +1,158 @@ +"""Tests for ``bauer.magnitude_estimation.MagnitudeEstimationModel``. + +Build tests for every option, analytic sanity checks of the observer (the +response distribution is a proper distribution, censoring puts mass on the +scale ends, a uniform prior compresses), and simulate -> fit -> recover tests +on synthetic data (single-subject MAP; hierarchical NUTS marked ``slow``). +""" +import itertools +import warnings + +import numpy as np +import pandas as pd +import pytest + +warnings.filterwarnings('ignore') + +from bauer.magnitude_estimation import MagnitudeEstimationModel # noqa: E402 + + +def make_paradigm(n_subjects=3, n_trials=120, seed=0, response=True): + rng = np.random.default_rng(seed) + rows = [] + for s in range(1, n_subjects + 1): + for t in range(n_trials): + n, u = rng.integers(5, 25, size=2) + rows.append({'subject': s, 'trial': t, 'n': int(n), 'n_uncued': int(u), + 'response': int(rng.integers(5, 26)) if response else 5}) + return pd.DataFrame(rows).set_index(['subject', 'trial']) + + +@pytest.fixture +def paradigm(): + return make_paradigm() + + +OPTIONS = [ + dict(encoding=e, prior=p, readout=r) + for e, p, r in itertools.product(('weber', 'constant', 'flexible'), + ('true', 'fitted', 'empirical'), + ('mean', 'median')) +] + [dict(lapse=False), dict(leakage='mixture'), dict(leakage='average')] + + +@pytest.mark.parametrize('kwargs', OPTIONS) +def test_builds_and_finite_gradient(paradigm, kwargs): + m = MagnitudeEstimationModel(paradigm, n_measurement_grid=60, + n_hypothesis_grid=80, **kwargs) + m.build_estimation_model(paradigm, hierarchical=True) + model = m.estimation_model + assert 'response' in model.named_vars + ip = model.initial_point() + assert np.isfinite(model.compile_logp()(ip)) + assert np.all(np.isfinite(model.compile_dlogp()(ip))) + expected = {'nu', 'sigma_r'} + if kwargs.get('encoding') == 'flexible': + expected.add('nu_exponent') + if kwargs.get('prior') == 'fitted': + expected |= {'prior_mu', 'prior_sd'} + if kwargs.get('lapse', True): + expected.add('p_lapse') + if kwargs.get('leakage'): + expected.add('leak') + assert set(m.free_parameters) == expected + + +def _pars(**kw): + base = dict(nu=0.35, sigma_r=1.5, p_lapse=0.03) + base.update(kw) + return base + + +def test_response_distribution_is_normalised(paradigm): + m = MagnitudeEstimationModel(paradigm, leakage='average') + p = m.predict_response_distribution(paradigm, _pars(leak=0.1)) + np.testing.assert_allclose(p.sum(1), 1.0, atol=1e-8) + assert (p.values >= 0).all() + + +def test_censoring_puts_mass_on_scale_ends(): + """With large motor noise the end options carry the censored tails.""" + par = pd.DataFrame({'subject': 1, 'n': [5, 24], 'response': [5, 25]}).set_index('subject') + m = MagnitudeEstimationModel(par, lapse=False) + p = m.predict_response_distribution(par, dict(nu=0.1, sigma_r=4.0)).values + assert p[0, 0] > 0.3 # n = 5: much of the mass at the bottom option + assert p[1, -1] > p[1, -2] # n = 24: top option collects the upper tail + + +def test_uniform_prior_compresses_and_noise_scales_compression(): + par = pd.DataFrame({'subject': 1, 'n': np.arange(5, 25), 'response': 10}).set_index('subject') + slopes = [] + for nu in (0.15, 0.3, 0.5): + m = MagnitudeEstimationModel(par, lapse=False) + pred = m.predict(par, dict(nu=nu, sigma_r=1.0)) + slopes.append(np.polyfit(pred['n'], pred['predicted_mean'], 1)[0]) + assert slopes[0] > slopes[1] > slopes[2] + assert slopes[0] < 1.0 + + +def test_median_and_mean_readouts_differ_under_weber(): + par = pd.DataFrame({'subject': 1, 'n': np.arange(5, 25), 'response': 10}).set_index('subject') + p_mean = MagnitudeEstimationModel(par, readout='mean', lapse=False).predict( + par, dict(nu=0.4, sigma_r=1.0))['predicted_mean'] + p_med = MagnitudeEstimationModel(par, readout='median', lapse=False).predict( + par, dict(nu=0.4, sigma_r=1.0))['predicted_mean'] + assert np.abs(p_mean - p_med).max() > 0.05 + + +def test_mixture_leak_shifts_report_towards_uncued(): + par = pd.DataFrame({'subject': 1, 'n': [10] * 2, 'n_uncued': [6, 22], + 'response': 10}).set_index('subject') + m = MagnitudeEstimationModel(par, leakage='mixture') + pred = m.predict(par, _pars(leak=0.2))['predicted_mean'].values + assert pred[1] > pred[0] + 1.0 + + +def test_simulate_shapes_and_support(paradigm): + m = MagnitudeEstimationModel(paradigm) + sim = m.simulate(paradigm, _pars(), n_samples=3, rng=0) + assert len(sim) == 3 * len(paradigm) + assert sim['simulated_response'].between(5, 25).all() + assert 'response' not in sim.columns + + +@pytest.mark.parametrize('encoding,truth', [ + ('weber', dict(nu=0.35, sigma_r=1.5, p_lapse=0.04)), + ('constant', dict(nu=5.0, sigma_r=1.5, p_lapse=0.04)), +]) +def test_single_subject_map_recovery(encoding, truth): + par = make_paradigm(n_subjects=1, n_trials=1500, seed=3).droplevel('subject') + gen = MagnitudeEstimationModel(par, encoding=encoding) + sim = gen.simulate(par, truth, n_samples=1, rng=4) + data = sim.droplevel('sample').rename(columns={'simulated_response': 'response'}) + fit = MagnitudeEstimationModel(data, encoding=encoding) + fit.build_estimation_model(data, hierarchical=False) + est = fit.fit_map(progressbar=False) + assert est['nu'] == pytest.approx(truth['nu'], rel=0.15) + assert est['sigma_r'] == pytest.approx(truth['sigma_r'], rel=0.3) + assert est['p_lapse'] == pytest.approx(truth['p_lapse'], abs=0.025) + + +@pytest.mark.slow +def test_hierarchical_nuts_recovery(): + par = make_paradigm(n_subjects=5, n_trials=400, seed=5) + rng = np.random.default_rng(6) + truth = pd.DataFrame({'nu': rng.uniform(0.2, 0.5, 5), + 'sigma_r': rng.uniform(1.0, 2.0, 5), + 'p_lapse': rng.uniform(0.01, 0.05, 5)}, + index=pd.Index(np.arange(1, 6), name='subject')) + gen = MagnitudeEstimationModel(par) + sim = gen.simulate(par, truth, n_samples=1, rng=7) + data = sim.droplevel('sample').rename(columns={'simulated_response': 'response'}) + fit = MagnitudeEstimationModel(data, n_measurement_grid=100, n_hypothesis_grid=150) + fit.build_estimation_model(data, hierarchical=True) + idata = fit.sample(draws=300, tune=300, chains=2, cores=1, target_accept=0.9, + progressbar=False, random_seed=1) + est = idata.posterior['nu'].mean(('chain', 'draw')).values + assert np.corrcoef(est, truth['nu'].values)[0, 1] > 0.8 + np.testing.assert_allclose(est, truth['nu'].values, atol=0.08) From 65399aaec3e78a540a9451cbeedb63c1c9c76dae Mon Sep 17 00:00:00 2001 From: Gilles de Hollander Date: Sun, 25 Oct 2026 14:48:58 +0100 Subject: [PATCH 02/20] EstimationTaskModel: small component API (PowerSpace / UniformPrior / GaussianPrior / lapse) replacing MagnitudeEstimationModel Encoding is Gaussian in a Box-Cox power space f_alpha (alpha free or fixed; 0 = log/Weber, 1 = linear). Prior: uniform (e.g. the task range) or Gaussian in the same space (log-normal for log). Posterior-mean readout, rounded and censored to the response scale; lapse uniform over options; optional Gaussian motor noise. Closed-form likelihood for log space + log-normal prior; else a grid whose estimate n_hat(m) is inverted at the response-option edges, which keeps the likelihood exact and smooth. Noise nu and prior width are in log units at a reference magnitude so they stay comparable across alpha. Tests: every combination builds with finite gradients, closed form = grid, alpha -> 0 = log, uniform-prior compression, flat s.d. for linear + Gaussian, MAP and hierarchical NUTS recovery (incl. free alpha). Co-Authored-By: Claude Opus 5.5 --- bauer/magnitude_estimation.py | 526 ----------------------------- bauer/models/__init__.py | 6 + bauer/models/estimation_task.py | 519 ++++++++++++++++++++++++++++ tests/test_estimation_task.py | 146 ++++++++ tests/test_magnitude_estimation.py | 158 --------- 5 files changed, 671 insertions(+), 684 deletions(-) delete mode 100644 bauer/magnitude_estimation.py create mode 100644 bauer/models/estimation_task.py create mode 100644 tests/test_estimation_task.py delete mode 100644 tests/test_magnitude_estimation.py diff --git a/bauer/magnitude_estimation.py b/bauer/magnitude_estimation.py deleted file mode 100644 index 47db798..0000000 --- a/bauer/magnitude_estimation.py +++ /dev/null @@ -1,526 +0,0 @@ -""" -Bayesian-observer models of magnitude estimation on a bounded, discrete scale. - -The task: on each trial a magnitude ``n`` is shown (e.g. a dot array) and the -participant reports it on a bounded response scale (e.g. an integer slider from -5 to 25). The generative model is - -1. **Encoding.** A noisy internal measurement ``m``: - - * ``encoding='weber'`` m ~ N(log n, nu^2) (log-normal noise) - * ``encoding='constant'`` m ~ N(n, nu^2) (constant, items) - * ``encoding='flexible'`` m ~ N(n, (nu * (n / n_ref)^beta)^2) (power law; beta = 0 - is ``constant``, beta = 1 is scalar variability) - -2. **Prior.** The observer's prior over ``n``: - - * ``prior='true'`` uniform on the presented range (the task distribution) - * ``prior='fitted'`` Gaussian with free mean and width, in the encoding - space (log-normal for ``weber``, Gaussian in items otherwise) - * ``prior='empirical'`` each participant's own histogram of presented ``n`` - -3. **Readout.** The posterior mean (``readout='mean'``, squared-error loss) or - the posterior median (``readout='median'``, absolute-error loss) of ``n`` - given ``m``, in the units of the response scale. - -4. **Response.** Motor noise ``r ~ N(n_hat, sigma_r^2)``, discretised to the - integer response options and **censored** at the scale ends (all mass below - the lowest option goes to that option, likewise at the top). With - ``lapse=True`` a free per-participant lapse rate ``p_lapse`` mixes in a - uniform distribution over the response options. - -5. **Leakage of a second, uncued magnitude** (optional; needs ``n_uncued``): - - * ``leakage='mixture'`` with probability ``leak`` the participant reports the - *other* array (a swap), else the cued one. - * ``leakage='average'`` the report is ``(1 - leak) * n_hat(m_cued) + - leak * n_hat(m_uncued)``. The uncued term is integrated with a Gaussian - approximation (its mean and variance given ``n_uncued``), exact in the - limit of small ``leak``. - -Implementation: everything is computed on fixed grids. For each participant -the estimate ``n_hat(m)`` is precomputed on a measurement grid (posterior over a -hypothesis grid), the response distribution of every presented ``n`` is the -measurement density integrated against the discretised motor kernel (one -batched matmul), and the per-trial likelihood is a ``pm.Categorical`` over the -response options. Because the likelihood is an *observed* RV, pointwise -log-likelihoods (``pm.compute_log_likelihood`` -> LOO) and posterior-predictive -draws (``pm.sample_posterior_predictive``) work out of the box. - -Data conventions: ``n`` (presented, integer), ``response`` (integer on the -response scale), optional ``n_uncued``; a ``subject`` index level for -hierarchical fits. -""" - -import numpy as np -import pandas as pd -import pymc as pm -import pytensor.tensor as pt - -from .estimation import EstimationBaseModel - - -ENCODINGS = ('weber', 'constant', 'flexible') -PRIORS = ('true', 'fitted', 'empirical') -READOUTS = ('mean', 'median') -LEAKAGES = (None, 'mixture', 'average') - - -def _norm_cdf(x): - return 0.5 * pt.erfc(-x / np.sqrt(2.0)) - - -class MagnitudeEstimationModel(EstimationBaseModel): - """Hierarchical Bayesian observer for continuous magnitude estimation. - - Parameters - ---------- - paradigm : pd.DataFrame - Columns ``n`` and ``response`` (integers), optionally ``n_uncued``; - a ``subject`` index level for hierarchical fits. - encoding : {'weber', 'constant', 'flexible'} - prior : {'true', 'fitted', 'empirical'} - readout : {'mean', 'median'} - lapse : bool - Free per-participant lapse rate (uniform over response options). - leakage : {None, 'mixture', 'average'} - Influence of the uncued magnitude ``n_uncued`` (see module docstring). - stimulus_range : (int, int) - Smallest and largest presented magnitude (inclusive integers). The - ``'true'`` prior is uniform on ``[lo - .5, hi + .5]``. - response_range : (int, int) - Smallest and largest response option (inclusive integers). - n_ref : float - Reference magnitude of the ``flexible`` noise power law; ``nu`` is the - encoding s.d. (items) at ``n_ref``. - n_measurement_grid, n_hypothesis_grid : int - Grid sizes (measurement axis; observer's hypothesis axis). - hypothesis_range : (float, float) - Support of the observer's hypothesis grid (must contain the prior's mass). - """ - - paradigm_keys = ['n'] - - def __init__(self, paradigm=None, encoding='weber', prior='true', readout='mean', - lapse=True, leakage=None, stimulus_range=(5, 24), - response_range=(5, 25), n_ref=12.0, n_measurement_grid=150, - n_hypothesis_grid=246, hypothesis_range=(1.0, 50.0), **kwargs): - if encoding not in ENCODINGS: - raise ValueError(f'encoding must be one of {ENCODINGS}') - if prior not in PRIORS: - raise ValueError(f'prior must be one of {PRIORS}') - if readout not in READOUTS: - raise ValueError(f'readout must be one of {READOUTS}') - if leakage not in LEAKAGES: - raise ValueError(f'leakage must be one of {LEAKAGES}') - self.encoding = encoding - self.prior = prior - self.readout = readout - self.lapse = lapse - self.leakage = leakage - self.stimulus_range = tuple(int(x) for x in stimulus_range) - self.response_range = tuple(int(x) for x in response_range) - self.n_ref = float(n_ref) - self.n_measurement_grid = int(n_measurement_grid) - self.n_hypothesis_grid = int(n_hypothesis_grid) - self.hypothesis_range = tuple(float(x) for x in hypothesis_range) - if leakage is not None: - self.paradigm_keys = ['n', 'n_uncued'] - super().__init__(paradigm, lapse_rate=0.0, **kwargs) - self._setup_grids(paradigm) - - # ------------------------------------------------------------------ - # Parameters - # ------------------------------------------------------------------ - - @property - def log_space(self): - return self.encoding == 'weber' - - def get_free_parameters(self): - pars = {} - if self.encoding == 'weber': - # nu in log units; softplus(-1) = .31 - pars['nu'] = dict(mu_intercept=-1.0, sigma_intercept=0.75, - cauchy_sigma_intercept=0.5, transform='softplus') - else: - # nu in items (at n_ref for 'flexible'); softplus(5) ~ 5 - pars['nu'] = dict(mu_intercept=5.0, sigma_intercept=2.5, - cauchy_sigma_intercept=1.5, transform='softplus') - if self.encoding == 'flexible': - pars['nu_exponent'] = dict(mu_intercept=0.5, sigma_intercept=1.0, - cauchy_sigma_intercept=0.5, transform='identity') - if self.prior == 'fitted': - lo, hi = self.stimulus_range - if self.log_space: - mid = 0.5 * (np.log(lo) + np.log(hi)) - pars['prior_mu'] = dict(mu_intercept=mid, sigma_intercept=0.3, - cauchy_sigma_intercept=0.2, transform='identity') - pars['prior_sd'] = dict(mu_intercept=-0.5, sigma_intercept=0.75, - cauchy_sigma_intercept=0.5, transform='softplus') - else: - pars['prior_mu'] = dict(mu_intercept=0.5 * (lo + hi), sigma_intercept=3.0, - cauchy_sigma_intercept=2.0, transform='identity') - pars['prior_sd'] = dict(mu_intercept=(hi - lo + 1) / np.sqrt(12), - sigma_intercept=2.5, cauchy_sigma_intercept=1.5, - transform='softplus') - # motor noise in items; softplus(1) = 1.31 - pars['sigma_r'] = dict(mu_intercept=1.0, sigma_intercept=1.0, - cauchy_sigma_intercept=0.75, transform='softplus') - if self.lapse: - pars['p_lapse'] = dict(transform='beta', beta_mu_mean=0.05, beta_mu_kappa=8.0) - if self.leakage is not None: - pars['leak'] = dict(transform='beta', beta_mu_mean=0.05, beta_mu_kappa=8.0) - return pars - - def get_model_inputs(self, parameters): - return {key: self.subjectwise(key) for key in self.free_parameters} - - # ------------------------------------------------------------------ - # Grids and paradigm - # ------------------------------------------------------------------ - - def _setup_grids(self, paradigm): - lo, hi = self.stimulus_range - self.stimuli = np.arange(lo, hi + 1, dtype=float) # (K,) - rlo, rhi = self.response_range - self.response_options = np.arange(rlo, rhi + 1, dtype=float) # (R,) - # Category edges, censored at the scale ends - # (finite outer edges: an infinite edge makes d/d(sd) = inf * 0 = NaN) - self.response_edges = np.concatenate( - [[-1e4], self.response_options[:-1] + 0.5, [1e4]]) - - h0, h1 = self.hypothesis_range - self.hyp_grid = np.linspace(h0, h1, self.n_hypothesis_grid) # (H,) - self.d_hyp = self.hyp_grid[1] - self.hyp_grid[0] - - if self.log_space: - self.meas_grid = np.linspace(np.log(h0) - 0.5, np.log(h1) + 0.5, - self.n_measurement_grid) - else: - self.meas_grid = np.linspace(h0 - 20.0, h1 + 10.0, self.n_measurement_grid) - self.d_meas = self.meas_grid[1] - self.meas_grid[0] - - # True prior: uniform on [lo - .5, hi + .5]; cell-overlap weights. - a, b = lo - 0.5, hi + 0.5 - left = np.clip(self.hyp_grid - self.d_hyp / 2, a, b) - right = np.clip(self.hyp_grid + self.d_hyp / 2, a, b) - w = right - left - self.true_prior = w / w.sum() - - self.subject_ids = None - self.empirical_prior = None - if paradigm is not None: - if 'subject' in paradigm.index.names: - subj = paradigm.index.get_level_values('subject') - elif 'subject' in paradigm.columns: - subj = paradigm['subject'].values - else: - subj = np.zeros(len(paradigm), dtype=int) - codes, uniques = pd.factorize(subj) - self.subject_ids = uniques - if self.prior == 'empirical': - n = paradigm['n'].values.astype(int) - counts = np.zeros((len(uniques), len(self.stimuli))) - np.add.at(counts, (codes, n - lo), 1.0) - # Spread each integer's mass over its [k - .5, k + .5] cell - cell = np.zeros((len(self.stimuli), len(self.hyp_grid))) - for k, nk in enumerate(self.stimuli): - l_ = np.clip(self.hyp_grid - self.d_hyp / 2, nk - .5, nk + .5) - r_ = np.clip(self.hyp_grid + self.d_hyp / 2, nk - .5, nk + .5) - cell[k] = (r_ - l_) - emp = counts @ cell - self.empirical_prior = emp / emp.sum(1, keepdims=True) - - def _get_paradigm(self, paradigm=None, subject_mapping=None): - if paradigm is None: - paradigm = self.paradigm - lo, hi = self.stimulus_range - rlo, rhi = self.response_range - n = paradigm['n'].values - if np.any(n != np.round(n)) or n.min() < lo or n.max() > hi: - raise ValueError(f'n must be integers in {self.stimulus_range}') - - paradigm_ = {'_data_n': len(paradigm)} - if subject_mapping is None: - if 'subject' in paradigm.index.names: - paradigm_['subject_ix'], _ = pd.factorize(paradigm.index.get_level_values('subject')) - elif 'subject' in paradigm.columns: - paradigm_['subject_ix'], _ = pd.factorize(paradigm['subject']) - else: - paradigm_['subject_ix'] = np.zeros(len(paradigm), dtype=int) - else: - s = (paradigm.index.get_level_values('subject') if 'subject' in paradigm.index.names - else paradigm['subject']) - paradigm_['subject_ix'] = np.array([subject_mapping[x] for x in s]) - - paradigm_['stimulus_ix'] = (n - lo).astype(int) - if self.leakage is not None: - u = paradigm['n_uncued'].values - paradigm_['uncued_ix'] = (u - lo).astype(int) - - if 'response' in paradigm.columns: - r = paradigm['response'].values.astype(float) - if np.any(np.isnan(r)): - raise ValueError('response has NaNs; drop no-response trials first') - r = np.clip(np.round(r), rlo, rhi) - paradigm_['response_ix'] = (r - rlo).astype(int) - else: - paradigm_['response_ix'] = np.zeros(len(paradigm), dtype=int) - return paradigm_ - - # ------------------------------------------------------------------ - # The observer - # ------------------------------------------------------------------ - - def _encoding_sd(self, nu, nu_exponent, x): - """Encoding s.d. at magnitudes x. nu: (S,), x: (..., P) -> (S, P).""" - if self.encoding == 'flexible': - return nu[:, None] * (x[None, :] / self.n_ref) ** nu_exponent[:, None] - return pt.ones((1, x.shape[0])) * nu[:, None] - - def _encode(self, x): - return np.log(x) if self.log_space else x - - def _prior_on_grid(self, inputs): - """(S, H) normalised prior mass on the hypothesis grid.""" - h = pt.as_tensor_variable(self.hyp_grid) - if self.prior == 'true': - return pt.as_tensor_variable(self.true_prior)[None, :] - if self.prior == 'empirical': - return pt.as_tensor_variable(self.empirical_prior) - mu = inputs['prior_mu'][:, None] - sd = inputs['prior_sd'][:, None] - if self.log_space: - logdens = -0.5 * ((pt.log(h)[None, :] - mu) / sd) ** 2 - pt.log(h)[None, :] - else: - logdens = -0.5 * ((h[None, :] - mu) / sd) ** 2 - logdens = logdens - pt.max(logdens, axis=1, keepdims=True) - dens = pt.exp(logdens) - return dens / pt.sum(dens, axis=1, keepdims=True) - - def _estimate_on_measurement_grid(self, inputs): - """n_hat(m): (S, M) estimate for every measurement on the grid.""" - nu = inputs['nu'] - beta = inputs.get('nu_exponent', None) - h = self.hyp_grid - m = pt.as_tensor_variable(self.meas_grid) - sd_h = self._encoding_sd(nu, beta, pt.as_tensor_variable(h)) # (S|1, H) - mu_h = pt.as_tensor_variable(self._encode(h)) # (H,) - # log p(m | h): (S, M, H) - loglik = (-0.5 * ((m[None, :, None] - mu_h[None, None, :]) / sd_h[:, None, :]) ** 2 - - pt.log(sd_h)[:, None, :]) - logprior = pt.log(self._prior_on_grid(inputs) + 1e-300) # (S|1, H) - logpost = loglik + logprior[:, None, :] - logpost = logpost - pt.max(logpost, axis=2, keepdims=True) - post = pt.exp(logpost) - post = post / pt.sum(post, axis=2, keepdims=True) # (S, M, H) - hh = pt.as_tensor_variable(h) - if self.readout == 'mean': - return pt.sum(post * hh[None, None, :], axis=2) - # Median: posterior mass is piecewise constant over cells of width d_hyp - # centred on the grid; the median is the point where the cumulative mass - # crosses .5, linearly interpolated within its cell (continuous in the - # parameters, so NUTS sees a usable gradient). - cum = pt.cumsum(post, axis=2) - before = cum - post - frac = pt.clip((0.5 - before) / (post + 1e-30), 0.0, 1.0) - return (h[0] - self.d_hyp / 2) + self.d_hyp * pt.sum(frac, axis=2) - - def _measurement_density(self, inputs): - """p(m | n_k) * dm for every presented magnitude: (S, K, M).""" - nu = inputs['nu'] - beta = inputs.get('nu_exponent', None) - x = pt.as_tensor_variable(self.stimuli) - sd = self._encoding_sd(nu, beta, x) # (S|1, K) - mu = pt.as_tensor_variable(self._encode(self.stimuli)) - m = pt.as_tensor_variable(self.meas_grid) - logd = -0.5 * ((m[None, None, :] - mu[None, :, None]) / sd[:, :, None]) ** 2 - logd = logd - pt.max(logd, axis=2, keepdims=True) - d = pt.exp(logd) - return d / pt.sum(d, axis=2, keepdims=True) - - def _motor_kernel(self, centre, sd): - """P(response option | centre) for centre (..., M), sd broadcastable.""" - edges = pt.as_tensor_variable(self.response_edges) - z = (edges - centre[..., None]) / sd[..., None] - cdf = _norm_cdf(z) - return cdf[..., 1:] - cdf[..., :-1] # (..., R) - - def response_table(self, inputs): - """Response distribution per participant and presented magnitude. - - Returns (S, K, R), or (S, K, K, R) indexed [s, cued, uncued, r] for - ``leakage='average'``. Lapses are mixed in, mixtures are not (the - mixture is formed per trial in ``trial_probabilities``). - """ - n_hat = self._estimate_on_measurement_grid(inputs) # (S, M) - p_m = self._measurement_density(inputs) # (S, K, M) - sigma_r = inputs['sigma_r'] - R = len(self.response_options) - - if self.leakage == 'average': - leak = inputs['leak'] - mu_u = pt.sum(p_m * n_hat[:, None, :], axis=2) # (S, K) - var_u = pt.sum(p_m * (n_hat[:, None, :] - mu_u[:, :, None]) ** 2, axis=2) - centre = ((1 - leak)[:, None, None] * n_hat[:, None, :] - + leak[:, None, None] * mu_u[:, :, None]) # (S, U, M) - sd = pt.sqrt(sigma_r[:, None] ** 2 + leak[:, None] ** 2 * var_u) # (S, U) - kern = self._motor_kernel(centre, pt.repeat(sd[:, :, None], centre.shape[2], axis=2)) - # (S, K_c, M) x (S, U, M, R) -> (S, K_c, U, R), as one batched matmul - # over M (no 5-D intermediate in the gradient graph) - S_, U_ = kern.shape[0], kern.shape[1] - kern_m = kern.dimshuffle(0, 2, 1, 3).reshape((S_, kern.shape[2], U_ * R)) - table = pt.batched_dot(p_m, kern_m).reshape((S_, p_m.shape[1], U_, R)) - else: - kern = self._motor_kernel(n_hat, sigma_r[:, None] * pt.ones_like(n_hat)) # (S, M, R) - table = pt.batched_dot(p_m, kern) # (S, K, R) - - if self.lapse: - lam = inputs['p_lapse'] - lam = lam.reshape((-1,) + (1,) * (table.ndim - 1)) - table = (1 - lam) * table + lam / R - return table - - def trial_probabilities(self, inputs, subject_ix, stimulus_ix, uncued_ix=None): - table = self.response_table(inputs) - if self.leakage == 'average': - p = table[subject_ix, stimulus_ix, uncued_ix] - elif self.leakage == 'mixture': - leak = inputs['leak'][subject_ix][:, None] - p = (1 - leak) * table[subject_ix, stimulus_ix] + leak * table[subject_ix, uncued_ix] - else: - p = table[subject_ix, stimulus_ix] - p = pt.clip(p, 1e-10, 1.0) - return p / pt.sum(p, axis=1, keepdims=True) - - # ------------------------------------------------------------------ - # PyMC graph - # ------------------------------------------------------------------ - - def build_estimation_model(self, data=None, coords=None, hierarchical=True, - save_p_choice=False, flat_prior=False, paradigm=None): - if data is None: - data = paradigm if paradigm is not None else self.paradigm - self._setup_grids(data) - if hierarchical and coords is None: - coords = {'subject': data.index.unique(level='subject')} - with pm.Model(coords=coords) as self.estimation_model: - paradigm_ = self._get_paradigm(paradigm=data) - self.set_paradigm(paradigm_) - self.build_priors(hierarchical=hierarchical, flat_prior=flat_prior) - self.build_likelihood(None, save_p_choice=save_p_choice) - - def build_likelihood(self, parameters, save_p_choice=False): - model = pm.Model.get_context() - inputs = self.get_model_inputs(parameters) - p = self.trial_probabilities( - inputs, model['subject_ix'], model['stimulus_ix'], - model['uncued_ix'] if self.leakage is not None else None) - if save_p_choice: - p = pm.Deterministic('p_response', p) - pm.Categorical('response', p=p, observed=model['response_ix']) - - # ------------------------------------------------------------------ - # Prediction / simulation - # ------------------------------------------------------------------ - - def _parameter_arrays(self, parameters, subject_ids): - """dict name -> (S,) float array, aligned to ``subject_ids``.""" - if isinstance(parameters, pd.DataFrame): - pars = parameters.loc[list(subject_ids)] - return {k: pars[k].values.astype(float) for k in self.free_parameters} - out = {} - for k in self.free_parameters: - v = np.atleast_1d(np.asarray(parameters[k], dtype=float)) - out[k] = np.broadcast_to(v, (len(subject_ids),)).copy() - return out - - def predict_response_distribution(self, paradigm, parameters): - """Per-trial probabilities over the response options. - - Returns a DataFrame (index = paradigm.index, columns = response options). - ``parameters``: DataFrame indexed by subject, or a dict of scalars/arrays. - """ - if self.prior == 'empirical': - self._setup_grids(paradigm) - if 'subject' in paradigm.index.names: - subj = paradigm.index.get_level_values('subject') - elif 'subject' in paradigm.columns: - subj = paradigm['subject'].values - else: - subj = np.zeros(len(paradigm), dtype=int) - codes, uniques = pd.factorize(subj) - pars = self._parameter_arrays(parameters, uniques) - inputs = {k: pt.as_tensor_variable(v) for k, v in pars.items()} - par_ = self._get_paradigm(paradigm) - par_['subject_ix'] = codes - p = self.trial_probabilities( - inputs, pt.as_tensor_variable(par_['subject_ix']), - pt.as_tensor_variable(par_['stimulus_ix']), - pt.as_tensor_variable(par_['uncued_ix']) if self.leakage is not None else None).eval() - return pd.DataFrame(p, index=paradigm.index, - columns=pd.Index(self.response_options.astype(int), name='response')) - - def predict(self, paradigm, parameters): - """Predicted mean and s.d. of the response per trial.""" - p = self.predict_response_distribution(paradigm, parameters) - r = self.response_options - mean = p.values @ r - sd = np.sqrt(np.maximum(p.values @ r ** 2 - mean ** 2, 0)) - out = paradigm.copy() - out['predicted_mean'] = mean - out['predicted_sd'] = sd - return out - - def simulate(self, paradigm, parameters, n_samples=1, rng=None): - """Simulate integer responses (lapses, censoring and leakage included). - - Returns a long DataFrame with a ``sample`` index level and a - ``simulated_response`` column (the observed ``response`` column, if - any, is dropped to avoid collisions). - """ - rng = np.random.default_rng(rng) - p = self.predict_response_distribution(paradigm, parameters).values - cdf = np.cumsum(p, axis=1) - u = rng.random((n_samples, len(p), 1)) - ix = (u > cdf[None]).sum(-1) - ix = np.minimum(ix, p.shape[1] - 1) - sim = self.response_options[ix].T # (n_trials, n_samples) - # Built by position, not by index join: a paradigm index need not be unique. - par = paradigm.drop(columns=['response'], errors='ignore') - out = pd.concat([par.assign(sample=k + 1, simulated_response=sim[:, k]) - for k in range(n_samples)]) - return out.set_index('sample', append=True) - - def ppc(self, paradigm=None, idata=None, n_posterior_samples=200, random_seed=None, - progressbar=False): - """Posterior-predictive simulated datasets for the fitted trials. - - Draws ``n_posterior_samples`` posterior draws and simulates one full - dataset (same trials) from each. Returns a long DataFrame with index - ``paradigm.index + ppc_sample`` and a ``simulated_response`` column. - """ - idata = self._get_idata(idata) - if paradigm is None: - paradigm = self.paradigm - post = idata.posterior.stack(sample=('chain', 'draw')) - rng = np.random.default_rng(random_seed) - sel = rng.choice(post.sizes['sample'], size=min(n_posterior_samples, post.sizes['sample']), - replace=False) - thinned = post.isel(sample=sel) - thinned = thinned.assign_coords(sample=np.arange(len(sel))).rename(sample='draw') - thinned = thinned.expand_dims('chain').transpose('chain', 'draw', ...) - import arviz as az - id_thin = az.InferenceData(posterior=thinned) - with self.estimation_model: - pp = pm.sample_posterior_predictive(id_thin, var_names=['response'], - random_seed=random_seed, progressbar=progressbar) - arr = pp.posterior_predictive['response'].values[0] # (draw, trial) - sim = self.response_options[arr].T - out = pd.DataFrame(sim, index=paradigm.index, - columns=pd.Index(np.arange(len(sel)), name='ppc_sample')) - return out.stack().rename('simulated_response').to_frame() - - def sample_parameters_from_prior(self, n_subjects=None): - return super().sample_parameters_from_prior(n_subjects=n_subjects) diff --git a/bauer/models/__init__.py b/bauer/models/__init__.py index 596e2a7..b86191d 100644 --- a/bauer/models/__init__.py +++ b/bauer/models/__init__.py @@ -64,3 +64,9 @@ RaceDiffusionPowerLawNoiseRiskRegressionModel, logp_race_diffusion_2, ) + +from .estimation_task import ( + EstimationTaskModel, + PowerSpace, LogSpace, LinearSpace, + UniformPrior, GaussianPrior, LogNormalPrior, +) diff --git a/bauer/models/estimation_task.py b/bauer/models/estimation_task.py new file mode 100644 index 0000000..927bb80 --- /dev/null +++ b/bauer/models/estimation_task.py @@ -0,0 +1,519 @@ +""" +Bayesian-observer model of magnitude estimation on a bounded response scale. + +A participant sees a magnitude ``n`` (e.g. a dot array) and reports it on a +bounded, discrete scale (e.g. an integer slider from 5 to 25). The model has +three pluggable parts: + +**Encoding space** -- ``PowerSpace(alpha)``. The internal measurement is +Gaussian in a Box-Cox / power-transformed space, + + m ~ N(f_alpha(n), nu_f^2), f_alpha(n) = (n^alpha - 1) / alpha, + +with ``alpha -> 0`` the log space (Weber's law: noise in items grows in +proportion to n) and ``alpha = 1`` the linear space (constant noise in items). +In between, the noise in items grows as ``n^(1 - alpha)`` -- a generalised Weber +law. ``LogSpace()`` and ``LinearSpace()`` are the two fixed ends; +``PowerSpace()`` (no argument) makes alpha a free, hierarchical parameter. + +Efficient coding (Wei & Stocker 2015; Morais & Pillow 2018) is a special case +of the same family: an encoder whose internal space is the CDF of an encoding +prior ``p_enc`` with constant noise there is a power space whenever ``p_enc`` +is a power law. Efficient for a ``1/n`` ("natural") prior = log space; +efficient for the task's uniform prior = linear space; ``p_enc ~ n^-kappa`` +gives ``alpha = 1 - kappa``. So a fitted alpha can be read as the exponent of +the stimulus distribution the encoding is adapted to. + +The free noise parameter ``nu`` is the noise **in log units at n_ref** +(a Weber fraction), whatever alpha is; internally ``nu_f = nu * n_ref^alpha``. +This keeps ``nu`` comparable across alpha and removes most of the alpha / noise +trade-off that a raw ``nu_f`` would have. + +**Prior** -- the observer's belief about ``n`` used to decode. + +* ``UniformPrior(lo, hi)`` -- e.g. the true task distribution (no free + parameters). For integer stimuli 5..24 use ``UniformPrior(4.5, 24.5)``. +* ``GaussianPrior()`` -- Gaussian in the *same* encoding space, + ``N(f_alpha(mu), sd_f^2)``: log-normal for alpha = 0, Gaussian in items for + alpha = 1. Free parameters ``prior_mu`` (its centre, in items) and + ``prior_sd`` (its width in log units at the centre; ``sd_f = prior_sd * + prior_mu^alpha``). + +**Lapse** -- with probability ``p_lapse`` the response is uniform over the +response options (on by default). + +**Readout** is the posterior mean of ``n`` (in items); the estimate is reported +directly, rounded to the nearest response option and censored at the scale +ends. There is no separate motor noise by default (``motor_noise=False``): in a +Bayesian observer the encoding noise already sets both the compression and the +report scatter, and on the round-1 retinonumeral data an extra Gaussian motor +noise was not separately recoverable from the encoding noise (see +``tests/test_estimation_task.py``). ``motor_noise=True`` adds a Gaussian +``sigma_r`` (items) for users who want it. + +Likelihood -- two paths, chosen automatically +---------------------------------------------- +* **Closed form** (``LogSpace`` + ``GaussianPrior``, no motor noise): the + posterior over ``log n`` is Gaussian, so ``log n_hat = w m + (1 - w) mu + + w nu^2 / 2`` with ``w = sd^2 / (sd^2 + nu^2)``, the report is log-normal, + ``log r ~ N(w log n + (1 - w) mu + w nu^2 / 2, (w nu)^2)``, and the + probability of each response option is a difference of normal CDFs at the + option edges. +* **Grid** (everything else, e.g. the uniform prior or a free alpha): for each + participant the estimate ``n_hat(m)`` is computed on a measurement grid (the + posterior mean over a hypothesis grid), then *inverted* at the response-option + edges (``n_hat`` is monotone in ``m``), so P(option) is again a difference of + normal CDFs of the measurement -- exact up to the grid's interpolation and + smooth in the parameters (usable gradients for NUTS). The measurement grid + moves with alpha. The two paths agree to < 1e-3 per option probability on + the cases where both apply (tested). + +The per-trial likelihood is an observed ``pm.Categorical`` over the response +options, so ``pm.compute_log_likelihood`` (LOO / ``az.compare``) and +posterior-predictive sampling work directly. + +Example +------- +>>> from bauer.models import EstimationTaskModel, LogSpace, UniformPrior +>>> model = EstimationTaskModel(data, encoding_space=LogSpace(), +... prior=UniformPrior(4.5, 24.5), response_range=(5, 25)) +>>> model.build_estimation_model(data); idata = model.sample() + +``data`` has columns ``n`` (presented magnitude) and ``response`` (integer +report) and a ``subject`` index level. +""" + +import numpy as np +import pandas as pd +import pymc as pm +import pytensor.tensor as pt + +from ..estimation import EstimationBaseModel + + +def _norm_cdf(x): + return 0.5 * pt.erfc(-x / np.sqrt(2.0)) + + +# ============================================================================ +# Components +# ============================================================================ + +class PowerSpace: + """Encoding space f_alpha(n) = (n^alpha - 1) / alpha (Box-Cox). + + Parameters + ---------- + alpha : float or None + Fixed exponent, or ``None`` for a free hierarchical parameter + ``alpha`` (default prior N(0.5, 0.5) on the group mean, i.e. 95% mass + on [-0.5, 1.5]). + """ + + def __init__(self, alpha=None): + self.alpha = alpha + + @property + def free(self): + return self.alpha is None + + @property + def is_log(self): + return (not self.free) and self.alpha == 0.0 + + def transform(self, n, alpha): + """f_alpha(n); ``alpha`` scalar or tensor broadcastable to ``n``.""" + if not self.free and self.alpha == 0.0: + return pt.log(n) + # expm1 form; |alpha| floored at 1e-4 (error ~1e-4 * log(n)^2 / 2) + a = pt.switch(pt.lt(pt.abs(alpha), 1e-4), 1e-4, alpha) + return pt.expm1(a * pt.log(n)) / a + + def transform_np(self, n, alpha): + if alpha == 0.0: + return np.log(n) + return np.expm1(alpha * np.log(n)) / alpha + + def __repr__(self): + return f'PowerSpace(alpha={self.alpha})' + + +def LogSpace(): + """Log encoding (Weber's law): ``PowerSpace(0)``.""" + return PowerSpace(0.0) + + +def LinearSpace(): + """Linear encoding (constant noise in items): ``PowerSpace(1)``.""" + return PowerSpace(1.0) + + +class UniformPrior: + """Uniform prior on [lo, hi] (items); no free parameters.""" + free_parameters = () + + def __init__(self, lo, hi): + self.lo, self.hi = float(lo), float(hi) + + def __repr__(self): + return f'UniformPrior({self.lo}, {self.hi})' + + +class GaussianPrior: + """Gaussian prior in the encoding space (log-normal for log space). + + Free parameters: ``prior_mu`` (centre, items) and ``prior_sd`` (width in + log units at the centre). + """ + free_parameters = ('prior_mu', 'prior_sd') + + def __repr__(self): + return 'GaussianPrior()' + + +# Alias in the spirit of the docs (log-normal when the space is log) +LogNormalPrior = GaussianPrior + + +# ============================================================================ +# Model +# ============================================================================ + +class EstimationTaskModel(EstimationBaseModel): + """Hierarchical Bayesian observer for magnitude estimation (see module doc). + + Parameters + ---------- + paradigm : pd.DataFrame + ``n`` (presented magnitude, > 0), ``response`` (integer); ``subject`` + index level for hierarchical fits. + encoding_space : PowerSpace + prior : UniformPrior or GaussianPrior + lapse : bool + motor_noise : bool + response_range : (int, int) + Smallest and largest response option (inclusive integers, step 1). + n_ref : float + Magnitude at which ``nu`` is expressed (log units). + n_measurement_grid, n_hypothesis_grid : int + hypothesis_range : (float, float) + Support of the observer's hypothesis grid (items). + """ + + def __init__(self, paradigm=None, encoding_space=None, prior=None, lapse=True, + motor_noise=False, response_range=(5, 25), n_ref=12.0, + n_measurement_grid=200, n_hypothesis_grid=246, + hypothesis_range=(1.0, 50.0), **kwargs): + self.encoding_space = encoding_space if encoding_space is not None else LogSpace() + self.prior = prior if prior is not None else UniformPrior(4.5, 24.5) + self.lapse = lapse + self.motor_noise = motor_noise + self.response_range = tuple(int(x) for x in response_range) + self.n_ref = float(n_ref) + self.n_measurement_grid = int(n_measurement_grid) + self.n_hypothesis_grid = int(n_hypothesis_grid) + self.hypothesis_range = tuple(float(x) for x in hypothesis_range) + super().__init__(paradigm, lapse_rate=0.0, **kwargs) + self._setup_grids() + + @property + def closed_form(self): + """True when the likelihood is computed analytically (no grid).""" + return (self.encoding_space.is_log and isinstance(self.prior, GaussianPrior) + and not self.motor_noise) + + # ------------------------------------------------------------------ + def get_free_parameters(self): + pars = {'nu': dict(mu_intercept=-1.0, sigma_intercept=0.75, + cauchy_sigma_intercept=0.5, transform='softplus')} + if self.encoding_space.free: + pars['alpha'] = dict(mu_intercept=0.5, sigma_intercept=0.5, + cauchy_sigma_intercept=0.3, transform='identity') + if isinstance(self.prior, GaussianPrior): + pars['prior_mu'] = dict(mu_intercept=12.0, sigma_intercept=4.0, + cauchy_sigma_intercept=2.0, transform='softplus') + pars['prior_sd'] = dict(mu_intercept=-0.5, sigma_intercept=0.75, + cauchy_sigma_intercept=0.5, transform='softplus') + if self.motor_noise: + pars['sigma_r'] = dict(mu_intercept=1.0, sigma_intercept=1.0, + cauchy_sigma_intercept=0.75, transform='softplus') + if self.lapse: + pars['p_lapse'] = dict(transform='beta', beta_mu_mean=0.05, beta_mu_kappa=8.0) + return pars + + def get_model_inputs(self, parameters): + return {key: self.subjectwise(key) for key in self.free_parameters} + + # ------------------------------------------------------------------ + def _setup_grids(self, paradigm=None): + rlo, rhi = self.response_range + self.response_options = np.arange(rlo, rhi + 1, dtype=float) + # finite outer edges (censoring); infinite ones give NaN gradients + self.response_edges = np.concatenate( + [[1e-3], self.response_options[:-1] + 0.5, [1e4]]) + h0, h1 = self.hypothesis_range + self.hyp_grid = np.linspace(h0, h1, self.n_hypothesis_grid) + self.d_hyp = self.hyp_grid[1] - self.hyp_grid[0] + # measurement grid in units of the hypothesis range in f-space + self.meas_t = np.linspace(-0.5, 1.5, self.n_measurement_grid) + if isinstance(self.prior, UniformPrior): + a, b = self.prior.lo, self.prior.hi + left = np.clip(self.hyp_grid - self.d_hyp / 2, a, b) + right = np.clip(self.hyp_grid + self.d_hyp / 2, a, b) + w = right - left + self.uniform_prior_mass = w / w.sum() + + def _get_paradigm(self, paradigm=None, subject_mapping=None): + if paradigm is None: + paradigm = self.paradigm + rlo, rhi = self.response_range + paradigm_ = {'_data_n': len(paradigm)} + if 'subject' in paradigm.index.names: + paradigm_['subject_ix'], _ = pd.factorize(paradigm.index.get_level_values('subject')) + elif 'subject' in paradigm.columns: + paradigm_['subject_ix'], _ = pd.factorize(paradigm['subject']) + else: + paradigm_['subject_ix'] = np.zeros(len(paradigm), dtype=int) + paradigm_['n'] = paradigm['n'].values.astype(float) + if 'response' in paradigm.columns: + r = paradigm['response'].values.astype(float) + if np.any(np.isnan(r)): + raise ValueError('response has NaNs; drop no-response trials first') + r = np.clip(np.round(r), rlo, rhi) + paradigm_['response_ix'] = (r - rlo).astype(int) + else: + paradigm_['response_ix'] = np.zeros(len(paradigm), dtype=int) + return paradigm_ + + # ------------------------------------------------------------------ + # Observer + # ------------------------------------------------------------------ + def _alpha(self, inputs, S): + if self.encoding_space.free: + return inputs['alpha'] + return pt.ones((S,)) * self.encoding_space.alpha + + def _f(self, x, alpha): + """f_alpha(x) for x (P,) and alpha (S,) -> (S, P).""" + # (+ 0 * alpha keeps the subject axis when the space ignores alpha) + return self.encoding_space.transform(x[None, :], alpha[:, None]) + 0.0 * alpha[:, None] + + def _nu_f(self, inputs, alpha): + return inputs['nu'] * self.n_ref ** alpha # (S,) + + def _option_probs_closed(self, inputs, n, subject_ix): + """(n_trials, R) for log space + Gaussian (log-normal) prior.""" + nu = inputs['nu'][subject_ix] + mu = pt.log(inputs['prior_mu'][subject_ix]) + sd = inputs['prior_sd'][subject_ix] + w = sd ** 2 / (sd ** 2 + nu ** 2) + loc = w * pt.log(n) + (1 - w) * mu + w * nu ** 2 / 2 + scale = w * nu + edges = pt.log(pt.as_tensor_variable(self.response_edges)) + cdf = _norm_cdf((edges[None, :] - loc[:, None]) / scale[:, None]) + return cdf[:, 1:] - cdf[:, :-1] + + def estimate_on_grid(self, inputs, S): + """Measurement grid m (S, M) and posterior-mean estimate n_hat(m) (S, M).""" + alpha = self._alpha(inputs, S) + nu_f = self._nu_f(inputs, alpha) + h = pt.as_tensor_variable(self.hyp_grid) + fh = self._f(h, alpha) # (S, H) + lo = fh[:, 0][:, None] + hi = fh[:, -1][:, None] + m = lo + pt.as_tensor_variable(self.meas_t)[None, :] * (hi - lo) # (S, M) + loglik = -0.5 * ((m[:, :, None] - fh[:, None, :]) / nu_f[:, None, None]) ** 2 + if isinstance(self.prior, UniformPrior): + logprior = pt.log(pt.as_tensor_variable(self.uniform_prior_mass) + 1e-300)[None, :] + else: + mu_f = self.encoding_space.transform(inputs['prior_mu'], alpha) # (S,) + sd_f = inputs['prior_sd'] * inputs['prior_mu'] ** alpha + # density in n: N(f(h); mu_f, sd_f) * f'(h), f'(h) = h^(alpha - 1) + logprior = (-0.5 * ((fh - mu_f[:, None]) / sd_f[:, None]) ** 2 + + (alpha[:, None] - 1) * pt.log(h)[None, :]) + logpost = loglik + logprior[:, None, :] + logpost = logpost - pt.max(logpost, axis=2, keepdims=True) + post = pt.exp(logpost) + post = post / pt.sum(post, axis=2, keepdims=True) + n_hat = pt.sum(post * h[None, None, :], axis=2) # (S, M) + return m, n_hat, alpha, nu_f + + def _invert(self, m, n_hat, values): + """m at which the monotone n_hat(m) crosses each of ``values`` (R+1,). + + Linear interpolation per participant; values outside the range of + n_hat map to the grid ends (where the measurement density is ~0). + """ + M = self.n_measurement_grid + v = pt.as_tensor_variable(values) + below = pt.sum(pt.lt(n_hat[:, :, None], v[None, None, :]), axis=1) # (S, V) + j = pt.clip(below - 1, 0, M - 2) + grid_ix = pt.arange(M) + oh0 = pt.eq(grid_ix[None, None, :], j[:, :, None]) # (S, V, M) + oh1 = pt.eq(grid_ix[None, None, :], (j + 1)[:, :, None]) + n0 = pt.sum(oh0 * n_hat[:, None, :], axis=2) + n1 = pt.sum(oh1 * n_hat[:, None, :], axis=2) + m0 = pt.sum(oh0 * m[:, None, :], axis=2) + m1 = pt.sum(oh1 * m[:, None, :], axis=2) + frac = pt.clip((v[None, :] - n0) / (n1 - n0 + 1e-12), 0.0, 1.0) + out = m0 + frac * (m1 - m0) + # entirely below / above the estimate's range + out = pt.switch(pt.eq(below, 0), m[:, :1] - 1e3, out) + out = pt.switch(pt.eq(below, M), m[:, -1:] + 1e3, out) + return out # (S, V) + + def _option_probs_grid(self, inputs, n, subject_ix, S): + m, n_hat, alpha, nu_f = self.estimate_on_grid(inputs, S) + fn = self.encoding_space.transform(n, alpha[subject_ix]) # (T,) + nu_t = nu_f[subject_ix] + if not self.motor_noise: + m_edges = self._invert(m, n_hat, self.response_edges) # (S, R+1) + z = (m_edges[subject_ix] - fn[:, None]) / nu_t[:, None] + cdf = _norm_cdf(z) + return cdf[:, 1:] - cdf[:, :-1] + # motor noise: integrate the measurement density over the grid + dens = pt.exp(-0.5 * ((m[subject_ix] - fn[:, None]) / nu_t[:, None]) ** 2) + dens = dens / pt.sum(dens, axis=1, keepdims=True) # (T, M) + edges = pt.as_tensor_variable(self.response_edges) + sig = inputs['sigma_r'][:, None, None] + cdf = _norm_cdf((edges[None, None, :] - n_hat[:, :, None]) / sig) # (S, M, R+1) + kern = cdf[:, :, 1:] - cdf[:, :, :-1] # (S, M, R) + return pt.sum(dens[:, :, None] * kern[subject_ix], axis=1) + + def trial_probabilities(self, inputs, n, subject_ix, S): + if self.closed_form: + p = self._option_probs_closed(inputs, n, subject_ix) + else: + p = self._option_probs_grid(inputs, n, subject_ix, S) + if self.lapse: + lam = inputs['p_lapse'][subject_ix][:, None] + p = (1 - lam) * p + lam / len(self.response_options) + p = pt.clip(p, 1e-10, 1.0) + return p / pt.sum(p, axis=1, keepdims=True) + + # ------------------------------------------------------------------ + # PyMC graph + # ------------------------------------------------------------------ + def build_estimation_model(self, data=None, coords=None, hierarchical=True, + save_p_choice=False, flat_prior=False, paradigm=None): + if data is None: + data = paradigm if paradigm is not None else self.paradigm + self.paradigm = data + if hierarchical and coords is None: + coords = {'subject': data.index.unique(level='subject')} + with pm.Model(coords=coords) as self.estimation_model: + paradigm_ = self._get_paradigm(paradigm=data) + self.set_paradigm(paradigm_) + self.build_priors(hierarchical=hierarchical, flat_prior=flat_prior) + self.build_likelihood(None, save_p_choice=save_p_choice) + + def build_likelihood(self, parameters, save_p_choice=False): + model = pm.Model.get_context() + inputs = self.get_model_inputs(parameters) + S = len(model.coords['subject']) if 'subject' in model.coords else 1 + p = self.trial_probabilities(inputs, model['n'], model['subject_ix'], S) + if save_p_choice: + p = pm.Deterministic('p_response', p) + pm.Categorical('response', p=p, observed=model['response_ix']) + + # ------------------------------------------------------------------ + # Prediction / simulation / PPC / recovery + # ------------------------------------------------------------------ + def _subjects(self, paradigm): + if 'subject' in paradigm.index.names: + subj = paradigm.index.get_level_values('subject') + elif 'subject' in paradigm.columns: + subj = paradigm['subject'].values + else: + subj = np.zeros(len(paradigm), dtype=int) + return pd.factorize(subj) + + def predict_response_distribution(self, paradigm, parameters): + """Per-trial probabilities over the response options (DataFrame). + + ``parameters``: DataFrame indexed by subject, or a dict of scalars. + """ + codes, uniques = self._subjects(paradigm) + if isinstance(parameters, pd.DataFrame): + pars = parameters.loc[list(uniques)] + arrs = {k: pars[k].values.astype(float) for k in self.free_parameters} + else: + arrs = {k: np.broadcast_to(np.atleast_1d(np.asarray(parameters[k], float)), + (len(uniques),)).copy() for k in self.free_parameters} + inputs = {k: pt.as_tensor_variable(v) for k, v in arrs.items()} + p = self.trial_probabilities(inputs, pt.as_tensor_variable(paradigm['n'].values.astype(float)), + pt.as_tensor_variable(codes), len(uniques)).eval() + return pd.DataFrame(p, index=paradigm.index, + columns=pd.Index(self.response_options.astype(int), name='response')) + + def predict(self, paradigm, parameters): + """Predicted mean and s.d. of the report per trial.""" + p = self.predict_response_distribution(paradigm, parameters).values + r = self.response_options + mean = p @ r + out = paradigm.copy() + out['predicted_mean'] = mean + out['predicted_sd'] = np.sqrt(np.maximum(p @ r ** 2 - mean ** 2, 0)) + return out + + def simulate(self, paradigm, parameters, n_samples=1, rng=None): + """Simulated integer reports (lapses and censoring included). + + Long DataFrame with a ``sample`` index level and ``simulated_response``. + """ + rng = np.random.default_rng(rng) + p = self.predict_response_distribution(paradigm, parameters).values + cdf = np.cumsum(p, axis=1) + u = rng.random((n_samples, len(p), 1)) + ix = np.minimum((u > cdf[None]).sum(-1), p.shape[1] - 1) + sim = self.response_options[ix].T + par = paradigm.drop(columns=['response'], errors='ignore') + out = pd.concat([par.assign(sample=k + 1, simulated_response=sim[:, k]) + for k in range(n_samples)]) + return out.set_index('sample', append=True) + + def posterior_predictive(self, idata=None, n_posterior_samples=200, random_seed=None): + """Simulated datasets (same trials as the fit), one per posterior draw. + + Long DataFrame: index = fitted paradigm's index + ``ppc_sample``, + column ``simulated_response``. + """ + import arviz as az + idata = self._get_idata(idata) + post = idata.posterior.stack(sample=('chain', 'draw')) + rng = np.random.default_rng(random_seed) + sel = rng.choice(post.sizes['sample'], size=min(n_posterior_samples, post.sizes['sample']), + replace=False) + thin = post.isel(sample=sel).drop_vars(['sample', 'chain', 'draw']) + thin = thin.assign_coords(sample=np.arange(len(sel))).rename(sample='draw') + thin = thin.expand_dims('chain').transpose('chain', 'draw', ...) + with self.estimation_model: + pp = pm.sample_posterior_predictive(az.InferenceData(posterior=thin), + var_names=['response'], + random_seed=random_seed, progressbar=False) + arr = pp.posterior_predictive['response'].values[0] + sim = self.response_options[arr].T + out = pd.DataFrame(sim, index=self.paradigm.index, + columns=pd.Index(np.arange(len(sel)), name='ppc_sample')) + return out.stack().rename('simulated_response').to_frame() + + ppc = posterior_predictive + + def parameter_recovery(self, paradigm, parameters, rng=None, **sample_kwargs): + """Simulate one dataset from ``parameters`` (DataFrame by subject) on + ``paradigm``'s trials, refit a fresh copy of this model hierarchically, + and return true vs recovered (posterior mean) parameters per subject.""" + sim = self.simulate(paradigm, parameters, n_samples=1, rng=rng) + data = sim.droplevel('sample').rename(columns={'simulated_response': 'response'}) + fit = EstimationTaskModel(data, encoding_space=self.encoding_space, prior=self.prior, + lapse=self.lapse, motor_noise=self.motor_noise, + response_range=self.response_range, n_ref=self.n_ref, + n_measurement_grid=self.n_measurement_grid, + n_hypothesis_grid=self.n_hypothesis_grid, + hypothesis_range=self.hypothesis_range) + fit.build_estimation_model(data, hierarchical=True) + idata = fit.sample(**sample_kwargs) + rec = pd.DataFrame({k: idata.posterior[k].mean(('chain', 'draw')).to_series() + for k in self.free_parameters}) + return pd.concat([parameters[list(self.free_parameters)], rec.loc[parameters.index]], + axis=1, keys=['true', 'recovered']), idata diff --git a/tests/test_estimation_task.py b/tests/test_estimation_task.py new file mode 100644 index 0000000..e8048c8 --- /dev/null +++ b/tests/test_estimation_task.py @@ -0,0 +1,146 @@ +"""Tests for ``bauer.models.EstimationTaskModel``. + +* builds + finite gradients for every component combination; +* the closed-form path (log space + log-normal prior) agrees with the grid path; +* a uniform prior compresses, more so with more noise; +* alpha -> 0 of the power space reproduces the log space; +* simulate -> fit -> recover (single-subject MAP; hierarchical NUTS, ``slow``). +""" +import itertools +import warnings + +import numpy as np +import pandas as pd +import pytest + +warnings.filterwarnings('ignore') + +from bauer.models import (EstimationTaskModel, PowerSpace, LogSpace, LinearSpace, # noqa: E402 + UniformPrior, GaussianPrior) + + +def make_paradigm(n_subjects=3, n_trials=120, seed=0): + rng = np.random.default_rng(seed) + rows = [{'subject': s, 'trial': t, 'n': int(rng.integers(5, 25)), + 'response': int(rng.integers(5, 26))} + for s in range(1, n_subjects + 1) for t in range(n_trials)] + return pd.DataFrame(rows).set_index(['subject', 'trial']) + + +def grid_paradigm(): + return pd.DataFrame({'subject': 1, 'n': np.arange(5, 25), 'response': 10}).set_index('subject') + + +SPACES = {'log': LogSpace, 'linear': LinearSpace, 'free': PowerSpace} +PRIORS = {'uniform': lambda: UniformPrior(4.5, 24.5), 'gaussian': GaussianPrior} + + +@pytest.mark.parametrize('space,prior,motor', itertools.product(SPACES, PRIORS, (False, True))) +def test_builds_and_finite_gradient(space, prior, motor): + par = make_paradigm() + m = EstimationTaskModel(par, encoding_space=SPACES[space](), prior=PRIORS[prior](), + motor_noise=motor, n_measurement_grid=80, n_hypothesis_grid=100) + m.build_estimation_model(par, hierarchical=True) + ip = m.estimation_model.initial_point() + assert np.isfinite(m.estimation_model.compile_logp()(ip)) + assert np.all(np.isfinite(m.estimation_model.compile_dlogp()(ip))) + expected = {'nu', 'p_lapse'} + if space == 'free': + expected.add('alpha') + if prior == 'gaussian': + expected |= {'prior_mu', 'prior_sd'} + if motor: + expected.add('sigma_r') + assert set(m.free_parameters) == expected + assert m.closed_form == (space == 'log' and prior == 'gaussian' and not motor) + + +@pytest.mark.parametrize('nu,mu,sd', [(0.3, 11.0, 0.4), (0.5, 14.0, 0.3), (0.2, 9.0, 0.8)]) +def test_closed_form_matches_grid(nu, mu, sd): + par = grid_paradigm() + pars = dict(nu=nu, prior_mu=mu, prior_sd=sd, p_lapse=0.02) + closed = EstimationTaskModel(par, encoding_space=LogSpace(), prior=GaussianPrior()) + assert closed.closed_form + grid = EstimationTaskModel(par, encoding_space=PowerSpace(alpha=1e-9), prior=GaussianPrior(), + n_measurement_grid=400, n_hypothesis_grid=600, + hypothesis_range=(0.5, 80.0)) + assert not grid.closed_form + pc = closed.predict_response_distribution(par, pars).values + pg = grid.predict_response_distribution(par, pars).values + np.testing.assert_allclose(pc, pg, atol=2e-3) + + +def test_power_space_alpha_to_zero_is_log(): + par = grid_paradigm() + pars = dict(nu=0.4, p_lapse=0.0) + p_log = EstimationTaskModel(par, encoding_space=LogSpace()).predict_response_distribution( + par, pars).values + p_pow = EstimationTaskModel(par, encoding_space=PowerSpace(1e-6)).predict_response_distribution( + par, pars).values + np.testing.assert_allclose(p_log, p_pow, atol=5e-4) # |alpha| floored at 1e-4 + # free alpha at 0 is the same thing + p_free = EstimationTaskModel(par, encoding_space=PowerSpace()).predict_response_distribution( + par, dict(pars, alpha=0.0)).values + np.testing.assert_allclose(p_log, p_free, atol=5e-4) + + +def test_uniform_prior_compresses(): + par = grid_paradigm() + slopes = [] + for nu in (0.15, 0.3, 0.5): + pred = EstimationTaskModel(par, lapse=False).predict(par, dict(nu=nu)) + slopes.append(np.polyfit(pred['n'], pred['predicted_mean'], 1)[0]) + assert 1.0 > slopes[0] > slopes[1] > slopes[2] > 0.2 + # the estimate stays inside the prior's support + pred = EstimationTaskModel(par, lapse=False).predict(par, dict(nu=0.5)) + assert pred['predicted_mean'].between(4.5, 24.5).all() + + +def test_linear_gaussian_prior_gives_flat_sd(): + """Linear space + Gaussian prior: constant report s.d. away from the scale ends.""" + par = grid_paradigm() + pred = EstimationTaskModel(par, encoding_space=LinearSpace(), prior=GaussianPrior(), + lapse=False).predict(par, dict(nu=0.35, prior_mu=14.0, prior_sd=0.4)) + mid = pred[(pred.n >= 9) & (pred.n <= 20)]['predicted_sd'] + assert mid.max() - mid.min() < 0.15 + + +def test_response_distribution_and_simulation(): + par = make_paradigm() + m = EstimationTaskModel(par, encoding_space=PowerSpace(), prior=GaussianPrior()) + pars = dict(nu=0.35, alpha=0.5, prior_mu=12.0, prior_sd=0.5, p_lapse=0.03) + p = m.predict_response_distribution(par, pars) + np.testing.assert_allclose(p.sum(1), 1.0, atol=1e-8) + sim = m.simulate(par, pars, n_samples=2, rng=0) + assert len(sim) == 2 * len(par) + assert sim['simulated_response'].between(5, 25).all() + + +@pytest.mark.parametrize('space', ['log', 'linear']) +def test_single_subject_map_recovery(space): + par = make_paradigm(n_subjects=1, n_trials=1500, seed=3).droplevel('subject') + truth = dict(nu=0.35, p_lapse=0.04) + gen = EstimationTaskModel(par, encoding_space=SPACES[space]()) + data = gen.simulate(par, truth, rng=4).droplevel('sample').rename( + columns={'simulated_response': 'response'}) + fit = EstimationTaskModel(data, encoding_space=SPACES[space]()) + fit.build_estimation_model(data, hierarchical=False) + est = fit.fit_map(progressbar=False) + assert est['nu'] == pytest.approx(truth['nu'], rel=0.1) + assert est['p_lapse'] == pytest.approx(truth['p_lapse'], abs=0.02) + + +@pytest.mark.slow +def test_hierarchical_nuts_recovery_free_alpha(): + par = make_paradigm(n_subjects=6, n_trials=400, seed=5) + rng = np.random.default_rng(6) + truth = pd.DataFrame({'nu': rng.uniform(0.2, 0.5, 6), 'alpha': rng.uniform(-0.2, 1.0, 6), + 'p_lapse': rng.uniform(0.01, 0.05, 6)}, + index=pd.Index(np.arange(1, 7), name='subject')) + m = EstimationTaskModel(par, encoding_space=PowerSpace(), n_measurement_grid=120, + n_hypothesis_grid=150) + table, idata = m.parameter_recovery(par, truth, rng=7, draws=300, tune=300, chains=2, + cores=1, target_accept=0.9, progressbar=False, + random_seed=1) + assert np.corrcoef(table['true']['nu'], table['recovered']['nu'])[0, 1] > 0.8 + assert np.corrcoef(table['true']['alpha'], table['recovered']['alpha'])[0, 1] > 0.6 diff --git a/tests/test_magnitude_estimation.py b/tests/test_magnitude_estimation.py deleted file mode 100644 index 6ffda32..0000000 --- a/tests/test_magnitude_estimation.py +++ /dev/null @@ -1,158 +0,0 @@ -"""Tests for ``bauer.magnitude_estimation.MagnitudeEstimationModel``. - -Build tests for every option, analytic sanity checks of the observer (the -response distribution is a proper distribution, censoring puts mass on the -scale ends, a uniform prior compresses), and simulate -> fit -> recover tests -on synthetic data (single-subject MAP; hierarchical NUTS marked ``slow``). -""" -import itertools -import warnings - -import numpy as np -import pandas as pd -import pytest - -warnings.filterwarnings('ignore') - -from bauer.magnitude_estimation import MagnitudeEstimationModel # noqa: E402 - - -def make_paradigm(n_subjects=3, n_trials=120, seed=0, response=True): - rng = np.random.default_rng(seed) - rows = [] - for s in range(1, n_subjects + 1): - for t in range(n_trials): - n, u = rng.integers(5, 25, size=2) - rows.append({'subject': s, 'trial': t, 'n': int(n), 'n_uncued': int(u), - 'response': int(rng.integers(5, 26)) if response else 5}) - return pd.DataFrame(rows).set_index(['subject', 'trial']) - - -@pytest.fixture -def paradigm(): - return make_paradigm() - - -OPTIONS = [ - dict(encoding=e, prior=p, readout=r) - for e, p, r in itertools.product(('weber', 'constant', 'flexible'), - ('true', 'fitted', 'empirical'), - ('mean', 'median')) -] + [dict(lapse=False), dict(leakage='mixture'), dict(leakage='average')] - - -@pytest.mark.parametrize('kwargs', OPTIONS) -def test_builds_and_finite_gradient(paradigm, kwargs): - m = MagnitudeEstimationModel(paradigm, n_measurement_grid=60, - n_hypothesis_grid=80, **kwargs) - m.build_estimation_model(paradigm, hierarchical=True) - model = m.estimation_model - assert 'response' in model.named_vars - ip = model.initial_point() - assert np.isfinite(model.compile_logp()(ip)) - assert np.all(np.isfinite(model.compile_dlogp()(ip))) - expected = {'nu', 'sigma_r'} - if kwargs.get('encoding') == 'flexible': - expected.add('nu_exponent') - if kwargs.get('prior') == 'fitted': - expected |= {'prior_mu', 'prior_sd'} - if kwargs.get('lapse', True): - expected.add('p_lapse') - if kwargs.get('leakage'): - expected.add('leak') - assert set(m.free_parameters) == expected - - -def _pars(**kw): - base = dict(nu=0.35, sigma_r=1.5, p_lapse=0.03) - base.update(kw) - return base - - -def test_response_distribution_is_normalised(paradigm): - m = MagnitudeEstimationModel(paradigm, leakage='average') - p = m.predict_response_distribution(paradigm, _pars(leak=0.1)) - np.testing.assert_allclose(p.sum(1), 1.0, atol=1e-8) - assert (p.values >= 0).all() - - -def test_censoring_puts_mass_on_scale_ends(): - """With large motor noise the end options carry the censored tails.""" - par = pd.DataFrame({'subject': 1, 'n': [5, 24], 'response': [5, 25]}).set_index('subject') - m = MagnitudeEstimationModel(par, lapse=False) - p = m.predict_response_distribution(par, dict(nu=0.1, sigma_r=4.0)).values - assert p[0, 0] > 0.3 # n = 5: much of the mass at the bottom option - assert p[1, -1] > p[1, -2] # n = 24: top option collects the upper tail - - -def test_uniform_prior_compresses_and_noise_scales_compression(): - par = pd.DataFrame({'subject': 1, 'n': np.arange(5, 25), 'response': 10}).set_index('subject') - slopes = [] - for nu in (0.15, 0.3, 0.5): - m = MagnitudeEstimationModel(par, lapse=False) - pred = m.predict(par, dict(nu=nu, sigma_r=1.0)) - slopes.append(np.polyfit(pred['n'], pred['predicted_mean'], 1)[0]) - assert slopes[0] > slopes[1] > slopes[2] - assert slopes[0] < 1.0 - - -def test_median_and_mean_readouts_differ_under_weber(): - par = pd.DataFrame({'subject': 1, 'n': np.arange(5, 25), 'response': 10}).set_index('subject') - p_mean = MagnitudeEstimationModel(par, readout='mean', lapse=False).predict( - par, dict(nu=0.4, sigma_r=1.0))['predicted_mean'] - p_med = MagnitudeEstimationModel(par, readout='median', lapse=False).predict( - par, dict(nu=0.4, sigma_r=1.0))['predicted_mean'] - assert np.abs(p_mean - p_med).max() > 0.05 - - -def test_mixture_leak_shifts_report_towards_uncued(): - par = pd.DataFrame({'subject': 1, 'n': [10] * 2, 'n_uncued': [6, 22], - 'response': 10}).set_index('subject') - m = MagnitudeEstimationModel(par, leakage='mixture') - pred = m.predict(par, _pars(leak=0.2))['predicted_mean'].values - assert pred[1] > pred[0] + 1.0 - - -def test_simulate_shapes_and_support(paradigm): - m = MagnitudeEstimationModel(paradigm) - sim = m.simulate(paradigm, _pars(), n_samples=3, rng=0) - assert len(sim) == 3 * len(paradigm) - assert sim['simulated_response'].between(5, 25).all() - assert 'response' not in sim.columns - - -@pytest.mark.parametrize('encoding,truth', [ - ('weber', dict(nu=0.35, sigma_r=1.5, p_lapse=0.04)), - ('constant', dict(nu=5.0, sigma_r=1.5, p_lapse=0.04)), -]) -def test_single_subject_map_recovery(encoding, truth): - par = make_paradigm(n_subjects=1, n_trials=1500, seed=3).droplevel('subject') - gen = MagnitudeEstimationModel(par, encoding=encoding) - sim = gen.simulate(par, truth, n_samples=1, rng=4) - data = sim.droplevel('sample').rename(columns={'simulated_response': 'response'}) - fit = MagnitudeEstimationModel(data, encoding=encoding) - fit.build_estimation_model(data, hierarchical=False) - est = fit.fit_map(progressbar=False) - assert est['nu'] == pytest.approx(truth['nu'], rel=0.15) - assert est['sigma_r'] == pytest.approx(truth['sigma_r'], rel=0.3) - assert est['p_lapse'] == pytest.approx(truth['p_lapse'], abs=0.025) - - -@pytest.mark.slow -def test_hierarchical_nuts_recovery(): - par = make_paradigm(n_subjects=5, n_trials=400, seed=5) - rng = np.random.default_rng(6) - truth = pd.DataFrame({'nu': rng.uniform(0.2, 0.5, 5), - 'sigma_r': rng.uniform(1.0, 2.0, 5), - 'p_lapse': rng.uniform(0.01, 0.05, 5)}, - index=pd.Index(np.arange(1, 6), name='subject')) - gen = MagnitudeEstimationModel(par) - sim = gen.simulate(par, truth, n_samples=1, rng=7) - data = sim.droplevel('sample').rename(columns={'simulated_response': 'response'}) - fit = MagnitudeEstimationModel(data, n_measurement_grid=100, n_hypothesis_grid=150) - fit.build_estimation_model(data, hierarchical=True) - idata = fit.sample(draws=300, tune=300, chains=2, cores=1, target_accept=0.9, - progressbar=False, random_seed=1) - est = idata.posterior['nu'].mean(('chain', 'draw')).values - assert np.corrcoef(est, truth['nu'].values)[0, 1] > 0.8 - np.testing.assert_allclose(est, truth['nu'].values, atol=0.08) From cb252a4a1a948fd85c78c037e1c67d2716ec330f Mon Sep 17 00:00:00 2001 From: Gilles de Hollander Date: Sun, 25 Oct 2026 14:51:11 +0100 Subject: [PATCH 03/20] EstimationTaskModel: subject-level covariates on a parameter's group mean; CHANGELOG Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 37 ++++++++++++++++++------------- bauer/models/estimation_task.py | 39 ++++++++++++++++++++++++++++++++- tests/test_estimation_task.py | 11 ++++++++++ 3 files changed, 71 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7a2fd0e..f532c46 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,21 +6,28 @@ follows [Keep a Changelog](https://keepachangelog.com/) and semantic versioning. ## Unreleased (branch `estimation-model`) ### Added -- `bauer.magnitude_estimation.MagnitudeEstimationModel`: hierarchical Bayesian - observer for magnitude estimation on a bounded, discrete (integer) response - scale. Options: Weber (log-normal), constant or power-law (`flexible`) - encoding noise; true (uniform), fitted (Gaussian / log-normal) or per-subject - empirical prior; posterior-mean or posterior-median readout; motor noise - discretised and censored at the scale ends; free per-subject lapse rate; and - optional leakage of a second, uncued magnitude (`mixture` = swap, - `average` = weighted report). The likelihood is an observed - `pm.Categorical`, so `pm.compute_log_likelihood` (LOO) and - `pm.sample_posterior_predictive` (simulated datasets) work directly. - `predict`, `predict_response_distribution`, `simulate` and `ppc` return - integer responses with lapses, censoring and leakage included. -- `tests/test_magnitude_estimation.py`: build/gradient tests for every option, - analytic checks, single-subject MAP recovery and a hierarchical NUTS - recovery test (`slow`). +- `bauer.models.EstimationTaskModel`: hierarchical Bayesian observer for + magnitude estimation on a bounded, discrete (integer) response scale, built + from a few components: + - encoding space `PowerSpace(alpha)` (Box-Cox; `alpha=None` = free, + hierarchical), with `LogSpace()` (Weber) and `LinearSpace()` (constant + noise) as fixed ends; efficient coding for a power-law prior is the same + family (documented); + - prior `UniformPrior(lo, hi)` (e.g. the task range) or `GaussianPrior()` + (Gaussian in the encoding space; log-normal for log space); + - posterior-mean readout, rounded and censored to the response scale; + uniform lapse (default on); optional Gaussian motor noise; + - optional subject-level covariates on a parameter's group mean + (`covariates={'nu': column}`). + Closed-form likelihood for log space + log-normal prior, otherwise an exact + grid path (n_hat(m) inverted at the response-option edges). Observed + `pm.Categorical` likelihood: LOO and posterior-predictive draws come from + PyMC directly. `simulate`, `predict`, `posterior_predictive`, + `parameter_recovery`. +- `tests/test_estimation_task.py`: every component combination builds with + finite gradients, closed form = grid, alpha -> 0 = log, uniform-prior + compression, flat s.d. for linear + Gaussian, MAP and hierarchical NUTS + recovery (incl. free alpha), covariates. ## 0.5.0 (2026-10-18) diff --git a/bauer/models/estimation_task.py b/bauer/models/estimation_task.py index 927bb80..5f8a5e7 100644 --- a/bauer/models/estimation_task.py +++ b/bauer/models/estimation_task.py @@ -203,7 +203,8 @@ class EstimationTaskModel(EstimationBaseModel): def __init__(self, paradigm=None, encoding_space=None, prior=None, lapse=True, motor_noise=False, response_range=(5, 25), n_ref=12.0, n_measurement_grid=200, n_hypothesis_grid=246, - hypothesis_range=(1.0, 50.0), **kwargs): + hypothesis_range=(1.0, 50.0), covariates=None, **kwargs): + self.covariates = dict(covariates or {}) self.encoding_space = encoding_space if encoding_space is not None else LogSpace() self.prior = prior if prior is not None else UniformPrior(4.5, 24.5) self.lapse = lapse @@ -244,6 +245,42 @@ def get_free_parameters(self): def get_model_inputs(self, parameters): return {key: self.subjectwise(key) for key in self.free_parameters} + def build_hierarchical_nodes(self, name, mu_intercept=None, sigma_intercept=None, + cauchy_sigma_intercept=None, transform='identity', **kwargs): + """Hierarchical node, optionally with a subject-level covariate. + + With ``covariates={name: column}`` the participant values of ``name`` + (on the untransformed scale) are ``mu + beta * z_s + sd * offset_s``, + where ``z_s`` is the (standardised) column, constant within subject. + The slope is ``{name}_{column}``, prior N(0, sigma_intercept). + """ + if name not in self.covariates: + return super().build_hierarchical_nodes( + name, mu_intercept=mu_intercept, sigma_intercept=sigma_intercept, + cauchy_sigma_intercept=cauchy_sigma_intercept, transform=transform, **kwargs) + if transform not in ('identity', 'softplus'): + raise NotImplementedError('covariates only for identity / softplus parameters') + from ..core import _group_sd_rv + col = self.covariates[name] + data = self.paradigm + z = pd.Series(data[col].values, index=data.index.get_level_values('subject')) + z = z.groupby(level=0, sort=False).first() + model = pm.Model.get_context() + z = z.loc[list(model.coords['subject'])].values.astype(float) + mu_name = f'{name}_mu' if transform == 'identity' else f'{name}_mu_untransformed' + group_mu = pm.Normal(mu_name, mu=mu_intercept, sigma=sigma_intercept) + if transform == 'softplus': + pm.Deterministic(f'{name}_mu', pt.softplus(group_mu)) + beta = pm.Normal(f'{name}_{col}', mu=0.0, sigma=sigma_intercept) + group_sd = _group_sd_rv(f'{name}_sd', cauchy_sigma_intercept, + getattr(self, 'group_sd_dist', 'halfnormal')) + offset = pm.Normal(f'{name}_offset', 0.0, 1.0, dims=('subject',)) + x = group_mu + beta * z + group_sd * offset + if transform == 'identity': + return pm.Deterministic(name, x, dims=('subject',)) + pm.Deterministic(f'{name}_untransformed', x, dims=('subject',)) + return pm.Deterministic(name, pt.softplus(x), dims=('subject',)) + # ------------------------------------------------------------------ def _setup_grids(self, paradigm=None): rlo, rhi = self.response_range diff --git a/tests/test_estimation_task.py b/tests/test_estimation_task.py index e8048c8..afa1356 100644 --- a/tests/test_estimation_task.py +++ b/tests/test_estimation_task.py @@ -144,3 +144,14 @@ def test_hierarchical_nuts_recovery_free_alpha(): random_seed=1) assert np.corrcoef(table['true']['nu'], table['recovered']['nu'])[0, 1] > 0.8 assert np.corrcoef(table['true']['alpha'], table['recovered']['alpha'])[0, 1] > 0.6 + + +def test_subject_covariate_on_noise(): + par = make_paradigm() + z = {1: -1.0, 2: 0.0, 3: 1.0} + par['z'] = [z[s] for s in par.index.get_level_values('subject')] + m = EstimationTaskModel(par, covariates={'nu': 'z'}) + m.build_estimation_model(par, hierarchical=True) + assert 'nu_z' in m.estimation_model.named_vars + ip = m.estimation_model.initial_point() + assert np.all(np.isfinite(m.estimation_model.compile_dlogp()(ip))) From a8b1b404f041bba940f906d27dbc58fd5ac43d5f Mon Sep 17 00:00:00 2001 From: Gilles de Hollander Date: Sun, 25 Oct 2026 14:52:56 +0100 Subject: [PATCH 04/20] docs: EstimationTaskModel page (components, quick start, likelihood paths, efficient-coding equivalence) Co-Authored-By: Claude Opus 5.5 --- docs/estimation_task.rst | 73 ++++++++++++++++++++++++++++++++++++++++ docs/index.rst | 1 + 2 files changed, 74 insertions(+) create mode 100644 docs/estimation_task.rst diff --git a/docs/estimation_task.rst b/docs/estimation_task.rst new file mode 100644 index 0000000..6fc74e9 --- /dev/null +++ b/docs/estimation_task.rst @@ -0,0 +1,73 @@ +Estimation tasks (continuous reports) +===================================== + +``bauer.models.EstimationTaskModel`` is a hierarchical Bayesian observer for +tasks in which a participant sees a magnitude ``n`` and *reports* it on a +bounded scale (a slider, a typed number). It is built from three components. + +================= =========================================================== +Component Options +================= =========================================================== +Encoding space ``LogSpace()`` (Weber), ``LinearSpace()`` (constant noise), + ``PowerSpace()`` (Box-Cox exponent ``alpha`` fitted per + participant; ``PowerSpace(a)`` fixes it) +Prior ``UniformPrior(lo, hi)`` (e.g. the task's range) or + ``GaussianPrior()`` (Gaussian in the encoding space: + log-normal for log space; centre and width fitted) +Lapse uniform over the response options (``lapse=True``) +================= =========================================================== + +The readout is the posterior mean of ``n``. It is rounded to the response +options and censored at the scale ends (``response_range``). The free noise +``nu`` is expressed in log units at ``n_ref`` (a Weber fraction) for every +encoding space. + +Quick start +----------- + +.. code-block:: python + + from bauer.models import EstimationTaskModel, LogSpace, UniformPrior + + # data: columns n (presented) and response (integer), index level 'subject' + model = EstimationTaskModel(data, encoding_space=LogSpace(), + prior=UniformPrior(4.5, 24.5), response_range=(5, 25)) + model.build_estimation_model(data) + idata = model.sample(draws=1500, tune=1500, target_accept=0.95) + + ppc = model.posterior_predictive(idata, n_posterior_samples=200) # simulated datasets + sim = model.simulate(data, parameters_by_subject) # synthetic data + table, _ = model.parameter_recovery(data, parameters_by_subject) # simulate -> refit + +Because the likelihood is an observed ``pm.Categorical`` over the response +options, ``pm.compute_log_likelihood(idata, model=model.estimation_model)`` +gives pointwise log-likelihoods for ``az.loo`` / ``az.compare``. Subject-level +covariates on a parameter's group mean: ``covariates={'nu': 'column'}``. + +How the likelihood is computed +------------------------------ + +*Closed form* (log space + Gaussian prior, i.e. log-normal): the posterior +over ``log n`` is Gaussian, the posterior-mean estimate is log-normal in ``n``, +and the probability of each response option is a difference of normal CDFs. + +*Grid* (all other combinations, e.g. the uniform prior or a free ``alpha``): +for every participant the estimate ``n_hat(m)`` is computed on a measurement +grid (posterior mean over a hypothesis grid) and inverted at the edges of the +response options. Because ``n_hat`` is monotone in ``m``, the probability of +each option is again a difference of normal CDFs of the measurement. This is +exact up to linear interpolation, and smooth in the parameters, so NUTS gets +usable gradients. The two paths agree to < 2e-3 per option probability (tested). + +Efficient coding and power spaces +--------------------------------- + +An efficient (infomax) encoder for a stimulus density ``p_enc`` uses the CDF of +``p_enc`` as its internal space, with constant noise there (Wei & Stocker, +2015). For a power-law density ``p_enc ~ n^-kappa`` that is ``PowerSpace`` with +``alpha = 1 - kappa``. So the log space is efficient for a ``1/n`` ("natural") +prior, and the linear space is efficient for a uniform prior. A fitted +``alpha`` can be read as the exponent of the stimulus statistics the encoding is +adapted to. It is related to, but not the same as, Stevens' exponent of the +*reports*: the Bayesian readout undoes most of the transform and adds +compression toward the prior. diff --git a/docs/index.rst b/docs/index.rst index 55b4341..305a0e0 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -42,6 +42,7 @@ Quick start installation concepts + estimation_task .. toctree:: :maxdepth: 2 From 95f1ca9c0f4197ff3323e2ae7f5b922812f03625 Mon Sep 17 00:00:00 2001 From: Gilles de Hollander Date: Sun, 25 Oct 2026 15:14:10 +0100 Subject: [PATCH 05/20] EstimationTaskModel docstring: motor noise is recoverable alongside encoding noise (r > .93 in a 19 x 500 recovery) Co-Authored-By: Claude Opus 5.5 --- bauer/models/estimation_task.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/bauer/models/estimation_task.py b/bauer/models/estimation_task.py index 5f8a5e7..1ef388c 100644 --- a/bauer/models/estimation_task.py +++ b/bauer/models/estimation_task.py @@ -44,12 +44,13 @@ **Readout** is the posterior mean of ``n`` (in items); the estimate is reported directly, rounded to the nearest response option and censored at the scale -ends. There is no separate motor noise by default (``motor_noise=False``): in a -Bayesian observer the encoding noise already sets both the compression and the -report scatter, and on the round-1 retinonumeral data an extra Gaussian motor -noise was not separately recoverable from the encoding noise (see -``tests/test_estimation_task.py``). ``motor_noise=True`` adds a Gaussian -``sigma_r`` (items) for users who want it. +ends. ``motor_noise=True`` adds Gaussian response noise ``sigma_r`` (items) +around the estimate before rounding. It is separable from the encoding noise +because the encoding noise also sets the compression (through the prior) and +motor noise does not: on a 19-participant, ~500-trial-per-participant design +with a uniform prior, both recovered at r > .93. With ``motor_noise=False`` the +encoding noise alone sets the scatter, and the closed-form path is available +for log space + log-normal prior. Likelihood -- two paths, chosen automatically ---------------------------------------------- From 0ccf2d4c9b6f8ee342623f88742bcbd17d504638 Mon Sep 17 00:00:00 2001 From: Gilles de Hollander Date: Mon, 26 Oct 2026 12:24:03 +0100 Subject: [PATCH 06/20] EstimationTaskModel: grid likelihood per unique magnitude, gathered per trial The motor-noise integral was a per-trial (T, M, R) tensor: 0.75 s per gradient on 9,928 trials, so the hierarchical fits timed out at 12 h. Computing the (S, K, R) option table per participant x unique magnitude (a batched matmul) gives identical log-probabilities at 0.04 s per gradient (19x faster). Co-Authored-By: Claude Opus 5.5 --- bauer/models/estimation_task.py | 45 +++++++++++++++++++++++---------- 1 file changed, 32 insertions(+), 13 deletions(-) diff --git a/bauer/models/estimation_task.py b/bauer/models/estimation_task.py index 1ef388c..c405841 100644 --- a/bauer/models/estimation_task.py +++ b/bauer/models/estimation_task.py @@ -313,6 +313,8 @@ def _get_paradigm(self, paradigm=None, subject_mapping=None): else: paradigm_['subject_ix'] = np.zeros(len(paradigm), dtype=int) paradigm_['n'] = paradigm['n'].values.astype(float) + # grid path works per unique magnitude (the graph captures n_unique at build) + self.n_unique, paradigm_['n_ix'] = np.unique(paradigm_['n'], return_inverse=True) if 'response' in paradigm.columns: r = paradigm['response'].values.astype(float) if np.any(np.isnan(r)): @@ -400,29 +402,42 @@ def _invert(self, m, n_hat, values): out = pt.switch(pt.eq(below, M), m[:, -1:] + 1e3, out) return out # (S, V) - def _option_probs_grid(self, inputs, n, subject_ix, S): + def _option_table_grid(self, inputs, n_unique, S): + """(S, K, R) option probabilities for every participant x unique magnitude. + + Computed per unique presented magnitude (K values), not per trial, and + gathered afterwards: the motor-noise integral over the measurement grid is + then an (S, K, M) x (S, M, R) batched matmul instead of a per-trial + (T, M, R) tensor (which made the motor-noise fits ~50x slower). + """ m, n_hat, alpha, nu_f = self.estimate_on_grid(inputs, S) - fn = self.encoding_space.transform(n, alpha[subject_ix]) # (T,) - nu_t = nu_f[subject_ix] + nk = pt.as_tensor_variable(np.asarray(n_unique, dtype=float)) + fn = self._f(nk, alpha) # (S, K) if not self.motor_noise: m_edges = self._invert(m, n_hat, self.response_edges) # (S, R+1) - z = (m_edges[subject_ix] - fn[:, None]) / nu_t[:, None] + z = (m_edges[:, None, :] - fn[:, :, None]) / nu_f[:, None, None] cdf = _norm_cdf(z) - return cdf[:, 1:] - cdf[:, :-1] + return cdf[:, :, 1:] - cdf[:, :, :-1] # motor noise: integrate the measurement density over the grid - dens = pt.exp(-0.5 * ((m[subject_ix] - fn[:, None]) / nu_t[:, None]) ** 2) - dens = dens / pt.sum(dens, axis=1, keepdims=True) # (T, M) + dens = pt.exp(-0.5 * ((m[:, None, :] - fn[:, :, None]) / nu_f[:, None, None]) ** 2) + dens = dens / pt.sum(dens, axis=2, keepdims=True) # (S, K, M) edges = pt.as_tensor_variable(self.response_edges) sig = inputs['sigma_r'][:, None, None] cdf = _norm_cdf((edges[None, None, :] - n_hat[:, :, None]) / sig) # (S, M, R+1) kern = cdf[:, :, 1:] - cdf[:, :, :-1] # (S, M, R) - return pt.sum(dens[:, :, None] * kern[subject_ix], axis=1) + return pt.batched_dot(dens, kern) # (S, K, R) - def trial_probabilities(self, inputs, n, subject_ix, S): + def trial_probabilities(self, inputs, n, subject_ix, S, n_ix=None, n_unique=None): + """Per-trial option probabilities (T, R). + + Grid path: pass ``n_ix`` (index of each trial's magnitude into + ``n_unique``); the table is computed per unique magnitude. + """ if self.closed_form: p = self._option_probs_closed(inputs, n, subject_ix) else: - p = self._option_probs_grid(inputs, n, subject_ix, S) + table = self._option_table_grid(inputs, n_unique, S) + p = table[subject_ix, n_ix] if self.lapse: lam = inputs['p_lapse'][subject_ix][:, None] p = (1 - lam) * p + lam / len(self.response_options) @@ -449,7 +464,8 @@ def build_likelihood(self, parameters, save_p_choice=False): model = pm.Model.get_context() inputs = self.get_model_inputs(parameters) S = len(model.coords['subject']) if 'subject' in model.coords else 1 - p = self.trial_probabilities(inputs, model['n'], model['subject_ix'], S) + p = self.trial_probabilities(inputs, model['n'], model['subject_ix'], S, + n_ix=model['n_ix'], n_unique=self.n_unique) if save_p_choice: p = pm.Deterministic('p_response', p) pm.Categorical('response', p=p, observed=model['response_ix']) @@ -479,8 +495,11 @@ def predict_response_distribution(self, paradigm, parameters): arrs = {k: np.broadcast_to(np.atleast_1d(np.asarray(parameters[k], float)), (len(uniques),)).copy() for k in self.free_parameters} inputs = {k: pt.as_tensor_variable(v) for k, v in arrs.items()} - p = self.trial_probabilities(inputs, pt.as_tensor_variable(paradigm['n'].values.astype(float)), - pt.as_tensor_variable(codes), len(uniques)).eval() + n = paradigm['n'].values.astype(float) + n_unique, n_ix = np.unique(n, return_inverse=True) + p = self.trial_probabilities(inputs, pt.as_tensor_variable(n), pt.as_tensor_variable(codes), + len(uniques), n_ix=pt.as_tensor_variable(n_ix), + n_unique=n_unique).eval() return pd.DataFrame(p, index=paradigm.index, columns=pd.Index(self.response_options.astype(int), name='response')) From 800a9363e0843f5190823f550dd22934f803cdd9 Mon Sep 17 00:00:00 2001 From: Gilles de Hollander Date: Mon, 26 Oct 2026 12:46:50 +0100 Subject: [PATCH 07/20] EstimationTaskModel: TruncatedGaussianPrior (discrete integers by default, or continuous) and discrete UniformPrior The fitted Gaussian prior had support on the whole hypothesis grid (1..50), so the observer did not know the task's bounds. TruncatedGaussianPrior(lo, hi) restricts it to the task range; discrete=True puts the mass on the integers lo..hi only (weights = the prior's density in n at each integer). UniformPrior(lo, hi, discrete=True) likewise. The measurement grid no longer depends on the hypothesis grid. Tests: narrow truncated = untruncated Gaussian; very wide truncated = uniform in f_alpha space (= UniformPrior for the linear space). Discrete vs continuous truncation differ by <= .002 in any option probability at the fitted group parameters. Co-Authored-By: Claude Opus 5.5 --- bauer/models/__init__.py | 2 +- bauer/models/estimation_task.py | 80 +++++++++++++++++++++++++-------- tests/test_estimation_task.py | 32 +++++++++++-- 3 files changed, 91 insertions(+), 23 deletions(-) diff --git a/bauer/models/__init__.py b/bauer/models/__init__.py index b86191d..86c46ab 100644 --- a/bauer/models/__init__.py +++ b/bauer/models/__init__.py @@ -68,5 +68,5 @@ from .estimation_task import ( EstimationTaskModel, PowerSpace, LogSpace, LinearSpace, - UniformPrior, GaussianPrior, LogNormalPrior, + UniformPrior, GaussianPrior, LogNormalPrior, TruncatedGaussianPrior, ) diff --git a/bauer/models/estimation_task.py b/bauer/models/estimation_task.py index c405841..d1ac6af 100644 --- a/bauer/models/estimation_task.py +++ b/bauer/models/estimation_task.py @@ -150,28 +150,59 @@ def LinearSpace(): class UniformPrior: - """Uniform prior on [lo, hi] (items); no free parameters.""" + """Uniform prior on [lo, hi] (items); no free parameters. + + ``discrete=True``: equal mass on the integers lo, lo + 1, ..., hi (the + observer believes only in the magnitudes that can occur, e.g. + ``UniformPrior(5, 24, discrete=True)``). Otherwise a continuous uniform + density on [lo, hi] (for integers 5..24 use ``UniformPrior(4.5, 24.5)``). + """ free_parameters = () + truncated = True - def __init__(self, lo, hi): - self.lo, self.hi = float(lo), float(hi) + def __init__(self, lo, hi, discrete=False): + self.lo, self.hi, self.discrete = float(lo), float(hi), bool(discrete) def __repr__(self): - return f'UniformPrior({self.lo}, {self.hi})' + return f'UniformPrior({self.lo}, {self.hi}, discrete={self.discrete})' class GaussianPrior: """Gaussian prior in the encoding space (log-normal for log space). Free parameters: ``prior_mu`` (centre, items) and ``prior_sd`` (width in - log units at the centre). + log units at the centre). Its support is the whole hypothesis grid + (``hypothesis_range``), so it does not know the task's bounds. """ free_parameters = ('prior_mu', 'prior_sd') + truncated = False + discrete = False def __repr__(self): return 'GaussianPrior()' +class TruncatedGaussianPrior(GaussianPrior): + """``GaussianPrior`` restricted to [lo, hi] (the bounds participants know). + + ``discrete=True`` (default): mass only on the integers lo..hi, with weights + proportional to the prior's density in n at each integer, + ``N(f(k); mu_f, sd_f) * f'(k)`` (the same density-in-n convention as the + continuous prior, evaluated at the integers). ``discrete=False``: the + continuous density with the mass outside [lo, hi] zeroed (e.g. lo = 4.5, + hi = 24.5). A narrow prior centred mid-range reproduces ``GaussianPrior``. + A very wide one becomes uniform in the encoding space: ``UniformPrior`` + with the same support for the linear space, a 1/n prior for the log space. + """ + truncated = True + + def __init__(self, lo, hi, discrete=True): + self.lo, self.hi, self.discrete = float(lo), float(hi), bool(discrete) + + def __repr__(self): + return f'TruncatedGaussianPrior({self.lo}, {self.hi}, discrete={self.discrete})' + + # Alias in the spirit of the docs (log-normal when the space is log) LogNormalPrior = GaussianPrior @@ -221,7 +252,7 @@ def __init__(self, paradigm=None, encoding_space=None, prior=None, lapse=True, @property def closed_form(self): """True when the likelihood is computed analytically (no grid).""" - return (self.encoding_space.is_log and isinstance(self.prior, GaussianPrior) + return (self.encoding_space.is_log and type(self.prior) is GaussianPrior and not self.motor_noise) # ------------------------------------------------------------------ @@ -290,16 +321,25 @@ def _setup_grids(self, paradigm=None): self.response_edges = np.concatenate( [[1e-3], self.response_options[:-1] + 0.5, [1e4]]) h0, h1 = self.hypothesis_range - self.hyp_grid = np.linspace(h0, h1, self.n_hypothesis_grid) - self.d_hyp = self.hyp_grid[1] - self.hyp_grid[0] - # measurement grid in units of the hypothesis range in f-space + self.meas_range = (h0, h1) # the measurement grid always spans f(h0)..f(h1) + if getattr(self.prior, 'discrete', False): + # the observer believes only in the integers lo..hi + self.hyp_grid = np.arange(self.prior.lo, self.prior.hi + 1, dtype=float) + self.d_hyp = 1.0 + self.prior_mask = np.ones_like(self.hyp_grid) + else: + self.hyp_grid = np.linspace(h0, h1, self.n_hypothesis_grid) + self.d_hyp = self.hyp_grid[1] - self.hyp_grid[0] + if getattr(self.prior, 'truncated', False): + a, b = self.prior.lo, self.prior.hi + left = np.clip(self.hyp_grid - self.d_hyp / 2, a, b) + right = np.clip(self.hyp_grid + self.d_hyp / 2, a, b) + self.prior_mask = (right - left) / self.d_hyp # fraction of each cell inside + else: + self.prior_mask = np.ones_like(self.hyp_grid) + self.prior_mask = self.prior_mask / self.prior_mask.sum() + # measurement grid in units of f(h1) - f(h0) self.meas_t = np.linspace(-0.5, 1.5, self.n_measurement_grid) - if isinstance(self.prior, UniformPrior): - a, b = self.prior.lo, self.prior.hi - left = np.clip(self.hyp_grid - self.d_hyp / 2, a, b) - right = np.clip(self.hyp_grid + self.d_hyp / 2, a, b) - w = right - left - self.uniform_prior_mass = w / w.sum() def _get_paradigm(self, paradigm=None, subject_mapping=None): if paradigm is None: @@ -359,18 +399,20 @@ def estimate_on_grid(self, inputs, S): nu_f = self._nu_f(inputs, alpha) h = pt.as_tensor_variable(self.hyp_grid) fh = self._f(h, alpha) # (S, H) - lo = fh[:, 0][:, None] - hi = fh[:, -1][:, None] + f_ends = self._f(pt.as_tensor_variable(np.array(self.meas_range)), alpha) # (S, 2) + lo = f_ends[:, :1] + hi = f_ends[:, 1:] m = lo + pt.as_tensor_variable(self.meas_t)[None, :] * (hi - lo) # (S, M) loglik = -0.5 * ((m[:, :, None] - fh[:, None, :]) / nu_f[:, None, None]) ** 2 + logmask = pt.log(pt.as_tensor_variable(self.prior_mask) + 1e-300)[None, :] if isinstance(self.prior, UniformPrior): - logprior = pt.log(pt.as_tensor_variable(self.uniform_prior_mass) + 1e-300)[None, :] + logprior = logmask else: mu_f = self.encoding_space.transform(inputs['prior_mu'], alpha) # (S,) sd_f = inputs['prior_sd'] * inputs['prior_mu'] ** alpha # density in n: N(f(h); mu_f, sd_f) * f'(h), f'(h) = h^(alpha - 1) logprior = (-0.5 * ((fh - mu_f[:, None]) / sd_f[:, None]) ** 2 - + (alpha[:, None] - 1) * pt.log(h)[None, :]) + + (alpha[:, None] - 1) * pt.log(h)[None, :]) + logmask logpost = loglik + logprior[:, None, :] logpost = logpost - pt.max(logpost, axis=2, keepdims=True) post = pt.exp(logpost) diff --git a/tests/test_estimation_task.py b/tests/test_estimation_task.py index afa1356..243bfa7 100644 --- a/tests/test_estimation_task.py +++ b/tests/test_estimation_task.py @@ -16,7 +16,7 @@ warnings.filterwarnings('ignore') from bauer.models import (EstimationTaskModel, PowerSpace, LogSpace, LinearSpace, # noqa: E402 - UniformPrior, GaussianPrior) + UniformPrior, GaussianPrior, TruncatedGaussianPrior) def make_paradigm(n_subjects=3, n_trials=120, seed=0): @@ -32,7 +32,8 @@ def grid_paradigm(): SPACES = {'log': LogSpace, 'linear': LinearSpace, 'free': PowerSpace} -PRIORS = {'uniform': lambda: UniformPrior(4.5, 24.5), 'gaussian': GaussianPrior} +PRIORS = {'uniform': lambda: UniformPrior(4.5, 24.5), 'gaussian': GaussianPrior, + 'truncated': lambda: TruncatedGaussianPrior(5, 24)} @pytest.mark.parametrize('space,prior,motor', itertools.product(SPACES, PRIORS, (False, True))) @@ -47,7 +48,7 @@ def test_builds_and_finite_gradient(space, prior, motor): expected = {'nu', 'p_lapse'} if space == 'free': expected.add('alpha') - if prior == 'gaussian': + if prior in ('gaussian', 'truncated'): expected |= {'prior_mu', 'prior_sd'} if motor: expected.add('sigma_r') @@ -155,3 +156,28 @@ def test_subject_covariate_on_noise(): assert 'nu_z' in m.estimation_model.named_vars ip = m.estimation_model.initial_point() assert np.all(np.isfinite(m.estimation_model.compile_dlogp()(ip))) + + +@pytest.mark.parametrize('space', ['log', 'linear']) +def test_truncated_prior_limits(space): + """Narrow and mid-range = the untruncated Gaussian (both spaces). Very wide = + uniform in f_alpha space, which is uniform in n only for the linear space + (in log space it tends to a 1/n prior), so that limit is checked for linear.""" + par = grid_paradigm() + sp = SPACES[space] + base = dict(nu=0.3, p_lapse=0.0) + wide = dict(base, prior_mu=14.0, prior_sd=50.0) + for discrete, uni in (((True, UniformPrior(5, 24, discrete=True)), + (False, UniformPrior(4.5, 24.5))) if space == 'linear' else ()): + lo, hi = (5, 24) if discrete else (4.5, 24.5) + p_tr = EstimationTaskModel(par, encoding_space=sp(), prior=TruncatedGaussianPrior( + lo, hi, discrete=discrete), lapse=False).predict_response_distribution(par, wide).values + p_un = EstimationTaskModel(par, encoding_space=sp(), prior=uni, + lapse=False).predict_response_distribution(par, base).values + np.testing.assert_allclose(p_tr, p_un, atol=2e-3) + narrow = dict(base, prior_mu=14.0, prior_sd=0.08) + p_tr = EstimationTaskModel(par, encoding_space=sp(), prior=TruncatedGaussianPrior( + 4.5, 24.5, discrete=False), lapse=False).predict_response_distribution(par, narrow).values + p_g = EstimationTaskModel(par, encoding_space=sp(), prior=GaussianPrior(), + lapse=False).predict_response_distribution(par, narrow).values + np.testing.assert_allclose(p_tr, p_g, atol=2e-3) From 4c54816a5c186609e90a52aac1149872e751dd6c Mon Sep 17 00:00:00 2001 From: Gilles de Hollander Date: Mon, 26 Oct 2026 14:40:20 +0100 Subject: [PATCH 08/20] EstimationTaskModel: censored responses (per-trial censor -1/0/+1) A censored trial's likelihood is the summed option probability at and beyond the final position (cumsum + one-hot gather), via pm.CustomDist with an elementwise logp, so pointwise log-likelihoods / LOO still work; posterior- predictive draws are the intended reports. Without a censor column the model is unchanged (Categorical). Tests: censor = 0 reproduces the Categorical logp and gradient exactly; a censored trial equals the tail sum of its option probabilities; MAP with censoring recovers nu from simulated reports cut short on a third of trials, ignoring the censoring does not. Co-Authored-By: Claude Opus 5.5 --- bauer/models/estimation_task.py | 51 ++++++++++++++++++++++-- tests/test_estimation_task.py | 70 +++++++++++++++++++++++++++++++++ 2 files changed, 118 insertions(+), 3 deletions(-) diff --git a/bauer/models/estimation_task.py b/bauer/models/estimation_task.py index d1ac6af..dc289fe 100644 --- a/bauer/models/estimation_task.py +++ b/bauer/models/estimation_task.py @@ -69,8 +69,18 @@ moves with alpha. The two paths agree to < 1e-3 per option probability on the cases where both apply (tested). -The per-trial likelihood is an observed ``pm.Categorical`` over the response -options, so ``pm.compute_log_likelihood`` (LOO / ``az.compare``) and +Censored (unfinished) responses +------------------------------- +A ``censor`` column (-1 / 0 / +1) marks reports that were cut short, e.g. a slider +still moving away from its start when the response window closed: +1 means the +intended report is at least the final position, -1 at most. Such a trial's +likelihood is the summed probability of the response options beyond (and +including) the final one, under the same model; no extra parameters. Without the +column (or with all zeros) the likelihood is unchanged. Posterior-predictive +draws are the intended (uncensored) reports. + +The per-trial likelihood is an observed ``pm.Categorical`` (``pm.CustomDist`` +with censoring) over the response options, so ``pm.compute_log_likelihood`` (LOO / ``az.compare``) and posterior-predictive sampling work directly. Example @@ -207,6 +217,27 @@ def __repr__(self): LogNormalPrior = GaussianPrior +def _censored_logp(R): + """Per-trial log-likelihood with optional censoring (see build_likelihood).""" + def logp(value, p, censor): + value = pt.cast(value, 'int64') + oh = pt.eq(pt.arange(R)[None, :], value[:, None]) # (T, R) + p_obs = pt.sum(p * oh, axis=1) + cum = pt.cumsum(p, axis=1) + p_le = pt.sum(cum * oh, axis=1) # P(option <= final) + p_ge = 1.0 - p_le + p_obs # P(option >= final) + lik = pt.switch(pt.eq(censor, 0), p_obs, pt.switch(pt.gt(censor, 0), p_ge, p_le)) + return pt.log(pt.clip(lik, 1e-12, 1.0)) + return logp + + +def _censored_random(p, censor, rng=None, size=None): + """Uncensored draws (the report the observer intended).""" + p = np.asarray(p) + u = rng.random(p.shape[:-1])[..., None] + return np.minimum((u > np.cumsum(p, axis=-1)).sum(-1), p.shape[-1] - 1) + + # ============================================================================ # Model # ============================================================================ @@ -363,6 +394,12 @@ def _get_paradigm(self, paradigm=None, subject_mapping=None): paradigm_['response_ix'] = (r - rlo).astype(int) else: paradigm_['response_ix'] = np.zeros(len(paradigm), dtype=int) + self.censored = 'censor' in paradigm.columns + if self.censored: + c = paradigm['censor'].fillna(0).values.astype(int) + if not np.isin(c, (-1, 0, 1)).all(): + raise ValueError('censor must be -1, 0 or +1') + paradigm_['censor'] = c return paradigm_ # ------------------------------------------------------------------ @@ -510,7 +547,15 @@ def build_likelihood(self, parameters, save_p_choice=False): n_ix=model['n_ix'], n_unique=self.n_unique) if save_p_choice: p = pm.Deterministic('p_response', p) - pm.Categorical('response', p=p, observed=model['response_ix']) + if not getattr(self, 'censored', False): + pm.Categorical('response', p=p, observed=model['response_ix']) + return + # Censored responses: censor = +1 means the intended report is at least the + # final position (still moving up when time ran out), -1 at most, 0 observed. + R = len(self.response_options) + pm.CustomDist('response', p, model['censor'], logp=_censored_logp(R), + random=_censored_random, signature='(r),()->()', + observed=model['response_ix']) # ------------------------------------------------------------------ # Prediction / simulation / PPC / recovery diff --git a/tests/test_estimation_task.py b/tests/test_estimation_task.py index 243bfa7..56c515b 100644 --- a/tests/test_estimation_task.py +++ b/tests/test_estimation_task.py @@ -181,3 +181,73 @@ def test_truncated_prior_limits(space): p_g = EstimationTaskModel(par, encoding_space=sp(), prior=GaussianPrior(), lapse=False).predict_response_distribution(par, narrow).values np.testing.assert_allclose(p_tr, p_g, atol=2e-3) + + +# --------------------------------------------------------------------------- +# Censored (unfinished) responses +# --------------------------------------------------------------------------- + +def _pointwise(m): + model = m.estimation_model + ip = model.initial_point() + # the Deterministic is a graph of RVs: replace them by their value variables, + # otherwise compile_fn evaluates p at random draws + p_val = model.replace_rvs_by_values([model['p_response']])[0] + fn = model.compile_fn([p_val, model.logp(vars=[model['response']], sum=False)[0]], + inputs=model.value_vars, on_unused_input='ignore') + return fn(ip) + + +def test_censor_zero_equals_categorical(): + par = make_paradigm(n_subjects=2, n_trials=60) + a = EstimationTaskModel(par, prior=TruncatedGaussianPrior(5, 24), motor_noise=True) + a.build_estimation_model(par, hierarchical=True) + par_c = par.assign(censor=0) + b = EstimationTaskModel(par_c, prior=TruncatedGaussianPrior(5, 24), motor_noise=True) + b.build_estimation_model(par_c, hierarchical=True) + ip = a.estimation_model.initial_point() + np.testing.assert_allclose(a.estimation_model.compile_logp()(ip), + b.estimation_model.compile_logp()(ip), rtol=1e-10) + np.testing.assert_allclose(a.estimation_model.compile_dlogp()(ip), + b.estimation_model.compile_dlogp()(ip), rtol=1e-8) + + +def test_censored_trial_probability_is_tail_sum(): + par = make_paradigm(n_subjects=1, n_trials=30, seed=2).droplevel('subject') + par['censor'] = 0 + par.iloc[0, par.columns.get_loc('censor')] = 1 + par.iloc[1, par.columns.get_loc('censor')] = -1 + m = EstimationTaskModel(par, motor_noise=True) + m.build_estimation_model(par, hierarchical=False, save_p_choice=True) + p, ll = _pointwise(m) + r = (par['response'].values - 5).astype(int) + np.testing.assert_allclose(np.exp(ll[0]), p[0, r[0]:].sum(), rtol=1e-8) + np.testing.assert_allclose(np.exp(ll[1]), p[1, :r[1] + 1].sum(), rtol=1e-8) + np.testing.assert_allclose(np.exp(ll[2:]), p[np.arange(2, len(r)), r[2:]], rtol=1e-8) + + +def test_censoring_recovers_parameters_from_unfinished_movements(): + """Simulate reports, then cut a third of them short (a slider moving from a random + start towards the report stops early). Fitting with censoring recovers nu; treating + the cut reports as observed does not.""" + par = make_paradigm(n_subjects=1, n_trials=1500, seed=8).droplevel('subject') + truth = dict(nu=0.3, sigma_r=1.5, p_lapse=0.02) + gen = EstimationTaskModel(par, motor_noise=True) + data = gen.simulate(par, truth, rng=9).droplevel('sample').rename( + columns={'simulated_response': 'response'}) + rng = np.random.default_rng(10) + start = rng.integers(5, 26, len(data)) + dist = data['response'].values - start + cut = (rng.random(len(data)) < .33) & (np.abs(dist) >= 2) + frac = rng.uniform(.2, .8, len(data)) + final = np.round(start + frac * dist).astype(int) + data['censor'] = 0 + data.loc[cut, 'censor'] = np.sign(dist[cut]).astype(int) + data.loc[cut, 'response'] = final[cut] + est = {} + for name, d in (('censored', data), ('ignored', data.drop(columns='censor'))): + fit = EstimationTaskModel(d, motor_noise=True) + fit.build_estimation_model(d, hierarchical=False) + est[name] = fit.fit_map(progressbar=False) + assert est['censored']['nu'] == pytest.approx(truth['nu'], rel=0.12) + assert abs(est['ignored']['nu'] - truth['nu']) > abs(est['censored']['nu'] - truth['nu']) From 334cdc0f0bb0afd2bb97f0b8763e99955b9ad871 Mon Sep 17 00:00:00 2001 From: Gilles de Hollander Date: Mon, 26 Oct 2026 14:43:04 +0100 Subject: [PATCH 09/20] EstimationTaskModel: integer dtype for censored posterior-predictive draws Co-Authored-By: Claude Opus 5.5 --- bauer/models/estimation_task.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bauer/models/estimation_task.py b/bauer/models/estimation_task.py index dc289fe..761c0ce 100644 --- a/bauer/models/estimation_task.py +++ b/bauer/models/estimation_task.py @@ -554,7 +554,7 @@ def build_likelihood(self, parameters, save_p_choice=False): # final position (still moving up when time ran out), -1 at most, 0 observed. R = len(self.response_options) pm.CustomDist('response', p, model['censor'], logp=_censored_logp(R), - random=_censored_random, signature='(r),()->()', + random=_censored_random, signature='(r),()->()', dtype='int64', observed=model['response_ix']) # ------------------------------------------------------------------ @@ -635,7 +635,7 @@ def posterior_predictive(self, idata=None, n_posterior_samples=200, random_seed= pp = pm.sample_posterior_predictive(az.InferenceData(posterior=thin), var_names=['response'], random_seed=random_seed, progressbar=False) - arr = pp.posterior_predictive['response'].values[0] + arr = pp.posterior_predictive['response'].values[0].astype(int) sim = self.response_options[arr].T out = pd.DataFrame(sim, index=self.paradigm.index, columns=pd.Index(np.arange(len(sel)), name='ppc_sample')) From b498bd172a9302ff5ef46d377bd8d0ca513cd67f Mon Sep 17 00:00:00 2001 From: Gilles de Hollander Date: Mon, 26 Oct 2026 14:56:11 +0100 Subject: [PATCH 10/20] EstimationTaskModel: 600-point measurement grid by default without motor noise; grid-accuracy test Checked at fitted parameters against M = 4000 over a 3.5x wider range: with motor noise 200 points give |dP| <= 5e-5 (total log-lik change <= .006 per participant); the no-motor inversion of n_hat(m) needed 600 (|dP| 6.9e-3 -> 5.6e-4, log-lik .50 -> .08). Co-Authored-By: Claude Opus 5.5 --- bauer/models/estimation_task.py | 7 ++++++- tests/test_estimation_task.py | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/bauer/models/estimation_task.py b/bauer/models/estimation_task.py index 761c0ce..a51f451 100644 --- a/bauer/models/estimation_task.py +++ b/bauer/models/estimation_task.py @@ -265,7 +265,7 @@ class EstimationTaskModel(EstimationBaseModel): def __init__(self, paradigm=None, encoding_space=None, prior=None, lapse=True, motor_noise=False, response_range=(5, 25), n_ref=12.0, - n_measurement_grid=200, n_hypothesis_grid=246, + n_measurement_grid=None, n_hypothesis_grid=246, hypothesis_range=(1.0, 50.0), covariates=None, **kwargs): self.covariates = dict(covariates or {}) self.encoding_space = encoding_space if encoding_space is not None else LogSpace() @@ -274,6 +274,11 @@ def __init__(self, paradigm=None, encoding_space=None, prior=None, lapse=True, self.motor_noise = motor_noise self.response_range = tuple(int(x) for x in response_range) self.n_ref = float(n_ref) + # Accuracy (checked against M = 4000 over a 3.5x wider range, at fitted + # parameters): with motor noise 200 points give |dP| < 1e-4; without it the + # inversion of n_hat(m) needs ~600 for |dP| < 1e-3. + if n_measurement_grid is None: + n_measurement_grid = 200 if motor_noise else 600 self.n_measurement_grid = int(n_measurement_grid) self.n_hypothesis_grid = int(n_hypothesis_grid) self.hypothesis_range = tuple(float(x) for x in hypothesis_range) diff --git a/tests/test_estimation_task.py b/tests/test_estimation_task.py index 56c515b..35a8ae3 100644 --- a/tests/test_estimation_task.py +++ b/tests/test_estimation_task.py @@ -251,3 +251,21 @@ def test_censoring_recovers_parameters_from_unfinished_movements(): est[name] = fit.fit_map(progressbar=False) assert est['censored']['nu'] == pytest.approx(truth['nu'], rel=0.12) assert abs(est['ignored']['nu'] - truth['nu']) > abs(est['censored']['nu'] - truth['nu']) + + +@pytest.mark.parametrize('motor', [True, False]) +def test_measurement_grid_accuracy(motor): + """Default grids against a fine, wide reference at strongly compressive, noisy + parameters (where mass near the grid ends matters most).""" + par = grid_paradigm() + pars = dict(nu=0.5, alpha=-1.2, prior_mu=17.0, prior_sd=0.5, p_lapse=0.0) + if motor: + pars['sigma_r'] = 1.8 + kw = dict(encoding_space=PowerSpace(), prior=TruncatedGaussianPrior(5, 24), lapse=False, + motor_noise=motor) + cur = EstimationTaskModel(par, **kw) + ref = EstimationTaskModel(par, n_measurement_grid=4000, **kw) + ref.meas_t = np.linspace(-3, 4, 4000) + pc = cur.predict_response_distribution(par, pars).values + pr = ref.predict_response_distribution(par, pars).values + assert np.abs(pc - pr).max() < 1e-3 From 4acae9ae33138449f61f2dc7dc4782df7605993b Mon Sep 17 00:00:00 2001 From: Gilles de Hollander Date: Mon, 26 Oct 2026 16:00:21 +0100 Subject: [PATCH 11/20] EstimationTaskModel: two-level condition offsets (e.g. cued side) on chosen parameters x[s, c] = x_s + (1/2 - c)(delta + delta_s) on the untransformed scale, group delta ({p}_cond_mu, level 0 minus level 1) and non-centred participant deviations; the option table is computed per (participant, condition). Test: builds, finite gradient, zero offsets reproduce the plain likelihood. Co-Authored-By: Claude Opus 5.5 --- bauer/models/estimation_task.py | 50 +++++++++++++++++++++++++++++++-- tests/test_estimation_task.py | 25 +++++++++++++++++ 2 files changed, 73 insertions(+), 2 deletions(-) diff --git a/bauer/models/estimation_task.py b/bauer/models/estimation_task.py index a51f451..ebc37e4 100644 --- a/bauer/models/estimation_task.py +++ b/bauer/models/estimation_task.py @@ -266,8 +266,11 @@ class EstimationTaskModel(EstimationBaseModel): def __init__(self, paradigm=None, encoding_space=None, prior=None, lapse=True, motor_noise=False, response_range=(5, 25), n_ref=12.0, n_measurement_grid=None, n_hypothesis_grid=246, - hypothesis_range=(1.0, 50.0), covariates=None, **kwargs): + hypothesis_range=(1.0, 50.0), covariates=None, condition=None, + condition_parameters=(), **kwargs): self.covariates = dict(covariates or {}) + self.condition = condition + self.condition_parameters = tuple(condition_parameters) self.encoding_space = encoding_space if encoding_space is not None else LogSpace() self.prior = prior if prior is not None else UniformPrior(4.5, 24.5) self.lapse = lapse @@ -389,6 +392,13 @@ def _get_paradigm(self, paradigm=None, subject_mapping=None): else: paradigm_['subject_ix'] = np.zeros(len(paradigm), dtype=int) paradigm_['n'] = paradigm['n'].values.astype(float) + if self.condition is not None: + vals = (paradigm.index.get_level_values(self.condition) + if self.condition in paradigm.index.names else paradigm[self.condition].values) + self.condition_levels = sorted(pd.unique(vals)) + if len(self.condition_levels) != 2: + raise ValueError('condition must have exactly two levels') + paradigm_['cond_ix'] = (np.asarray(vals) == self.condition_levels[1]).astype(int) # grid path works per unique magnitude (the graph captures n_unique at build) self.n_unique, paradigm_['n_ix'] = np.unique(paradigm_['n'], return_inverse=True) if 'response' in paradigm.columns: @@ -544,11 +554,47 @@ def build_estimation_model(self, data=None, coords=None, hierarchical=True, self.build_priors(hierarchical=hierarchical, flat_prior=flat_prior) self.build_likelihood(None, save_p_choice=save_p_choice) + def _condition_inputs(self, inputs, S): + """Per (participant, condition) parameters, 2S long (row 2s + c). + + For each parameter in ``condition_parameters`` (on its untransformed scale): + x[s, c] = x_s + (1/2 - c) * (delta + delta_s), delta_s ~ N(0, sd) non-centred, + so ``{p}_cond_mu`` = delta is level 0 minus level 1 (condition_levels). + """ + model = pm.Model.get_context() + sign = pt.as_tensor_variable(np.array([.5, -.5])) + out = {} + for k, v in inputs.items(): + if k not in self.condition_parameters: + out[k] = pt.repeat(v, 2) + continue + spec = self.free_parameters[k] + tr = spec.get('transform', 'identity') + if tr not in ('identity', 'softplus'): + raise NotImplementedError(f'condition offsets for {tr} parameters') + base = v if tr == 'identity' else model[f'{k}_untransformed'] + scale = spec.get('sigma_intercept', 1.0) / 2 + d_mu = pm.Normal(f'{k}_cond_mu', 0.0, scale) + d_sd = pm.HalfNormal(f'{k}_cond_sd', spec.get('cauchy_sigma_intercept', .5) / 2) + d_off = pm.Normal(f'{k}_cond_offset', 0.0, 1.0, dims=('subject',)) + delta = d_mu + d_sd * d_off # (S,) + x = base[:, None] + sign[None, :] * delta[:, None] # (S, 2) + x = x if tr == 'identity' else pt.softplus(x) + pm.Deterministic(f'{k}_by_condition', x, dims=('subject', 'condition')) + out[k] = x.reshape((2 * S,)) + return out + def build_likelihood(self, parameters, save_p_choice=False): model = pm.Model.get_context() inputs = self.get_model_inputs(parameters) S = len(model.coords['subject']) if 'subject' in model.coords else 1 - p = self.trial_probabilities(inputs, model['n'], model['subject_ix'], S, + sub_ix = model['subject_ix'] + if self.condition is not None: + model.add_coord('condition', [str(x) for x in self.condition_levels]) + inputs = self._condition_inputs(inputs, S) + sub_ix = 2 * sub_ix + model['cond_ix'] + S = 2 * S + p = self.trial_probabilities(inputs, model['n'], sub_ix, S, n_ix=model['n_ix'], n_unique=self.n_unique) if save_p_choice: p = pm.Deterministic('p_response', p) diff --git a/tests/test_estimation_task.py b/tests/test_estimation_task.py index 35a8ae3..fbf873c 100644 --- a/tests/test_estimation_task.py +++ b/tests/test_estimation_task.py @@ -269,3 +269,28 @@ def test_measurement_grid_accuracy(motor): pc = cur.predict_response_distribution(par, pars).values pr = ref.predict_response_distribution(par, pars).values assert np.abs(pc - pr).max() < 1e-3 + + +def test_condition_offsets(): + """Two-level condition offsets: builds, finite gradient, and with zero offsets the + response likelihood equals the model without them.""" + par = make_paradigm(n_subjects=3, n_trials=80) + par['side'] = np.where(np.arange(len(par)) % 2, 'right', 'left') + kw = dict(encoding_space=PowerSpace(), prior=TruncatedGaussianPrior(5, 24), motor_noise=True) + a = EstimationTaskModel(par, **kw) + a.build_estimation_model(par, hierarchical=True) + b = EstimationTaskModel(par, condition='side', + condition_parameters=('alpha', 'nu', 'prior_mu', 'prior_sd', 'sigma_r'), + **kw) + b.build_estimation_model(par, hierarchical=True) + assert 'nu_cond_mu' in b.estimation_model.named_vars + ipb = b.estimation_model.initial_point() + assert np.all(np.isfinite(b.estimation_model.compile_dlogp()(ipb))) + ipa = a.estimation_model.initial_point() + + def resp_logp(m, ip): + mod = m.estimation_model + return mod.compile_fn(mod.logp(vars=[mod['response']]), inputs=mod.value_vars, + on_unused_input='ignore')(ip) + la, lb = resp_logp(a, ipa), resp_logp(b, ipb) + np.testing.assert_allclose(la, lb, rtol=1e-10) From 4f90289d632a902dbf7074cad1d7eb40588e998e Mon Sep 17 00:00:00 2001 From: Gilles de Hollander Date: Mon, 26 Oct 2026 16:05:20 +0100 Subject: [PATCH 12/20] EstimationTaskModel: single-trial covariates -- measurement_shift (m ~ N(f(n) + beta nu_f z, nu_f^2)) and noise_modulator (nu_t = nu exp(gamma u), the observer decodes with its trial noise) Covariates are binned within participant into equally filled quantile bins (bin means); the option table is computed per (participant, u bin) x (n, z bin). Tests: zero effects reproduce the plain likelihood exactly; 7 bins vs per-trial evaluation differ by .002 nats per trial at beta = .4, gamma = .3. Co-Authored-By: Claude Opus 5.5 --- bauer/models/estimation_task.py | 81 ++++++++++++++++++++++++++++++--- tests/test_estimation_task.py | 36 +++++++++++++++ 2 files changed, 110 insertions(+), 7 deletions(-) diff --git a/bauer/models/estimation_task.py b/bauer/models/estimation_task.py index ebc37e4..7ef6ad4 100644 --- a/bauer/models/estimation_task.py +++ b/bauer/models/estimation_task.py @@ -267,8 +267,12 @@ def __init__(self, paradigm=None, encoding_space=None, prior=None, lapse=True, motor_noise=False, response_range=(5, 25), n_ref=12.0, n_measurement_grid=None, n_hypothesis_grid=246, hypothesis_range=(1.0, 50.0), covariates=None, condition=None, - condition_parameters=(), **kwargs): + condition_parameters=(), measurement_shift=None, noise_modulator=None, + n_covariate_bins=7, **kwargs): self.covariates = dict(covariates or {}) + self.measurement_shift = measurement_shift + self.noise_modulator = noise_modulator + self.n_covariate_bins = int(n_covariate_bins) self.condition = condition self.condition_parameters = tuple(condition_parameters) self.encoding_space = encoding_space if encoding_space is not None else LogSpace() @@ -292,7 +296,8 @@ def __init__(self, paradigm=None, encoding_space=None, prior=None, lapse=True, def closed_form(self): """True when the likelihood is computed analytically (no grid).""" return (self.encoding_space.is_log and type(self.prior) is GaussianPrior - and not self.motor_noise) + and not self.motor_noise and not getattr(self, 'measurement_shift', None) + and not getattr(self, 'noise_modulator', None)) # ------------------------------------------------------------------ def get_free_parameters(self): @@ -309,6 +314,12 @@ def get_free_parameters(self): if self.motor_noise: pars['sigma_r'] = dict(mu_intercept=1.0, sigma_intercept=1.0, cauchy_sigma_intercept=0.75, transform='softplus') + if getattr(self, 'measurement_shift', None): + pars['shift_beta'] = dict(mu_intercept=0.0, sigma_intercept=0.5, + cauchy_sigma_intercept=0.25, transform='identity') + if getattr(self, 'noise_modulator', None): + pars['noise_gamma'] = dict(mu_intercept=0.0, sigma_intercept=0.5, + cauchy_sigma_intercept=0.25, transform='identity') if self.lapse: pars['p_lapse'] = dict(transform='beta', beta_mu_mean=0.05, beta_mu_kappa=8.0) return pars @@ -392,6 +403,14 @@ def _get_paradigm(self, paradigm=None, subject_mapping=None): else: paradigm_['subject_ix'] = np.zeros(len(paradigm), dtype=int) paradigm_['n'] = paradigm['n'].values.astype(float) + for col, key in ((getattr(self, 'measurement_shift', None), 'shift'), + (getattr(self, 'noise_modulator', None), 'noise')): + if col is None: + continue + ix, centres = self._bin_covariate(paradigm[col].values.astype(float), + np.asarray(paradigm_['subject_ix'])) + paradigm_[f'{key}_bin'] = ix + setattr(self, f'{key}_centres', centres) if self.condition is not None: vals = (paradigm.index.get_level_values(self.condition) if self.condition in paradigm.index.names else paradigm[self.condition].values) @@ -417,6 +436,24 @@ def _get_paradigm(self, paradigm=None, subject_mapping=None): paradigm_['censor'] = c return paradigm_ + def _bin_covariate(self, x, subject_ix): + """Within-participant quantile bins of a trial covariate. + + Returns per-trial bin index and the (S, B) bin means (the value used for all + trials of a bin). Ties are broken by rank, so bins are equally filled. + """ + B = self.n_covariate_bins + S = int(subject_ix.max()) + 1 + ix = np.zeros(len(x), dtype=int) + centres = np.zeros((S, B)) + for s_ in range(S): + m = subject_ix == s_ + r = pd.Series(x[m]).rank(method='first').values + b = np.minimum((B * (r - 1) / m.sum()).astype(int), B - 1) + ix[m] = b + centres[s_] = [x[m][b == k].mean() for k in range(B)] + return ix, centres + # ------------------------------------------------------------------ # Observer # ------------------------------------------------------------------ @@ -496,7 +533,7 @@ def _invert(self, m, n_hat, values): out = pt.switch(pt.eq(below, M), m[:, -1:] + 1e3, out) return out # (S, V) - def _option_table_grid(self, inputs, n_unique, S): + def _option_table_grid(self, inputs, n_unique, S, shift_nu=None): """(S, K, R) option probabilities for every participant x unique magnitude. Computed per unique presented magnitude (K values), not per trial, and @@ -507,6 +544,11 @@ def _option_table_grid(self, inputs, n_unique, S): m, n_hat, alpha, nu_f = self.estimate_on_grid(inputs, S) nk = pt.as_tensor_variable(np.asarray(n_unique, dtype=float)) fn = self._f(nk, alpha) # (S, K) + if shift_nu is not None: + # measurement centres shifted by shift_nu (in units of nu_f): (S, K * Z) + Z = shift_nu.shape[1] + fn = (fn[:, :, None] + (nu_f[:, None] * shift_nu)[:, None, :]).reshape( + (fn.shape[0], fn.shape[1] * Z)) if not self.motor_noise: m_edges = self._invert(m, n_hat, self.response_edges) # (S, R+1) z = (m_edges[:, None, :] - fn[:, :, None]) / nu_f[:, None, None] @@ -521,7 +563,8 @@ def _option_table_grid(self, inputs, n_unique, S): kern = cdf[:, :, 1:] - cdf[:, :, :-1] # (S, M, R) return pt.batched_dot(dens, kern) # (S, K, R) - def trial_probabilities(self, inputs, n, subject_ix, S, n_ix=None, n_unique=None): + def trial_probabilities(self, inputs, n, subject_ix, S, n_ix=None, n_unique=None, + shift_nu=None): """Per-trial option probabilities (T, R). Grid path: pass ``n_ix`` (index of each trial's magnitude into @@ -530,7 +573,7 @@ def trial_probabilities(self, inputs, n, subject_ix, S, n_ix=None, n_unique=None if self.closed_form: p = self._option_probs_closed(inputs, n, subject_ix) else: - table = self._option_table_grid(inputs, n_unique, S) + table = self._option_table_grid(inputs, n_unique, S, shift_nu) p = table[subject_ix, n_ix] if self.lapse: lam = inputs['p_lapse'][subject_ix][:, None] @@ -589,13 +632,37 @@ def build_likelihood(self, parameters, save_p_choice=False): inputs = self.get_model_inputs(parameters) S = len(model.coords['subject']) if 'subject' in model.coords else 1 sub_ix = model['subject_ix'] + n_ix = model['n_ix'] + shift_nu = None if self.condition is not None: + if self.measurement_shift or self.noise_modulator: + raise NotImplementedError('condition offsets with trial covariates') model.add_coord('condition', [str(x) for x in self.condition_levels]) inputs = self._condition_inputs(inputs, S) sub_ix = 2 * sub_ix + model['cond_ix'] S = 2 * S - p = self.trial_probabilities(inputs, model['n'], sub_ix, S, - n_ix=model['n_ix'], n_unique=self.n_unique) + if self.noise_modulator: + # nu_t = nu * exp(gamma * u): one pseudo-participant per (participant, u bin); + # the observer decodes with its own trial noise + U = self.n_covariate_bins + uc = pt.as_tensor_variable(self.noise_centres) # (S, U) + scale = pt.exp(inputs['noise_gamma'][:, None] * uc).reshape((S * U,)) + inputs = {k: pt.repeat(v, U) for k, v in inputs.items()} + inputs['nu'] = inputs['nu'] * scale + sub_ix = U * sub_ix + model['noise_bin'] + shift_rows = pt.repeat(inputs['shift_beta'][::U], U) if self.measurement_shift else None + zc_rows = pt.repeat(pt.as_tensor_variable(self.shift_centres), U, axis=0) \ + if self.measurement_shift else None + S = S * U + elif self.measurement_shift: + shift_rows = inputs['shift_beta'] + zc_rows = pt.as_tensor_variable(self.shift_centres) + if self.measurement_shift: + # m ~ N(f(n) + beta * nu_f * z, nu_f^2): one stimulus position per (n, z bin) + shift_nu = shift_rows[:, None] * zc_rows # (S, Z) + n_ix = n_ix * self.n_covariate_bins + model['shift_bin'] + p = self.trial_probabilities(inputs, model['n'], sub_ix, S, n_ix=n_ix, + n_unique=self.n_unique, shift_nu=shift_nu) if save_p_choice: p = pm.Deterministic('p_response', p) if not getattr(self, 'censored', False): diff --git a/tests/test_estimation_task.py b/tests/test_estimation_task.py index fbf873c..253cd40 100644 --- a/tests/test_estimation_task.py +++ b/tests/test_estimation_task.py @@ -294,3 +294,39 @@ def resp_logp(m, ip): on_unused_input='ignore')(ip) la, lb = resp_logp(a, ipa), resp_logp(b, ipb) np.testing.assert_allclose(la, lb, rtol=1e-10) + + +def _resp_logp_at(m, values): + """Response log-likelihood with the given parameter values (by RV name).""" + mod = m.estimation_model + ip = mod.initial_point() + for k, v in values.items(): + ip[k] = np.asarray(v, dtype=float) + return mod.compile_fn(mod.logp(vars=[mod['response']]), inputs=mod.value_vars, + on_unused_input='ignore')(ip) + + +def test_trial_covariates_reduce_to_plain_model_and_bin_finely(): + par = make_paradigm(n_subjects=2, n_trials=150, seed=4) + rng = np.random.default_rng(5) + par['z'] = rng.normal(size=len(par)) + par['u'] = rng.normal(size=len(par)) + kw = dict(encoding_space=PowerSpace(), prior=TruncatedGaussianPrior(5, 24), motor_noise=True) + base = EstimationTaskModel(par, **kw) + base.build_estimation_model(par, hierarchical=False if False else True) + both = EstimationTaskModel(par, measurement_shift='z', noise_modulator='u', **kw) + both.build_estimation_model(par, hierarchical=True) + # zero effects: identical likelihood + zero = {'shift_beta_mu': 0.0, 'shift_beta_offset': np.zeros(2), + 'noise_gamma_mu': 0.0, 'noise_gamma_offset': np.zeros(2)} + np.testing.assert_allclose(_resp_logp_at(base, {}), _resp_logp_at(both, zero), rtol=1e-10) + assert np.all(np.isfinite(both.estimation_model.compile_dlogp()( + both.estimation_model.initial_point()))) + # 7 bins vs (nearly) per-trial evaluation, at sizeable effects + eff = {'shift_beta_mu': 0.4, 'shift_beta_offset': np.zeros(2), + 'noise_gamma_mu': 0.3, 'noise_gamma_offset': np.zeros(2)} + fine = EstimationTaskModel(par, measurement_shift='z', noise_modulator='u', + n_covariate_bins=50, **kw) + fine.build_estimation_model(par, hierarchical=True) + l7, l50 = _resp_logp_at(both, eff), _resp_logp_at(fine, eff) + assert abs(l7 - l50) / len(par) < 0.01 # < .01 nats per trial From 9b54adb475c038888e0def1ab671afe5643f4799 Mon Sep 17 00:00:00 2001 From: Gilles de Hollander Date: Mon, 26 Oct 2026 17:15:22 +0100 Subject: [PATCH 13/20] TruncatedGaussianPrior(space='n'): Gaussian in numerosity (items), independent of alpha Co-Authored-By: Claude Opus 5.5 --- bauer/models/estimation_task.py | 24 +++++++++++++++++++----- tests/test_estimation_task.py | 27 +++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 5 deletions(-) diff --git a/bauer/models/estimation_task.py b/bauer/models/estimation_task.py index 7ef6ad4..c173a50 100644 --- a/bauer/models/estimation_task.py +++ b/bauer/models/estimation_task.py @@ -198,7 +198,9 @@ class TruncatedGaussianPrior(GaussianPrior): ``discrete=True`` (default): mass only on the integers lo..hi, with weights proportional to the prior's density in n at each integer, ``N(f(k); mu_f, sd_f) * f'(k)`` (the same density-in-n convention as the - continuous prior, evaluated at the integers). ``discrete=False``: the + continuous prior, evaluated at the integers). ``space='n'``: Gaussian in + numerosity itself, mass on k proportional to N(k; prior_mu, prior_sd) with both + in ITEMS, so the prior does not depend on alpha. ``discrete=False``: the continuous density with the mass outside [lo, hi] zeroed (e.g. lo = 4.5, hi = 24.5). A narrow prior centred mid-range reproduces ``GaussianPrior``. A very wide one becomes uniform in the encoding space: ``UniformPrior`` @@ -206,11 +208,14 @@ class TruncatedGaussianPrior(GaussianPrior): """ truncated = True - def __init__(self, lo, hi, discrete=True): - self.lo, self.hi, self.discrete = float(lo), float(hi), bool(discrete) + def __init__(self, lo, hi, discrete=True, space='internal'): + if space not in ('internal', 'n'): + raise ValueError("space must be 'internal' or 'n'") + self.lo, self.hi, self.discrete, self.space = float(lo), float(hi), bool(discrete), space def __repr__(self): - return f'TruncatedGaussianPrior({self.lo}, {self.hi}, discrete={self.discrete})' + return (f'TruncatedGaussianPrior({self.lo}, {self.hi}, discrete={self.discrete}, ' + f'space={self.space!r})') # Alias in the spirit of the docs (log-normal when the space is log) @@ -306,7 +311,12 @@ def get_free_parameters(self): if self.encoding_space.free: pars['alpha'] = dict(mu_intercept=0.5, sigma_intercept=0.5, cauchy_sigma_intercept=0.3, transform='identity') - if isinstance(self.prior, GaussianPrior): + if isinstance(self.prior, GaussianPrior) and getattr(self.prior, 'space', 'internal') == 'n': + pars['prior_mu'] = dict(mu_intercept=14.5, sigma_intercept=4.0, + cauchy_sigma_intercept=2.0, transform='softplus') + pars['prior_sd'] = dict(mu_intercept=6.0, sigma_intercept=3.0, + cauchy_sigma_intercept=1.5, transform='softplus') + elif isinstance(self.prior, GaussianPrior): pars['prior_mu'] = dict(mu_intercept=12.0, sigma_intercept=4.0, cauchy_sigma_intercept=2.0, transform='softplus') pars['prior_sd'] = dict(mu_intercept=-0.5, sigma_intercept=0.75, @@ -496,6 +506,10 @@ def estimate_on_grid(self, inputs, S): logmask = pt.log(pt.as_tensor_variable(self.prior_mask) + 1e-300)[None, :] if isinstance(self.prior, UniformPrior): logprior = logmask + elif getattr(self.prior, 'space', 'internal') == 'n': + # Gaussian in items, independent of alpha + logprior = (-0.5 * ((h[None, :] - inputs['prior_mu'][:, None]) + / inputs['prior_sd'][:, None]) ** 2 + logmask) else: mu_f = self.encoding_space.transform(inputs['prior_mu'], alpha) # (S,) sd_f = inputs['prior_sd'] * inputs['prior_mu'] ** alpha diff --git a/tests/test_estimation_task.py b/tests/test_estimation_task.py index 253cd40..74df01f 100644 --- a/tests/test_estimation_task.py +++ b/tests/test_estimation_task.py @@ -330,3 +330,30 @@ def test_trial_covariates_reduce_to_plain_model_and_bin_finely(): fine.build_estimation_model(par, hierarchical=True) l7, l50 = _resp_logp_at(both, eff), _resp_logp_at(fine, eff) assert abs(l7 - l50) / len(par) < 0.01 # < .01 nats per trial + + +def test_prior_gaussian_in_items(): + """space='n': a very wide prior equals the discrete uniform prior, and the prior (hence + predictions at fixed noise) does not depend on alpha through the prior.""" + par = grid_paradigm() + pars = dict(nu=0.3, alpha=0.3, prior_mu=14.0, prior_sd=500.0, p_lapse=0.0) + m = EstimationTaskModel(par, encoding_space=PowerSpace(), + prior=TruncatedGaussianPrior(5, 24, space='n'), lapse=False) + u = EstimationTaskModel(par, encoding_space=PowerSpace(), + prior=UniformPrior(5, 24, discrete=True), lapse=False) + np.testing.assert_allclose(m.predict_response_distribution(par, pars).values, + u.predict_response_distribution(par, pars).values, atol=1e-4) + # prior mass independent of alpha: evaluate the log-prior term directly + import pytensor.tensor as pt + for a in (-1.0, 0.0, 1.0): + inp = {'nu': pt.as_tensor([.3]), 'alpha': pt.as_tensor([a]), + 'prior_mu': pt.as_tensor([12.0]), 'prior_sd': pt.as_tensor([4.0])} + m2 = EstimationTaskModel(par, encoding_space=PowerSpace(), + prior=TruncatedGaussianPrior(5, 24, space='n'), lapse=False) + mg, nh, _, _ = [x.eval() for x in m2.estimate_on_grid(inp, 1)] + # with very large noise the estimate is the prior mean, whatever alpha + inp['nu'] = pt.as_tensor([50.0]) + mg, nh, _, _ = [x.eval() for x in m2.estimate_on_grid(inp, 1)] + k = np.arange(5, 25) + w = np.exp(-.5 * ((k - 12.0) / 4.0) ** 2) + np.testing.assert_allclose(nh[0, len(nh[0]) // 2], (w * k).sum() / w.sum(), atol=1e-2) From da6f45cc59e332f8b68230117693ca4e957f662d Mon Sep 17 00:00:00 2001 From: Gilles de Hollander Date: Tue, 27 Oct 2026 08:49:29 +0100 Subject: [PATCH 14/20] EstimationTaskModel: leak=: measurement centred on (1 - w) f(n) + w f(n_u) (uncued magnitude leaks into encoding; observer decodes as if from n); per unique (n, n_u) pair Co-Authored-By: Claude Opus 5.5 --- bauer/models/estimation_task.py | 32 ++++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/bauer/models/estimation_task.py b/bauer/models/estimation_task.py index c173a50..0d24452 100644 --- a/bauer/models/estimation_task.py +++ b/bauer/models/estimation_task.py @@ -273,8 +273,11 @@ def __init__(self, paradigm=None, encoding_space=None, prior=None, lapse=True, n_measurement_grid=None, n_hypothesis_grid=246, hypothesis_range=(1.0, 50.0), covariates=None, condition=None, condition_parameters=(), measurement_shift=None, noise_modulator=None, - n_covariate_bins=7, **kwargs): + n_covariate_bins=7, leak=None, **kwargs): self.covariates = dict(covariates or {}) + # leak: column with a second (uncued) magnitude n_u; the measurement is centred on + # (1 - w) f(n) + w f(n_u), the observer decodes it as if it came from n alone + self.leak = leak self.measurement_shift = measurement_shift self.noise_modulator = noise_modulator self.n_covariate_bins = int(n_covariate_bins) @@ -302,7 +305,8 @@ def closed_form(self): """True when the likelihood is computed analytically (no grid).""" return (self.encoding_space.is_log and type(self.prior) is GaussianPrior and not self.motor_noise and not getattr(self, 'measurement_shift', None) - and not getattr(self, 'noise_modulator', None)) + and not getattr(self, 'noise_modulator', None) + and not getattr(self, 'leak', None)) # ------------------------------------------------------------------ def get_free_parameters(self): @@ -330,6 +334,9 @@ def get_free_parameters(self): if getattr(self, 'noise_modulator', None): pars['noise_gamma'] = dict(mu_intercept=0.0, sigma_intercept=0.5, cauchy_sigma_intercept=0.25, transform='identity') + if getattr(self, 'leak', None): + pars['leak_w'] = dict(mu_intercept=0.0, sigma_intercept=0.25, + cauchy_sigma_intercept=0.1, transform='identity') if self.lapse: pars['p_lapse'] = dict(transform='beta', beta_mu_mean=0.05, beta_mu_kappa=8.0) return pars @@ -430,6 +437,11 @@ def _get_paradigm(self, paradigm=None, subject_mapping=None): paradigm_['cond_ix'] = (np.asarray(vals) == self.condition_levels[1]).astype(int) # grid path works per unique magnitude (the graph captures n_unique at build) self.n_unique, paradigm_['n_ix'] = np.unique(paradigm_['n'], return_inverse=True) + if getattr(self, 'leak', None): + # per unique (n, n_u) pair instead + pairs = np.column_stack([paradigm_['n'], paradigm[self.leak].values.astype(float)]) + self.n_unique, ix = np.unique(pairs, axis=0, return_inverse=True) + paradigm_['n_ix'] = np.asarray(ix).ravel() if 'response' in paradigm.columns: r = paradigm['response'].values.astype(float) if np.any(np.isnan(r)): @@ -556,8 +568,14 @@ def _option_table_grid(self, inputs, n_unique, S, shift_nu=None): (T, M, R) tensor (which made the motor-noise fits ~50x slower). """ m, n_hat, alpha, nu_f = self.estimate_on_grid(inputs, S) - nk = pt.as_tensor_variable(np.asarray(n_unique, dtype=float)) - fn = self._f(nk, alpha) # (S, K) + nk = np.asarray(n_unique, dtype=float) + if getattr(self, 'leak', None): + # n_unique are (n, n_u) pairs: m centred on (1 - w) f(n) + w f(n_u) + w = inputs['leak_w'][:, None] + fn = ((1 - w) * self._f(pt.as_tensor_variable(nk[:, 0]), alpha) + + w * self._f(pt.as_tensor_variable(nk[:, 1]), alpha)) # (S, K) + else: + fn = self._f(pt.as_tensor_variable(nk), alpha) # (S, K) if shift_nu is not None: # measurement centres shifted by shift_nu (in units of nu_f): (S, K * Z) Z = shift_nu.shape[1] @@ -648,6 +666,8 @@ def build_likelihood(self, parameters, save_p_choice=False): sub_ix = model['subject_ix'] n_ix = model['n_ix'] shift_nu = None + if self.leak and (self.measurement_shift or self.noise_modulator): + raise NotImplementedError('leak with trial covariates') if self.condition is not None: if self.measurement_shift or self.noise_modulator: raise NotImplementedError('condition offsets with trial covariates') @@ -716,6 +736,10 @@ def predict_response_distribution(self, paradigm, parameters): inputs = {k: pt.as_tensor_variable(v) for k, v in arrs.items()} n = paradigm['n'].values.astype(float) n_unique, n_ix = np.unique(n, return_inverse=True) + if getattr(self, 'leak', None): + n_unique, n_ix = np.unique(np.column_stack([n, paradigm[self.leak].values.astype(float)]), + axis=0, return_inverse=True) + n_ix = np.asarray(n_ix).ravel() p = self.trial_probabilities(inputs, pt.as_tensor_variable(n), pt.as_tensor_variable(codes), len(uniques), n_ix=pt.as_tensor_variable(n_ix), n_unique=n_unique).eval() From 94fab4539d33e75a043ccaf2e90d6781f8cc34e6 Mon Sep 17 00:00:00 2001 From: Gilles de Hollander Date: Thu, 29 Oct 2026 10:44:31 +0100 Subject: [PATCH 15/20] EstimationTaskModel: prior_leak=: prior centre mu + k (n_u - mu) per trial (parameter prior_leak_k), observer decodes with that prior; table per (participant, n_u); combines with leak Co-Authored-By: Claude Opus 5.5 --- bauer/models/estimation_task.py | 85 ++++++++++++++++++++++++++++----- 1 file changed, 73 insertions(+), 12 deletions(-) diff --git a/bauer/models/estimation_task.py b/bauer/models/estimation_task.py index 0d24452..f7a02d1 100644 --- a/bauer/models/estimation_task.py +++ b/bauer/models/estimation_task.py @@ -273,11 +273,17 @@ def __init__(self, paradigm=None, encoding_space=None, prior=None, lapse=True, n_measurement_grid=None, n_hypothesis_grid=246, hypothesis_range=(1.0, 50.0), covariates=None, condition=None, condition_parameters=(), measurement_shift=None, noise_modulator=None, - n_covariate_bins=7, leak=None, **kwargs): + n_covariate_bins=7, leak=None, prior_leak=None, **kwargs): self.covariates = dict(covariates or {}) # leak: column with a second (uncued) magnitude n_u; the measurement is centred on # (1 - w) f(n) + w f(n_u), the observer decodes it as if it came from n alone self.leak = leak + # prior_leak: column with n_u; the prior centre on that trial is mu + k (n_u - mu) + # (parameter prior_leak_k) and the observer decodes with that prior. With leak + # as well (same column), both act. + if leak and prior_leak and leak != prior_leak: + raise ValueError('leak and prior_leak must name the same column') + self.prior_leak = prior_leak self.measurement_shift = measurement_shift self.noise_modulator = noise_modulator self.n_covariate_bins = int(n_covariate_bins) @@ -306,7 +312,8 @@ def closed_form(self): return (self.encoding_space.is_log and type(self.prior) is GaussianPrior and not self.motor_noise and not getattr(self, 'measurement_shift', None) and not getattr(self, 'noise_modulator', None) - and not getattr(self, 'leak', None)) + and not getattr(self, 'leak', None) + and not getattr(self, 'prior_leak', None)) # ------------------------------------------------------------------ def get_free_parameters(self): @@ -337,6 +344,12 @@ def get_free_parameters(self): if getattr(self, 'leak', None): pars['leak_w'] = dict(mu_intercept=0.0, sigma_intercept=0.25, cauchy_sigma_intercept=0.1, transform='identity') + if getattr(self, 'prior_leak', None): + if not (isinstance(self.prior, GaussianPrior) + and getattr(self.prior, 'space', 'internal') == 'n'): + raise NotImplementedError('prior_leak needs a Gaussian prior in items') + pars['prior_leak_k'] = dict(mu_intercept=0.0, sigma_intercept=0.25, + cauchy_sigma_intercept=0.1, transform='identity') if self.lapse: pars['p_lapse'] = dict(transform='beta', beta_mu_mean=0.05, beta_mu_kappa=8.0) return pars @@ -437,11 +450,9 @@ def _get_paradigm(self, paradigm=None, subject_mapping=None): paradigm_['cond_ix'] = (np.asarray(vals) == self.condition_levels[1]).astype(int) # grid path works per unique magnitude (the graph captures n_unique at build) self.n_unique, paradigm_['n_ix'] = np.unique(paradigm_['n'], return_inverse=True) - if getattr(self, 'leak', None): - # per unique (n, n_u) pair instead - pairs = np.column_stack([paradigm_['n'], paradigm[self.leak].values.astype(float)]) - self.n_unique, ix = np.unique(pairs, axis=0, return_inverse=True) - paradigm_['n_ix'] = np.asarray(ix).ravel() + if getattr(self, 'leak', None) or getattr(self, 'prior_leak', None): + self.n_unique, paradigm_['n_ix'] = self._pair_index( + paradigm_['n'], paradigm[self.leak or self.prior_leak].values) if 'response' in paradigm.columns: r = paradigm['response'].values.astype(float) if np.any(np.isnan(r)): @@ -458,6 +469,21 @@ def _get_paradigm(self, paradigm=None, subject_mapping=None): paradigm_['censor'] = c return paradigm_ + def _pair_index(self, n, u): + """(K, 2) table of (n, n_u) and each trial's row in it. + + leak only: the unique pairs. With prior_leak: the full grid, n_u-major + (row = u_ix * N + n_ix), so the table can be computed per (participant, n_u). + """ + n, u = np.asarray(n, float), np.asarray(u, float) + if not getattr(self, 'prior_leak', None): + pairs, ix = np.unique(np.column_stack([n, u]), axis=0, return_inverse=True) + return pairs, np.asarray(ix).ravel() + nv, n_ix = np.unique(n, return_inverse=True) + uv, u_ix = np.unique(u, return_inverse=True) + pairs = np.column_stack([np.tile(nv, len(uv)), np.repeat(uv, len(nv))]) + return pairs, np.asarray(u_ix).ravel() * len(nv) + np.asarray(n_ix).ravel() + def _bin_covariate(self, x, subject_ix): """Within-participant quantile bins of a trial covariate. @@ -567,6 +593,8 @@ def _option_table_grid(self, inputs, n_unique, S, shift_nu=None): then an (S, K, M) x (S, M, R) batched matmul instead of a per-trial (T, M, R) tensor (which made the motor-noise fits ~50x slower). """ + if getattr(self, 'prior_leak', None): + return self._option_table_prior_leak(inputs, n_unique, S) m, n_hat, alpha, nu_f = self.estimate_on_grid(inputs, S) nk = np.asarray(n_unique, dtype=float) if getattr(self, 'leak', None): @@ -595,6 +623,41 @@ def _option_table_grid(self, inputs, n_unique, S, shift_nu=None): kern = cdf[:, :, 1:] - cdf[:, :, :-1] # (S, M, R) return pt.batched_dot(dens, kern) # (S, K, R) + def _option_table_prior_leak(self, inputs, n_unique, S): + """(S, U * N, R) option probabilities with the prior centre shifted by n_u. + + ``n_unique`` is the full (n, n_u) grid from ``_pair_index`` (n_u-major). One + pseudo-participant per (participant, n_u): prior centre mu + k (n_u - mu), its + own estimate n_hat(m); the measurement is centred on f(n), or with ``leak`` on + (1 - w) f(n) + w f(n_u). + """ + nk = np.asarray(n_unique, dtype=float) + nv, uv = np.unique(nk[:, 0]), np.unique(nk[:, 1]) + N, U = len(nv), len(uv) + rows = {k: pt.repeat(v, U) for k, v in inputs.items()} # row s * U + u + u_row = pt.as_tensor_variable(np.tile(uv, S)) + mu = rows['prior_mu'] + rows['prior_mu'] = mu + rows['prior_leak_k'] * (u_row - mu) + m, n_hat, alpha, nu_f = self.estimate_on_grid(rows, S * U) # (SU, M) + fn = self._f(pt.as_tensor_variable(nv), alpha) # (SU, N) + if getattr(self, 'leak', None): + pick = pt.as_tensor_variable(np.tile(np.eye(U), (S, 1))) # (SU, U) + fu = pt.sum(self._f(pt.as_tensor_variable(uv), alpha) * pick, axis=1) + w = rows['leak_w'][:, None] + fn = (1 - w) * fn + w * fu[:, None] + if not self.motor_noise: + m_edges = self._invert(m, n_hat, self.response_edges) # (SU, R+1) + cdf = _norm_cdf((m_edges[:, None, :] - fn[:, :, None]) / nu_f[:, None, None]) + p = cdf[:, :, 1:] - cdf[:, :, :-1] + else: + dens = pt.exp(-0.5 * ((m[:, None, :] - fn[:, :, None]) / nu_f[:, None, None]) ** 2) + dens = dens / pt.sum(dens, axis=2, keepdims=True) # (SU, N, M) + edges = pt.as_tensor_variable(self.response_edges) + sig = rows['sigma_r'][:, None, None] + cdf = _norm_cdf((edges[None, None, :] - n_hat[:, :, None]) / sig) + p = pt.batched_dot(dens, cdf[:, :, 1:] - cdf[:, :, :-1]) # (SU, N, R) + return p.reshape((S, U * N, p.shape[-1])) + def trial_probabilities(self, inputs, n, subject_ix, S, n_ix=None, n_unique=None, shift_nu=None): """Per-trial option probabilities (T, R). @@ -666,7 +729,7 @@ def build_likelihood(self, parameters, save_p_choice=False): sub_ix = model['subject_ix'] n_ix = model['n_ix'] shift_nu = None - if self.leak and (self.measurement_shift or self.noise_modulator): + if (self.leak or self.prior_leak) and (self.measurement_shift or self.noise_modulator): raise NotImplementedError('leak with trial covariates') if self.condition is not None: if self.measurement_shift or self.noise_modulator: @@ -736,10 +799,8 @@ def predict_response_distribution(self, paradigm, parameters): inputs = {k: pt.as_tensor_variable(v) for k, v in arrs.items()} n = paradigm['n'].values.astype(float) n_unique, n_ix = np.unique(n, return_inverse=True) - if getattr(self, 'leak', None): - n_unique, n_ix = np.unique(np.column_stack([n, paradigm[self.leak].values.astype(float)]), - axis=0, return_inverse=True) - n_ix = np.asarray(n_ix).ravel() + if getattr(self, 'leak', None) or getattr(self, 'prior_leak', None): + n_unique, n_ix = self._pair_index(n, paradigm[self.leak or self.prior_leak].values) p = self.trial_probabilities(inputs, pt.as_tensor_variable(n), pt.as_tensor_variable(codes), len(uniques), n_ix=pt.as_tensor_variable(n_ix), n_unique=n_unique).eval() From 31df7998bb8f1322cc4cb77e9c270f4db209bdb0 Mon Sep 17 00:00:00 2001 From: Gilles de Hollander Date: Thu, 29 Oct 2026 17:25:12 +0100 Subject: [PATCH 16/20] EstimationTaskModel: response_pull= (report centre n_hat + w (n_u - n_hat), w = pull_k (n_hat/15)^(1 - alpha), per (participant, n_u) rows; needs motor noise) and swap= (mixture with the exchanged-roles option probabilities, logit p = swap_a + swap_b (n - 15)/10; lapses outside); both reduce exactly to the plain model Co-Authored-By: Claude Opus 5.5 --- bauer/models/estimation_task.py | 117 +++++++++++++++++++++++++++----- 1 file changed, 100 insertions(+), 17 deletions(-) diff --git a/bauer/models/estimation_task.py b/bauer/models/estimation_task.py index f7a02d1..147e3cd 100644 --- a/bauer/models/estimation_task.py +++ b/bauer/models/estimation_task.py @@ -273,7 +273,8 @@ def __init__(self, paradigm=None, encoding_space=None, prior=None, lapse=True, n_measurement_grid=None, n_hypothesis_grid=246, hypothesis_range=(1.0, 50.0), covariates=None, condition=None, condition_parameters=(), measurement_shift=None, noise_modulator=None, - n_covariate_bins=7, leak=None, prior_leak=None, **kwargs): + n_covariate_bins=7, leak=None, prior_leak=None, response_pull=None, + swap=None, **kwargs): self.covariates = dict(covariates or {}) # leak: column with a second (uncued) magnitude n_u; the measurement is centred on # (1 - w) f(n) + w f(n_u), the observer decodes it as if it came from n alone @@ -284,6 +285,19 @@ def __init__(self, paradigm=None, encoding_space=None, prior=None, lapse=True, if leak and prior_leak and leak != prior_leak: raise ValueError('leak and prior_leak must name the same column') self.prior_leak = prior_leak + # response_pull: column with n_u; the report (before motor noise) is centred on + # n_hat + w (n_u - n_hat), w = pull_k (n_hat / 15)^(1 - alpha) (grows with the + # encoding s.d. in items at the estimate). Needs motor noise. + self.response_pull = response_pull + # swap: column with n_u; with probability p (logit p = swap_a + swap_b (n - 15) / 10) + # the observer reports the uncued array as if it were the cued one (same parameters, + # roles of n and n_u exchanged). Lapses act outside the mixture. + self.swap = swap + cols = {c for c in (leak, prior_leak, response_pull, swap) if c} + if len(cols) > 1: + raise ValueError('leak / prior_leak / response_pull / swap must name the same column') + if response_pull and not motor_noise: + raise NotImplementedError('response_pull needs motor noise') self.measurement_shift = measurement_shift self.noise_modulator = noise_modulator self.n_covariate_bins = int(n_covariate_bins) @@ -313,7 +327,9 @@ def closed_form(self): and not self.motor_noise and not getattr(self, 'measurement_shift', None) and not getattr(self, 'noise_modulator', None) and not getattr(self, 'leak', None) - and not getattr(self, 'prior_leak', None)) + and not getattr(self, 'prior_leak', None) + and not getattr(self, 'response_pull', None) + and not getattr(self, 'swap', None)) # ------------------------------------------------------------------ def get_free_parameters(self): @@ -350,6 +366,14 @@ def get_free_parameters(self): raise NotImplementedError('prior_leak needs a Gaussian prior in items') pars['prior_leak_k'] = dict(mu_intercept=0.0, sigma_intercept=0.25, cauchy_sigma_intercept=0.1, transform='identity') + if getattr(self, 'response_pull', None): + pars['pull_k'] = dict(mu_intercept=0.0, sigma_intercept=0.25, + cauchy_sigma_intercept=0.1, transform='identity') + if getattr(self, 'swap', None): + pars['swap_a'] = dict(mu_intercept=-3.5, sigma_intercept=1.0, + cauchy_sigma_intercept=0.5, transform='identity') + pars['swap_b'] = dict(mu_intercept=0.0, sigma_intercept=1.0, + cauchy_sigma_intercept=0.5, transform='identity') if self.lapse: pars['p_lapse'] = dict(transform='beta', beta_mu_mean=0.05, beta_mu_kappa=8.0) return pars @@ -450,9 +474,11 @@ def _get_paradigm(self, paradigm=None, subject_mapping=None): paradigm_['cond_ix'] = (np.asarray(vals) == self.condition_levels[1]).astype(int) # grid path works per unique magnitude (the graph captures n_unique at build) self.n_unique, paradigm_['n_ix'] = np.unique(paradigm_['n'], return_inverse=True) - if getattr(self, 'leak', None) or getattr(self, 'prior_leak', None): - self.n_unique, paradigm_['n_ix'] = self._pair_index( - paradigm_['n'], paradigm[self.leak or self.prior_leak].values) + if self._uncued_col: + self.n_unique, paradigm_['n_ix'], swap_ix = self._index( + paradigm_['n'], paradigm[self._uncued_col].values) + if getattr(self, 'swap', None): + paradigm_['swap_ix'] = swap_ix if 'response' in paradigm.columns: r = paradigm['response'].values.astype(float) if np.any(np.isnan(r)): @@ -469,14 +495,56 @@ def _get_paradigm(self, paradigm=None, subject_mapping=None): paradigm_['censor'] = c return paradigm_ + @property + def _uncued_col(self): + return (getattr(self, 'leak', None) or getattr(self, 'prior_leak', None) + or getattr(self, 'response_pull', None) or getattr(self, 'swap', None)) + + @property + def _rows_path(self): + """Option table per (participant, n_u) pseudo-participant.""" + return bool(getattr(self, 'prior_leak', None) or getattr(self, 'response_pull', None)) + + def _index(self, n, u): + """(n_unique, n_ix, swap_ix) for trials with a second (uncued) magnitude u. + + swap_ix points at the table entry for the exchanged roles (stimulus u, other n); + it is None unless ``swap`` is set. + """ + n, u = np.asarray(n, float), np.asarray(u, float) + swap = getattr(self, 'swap', None) + if self._rows_path: + if not swap: + pairs, ix = self._pair_index(n, u) + return pairs, ix, None + # full grid on the union of values (n_u-major), so the swapped pair exists + v = np.unique(np.concatenate([n, u])) + V = len(v) + pairs = np.column_stack([np.tile(v, V), np.repeat(v, V)]) + ni, ui = np.searchsorted(v, n), np.searchsorted(v, u) + return pairs, ui * V + ni, ni * V + ui + if getattr(self, 'leak', None): + if not swap: + pairs, ix = self._pair_index(n, u) + return pairs, ix, None + pairs = np.unique(np.concatenate([np.column_stack([n, u]), np.column_stack([u, n])]), + axis=0) + key = {tuple(p): i for i, p in enumerate(pairs)} + ix = np.array([key[(a, b)] for a, b in zip(n, u)]) + sx = np.array([key[(b, a)] for a, b in zip(n, u)]) + return pairs, ix, sx + # swap only: per-magnitude table over the union of n and n_u + v = np.unique(np.concatenate([n, u])) + return v, np.searchsorted(v, n), np.searchsorted(v, u) + def _pair_index(self, n, u): """(K, 2) table of (n, n_u) and each trial's row in it. - leak only: the unique pairs. With prior_leak: the full grid, n_u-major + leak only: the unique pairs. With prior_leak / response_pull: the full grid, n_u-major (row = u_ix * N + n_ix), so the table can be computed per (participant, n_u). """ n, u = np.asarray(n, float), np.asarray(u, float) - if not getattr(self, 'prior_leak', None): + if not self._rows_path: pairs, ix = np.unique(np.column_stack([n, u]), axis=0, return_inverse=True) return pairs, np.asarray(ix).ravel() nv, n_ix = np.unique(n, return_inverse=True) @@ -593,7 +661,7 @@ def _option_table_grid(self, inputs, n_unique, S, shift_nu=None): then an (S, K, M) x (S, M, R) batched matmul instead of a per-trial (T, M, R) tensor (which made the motor-noise fits ~50x slower). """ - if getattr(self, 'prior_leak', None): + if self._rows_path: return self._option_table_prior_leak(inputs, n_unique, S) m, n_hat, alpha, nu_f = self.estimate_on_grid(inputs, S) nk = np.asarray(n_unique, dtype=float) @@ -636,9 +704,15 @@ def _option_table_prior_leak(self, inputs, n_unique, S): N, U = len(nv), len(uv) rows = {k: pt.repeat(v, U) for k, v in inputs.items()} # row s * U + u u_row = pt.as_tensor_variable(np.tile(uv, S)) - mu = rows['prior_mu'] - rows['prior_mu'] = mu + rows['prior_leak_k'] * (u_row - mu) + if getattr(self, 'prior_leak', None): + mu = rows['prior_mu'] + rows['prior_mu'] = mu + rows['prior_leak_k'] * (u_row - mu) m, n_hat, alpha, nu_f = self.estimate_on_grid(rows, S * U) # (SU, M) + centre = n_hat + if getattr(self, 'response_pull', None): + # report centre pulled towards n_u, weight ~ encoding s.d. in items at n_hat + w = rows['pull_k'][:, None] * (pt.maximum(n_hat, 1e-3) / 15.0) ** (1.0 - alpha[:, None]) + centre = n_hat + w * (u_row[:, None] - n_hat) fn = self._f(pt.as_tensor_variable(nv), alpha) # (SU, N) if getattr(self, 'leak', None): pick = pt.as_tensor_variable(np.tile(np.eye(U), (S, 1))) # (SU, U) @@ -654,12 +728,12 @@ def _option_table_prior_leak(self, inputs, n_unique, S): dens = dens / pt.sum(dens, axis=2, keepdims=True) # (SU, N, M) edges = pt.as_tensor_variable(self.response_edges) sig = rows['sigma_r'][:, None, None] - cdf = _norm_cdf((edges[None, None, :] - n_hat[:, :, None]) / sig) + cdf = _norm_cdf((edges[None, None, :] - centre[:, :, None]) / sig) p = pt.batched_dot(dens, cdf[:, :, 1:] - cdf[:, :, :-1]) # (SU, N, R) return p.reshape((S, U * N, p.shape[-1])) def trial_probabilities(self, inputs, n, subject_ix, S, n_ix=None, n_unique=None, - shift_nu=None): + shift_nu=None, swap_ix=None): """Per-trial option probabilities (T, R). Grid path: pass ``n_ix`` (index of each trial's magnitude into @@ -670,6 +744,10 @@ def trial_probabilities(self, inputs, n, subject_ix, S, n_ix=None, n_unique=None else: table = self._option_table_grid(inputs, n_unique, S, shift_nu) p = table[subject_ix, n_ix] + if getattr(self, 'swap', None): + ps = pt.sigmoid(inputs['swap_a'][subject_ix] + + inputs['swap_b'][subject_ix] * (n - 15.0) / 10.0)[:, None] + p = (1 - ps) * p + ps * table[subject_ix, swap_ix] if self.lapse: lam = inputs['p_lapse'][subject_ix][:, None] p = (1 - lam) * p + lam / len(self.response_options) @@ -729,7 +807,7 @@ def build_likelihood(self, parameters, save_p_choice=False): sub_ix = model['subject_ix'] n_ix = model['n_ix'] shift_nu = None - if (self.leak or self.prior_leak) and (self.measurement_shift or self.noise_modulator): + if self._uncued_col and (self.measurement_shift or self.noise_modulator): raise NotImplementedError('leak with trial covariates') if self.condition is not None: if self.measurement_shift or self.noise_modulator: @@ -759,7 +837,9 @@ def build_likelihood(self, parameters, save_p_choice=False): shift_nu = shift_rows[:, None] * zc_rows # (S, Z) n_ix = n_ix * self.n_covariate_bins + model['shift_bin'] p = self.trial_probabilities(inputs, model['n'], sub_ix, S, n_ix=n_ix, - n_unique=self.n_unique, shift_nu=shift_nu) + n_unique=self.n_unique, shift_nu=shift_nu, + swap_ix=model['swap_ix'] if getattr(self, 'swap', None) + else None) if save_p_choice: p = pm.Deterministic('p_response', p) if not getattr(self, 'censored', False): @@ -799,11 +879,14 @@ def predict_response_distribution(self, paradigm, parameters): inputs = {k: pt.as_tensor_variable(v) for k, v in arrs.items()} n = paradigm['n'].values.astype(float) n_unique, n_ix = np.unique(n, return_inverse=True) - if getattr(self, 'leak', None) or getattr(self, 'prior_leak', None): - n_unique, n_ix = self._pair_index(n, paradigm[self.leak or self.prior_leak].values) + swap_ix = None + if self._uncued_col: + n_unique, n_ix, swap_ix = self._index(n, paradigm[self._uncued_col].values) p = self.trial_probabilities(inputs, pt.as_tensor_variable(n), pt.as_tensor_variable(codes), len(uniques), n_ix=pt.as_tensor_variable(n_ix), - n_unique=n_unique).eval() + n_unique=n_unique, + swap_ix=None if swap_ix is None + else pt.as_tensor_variable(swap_ix)).eval() return pd.DataFrame(p, index=paradigm.index, columns=pd.Index(self.response_options.astype(int), name='response')) From 89e56edb9d6f9f667b046e9b00bbbc19fd2ad6e6 Mon Sep 17 00:00:00 2001 From: Gilles de Hollander Date: Sun, 1 Nov 2026 11:14:17 +0100 Subject: [PATCH 17/20] Pooled lapse option: EstimationTaskModel(lapse='pooled') / transform 'beta_pooled' -- one rate for all subjects, for datasets with lapses ~ 0 where the hierarchical Beta concentration is unidentified (centred funnel, NUTS saturates the tree depth); likelihood identical to the hierarchical model at equal rates Co-Authored-By: Claude Opus 5.5 --- bauer/core.py | 25 ++++++++++++++++++------- bauer/models/estimation_task.py | 8 ++++++-- 2 files changed, 24 insertions(+), 9 deletions(-) diff --git a/bauer/core.py b/bauer/core.py index aedc5fe..223cb09 100644 --- a/bauer/core.py +++ b/bauer/core.py @@ -265,13 +265,13 @@ def build_prior(self, name, mu_intercept=None, sigma_intercept=None, transform=' pm.Flat(name) elif transform == 'softplus': pm.HalfFlat(name) - elif transform in ('logistic', 'beta'): + elif transform in ('logistic', 'beta', 'beta_pooled'): pm.Uniform(name, lower=0, upper=1) else: raise NotImplementedError return - if transform == 'beta': + if transform in ('beta', 'beta_pooled'): # Single-subject Beta prior with the same small-mean / heavy-tail # shape used by the hierarchical 'beta' group prior (see # build_hierarchical_nodes). Concentration = beta_mu_kappa. @@ -819,7 +819,7 @@ def build_hierarchical_nodes(self, name, mu_intercept=None, sigma_intercept=None beta_kappa_sd=3.0, **kwargs): """Build a hierarchical (group_mu, group_sd, per-subject offset) node. - ``transform`` ∈ {'identity', 'softplus', 'logistic', 'beta'}. When + ``transform`` ∈ {'identity', 'softplus', 'logistic', 'beta', 'beta_pooled'}. When ``transform`` is 'softplus' and ``min_value > 0``, the transformed parameter has a hard lower bound: ``param = min_value + softplus(x)``. Used to keep e.g. the DDM/RDM threshold ``a`` away from the a→0 collapse @@ -856,6 +856,15 @@ def build_hierarchical_nodes(self, name, mu_intercept=None, sigma_intercept=None ``get_groupwise_parameter_estimates`` keeps working via ``{name}_mu``). """ + if transform == 'beta_pooled': + # one rate shared by all subjects (prior as the 'beta' group mean); for rates + # ~ 0 with little information per subject, where the hierarchical Beta's + # concentration (kappa) is unidentified and the centred p[s] | kappa funnels + group_mu = pm.Beta(f'{name}_mu', alpha=beta_mu_mean * beta_mu_kappa, + beta=(1.0 - beta_mu_mean) * beta_mu_kappa) + n_sub = len(pm.modelcontext(None).coords['subject']) + return pm.Deterministic(name, group_mu * pt.ones(n_sub), dims=('subject',)) + if transform == 'beta': a0 = beta_mu_mean * beta_mu_kappa b0 = (1.0 - beta_mu_mean) * beta_mu_kappa @@ -939,7 +948,9 @@ def get_groupwise_parameter_estimates(self, idata=None, parameters=None, include def _spread(par): if par + '_sd' in idata.posterior: return idata.posterior[par + '_sd'].to_dataframe() - return idata.posterior[par + '_kappa'].to_dataframe() + if par + '_kappa' in idata.posterior: + return idata.posterior[par + '_kappa'].to_dataframe() + return (0 * idata.posterior[par + '_mu']).to_dataframe() # pooled: no spread sd_pars = pd.concat([_spread(par) for par in self.free_parameters], axis=1, keys=self.free_parameters, names=['parameter']).droplevel(1, axis=1) pars = pd.concat((mu_pars, sd_pars), keys=['mu', 'sd'], names=['type'], axis=1) @@ -973,7 +984,7 @@ def sample_parameters_from_prior(self, n_subjects=None): if 'transform' not in pars.keys(): pars['transform'] = 'identity' - if pars['transform'] == 'beta': + if pars['transform'] in ('beta', 'beta_pooled'): mean = pars.get('beta_mu_mean', 0.05) kappa = pars.get('beta_mu_kappa', 8.0) samples_pars[key] = np.random.beta(mean * kappa, @@ -997,7 +1008,7 @@ def sample_parameters_from_prior(self, n_subjects=None): def forward_transform(self, data, parameter): transform = self.free_parameters[parameter]['transform'] - if transform in ('identity', 'beta'): + if transform in ('identity', 'beta', 'beta_pooled'): # 'beta' rates already live in (0, 1) — natural == sampling scale. return data elif transform == 'softplus': @@ -1008,7 +1019,7 @@ def forward_transform(self, data, parameter): def backward_transform(self, data, parameter): transform = self.free_parameters[parameter]['transform'] - if transform in ('identity', 'beta'): + if transform in ('identity', 'beta', 'beta_pooled'): return data elif transform == 'softplus': return inverse_softplus_np(data) diff --git a/bauer/models/estimation_task.py b/bauer/models/estimation_task.py index 147e3cd..1e76cf7 100644 --- a/bauer/models/estimation_task.py +++ b/bauer/models/estimation_task.py @@ -257,7 +257,10 @@ class EstimationTaskModel(EstimationBaseModel): index level for hierarchical fits. encoding_space : PowerSpace prior : UniformPrior or GaussianPrior - lapse : bool + lapse : bool or 'pooled' + True: per-subject lapse rate with a hierarchical Beta group prior; 'pooled': one + rate shared by all subjects (use when lapses are ~0 and the hierarchical + concentration is unidentified -- it funnels and saturates the NUTS tree depth). motor_noise : bool response_range : (int, int) Smallest and largest response option (inclusive integers, step 1). @@ -375,7 +378,8 @@ def get_free_parameters(self): pars['swap_b'] = dict(mu_intercept=0.0, sigma_intercept=1.0, cauchy_sigma_intercept=0.5, transform='identity') if self.lapse: - pars['p_lapse'] = dict(transform='beta', beta_mu_mean=0.05, beta_mu_kappa=8.0) + pars['p_lapse'] = dict(transform='beta_pooled' if self.lapse == 'pooled' else 'beta', + beta_mu_mean=0.05, beta_mu_kappa=8.0) return pars def get_model_inputs(self, parameters): From 247395073d5b784700fc97152a2c82a2f3f1557c Mon Sep 17 00:00:00 2001 From: Gilles de Hollander Date: Mon, 2 Nov 2026 10:17:19 +0100 Subject: [PATCH 18/20] Tests: uncued-magnitude terms (leak, prior_leak, response_pull, swap) and the pooled lapse reduce exactly to the plain model; swap probability 1 = exchanged roles Co-Authored-By: Claude Opus 5.5 --- tests/test_estimation_task.py | 61 ++++++++++++++++++++++++++++++++++- 1 file changed, 60 insertions(+), 1 deletion(-) diff --git a/tests/test_estimation_task.py b/tests/test_estimation_task.py index 74df01f..9b59350 100644 --- a/tests/test_estimation_task.py +++ b/tests/test_estimation_task.py @@ -4,7 +4,9 @@ * the closed-form path (log space + log-normal prior) agrees with the grid path; * a uniform prior compresses, more so with more noise; * alpha -> 0 of the power space reproduces the log space; -* simulate -> fit -> recover (single-subject MAP; hierarchical NUTS, ``slow``). +* simulate -> fit -> recover (single-subject MAP; hierarchical NUTS, ``slow``); +* the uncued-magnitude terms (leak, prior_leak, response_pull, swap) and the pooled lapse + reduce exactly to the plain model. """ import itertools import warnings @@ -357,3 +359,60 @@ def test_prior_gaussian_in_items(): k = np.arange(5, 25) w = np.exp(-.5 * ((k - 12.0) / 4.0) ** 2) np.testing.assert_allclose(nh[0, len(nh[0]) // 2], (w * k).sum() / w.sum(), atol=1e-2) + + +def _uncued_paradigm(seed=6): + par = make_paradigm(n_subjects=2, n_trials=100, seed=seed) + par['n_u'] = np.random.default_rng(seed + 1).integers(5, 25, len(par)) + return par + + +UNCUED_KW = dict(encoding_space=PowerSpace(), prior=TruncatedGaussianPrior(5, 24, space='n'), + motor_noise=True) + + +@pytest.mark.parametrize('term,zero', [ + ('leak', {'leak_w_mu': 0.0, 'leak_w_offset': np.zeros(2)}), + ('prior_leak', {'prior_leak_k_mu': 0.0, 'prior_leak_k_offset': np.zeros(2)}), + ('response_pull', {'pull_k_mu': 0.0, 'pull_k_offset': np.zeros(2)}), + ('swap', {'swap_a_mu': -60.0, 'swap_a_offset': np.zeros(2), + 'swap_b_mu': 0.0, 'swap_b_offset': np.zeros(2)}), +]) +def test_uncued_terms_reduce_to_plain_model(term, zero): + """leak / prior_leak / response_pull / swap at zero effect = the model without them.""" + par = _uncued_paradigm() + base = EstimationTaskModel(par, **UNCUED_KW) + base.build_estimation_model(par, hierarchical=True) + m = EstimationTaskModel(par, **{term: 'n_u'}, **UNCUED_KW) + m.build_estimation_model(par, hierarchical=True) + assert np.all(np.isfinite(m.estimation_model.compile_dlogp()( + m.estimation_model.initial_point()))) + np.testing.assert_allclose(_resp_logp_at(base, {}), _resp_logp_at(m, zero), rtol=1e-8) + + +def test_swap_probability_one_exchanges_roles(): + par = _uncued_paradigm(seed=8) + m = EstimationTaskModel(par, swap='n_u', **UNCUED_KW) + m.build_estimation_model(par, hierarchical=True) + swapped = par.copy() + swapped['n'], swapped['n_u'] = par['n_u'].values, par['n'].values + base = EstimationTaskModel(swapped, **UNCUED_KW) + base.build_estimation_model(swapped, hierarchical=True) + one = {'swap_a_mu': 60.0, 'swap_a_offset': np.zeros(2), + 'swap_b_mu': 0.0, 'swap_b_offset': np.zeros(2)} + np.testing.assert_allclose(_resp_logp_at(base, {}), _resp_logp_at(m, one), rtol=1e-8) + + +def test_pooled_lapse_equals_hierarchical_at_equal_rates(): + par = make_paradigm(n_subjects=3, n_trials=80, seed=9) + kw = dict(encoding_space=PowerSpace(), prior=TruncatedGaussianPrior(5, 24), motor_noise=True) + hier = EstimationTaskModel(par, **kw) + hier.build_estimation_model(par, hierarchical=True) + pooled = EstimationTaskModel(par, lapse='pooled', **kw) + pooled.build_estimation_model(par, hierarchical=True) + mod = pooled.estimation_model + assert 'p_lapse_kappa' not in mod.named_vars and 'p_lapse_log_kappa' not in mod.named_vars + assert np.all(np.isfinite(mod.compile_dlogp()(mod.initial_point()))) + x = np.log(.03 / .97) + np.testing.assert_allclose(_resp_logp_at(hier, {'p_lapse_logodds__': np.full(3, x)}), + _resp_logp_at(pooled, {'p_lapse_mu_logodds__': x}), rtol=1e-10) From e7b0dd606ef067149c324cc4b61d5bbfb4d0491c Mon Sep 17 00:00:00 2001 From: Gilles de Hollander Date: Mon, 2 Nov 2026 10:17:20 +0100 Subject: [PATCH 19/20] Release 0.5.2 Co-Authored-By: Claude Opus 5.5 --- CITATION.cff | 2 +- bauer/__init__.py | 2 +- pyproject.toml | 2 +- setup.cfg | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CITATION.cff b/CITATION.cff index 4bf6f7c..986913c 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -9,7 +9,7 @@ type: software license: MIT repository-code: "https://github.com/ruffgroup/bauer" url: "https://ruffgroup.github.io/bauer/" -version: "0.5.1" +version: "0.5.2" authors: - family-names: "de Hollander" given-names: "Gilles" diff --git a/bauer/__init__.py b/bauer/__init__.py index 70bfeaa..b91b610 100644 --- a/bauer/__init__.py +++ b/bauer/__init__.py @@ -2,4 +2,4 @@ __author__ = """Gilles de Hollander""" __email__ = 'giles.de.hollander@gmail.com' -__version__ = '0.5.1' +__version__ = '0.5.2' diff --git a/pyproject.toml b/pyproject.toml index 267da0c..59c1485 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "bauer" -version = "0.5.1" +version = "0.5.2" description = "Bayesian Estimation of Perceptual, Numerical and Risky Choice" authors = [{ name = "Gilles de Hollander", email = "gilles.de.hollander@gmail.com" }] license = { text = "MIT" } diff --git a/setup.cfg b/setup.cfg index 55b0894..a0ee44b 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 0.5.1 +current_version = 0.5.2 commit = True tag = True From 8f36eebd994189c5b5696568530d817aee32a7ff Mon Sep 17 00:00:00 2001 From: Gilles de Hollander Date: Mon, 2 Nov 2026 11:42:19 +0100 Subject: [PATCH 20/20] Speed up the slow EstimationTaskModel NUTS recovery test: numpyro, 60 x 80 grid, 250 trials, 2 x 50 draws (~1.5 min locally; ~1 h on CI before, same recovery r > .95) Co-Authored-By: Claude Opus 5.5 --- tests/test_estimation_task.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/tests/test_estimation_task.py b/tests/test_estimation_task.py index 9b59350..efc9fb4 100644 --- a/tests/test_estimation_task.py +++ b/tests/test_estimation_task.py @@ -135,16 +135,18 @@ def test_single_subject_map_recovery(space): @pytest.mark.slow def test_hierarchical_nuts_recovery_free_alpha(): - par = make_paradigm(n_subjects=6, n_trials=400, seed=5) + # kept small so it runs in ~1.5 min (60 x 80 grid, 2 x 50 numpyro draws); 400 trials, + # a 120 x 150 grid and 2 x 300 pymc draws took about an hour on CI for the same answer + par = make_paradigm(n_subjects=6, n_trials=250, seed=5) rng = np.random.default_rng(6) truth = pd.DataFrame({'nu': rng.uniform(0.2, 0.5, 6), 'alpha': rng.uniform(-0.2, 1.0, 6), 'p_lapse': rng.uniform(0.01, 0.05, 6)}, index=pd.Index(np.arange(1, 7), name='subject')) - m = EstimationTaskModel(par, encoding_space=PowerSpace(), n_measurement_grid=120, - n_hypothesis_grid=150) - table, idata = m.parameter_recovery(par, truth, rng=7, draws=300, tune=300, chains=2, - cores=1, target_accept=0.9, progressbar=False, - random_seed=1) + m = EstimationTaskModel(par, encoding_space=PowerSpace(), n_measurement_grid=60, + n_hypothesis_grid=80) + table, idata = m.parameter_recovery(par, truth, rng=7, draws=50, tune=50, chains=2, + backend='numpyro', target_accept=0.8, + progressbar=False, random_seed=1) assert np.corrcoef(table['true']['nu'], table['recovered']['nu'])[0, 1] > 0.8 assert np.corrcoef(table['true']['alpha'], table['recovered']['alpha'])[0, 1] > 0.6