-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot_flow_field_rory.py
More file actions
2116 lines (1980 loc) · 93.2 KB
/
plot_flow_field_rory.py
File metadata and controls
2116 lines (1980 loc) · 93.2 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
"""
Midline-and-goals analysis per animal (u-v camera space).
Generates: elevation/flow panels, midline + goals JSON, path plots (trial start → reward; by crossing count; phase and vertical left/right), crossing-location histograms, goal-region heatmaps, etc.
Outputs: trajectory_analysis/<animal>/midline_and_goals/*.png and midline_and_goals.json.
Use --animal rory or --animal wilfred (default: rory). See docs/RORY_MIDLINE_AND_GOALS.md for full documentation.
"""
import argparse
import json
import re
import sys
from pathlib import Path
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
# Optional: resolve reward time from cbot_climb_log
_script_dir = Path(__file__).resolve().parent
if str(_script_dir) not in sys.path:
sys.path.insert(0, str(_script_dir))
import numpy as np
import pandas as pd
from scipy import ndimage
import analyze_trajectories as at
FPS = getattr(at, "FPS", 180)
# Video FPS for converting log time_to_target (sec) to reward frame
VIDEO_FPS = 180
# Trial folder name: Predictions_3D_trial_0000_11572-20491 -> frame_start=11572, frame_end=20491
TRIAL_PATTERN = re.compile(r"^Predictions_3D_trial_(\d+)_(\d+)-(\d+)$")
# Geometry of rectangular goal regions (set by _flow_field_uv_highlight_high_z in the current run)
GOAL_RECT_GEOM: dict | None = None
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 only.
Session folder is expected to start with '<animal>_' (e.g. rory_..., wilfred_...)."""
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 _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)
if not m:
return None
return int(m.group(2)), int(m.group(3))
def _video_folder_to_date_minutes(vf: str) -> tuple[str, int] | None:
"""Parse video_folder YYYY_MM_DD_HH_MM_SS -> (YYYY_MM_DD, minutes_since_midnight)."""
parts = vf.strip().split("_")
if len(parts) != 6:
return None
try:
y, mo, d, h, mi, s = (int(x) for x in parts)
date_str = f"{y:04d}_{mo:02d}_{d:02d}"
minutes = h * 60 + mi + s / 60.0
return (date_str, int(minutes))
except (ValueError, TypeError):
return None
def _best_matching_video_folder(pred_vf: str, csv_video_folders: list[str], max_minutes_diff: int = 15) -> str | None:
"""Return CSV video_folder with same date and closest time to pred_vf, or None."""
pred_parsed = _video_folder_to_date_minutes(pred_vf)
if pred_parsed is None:
return None
pred_date, pred_m = pred_parsed
best_vf: str | None = None
best_diff: int = max_minutes_diff + 1
for vf in csv_video_folders:
p = _video_folder_to_date_minutes(vf)
if p is None or p[0] != pred_date:
continue
diff = abs(p[1] - pred_m)
if diff < best_diff:
best_diff = diff
best_vf = vf
return best_vf
def _get_reward_frame_from_csv(
trials_list: list[tuple[Path, str, str | None]],
reward_times_path: Path,
) -> dict[str, int]:
"""Load reward_times.csv (animal, video_folder, trial_index, time_to_target_sec) and return dict trial_id -> reward_frame.
Matches prediction session to CSV by same animal and same date + closest time (log vs video folder can differ slightly)."""
reward_times_path = Path(reward_times_path)
if not reward_times_path.is_file():
return {}
try:
df = pd.read_csv(reward_times_path)
except Exception:
return {}
if "animal" not in df.columns or "video_folder" not in df.columns or "trial_index" not in df.columns or "time_to_target_sec" not in df.columns:
return {}
df = df.dropna(subset=["time_to_target_sec"])
lookup: dict[tuple[str, str, int], float] = {}
for _, row in df.iterrows():
key = (str(row["animal"]).strip().lower(), str(row["video_folder"]).strip(), int(row["trial_index"]))
lookup[key] = float(row["time_to_target_sec"])
csv_by_animal: dict[str, list[str]] = {}
for (a, vf, _) in lookup:
csv_by_animal.setdefault(a, []).append(vf)
for a in csv_by_animal:
csv_by_animal[a] = list(dict.fromkeys(csv_by_animal[a]))
out: dict[str, int] = {}
for _csv_path, trial_id, session_folder in trials_list:
if not session_folder:
continue
parts = session_folder.split("_", 1)
animal = parts[0].lower() if len(parts) > 1 else ""
video_folder = parts[1] if len(parts) > 1 else ""
frames = _parse_trial_frames(trial_id)
if not frames:
continue
frame_start, _ = frames
trial_index = int(TRIAL_PATTERN.match(trial_id).group(1))
key = (animal, video_folder, trial_index)
if key not in lookup:
matched_vf = _best_matching_video_folder(video_folder, csv_by_animal.get(animal, [])) if animal else None
if matched_vf is not None:
key = (animal, matched_vf, trial_index)
if key not in lookup:
continue
time_to_target = lookup[key]
reward_frame = int(frame_start + time_to_target * VIDEO_FPS)
out[trial_id] = reward_frame
return out
def _get_reward_frame_per_trial(
trials_list: list[tuple[Path, str, str | None]],
logs_dir: Path,
animal: str,
) -> dict[str, int]:
"""Resolve reward frame for each trial_id from robot_manager.log. Returns dict trial_id -> reward_frame (video frame index).
Uses time_to_target = door open -> reward (sec); reward_frame = frame_start + time_to_target * VIDEO_FPS."""
try:
from cbot_climb_log.analyze_logs import parse_robot_manager_log
from cbot_climb_log.extract_trial_frames import find_matching_log_session
except ImportError:
return {}
logs_dir = Path(logs_dir)
if not logs_dir.is_dir():
return {}
animal_lower = animal.strip().lower()
out: dict[str, int] = {}
for csv_path, trial_id, session_folder in trials_list:
if not session_folder or not session_folder.lower().startswith(f"{animal_lower}_"):
continue
frames = _parse_trial_frames(trial_id)
if not frames:
continue
frame_start, _ = frames
parts = session_folder.split("_", 1)
animal_name = parts[0].lower() if len(parts) > 1 else animal_lower
video_folder = parts[1] if len(parts) > 1 else ""
log_path = find_matching_log_session(video_folder, animal_name, logs_dir)
if log_path is None:
continue
_, training = parse_robot_manager_log(log_path)
trial_num = int(TRIAL_PATTERN.match(trial_id).group(1))
if trial_num >= len(training):
continue
time_to_target = training[trial_num][4]
if time_to_target is None:
continue
reward_frame = int(frame_start + time_to_target * VIDEO_FPS)
out[trial_id] = reward_frame
return out
def _ordered_uvz_frame_path(df: pd.DataFrame) -> np.ndarray:
"""Return (N, 4) array of (u, v, z, frame_number) along path."""
if "u" not in df.columns or "v" not in df.columns:
return np.zeros((0, 4))
rows = []
for seg_id in sorted(df["segment_id"].unique()):
seg = df[df["segment_id"] == seg_id].sort_values("frame_number")
rows.append(seg[["u", "v", "z", "frame_number"]].values.astype(float))
if not rows:
return np.zeros((0, 4))
return np.vstack(rows)
def uv_limits(trials_list: list[tuple[Path, str, str | None]], margin: float = 0.05) -> tuple[float, float, float, float]:
"""Compute u_min, u_max, v_min, v_max from trajectory CSVs (after load_trajectory_csv filters)."""
all_u, all_v = [], []
for csv_path, _, _ in trials_list:
df = at.load_trajectory_csv(csv_path)
if len(df) < 1 or "u" not in df.columns or "v" not in df.columns:
continue
all_u.extend(df["u"].tolist())
all_v.extend(df["v"].tolist())
if not all_u or not all_v:
return 0.0, 1000.0, 0.0, 1000.0
u_min, u_max = min(all_u), max(all_u)
v_min, v_max = min(all_v), max(all_v)
du = (u_max - u_min) or 1
dv = (v_max - v_min) or 1
u_min -= margin * du
u_max += margin * du
v_min -= margin * dv
v_max += margin * dv
return u_min, u_max, v_min, v_max
def _compute_flow_field_grids(
trials_list: list[tuple[Path, str, str | None]],
u_min: float,
u_max: float,
v_min: float,
v_max: float,
n_bins: int = 40,
) -> tuple[
np.ndarray, np.ndarray, np.ndarray,
np.ndarray, np.ndarray, np.ndarray, np.ndarray,
np.ndarray, float, float, float, float,
]:
"""Build elevation grid, flow, and mesh. Returns (elev_grid, u_edges, v_edges, flow_u, flow_v, UU, VV, mean_vel, scale, elev_vmin, elev_vmax)."""
u_edges = np.linspace(u_min, u_max, n_bins + 1)
v_edges = np.linspace(v_min, v_max, n_bins + 1)
sum_z_elev = np.zeros((n_bins, n_bins))
count_z = np.zeros((n_bins, n_bins))
sum_du = np.zeros((n_bins, n_bins))
sum_dv = np.zeros((n_bins, n_bins))
sum_w = np.zeros((n_bins, n_bins)) + 1e-12
sum_vel = np.zeros((n_bins, n_bins))
for csv_path, _, _ in trials_list:
df = at.load_trajectory_csv(csv_path)
if len(df) < 2 or "u" not in df.columns or "v" not in df.columns:
continue
uvzf = _ordered_uvz_frame_path(df)
if len(uvzf) < 2:
continue
u_vals, v_vals = uvzf[:, 0], uvzf[:, 1]
z_vals, frames = uvzf[:, 2], uvzf[:, 3]
for k in range(len(uvzf)):
iu = np.searchsorted(u_edges, u_vals[k], side="right") - 1
iv = np.searchsorted(v_edges, v_vals[k], side="right") - 1
iu = max(0, min(iu, n_bins - 1))
iv = max(0, min(iv, n_bins - 1))
sum_z_elev[iv, iu] += z_vals[k]
count_z[iv, iu] += 1
for i in range(len(uvzf) - 1):
du = u_vals[i + 1] - u_vals[i]
dv = v_vals[i + 1] - v_vals[i]
dz = z_vals[i + 1] - z_vals[i]
dt = (frames[i + 1] - frames[i]) / FPS
if dt <= 0 or max(0.0, dz) <= 0:
continue
weight = max(0.0, dz)
mid_u = (u_vals[i] + u_vals[i + 1]) / 2
mid_v = (v_vals[i] + v_vals[i + 1]) / 2
iu = np.searchsorted(u_edges, mid_u, side="right") - 1
iv = np.searchsorted(v_edges, mid_v, side="right") - 1
iu = max(0, min(iu, n_bins - 1))
iv = max(0, min(iv, n_bins - 1))
raw_vel = np.sqrt(du * du + dv * dv) / dt
sum_du[iv, iu] += du * weight
sum_dv[iv, iu] += dv * weight
sum_w[iv, iu] += weight
sum_vel[iv, iu] += raw_vel * weight
with np.errstate(divide="ignore", invalid="ignore"):
flow_u = sum_du / sum_w
flow_v = sum_dv / sum_w
elev_grid = np.where(count_z > 0, sum_z_elev / count_z, np.nan)
cu = (u_edges[:-1] + u_edges[1:]) / 2
cv = (v_edges[:-1] + v_edges[1:]) / 2
UU, VV = np.meshgrid(cu, cv)
speed = np.sqrt(flow_u ** 2 + flow_v ** 2)
scale = np.percentile(speed[speed > 0], 95) / (0.05 * (u_max - u_min)) if (speed > 0).any() else 1.0
scale = max(scale, 1e-6) * 2.5
mean_vel = np.where(sum_w > 1e-10, sum_vel / sum_w, 0.0)
elev_vmin = np.nanmin(elev_grid) if np.any(np.isfinite(elev_grid)) else 0.0
elev_vmax = np.nanmax(elev_grid) if np.any(np.isfinite(elev_grid)) else 1.0
return elev_grid, u_edges, v_edges, flow_u, flow_v, UU, VV, mean_vel, scale, elev_vmin, elev_vmax
def _find_two_high_z_peaks(
elev_grid: np.ndarray,
u_edges: np.ndarray,
v_edges: np.ndarray,
) -> list[tuple[float, float]]:
"""Find the two highest local maxima; return list of (u_center, v_center) for the two peaks."""
filled = np.nan_to_num(elev_grid, nan=-np.inf, posinf=0, neginf=-np.inf)
if not np.any(np.isfinite(elev_grid)):
return []
smoothed = ndimage.gaussian_filter(filled, sigma=1.0, mode="constant", cval=-np.inf)
nv, nu = elev_grid.shape
peaks = []
for iv in range(1, nv - 1):
for iu in range(1, nu - 1):
v = smoothed[iv, iu]
if v <= -np.inf or not np.isfinite(v):
continue
if v >= smoothed[iv - 1 : iv + 2, iu - 1 : iu + 2].max() and np.isfinite(elev_grid[iv, iu]):
cu = (u_edges[iu] + u_edges[iu + 1]) / 2
cv = (v_edges[iv] + v_edges[iv + 1]) / 2
peaks.append((elev_grid[iv, iu], cu, cv))
peaks.sort(key=lambda x: -x[0])
return [(u, v) for (_, u, v) in peaks[:2]]
def _flow_field_uv_highlight_high_z(
trials_list: list[tuple[Path, str, str | None]],
u_min: float,
u_max: float,
v_min: float,
v_max: float,
out_path: Path,
title_suffix: str = "",
params_override: dict | None = None,
) -> tuple[float, float, float, float, float] | None:
"""Single-panel: elevation + flow with two regions split by v. Returns (v_mid, goal1_u, goal1_v, goal2_u, goal2_v).
If params_override is provided (e.g. from another animal's midline_and_goals.json), use it for midline and goals
instead of auto-detecting peaks."""
global GOAL_RECT_GEOM
if len(trials_list) == 0:
return None
elev_grid, u_edges, v_edges, flow_u, flow_v, UU, VV, _mean_vel, scale, elev_vmin, elev_vmax = _compute_flow_field_grids(
trials_list, u_min, u_max, v_min, v_max
)
if params_override is not None:
v_mid = float(params_override["v_mid"])
g1_u = float(params_override["goal1_u"])
g1_v = float(params_override["goal1_v"])
g2_u = float(params_override["goal2_u"])
g2_v = float(params_override["goal2_v"])
if "half_u" in params_override:
GOAL_RECT_GEOM = {
"half_u": float(params_override["half_u"]),
"top_bottom": float(params_override["top_bottom"]),
"top_top": float(params_override["top_top"]),
"bottom_bottom": float(params_override["bottom_bottom"]),
"bottom_top": float(params_override["bottom_top"]),
}
else:
GOAL_RECT_GEOM = _goal_rect_geom_from_params(v_mid, g1_u, g1_v, g2_u, g2_v, u_min, u_max, v_min, v_max)
half_u = GOAL_RECT_GEOM["half_u"]
rect_top_bottom = GOAL_RECT_GEOM["top_bottom"]
rect_top_top = GOAL_RECT_GEOM["top_top"]
rect_bottom_bottom = GOAL_RECT_GEOM["bottom_bottom"]
rect_bottom_top = GOAL_RECT_GEOM["bottom_top"]
v1, v2 = (g1_v, g2_v) if g1_v < g2_v else (g2_v, g1_v)
else:
peaks = _find_two_high_z_peaks(elev_grid, u_edges, v_edges)
if len(peaks) < 2:
return None
(u1, v1), (u2, v2) = peaks[0], peaks[1]
v_mid = (v1 + v2) / 2.0
# --- Derive extended goal regions around the two high-z peaks ---
cu = (u_edges[:-1] + u_edges[1:]) / 2.0
cv = (v_edges[:-1] + v_edges[1:]) / 2.0
CU, CV = np.meshgrid(cu, cv)
elev_vals = elev_grid[np.isfinite(elev_grid)]
if elev_vals.size == 0:
return None
max_elev = float(elev_vals.max())
z_thresh = 50.0 if max_elev > 50.0 else float(np.percentile(elev_vals, 80.0))
high_mask = np.isfinite(elev_grid) & (elev_grid >= z_thresh)
top_mask = high_mask & (CV < v_mid)
bottom_mask = high_mask & (CV >= v_mid)
def _half_extents_for_peak(u_peak: float, v_peak: float) -> tuple[float, float]:
du = (u_max - u_min) * 0.05
dv_raw = abs(v_mid - v_peak) * 0.45
max_dv = max(5.0, abs(v_mid - v_peak) - 10.0)
dv = min(dv_raw, max_dv)
return float(max(8.0, du)), float(max(10.0, dv))
half_u1, _ = _half_extents_for_peak(u1, v1)
half_u2, _ = _half_extents_for_peak(u2, v2)
half_u = min(half_u1, half_u2)
top_y = CV[top_mask]
bottom_y = CV[bottom_mask]
if top_y.size > 0:
band_top_bottom = float(np.min(top_y))
band_top_top = float(min(v_mid - 5.0, np.max(top_y) + 5.0))
else:
band_top_bottom = float(max(v_min, v1 - 20.0))
band_top_top = float(min(v_mid - 5.0, v1 + 20.0))
if bottom_y.size > 0:
band_bottom_bottom = float(max(v_mid + 5.0, np.min(bottom_y) - 5.0))
band_bottom_top = float(min(v_max, np.max(bottom_y) + 5.0))
else:
band_bottom_bottom = float(max(v_mid + 5.0, v2 - 20.0))
band_bottom_top = float(min(v_max, v2 + 20.0))
base_height = min(
max(0.0, band_top_top - band_top_bottom),
max(0.0, band_bottom_top - band_bottom_bottom),
)
rect_height = max(15.0, 0.7 * base_height)
margin = 5.0
rect_top_top = v_mid - margin
rect_top_bottom = max(v_min, rect_top_top - rect_height)
rect_bottom_bottom = v_mid + margin
rect_bottom_top = min(v_max, rect_bottom_bottom + rect_height)
GOAL_RECT_GEOM = {
"half_u": half_u,
"top_bottom": rect_top_bottom,
"top_top": rect_top_top,
"bottom_bottom": rect_bottom_bottom,
"bottom_top": rect_bottom_top,
}
g1_u, g1_v = u1, v1
g2_u, g2_v = u2, v2
fig, ax = plt.subplots(1, 1, figsize=(10, 8))
ax.set_xlim(u_min, u_max)
ax.set_ylim(v_max, v_min)
ax.set_aspect("equal")
ax.set_xlabel("u (px)")
ax.set_ylabel("v (px)")
if np.any(np.isfinite(elev_grid)):
im = ax.pcolormesh(u_edges, v_edges, elev_grid, cmap="turbo", shading="flat", vmin=elev_vmin, vmax=elev_vmax, alpha=0.9, zorder=0)
plt.colorbar(im, ax=ax, label="elevation z", shrink=0.7)
# Two regions: split along v = v_mid. Shade so red region contains (u1,v1), blue contains (u2,v2).
color_red, color_blue = "#e63946", "#1d3557"
if v1 < v_mid: # red dot in top half (smaller v)
ax.axhspan(v_min, v_mid, alpha=0.25, color=color_red, zorder=1)
ax.axhspan(v_mid, v_max, alpha=0.25, color=color_blue, zorder=1)
else:
ax.axhspan(v_mid, v_max, alpha=0.25, color=color_red, zorder=1)
ax.axhspan(v_min, v_mid, alpha=0.25, color=color_blue, zorder=1)
ax.axhline(v_mid, color="black", linewidth=2, zorder=9)
ax.quiver(UU, VV, flow_u, flow_v, color="black", alpha=0.9, scale_units="xy", scale=scale, width=0.006, headwidth=3, headlength=4, edgecolor="white", linewidth=0.2, zorder=5)
# Draw high-z goal regions as symmetric rectangles (one per side of the midline).
def _add_goal_rect(u_peak: float, v_peak: float, color: str) -> None:
# Horizontal extent is symmetric around u_peak
left = u_peak - half_u
width = 2 * half_u
# Vertical extent: same height on both sides, anchored near the midline,
# slightly narrower than the full z>=60 band.
if v_peak < v_mid:
bottom = rect_top_bottom
top = rect_top_top
else:
bottom = rect_bottom_bottom
top = rect_bottom_top
height = max(0.0, top - bottom)
if height <= 0.0:
return
rect = Rectangle((left, bottom), width, height, linewidth=2.0, edgecolor=color, facecolor="none", linestyle="--", zorder=10)
ax.add_patch(rect)
_add_goal_rect(g1_u, g1_v, color_red)
_add_goal_rect(g2_u, g2_v, color_blue)
# Mark goal points
ax.plot(g1_u, g1_v, "o", color=color_red, markersize=10, markeredgecolor="white", markeredgewidth=2, zorder=11)
ax.plot(g2_u, g2_v, "o", color=color_blue, markersize=10, markeredgecolor="white", markeredgewidth=2, zorder=11)
ax.annotate("Goal region 1", (g1_u, g1_v), xytext=(8, 8), textcoords="offset points", fontsize=11, fontweight="bold", color=color_red)
ax.annotate("Goal region 2", (g2_u, g2_v), xytext=(8, 8), textcoords="offset points", fontsize=11, fontweight="bold", color=color_blue)
ax.set_title("Elevation + flow (u-v) — two regions split by v" + title_suffix)
plt.tight_layout()
fig.savefig(out_path, dpi=150, bbox_inches="tight")
plt.close()
return (v_mid, g1_u, g1_v, g2_u, g2_v)
def _flow_field_uv_two_panels(
trials_list: list[tuple[Path, str, str | None]],
u_min: float,
u_max: float,
v_min: float,
v_max: float,
out_path: Path,
title_suffix: str = "",
) -> None:
"""Flow field in u-v space: elevation + flow direction, speed + flow direction. v-axis inverted for camera view."""
if len(trials_list) == 0:
return
elev_grid, u_edges, v_edges, flow_u, flow_v, UU, VV, mean_vel, scale, elev_vmin, elev_vmax = _compute_flow_field_grids(
trials_list, u_min, u_max, v_min, v_max
)
speed = np.sqrt(flow_u ** 2 + flow_v ** 2)
vel_finite = mean_vel[(mean_vel > 0) & np.isfinite(mean_vel)]
vmin_vel = np.percentile(vel_finite, 10) if len(vel_finite) > 0 else 0.0
vmax_vel = np.percentile(vel_finite, 95) if len(vel_finite) > 0 else 1.0
fig2, (ax_left, ax_right) = plt.subplots(1, 2, figsize=(18, 8))
for ax in (ax_left, ax_right):
ax.set_xlim(u_min, u_max)
ax.set_ylim(v_max, v_min) # invert v for camera view
ax.set_aspect("equal")
ax.set_xlabel("u (px)")
ax.set_ylabel("v (px)")
if np.any(np.isfinite(elev_grid)):
im = ax_left.pcolormesh(u_edges, v_edges, elev_grid, cmap="turbo", shading="flat", vmin=elev_vmin, vmax=elev_vmax, alpha=0.9, zorder=0)
plt.colorbar(im, ax=ax_left, label="elevation z", shrink=0.7)
q_left = ax_left.quiver(UU, VV, flow_u, flow_v, color="black", alpha=0.9, scale_units="xy", scale=scale, width=0.006, headwidth=3, headlength=4, edgecolor="white", linewidth=0.2, zorder=10)
ax_left.quiverkey(q_left, 0.88, 0.96, np.percentile(speed[speed > 0], 50) if (speed > 0).any() else 1.0, "flow", coordinates="axes")
ax_left.set_title("Elevation + flow direction (u-v)" + title_suffix)
speed_display = np.where(mean_vel > 0, mean_vel, np.nan)
cmap_turbo = plt.cm.turbo.copy()
cmap_turbo.set_bad("white")
im_speed = ax_right.pcolormesh(u_edges, v_edges, speed_display, cmap=cmap_turbo, shading="flat", vmin=vmin_vel, vmax=vmax_vel, alpha=0.9, zorder=0)
plt.colorbar(im_speed, ax=ax_right, label="speed (px/s)", shrink=0.7)
q_right = ax_right.quiver(UU, VV, flow_u, flow_v, color="black", alpha=0.9, scale_units="xy", scale=scale, width=0.006, headwidth=3, headlength=4, edgecolor="white", linewidth=0.2, zorder=10)
ax_right.quiverkey(q_right, 0.88, 0.96, np.percentile(speed[speed > 0], 50) if (speed > 0).any() else 1.0, "flow", coordinates="axes")
ax_right.set_title("Flow speed + flow direction (u-v)" + title_suffix)
plt.tight_layout()
fig2.savefig(out_path, dpi=150, bbox_inches="tight")
plt.close()
def _goal_rect_geom_from_params(
v_mid: float,
g1_u: float,
g1_v: float,
g2_u: float,
g2_v: float,
u_min: float,
u_max: float,
v_min: float,
v_max: float,
) -> dict:
"""Compute GOAL_RECT_GEOM from midline and goal points (e.g. loaded from another animal's JSON)."""
half_u = max(8.0, (u_max - u_min) * 0.05)
margin = 5.0
v_above = min(g1_v, g2_v)
v_below = max(g1_v, g2_v)
dist_top = max(0.0, v_mid - margin - v_above)
dist_bottom = max(0.0, v_below - (v_mid + margin))
rect_height = 0.7 * min(dist_top, dist_bottom) if (dist_top > 0 and dist_bottom > 0) else 80.0
rect_height = max(rect_height, 15.0)
rect_top_top = v_mid - margin
rect_top_bottom = max(v_min, rect_top_top - rect_height)
rect_bottom_bottom = v_mid + margin
rect_bottom_top = min(v_max, rect_bottom_bottom + rect_height)
return {
"half_u": half_u,
"top_bottom": rect_top_bottom,
"top_top": rect_top_top,
"bottom_bottom": rect_bottom_bottom,
"bottom_top": rect_bottom_top,
}
# Midline crossing: when goal positions are given, "crossing" = clearly heading toward the *other* dot
# (past the midpoint between v_mid and that goal). Otherwise fallback to fixed tolerance (px).
MIDLINE_CROSSING_TOLERANCE_PX = 25.0
def _path_crossing_count(
v_vals: np.ndarray,
v_mid: float,
tolerance: float | None = None,
goal1_v: float | None = None,
goal2_v: float | None = None,
) -> int:
"""Number of times the path crosses the midline toward the other goal.
When goal1_v and goal2_v are provided: count only when path goes clearly toward the other dot,
i.e. past the midpoint between v_mid and that goal (so it's clearly committed to the other side).
Otherwise use tolerance (px) each side of v_mid. Smaller v = top of image (one goal), larger v = bottom."""
if len(v_vals) < 2:
return 0
if goal1_v is not None and goal2_v is not None:
v_above_goal = min(goal1_v, goal2_v)
v_below_goal = max(goal1_v, goal2_v)
# Past midpoint toward each goal = "clearly on that side"
v_thresh_toward_top = (v_mid + v_above_goal) / 2.0
v_thresh_toward_bottom = (v_mid + v_below_goal) / 2.0
# above = toward top goal (smaller v); below = toward bottom goal (larger v)
use_toward_top = -1
use_toward_bottom = 1
else:
tol = tolerance if tolerance is not None and tolerance >= 0 else MIDLINE_CROSSING_TOLERANCE_PX
v_thresh_toward_top = v_mid - tol
v_thresh_toward_bottom = v_mid + tol
use_toward_top = -1
use_toward_bottom = 1
count = 0
last_side = None
for v in v_vals:
if v <= v_thresh_toward_top:
side = use_toward_top
elif v >= v_thresh_toward_bottom:
side = use_toward_bottom
else:
side = 0
if side != 0:
if last_side is not None and side != last_side:
count += 1
last_side = side
return count
def _point_goal_region(
u: float,
v: float,
params: dict,
) -> int:
"""Return 1 if (u,v) is inside goal1 rectangle, 2 if inside goal2 rectangle, 0 otherwise.
Uses rectangular geometry derived in _flow_field_uv_highlight_high_z (GOAL_RECT_GEOM)."""
geom = GOAL_RECT_GEOM
if geom is None:
return 0
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 g1_v is None or g2_u is None or g2_v is None:
return 0
half_u = float(geom.get("half_u", 0.0))
top_bottom = float(geom.get("top_bottom", v_mid))
top_top = float(geom.get("top_top", v_mid))
bottom_bottom = float(geom.get("bottom_bottom", v_mid))
bottom_top = float(geom.get("bottom_top", v_mid))
# Goal 1 is the one on the same side of v_mid as (goal1_v)
if g1_v < v_mid:
# goal1 in top rectangle, goal2 in bottom
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:
# goal1 in bottom rectangle, goal2 in top
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 _path_crosses_midline(
v_vals: np.ndarray,
v_mid: float,
tolerance: float | None = None,
goal1_v: float | None = None,
goal2_v: float | None = None,
) -> bool:
"""True if path clearly crosses the midline toward the other goal (see _path_crossing_count)."""
return _path_crossing_count(v_vals, v_mid, tolerance, goal1_v, goal2_v) > 0
def _trial_goal_hits(
df: pd.DataFrame,
params: dict,
) -> tuple[bool, bool]:
"""Return (hits_goal1, hits_goal2) based on whether the path ever enters each goal rectangle."""
if len(df) < 1 or "u" not in df.columns or "v" not in df.columns:
return (False, False)
hit1 = False
hit2 = False
for u, v in zip(df["u"].values, df["v"].values):
lab = _point_goal_region(float(u), float(v), params)
if lab == 1:
hit1 = True
elif lab == 2:
hit2 = True
if hit1 and hit2:
break
return (hit1, hit2)
def _classify_trials_by_goal_region(
trials_list: list[tuple[Path, str, str | None]],
reward_frame_by_trial: dict[str, int],
params: dict,
) -> tuple[list[str], list[str]]:
"""Classify trials that visit only goal1 region or only goal2 region (start → reward)."""
goal1_only: list[str] = []
goal2_only: list[str] = []
for csv_path, trial_id, _ in trials_list:
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
df = at.load_trajectory_csv(csv_path)
if len(df) < 1 or "u" not in df.columns or "v" not in df.columns:
continue
mask = (df["frame_number"] >= frame_start) & (df["frame_number"] <= reward_frame)
df_tr = df.loc[mask].sort_values("frame_number")
if len(df_tr) < 1:
continue
hit1, hit2 = _trial_goal_hits(df_tr, params)
if hit1 and not hit2:
goal1_only.append(trial_id)
elif hit2 and not hit1:
goal2_only.append(trial_id)
return (goal1_only, goal2_only)
def _first_goal_visited(
df: pd.DataFrame,
params: dict,
) -> int:
"""Return 1 or 2 for the first goal rectangle the path enters, 0 if it never enters either."""
if len(df) < 1 or "u" not in df.columns or "v" not in df.columns:
return 0
for u, v in zip(df["u"].values, df["v"].values):
lab = _point_goal_region(float(u), float(v), params)
if lab in (1, 2):
return lab
return 0
def _get_first_goal_visit_locations(
trials_list: list[tuple[Path, str, str | None]],
reward_frame_by_trial: dict[str, int],
params: dict,
) -> list[tuple[int, float, float, int]]:
"""Return (goal_label, u, v, phase_id) for each trial's first entry into either goal rectangle.
phase_id: 0=early, 1=mid, 2=late."""
early, mid, late = _split_phase_trials(trials_list)
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
out: list[tuple[int, float, float, int]] = []
for csv_path, trial_id, _ in trials_list:
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
df = at.load_trajectory_csv(csv_path)
if len(df) < 1 or "u" not in df.columns or "v" not in df.columns:
continue
mask = (df["frame_number"] >= frame_start) & (df["frame_number"] <= reward_frame)
df_tr = df.loc[mask].sort_values("frame_number")
for _, row in df_tr.iterrows():
u, v = float(row["u"]), float(row["v"])
lab = _point_goal_region(u, v, params)
if lab in (1, 2):
phase_id = trial_to_phase.get(trial_id, 0)
out.append((lab, u, v, phase_id))
break
return out
def _get_first_visit_to_goal_when_other_first_locations(
trials_list: list[tuple[Path, str, str | None]],
reward_frame_by_trial: dict[str, int],
params: dict,
) -> tuple[list[tuple[float, float, int]], list[tuple[float, float, int]], dict[str, tuple[int, int, int]]]:
"""First visit to goal 1 when goal 2 was visited first, and first visit to goal 2 when goal 1 was visited first.
Only trials that visit BOTH goals are included; trials that visit only one goal are excluded.
Returns (list of (u, v, phase_id) for first entry to goal 1 in trials that visited goal 2 first,
list of (u, v, phase_id) for first entry to goal 2 in trials that visited goal 1 first,
per_phase_counts: phase_name -> (n_both_goals, n_goal2_first_then_goal1, n_goal1_first_then_goal2))."""
early, mid, late = _split_phase_trials(trials_list)
trial_to_phase: dict[str, int] = {}
for t in early:
trial_to_phase[str(t[1])] = 0
for t in mid:
trial_to_phase[str(t[1])] = 1
for t in late:
trial_to_phase[str(t[1])] = 2
phase_names = ["early", "mid", "late"]
per_phase: dict[str, tuple[int, int, int]] = {p: (0, 0, 0) for p in phase_names}
first_visit_to_goal1_when_goal2_first: list[tuple[float, float, int]] = []
first_visit_to_goal2_when_goal1_first: list[tuple[float, float, int]] = []
for csv_path, trial_id, _ in trials_list:
trial_id_str = str(trial_id)
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
df = at.load_trajectory_csv(csv_path)
if len(df) < 1 or "u" not in df.columns or "v" not in df.columns:
continue
mask = (df["frame_number"] >= frame_start) & (df["frame_number"] <= reward_frame)
df_tr = df.loc[mask].sort_values("frame_number")
# Build ordered list of (goal, u, v) at each entry into a goal (transition from 0 or from other goal)
entries: list[tuple[int, float, float]] = []
prev_lab = 0
for _, row in df_tr.iterrows():
u, v = float(row["u"]), float(row["v"])
lab = _point_goal_region(u, v, params)
if lab in (1, 2) and lab != prev_lab:
entries.append((lab, u, v))
prev_lab = lab if lab != 0 else prev_lab
if not entries:
continue
# Only count trials that visit BOTH goals (have at least one entry to each)
has_goal1 = any(g == 1 for g, _, _ in entries)
has_goal2 = any(g == 2 for g, _, _ in entries)
if not (has_goal1 and has_goal2):
continue
phase_id = trial_to_phase.get(trial_id_str, 0)
pname = phase_names[phase_id]
n_both, n_g2_first, n_g1_first = per_phase[pname]
per_phase[pname] = (n_both + 1, n_g2_first, n_g1_first)
first_goal = entries[0][0]
if first_goal == 1:
for g, u, v in entries:
if g == 2:
first_visit_to_goal2_when_goal1_first.append((u, v, phase_id))
per_phase[pname] = (n_both + 1, n_g2_first, n_g1_first + 1)
break
else:
for g, u, v in entries:
if g == 1:
first_visit_to_goal1_when_goal2_first.append((u, v, phase_id))
per_phase[pname] = (n_both + 1, n_g2_first + 1, n_g1_first)
break
return (first_visit_to_goal1_when_goal2_first, first_visit_to_goal2_when_goal1_first, per_phase)
def _goal_rect_bounds(params: dict, goal_label: int) -> tuple[float, float, float, float] | None:
"""Return (u_lo, u_hi, v_lo, v_hi) for the given goal rectangle (1 or 2)."""
geom = GOAL_RECT_GEOM
if geom is None:
return None
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 None
half_u = float(geom.get("half_u", 0.0))
top_bottom = float(geom.get("top_bottom", v_mid))
top_top = float(geom.get("top_top", v_mid))
bottom_bottom = float(geom.get("bottom_bottom", v_mid))
bottom_top = float(geom.get("bottom_top", v_mid))
if goal_label == 1:
u_center = g1_u
if g1_v < v_mid:
v_lo, v_hi = top_bottom, top_top
else:
v_lo, v_hi = bottom_bottom, bottom_top
else:
u_center = g2_u
if g2_v < v_mid:
v_lo, v_hi = top_bottom, top_top
else:
v_lo, v_hi = bottom_bottom, bottom_top
u_lo = u_center - half_u
u_hi = u_center + half_u
return (u_lo, u_hi, v_lo, v_hi)
def _classify_trials_by_first_goal(
trials_list: list[tuple[Path, str, str | None]],
reward_frame_by_trial: dict[str, int],
params: dict,
) -> tuple[list[str], list[str]]:
"""Return (first_goal_left_ids, first_goal_right_ids). Left = smaller u; right = larger u."""
g1_u = params.get("goal1_u")
g2_u = params.get("goal2_u")
if g1_u is None or g2_u is None:
return ([], [])
left_goal = 1 if g1_u < g2_u else 2
right_goal = 2 if g1_u < g2_u else 1
first_left: list[str] = []
first_right: list[str] = []
for csv_path, trial_id, _ in trials_list:
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
df = at.load_trajectory_csv(csv_path)
if len(df) < 1 or "u" not in df.columns or "v" not in df.columns:
continue
mask = (df["frame_number"] >= frame_start) & (df["frame_number"] <= reward_frame)
df_tr = df.loc[mask].sort_values("frame_number")
if len(df_tr) < 1:
continue
fg = _first_goal_visited(df_tr, params)
if fg == left_goal:
first_left.append(trial_id)
elif fg == right_goal:
first_right.append(trial_id)
return (first_left, first_right)
def _count_goal_regions_visited(
df: pd.DataFrame,
params: dict,
) -> int:
"""Return 0, 1, or 2: number of distinct goal rectangles the path enters."""
hit1, hit2 = _trial_goal_hits(df, params)
return (1 if hit1 else 0) + (1 if hit2 else 0)
def _get_both_goals_crossing_events(
trials_list: list[tuple[Path, str, str | None]],
reward_frame_by_trial: dict[str, int],
params: dict,
) -> list[tuple[str, int, float, float, int, int, int]]:
"""For trials that visit both goals, return (trial_id, frame, u, v, phase_id, frame_start, reward_frame) at first transition.
phase_id: 0=early, 1=mid, 2=late. Uses chronological order of trials_list for phase assignment."""
early, mid, late = _split_phase_trials(trials_list)
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
events: list[tuple[str, int, float, float, int, int, int]] = []
for csv_path, trial_id, _ in trials_list:
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
df = at.load_trajectory_csv(csv_path)
if len(df) < 2 or "u" not in df.columns or "v" not in df.columns:
continue
mask = (df["frame_number"] >= frame_start) & (df["frame_number"] <= reward_frame)
df_tr = df.loc[mask].sort_values("frame_number").reset_index(drop=True)
if len(df_tr) < 2:
continue
hit1, hit2 = _trial_goal_hits(df_tr, params)
if not (hit1 and hit2):
continue
# Find first transition from one goal to the other (first point in the second goal)
prev_lab = 0
for i in range(len(df_tr)):
row = df_tr.iloc[i]
u, v = float(row["u"]), float(row["v"])
lab = _point_goal_region(u, v, params)
if lab == 0:
continue
if prev_lab != 0 and lab != prev_lab:
frame = int(row["frame_number"])
phase_id = trial_to_phase.get(trial_id, 0)
events.append((trial_id, frame, u, v, phase_id, frame_start, reward_frame))
break
prev_lab = lab
return events
def _path_crossing_u_locations(
u_vals: np.ndarray,
v_vals: np.ndarray,
v_mid: float,
goal1_v: float | None = None,
goal2_v: float | None = None,
tolerance: float | None = None,
) -> list[float]:
"""Return u-coordinates where the path crosses the midline (same goal-based logic as _path_crossing_count)."""
if len(u_vals) < 2 or len(v_vals) < 2 or len(u_vals) != len(v_vals):
return []
if goal1_v is not None and goal2_v is not None:
v_above_goal = min(goal1_v, goal2_v)
v_below_goal = max(goal1_v, goal2_v)
v_thresh_toward_top = (v_mid + v_above_goal) / 2.0
v_thresh_toward_bottom = (v_mid + v_below_goal) / 2.0
else:
tol = tolerance if tolerance is not None and tolerance >= 0 else MIDLINE_CROSSING_TOLERANCE_PX
v_thresh_toward_top = v_mid - tol
v_thresh_toward_bottom = v_mid + tol
def side(v: float) -> int:
if v <= v_thresh_toward_top:
return -1
if v >= v_thresh_toward_bottom:
return 1
return 0
out: list[float] = []
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:
v0, v1 = float(v_vals[i - 1]), float(v_vals[i])
if v1 != v0:
t = (v_mid - v0) / (v1 - v0)
u_cross = float(u_vals[i - 1]) + t * (float(u_vals[i]) - float(u_vals[i - 1]))
out.append(u_cross)
if s != 0:
last_side = s
return out
def _classify_trials_by_crossing_count(
trials_list: list[tuple[Path, str, str | None]],