"""Plots of choices: psychometric curves, choices by difficulty, bias, win-stay / lose-switch."""
import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
from matplotlib.collections import LineCollection
from lecilab_behavior_analysis.common import column_checker
from lecilab_behavior_analysis.models.psychometric import fit_lapse_logistic_independent
from lecilab_behavior_analysis.style import cmap, color, group_colors, shows
[docs]
def psychometric_plot(
df: pd.DataFrame, x, y, ax: plt.Axes = None, point_kwargs=None, line_kwargs=None, valueType="discrete", bins=6
) -> plt.Axes:
if ax is None:
ax = plt.gca()
default_point_kwargs = {
"color": color("data"),
"markers": "o",
"errorbar": ("ci", 95),
"label": "Observed Choices",
"native_scale": True,
"linestyles": "",
"markersize": 5,
"capsize": 0.01,
"alpha": 1.0,
}
if point_kwargs is None:
point_kwargs = {}
point_kwargs = {**default_point_kwargs, **point_kwargs}
default_line_kwargs = {
"color": color("fit"),
"label": "Lapse Logistic Fit (Independent)",
"linestyle": "-",
"alpha": 1.0,
}
if line_kwargs is None:
line_kwargs = {}
line_kwargs = {**default_line_kwargs, **line_kwargs}
column_checker(df, required_columns={x, y})
df_copy = df.copy(deep=True)
if valueType == "discrete":
if 0 in df_copy[x].unique():
# if there are 0s in the data, we need to add a small value to avoid log(0)
df_copy[x + "_fit"] = df_copy[x]
df_copy[x + "_fit"].replace(0, 0.0001, inplace=True)
df_copy[x + "_fit"] = np.sign(df_copy[x]) * (np.log(abs(df_copy[x])).round(4))
ax.set_xlabel("log_" + x)
else:
# bin the continuous values when valueType is not discrete
# each value is replaced by the mean of its bin (bins may be empty,
# e.g. sound levels never close to 0)
bin_groups = pd.cut(df_copy[x], bins=bins)
df_copy[x + "_fit"] = df_copy[x].groupby(bin_groups, observed=True).transform("mean").astype(float)
# df_copy[x + "_fit"] = np.sign(df_copy[x + "_fit"]) * (np.log(abs(df_copy[x + "_fit"]*10)).round(4))
# ax.set_xlabel("log_" + x + "*10")
ax.set_xlabel(x + " (binned)")
sns.pointplot(x=x + "_fit", y=y, data=df_copy, estimator=lambda x: np.mean(x), ax=ax, **point_kwargs)
xs = np.linspace(df_copy[x + "_fit"].min(), df_copy[x + "_fit"].max(), 100).reshape(-1, 1)
p_left, (lapse_left, lapse_right, slope, bias) = fit_lapse_logistic_independent(df_copy[x + "_fit"], df_copy[y])
ax.plot(xs, p_left, **line_kwargs)
if y == "first_choice_numeric":
ax.set_ylabel("P(Leftward Choices)")
elif y == "correct_choice_numeric":
ax.set_ylabel("P(Correct Choices)")
ax.set_ylim(0, 1)
if shows("full"):
# the number of trials of each point, and the parameters of the fit
points = df_copy.groupby(x + "_fit")[y].agg(["mean", "size"])
for value, row in points.iterrows():
ax.annotate(
f"{row['size']:.0f}",
(value, row["mean"]),
xytext=(0, 6),
textcoords="offset points",
ha="center",
fontsize="xx-small",
color=color("text"),
)
ax.text(
0.98,
0.02,
f"lapses {lapse_left:.2f} / {lapse_right:.2f}\nslope {slope:.2f}\nbias {bias:.2f}",
ha="right",
va="bottom",
fontsize="x-small",
color=color("text"),
transform=ax.transAxes,
)
if shows("standard"):
ax.legend()
# remove legend box
ax.get_legend().get_frame().set_linewidth(0.0)
# despine
ax.spines[["top", "right"]].set_visible(False)
return ax
[docs]
def choice_by_difficulty_plot(df: pd.DataFrame, ax: plt.Axes = None, **kwargs) -> plt.Axes:
"""
Plot the performance by difficulty of each trial.
"""
column_checker(df, required_columns={"side_difficulty", "first_choice_numeric"})
if ax is None:
ax = plt.gca()
sns.pointplot(
x="side_difficulty",
y="first_choice_numeric",
data=df,
estimator=lambda x: np.nanmean(x),
ax=ax,
# remove line
linestyles="",
# do categorical
native_scale=False,
**{"color": color("data"), **kwargs},
)
ax.set_ylim(0, 1)
if shows("full"):
# the number of trials of each point (categorical axis: one position per level)
points = df.groupby("side_difficulty")["first_choice_numeric"].agg(["mean", "size"])
for position, (_, row) in enumerate(points.iterrows()):
ax.annotate(
f"{row['size']:.0f}",
(position, row["mean"]),
xytext=(0, 6),
textcoords="offset points",
ha="center",
fontsize="xx-small",
color=color("text"),
)
ax.set_ylabel("Leftward Choices")
ax.set_xlabel("Leftward Evidence Level")
# despine
ax.spines[["top", "right"]].set_visible(False)
return ax
[docs]
def bias_vs_trials_plot(df: pd.DataFrame, ax: plt.Axes = None) -> plt.Axes:
if ax is None:
ax = plt.gca()
column_checker(df, required_columns={"total_trial", "bias"})
sns.lineplot(data=df, x="total_trial", y="bias", ax=ax, color=color("data"))
ax.set_xlabel("Trial number")
ax.set_ylabel("Bias")
# set y ticks label to be -1, 0, 1
ax.set_yticks([-1, 0, 1])
ax.set_yticklabels(["left", "alternate", "right"])
ax.axhline(0, linestyle="--", color=color("reference"))
ax.spines[["top", "right"]].set_visible(False)
return ax
[docs]
def triangle_polar_plot(df_bias: pd.DataFrame, ax: plt.Axes = None) -> plt.Axes:
column_checker(df_bias, required_columns={"subject", "bias_angle", "percentage"})
if ax is None:
ax = plt.subplot(111, polar=True)
# Plot each subject in a polar plot
subjects = df_bias["subject"].unique()
for subject, subject_color in zip(subjects, group_colors(len(subjects))):
subject_data = df_bias[df_bias["subject"] == subject]
# Extract the angles and distances
angles = subject_data["bias_angle"].values
percentages = subject_data["percentage"].values
# Close the triangle by repeating the first point
angles = np.append(angles, angles[0])
percentages = np.append(percentages, percentages[0])
# Plot the triangle
ax.plot(angles, percentages, marker="o", linestyle="-", label=subject, color=subject_color)
# Set title and formatting
# ax.set_title(f"Animal biases", va='bottom', fontsize=16)
ax.set_rlabel_position(-22.5) # Adjust label position
ax.grid(True)
# make the circular 0.33 grid thicker
ax.yaxis.grid(True, color=color("reference"), linestyle="--", linewidth=0.5)
# plot the 0.33 grid
ax.set_yticks([0.25, 0.5])
ax.set_xticks([2 * np.pi / 4, 5 * np.pi / 4, 7 * np.pi / 4])
ax.set_xticklabels(["Alternate", "Left", "Right"], fontsize=14)
# Show the legend outside the plot
plt.legend(loc="upper right", bbox_to_anchor=(1.4, 0.8), ncol=1)
# remove border of legend box
plt.setp(ax.get_legend().get_frame(), linewidth=0) # Set legend frame color and linewidth
return ax
[docs]
def plot_decision_evolution_triangle(df: pd.DataFrame, hue: str, ax: plt.Axes = None, **kwargs) -> plt.Axes:
"""The older bias triangle (lines from points_to_lines_for_bias_evolution); see bias_triangle_plot."""
column_checker(df, required_columns={"left_right_bias", "alternating_bias", hue})
if ax is None:
ax = plt.gca()
if "palette" in kwargs:
palette = kwargs["palette"]
else:
palette = sns.color_palette(cmap("sequential"), as_cmap=True)
# plot the trajectory of the left_right_bias and alternating_bias through the sessions,
# without averaging the same values
sns.lineplot(
data=df,
x="left_right_bias",
y="alternating_bias",
ax=ax,
hue=hue,
palette=palette,
legend=False,
linewidth=3,
alpha=0.8,
)
# connect the points in the order of the session
# plt.plot(df_bias_pivot['xs'], df_bias_pivot['ys'], marker='o', linestyle='-')
# plot a triangle between -1 and 1 in the x axis and 0 and 1 in the y axis
triangle = np.array([[0, 1], [1, 0], [-1, 0], [0, 1]])
ax.plot(triangle[:, 0], triangle[:, 1], color=color("highlight"), linestyle="--")
# draw a dashed circle in 0, 0.5 of radius 0.1, no linestyle, fill it with black and alpha 0.1
circle = plt.Circle((0, 0.5), 0.1, color=color("highlight"), fill=True, alpha=0.1)
ax.add_artist(circle)
# label the triangle vertices
ax.text(0, 1.05, "Alternating", ha="center", va="center")
ax.text(1.05, -0.05, "Right", ha="center", va="center")
ax.text(-1.05, -0.05, "Left", ha="center", va="center")
# remove spines and ticks
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.spines["left"].set_visible(False)
ax.spines["bottom"].set_visible(False)
ax.set_xticks([])
ax.set_yticks([])
ax.set_xlabel("")
ax.set_ylabel("")
return ax
[docs]
def plot_filter_model_variables(corr_mat_list: list, norm_contribution_df: pd.DataFrame, **kwargs) -> plt.Axes:
"""Plot the mean correlation matrix and the mean contribution of each variable.
corr_mat_list: list of correlation matrices
norm_contribution_df: DataFrame with the normalized contribution of each variable
"""
fig, ax = plt.subplots(2, 1, figsize=(10, 10))
# get the variable names from the first correlation matrix
X = corr_mat_list[0].index
# Calculate the mean correlation matrix
corr_mat_mean = np.mean(np.stack(corr_mat_list), axis=0)
# # Create a mask for the upper triangle
# mask = np.triu(np.ones_like(corr_mat_mean, dtype=bool), k=1)
sns.heatmap(corr_mat_mean, ax=ax[0], cmap=cmap("diverging"), annot=True, fmt=".2f")
ax[0].set_xticklabels(X, rotation=16, ha="right", rotation_mode="anchor")
ax[0].set_yticklabels(X, rotation=8, ha="right", rotation_mode="anchor")
ax[0].set_title("Mean Correlation Matrix")
# Plot the mean contribution of each variable
norm_contribution_df.mean(axis=1).sort_values().plot(kind="barh", ax=ax[1])
ax[1].set_xlabel("Mean Contribution")
plt.tight_layout()
plt.show()
[docs]
def pointplot_stimulus_dual_dependence(
df,
x_variable,
column_name,
hue_variable,
ax=None,
folded=False,
x_label=None,
y_label=None,
estimator=np.mean,
):
"""Plot a pointplot showing the dependence of a column on the stimulus evidence,
with different lines for a different variable (e.g., overall dB)."""
if ax is None:
fig, ax = plt.subplots(figsize=(4, 3))
x = f"{x_variable}_abs" if folded else x_variable
x_label = x_variable if x_label is None else x_label
x_label = f"{x_label} (abs)" if folded else x_label
ax = sns.pointplot(
data=df,
x=x,
y=column_name,
hue=hue_variable,
dodge=True,
markers="o",
linestyles="-",
palette=cmap("diverging"),
native_scale=True,
ax=ax,
estimator=estimator,
)
ax.set_xlabel(x_label, size=14)
ax.set_ylabel(y_label if y_label is not None else column_name, size=14)
# change the size of the ticks using tick_params
ax.tick_params(axis="x", labelsize=12)
ax.tick_params(axis="y", labelsize=12)
# plt.xticks(rotation=45, ha='right')
# despine
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
# plt.tight_layout()
return ax
# more groups than this are colored from dark to yellow (legend: the first and the last)
MAX_LEGEND_ITEMS = 10
# the strategy of each corner of the win-stay / lose-switch square
WSLS_CORNERS = {
(1, 1): "win-stay\nlose-switch",
(0, 1): "always\nstay",
(1, 0): "always\nswitch",
(0, 0): "win-switch\nlose-stay",
}
def _draw_points(ax: plt.Axes, points: pd.DataFrame, x: str, y: str, hue, trajectory, palette, legend) -> None:
"""
The points of win_stay_lose_switch_plot and bias_triangle_plot: one
colour, a colour per value of hue, or a trajectory in the order of hue.
palette: a list of colours (or a colormap for the trajectory), or a dict
{value of hue: colour}, e.g. a fixed colour per mouse (every value in the
legend).
"""
if trajectory and len(points) > 1:
colormap = plt.get_cmap(palette or cmap("sequential"))
xy = points[[x, y]].to_numpy()
colors = colormap(np.linspace(0, 1, len(xy)))
segments = np.stack([xy[:-1], xy[1:]], axis=1)
ax.add_collection(LineCollection(segments, colors=colors[1:], linewidths=2.5, alpha=0.8))
ax.scatter(xy[:, 0], xy[:, 1], c=colors, s=12, zorder=3)
ax.scatter(*xy[0], s=50, facecolor="white", edgecolor=colors[0], linewidth=1.5, zorder=4, label="start")
ax.scatter(*xy[-1], s=50, color=colors[-1], edgecolor=color("highlight"), linewidth=0.8, zorder=4, label="end")
if legend:
ax.legend(loc="upper left", bbox_to_anchor=(1.0, 1.0), fontsize="x-small")
return
if hue is None:
ax.scatter(points[x], points[y], s=50, color=color("data"), edgecolor="white", zorder=3)
return
values = list(dict.fromkeys(points[hue]))
# up to 10 groups, a color each; more (e.g. days), from dark to yellow, with the first and last in the legend
many = len(values) > MAX_LEGEND_ITEMS and not isinstance(palette, dict)
if isinstance(palette, dict):
colors = [palette.get(value, color("neutral")) for value in values]
elif palette:
colors = sns.color_palette(palette, len(values))
else:
colors = group_colors(len(values), ordered=many)
for index, (value, point_color) in enumerate(zip(values, colors)):
group = points[points[hue] == value]
labelled = not many or index in (0, len(values) - 1)
ax.scatter(
group[x],
group[y],
s=30 if many else 50,
color=point_color,
edgecolor="white",
zorder=3,
label=value if labelled else None,
)
if legend and values:
ax.legend(title=hue, loc="upper left", bbox_to_anchor=(1.0, 1.0), fontsize="x-small")
def _number_of_trials(ax: plt.Axes, points: pd.DataFrame, x: str, y: str) -> None:
"""In the "full" style, the number of trials next to each point."""
if not shows("full") or "n_trials" not in points.columns:
return
for _, row in points.iterrows():
ax.annotate(
f"{row['n_trials']:.0f}",
(row[x], row[y]),
xytext=(4, 4),
textcoords="offset points",
fontsize="xx-small",
color=color("text"),
)
[docs]
def win_stay_lose_switch_plot(
df: pd.DataFrame,
hue: str = None,
ax: plt.Axes = None,
trajectory: bool = False,
palette=None,
legend: bool = True,
corners: bool = True,
) -> plt.Axes:
"""
Win-stay (y) against lose-switch (x) probabilities, in a square from 0
to 1: a point per row of df (from metrics.choices.get_win_stay_lose_switch_df),
e.g. one per session, per mouse or per group of trials. Chance (0.5) is
marked with dashed lines; a mouse that follows the win-stay / lose-switch
strategy is on the top right.
Args:
df: win_stay and lose_switch of each group (rows with NaN are left out).
hue: the column that colors the points ("session", "subject"...), with
a legend. More than 10 groups (e.g. days) go from dark to yellow,
and the legend shows the first and the last. None: one color.
trajectory: join the points in the order of hue (e.g. "trial_group",
through training), from dark (start) to yellow (end), as one line.
palette: colors of the points (a list, or a dict {value of hue:
color}, e.g. a fixed color per mouse), or the colormap of the
trajectory (default: the group colours and the sequential colormap
of the style, see style.py).
legend: show the legend of hue.
corners: write the strategy of each corner.
"""
column_checker(df, required_columns={"win_stay", "lose_switch"} | ({hue} if hue else set()))
if ax is None:
ax = plt.gca()
points = df.dropna(subset=["win_stay", "lose_switch"])
if hue is not None:
points = points.sort_values(hue)
ax.axhline(0.5, color=color("reference"), linestyle="--", linewidth=0.8, zorder=0)
ax.axvline(0.5, color=color("reference"), linestyle="--", linewidth=0.8, zorder=0)
if corners and shows("standard"):
for (x, y), name in WSLS_CORNERS.items():
ax.text(
0.03 if x == 0 else 0.97,
0.03 if y == 0 else 0.97,
name,
ha="left" if x == 0 else "right",
va="bottom" if y == 0 else "top",
color=color("reference"),
fontsize="x-small",
transform=ax.transAxes,
)
_draw_points(ax, points, "lose_switch", "win_stay", hue, trajectory, palette, legend)
_number_of_trials(ax, points, "lose_switch", "win_stay")
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.set_aspect("equal")
ax.set_xticks([0, 0.5, 1])
ax.set_yticks([0, 0.5, 1])
ax.set_xlabel("P(switch after error)\nlose-switch →")
ax.set_ylabel("win-stay →\nP(stay after correct)")
return ax
[docs]
def bias_triangle_plot(
df: pd.DataFrame,
hue: str = None,
ax: plt.Axes = None,
trajectory: bool = False,
palette=None,
legend: bool = True,
corners: bool = True,
) -> plt.Axes:
"""
Side and alternation bias in a triangle: a point per row of df (from
metrics.choices.get_bias_evolution_df), e.g. one per mouse, per session
or per group of trials. The corners are always left, always right and
always alternating; a mouse that chooses at random is in the circle (it
alternates half of the time, and repeats to each side a quarter).
Args:
df: left_right_bias (x: the fraction of right minus left repetitions,
-1 to 1) and alternating_bias (y: the fraction of alternations, 0
to 1) of each group. With n_trials, the "full" style writes it
next to each point.
hue, trajectory, palette, legend: as in win_stay_lose_switch_plot.
corners: name the corners (in the "publication" style they are not).
"""
column_checker(df, required_columns={"left_right_bias", "alternating_bias"} | ({hue} if hue else set()))
if ax is None:
ax = plt.gca()
points = df.dropna(subset=["left_right_bias", "alternating_bias"])
if hue is not None:
points = points.sort_values(hue)
triangle = np.array([[0, 1], [1, 0], [-1, 0], [0, 1]])
ax.plot(triangle[:, 0], triangle[:, 1], color=color("reference"), linestyle="--", linewidth=0.8, zorder=0)
# choosing at random: alternate half of the time, repeat to each side a quarter
ax.add_patch(plt.Circle((0, 0.5), 0.1, color=color("reference"), fill=True, alpha=0.15, zorder=0))
if corners and shows("standard"):
ax.text(0, 1.05, "Alternate", ha="center", va="bottom", color=color("text"))
ax.text(1, -0.05, "Right", ha="center", va="top", color=color("text"))
ax.text(-1, -0.05, "Left", ha="center", va="top", color=color("text"))
_draw_points(ax, points, "left_right_bias", "alternating_bias", hue, trajectory, palette, legend)
_number_of_trials(ax, points, "left_right_bias", "alternating_bias")
ax.set_xlim(-1.15, 1.15)
ax.set_ylim(-0.12, 1.12)
ax.set_aspect("equal")
ax.spines[["top", "right", "left", "bottom"]].set_visible(False)
ax.set_xticks([])
ax.set_yticks([])
ax.set_xlabel("")
ax.set_ylabel("")
return ax