API reference

This page documents the public functions and experiment objects used by the tutorial workflow. New user scripts should normally start with import ic_analysis as ic and build an experiment object via ic_analysis.experiment().

Experiment creation

experiment(*, EXPERIMENT, PHASES=None, SUBJECTS=None)[source]

Build a generic IntelliCage experiment object from user-script metadata.

This is the recommended public entry point after import ic_analysis as ic. It validates experiment-level metadata, phase definitions, and the subject registry, creates the configured results folder, and returns an ic_analysis.experiment.IntelliCageExperiment object ready for load(), prepare_analysis(), and modular plotting calls.

Parameters:
  • EXPERIMENT (ExperimentMetadata | dict[str, Any]) – Experiment metadata as an ExperimentMetadata instance or a dictionary. Required keys for dictionaries are name, root_data_path, results_data_path, and group_names. The optional mouse_day dictionary can define {"start": "06:00", "end": "18:00"}.

  • PHASES (dict[int | str, PhaseMetadata | dict[str, Any]] | None) – Phase definitions as a mapping from phase number to PhaseMetadata or dictionary. Default is None when phases are embedded in EXPERIMENT. Each phase can define short_name, long_name, folder_name, color, and scheduled_start_hour.

  • SUBJECTS (SubjectRegistry | dict[str | int, SubjectMetadata | dict[str, Any]] | None) – Subject definitions as a SubjectRegistry or dictionary. No default is allowed: the toolkit deliberately analyzes only explicitly declared animals.

Return type:

IntelliCageExperiment

Returns:

A configured ic_analysis.experiment.IntelliCageExperiment.

Raises:

ValueError – If phases, groups, or subjects are missing or invalid.

create_subjects_yaml_template(*, EXPERIMENT, PHASES=None, number_of_phases=None, output_path=None)[source]

Create or update a subject YAML template from detected raw animal IDs.

The helper scans Visits.txt files below the experiment data root, detects unique raw IntelliCage animal IDs, and writes editable subject entries to YAML. Existing entries are preserved; newly detected IDs are appended. IDs present in the YAML but absent from current raw data are reported but not deleted.

Parameters:
  • EXPERIMENT (ExperimentMetadata | dict[str, Any]) – Experiment metadata object or dictionary. It must define root_data_path so raw exports can be scanned.

  • PHASES (dict[int | str, PhaseMetadata | dict[str, Any]] | None) – Optional phase mapping. Default is None when using number_of_phases. If provided, phase folder_name values are used only to prefill phase windows when export-block folder names happen to match biological phase names.

  • number_of_phases (int | None) – Optional number of default PhaseN folders to scan. Default is None. Use this only when no PHASES dictionary is available yet.

  • output_path (Path | str | None) – Optional YAML path. Default is <root_data_path>/subjects.yaml.

Return type:

Path

Returns:

The written YAML path.

Raises:

ValueError – If neither PHASES nor number_of_phases is provided, or if an existing YAML file is not a subject mapping.

load_subjects_yaml(path)[source]

Load a user-edited subject YAML file as a SUBJECTS dictionary.

The YAML may either be a direct subject mapping or contain a top-level subjects mapping. The returned dictionary can be passed directly to ic.experiment(EXPERIMENT=..., PHASES=..., SUBJECTS=...).

Parameters:

path (Path | str) – Path to the subject YAML file.

Return type:

dict[str, dict[str, Any]]

Returns:

A dict keyed by raw IntelliCage animal ID.

Raises:

ValueError – If the YAML file does not contain a subject mapping.

Experiment definitions

class PhaseMetadata(number, short_name, long_name, folder_name=None, color=None, scheduled_start_hour=None)[source]

Description of one experiment phase.

Parameters:
  • number (int)

  • short_name (str)

  • long_name (str)

  • folder_name (str | None)

  • color (str | None)

  • scheduled_start_hour (float | None)

property raw_folder_name: str

Return the IntelliCage export folder expected for this phase.

class ExperimentMetadata(name, root_data_path, results_data_path, phases, group_names, group_colors=<factory>, phase_colors=<factory>, optional_phase_numbers=<factory>, mouse_day_start_hour=6.0, awake_duration_hours=12.0, mouse_day_start_time=None, mouse_day_end_time=None, experiment_day0_start_hour=None, schedule_anchor_phase_number=None)[source]

Experiment-level metadata defined by the user script.

Parameters:
  • name (str)

  • root_data_path (Path | str)

  • results_data_path (Path | str)

  • phases (dict[int, PhaseMetadata | dict[str, Any]])

  • group_names (list[str] | tuple[str, ...])

  • group_colors (dict[str, str])

  • phase_colors (dict[int, str])

  • optional_phase_numbers (set[int])

  • mouse_day_start_hour (float)

  • awake_duration_hours (float)

  • mouse_day_start_time (str | None)

  • mouse_day_end_time (str | None)

  • experiment_day0_start_hour (float | None)

  • schedule_anchor_phase_number (int | None)

property phase_name_map: dict[str, int]

Return a loader-compatible mapping from folder names to phase numbers.

property optional_phase_names: set[str]

Return optional phase folder names for the loader.

property phase_display_names: dict[int, str]

Return short phase labels for figures.

explicit_scheduled_phase_start_hours()[source]

Return scheduled start hours defined directly on phases.

Return type:

dict[int, float]

class SubjectMetadata(animal_id, group, sex, true_id, phase_windows=<factory>, age_months=None, date_of_birth=None, corner_assignments=<factory>)[source]

Subject-level metadata declared in a user script.

Parameters:
  • animal_id (str | int)

  • group (str)

  • sex (str)

  • true_id (str)

  • phase_windows (dict[int, tuple[str | datetime | Timestamp, str | datetime | Timestamp]])

  • age_months (float | None)

  • date_of_birth (str | datetime | Timestamp | None)

  • corner_assignments (dict[int, int])

property animal_id_key: str

Return the normalized raw IntelliCage animal ID.

phase_start(phase_number)[source]

Return the start timestamp for one phase.

Return type:

Timestamp

Parameters:

phase_number (int)

phase_end(phase_number)[source]

Return the end timestamp for one phase.

Return type:

Timestamp

Parameters:

phase_number (int)

to_loader_record(phase_numbers)[source]

Return one row of loader-compatible subject metadata.

Return type:

dict[str, Any]

Parameters:

phase_numbers (list[int])

class SubjectRegistry(subjects)[source]

Validated collection of subject metadata.

Parameters:

subjects (dict[str, SubjectMetadata])

classmethod from_mapping(data, *, default_phase_windows=None)[source]

Build a registry from a user-script dictionary.

Return type:

SubjectRegistry

Parameters:
  • data (dict[str | int, SubjectMetadata | dict[str, Any]])

  • default_phase_windows (dict[int, tuple[str | datetime | Timestamp, str | datetime | Timestamp]] | None)

validate_for_experiment(experiment)[source]

Check that every subject defines every required experiment phase.

Return type:

None

Parameters:

experiment (ExperimentMetadata)

to_loader_frame(experiment)[source]

Return all subjects as a loader-compatible DataFrame.

Return type:

DataFrame

Parameters:

experiment (ExperimentMetadata)

scheduled_phase_start_hours(experiment)[source]

Infer protocol start hours from subject-level phase windows.

Return type:

dict[int, float]

Parameters:

experiment (ExperimentMetadata)

The experiment object

class IntelliCageExperiment(experiment, subjects, cohort=None, visits=None, phase_windows=None, analysis_visits=None, analysis_metadata=None, analysis_nosepokes=None, analysis_phase_windows=None)[source]

Generic user-facing IntelliCage experiment object.

Parameters:
  • experiment (ExperimentMetadata)

  • subjects (SubjectRegistry)

  • cohort (CohortData | None)

  • visits (DataFrame | None)

  • phase_windows (DataFrame | None)

  • analysis_visits (DataFrame | None)

  • analysis_metadata (DataFrame | None)

  • analysis_nosepokes (DataFrame | None)

  • analysis_phase_windows (DataFrame | None)

property root_data_path: Path

Return the raw dataset root.

property results_data_path: Path

Return the configured result directory.

property scheduled_phase_start_hours: dict[int, float]

Return the active protocol schedule.

property phase_display_names: dict[int, str]

Return short phase names for plotting.

property phases: dict[int, Any]

Return the experiment phase metadata.

property group_names: list[str]

Return the configured group order.

property awake_start_clock_hour: float

Return the configured active-period start.

property awake_end_clock_hour: float

Return the configured active-period end.

load()[source]

Load raw IntelliCage exports and write reproducibility audit files.

load reads all configured Visits.txt and Nosepokes.txt exports below experiment.root_data_path, keeps only animals declared in subjects, joins subject metadata, summarizes nose-poke events per visit, assigns phase labels, and creates aligned experiment-time columns. It also writes the loaded visit/nose-poke tables plus experiment.yaml, phases.yaml, and subjects.yaml to the results folder.

Return type:

None

Returns:

None. The loaded tables are stored on the experiment object as visits, cohort, and phase_windows.

require_loaded()[source]

Return loaded cohort data and visits.

Return type:

tuple[CohortData, DataFrame]

Returns:

(cohort, visits) after load() has been called.

Raises:

RuntimeError – If the experiment has not been loaded yet.

filtered_visits(phase_max_hours=None, dayphase='all')[source]

Return loaded visits filtered by phase duration and dayphase.

Parameters:
  • phase_max_hours (dict[int, float] | None) – Optional dictionary mapping phase number to the maximum number of phase-elapsed hours to keep, for example {3: 72.0, 4: 72.0}. Default is None and keeps all available phase time.

  • dayphase (Literal['day', 'night', 'all']) – "day" keeps the configured active mouse-day, "night" keeps the inactive interval, and "all" keeps both. Default is "all" for this low-level accessor.

Return type:

DataFrame

Returns:

A filtered visit-level DataFrame.

prepare_analysis(*, phase_max_hours=None, excluded_groups=None, verbose=True)[source]

Prepare reusable analysis tables from loaded raw data.

This method applies optional phase-duration limits, applies group inclusion/exclusion, stores analysis-ready visits, metadata, nosepokes, and phase windows on the object, and writes audit tables to the results folder. Most plotting methods call this automatically when needed, but calling it explicitly is recommended in interactive scripts so the printed summary and audit files are created before plotting.

Parameters:
  • phase_max_hours (dict[int, float] | None) – Optional phase limits in hours, e.g. {3: 72.0, 4: 72.0}. Default is None. Use this when learning phases have unequal recording lengths and you want comparable analysis windows.

  • excluded_groups (list[str] | None) – Optional list of group labels to remove. Default is None. Use it for temporary QC reruns without editing the subject metadata.

  • verbose (bool) – Whether to print the analysis-preparation summary. Default is True for explicit interactive calls. Internal plot calls use False to avoid repeated terminal output.

Return type:

None

Returns:

None. Prepared tables are stored as analysis_visits, analysis_metadata, analysis_nosepokes, and analysis_phase_windows.

plot_ages(*, output_path=None, time_unit='months', show_N=True, plot_layout=None, base_font_size=10.0, font_family='Arial', figsize_cm=None)[source]

Plot mouse age at the first experiment phase start.

Age is computed from date_of_birth to the first phase start for each subject. If no date of birth is available, the subject-level age_months value is used when possible. The plotted table is saved alongside the figure for downstream use in GraphPad Prism or similar tools.

Parameters:
  • output_path (Path | None) – Optional explicit output file path. Default is None, which writes mouse_age_at_phase1_start_<unit>_violin to the experiment results folder.

  • time_unit (Literal['months', 'days', 'years']) – Unit for age values. Default is "months". Accepted values are "days", "months", and "years".

  • show_N (bool) – Whether x tick labels include per-group sample size. Default is True and recommended for public/reporting figures.

  • plot_layout (PlotLayout | dict | None) – Optional dict or PlotLayout. Supported keys are title, ylabel, ylim, and figsize_cm for this plot. Other common keys such as xlabel, xlim, xticks, yticks, and legend are ignored when they do not apply to the figure.

  • base_font_size (float) – Base font size in points. Default is 10.0.

  • font_family (str) – Matplotlib font family. Default is "Arial".

  • figsize_cm (tuple[float, float] | None) – Optional figure size as (width_cm, height_cm). Default is None and uses the plot preset unless overridden by plot_layout["figsize_cm"].

Return type:

None

Returns:

None.

plot_mice_activity(*, bin_hours=1, phases='all', dayphase='all', phase_max_hours=None, spread_metric='sem', plot_style='line', day_night_indicator=('awake', 'sleep'), output_dir=None, plot_layout=None, base_font_size=10.0, font_family='Arial', figsize_cm=None)[source]

