From your files to an experiment#

This tutorial loads behaviour from files on disk: it writes a config for them, checks it, finds the sessions, loads some of them, shows what happens when a file is broken, and saves the result as a store. It first writes its own small set of files, into a temporary folder; with your own data, start at the config and point data_dir at your folder.

The files are what a rig might write: one folder per animal and per day, each holding a trials.csv with the tone in kHz, the response as ‘L’, ‘R’ or ‘N’ (no response), the laser, the reaction time in milliseconds, each trial’s start time in seconds, and the training stage.

import tempfile
from pathlib import Path

import numpy as np
import pandas as pd

root = Path(tempfile.mkdtemp())
rng = np.random.default_rng(1)
for animal_id in ('R01', 'R02'):
    for day, stage in (('2025_03_10', 'training'), ('2025_03_11', 'task'), ('2025_03_12', 'task')):
        folder = root / 'data' / animal_id / day
        folder.mkdir(parents=True)
        n = 150
        tone = np.round(2 ** rng.uniform(1, 4, n), 2)
        p_right = 1 / (1 + np.exp(-(np.log2(tone) - 3) / 0.3))
        response = np.where(rng.random(n) < p_right, 'R', 'L')
        response[rng.random(n) < 0.03] = 'N'
        pd.DataFrame({
            'TrialNum': np.arange(1, n + 1),
            'Tone_kHz': tone,
            'Response': response,
            'Laser': (rng.random(n) < 0.3).astype(int),
            'RT_ms': np.round(rng.lognormal(np.log(450), 0.3, n)),
            'TrialStart_s': np.round(np.cumsum(rng.uniform(4, 7, n)), 3),
            'Stage': stage,
        }).to_csv(folder / 'trials.csv', index=False)

sorted(p.relative_to(root).as_posix() for p in root.rglob('*.csv'))
['data/R01/2025_03_10/trials.csv',
 'data/R01/2025_03_11/trials.csv',
 'data/R01/2025_03_12/trials.csv',
 'data/R02/2025_03_10/trials.csv',
 'data/R02/2025_03_11/trials.csv',
 'data/R02/2025_03_12/trials.csv']

The config#

The config says where the files are and how to read them. reader: finds the sessions: here one folder per animal and per day, with the date in the folder’s name. task: puts the tone on the library’s axis: the boundary, 8 kHz, goes to 0 and the range, 2 to 16 kHz, to −1 and +1, on a log scale (see The stimulus axis). columns: maps each column to a field: the response through mapping, so ‘L’ is category A (0), ‘R’ category B (1) and ‘N’ a no-response; the reaction time from milliseconds; and t_trial_start as an event time on the rig clock. session_metadata: reads the stage from each file’s first row. The configuration guide describes every key.

from behav_utils import load_config

config_text = """
project:
  name: tone categorisation

reader:
  type: csv_folders
  data_dir: data
  behaviour_file: trials.csv
  date_regex: '(\\d{4})_(\\d{2})_(\\d{2})'

task:
  boundary: 8.0
  stimulus_range: [2.0, 16.0]
  stimulus_scale: log
  choice_mapping:
    type: identity
    no_response_value: null

clock:
  name: rig
  unit: s

columns:
  trial_number: {csv_name: TrialNum, dtype: int}
  stimulus: {csv_name: Tone_kHz, dtype: float}
  choice: {csv_name: Response, dtype: float, mapping: {L: 0, R: 1, N: .nan}}
  opto_on: {csv_name: Laser, dtype: bool}
  reaction_time: {csv_name: RT_ms, dtype: float, unit: ms}
  t_trial_start: {csv_name: TrialStart_s, dtype: float}

session_metadata:
  stage: {csv_name: Stage, dtype: str}
"""
(root / 'config.yaml').write_text(config_text)
config = load_config(root / 'config.yaml')
config.name, config.task.boundary, config.task.stimulus_scale
('tone categorisation', 8.0, 'log')

load_config checks every key, and refuses one it does not know rather than ignoring it:

typo_text = config_text.replace('behaviour_file', 'behavior_file')
(root / 'typo.yaml').write_text(typo_text)
load_config(root / 'typo.yaml')
---------------------------------------------------------------------------
ConfigError                               Traceback (most recent call last)
Cell In[3], line 3
      1 typo_text = config_text.replace('behaviour_file', 'behavior_file')
      2 (root / 'typo.yaml').write_text(typo_text)
----> 3 load_config(root / 'typo.yaml')

File ~/work/behav_utils/behav_utils/src/behav_utils/config/schema.py:903, in load_config(path)
    900 _check_keys('project', project_raw, _PROJECT_KEYS)
    902 # Reader and animal metadata
--> 903 reader = _parse_reader(_section(raw, 'reader'))
    904 animal_metadata = raw.get('animal_metadata')
    905 if animal_metadata is not None and not isinstance(animal_metadata, str):

File ~/work/behav_utils/behav_utils/src/behav_utils/config/schema.py:622, in _parse_reader(raw)
    620 cls = readers[reader_type]
    621 known = [f.name for f in dataclasses.fields(cls)]
--> 622 _check_keys(f'reader ({reader_type})', raw, known)
    623 required = [f.name for f in dataclasses.fields(cls)
    624             if f.default is dataclasses.MISSING and f.default_factory is dataclasses.MISSING]
    625 missing = [k for k in required if k not in raw]

File ~/work/behav_utils/behav_utils/src/behav_utils/config/schema.py:611, in _check_keys(section, given, allowed)
    609     hints.append(f"{key!r} (did you mean {close[0]!r}?)" if close else repr(key))
    610 plural = 's' if len(unknown) > 1 else ''
