behav_utils.analysis#

behav_utils.analysis — phase-level statistics, contrasts, resampling, group tests.

compute_phase_stats gives the statistics of one phase, pooled or per session; compute_delta_stat contrasts phases with bootstrap and permutation uncertainty; compute_interaction takes the difference of two contrasts; and the group functions test per-animal values across animals.

Scalar statistics live in behav_utils.stats; array-valued readouts and the two fit engines on raw arrays (fit_psychometric, fit_update_matrix) in behav_utils.readouts.

Files: phase.py (compute_phase_stats), comparison.py (contrasts), resampling.py (the draw engine and draw summaries), group.py (across-animal tests), rolling.py.

class behav_utils.analysis.PhaseStats(pooled, sessions, animal, n_sessions, n_trials)[source]#

Scalar statistics of one phase.

pooled is a float Series indexed by stat name; sessions is the tidy per-session frame (SESSION_COLUMNS: animal, session, session_type, distribution, stat, value, n_trials) or None. n_trials counts responded trials.

Variables:
  • pooled (pandas.Series) – The pooled value of each statistic, a float Series.

  • sessions (pandas.DataFrame | None) – The per-session values, a tidy frame; None unless per_session=True.

  • animal (str) – The animal, when the phase is one animal’s.

  • n_sessions (int) – Sessions in the phase.

  • n_trials (int) – Responded trials in the phase.

Parameters:
  • pooled (Series)

  • sessions (DataFrame | None)

  • animal (str)

  • n_sessions (int)

  • n_trials (int)

to_rows()[source]#

The pooled values as tidy rows, with session set to ‘pooled’.

Returns:

The rows, with the same columns as sessions.

Return type:

DataFrame

behav_utils.analysis.compute_phase_stats(phase, names, *, per_session=False, animal_id=None, rng=None)[source]#

Scalar statistics for a phase.

Parameters:
  • phase (Sequence[SessionData]) – list of SessionData — the output of filter_trials.

  • names (Sequence[str]) – scalar stat names (list_stats()); splat PSYCHOMETRIC for the four psychometric parameters.

  • per_session (bool) – also fit each session separately and fill sessions.

  • animal_id (str | None) – stamped into the frames; inferred from the phase if None.

  • rng (Generator | None) – generator for stochastic stats (seed it for reproducibility).

Returns:

PhaseStats.

Return type:

PhaseStats

class behav_utils.analysis.DeltaStats(phases, contrasts, reference, names, units, downsample=False, n_matched=<factory>, seed=0)[source]#

Result of compute_delta_stat().

Variables:
  • phases (Dict[str, behav_utils.analysis.comparison.PhaseSummary]) – Each phase’s summary, {label: PhaseSummary}.

  • contrasts (Dict[str, behav_utils.analysis.comparison.Contrast]) – Each phase against the reference, {label: Contrast}.

  • reference (str) – The reference phase’s label.

  • names (Tuple[str, ...]) – The statistics compared.

  • units (Tuple[str, ...]) – The resampling units used.

  • downsample (bool) – Whether the phases were matched to the same number of trials.

  • n_matched (Mapping[str, int]) – The matched number of trials per unit, when they were.

  • seed (int) – The random seed.

Parameters:
  • phases (Dict[str, PhaseSummary])

  • contrasts (Dict[str, Contrast])

  • reference (str)

  • names (Tuple[str, ...])

  • units (Tuple[str, ...])

  • downsample (bool)

  • n_matched (Mapping[str, int])

  • seed (int)

contrast(label)[source]#

The contrast of one phase against the reference.

Parameters:

label (str) – The phase’s label.

Returns:

The contrast.

Return type:

Contrast

table(unit=None, *, ci=0.95)[source]#

All contrasts in one table, with a contrast column.

Parameters:
  • unit (str | None) – The resampling unit; None for the first one available.

  • ci (float) – The interval’s coverage.

Returns:

One row per contrast and statistic.

Return type:

DataFrame

class behav_utils.analysis.PhaseSummary(label, stats, n_trials, n_sessions, draws=<factory>, stats_matched=None, curve=None, update_matrix=None)[source]#

One condition: observed stats, its bootstrap draws per unit, and optional readouts.

Variables:
  • label (str) – The phase’s label.

  • stats (pandas.Series) – The observed value of each statistic.

  • n_trials (int) – Responded trials in the phase.

  • n_sessions (int) – Sessions in the phase.

  • draws (Mapping[str, pandas.DataFrame]) – The bootstrap draws per unit, {unit: frame}.

  • stats_matched (pandas.Series | None) – The values on the matched-n draw, when downsample was set; else None.

  • curve (behav_utils.readouts.psychometric.PsychometricCurve | None) – The psychometric curve, when requested; else None.

  • update_matrix (behav_utils.readouts.update_matrix.UpdateMatrix | None) – The update matrix, when requested; else None.

