Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CITATION.cff
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ type: software
license: MIT
repository-code: "https://github.com/ruffgroup/bauer"
url: "https://ruffgroup.github.io/bauer/"
version: "0.5.2"
version: "0.6.0"
authors:
- family-names: "de Hollander"
given-names: "Gilles"
Expand Down
25 changes: 25 additions & 0 deletions HISTORY.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,31 @@
History
=======

0.6.0 (unreleased)
------------------

Tools for repeated-measures designs (conditions, drugs, sessions) and for reading
out any fit:

* ``bauer.models.ReproductionModel`` / ``ReproductionRegressionModel``: log-space
Bayesian observer for magnitude reproduction (e.g. interval timing); the response
SD is the SD of the posterior mean, ``w * nu``.
* Posterior summaries in long format (``bauer.utils``): ``summarize_posterior``
(posterior mean, 95% HDI, P(> 0)), ``contrast_draws`` (per-draw differences from a
reference level), ``posterior_draws``, and ``RegressionModel.conditionwise_draws``
(natural-scale draws per condition).
* Posterior predictive summaries: ``ppc_summary`` / ``ppc_observed`` (within subject,
then across subjects, per sample) and ``ppc_coverage``.
* Plots: ``plot_forest`` (group level), ``plot_sorted_forest`` (subject level),
``plot_ppc_panels``, ``plot_ppc_overlay``, ``plot_subject_ppc``,
``set_house_style``; and ``convergence_report`` (r-hat, ESS, divergences, verdict).
* Fixes: ``*LapseRegressionModel`` built ``p_lapse`` as an untransformed Normal that
could leave (0, 1) (since 0.3.0); it now uses a logit-normal group prior. Re-fit
lapse-regression fits made with 0.3.0-0.5.x. Rank-deficient regression designs
now raise instead of fitting silently.

See :ref:`summarising-posteriors` in the usage page, and tutorial lesson 1.

0.5.0 (2026-10-18)
------------------

Expand Down
2 changes: 1 addition & 1 deletion bauer/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@

__author__ = """Gilles de Hollander"""
__email__ = 'giles.de.hollander@gmail.com'
__version__ = '0.5.2'
__version__ = '0.6.0'
115 changes: 109 additions & 6 deletions bauer/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -1052,7 +1052,22 @@ def get_model_inputs(self, parameters):
BaseModel.__init__ = _translate_deprecated_kwargs(BaseModel.__init__)


def _lapse_param_spec(group, mu_mean, mu_kappa, kappa_sd):
def _effective_lapse_group(model):
"""The lapse group prior actually used for ``model``.

The hierarchical-Beta prior is built by ``BaseModel.build_hierarchical_nodes``;
``RegressionModel`` builds every parameter through a design matrix on the
untransformed scale and has no Beta branch. Before this guard, a
``*LapseRegressionModel`` with the (default) Beta group silently got an
untransformed ``Normal(0, 0.5)`` lapse rate that could leave (0, 1).
Regression models therefore always use the logit-Normal group prior.
"""
if isinstance(model, RegressionModel) and model.lapse_group == 'beta':
return 'logit_normal'
return model.lapse_group


