behav_utils.data#
behav_utils.data — data structures, loading, selection, filtering and synthetic data.
Hierarchical containers, config-driven loading, session selection, trial-level filtering, and synthetic generation.
Pipeline:
load_experiment(config) → ExperimentData (reader → build_session)
select_sessions(animal, preset='expert') → List[SessionData]
filter_trials(sessions, trial_type='non_opto') → List[SessionData]
TrialArrays.from_sessions(clean) → TrialArrays (pool_arrays underneath)
- class behav_utils.data.ExperimentData(animals=<factory>, metadata=<factory>, config=None)[source]#
Top-level container for all animals, with the config they were loaded with.
load_experimentreturns one, andgenerate_synthetic_experimentbuilds one with the same structure. It answers queries across animals:get_animal,summary,session_table.- Variables:
animals (Dict[str, behav_utils.data.structures.AnimalData]) – The animals,
{animal_id: AnimalData}.metadata (Dict[str, Any]) – Free-form metadata about the experiment.
config (Any | None) – The
ProjectConfigit was loaded with; None when built in code.
- Parameters:
animals (Dict[str, AnimalData])
metadata (Dict[str, Any])
config (Any | None)
- add_animal(animal)[source]#
Add an animal, keyed by its id.
- Parameters:
animal (AnimalData) – The animal to add.
- Return type:
None
- get_animal(animal_id)[source]#
One animal, by its id.
- Parameters:
animal_id (str) – The animal’s id.
- Returns:
The animal.
- Return type:
- property session_table: DataFrame#
the identity columns first (as
discover_sessionsgives them), then each session’s summary.- Type:
Every animal’s sessions in one table
- summary()[source]#
One-row-per-animal summary.
- Returns:
A table with each animal’s number of sessions, stages and first and last dates.
- Return type:
DataFrame
- save(path, *, overwrite=False)[source]#
Save the experiment as a store: a directory of Parquet tables and JSON that reloads exactly.
The store can be reloaded whole or in part (see
save_storeandload_store). The config is not stored; reload it from its YAML.- Parameters:
path (str | Path) – The store’s directory.
overwrite (bool) – Replace an existing store at
path; any other existing path is refused.
- Returns:
The store’s path.
- Return type:
Path
- classmethod load(path, *, sessions=None, strict=True)[source]#
Load a store written by
save, whole or only the chosen sessions.Pickle snapshots from before 1.0 cannot be opened: reload from the raw data with
load_experimentand save again.- Parameters:
path (str | Path) – The store’s directory.
sessions – Only these sessions: a filtered
read_manifestor session ids; None for all.strict (bool) – Raise when the store does not have a requested session (the default); False warns instead.
- Returns:
The experiment.
- Return type:
- class behav_utils.data.AnimalData(animal_id, sessions, metadata=<factory>)[source]#
All data for a single animal: its sessions, in chronological order, and its metadata.
select_sessionspicks sessions from it by preset or criteria, andsession_tablehas one row per session for picking them by hand.- Variables:
animal_id (str) – The animal’s id.
sessions (List[behav_utils.data.structures.SessionData]) – Its sessions,
SessionData, in chronological order.metadata (Dict[str, Any]) – Per-animal metadata from the config’s
animal_metadatafile (group, for example).
- Parameters:
animal_id (str)
sessions (List[SessionData])
metadata (Dict[str, Any])
_config (Any | None)
_session_table_cache (DataFrame | None)
- property session_ids: list#
List of session IDs in chronological order.
- property session_table: DataFrame#
One-row-per-session summary table for selection masks.
- create_session_table()[source]#
One row per session — a tabular view for building selection masks.
Convenience for picking sessions (not trials). Mask against it like any DataFrame, for example
t[t.session_type == 'opto']for the sessions with laser trials.Columns (exactly these; the per-session statistics come from
compute_phase_stats(..., per_session=True), not from here):session_idx, session_id, date, stage, distribution, session_type, n_trials, n_valid, n_abort, n_no_response, accuracy
session_typeis ‘regular’ | ‘opto’ (derived from the data) or a type stamped fromconfig.session_types;session_type_sourcesays which.accuracyisSessionData.summary().accuracy. Trial-level opto masks are not a session property — usefilter_trials(trial_type=...).- Returns:
The table, one row per session.
- Return type:
DataFrame
- get_sessions(stage=None, distribution=None, idx=None, idx_range=None, mask=None, date_range=None, return_indices=False)[source]#
Filter sessions by criteria.
- Parameters:
stage (str | List[str] | None) – Stage filter. A single string matches exactly; a list matches any (OR logic). None = no filter.
distribution (str | List[str] | None) – Distribution filter. A single string matches exactly; a list matches any (OR logic). None = no filter.
idx (int | List[int] | ndarray | None) – Specific session_idx values to include (int or list).
idx_range (Tuple[int, int] | None) – (start, end) session_idx range (inclusive)
mask (ndarray | Series | None) – Boolean mask, length = n_sessions, positionally aligned with self.sessions (i.e. with session_table rows). Selects sessions.
date_range (Tuple[date, date] | None) – (start, end) date range (inclusive)
return_indices (bool) – If True, also return session_idx values.
- Returns:
The matching sessions, in chronological order. With
return_indices=True, the tuple(sessions, indices), whereindicesholds each matched session’ssession_idx.- Return type:
List[SessionData] | Tuple[List[SessionData], List[int]]
- save(path, *, overwrite=False)[source]#
Save this animal as a store: a directory of Parquet tables and JSON that reloads exactly.
- Parameters:
path (str | Path) – The store’s directory.
overwrite (bool) – Replace an existing store at
path.
- Returns:
The store’s path.
- Return type:
Path
- class behav_utils.data.SessionData(session_id, session_idx, date, metadata, trials, session_type='regular', start=None, session_type_source='derived', source_id=None, experimenter='', task=<factory>, task_name='default', clock='', source=None, filter_info=None)[source]#
All data for a single behavioural session.
- Variables:
session_id (str) –
<animal>_<YYYYMMDD>, plusT<HHMM>when the start time is known; sessions that would still share an id are all numbered_1,_2, … in name order (set at load).session_idx (int) – Position among the animal’s sessions, 0-based and chronological.
date (datetime.date) – The session’s date.
metadata (behav_utils.data.structures.SessionMetadata) –
SessionMetadata: stage, contingency, protocol and the other session-level fields.trials (behav_utils.data.structures.TrialData) – The per-trial arrays,
TrialData.session_type (str) – ‘regular’ or ‘opto’, derived from the data, or a project type stamped from
config.session_types(e.g. ‘sham’); the one place a session’s type is kept.start (datetime.time | None) – Time of day the session started, when the reader knows it.
session_type_source (str) – Where
session_typecame from: ‘config’ (asession_typeslist), ‘column’ (a mapped session_type field) or ‘derived’ (the trials).source_id (str | None) – The reader’s own name for the session (a folder name, a table value).
experimenter (str) – Whose session (
project.experimenter, or the animal metadata’s).task (behav_utils.tasks.base.Task) – The session’s
Task, built from the config; it alone defines what is correct.task_name (str) – ‘default’, or the
tasksentry thattask_bypicked.clock (str) – The clock the event times are on (
config.clock.name; ‘’ if none).source (str | None) – Where the reader found the session (a folder, a file, a table key).
filter_info (Dict[str, Any] | None) – What filtering produced this session; None if it is unfiltered.
- Parameters:
session_id (str)
session_idx (int)
date (date)
metadata (SessionMetadata)
trials (TrialData)
session_type (str)
start (time | None)
session_type_source (str)
source_id (str | None)
experimenter (str)
task (Task)
task_name (str)
clock (str)
source (str | None)
filter_info (Dict[str, Any] | None)
_days_since_first (float | None)
To filter,
filter_session(session)drops aborted and laser-on trials and takes a mask for anything else; Filtering trials in the data-structures reference shows it on synthetic data.- property session_hash: int#
the upper bits of this session’s trial keys, the same on every machine and every load.
- Type:
43-bit hash of experimenter, animal and session id
- property n_trials: int#
Number of trials (reflects filtering if filtered).
- property is_filtered: bool#
Whether this session has been through filter().
- get_arrays()[source]#
The session’s trial arrays as a dict, a projection of
trialsthat filters nothing.Aborted trials included;
get_arraysis called with this session, so thetrial_keysare unique across sessions and animals.- Returns:
The arrays, keyed as in
behav_utils.data.get_arrays.- Return type:
Dict[str, ndarray]
- class behav_utils.data.SessionMetadata(fields=<factory>)[source]#
Session-level metadata (constant within a session). Populated from the config’s session_metadata mappings.
The ‘fields’ dict holds all metadata key-value pairs. Common fields are exposed as properties for convenience.
- Variables:
fields (Dict[str, Any]) – Every metadata field of the session,
{name: value}.- Parameters:
fields (Dict[str, Any])
- class behav_utils.data.SessionSummary(session_id, session_idx, date, stage, distribution, session_type, n_trials, n_valid, n_abort, n_no_response, accuracy, start=None, session_type_source='derived', task='two_afc', animal_id='', experimenter='', source_id=None, source=None, filter=None)[source]#
Counts and accuracy of one session (
SessionData.summary()).accuracyis fraction correct over valid trials (non-abort, responded): the one definition of session accuracy in the library, used bySessionFilter.min_accuracyandAnimalData.session_table.- Variables:
session_id (str) – The session’s id.
session_idx (int) – Its position among the animal’s sessions.
date (datetime.date) – Its date.
stage (str) – Its stage, from the metadata.
distribution (str) – Its distribution label, from the metadata.
session_type (str) – Its type, as in
SessionData.session_type.n_trials (int) – All trials the session holds.
n_valid (int) – Trials neither aborted nor without a response.
n_abort (int) – Aborted trials.
n_no_response (int) – Trials without a response.
accuracy (float) – The fraction correct over valid trials.
start (datetime.time | None) – Time of day the session started, when known.
session_type_source (str) – Where
session_typecame from.task (str) – The name of the session’s task block.
animal_id (str) – The animal.
experimenter (str) – Whose session.
source_id (str | None) – The reader’s own name for the session.
source (str | None) – Where the reader found it.
filter (str | None) – What filtering produced the session; None if unfiltered.
- Parameters:
session_id (str)
session_idx (int)
date (date)
stage (str)
distribution (str)
session_type (str)
n_trials (int)
n_valid (int)
n_abort (int)
n_no_response (int)
accuracy (float)
start (time | None)
session_type_source (str)
task (str)
animal_id (str)
experimenter (str)
source_id (str | None)
source (str | None)
filter (str | None)
- class behav_utils.data.TrialData(trial_number, stimulus, choice, outcome, correct, category, choice_raw=<factory>, stimulus_raw=<factory>, reaction_time=<factory>, abort=<factory>, opto_on=<factory>, distribution=<factory>, correct_recorded=<factory>, outcome_recorded=<factory>, optional_fields=<factory>, extra=<factory>, events=<factory>, prev_stimulus=<factory>, prev_choice=<factory>, prev_correct=<factory>, prev_category=<factory>, prev_reaction_time=<factory>, prev_opto_on=<factory>, prev_has_prev=<factory>)[source]#
Per-trial arrays for a single session, all of the same length.
Functions in
behav_utils.data(build_mask,opto_mask,filter_session,filter_trials) build new TrialData; nothing here filters.- Variables:
trial_number (numpy.ndarray) – 1-based trial number, as read.
stimulus (numpy.ndarray) – The stimulus on the library’s axis, [-1, 1] with the category boundary at 0 (the loader applies the config’s
tasktransform, the identity for data already on that axis).choice (numpy.ndarray) – The response in category space: 0 = A, 1 = B, NaN = no response.
outcome (numpy.ndarray) – How the session’s task scored the trial, as
Outcomecodes (int8).correct (numpy.ndarray) –
outcome == Outcome.CORRECT.category (numpy.ndarray) – The task’s category for the stimulus: 0, 1, or NaN where it has none.
choice_raw (numpy.ndarray) – The response as read, before mapping to category space.
stimulus_raw (numpy.ndarray) – The stimulus as read.
reaction_time (numpy.ndarray) – Response latency in seconds; NaN where missing.
abort (numpy.ndarray) – Whether the trial was aborted.
opto_on (numpy.ndarray) – Whether the laser was on in the trial.
distribution (numpy.ndarray) – The stimulus distribution’s label.
correct_recorded (numpy.ndarray) – A mapped
correctcolumn, kept to check the task’s score against; empty if unmapped.outcome_recorded (numpy.ndarray) – A mapped
outcomecolumn, likewise.optional_fields (Dict[str, numpy.ndarray]) – Mapped optional columns,
{name: array}.extra (Dict[str, numpy.ndarray]) – Columns the config does not map,
{name: array}.events (Dict[str, numpy.ndarray]) – Event times (columns named
t_*) in float64 seconds on the session’s clock,{name: array}.prev_stimulus (numpy.ndarray) – The stimulus of the previous non-aborted trial; NaN where there is none.
prev_choice (numpy.ndarray) – That trial’s choice.
prev_correct (numpy.ndarray) – Whether that trial was correct, as 1.0, 0.0 or NaN.
prev_category (numpy.ndarray) – That trial’s category.
prev_reaction_time (numpy.ndarray) – That trial’s reaction time.
prev_opto_on (numpy.ndarray) – Whether the laser was on in that trial.
prev_has_prev (numpy.ndarray) – Whether the trial has such a previous trial.
- Parameters:
trial_number (ndarray)
stimulus (ndarray)
choice (ndarray)
outcome (ndarray)
correct (ndarray)
category (ndarray)
choice_raw (ndarray)
stimulus_raw (ndarray)
reaction_time (ndarray)
abort (ndarray)
opto_on (ndarray)
distribution (ndarray)
correct_recorded (ndarray)
outcome_recorded (ndarray)
optional_fields (Dict[str, ndarray])
extra (Dict[str, ndarray])
events (Dict[str, ndarray])
prev_stimulus (ndarray)
prev_choice (ndarray)
prev_correct (ndarray)
prev_category (ndarray)
prev_reaction_time (ndarray)
prev_opto_on (ndarray)
prev_has_prev (ndarray)
The
prev_*arrays are computed once on the raw session, skipping aborts but not laser or no-response trials, and carried unchanged through filtering and pooling, so a filtered trial’s previous trial is still the one the animal saw.- property n_trials: int#
Number of trials.
- property no_response: ndarray#
True where choice is NaN (animal didn’t respond).
- Type:
Boolean mask
- property valid_mask: ndarray#
non-abort, responded trials.
- Type:
Boolean mask
- property prev_trial: PrevTrial#
Lag-1 view of the previous trial’s values (see PrevTrial). Frozen on the raw session and carried through filtering/pooling, so it stays the real predecessor even after interleaved trials are removed.
- class behav_utils.data.TrialArrays(choice, stimulus, category, prev_choice=None, prev_stimulus=None, prev_category=None, reaction_time=None, trial_key=None, correct=None, prev_correct=None, task=None, truth=None)[source]#
Aligned per-trial arrays for one block of (pre-filtered) trials.
All fields are 1-D float arrays of equal length.
choiceis NaN on no-response trials;prev_*are NaN where there is no usable predecessor.trial_key(int64, or None) identifies each row across resampling.correctandprev_correctare the task’s score: 1.0 correct, 0.0 error, NaN where the task gives none (no response, abort, unscored).taskis the Task that scored them; every statistic reads correctness from here, never fromchoice == category. Built without a score (by hand), both are derived from the task (TwoAFC()unless given).truthis the task’s correct response per trial (the category in 2-AFC, the stimulus in reproduction), so error statistics never recompute it.- Variables:
choice (numpy.ndarray) – The response in category space; NaN on no-response trials.
stimulus (numpy.ndarray) – The stimulus on the library’s axis.
category (numpy.ndarray) – The task’s category for the stimulus.
prev_choice (numpy.ndarray) – The previous trial’s choice; NaN where there is no usable predecessor.
prev_stimulus (numpy.ndarray) – The previous trial’s stimulus, likewise.
prev_category (numpy.ndarray) – The previous trial’s category, likewise.
reaction_time (numpy.ndarray) – Response latency in seconds.
trial_key (numpy.ndarray | None) – The row’s identity across resampling (int64), or None.
correct (numpy.ndarray | None) – The task’s score: 1.0 correct, 0.0 error, NaN where the task gives none.
prev_correct (numpy.ndarray | None) – The previous trial’s score, likewise.
task (behav_utils.tasks.base.Task | None) – The
Taskthat scored the trials.truth (numpy.ndarray | None) – The task’s correct response per trial.
- Parameters:
choice (ndarray)
stimulus (ndarray)
category (ndarray)
prev_choice (ndarray)
prev_stimulus (ndarray)
prev_category (ndarray)
reaction_time (ndarray)
trial_key (ndarray | None)
correct (ndarray | None)
prev_correct (ndarray | None)
task (Task | None)
truth (ndarray | None)
- classmethod from_pooled(pooled)[source]#
Arrays from the dict that
pool_arraysorget_arraysreturns.- Parameters:
pooled (Mapping[str, ndarray]) – That dict.
- Returns:
The arrays.
- Return type:
- classmethod from_sessions(sessions)[source]#
Arrays from pre-filtered sessions, pooled with
pool_arrays.- Parameters:
sessions (Sequence) – The sessions, already selected and filtered.
- Returns:
The arrays, with the previous-trial view carried from each raw session and a
trial_keyper row.- Return type:
- classmethod from_sequence(choice, stimulus, category=None, reaction_time=None, *, task=None)[source]#
From one contiguous block with no carried lag-1 view.
The task (
TwoAFC()unless given) decides the categories and scores the trials, exactly as on loading: a go/no-go blank is read as a withhold.category, if given, is only checked against the task’s.The predecessor of trial t is trial t-1 by adjacency, with no predecessor at t = 0. A no-response predecessor carries its NaN choice through (so
has_previs False there) while its stimulus and category are still recorded — the same rule the loader applies when it freezes the lag-1 view on a raw session, so this matchesfrom_sessionsexactly on one abort-free block.- Parameters:
choice – Responses, NaN where there is none.
stimulus – Stimuli on the library’s axis.
category – Categories to check against the task’s; None to take the task’s.
reaction_time – Reaction times in seconds; None for all NaN.
task (Task | None) – The task that decides categories and scores the trials; None for
TwoAFC().
- Returns:
The arrays, with no
trial_keyand the previous trial taken from array order.- Return type:
- with_trial_key(trial_key)[source]#
A copy with
trial_keyset.- Parameters:
trial_key – One int64 key per row.
- Returns:
The copy.
- Return type:
- property responded: ndarray#
Boolean mask of trials with a recorded choice.
- property has_prev: ndarray#
Boolean mask of trials with a usable (responded, same-block) predecessor.
- valid()[source]#
Responded trials only.
The
prev_*view is kept as it was, not re-shifted.- Returns:
The subset.
- Return type:
- take(mask_or_index)[source]#
A subset of rows;
prev_*andtrial_keytravel with them.- Parameters:
mask_or_index – A boolean mask, or integer positions.
- Returns:
The subset.
- Return type:
- static concat(items)[source]#
Rows of several arrays, one after another.
trial_keyis kept only if every item carries one.- Parameters:
items (Sequence[TrialArrays]) – The arrays to join.
- Returns:
The joined arrays.
- Raises:
ValueError – There is nothing to join, or the items were scored by different tasks.
- Return type:
- behav_utils.data.trial_key_of(session, trial_number)[source]#
The int64 trial keys of one session’s trials: its session hash above the trial number’s 20 bits.
- Parameters:
session – The session; its experimenter, animal and session id are hashed.
trial_number – Trial numbers, each between 0 and 1,048,575.
- Returns:
One key per trial number.
- Return type:
ndarray
- behav_utils.data.load_experiment(config_or_path, *, reader=None, strict=True, sessions=None)[source]#
Load every session a reader finds, or the chosen
sessions, into an ExperimentData.Sessions in
sessions_to_ignoreare dropped before their tables are read. Animal metadata comes fromanimal_metadata(oranimal_metadata.jsonin the csv_folders data directory); thensession_typesare stamped andsession_presetsregistered.- Parameters:
config_or_path (ProjectConfig | str | Path) – A
ProjectConfig, or the path of a YAML config.reader (Callable[[...], Iterable[RawSession]] | None) – Where the trial tables come from; by default the reader the config’s
reader:block names. Any callable that takes the config and yieldsRawSessionobjects works, and one that accepts astrictkeyword is given this function’s.strict (bool) – Raise on the first session that fails to load (the default); False logs it and skips it.
sessions (DataFrame | Iterable[str] | None) – Only these sessions: a table with a
session_idcolumn (discover_sessions, filtered) or session ids. The others are never read, andsessions_to_ignorestill applies.
- Returns:
The experiment, its animals sorted by id and each animal’s sessions in chronological order.
- Raises:
FileNotFoundError – The config file, or the
animal_metadatafile it names, does not exist.ConfigError – The config cannot be used as written.
RuntimeError – With
strict, a session failed to load; the message names it and the reason.ValueError – A
sessionstable has nosession_idcolumn, or, withstrict, the reader does not find a requested session.
- Warns:
UserWarning – Without
strict, the reader does not find a requested session. Also, once per value, a session type read from a column that is neither derived nor listed insession_types, which is usually a typo.- Return type:
- behav_utils.data.load_animal(animal_dir, config, *, strict=True)[source]#
Load one animal folder with the csv_folders reader: every sub-directory is a session folder.
Sessions in
sessions_to_ignoreare not read; a session that fails raises understrictand is logged and skipped otherwise.- Parameters:
animal_dir (str | Path) – The animal’s folder.
config (ProjectConfig) – The project config.
strict (bool) – Raise on the first session that fails to load (the default); False logs it and skips it.
- Returns:
The animal, its sessions in chronological order.
- Return type:
- behav_utils.data.load_session_csv(csv_path, config, *, date=None)[source]#
Load one CSV file as one session, by the csv_folders reader’s rules for a single file.
The date is
dateif given, else read withreader.date_regexfrom the folder name, else from the file name. The animal is the mappedanimal_idcolumn when there is one, else the grandparent folder; the session id is the parent folder.- Raises:
ValueError – no date, no rows left, or a missing required column.
- Parameters:
csv_path (str | Path) – The file.
config (ProjectConfig) – The project config.
date (date | None) – The session’s date; None to read it from the folder or file name.
- Returns:
The session.
- Return type:
- behav_utils.data.build_session(raw, config, *, strict=True, session_idx=0, source_id=None)[source]#
One raw session → SessionData: the half of loading that every reader shares.
Checks the required columns, reads session metadata from the first row, maps and coerces the trial columns, normalises the stimulus, converts the choice and derives the category, correctness and session type. The animal id is the reader’s; a mapped
animal_idcolumn that disagrees raises (strict) or warns and is overwritten. Trial numbers must be unique (repeats raise, or withstrict=Falsewarn and are renumbered from 1) and lie in 0..1,048,575, the trial key’s range.AnimalDatasetssession_idx; the loader passes the canonical session id inrawand the reader’s own name assource_id.- Raises:
ValueError – no date, no trials, a missing required column, or (strict) an animal-id mismatch.
- Parameters:
raw (RawSession) – The raw session from a reader.
config (ProjectConfig) – The project config.
strict (bool) – Raise when the session cannot be built (the default); False lets the caller skip it.
session_idx (int) – The session’s position among the animal’s sessions.
source_id (str | None) – The reader’s own name for the session; None to take
raw’s.
- Returns:
The session.
- Return type:
- class behav_utils.data.RawSession(animal_id, session_id, date, trials, start=None, metadata=<factory>, source=None, files=<factory>, peek=None)[source]#
One session as a reader found it, before any column mapping.
- Variables:
animal_id (str) – the animal, as the data layout names it
session_id (str) – the session, unique within the animal
date (datetime.date | None) – the session’s date; None when the reader could not tell (the loader refuses it)
trials (pandas.DataFrame | Callable[[], pandas.DataFrame]) – the raw trial table, or a function that reads it
start (datetime.time | None) – the time of day the session started, when known; orders sessions within a day
metadata (Mapping[str, Any]) – reader-supplied session metadata; config-mapped columns take precedence
source (str | None) – where it came from (a folder, a file, a table and key), for messages
files (Mapping[str, Any]) – related files the reader knows about, by name ({‘video’: path}); discovery shows them as
file_<name>columns. The library defines no names.peek (Callable[[...], pandas.DataFrame] | None) – optional cheap look at the trials,
peek(columns=None, nrows=None): the firstnrowsrows, or onlycolumns, under the reader’s own row rules. Discovery uses it; without one it reads the whole table.
- Parameters:
animal_id (str)
session_id (str)
date (date | None)
trials (DataFrame | Callable[[], DataFrame])
start (time | None)
metadata (Mapping[str, Any])
source (str | None)
files (Mapping[str, Any])
peek (Callable[[...], DataFrame] | None)
- behav_utils.data.csv_folder_reader(config, *, strict=True)[source]#
The
csv_foldersreader.Every sub-directory of
data_diris an animal, and every sub-directory of an animal a session folder; the config’sreader:block holds the settings.- Parameters:
config (ProjectConfig) – The project config.
strict (bool) – Raise on a session folder that cannot be read (the default); False skips it.
- Returns:
The raw sessions, one at a time.
- Return type:
Iterator[RawSession]
- behav_utils.data.table_reader(source, *, animal, session, date, start=None)[source]#
A reader over one table holding every trial.
The table is a DataFrame, or a
.csv,.tsvor.parquetpath (relative paths resolve against the config file’s folder; Parquet needs pyarrow).animalandsessionname the columns that identify a session,datethe column that dates it, andstartan optional column with its start time. Sessions keep their order of first appearance and their rows keep table order.- Parameters:
source (str | Path | DataFrame) – The table, or the path of a .csv, .tsv or .parquet file.
animal (str) – The column naming each row’s animal.
session (str) – The column naming each row’s session.
date (str) – The column holding each session’s date.
start (str | None) – The column holding each session’s start time; None for none.
- Returns:
A reader, to pass as
load_experiment(config, reader=...).- Return type:
Callable[[…], Iterable[RawSession]]
- behav_utils.data.is_empty_csv(path)[source]#
True for a file with nothing in it, not even a header (a run stopped before writing anything). The reader skips such files; projects that re-read the CSVs should do the same.
- Parameters:
path (str | Path) – The file.
- Returns:
Whether the file is empty.
- Return type:
bool
- behav_utils.data.select_sessions(animal, preset=None, **overrides)[source]#
Select sessions from an animal using a preset and/or keyword criteria.
Three ways to call it: a preset alone (
select_sessions(animal, 'expert')), a preset with fields overridden (select_sessions(animal, 'expert', min_accuracy=0.80)), or fields alone (select_sessions(animal, stage='task', last_n=5)).A preset is resolved on the animal’s own config (
session_presetsof the experiment it was loaded with) before the process-wide registry, so two experiments loaded in one session never see each other’s presets.- Parameters:
animal (AnimalData) – The animal to select from.
preset (str | None) – The name of a preset, from the animal’s config (
session_presets) or registered withregister_preset; None for criteria alone.**overrides (Any) –
SessionFilterfields, on their own or overriding the preset’s.
- Returns:
The matching sessions, in chronological order; possibly none.
- Raises:
KeyError –
presetis neither in the animal’s config nor registered.TypeError – An override is not a
SessionFilterfield.
- Return type:
List[SessionData]
- class behav_utils.data.SessionFilter(stage=None, distribution=None, session_type=None, min_accuracy=None, max_accuracy=None, last_fraction=None, first_n=None, last_n=None, last_n_qualifying=None, after_session_idx=None, before_session_idx=None, session_indices=None, min_trials=10, exclude_opto=False, exclude_types=(), custom_filter=None)[source]#
Immutable session selection criteria.
Every field is optional; None means no constraint.
select_sessionsapplies them in this order, each step narrowing the previous: metadata (stage,distribution); session type (session_type, or else the exclusionsexclude_optoandexclude_types); index range (after_session_idx,before_session_idx,session_indices); position (last_fraction,first_n,last_n); quality (min_accuracy,max_accuracy,min_trials);last_n_qualifying; andcustom_filter. Which sessions count is settled before any position is taken, solast_n=5withexclude_types=('sham',)gives the last five sessions that are not sham.- Variables:
stage (str | List[str] | None) – Task stage (exact match, or list for OR-logic)
distribution (str | List[str] | None) – Stimulus distribution (exact match, or list for OR-logic)
session_type (str | List[str] | None) – Session type — ‘regular’, ‘opto’, or any project type stamped from config.session_types (e.g. ‘sham’). Accepts a string or list. When set, exclude_opto and exclude_types are ignored (the caller is explicitly choosing which types to include).
min_accuracy (float | None) – Minimum session accuracy (fraction correct)
max_accuracy (float | None) – Maximum session accuracy
last_fraction (float | None) – Keep only the last X fraction of sessions (applied BEFORE accuracy filtering)
first_n (int | None) – Keep only the first N sessions (after the metadata, session-type and exclusion filters)
last_n (int | None) – Keep only the last N sessions (likewise)
last_n_qualifying (int | None) – Keep only the last N sessions that pass the quality filters (applied AFTER min_accuracy / max_accuracy / min_trials, unlike last_n which is applied before them)
after_session_idx (int | None) – Only sessions with session_idx > this value
before_session_idx (int | None) – Only sessions with session_idx < this value
session_indices (List[int] | None) – Explicit list of session_idx values to include
min_trials (int) – Minimum valid (non-abort, responded) trials
exclude_opto (bool) – If True, exclude sessions with opto trials (ignored when session_type is set). Applied before the positional steps.
exclude_types (Tuple[str, ...]) – Session types to drop when session_type is not set, e.g. (‘sham’, ‘washout’). The names are the project’s; the library derives only ‘regular’ and ‘opto’ from the data. Applied before the positional steps.
custom_filter (Callable | None) – Callable(SessionData) -> bool for arbitrary filtering
- Parameters:
stage (str | List[str] | None)
distribution (str | List[str] | None)
session_type (str | List[str] | None)
min_accuracy (float | None)
max_accuracy (float | None)
last_fraction (float | None)
first_n (int | None)
last_n (int | None)
last_n_qualifying (int | None)
after_session_idx (int | None)
before_session_idx (int | None)
session_indices (List[int] | None)
min_trials (int)
exclude_opto (bool)
exclude_types (Tuple[str, ...])
custom_filter (Callable | None)
- apply(animal)[source]#
Apply this filter to an animal’s sessions.
- Parameters:
animal (AnimalData) – The animal.
- Returns:
The matching sessions, in chronological order; possibly none.
- Return type:
List[SessionData]
- behav_utils.data.register_preset(name, filt)[source]#
Register a named session filter preset, replacing any of the same name.
- Parameters:
name (str) – The preset’s name, e.g. ‘expert’.
filt (SessionFilter) – The criteria.
- Raises:
TypeError –
filtis not aSessionFilter.- Return type:
None
- behav_utils.data.list_presets()[source]#
Return {name: description} for all registered presets.
- Returns:
{name: description}for every preset registered in this process, sorted by name; the description is the preset’sSessionFilter.describe().- Return type:
Dict[str, str]
- behav_utils.data.register_presets_from_config(config_raw)[source]#
Register the
session_presetsof a parsed YAML config in the process-wide registry.load_experimentdoes this; the config’s own copy, kept on each animal, takes priority inselect_sessions. Each entry is a dict ofSessionFilterfields under the preset’s name.- Parameters:
config_raw (Dict[str, Any]) – The parsed config, as a dict.
- Returns:
How many presets were registered.
- Return type:
int
- behav_utils.data.preset_from_spec(name, spec)[source]#
Build a SessionFilter from a raw
session_presetsentry (YAML dict).Unknown fields are ignored with a warning;
exclude_typeslists become tuples.- Parameters:
name (str) – The preset’s name, used in warnings.
spec (Dict[str, Any]) – The raw entry, a dict of
SessionFilterfields.
- Returns:
The filter.
- Return type:
- behav_utils.data.find_switches(sessions, *, min_block_trials=0)[source]#
Boundaries between consecutive qualifying blocks.
- Parameters:
sessions (Sequence) – Sessions in order, typically one animal’s.
min_block_trials (int) – As in
find_blocks, the fewest trials a run needs to count as a block.
- Returns:
One dict per switch, with
switch_idx,session_idx(the first session after the switch),order(its position insessions),trial_index(the trials before the boundary),from_distribution,to_distribution,n_trials_before,n_trials_afterandn_sessions_after.- Return type:
List[Dict]
- behav_utils.data.find_blocks(sessions, *, min_block_trials=0)[source]#
Maximal runs of consecutive sessions sharing
session.distribution.With
min_block_trials> 0, a run shorter than that is merged into the preceding block of the same distribution if the run it interrupts resumes afterwards (an excursion), and otherwise dropped from the block list; the sessions themselves are untouched.- Parameters:
sessions (Sequence) – Sessions in order, typically one animal’s.
min_block_trials (int) – The fewest trials a run needs to count as a block of its own; 0 keeps every run.
- Returns:
The blocks in order, each with its
distribution, itsstartandstoppositions insessions(stopexclusive),trial_start(the trials before it) andn_trials.- Return type:
List[Block]
- behav_utils.data.block_before(sessions, switch)[source]#
The ordered sessions of the block that ends at
switch.- Parameters:
sessions (Sequence) – The sessions given to
find_switches.switch (Dict) – One of its switches.
- Returns:
The sessions.
- Return type:
list
- behav_utils.data.block_after(sessions, switch)[source]#
The ordered sessions of the block that starts at
switch.- Parameters:
sessions (Sequence) – The sessions given to
find_switches.switch (Dict) – One of its switches.
- Returns:
The sessions.
- Return type:
list
- class behav_utils.data.Block(distribution, start, stop, trial_start, n_trials)[source]#
A run of consecutive sessions on one distribution, as
find_blocksreturns it.- Variables:
distribution (str) – The sessions’ distribution label.
start (int) – Position of the first session in the list given to
find_blocks.stop (int) – Position after the last session (exclusive).
trial_start (int) – Trials in the sessions before the block.
n_trials (int) – Trials in the block.
- Parameters:
distribution (str)
start (int)
stop (int)
trial_start (int)
n_trials (int)
- behav_utils.data.filter_trials(sessions, mask_fn=None, min_trials=10, label='', exclude_abort=True, exclude_opto=True, trial_type=None)[source]#
Filter trials within each session. Returns new SessionData objects.
Each session is filtered independently and rebuilt via
filter_session; sessions with fewer thanmin_trialssurviving trials are dropped. Aborts are always dropped bytrial_type; no-response trials are kept (their choice is NaN and every statistic ignores them).Three ways to say which trials, in order of preference:
trial_type, the named selections (use this):'all': every non-abort trial, opto included'non_opto': non-abort, laser-off trials'opto': laser-on trials only'post_opto': the first laser-off trial after each opto run
mask_fn, asession -> bool maskfor anything else (exclude_abortandexclude_optoare then ignored).Neither:
build_maskwithexclude_abort/exclude_opto(equivalent totrial_type='non_opto'by default).
trial_typeandmask_fnare exclusive; passing both raises. Filtering trials in the data-structures reference shows these calls on synthetic data.- Parameters:
sessions (List[SessionData]) – List of SessionData.
mask_fn (Callable | None) – Callable: session -> boolean mask (length n_trials).
min_trials (int) – Drop sessions below this surviving-trial count.
label (str) – Human-readable description (auto-generated if empty).
exclude_abort (bool) – (no mask_fn / trial_type only) drop aborted trials.
exclude_opto (bool) – (no mask_fn / trial_type only) drop laser-on trials.
trial_type (Literal['all', 'non_opto', 'opto', 'post_opto'] | None) – One of the named selections above.
- Returns:
List of new SessionData with
filter_infoset.- Raises:
ValueError – unknown
trial_type, or bothtrial_typeandmask_fngiven.- Return type:
List[SessionData]
- behav_utils.data.pool_arrays(sessions)[source]#
Concatenate trial arrays across sessions.
Calls get_arrays() on each session’s trials and concatenates. Pooling only — no filtering of any kind; filter BEFORE calling this (filter_trials drops short sessions).
- Parameters:
sessions (List[SessionData]) – List of SessionData (must be pre-filtered).
- Returns:
A dict with these keys:
stimuli, stimuli_raw, categories, choices, correct, truth, no_response, reaction_times concatenated current-trial arrays prev_stimuli, prev_choices, prev_correct, prev_categories, prev_reaction_time, prev_opto_on, prev_has_prev concatenated carried lag-1 view (prev_has_prev is the pooled not_blockstart) trial_keys int64 trial_key_of(session, trial_number) per row task Task the sessions' task (pooling sessions of different tasks raises) n_trials int total trial count n_sessions int number of sessions included session_boundaries list cumulative trial counts [0, n1, n1+n2, ...]
- Raises:
ValueError – The sessions use different tasks.
- Return type:
Dict[str, Any]
- behav_utils.data.build_mask(trials, exclude_abort=True, exclude_opto=True, exclude_no_response=False)[source]#
Build a boolean trial mask from standard exclusion flags.
This is the standard “clean trials for analysis” mask. Combine it with other conditions using
&, as inbuild_mask(trials) & trials.correct.- Parameters:
trials (TrialData) – TrialData object.
exclude_abort (bool) – Remove aborted trials (default True).
exclude_opto (bool) – Remove opto trials (default True).
exclude_no_response (bool) – Remove no-response trials (default False).
- Returns:
Boolean mask of length trials.n_trials.
- Return type:
ndarray
- behav_utils.data.opto_mask(trials, delta=0)[source]#
Boolean mask for trials at a fixed offset from opto events.
Aborted trials are excluded from all masks (they are invalid data). Consecutive opto trials are treated as one “run” — offsets are measured from run boundaries, not individual trials within a run.
- Parameters:
trials (TrialData) – TrialData object.
delta (int | str | None) –
Which trials, as an offset from each opto run:
None: all non-abort trials0: opto trials1: the first non-abort, non-opto trial after each opto run2: the second non-abort, non-opto trial after each opto run-1: the last non-abort, non-opto trial before each opto run'control': all non-abort, non-opto trials; adjacency to an opto run is NOT considered, so combine withdelta=±kmasks to exclude neighbours
- Returns:
Boolean mask of length trials.n_trials.
- Return type:
ndarray
- behav_utils.data.filter_session(session, mask=None, label='', trial_type=None)[source]#
Return new SessionData with only the selected trials.
If mask is None, applies standard exclusions (abort + opto) via build_mask(). Metadata, date, session_id are preserved. filter_info records what was done.
- Parameters:
session (SessionData) – SessionData to filter.
mask (ndarray | None) – Boolean array of length n_trials. If None, uses build_mask() defaults.
label (str) – Human-readable description (auto-generated if empty).
trial_type (str | None) – The named selection the mask came from, recorded in
filter_info; None for a mask of your own.
- Returns:
New SessionData with filtered trials and filter_info set.
- Return type:
- behav_utils.data.filter_trial_data(trials, mask, clear_flags=True)[source]#
Return new TrialData containing only trials where mask is True.
All arrays are sliced to match the mask. By default, abort and opto_on flags are cleared on survivors (they served their purpose during selection — downstream code should receive clean data).
- behav_utils.data.get_arrays(trials, session=None)[source]#
Extract trial arrays from a TrialData object — a pure projection.
NO filtering is done here. ALL filtering, INCLUDING abort removal, must be done BEFORE calling this, via filter_session / filter_trials (abort removal lives in build_mask, default
exclude_abort=True). Passing an unfiltered session will therefore include abort trials.- Parameters:
trials (TrialData) – The trials to project.
session (SessionData | None) – The session they belong to, which makes the trial keys unique across sessions; None for keys unique only within these trials.
- Returns:
A dict with these keys:
stimuli np.ndarray on the library's axis stimuli_raw np.ndarray as read from the file categories np.ndarray choices np.ndarray NaN = no response no_response np.ndarray bool reaction_times np.ndarray correct np.ndarray the task's score: 1 / 0 / NaN (no score) truth np.ndarray the task's correct response per trial prev_stimuli np.ndarray ┐ the carried lag-1 view (abort-aware, frozen prev_choices np.ndarray │ on the raw session); NaN where there is no prev_correct np.ndarray │ predecessor or the previous trial was a prev_categories np.ndarray │ no-response prev_reaction_time np.ndarray │ prev_opto_on np.ndarray │ prev_has_prev np.ndarray ┘ bool (per-trial not_blockstart) trial_keys np.ndarray int64 identity per row (see TrialArrays) when session is given; without it, the trial numbers, unique only within these trials n_trials int- Return type:
Dict[str, ndarray]
- behav_utils.data.session_from_arrays(stimuli, choices, categories=None, session_idx=0, distribution=None, abort=None, reaction_time=None, animal_id='SIM', stage='task', base_date=None, stim_range=(-1.0, 1.0), task=None, laser=None, events=None, clock='', session_date=None)[source]#
Assemble a SessionData from raw per-trial arrays, scored by
task(defaultTwoAFC()).The one constructor for sessions that do not come from files:
simulateand the synthetic generators use it, and so can a simulator of your own. Building a real SessionData (rather than pooling arrays by hand) meansprev_*are frozen byTrialData.__post_init__and pooling is identical to loaded sessions.- Parameters:
stimuli (ndarray) – Per-trial stimuli on the library’s axis, shape (T,).
choices (ndarray) – Per-trial responses, shape (T,); NaN for aborted and no-response trials.
categories (ndarray | None) – The task decides categories; pass None, or arrays that must agree with
task.category(stimuli)(a check, not an override).session_idx (int) – Ordinal session index (the date is
base_dateplus this many days, unlesssession_dateis given). The session id is<animal_id>_<YYYYMMDD>, as on loading.distribution (str | None) – Optional distribution label, stored with the trials and in the metadata.
abort (ndarray | None) – Boolean abort mask; None for no aborts.
reaction_time (ndarray | None) – Per-trial reaction times in seconds; None for all NaN.
animal_id (str) – The animal the session belongs to.
stage (str) – The session’s stage, in its metadata.
base_date (date | None) – The date of session 0; None for 1 January 2025.
stim_range (Tuple[float, float]) – The raw stimulus range, recorded in the metadata.
task (Task | None) – The Task that scores the trials and that the session carries.
laser (ndarray | None) – Boolean laser mask (
trials.opto_on). None -> all False. Any laser trial makes the session type ‘opto’ (else ‘regular’), the loader’s rule.events (Mapping[str, ndarray] | None) – Event times by name (
trials.events), seconds onclock.clock (str) – The clock the event times are on (
SessionData.clock).session_date (date | None) – The session’s date, overriding
base_date+session_idx.
- Returns:
The session, scored by
task.- Return type:
- behav_utils.data.discover_sessions(config_or_path, *, reader=None, peek=True, laser=False)[source]#
Every session the reader finds, one row each, without loading trials.
The session type comes from a
session_typeslist or a mapped session_type column; one derived from the trials (‘opto’ or ‘regular’) needslaser=Trueand is otherwise left empty rather than guessed. The ids are the onesload_experimentgives.- Parameters:
config_or_path (ProjectConfig | str | Path) – A
ProjectConfig, or the path of a YAML config.reader (Callable[[...], Iterable[RawSession]] | None) – Where the sessions come from; by default the reader the config’s
reader:block names.peek (bool) – Read each session’s first row for its
session_metadatafields. A reader that cannot read one row cheaply reads the whole table instead, and a warning says so.laser (bool) – Read the laser column, to derive ‘opto’ or ‘regular’ and to add a
lasercolumn.
- Returns:
One row per session, with the identity columns (
session_id,animal_id,experimenter,date,start,source_id,source),ignored,task_nameandtask,session_typeandsession_type_source, the reader’s metadata, the peekedsession_metadatafields, andfile_<name>for related files a reader attached.- Raises:
FileNotFoundError – Given a path, the config file does not exist.
ConfigError – Given a path, the config cannot be used as written.
- Warns:
UserWarning – The reader cannot peek, so whole tables were read (
peek=Falseavoids it).- Return type:
DataFrame
- behav_utils.data.save_store(experiment, path, *, overwrite=False)[source]#
Save
experimentas a store atpath, a directory of Parquet and JSON files.The store is written to a temporary directory beside
pathand moved into place only when complete, so a failed write leaves nothing behind.- Parameters:
experiment (ExperimentData) – The experiment to save.
path (str | Path) – The store’s directory.
overwrite (bool) – Replace an existing store at
path; any other existing path is refused and left untouched.
- Returns:
The store’s path.
- Raises:
StoreError – pyarrow is not installed;
pathis already a store andoverwriteis False; orpathexists and is not a store (a .pkl file included).- Return type:
Path
- behav_utils.data.load_store(path, *, sessions=None, strict=True)[source]#
Load a store, or only the chosen
sessionsof it, opening only their trial files.- Parameters:
path (str | Path) – The store’s directory.
sessions (DataFrame | Iterable[str] | None) – Only these sessions: a table with a
session_idcolumn (such as a filteredread_manifest) or session ids.strict (bool) – Raise when the store does not have a requested session (the default); False warns instead.
- Returns:
The experiment, as it was saved.
- Raises:
StoreError –
pathis not a store; it was written with a newer store schema than this library reads; a chosen session’s trial file is missing (the store is incomplete); or, withstrict, the store does not have a requested session.- Warns:
UserWarning – Without
strict, the store does not have a requested session.- Return type:
- behav_utils.data.read_manifest(path)[source]#
The store’s sessions, one row each, without opening any trial file.
- Parameters:
path (str | Path) – The store’s directory.
- Returns:
One row per session, with the shared session-table columns (dates and start times as
dateandtime), thentask_name,task_spec,metadata_json,clockandtrials_file. Filter it and pass it toload_store(path, sessions=...).- Raises:
StoreError –
pathis not a store, or was written with a newer store schema than this library reads.- Return type:
DataFrame