Parameters:
  • label (str)

  • stats (Series)

  • n_trials (int)

  • n_sessions (int)

  • draws (Mapping[str, DataFrame])

  • stats_matched (Series | None)

  • curve (PsychometricCurve | None)

  • update_matrix (UpdateMatrix | None)

ci(unit=None, *, ci=0.95)[source]#

The bootstrap interval of each statistic.

Parameters:
  • unit (str | None) – The resampling unit; None for the first one available.

  • ci (float) – The interval’s coverage.

Returns:

One row per statistic, with ci_lo, ci_hi, p, median and n_draws.

Return type:

DataFrame

class behav_utils.analysis.Contrast(label_a, label_b, diff, n_a, n_b, n_sessions_a, n_sessions_b, difference_draws=<factory>, perm_p=None, um_diff=None, um_rmse=nan, um_corr=nan)[source]#

Δ = a − b, with difference draws per unit and an optional permutation p.

Variables:
  • label_a (str) – The compared phase.

  • label_b (str) – The reference phase.

  • diff (pandas.Series) – The observed difference a − b per statistic.

  • n_a (int) – Responded trials in the compared phase.

  • n_b (int) – Responded trials in the reference.

  • n_sessions_a (int) – Sessions in the compared phase.

  • n_sessions_b (int) – Sessions in the reference.

  • difference_draws (Mapping[str, pandas.DataFrame]) – The bootstrap draws of the difference per unit, {unit: frame}.

  • perm_p (pandas.Series | None) – The permutation p per statistic, when permutations were run; else None.

  • um_diff (numpy.ndarray | None) – The difference of the two update matrices, when computed; else None.

  • um_rmse (float) – The root-mean-square of um_diff, when computed.

  • um_corr (float) – The correlation between the two update matrices, when computed.

Parameters:
  • label_a (str)

  • label_b (str)

  • diff (Series)

  • n_a (int)

  • n_b (int)

  • n_sessions_a (int)

  • n_sessions_b (int)

  • difference_draws (Mapping[str, DataFrame])

  • perm_p (Series | None)

  • um_diff (ndarray | None)

  • um_rmse (float)

  • um_corr (float)

boot(unit=None, *, ci=0.95)[source]#

The bootstrap interval of each difference, with its two-sided p against 0.

Parameters:
  • unit (str | None) – The resampling unit; None for the first one available.

  • ci (float) – The interval’s coverage.

Returns:

One row per statistic, with ci_lo, ci_hi, p, median and n_draws.

Return type:

DataFrame

table(unit=None, *, ci=0.95)[source]#

The contrast as a table.

Parameters:
  • unit (str | None) – The resampling unit; None for the first one available.

  • ci (float) – The interval’s coverage.

Returns:

One row per statistic, with diff, ci_lo, ci_hi, boot_p, perm_p and unit.

Return type:

DataFrame

class behav_utils.analysis.Interaction(label_a, label_b, contrast_a, contrast_b, delta_a, delta_b, interaction, draws, draws_a, draws_b, shared_result=False)[source]#

Difference of differences: (Δ_a) − (Δ_b), bootstrap only.

Variables:
  • label_a (str) – The first result’s name.

  • label_b (str) – The second result’s name.

  • contrast_a (str) – The contrast taken from the first result.

  • contrast_b (str) – The contrast taken from the second.

  • delta_a (pandas.Series) – The first contrast’s difference per statistic.

  • delta_b (pandas.Series) – The second’s.

  • interaction (pandas.Series) – delta_a − delta_b per statistic.

  • draws (Mapping[str, pandas.DataFrame]) – The bootstrap draws of the interaction per unit.

  • draws_a (Mapping[str, pandas.DataFrame]) – The first contrast’s draws per unit.

  • draws_b (Mapping[str, pandas.DataFrame]) – The second’s.

  • shared_result (bool) – Whether both contrasts came from one result, so their shared reference cancels.

Parameters:
  • label_a (str)

  • label_b (str)

  • contrast_a (str)

  • contrast_b (str)

  • delta_a (Series)

  • delta_b (Series)

  • interaction (Series)

  • draws (Mapping[str, DataFrame])

  • draws_a (Mapping[str, DataFrame])

  • draws_b (Mapping[str, DataFrame])

  • shared_result (bool)

table(unit=None, *, ci=0.95)[source]#

The interaction as a table.

Parameters:
  • unit (str | None) – The resampling unit; None for the first one available.

  • ci (float) – The interval’s coverage.

Returns:

One row per statistic, with delta_a and its interval, delta_b and its interval, interaction, ci_lo, ci_hi, p and n_draws.

Return type:

DataFrame

behav_utils.analysis.compute_delta_stat(phases, names=('mu', 'sigma', 'lapse_low', 'lapse_high'), *, labels=None, reference=None, curve=True, update_matrix=False, downsample=False, n_permutations=0, n_bootstrap=1000, units=('trials',), n_bins=8, trial_filter='post_correct', n_repeats=200, seed=42)[source]#

