-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot_head_direction.py
More file actions
2114 lines (1995 loc) · 99.3 KB
/
plot_head_direction.py
File metadata and controls
2114 lines (1995 loc) · 99.3 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
#!/usr/bin/env python3
"""
Head direction analysis from snout + left/right ears (data3D.csv).
Uses the triangle (Snout, EarL, EarR) to compute head direction angle in the camera (u,v) plane.
Outputs: trajectory_analysis/<animal>/head_direction/ including average head-direction heatmaps
by phase (early, mid, late).
Requires data3D.csv per trial (Snout, EarL, EarR) and calibration for 3D→2D projection.
"""
from pathlib import Path
import argparse
import json
import re
import sys
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy import stats
_script_dir = Path(__file__).resolve().parent
if str(_script_dir) not in sys.path:
sys.path.insert(0, str(_script_dir))
sys.path.insert(0, str(_script_dir / "predictions3D"))
import analyze_trajectories as at
from plot_trajectory_on_frame import load_calib, project_3d_to_2d
from plot_trajectory_xy import parse_data3d_csv
# Trial folder name pattern
TRIAL_PATTERN = re.compile(r"^Predictions_3D_trial_(\d+)_(\d+)-(\d+)$")
# Reward frame lookup: import from midline-and-goals pipeline when available
def _get_reward_frame_by_trial(
trials_list: list[tuple[Path, str, str | None]],
reward_times_path: Path,
logs_dir: Path | None,
animal: str,
) -> dict[str, int]:
"""Return dict trial_id -> reward_frame. Uses plot_flow_field_rory helpers if available."""
reward_frame_by_trial: dict[str, int] = {}
try:
from plot_flow_field_rory import _get_reward_frame_from_csv, _get_reward_frame_per_trial
except ImportError:
return reward_frame_by_trial
reward_times_path = Path(reward_times_path)
if reward_times_path.is_file():
reward_frame_by_trial = _get_reward_frame_from_csv(trials_list, reward_times_path)
if not reward_frame_by_trial and logs_dir is not None and Path(logs_dir).is_dir():
reward_frame_by_trial = _get_reward_frame_per_trial(trials_list, Path(logs_dir), animal)
return reward_frame_by_trial
def get_animal_trials(predictions_dir: Path, animal: str) -> list[tuple[Path, str, str | None]]:
"""Return list of (csv_path, trial_id, session_folder) for the given animal."""
animal_lower = animal.strip().lower()
all_trials = at.find_trajectory_csvs(predictions_dir)
return [t for t in all_trials if t[2] and t[2].lower().startswith(f"{animal_lower}_")]
def _split_phase_trials(
trials_list: list[tuple[Path, str, str | None]],
) -> tuple[list[tuple[Path, str, str | None]], list[tuple[Path, str, str | None]], list[tuple[Path, str, str | None]]]:
"""Return (early, mid, late) thirds when ordered chronologically (session_folder, trial_id)."""
if not trials_list:
return [], [], []
ordered = sorted(trials_list, key=lambda t: ((t[2] or ""), t[1]))
n = len(ordered)
k = max(1, n // 3)
early = ordered[:k]
mid = ordered[k : 2 * k] if 2 * k <= n else []
late = ordered[2 * k :] if 2 * k < n else []
return (early, mid, late)
def _resolve_calib_path(trial_dir: Path, calib_root: Path | None, camera: str) -> Path | None:
"""Resolve calibration path for a trial: info.yaml dataset_name under calib_root, or direct path."""
info_path = trial_dir / "info.yaml"
if not info_path.exists():
return None
try:
import yaml
with open(info_path) as f:
info = yaml.safe_load(f)
except Exception:
return None
dataset_name = info.get("dataset_name")
if not dataset_name:
return None
# If dataset_name is already an absolute path, use it
base = Path(dataset_name)
if base.is_absolute():
calib_path = base / f"{camera}.yaml"
elif calib_root is not None:
calib_path = Path(calib_root) / dataset_name / f"{camera}.yaml"
else:
calib_path = base / f"{camera}.yaml"
return calib_path.resolve() if calib_path.exists() else None
def _head_angle_deg_from_triangle(snout_uv: np.ndarray, earL_uv: np.ndarray, earR_uv: np.ndarray) -> np.ndarray:
"""Head direction angle in degrees (0 = right/u+, 90 = down/v+ in image coords).
Angle from ear midpoint toward snout in the u-v plane."""
mid_u = (earL_uv[:, 0] + earR_uv[:, 0]) / 2
mid_v = (earL_uv[:, 1] + earR_uv[:, 1]) / 2
du = snout_uv[:, 0] - mid_u
dv = snout_uv[:, 1] - mid_v
rad = np.arctan2(dv, du)
return np.degrees(rad)
def _body_angle_deg_from_tail_ear_mid(tail_uv: np.ndarray, earL_uv: np.ndarray, earR_uv: np.ndarray) -> np.ndarray:
"""Body direction angle in degrees (0 = right, 90 = down). From tail toward ear midpoint."""
mid_u = (earL_uv[:, 0] + earR_uv[:, 0]) / 2
mid_v = (earL_uv[:, 1] + earR_uv[:, 1]) / 2
du = mid_u - tail_uv[:, 0]
dv = mid_v - tail_uv[:, 1]
rad = np.arctan2(dv, du)
return np.degrees(rad)
def load_head_direction_per_trial(
csv_path: Path,
trial_dir: Path,
calib: dict,
frame_start: int,
min_confidence: float = 0.15,
) -> pd.DataFrame | None:
"""
Load data3D.csv for trial, project Snout/EarL/EarR to uv, compute head angle per frame.
Returns DataFrame with columns: frame_number, u, v, head_angle_deg (only rows with valid triangle).
"""
data3d_path = trial_dir / "data3D.csv"
if not data3d_path.exists():
return None
body_parts = parse_data3d_csv(data3d_path)
for key in ["Snout", "EarL", "EarR"]:
if key not in body_parts:
return None
n_rows = len(body_parts["Snout"])
frame_numbers = frame_start + np.arange(n_rows, dtype=np.int64)
snout_xyz = body_parts["Snout"][["x", "y", "z"]].values.astype(float)
earL_xyz = body_parts["EarL"][["x", "y", "z"]].values.astype(float)
earR_xyz = body_parts["EarR"][["x", "y", "z"]].values.astype(float)
conf_s = body_parts["Snout"]["confidence"].values.astype(float)
conf_l = body_parts["EarL"]["confidence"].values.astype(float)
conf_r = body_parts["EarR"]["confidence"].values.astype(float)
keep = (conf_s >= min_confidence) & (conf_l >= min_confidence) & (conf_r >= min_confidence)
if not np.any(keep):
return None
snout_uv = project_3d_to_2d(snout_xyz[keep], calib)
earL_uv = project_3d_to_2d(earL_xyz[keep], calib)
earR_uv = project_3d_to_2d(earR_xyz[keep], calib)
head_angle = _head_angle_deg_from_triangle(snout_uv, earL_uv, earR_uv)
frames = frame_numbers[keep]
return pd.DataFrame({
"frame_number": frames,
"u": snout_uv[:, 0],
"v": snout_uv[:, 1],
"head_angle_deg": head_angle,
})
def load_body_direction_per_trial(
csv_path: Path,
trial_dir: Path,
calib: dict,
frame_start: int,
min_confidence: float = 0.15,
) -> pd.DataFrame | None:
"""
Load data3D.csv for trial, project Tail/EarL/EarR to uv; body direction = tail → ear midpoint.
Returns DataFrame with columns: frame_number, u, v, body_angle_deg. (u,v) = tail position.
"""
data3d_path = trial_dir / "data3D.csv"
if not data3d_path.exists():
return None
body_parts = parse_data3d_csv(data3d_path)
for key in ["Tail", "EarL", "EarR"]:
if key not in body_parts:
return None
n_rows = len(body_parts["Tail"])
frame_numbers = frame_start + np.arange(n_rows, dtype=np.int64)
tail_xyz = body_parts["Tail"][["x", "y", "z"]].values.astype(float)
earL_xyz = body_parts["EarL"][["x", "y", "z"]].values.astype(float)
earR_xyz = body_parts["EarR"][["x", "y", "z"]].values.astype(float)
conf_t = body_parts["Tail"]["confidence"].values.astype(float)
conf_l = body_parts["EarL"]["confidence"].values.astype(float)
conf_r = body_parts["EarR"]["confidence"].values.astype(float)
keep = (conf_t >= min_confidence) & (conf_l >= min_confidence) & (conf_r >= min_confidence)
if not np.any(keep):
return None
tail_uv = project_3d_to_2d(tail_xyz[keep], calib)
earL_uv = project_3d_to_2d(earL_xyz[keep], calib)
earR_uv = project_3d_to_2d(earR_xyz[keep], calib)
body_angle = _body_angle_deg_from_tail_ear_mid(tail_uv, earL_uv, earR_uv)
frames = frame_numbers[keep]
return pd.DataFrame({
"frame_number": frames,
"u": tail_uv[:, 0],
"v": tail_uv[:, 1],
"body_angle_deg": body_angle,
})
def circular_mean_deg(angles_deg: np.ndarray) -> float:
"""Circular mean of angles in degrees; returns NaN if empty."""
if len(angles_deg) == 0:
return np.nan
rad = np.deg2rad(angles_deg)
return np.degrees(np.arctan2(np.nanmean(np.sin(rad)), np.nanmean(np.cos(rad))))
def compute_phase_head_direction_grid(
trials_list: list[tuple[Path, str, str | None]],
u_edges: np.ndarray,
v_edges: np.ndarray,
calib_root: Path | None,
camera: str,
min_confidence: float = 0.15,
reward_frame_by_trial: dict[str, int] | None = None,
) -> tuple[np.ndarray, np.ndarray]:
"""
For all trials, load (u, v, head_angle) restricted to trajectory_filtered frames; optionally
restrict to start→reward (frame_number <= reward_frame) when reward_frame_by_trial is provided.
Returns (mean_angle_grid_deg, count_grid). Grid shape (len(v_edges)-1, len(u_edges)-1).
"""
n_u, n_v = len(u_edges) - 1, len(v_edges) - 1
sum_sin = np.zeros((n_v, n_u))
sum_cos = np.zeros((n_v, n_u))
count = np.zeros((n_v, n_u))
for csv_path, trial_id, session_folder in trials_list:
trial_dir = csv_path.parent
m = TRIAL_PATTERN.match(trial_id)
frame_start = int(m.group(2)) if m else 0
calib_path = _resolve_calib_path(trial_dir, calib_root, camera)
if calib_path is None or not calib_path.exists():
continue
try:
calib = load_calib(calib_path)
except Exception:
continue
hd_df = load_head_direction_per_trial(csv_path, trial_dir, calib, frame_start, min_confidence)
if hd_df is None or len(hd_df) == 0:
continue
# Restrict to frames that appear in trajectory_filtered (valid path)
traj = at.load_trajectory_csv(csv_path)
if len(traj) == 0 or "u" not in traj.columns or "v" not in traj.columns:
continue
valid_frames = set(traj["frame_number"].astype(int).tolist())
hd_df = hd_df[hd_df["frame_number"].isin(valid_frames)]
# Optionally restrict to start → reward only
if reward_frame_by_trial is not None:
reward_frame = reward_frame_by_trial.get(trial_id)
if reward_frame is None:
continue
hd_df = hd_df[hd_df["frame_number"] <= reward_frame]
if len(hd_df) == 0:
continue
u_vals = hd_df["u"].values
v_vals = hd_df["v"].values
rad = np.deg2rad(hd_df["head_angle_deg"].values)
iu = np.searchsorted(u_edges, u_vals, side="right") - 1
iv = np.searchsorted(v_edges, v_vals, side="right") - 1
iu = np.clip(iu, 0, n_u - 1)
iv = np.clip(iv, 0, n_v - 1)
for idx in range(len(hd_df)):
jv, ju = iv[idx], iu[idx]
sum_sin[jv, ju] += np.sin(rad[idx])
sum_cos[jv, ju] += np.cos(rad[idx])
count[jv, ju] += 1
with np.errstate(invalid="ignore", divide="ignore"):
mean_angle_rad = np.arctan2(sum_sin, sum_cos)
mean_angle_deg = np.degrees(mean_angle_rad)
mean_angle_deg[count == 0] = np.nan
return mean_angle_deg, count
def compute_phase_body_direction_grid(
trials_list: list[tuple[Path, str, str | None]],
u_edges: np.ndarray,
v_edges: np.ndarray,
calib_root: Path | None,
camera: str,
min_confidence: float = 0.15,
reward_frame_by_trial: dict[str, int] | None = None,
) -> tuple[np.ndarray, np.ndarray]:
"""Same as compute_phase_head_direction_grid but for body (tail → ear mid). Returns (mean_angle_deg, count)."""
n_u, n_v = len(u_edges) - 1, len(v_edges) - 1
sum_sin = np.zeros((n_v, n_u))
sum_cos = np.zeros((n_v, n_u))
count = np.zeros((n_v, n_u))
for csv_path, trial_id, session_folder in trials_list:
trial_dir = csv_path.parent
m = TRIAL_PATTERN.match(trial_id)
frame_start = int(m.group(2)) if m else 0
calib_path = _resolve_calib_path(trial_dir, calib_root, camera)
if calib_path is None or not calib_path.exists():
continue
try:
calib = load_calib(calib_path)
except Exception:
continue
bd_df = load_body_direction_per_trial(csv_path, trial_dir, calib, frame_start, min_confidence)
if bd_df is None or len(bd_df) == 0:
continue
traj = at.load_trajectory_csv(csv_path)
if len(traj) == 0 or "u" not in traj.columns or "v" not in traj.columns:
continue
valid_frames = set(traj["frame_number"].astype(int).tolist())
bd_df = bd_df[bd_df["frame_number"].isin(valid_frames)]
if reward_frame_by_trial is not None:
reward_frame = reward_frame_by_trial.get(trial_id)
if reward_frame is None:
continue
bd_df = bd_df[bd_df["frame_number"] <= reward_frame]
if len(bd_df) == 0:
continue
u_vals = bd_df["u"].values
v_vals = bd_df["v"].values
rad = np.deg2rad(bd_df["body_angle_deg"].values)
iu = np.searchsorted(u_edges, u_vals, side="right") - 1
iv = np.searchsorted(v_edges, v_vals, side="right") - 1
iu = np.clip(iu, 0, n_u - 1)
iv = np.clip(iv, 0, n_v - 1)
for idx in range(len(bd_df)):
jv, ju = iv[idx], iu[idx]
sum_sin[jv, ju] += np.sin(rad[idx])
sum_cos[jv, ju] += np.cos(rad[idx])
count[jv, ju] += 1
with np.errstate(invalid="ignore", divide="ignore"):
mean_angle_rad = np.arctan2(sum_sin, sum_cos)
mean_angle_deg = np.degrees(mean_angle_rad)
mean_angle_deg[count == 0] = np.nan
return mean_angle_deg, count
def _cyclic_cmap_for_angle():
"""Cyclic colormap: 90° (down) = red, -90° (up) = blue; 0° and ±180° = yellow/cyan for clarity."""
from matplotlib.colors import LinearSegmentedColormap
# With norm vmin=-180, vmax=180: norm gives 0=-180°, 0.25=-90°, 0.5=0°, 0.75=90°, 1=180°
# 5 evenly spaced stops: -90° = blue, 90° = red
cmap = LinearSegmentedColormap.from_list("head_angle_rb", [
(0.2, 0.8, 0.8), # -180° cyan
(0.0, 0.2, 1.0), # -90° blue
(1.0, 1.0, 0.2), # 0° yellow
(1.0, 0.0, 0.0), # 90° red
(0.2, 0.8, 0.8), # 180° cyan (wraps)
], N=256)
return cmap
def plot_head_direction_by_phase(
early_trials: list[tuple[Path, str, str | None]],
mid_trials: list[tuple[Path, str, str | None]],
late_trials: list[tuple[Path, str, str | None]],
u_min: float,
u_max: float,
v_min: float,
v_max: float,
calib_root: Path | None,
camera: str,
out_path: Path,
animal: str = "",
params: dict | None = None,
n_bins: int = 40,
reward_frame_by_trial: dict[str, int] | None = None,
title_suffix: str = "",
) -> None:
"""
Three panels: early, mid, late. Each shows (u,v) heatmap colored by mean head direction (cyclic).
If reward_frame_by_trial is provided, only frames from start to reward are included; otherwise full path.
title_suffix: e.g. " (full path)" or " (start to reward)".
"""
u_edges = np.linspace(u_min, u_max, n_bins + 1)
v_edges = np.linspace(v_min, v_max, n_bins + 1)
# Larger figure and fonts
fig, axes = plt.subplots(1, 3, figsize=(22, 9))
font_title = 16
font_axis = 14
font_ticks = 12
phase_lists = [early_trials, mid_trials, late_trials]
phase_names = ["Early", "Mid", "Late"]
norm = plt.Normalize(vmin=-180, vmax=180)
cmap = _cyclic_cmap_for_angle()
for ax, trials, name in zip(axes, phase_lists, phase_names):
ax.tick_params(axis="both", labelsize=font_ticks)
if not trials:
ax.set_xlim(u_min, u_max)
ax.set_ylim(v_max, v_min)
ax.set_aspect("equal")
ax.set_title(f"{name} (n=0)", fontsize=font_title)
ax.set_xlabel("u (px)", fontsize=font_axis)
ax.set_ylabel("v (px)", fontsize=font_axis)
continue
mean_angle, count = compute_phase_head_direction_grid(
trials, u_edges, v_edges, calib_root, camera,
reward_frame_by_trial=reward_frame_by_trial,
)
count_min = max(3, np.nanpercentile(count[count > 0], 5) if (count > 0).any() else 3)
mean_angle_masked = np.where(count >= count_min, mean_angle, np.nan)
ax.pcolormesh(
u_edges, v_edges, mean_angle_masked,
cmap=cmap, norm=norm, shading="flat", alpha=0.9,
)
ax.set_xlim(u_min, u_max)
ax.set_ylim(v_max, v_min)
ax.set_aspect("equal")
ax.set_xlabel("u (px)", fontsize=font_axis)
ax.set_ylabel("v (px)", fontsize=font_axis)
ax.set_title(f"{name} (n={len(trials)} trials)", fontsize=font_title)
if params:
v_mid = params.get("v_mid")
if v_mid is not None:
ax.axhline(float(v_mid), color="black", linewidth=1.5, zorder=5)
for key, color in [("goal1", "#e63946"), ("goal2", "#1d3557")]:
gu, gv = params.get(f"{key}_u"), params.get(f"{key}_v")
if gu is not None and gv is not None:
ax.plot(float(gu), float(gv), "o", color=color, markersize=10, markeredgecolor="white", zorder=6)
# Leave space on the right for colorbar so it doesn't overlap the plot
plt.tight_layout(rect=[0, 0, 0.88, 0.96])
cax = fig.add_axes([0.90, 0.12, 0.022, 0.76]) # [left, bottom, width, height]
cbar = fig.colorbar(plt.cm.ScalarMappable(norm=norm, cmap=cmap), cax=cax, label="Head direction (°)")
cbar.set_ticks([-180, -90, 0, 90, 180])
cbar.ax.tick_params(labelsize=font_ticks)
cbar.set_label("Head direction (°)", fontsize=font_axis)
title = "Head direction by phase (snout–ear triangle)"
if animal:
title += f" — {animal}"
if title_suffix:
title += title_suffix
fig.suptitle(title, fontsize=font_title + 2, y=0.98)
fig.savefig(out_path, dpi=150, bbox_inches="tight")
plt.close()
def plot_body_direction_by_phase(
early_trials: list[tuple[Path, str, str | None]],
mid_trials: list[tuple[Path, str, str | None]],
late_trials: list[tuple[Path, str, str | None]],
u_min: float,
u_max: float,
v_min: float,
v_max: float,
calib_root: Path | None,
camera: str,
out_path: Path,
animal: str = "",
params: dict | None = None,
n_bins: int = 40,
reward_frame_by_trial: dict[str, int] | None = None,
title_suffix: str = "",
) -> None:
"""Three panels: early, mid, late. Each shows (u,v) heatmap colored by mean body direction (tail → ear mid)."""
u_edges = np.linspace(u_min, u_max, n_bins + 1)
v_edges = np.linspace(v_min, v_max, n_bins + 1)
fig, axes = plt.subplots(1, 3, figsize=(22, 9))
font_title, font_axis, font_ticks = 16, 14, 12
phase_lists = [early_trials, mid_trials, late_trials]
phase_names = ["Early", "Mid", "Late"]
norm = plt.Normalize(vmin=-180, vmax=180)
cmap = _cyclic_cmap_for_angle()
for ax, trials, name in zip(axes, phase_lists, phase_names):
ax.tick_params(axis="both", labelsize=font_ticks)
if not trials:
ax.set_xlim(u_min, u_max)
ax.set_ylim(v_max, v_min)
ax.set_aspect("equal")
ax.set_title(f"{name} (n=0)", fontsize=font_title)
ax.set_xlabel("u (px)", fontsize=font_axis)
ax.set_ylabel("v (px)", fontsize=font_axis)
continue
mean_angle, count = compute_phase_body_direction_grid(
trials, u_edges, v_edges, calib_root, camera,
reward_frame_by_trial=reward_frame_by_trial,
)
count_min = max(3, np.nanpercentile(count[count > 0], 5) if (count > 0).any() else 3)
mean_angle_masked = np.where(count >= count_min, mean_angle, np.nan)
ax.pcolormesh(
u_edges, v_edges, mean_angle_masked,
cmap=cmap, norm=norm, shading="flat", alpha=0.9,
)
ax.set_xlim(u_min, u_max)
ax.set_ylim(v_max, v_min)
ax.set_aspect("equal")
ax.set_xlabel("u (px)", fontsize=font_axis)
ax.set_ylabel("v (px)", fontsize=font_axis)
ax.set_title(f"{name} (n={len(trials)} trials)", fontsize=font_title)
if params:
v_mid = params.get("v_mid")
if v_mid is not None:
ax.axhline(float(v_mid), color="black", linewidth=1.5, zorder=5)
for key, color in [("goal1", "#e63946"), ("goal2", "#1d3557")]:
gu, gv = params.get(f"{key}_u"), params.get(f"{key}_v")
if gu is not None and gv is not None:
ax.plot(float(gu), float(gv), "o", color=color, markersize=10, markeredgecolor="white", zorder=6)
plt.tight_layout(rect=[0, 0, 0.88, 0.96])
cax = fig.add_axes([0.90, 0.12, 0.022, 0.76])
cbar = fig.colorbar(plt.cm.ScalarMappable(norm=norm, cmap=cmap), cax=cax, label="Body direction (°)")
cbar.set_ticks([-180, -90, 0, 90, 180])
cbar.ax.tick_params(labelsize=font_ticks)
cbar.set_label("Body direction (°)", fontsize=font_axis)
title = "Body direction by phase (tail → ear midpoint)"
if animal:
title += f" — {animal}"
if title_suffix:
title += title_suffix
fig.suptitle(title, fontsize=font_title + 2, y=0.98)
fig.savefig(out_path, dpi=150, bbox_inches="tight")
plt.close()
def plot_head_direction_angle_reference(
out_path: Path,
direction_label: str = "Head direction",
sublabel: str = "snout–ear triangle",
) -> None:
"""
Draw a reference diagram: which angle (degrees) corresponds to which direction in the image.
direction_label and sublabel allow reuse for body (tail → ear midpoint).
Convention: 0° = right (u+), 90° = down (v+).
"""
fig, ax = plt.subplots(1, 1, figsize=(10, 9))
ax.set_aspect("equal")
# Image convention: u horizontal (right = +), v vertical (down = +)
# So in math coords we plot u → x, v → y with y inverted for "image": y_down = -v so down = +v in image = -y in plot
# Actually for the reference we just draw a circle and show angles; no need to invert. Use standard math: angle 0 = right (1,0), 90 = up (0,1).
# Our head angle: atan2(dv, du) so 0° = (du>0, dv=0) = right, 90° = (du=0, dv>0) = down in image.
# In a typical plot, x = u (right), y = v. If we use ax.invert_yaxis() then up = small v, down = large v. So 90° (down) = arrow pointing in +v = downward in plot after invert = upward in data. So let's not invert: just use a compass where 0° is right, 90° is downward in the figure (positive y).
center = 0.0
radius = 1.0
theta = np.linspace(0, 2 * np.pi, 100)
ax.plot(radius * np.cos(theta), radius * np.sin(theta), "k-", linewidth=1)
ax.plot(center, center, "ko", markersize=6)
# Arrows: angle in degrees -> direction. Our convention: head_angle = atan2(dv, du), so 0° = (1,0), 90° = (0,1)
# In plot coordinates: x = u, y = v. So 0° -> (1,0) right; 90° -> (0,1) up in plot. But in image v increases downward! So 90° in our convention = (0,1) in (du,dv) = down in image = (0, +1) in (u,v). So in plot (x,y)=(u,v), 90° is positive y = upward in plot. So "down in image" = "up in plot" if we use y=v. So we need to say "90° = down (in image)" and draw the arrow in the direction of (0, +1) in (u,v) = (0, +1) in plot = upward. So arrow at 90° goes upward in the figure, and we label it "90° = down (v+ in image)".
arrow_length = 0.85
for deg, label, color in [
(0, "0° right (u+)", "green"),
(90, "90° down (v+)", "blue"),
(180, "±180° left", "red"),
(-90, "-90° up (v−)", "purple"),
]:
rad = np.deg2rad(deg)
dx = arrow_length * np.cos(rad)
dy = arrow_length * np.sin(rad)
ax.arrow(center, center, dx, dy, head_width=0.12, head_length=0.08, fc=color, ec=color, linewidth=2)
# Label at arrow tip (slightly beyond)
text_dist = 1.05
ax.text(text_dist * np.cos(rad), text_dist * np.sin(rad), label, ha="center", va="center", fontsize=12, color=color)
ax.set_xlim(-1.5, 1.5)
ax.set_ylim(-1.5, 1.5)
ax.set_xlabel("u (pixels) →", fontsize=12)
ax.set_ylabel("v (pixels) →", fontsize=12)
ax.set_title(f"{direction_label} angle reference (camera image coordinates)", fontsize=14)
ax.axhline(0, color="gray", linestyle=":", alpha=0.6)
ax.axvline(0, color="gray", linestyle=":", alpha=0.6)
note = (
f"{direction_label} = {sublabel}.\n"
"0° = points right (increasing u); 90° = points down (increasing v).\n"
"Angles in [-180°, 180°]. Same convention used in heatmaps and analyses."
)
fig.text(0.5, 0.02, note, ha="center", fontsize=10, wrap=True)
plt.tight_layout(rect=[0, 0.06, 1, 1])
fig.savefig(out_path, dpi=150, bbox_inches="tight")
plt.close()
def plot_head_body_vector_diagram(out_path: Path) -> None:
"""
Draw a schematic of head vs body direction vectors from one frame.
Shows: Tail, Ear midpoint, Snout; body vector (tail → ear mid); head vector (ear mid → snout).
Uses example positions so body ≈ 0°, head ≈ 53° (camera convention: 0° = right, 90° = down).
"""
fig, ax = plt.subplots(1, 1, figsize=(10, 8))
ax.set_aspect("equal")
# Example positions in (u, v) style: u = x (right), v = y (down in image)
tail_u, tail_v = 0.0, 0.0
ear_mid_u, ear_mid_v = 2.0, 0.0
snout_u, snout_v = 2.6, 0.85
# Body vector: tail → ear mid
body_du = ear_mid_u - tail_u
body_dv = ear_mid_v - tail_v
body_angle_deg = float(np.degrees(np.arctan2(body_dv, body_du)))
# Head vector: ear mid → snout
head_du = snout_u - ear_mid_u
head_dv = snout_v - ear_mid_v
head_angle_deg = float(np.degrees(np.arctan2(head_dv, head_du)))
# Points
ax.plot(tail_u, tail_v, "ko", markersize=12, zorder=5)
ax.plot(ear_mid_u, ear_mid_v, "ko", markersize=10, zorder=5)
ax.plot(snout_u, snout_v, "ko", markersize=12, zorder=5)
ax.text(tail_u - 0.35, tail_v, "Tail", fontsize=12, ha="right", va="center")
ax.text(ear_mid_u, ear_mid_v - 0.35, "Ear mid\n(EarL+EarR)/2", fontsize=11, ha="center", va="top")
ax.text(snout_u + 0.25, snout_v, "Snout", fontsize=12, ha="left", va="center")
# Body direction vector (tail → ear mid)
ax.arrow(
tail_u, tail_v, body_du * 0.85, body_dv * 0.85,
head_width=0.15, head_length=0.1, fc="#1d3557", ec="#1d3557", linewidth=3, zorder=4,
)
ax.text(tail_u + body_du * 0.45, tail_v + body_dv * 0.45 + 0.2, "Body direction\n(tail → ear mid)", fontsize=11, ha="center", color="#1d3557", fontweight="bold")
# Head direction vector (ear mid → snout)
ax.arrow(
ear_mid_u, ear_mid_v, head_du * 0.95, head_dv * 0.95,
head_width=0.15, head_length=0.1, fc="#e63946", ec="#e63946", linewidth=3, zorder=4,
)
ax.text(ear_mid_u + head_du * 0.6, ear_mid_v + head_dv * 0.6 + 0.15, "Head direction\n(ear mid → snout)", fontsize=11, ha="center", color="#e63946", fontweight="bold")
# Angle labels
ax.text(1.0, -0.5, f"Body angle = {body_angle_deg:.0f}° (0° = right)", fontsize=10, color="#1d3557")
ax.text(2.4, 0.6, f"Head angle = {head_angle_deg:.0f}°", fontsize=10, color="#e63946")
ax.set_xlabel("u (pixels) →", fontsize=12)
ax.set_ylabel("v (pixels) →", fontsize=12)
ax.set_title("Head direction vs body direction (example frame)", fontsize=14)
ax.set_xlim(-0.8, 3.2)
ax.set_ylim(-0.9, 1.8)
ax.axhline(0, color="gray", linestyle=":", alpha=0.5)
ax.axvline(0, color="gray", linestyle=":", alpha=0.5)
note = (
"Body = angle from tail to ear midpoint. Head = angle from ear midpoint to snout.\n"
"Same convention: 0° = right (u+), 90° = down (v+). |head − body| = head–body alignment."
)
fig.text(0.5, 0.02, note, ha="center", fontsize=10, wrap=True)
plt.tight_layout(rect=[0, 0.05, 1, 1])
fig.savefig(out_path, dpi=150, bbox_inches="tight")
plt.close()
# ---------- Start-to-reward analyses (require reward_frame_by_trial and params) ----------
def _p_to_stars(p: float, bonferroni_alpha: float | None = None) -> str:
"""Return *, **, *** for p < 0.05, 0.01, 0.001 (vs alpha or bonferroni_alpha)."""
alpha = bonferroni_alpha if bonferroni_alpha is not None else 0.05
if p < 0.001:
return "***"
if p < 0.01:
return "**"
if p < alpha:
return "*"
return ""
def _annotate_boxplot_significance(
ax: plt.Axes,
groups: list[np.ndarray],
alpha: float = 0.05,
) -> None:
"""
If significant, draw asterisks on the boxplot. groups = list of 1d arrays (2, 3, or 4).
For 2 groups: Mann-Whitney; one asterisk centered above. For 3: Kruskal-Wallis + post-hoc
Mann-Whitney with Bonferroni; bracket + asterisk for each significant pair.
For 4+ groups: Kruskal-Wallis only; one asterisk centered above if significant.
"""
groups = [np.asarray(g).flatten() for g in groups]
groups = [g[~np.isnan(g)] for g in groups]
if any(len(g) < 2 for g in groups):
return
ylim = ax.get_ylim()
y_range = ylim[1] - ylim[0]
y_annot = ylim[1] + 0.02 * y_range
if len(groups) == 2:
try:
_, p = stats.mannwhitneyu(groups[0], groups[1], alternative="two-sided")
if p < alpha:
stars = _p_to_stars(p)
ax.text(1.5, y_annot, stars, ha="center", va="bottom", fontsize=12)
ax.set_ylim(ylim[0], ylim[1] + 0.08 * y_range)
except Exception:
pass
return
if len(groups) > 3:
try:
stat, p_kw = stats.kruskal(*groups)
if p_kw < alpha:
stars = _p_to_stars(p_kw)
n = len(groups)
ax.text((1 + n) / 2, y_annot, stars, ha="center", va="bottom", fontsize=12)
ax.set_ylim(ylim[0], ylim[1] + 0.08 * y_range)
except Exception:
pass
return
if len(groups) != 3:
return
try:
stat, p_kw = stats.kruskal(*groups)
if p_kw >= alpha:
return
bonferroni_alpha = alpha / 3
pairs_sig: list[tuple[int, int, float]] = []
for i in range(3):
for j in range(i + 1, 3):
if len(groups[i]) < 2 or len(groups[j]) < 2:
continue
_, p = stats.mannwhitneyu(groups[i], groups[j], alternative="two-sided")
if p < bonferroni_alpha:
pairs_sig.append((i, j, p))
if not pairs_sig:
return
# Draw bracket and asterisk for each significant pair; stack vertically if multiple
n_pairs = len(pairs_sig)
step = 0.04 * y_range
for k, (i, j, p) in enumerate(pairs_sig):
y = y_annot + k * step
ax.plot([i + 1, i + 1, j + 1, j + 1], [y, y + step * 0.5, y + step * 0.5, y], "k-", lw=1)
stars = _p_to_stars(p, bonferroni_alpha)
ax.text((i + 1 + j + 1) / 2, y + step * 0.5, stars, ha="center", va="bottom", fontsize=10)
ax.set_ylim(ylim[0], ylim[1] + 0.08 * y_range + n_pairs * step)
except Exception:
pass
def _parse_trial_frames(trial_id: str) -> tuple[int, int] | None:
"""Parse trial_id (e.g. Predictions_3D_trial_0000_11572-20491) -> (frame_start, frame_end)."""
m = TRIAL_PATTERN.match(trial_id)
return (int(m.group(2)), int(m.group(3))) if m else None
def _point_goal_region_local(u: float, v: float, params: dict) -> int:
"""Return 1 if (u,v) in goal1 rect, 2 if in goal2 rect, 0 otherwise. Uses params (half_u, top_bottom, etc.)."""
v_mid = params.get("v_mid")
g1_u, g1_v = params.get("goal1_u"), params.get("goal1_v")
g2_u, g2_v = params.get("goal2_u"), params.get("goal2_v")
if v_mid is None or g1_u is None or g2_u is None:
return 0
half_u = float(params.get("half_u", (params.get("goal2_u", 0) - params.get("goal1_u", 0)) or 50))
top_bottom = float(params.get("top_bottom", v_mid - 100))
top_top = float(params.get("top_top", v_mid - 5))
bottom_bottom = float(params.get("bottom_bottom", v_mid + 5))
bottom_top = float(params.get("bottom_top", v_mid + 100))
if g1_v < v_mid:
if top_bottom <= v <= top_top and abs(u - g1_u) <= half_u:
return 1
if bottom_bottom <= v <= bottom_top and abs(u - g2_u) <= half_u:
return 2
else:
if bottom_bottom <= v <= bottom_top and abs(u - g1_u) <= half_u:
return 1
if top_bottom <= v <= top_top and abs(u - g2_u) <= half_u:
return 2
return 0
def _load_trial_start_to_reward_with_head(
csv_path: Path,
trial_id: str,
reward_frame: int,
trial_dir: Path,
calib: dict,
frame_start: int,
) -> pd.DataFrame | None:
"""Load trajectory start→reward and merge with head direction. Returns df with frame_number, u, v, head_angle_deg, movement_angle_deg (deg)."""
df = at.load_trajectory_csv(csv_path)
if len(df) < 1 or "u" not in df.columns or "v" not in df.columns:
return None
mask = (df["frame_number"] >= frame_start) & (df["frame_number"] <= reward_frame)
df = df.loc[mask].sort_values("frame_number").reset_index(drop=True)
if len(df) < 2:
return None
hd_df = load_head_direction_per_trial(csv_path, trial_dir, calib, frame_start)
if hd_df is None or len(hd_df) == 0:
return None
merged = df.merge(hd_df[["frame_number", "head_angle_deg"]], on="frame_number", how="inner")
if len(merged) < 2:
return None
du = np.diff(merged["u"].values.astype(float))
dv = np.diff(merged["v"].values.astype(float))
movement_deg = np.degrees(np.arctan2(dv, du))
movement_deg = np.concatenate([[movement_deg[0]], movement_deg])
merged = merged.copy()
merged["movement_angle_deg"] = movement_deg
return merged
def _load_trial_start_to_reward_with_head_and_body(
csv_path: Path,
trial_id: str,
reward_frame: int,
trial_dir: Path,
calib: dict,
frame_start: int,
) -> pd.DataFrame | None:
"""Load trajectory start→reward with both head and body direction. Returns df with frame_number, u, v (snout), head_angle_deg, body_angle_deg."""
df = at.load_trajectory_csv(csv_path)
if len(df) < 2 or "u" not in df.columns or "v" not in df.columns:
return None
mask = (df["frame_number"] >= frame_start) & (df["frame_number"] <= reward_frame)
df = df.loc[mask].sort_values("frame_number").reset_index(drop=True)
hd_df = load_head_direction_per_trial(csv_path, trial_dir, calib, frame_start)
bd_df = load_body_direction_per_trial(csv_path, trial_dir, calib, frame_start)
if hd_df is None or len(hd_df) == 0 or bd_df is None or len(bd_df) == 0:
return None
merged = df[["frame_number", "u", "v"]].merge(
hd_df[["frame_number", "head_angle_deg"]], on="frame_number", how="inner"
).merge(
bd_df[["frame_number", "body_angle_deg"]], on="frame_number", how="inner"
)
if len(merged) < 2:
return None
return merged
def _load_trial_start_to_reward_with_body(
csv_path: Path,
trial_id: str,
reward_frame: int,
trial_dir: Path,
calib: dict,
frame_start: int,
) -> pd.DataFrame | None:
"""Load trajectory start→reward and merge with body direction. Returns df with frame_number, u, v (snout from traj), body_angle_deg, movement_angle_deg."""
df = at.load_trajectory_csv(csv_path)
if len(df) < 1 or "u" not in df.columns or "v" not in df.columns:
return None
mask = (df["frame_number"] >= frame_start) & (df["frame_number"] <= reward_frame)
df = df.loc[mask].sort_values("frame_number").reset_index(drop=True)
if len(df) < 2:
return None
bd_df = load_body_direction_per_trial(csv_path, trial_dir, calib, frame_start)
if bd_df is None or len(bd_df) == 0:
return None
merged = df.merge(bd_df[["frame_number", "body_angle_deg"]], on="frame_number", how="inner")
if len(merged) < 2:
return None
du = np.diff(merged["u"].values.astype(float))
dv = np.diff(merged["v"].values.astype(float))
movement_deg = np.degrees(np.arctan2(dv, du))
movement_deg = np.concatenate([[movement_deg[0]], movement_deg])
merged = merged.copy()
merged["movement_angle_deg"] = movement_deg
return merged
def _crossing_events_with_frame(
df: pd.DataFrame,
params: dict,
) -> list[tuple[int, float, float, int]]:
"""Return list of (frame_number, u, v, toward_goal) at each midline crossing. toward_goal 1 or 2."""
v_mid = params["v_mid"]
g1_v, g2_v = params.get("goal1_v"), params.get("goal2_v")
if g1_v is None or g2_v is None:
return []
v_above = min(g1_v, g2_v)
v_below = max(g1_v, g2_v)
v_thresh_top = (v_mid + v_above) / 2.0
v_thresh_bottom = (v_mid + v_below) / 2.0
g1_is_top = g1_v < v_mid
def side(v: float) -> int:
if v <= v_thresh_top:
return -1
if v >= v_thresh_bottom:
return 1
return 0
out: list[tuple[int, float, float, int]] = []
v_vals = df["v"].values.astype(float)
u_vals = df["u"].values.astype(float)
frames = df["frame_number"].values.astype(int)
last_side = side(float(v_vals[0]))
for i in range(1, len(v_vals)):
s = side(float(v_vals[i]))
if s != 0 and last_side != 0 and s != last_side:
toward = 1 if (s == -1 and g1_is_top) or (s == 1 and not g1_is_top) else 2
out.append((int(frames[i]), float(u_vals[i]), float(v_vals[i]), toward))
if s != 0:
last_side = s
return out
def _first_goal_entries(
df: pd.DataFrame,
params: dict,
) -> tuple[int | None, float, float, int | None, float, float]:
"""Return (frame_g1, u_g1, v_g1, frame_g2, u_g2, v_g2) for first entry to each goal. None if never."""
f1, u1, v1 = None, np.nan, np.nan
f2, u2, v2 = None, np.nan, np.nan
for _, row in df.iterrows():
lab = _point_goal_region_local(float(row["u"]), float(row["v"]), params)
if lab == 1 and f1 is None:
f1, u1, v1 = int(row["frame_number"]), float(row["u"]), float(row["v"])
elif lab == 2 and f2 is None:
f2, u2, v2 = int(row["frame_number"]), float(row["u"]), float(row["v"])
if f1 is not None and f2 is not None:
break
return (f1, u1, v1, f2, u2, v2)
def _angle_to_goal_deg(u: float, v: float, g_u: float, g_v: float) -> float:
"""Angle in degrees from (u,v) toward goal (g_u, g_v). 0 = right, 90 = down."""
return float(np.degrees(np.arctan2(g_v - v, g_u - u)))
def _run_all_head_direction_analyses(
trials: list[tuple[Path, str, str | None]],
early: list,
mid: list,
late: list,
reward_frame_by_trial: dict[str, int],
params: dict,
calib_root: Path | None,
camera: str,
u_min: float,
u_max: float,
v_min: float,
v_max: float,
out_dir: Path,
animal: str,
) -> None:
"""Run all 6 suggested head-direction analyses (start to reward only), save figures to out_dir."""
trial_to_phase: dict[str, int] = {}
for t in early:
trial_to_phase[t[1]] = 0
for t in mid:
trial_to_phase[t[1]] = 1
for t in late:
trial_to_phase[t[1]] = 2
phase_names = ["Early", "Mid", "Late"]
g1_u, g1_v = params.get("goal1_u"), params.get("goal1_v")
g2_u, g2_v = params.get("goal2_u"), params.get("goal2_v")
v_mid = params.get("v_mid")
# Collect per-trial data with head direction (start→reward)
records: list[dict] = []
crossing_head_angles: list[tuple[int, float, int]] = [] # phase_id, head_deg, toward_goal
goal1_entry_heads: list[tuple[int, float]] = []
goal2_entry_heads: list[tuple[int, float]] = []
for csv_path, trial_id, _ in trials:
reward_frame = reward_frame_by_trial.get(trial_id)
if reward_frame is None:
continue
frames = _parse_trial_frames(trial_id)
if not frames:
continue
frame_start, _ = frames
calib_path = _resolve_calib_path(csv_path.parent, calib_root, camera)
if calib_path is None or not calib_path.exists():
continue
try:
calib = load_calib(calib_path)
except Exception:
continue
df = _load_trial_start_to_reward_with_head(csv_path, trial_id, reward_frame, csv_path.parent, calib, frame_start)
if df is None or len(df) < 2:
continue
phase_id = trial_to_phase.get(trial_id, 0)
for _, row in df.iterrows():
records.append({
"trial_id": trial_id,
"phase_id": phase_id,
"frame": int(row["frame_number"]),
"u": float(row["u"]),
"v": float(row["v"]),
"head_deg": float(row["head_angle_deg"]),
"movement_deg": float(row["movement_angle_deg"]),
})
for (frame, u, v, toward) in _crossing_events_with_frame(df, params):
head_row = df[df["frame_number"] == frame]
if len(head_row) > 0:
crossing_head_angles.append((phase_id, float(head_row["head_angle_deg"].iloc[0]), toward))
f1, u1, v1, f2, u2, v2 = _first_goal_entries(df, params)
if f1 is not None:
r = df[df["frame_number"] == f1]
if len(r) > 0:
goal1_entry_heads.append((phase_id, float(r["head_angle_deg"].iloc[0])))
if f2 is not None:
r = df[df["frame_number"] == f2]
if len(r) > 0:
goal2_entry_heads.append((phase_id, float(r["head_angle_deg"].iloc[0])))
if not records:
return
rec_df = pd.DataFrame(records)
# 1) Head direction at midline crossing
if crossing_head_angles:
fig1, axes = plt.subplots(1, 2, figsize=(12, 5))
by_phase: dict[int, list[float]] = {0: [], 1: [], 2: []}
for pid, hd, _ in crossing_head_angles:
by_phase[pid].append(hd)
by_phase_list = [by_phase.get(i, []) for i in range(3)]
axes[0].boxplot(by_phase_list, tick_labels=phase_names)
_annotate_boxplot_significance(axes[0], by_phase_list)
axes[0].set_ylabel("Head direction (°)")
axes[0].set_title("Head direction at midline crossing (by phase)")
toward1 = [hd for _, hd, t in crossing_head_angles if t == 1]
toward2 = [hd for _, hd, t in crossing_head_angles if t == 2]
axes[1].boxplot([toward1, toward2], tick_labels=["Toward goal 1", "Toward goal 2"])
_annotate_boxplot_significance(axes[1], [np.array(toward1), np.array(toward2)])
axes[1].set_ylabel("Head direction (°)")
axes[1].set_title("Head direction at crossing (by direction)")
fig1.suptitle(f"Head at midline crossing (start→reward) — {animal}", fontsize=12)
plt.tight_layout()
fig1.savefig(out_dir / "head_at_midline_crossing.png", dpi=150, bbox_inches="tight")