Plot visit activity across all phases or a selected phase subset.

The plot shows visit counts per mouse and bin, plus group mean ΞΌ Β± SEM or ΞΌ Β± SD depending on spread_metric. Group-specific figures include individual mouse traces; the all-groups figure shows group summaries only. This is a quality-control plot, not a learning metric.

Parameters:
  • bin_hours (int) – Width of time bins in hours. Default is 1. Use 1 for detailed QC and larger values such as 2 or 24 for smoother overview plots.

  • phases (Union[Literal['all'], int, tuple[int, ...], list[int]]) – Phase selection. Default is "all". Use an integer such as 2 for one phase or a tuple such as (2, 4) for several phases.

  • dayphase (Literal['day', 'night', 'all']) – "all" plots full 24 h behavior, "day" plots the configured active mouse-day, and "night" plots the inactive interval. Default is "all" for activity QC.

  • phase_max_hours (dict[int, float] | None) – Optional phase limits in hours. Default is None.

  • spread_metric (Literal['sem', 'std']) – Group spread around the mean. Default is "sem"; use "std" to show standard deviation.

  • plot_style (str) – "line" or "step". Default is "line".

  • output_dir (Path | None) – Optional output folder. Default is a bin/dayphase folder below the experiment results folder.

  • plot_layout (PlotLayout | dict | None) – Optional dict or PlotLayout. Common keys are title, xlabel, ylabel, xlim, ylim, xticks, yticks, legend, and figsize_cm. Use {"legend": False} to hide legends or {"xlim": (0, 48)} to crop the displayed time range.

  • base_font_size (float) – Base font size in points. Default is 10.0.

  • font_family (str) – Matplotlib font family. Default is "Arial".

  • figsize_cm (tuple[float, float] | None) – Optional figure size as (width_cm, height_cm).

  • day_night_indicator (tuple[str, str] | None) – Labels for active/inactive background bands. Default is ("awake", "sleep"). Use ("aw", "sl") for compact labels or None to keep shading without text.

Return type:

Path

Returns:

The output directory as Path.

plot_NP_adaptation(*, phases=2, phase_number=None, bin_hours=1, dayphase='day', secondary_metric='lick_positive_visits', phase_max_hours=None, spread_metric='sem', plot_style='line', day_night_indicator=('awake', 'sleep'), show_all_visits=True, show_all_groups_SEM=False, single_group_display='spread', output_dir=None, plot_layout=None, base_font_size=10.0, font_family='Arial', figsize_cm=None)[source]

Plot visits against drinking visits for selected phases.

This diagnostic plot compares all visits with visits that contain licking. In formula form, the two plotted binned values are visits_per_bin and lick_positive_visits_per_bin per mouse, summarized as group mean plus the selected spread. The x-axis remains on elapsed experimental time. With phases="all", the full prepared timeline is shown. For phase subsets, only the requested phase windows are displayed while their real position on the experimental timeline is preserved.

Parameters:
  • phases (Union[Literal['all'], int, tuple[int, ...], list[int]]) – Phase selection. Default is 2 for the usual nose-poke adaptation phase. Use "all", an integer, or a tuple of integers.

  • phase_number (int | None) – Backward-compatible alias for one phase. Default is None; prefer phases in new scripts.

  • bin_hours (int) – Width of time bins in hours. Default is 1.

  • dayphase (Literal['day', 'night', 'all']) – "day", "night", or "all". Default is "day". Use "all" when the aim is protocol QC.

  • secondary_metric (str) – Reserved label selector. Default is "lick_positive_visits" and currently plots drinking visits.

  • phase_max_hours (dict[int, float] | None) – Optional phase limits in hours. Default is None.

  • spread_metric (Literal['sem', 'std']) – "sem" or "std". Default is "sem".

  • plot_style (str) – "line" or "bar". Default is "line".

  • show_all_visits (bool) – Whether the all-groups plot includes total visits in addition to drinking visits. Default is True. If False, only drinking visits are shown as solid group traces.

  • show_all_groups_SEM (bool) – Whether the all-groups plot shades the selected spread around each group mean. Default is False for a cleaner multi-group overview.

  • single_group_display (Literal['spread', 'individual']) – "spread" plots group mean plus spread_metric for each single-group panel. "individual" plots each mouse as a thin trace and overlays the group mean as a thicker trace. Default is "spread".

  • output_dir (Path | None) – Optional output folder. Default is a bin/dayphase folder below the experiment results folder.

  • plot_layout (PlotLayout | dict | None) – Optional dict or PlotLayout. Supported keys are title, xlabel, ylabel, xlim, ylim, xticks, yticks, legend, and figsize_cm.

  • base_font_size (float) – Base font size in points. Default is 10.0.

  • font_family (str) – Matplotlib font family. Default is "Arial".

  • figsize_cm (tuple[float, float] | None) – Optional figure size as (width_cm, height_cm).

  • day_night_indicator (tuple[str, str] | None) – Background labels. Default is ("awake", "sleep"); use None to hide text labels.

Return type:

Path

Returns:

The output directory as Path.

plot_NP_counts(*, phases='all', bin_hours=1, dayphase='day', phase_max_hours=None, spread_metric='sem', plot_style='line', day_night_indicator=('awake', 'sleep'), output_dir=None, plot_layout=None, base_font_size=10.0, font_family='Arial', figsize_cm=None)[source]

Plot nose-poke event counts for selected phases.

The plotted value is the sum of nose-poke events per mouse and time bin, summarized by group. Use this alongside learning-rate plots to check whether group differences reflect operant engagement rather than spatial learning. Selected phases are displayed on a compact x-axis without empty gaps for unrequested phases.

Parameters:
  • phases (Union[Literal['all'], int, tuple[int, ...], list[int]]) – Phase selection. Default is "all". Use one integer or a tuple of integers to restrict the plot.

  • bin_hours (int) – Width of time bins in hours. Default is 1.

  • dayphase (Literal['day', 'night', 'all']) – "day", "night", or "all". Default is "day".

  • phase_max_hours (dict[int, float] | None) – Optional phase limits in hours. Default is None.

  • spread_metric (Literal['sem', 'std']) – "sem" or "std". Default is "sem".

  • plot_style (str) – "line" or "step". Default is "line".

  • output_dir (Path | None) – Optional output folder. Default is a bin/dayphase folder below the experiment results folder.

  • plot_layout (PlotLayout | dict | None) – Optional dict or PlotLayout with title, xlabel, ylabel, xlim, ylim, xticks, yticks, legend, and figsize_cm.

  • base_font_size (float) – Base font size in points. Default is 10.0.

  • font_family (str) – Matplotlib font family. Default is "Arial".

  • figsize_cm (tuple[float, float] | None) – Optional figure size as (width_cm, height_cm).

  • day_night_indicator (tuple[str, str] | None) – Background labels, default ("awake", "sleep"). Use None to hide text labels.

Return type:

Path

Returns:

The output directory as Path.

plot_licking_counts(*, phases='all', bin_hours=1, dayphase='day', phase_max_hours=None, spread_metric='sem', plot_style='line', output_dir=None, plot_layout=None, base_font_size=10.0, font_family='Arial', figsize_cm=None, day_night_indicator=('awake', 'sleep'))[source]

Plot lick counts for selected phases.

The plotted value is the total number of licks per mouse and time bin, summarized by group. This is useful for separating learning effects from changes in drinking output, motivation, or bottle interaction. Selected phases are displayed on a compact x-axis without empty gaps.

Parameters:
  • phases (Union[Literal['all'], int, tuple[int, ...], list[int]]) – Phase selection. Default is "all". Use one integer or a tuple of integers to restrict the plot.

  • bin_hours (int) – Width of time bins in hours. Default is 1.

  • dayphase (Literal['day', 'night', 'all']) – "day", "night", or "all". Default is "day".

  • phase_max_hours (dict[int, float] | None) – Optional phase limits in hours. Default is None.

  • spread_metric (Literal['sem', 'std']) – "sem" or "std". Default is "sem".

  • plot_style (str) – "line" or "step". Default is "line".

  • output_dir (Path | None) – Optional output folder. Default is a bin/dayphase folder below the experiment results folder.

  • plot_layout (PlotLayout | dict | None) – Optional dict or PlotLayout with title, xlabel, ylabel, xlim, ylim, xticks, yticks, legend, and figsize_cm.

  • base_font_size (float) – Base font size in points. Default is 10.0.

  • font_family (str) – Matplotlib font family. Default is "Arial".

  • figsize_cm (tuple[float, float] | None) – Optional figure size as (width_cm, height_cm).

  • day_night_indicator (tuple[str, str] | None) – Background labels, default ("awake", "sleep"). Use None to hide text labels.

Return type:

Path

Returns:

The output directory as Path.

plot_bottle_preference(*, phases='all', dayphase='day', left_bottle='plain water', right_bottle='saccharin', calc='left_bottle', bin_h=24, phase_max_hours=None, consumption_col='LickNumber', left_sides=(1, 3, 5, 7), right_sides=(2, 4, 6, 8), spread_metric='sem', plot_style='line', x_unit='hours', indicate_dots=False, calc_stats=False, output_dir=None, plot_layout=None, base_font_size=10.0, font_family='Arial', figsize_cm=None, day_night_indicator=None)[source]

Plot left/right bottle consumption or relative bottle preference.

Bottle use is computed from nose-poke side events. The "all" mode plots summed consumption from both side classes. Other raw modes plot summed consumption for one side class. Relative modes compute left / (left + right) or right / (left + right) per mouse and bin, then plot group mean preference in percent. Binned x positions are centered in their bins.

Parameters:
  • phases (Union[Literal['all'], int, tuple[int, ...], list[int]]) – Phase selection. Default is "all".

  • dayphase (Literal['day', 'night', 'all']) – "day", "night", or "all". Default is "day" and is recommended for preference analyses when inactive periods contain sparse visits.

  • left_bottle (str) – Label for left-side bottle positions. Default is "plain water".

  • right_bottle (str) – Label for right-side bottle positions. Default is "saccharin".

  • calc (str) – Calculation mode. Default is "left_bottle". Accepted values are "all", "left_bottle", "right_bottle", "left_bottle/right_bottle", and "right_bottle/left_bottle".

  • bin_h (int | float) – Bin width in hours. Default is 24. Use 1 for hourly, 24 for daily, and 7 * 24 for weekly summaries.

  • phase_max_hours (dict[int, float] | None) – Optional phase limits in hours. Default is None.

  • consumption_col (str) – Nose-poke column to sum. Default is "LickNumber".

  • left_sides (tuple[int, ...] | list[int]) – Side numbers treated as left bottle positions. Default is (1, 3, 5, 7).

  • right_sides (tuple[int, ...] | list[int]) – Side numbers treated as right bottle positions. Default is (2, 4, 6, 8).

  • spread_metric (Literal['sem', 'std']) – "sem" or "std". Default is "sem".

  • plot_style (str) – "line" or "step". Default is "line".

  • x_unit (Literal['hours', 'days', 'weeks']) – X-axis unit. Default is "hours". Accepted values are "hours", "days", and "weeks".

  • indicate_dots (bool) – If True, draws a point at each binned mean. Default is False. Useful for daily or weekly bins.

  • calc_stats (bool) – If True, computes bin-wise group tests on mouse-level values and annotates significant bins in the plot. Two groups are compared by Welch’s t-test for normal data and Mann-Whitney U otherwise. More than two groups are tested by one-way ANOVA for normal data and Kruskal-Wallis otherwise. Default is False.

  • output_dir (Path | None) – Optional output folder. Default is a bin/dayphase folder below the experiment results folder.

  • plot_layout (PlotLayout | dict | None) – Optional dict or PlotLayout with title, xlabel, ylabel, xlim, ylim, xticks, yticks, legend, and figsize_cm.

  • base_font_size (float) – Base font size in points. Default is 10.0.

  • font_family (str) – Matplotlib font family. Default is "Arial".

  • figsize_cm (tuple[float, float] | None) – Optional figure size as (width_cm, height_cm).

  • day_night_indicator (tuple[str, str] | None) – Optional background labels for awake and sleep periods. Default is None. Use e.g. ("aw", "sl") to draw the same day/night indicator used by the activity plots.

Return type:

Path

Returns:

The output directory as Path.