Compare N phases against a reference, with bootstrap CI and permutation p.

Parameters:
  • phases (Mapping[str, Sequence[SessionData]] | Sequence[Sequence[SessionData]]) – {label: phase}, or a list of phases with labels. Each phase is the output of filter_trials.

  • names (Sequence[str]) – scalar stat names (default: the four psychometric params).

  • labels (Sequence[str] | None) – The phase labels, in order, when phases is a list; None for ‘phase_0’, ‘phase_1’, and so on. Ignored when phases is a dict.

  • reference (str | None) – label the others are contrasted against (default: first).

  • curve (bool) – also fit a PsychometricCurve per phase (display).

  • update_matrix (bool) – also fit an UpdateMatrix per phase and report the matrix difference, RMSE and correlation per contrast (descriptive only — no resampling; one matrix is nine fits).

  • downsample (bool) – match trial counts across phases before comparing (matched n per unit: trials for stats and the curve, post-correct pairs for the matrix). Removes precision bias at the cost of power.

  • n_permutations (int) – label shuffles for a permutation p (default 0 = none). Valid only when the label was randomised per trial, so every non-reference phase must share at least one session with the reference (same session_id) and none may share a trial with it, or a ValueError is raised. Floor is 1 / (n_permutations + 1).

  • n_bootstrap (int) – resamples per phase per unit (0 to skip).

  • units (Sequence[str]) – resampling units, e.g. ('trials', 'sessions'). The first is the default for .boot() / .table(). Sessions are drawn once per draw for all phases, within groups of sessions that belong to the same phases: phases cut from the same sessions get the same sessions in every draw (a paired contrast), and phases with different sessions are drawn separately. A phase with < 2 sessions gets no session draws.

  • n_bins (int) – Stimulus bins of the update matrices.

  • trial_filter (str) – Which pairs the update matrices use, ‘post_correct’ or ‘all’.

  • n_repeats (int) – matched-n draws for the readouts when downsampling.

  • seed (int) – base RNG seed.

Returns:

DeltaStats.

Raises:

ValueError – fewer than two phases, unknown reference or unit, an order-dependent stat requested with trial-level resampling, or a permutation requested between phases that share no session or that share trials.

Warns:
  • UserWarning – a phase shares trials with the reference (no permutation requested). One trial class containing another, e.g. post_opto inside non_opto, dilutes the contrast; make the reference disjoint with a mask_fn.

  • UserWarning – 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), so its variation is left out of the session interval.

Return type:

DeltaStats

behav_utils.analysis.compute_interaction(result_a, result_b, contrast, *, contrast_b=None, label_a='a', label_b='b')[source]#

Difference of differences between two DeltaStats results.

Answers “is the opto effect different in these sessions than in those” — e.g. whether the on − off shift on sham sessions differs from the shift on real opto sessions, which is what separates an inactivation effect from the light-delivery artefact. Comparing two p-values is not a substitute: “significant here, not there” is not evidence they differ.

Bootstrap only: session type was not randomised per trial, so no shuffle reproduces the design.

Parameters:
  • result_a (DeltaStats) – The first output of compute_delta_stat.

  • result_b (DeltaStats) – The second. Pass the same object twice to compare two contrasts within one result; their shared reference draws then cancel exactly.

  • contrast (str) – contrast key in result_a, e.g. ‘opto_vs_non_opto’.

  • contrast_b (str | None) – contrast key in result_b; defaults to contrast.

  • label_a (str) – The first result’s name in the output.

  • label_b (str) – The second result’s name in the output.

Returns:

An Interaction, the difference between the two contrasts per statistic, with its bootstrap uncertainty.

Raises:
  • KeyError – if either contrast is absent.

  • ValueError – if the two contrasts share no bootstrap unit.

Return type:

Interaction

behav_utils.analysis.bootstrap_phase_stats(phase, names, *, n_draws=1000, n_trials=None, seed=0, unit='trials')[source]#

Resample one phase’s trials (or sessions) and recompute its statistics.

Delegates to resample_stat_vectors(), the library’s single resample-and-recompute engine, so the frozen lag-1 prev_* pairing survives every draw (a repeated trial carries its own predecessor).

unit='trials' (default) is a per-trial bootstrap, stratified by stimulus bin, and answers “how precisely is this phase’s stat pinned by its trials”. unit='sessions' resamples whole sessions with replacement instead: it treats the session as the independent unit, so the interval reflects session-to-session scatter (the right unit when the phase spans sessions that were not randomised per trial — e.g. an opto phase vs a sham phase). A matched n_trials only applies to the trial bootstrap.

