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 anic_analysis.experiment.IntelliCageExperimentobject ready forload(),prepare_analysis(), and modular plotting calls.- Parameters:
EXPERIMENT (
ExperimentMetadata|dict[str,Any]) β Experiment metadata as anExperimentMetadatainstance or a dictionary. Required keys for dictionaries arename,root_data_path,results_data_path, andgroup_names. The optionalmouse_daydictionary 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 toPhaseMetadataor dictionary. Default isNonewhen phases are embedded inEXPERIMENT. Each phase can defineshort_name,long_name,folder_name,color, andscheduled_start_hour.SUBJECTS (
SubjectRegistry|dict[str|int,SubjectMetadata|dict[str,Any]] |None) β Subject definitions as aSubjectRegistryor dictionary. No default is allowed: the toolkit deliberately analyzes only explicitly declared animals.
- Return type:
- 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.txtfiles 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 defineroot_data_pathso raw exports can be scanned.PHASES (
dict[int|str,PhaseMetadata|dict[str,Any]] |None) β Optional phase mapping. Default isNonewhen usingnumber_of_phases. If provided, phasefolder_namevalues 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 defaultPhaseNfolders to scan. Default isNone. Use this only when noPHASESdictionary 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
PHASESnornumber_of_phasesis 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
SUBJECTSdictionary.The YAML may either be a direct subject mapping or contain a top-level
subjectsmapping. The returned dictionary can be passed directly toic.experiment(EXPERIMENT=..., PHASES=..., SUBJECTS=...).- Parameters:
path (
Path|str) β Path to the subject YAML file.- Return type:
dict[str,dict[str,Any]]- Returns:
A
dictkeyed 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.
- 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)
- 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:
- 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.
loadreads all configuredVisits.txtandNosepokes.txtexports belowexperiment.root_data_path, keeps only animals declared insubjects, 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 plusexperiment.yaml,phases.yaml, andsubjects.yamlto the results folder.- Return type:
None- Returns:
None. The loaded tables are stored on the experiment object asvisits,cohort, andphase_windows.
- require_loaded()[source]ο
Return loaded cohort data and visits.
- Return type:
tuple[CohortData,DataFrame]- Returns:
(cohort, visits)afterload()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 isNoneand 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 isNone. 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 isNone. Use it for temporary QC reruns without editing the subject metadata.verbose (
bool) β Whether to print the analysis-preparation summary. Default isTruefor explicit interactive calls. Internal plot calls useFalseto avoid repeated terminal output.
- Return type:
None- Returns:
None. Prepared tables are stored asanalysis_visits,analysis_metadata,analysis_nosepokes, andanalysis_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_birthto the first phase start for each subject. If no date of birth is available, the subject-levelage_monthsvalue 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 isNone, which writesmouse_age_at_phase1_start_<unit>_violinto 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 isTrueand recommended for public/reporting figures.plot_layout (
PlotLayout|dict|None) β OptionaldictorPlotLayout. Supported keys aretitle,ylabel,ylim, andfigsize_cmfor this plot. Other common keys such asxlabel,xlim,xticks,yticks, andlegendare ignored when they do not apply to the figure.base_font_size (
float) β Base font size in points. Default is10.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 isNoneand uses the plot preset unless overridden byplot_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
ΞΌ Β± SEMorΞΌ Β± SDdepending onspread_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 is1. Use1for detailed QC and larger values such as2or24for smoother overview plots.phases (
Union[Literal['all'],int,tuple[int,...],list[int]]) β Phase selection. Default is"all". Use an integer such as2for 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 isNone.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) β OptionaldictorPlotLayout. Common keys aretitle,xlabel,ylabel,xlim,ylim,xticks,yticks,legend, andfigsize_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 is10.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 orNoneto 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_binandlick_positive_visits_per_binper mouse, summarized as group mean plus the selected spread. The x-axis remains on elapsed experimental time. Withphases="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 is2for 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 isNone; preferphasesin new scripts.bin_hours (
int) β Width of time bins in hours. Default is1.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 isNone.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 isTrue. IfFalse, 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 isFalsefor a cleaner multi-group overview.single_group_display (
Literal['spread','individual']) β"spread"plots group mean plusspread_metricfor 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) β OptionaldictorPlotLayout. Supported keys aretitle,xlabel,ylabel,xlim,ylim,xticks,yticks,legend, andfigsize_cm.base_font_size (
float) β Base font size in points. Default is10.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"); useNoneto 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 is1.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 isNone.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) β OptionaldictorPlotLayoutwithtitle,xlabel,ylabel,xlim,ylim,xticks,yticks,legend, andfigsize_cm.base_font_size (
float) β Base font size in points. Default is10.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"). UseNoneto 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 is1.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 isNone.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) β OptionaldictorPlotLayoutwithtitle,xlabel,ylabel,xlim,ylim,xticks,yticks,legend, andfigsize_cm.base_font_size (
float) β Base font size in points. Default is10.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"). UseNoneto 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 computeleft / (left + right)orright / (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 is24. Use1for hourly,24for daily, and7 * 24for weekly summaries.phase_max_hours (
dict[int,float] |None) β Optional phase limits in hours. Default isNone.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) β IfTrue, draws a point at each binned mean. Default isFalse. Useful for daily or weekly bins.calc_stats (
bool) β IfTrue, 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 isFalse.output_dir (
Path|None) β Optional output folder. Default is a bin/dayphase folder below the experiment results folder.plot_layout (
PlotLayout|dict|None) β OptionaldictorPlotLayoutwithtitle,xlabel,ylabel,xlim,ylim,xticks,yticks,legend, andfigsize_cm.base_font_size (
float) β Base font size in points. Default is10.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 isNone. 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
calcmodes asplot_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.10forDay 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 isNone.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 isTrue.output_dir (
Path|None) β Optional output folder. Default isresults/bottle_preference_summary.plot_layout (
PlotLayout|dict|None) β OptionaldictorPlotLayoutwithtitle,ylabel,ylim,yticks, andfigsize_cm.show_N (
bool) β Whether group labels include sample size. Default isTrue.xtick_rotation (
float) β Rotation angle for group labels. Default is25.0.base_font_size (
float) β Base font size in points. Default is10.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 orNoneto 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 withSEMorSDshading. Use this for the main time-resolved place-learning or reversal-learning readout.- Parameters:
phase_number (
int) β Phase number to analyze, for example3for PL or4for 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 is1.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 isNone.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) β OptionaldictorPlotLayoutwithtitle,xlabel,ylabel,xlim,ylim,xticks,yticks,legend, andfigsize_cm. Use{"legend": False}for manuscript panels with external labels.base_font_size (
float) β Base font size in points. Default is10.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 orNoneto 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 is1.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 isNone.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) β OptionaldictorPlotLayoutwithtitle,xlabel,ylabel,xlim,ylim,xticks,yticks,legend, andfigsize_cm.base_font_size (
float) β Base font size in points. Default is10.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_visitsper 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; use4for the synthetic PL/PR example.bin_hours (
int) β Bin width in hours. Default is1.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 isNone.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) β OptionaldictorPlotLayoutwithtitle,xlabel,ylabel,xlim,ylim,xticks,yticks,legend, andfigsize_cm.base_font_size (
float) β Base font size in points. Default is10.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 orNoneto 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 isNone.output_dir (
Path|None) β Optional output folder. Default isresults/visit_activity_summary.plot_layout (
PlotLayout|dict|None) β OptionaldictorPlotLayout. Supported keys aretitle,ylabel,ylim,yticks,legend,figsize_cm, plusshow_Nandxtick_rotationinextraor directly in the dictionary.show_N (
bool) β Whether group x tick labels include sample size. Default isTrue.xtick_rotation (
float) β Rotation angle for group labels. Default is45.0.median_line_width (
float) β Width of the line connecting phase medians or means within each group. Default is1.2.median_marker_size (
float) β Marker size for the connected phase summary points. Default is4.0.base_font_size (
float) β Base font size in points. Default is10.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 isNone.spread_metric (
Literal['sem','std']) β"sem"or"std". Default is"sem".output_dir (
Path|None) β Optional output folder. Default isresults/plr_segments.plot_layout (
PlotLayout|dict|None) β OptionaldictorPlotLayoutwithtitle,ylabel,legend, andfigsize_cm. Axis-limit keys are reserved for future support in this plot family.base_font_size (
float) β Base font size in points. Default is10.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_visitsis determined bymetric. 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 isNone.spread_metric (
Literal['sem','std']) β"sem"or"std". Default is"sem".output_dir (
Path|None) β Optional output folder. Default isresults/plr_segments.plot_layout (
PlotLayout|dict|None) β OptionaldictorPlotLayoutwithtitle,ylabel,legend,legend_loc,legend_font_size, andfigsize_cm.base_font_size (
float) β Base font size in points. Default is10.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_visitsduring 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 isNone.exclude_outliers (
bool) β Whether IQR-flagged outliers are excluded from statistics and hidden from violin bodies. Default isTrue.output_dir (
Path|None) β Optional output folder. Default isresults/plr_endpoints.plot_layout (
PlotLayout|dict|None) β OptionaldictorPlotLayout. Supported keys aretitle,ylabel,ylim, andfigsize_cm.base_font_size (
float) β Base font size in points. Default is10.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_visitsfor each mouse and selected phase day.success_visitsis usually the success column selected bymetric. For rewarded metrics,error_against="spatial_correct"switches the complement tocorrect_corner_visitand 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 isNone.exclude_outliers (
bool) β Whether IQR-flagged outliers are excluded from statistics and hidden from violin bodies. Default isTrue.output_dir (
Path|None) β Optional output folder. Default isresults/plr_endpoints.plot_layout (
PlotLayout|dict|None) β OptionaldictorPlotLayoutwithtitle,ylabel,ylim,legend,legend_loc,legend_font_size, andfigsize_cm.base_font_size (
float) β Base font size in points. Default is10.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 / visitswithin 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 isNone.spread_metric (
Literal['sem','std']) β"sem"or"std". Default is"sem".exclude_outliers (
bool) β Reserved for API symmetry with onset plots. Default isTrue.output_dir (
Path|None) β Optional output folder. Default isresults/plr_experience.plot_layout (
PlotLayout|dict|None) β OptionaldictorPlotLayoutwithtitle,xlabel,ylabel,xlim,ylim,xticks,yticks,legend, andfigsize_cm.base_font_size (
float) β Base font size in points. Default is10.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 isNone.exclude_outliers (
bool) β Whether IQR-flagged outliers are excluded from statistics and hidden from violin bodies. Default isTrue.output_dir (
Path|None) β Optional output folder. Default isresults/plr_experience.plot_layout (
PlotLayout|dict|None) β OptionaldictorPlotLayout. Supported keys aretitle,ylabel,ylim,figsize_cm, andshow_Nviaextraor directly in the dictionary.show_N (
bool) β Whether group x tick labels include sample size. Default isTrue.base_font_size (
float) β Base font size in points. Default is10.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 is70.0. Use lower values such as50for permissive responder screens and higher values such as80for robust learning.bin_hours (
int) β Bin width in hours. Default is1.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 isNone.exclude_outliers (
bool) β Whether IQR-flagged outliers are excluded from statistics and hidden from violin bodies. Default isTrue.output_dir (
Path|None) β Optional output folder. Default isresults/plr_thresholds.plot_layout (
PlotLayout|dict|None) β OptionaldictorPlotLayout. Supported keys aretitle,ylabel,ylim, andfigsize_cm.base_font_size (
float) β Base font size in points. Default is10.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_scalewithin 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 isNone.pseudocount (
float) β Value added to numerator and denominator before division. Default is0.0. Use only when zero-denominator mice should remain in exploratory plots.value_scale (
float) β Multiplicative scale. Default is100.0for percent-like outputs; use1.0for bounded ratios.format_as_percent (
bool) β Whether to format the y-axis as percent. Default isTrue.reference_line (
float|None) β Optional horizontal reference line. Default isNone. Use0.5for reversal preference whenvalue_scale=1.0.exclude_outliers (
bool) β Whether IQR-flagged outliers are excluded from statistics. Default isTrue.output_dir (
Path|None) β Optional output folder. Default isresults/plr_derived.plot_layout (
PlotLayout|dict|None) β OptionaldictorPlotLayout. Supported keys aretitle,ylabel,ylim,legend,legend_loc,legend_font_size,figsize_cm, and the plot-specificstats_bracket_dropfor manually adjusting the vertical length of significance brackets.base_font_size (
float) β Base font size in points. Default is10.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 isNone.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, orNoneto hide these labels while keeping the shaded bands.output_dir (
Path|None) β Optional output folder. Default isresults/plr_cumulative.plot_layout (
PlotLayout|dict|None) β OptionaldictorPlotLayoutwithlegend,legend_loc,legend_font_size, andfigsize_cm.base_font_size (
float) β Base font size in points. Default is10.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.
PlotLayoutis a small convenience container used by plotting methods that acceptplot_layout. Users can pass either aPlotLayoutinstance or a plain dictionary with the same keys.- Parameters:
figsize_cm (
tuple[float,float] |None) β Optional figure size as(width_cm, height_cm). Default isNone, which uses the methodβsfigsize_cmargument or the toolkit default for that plot type.title (
str|None) β Optional custom plot title. Default isNone.xlabel (
str|None) β Optional custom x-axis label. Default isNone.ylabel (
str|None) β Optional custom y-axis label. Default isNone.xlim (
tuple[float,float] |None) β Optional x-axis limits as(min, max)in the plotted x-axis unit. Default isNone.ylim (
tuple[float,float] |None) β Optional y-axis limits as(min, max). Default isNone.xticks (
list[float] |None) β Optional explicit x tick locations. Default isNone.yticks (
list[float] |None) β Optional explicit y tick locations. Default isNone.legend (
bool|None) β Optional legend switch. UseTrueto show,Falseto hide, orNoneto 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 isNone, which keeps the individual plotβs default legend placement.legend_font_size (
float|None) β Optional legend font size in points. Default isNone, which uses the currentbase_font_size.extra (
dict[str,Any]) β Optional dictionary for plot-specific controls. Current high-level methods useshow_Nandxtick_rotationwhere relevant.
- classmethod from_mapping(value)[source]ο
Normalize a layout mapping passed by a user script.
- Return type:
- 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:
- 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_hourfor 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)
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_visitsusing the same denominator ascompute_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. Withdayphase_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_segmentselects 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_houris 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)