plot_bottle_preference_day(*, experiment_day, phases='all', dayphase='day', left_bottle='plain water', right_bottle='saccharin', calc='right_bottle/left_bottle', phase_max_hours=None, consumption_col='LickNumber', left_sides=(1, 3, 5, 7), right_sides=(2, 4, 6, 8), calc_stats=True, output_dir=None, plot_layout=None, show_N=True, xtick_rotation=25.0, base_font_size=10.0, font_family='Arial', figsize_cm=None)[source]

Plot bottle consumption or preference for one experimental day.

This endpoint uses the same calc modes as plot_bottle_preference(), but collapses one selected experimental day into one mouse-level value and renders a group violin plot. It is useful for explicit endpoint comparisons such as saccharin preference or total liquid uptake on the last protocol day.

Parameters:
  • experiment_day (int) – Zero-based experimental day to summarize, e.g. 10 for Day 10.

  • phases (Union[Literal['all'], int, tuple[int, ...], list[int]]) – Phase selection. Default is "all".

  • dayphase (Literal['day', 'night', 'all']) – "day", "night", or "all". Default is "day".

  • left_bottle (str) – Label for left-side bottle positions. Default is "plain water".

  • right_bottle (str) – Label for right-side bottle positions. Default is "saccharin".

  • calc (str) – Calculation mode. Default is "right_bottle/left_bottle". Accepted values are "all", "left_bottle", "right_bottle", "left_bottle/right_bottle", and "right_bottle/left_bottle".

  • phase_max_hours (dict[int, float] | None) – Optional phase limits in hours. Default is None.

  • consumption_col (str) – Nose-poke column to sum. Default is "LickNumber".

  • left_sides (tuple[int, ...] | list[int]) – Side numbers treated as left bottle positions. Default is (1, 3, 5, 7).

  • right_sides (tuple[int, ...] | list[int]) – Side numbers treated as right bottle positions. Default is (2, 4, 6, 8).

  • calc_stats (bool) – Whether to compute and annotate a group test. Default is True.

  • output_dir (Path | None) – Optional output folder. Default is results/bottle_preference_summary.

  • plot_layout (PlotLayout | dict | None) – Optional dict or PlotLayout with title, ylabel, ylim, yticks, and figsize_cm.

  • show_N (bool) – Whether group labels include sample size. Default is True.

  • xtick_rotation (float) – Rotation angle for group labels. Default is 25.0.

  • base_font_size (float) – Base font size in points. Default is 10.0.

  • font_family (str) – Matplotlib font family. Default is "Arial".

  • figsize_cm (tuple[float, float] | None) – Optional figure size as (width_cm, height_cm).

  • day_night_indicator – Labels for the active/inactive background shading. Default is ("awake", "sleep"). Use e.g. ("aw", "sl") for compact labels or None to hide labels while keeping the sleep shading.

Return type:

Path

Returns:

The output directory as Path.

plot_plr_learning_rate(*, phase_number, metric='rewarded_correct_corner_visit', bin_hours=1, dayphase='day', phase_max_hours=None, spread_metric='sem', plot_style='line', output_dir=None, plot_layout=None, base_font_size=10.0, font_family='Arial', figsize_cm=None)[source]

Plot one PLR success-rate metric for one selected phase.

For each mouse and bin, the rate is success_visits / all_visits. The plotted group trace is the mean rate in percent with SEM or SD shading. Use this for the main time-resolved place-learning or reversal-learning readout.

Parameters:
  • phase_number (int) – Phase number to analyze, for example 3 for PL or 4 for PR in the synthetic example. Required.

  • metric (str) – Success definition. Default is "rewarded_correct_corner_visit". Accepted values are "correct_corner_visit", "correct_np_visit", and "rewarded_correct_corner_visit".

  • bin_hours (int) – Bin width in hours. Default is 1.

  • dayphase (Literal['day', 'night', 'all']) – "day", "night", or "all". Default is "day".

  • phase_max_hours (dict[int, float] | None) – Optional phase limits in hours. Default is None.

  • spread_metric (Literal['sem', 'std']) – "sem" or "std". Default is "sem".

  • plot_style (str) – "line" or "step". Default is "line".

  • output_dir (Path | None) – Optional output folder. Default is a bin/dayphase folder below the experiment results folder.

  • plot_layout (PlotLayout | dict | None) – Optional dict or PlotLayout with title, xlabel, ylabel, xlim, ylim, xticks, yticks, legend, and figsize_cm. Use {"legend": False} for manuscript panels with external labels.

  • base_font_size (float) – Base font size in points. Default is 10.0.

  • font_family (str) – Matplotlib font family. Default is "Arial".

  • figsize_cm (tuple[float, float] | None) – Optional figure size as (width_cm, height_cm).

  • day_night_indicator – Labels for the active/inactive background shading. Default is ("awake", "sleep"). Use e.g. ("aw", "sl") for compact labels or None to hide labels while keeping the sleep shading.

Return type:

Path

Returns:

The output directory as Path.

plot_plr_learning_counts(*, phase_number, metric='rewarded_correct_corner_visit', bin_hours=1, dayphase='day', phase_max_hours=None, spread_metric='sem', plot_style='line', output_dir=None, plot_layout=None, base_font_size=10.0, font_family='Arial', figsize_cm=None)[source]

Plot one PLR absolute-count metric for one selected phase.

For each mouse and bin, this plots the number of successful visits rather than a denominator-normalized rate. Use count plots whenever visit activity differs between groups and rate plots might hide sparse sampling.

Parameters:
  • phase_number (int) – Phase number to analyze. Required.

  • metric (str) – Success definition. Default is "rewarded_correct_corner_visit". Accepted values are "correct_corner_visit", "correct_np_visit", and "rewarded_correct_corner_visit".

  • bin_hours (int) – Bin width in hours. Default is 1.

  • dayphase (Literal['day', 'night', 'all']) – "day", "night", or "all". Default is "day".

  • phase_max_hours (dict[int, float] | None) – Optional phase limits in hours. Default is None.

  • spread_metric (Literal['sem', 'std']) – "sem" or "std". Default is "sem".

  • plot_style (str) – "line" or "step". Default is "line".

  • output_dir (Path | None) – Optional output folder. Default is a bin/dayphase folder below the experiment results folder.

  • plot_layout (PlotLayout | dict | None) – Optional dict or PlotLayout with title, xlabel, ylabel, xlim, ylim, xticks, yticks, legend, and figsize_cm.

  • base_font_size (float) – Base font size in points. Default is 10.0.

  • font_family (str) – Matplotlib font family. Default is "Arial".

  • figsize_cm (tuple[float, float] | None) – Optional figure size as (width_cm, height_cm).

Return type:

Path

Returns:

The output directory as Path.

plot_plr_reversal_components(*, phase_number, bin_hours=1, dayphase='day', phase_max_hours=None, spread_metric='sem', plot_style='line', output_dir=None, plot_layout=None, base_font_size=10.0, font_family='Arial', figsize_cm=None, day_night_indicator=('awake', 'sleep'))[source]

Plot new, previous, and neutral corner components for reversal.

This decomposes reversal-phase corner visits into four mutually interpretable rates: new correct corner, previous correct corner, and two neutral incorrect corners. Rates are computed as component_visits / all_visits per bin and mouse, then summarized by group. It is most useful when phase-level reversal performance is low and you need to distinguish weak new learning from perseveration.

Parameters:
  • phase_number (int) – Reversal phase number. Default-free and required; use 4 for the synthetic PL/PR example.

  • bin_hours (int) – Bin width in hours. Default is 1.

  • dayphase (Literal['day', 'night', 'all']) – "day", "night", or "all". Default is "day".

  • phase_max_hours (dict[int, float] | None) – Optional phase limits in hours. Default is None.

  • spread_metric (Literal['sem', 'std']) – "sem" or "std". Default is "sem".

  • plot_style (str) – "line" or "step". Default is "line".

  • output_dir (Path | None) – Optional output folder. Default is a bin/dayphase folder below the experiment results folder.

  • plot_layout (PlotLayout | dict | None) – Optional dict or PlotLayout with title, xlabel, ylabel, xlim, ylim, xticks, yticks, legend, and figsize_cm.

  • base_font_size (float) – Base font size in points. Default is 10.0.

  • font_family (str) – Matplotlib font family. Default is "Arial".

  • figsize_cm (tuple[float, float] | None) – Optional figure size as (width_cm, height_cm).

  • day_night_indicator (tuple[str, str] | None) – Labels for the active/inactive background shading. Default is ("awake", "sleep"). Use e.g. ("aw", "sl") for compact labels or None to hide labels while keeping the sleep shading.

Return type:

Path

Returns:

The output directory as Path.

plot_phase_activity_summary(*, dayphase='day', summary_metric='mean', phase_max_hours=None, output_dir=None, plot_layout=None, show_N=True, xtick_rotation=45.0, median_line_width=1.2, median_marker_size=4.0, base_font_size=10.0, font_family='Arial', figsize_cm=None)[source]

Plot phase-wise activity summary boxplots.

The method summarizes visit activity per mouse and phase as either the mean or median number of visits per hour. The mean is usually more informative for sparse IntelliCage data because median hourly bins can be zero even when mice are active in bursts.

Parameters:
  • dayphase (Literal['day', 'night', 'all']) – "day", "night", or "all". Default is "day".

  • summary_metric (Literal['mean', 'median']) – "mean" or "median" visits per hour. Default is "mean".

  • phase_max_hours (dict[int, float] | None) – Optional phase limits in hours. Default is None.

  • output_dir (Path | None) – Optional output folder. Default is results/visit_activity_summary.

  • plot_layout (PlotLayout | dict | None) – Optional dict or PlotLayout. Supported keys are title, ylabel, ylim, yticks, legend, figsize_cm, plus show_N and xtick_rotation in extra or directly in the dictionary.

  • show_N (bool) – Whether group x tick labels include sample size. Default is True.

  • xtick_rotation (float) – Rotation angle for group labels. Default is 45.0.

  • median_line_width (float) – Width of the line connecting phase medians or means within each group. Default is 1.2.

  • median_marker_size (float) – Marker size for the connected phase summary points. Default is 4.0.

  • base_font_size (float) – Base font size in points. Default is 10.0.

  • font_family (str) – Matplotlib font family. Default is "Arial".

  • figsize_cm (tuple[float, float] | None) – Optional figure size as (width_cm, height_cm).

Return type:

Path

Returns:

The output directory as Path.

plot_plr_phase_segment_rate(*, phase_number, metric='rewarded_correct_corner_visit', dayphase='day', phase_max_hours=None, spread_metric='sem', output_dir=None, plot_layout=None, base_font_size=10.0, font_family='Arial', figsize_cm=None)[source]

Plot PLR rate across awake/sleep mouse-day segments.

Each selected phase is split into alternating awake and sleep segments. For each mouse and segment, the rate is success_visits / all_visits. The figure shows group mean rate over sequential mouse-day segments, which helps reveal whether learning is concentrated in active periods or continues across the full clock day.

Parameters:
  • phase_number (int) – Phase number to analyze. Required.

  • metric (str) – Success definition. Default is "rewarded_correct_corner_visit". Accepted values are "correct_corner_visit", "correct_np_visit", and "rewarded_correct_corner_visit".

  • dayphase (Literal['day', 'night', 'all']) – "day", "night", or "all" applied before segment aggregation. Default is "day"; use "all" when you want the explicit awake/sleep segment comparison.

  • phase_max_hours (dict[int, float] | None) – Optional phase limits in hours. Default is None.

  • spread_metric (Literal['sem', 'std']) – "sem" or "std". Default is "sem".

  • output_dir (Path | None) – Optional output folder. Default is results/plr_segments.

  • plot_layout (PlotLayout | dict | None) – Optional dict or PlotLayout with title, ylabel, legend, and figsize_cm. Axis-limit keys are reserved for future support in this plot family.

  • base_font_size (float) – Base font size in points. Default is 10.0.

  • font_family (str) – Matplotlib font family. Default is "Arial".

  • figsize_cm (tuple[float, float] | None) – Optional figure size as (width_cm, height_cm).

Return type:

Path

Returns:

The output directory as Path.

plot_plr_phase_segment_error_rate(*, phase_number, metric='rewarded_correct_corner_visit', error_against='selected_success', dayphase='day', phase_max_hours=None, spread_metric='sem', output_dir=None, plot_layout=None, base_font_size=10.0, font_family='Arial', figsize_cm=None)[source]

Plot PLR error rate across awake/sleep mouse-day segments.

The error rate is the complement of the selected success definition: (all_visits - success_visits) / all_visits. By default, success_visits is determined by metric. For rewarded metrics, error_against="spatial_correct" instead defines errors as visits to non-correct corners, independent of whether reward delivery occurred.

