behav_utils.models#
behav_utils.models — behavioural models and simulation.
A model is anything with simulate(design, rng) -> Responses; a Design is a run without its
responses (task, stimuli, laser, abort and no-response flags), drawn by make_design.
simulate(model, design) returns a SessionData scored by the task, so synthetic data goes through
the same statistics as real data; simulate_responses returns only the choices.
TrialwiseModel runs the trial loop for models that learn (write p_choice or respond, and
update, each taking a TrialInfo);
IdealObserver and normative_pse give the Bayesian benchmark for a stimulus distribution.
generate_synthetic_session / _animal / _experiment produce synthetic data with every trial
class and event times, from the built-in PsychometricModel or any model.
- class behav_utils.models.Model[source]#
A behavioural model:
simulate(design, rng)returns itsResponsesto a run.Anything with that method works with
simulate(); subclassing is optional. A model may look at the whole design, the laser flags included.simulate()blanks aborted and no-response trials afterwards, whatever the model returns for them.requiresnames the task capabilities the model needs (as statistics do);simulate()refuses a design whose task lacks them.
- class behav_utils.models.TrialwiseModel[source]#
A model that responds trial by trial and may learn from feedback.
A binary model writes
p_choice(trial), the probability of response 1; any other writesrespond(trial, rng), which returns the response itself.update(trial)(learning) andreset()(the start of a run) are optional.simulatecallsreset(), then, for each trial that is neither aborted nor a no-response, asks for a response and callsupdatewith the trial completed: its choice, the task’s score of it and the truth (TrialInfo).- p_choice(trial)[source]#
The probability of response 1, for a binary model.
- Parameters:
trial (TrialInfo) – The trial, as the model sees it before choosing.
- Returns:
The probability.
- Return type:
float
- respond(trial, rng)[source]#
The response to a trial; the default draws 1 with probability
p_choice(trial).- Parameters:
trial (TrialInfo) – The trial, as the model sees it before choosing.
rng (Generator) – Random generator.
- Returns:
The response.
- Return type:
float
- class behav_utils.models.TrialInfo(t, stimulus, laser, choice=None, correct=None, truth=None)[source]#
One trial as a
TrialwiseModelsees it.When the model chooses,
t,stimulusandlaserare set; inupdatethe rest are too. Fields may be added in later versions.- Variables:
t (int) – The trial’s index in the run.
stimulus (float) – The stimulus, on the library’s axis.
laser (bool) – Whether the laser is on.
choice (float | None) – The response given; None while choosing.
correct (bool | None) – The task’s score of it; None while choosing, or where the task gives none.
truth (float | None) – The correct response; None while choosing.
- Parameters:
t (int)
stimulus (float)
laser (bool)
choice (float | None)
correct (bool | None)
truth (float | None)
- class behav_utils.models.Responses(choice, reaction_time=None)[source]#
What a model returns for a run.
- Variables:
choice (numpy.ndarray) – One response per trial; NaN for no response.
reaction_time (numpy.ndarray | None) – Reaction times in seconds, or None.
- Parameters:
choice (ndarray)
reaction_time (ndarray | None)
- class behav_utils.models.Design(task, stimulus, label='', laser=None, abort=None, no_response=None)[source]#
A run without its responses.
stimulusis on the library’s axis;laser,abortandno_responseare per-trial flags drawn before any model sees the run (all False if omitted);truthis the task’s correct response per trial.- Variables:
task (behav_utils.tasks.base.Task) – The task that scores the run.
stimulus (numpy.ndarray) – The stimuli, on the library’s axis.
label (str) – The distribution label stamped on the trials; ‘’ for none.
laser (numpy.ndarray | None) – Whether each trial carries the laser.
abort (numpy.ndarray | None) – Whether each trial is aborted.
no_response (numpy.ndarray | None) – Whether each trial gets no response.
- Parameters:
task (Task)
stimulus (ndarray)
label (str)
laser (ndarray | None)
abort (ndarray | None)
no_response (ndarray | None)
- behav_utils.models.make_design(task=None, distribution=None, n_trials=300, *, label='', laser_fraction=0.0, max_laser_run=None, abort_rate=0.0, no_response_rate=0.0, rng=None)[source]#
Draw a run of trials: the stimuli, and which trials carry the laser, abort or get no response.
Each trial is independently a laser trial, an abort and, if not aborted, a no-response. A task that reads a blank as a response (go/no-go) has no no-response trials.
- Parameters:
task (Task | None) – The task; None for
TwoAFC().distribution (StimulusDistribution | None) – Where the stimuli come from; None for
Uniform().n_trials (int) – How many trials.
label (str) – The distribution label stamped on the trials; ‘’ for none.
laser_fraction (float) – Probability that a trial is a laser trial.
max_laser_run (int | None) – At most this many laser trials in a row; None for no limit.
abort_rate (float) – Probability that a trial is aborted.
no_response_rate (float) – Probability that a trial that is not aborted gets no response.
rng (Generator | None) – Random generator; None starts a fresh one.
- Returns:
A
Design.- Return type:
- behav_utils.models.simulate(model, design, rng=None, *, session_idx=0, animal_id='SIM', stage='task', base_date=None)[source]#
Run
modelondesign, giving a session scored by the design’s task.Aborted and no-response trials have no choice, whatever the model returned for them, and the design’s laser flags become
trials.opto_on.- Parameters:
model (Model) – Anything with
simulate(design, rng); subclassingModelis optional.design (Design) – The run, from
make_design.rng (Generator | None) – Random generator; None starts a fresh one.
session_idx (int) – The session’s position among the animal’s sessions.
animal_id (str) – The animal the session belongs to.
stage (str) – The session’s stage.
base_date (date | None) – The date of session 0, to which
session_idxdays are added; None for 1 January 2025.
- Returns:
A
SessionData.- Raises:
TypeError –
modelhas nosimulate(design, rng)method.RequirementError – The design’s task lacks a capability the model requires.
- Return type:
- behav_utils.models.simulate_responses(model, stimuli, task=None, rng=None, laser=None)[source]#
Just the model’s choices to
stimuli, with no aborts and no session.It is the fast path for many runs, such as a training set for simulation-based inference.
- Parameters:
model (Model) – Anything with
simulate(design, rng).stimuli (ndarray) – The stimuli, on the library’s axis.
task (Task | None) – The task; None for
TwoAFC().rng (Generator | None) – Random generator; None starts a fresh one.
laser (ndarray | None) – Whether each trial carries the laser; None for none.
- Returns:
One response per stimulus.
- Return type:
ndarray
- class behav_utils.models.PsychometricModel(mu=0.0, sigma=0.3, lapse_low=0.02, lapse_high=0.02, laser=None)[source]#
Choices from the psychometric curve the library fits (
fit_psychometric).P(response 1 | s) = lapse_low + (1 - lapse_low - lapse_high) * Phi((s - mu) / sigma). Simulate, then fit, and the parameters come back.- Variables:
mu (float) – The point of subjective equality, on the library’s axis.
sigma (float) – The cumulative Gaussian’s SD; smaller is steeper.
lapse_low (float) – The lower asymptote.
lapse_high (float) – One minus the upper asymptote.
laser (Mapping[str, float] | None) – Values used instead of the model’s own on laser trials,
{parameter: value}; None for none. A name the model does not have is refused with aValueError.
- Parameters:
mu (float)
sigma (float)
lapse_low (float)
lapse_high (float)
laser (Mapping[str, float] | None)
- class behav_utils.models.RandomModel(p=0.5, laser=None)[source]#
Response 1 with probability
pon every trial, whatever the stimulus.- Variables:
p (float) – The probability of response 1.
laser (Mapping[str, float] | None) – Values used instead of the model’s own on laser trials,
{parameter: value}; None for none. A name the model does not have is refused with aValueError.
- Parameters:
p (float)
laser (Mapping[str, float] | None)
- class behav_utils.models.IdealObserver(noise=0.3, distribution=<factory>, lapse=0.0, laser=None)[source]#
The Bayesian observer, with Gaussian sensory noise and a prior of its own.
It perceives each stimulus with Gaussian noise (sd
noise) and, under its priordistributionand the design’s task, gives the response whose category has the higher posterior (a binary task with a stimulus axis), or its posterior mean of the stimulus (a continuous task, which pulls responses towards the middle: seenormative_slope). With probabilitylapseit responds at random. Its prior can differ from the distribution the design draws from.- Variables:
noise (float) – SD of the Gaussian noise on each perceived stimulus, on the library’s axis.
distribution (behav_utils.tasks.distributions.StimulusDistribution) – Its prior over stimuli;
Uniform()by default.lapse (float) – Probability of a random response.
laser (Mapping[str, float] | None) – Values of
noiseorlapseused instead on laser trials,{parameter: value}; None for none. Any other name is refused with aValueError.
- Parameters:
noise (float)
distribution (StimulusDistribution)
lapse (float)
laser (Mapping[str, float] | None)
- behav_utils.models.normative_pse(distribution, noise, task=None)[source]#
The ideal observer’s point of subjective equality.
It is the percept at which both categories are equally probable under
distributionwith sensory noisenoise. With a likelihood that rises with the stimulus, the observer answers 1 above it, so it is also the PSE a psychometric fit to its choices estimates. NaN, with a warning, if no such point lies near the support.- Parameters:
distribution (StimulusDistribution) – The stimulus distribution, which is also the observer’s prior.
noise (float) – SD of the sensory noise, on the library’s axis.
task (Task | None) – The task; None for
TwoAFC().
- Returns:
The PSE, or NaN when no such point lies near the support.
- Warns:
UserWarning – No such point lies near the support.
- Return type:
float
- behav_utils.models.normative_slope(distribution, noise)[source]#
The ideal observer’s expected response slope on a continuous task.
It is the least-squares slope of its posterior-mean response on the stimulus, stimuli drawn from
distribution(also its prior) and percepts carrying Gaussian noise of sdnoise. Below 1 is the pull towards the middle a Bayesian observer shows; for a Gaussian prior of sd s it is s² / (s² + noise²).- Parameters:
distribution (StimulusDistribution) – The stimulus distribution, which is also the observer’s prior.
noise (float) – SD of the sensory noise, on the library’s axis.
- Returns:
The expected slope.
- Return type:
float
- class behav_utils.models.ReproductionModel(bias=0.0, slope=1.0, noise=0.1, lapse=0.0, laser=None)[source]#
A reproducer whose response is a linear function of the stimulus, plus noise.
response = slope * stimulus + biasplus Gaussian noise (sdnoise), clipped to the axis [-1, 1]; with probabilitylapsethe response is a uniformly random location instead. A slope below 1 pulls responses towards the middle. Simulate, then computeresponse_bias,response_slopeanderror_sd, and they come back.- Variables:
bias (float) – Added to every response.
slope (float) – How the response scales with the stimulus.
noise (float) – SD of the Gaussian noise on the response.
lapse (float) – Probability of a uniformly random response.
laser (Mapping[str, float] | None) – Values of any of the four used instead on laser trials,
{parameter: value}; None for none. A name the model does not have is refused with aValueError.
- Parameters:
bias (float)
slope (float)
noise (float)
lapse (float)
laser (Mapping[str, float] | None)
- behav_utils.models.generate_synthetic_session(model=None, *, task=None, distribution=None, n_trials=300, label='', laser_fraction=0.0, max_laser_run=None, abort_rate=0.05, no_response_rate=None, timing=None, animal_id='SYN01', stage='task', session_date=None, session_idx=0, rng=None)[source]#
One synthetic session, with the structure of one loaded from files.
A design drawn by
make_design, the model’s responses and event times on the clock ‘synthetic’, scored bytask.- Parameters:
model (Model | None) – The responder; None for
PsychometricModel().task (Task | None) – The task; None for
TwoAFC().distribution (StimulusDistribution | None) – Where the stimuli come from; None for
Uniform().n_trials (int) – How many trials.
label (str) – The distribution label stamped on the trials; ‘’ for none.
laser_fraction (float) – Probability that a trial is a laser trial.
max_laser_run (int | None) – At most this many laser trials in a row; None for no limit.
abort_rate (float) – Probability that a trial is aborted.
no_response_rate (float | None) – Probability that a trial that is not aborted gets no response; None for 0.02 where the task has no-response trials and 0 where a blank is a withhold.
timing (Timing | None) – How each trial unfolds in time; None for
Timing().animal_id (str) – The animal the session belongs to.
stage (str) – The session’s stage.
session_date (date | None) – The session’s date; None for 5 January 2026.
session_idx (int) – The session’s position among the animal’s sessions.
rng (int | Generator | None) – A seed or a
numpy.random.Generator; None starts a fresh one.
- Returns:
A
SessionData.- Raises:
TypeError –
modelhas nosimulate(design, rng)method.RequirementError – The task lacks a capability the model requires.
- Return type:
- behav_utils.models.generate_synthetic_animal(model=None, n_sessions=20, trials_per_session=300, *, animal_id='SYN01', task=None, distribution=None, label='', stage='task', start_date=None, laser_fraction=0.0, max_laser_run=None, abort_rate=0.05, no_response_rate=None, timing=None, metadata=None, rng=None)[source]#
n_sessionssynthetic sessions on consecutive days fromstart_date, as anAnimalData.model,distribution,labelandtrials_per_sessioneach take one value or a list with one per session (a learning curve, a switch of distribution).- Parameters:
model (Model | Sequence[Model] | None) – The responder in every session, or one per session; None for
PsychometricModel().n_sessions (int) – How many sessions.
trials_per_session (int | Sequence[int]) – Trials in every session, or one count per session.
animal_id (str) – The animal’s id.
task (Task | None) – The task in every session; None for
TwoAFC().distribution (StimulusDistribution | Sequence[StimulusDistribution] | None) – Where the stimuli come from, in every session or one per session; None for
Uniform().label (str | Sequence[str]) – The distribution label, in every session or one per session; ‘’ for none.
stage (str) – Every session’s stage.
start_date (date | None) – The first session’s date; None for 5 January 2026.
laser_fraction (float) – Probability that a trial is a laser trial.
max_laser_run (int | None) – At most this many laser trials in a row; None for no limit.
abort_rate (float) – Probability that a trial is aborted.
no_response_rate (float | None) – As in
generate_synthetic_session.timing (Timing | None) – How each trial unfolds in time; None for
Timing().metadata (Mapping[str, Any] | None) – Goes to
animal.metadata.rng (int | Generator | None) – A seed or a
numpy.random.Generator; None starts a fresh one.
- Returns:
The animal.
- Raises:
ValueError – A per-session list does not have
n_sessionsentries.- Return type:
- behav_utils.models.generate_synthetic_experiment(animals, rng=None)[source]#
Synthetic animals as an
ExperimentData.Each animal’s random stream comes from
rngand its own id, so adding or removing an animal leaves the others unchanged.- Parameters:
animals (Mapping[str, Mapping[str, Any]]) – Maps an animal id to the keyword arguments of
generate_synthetic_animal(model,n_sessions,metadatasuch as a group, …), other thananimal_idandrng.rng (int | Generator | None) – A seed or a
numpy.random.Generator; None starts a fresh one.
- Returns:
The experiment.
- Raises:
ValueError – An animal’s arguments include
animal_idorrng, which the experiment sets.- Return type:
- class behav_utils.models.Timing(session_start=32400.0, stimulus_delay=0.5, rt_median=0.45, rt_sigma=0.35, response_window=2.0, abort_after=0.2, iti=2.0)[source]#
How a synthetic trial unfolds, in seconds.
The session starts
session_startafter midnight. Each trial presents the stimulusstimulus_delayafter it starts; a response follows after the reaction time (lognormal with medianrt_medianand log-sdrt_sigma, unless the model gives its own), a trial without one waits outresponse_window, and an abort endsabort_afterafter the stimulus. The next trial startsitilater.- Variables:
session_start (float) – Seconds after midnight at which the session starts.
stimulus_delay (float) – Seconds from a trial’s start to the stimulus.
rt_median (float) – Median of the lognormal reaction time.
rt_sigma (float) – Log-SD of the lognormal reaction time.
response_window (float) – How long a trial without a response waits.
abort_after (float) – Seconds after the stimulus at which an abort ends the trial.
iti (float) – Seconds from one trial’s end to the next trial’s start.
- Parameters:
session_start (float)
stimulus_delay (float)
rt_median (float)
rt_sigma (float)
response_window (float)
abort_after (float)
iti (float)