"""
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]
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]
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",
]