def _lapse_param_spec(group, mu_mean, mu_kappa, kappa_sd, regression=False):
"""Free-parameter spec dict for a lapse / outlier rate in (0, 1).

``group='logit_normal'`` (default) reproduces the historical logit-Normal
Expand All @@ -1068,7 +1083,15 @@ def _lapse_param_spec(group, mu_mean, mu_kappa, kappa_sd):
'beta_mu_kappa': mu_kappa,
'beta_kappa_sd': kappa_sd}
elif group == 'logit_normal':
return {'mu_intercept': logit_np(mu_mean), 'transform': 'logistic'}
spec = {'mu_intercept': logit_np(mu_mean), 'transform': 'logistic'}
if regression:
# Lapse rates differ a lot between people (2% vs 15% is common).
# The regression path's default between-subject SD prior on the
# logit (HalfNormal(0.25)) shrinks a 15% lapser towards the group
# mean, and the model then explains their random answers with
# extra noise (inflated nu / evidence_sd). Widen it.
spec.update(sigma_intercept=1.0, cauchy_sigma_intercept=1.0)
return spec
raise ValueError(
f"lapse_group must be 'logit_normal' or 'beta', got {group!r}.")

Expand All @@ -1091,10 +1114,11 @@ class LapseModel(BaseModel):
def get_free_parameters(self):
pars = super().get_free_parameters()

pars['p_lapse'] = _lapse_param_spec(self.lapse_group,
pars['p_lapse'] = _lapse_param_spec(_effective_lapse_group(self),
self.lapse_mu_mean,
self.lapse_mu_kappa,
self.lapse_kappa_sd)
self.lapse_kappa_sd,
regression=isinstance(self, RegressionModel))
return pars

def _get_choice_predictions(self, model_inputs):
Expand Down Expand Up @@ -1210,10 +1234,11 @@ def get_free_parameters(self):
if isinstance(self.p_outlier, (int, float)):
# Fixed contaminant rate (HSSM default): not a free parameter.
return pars
spec = _lapse_param_spec(self.lapse_group,
spec = _lapse_param_spec(_effective_lapse_group(self),
self.lapse_mu_mean,
self.lapse_mu_kappa,
self.lapse_kappa_sd)
self.lapse_kappa_sd,
regression=isinstance(self, RegressionModel))
if self.lapse_group == 'logit_normal':
# Preserve the historical sigma_intercept=0.5 on the logit prior.
spec['sigma_intercept'] = 0.5
Expand Down Expand Up @@ -1251,6 +1276,24 @@ def _mix_with_lapse(self, ll_model, p_outlier):
return pt.logaddexp(mixed, pt.constant(np.log(1e-29)))


def _check_full_rank(dm, parameter, formula):
"""Raise if a parameter's design matrix is rank-deficient.

A rank-deficient design (e.g. ``C(condition) + C(session)`` when baseline
is always session 1) is not identified: the sampler wanders along a flat
ridge and never converges. Better to fail before sampling.
"""
X = np.asarray(dm, dtype=float)
rank = np.linalg.matrix_rank(X)
if rank < X.shape[1]:
raise ValueError(
f"Design matrix for {parameter!r} (formula {formula!r}) is rank-deficient: "
f"{X.shape[1]} columns {list(dm.design_info.column_names)} but rank {rank}. "
"Some terms are perfectly confounded (e.g. a condition that only ever "
"occurs in one session). Drop or recode a term, e.g. a linear session "
"trend instead of C(session).")


class RegressionModel(BaseModel):

def __init__(self, regressors=None, fixed_regressors=None,
Expand Down Expand Up @@ -1302,6 +1345,7 @@ def _get_paradigm(self, paradigm=None, subject_mapping=None):

for key in free_parameters:
dm = self.build_design_matrix(paradigm, key)
_check_full_rank(dm, key, self.regressors.get(key, '1'))
self.design_matrices[key] = dm
paradigm_[f'_dm_{key}'] = np.asarray(dm)
self._compute_random_cols(paradigm, key, dm)
Expand Down Expand Up @@ -1353,6 +1397,20 @@ def _compute_random_cols(self, data, parameter, fixed_dm):
"between-subject variance heteroscedastic. Put it only "
"in fixed_regressors unless this is intended.",
UserWarning, stacklevel=2)
# Within-subject identifiability of the random effects: if no
# subject's own rows span the random columns, the per-subject
# coefficients are separated only by the prior.
arr_r = np.asarray(fixed_dm)[:, cols]
ranks = [np.linalg.matrix_rank(arr_r[subj == s]) for s in np.unique(subj)]
if len(cols) and max(ranks) < len(cols):
names = [fixed_names[j] for j in cols]
warnings.warn(
f"Random effects on {names} for {parameter!r} are not identified within "
f"any subject (per-subject rank {max(ranks)} < {len(cols)}): each subject's "
"data cannot separate them, only the prior does. Typical cause: a "
"condition and a session trend that are fully crossed within subject "
"(one condition per session). Keep the confounded term (e.g. session_c) "
"in fixed_regressors only.", UserWarning, stacklevel=2)
self._random_cols[parameter] = cols

def rebuild_design_matrix(self, paradigm, parameter):
Expand Down Expand Up @@ -1608,6 +1666,51 @@ def sample_parameters_from_prior(self, paradigm, n_subjects=None):
else:
return samples_pars

def conditionwise_draws(self, idata, conditions, parameters=None, group=True):
"""Posterior draws of each parameter per condition, natural scale, long format.