Parameters:
  • phase_number (int) – Phase number to analyze. Required.

  • metric (str) – Success definition used to derive errors. Default is "rewarded_correct_corner_visit".

  • error_against (Literal['selected_success', 'spatial_correct']) – "selected_success" or "spatial_correct". Default is "selected_success". Use "spatial_correct" when reward delivery should not be counted as part of the error concept.

  • dayphase (Literal['day', 'night', 'all']) – "day", "night", or "all" applied before segment aggregation. Default is "day"; use "all" for the explicit awake/sleep segment comparison.

  • phase_max_hours (dict[int, float] | None) – Optional phase limits in hours. Default is None.

  • spread_metric (Literal['sem', 'std']) – "sem" or "std". Default is "sem".

  • output_dir (Path | None) – Optional output folder. Default is results/plr_segments.

  • plot_layout (PlotLayout | dict | None) – Optional dict or PlotLayout with title, ylabel, legend, legend_loc, legend_font_size, and figsize_cm.

  • base_font_size (float) – Base font size in points. Default is 10.0.

  • font_family (str) – Matplotlib font family. Default is "Arial".

  • figsize_cm (tuple[float, float] | None) – Optional figure size as (width_cm, height_cm).

Return type:

Path

Returns:

The output directory as Path.

plot_plr_awake_day_rate(*, phase_number, metric='rewarded_correct_corner_visit', phase_day=(1, 2, 3), dayphase='day', phase_max_hours=None, exclude_outliers=True, output_dir=None, plot_layout=None, base_font_size=10.0, font_family='Arial', figsize_cm=None)[source]

Plot mouse-level PLR rates per phase day and dayphase.

For each mouse and selected phase day, the endpoint is success_visits / all_visits during the selected dayphase. The method writes mouse-level tables, omnibus/pairwise statistics, and one violin plot per requested phase day.

Parameters:
  • phase_number (int) – Phase number to analyze. Required.

  • metric (str) – Success definition. Default is "rewarded_correct_corner_visit".

  • phase_day (int | tuple[int, ...]) – Phase day or days to plot. Default is (1, 2, 3). Use an integer for one day or a tuple for several days.

  • dayphase (Literal['day', 'night', 'all']) – "day", "night", or "all". Default is "day". "day" analyzes the awake segment, "night" analyzes the sleep segment, and "all" combines both into a full phase-day rate.

  • phase_max_hours (dict[int, float] | None) – Optional phase limits in hours. Default is None.

  • exclude_outliers (bool) – Whether IQR-flagged outliers are excluded from statistics and hidden from violin bodies. Default is True.

  • output_dir (Path | None) – Optional output folder. Default is results/plr_endpoints.

  • plot_layout (PlotLayout | dict | None) – Optional dict or PlotLayout. Supported keys are title, ylabel, ylim, and figsize_cm.

  • base_font_size (float) – Base font size in points. Default is 10.0.

  • font_family (str) – Matplotlib font family. Default is "Arial".

  • figsize_cm (tuple[float, float] | None) – Optional figure size as (width_cm, height_cm).

Return type:

Path

Returns:

The output directory as Path.

plot_plr_awake_day_error_rate(*, phase_number, metric='rewarded_correct_corner_visit', error_against='selected_success', phase_day=(1, 2, 3), dayphase='day', phase_max_hours=None, exclude_outliers=True, output_dir=None, plot_layout=None, base_font_size=10.0, font_family='Arial', figsize_cm=None)[source]

Plot mouse-level PLR error rates per phase day and dayphase.

The endpoint is (all_visits - success_visits) / all_visits for each mouse and selected phase day. success_visits is usually the success column selected by metric. For rewarded metrics, error_against="spatial_correct" switches the complement to correct_corner_visit and therefore asks whether mice chose a wrong corner, independent of reward delivery.

Parameters:
  • phase_number (int) – Phase number to analyze. Required.

  • metric (str) – Success definition used to derive errors. Default is "rewarded_correct_corner_visit".

  • error_against (Literal['selected_success', 'spatial_correct']) – "selected_success" or "spatial_correct". Default is "selected_success".

  • phase_day (int | tuple[int, ...]) – Phase day or days to plot. Default is (1, 2, 3).

  • dayphase (Literal['day', 'night', 'all']) – "day", "night", or "all". Default is "day".

  • phase_max_hours (dict[int, float] | None) – Optional phase limits in hours. Default is None.

  • exclude_outliers (bool) – Whether IQR-flagged outliers are excluded from statistics and hidden from violin bodies. Default is True.

  • output_dir (Path | None) – Optional output folder. Default is results/plr_endpoints.

  • plot_layout (PlotLayout | dict | None) – Optional dict or PlotLayout with title, ylabel, ylim, legend, legend_loc, legend_font_size, and figsize_cm.

  • base_font_size (float) – Base font size in points. Default is 10.0.

  • font_family (str) – Matplotlib font family. Default is "Arial".

  • figsize_cm (tuple[float, float] | None) – Optional figure size as (width_cm, height_cm).

Return type:

Path

Returns:

The output directory as Path.

plot_plr_experience_learning_curve(*, phase_number, metric='rewarded_correct_corner_visit', dayphase='day', phase_max_hours=None, spread_metric='sem', exclude_outliers=True, output_dir=None, plot_layout=None, base_font_size=10.0, font_family='Arial', figsize_cm=None)[source]

Plot experience-normalized PLR learning curves.

Instead of clock-time bins, this method bins each mouse by visit number and computes success_visits / visits within sliding visit windows. It is useful when groups differ in gross activity and you want to ask how performance changes as a function of accumulated experience.

Parameters:
  • phase_number (int) – Phase number to analyze. Required.

  • metric (str) – Success definition. Default is "rewarded_correct_corner_visit".

  • dayphase (Literal['day', 'night', 'all']) – "day", "night", or "all". Default is "day".

  • phase_max_hours (dict[int, float] | None) – Optional phase limits in hours. Default is None.

  • spread_metric (Literal['sem', 'std']) – "sem" or "std". Default is "sem".

  • exclude_outliers (bool) – Reserved for API symmetry with onset plots. Default is True.

  • output_dir (Path | None) – Optional output folder. Default is results/plr_experience.

  • plot_layout (PlotLayout | dict | None) – Optional dict or PlotLayout with title, xlabel, ylabel, xlim, ylim, xticks, yticks, legend, and figsize_cm.

  • base_font_size (float) – Base font size in points. Default is 10.0.

  • font_family (str) – Matplotlib font family. Default is "Arial".

  • figsize_cm (tuple[float, float] | None) – Optional figure size as (width_cm, height_cm).

Return type:

Path

Returns:

The output directory as Path.

plot_plr_experience_learning_onset(*, phase_number, metric='rewarded_correct_corner_visit', dayphase='day', phase_max_hours=None, exclude_outliers=True, output_dir=None, plot_layout=None, show_N=True, base_font_size=10.0, font_family='Arial', figsize_cm=None)[source]

Plot experience-normalized PLR learning-onset distributions.

Learning onset is the first visit-window position at which a mouse reaches the internal success criterion for the selected metric. The result is a mouse-level onset value in visit number, plotted as group violins with optional outlier handling and pairwise statistics.

Parameters:
  • phase_number (int) – Phase number to analyze. Required.

  • metric (str) – Success definition. Default is "rewarded_correct_corner_visit".

  • dayphase (Literal['day', 'night', 'all']) – "day", "night", or "all". Default is "day".

  • phase_max_hours (dict[int, float] | None) – Optional phase limits in hours. Default is None.

  • exclude_outliers (bool) – Whether IQR-flagged outliers are excluded from statistics and hidden from violin bodies. Default is True.

  • output_dir (Path | None) – Optional output folder. Default is results/plr_experience.

  • plot_layout (PlotLayout | dict | None) – Optional dict or PlotLayout. Supported keys are title, ylabel, ylim, figsize_cm, and show_N via extra or directly in the dictionary.

  • show_N (bool) – Whether group x tick labels include sample size. Default is True.

  • base_font_size (float) – Base font size in points. Default is 10.0.

  • font_family (str) – Matplotlib font family. Default is "Arial".

  • figsize_cm (tuple[float, float] | None) – Optional figure size as (width_cm, height_cm).

Return type:

Path

Returns:

The output directory as Path.

plot_plr_threshold_onset(*, phase_number, metric='rewarded_correct_corner_visit', threshold_pct=70.0, bin_hours=1, dayphase='day', phase_max_hours=None, exclude_outliers=True, output_dir=None, plot_layout=None, base_font_size=10.0, font_family='Arial', figsize_cm=None)[source]

Plot first threshold-crossing time for a binned PLR rate.

For each mouse, the selected success rate is binned in clock time. The onset value is the first bin start at which the rate reaches or exceeds threshold_pct. This is useful for comparing learning speed rather than final performance.

Parameters:
  • phase_number (int) – Phase number to analyze. Required.

  • metric (str) – Success definition. Default is "rewarded_correct_corner_visit".

  • threshold_pct (float) – Threshold in percent. Default is 70.0. Use lower values such as 50 for permissive responder screens and higher values such as 80 for robust learning.

  • bin_hours (int) – Bin width in hours. Default is 1.

  • dayphase (Literal['day', 'night', 'all']) – "day", "night", or "all". Default is "day".

  • phase_max_hours (dict[int, float] | None) – Optional phase limits in hours. Default is None.

  • exclude_outliers (bool) – Whether IQR-flagged outliers are excluded from statistics and hidden from violin bodies. Default is True.

  • output_dir (Path | None) – Optional output folder. Default is results/plr_thresholds.

  • plot_layout (PlotLayout | dict | None) – Optional dict or PlotLayout. Supported keys are title, ylabel, ylim, and figsize_cm.

  • base_font_size (float) – Base font size in points. Default is 10.0.

  • font_family (str) – Matplotlib font family. Default is "Arial".

  • figsize_cm (tuple[float, float] | None) – Optional figure size as (width_cm, height_cm).

Return type:

Path

Returns:

The output directory as Path.

plot_plr_derived_ratio(*, phase_number, numerator_col='rewarded_correct_corner_visit', denominator_col='correct_np_visit', metric_name='completion_efficiency', title='completion efficiency', ylabel='Rewarded correct / correct NP [%]', phase_day=(1, 2, 3), dayphase='day', phase_max_hours=None, pseudocount=0.0, value_scale=100.0, format_as_percent=True, reference_line=None, exclude_outliers=True, output_dir=None, plot_layout=None, base_font_size=10.0, font_family='Arial', figsize_cm=None)[source]

Plot a phase/day-wise derived ratio endpoint.

The endpoint is computed per mouse as numerator / denominator * value_scale within each selected phase day. It supports custom ratios such as completion efficiency (rewarded correct visits divided by correct nose-poke visits) or reversal preference (new correct visits divided by new plus previous correct visits).

Parameters:
  • phase_number (int) – Phase number to analyze. Required.

  • numerator_col (str) – Visit-level numerator column. Default is "rewarded_correct_corner_visit".

  • denominator_col (str) – Visit-level denominator column. Default is "correct_np_visit". The special value "new_or_previous_correct_corner_visit" is built internally for reversal preference.

  • metric_name (str) – Filename-safe metric name. Default is "completion_efficiency".

  • title (str) – Figure title stem. Default is "completion efficiency".

  • ylabel (str) – Y-axis label. Default is "Rewarded correct / correct NP [%]".

  • phase_day (int | tuple[int, ...]) – Phase day or days to plot. Default is (1, 2, 3).

  • dayphase (Literal['day', 'night', 'all']) – "day", "night", or "all". Default is "day".

  • phase_max_hours (dict[int, float] | None) – Optional phase limits in hours. Default is None.

  • pseudocount (float) – Value added to numerator and denominator before division. Default is 0.0. Use only when zero-denominator mice should remain in exploratory plots.

  • value_scale (float) – Multiplicative scale. Default is 100.0 for percent-like outputs; use 1.0 for bounded ratios.

  • format_as_percent (bool) – Whether to format the y-axis as percent. Default is True.

  • reference_line (float | None) – Optional horizontal reference line. Default is None. Use 0.5 for reversal preference when value_scale=1.0.

  • exclude_outliers (bool) – Whether IQR-flagged outliers are excluded from statistics. Default is True.

  • output_dir (Path | None) – Optional output folder. Default is results/plr_derived.

  • plot_layout (PlotLayout | dict | None) – Optional dict or PlotLayout. Supported keys are title, ylabel, ylim, legend, legend_loc, legend_font_size, figsize_cm, and the plot-specific stats_bracket_drop for manually adjusting the vertical length of significance brackets.

  • base_font_size (float) – Base font size in points. Default is 10.0.

  • font_family (str) – Matplotlib font family. Default is "Arial".

  • figsize_cm (tuple[float, float] | None) – Optional figure size as (width_cm, height_cm).