The trial draw is stratified by stimulus bin: the stimulus composition is held roughly fixed across draws because the stimulus set is fixed by the design, so the interval is conditional on it (slightly narrower than an unconditional bootstrap). The session draw is unstratified.

Parameters:
  • phase – list of SessionData from filter_trials.

  • names (Sequence[str]) – scalar stat names. For unit='trials' these must be trial-exchangeable; unit='sessions' accepts any stat.

  • n_draws (int) – number of resamples.

  • n_trials (int | None) – trial bootstrap only — draw this many trials instead of the natural count (a matched n for equal-precision contrasts).

  • seed (int) – RNG seed.

  • unit (str) – ‘trials’ (default) or ‘sessions’.

Returns:

pd.DataFrame (n_draws × names). Failed draws are NaN rows.

Raises:

ValueError – if unit='trials' and any stat is not trial-exchangeable.

Return type:

DataFrame

behav_utils.analysis.permute_phase_difference(phase_a, phase_b, names, *, n_draws=1000, n_trials=None, seed=0)[source]#

Null distribution of stat(a) - stat(b) from shuffling the labels.

Pools both phases, reassigns the phase label at random keeping the group sizes fixed, and recomputes the difference — the null being “which phase a trial belongs to carries no information”.

Only use this where the label really was randomised per trial. Opto vs non-opto within a phase qualifies (the rig interleaved it). Comparing phases that differ by session type does not: those trials were collected on different days, so a shuffle would treat non-exchangeable trials as exchangeable and absorb every between-day difference into the null. Use bootstrap_phase_stats() and an interval there instead.

Parameters:
  • phase_a – the first phase; the difference is a - b.

  • phase_b – the second phase.

  • names (Sequence[str]) – scalar stat names.

  • n_draws (int) – number of shuffles. The smallest reportable p is 1 / (n_draws + 1).

  • n_trials (int | None) – draw this many per side instead of the natural counts.

  • seed (int) – RNG seed.

Returns:

pd.DataFrame (n_draws × names) of differences under the null. A shuffle that produced an unfittable split is a NaN row; summarise_draws drops NaNs rather than counting them as zero.

Raises:

ValueError – the phases share trials (shared_trial_count > 0).

Return type:

DataFrame

behav_utils.analysis.shared_trial_count(phase_a, phase_b)[source]#

How many trials two phases have in common (same session_id and trial_number).

Two phases cut from the same sessions overlap when one trial class contains the other, e.g. post_opto trials are also non_opto trials. A contrast between overlapping phases is diluted (the shared trials sit on both sides), and a permutation cannot give one trial two labels, so permute_phase_difference refuses them and compute_delta_stat refuses or warns.

Parameters:
  • phase_a – One phase, a list of sessions.

  • phase_b – Another.

Returns:

The number of trials in both.

Return type:

int

behav_utils.analysis.summarise_draws(draws, *, observed=None, ci=0.95, null_value=0.0)[source]#

Percentile interval and two-sided p from a distribution of draws.

