Data Structures Reference#
Overview#
behav_utils organises behavioural data in a hierarchy that mirrors experimental structure:
ExperimentData All animals in a project
└── AnimalData One animal, all its sessions
└── SessionData One behavioural session
├── SessionMetadata Task parameters (constant within session)
└── TrialData Trial-by-trial arrays
TrialArrays (in behav_utils.data) is the flat, pooled view every statistic and readout
computes from; TrialArrays.from_sessions(clean) builds it (pool_arrays is the raw dict
underneath). The data classes hold data only: filtering is done by functions in behav_utils.data,
statistics in behav_utils.stats / behav_utils.analysis.
The examples on this page run, top to bottom, on the synthetic experiment this block builds: six animals in two
groups, laser on a third of each animal’s trials, and an expert preset. With your own data,
load_experiment('config.yaml') returns the same structure.
import matplotlib.pyplot as plt
import pandas as pd
from behav_utils import (PsychometricModel, SessionFilter, filter_trials, generate_synthetic_experiment,
register_preset, select_sessions)
register_preset('expert', SessionFilter(stage='task', last_fraction=0.5))
groups = {'A05': 'control', 'A06': 'control', 'A07': 'control',
'A08': 'treated', 'A09': 'treated', 'A10': 'treated'}
experiment = generate_synthetic_experiment(
{animal_id: {'model': PsychometricModel(sigma=0.3 if group == 'control' else 0.5), 'n_sessions': 6,
'trials_per_session': 200, 'laser_fraction': 0.33, 'metadata': {'group': group}}
for animal_id, group in groups.items()}, rng=0)
animal = experiment.get_animal('A05')
sessions = select_sessions(animal, stage='task')
session = sessions[0]
clean = filter_trials(sessions, trial_type='non_opto')
TrialData#
The lowest level — per-trial arrays for a single session.
Core Fields#
Field |
Type |
Description |
|---|---|---|
|
int array |
Original trial numbers from CSV |
|
float array |
Stimulus on the library’s axis: [-1, 1], boundary at 0 (see |
|
float array |
Stimulus as read from the CSV |
|
float array |
Category-space choice: 0=A, 1=B, NaN=no response |
|
float array |
Raw choice from CSV (before conversion) |
|
int8 array |
how the session’s task scored the trial: |
|
bool array |
|
|
float array |
the task’s category for the stimulus: 0=A, 1=B, NaN where it has none |
|
arrays (empty if unmapped) |
mapped CSV |
Optional Fields#
Field |
Type |
Description |
|---|---|---|
|
float array |
Response latency (NaN if missing) |
|
bool array |
Trial aborted |
|
bool array |
Laser on this trial |
|
str array |
Stimulus distribution label |
|
dict |
Other mapped / unmapped CSV columns |
|
dict |
Event times (columns named |
Lag-1 view#
prev_stimulus, prev_choice, prev_correct, prev_category, prev_reaction_time,
prev_opto_on, prev_has_prev are frozen on the raw session (the predecessor is the previous
non-abort trial; NaN where there is none) and sliced, never recomputed, through filtering and
pooling. trials.prev_trial exposes them as a PrevTrial.
Properties#
Property |
Returns |
Description |
|---|---|---|
|
int |
Total trial count |
|
bool array |
True where |
|
bool array |
|
SessionData#
One behavioural session — metadata + trial data.
Fields#
Field |
Type |
Description |
|---|---|---|
|
str |
|
|
str or None |
the reader’s own name for the session (folder name, table value) |
|
str |
|
|
int |
Ordinal position within animal (0-based) |
|
datetime.date |
Session date |
|
SessionMetadata |
Task parameters |
|
TrialData |
Trial-by-trial arrays |
|
str |
a type from |
|
str |
where |
|
Task |
the session’s task (the config’s |
|
str |
|
|
str |
the recording clock the event times are on ( |
|
datetime.time or None |
time of day the session started, when the reader knows it |
|
dict or None |
What filtering produced this session ( |
Properties and methods#
Name |
Returns |
Description |
|---|---|---|
|
int |
Total trials (reflects filtering) |
|
str |
Training stage (from metadata) |
|
str |
Stimulus distribution (majority label of the trials, else metadata) |
|
bool |
Whether filtering has been applied |
|
|
counts and accuracy — |
|
dict |
the trial arrays (a pure projection — nothing is filtered, aborts included); see |
Filtering trials#
Filtering uses functions from behav_utils.data; the data classes have
no filter methods.
from behav_utils import filter_trials
from behav_utils.data import build_mask, filter_session, opto_mask
clean = filter_trials(sessions, trial_type='non_opto') # aborts and laser-on trials dropped
allv = filter_trials(sessions, trial_type='all') # aborts dropped, laser trials kept
opto = filter_trials(sessions, trial_type='opto') # laser-on trials only
post = filter_trials(sessions, trial_type='post_opto') # first laser-off trial after each run
one = filter_session(sessions[0]) # one session, standard mask
pre = filter_trials(sessions, mask_fn=lambda s: build_mask(s.trials) & opto_mask(s.trials, -1),
label='pre-opto') # anything else: a mask_fn
trial_type always drops aborts and keeps no-response trials (NaN choice; every statistic ignores
them). trial_type and mask_fn are exclusive.
opto_mask(trials, delta):
delta=0— opto trials themselvesdelta=k>0— k-th non-abort, non-opto trial after each opto rundelta=-k— k-th non-abort, non-opto trial before each opto rundelta='control'— every non-abort, non-opto trial (adjacency is not considered)delta=None— every non-abort trial
SessionMetadata#
Task parameters constant within a session. Access by attribute or .get():
session.metadata.stage
session.metadata.animal_id
session.metadata.get('protocol')
session.metadata.fields # raw dict
Only animal_id and stage are read by the library; everything else is your config’s vocabulary.
AnimalData#
One animal — all sessions in chronological order.
Fields#
Field |
Type |
Description |
|---|---|---|
|
str |
Animal identifier |
|
list[SessionData] |
Chronologically ordered sessions |
|
dict |
Animal-level metadata, merged from |
Properties#
Property |
Returns |
Description |
|---|---|---|
|
int |
Session count |
|
list[str] |
All session IDs |
|
list[str] |
Stages present, in order of first appearance |
|
DataFrame |
one row per session: `session_id, animal_id, experimenter, date, start, source_id, source, session_idx, stage, distribution, |
session_type, session_type_source, task, n_trials, n_valid, n_abort, n_no_response, accuracy` — a view for picking sessions, not a statistics table |
Working with an animal#
from behav_utils import select_sessions, filter_trials, TrialArrays
from behav_utils import compute_psychometric_curve, plot_psychometric_curve
from behav_utils.plotting import PALETTE
# 1. Select sessions (presets come from your config's session_presets)
sessions = select_sessions(animal, preset='expert')
# 2. Filter trials
clean = filter_trials(sessions, trial_type='non_opto')
# 3. Compute a readout on the pooled arrays
curve = compute_psychometric_curve(TrialArrays.from_sessions(clean), n_bootstrap=200)
# 4. Draw
fig, ax = plt.subplots()
plot_psychometric_curve(curve, ax=ax, color=PALETTE[0])
ExperimentData#
All animals in one project.
Field / method |
Description |
|---|---|
|
|
|
the |
|
dict, stored by |
|
sorted ids / count |
|
one animal (KeyError with the available ids otherwise) |
|
one row per animal: sessions, stages, first/last date |
|
write or read a store (see Saving and reloading); |
load_experiment('config.yaml') builds one from your files, strictly by default (a broken session raises); on this
page the synthetic experiment from the top stands in for it.
experiment.animal_ids, experiment.n_animals
experiment.summary() # one row per animal
animal = experiment.get_animal('A05')
experiment.session_table stacks every animal’s session table (identity columns first);
discover_sessions(config) gives the same identity columns before anything is loaded.
Saving and reloading#
An experiment is saved as a store: a directory of Parquet tables and JSON that reloads exactly, whole or in part,
and that pandas, polars or R can read without behav_utils. Saving and reloading need pyarrow
(pip install 'behav_utils[store]').
<store>/store.json format, schema version, library version, creation time, counts
<store>/animals.json each animal's metadata
<store>/manifest.parquet one row per session: the session table, then task_name, task_spec,
metadata_json, clock, trials_file
<store>/trials/<file>.parquet every per-trial field of one session
import tempfile
from pathlib import Path
from behav_utils import load_store, read_manifest, save_store
path = Path(tempfile.mkdtemp()) / 'cohort1'
save_store(experiment, path) # or experiment.save(path)
manifest = read_manifest(path) # one row per session: the session table
chosen = manifest[manifest.animal_id == 'A05']
part = load_store(path, sessions=chosen) # opens only those sessions' files
The manifest is the session table that discover_sessions and experiment.session_table give, so it is filtered
the same way. A write goes to a temporary directory and is moved into place only when complete; an existing store
is replaced only with overwrite=True, and any other existing path is refused and left untouched. A store
written by a newer behav_utils (a higher schema version) is refused with a request to upgrade, and a missing trial
file is reported as an incomplete store. The lag-1 view is rebuilt on load exactly as on loading; an extra column
mixing numbers and text comes back as text. Pickle snapshots from before 1.0 cannot be opened: reload from the raw
data and save a store.
TrialArrays#
The one input type every statistic and readout consumes: aligned 1-D float arrays
choice, stimulus, category, prev_choice, prev_stimulus, prev_category, reaction_time; the task’s
score correct and prev_correct (1 correct, 0 error, NaN where the task gives none: no response,
abort, unscored) with the task that gave it; truth, the task’s correct response per trial (the category in 2-AFC, the
stimulus in reproduction); plus
trial_key (int64: the session’s hash of experimenter, animal and session id in the upper 43 bits and the trial number in the low 20, the same on every load and machine and unique across animals) when built from sessions; session.session_hash is its upper part.
from behav_utils import TrialArrays, compute_stats
from behav_utils.stats import PSYCHOMETRIC
arrays = TrialArrays.from_sessions(clean) # the pipeline path
arrays.n_trials, arrays.n_responded # counts
arrays.valid() # responded trials only
arrays.lag1_pairs() # responded with a usable predecessor
arrays.take(arrays.stimulus > 0) # row subset; prev_* and trial_key travel with the rows
arrays.trial_key # mask an external per-trial dataset to exactly these rows
trial_key survives every take, valid and resample (a repeated trial carries its key twice), so
a neural tensor indexed by the same key can be aligned to the trials a statistic actually used.
Every statistic reads correctness from correct / prev_correct, never from choice == category,
so a task’s definition (an unscored boundary, go/no-go withholds) reaches every number. Sessions of
different tasks are not pooled: pool_arrays and TrialArrays.concat raise.
TrialArrays.from_sequence(choice, stimulus, category=None, *, task=None) builds one contiguous block (a
simulator output) with no key; the task (TwoAFC() unless given) decides the categories and the score, and
given categories are only checked against it.
Pipeline pattern#
Every analysis follows the same four steps:
from behav_utils import (select_sessions, filter_trials, TrialArrays, compute_stats,
compute_psychometric_curve, compute_update_matrix, compute_phase_stats,
plot_psychometric_curve, plot_update_matrix, plot_trajectory, apply_style)
from behav_utils.plotting import PALETTE
from behav_utils.stats import PSYCHOMETRIC
apply_style()
# 1. LOAD: experiment = load_experiment('config.yaml'); here, the synthetic experiment from the top
animal = experiment.get_animal('A05')
# 2. SELECT sessions, FILTER trials
sessions = select_sessions(animal, preset='expert')
clean = filter_trials(sessions, trial_type='non_opto')
arrays = TrialArrays.from_sessions(clean)
# 3. COMPUTE — scalars, readouts, per-session trajectory
scalars = compute_stats(arrays, ['accuracy', *PSYCHOMETRIC]) # pd.Series
curve = compute_psychometric_curve(arrays, n_bootstrap=200) # PsychometricCurve
um = compute_update_matrix(arrays) # UpdateMatrix
traj = compute_phase_stats(clean, ['accuracy', 'mu'], per_session=True) # PhaseStats
# 4. PLOT — draw-only, one axes each
fig, axes = plt.subplots(1, 3, figsize=(15, 4))
plot_psychometric_curve(curve, ax=axes[0], color=PALETTE[0])
plot_update_matrix(um, ax=axes[1])
plot_trajectory(traj, 'accuracy', ax=axes[2])
Comparing two conditions#
from behav_utils import filter_trials, compute_delta_stat, compute_interaction, select_sessions
from behav_utils.plotting import plot_psychometric_comparison, plot_stat_comparison, plot_stat_comparison_grid
from behav_utils.stats import PSYCHOMETRIC
off = filter_trials(sessions, trial_type='non_opto')
on = filter_trials(sessions, trial_type='opto')
# Within-session, per-trial randomised label: a permutation p is valid, and trials are a valid unit.
# The session unit draws the same sessions for both phases, so that interval is paired.
d = compute_delta_stat({'off': off, 'on': on}, ['accuracy', *PSYCHOMETRIC], reference='off',
n_bootstrap=1000, n_permutations=1000, units=('trials', 'sessions'))
fig, axes = plt.subplots(1, 2)
plot_psychometric_comparison(d, ax=axes[0]) # psychometric curves of both conditions
plot_stat_comparison(d, 'mu', ax=axes[1]) # one stat: a point + CI per phase
plot_stat_comparison_grid(d, ['mu', 'sigma']) # the layout helper: one panel per stat
# Different sessions (e.g. two distributions): no permutation, sessions are the unit. Here the first and
# last three task sessions stand in for sessions on two distributions.
task_sessions = filter_trials(select_sessions(animal, stage='task'), trial_type='non_opto')
d2 = compute_delta_stat({'uniform': task_sessions[:3], 'hard': task_sessions[3:]}, ['mu'], reference='uniform',
units=('sessions',))
compute_delta_stat refuses n_permutations > 0 when a phase shares no session with the
reference, and n_permutations defaults to 0. It returns a DeltaStats:
field |
what it holds |
|---|---|
|
|
|
|
|
the reference label |
Contrast.boot(unit) gives ci_lo, ci_hi, p, median, n_draws per stat; Contrast.table(unit) one
tidy row per stat (diff, ci_lo, ci_hi, boot_p, perm_p, unit). Units: 'trials' (valid only when the
condition was randomised per trial) and 'sessions' (always valid). compute_interaction(d1, d2, key)
gives the delta of deltas as an Interaction, with plot_interaction(ix, stat, ax=).
Group-level claims (across animals)#
For across-animal comparisons (two groups, or paired on/off effects), use the group-level functions —
never pool trials across animals. compute_phase_stats turns each animal’s sessions into one pooled
row per stat (stamped with the animal id from the data); analysis.group tests the per-animal
values. The animal is the unit.
from behav_utils.analysis import collect_rows, compare_groups, paired_diff, bootstrap_units
from behav_utils import compute_phase_stats
from behav_utils.stats import PSYCHOMETRIC
# One pooled row per animal, stamped with its group
rows = []
for animal in experiment.animals.values():
clean = filter_trials(select_sessions(animal, preset='expert'), trial_type='non_opto')
r = compute_phase_stats(clean, [*PSYCHOMETRIC, 'accuracy'])
rows += collect_rows(r.to_rows().to_dict('records'), animal=animal.animal_id,
group=animal.metadata['group'])
# Unpaired (between-group): one rank test per stat, control first
res = compare_groups(rows, groups=('control', 'treated')) # GroupComparison
res.test('mu').p, res.test('mu').min_p # min_p = floor at these group sizes
res.table() # one tidy row per stat
# Paired (on vs off within the same animals): one row per animal and condition, per-animal Δ,
# then an across-animal CI
rows_on, rows_off = [], []
for a in experiment.animals.values():
task = select_sessions(a, stage='task')
for condition, trial_type, out in (('on', 'opto', rows_on), ('off', 'non_opto', rows_off)):
r = compute_phase_stats(filter_trials(task, trial_type=trial_type), ['mu'])
out += collect_rows(r.to_rows().to_dict('records'), animal=a.animal_id, condition=condition)
points = pd.DataFrame(rows_on + rows_off) # rows stamped condition='on' / 'off'
delta = paired_diff(points, by='condition', a='on', b='off')
bootstrap_units(delta[delta.stat == 'mu'].delta.values) # UnitBootstrap(point, lo, hi, n)
# or in one call, aligned by animal:
compare_groups(rows_on + rows_off, group_col='condition', groups=('on', 'off'), paired=True)
Psychometric naming convention#
Psychometric fit parameters use math names everywhere in code:
Code key |
Display label |
Meaning |
|---|---|---|
|
PSE |
Point of subjective equality (boundary) |
|
slope |
Noise width (smaller = steeper psychometric) |
|
λ_low |
Lower asymptote lapse |
|
λ_high |
Upper asymptote lapse |
|
Accuracy |
Overall correctness |
Plot functions translate mu/sigma to PSE/slope for y-axis labels. You write 'mu' in code;
the plot shows “PSE”.
# Per-session trajectory of PSE
r = compute_phase_stats(clean, ['accuracy', 'mu', 'sigma'], per_session=True)
plot_trajectory(r, 'mu') # y-axis label: "PSE"
plot_trajectory(r, 'sigma') # y-axis label: "slope"
Synthetic Data#
Synthetic sessions come from a model (behav_utils.models): anything with simulate(design, rng). Each session
has every trial class (responses, no-responses where the task has them, aborts, and with laser_fraction laser
trials and the trials after them) and event times on a clock named synthetic, and is scored by its task:
from behav_utils import PsychometricModel, generate_synthetic_animal, generate_synthetic_experiment
# One model for every session
animal = generate_synthetic_animal(PsychometricModel(sigma=0.3), n_sessions=20, trials_per_session=200,
animal_id='SYN01', rng=0)
# A learning trajectory: one model per session, with laser trials
models = [PsychometricModel(sigma=0.8 - i * 0.03) for i in range(20)]
learner = generate_synthetic_animal(models, n_sessions=20, animal_id='LEARN01', laser_fraction=0.3, rng=1)
# An experiment: animals with groups, each on its own random stream
experiment = generate_synthetic_experiment(
{'A01': {'model': PsychometricModel(sigma=0.3), 'metadata': {'group': 'control'}},
'A02': {'model': PsychometricModel(sigma=0.5), 'metadata': {'group': 'treated'}}},
rng=2,
)
distribution (a behav_utils.tasks distribution) and label set the stimuli and their label, per session if
given as lists; task=GoNoGo() gives go/no-go sessions, where a blank is a withhold; timing=Timing(...) sets the
inter-trial interval, stimulus delay and reaction times. A model of your own, a learner included, is shown in
EXTENDING.md; simulate(model, make_design(...)) runs a single design, and session_from_arrays builds a
session from arrays you already have.