Changelog#
Plans for later releases are in ROADMAP.md.
1.1.0 — 2026-11-15#
One change moves numbers: the session-unit intervals of compute_delta_stat. Everything else gives the same values
as 1.0.2.
▲ The session bootstrap of
compute_delta_statdraws the sessions of all its phases together. Sessions are resampled within groups that belong to the same phases, so two phases cut from the same sessions (laser on and off) get the same sessions in every draw and their shared session-to-session variation cancels in the difference. Until now each phase drew its sessions independently, which left that variation in the difference and made the interval of a within-session contrast too wide (and its bootstrap p too large). Phases with different sessions are still drawn separately, each keeping its number of sessions, but from a different random stream, so their session intervals move by resampling noise. Trial-unit intervals, permutation p-values and observed values are unchanged, and so isbootstrap_phase_statscalled on one phase. No signature changes. With the excess width gone, the usual limit of a bootstrap over few units shows: from fewer than about ten sessions the session interval is too narrow (Resampling units in the docs).compute_delta_statwarns when, with the session unit, a session has no other session in the same phases to be drawn with (the phases share only some of their sessions): it is the same in every draw, so the interval leaves out its variation.downsample: the docstring named a'sessions'unit that does not exist (the units are'trials'and'pairs'), andrngnow also takes an int seed.The golden values are regenerated per table:
python tests/golden/make_golden.py --table delta. Without--tablethe script failed in 1.0.2, because it asked for statistics the 2-AFC task cannot compute; it now uses the pinned statistics. Only the session-unit rows ofdelta.csvchanged.CI runs the suite on Python 3.11 with the oldest dependency versions
pyproject.tomlallows, so the declared floors are tested. Its first run raised two of them: pandas to 2.1 (paired_diffrelies onpivot_table(dropna=False)keeping rows whose label columns are empty, which older pandas dropped) and numpy to 1.24.1 (in 1.24.0np.ma.masked_invalidreturns a mask that breaks matplotlib’sfill_between, so the psychometric band could not be drawn).CITATION.cffadded. A test keeps its version, and the version in the README’s install commands, equal to__version__.Streams (recordings aligned to trials) are now planned for 1.2; the README, the roadmap and the contributor notes say so consistently.
1.0.2 — 2026-11-14#
Documentation only; the library behaves exactly as in 1.0.1. The changes to the source are docstrings and type annotations.
The docs site gains concept pages (the pipeline, tasks, the stimulus axis, identities and time, resampling units), four tutorials (from files to an experiment, go/no-go, continuous responses, models), eight how-to guides, a pitfalls page, and a references page; sources sit next to the definitions they support.
Every code example on the site runs in CI, and YAML config examples load.
Every public name and public method has a docstring in one standard (CONTRIBUTING, Docstrings), checked by
tests/test_docstrings.py. Code moved out of docstrings onto the pages.Docstrings that were wrong are corrected: session ids that would clash are all numbered
_1,_2, … (not_2,_3for later ones);get_arraysandpool_arrayslist every key they return;Discrete.gridreturns the distribution’s own values;session_from_arraysno longer says reaction times are unused.The
docsextra includes pyarrow; the package is classified Production/Stable.
1.0.1 — 2026-11-13#
Documentation only; the library behaves exactly as in 1.0.0.
A documentation site, built with Sphinx and published at https://serkanshentyurk.github.io/behav_utils/, one version per minor release: the 2-AFC tutorial (now
docs/tutorials/two_afc.ipynb), the API by sub-package from the docstrings, the statistics, configuration and data-structures references, and the contributor pages.Every example on the site runs in CI: each page’s Python blocks top to bottom, and its YAML blocks as configs.
Docstrings reformatted so the API pages render, with the code in them moved to the pages. Three were wrong:
get_arraysandpool_arraysdid not list every key they return, andfit_psychometric_gofshowed R² garbled.The config guide’s Validation section uses public functions only.
1.0.0 — 2026-11-12#
The first stable release: from here, public names change only in a major release, after a minor release in which they warn (CONTRIBUTING.md). behav_utils is now task- and model-agnostic: readers bring anyone’s trial data in, the session’s task alone decides what is correct, any model simulates through the same pipeline, and every statistic, readout and model says what a task must provide. Every 2-AFC statistic, readout, contrast and rolling statistic on the golden dataset is unchanged from 0.10.0 except where marked ▲.
Breaking changes from 0.10#
Config
An unknown key in any section raises
ConfigError(aValueError) naming the valid keys and the closest match; it used to be ignored. A top-levelcustom:block is reserved for the project;nameanddescriptionbelong underproject:. Keys that were never read are gone (task.inputs,task.outputs,task.n_categories,file_structure.animal_pattern,session_pattern,date_format).▲
task.choice_mapping.no_response_valueis required whenever a choice column is mapped (nullwhen no raw value means no response). The old default of 0 turned every A choice in a 0/1 column into a no-response.reader:(with atype) replacesfile_structure;contingency_fieldhas no default;category_ruleis replaced byb_side(two_afc) andgo_side(go_nogo). Leftover keys raise with the new names. Relative paths resolve against the config file’s folder.
Loading and identities
▲ Stricter loading: an unparseable file raises under
strict(it was dropped silently in a multi-file session);min_trials_per_fileapplies to single-file sessions too; the date comes from the reader only (noDate-column fallback, no 1 Jan 2000 default); a mappedanimal_idthat disagrees with the reader raises. Sessions insessions_to_ignoreare not read at all.▲ A
session_typeslist overrides a recorded type (it was the other way round); a column sets the type only whensession_typeis mapped.Session ids are
<animal>_<YYYYMMDD>, plusT<HHMM>with a start time and_1,_2where they would clash; the reader’s own name isSessionData.source_id.TrialArrays.trial_keyis a hash of experimenter, animal and session above the trial number: stable across loads and unique across animals (it was the session’s position × 10⁶ + the trial number). Trial numbers must be unique within a session and below 1,048,576.animal.session_tablestarts with the identity columns (session_id,animal_id,experimenter,date,start,source_id,source).SessionData.csv_pathis renamedsource.load_session_csv(path, config, *, date=None)losessession_idxanddf;parse_date_from_pathandparse_date_from_csvare gone.
Scoring
▲ The session’s task decides what is correct.
TrialData.outcomeholdsOutcomecodes andTrialData.correctis alwaysoutcome == CORRECT; a mappedcorrectoroutcomecolumn is kept ascorrect_recorded/outcome_recordedand checked, never used instead.▲ A stimulus exactly on the boundary follows
on_boundary(default A) on either side (undercategory_rule: below_boundaryit counted as B); a NaN stimulus has category NaN (it was A);TrialData.prev_correctis NaN after a predecessor without a score (it was 0 after a no-response).TrialArrays.prev_rewardis removed (useprev_correct).fit_update_matrixtakes the score as the keywordcorrect=(andprev_correct=) instead ofcategories.On go/no-go, statistics that need two active choices are refused:
side_bias→go_bias,accuracy_b_minus_a→hit_minus_cr_rate;logistic_historyandhistory_interaction_r2have no go/no-go version.
Models and synthetic data
The simulator functions (
sample_stimuli,generate_stimuli,random_choice_simulator,noisy_psychometric_simulator) and the old generators are gone: a simulator becomes a model withsimulate(design, rng).generate_synthetic_animallives inbehav_utils.models, takesrnginstead ofseedand returns anAnimalData(it returned(animal, info)).session_from_arraysgives the loader’s session ids.
Saving
▲ Pickle is gone.
ExperimentData.save/.loadandAnimalData.save/.loadwrite and read a store (a directory of Parquet and JSON); a.pklpath raises with directions.saveno longer stamps the library version into the experiment’s metadata (the store records it).
Public API
The top level holds the 71 everyday names; everything else imports from its package (for example
from behav_utils.stats import PSYCHOMETRIC,from behav_utils.data import session_from_arrays, trial_key_of,from behav_utils.models import normative_pse).docs/public_api.mdlists every name and its home.Renamed:
plot_comparison→plot_psychometric_comparison. Private now:apply_session_typeand six helpers (_infer_animal_id,_contrast_key,_calculate_min_n,_validate_names,_producer_of,_list_producers). Removed:readouts.PARAMS(it wasstats.PSYCHOMETRIC).plot_psychometric_comparison,plot_stat_comparisonandplot_interactionreturn(fig, ax)like every single-panel plot (they returnedax).Python ≥ 3.11.
Added#
Data and loading
Readers:
csv_folder_reader(several sessions a day;merge_files),table_reader(one table: a DataFrame, CSV, TSV or Parquet), or any function yieldingRawSession(with optionalfilesand a cheappeek);build_sessionmaps any of them ontoSessionData.discover_sessions(config): every session before loading, with the ids loading gives;load_experiment(config, sessions=...)reads only those chosen.experiment.session_tablestacks every animal’s.project.experimenterand per-animal metadata (animal_metadata:);SessionData.session_type_source.Event times: columns named
t_*, in seconds on one recording clock (clock:block,ClockConfig), stored inTrialData.events, checked at load (times going backwards, negative reaction times, within-trial order).
Tasks
behav_utils.tasks:Task,TwoAFC,GoNoGo,Reproduction,Outcome,ResponseSpace, a registry (register_task,task_from_dict,list_tasks), stimulus distributions (Uniform,TruncatedNormal,Discrete,StimulusDistribution) and capabilities (CAPABILITIES,require,RequirementError).Config:
task: {type, ...}with the type’s own settings,tasks:alternatives picked per session bytask_by:, andscoring:(what happens when a recorded column disagrees).The continuous-response family:
Reproduction(tolerance); stimulus and response share one linear map onto [-1, 1];TrialArrays.truth.
Statistics and readouts
@stat/@fittakerequires=andinstead=;compute_stats(arrays)andlist_stats(task=...)give what applies.TrialArrayscarriescorrect,prev_correct,truthandtask.Go/no-go:
go_bias,hit_minus_cr_rate. Continuous:response_bias,error_sd,mean_abs_error,response_slope,serial_bias, and the readoutscompute_response_curve,compute_error_distribution,compute_serial_biaswith their plots.
Models
behav_utils.models:Model,TrialwiseModel(hooks take aTrialInfo;p_choiceorrespond,update),Responses,Design,make_design,simulate,simulate_responses; built-insPsychometricModel,RandomModel,IdealObserver(both families),ReproductionModel, withlaser={...}overrides;normative_pse,normative_slope.Synthetic data from any model with every trial class and event times:
generate_synthetic_session,generate_synthetic_animal,generate_synthetic_experiment,Timing.
Saving
The store:
save_store,read_manifest,load_store,StoreError. Its manifest is the session table, so it is filtered like discovery; writes are atomic; partial loads open only the chosen sessions’ files; the schema version is checked. Needs pyarrow (pip install 'behav_utils[store]').
Tooling and documentation
Golden values on two frozen fixtures (2-AFC from 0.10.0; continuous from this release), exact on the reference machine and with set tolerances across library versions; a generated, tested
docs/public_api.md; CI on Python 3.11 and 3.14 with real Parquet;EXTENDING.md(a statistic, a readout, a task, a statistic for your own task, a model, a reader); the doc-example runner skips blocks marked# requires: <module>where it is missing.
Fixed#
The shipped minimal preset mapped no response to 0 in a 0/1 column, turning every A choice into a no-response.
The shipped go/no-go example mapped
correct: Hit, marking every correct rejection wrong.Under pandas 3, loaded text columns were pandas
StringArrays, which filtering did not slice.compute_rolling_statspassed empty frames topd.concat(a pandas FutureWarning).
Deferred#
1.1: streams (pupil, imaging, spikes aligned to trials by trial key and the shared clock), with companion files linked to sessions.
1.x: the K-choice family; per-trial context from loaded columns; stimuli with several features; reaction time derived from two events; event times in
TrialArrays; clocks that wrap at midnight; adding sessions to an existing store; NWB export.
0.10.0 — 2026-11-07#
Added#
accuracy_b_minus_a: accuracy on category-B trials minus accuracy on category-A trials. Unlikeside_bias, it does not move with how often each category is presented (bias-correcting trial selection, asymmetric stimulus distributions); it does move when the categories differ in difficulty. No existing number changes.
Docs#
Stats reference regenerated. Its go/no-go table gives
side_biasas P(choose B) − 0.5 (it said P(choose B)) and reads the new statistic as hit rate minus correct-rejection rate.
0.9.1 — 2026-11-04#
Fixed#
load_animalskips empty CSV files (nothing in them, not even a header: a run stopped before writing anything) with a warning, as if absent; a session with only empty files is skipped. In a session with several files an empty one raisedEmptyDataErrorand, understrict=True, stopped the whole load.is_empty_csv(path)is the check, for projects that re-read the CSVs.
0.9.0 — 2026-11-02#
Number-affecting changes are marked ▲.
Changed ▲#
select_sessions/SessionFilter:exclude_optoandexclude_typesnow apply beforefirst_n,last_n,last_fractionandlast_n_qualifying. Before, excluded sessions still took up positions, solast_n=5could return fewer than 5.
Changed#
compute_delta_statraises if a permutation is requested and a phase shares trials with the reference (e.g.post_optoinsidenon_opto); without a permutation it warns.permute_phase_differenceraises too.
Added#
shared_trial_count(phase_a, phase_b): how many trials two phases share.
Fixed#
pool_arrays([])returnssession_boundaries == [0](was[]).CI ran the stats-reference check twice.
Tests: the comparison tests gave every phase the same trial numbers; each phase now has its own.
Docs#
Install and test commands without inline comments; LLM_CONTEXT notes the selection order and the shared-trial guard.
0.8.0 — 2026-10-31#
Handover release. Number-affecting defaults are marked ▲.
Fixed#
infer_animal_idnever found the id the loader writes (session.metadata.animal_id), soPhaseStats.animalwas'unknown'andcollect_rowslet that overwrite the explicitanimal=: every animal collapsed into one unit incompare_groups(the example notebook’s group section reported n = 1 vs 1). Both fixed;collect_rows(animal=...)now always wins and warns on a conflict.paired_diffdropped every pooled row (distribution=Noneis a pivot index key; pandas’ defaultdropnadiscarded it).dropna=False.compare_groups(paired=True)dropped non-finite values per group independently, so pairs could misalign silently; values are now aligned byunit_coland disjoint animal sets raise.filter_trials:trial_typesilently discarded a passedmask_fn(now raises);trial_typewithexclude_abort=Falsekept aborts (now everytrial_typedrops aborts).Docs:
data_structures_reference.mdrewritten against the real API (compute_delta_statkwargs, non-existentget_animals/trials.get_arrays/'trial_indices',get_arrays“excludes aborts”,opto_mask('control')adjacency) and executed bydocs/run_doc_examples.py; stale module docstrings instructures,selection,filtering,group,config,data.ops; README install pin; the go/no-go and orientation example configs (deadanalysis:section, raw-unit stimuli).
Changed ▲#
compute_delta_stat(n_permutations=0)by default;n_permutations > 0raises unless every phase shares a session with the reference. Calls that passedn_permutationsexplicitly on within-session contrasts are unchanged; calls that relied on the default lose a p they should not have had.rank_test -> RankTest,bootstrap_units -> UnitBootstrap,average_arrays -> ArrayAverage,compare_groups -> GroupComparison(.test(stat),.table()): frozen dataclasses instead of dicts (rule 2). Values identical; access is by attribute.SessionData.summary() -> SessionSummary(.accuracy, formerly['perf']).AnimalData.session_tableis counts + accuracy only (SESSION_TABLE_COLUMNS); it no longer runs every registered statistic (including thepse_dynamicscurve fit) on every session, which cost ~0.7 s per session and was a data→stats import.Plotting:
plot_stat_comparison/plot_interactionare now the single-panel plotters (formerly*_single); the grids areplot_stat_comparison_grid/plot_interaction_grid, the one documented exception to “layout is the caller’s”.Loading:
print→logging(behav_utils.data.loading);load_animal/load_experimenttakestrict=True(a broken session raises instead of being skipped with a warning).Session presets resolve on the animal’s own config (
ExperimentData.config.session_presets) before the process-wide registry;preset_from_specexported.SessionMetadataloses the project-vocabulary propertiessound_contingency,stim_range_min/max(.get()still works).
Added#
Stimulus normalisation at load:
task.stimulus_scale(linear|log) alongsideboundaryandstimulus_range;TaskConfig.normalise_stimulusmaps raw units onto[-1, 1]with the boundary at 0 (identity for the defaults).TrialData.stimulus_rawkeeps the CSV value;pool_arraysaddsstimuli_raw.stimulus_rangewas parsed and never used before: configs in Hz or degrees produced silently wrong bins.TrialArrays.trial_key(int64session_idx * 10**6 + trial_number), carried throughtake,valid,lag1_pairs,concatand every resample;trial_key_of,with_trial_key,TrialArrays.concat. The hook for aligning neural (or any per-trial) data.Go/no-go support documented: the two config differences (
docs/config_guide.md), a table of what each statistic measures (docs/stats_reference.md), the loader’s NaN-choice warning.plot_rolling_stats(result, stat, ax=None)forRollingStats.ExperimentData.savestampsbehav_utils_version/config_name;loadwarns on a version mismatch.docs/run_doc_examples.py(run in CI).
Removed#
analysis/session_features.py(compute_session_features): a dict result, mislabelledn_trials_abort/abort_rate(they counted no-response), duplicatingcompute_phase_stats(per_session=True)andstats/rt.py.The second copy of the stimulus-binning helpers (
stats/_binning.pynow re-exportsreadouts/_base.py).
0.7.1 — 2026-10#
SessionFilter.last_n_qualifying: the last N sessions that pass the quality filters (min_accuracy,max_accuracy,min_trials).last_nis unchanged and still applied before them, so “last 5 sessions with accuracy > 0.7” is now expressible as a preset.No numbers change.
0.7.0 — 2026-10#
analysis/has one job per file:statistics.py→phase.py;downsample.pymerged intoresampling.py(draw engine + draw summaries);across_animals.pymerged intogroup.py;psychometry.py,update_matrix.pyandutils.py→readouts/fit.py(the two fit engines andcumulative_gaussian),generate_stimuli→data/synthetic.py. Every public name is unchanged and still exported frombehav_utilsandbehav_utils.analysis; only the submodule paths moved.docs/config_guide.mdkeeps the reference; the three complete example configs are files underdocs/config_examples/.No numbers change.
0.6.0 — 2026-10#
New fitter
sdt→dprime,criterion(B as signal, log-linear correction; exchangeable).The library lives in its own repository again (github.com/serkanshentyurk/behav_utils) with its own CI (
ruff, the suite on 3.10 and 3.12, the example notebook, the generated stats reference) and av*tag release workflow; packaging metadata (classifiers, keywords, URLs).
0.5.0 — 2026-10#
compute_stat→compute_phase_stats(one name per level:compute_statson arrays,compute_phase_statson sessions). No alias.apply_session_typeis public (was_apply_session_type).Removed, no consumer:
analysis/session_raster.py,plotting/session.py,plotting/session_stats.py,compare_genotypes,AnimalData.genotype(readanimal.metadata['genotype']),AnalysisConfig/PlottingConfig(theanalysis:/plotting:config sections were parsed and never read), the legacy*_sessionsconfig keys, the experiment-specific config presets, the empty example notebook.compare_groupsno longer orders('wt', 'het')first; passgroups=(a, b)to fix the reference group.Docstrings and docs use neutral vocabulary;
docs/data_structures_reference.mdexamples rewritten against the 0.3+ API;docs/config_guide.mdnow documentscohorts,session_types,session_presetsandsessions_to_ignore(the removedanalysis:/plotting:sections are gone);docs/stats_reference.mdis generated from the registry bydocs/gen_stats_reference.py.The shipped presets (
config_minimal.yaml,config_full_reference.yaml) are experiment-neutral.generate_synthetic_animal/generate_synthetic_sessiondefaultstageis'task'(was a project stage name); passstage=explicitly if you select by stage afterwards.
0.4.0 — 2026-09#
Library is task-agnostic:
session_typesandsession_presetscome from the config; hardcoded presets,masking/washout/ALM vocabulary and the Hard-A/B adaptation module removed.SessionFilter.exclude_typesreplaces the three exclusion flags.SessionData.masking/.washoutremoved.find_switches(generic distribution-switch detection).pse_dynamicsfit producer (exponential vs step PSE trajectory), optional pinned shape.UpdateMatrix.from_matrix.filter_trials(trial_type='all')drops abort trials (bug fix; docstring and code disagreed).src/ layout; own test suite in
tests/.
0.3.0 — 2026-09#
Typed stat registry:
TrialArrays+compute_stats -> pd.Series;@stat/@fit; no family names.Readout dataclasses:
PsychometricCurve,UpdateMatrix,ConditionalPsychometric,BinnedCurve,SerialDependenceProfile, each with one draw-only plotter.compute_phase_stats -> PhaseStats,compute_delta_stat -> DeltaStats,compute_interaction -> Interaction,compute_rolling_stats -> RollingStats; resampling engines return DataFrames of draws.Removed:
summary_stats,stats_table,trajectory,compute_psychometric,compute_um,average_um,plot_um,plot_psychometric,compare_phases.Bit-exact with 0.2 for every scalar statistic and every bootstrap draw (verified before deletion).
0.2.0 — 2026-07#
Baseline before the refactor.