Source code for lecilab_behavior_analysis.reports.overview

"""
Tables and figures of the overview page of the daily report
(village-report-generator), one function per report cell.

They take the trials of all the subjects of a project, prepared with
preprocessing.prepare (or analyze_df). None of them raises: if something
fails, they return a figure that says what failed (and log the error), so
that one broken cell does not stop the report.

Performance counts timeouts (correct = None) as errors, as in the figures
(see data_format_changes.py).
"""

import functools
import logging
from typing import Callable, Dict, List, Optional, Union

import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import seaborn as sns
from matplotlib import pyplot as plt
from matplotlib.figure import Figure

import lecilab_behavior_analysis.data_format_changes as dfc
from lecilab_behavior_analysis.figures.render import PanelProblem
from lecilab_behavior_analysis.metrics.choices import get_bias_evolution_df, get_win_stay_lose_switch_df
from lecilab_behavior_analysis.metrics.occupancy import (
    get_daily_occupancy_percentages,
    get_followers_matrix,
    get_occupancy_heatmap,
    get_start_and_end_of_sessions_df,
)
from lecilab_behavior_analysis.metrics.performance import (
    get_performance_by_trials_in_stage,
    get_performance_through_trials,
)
from lecilab_behavior_analysis.plots.choices import bias_triangle_plot, win_stay_lose_switch_plot
from lecilab_behavior_analysis.plots.occupancy import (
    plot_percentage_of_occupancy_per_day,
    plot_training_times_clock_heatmap,
    plot_transition_network_with_curved_edges,
)
from lecilab_behavior_analysis.plots.training import format_date_axis, plot_table_from_df
from lecilab_behavior_analysis.reports.tables import generate_tv_report
from lecilab_behavior_analysis.style import Style, color, group_colors, shows, stage_colors, title, use_style

logger = logging.getLogger(__name__)

# cells that failed since the last reset_failed_cells(), for problems_table
_FAILED_CELLS: List[PanelProblem] = []


