API Reference¶
Core¶
- class bauer.core.BaseModel(paradigm, save_trialwise_n_estimates=False)[source]¶
Bases:
object- build_hierarchical_nodes(name, mu_intercept=None, sigma_intercept=None, cauchy_sigma_intercept=None, transform='identity', min_value=0.0, beta_mu_mean=0.05, beta_mu_kappa=8.0, beta_kappa_sd=3.0, **kwargs)[source]¶
Build a hierarchical (group_mu, group_sd, per-subject offset) node.
transform∈ {‘identity’, ‘softplus’, ‘logistic’, ‘beta’, ‘beta_pooled’}. Whentransformis ‘softplus’ andmin_value > 0, the transformed parameter has a hard lower bound:param = min_value + softplus(x). Used to keep e.g. the DDM/RDM thresholdaaway from the a→0 collapse mode.Hierarchical-Beta group prior (
transform='beta')¶A per-subject rate in
(0, 1)whose population density is concentrated near 0 with a heavy upper tail — the “1/x”-like shape — for parameters such as a lapse / outlier rate, where most subjects are ≈ 0 but a minority genuinely lapse a lot. This replaces the logit-Normal parameterization (transform='logistic'), which funnels when the true rate ≈ 0: the per-subject logit → −∞, the group SD inflates without bound, and NUTS diverges.The model is:
mu ~ Beta(beta_mu_mean·beta_mu_kappa, (1-beta_mu_mean)·beta_mu_kappa) kappa = 2 + exp(log_kappa), log_kappa ~ Normal(0, beta_kappa_sd) p[s] ~ Beta(alpha, beta), alpha = mu·kappa, beta = (1-mu)·kappa
muis the group-mean rate (prior meanbeta_mu_mean, default 0.05);kappais the population concentration. The per-subject density is∝ p^(alpha-1)(1-p)^(beta-1): whenalpha = mu·kappa < 1(smallmu) this is an integrable spike at 0 (the “1/x” shape) with a fat upper tail, exactly matching “most subjects ≈ 0, a few disengaged”. Thekappa = 2 + exp(...)floor keepsbeta = (1-mu)·kappa > 1so the density is bounded near 1 (no spurious upper-edge spike) while still allowingalpha < 1.p[s]is sampled directly as apm.Beta, whose default log-odds transform gives NUTS a clean unconstrained geometry without the logit funnel (the per-subject scale is set by the data-informed Beta, not a shared inflating SD). Group nodes{name}_muand{name}_kappaare exposed for reporting (soget_groupwise_parameter_estimateskeeps working via{name}_mu).
- fit_map_individual(data=None, flat_prior=True, **kwargs)[source]¶
Fit MLE/MAP estimates for each subject independently (no pooling).
Loops over subjects, builds a non-hierarchical model on each subject’s data alone, and returns a DataFrame of point estimates in natural (transformed) scale.
- Parameters:
data (pd.DataFrame or None) – Trial-level data with a ‘subject’ index level. If None, uses
self.paradigm.flat_prior (bool) – If True (default), uses a very wide prior (sigma=100), making this effectively maximum-likelihood estimation. If False, uses the model’s default prior.
**kwargs – Forwarded to
pm.find_MAP.
- Returns:
Index = subject, columns = free parameter names (transformed scale).
- Return type:
pd.DataFrame
- get_initial_points(chains=4, jitter_frac=0.1, use_map=True, n_prior=500, seed=None)[source]¶
Dispersed per-chain starting points for the sampler.
Returns a list of
chainsinitval dicts (keyed by the model’s free-RV value-variable names). Each is a plausible centre plus per-parameter Gaussian jitter whose SD isjitter_fractimes that parameter’s prior SD. Chains are dispersed around the centre — never all placed at it — so the mode (which is not in the typical set) is not the start, and between-chain r̂ stays meaningful.- centre
find_MAP(the data-informed posterior mode / plausible value) whenuse_map; otherwise the model’s prior-centralinitial_point(). Falls back toinitial_point()if MAP fails.- jitter scale
Each free parameter is a plain unconstrained Normal in bauer’s models (softplus/logistic links are applied downstream as Deterministics), so prior draws live in the same space as the initvals and their SD is a natural, safe jitter scale.
Mirrors the init strategy HSSM uses (curated centre + small jitter) — which bauer otherwise omits, leaving convergence of hard posteriors a seed lottery.
- ppc(paradigm, idata, n_posterior_samples=200, out_of_sample=False, random_seed=None, progressbar=True)[source]¶
Posterior-predictive choices for
paradigm.- Returns:
Index:
paradigm.indexlevels +ppc_sample. Single columnsimulated_choice(bool). Format matchesDDMMixin.ppc/RaceMixin.ppcso all bauer models can be fed into the same downstream summarizers.- Return type:
pd.DataFrame
- sample(draws=1000, tune=1000, target_accept=0.8, chains=4, backend='pymc', find_init=None, **kwargs)[source]¶
Sample from the posterior using the requested NUTS backend.
- Parameters:
backend ({'pymc', 'numpyro', 'blackjax'}) – ‘pymc’ uses
pm.sample()(default). ‘numpyro’ / ‘blackjax’ use the corresponding JAX-NUTS sampler frompm.sampling.jax. JAX backends are much faster on GPU.chains (int) – Number of chains. Default 4.
target_accept (float) – NUTS target acceptance probability. 0.8 is fine for well-behaved models; 0.95 for hierarchical / DDM-like ones; 0.99 only if divergences persist.
draws (int) – Posterior and warmup draws per chain.
tune (int) – Posterior and warmup draws per chain.
find_init ({None, 'mapjitter', 'priorjitter', 'pathfinder'}) – Starting-point strategy.
Noneuses the class default (recommended_init;'mapjitter'for DDM/Race).'mapjitter'= MAP centre + prior-scaled jitter;'priorjitter'= prior-central centre + jitter;'pathfinder'= seed each chain from a multipath Pathfinder draw (variational; lands in the typical set — best for nasty high-dimensional DDM geometries, needspymc_extras, falls back to'mapjitter'if unavailable). Ignored ifinitvalsis passed in**kwargs.**kwargs –
Forwarded to the underlying sampler. Notably:
pymc backend:
init=(e.g. ‘jitter+adapt_full’ for dense mass adaptation),cores=,random_seed=.JAX backends:
nuts_kwargs={'dense_mass': True},chain_method='vectorized',random_seed=.
defaults (Auto-applied)
---------------------
via (Subclasses can declare strongly-correlated posteriors)
this (recommended_pymc_init and recommended_nuts_kwargs;)
kwarg (method applies them unless the user passes the corresponding)
mass-matrix (explicitly. DDMMixin / RaceMixin do this for full)
adaptation.
- class bauer.core.LapseModel(paradigm, save_trialwise_n_estimates=False)[source]¶
Bases:
BaseModelStatic-choice model with a per-subject random-lapse rate
p_lapse.lapse_groupselects the group prior on the per-subject lapse rate:'logit_normal'(legacy opt-in; Beta is now the default) or'beta'(the heavy-tailed “1/x”-like hierarchical Beta; seeBaseModel.build_hierarchical_nodes()). The Beta option is preferable when most subjects lapse ≈ 0 (it avoids the logit funnel).
- class bauer.core.RegressionModel(regressors=None, fixed_regressors=None, random_regressors=None)[source]¶
Bases:
BaseModel- build_hierarchical_nodes(name, mu_intercept=0.0, sigma_intercept=None, cauchy_sigma_intercept=None, sigma_regressors=1.0, cauchy_sigma_regressors=0.25, transform='identity', min_value=0.0, **kwargs)[source]¶
Build a hierarchical (group_mu, group_sd, per-subject offset) node.
transform∈ {‘identity’, ‘softplus’, ‘logistic’, ‘beta’, ‘beta_pooled’}. Whentransformis ‘softplus’ andmin_value > 0, the transformed parameter has a hard lower bound:param = min_value + softplus(x). Used to keep e.g. the DDM/RDM thresholdaaway from the a→0 collapse mode.Hierarchical-Beta group prior (
transform='beta')¶A per-subject rate in
(0, 1)whose population density is concentrated near 0 with a heavy upper tail — the “1/x”-like shape — for parameters such as a lapse / outlier rate, where most subjects are ≈ 0 but a minority genuinely lapse a lot. This replaces the logit-Normal parameterization (transform='logistic'), which funnels when the true rate ≈ 0: the per-subject logit → −∞, the group SD inflates without bound, and NUTS diverges.The model is:
mu ~ Beta(beta_mu_mean·beta_mu_kappa, (1-beta_mu_mean)·beta_mu_kappa) kappa = 2 + exp(log_kappa), log_kappa ~ Normal(0, beta_kappa_sd) p[s] ~ Beta(alpha, beta), alpha = mu·kappa, beta = (1-mu)·kappa
muis the group-mean rate (prior meanbeta_mu_mean, default 0.05);kappais the population concentration. The per-subject density is∝ p^(alpha-1)(1-p)^(beta-1): whenalpha = mu·kappa < 1(smallmu) this is an integrable spike at 0 (the “1/x” shape) with a fat upper tail, exactly matching “most subjects ≈ 0, a few disengaged”. Thekappa = 2 + exp(...)floor keepsbeta = (1-mu)·kappa > 1so the density is bounded near 1 (no spurious upper-edge spike) while still allowingalpha < 1.p[s]is sampled directly as apm.Beta, whose default log-odds transform gives NUTS a clean unconstrained geometry without the logit funnel (the per-subject scale is set by the data-informed Beta, not a shared inflating SD). Group nodes{name}_muand{name}_kappaare exposed for reporting (soget_groupwise_parameter_estimateskeeps working via{name}_mu).
- conditionwise_draws(idata, conditions, parameters=None, group=True)[source]¶
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.
conditionandsession_c=0for “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,]theconditionscolumns, andvalue. Feed it tobauer.utils.summarize_posterior()and the forest plots.
Psychophysical models¶
- class bauer.models.PsychophysicalModel(paradigm=None)[source]¶
Bases:
BaseModelPsychophysical model for two-alternative forced choice with a sensitivity and bias parameter.
Parameters
nu(discrimination sensitivity, softplus-transformed) andbias(decision criterion) describe the probability of choosing option 2 given stimuli x1 and x2. Paradigm requires columnsx1,x2, andchoice.nuandbiasare in the raw units ofx, while the default priors (notably the HalfNormal(0.25) group-SD prior) assume order-1 parameters. Standardize x so that x2 - x1 is of order 1 (e.g. divide by its SD); otherwise hierarchical shrinkage is near-total (large units) or absent (small units). A warning is raised when this looks off.
- class bauer.models.PsychophysicalLapseModel(paradigm=None)[source]¶
Bases:
LapseModel,PsychophysicalModelPsychophysicalModel extended with a lapse rate parameter.
- class bauer.models.PsychophysicalRegressionModel(paradigm, regressors=None, save_trialwise_estimates=False, fixed_regressors=None, random_regressors=None)[source]¶
Bases:
RegressionModel,PsychophysicalModelPsychophysicalModel with patsy formula regression on nu and/or bias.
- class bauer.models.PsychophysicalLapseRegressionModel(paradigm, regressors=None, save_trialwise_estimates=False, fixed_regressors=None, random_regressors=None)[source]¶
Bases:
LapseModel,PsychophysicalRegressionModelPsychophysicalModel with both a lapse rate and patsy formula regression.
Magnitude comparison models¶
- class bauer.models.MagnitudeComparisonModel(paradigm=None, fit_prior=False, fit_separate_evidence_sd=None, memory_model='independent', save_trialwise_n_estimates=False, fit_prior_mu_only=False, flat_observer_prior=False)[source]¶
Bases:
BaseModelBayesian observer model for two-alternative magnitude comparison (e.g. numerosity).
Choices between quantities n1 and n2 are modelled as Bayesian inference over log-scale representations corrupted by Gaussian noise. The prior is either estimated from the stimulus distribution (
fit_prior=False) or treated as free parameters.- Parameters:
paradigm (pd.DataFrame, optional) – Must contain columns
n1,n2, andchoice.fit_prior (bool) – If True, fit
prior_muandprior_sdas free parameters.fit_separate_evidence_sd (bool) – If True, fit separate noise parameters for n1 and n2 (or perceptual/memory noise when
memory_model='shared_perceptual_noise').memory_model ({'independent', 'shared_perceptual_noise'}) – Noise structure.
'independent'fits n1_evidence_sd and n2_evidence_sd separately.'shared_perceptual_noise'decomposes into perceptual and memory noise.
- class bauer.models.MagnitudeComparisonLapseModel(paradigm=None, fit_prior=False, fit_separate_evidence_sd=None, memory_model='independent', save_trialwise_n_estimates=False, fit_prior_mu_only=False, flat_observer_prior=False)[source]¶
Bases:
LapseModel,MagnitudeComparisonModelMagnitudeComparisonModel extended with a lapse rate parameter.
- class bauer.models.MagnitudeComparisonRegressionModel(paradigm, regressors=None, fit_prior=False, fit_separate_evidence_sd=None, memory_model='independent', save_trialwise_estimates=False, fixed_regressors=None, random_regressors=None)[source]¶
Bases:
RegressionModel,MagnitudeComparisonModelMagnitudeComparisonModel with patsy formula regression on noise/prior parameters.
- class bauer.models.MagnitudeComparisonLapseRegressionModel(paradigm, regressors=None, fit_prior=False, fit_separate_evidence_sd=None, memory_model='independent', save_trialwise_estimates=False, fixed_regressors=None, random_regressors=None)[source]¶
Bases:
LapseModel,MagnitudeComparisonRegressionModelMagnitudeComparisonModel with both a lapse rate and patsy formula regression.
- class bauer.models.FlexibleNoiseComparisonModel(paradigm, fit_separate_evidence_sd=True, fit_prior=False, spline_order=5, memory_model='independent', fit_prior_mu_only=False, flat_observer_prior=False)[source]¶
Bases:
BaseModelMagnitude comparison model with stimulus-dependent noise parameterised by a polynomial spline.
Unlike
MagnitudeComparisonModel, evidence noise is modelled as a polynomial function of log-magnitude, allowing the noise level to vary smoothly with stimulus size.- Parameters:
paradigm (pd.DataFrame) – Must contain columns
n1,n2, andchoice.spline_order (int or tuple of int) – Order(s) of the polynomial for the noise curve (one per prospect when
fit_separate_evidence_sd=True).memory_model ({'independent', 'shared_perceptual_noise'}) – Noise decomposition; see
MagnitudeComparisonModel.
- make_dm(x, variable='n1_evidence_sd')[source]¶
Evaluate the spline basis at
xusing the design_info that was fixed at construction time (anchored to the paradigm column for this variable). Knot positions DO NOT depend onx— they were determined once when the model was instantiated. Pass any x array (training data, a linspace for plotting, a few selected points for tabulation) and you’ll get the basis evaluated against the same fixed knots.
- class bauer.models.FlexibleNoiseComparisonRegressionModel(paradigm, regressors, fit_separate_evidence_sd=True, fit_prior=False, spline_order=5, memory_model='independent')[source]¶
Bases:
RegressionModel,FlexibleNoiseComparisonModelFlexibleNoiseComparisonModel with patsy formula regression on noise spline coefficients.
Risky choice models¶
- class bauer.models.RiskModel(paradigm=None, prior_estimate='objective', fit_separate_evidence_sd=True, save_trialwise_n_estimates=False, memory_model='independent')[source]¶
Bases:
BaseModelBayesian observer model for risky choice between two monetary lotteries.
Each lottery is characterised by a magnitude (n) and a probability (p). The Bayesian observer applies a Gaussian prior to
log(n_k)only — probabilitiesp_kare observed precisely. The decision rule compareslog(EU)of the two options:choose 2 iff post_log_n_2 + log(p_2) > post_log_n_1 + log(p_1)
Equivalently, the static cumulative-normal likelihood compares the perceived log-magnitude difference
post_log_n_2 - post_log_n_1to a thresholdlog(p_1/p_2).DDMRiskModelandRaceDiffusionRiskModeluse the same front-end with an analytical RT likelihood.- Parameters:
paradigm (pd.DataFrame, optional) – Must contain columns
n1,n2,p1,p2,choice.prior_estimate ({'objective', 'shared', 'full', 'klw'}) – Strategy for the magnitude prior.
objective= empirical mean/std oflog(n)(no fitted parameters);shared= single fitted Gaussian shared across options;klw= Khaw-Li-Woodford style (empiricalmu, fittedsd);full= separate fitted(mu, sd)for the risky and safe options.fit_separate_evidence_sd (bool) – Fit separate encoding noise for n1 and n2 (default
True).memory_model ({'independent', 'shared_perceptual_noise'}) – Noise structure; see
MagnitudeComparisonModel.
- class bauer.models.RiskLapseModel(paradigm=None, prior_estimate='objective', fit_separate_evidence_sd=True, save_trialwise_n_estimates=False, memory_model='independent')[source]¶
Bases:
LapseModel,RiskModelRiskModel extended with a lapse rate parameter.
- class bauer.models.RiskRegressionModel(paradigm, regressors, prior_estimate='objective', fit_separate_evidence_sd=True, save_trialwise_n_estimates=False, memory_model='independent')[source]¶
Bases:
RegressionModel,RiskModelRiskModel with patsy formula regression on noise, prior, or bias parameters.
- class bauer.models.RiskLapseRegressionModel(paradigm, regressors, prior_estimate='objective', fit_separate_evidence_sd=True, save_trialwise_n_estimates=False, memory_model='independent')[source]¶
Bases:
LapseModel,RiskRegressionModelRiskModel with both a lapse rate and patsy formula regression.
- class bauer.models.ProspectTheoryModel(paradigm, save_trialwise_n_estimates=False)[source]¶
Bases:
BaseModelClassic Prospect Theory model for mixed (gain/loss) gambles.
Utility function:
p * gain^alpha - (1-p) * lambda * loss^beta. Free parameters:alpha(gain sensitivity),beta(loss sensitivity),lambda(loss aversion coefficient). Paradigm requires columnsgain,loss,prob_gain, andchoice.
- class bauer.models.LossAversionModel(paradigm=None, save_trialwise_n_estimates=False, magnitude_grid=None, ev_diff_grid=None, lapse_rate=0.01, normalize_likelihoods=True, paradigm_type='mixed_vs_mixed', fix_prior_sds=True)[source]¶
Bases:
BaseModelBayesian observer model for risky choices with separate gain and loss representations.
Models perceptual noise and prior beliefs over gains and losses independently, integrating over a discrete grid of possible values to compute choice probabilities. Supports
'mixed_vs_mixed'(two lotteries) and'mixed_vs_0'(lottery vs. sure zero) paradigm types.
- class bauer.models.LossAversionRegressionModel(paradigm=None, save_trialwise_n_estimates=False, magnitude_grid=None, ev_diff_grid=None, lapse_rate=0.01, normalize_likelihoods=True, paradigm_type='mixed_vs_mixed', fix_prior_sds=True, regressors=None)[source]¶
Bases:
RegressionModel,LossAversionModelLossAversionModel with patsy formula regression on noise/prior parameters.
- class bauer.models.RiskModelProbabilityDistortion(paradigm=None, magnitude_prior_estimate='objective', save_trialwise_n_estimates=False, n_prospects=2, p_grid_size=20, lapse_rate=0.01, distort_magnitudes=True, distort_probabilities=True, fix_magnitude_prior_sd=False, fix_probabiliy_prior_sd=False, estimate_magnitude_prior_mu=False)[source]¶
Bases:
BaseModelRisky choice model with Bayesian distortion of magnitudes and/or probabilities.
Computes the probability of choosing option 2 by integrating over posterior distributions of magnitudes and probabilities in log-odds space. Paradigm requires columns
n1,n2,p1,p2, andchoice.
- class bauer.models.FlexibleNoiseRiskModel(paradigm, prior_estimate='full', fit_separate_evidence_sd=True, save_trialwise_n_estimates=False, spline_order=5, representational_noise='payoff', memory_model='independent')[source]¶
Bases:
FlexibleNoiseComparisonModel,RiskModelRisky choice model combining flexible (polynomial) noise with Bayesian magnitude inference.
- class bauer.models.FlexibleNoiseRiskRegressionModel(paradigm, regressors, prior_estimate='full', fit_separate_evidence_sd=True, save_trialwise_n_estimates=False, spline_order=5, representational_noise='payoff', memory_model='independent')[source]¶
Bases:
RegressionModel,FlexibleNoiseRiskModelFlexibleNoiseRiskModel with patsy formula regression on noise spline coefficients.
- class bauer.models.ExpectedUtilityRiskModel(paradigm, save_trialwise_eu=False, probability_distortion=False, n_outcomes=1)[source]¶
Bases:
BaseModelExpected utility model for risky choice with optional probability distortion.
Computes expected utility for each lottery and converts the utility difference to a choice probability. Supports a single-outcome paradigm (
n_outcomes=1) and a multi-outcome extension. Paradigm requires columnsn1,n2,p1,p2, andchoice.
- class bauer.models.ExpectedUtilityRiskRegressionModel(paradigm, save_trialwise_eu, probability_distortion, regressors)[source]¶
Bases:
RegressionModel,ExpectedUtilityRiskModelExpectedUtilityRiskModel with patsy formula regression on utility or noise parameters.
Reproduction models¶
- class bauer.models.ReproductionModel(paradigm, response_range=None, prior_mu=None, prior_sd=None, fit_prior_mu=True, fit_prior_sd=False, fit_bias=False, fit_lapse=True, fit_motor_noise=False, stimulus_col='stimulus', response_col='response')[source]¶
Bases:
BaseModelLog-space Bayesian observer for reproduction tasks.
Data columns:
stimulus(positive, e.g. seconds),response(same units), andsubjectin the index for hierarchical fits.- Parameters:
paradigm (pd.DataFrame)
response_range ((float, float), optional) – Range of possible responses (natural units), used for the uniform lapse density. Default: observed range ± 20%.
prior_mu (float, optional) – Observer prior on log stimulus. Default: mean and SD of
log(stimulus)inparadigm(the presented distribution). When fitted, these are the starting points (prior centres) instead.prior_sd (float, optional) – Observer prior on log stimulus. Default: mean and SD of
log(stimulus)inparadigm(the presented distribution). When fitted, these are the starting points (prior centres) instead.fit_prior_mu (bool) – Fit the prior mean
prior_muper subject (default True). Its group prior is centred on the presented mean.fit_prior_sd (bool) – Fit the prior width
prior_sdper subject (default False: fixed at the presented SD). Identified from slope + spread whenfit_motor_noiseis False.fit_bias (bool) – Fit an additive measurement bias in log space (default False). Mutually exclusive with
fit_prior_mu(same intercept).fit_lapse (bool) – Include the uniform lapse component (default True).
fit_motor_noise (bool) – Add log-space motor noise
sigma_motor(default False).stimulus_col (str) – Column names (defaults
'stimulus'/'response').response_col (str) – Column names (defaults
'stimulus'/'response').
- ppc(paradigm, idata, n_posterior_samples=200, random_seed=None, progressbar=False)[source]¶
Posterior-predictive reproductions for the fitted data.
Returns a DataFrame indexed by
paradigm.index+ppc_samplewith columnsimulated_response(natural units), like the choice models’ppc. Usesn_posterior_samplesevenly thinned posterior draws.
- class bauer.models.ReproductionRegressionModel(paradigm, regressors=None, fixed_regressors=None, random_regressors=None, **kwargs)[source]¶
Bases:
RegressionModel,ReproductionModelReproductionModelwith patsy formulas on any parameter.fixed_regressors: population design per parameter;random_regressors: which terms also vary per subject (default: random intercept only). E.g. for a within-subject drug design:f = "C(condition, Treatment('placebo')) + session_c" ReproductionRegressionModel(df, fixed_regressors={'nu': f, 'bias': f}, random_regressors={'nu': f, 'bias': f})
Posterior summaries and plots¶
See Summarising and plotting posteriors for how these fit together.
- RegressionModel.conditionwise_draws(idata, conditions, parameters=None, group=True)[source]
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.
conditionandsession_c=0for “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,]theconditionscolumns, andvalue. Feed it tobauer.utils.summarize_posterior()and the forest plots.
- bauer.utils.summaries.summarize_posterior(draws, by, value='value', hdi_prob=0.95, min_draws=100)[source]¶
Posterior mean, 95% HDI and P(> 0) per group of a long draws DataFrame.
- Parameters:
draws (DataFrame with one row per posterior draw (e.g. from) –
model.conditionwise_draws,contrast_draws()orposterior_draws()).by (column name(s) to summarise per, e.g.
['parameter', 'condition'].) – Every column that distinguishes rows within a draw must be listed, otherwise different quantities are pooled into one summary.
- Returns:
DataFrame with the
bycolumns plusmean,lo,hi(HDIbounds) and
p_positive(posterior probability that the value is abovezero; meaningful for contrasts).
- bauer.utils.summaries.contrast_draws(draws, column, reference, value='value', keys=None)[source]¶
Per-draw differences from a reference level of
column.contrast_draws(draws, 'condition', 'placebo')gives, for every draw (and every parameter / subject), each condition minus placebo. The reference level itself is dropped. Level order is preserved.Rows are matched on
keys(default: whichever ofparameter,subject,chain,draware present). Any other column must be constant (it is dropped) or listed inkeys; a column that varies, such assession_cwith different values per condition, raises.
- bauer.utils.summaries.posterior_draws(idata, var_names, transform=None)[source]¶
Long draws for plain (non-regression) variables, e.g.
'nu'with dims(chain, draw, subject)or the group mean'nu_mu'.For regression parameters (a
*_regressorsdimension) usemodel.conditionwise_drawsinstead: the raw coefficients are on the untransformed scale.transformis an optional callable applied to the values.
- bauer.utils.summaries.ppc_summary(ppc, by, value, subject_col='subject', sample_col='ppc_sample', subject_level=False, interval=0.95)[source]¶
Summarise simulated data the same way as the observed data.
For every posterior-predictive sample: average
valuewithin each subject ×bycell, then (unlesssubject_level) across subjects. Returns, per cell, the mean over samples (pred) and the centralintervalover samples (lo,hi). The band contains parameter uncertainty and sampling noise, so ~95% of observed cells should fall inside it (seeppc_coverage()).ppcis long: one row per trial × sample, e.g.model.ppc(...)afterreset_index()and joining the condition columns.
- bauer.utils.summaries.ppc_observed(data, by, value, subject_col='subject', subject_level=False)[source]¶
The observed counterpart of
ppc_summary()(columnobs).
- bauer.utils.summaries.ppc_coverage(pred, obs, by)[source]¶
Fraction of observed cells inside the predictive interval.
bymust identify cells uniquely in both frames (pass['subject', ...]for subject-level summaries), and every cell must be in both.
- bauer.utils.diagnostics.convergence_report(idata, var_names=None, rhat_max=1.01, ess_min=400, max_divergences=0, verbose=True)[source]¶
r̂, bulk ESS and divergences, with a one-line verdict.
By default checks every group-level variable (
*_mu,*_mu_untransformedand*_sd): the ones that get interpreted and the group SDs, which are often the worst-mixing. Passvar_namesto check others (e.g. the subject-level parameters). A NaN r̂ (a stuck or constant chain) counts as a failure.Returns the arviz diagnostics table;
table.attrs['ok']is the verdict.
- bauer.utils.diagnostics.trim_stuck_chains(idata, isolation_z=3.0, verbose=True)[source]¶
Return
(trimmed_idata, report)dropping chains isolated from the agreeing majority on the group-level*_muparameters.A chain is dropped only if its robust z-distance (over standardized group-level means) from the chain-median exceeds
isolation_zAND the surviving (non-isolated) chains are a strict majority. Nothing is dropped otherwise.lpis reported for context but not used as a criterion.
- bauer.utils.plotting.set_house_style()[source]¶
Publication style: Helvetica 7–8 pt, despined, outward ticks, editable PDF text.
- bauer.utils.plotting.plot_forest(summary, parameters, by='condition', order=None, palette=None, level_labels=None, xlabels=None, ref=None, true_col=None, figsize=None, axes=None)[source]¶
Group-level forest plot.
One panel per parameter, one row per level of
by(e.g. condition or contrast). Dot = posterior mean, horizontal line = 95% HDI (lo–hi), dashed vertical line atref(use 0 for contrasts), open circles attrue_col(simulations).- Parameters:
summary (DataFrame from
bauer.utils.summarize_posterior()with) – columnsparameter,by,mean,lo,hi; one row per parameter × level.parameters (parameter name or list of names (one panel each).)
xlabels (dict parameter -> x-axis label.)
- bauer.utils.plotting.plot_sorted_forest(subject_summary, parameter, xlabel=None, by='condition', order=None, sort_by=None, palette=None, level_labels=None, group_summary=None, ref=None, true_col=None, figsize=None, subject_col='subject')[source]¶
Subject-level sorted forest plot (caterpillar), one panel per level of
by.Subjects are sorted by their posterior mean under
sort_by(default: the first level) and keep that row in every panel, so a subject can be followed across conditions. Dot = posterior mean, line = 95% HDI, dashed line = group mean (group_summary, matched onby) orref. Useby=Nonefor a parameter with one value per subject.
- bauer.utils.plotting.plot_ppc_panels(pred, obs, x, by='condition', order=None, palette=None, level_labels=None, xlabel=None, ylabel=None, ref=None, xref=None, figsize=None, logx=False, xticks=None, yticks=None)[source]¶
Group-level PPC, one panel per level of
by: observed data as dots, model as line + 95% band (frombauer.utils.ppc_summary()andbauer.utils.ppc_observed()).ref/xref: dotted horizontal / vertical reference lines, e.g.ref=0.5(chance) andxref=0(no stimulus difference) for a psychometric curve.
- bauer.utils.plotting.plot_ppc_overlay(pred, obs, x, by='condition', order=None, palette=None, level_labels=None, xlabel=None, ylabel=None, ref=None, xref=None, figsize=(3.4, 2.3), logx=False, xticks=None, yticks=None)[source]¶
All levels of
byon one axis (model line + data dots), with a coloured text key in the upper left.
- bauer.utils.plotting.plot_subject_ppc(pred, obs, x, subject_col='subject', col_wrap=8, palette='#3B5BA5', xlabel=None, ylabel=None, logx=False, logy=False, xticks=None, yticks=None, identity=False, ref=None, xref=None, height=0.95, aspect=1.2)[source]¶
Subject-level PPC as small multiples: data dots, model line + 95% band.
pred/obsfromppc_summary(..., subject_level=True)andppc_observed(..., subject_level=True). Returns the Figure.
Utilities¶
- bauer.utils.data.load_garcia2022(task='magnitude', remove_non_responses=True, min_rt=0.15, max_rt=None)[source]¶
Behavioural data from Barreto-Garcia et al. (2022).
For the magnitude task, the raw CSV stores rt in milliseconds; this loader converts to seconds. Implausibly fast trials (rt < 150 ms) are dropped by default — typical motor anticipations distort DDM non-decision times.
The magnitude-task dataframe carries an ``isi`` column (seconds) extracted from the original BIDS events.tsv files — the inter-stimulus interval between offset of n1 and onset of n2. The design jitters ISI over seven half-second levels {6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0}; useful for testing whether memory-load duration changes encoding noise or response caution (see docs/tutorial/lesson8.ipynb).
- bauer.utils.data.load_dehollander2024_risk(sessions=None, remove_non_responses=True, min_rt=0.15, max_rt=None)[source]¶
De Hollander et al. (2024, bioRxiv preprint) dotcloud risky-choice task — N=30 subjects across 3T and 7T sessions, ~256 trials/subject.
choice = Truemeans option 2 chosen (bauer’s risk convention). The risky lottery is at p=0.55, the safe at p=1. Derived columns (risky_first,chose_risky, etc.) are not bundled — compute on the fly fromp1, p2.
- bauer.utils.data.load_dehollander2024_symbolic(remove_non_responses=True, min_rt=0.15, max_rt=None)[source]¶
De Hollander 2024 symbolic (Arabic-numeral) risky-choice task — N=58 subjects, ~256 trials each. Unlike the dotcloud task, n1/n2 are continuous (range ~5–100), making this a stronger test of stimulus- dependent encoding-noise (flex) models.
- bauer.utils.data.load_dehollander_tms_risk(stimulation_conditions=None, sessions=None, tms_only=True, remove_non_responses=True, min_rt=0.15, max_rt=None)[source]¶
De Hollander TMS-risk experiment — 73 subjects total but only 35 of them completed the TMS sessions (sessions 2 and 3); the remaining 38 only did the baseline session.
For TMS analyses you usually want only the 35 TMS subjects (sessions 2/3) — that’s the
tms_only=Truedefault. Settms_only=Falseto get all 73 subjects across all sessions.- Parameters:
- bauer.utils.data.load_bedi2026(remove_non_responses=True)[source]¶
Bedi 2026 abstract-value estimation pilot — orientation→value mapping.
13 subjects across 2 sessions × 2 mapping conditions (‘cdf’ / ‘inverse_cdf’) × 8 runs. On each trial the participant sees an oriented Gabor and estimates its associated value (CHF) on a continuous scale; a BDM-auction-derived
valueis the ground truth andrewardis what they actually earn.This is a continuous-response task — use the continuous-response models (
EstimationBaseModelfamily) rather than the discrete-choice family.Bundled CSV:
bauer/data/bedi2026.csvwith columns subject, session, mapping, run, trial_nr, orientation, value, reward, response, response_time.
- bauer.utils.bayes.summarize_ppc(ppc, groupby=None)[source]¶
Single-step PPC summary (legacy). Prefer summarize_ppc_group for group-level PPCs.
- bauer.utils.bayes.summarize_ppc_group(ppc, condition_cols, subject_col='subject', hdi_prob=0.95)[source]¶
Two-step group-mean PPC summary.
For each posterior sample, first averages simulated choices within each (subject, condition) cell, then averages those subject means across subjects. The HDI is then computed across the resulting per-sample group means.
This correctly represents “where 95 % of plausible group-mean observations would fall under the model” — including both parameter uncertainty and Bernoulli noise — rather than the uncertainty on the per-trial probability.
- Parameters:
ppc (pd.DataFrame, shape (trials, posterior_samples)) – Raw PPC samples from
model.ppc().xs(var_name, level='variable'). Posterior-sample columns can be any column not in condition_cols or subject_col. All grouping keys (including subject_col) must be present either as index levels or as regular columns.condition_cols (list of str) – Condition dimensions to summarise over, e.g.
['n1', 'log_ratio_bin']or['order', 'n_safe_bin', 'log_ratio_bin']. These must be index levels or columns of ppc.subject_col (str) – Name of the subject dimension (default
'subject').hdi_prob (float) – Posterior mass for HDI interval (default 0.95).
- Returns:
Index: condition_cols. Columns:
p_predicted(posterior mean),hdi025,hdi975.- Return type:
pd.DataFrame
Examples
>>> ppc_ll = model.ppc(data, idata, var_names=['ll_bernoulli']) ... .xs('ll_bernoulli', level='variable') >>> # add derived condition columns if needed >>> ppc_ll_flat = ppc_ll.reset_index() >>> ppc_ll_flat['bin'] = pd.cut(ppc_ll_flat['log(n2/n1)'], 12) ... .apply(lambda x: x.mid).astype(float) >>> summary = summarize_ppc_group(ppc_ll_flat, ... condition_cols=['n1', 'bin']) >>> # summary has columns p_predicted, hdi025, hdi975 indexed by (n1, bin)
- bauer.utils.plotting.plot_ppc(df, ppc, exp_type='magnitude', plot_type=1, var_name='p', level='subject', col_wrap=5, n_clusters=13)[source]¶
- bauer.utils.plotting.plot_subjectwise_parameters(idata, parameter, transform=None, sort_subjects=True, plot_group_mean=True, hdi_prob=0.94, color='steelblue', ax=None, label=None, **kwargs)[source]¶
Plot subject-level posterior estimates as a sorted point-plot with HDI error bars.
- Parameters:
idata (arviz.InferenceData) – Posterior samples from a fitted bauer model.
parameter (str) – Name of the subject-level parameter (e.g.
'n1_evidence_sd').transform (str or None) – Optional transform applied to samples before plotting. One of
'softplus','logistic', orNone.sort_subjects (bool) – If True (default) subjects are sorted by their posterior mean on the x-axis. If False, subjects appear in their original order.
plot_group_mean (bool) – If True (default) and a
{parameter}_muvariable exists inidata, draw a dashed horizontal line at the group-mean posterior mean.hdi_prob (float) – Posterior mass for the HDI interval shown as error bars (default 0.94).
color (str) – Colour for the points and error bars.
ax (matplotlib.axes.Axes or None) – Axes to plot on. If None, the current axes are used.
label (str or None) – Legend label for the series.
- Return type:
matplotlib.axes.Axes