--> 611 raise ConfigError(f"{section}: unknown key{plural} {', '.join(hints)}. Valid keys: {', '.join(allowed)}.")

ConfigError: reader (csv_folders): unknown key 'behavior_file' (did you mean 'behaviour_file'?). Valid keys: behaviour_file, data_dir, date_regex, drop_last_row, merge_files, min_trials_per_file.

Finding the sessions#

discover_sessions lists what the reader finds, with the ids that loading will give, without reading any trials. Its table is the place to choose sessions:

from behav_utils import discover_sessions

table = discover_sessions(config)
table[['session_id', 'animal_id', 'date', 'stage', 'ignored']]
session_id animal_id date stage ignored
0 R01_20250310 R01 2025-03-10 training False
1 R01_20250311 R01 2025-03-11 task False
2 R01_20250312 R01 2025-03-12 task False
3 R02_20250310 R02 2025-03-10 training False
4 R02_20250311 R02 2025-03-11 task False
5 R02_20250312 R02 2025-03-12 task False

Loading#

Only the chosen sessions are read:

from behav_utils import load_experiment

chosen = table[table.stage == 'task']
experiment = load_experiment(config, sessions=chosen)
experiment.summary()
animal_id n_sessions stages date_first date_last
0 R01 2 [task] 2025-03-11 2025-03-12
1 R02 2 [task] 2025-03-11 2025-03-12

Each trial keeps the stimulus as read beside its value on the axis, and times are in seconds:

session = experiment.get_animal('R01').sessions[0]
trials = session.trials
pd.DataFrame({'stimulus_raw': trials.stimulus_raw[:5], 'stimulus': trials.stimulus[:5].round(3),
              'choice': trials.choice[:5], 'reaction_time': trials.reaction_time[:5],
              't_trial_start': trials.events['t_trial_start'][:5]})
stimulus_raw stimulus choice reaction_time t_trial_start
0 3.24 -0.652 0.0 0.473 4.133
1 14.60 0.868 1.0 0.732 10.762
2 3.00 -0.708 0.0 0.325 17.702
3 3.86 -0.526 0.0 0.342 23.547
4 15.48 0.952 1.0 0.324 28.183

A broken file#

Loading is strict by default. Suppose one file has lost its response column:

broken = root / 'data' / 'R02' / '2025_03_12' / 'trials.csv'
pd.read_csv(broken).drop(columns='Response').to_csv(broken, index=False)

A full load then stops at that session, and the error names it:

load_experiment(config)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
File ~/work/behav_utils/behav_utils/src/behav_utils/data/loading.py:693, in _build_all(raws, config, strict, wanted)
    692         continue
--> 693     session = build_session(replace(raw, session_id=session_id, trials=table), config,
    694                             strict=strict, source_id=raw.session_id)
    695 except Exception as e:

File ~/work/behav_utils/behav_utils/src/behav_utils/data/loading.py:382, in build_session(raw, config, strict, session_idx, source_id)
    381 if validation['missing_required']:
--> 382     raise ValueError(f"{label}: missing required columns {validation['missing_required']}")
    384 metadata = _extract_session_metadata(df, config)

ValueError: R02/R02_20250312: missing required columns ['Response']

The above exception was the direct cause of the following exception:

RuntimeError                              Traceback (most recent call last)
Cell In[8], line 1
----> 1 load_experiment(config)

File ~/work/behav_utils/behav_utils/src/behav_utils/data/loading.py:892, in load_experiment(config_or_path, reader, strict, sessions)
    890 if reader is None:
    891     reader = _reader_from_config(config)
--> 892 by_animal = _build_all(_call_reader(reader, config, strict), config, strict, _wanted_ids(sessions))
    894 experiment = ExperimentData(config=config)
    895 for animal_id in sorted(by_animal):

File ~/work/behav_utils/behav_utils/src/behav_utils/data/loading.py:697, in _build_all(raws, config, strict, wanted)
    695 except Exception as e:
    696     if strict:
--> 697         raise RuntimeError(f'Failed to load {label}: {e}') from e
    698     log.warning('Failed to load %s: %s (skipped)', label, e)
    699     continue

RuntimeError: Failed to load R02/R02_20250312 (2025_03_12): R02/R02_20250312: missing required columns ['Response']

With strict=False the session is skipped, with a warning, and the rest load:

experiment = load_experiment(config, strict=False)
experiment.summary()
Failed to load R02/R02_20250312 (2025_03_12): R02/R02_20250312: missing required columns ['Response'] (skipped)
animal_id n_sessions stages date_first date_last
0 R01 3 [training, task] 2025-03-10 2025-03-12
1 R02 2 [training, task] 2025-03-10 2025-03-11

The store#

A store keeps a loaded experiment as Parquet and JSON files, so it loads again as it was without the original files or config. Its manifest lists the sessions without opening any trials, so part of a store can be loaded. It needs pyarrow, the store extra.

from behav_utils import load_store, read_manifest

experiment.save(root / 'store')
manifest = read_manifest(root / 'store')
manifest[['session_id', 'animal_id', 'date']]
session_id animal_id date
0 R01_20250310 R01 2025-03-10
1 R01_20250311 R01 2025-03-11
2 R01_20250312 R01 2025-03-12
3 R02_20250310 R02 2025-03-10
4 R02_20250311 R02 2025-03-11

Only R01’s sessions:

part = load_store(root / 'store', sessions=manifest[manifest.animal_id == 'R01'])
part.summary()
animal_id n_sessions stages date_first date_last
0 R01 3 [training, task] 2025-03-10 2025-03-12

Where to go next#