Source code for lecilab_behavior_analysis.plots.online
"""
The online plot: what is happening in a session while the mouse does the
task, updated after every trial (in the village, on a Raspberry Pi).
It is drawn from the raw trials of the session (Task.session_df), not from
prepared data, and it is made to be cheap: the figure and its artists are
made once, and each update only changes their data (no ax.clear(), no
seaborn, no tight_layout). What is computed from each trial (its outcome,
the side the mouse chose...) is computed once, when the trial is new, so an
update takes about the same time at trial 10 and at trial 1000.
Use it from the task's online_plot.py:
from lecilab_behavior_analysis.plots.online import OnlineSessionFigure
class OnlinePlot(OnlinePlotBase):
def create_figure_and_axes(self):
self.online = OnlineSessionFigure()
self.fig = self.online.fig
def update_plot(self, df):
self.online.update(df)
"""
import time
from typing import Dict, List, Optional, Union
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from matplotlib.collections import LineCollection, PolyCollection
from matplotlib.colors import to_rgba
from matplotlib.figure import Figure
import lecilab_behavior_analysis.data_format_changes as dfc
from lecilab_behavior_analysis.metrics.trial_events import _side_of_first_poke, parse_events
from lecilab_behavior_analysis.style import Style, color, modality_color, use_style
# outcomes of a trial, as in the task (twoAFC.py): a timeout has correct None, an
# early withdrawal (the trial ended before the stimulus) has correct False
CORRECT, ERROR, TIMEOUT, EARLY = "correct", "error", "timeout", "early withdrawal"
OUTCOMES = (CORRECT, ERROR, TIMEOUT, EARLY)
# easier trials are drawn darker
DIFFICULTY_ALPHA = {"easy": 1.0, "medium": 0.6, "hard": 0.35}
# leftward evidence of each difficulty (right is negative)
EVIDENCE = {"easy": 1.0, "medium": 2 / 3, "hard": 1 / 3}
# rows of the trial-by-trial strip (y), from top to bottom
LANE_LEFT, LANE_RIGHT, LANE_OUTCOME = 2, 1, 0
TABLE_COLUMNS = [
"trial",
"start",
"end",
"stage",
"modality",
"side",
"difficulty",
"correct",
"outcome",
"choice",
"water",
"holding_time",
]
def _text(value) -> Optional[str]:
if value is None or (isinstance(value, float) and np.isnan(value)):
return None
return str(value)
def _float(value) -> float:
try:
return float(value)
except (TypeError, ValueError):
return np.nan
def _correct(value) -> Optional[bool]:
"""True, False, or None (timeout); accepts the text of a csv."""
if isinstance(value, str):
return {"True": True, "False": False}.get(value.strip())
if value is None or (isinstance(value, float) and np.isnan(value)):
return None
return bool(value)
[docs]
def trial_row(row: dict) -> dict:
"""What the online plot needs from one raw trial (a row of Task.session_df)."""
correct = _correct(row.get("correct"))
side = _text(row.get("correct_side"))
stimulus = parse_events(row.get("STATE_stimulus_state_START"))
port1, port3 = parse_events(row.get("Port1In")), parse_events(row.get("Port3In"))
if side is None:
# habituation: no stimulus, the side the mouse went to
outcome, choice = CORRECT, _side_of_first_poke(port1, port3, -np.inf)
elif correct is None:
outcome, choice = TIMEOUT, None
elif not stimulus:
outcome, choice = EARLY, None
else:
outcome = CORRECT if correct else ERROR
choice = _side_of_first_poke(port1, port3, min(stimulus))
return {
"trial": _float(row.get("trial")),
"start": _float(row.get("TRIAL_START")),
"end": _float(row.get("TRIAL_END")),
"stage": _text(row.get("current_training_stage")),
"modality": _text(row.get("stimulus_modality")),
"side": side,
"difficulty": _text(row.get("difficulty")),
# 1 / 0, and timeouts as in the reports (see data_format_changes.py)
"correct": dfc.correct_as_number(correct) if side is not None else np.nan,
"outcome": outcome,
"choice": choice,
"water": _float(row.get("water")),
"holding_time": _float(row.get("holding_time")),
}
[docs]
def online_trials_table(df: pd.DataFrame) -> pd.DataFrame:
"""trial_row for every trial of a session: a row per trial with TABLE_COLUMNS."""
rows = [trial_row(row) for row in df.to_dict("records")]
return pd.DataFrame(rows, columns=TABLE_COLUMNS)
[docs]
def win_stay_lose_switch(choice: pd.Series, correct: pd.Series) -> tuple:
"""
(win_stay, lose_switch, n_wins, n_losses) of consecutive trials, as in
metrics.choices.get_win_stay_lose_switch_df: after a correct trial, did
the mouse choose the same side? After an error with a choice, the other?
"""
previous_choice, previous_correct = choice.shift(1), correct.shift(1)
both = choice.notna() & previous_choice.notna()
stay = choice == previous_choice
wins = both & (previous_correct == 1)
losses = both & (previous_correct == 0)
n_wins, n_losses = int(wins.sum()), int(losses.sum())
win_stay = stay[wins].mean() if n_wins else np.nan
lose_switch = 1 - stay[losses].mean() if n_losses else np.nan
return win_stay, lose_switch, n_wins, n_losses
[docs]
class OnlineSessionFigure:
"""
The figure of the online plot:
- top: the last trials, one per column: the correct side (coloured by
modality, darker for easier trials) with a dot on the side the mouse
chose, and the outcome (correct, error, timeout, early withdrawal).
Above them, the performance and the early withdrawals in the last
`window` trials.
- bottom: a summary of the session; the choices by side and difficulty
of each modality; the performance on each side; win-stay /
lose-switch of the session.
In habituation (no correct side) the strip shows the side the mouse
went to, and the rest says it is not used.
Args:
fig: draw here (default: a new figure of figsize).
last_trials: trials shown in the strip.
window: trials of the rolling performance.
style: the colours (see style.py; default: the active style).
"""
[docs]
def __init__(
self,
fig: Optional[Figure] = None,
last_trials: int = 100,
window: int = 20,
figsize: tuple = (16, 7),
style: Union[str, Style, None] = None,
) -> None:
self.last_trials = last_trials
self.window = window
self.table = pd.DataFrame(columns=TABLE_COLUMNS)
self._first_trial = None
with use_style(style):
self.colors = {
CORRECT: color("correct"),
ERROR: color("incorrect"),
TIMEOUT: color("neutral"),
EARLY: "#e6b800", # not the orange of auditory-cot
"neutral": color("neutral"),
"reference": color("reference"),
"text": color("text"),
"data": color("data"),
"choice": color("highlight"),
}
self._modality_color = {}
self._style = style
self.fig = fig if fig is not None else plt.figure(figsize=figsize)
self._make_axes()
# ------------------------------------------------------------------
# The figure, made once
# ------------------------------------------------------------------
def _make_axes(self) -> None:
fig = self.fig
grid = fig.add_gridspec(
3, 4, height_ratios=[1, 1.1, 2.6], width_ratios=[1, 1.2, 0.8, 0.9],
left=0.06, right=0.98, top=0.93, bottom=0.08, hspace=0.25, wspace=0.35,
) # fmt: skip
self.ax_rate = fig.add_subplot(grid[0, :])
self.ax_strip = fig.add_subplot(grid[1, :], sharex=self.ax_rate)
self.ax_summary = fig.add_subplot(grid[2, 0])
self.ax_choices = fig.add_subplot(grid[2, 1])
self.ax_sides = fig.add_subplot(grid[2, 2])
self.ax_wsls = fig.add_subplot(grid[2, 3])
self._problems = {}
# rates
ax = self.ax_rate
ax.set_ylim(0, 105)
ax.set_yticks([0, 50, 100])
ax.set_ylabel("% of last\ntrials")
ax.axhline(50, color=self.colors["reference"], linestyle="--", linewidth=0.8)
(self.performance_line,) = ax.plot([], [], color=self.colors["data"], linewidth=2, label="correct")
(self.early_line,) = ax.plot([], [], color=self.colors[EARLY], linewidth=1.5, label="early withdrawals")
ax.tick_params(labelbottom=False)
ax.spines[["top", "right"]].set_visible(False)
self.title = ax.text(0, 1.04, "", transform=ax.transAxes, ha="left", va="bottom", fontsize="small")
# the strip
ax = self.ax_strip
self.stimulus_bars = PolyCollection([], linewidths=0)
self.outcome_bars = PolyCollection([], linewidths=0)
ax.add_collection(self.stimulus_bars)
ax.add_collection(self.outcome_bars)
self.choice_dots = ax.scatter([], [], s=10, color=self.colors["choice"], zorder=3)
ax.set_ylim(-0.6, 2.6)
ax.set_yticks([LANE_LEFT, LANE_RIGHT, LANE_OUTCOME])
ax.set_yticklabels(["left", "right", "outcome"])
ax.spines[["top", "right", "left"]].set_visible(False)
ax.tick_params(left=False)
# one legend, above: the rates, the outcomes and the choice
handles = [self.performance_line, self.early_line]
handles += [plt.Rectangle((0, 0), 1, 1, color=self.colors[o]) for o in OUTCOMES]
handles.append(plt.Line2D([], [], marker="o", linestyle="", color=self.colors["choice"], markersize=4))
labels = ["% correct", "% early withdrawals"] + list(OUTCOMES) + ["the mouse's choice"]
self.ax_rate.legend(
handles, labels, loc="lower right", bbox_to_anchor=(1, 1), ncol=len(labels), frameon=False,
fontsize="x-small", handlelength=1.2, columnspacing=1,
) # fmt: skip
self._x_limits(0)
# summary
ax = self.ax_summary
ax.set_axis_off()
self.summary = ax.text(0, 1, "", va="top", ha="left", fontsize="small", family="monospace")
# choices by side and difficulty
ax = self.ax_choices
ax.set_xlim(-1.2, 1.2)
ax.set_ylim(-0.03, 1.03)
ax.axhline(0.5, color=self.colors["reference"], linestyle="--", linewidth=0.8)
ax.axvline(0, color=self.colors["reference"], linestyle="--", linewidth=0.8)
ax.set_xticks([-1, -2 / 3, -1 / 3, 1 / 3, 2 / 3, 1])
ax.set_xticklabels(["easy", "med", "hard", "hard", "med", "easy"], fontsize="x-small")
ax.set_xlabel("← right correct side left →", fontsize="small")
ax.set_ylabel("P(left choice)")
ax.spines[["top", "right"]].set_visible(False)
self.choice_lines: Dict[str, tuple] = {}
# performance on each side
ax = self.ax_sides
self.side_bars = ax.bar([0, 1], [0, 0], color=self.colors["neutral"], width=0.6)
self.side_texts = [ax.text(x, 0, "", ha="center", va="bottom", fontsize="x-small") for x in (0, 1)]
ax.set_xticks([0, 1])
ax.set_xticklabels(["left", "right"])
ax.set_ylim(0, 115)
ax.set_yticks([0, 50, 100])
ax.axhline(50, color=self.colors["reference"], linestyle="--", linewidth=0.8)
ax.set_ylabel("% correct")
ax.spines[["top", "right"]].set_visible(False)
# win-stay / lose-switch
ax = self.ax_wsls
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.set_aspect("equal")
ax.axhline(0.5, color=self.colors["reference"], linestyle="--", linewidth=0.8)
ax.axvline(0.5, color=self.colors["reference"], linestyle="--", linewidth=0.8)
ax.set_xticks([0, 0.5, 1])
ax.set_yticks([0, 0.5, 1])
ax.set_xlabel("lose-switch", fontsize="small")
ax.set_ylabel("win-stay", fontsize="small")
ax.text(0.97, 0.97, "win-stay\nlose-switch", ha="right", va="top", fontsize="xx-small",
color=self.colors["reference"], transform=ax.transAxes) # fmt: skip
(self.wsls_trail,) = ax.plot([], [], color=self.colors["reference"], linewidth=1, marker="o", markersize=3)
self.wsls_point = ax.scatter([], [], s=60, color=self.colors["data"], edgecolor="white", zorder=3)
self.wsls_text = ax.text(0.03, 0.03, "", fontsize="xx-small", transform=ax.transAxes)
def _x_limits(self, last: float) -> None:
last = max(last, self.last_trials)
self.ax_strip.set_xlim(last - self.last_trials + 0.5, last + 0.5)
def _modality(self, modality: Optional[str]) -> str:
if modality not in self._modality_color:
with use_style(self._style):
self._modality_color[modality] = modality_color(modality)
return self._modality_color[modality]
# ------------------------------------------------------------------
# Updates
# ------------------------------------------------------------------
[docs]
def add_trials(self, df: pd.DataFrame) -> pd.DataFrame:
"""
Brings the table of trials up to date with df (the trials of the
session so far): only the new trials are read. A new session (fewer
trials, or another first trial) starts the table again.
"""
first = df["TRIAL_START"].iloc[0] if len(df) and "TRIAL_START" in df.columns else None
if len(df) < len(self.table) or first != self._first_trial:
self.table = pd.DataFrame(columns=TABLE_COLUMNS)
self._first_trial = first
new = df.iloc[len(self.table) :]
if len(new):
rows = online_trials_table(new)
self.table = rows if self.table.empty else pd.concat([self.table, rows], ignore_index=True)
return self.table
[docs]
def update(self, df: pd.DataFrame) -> None:
"""Shows the trials of df (the trials of the session so far)."""
table = self.add_trials(df)
habituation = table.empty or table["side"].isna().all()
for name, draw in (
("rates", self._draw_rates),
("strip", self._draw_strip),
("summary", self._draw_summary),
("choices", self._draw_choices),
("sides", self._draw_sides),
("wsls", self._draw_wsls),
):
try:
draw(table, habituation)
self._problem(name, None)
except Exception as error: # one panel that fails does not stop the others
self._problem(name, f"{type(error).__name__}: {error}")
def _problem(self, name: str, message: Optional[str]) -> None:
"""Says why a panel could not be drawn (in its axes), or removes the message."""
ax = {
"rates": self.ax_rate, "strip": self.ax_strip, "summary": self.ax_summary,
"choices": self.ax_choices, "sides": self.ax_sides, "wsls": self.ax_wsls,
}[name] # fmt: skip
if name not in self._problems:
self._problems[name] = ax.text(
0.5, 0.5, "", transform=ax.transAxes, ha="center", va="center", fontsize="x-small",
color=self.colors[ERROR], wrap=True, zorder=10,
) # fmt: skip
self._problems[name].set_text("" if message is None else f"Could not draw this:\n{message[:150]}")
def _shown(self, table: pd.DataFrame) -> pd.DataFrame:
return table.iloc[-self.last_trials :]
def _draw_rates(self, table: pd.DataFrame, habituation: bool) -> None:
shown = self._shown(table)
if habituation or shown.empty:
self.performance_line.set_data([], [])
self.early_line.set_data([], [])
return
window = min(self.window, 5)
performance = table["correct"].rolling(self.window, min_periods=window).mean() * 100
early = (table["outcome"] == EARLY).astype(float).rolling(self.window, min_periods=window).mean() * 100
keep = slice(len(table) - len(shown), None)
self.performance_line.set_data(shown["trial"], performance.iloc[keep])
self.early_line.set_data(shown["trial"], early.iloc[keep])
def _draw_strip(self, table: pd.DataFrame, habituation: bool) -> None:
shown = self._shown(table)
self._x_limits(shown["trial"].max() if len(shown) else 0)
x = shown["trial"].to_numpy(dtype=float)
# the correct side, by modality and difficulty
lanes = np.where(shown["side"] == "left", LANE_LEFT, LANE_RIGHT)
has_side = shown["side"].notna().to_numpy()
colours = [
to_rgba(self._modality(m), DIFFICULTY_ALPHA.get(d, 1.0))
for m, d in zip(shown["modality"][has_side], shown["difficulty"][has_side])
]
self.stimulus_bars.set_verts(_bars(x[has_side], lanes[has_side]))
self.stimulus_bars.set_facecolors(colours)
# the outcome
self.outcome_bars.set_verts(_bars(x, np.full(len(x), LANE_OUTCOME)))
self.outcome_bars.set_facecolors([self.colors[o] for o in shown["outcome"]])
# the side the mouse chose
chose = shown["choice"].notna().to_numpy()
y = np.where(shown["choice"][chose] == "left", LANE_LEFT, LANE_RIGHT)
self.choice_dots.set_offsets(np.column_stack([x[chose], y]) if chose.any() else np.empty((0, 2)))
def _draw_summary(self, table: pd.DataFrame, habituation: bool) -> None:
if table.empty:
self.summary.set_text("No trials yet")
self.title.set_text("")
return
last = table.iloc[-1]
minutes = (table["end"].max() - table["start"].min()) / 60
recent = (table["start"] >= table["start"].max() - 600).sum()
lines = [
f"stage {last['stage']}",
f"trials {len(table)} ({recent} in the last 10 min)",
f"time {minutes:.0f} min",
f"water {np.nansum(table['water']):.0f} µl",
]
if not habituation:
counts = table["outcome"].value_counts()
lines += [
f"correct {np.nanmean(table['correct']) * 100:.0f}% (last {self.window}: "
f"{np.nanmean(table['correct'].iloc[-self.window :]) * 100:.0f}%)",
f"errors {counts.get(ERROR, 0)}",
f"timeouts {counts.get(TIMEOUT, 0)}",
f"early withdr. {counts.get(EARLY, 0)}",
f"holding time {last['holding_time']:.2f} s",
]
last_text = f"last trial: {last['side']} {last['difficulty']}, {last['outcome']}"
else:
sides = table["choice"].value_counts()
lines.append(f"went left/right {sides.get('left', 0)} / {sides.get('right', 0)}")
last_text = f"last trial: {last['choice'] or 'no side poke'}"
self.summary.set_text("\n".join(lines))
self.title.set_text(f"trial {int(last['trial'])}, {last_text}, updated {time.strftime('%H:%M:%S')}")
def _not_used(self, ax, habituation: bool) -> None:
"""A message in the panels that habituation does not use."""
if not hasattr(ax, "_habituation_text"):
ax._habituation_text = ax.text(
0.5, 0.5, "", transform=ax.transAxes, ha="center", va="center", fontsize="small",
color=self.colors["reference"],
) # fmt: skip
ax._habituation_text.set_text("not used in habituation" if habituation else "")
def _draw_choices(self, table: pd.DataFrame, habituation: bool) -> None:
self._not_used(self.ax_choices, habituation)
chose = table[table["choice"].notna() & table["side"].notna()]
sign = np.where(chose["side"] == "left", 1.0, -1.0)
evidence = chose["difficulty"].map(EVIDENCE).to_numpy(dtype=float) * sign
points = pd.DataFrame(
{"modality": chose["modality"].to_numpy(), "x": evidence, "left": (chose["choice"] == "left").to_numpy()}
).dropna(subset=["x"])
modalities = list(dict.fromkeys(points["modality"]))
for index, modality in enumerate(modalities):
group = points[points["modality"] == modality].groupby("x")["left"].agg(["mean", "size"])
# a little apart, so that the modalities do not hide each other
x = group.index.to_numpy() + 0.03 * (index - (len(modalities) - 1) / 2)
p, n = group["mean"].to_numpy(), group["size"].to_numpy()
error = np.sqrt(p * (1 - p) / n)
if modality not in self.choice_lines:
colour = self._modality(modality)
(line,) = self.ax_choices.plot([], [], marker="o", color=colour, label=modality, markersize=4)
bars = LineCollection([], colors=colour, linewidths=1)
self.ax_choices.add_collection(bars)
self.choice_lines[modality] = (line, bars)
self.ax_choices.legend(loc="upper left", fontsize="x-small", frameon=False)
line, bars = self.choice_lines[modality]
line.set_data(x, p)
bars.set_segments([[(xi, pi - e), (xi, pi + e)] for xi, pi, e in zip(x, p, error)])
for modality, (line, bars) in self.choice_lines.items():
if modality not in modalities:
line.set_data([], [])
bars.set_segments([])
def _draw_sides(self, table: pd.DataFrame, habituation: bool) -> None:
self._not_used(self.ax_sides, habituation)
for bar, text, side in zip(self.side_bars, self.side_texts, ("left", "right")):
trials = table[table["side"] == side]
performance = np.nanmean(trials["correct"]) * 100 if len(trials) else 0
timeouts = (trials["outcome"] == TIMEOUT).sum()
bar.set_height(performance)
text.set_y(performance + 2)
text.set_text(
""
if trials.empty
else f"{performance:.0f}%\nn={len(trials)}" + (f", {timeouts} t.o." if timeouts else "")
)
def _draw_wsls(self, table: pd.DataFrame, habituation: bool) -> None:
self._not_used(self.ax_wsls, habituation)
if habituation:
self.wsls_point.set_offsets(np.empty((0, 2)))
self.wsls_trail.set_data([], [])
self.wsls_text.set_text("")
return
win_stay, lose_switch, n_wins, n_losses = win_stay_lose_switch(table["choice"], table["correct"])
point = np.array([[lose_switch, win_stay]])
self.wsls_point.set_offsets(point if np.isfinite(point).all() else np.empty((0, 2)))
# blocks of 50 trials, in order
trail = []
for start in range(0, len(table), 50):
block = table.iloc[start : start + 50]
ws, ls, nw, nl = win_stay_lose_switch(block["choice"], block["correct"])
if nw >= 5 and nl >= 5:
trail.append((ls, ws))
self.wsls_trail.set_data([p[0] for p in trail], [p[1] for p in trail])
self.wsls_text.set_text(f"{n_wins} after correct, {n_losses} after error; line: blocks of 50")
def _bars(x: np.ndarray, lanes: np.ndarray) -> List[np.ndarray]:
"""A rectangle per trial, in its lane (one trial wide)."""
if len(x) == 0:
return []
left, right = x - 0.45, x + 0.45
bottom, top = lanes - 0.4, lanes + 0.4
return list(np.stack([np.column_stack([left, bottom]), np.column_stack([right, bottom]),
np.column_stack([right, top]), np.column_stack([left, top])], axis=1)) # fmt: skip
__all__ = ["OnlineSessionFigure", "online_trials_table", "trial_row", "win_stay_lose_switch"]