Return type:

Path

Returns:

The output directory as Path.

plot_plr_cumulative_preferences(*, phases=(2, 3, 4), dayphase='day', phase_max_hours=None, spread_metric='sem', plot_style='line', day_night_indicator=('awake', 'sleep'), output_dir=None, plot_layout=None, base_font_size=10.0, font_family='Arial', figsize_cm=None)[source]

Plot cumulative corner-role preference trajectories.

The method tracks cumulative visits to role-defined corners across the selected phases and plots relative preference trajectories by group. Roles include current correct, previous correct, and neutral incorrect corners where those roles are defined. This is useful for visualizing how place-learning and reversal histories unfold across phases.

Parameters:
  • phases (Union[Literal['all'], int, tuple[int, ...], list[int]]) – Phase selection. Default is (2, 3, 4) for NPA, PL, and PR in the synthetic example. Use "all", one integer, or a tuple of integers.

  • dayphase (Literal['day', 'night', 'all']) – "day", "night", or "all". Default is "day".

  • phase_max_hours (dict[int, float] | None) – Optional phase limits in hours. Default is None.

  • spread_metric (Literal['sem', 'std']) – "sem" or "std". Default is "sem".

  • plot_style (str) – "line" or "step". Default is "line".

  • day_night_indicator (tuple[str, str] | None) – Labels for the active/inactive background bands. Default is ("awake", "sleep"). Use shorter labels such as ("aw", "sl") for compact figures, or None to hide these labels while keeping the shaded bands.

  • output_dir (Path | None) – Optional output folder. Default is results/plr_cumulative.

  • plot_layout (PlotLayout | dict | None) – Optional dict or PlotLayout with legend, legend_loc, legend_font_size, and figsize_cm.

  • base_font_size (float) – Base font size in points. Default is 10.0.

  • font_family (str) – Matplotlib font family. Default is "Arial".

  • figsize_cm (tuple[float, float] | None) – Optional figure size as (width_cm, height_cm).

Return type:

Path

Returns:

The output directory as Path.

Analysis and plotting functions

configure_plot_style(*, font_size=10.0, font_family='Arial')[source]

Apply global matplotlib defaults for IntelliCage publication figures.

Return type:

None

Parameters:
  • font_size (float)

  • font_family (str)

set_group_colors(color_mapping)[source]

Update the global experimental-group color mapping used across all plots.

Return type:

None

Parameters:

color_mapping (dict[str, str] | None)

sanitize_filename_part(value)[source]

Convert a label into a filesystem-friendly filename part.

Return type:

str

Parameters:

value (str)

plot_experiment_overview(mouse_bins, summary_bins, *, group_name, bin_hours, output_path, phase_window_table, phase_display_names, spread_metric, legend_spread_label=True, x_end_hours=None, plot_style='step', show_individual_labels=True, title_label='visits across all phases', ylabel='Visits per mouse and bin', origin_clock_hour=6.0, awake_start_clock_hour=6.0, awake_end_clock_hour=18.0, show_legend=True, legend_inside=False, legend_loc=None, legend_font_size=None, xlim=None, ylim=None, xticks=None, yticks=None, xlabel=None, day_night_indicator=('awake', 'sleep'))[source]

Plot full-experiment visit activity for one experimental group.

Return type:

None

Parameters:
  • mouse_bins (DataFrame)

  • summary_bins (DataFrame)

  • group_name (str)

  • bin_hours (int)

  • output_path (Path)

  • phase_window_table (DataFrame)

  • phase_display_names (dict[int, str])

  • spread_metric (str)

  • legend_spread_label (bool)

  • x_end_hours (float | None)

  • plot_style (str)

  • show_individual_labels (bool)

  • title_label (str)

  • ylabel (str)

  • origin_clock_hour (float)

  • awake_start_clock_hour (float)

  • awake_end_clock_hour (float)

  • show_legend (bool)

  • legend_inside (bool)

  • legend_loc (str | int | None)

  • legend_font_size (float | None)

  • xlim (tuple[float, float] | None)

  • ylim (tuple[float, float] | None)

  • xticks (list[float] | tuple[float, ...] | ndarray | None)

  • yticks (list[float] | tuple[float, ...] | ndarray | None)

  • xlabel (str | None)

  • day_night_indicator (tuple[str, str] | None)

plot_experiment_overview_groups(summary_bins, *, output_path, phase_window_table, phase_display_names, spread_metric, legend_spread_label=True, x_end_hours=None, plot_style='step', title_label='Visits across all phases by group', ylabel='Visits per mouse and bin', origin_clock_hour=6.0, awake_start_clock_hour=6.0, awake_end_clock_hour=18.0, show_legend=True, legend_inside=False, legend_loc=None, legend_font_size=None, xlim=None, ylim=None, xticks=None, yticks=None, xlabel=None, day_night_indicator=('awake', 'sleep'))[source]

Plot all experimental-group visit means across the full experiment.

Return type:

None

Parameters:
  • summary_bins (DataFrame)

  • output_path (Path)

  • phase_window_table (DataFrame)

  • phase_display_names (dict[int, str])

  • spread_metric (str)

  • legend_spread_label (bool)

  • x_end_hours (float | None)

  • plot_style (str)

  • title_label (str)

  • ylabel (str)

  • origin_clock_hour (float)

  • awake_start_clock_hour (float)

  • awake_end_clock_hour (float)

  • show_legend (bool)

  • legend_inside (bool)

  • legend_loc (str | int | None)

  • legend_font_size (float | None)

  • xlim (tuple[float, float] | None)

  • ylim (tuple[float, float] | None)

  • xticks (list[float] | tuple[float, ...] | ndarray | None)

  • yticks (list[float] | tuple[float, ...] | ndarray | None)

  • xlabel (str | None)

  • day_night_indicator (tuple[str, str] | None)

plot_bottle_preference_groups(summary_bins, *, output_path, left_bottle, right_bottle, calc, bin_h, spread_metric='sem', plot_style='line', x_unit='hours', indicate_dots=False, stats_table=None, figsize_cm=None, show_legend=True, legend_loc=None, legend_font_size=None, xlim=None, ylim=None, xticks=None, yticks=None, xlabel=None, phase_window_table=None, phase_display_names=None, title_label=None, ylabel=None, origin_clock_hour=6.0, awake_start_clock_hour=6.0, awake_end_clock_hour=18.0, day_night_indicator=None)[source]

Plot binned bottle consumption or preference across groups.

Return type:

None

Parameters:
  • summary_bins (DataFrame)

  • output_path (Path)

  • left_bottle (str)

  • right_bottle (str)

  • calc (str)

  • bin_h (int | float)

  • spread_metric (str)

  • plot_style (str)

  • x_unit (Literal['hours', 'days', 'weeks'])

  • indicate_dots (bool)

  • stats_table (DataFrame | None)

  • figsize_cm (tuple[float, float] | None)

  • show_legend (bool)

  • legend_loc (str | int | None)

  • legend_font_size (float | None)

  • xlim (tuple[float, float] | None)

  • ylim (tuple[float, float] | None)

  • xticks (list[float] | tuple[float, ...] | ndarray | None)

  • yticks (list[float] | tuple[float, ...] | ndarray | None)

  • xlabel (str | None)

  • phase_window_table (DataFrame | None)

  • phase_display_names (dict[int, str] | None)

  • title_label (str | None)

  • ylabel (str | None)

  • origin_clock_hour (float)

  • awake_start_clock_hour (float)

  • awake_end_clock_hour (float)

  • day_night_indicator (tuple[str, str] | None)

plot_bottle_preference_day_violin(mouse_day_values, *, output_path, experiment_day, left_bottle, right_bottle, calc, stats_table=None, dayphase_label='day', figsize_cm=None, show_n=True, xtick_rotation=25.0, ylim=None, yticks=None, title=None, ylabel=None, reference_line=None)[source]

Plot a group violin for one bottle-consumption or preference day.

Return type:

None

Parameters:
  • mouse_day_values (DataFrame)

  • output_path (Path)

  • experiment_day (int)

  • left_bottle (str)

  • right_bottle (str)

  • calc (str)

  • stats_table (DataFrame | None)

  • dayphase_label (str)

  • figsize_cm (tuple[float, float] | None)

  • show_n (bool)

  • xtick_rotation (float)

  • ylim (tuple[float | None, float | None] | None)

  • yticks (list[float] | tuple[float, ...] | ndarray | None)

  • title (str | None)

  • ylabel (str | None)

  • reference_line (float | None)

plot_phase2_adaptation(primary_summary, secondary_summary, *, group_name, bin_hours, output_path, secondary_label, phase_display_name, plot_style='bar', spread_metric='sem', x_end_hours=None, origin_clock_hour=8.0, awake_start_clock_hour=6.0, awake_end_clock_hour=18.0, starting_day=1, show_legend=True, legend_loc=None, legend_font_size=None, xlim=None, ylim=None, xticks=None, yticks=None, xlabel=None, day_night_indicator=('awake', 'sleep'))[source]

Plot the phase-2 adaptation metric as bars or mean traces with spread.

Return type:

None

Parameters:
  • primary_summary (DataFrame)

  • secondary_summary (DataFrame)

  • group_name (str)

  • bin_hours (int)

  • output_path (Path)

  • secondary_label (str)

  • phase_display_name (str)

  • plot_style (str)

  • spread_metric (str)

  • x_end_hours (float | None)

  • origin_clock_hour (float)

  • awake_start_clock_hour (float)

  • awake_end_clock_hour (float)

  • starting_day (int)

  • show_legend (bool)

  • legend_loc (str | int | None)

  • legend_font_size (float | None)

  • xlim (tuple[float, float] | None)

  • ylim (tuple[float, float] | None)

  • xticks (list[float] | tuple[float, ...] | ndarray | None)

  • yticks (list[float] | tuple[float, ...] | ndarray | None)

  • xlabel (str | None)

  • day_night_indicator (tuple[str, str] | None)

plot_phase2_adaptation_groups(primary_summary, secondary_summary, *, group_names, bin_hours, output_path, secondary_label, phase_display_name, x_end_hours=None, origin_clock_hour=8.0, awake_start_clock_hour=6.0, awake_end_clock_hour=18.0, starting_day=1, show_legend=True, legend_loc=None, legend_font_size=None, xlim=None, ylim=None, xticks=None, yticks=None, xlabel=None, ylabel=None, title_label=None, day_night_indicator=('awake', 'sleep'))[source]

Plot the phase-2 adaptation metric for all groups in one combined panel.

Return type:

None

Parameters:
  • primary_summary (DataFrame)

  • secondary_summary (DataFrame)

  • group_names (list[str])

  • bin_hours (int)

  • output_path (Path)

  • secondary_label (str)

  • phase_display_name (str)

  • x_end_hours (float | None)

  • origin_clock_hour (float)

  • awake_start_clock_hour (float)

  • awake_end_clock_hour (float)

  • starting_day (int)

  • show_legend (bool)

  • legend_loc (str | int | None)

  • legend_font_size (float | None)

  • xlim (tuple[float, float] | None)

  • ylim (tuple[float, float] | None)

  • xticks (list[float] | tuple[float, ...] | ndarray | None)

  • yticks (list[float] | tuple[float, ...] | ndarray | None)

  • xlabel (str | None)

  • ylabel (str | None)

  • title_label (str | None)

  • day_night_indicator (tuple[str, str] | None)

plot_phase_learning_counts(mouse_bins, summary_bins, *, group_name, phase_number, phase_display_name, bin_hours, output_path, spread_metric, title_label, ylabel, x_end_hours=None, plot_style='step', origin_clock_hour=8.0, awake_start_clock_hour=6.0, awake_end_clock_hour=18.0, starting_day=1, show_legend=True, legend_loc=None, legend_font_size=None, xlim=None, ylim=None, xticks=None, yticks=None, xlabel=None, day_night_indicator=('awake', 'sleep'))[source]

Plot one selected place-learning count metric for phase 3 or phase 4.

Return type:

None