Works for either engine, but the p means different things:

  • bootstrap draws (of a difference) — p is the proportion of draws on the far side of null_value, doubled. Report observed as the estimate and the interval as its uncertainty.

  • permutation draws — pass observed (the unshuffled difference) and p becomes the proper permutation p-value, (1 + #{|draw| >= |observed|}) / (n + 1). The +1 keeps it from ever being exactly zero; the floor is 1 / (n + 1).

Do not compare two intervals by eye to judge a difference. Two 95% intervals can overlap while the difference is significant. Build the difference distribution and summarise that instead.

Parameters:
  • draws – 1-D array-like of resampled values (a DataFrame column). NaNs dropped.

  • observed (float | None) – the unshuffled statistic — required for a permutation p.

  • ci (float) – interval mass, e.g. 0.95.

  • null_value (float) – value corresponding to “no effect”.

Returns:

DrawSummary; all NaN (except n_draws) if fewer than 10 usable draws.

Return type:

DrawSummary

Source: percentile bootstrap intervals (Efron & Tibshirani, 1993); the permutation p with one added to the count and to the number of permutations (Phipson & Smyth, 2010); the docs site lists the references.

behav_utils.analysis.summarise_draw_frame(draws, *, observed=None, ci=0.95, null_value=0.0)[source]#

summarise_draws for every column of a frame of draws.

Parameters:
  • draws (DataFrame) – Draws, one column per statistic.

  • observed (Series | None) – The observed values, by statistic; None when the draws are bootstrap draws.

  • ci (float) – The interval’s coverage.

  • null_value (float) – The value the p is computed against.

Returns:

One row per statistic, with ci_lo, ci_hi, p, median and n_draws.

Return type:

DataFrame

class behav_utils.analysis.DrawSummary(ci_lo, ci_hi, p, median, n_draws)[source]#

The summary of one statistic’s draws, from summarise_draws.

Variables:
  • ci_lo (float) – Lower end of the percentile interval.

  • ci_hi (float) – Upper end of the percentile interval.

  • p (float) – The two-sided p: doubled tail proportion for bootstrap draws, the permutation p when observed was given.

  • median (float) – The draws’ median.

  • n_draws (int) – How many finite draws there were.

Parameters:
  • ci_lo (float)

  • ci_hi (float)

  • p (float)

  • median (float)

  • n_draws (int)

behav_utils.analysis.downsample(clean, n, unit='trials', with_replacement=True, n_bins=8, rng=None)[source]#

Subsample clean sessions to ~n of the chosen unit; returns new [SessionData].

The matched-n draw is pooled across sessions (frozen prev_* make this safe), then split back per session and rebuilt, so the output is consumable by compute_psychometric_curve / compute_update_matrix unchanged. with_replacement=True allows a trial to be drawn more than once (a bootstrap resample); False is a clean subsample.

Parameters:
  • clean – The sessions, already filtered.

  • n – How many of unit to draw.

  • unit – ‘trials’ (responded trials) or ‘pairs’ (post-correct pairs).

  • with_replacement – Draw with replacement (a bootstrap resample) or without (a subsample).

  • n_bins – Stimulus bins for stratifying the draw.

  • rng – A random generator or an int seed; None starts a fresh generator.

Returns:

The drawn sessions.

Raises:

ValueError – unit is neither ‘trials’ nor ‘pairs’.

behav_utils.analysis.resample_stat_vectors(clean, stat_names, *, n=None, n_repeats=1000, with_replacement=True, unit='trials', seed=0)[source]#

Resample trials K times and recompute summary stats — one matrix of replicates.

The single resample-and-recompute engine for scalar stats. It is the scalar analogue of resample_psychometric_curve() / resample_update_matrix() (which target the readouts), and serves BOTH uses via its arguments:

  • trial bootstrap — with_replacement=True, n=None (natural count)

  • matched-n draw — with_replacement=False, n=target_n

Drawing is delegated to downsample(), so the frozen lag-1 prev_* pairing is preserved on every resample (a repeated trial index carries its own predecessor). Stats registered exchangeable=False are refused: trial resampling is invalid for order-dependent stats and would return a confidently-wrong interval.

Parameters:
  • clean – list of [SessionData], abort/opto-cleared (a phase/condition).

  • stat_names – scalar stat names (list_stats()).

  • n – trials/pairs to draw per repeat; None → the natural count of unit in clean (the right default for a bootstrap).

  • n_repeats – number of resamples (rows of the returned matrix).

  • with_replacement – True for a bootstrap resample, False for a clean subsample.

  • unit – ‘trials’ (responded trials), ‘pairs’ (post-correct pairs), or ‘sessions’ (whole sessions, drawn intact — valid for order-dependent stats; natural n = n_sessions).

  • seed – RNG seed.

Returns:

pd.DataFrame of shape (n_repeats, len(stat_names)), columns in request order. Rows where the draw was empty are NaN.

Raises:

ValueError – if any requested stat is not trial-exchangeable.

behav_utils.analysis.resample_psychometric_curve(clean, n, *, n_repeats=100, with_replacement=True, n_bins=8, seed=42)[source]#

n_repeats matched-n draws of n responded trials, each fitted, then aggregated.

Parameters:
  • clean – The sessions, already filtered.

  • n – Responded trials per draw.

  • n_repeats – How many draws.

  • with_replacement – Draw with replacement or without.

  • n_bins – Stimulus bins for stratifying the draws.

  • seed – Random seed.

Returns:

The aggregated curve.

Return type:

PsychometricCurve

behav_utils.analysis.resample_update_matrix(clean, n, *, n_repeats=100, with_replacement=True, n_bins=8, trial_filter='post_correct', seed=42)[source]#

n_repeats matched-n draws of n post-correct pairs, each fitted, cell-wise mean.

Parameters:
  • clean – The sessions, already filtered.

  • n – Post-correct pairs per draw.

  • n_repeats – How many draws.

  • with_replacement – Draw with replacement or without.

  • n_bins – Stimulus bins.

  • trial_filter – ‘post_correct’ or ‘all’.

  • seed – Random seed.

Returns:

The cell-wise mean matrix.

Return type:

UpdateMatrix

class behav_utils.analysis.RollingStats(curves, session_info, names, window, step, per_session)[source]#

Rolling statistics as a tidy frame.

curves columns: session, session_idx, session_type, distribution, trial, stat, value; session_info columns: session, session_idx, session_type, distribution, n_trials (a session too short for any window still has its row). In pooled mode there is a single session labelled 'pooled'.

Variables:
  • curves (pandas.DataFrame) – The rolling values, a tidy frame.

  • session_info (pandas.DataFrame) – One row per session.

  • names (Tuple[str, ...]) – The statistics computed.

  • window (int) – Trials per window.

  • step (int) – Trials between window starts.

  • per_session (bool) – Whether windows run within each session or over the pooled trials.

Parameters:
  • curves (DataFrame)

  • session_info (DataFrame)

  • names (Tuple[str, ...])

  • window (int)

  • step (int)

  • per_session (bool)

curve(stat, session=None)[source]#

The trial, value rows of one statistic.

Parameters:
  • stat (str) – The statistic.

  • session – Only this session; None for all.

Returns:

The rows.

Return type:

DataFrame

n_trials(session)[source]#

How many trials a session has.

Parameters:

session – The session’s label in session_info.

Returns:

The count.

Return type:

int

behav_utils.analysis.compute_rolling_stats(sessions, names, *, per_session=True, window=50, step=10, min_short=10)[source]#

Rolling scalar statistics over pre-filtered sessions.

Slides a window-trial window (stride step) along trials in acquisition order and computes names in each window.

Parameters:
  • sessions (Sequence[SessionData]) – pre-filtered SessionData. filter_trials must have run.

  • names (str | Sequence[str]) – scalar stat name(s); str or list.

  • per_session (bool) – True windows within each session (no window crosses a boundary), one curve per session. False concatenates all sessions in order and windows across the run.

  • window (int) – window size in trials.

  • step (int) – stride between window centres. Overlapping windows smooth the curve but do NOT add independent information.

  • min_short (int) – a block of min_short..window-1 trials still gets one whole-block point; below this it gets nothing.

Returns:

RollingStats.

Return type:

RollingStats

behav_utils.analysis.collect_rows(scalars, animal, group=None, group_col='group', **labels)[source]#

Stamp per-animal scalar rows with the animal, its group and any labels.

Turns the rows an analysis emits for one animal — PhaseStats.to_rows() / .sessions, Contrast.table(), as to_dict('records') — into fully-labelled rows ready to accumulate across animals.

animal always wins: a row’s own animal key is overwritten (a warning is issued if it held a different real id), so a frame built without the id can never collapse several animals into one unit.

Parameters:
  • scalars (Sequence[Mapping]) – mappings with at least stat and value (extra keys carried through).

  • animal (str) – animal id.

  • group (str | None) – the group this animal belongs to (cohort, condition, …). Optional: omit if you will split by explicit name-lists in compare_groups instead.

  • group_col (str) – the column name to store group under. Default ‘group’.

  • **labels – any extra columns to stamp on every row (session_type, distribution, contrast, …).

Returns:

A list of dicts, one per scalar.

Return type:

List[Dict]

behav_utils.analysis.compare_groups(rows, group_col='group', groups=None, stats=None, value_col='value', stat_col='stat', unit_col='animal', paired=False, alternative='two-sided')[source]#

Rank-test each stat across animals, split into two groups.

One test per stat: one value per animal (rows of the same animal within a group are averaged), split into the two groups, rank-test. Animals with a non-finite value for a stat are dropped from that stat’s test only.

Grouping is specified one of two ways:

  • by column — group_col names a column already on the rows (the default, ‘group’);

  • by name-lists — groups={label: [animal, ...]} assigns each animal to a group explicitly, needing no group column. Use this for an ad-hoc split.

Parameters:
  • rows (DataFrame | Sequence[Mapping[str, Any]]) – list of dicts, or a DataFrame — accumulated collect_rows output across animals.

  • group_col (str) – column holding the grouping (ignored if groups given).

  • groups (Sequence[str] | Mapping[str, Sequence[str]] | None) – either the two group labels in (a, b) order (selecting from group_col), or a {label: [animal_ids]} mapping that defines the split directly. If None, the two labels present in group_col are used in sorted order — pass the pair explicitly whenever the reference group matters.

  • stats (Sequence[str] | None) – which stats to test; default is every stat present.

  • value_col (str) – The column holding the values.

  • stat_col (str) – The column holding each value’s statistic name.

  • unit_col (str) – The column identifying the unit, usually the animal, a value belongs to.

  • paired (bool) – Wilcoxon signed-rank instead of Mann-Whitney. The two “groups” are then two conditions of the same animals: the values are aligned by unit_col and an animal missing a finite value on either side is dropped from that pair.

  • alternative (str) – ‘two-sided’ | ‘less’ | ‘greater’.

Returns:

GroupComparison — .test(stat) is a RankTest whose min_p is the smallest p obtainable at these group sizes; compare a p against it before reading a null as no effect. .table() is tidy.

Raises:

ValueError – on no rows, fewer than two groups, a name-list mapping without exactly two groups, or paired=True with disjoint animals.

Return type:

GroupComparison

class behav_utils.analysis.GroupComparison(tests=<factory>, group_a=None, group_b=None, paired=False)[source]#

One RankTest per stat between two groups of animals (compare_groups).

Variables:
  • tests (Dict[str, behav_utils.analysis.group.RankTest]) – One rank test per statistic, {stat: RankTest}.

  • group_a (object) – The first group’s label.

  • group_b (object) – The second group’s label.

  • paired (bool) – Whether the tests were paired.

Parameters:
  • tests (Dict[str, RankTest])

  • group_a (object)

  • group_b (object)

  • paired (bool)

test(stat)[source]#

The rank test for one statistic.

Parameters:

stat (str) – The statistic.

Returns:

The test.

Return type:

RankTest

table()[source]#

One tidy row per statistic.

Returns:

The rows, with stat, group_a, group_b, n_a, n_b, median_a, median_b, statistic, p, min_p and note.

Return type:

DataFrame

to_rows()#

One tidy row per statistic.

Returns:

The rows, with stat, group_a, group_b, n_a, n_b, median_a, median_b, statistic, p, min_p and note.

Return type:

DataFrame

class behav_utils.analysis.RankTest(test, paired, alternative, statistic, p, n_a, n_b, min_p, group_a=None, group_b=None, median_a=nan, median_b=nan, note='')[source]#

One rank test (rank_test): Wilcoxon signed-rank (paired) or Mann-Whitney U.

n is the number of pairs used (paired) or n_a + n_b (unpaired); min_p the smallest two-sided p this test could return at that size.

Variables:
  • test (str) – ‘signed_rank’ or ‘rank_sum’.

  • paired (bool) – Whether the test was paired.

  • alternative (str) – ‘two-sided’, ‘less’ or ‘greater’.

  • statistic (float) – The test statistic.

  • p (float) – The p value.

  • n_a (int) – Values in the first group.

  • n_b (int) – Values in the second group.

  • min_p (float) – The smallest two-sided p the test could give at these sizes.

  • group_a (object) – The first group’s label.

  • group_b (object) – The second group’s label.

  • median_a (float) – The first group’s median.

  • median_b (float) – The second group’s median.

  • note (str) – Why the test could not run, when it could not; else ‘’.

Parameters:
  • test (str)

  • paired (bool)

  • alternative (str)

  • statistic (float)

  • p (float)

  • n_a (int)

  • n_b (int)

  • min_p (float)

  • group_a (object)

  • group_b (object)

  • median_a (float)

  • median_b (float)

  • note (str)

to_rows()[source]#

The result as a one-row table.

Returns:

The row.

Return type:

DataFrame

class behav_utils.analysis.UnitBootstrap(point, lo, hi, n)[source]#

Across-unit bootstrap of one per-unit value array (bootstrap_units).

Variables:
  • point (float) – The statistic of the units’ values, the mean by default.

  • lo (float) – Lower end of the interval.

  • hi (float) – Upper end of the interval.

  • n (int) – How many units.

Parameters:
  • point (float)

  • lo (float)

  • hi (float)

  • n (int)

to_rows()[source]#

The result as a one-row table.

Returns:

The row.

Return type:

DataFrame

class behav_utils.analysis.ArrayAverage(mean, sem, n)[source]#

Element-wise mean and SEM across a stack (average_arrays).

Variables:
  • mean (numpy.ndarray) – The element-wise mean.

  • sem (numpy.ndarray) – The element-wise SEM.

  • n (int) – How many arrays were averaged.

Parameters:
  • mean (ndarray)

  • sem (ndarray)

  • n (int)

behav_utils.analysis.combine(points, *, over='session', how='mean', weight=None)[source]#

Collapse one axis of a tidy stat table, carrying all other label columns.

Groups by every column except over and the value/weight/CI columns, so it can never silently average across conditions, phases, stats or groups.

  • over='session' → one value per (animal, stat, label…) — per-animal.

  • over='animal' → one value per (stat, label…) — per-group.

This is the average path. The trial-weighted alternative (re-pool trials, compute once) comes from compute_phase_stats(...).to_rows() instead — a deliberately different number. Within-unit CIs are dropped on output because they no longer apply; a group CI comes from bootstrap_units().

Parameters:
  • points (DataFrame) – tidy stat frame (columns include value, n_trials and the axis over).

  • over (str) – axis column to collapse.

  • how (str) – ‘mean’ or ‘median’.

  • weight (str | None) – None (equal weight) or ‘n_trials’ (trial-weighted mean; ignored when how='median').

Returns:

The collapsed frame, with the grouping keys, value, n_trials (summed) and n_units (the number of contributing rows).

Raises:

ValueError – if over is absent, already collapsed (all-<NA>), or if no grouping columns would remain.

Return type:

DataFrame

behav_utils.analysis.paired_diff(points, *, by, a, b, keys=('animal',), value='value')[source]#

Per-unit difference value[a] - value[b] across label column by.

Expects one row per (unit, by-level, stat) — i.e. animal-level input (use compute_phase_stats(...).to_rows() or combine() first). Inner-joins the two levels on every identifying column, so units missing a or b are dropped — and a warning reports how many.

Produces the Δ table used both for the opto−nonopto effect and, applied twice, the difference-of-differences.

Parameters:
  • points (DataFrame) – tidy stat frame.

  • by (str) – label column holding the two conditions.

  • a (str) – the first level of by; the difference is a - b.

  • b (str) – the second level of by.

  • keys (Sequence[str]) – the unit identifier(s) (e.g. ('animal',)); used only to name dropped units in the warning.

  • value (str) – value column.

Returns:

Frame with the identifying columns, a and b (the two values) and delta.

Raises:

ValueError – if by, a or b is absent.

Return type:

DataFrame

behav_utils.analysis.bootstrap_units(values, *, n_boot=2000, ci=0.95, statistic=<function mean>, seed=0)[source]#

Across-unit (cluster) bootstrap CI on a per-unit value array.

Resamples the units (animals) with replacement — this is the interval for a group claim (between-animal variability), NOT the within-unit interval compute_delta_stat stores per animal.

Parameters:
  • values (Iterable[float]) – 1D per-unit values (e.g. one Δ per animal). NaNs dropped.

  • n_boot (int) – bootstrap resamples.

  • ci (float) – central interval width (0.95 → 2.5/97.5 percentiles).

  • statistic (Callable[[ndarray], float]) – summary applied to each resample (default mean).

  • seed (int) – RNG seed.

Returns:

UnitBootstrap; lo/hi are NaN when n<2.

Return type:

UnitBootstrap

behav_utils.analysis.rank_test(a, b, *, paired=False, alternative='two-sided')[source]#

Rank test between two per-unit value arrays.

Paired → Wilcoxon signed-rank (requires aligned, equal-length arrays; align with paired_diff() first). Unpaired → Mann-Whitney U. Plain arrays in, not frames — the project’s within/between/interaction opto tests are all expressed through this one function plus paired_diff().

Power is limited at small n; with 6 paired animals a two-sided Wilcoxon p cannot fall below ~0.031 — min_p on the result says what the floor is.

Returns:

RankTest. Degenerate cases (no data, all-zero paired differences) have NaN p and a note.

Raises:

ValueError – paired with mismatched lengths.

Parameters:
  • a (Iterable[float]) – One group’s values, one per unit.

  • b (Iterable[float]) – The other group’s, aligned with a when paired.

  • paired (bool) – Use the Wilcoxon signed-rank test on a - b instead of Mann–Whitney U.

  • alternative (str) – ‘two-sided’, ‘less’ or ‘greater’.

Returns:

The test’s result.

Return type:

RankTest

Source: the Wilcoxon signed-rank test (Wilcoxon, 1945) and the Mann–Whitney U test (Mann & Whitney, 1947); the docs site lists the references.

behav_utils.analysis.average_arrays(arrays, *, ddof=1)[source]#

Element-wise mean and SEM across a stack of same-shaped arrays.

Shape-agnostic: scalars, 1D psychometric curves and 2D update matrices all go through here — the caller picks which field to stack (y_fit for a curve band, the params vector, or the UM grid). Averaging curves point-wise and averaging the fitted params give different mean curves; choose deliberately.

Element [i] of every input must correspond (same x-grid for curves, same bin layout for UMs). Mismatched shapes raise rather than broadcast.

Parameters:
  • arrays (Sequence[ndarray]) – list of ndarrays, all the same shape.

  • ddof (int) – delta-DOF for the across-stack std (1 = sample SEM).

Returns:

ArrayAverage; sem is all-NaN when n<2.

Raises:

ValueError – empty input, or shapes that do not match.

Return type:

ArrayAverage

behav_utils.analysis.min_achievable_p(test, *, n=None, n1=None, n2=None)[source]#

Smallest two-sided p-value the given rank test can return at this sample size.

Rank tests are discrete: with few observations even a perfectly consistent effect cannot drop below a floor set by the number of possible rank arrangements. Report this beside a non-significant result to show whether the test could have rejected at all — a p that merely equals this floor is the strongest evidence the sample can give, not a meaningful null.

Parameters:
  • test – ‘signed_rank’ (Wilcoxon signed-rank / paired) — needs n, the number of non-zero pairs; floor = 2 / 2**n (all pairs the same sign). ‘rank_sum’ (Mann-Whitney U / unpaired) — needs n1, n2; floor = 2 / C(n1 + n2, n1) (the most extreme rank separation).

  • n – non-zero pair count for ‘signed_rank’.

  • n1 – the first group’s size, for ‘rank_sum’.

  • n2 – the second group’s size, for ‘rank_sum’.

Returns:

Minimum two-sided p in (0, 1], or nan if sizes are missing / too small.

Assumes the exact (permutation) null and no ties; scipy uses the exact distribution at these small n, so the floor matches what rank_test() can actually return.