-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot_test.py
More file actions
3828 lines (3378 loc) · 105 KB
/
plot_test.py
File metadata and controls
3828 lines (3378 loc) · 105 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import textwrap
from pathlib import Path
import os
import re
import matplotlib as mpl
from matplotlib.collections import LineCollection
import matplotlib.patches as patches
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from scipy.optimize import minimize
from scipy import stats
from scipy.special import expit
from statsmodels.tsa.stattools import acf
import behavior_utils
DEFAULT_SVG_SAVE_DIR = r"E:\data\LeciLab\behavioral_data\tmp"
def _resolve_save_dir(save_dir=DEFAULT_SVG_SAVE_DIR):
save_dir = str(save_dir)
windows_drive = re.match(r"^([A-Za-z]):[\\/](.*)$", save_dir)
if os.name != "nt" and windows_drive:
drive = windows_drive.group(1).lower()
rest = windows_drive.group(2).replace("\\", "/")
return Path("/mnt") / drive / rest
return Path(save_dir)
def _slug(text):
text = str(text)
text = re.sub(r"[^\w.-]+", "_", text)
text = re.sub(r"_+", "_", text).strip("_")
return text or "figure"
def _figure_title_parts(fig):
title_parts = []
suptitle = getattr(fig, "_suptitle", None)
if suptitle is not None and suptitle.get_text():
title_parts.append(suptitle.get_text())
for ax in fig.axes:
for text in [ax.get_title(), ax.get_ylabel()]:
if text and not text.startswith("State t"):
title_parts.append(text)
clean_parts = []
seen = set()
for title in title_parts:
title = str(title).strip()
if title and title not in seen:
clean_parts.append(title)
seen.add(title)
return clean_parts
def figure_title_filename(fig, fallback="figure", max_len=180):
title_parts = _figure_title_parts(fig)
filename = "_".join(title_parts) if title_parts else str(fallback)
filename = _slug(filename)
if len(filename) > max_len:
filename = filename[:max_len].rstrip("_.-")
return filename or _slug(fallback)
def _unique_filename(filename, used_names):
filename = _slug(filename)
stem = filename[:-4] if filename.lower().endswith(".svg") else filename
candidate = stem
counter = 2
while candidate in used_names:
candidate = f"{stem}_{counter:02d}"
counter += 1
used_names.add(candidate)
return f"{candidate}.svg"
def save_figure_svg(
fig,
filename,
save_dir=DEFAULT_SVG_SAVE_DIR,
enabled=True,
subfolder=None,
):
if not enabled:
return None
save_path = _resolve_save_dir(save_dir)
if subfolder is not None:
save_path = save_path / _slug(subfolder)
save_path.mkdir(parents=True, exist_ok=True)
filename = _slug(filename)
if not filename.lower().endswith(".svg"):
filename = f"{filename}.svg"
out_path = save_path / filename
fig.savefig(out_path, format="svg", bbox_inches="tight", dpi = 150)
return out_path
def save_figures_svg(
figures,
prefix,
save_dir=DEFAULT_SVG_SAVE_DIR,
enabled=True,
use_titles=True,
):
if not enabled:
return []
saved_paths = []
batch_dir = _resolve_save_dir(save_dir) / _slug(prefix)
used_names = set()
if isinstance(figures, dict):
iterable = figures.items()
else:
iterable = enumerate(figures)
for key, fig in iterable:
if use_titles:
filename = figure_title_filename(fig, fallback=f"{prefix}_{key}")
else:
filename = f"{prefix}_{key}"
filename = _unique_filename(filename, used_names)
saved_path = save_figure_svg(
fig,
filename,
save_dir=batch_dir,
enabled=enabled,
)
if saved_path is not None:
saved_paths.append(saved_path)
return saved_paths
def p_to_star(p_value):
if p_value is None or not np.isfinite(p_value):
return "ns"
if p_value < 0.001:
return "***"
if p_value < 0.01:
return "**"
if p_value < 0.05:
return "*"
return "ns"
def add_paired_significance_label(
ax,
values_left,
values_right,
label,
x0=0,
x1=1,
):
values = pd.to_numeric(
pd.concat(
[
pd.Series(values_left),
pd.Series(values_right),
],
ignore_index=True,
),
errors="coerce",
).dropna()
if values.empty:
y = 1
h = 0.05
else:
y_min = values.min()
y_max = values.max()
y_range = y_max - y_min
if not np.isfinite(y_range) or y_range == 0:
y_range = max(abs(y_max), 1) * 0.1
y = y_max + y_range * 0.08
h = y_range * 0.04
ax.plot([x0, x0, x1, x1], [y, y + h, y + h, y], color="black", linewidth=1)
ax.text(
(x0 + x1) / 2,
y + h,
label,
ha="center",
va="bottom",
fontsize=11,
color="black",
)
ax.set_ylim(bottom=0, top=max(y + h * 3, 1e-6))
def _state_colors(n_states, colors=None):
if colors is not None and len(colors) >= n_states:
return list(colors)
default_colors = [plt.get_cmap("tab10")(i % 10) for i in range(n_states)]
if colors is None:
return default_colors
colors = list(colors)
return colors + default_colors[len(colors):]
def _condition_from_observation(observation):
observation = str(observation).lower()
if "dcz" in observation:
return "DCZ"
if "saline" in observation:
return "saline"
return None
def _pretty_label(label, width=18):
label = str(label).replace("_", " ")
return "\n".join(textwrap.wrap(label, width=width)) or label
def plot_filter_model_variables(
corr_mat_list: list,
norm_contribution_df: pd.DataFrame,
title=None,
figsize=None,
cmap="vlag",
show_subject_points=True,
label_width=18,
):
"""Plot model-variable correlations and normalized contributions.
This is a prettier drop-in replacement for
lecilab_behavior_analysis.plots.plot_filter_model_variables.
It accepts the same two core inputs but returns the matplotlib figure.
"""
if not corr_mat_list:
raise ValueError("corr_mat_list is empty")
if norm_contribution_df.empty:
raise ValueError("norm_contribution_df is empty")
variables = list(corr_mat_list[0].index)
corr_stack = np.stack(
[
corr_mat.reindex(index=variables, columns=variables).to_numpy()
for corr_mat in corr_mat_list
]
)
corr_mean = np.nanmean(corr_stack, axis=0)
corr_mean_df = pd.DataFrame(corr_mean, index=variables, columns=variables)
contrib_mean = norm_contribution_df.mean(axis=1).sort_values()
contrib_sem = norm_contribution_df.sem(axis=1).reindex(contrib_mean.index)
n_vars = len(variables)
if figsize is None:
figsize = (
max(8.0, 0.75 * n_vars + 4.5),
max(8.5, 0.52 * n_vars + 6.0),
)
fig = plt.figure(figsize=figsize, dpi=160)
gs = fig.add_gridspec(
nrows=2,
ncols=1,
height_ratios=[1.15, 0.95],
hspace=0.42,
)
ax_corr = fig.add_subplot(gs[0, 0])
ax_contrib = fig.add_subplot(gs[1, 0])
mask = np.triu(np.ones_like(corr_mean_df, dtype=bool), k=1)
tick_labels = [_pretty_label(var, width=label_width) for var in variables]
sns.heatmap(
corr_mean_df,
mask=mask,
ax=ax_corr,
cmap=cmap,
vmin=-1,
vmax=1,
center=0,
square=True,
linewidths=0.6,
linecolor="white",
annot=True,
fmt=".2f",
annot_kws={"fontsize": 7},
cbar_kws={"label": "Mean r", "shrink": 0.75},
)
ax_corr.set_title("Mean Predictor Correlation", fontsize=12, pad=10)
ax_corr.set_xticklabels(tick_labels, rotation=35, ha="right")
ax_corr.set_yticklabels(tick_labels, rotation=0)
ax_corr.tick_params(axis="both", length=0, labelsize=8)
y_pos = np.arange(len(contrib_mean))
bar_colors = sns.color_palette("crest", len(contrib_mean))
ax_contrib.barh(
y_pos,
contrib_mean.values,
xerr=contrib_sem.values if norm_contribution_df.shape[1] > 1 else None,
color=bar_colors,
edgecolor="0.25",
linewidth=0.4,
alpha=0.9,
error_kw={"elinewidth": 1, "capsize": 2, "ecolor": "0.25"},
)
if show_subject_points:
rng = np.random.default_rng(0)
for y_idx, var in enumerate(contrib_mean.index):
values = pd.to_numeric(
norm_contribution_df.loc[var],
errors="coerce",
).dropna()
jitter = rng.normal(0, 0.055, size=len(values))
ax_contrib.scatter(
values,
y_idx + jitter,
s=18,
color="black",
alpha=0.45,
linewidth=0,
zorder=3,
)
ax_contrib.set_yticks(y_pos)
ax_contrib.set_yticklabels(
[_pretty_label(var, width=label_width) for var in contrib_mean.index],
fontsize=9,
)
ax_contrib.set_xlabel("Normalized contribution", fontsize=10)
ax_contrib.set_title("Drop-One Variable Contribution", fontsize=12, pad=10)
ax_contrib.grid(axis="x", color="0.88", linewidth=0.8)
ax_contrib.set_axisbelow(True)
ax_contrib.spines[["top", "right", "left"]].set_visible(False)
ax_contrib.tick_params(axis="y", length=0)
if title:
fig.suptitle(title, fontsize=14, y=0.995)
fig.tight_layout()
return fig
def _fit_logistic_probability(x, y, x_grid):
x = np.asarray(x, dtype=float)
y = np.asarray(y, dtype=float)
valid = np.isfinite(x) & np.isfinite(y)
x = x[valid]
y = y[valid]
if len(x) < 3 or len(np.unique(x)) < 2:
return None
x_mean = np.mean(x)
x_std = np.std(x)
if not np.isfinite(x_std) or x_std == 0:
return None
x_scaled = (x - x_mean) / x_std
def neg_log_likelihood(params):
logits = params[0] + params[1] * x_scaled
p = np.clip(expit(logits), 1e-6, 1 - 1e-6)
return -np.sum(y * np.log(p) + (1 - y) * np.log(1 - p))
result = minimize(
neg_log_likelihood,
x0=np.array([0.0, 1.0]),
method="BFGS",
)
if not result.success and not np.isfinite(result.fun):
return None
x_grid_scaled = (np.asarray(x_grid, dtype=float) - x_mean) / x_std
return expit(result.x[0] + result.x[1] * x_grid_scaled)
def _psychometric_group_columns(df, preferred=None):
if preferred is not None:
return [column for column in preferred if column in df.columns]
group_cols = []
for column in ["subject", "year_month_day", "session"]:
if column in df.columns:
group_cols.append(column)
return group_cols
def _filter_paired_psychometric_trials(
df,
paired_dates,
subject_col="subject",
date_col="year_month_day",
):
if paired_dates is None or paired_dates.empty:
return df.copy()
if subject_col not in df.columns or date_col not in df.columns:
return pd.DataFrame()
df_copy = df.copy()
df_copy["_psych_date_key"] = pd.to_datetime(
df_copy[date_col],
errors="coerce",
).dt.strftime("%Y-%m-%d")
df_copy[subject_col] = df_copy[subject_col].astype(str)
pair_rows = []
for _, pair_row in paired_dates.iterrows():
subject = str(pair_row[subject_col])
pair_id = pair_row["pair_id"]
for condition, date_column in [
("saline", "saline_date"),
("DCZ", "DCZ_date"),
]:
date_key = pd.to_datetime(
pair_row[date_column],
errors="coerce",
).strftime("%Y-%m-%d")
pair_df = df_copy[
(df_copy[subject_col] == subject)
& (df_copy["_psych_date_key"] == date_key)
].copy()
if pair_df.empty:
continue
pair_df["_psych_pair_id"] = pair_id
pair_df["observation_group"] = condition
pair_rows.append(pair_df)
if not pair_rows:
return pd.DataFrame()
paired_df = pd.concat(pair_rows, ignore_index=True)
complete_pair_ids = (
paired_df.groupby("_psych_pair_id")["observation_group"]
.nunique()
.loc[lambda counts: counts >= 2]
.index
)
return paired_df[
paired_df["_psych_pair_id"].isin(complete_pair_ids)
].copy()
def plot_condition_psychometric_curves(
df,
group_name,
x_col="total_evidence_strength",
y_col="first_choice_numeric",
observation_col="observations",
paired_dates=None,
group_cols=None,
min_trials=20,
colors=None,
figsize=(6, 4),
ax=None,
valueType="continue",
bins=6,
log=False,
):
import utils_test
colors = colors or {"saline": "blue", "DCZ": "red"}
if ax is None:
fig, ax = plt.subplots(figsize=figsize)
else:
fig = ax.figure
required_cols = {x_col, y_col, observation_col}
missing_cols = required_cols - set(df.columns)
if missing_cols:
ax.text(
0.5,
0.5,
f"Missing columns: {sorted(missing_cols)}",
ha="center",
va="center",
transform=ax.transAxes,
)
ax.set_axis_off()
return fig, pd.DataFrame()
if paired_dates is not None:
plot_df = _filter_paired_psychometric_trials(
df,
paired_dates,
)
else:
plot_df = df.copy()
plot_df["observation_group"] = plot_df[observation_col].apply(
_condition_from_observation
)
plot_df = plot_df.dropna(subset=[x_col, y_col, "observation_group"])
plot_df[y_col] = pd.to_numeric(plot_df[y_col], errors="coerce")
plot_df[x_col] = pd.to_numeric(plot_df[x_col], errors="coerce")
plot_df = plot_df.dropna(subset=[x_col, y_col])
if plot_df.empty:
ax.text(
0.5,
0.5,
f"No saline/DCZ psychometric data for {group_name}",
ha="center",
va="center",
transform=ax.transAxes,
)
ax.set_axis_off()
return fig, pd.DataFrame()
if paired_dates is not None:
group_cols = ["_psych_pair_id"]
else:
group_cols = _psychometric_group_columns(plot_df, preferred=group_cols)
if not group_cols:
group_cols = ["observation_group"]
summary_rows = []
label_added = {"saline": False, "DCZ": False}
for group_keys, df_one in plot_df.groupby(group_cols + ["observation_group"], sort=True):
if len(df_one) < min_trials:
continue
if not isinstance(group_keys, tuple):
group_keys = (group_keys,)
condition = group_keys[-1]
try:
utils_test.psychometric_plot_easy_logistic(
df_one,
x=x_col,
y=y_col,
ax=ax,
point_kwargs={
"color": colors.get(condition, "gray"),
"alpha": 0.12,
"label": "_nolegend_",
"markersize": 3,
},
line_kwargs={
"color": colors.get(condition, "gray"),
"alpha": 0.55,
"linewidth": 1.4,
"label": condition
if not label_added.get(condition, False)
else "_nolegend_",
},
valueType=valueType,
bins=bins,
log=log,
)
except Exception:
continue
label_added[condition] = True
row = {
"group": group_name,
"condition": condition,
"n_trials": len(df_one),
}
for column, value in zip(group_cols, group_keys[:-1]):
row[column] = value
summary_rows.append(row)
ax.set_title(f"{group_name} saline/DCZ psychometric curves")
ax.set_xlabel(x_col)
ax.set_ylabel("P(left choice)")
ax.set_ylim(0, 1)
ax.spines[["top", "right"]].set_visible(False)
ax.grid(alpha=0.25)
if any(label_added.values()):
handles, labels = ax.get_legend_handles_labels()
legend_items = []
seen_labels = set()
for handle, label in zip(handles, labels):
if label in {"_nolegend_", ""} or label in seen_labels:
continue
legend_items.append((handle, label))
seen_labels.add(label)
if legend_items:
ax.legend(
[item[0] for item in legend_items],
[item[1] for item in legend_items],
frameon=False,
)
elif ax.get_legend() is not None:
ax.get_legend().remove()
else:
ax.text(
0.5,
0.5,
"No paired sessions with enough trials.",
ha="center",
va="center",
transform=ax.transAxes,
)
fig.tight_layout()
return fig, pd.DataFrame(summary_rows)
def plot_traj_speed(df_bp, cmap, ax, norm):
"""
df_bp: DataFrame with columns ['x', 'y', 'mean_speed'] (no NaNs).
Plot trajectory as colored line segments based on speed.
"""
x = df_bp['x'].to_numpy()
y = df_bp['y'].to_numpy()
sp = df_bp['mean_speed'].to_numpy()
# Line segments with shape (N-1, 2, 2)
points = np.column_stack([x, y]).reshape(-1, 1, 2)
segs = np.concatenate([points[:-1], points[1:]], axis=1)
# Speed per segment (using the average of start and end speeds)
sp_seg = (sp[:-1] + sp[1:]) / 2.0
lc = LineCollection(segs, cmap=cmap, norm=norm)
lc.set_array(sp_seg)
lc.set_linewidth(7)
lc.set_capstyle('round')
lc.set_joinstyle('round')
ax.add_collection(lc)
# # Mark start and end points
# ax.scatter(x[0], y[0], color='k', s=200, marker='o',
# edgecolors='k', zorder=3)
# ax.scatter(x[-1], y[-1], color='w', s=200, marker='o',
# edgecolors='k', zorder=3)
def _normalize_from_values(values, quantiles=(0.01, 0.99), default=(0, 1)):
values = np.asarray(values, dtype=float)
values = values[np.isfinite(values)]
if len(values) == 0:
return mpl.colors.Normalize(vmin=default[0], vmax=default[1])
vmin = np.nanquantile(values, quantiles[0])
vmax = np.nanquantile(values, quantiles[1])
if not np.isfinite(vmin) or not np.isfinite(vmax):
vmin, vmax = default
if vmin == vmax:
vmax = vmin + 1
return mpl.colors.Normalize(vmin=vmin, vmax=vmax)
def prep_traj_speed_df(dlc_df, bodypart="Center"):
return (
dlc_df[bodypart][["x", "y", "mean_speed"]]
.apply(pd.to_numeric, errors="coerce")
.interpolate(limit_direction="both")
.dropna()
.copy()
)
def plot_pair_occupancy(
pair_id,
behav_df_dic_saline,
behav_df_dic_dcz,
roi_left,
roi_right,
roi_bottom,
roi_top,
bodypart="Center",
timestamp_col=("timestamp", ""),
xbins=15,
ybins=15,
cmap="viridis",
figsize=(10, 5),
quantiles=(0.01, 0.99),
interpolation="gaussian",
):
pair_dcz = behav_df_dic_dcz[pair_id]
pair_saline = behav_df_dic_saline[pair_id]
occ_dcz = behavior_utils.occupancy_map(
pair_dcz[(bodypart, "x")],
pair_dcz[(bodypart, "y")],
pair_dcz[timestamp_col],
xbins=xbins,
ybins=ybins,
)
occ_saline = behavior_utils.occupancy_map(
pair_saline[(bodypart, "x")],
pair_saline[(bodypart, "y")],
pair_saline[timestamp_col],
xbins=xbins,
ybins=ybins,
)
pair_extents = (
np.nanmin([
pair_dcz[(bodypart, "x")].min(),
pair_saline[(bodypart, "x")].min(),
]),
np.nanmax([
pair_dcz[(bodypart, "x")].max(),
pair_saline[(bodypart, "x")].max(),
]),
np.nanmin([
pair_dcz[(bodypart, "y")].min(),
pair_saline[(bodypart, "y")].min(),
]),
np.nanmax([
pair_dcz[(bodypart, "y")].max(),
pair_saline[(bodypart, "y")].max(),
]),
)
pair_occ_values = np.concatenate([
occ_dcz.ravel(),
occ_saline.ravel(),
])
pair_occ_norm = _normalize_from_values(pair_occ_values, quantiles=quantiles)
pair_occ_fig, pair_occ_axes = plt.subplots(
1,
2,
figsize=figsize,
sharex=True,
sharey=True,
)
pair_occ_im0 = pair_occ_axes[0].imshow(
occ_saline.T,
origin="lower",
extent=pair_extents,
cmap=cmap,
norm=pair_occ_norm,
interpolation=interpolation,
)
pair_occ_axes[0].set_title(f"{pair_id} saline", fontsize=10)
pair_occ_im1 = pair_occ_axes[1].imshow(
occ_dcz.T,
origin="lower",
extent=pair_extents,
cmap=cmap,
norm=pair_occ_norm,
interpolation=interpolation,
)
pair_occ_axes[1].set_title(f"{pair_id} DCZ", fontsize=10)
for pair_occ_ax in pair_occ_axes:
pair_roi_rect = patches.Rectangle(
(roi_left, roi_bottom),
roi_right - roi_left,
roi_top - roi_bottom,
linewidth=1.5,
edgecolor="white",
facecolor="none",
linestyle="--",
)
pair_occ_ax.add_patch(pair_roi_rect)
pair_occ_ax.set_aspect("equal")
pair_occ_ax.set_xlim(0, 640)
pair_occ_ax.set_ylim(0, 480)
pair_occ_ax.set_xticks([])
pair_occ_ax.set_yticks([])
pair_occ_axes[0].invert_yaxis()
pair_occ_fig.colorbar(
pair_occ_im1,
ax=pair_occ_axes,
label="occupancy (s/pixels)",
shrink=0.7,
fraction=0.04,
pad=0.02,
extend="both",
)
return pair_occ_fig
def plot_pair_traj_speed(
pair_id,
behav_df_dic_saline,
behav_df_dic_dcz,
bodypart="Center",
cmap="inferno",
figsize=(12, 6),
quantiles=(0.01, 0.99),
invert_y=True,
):
pair_dcz = behav_df_dic_dcz[pair_id]
pair_saline = behav_df_dic_saline[pair_id]
pair_dcz_traj = prep_traj_speed_df(pair_dcz, bodypart=bodypart)
pair_saline_traj = prep_traj_speed_df(pair_saline, bodypart=bodypart)
pair_speed_values = pd.concat(
[
pair_dcz_traj["mean_speed"],
pair_saline_traj["mean_speed"],
],
ignore_index=True,
).dropna()
pair_speed_norm = _normalize_from_values(
pair_speed_values,
quantiles=quantiles,
)
pair_traj_fig, pair_traj_axes = plt.subplots(
1,
2,
figsize=figsize,
sharex=True,
sharey=True,
)
plot_traj_speed(
pair_saline_traj,
cmap=cmap,
ax=pair_traj_axes[0],
norm=pair_speed_norm,
)
pair_traj_axes[0].set_title(f"{pair_id} saline")
plot_traj_speed(
pair_dcz_traj,
cmap=cmap,
ax=pair_traj_axes[1],
norm=pair_speed_norm,
)
pair_traj_axes[1].set_title(f"{pair_id} DCZ")
for pair_traj_ax in pair_traj_axes:
pair_traj_ax.set_aspect("equal")
pair_traj_ax.autoscale()
pair_traj_ax.set_xlim(0, 640)
pair_traj_ax.set_ylim(0, 480)
pair_traj_ax.set_xticks([])
pair_traj_ax.set_yticks([])
if invert_y:
pair_traj_axes[0].invert_yaxis()
pair_speed_sm = mpl.cm.ScalarMappable(
norm=pair_speed_norm,
cmap=cmap,
)
pair_traj_fig.colorbar(
pair_speed_sm,
ax=pair_traj_axes,
label="mean speed (pixels/s)",
shrink=0.6,
)
return pair_traj_fig
def plot_paired_behavior_figures(
pair_ids,
behav_df_dic_saline,
behav_df_dic_dcz,
roi_left,
roi_right,
roi_bottom,
roi_top,
bodypart="Center",
):
figures = []
for pair_id in pair_ids:
figures.append(
plot_pair_occupancy(
pair_id=pair_id,
behav_df_dic_saline=behav_df_dic_saline,
behav_df_dic_dcz=behav_df_dic_dcz,
roi_left=roi_left,
roi_right=roi_right,
roi_bottom=roi_bottom,
roi_top=roi_top,
bodypart=bodypart,
)
)
figures.append(
plot_pair_traj_speed(
pair_id=pair_id,
behav_df_dic_saline=behav_df_dic_saline,
behav_df_dic_dcz=behav_df_dic_dcz,
bodypart=bodypart,
)
)
return figures
def plot_stationary_time_ratio_groups(
stationary_time_ratio_summary,
hM4Di_mice,
hM3Dq_mice,
figsize=(8, 5),
):
plot_df = stationary_time_ratio_summary.copy()
if "subject" not in plot_df.columns:
plot_df["subject"] = plot_df["pair_id"].astype(str).str[:6]
fig, axes = plt.subplots(1, 2, figsize=figsize, sharey=True)
def _plot_group(ax, mice, group_name):
group_df = plot_df[
plot_df["subject"].isin(mice)
].dropna(subset=["saline", "DCZ"]).copy()
for _, row in group_df.iterrows():
ax.plot(
[0, 1],
[row["saline"], row["DCZ"]],
color="gray",
alpha=0.4,
linewidth=1,
)
ax.scatter(
[0] * len(group_df),
group_df["saline"],
color="blue",
edgecolor="black",
label="saline",
zorder=3,
)
ax.scatter(
[1] * len(group_df),
group_df["DCZ"],
color="red",
edgecolor="black",
label="DCZ",
zorder=3,
)
if len(group_df) > 0:
try:
p_value = stats.wilcoxon(
group_df["saline"],
group_df["DCZ"],
).pvalue
p_text = f"p={p_value:.3g}"
except ValueError:
p_value = np.nan
p_text = "p=NA"
else:
p_value = np.nan
p_text = "p=NA"
ax.set_xticks([0, 1])
ax.set_xticklabels(["saline", "DCZ"])
ax.set_title(f"{group_name}, n={len(group_df)}, {p_text}")
add_paired_significance_label(
ax,
group_df["saline"],
group_df["DCZ"],
p_to_star(p_value),
)
ax.grid(axis="y", alpha=0.3)
return group_df
hm4_df = _plot_group(axes[0], hM4Di_mice, "hM4Di")
hm3_df = _plot_group(axes[1], hM3Dq_mice, "hM3Dq")
axes[0].set_ylabel("fraction of time stationary")
fig.tight_layout()
return fig, hm4_df, hm3_df
def _speed_trace_df(
behav_df,
bodypart="Center",
speed_col="mean_speed",
timestamp_col=("timestamp", ""),
):
speed = pd.to_numeric(
behavior_utils.get_behavior_column(behav_df, (bodypart, speed_col)),
errors="coerce",
)
try:
x_values = pd.to_numeric(
behavior_utils.get_behavior_column(behav_df, timestamp_col),
errors="coerce",
)
x_label = "time (s)"
except KeyError:
x_values = pd.Series(np.arange(len(speed)), index=speed.index)
x_label = "frame"
trace_df = pd.DataFrame(
{
"x": x_values.to_numpy(),
"speed": speed.to_numpy(),
}
)
trace_df = trace_df.dropna(subset=["x", "speed"]).reset_index(drop=True)