Parameters:
  • mouse_bins (DataFrame)

  • summary_bins (DataFrame)

  • group_name (str)

  • phase_number (int)

  • phase_display_name (str)

  • bin_hours (int)

  • output_path (Path)

  • spread_metric (str)

  • title_label (str)

  • ylabel (str)

  • x_end_hours (float | None)

  • plot_style (str)

  • origin_clock_hour (float)

  • awake_start_clock_hour (float)

  • awake_end_clock_hour (float)

  • starting_day (int)

  • show_legend (bool)

  • legend_loc (str | int | None)

  • legend_font_size (float | None)

  • xlim (tuple[float, float] | None)

  • ylim (tuple[float, float] | None)

  • xticks (list[float] | tuple[float, ...] | ndarray | None)

  • yticks (list[float] | tuple[float, ...] | ndarray | None)

  • xlabel (str | None)

  • day_night_indicator (tuple[str, str] | None)

plot_phase_learning_rate(mouse_bins, summary_bins, *, group_name, phase_number, phase_display_name, bin_hours, output_path, spread_metric, title_label, ylabel, chance_level=None, x_end_hours=None, plot_style='step', origin_clock_hour=8.0, awake_start_clock_hour=6.0, awake_end_clock_hour=18.0, starting_day=1, show_legend=True, legend_loc=None, legend_font_size=None, xlim=None, ylim=None, xticks=None, yticks=None, xlabel=None, day_night_indicator=('awake', 'sleep'))[source]

Plot one selected place-learning rate metric for phase 3 or phase 4.

Return type:

None

Parameters:
  • mouse_bins (DataFrame)

  • summary_bins (DataFrame)

  • group_name (str)

  • phase_number (int)

  • phase_display_name (str)

  • bin_hours (int)

  • output_path (Path)

  • spread_metric (str)

  • title_label (str)

  • ylabel (str)

  • chance_level (float | None)

  • x_end_hours (float | None)

  • plot_style (str)

  • origin_clock_hour (float)

  • awake_start_clock_hour (float)

  • awake_end_clock_hour (float)

  • starting_day (int)

  • show_legend (bool)

  • legend_loc (str | int | None)

  • legend_font_size (float | None)

  • xlim (tuple[float, float] | None)

  • ylim (tuple[float, float] | None)

  • xticks (list[float] | tuple[float, ...] | ndarray | None)

  • yticks (list[float] | tuple[float, ...] | ndarray | None)

  • xlabel (str | None)

  • day_night_indicator (tuple[str, str] | None)

plot_phase_learning_rate_groups(summary_bins, *, phase_number, phase_display_name, bin_hours, output_path, spread_metric, title_label, ylabel, chance_level=None, x_end_hours=None, plot_style='step', origin_clock_hour=8.0, awake_start_clock_hour=6.0, awake_end_clock_hour=18.0, starting_day=1, show_legend=True, legend_loc=None, legend_font_size=None, xlim=None, ylim=None, xticks=None, yticks=None, xlabel=None, day_night_indicator=('awake', 'sleep'))[source]

Plot one selected place-learning rate metric across all experimental groups.

Return type:

None

Parameters:
  • summary_bins (DataFrame)

  • phase_number (int)

  • phase_display_name (str)

  • bin_hours (int)

  • output_path (Path)

  • spread_metric (str)

  • title_label (str)

  • ylabel (str)

  • chance_level (float | None)

  • x_end_hours (float | None)

  • plot_style (str)

  • origin_clock_hour (float)

  • awake_start_clock_hour (float)

  • awake_end_clock_hour (float)

  • starting_day (int)

  • show_legend (bool)

  • legend_loc (str | int | None)

  • legend_font_size (float | None)

  • xlim (tuple[float, float] | None)

  • ylim (tuple[float, float] | None)

  • xticks (list[float] | tuple[float, ...] | ndarray | None)

  • yticks (list[float] | tuple[float, ...] | ndarray | None)

  • xlabel (str | None)

  • day_night_indicator (tuple[str, str] | None)

plot_phase_learning_counts_groups(summary_bins, *, phase_display_name, bin_hours, output_path, spread_metric, x_end_hours=None, plot_style='step', title_prefix='Rewarded correct visit counts across groups', ylabel='Rewarded correct visits per mouse and bin', origin_clock_hour=8.0, awake_start_clock_hour=6.0, awake_end_clock_hour=18.0, starting_day=1, phase_number=None, show_legend=True, legend_loc=None, legend_font_size=None, xlim=None, ylim=None, xticks=None, yticks=None, xlabel=None, day_night_indicator=('awake', 'sleep'))[source]

Plot all experimental-group correct-visit counts in one figure.

Return type:

None

Parameters:
  • summary_bins (DataFrame)

  • phase_display_name (str)

  • bin_hours (int)

  • output_path (Path)

  • spread_metric (str)

  • x_end_hours (float | None)

  • plot_style (str)

  • title_prefix (str)

  • ylabel (str)

  • origin_clock_hour (float)

  • awake_start_clock_hour (float)

  • awake_end_clock_hour (float)

  • starting_day (int)

  • phase_number (int | None)

  • show_legend (bool)

  • legend_loc (str | int | None)

  • legend_font_size (float | None)

  • xlim (tuple[float, float] | None)

  • ylim (tuple[float, float] | None)

  • xticks (list[float] | tuple[float, ...] | ndarray | None)

  • yticks (list[float] | tuple[float, ...] | ndarray | None)

  • xlabel (str | None)

  • day_night_indicator (tuple[str, str] | None)

plot_experiment_dual_metric_bars(primary_summary, secondary_summary, *, primary_mouse=None, secondary_mouse=None, group_name, bin_hours, output_path, secondary_label, phase_window_table, phase_display_names, plot_style='bar', spread_metric='sem', origin_clock_hour=6.0, awake_start_clock_hour=6.0, awake_end_clock_hour=18.0, show_legend=True, legend_loc=None, legend_font_size=None, xlim=None, ylim=None, xticks=None, yticks=None, xlabel=None, ylabel=None, title_label=None, day_night_indicator=('awake', 'sleep'), single_group_display='spread')[source]

Plot paired dual-metric summaries across the full experiment timeline.

Return type:

None

Parameters:
  • primary_summary (DataFrame)

  • secondary_summary (DataFrame)

  • primary_mouse (DataFrame | None)

  • secondary_mouse (DataFrame | None)

  • group_name (str)

  • bin_hours (int)

  • output_path (Path)

  • secondary_label (str)

  • phase_window_table (DataFrame)

  • phase_display_names (dict[int, str])

  • plot_style (str)

  • spread_metric (str)

  • origin_clock_hour (float)

  • awake_start_clock_hour (float)

  • awake_end_clock_hour (float)

  • show_legend (bool)

  • legend_loc (str | int | None)

  • legend_font_size (float | None)

  • xlim (tuple[float, float] | None)

  • ylim (tuple[float, float] | None)

  • xticks (list[float] | tuple[float, ...] | ndarray | None)

  • yticks (list[float] | tuple[float, ...] | ndarray | None)

  • xlabel (str | None)

  • ylabel (str | None)

  • title_label (str | None)

  • day_night_indicator (tuple[str, str] | None)

  • single_group_display (str)

plot_experiment_dual_metric_groups(primary_summary, secondary_summary, *, group_names, bin_hours, output_path, secondary_label, phase_window_table, phase_display_names, origin_clock_hour=6.0, awake_start_clock_hour=6.0, awake_end_clock_hour=18.0, show_legend=True, legend_loc=None, legend_font_size=None, xlim=None, ylim=None, xticks=None, yticks=None, xlabel=None, ylabel=None, title_label=None, day_night_indicator=('awake', 'sleep'), show_all_visits=True, show_all_groups_sem=False, spread_metric='sem')[source]

Plot all-groups full-experiment dual metrics with reduced legend semantics.

Return type:

None

Parameters:
  • primary_summary (DataFrame)

  • secondary_summary (DataFrame)

  • group_names (list[str])

  • bin_hours (int)

  • output_path (Path)

  • secondary_label (str)

  • phase_window_table (DataFrame)

  • phase_display_names (dict[int, str])

  • origin_clock_hour (float)

  • awake_start_clock_hour (float)

  • awake_end_clock_hour (float)

  • show_legend (bool)

  • legend_loc (str | int | None)

  • legend_font_size (float | None)

  • xlim (tuple[float, float] | None)

  • ylim (tuple[float, float] | None)

  • xticks (list[float] | tuple[float, ...] | ndarray | None)

  • yticks (list[float] | tuple[float, ...] | ndarray | None)

  • xlabel (str | None)

  • ylabel (str | None)

  • title_label (str | None)

  • day_night_indicator (tuple[str, str] | None)

  • show_all_visits (bool)

  • show_all_groups_sem (bool)

  • spread_metric (str)

plot_phase4_reversal_components(summary_by_component, *, group_name, phase_display_name, bin_hours, output_path, spread_metric, x_end_hours=None, plot_style='step', origin_clock_hour=8.0, awake_start_clock_hour=6.0, awake_end_clock_hour=18.0, starting_day=1, show_legend=True, legend_loc=None, legend_font_size=None, xlim=None, ylim=None, xticks=None, yticks=None, xlabel=None, ylabel=None, title_label=None, day_night_indicator=('awake', 'sleep'))[source]

Plot new-correct, previous-correct, and neutral-corner visit rates for reversal.

Return type:

None

Parameters:
  • summary_by_component (dict[str, DataFrame])

  • group_name (str)

  • phase_display_name (str)

  • bin_hours (int)

  • output_path (Path)

  • spread_metric (str)

  • x_end_hours (float | None)

  • plot_style (str)

  • origin_clock_hour (float)

  • awake_start_clock_hour (float)

  • awake_end_clock_hour (float)

  • starting_day (int)

  • show_legend (bool)

  • legend_loc (str | int | None)

  • legend_font_size (float | None)

  • xlim (tuple[float, float] | None)

  • ylim (tuple[float, float] | None)

  • xticks (list[float] | tuple[float, ...] | ndarray | None)

  • yticks (list[float] | tuple[float, ...] | ndarray | None)

  • xlabel (str | None)

  • ylabel (str | None)

  • title_label (str | None)

  • day_night_indicator (tuple[str, str] | None)

plot_phase_segment_rate_groups(summary_bins, *, phase_number, phase_display_name, title_label, ylabel, output_path, spread_metric, add_zero_start=True, starting_day=1, chance_level=None, show_legend=True, legend_loc=None, legend_font_size=None)[source]

Plot group mean rates across awake/sleep segments within one phase.

Return type:

None

Parameters:
  • summary_bins (DataFrame)

  • phase_number (int)

  • phase_display_name (str)

  • title_label (str)

  • ylabel (str)

  • output_path (Path)

  • spread_metric (str)

  • add_zero_start (bool)

  • starting_day (int)

  • chance_level (float | None)

  • show_legend (bool)

  • legend_loc (str | int | None)

  • legend_font_size (float | None)

plot_group_day_violin(mouse_day_rates, *, phase_number, phase_display_name, phase_day, metric_title, ylabel, pairwise_stats, chance_stats, output_path, dayphase_label='awake', outlier_col='is_outlier', reference_line=25.0, value_scale=100.0, format_as_percent=True, y_limits=None, stats_bracket_drop=None)[source]

Plot one day-wise group violin panel with significance annotations.

Return type:

None

Parameters:
  • mouse_day_rates (DataFrame)

  • phase_number (int)

  • phase_display_name (str)

  • phase_day (int)

  • metric_title (str)

  • ylabel (str)

  • pairwise_stats (DataFrame)

  • chance_stats (DataFrame | None)

  • output_path (Path)

  • dayphase_label (str)

  • outlier_col (str)

  • reference_line (float | None)

  • value_scale (float)

  • format_as_percent (bool)

  • y_limits (tuple[float | None, float | None] | None)

  • stats_bracket_drop (float | None)

plot_cumulative_role_curves(summary_bins, *, group_name, output_path, title_label, ylabel, value_col, spread_col, plot_style, phase_window_table, phase_display_names, origin_clock_hour, awake_start_clock_hour, awake_end_clock_hour, x_start_hours=None, onset_points=None, starting_day=1, day_night_indicator=('awake', 'sleep'), show_legend=True, legend_loc=None, legend_font_size=None)[source]

Plot cumulative role-based corner trajectories for one experimental group.

Return type:

None

Parameters:
  • summary_bins (DataFrame)

  • group_name (str)

  • output_path (Path)

  • title_label (str)

  • ylabel (str)

  • value_col (str)

  • spread_col (str)

  • plot_style (str)

  • phase_window_table (DataFrame)

  • phase_display_names (dict[int, str])

  • origin_clock_hour (float)

  • awake_start_clock_hour (float)

  • awake_end_clock_hour (float)

  • x_start_hours (float | None)

  • onset_points (list[dict[str, float | str]] | None)

  • starting_day (int)

  • day_night_indicator (tuple[str, str] | None)

  • show_legend (bool)

  • legend_loc (str | int | None)

  • legend_font_size (float | None)

