behav_utils.readouts#
Array-valued readouts of a block of trials (see _base for the contract).
Each compute_x(arrays) returns a frozen dataclass with one draw-only plotter: for example
compute_update_matrix(arrays) gives an UpdateMatrix, with .matrix, .profile() and
.to_rows().
The fit engines on raw arrays (fit_psychometric, fit_update_matrix) live in fit.py;
stats and the readouts both import them, and fit.py imports nothing from the package.
- behav_utils.readouts.fit_psychometric(stimuli, choices, x_eval=None, n_bootstrap=0, seed=42)[source]#
Fit psychometric curve to choice data.
- Parameters:
stimuli (ndarray) – Array of stimulus values
choices (ndarray) – Array of binary choices (0 = A, 1 = B)
x_eval (ndarray | None) – Points at which to evaluate fitted curve (default: linspace(-1, 1, 100))
n_bootstrap (int) – Number of bootstrap samples for confidence intervals (0 = no bootstrap)
seed (int) – Random seed for bootstrap
- Returns:
A dict with these keys:
'mu' PSE (point of subjective equality) 'sigma' Slope (smaller = steeper) 'lapse_low' Lower lapse rate (floor) 'lapse_high' Upper lapse rate (1 - ceiling) 'x_fit' Evaluation points 'y_fit' Fitted curve values 'nll' Negative log-likelihood 'success' Whether fit succeeded
With
n_bootstrap > 0, also:'mu_ci' (lower, upper) 95% CI for mu 'sigma_ci' (lower, upper) 95% CI for sigma 'lapse_low_ci' (lower, upper) 95% CI for lapse_low 'lapse_high_ci' (lower, upper) 95% CI for lapse_high 'y_fit_ci' (lower, upper) curves for the 95% CI band 'bootstrap_params' DataFrame with all bootstrap parameter values
- Return type:
Dict
Source: the form with lapse rates and the constrained maximum-likelihood fit follow Wichmann & Hill (2001); the docs site lists the references.
- behav_utils.readouts.fit_psychometric_gof(stimuli, choices, psych_params, n_bins=8)[source]#
Compute goodness-of-fit metrics for psychometric curve.
- Parameters:
stimuli (ndarray) – Stimulus values
choices (ndarray) – Binary choices
psych_params (Dict) – Fitted psychometric parameters (from fit_psychometric)
n_bins (int) – Number of bins for binned metrics
- Returns:
A dict with these keys:
'r_squared' R² between binned data and fitted curve 'deviance' Binomial deviance 'deviance_explained' Fraction of null deviance explained 'rmse' Root mean squared error (binned) 'mae' Mean absolute error (binned) 'log_likelihood' Log-likelihood of fit 'aic' Akaike information criterion 'bic' Bayesian information criterion
- Return type:
Dict
- behav_utils.readouts.fit_update_matrix(stimuli, choices, *, correct, n_bins=8, trial_filter='post_correct', no_response=None, not_blockstart=None, prev_stimuli=None, prev_choices=None, prev_correct=None)[source]#
Compute update matrix from raw behavioural arrays.
The update matrix captures serial dependence: how does the previous trial’s stimulus shift the current psychometric curve?
- Parameters:
stimuli (ndarray) – Stimulus values for each trial.
choices (ndarray) – Binary choices (0=A, 1=B).
correct (ndarray) – The task’s score per trial (
TrialArrays.correct): 1 correct, 0 error, NaN no score. Keyword-only: the engine never decides correctness itself.n_bins (int) – Number of bins for stimulus discretisation.
trial_filter (Literal['all', 'post_correct']) – ‘post_correct’ (only after correct) or ‘all’.
no_response (ndarray | None) – Bool array (True = no response). Inferred from NaN if None.
not_blockstart (ndarray | None) – Bool array (True = not start of block). Auto if None.
prev_stimuli (ndarray | None) – The previous trial’s stimulus for every trial, from the frozen, abort-aware lag-1 view. When given, the previous trial is taken from these, not from array adjacency, so the matrix is correct on a non-consecutive subset such as the opto trials only. None takes the preceding array element instead, through
not_blockstart.prev_choices (ndarray | None) – The previous trial’s choice, aligned the same way.
prev_correct (ndarray | None) – The previous trial’s score, aligned the same way; required with
prev_stimuli.
- Returns:
The tuple
(update_matrix, conditional_matrix, info), with the (n_bins, n_bins) shift in P(B), the (n_bins, n_bins) conditional P(B) values, and a dict of fitting details.- Raises:
ValueError –
prev_stimuliis given withoutprev_correct.- Return type:
Tuple[ndarray, ndarray, Dict]
- behav_utils.readouts.matrix_error(matrix1, matrix2)[source]#
Mean squared error between two matrices, ignoring NaNs.
- Parameters:
matrix1 (ndarray) – One matrix.
matrix2 (ndarray) – Another of the same shape.
- Returns:
The mean of the squared differences over the cells where both are finite.
- Return type:
float
- behav_utils.readouts.cumulative_gaussian(x, mu, sigma, lapse_low=0.0, lapse_high=0.0)[source]#
Compute cumulative Gaussian psychometric function.
- Parameters:
x (ndarray) – Stimulus values
mu (float) – Mean (PSE - point of subjective equality)
sigma (float) – Standard deviation (slope)
lapse_low (float) – Lower lapse rate (guess rate for category A)
lapse_high (float) – Upper lapse rate (lapse rate for category B)
- Returns:
P(choose B) for each stimulus value
- Return type:
ndarray
- class behav_utils.readouts.UpdateMatrix(matrix, conditional, unconditional, n_pairs, n_trials, trial_filter, n_sources=1, coverage=None, sem=None)[source]#
(n_bins × n_bins) shift in P(B). Row = current-stimulus bin, column = previous-stimulus bin.
matrix[i, j]= P(B | cur bin i, prev bin j) − P(B | cur bin i), from a per-previous-bin cumulative-Gaussian fit minus the unconditional fit, both evaluated at the bin centres. NaN columns had fewer thanMIN_PAIRS_PER_BINpairs or a failed fit.- Variables:
matrix (numpy.ndarray) – The shift in P(B), (n_bins, n_bins).
conditional (numpy.ndarray) – P(B) given the current and previous bins, (n_bins, n_bins).
unconditional (numpy.ndarray) – P(B) at the bin centres from the unconditional fit, (n_bins,).
n_pairs (numpy.ndarray) – Trial pairs per previous-stimulus bin, (n_bins,).
n_trials (int) – Pairs entering the unconditional fit.
trial_filter (str) – ‘post_correct’ or ‘all’.
n_sources (int) – How many blocks were averaged into this matrix; 1 for a single fit.
coverage (numpy.ndarray | None) – Sources per cell, (n_bins, n_bins), when averaged; else None.
sem (numpy.ndarray | None) – SEM per cell across sources, (n_bins, n_bins), when averaged; else None.
- Parameters:
matrix (ndarray)
conditional (ndarray)
unconditional (ndarray)
n_pairs (ndarray)
n_trials (int)
trial_filter (str)
n_sources (int)
coverage (ndarray | None)
sem (ndarray | None)
- profile()[source]#
The mean shift per previous-stimulus bin.
- Returns:
The column means of
matrix, ignoring NaN, (n_bins,).- Return type:
ndarray
- to_rows()[source]#
The matrix as a tidy table.
- Returns:
One row per cell, with
cur_bin,prev_bin,cur_centre,prev_centre,shiftandconditional.- Return type:
DataFrame
- classmethod from_matrix(matrix, *, trial_filter='post_correct')[source]#
Wrap a shift matrix from elsewhere, such as a model, for plotting.
- Parameters:
matrix – The (n_bins, n_bins) shift in P(B).
trial_filter (str) – The pairs it describes, ‘post_correct’ or ‘all’.
- Returns:
An
UpdateMatrixwhose other fields are NaN or 0.- Return type:
- classmethod average(items, *, min_sources=1)[source]#
Cell-wise mean over matrices (equal weight per item; the item is the unit).
Valid because every matrix bins on the same fixed grid. Cells backed by fewer than
min_sourcesfinite items are NaN.- Parameters:
items (Sequence[UpdateMatrix]) – The matrices to average, all on the same grid.
min_sources (int) – The fewest finite values a cell needs to be kept.
- Returns:
The average, with
n_sources,coverageandsemfilled.- Return type:
- behav_utils.readouts.compute_update_matrix(arrays, *, n_bins=8, trial_filter='post_correct')[source]#
Update matrix on one block of trials, using the frozen lag-1 view.
- Parameters:
arrays (TrialArrays) – Pre-filtered trials of one block. They may be a non-consecutive subset, such as the opto trials only: each trial’s predecessor comes from the
prev_*arrays, never from its neighbour in the arrays.n_bins (int) – Stimulus bins on the fixed [-1, 1] grid.
trial_filter (Literal['post_correct', 'all']) – ‘post_correct’ keeps the pairs whose previous trial was correct; ‘all’ keeps every responded pair.
- Returns:
An
UpdateMatrix. A previous-stimulus bin with fewer than 10 pairs, or whose fit fails, stays NaN.- Raises:
RequirementError – The task is not binary or has no stimulus axis.
- Return type:
Source: the updating analysis of Lak et al. (2020). Each conditional curve here is a maximum-likelihood fit to single trials; the docs site lists the references.
- class behav_utils.readouts.PsychometricCurve(mu, sigma, lapse_low, lapse_high, x, y, bin_centres, bin_means, bin_counts, n_trials, success, ci=None, band=None, n_bootstrap=0)[source]#
Cumulative-Gaussian fit to P(B | stimulus), with binned data and a bootstrap band.
ciis a (4, 2) array of 95% intervals in PARAMS order andbanda (2, len(x)) array of curve percentiles; both are None whenn_bootstrap=0or no bootstrap fit succeeded.successFalse means the point fit failed: params are NaN,yis NaN, the binned data are still filled.- Variables:
mu (float) – The point of subjective equality.
sigma (float) – The cumulative Gaussian’s SD.
lapse_low (float) – The lower lapse rate.
lapse_high (float) – The upper lapse rate.
x (numpy.ndarray) – Where the fitted curve is evaluated.
y (numpy.ndarray) – The fitted curve at
x.bin_centres (numpy.ndarray) – Centres of the stimulus bins.
bin_means (numpy.ndarray) – P(B) per bin, from the trials.
bin_counts (numpy.ndarray) – Trials per bin.
n_trials (int) – Trials fitted.
success (bool) – Whether the fit succeeded.
ci (numpy.ndarray | None) – 95% intervals of the four parameters, (4, 2), or None without a bootstrap.
band (numpy.ndarray | None) – The curve’s 95% band, (2, len(x)), or None without a bootstrap.
n_bootstrap (int) – Bootstrap fits that succeeded.
- Parameters:
mu (float)
sigma (float)
lapse_low (float)
lapse_high (float)
x (ndarray)
y (ndarray)
bin_centres (ndarray)
bin_means (ndarray)
bin_counts (ndarray)
n_trials (int)
success (bool)
ci (ndarray | None)
band (ndarray | None)
n_bootstrap (int)
- behav_utils.readouts.compute_psychometric_curve(arrays, *, n_bins=8, n_bootstrap=1000, seed=42)[source]#
Fit a cumulative Gaussian to one block; CIs and band from trial bootstrap.
- Parameters:
arrays (TrialArrays) – Pre-filtered trials of one block.
n_bins (int) – Bins for the empirical points only; the fit uses the single trials.
n_bootstrap (int) – Trial resamples for the confidence intervals and the band; 0 skips them.
seed (int) – Seed for the bootstrap.
- Returns:
A
PsychometricCurve. When the fit fails its parameters and curve are NaN andsuccessis False; the binned points are filled either way.- Raises:
RequirementError – The task is not binary or has no stimulus axis.
- Return type:
- class behav_utils.readouts.ConditionalPsychometric(params, unconditional, n_per_bin, fell_back, n_trials, success)[source]#
(n_bins × 4) psychometric parameters conditioned on the previous-stimulus bin.
A bin with fewer than
min_per_binpairs, a failed fit, or an unreliable fit (sigma > SLOPE_THRESHOLD or|mu| > MU_BOUND) falls back to the unconditional parameters;fell_backrecords which. mu/sigma fall back together, lapses only on failure — matching the legacy stat exactly.- Variables:
params (numpy.ndarray) – The four parameters per previous-stimulus bin, (n_bins, 4).
unconditional (numpy.ndarray) – The four parameters of the unconditional fit.
n_per_bin (numpy.ndarray) – Trial pairs per previous-stimulus bin.
fell_back (numpy.ndarray) – Whether each bin took the unconditional fit.
n_trials (int) – Valid trials in the block.
success (bool) – Whether the unconditional fit succeeded.
- Parameters:
params (ndarray)
unconditional (ndarray)
n_per_bin (ndarray)
fell_back (ndarray)
n_trials (int)
success (bool)
- behav_utils.readouts.compute_conditional_psychometric(arrays, *, n_bins=8, min_per_bin=15)[source]#
Per-previous-stimulus-bin psychometric fits on one block.
A bin with fewer than
min_per_binpairs, or whose fit fails or is implausible, takes the unconditional fit instead, andfell_backmarks it.- Parameters:
arrays (TrialArrays) – Pre-filtered trials of one block.
n_bins (int) – Previous-stimulus bins on the fixed [-1, 1] grid.
min_per_bin (int) – The fewest trial pairs a bin needs for a fit of its own.
- Returns:
A
ConditionalPsychometric, all NaN when there are fewer than 50 valid trials or the unconditional fit fails.- Raises:
RequirementError – The task is not binary or has no stimulus axis.
- Return type:
- class behav_utils.readouts.BinnedCurve(kind, centres, values, counts)[source]#
Per-stimulus-bin mean of either P(B) (
choice_prob) or P(correct) (accuracy).- Variables:
kind (str) – ‘choice_prob’ or ‘accuracy’.
centres (numpy.ndarray) – Centres of the stimulus bins.
values (numpy.ndarray) – The proportion per bin; NaN for an empty bin.
counts (numpy.ndarray) – Trials per bin.
- Parameters:
kind (str)
centres (ndarray)
values (ndarray)
counts (ndarray)
- behav_utils.readouts.compute_binned_curve(arrays, *, kind='choice_prob', n_bins=8)[source]#
Empirical curve on one block (responded trials only).
- Parameters:
arrays (TrialArrays) – Pre-filtered trials of one block.
kind (Literal['choice_prob', 'accuracy']) – ‘choice_prob’ for the proportion of B choices per stimulus bin, or ‘accuracy’ for the proportion correct among the trials the task scores.
n_bins (int) – Stimulus bins on the fixed [-1, 1] grid.
- Returns:
A
BinnedCurve; an empty bin is NaN with a count of 0.- Raises:
RequirementError – The task is not binary or has no stimulus axis, or, for ‘accuracy’, does not score trials.
ValueError –
kindis neither ‘choice_prob’ nor ‘accuracy’.
- Return type:
- class behav_utils.readouts.SerialDependenceProfile(centres, profile, marginal, n_pairs)[source]#
profile[j]= mean over current bins i of P(B | prev j, cur i) − P(B | cur i), post-correct pairs.- Variables:
centres (numpy.ndarray) – Centres of the previous-stimulus bins.
profile (numpy.ndarray) – The mean shift in P(B) per previous-stimulus bin.
marginal (numpy.ndarray) – P(B) per current-stimulus bin, from the post-correct pairs.
n_pairs (int) – Pairs per previous-stimulus bin.
- Parameters:
centres (ndarray)
profile (ndarray)
marginal (ndarray)
n_pairs (int)
- behav_utils.readouts.compute_sd_profile(arrays, *, n_bins=8)[source]#
Serial-dependence profile on one block of a binary task.
After a correct trial, how much P(B) shifts with the previous stimulus’s bin, averaged over the current-stimulus bins.
- Parameters:
arrays (TrialArrays) – Pre-filtered trials of one block.
n_bins (int) – Stimulus bins on the fixed [-1, 1] grid, for the previous and the current stimulus.
- Returns:
A
SerialDependenceProfile, all NaN when there are fewer than 50 valid trials or fewer than 30 after a correct trial; a previous-stimulus bin with fewer than 5 of those is NaN.- Raises:
RequirementError – The task is not binary, has no stimulus axis or does not score trials.
- Return type:
- class behav_utils.readouts.ResponseCurve(centres, values, sem, counts)[source]#
Mean response per stimulus bin, with its SEM and count.
A faithful reproducer lies on the identity line; a slope below it is a pull towards the middle.
- Variables:
centres (numpy.ndarray) – Centres of the stimulus bins.
values (numpy.ndarray) – The mean response per bin.
sem (numpy.ndarray) – Its SEM.
counts (numpy.ndarray) – Trials per bin.
- Parameters:
centres (ndarray)
values (ndarray)
sem (ndarray)
counts (ndarray)
- behav_utils.readouts.compute_response_curve(arrays, *, n_bins=8)[source]#
Mean response, on the library’s axis, per stimulus bin.
- Parameters:
arrays (TrialArrays) – Pre-filtered trials of one block.
n_bins (int) – Stimulus bins on the fixed [-1, 1] grid.
- Returns:
A
ResponseCurve.- Raises:
RequirementError – The task’s responses are not continuous.
- Return type:
- class behav_utils.readouts.ErrorDistribution(edges, counts, density, mean, sd, n)[source]#
Signed errors (response − truth), binned.
Counts and density over symmetric bins, errors beyond the outer edges counted in the end bins, with the mean, SD and number of errors.
- Variables:
edges (numpy.ndarray) – The bin edges.
counts (numpy.ndarray) – Errors per bin.
density (numpy.ndarray) – The density per bin.
mean (float) – The mean error.
sd (float) – The errors’ SD.
n (int) – How many errors.
- Parameters:
edges (ndarray)
counts (ndarray)
density (ndarray)
mean (float)
sd (float)
n (int)
- behav_utils.readouts.compute_error_distribution(arrays, *, n_bins=20, limit=1.0)[source]#
The signed errors binned over [-limit, limit] on the library’s axis.
An error is the response minus the correct response, on trials with both.
- Parameters:
arrays (TrialArrays) – Pre-filtered trials of one block.
n_bins (int) – Bins over [-limit, limit].
limit (float) – Half-width of the binned range; errors beyond it count in the outermost bins.
- Returns:
An
ErrorDistribution, with the counts and density per bin and the errors’ mean and SD.- Raises:
RequirementError – The task’s responses are not continuous.
- Return type:
- class behav_utils.readouts.SerialBiasCurve(centres, values, sem, counts)[source]#
Mean error per bin of previous − current stimulus.
The current stimulus’s linear effect is removed first (as in the
serial_biasstatistic), so a pull towards the middle does not draw a false curve. Rising through zero means attraction to the previous stimulus.- Variables:
centres (numpy.ndarray) – Centres of the bins of previous − current stimulus.
values (numpy.ndarray) – The mean remaining error per bin.
sem (numpy.ndarray) – Its SEM.
counts (numpy.ndarray) – Trial pairs per bin.
- Parameters:
centres (ndarray)
values (ndarray)
sem (ndarray)
counts (ndarray)
- behav_utils.readouts.compute_serial_bias(arrays, *, n_bins=8)[source]#
The serial-bias curve over previous − current stimulus in [-2, 2] on the library’s axis.
The errors are regressed on the difference and on the current stimulus, and the current stimulus’s part, with the intercept, is removed, so central tendency does not show as serial bias. The curve is the mean of what remains per bin of the difference.
- Parameters:
arrays (TrialArrays) – Pre-filtered trials of one block.
n_bins (int) – Bins over the difference between the previous and the current stimulus, [-2, 2].
- Returns:
A
SerialBiasCurve, with the mean, SEM and count per bin.- Raises:
RequirementError – The task’s responses are not continuous.
- Return type:
Source: the serial dependence of Fischer & Whitney (2014), measured here by a linear regression rather than a fitted curve; the docs site lists the references.