[docs] def failed_cells() -> List[PanelProblem]: """The report cells that failed (and showed a message instead) so far.""" return list(_FAILED_CELLS)
[docs] def reset_failed_cells() -> None: _FAILED_CELLS.clear()
# --------------------------------------------------------------------------- # Never raise # --------------------------------------------------------------------------- def _plotly_message(title: str, text: str) -> go.Figure: fig = go.Figure() fig.add_annotation( text=text, showarrow=False, font=dict(color="firebrick"), xref="paper", yref="paper", x=0.5, y=0.5 ) fig.update_layout(title_text=title, xaxis_visible=False, yaxis_visible=False, height=200) return fig def _matplotlib_message(title: str, text: str) -> Figure: fig, ax = plt.subplots(figsize=(8, 2)) ax.text(0.5, 0.5, text, color="firebrick", ha="center", va="center", wrap=True) ax.set_title(title) ax.set_axis_off() return fig
[docs] def never_raises(title: str, kind: str) -> Callable: """ Decorator: if the function raises, log the error and return a figure (kind "plotly" or "matplotlib") with the message instead. """ def decorate(function: Callable) -> Callable: @functools.wraps(function) def wrapper(*args, **kwargs): try: return function(*args, **kwargs) except Exception as error: logger.warning("Report cell '%s' failed: %s: %s", title, type(error).__name__, error) _FAILED_CELLS.append(PanelProblem(title, type(error).__name__, str(error))) text = f"Could not generate {title}<br>{type(error).__name__}: {error}" if kind == "plotly": return _plotly_message(title, text) return _matplotlib_message(title, text.replace("<br>", "\n")) return wrapper return decorate
def _correct_numeric(df: pd.DataFrame) -> pd.Series: return df["correct"].apply(dfc.correct_as_number) # --------------------------------------------------------------------------- # Tables # ---------------------------------------------------------------------------
[docs] @never_raises("TV report", "plotly") def tv_report_table(events_df: pd.DataFrame, sessions_summary_df: pd.DataFrame, hours: int = 24) -> go.Figure: """Detections, sessions, water and weight of each subject in the last hours.""" if events_df is None or sessions_summary_df is None: return _plotly_message("TV report", "No events or sessions summary for this setup") report_df, last_date = generate_tv_report(events_df.copy(), sessions_summary_df.copy(), hours) return plot_table_from_df(report_df, title=f"TV Report - Last {hours} Hours from {last_date}")
[docs] def trials_by_stage(df: pd.DataFrame) -> pd.DataFrame: """Number of trials of each subject in each training stage (stages in order of appearance).""" stages = df["current_training_stage"].dropna().unique().tolist() table = df.groupby(["subject", "current_training_stage"]).size().unstack(fill_value=0).reset_index() return table.reindex(columns=["subject"] + stages)
[docs] @never_raises("Trials by Training Stage", "plotly") def trials_by_stage_table(df: pd.DataFrame) -> go.Figure: return plot_table_from_df(trials_by_stage(df), title="Trials by Training Stage")
[docs] def last_days(df: pd.DataFrame, n_days: int = 3) -> pd.DataFrame: """ Trials and performance of each subject in the last n_days days with data, one column per day ("trials_<day>", "performance_<day>"). """ df = df.assign(correct_numeric=_correct_numeric(df)) table = ( df.groupby(["subject", "year_month_day"]) .agg(trials=("trial", "count"), performance=("correct_numeric", "mean")) .reset_index() ) days = sorted(table["year_month_day"].unique())[-n_days:] table = table[table["year_month_day"].isin(days)] table["performance"] = table["performance"].map(lambda x: f"{x:.3f}") table = table.pivot(index="subject", columns="year_month_day", values=["trials", "performance"]) table.columns = [f"{name}_{day}" for name, day in table.columns] return table.reset_index()
[docs] @never_raises("Trials and Performance of last days", "plotly") def last_days_table(df: pd.DataFrame, n_days: int = 3) -> go.Figure: return plot_table_from_df(last_days(df, n_days), title="Trials and Performance of last days")
[docs] @never_raises("Panels that could not be generated", "plotly") def problems_table(problems: Dict[str, List[PanelProblem]]) -> go.Figure: """ The figure panels that failed, e.g. {"NUO003": fig.panel_problems, ...}. Shows "All panels were generated" if there are none. To include the report cells that failed, add {"Overview": failed_cells()}. """ rows = [ {"figure": name, "panel": p.panel, "error": p.error, "message": p.message[:200]} for name, figure_problems in problems.items() for p in figure_problems ] if not rows: return _plotly_message("Panels that could not be generated", "All panels were generated") return plot_table_from_df(pd.DataFrame(rows), title="Panels that could not be generated")
# --------------------------------------------------------------------------- # Figures # ---------------------------------------------------------------------------
[docs] def group_trials(df: pd.DataFrame, column: str = "performance_w", max_points: int = 1000) -> pd.DataFrame: """ At most max_points points per subject: consecutive trials are grouped (as few per group as needed) and each group is one point, at the last trial of the group (total_trial) with the mean of column. Columns: subject, total_trial, column. """ groups = [] for subject, trials in df.sort_values("total_trial").groupby("subject", sort=True): trials = trials[["total_trial", column]].dropna() if trials.empty: continue size = int(np.ceil(len(trials) / max_points)) group = np.arange(len(trials)) // size points = trials.groupby(group).agg(total_trial=("total_trial", "last"), value=(column, "mean")) points = points.rename(columns={"value": column}) points.insert(0, "subject", subject) groups.append(points) if not groups: return pd.DataFrame(columns=["subject", "total_trial", column]) return pd.concat(groups, ignore_index=True)
[docs] @never_raises("Performance over trials", "plotly") def performance_over_trials_figure(df: pd.DataFrame, window: int = 50, max_points: int = 1000) -> go.Figure: """ Performance through the trials of every subject (interactive), with at most max_points points per subject (see group_trials), so that the size of the report does not grow with the number of trials. """ if "performance_w" not in df.columns: df = pd.concat( [get_performance_through_trials(d, window=window) for _, d in df.groupby("subject")], ignore_index=True, ) points = group_trials(df, "performance_w", max_points) points["performance_w"] = points["performance_w"].round(1) fig = px.line( points, x="total_trial", y="performance_w", color="subject", color_discrete_sequence=group_colors(max(points["subject"].nunique(), 1)), ) fig.update_layout(xaxis_title="Trial", yaxis_title=f"Performance (%, window of {window} trials)") return fig
[docs] def subject_colors(subjects) -> Dict[str, str]: """A colour per subject (in alphabetical order), the same in every figure of the overview.""" subjects = sorted(pd.unique(pd.Series(list(subjects)).dropna())) return dict(zip(subjects, group_colors(max(len(subjects), 1))))
[docs] def last_hours(df: pd.DataFrame, hours: float = 48) -> pd.DataFrame: """The trials that started in the last hours before the last trial of df (of any subject).""" start = pd.to_numeric(df["TRIAL_START"], errors="coerce") return df[start >= start.max() - hours * 3600]
[docs] @never_raises("Box occupancy, training times and who follows whom", "matplotlib") def box_occupancy_figure(df: pd.DataFrame, style: Optional[Union[str, Style]] = None) -> Figure: """ Percentage of each day the box was used, the hours of the day it was used, and which mouse used it after which (an arrow from A to B: B started a session right after A). style: see style.py (default: the active style). """ occupancy = get_start_and_end_of_sessions_df(df) with use_style(style): fig = plt.figure(figsize=(14, 4), layout="constrained") ax_days = fig.add_subplot(1, 3, 1) ax_clock = fig.add_subplot(1, 3, 2, projection="polar") ax_network = fig.add_subplot(1, 3, 3) plot_percentage_of_occupancy_per_day(get_daily_occupancy_percentages(occupancy), ax=ax_days) plot_training_times_clock_heatmap(get_occupancy_heatmap(occupancy, window_size=30), ax=ax_clock) if occupancy["subject"].nunique() > 1: plot_transition_network_with_curved_edges( get_followers_matrix(occupancy), ax=ax_network, node_colors=subject_colors(occupancy["subject"]), colorbar_label="times B followed A", ) title(ax_network, "Who follows whom (A \u2192 B)") else: ax_network.set_axis_off() return fig
[docs] @never_raises("Strategies of the last hours", "matplotlib") def strategies_figure( df: pd.DataFrame, hours: float = 48, min_trials: int = 10, style: Optional[Union[str, Style]] = None ) -> Figure: """ Win-stay / lose-switch and side / alternation bias of each mouse in the last hours (before the last trial of df), a point per mouse with its colour of the overview. Habituation is left out; a mouse with fewer than min_trials correct (or error) trials has no win-stay (or lose-switch) point. style: see style.py (default: the active style). """ recent = last_hours(df, hours) if "task" in recent.columns: recent = recent[recent["task"] != "Habituation"] colors = subject_colors(df["subject"]) with use_style(style): fig, (ax_wsls, ax_bias) = plt.subplots(1, 2, figsize=(10, 4.2), layout="constrained") if recent.empty: for ax in (ax_wsls, ax_bias): ax.text(0.5, 0.5, f"No trials in the last {hours:g} hours", ha="center", va="center") ax.set_axis_off() return fig wsls = get_win_stay_lose_switch_df(recent, by="subject", min_trials=min_trials) win_stay_lose_switch_plot(wsls, hue="subject", palette=colors, legend=False, ax=ax_wsls) title(ax_wsls, f"Win-stay / lose-switch, last {hours:g} h") bias = get_bias_evolution_df(recent.dropna(subset=["roa_choice_numeric"]), groupby=[]) bias["n_trials"] = bias["subject"].map(recent.groupby("subject")["roa_choice_numeric"].count()) bias_triangle_plot(bias, hue="subject", palette=colors, legend=False, ax=ax_bias) title(ax_bias, f"Bias, last {hours:g} h") shown = [s for s in colors if s in set(wsls["subject"]) | set(bias["subject"])] handles = [ plt.Line2D([], [], marker="o", linestyle="", color=colors[s], markeredgecolor="white", markersize=8) for s in shown ] if handles: fig.legend(handles, shown, loc="outside right upper", frameon=False, fontsize="small") return fig
[docs] @never_raises("Performance through the trials of each stage", "matplotlib") def stage_performance_figure( df: pd.DataFrame, bin_size: int = 100, columns: int = 4, style: Optional[Union[str, Style]] = None ) -> Figure: """ Performance against the number of trials done in each training stage (bins of bin_size trials), a plot per stage (Habituation left out): the mean of the mice (with its 95% confidence interval) in the colour of the stage, and each mouse as a thin line (not in the "publication" style). style: see style.py (default: the active style). """ table = get_performance_by_trials_in_stage(df, bin_size=bin_size) # the last bin of a mouse in a stage can have a few trials (a spike to 0 or 1) table = table[table["n_trials"] >= bin_size / 2] with use_style(style): if table.empty: fig, ax = plt.subplots(figsize=(6, 2)) ax.text(0.5, 0.5, "No trials in a training stage (other than habituation)", ha="center", va="center") ax.set_axis_off() return fig # stages in the order the cohort reached them first = df.groupby("current_training_stage")["total_trial"].min() stages = sorted(table["current_training_stage"].unique(), key=lambda stage: first.get(stage, np.inf)) palette = stage_colors(stages) mice = subject_colors(table["subject"]) n_rows = int(np.ceil(len(stages) / columns)) fig, axs = plt.subplots( n_rows, min(columns, len(stages)), figsize=(3.6 * min(columns, len(stages)), 3 * n_rows), layout="constrained", sharey=True, squeeze=False, ) for ax, stage in zip(axs.flat, stages): points = table[table["current_training_stage"] == stage] if shows("standard"): for subject, mouse in points.groupby("subject"): ax.plot( mouse["trials_in_stage"], mouse["performance"], color=mice[subject], linewidth=0.7, alpha=0.6 ) sns.lineplot( data=points, x="trials_in_stage", y="performance", color=palette[stage], linewidth=2.5, errorbar=("ci", 95), ax=ax, ) ax.axhline(0.5, color=color("reference"), linestyle="--", linewidth=0.8) ax.set_ylim(0, 1) ax.set_xlabel("Trials in this stage") ax.set_ylabel("Performance") ax.spines[["top", "right"]].set_visible(False) n_mice = points["subject"].nunique() title(ax, f"{stage} ({n_mice} {'mouse' if n_mice == 1 else 'mice'})", fontsize="small") for ax in list(axs.flat)[len(stages) :]: ax.set_axis_off() return fig
[docs] def daily_trials_and_performance(df: pd.DataFrame) -> pd.DataFrame: """Trials, performance and misses of each subject per day and training stage.""" df = df.assign(correct_numeric=_correct_numeric(df)) keys = ["subject", "year_month_day", "current_training_stage"] table = ( df.groupby(keys) .agg( trials=("trial", "size"), correct=("correct_numeric", "mean"), miss_trial=("miss_trial", "mean"), ) .reset_index() ) table["current_training_stage"] = table["current_training_stage"].replace({"not saved": "Habituation"}) table["day"] = pd.to_datetime(table["year_month_day"]) return table.sort_values("day")
[docs] @never_raises("Trials and performance of the cohort", "matplotlib") def cohort_trials_and_performance_figure(df: pd.DataFrame, style: Optional[Union[str, Style]] = None) -> Figure: """ Number of trials and performance per day of the whole cohort, by training stage. style: see style.py (default: the active style). """ with use_style(style): return _cohort_trials_and_performance(daily_trials_and_performance(df))
def _cohort_trials_and_performance(table: pd.DataFrame) -> Figure: fig, axs = plt.subplots(1, 2, figsize=(12, 3), layout="constrained") palette = stage_colors(pd.unique(table["current_training_stage"])) sns.lineplot(data=table, x="day", y="trials", hue="current_training_stage", palette=palette, ax=axs[0]) title(axs[0], "Number of trials per day") sns.lineplot( data=table, x="day", y="correct", hue="current_training_stage", palette=palette, ax=axs[1], legend=False ) title(axs[1], "Correct percentage per day") for ax in axs: format_date_axis(ax) ax.spines[["top", "right"]].set_visible(False) if axs[0].get_legend() is not None: # one legend for both plots, outside, so that it does not hide the lines handles, labels = axs[0].get_legend_handles_labels() axs[0].get_legend().remove() fig.legend(handles, labels, loc="outside right upper", frameon=False) return fig __all__ = [ "never_raises", "failed_cells", "reset_failed_cells", "tv_report_table", "trials_by_stage", "trials_by_stage_table", "last_days", "last_days_table", "problems_table", "group_trials", "performance_over_trials_figure", "subject_colors", "last_hours", "box_occupancy_figure", "strategies_figure", "stage_performance_figure", "daily_trials_and_performance", "cohort_trials_and_performance_figure", ]