plot_visit_learning_curve_groups(summary_bins, *, phase_display_name, title_label, ylabel, output_path, spread_metric, chance_level=25.0, show_legend=True, legend_loc=None, legend_font_size=None, xlim=None, ylim=None, xticks=None, yticks=None, xlabel=None, figsize_cm=None)[source]

Plot experience-dependent learning curves across groups.

Return type:

None

Parameters:
  • summary_bins (DataFrame)

  • phase_display_name (str)

  • title_label (str)

  • ylabel (str)

  • output_path (Path)

  • spread_metric (str)

  • chance_level (float | None)

  • show_legend (bool)

  • legend_loc (str | int | None)

  • legend_font_size (float | None)

  • xlim (tuple[float, float] | None)

  • ylim (tuple[float, float] | None)

  • xticks (list[float] | tuple[float, ...] | ndarray | None)

  • yticks (list[float] | tuple[float, ...] | ndarray | None)

  • xlabel (str | None)

  • figsize_cm (tuple[float, float] | None)

plot_onset_violin(onset_table, *, onset_col, phase_display_name, title_label, ylabel, output_path, pairwise_stats=None, outlier_col='is_outlier', reference_line=None, y_limits=None, show_n=False, figsize_cm=None)[source]

Plot onset distributions per group as violins with point overlays.

Return type:

None

Parameters:
  • onset_table (DataFrame)

  • onset_col (str)

  • phase_display_name (str)

  • title_label (str)

  • ylabel (str)

  • output_path (Path)

  • pairwise_stats (DataFrame | None)

  • outlier_col (str)

  • reference_line (float | None)

  • y_limits (tuple[float, float] | None)

  • show_n (bool)

  • figsize_cm (tuple[float, float] | None)

plot_phase_activity_boxplot(mouse_phase_activity, stats_table, *, phase_display_names, output_path, value_col='mean_visits_per_hour', title='Mice activity per group and phase', ylabel='Mean number of corner visits per hour', figsize_cm=None, show_legend=True, legend_loc=None, legend_font_size=None, show_n=True, xtick_rotation=45.0, median_line_width=1.2, median_marker_size=4.0, ylim=None, yticks=None)[source]

Plot hourly activity per phase and experimental group.

Return type:

None

Parameters:
  • mouse_phase_activity (DataFrame)

  • stats_table (DataFrame)

  • phase_display_names (dict[int, str])

  • output_path (Path)

  • value_col (str)

  • title (str)

  • ylabel (str)

  • figsize_cm (tuple[float, float] | None)

  • show_legend (bool)

  • legend_loc (str | int | None)

  • legend_font_size (float | None)

  • show_n (bool)

  • xtick_rotation (float)

  • median_line_width (float)

  • median_marker_size (float)

  • ylim (tuple[float, float] | None)

  • yticks (list[float] | tuple[float, ...] | ndarray | None)

The PlotLayout object

class PlotLayout(figsize_cm=None, title=None, xlabel=None, ylabel=None, xlim=None, ylim=None, xticks=None, yticks=None, legend=None, legend_loc=None, legend_font_size=None, extra=<factory>)[source]

Optional plot-level styling overrides for one figure family.

PlotLayout is a small convenience container used by plotting methods that accept plot_layout. Users can pass either a PlotLayout instance or a plain dictionary with the same keys.

Parameters:
  • figsize_cm (tuple[float, float] | None) – Optional figure size as (width_cm, height_cm). Default is None, which uses the method’s figsize_cm argument or the toolkit default for that plot type.

  • title (str | None) – Optional custom plot title. Default is None.

  • xlabel (str | None) – Optional custom x-axis label. Default is None.

  • ylabel (str | None) – Optional custom y-axis label. Default is None.

  • xlim (tuple[float, float] | None) – Optional x-axis limits as (min, max) in the plotted x-axis unit. Default is None.

  • ylim (tuple[float, float] | None) – Optional y-axis limits as (min, max). Default is None.

  • xticks (list[float] | None) – Optional explicit x tick locations. Default is None.

  • yticks (list[float] | None) – Optional explicit y tick locations. Default is None.

  • legend (bool | None) – Optional legend switch. Use True to show, False to hide, or None to use the plot default.

  • legend_loc (str | int | None) – Optional Matplotlib legend location such as "upper right", "upper left", "lower right", "best", or an integer location code. Default is None, which keeps the individual plot’s default legend placement.

  • legend_font_size (float | None) – Optional legend font size in points. Default is None, which uses the current base_font_size.

  • extra (dict[str, Any]) – Optional dictionary for plot-specific controls. Current high-level methods use show_N and xtick_rotation where relevant.

classmethod from_mapping(value)[source]

Normalize a layout mapping passed by a user script.

Return type:

PlotLayout

Parameters:

value (PlotLayout | dict[str, Any] | None)

Data loading and time alignment

class CohortData(visits, metadata, nosepokes, phase_manifest)[source]

Container that keeps the loaded cohort tables together.

Parameters:
  • visits (DataFrame)

  • metadata (DataFrame)

  • nosepokes (DataFrame)

  • phase_manifest (DataFrame)

load_cohort_data(dataset_root, *, phase_name_map=None, optional_phase_names=None, drop_unmatched_visits=False, group_names=None, subject_metadata=None, drop_unregistered_subjects=True)[source]

Load and harmonize one IntelliCage cohort directory.

Parameters:
  • dataset_root – Root directory of one IntelliCage cohort.

  • phase_name_map – Legacy argument kept for configuration compatibility. Raw subfolders are now treated as technical export blocks and no longer define analysis phases.

  • optional_phase_names – Legacy argument kept for configuration compatibility. Missing biological phase folders are no longer checked during loading.

  • group_names – Optional group display order. Missing entries are filled with generic Group N names so partially specified group-name lists remain valid.

  • subject_metadata – Script-defined subject table. Rows are matched by AnimalID against raw IntelliCage AnimalTag values.

  • drop_unregistered_subjects – If subject_metadata is provided, control whether raw animals without a subject entry are silently excluded. This is the recommended public policy for script-defined analyses.

Return type:

CohortData

Parameters:
  • dataset_root (Path | str)

  • phase_name_map (dict[str, int] | None)

  • optional_phase_names (set[str] | list[str] | tuple[str, ...] | None)

  • drop_unmatched_visits (bool)

  • group_names (list[str] | tuple[str, ...] | None)

  • subject_metadata (DataFrame | None)

  • drop_unregistered_subjects (bool)

attach_analysis_time_columns(visits, phase_manifest, *, scheduled_phase_start_hours, mouse_day_start_hour, experiment_day0_start_hour=None, schedule_anchor_phase_number=None)[source]

Attach globally aligned analysis-time columns.

Raw IntelliCage exports are treated as technical export blocks. Their file boundaries do not have to match the experimental protocol. For cross-group comparisons we therefore create a second time axis:

  • experimental time starts at the mouse-day onset of day 0

  • protocol phase windows are assigned from subject-level absolute phase timestamps when available

  • phase-relative elapsed time is then computed from the subject-level phase start

Parameters:
  • visits – Visit-level table returned by load_cohort_data().

  • phase_manifest – Manifest with the observed temporal range of each raw export block.

  • scheduled_phase_start_hours – Mapping from phase number to global experiment-relative start hour. An additional trailing marker, for example 5=266, can be provided to define the exclusive end of phase 4.

  • mouse_day_start_hour – Clock time that defines the beginning of the mouse day on day 0.

  • experiment_day0_start_hour – Optional independent wall-clock hour that defines experiment elapsed time zero on day 0. When omitted, the experiment timeline continues to start at mouse_day_start_hour for backward compatibility. Set this separately when day counting should start before the awake phase, for example at midnight while the mouse day still begins at 07:00.

  • schedule_anchor_phase_number – Optional legacy raw export-block number whose observed start should be aligned to the configured scheduled start hour. This is only used when subject-level phase windows are absent.

Return type:

DataFrame

Parameters:
  • visits (DataFrame)

  • phase_manifest (DataFrame)

  • scheduled_phase_start_hours (dict[int, float])

  • mouse_day_start_hour (float)

  • experiment_day0_start_hour (float | None)

  • schedule_anchor_phase_number (int | None)

read_visits_file(visits_path, run_group, phase_name, phase_number)[source]

Read one IntelliCage Visits.txt file into a typed DataFrame.

Return type:

DataFrame

Parameters:
  • visits_path (Path)

  • run_group (str)

  • phase_name (str)

  • phase_number (int)

read_nosepokes_file(nosepokes_path, run_group, phase_name, phase_number)[source]

Read one IntelliCage Nosepokes.txt file into a typed DataFrame.

Return type:

DataFrame

Parameters:
  • nosepokes_path (Path)

  • run_group (str)

  • phase_name (str)

  • phase_number (int)

summarize_nosepokes_by_visit(nosepokes)[source]

Aggregate raw nose-poke rows to one row per visit.

Return type:

DataFrame

Parameters:

nosepokes (DataFrame)

Metric tables

flag_iqr_outliers(data, *, value_col, group_cols, fence_factor=1.5, min_group_size=4)[source]

Flag IQR-based outliers within user-defined groups.

The returned frame keeps all original rows and appends the columns is_outlier, outlier_lower_fence, and outlier_upper_fence. Outlier detection is only applied when a subgroup contains at least min_group_size non-missing values.

Return type:

DataFrame

Parameters:
  • data (DataFrame)

  • value_col (str)

  • group_cols (list[str])

  • fence_factor (float)

  • min_group_size (int)

infer_phase_boundaries(phase_manifest)[source]

Infer experiment-relative phase start hours from the manifest.

Return type:

dict[int, float]

Parameters:

phase_manifest (DataFrame)

build_phase_time_limit_table(phase_manifest)[source]

Build a table of observed and robust common phase durations.

The recommended common duration is the maximum non-outlier duration across run groups, using the standard 1.5 IQR rule to detect unusually long phase recordings.

Return type:

DataFrame

Parameters:

phase_manifest (DataFrame)

suggest_common_phase_limits(phase_manifest)[source]

Return robust common phase-duration limits keyed by phase number.

Return type:

dict[int, float]

Parameters:

phase_manifest (DataFrame)

filter_visits_by_phase_limits(visits, phase_max_hours)[source]

Filter visits so that selected phases stop after a configured hour.

Return type:

DataFrame

Parameters:
  • visits (DataFrame)

  • phase_max_hours (dict[int, float] | None)

filter_by_dayphase(data, *, dayphase='day', awake_start_clock_hour=6.0, awake_end_clock_hour=18.0, time_col='Start', elapsed_col='analysis_experiment_elapsed_hours', origin_clock_hour=6.0)[source]

Return rows from the active day phase, inactive night phase, or both.

Return type:

DataFrame

Parameters:
  • data (DataFrame)

  • dayphase (Literal['day', 'night', 'all'])

  • awake_start_clock_hour (float)

  • awake_end_clock_hour (float)

  • time_col (str)

  • elapsed_col (str)

  • origin_clock_hour (float)

build_analysis_phase_window_table(visits, scheduled_phase_start_hours)[source]

Describe the visible protocol phase windows on the aligned timeline.

Return type:

DataFrame

Parameters:
  • visits (DataFrame)

  • scheduled_phase_start_hours (dict[int, float])

compute_experiment_visit_bins(visits, *, bin_hours)[source]

Count total visits per mouse across the full experiment timeline.

Return type:

tuple[DataFrame, DataFrame]

Parameters:
  • visits (DataFrame)

  • bin_hours (int)

compute_experiment_drinking_visit_bins(visits, *, bin_hours)[source]

Count lick-positive nose-poke visits across the full experiment timeline.

Return type:

tuple[DataFrame, DataFrame]

Parameters:
  • visits (DataFrame)

  • bin_hours (int)

compute_experiment_nosepoke_count_bins(visits, *, bin_hours)[source]

Sum nose-poke event counts per mouse across the aligned experiment timeline.

Return type:

tuple[DataFrame, DataFrame]

Parameters:
  • visits (DataFrame)

  • bin_hours (int)

compute_experiment_lick_count_bins(visits, *, bin_hours)[source]

Sum lick counts per mouse across the aligned experiment timeline.

Return type:

tuple[DataFrame, DataFrame]

Parameters:
  • visits (DataFrame)

  • bin_hours (int)

