diff --git a/CHANGELOG.md b/CHANGELOG.md index 306a71a..213edf3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,66 @@ All notable changes to **bauer** are documented here. This project loosely follows [Keep a Changelog](https://keepachangelog.com/) and semantic versioning. +## 0.5.2 (2026-11-02) + +A new observer model for magnitude *estimation* (a slider / integer response +scale), `bauer.models.EstimationTaskModel`, developed for the retinonumeral +paper (two simultaneous numerosities, one cued for report). No changes to +existing models; the only change to shared code is a new `beta_pooled` +transform in `bauer.core.build_hierarchical_nodes`. + +### Added +- `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. +- `EstimationTaskModel` extensions: + - `TruncatedGaussianPrior(lo, hi, discrete=True, space='internal'|'n')` + (prior restricted to the known task bounds; `space='n'` = Gaussian in + items, independent of alpha) and a discrete `UniformPrior`; + - censored responses (per-trial `censor` column, -1 / 0 / +1, e.g. + time-outs at the slider ends); + - `condition=, condition_parameters=(...)`: two-level condition + offsets (e.g. cued side) on chosen parameters; + - single-trial covariates: `measurement_shift` (shifts the measurement + mean) and `noise_modulator` (scales the encoding noise per trial; the + observer decodes with its trial noise); + - the influence of a second, uncued magnitude (`n_u`, a column): + `leak` (measurement centred on (1 - w) f(n) + w f(n_u)), `prior_leak` + (prior centre shifted towards n_u), `response_pull` (report centre pulled + towards n_u, weight growing with the encoding noise) and `swap` + (occasionally reporting the other magnitude, rate may depend on n). + Each reduces exactly to the plain model when its parameter is 0; + - `lapse='pooled'`: one lapse rate shared by all subjects (new + `beta_pooled` transform). Use it when lapses are near zero: the + hierarchical Beta concentration is then unidentified and NUTS funnels + (in one dataset 26 min -> >24 h with raised `target_accept`; pooled: + 21-45 min, 0 divergences, identical other parameters); + - grid likelihood computed per unique magnitude (or magnitude pair) and + gathered per trial; 600-point measurement grid by default without + motor noise. +- `tests/test_estimation_task.py` covers the extensions (each reduces to the + plain model, swap probability 1 = exchanged roles, pooled lapse = the + hierarchical model at equal rates). + ## 0.5.1 (2026-10-26) ### Fixed @@ -41,6 +101,7 @@ follows [Keep a Changelog](https://keepachangelog.com/) and semantic versioning. - `ppc` / `posterior_predicted_moments` compile the trial density once and swap parameter values per draw (~0.1 s per draw instead of ~2 s). +||||||| d338120 ## 0.5.0 (2026-10-18) The headline of this release is a much-extended `bauer.efficient_coding` 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/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/__init__.py b/bauer/models/__init__.py index 596e2a7..86c46ab 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, TruncatedGaussianPrior, +) diff --git a/bauer/models/estimation_task.py b/bauer/models/estimation_task.py new file mode 100644 index 0000000..1e76cf7 --- /dev/null +++ b/bauer/models/estimation_task.py @@ -0,0 +1,967 @@ +""" +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. ``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 +---------------------------------------------- +* **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). + +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 +------- +>>> 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. + + ``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, discrete=False): + self.lo, self.hi, self.discrete = float(lo), float(hi), bool(discrete) + + def __repr__(self): + 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). 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). ``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`` + 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, 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}, ' + f'space={self.space!r})') + + +# Alias in the spirit of the docs (log-normal when the space is log) +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 +# ============================================================================ + +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 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). + 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=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, 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 + 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 + # 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) + 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 + 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) + 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 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, 'prior_leak', None) + and not getattr(self, 'response_pull', None) + and not getattr(self, 'swap', None)) + + # ------------------------------------------------------------------ + 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) 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, + 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 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 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 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_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): + 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 + 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.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) + + 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) + 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) + 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 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)): + 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) + 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_ + + @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 / 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 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) + 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. + + 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 + # ------------------------------------------------------------------ + 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) + 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 = 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 + # 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, :]) + logmask + 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_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 + 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). + """ + 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) + 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] + 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] + cdf = _norm_cdf(z) + return cdf[:, :, 1:] - cdf[:, :, :-1] + # motor noise: integrate the measurement density over the grid + 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.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)) + 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) + 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, :] - 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, swap_ix=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: + 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) + 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 _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 + sub_ix = model['subject_ix'] + n_ix = model['n_ix'] + shift_nu = None + 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: + 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 + 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, + 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): + 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),()->()', dtype='int64', + 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()} + n = paradigm['n'].values.astype(float) + n_unique, n_ix = np.unique(n, return_inverse=True) + 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, + 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')) + + 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].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')) + 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/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 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 diff --git a/tests/test_estimation_task.py b/tests/test_estimation_task.py new file mode 100644 index 0000000..efc9fb4 --- /dev/null +++ b/tests/test_estimation_task.py @@ -0,0 +1,420 @@ +"""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``); +* the uncued-magnitude terms (leak, prior_leak, response_pull, swap) and the pooled lapse + reduce exactly to the plain model. +""" +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, TruncatedGaussianPrior) + + +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, + 'truncated': lambda: TruncatedGaussianPrior(5, 24)} + + +@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 in ('gaussian', 'truncated'): + 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(): + # 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=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 + + +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))) + + +@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) + + +# --------------------------------------------------------------------------- +# 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']) + + +@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 + + +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) + + +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 + + +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) + + +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)