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’}. 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 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

mu is the group-mean rate (prior mean beta_mu_mean, default 0.05); kappa is the population concentration. The per-subject density is ∝ p^(alpha-1)(1-p)^(beta-1): when alpha = mu·kappa < 1 (small mu) this is an integrable spike at 0 (the “1/x” shape) with a fat upper tail, exactly matching “most subjects ≈ 0, a few disengaged”. The kappa = 2 + exp(...) floor keeps beta = (1-mu)·kappa > 1 so the density is bounded near 1 (no spurious upper-edge spike) while still allowing alpha < 1. p[s] is sampled directly as a pm.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}_mu and {name}_kappa are exposed for reporting (so get_groupwise_parameter_estimates keeps 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 chains initval dicts (keyed by the model’s free-RV value-variable names). Each is a plausible centre plus per-parameter Gaussian jitter whose SD is jitter_frac times 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) when use_map; otherwise the model’s prior-central initial_point(). Falls back to initial_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.index levels + ppc_sample. Single column simulated_choice (bool). Format matches DDMMixin.ppc / RaceMixin.ppc so 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 from pm.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. None uses 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, needs pymc_extras, falls back to 'mapjitter' if unavailable). Ignored if initvals is 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: BaseModel

Static-choice model with a per-subject random-lapse rate p_lapse.

lapse_group selects 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; see BaseModel.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’}. 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 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

mu is the group-mean rate (prior mean beta_mu_mean, default 0.05); kappa is the population concentration. The per-subject density is ∝ p^(alpha-1)(1-p)^(beta-1): when alpha = mu·kappa < 1 (small mu) this is an integrable spike at 0 (the “1/x” shape) with a fat upper tail, exactly matching “most subjects ≈ 0, a few disengaged”. The kappa = 2 + exp(...) floor keeps beta = (1-mu)·kappa > 1 so the density is bounded near 1 (no spurious upper-edge spike) while still allowing alpha < 1. p[s] is sampled directly as a pm.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}_mu and {name}_kappa are exposed for reporting (so get_groupwise_parameter_estimates keeps 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. 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

  • bauer.utils.summarize_posterior() and the forest plots.

Psychophysical models

class bauer.models.PsychophysicalModel(paradigm=None)[source]

Bases: BaseModel

Psychophysical model for two-alternative forced choice with a sensitivity and bias parameter.

Parameters nu (discrimination sensitivity, softplus-transformed) and bias (decision criterion) describe the probability of choosing option 2 given stimuli x1 and x2. Paradigm requires columns x1, x2, and choice.

nu and bias are in the raw units of x, 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, PsychophysicalModel

PsychophysicalModel 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, PsychophysicalModel

PsychophysicalModel 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, PsychophysicalRegressionModel

PsychophysicalModel 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: BaseModel

Bayesian 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, and choice.

  • fit_prior (bool) – If True, fit prior_mu and prior_sd as 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, MagnitudeComparisonModel

MagnitudeComparisonModel 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, MagnitudeComparisonModel

MagnitudeComparisonModel 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, MagnitudeComparisonRegressionModel

MagnitudeComparisonModel 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: BaseModel

Magnitude 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, and choice.

  • 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 x using the design_info that was fixed at construction time (anchored to the paradigm column for this variable). Knot positions DO NOT depend on x — 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, FlexibleNoiseComparisonModel

FlexibleNoiseComparisonModel 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: BaseModel

Bayesian 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 — probabilities p_k are observed precisely. The decision rule compares log(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_1 to a threshold log(p_1/p_2). DDMRiskModel and RaceDiffusionRiskModel use 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 of log(n) (no fitted parameters); shared = single fitted Gaussian shared across options; klw = Khaw-Li-Woodford style (empirical mu, fitted sd); 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, RiskModel

RiskModel 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, RiskModel

RiskModel 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, RiskRegressionModel

RiskModel with both a lapse rate and patsy formula regression.

class bauer.models.ProspectTheoryModel(paradigm, save_trialwise_n_estimates=False)[source]

Bases: BaseModel

Classic 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 columns gain, loss, prob_gain, and choice.

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: BaseModel

Bayesian 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, LossAversionModel

LossAversionModel 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: BaseModel

Risky 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, and choice.

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, RiskModel

Risky 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, FlexibleNoiseRiskModel

FlexibleNoiseRiskModel 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: BaseModel

Expected 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 columns n1, n2, p1, p2, and choice.

class bauer.models.ExpectedUtilityRiskRegressionModel(paradigm, save_trialwise_eu, probability_distortion, regressors)[source]

Bases: RegressionModel, ExpectedUtilityRiskModel

ExpectedUtilityRiskModel 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: BaseModel

Log-space Bayesian observer for reproduction tasks.

Data columns: stimulus (positive, e.g. seconds), response (same units), and subject in 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) in paradigm (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) in paradigm (the presented distribution). When fitted, these are the starting points (prior centres) instead.

  • fit_prior_mu (bool) – Fit the prior mean prior_mu per subject (default True). Its group prior is centred on the presented mean.

  • fit_prior_sd (bool) – Fit the prior width prior_sd per subject (default False: fixed at the presented SD). Identified from slope + spread when fit_motor_noise is 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_sample with column simulated_response (natural units), like the choice models’ ppc. Uses n_posterior_samples evenly thinned posterior draws.

predicted_log_response(log_stimulus, parameters)[source]

Mean and SD of log reproductions (excluding lapses).

class bauer.models.ReproductionRegressionModel(paradigm, regressors=None, fixed_regressors=None, random_regressors=None, **kwargs)[source]

Bases: RegressionModel, ReproductionModel

ReproductionModel with 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. 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

  • bauer.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() or posterior_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 by columns plus mean, lo, hi (HDI

  • bounds) and p_positive (posterior probability that the value is above

  • zero; 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 of parameter, subject, chain, draw are present). Any other column must be constant (it is dropped) or listed in keys; a column that varies, such as session_c with 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 *_regressors dimension) use model.conditionwise_draws instead: the raw coefficients are on the untransformed scale. transform is 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 value within each subject × by cell, then (unless subject_level) across subjects. Returns, per cell, the mean over samples (pred) and the central interval over samples (lo, hi). The band contains parameter uncertainty and sampling noise, so ~95% of observed cells should fall inside it (see ppc_coverage()).