compute_bottle_preference_bins(nosepokes, *, phases='all', bin_h=24, left_sides=(1, 3, 5, 7), right_sides=(2, 4, 6, 8), consumption_col='LickNumber', calc='right_bottle/left_bottle')[source]

Compute binned left/right bottle consumption or preference.

Return type:

tuple[DataFrame, DataFrame]

Parameters:
  • nosepokes (DataFrame)

  • phases (str | int | tuple[int, ...] | list[int])

  • bin_h (int | float)

  • left_sides (tuple[int, ...] | list[int])

  • right_sides (tuple[int, ...] | list[int])

  • consumption_col (str)

  • calc (str)

compute_binned_group_statistics(mouse_bins, *, value_col='value', group_col='Group', bin_col='bin_start_hours', normality_alpha=0.05, alpha=0.05)[source]

Compute bin-wise group statistics on mouse-level values.

Two-group bins are tested with Welch’s t-test when both groups are compatible with normality by Shapiro-Wilk tests; otherwise Mann-Whitney U is used. Bins with more than two groups use one-way ANOVA for normally distributed groups and Kruskal-Wallis otherwise.

Return type:

DataFrame

Parameters:
  • mouse_bins (DataFrame)

  • value_col (str)

  • group_col (str)

  • bin_col (str)

  • normality_alpha (float)

  • alpha (float)

compute_phase2_adaptation_bins(visits, *, bin_hours, phase_number=2, secondary_metric='lick_positive_visits')[source]

Summarize nose-poke adaptation with two complementary metrics.

Return type:

dict[str, tuple[DataFrame, DataFrame]]

Parameters:
  • visits (DataFrame)

  • bin_hours (int)

  • phase_number (int)

  • secondary_metric (Literal['lick_positive_visits', 'lick_count'])

compute_place_learning_count_bins(visits, *, phase_number, bin_hours, success_col)[source]

Summarize selected place-learning event counts for phase 3 or phase 4.

Return type:

tuple[DataFrame, DataFrame]

Parameters:
  • visits (DataFrame)

  • phase_number (int)

  • bin_hours (int)

  • success_col (str)

compute_phase_visit_count_bins(visits, *, phase_number, bin_hours)[source]

Summarize all visit counts for a selected phase.

Return type:

tuple[DataFrame, DataFrame]

Parameters:
  • visits (DataFrame)

  • phase_number (int)

  • bin_hours (int)

compute_place_learning_rate_bins(visits, *, phase_number, bin_hours, success_col)[source]

Summarize selected place-learning rates for phase 3 or phase 4.

Return type:

tuple[DataFrame, DataFrame]

Parameters:
  • visits (DataFrame)

  • phase_number (int)

  • bin_hours (int)

  • success_col (str)

compute_phase4_reversal_rate_bins(visits, *, bin_hours, phase_number=4)[source]

Summarize place-reversal corner-choice rates for new, previous, and neutral corners.

Return type:

dict[str, tuple[DataFrame, DataFrame]]

Parameters:
  • visits (DataFrame)

  • bin_hours (int)

  • phase_number (int)

compute_phase4_reversal_count_bins(visits, *, bin_hours, phase_number=4)[source]

Summarize phase-4 reversal component counts for new, old, and neutral corners.

Return type:

dict[str, tuple[DataFrame, DataFrame]]

Parameters:
  • visits (DataFrame)

  • bin_hours (int)

  • phase_number (int)

compute_phase_segment_rate_tables(visits, *, phase_number, success_col, origin_clock_hour, awake_start_clock_hour, awake_end_clock_hour, max_days=3)[source]

Compute mouse-level and group-level rates for awake/sleep segments within one phase.

Return type:

tuple[DataFrame, DataFrame]

Parameters:
  • visits (DataFrame)

  • phase_number (int)

  • success_col (str)

  • origin_clock_hour (float)

  • awake_start_clock_hour (float)

  • awake_end_clock_hour (float)

  • max_days (int)

compute_phase_segment_error_rate_tables(visits, *, phase_number, success_col, origin_clock_hour, awake_start_clock_hour, awake_end_clock_hour, max_days=3)[source]

Compute mouse-level and group-level error rates for awake/sleep segments.

The error rate is defined as (all_visits - success_visits) / all_visits using the same denominator as compute_phase_segment_rate_tables().

Return type:

tuple[DataFrame, DataFrame]

Parameters:
  • visits (DataFrame)

  • phase_number (int)

  • success_col (str)

  • origin_clock_hour (float)

  • awake_start_clock_hour (float)

  • awake_end_clock_hour (float)

  • max_days (int)

compute_awake_day_rate_tables(visits, *, phase_number, success_col, origin_clock_hour, awake_start_clock_hour, awake_end_clock_hour, max_days=3, dayphase_segment='awake')[source]

Compute per-mouse day-wise rates for awake, sleep, or full-day segments.

Return type:

tuple[DataFrame, DataFrame]

Parameters:
  • visits (DataFrame)

  • phase_number (int)

  • success_col (str)

  • origin_clock_hour (float)

  • awake_start_clock_hour (float)

  • awake_end_clock_hour (float)

  • max_days (int)

  • dayphase_segment (Literal['awake', 'sleep', 'all'])

compute_awake_day_error_rate_tables(visits, *, phase_number, success_col, origin_clock_hour, awake_start_clock_hour, awake_end_clock_hour, max_days=3, dayphase_segment='awake')[source]

Compute per-mouse day-wise error rates for awake, sleep, or full-day segments.

The error rate is (all_visits - success_visits) / all_visits. With dayphase_segment="all", awake and sleep counts are summed before the rate is calculated, producing one full-day value per mouse and phase day.

Return type:

tuple[DataFrame, DataFrame]

Parameters:
  • visits (DataFrame)

  • phase_number (int)

  • success_col (str)

  • origin_clock_hour (float)

  • awake_start_clock_hour (float)

  • awake_end_clock_hour (float)

  • max_days (int)

  • dayphase_segment (Literal['awake', 'sleep', 'all'])

compute_awake_day_ratio_tables(visits, *, phase_number, numerator_col, denominator_col, origin_clock_hour, awake_start_clock_hour, awake_end_clock_hour, max_days=3, pseudocount=0.0, dayphase_segment='awake')[source]

Compute daily ratios from two visit-level indicator columns.

Ratios are computed per mouse as numerator_count / denominator_count. dayphase_segment selects awake, sleep, or full-day windows. With "all", awake and sleep counts are summed before the ratio is calculated.

Return type:

tuple[DataFrame, DataFrame]

Parameters:
  • visits (DataFrame)

  • phase_number (int)

  • numerator_col (str)

  • denominator_col (str)

  • origin_clock_hour (float)

  • awake_start_clock_hour (float)

  • awake_end_clock_hour (float)

  • max_days (int)

  • pseudocount (float)

  • dayphase_segment (Literal['awake', 'sleep', 'all'])

compute_first_hours_rate_table(visits, *, phase_number, success_col, first_hours=24.0)[source]

Aggregate per-mouse success counts and rates within the first phase hours.

The resulting table is intended for early-learning analyses that use the natural binomial structure of the IntelliCage data instead of only the derived percentage values.

Return type:

DataFrame

Parameters:
  • visits (DataFrame)

  • phase_number (int)

  • success_col (str)

  • first_hours (float)

compute_threshold_responder_table(onset_table, *, phase_number, threshold_pct, horizons_hours=(24.0, 48.0, 72.0))[source]

Convert threshold-onset times into responder yes/no labels by horizon.

Return type:

DataFrame

Parameters:
  • onset_table (DataFrame)

  • phase_number (int)

  • threshold_pct (float)

  • horizons_hours (tuple[float, ...])

compute_responder_group_statistics(responder_table, *, phase_number, metric_name)[source]

Compute responder summaries and group-comparison statistics.

Omnibus testing uses Fisher’s exact test for two groups and chi-square for more than two groups. Pairwise comparisons use Fisher’s exact test with FDR-BH correction.

Return type:

tuple[DataFrame, DataFrame, DataFrame]

Parameters:
  • responder_table (DataFrame)

  • phase_number (int)

  • metric_name (str)

compute_binomial_glm_group_statistics(data, *, phase_number, metric_name, success_col, total_col, subset_col=None, subset_label='subset')[source]

Fit count-based binomial GLMs and derive omnibus/pairwise group tests.

The model uses mouse-level success counts with the corresponding visit totals as binomial weights. If available and non-degenerate, SEX is included as a covariate. The function fits separate models per subset, for example phase_day or first_hours.

Return type:

tuple[DataFrame, DataFrame]

Parameters:
  • data (DataFrame)

  • phase_number (int)

  • metric_name (str)

  • success_col (str)

  • total_col (str)

  • subset_col (str | None)

  • subset_label (str)

compute_binomial_gee_group_statistics(data, *, phase_number, metric_name, success_col, total_col, cluster_col='ET', subset_col=None, subset_label='subset')[source]

Fit mouse-clustered binomial GEEs and derive omnibus/pairwise tests.

Compared with the simpler weighted GLM, this approach retains repeated within-mouse observations, for example 1 h bins, and uses a clustered sandwich covariance via GEE. This yields more conservative standard errors when mice contribute many bins with correlated behavior.

Return type:

tuple[DataFrame, DataFrame]

Parameters:
  • data (DataFrame)

  • phase_number (int)

  • metric_name (str)

  • success_col (str)

  • total_col (str)

  • cluster_col (str)

  • subset_col (str | None)

  • subset_label (str)

compute_group_day_violin_statistics(mouse_day_rates, *, phase_number, metric_name, chance_level, exclude_outliers=False)[source]

Compute omnibus, pairwise, and chance-level statistics for one phase/day-rate panel set.

Return type:

tuple[DataFrame, DataFrame, DataFrame]

Parameters:
  • mouse_day_rates (DataFrame)

  • phase_number (int)

  • metric_name (str)

  • chance_level (float)

  • exclude_outliers (bool)

compute_role_cumulative_curves(visits, *, pre_phase_hours=24.0, anchor_phase_number=3)[source]

Compute event-based cumulative corner-role visits across late NPA, PL, and PR.

This version is intentionally not time-binned. Each cumulative step is aligned to the actual visit-event times, which keeps the trajectories as close as possible to the underlying behavioral sequence.

Return type:

tuple[DataFrame, DataFrame]

Parameters:
  • visits (DataFrame)

  • pre_phase_hours (float)

  • anchor_phase_number (int)

compute_time_window_learning_curves(visits, *, phase_number, success_col, window_hours=1.0, step_hours=0.5, min_visits=5, threshold=0.4, consecutive_windows=3)[source]

Compute sliding-window clock-time learning curves and onset times.

Return type:

tuple[DataFrame, DataFrame, DataFrame]

Parameters:
  • visits (DataFrame)

  • phase_number (int)

  • success_col (str)

  • window_hours (float)

  • step_hours (float)

  • min_visits (int)

  • threshold (float)

  • consecutive_windows (int)

compute_visit_window_learning_curves(visits, *, phase_number, success_col, window_visits=20, min_visits=20, threshold=0.4, consecutive_windows=3)[source]

Compute rolling learning curves over visit number and the resulting onset by experience.

Return type:

tuple[DataFrame, DataFrame, DataFrame]

Parameters:
  • visits (DataFrame)

  • phase_number (int)

  • success_col (str)

  • window_visits (int)

  • min_visits (int)

  • threshold (float)

  • consecutive_windows (int)

compute_onset_group_statistics(onset_table, *, onset_col, phase_number, metric_name, exclude_outliers=False)[source]

Compute omnibus and pairwise group statistics for one onset metric.

Return type:

tuple[DataFrame, DataFrame]

Parameters:
  • onset_table (DataFrame)

  • onset_col (str)

  • phase_number (int)

  • metric_name (str)

  • exclude_outliers (bool)

compute_phase_activity_medians(visits, *, hourly_bin_size=1)[source]

Compute per-mouse hourly visit activity summaries for each phase.

Missing hourly bins are filled with zeros so the output reflects activity over the full available phase window. Sparse data can therefore have a median of zero; mean_visits_per_hour is usually the more informative default for plotting.

Return type:

DataFrame

Parameters:
  • visits (DataFrame)

  • hourly_bin_size (int)

compute_phase_activity_statistics(mouse_phase_activity)[source]

Compute legacy-style phase activity statistics per experimental group.

The old exported CSV files contain an omnibus one-way ANOVA plus pairwise phase comparisons. This function reproduces that logic using one-way ANOVA across phases 1-4 within an experimental group and Tukey HSD for the pairwise post-hoc tests.

Return type:

DataFrame

Parameters:

mouse_phase_activity (DataFrame)