Parameters
----------
conditions : pd.DataFrame
One row per condition, with every column the regression formulas use
(e.g. ``condition`` and ``session_c=0`` for "an average session").
parameters : list of str, optional
Subset of free parameters (default: all).
group : bool
True: group-level (``{par}_mu``) values. False: every subject.

Returns
-------
pd.DataFrame with columns ``parameter, chain, draw, [subject,]`` the
``conditions`` columns, and ``value``. Feed it to
:func:`bauer.utils.summarize_posterior` and the forest plots.
"""
if isinstance(parameters, str):
parameters = [parameters]
if parameters is not None:
unknown = sorted(set(parameters) - set(self.get_free_parameters()))
if unknown:
raise ValueError(f'Unknown parameter(s) {unknown}; free parameters are '
f'{list(self.get_free_parameters())}')
if conditions.duplicated().any():
raise ValueError('`conditions` has duplicate rows; every row should be a different '
'condition.')
est = self.get_conditionwise_parameters(idata, conditions, group=group)
if parameters is not None:
est = est.loc[[p for p in est.index.unique('parameter') if p in parameters]]
# Columns are the condition rows (one level per conditions column).
# Build the long frame explicitly: rows x condition-columns.
rows = est.index.to_frame(index=False)
n_rows, n_cols = est.shape
long = rows.loc[np.repeat(np.arange(n_rows), n_cols)].reset_index(drop=True)
cond = conditions.reset_index(drop=True)
cond_rep = cond.loc[np.tile(np.arange(n_cols), n_rows)].reset_index(drop=True)
long = pd.concat([long, cond_rep], axis=1)
long['value'] = est.values.ravel()
if parameters is not None:
long = long[long['parameter'].isin(parameters)].reset_index(drop=True)
return long

def get_conditionwise_parameters(self, idata, conditions, group=True):

parameter_values = []
Expand Down
1 change: 1 addition & 0 deletions bauer/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
PowerLawNoiseComparisonModel, PowerLawNoiseComparisonRegressionModel,
PowerLawEncodingComparisonModel, PowerLawEncodingComparisonRegressionModel,
)
from .reproduction import ReproductionModel, ReproductionRegressionModel
from .risky_choice import (
RiskModelProbabilityDistortion, ProspectTheoryModel,
LossAversionModel, LossAversionRegressionModel,
Expand Down
6 changes: 4 additions & 2 deletions bauer/models/psychophysics.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,10 @@ class PsychophysicalLapseModel(LapseModel, PsychophysicalModel):
class PsychophysicalRegressionModel(RegressionModel, PsychophysicalModel):
"""PsychophysicalModel with patsy formula regression on nu and/or bias."""

def __init__(self, paradigm, regressors, save_trialwise_estimates=False):
RegressionModel.__init__(self, regressors)
def __init__(self, paradigm, regressors=None, save_trialwise_estimates=False,
fixed_regressors=None, random_regressors=None):
RegressionModel.__init__(self, regressors, fixed_regressors=fixed_regressors,
random_regressors=random_regressors)
PsychophysicalModel.__init__(self, paradigm)


Expand Down
Loading
Loading