ppc is long: one row per trial × sample, e.g. model.ppc(...) after reset_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() (column obs).

bauer.utils.summaries.ppc_coverage(pred, obs, by)[source]

Fraction of observed cells inside the predictive interval.

by must 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_untransformed and *_sd): the ones that get interpreted and the group SDs, which are often the worst-mixing. Pass var_names to 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 *_mu parameters.

A chain is dropped only if its robust z-distance (over standardized group-level means) from the chain-median exceeds isolation_z AND the surviving (non-isolated) chains are a strict majority. Nothing is dropped otherwise. lp is 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 at ref (use 0 for contrasts), open circles at true_col (simulations).

Parameters:
  • summary (DataFrame from bauer.utils.summarize_posterior() with) – columns parameter, 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 on by) or ref. Use by=None for 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 (from bauer.utils.ppc_summary() and bauer.utils.ppc_observed()).

ref / xref: dotted horizontal / vertical reference lines, e.g. ref=0.5 (chance) and xref=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 by on 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 / obs from ppc_summary(..., subject_level=True) and ppc_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).

Parameters:
  • task ({'magnitude', 'risk'})

  • remove_non_responses (bool)

  • min_rt (float) – RT cutoffs in seconds (post-conversion). Set min_rt=0 to disable.

  • max_rt (float) – RT cutoffs in seconds (post-conversion). Set min_rt=0 to disable.

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 = True means 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 from p1, 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=True default. Set tms_only=False to get all 73 subjects across all sessions.

Parameters:
  • stimulation_conditions (list of str or None) – Subset of {‘baseline’, ‘vertex’, ‘ips’} to keep. Default: all.

  • sessions (list of int or None) – Subset of {1, 2, 3}. Default: [2, 3] if tms_only=True, else all.

  • tms_only (bool) – If True, keep only the 35 TMS-completing subjects in sessions 2/3.

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 value is the ground truth and reward is what they actually earn.

This is a continuous-response task — use the continuous-response models (EstimationBaseModel family) rather than the discrete-choice family.

Bundled CSV: bauer/data/bedi2026.csv with columns subject, session, mapping, run, trial_nr, orientation, value, reward, response, response_time.

bauer.utils.bayes.get_posterior(mu1, sd1, mu2, sd2)[source]
bauer.utils.bayes.get_posterior_np(mu1, sd1, mu2, sd2)[source]
bauer.utils.bayes.get_diff_dist(mu1, sd1, mu2, sd2)[source]
bauer.utils.bayes.get_diff_dist_np(mu1, sd1, mu2, sd2)[source]
bauer.utils.bayes.cumulative_normal(x, mu, sd, s=Sqrt.0)[source]
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.math.logistic(x)[source]
bauer.utils.math.logistic_np(x)[source]
bauer.utils.math.softplus_np(x)[source]
bauer.utils.math.inverse_softplus_np(x)[source]
bauer.utils.math.logit(p)[source]
bauer.utils.math.logit_np(p)[source]
bauer.utils.math.logit_derivative(p)[source]
bauer.utils.math.gaussian_pdf(x, mean, std)[source]
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', or None.

  • 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}_mu variable exists in idata, 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

bauer.utils.plotting.plot_prediction(data, x, color, y='p_predicted', alpha=0.25, **kwargs)[source]
bauer.utils.plotting.cluster_offers(d, n=6, key='log(risky/safe)')[source]
bauer.utils.plotting.get_hdi(d)[source]