File size: 41,258 Bytes
868a5eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Helpers for scripts/refine_v2.py (per-episode calibration refinement v2; DIAGNOSIS P1.1/P1.2/P1.3/P1.5).

Everything here is pure numpy / cv2 / scipy plus the render_episode API (RobotRenderer, EpisodeSession);
the heavy work (rendering) runs in a pool of worker processes (RenderPool), each owning its own
EpisodeSession and a cache of pre-processed real frames (FrameData) for the steps it was given.

Objective (per camera, evaluated at EVAL_SCALE = 0.5 of the real MP4 size, K via dutils.scale_K_to):
  * GT mode  (out/gt/<uuid>/.gt_done): loss = (1 - IoU(render, GT) on ROI = (GT | render) dilated
    ROI_DIL_FULL px) + LAMBDA_R2G * r2g, r2g = render-silhouette-edge -> GT-edge distance (bilinear
    sampling of the GT edge distance transform at sub-pixel edge positions), clipped at BAND_PX,
    trimmed mean (worst TRIM_FRAC dropped).  With opts['trim_far'] > 0 the IoU union drops GT pixels
    farther than that many eval-res px from the rendered silhouette (far-trimmed IoU: cables along the
    arm, SAM3 blobs, held objects beyond the pads); per-step prec / far_frac / iou_full are reported.
    opts['dark_fallback']: a step pushed without a GT mask is scored with the dark-pixel objective (wrist).
  * Canny mode (no GT): symmetric band-limited chamfer = 0.5 * (render-edge -> real Canny edge DT,
    clipped) + 0.5 * (real Canny edges inside a +-BAND_PX band around the silhouette -> render edge
    DT, clipped).  Steps whose silhouette ring has < min_edge px (MIN_EDGE_PX at 640x360) are
    EXCLUDED from the mean (never scored with a constant).
  * Wrist fallback (no wrist GT): (1 - IoU(gripper render, dark pixels inside the render ROI)) +
    LAMBDA_R2G * render-edge -> real-edge chamfer, with a held-object guard (dark area >> render).
Sub-pixel edge positions: boundary ring pixels moved along the gradient of the Gaussian-smoothed
mask to the 0.5 iso-level (for a binary mask this puts the edge on the pixel border; with
supersample > 1 the soft mask carries true fractional coverage).
"""
import datetime as dtm
import json
import multiprocessing as mp
import os
import re
import sys
import time
from pathlib import Path

import cv2
import numpy as np
from scipy.optimize import minimize
from scipy.spatial.transform import Rotation as R

HERE = Path(__file__).resolve().parent
if str(HERE) not in sys.path:
    sys.path.insert(0, str(HERE))
from dutils import ROOT, _load_superset, mat_to_pose6, pose6_to_mat, scale_K, scale_K_to  # noqa: E402
import render_episode as RE  # noqa: E402

cv2.setNumThreads(1)

# ----------------------------------------------------------------------------- constants
EVAL_SCALE = 0.5                 # objective resolution relative to the real MP4 (1280x720 -> 640x360)
REF_EVAL_PX = 640 * 360          # reference area for pixel-count thresholds
MIN_EDGE_PX = 3000               # silhouette ring px (3x3 morph gradient) at 640x360 to score a step
MIN_EDGE_PX_RELAXED = 1500       # fallback when too few steps pass (flagged)
MIN_EDGE_LADDER = (3000, 1500, 800)  # first rung at which >= 50 % of the selected steps are scorable is used
TIME_SPEED_LADDER = ((0.10, 8), (0.05, 4))  # (min EE speed, min #steps) for the time-stage step set, else all steps
WRIST_MIN_EDGE_PX = 500          # gripper-only wrist render: sanity threshold only (ring px at 640x360)
MIN_AREA_FRAC = 0.05             # in-view: rendered area >= 5 % of the image
MIN_SPEED_MPS = 0.10             # moving step: EE speed >= 0.1 m/s
N_STEPS_EXT = 16                 # steps per exterior camera (fit)
N_STEPS_WRIST = 16               # steps for the wrist stage (open + closed)
MIN_STEPS_OK = 6                 # fewer -> quality 'degraded'
MIN_VALID_STEPS = 3              # fewer valid steps in an evaluation -> infeasible (BIG)
BAND_PX = 15.0                   # band / clip for the fine stages (eval-res px)
COARSE_CLIP_PX = 25.0            # clip for the coarse multi-start stage (longer capture range)
ROI_DIL_FULL = 60                # GT-mode ROI dilation in full-res px
LAMBDA_R2G = 0.02                # weight of r2g (eval-res px) against (1 - IoU)
TRIM_FRAC = 0.10                 # trimmed mean: drop this fraction of the worst edge points / steps
MIN_GT_PX = 800                  # GT mask smaller than this at eval res: step unusable
DARK_THR = 60                    # wrist fallback: gray < DARK_THR is 'gripper-dark'
DARK_ROI_DIL = 25                # eval-res px around the gripper render
DARK_GUARD_RATIO = 1.6           # dark area in ROI > ratio * render area -> held object / dark scene -> skip
BIG = 1e3                        # objective value for infeasible parameter sets
GT_TRIM_FAR_FULL = 60.0          # GT pixels farther than this (px at 1280x720) from the render are dropped from the
                                 # IoU union (cables / hallucinated blobs; the GT->render 'far fraction' of
                                 # benchmark_align uses the same 60 px); 0 = plain IoU
GT_RESCUE_IOU = 0.50             # wrist: a non-usable GT step (SAM3 status failed/marginal) is adopted when its IoU
                                 # at the first-pass solution is >= this (the 'failed' gate of gt_masks_scale is
                                 # IoU vs the DEFAULT render, which is itself off by 30-100 px on many wrist cams)
GT_SUPPORT_IOU = 0.25            # flip test: a step 'supports' a start pose when its IoU there is >= this
WRIST_MIN_STEPS_FULL = 8         # fewer scorable wrist steps -> rescue pass over the non-usable GT steps
WRIST_FLIP_BASELINE_M = 0.063    # ZED Mini stereo baseline: a 180-deg-rolled camera puts the left lens where the
                                 # right one was -> the flip start is roll 180 deg + (+-baseline, 0, 0)
WRIST_FLIP_MARGIN_IOU = 0.10     # the flipped hypothesis must beat identity by this much (post-NM mean IoU)
CAND_FINE_RATIO, CAND_FINE_MAX = 1.5, 2   # ext: every base-pose candidate whose coarse loss is within this ratio of the best
                                          # one (at most CAND_FINE_MAX candidates) gets the 6-DoF fine stage; the best FINAL
                                          # loss wins (the 4-DoF coarse stage alone can stall on a 5-cm candidate)
NONRIGID_IOU, NONRIGID_R2G = 0.80, 3.0   # gt mode: iou_after < .8 and r2g_after > 3 eval px (6 px full) with a
                                         # flat time sweep -> note 'nonrigid_suspect' (mobile-cart stations)

TIME_DEFAULT_MS = float(RE.TIME_OFFSET_DEFAULT_MS)   # +37 ms
TIME_SIGMA_MS = 25.0
TIME_BOUND_MS = 70.0
TIME_GRID_MS = 5.0
TIME_PRIOR_W = 0.05              # prior weight on the median-normalised data term
FLAT_RANGE_REL = 0.20            # sweep range / max < this -> 'flat'
MULTI_PROMINENCE = 0.25          # secondary minimum with barrier >= this * range -> 'multi'

EXT_PRIOR_SIGMA = {"GT": (0.02, np.deg2rad(2.0)), "Pred": (0.08, np.deg2rad(5.0))}
EXT_HARD_T_M, EXT_HARD_R_RAD = 0.15, np.deg2rad(15.0)
WRIST_PRIOR_SIGMA = (0.05, np.deg2rad(5.0))
WRIST_HARD_T_M, WRIST_HARD_R_RAD = 0.15, np.deg2rad(30.0)
PRIOR_FRAC = 0.15                # prior weight = PRIOR_FRAC * max(data term at start, floor)
PRIOR_FLOOR = {"canny": 1.0, "gt": 0.05, "dark": 0.05}

# status thresholds (metric after)
CANNY_FAILED_PX, CANNY_DEGRADED_PX = 10.0, 5.0
GT_FAILED_IOU, GT_DEGRADED_IOU = 0.50, 0.70
DARK_FAILED_IOU, DARK_DEGRADED_IOU = 0.35, 0.55

GT_USABLE_STATUS = ("ok", "single", "low_conf", "render_far_off", "render_missing_robot")  # per gt_masks_scale doc
GT_RESCUE_STATUS = ("failed", "marginal", "low_conf")   # statuses a wrist rescue pass may adopt (mask file must exist)
NO_V2 = str(ROOT / "nonexistent_calib_v2__refine_v2.json")   # EpisodeSession(calib_v2=...) -> never read an existing v2
K3 = np.ones((3, 3), np.uint8)
VERSION = "refine_v2 2026-10-17b (far-trimmed GT IoU, flip multi-start, wrist rescue, robust quality)"


def log(msg):
    print(f"[refine_v2 {time.strftime('%H:%M:%S')}] {msg}", flush=True)


# ----------------------------------------------------------------------------- small math helpers

def rot_angle(rvec_euler):
    return float(R.from_euler("xyz", np.asarray(rvec_euler, dtype=float)).magnitude())


def pose_dist(p, q):
    """(translation m, rotation rad) between two pose6."""
    Tp, Tq = pose6_to_mat(p), pose6_to_mat(q)
    dt = float(np.linalg.norm(Tp[:3, 3] - Tq[:3, 3]))
    dr = float((R.from_matrix(Tp[:3, :3]) * R.from_matrix(Tq[:3, :3]).inv()).magnitude())
    return dt, dr


def tmean(v, frac=TRIM_FRAC):
    """Trimmed mean: drop the largest `frac` of the values (at least keep 1)."""
    v = np.asarray(v, dtype=np.float64).ravel()
    if v.size == 0:
        return float("nan")
    k = max(1, int(np.floor(v.size * (1.0 - frac))))
    if k >= v.size:
        return float(v.mean())
    return float(np.partition(v, k - 1)[:k].mean())


def simplex_around(x0, scales, idx=None):
    """Explicit Nelder-Mead initial simplex: x0 and x0 + scale_i * e_i for the free indices."""
    x0 = np.asarray(x0, dtype=float)
    idx = list(range(len(x0))) if idx is None else list(idx)
    S = [x0.copy()]
    for i, j in enumerate(idx):
        v = x0.copy()
        v[j] += scales[i] if np.ndim(scales) else scales
        S.append(v)
    return np.array(S)


def ee_speed_per_step(cart_xyz, t_state_ms):
    """Per-step EE speed (m/s) from cartesian positions (same rule as scripts/diag/make_sample.py)."""
    pos = np.asarray(cart_xyz, dtype=float)[:, :3]
    t = np.asarray(t_state_ms, dtype=float) / 1000.0
    if len(pos) < 2:
        return np.zeros(len(pos))
    dt = np.diff(t)
    good = dt > 0
    dt[~good] = np.median(dt[good]) if good.any() else 1 / 15.0
    v = np.linalg.norm(np.diff(pos, axis=0), axis=1) / dt
    s = np.zeros(len(pos))
    s[1:-1] = 0.5 * (v[:-1] + v[1:])
    s[0], s[-1] = v[0], v[-1]
    return s


def uuid_datetime(u):
    """datetime from 'LAB+user+YYYY-MM-DD-HHh-MMm-SSs' (None if unparsable)."""
    m = re.search(r"(\d{4}-\d{2}-\d{2})-(\d{2})h-(\d{2})m-(\d{2})s", u)
    if not m:
        return None
    try:
        return dtm.datetime.strptime(f"{m.group(1)} {m.group(2)}:{m.group(3)}:{m.group(4)}", "%Y-%m-%d %H:%M:%S")
    except ValueError:
        return None


# ----------------------------------------------------------------------------- candidate poses

def gt_neighbor_candidates(uuid, serial, calib_dir=None, max_days=7, n_max=2):
    """GT-source cam->base poses of the same lab + serial from the superset, nearest in time first:
    [{'pose6', 'uuid', 'days', 'hours', 'n_same_pose'}].  Candidate 1 = nearest episode in time;
    candidate 2 = the most frequent pose of that same day if it differs (> 5 mm / 0.5 deg)."""
    calib_dir = Path(calib_dir) if calib_dir else ROOT / "calib"
    sup = _load_superset(str(calib_dir / "cam2base_extrinsic_superset.json"))
    lab = uuid.split("+")[0]
    t0 = uuid_datetime(uuid)
    if t0 is None:
        return []
    rows = []
    for u, e in sup.items():
        if u == uuid or not u.startswith(lab + "+") or serial not in e or e.get(f"{serial}_source") != "GT":
            continue
        t = uuid_datetime(u)
        if t is None:
            continue
        dt_h = abs((t - t0).total_seconds()) / 3600.0
        if dt_h <= max_days * 24.0:
            rows.append((dt_h, u, np.asarray(e[serial], dtype=float)))
    if not rows:
        return []
    rows.sort(key=lambda r: r[0])
    out = []
    nearest = rows[0]
    same_day = [r for r in rows if r[1].split("+")[2][:10] == nearest[1].split("+")[2][:10]]
    # frequency of (rounded) poses on the nearest day
    keys = {}
    for r in same_day:
        k = tuple(np.round(r[2], 3))
        keys.setdefault(k, []).append(r)
    n_same = len(keys.get(tuple(np.round(nearest[2], 3)), []))
    out.append(dict(pose6=nearest[2], uuid=nearest[1], days=nearest[0] / 24.0, hours=nearest[0], n_same_pose=n_same))
    if len(out) < n_max and keys:
        kbest = max(keys, key=lambda k: len(keys[k]))
        rbest = keys[kbest][0]
        dt_, dr_ = pose_dist(rbest[2], nearest[2])
        if dt_ > 0.005 or dr_ > np.deg2rad(0.5):
            out.append(dict(pose6=rbest[2], uuid=rbest[1], days=rbest[0] / 24.0, hours=rbest[0], n_same_pose=len(keys[kbest])))
    return out[:n_max]


def load_session_delta(uuid, serial, path=None):
    """calib/session_deltas.json entry for (uuid, serial) or None:
    {'session_id', 'official_pose6', 'delta', 'n_episodes', ...}."""
    path = Path(path) if path else ROOT / "calib/session_deltas.json"
    if not path.exists():
        return None
    try:
        j = json.load(open(path))
    except (OSError, ValueError):
        return None
    sid = (j.get("episode_sessions", {}).get(uuid) or {}).get(serial)
    if sid is None:
        return None
    s = (j.get("sessions") or {}).get(sid)
    if not s:
        return None
    d = dict(s)
    d["session_id"] = sid
    return d


# ----------------------------------------------------------------------------- GT masks at scale

def gt_available(uuid, gt_root=None):
    gt_root = Path(gt_root) if gt_root else ROOT / "out/gt"
    return (gt_root / uuid / ".gt_done").exists()


def load_gt_steps(uuid, gt_root=None):
    """-> (steps {serial: [record]}, status {serial: {step(str): status}}) from out/gt/<uuid>."""
    gt_root = Path(gt_root) if gt_root else ROOT / "out/gt"
    d = gt_root / uuid
    steps, status = {}, {}
    try:
        steps = json.load(open(d / "steps.json"))
    except (OSError, ValueError):
        steps = {}
    try:
        status = json.load(open(d / "status.json"))
    except (OSError, ValueError):
        status = {}
    return steps, status


def gt_mask_path(uuid, serial, step, gt_root=None):
    gt_root = Path(gt_root) if gt_root else ROOT / "out/gt"
    return gt_root / uuid / str(serial) / f"{int(step):04d}.png"


def usable_gt_steps(uuid, serial, gt_root=None, statuses=GT_USABLE_STATUS):
    """Steps of one camera with a GT mask file whose status is in `statuses`: [(step, record)] (record from
    steps.json or {}).  statuses=None: every step with a mask file."""
    steps, status = load_gt_steps(uuid, gt_root)
    recs = {int(r["step"]): r for r in (steps.get(str(serial)) or []) if "step" in r}
    st = status.get(str(serial)) or {}
    out = []
    cands = set(recs) | {int(k) for k in st.keys() if str(k).lstrip("-").isdigit()}
    for s in sorted(cands):
        stt = st.get(str(s), st.get(s, "ok" if s in recs else None))
        if statuses is not None and stt is not None and stt not in statuses:
            continue
        if gt_mask_path(uuid, serial, s, gt_root).exists():
            out.append((s, dict(recs.get(s, {}), status=stt)))
    return out


# ----------------------------------------------------------------------------- frames

def decode_frames_small(video, steps, wh_small):
    """Sequential decode (seeking is unreliable on these MP4s) -> {step: gray uint8 at wh_small},
    plus the number of decoded frames.  INTER_AREA keeps the pixel-centre convention of scale_K."""
    want = set(int(s) for s in steps)
    out = {}
    if not want:
        return out, 0
    cap = cv2.VideoCapture(str(video))
    i, last = 0, max(want)
    try:
        while i <= last:
            ok, fr = cap.read()
            if not ok:
                break
            if i in want:
                g = cv2.cvtColor(fr, cv2.COLOR_BGR2GRAY)
                out[i] = cv2.resize(g, tuple(int(v) for v in wh_small), interpolation=cv2.INTER_AREA)
            i += 1
    finally:
        cap.release()
    return out, i


def edge_mask(b):
    return cv2.morphologyEx(b.astype(np.uint8), cv2.MORPH_GRADIENT, K3) > 0


def dist_to(mask_true):
    """Distance (px) of every pixel to the nearest True pixel (exact L2)."""
    return cv2.distanceTransform((~mask_true).astype(np.uint8), cv2.DIST_L2, cv2.DIST_MASK_PRECISE).astype(np.float32)


def build_frame_data(gray_small, gt_small=None, roi_dil=None):
    """FrameData dict for one (camera, step): Canny edges + DT of the real image, optional GT mask,
    GT edge DT and GT dilation (all at eval resolution)."""
    E = cv2.Canny(gray_small, 40, 120) > 0
    fd = {"gray": gray_small, "E": E, "DT": dist_to(E)}
    if gt_small is not None:
        gt = gt_small.astype(bool)
        fd["gt"] = gt
        fd["gt_px"] = int(gt.sum())
        fd["DT_gt"] = dist_to(edge_mask(gt)) if fd["gt_px"] > 0 else None
        r = int(roi_dil) if roi_dil else int(round(ROI_DIL_FULL * EVAL_SCALE))
        ker = np.ones((2 * r + 1, 2 * r + 1), np.uint8)
        fd["roi_gt"] = cv2.dilate(gt.astype(np.uint8), ker) > 0
    return fd


def load_gt_small(path, wh_small):
    m = cv2.imread(str(path), cv2.IMREAD_GRAYSCALE)
    if m is None:
        return None
    return cv2.resize(m, tuple(int(v) for v in wh_small), interpolation=cv2.INTER_AREA) >= 128


# ----------------------------------------------------------------------------- per-step losses

def edge_points(mf):
    """Sub-pixel silhouette edge points of a soft mask (float32 in [0,1]) -> (pts Nx2 (x,y), n_ring).
    Ring = 3x3 morphological gradient of (mf > 0.5); each ring pixel is moved along the gradient of
    the Gaussian-smoothed mask to the 0.5 iso-level (|offset| <= 1 px)."""
    b = (mf > 0.5).astype(np.uint8)
    ring = cv2.morphologyEx(b, cv2.MORPH_GRADIENT, K3)
    ys, xs = np.nonzero(ring)
    n = int(len(xs))
    if n == 0:
        return np.zeros((0, 2), np.float32), 0
    sm = cv2.GaussianBlur(mf, (0, 0), 1.0)
    gx = cv2.Sobel(sm, cv2.CV_32F, 1, 0, ksize=3, scale=1.0 / 8.0)
    gy = cv2.Sobel(sm, cv2.CV_32F, 0, 1, ksize=3, scale=1.0 / 8.0)
    g = np.stack([gx[ys, xs], gy[ys, xs]], axis=1)
    gn = np.linalg.norm(g, axis=1) + 1e-6
    off = np.clip((0.5 - sm[ys, xs]) / gn, -1.0, 1.0)
    pts = np.stack([xs + off * g[:, 0] / gn, ys + off * g[:, 1] / gn], axis=1).astype(np.float32)
    return pts, n


def sample_bilinear(img, pts):
    if len(pts) == 0:
        return np.zeros(0, np.float32)
    mapx = np.ascontiguousarray(pts[:, 0]).reshape(1, -1)
    mapy = np.ascontiguousarray(pts[:, 1]).reshape(1, -1)
    return cv2.remap(img, mapx, mapy, cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE).ravel()


def _rect(r):
    r = int(round(r))
    return np.ones((2 * r + 1, 2 * r + 1), np.uint8)


def loss_canny(fd, mf, min_edge, clip=BAND_PX, band=BAND_PX):
    """Symmetric band-limited chamfer (eval-res px) of a render soft mask against real Canny edges."""
    area = float(mf.sum())
    pts, n_edge = edge_points(mf)
    if n_edge < min_edge:
        return dict(valid=False, n_edge=n_edge, area=area, why="edge<min")
    d1 = np.minimum(sample_bilinear(fd["DT"], pts), clip)
    r2r = tmean(d1)
    b = (mf > 0.5).astype(np.uint8)
    ker = _rect(band)
    bandmask = (cv2.dilate(b, ker) > 0) & ~(cv2.erode(b, ker) > 0)
    sel = fd["E"] & bandmask
    if int(sel.sum()) >= 50:
        DT_r = dist_to(edge_mask(b > 0))
        real2r = tmean(np.minimum(DT_r[sel], clip))
    else:
        real2r = float(clip)
    return dict(valid=True, loss=0.5 * (r2r + real2r), r2r=r2r, real2r=real2r, n_edge=n_edge, area=area)


def loss_gt(fd, mf, band=BAND_PX, lam=LAMBDA_R2G, roi_dil=None, trim_far=0.0):
    """(1 - IoU on ROI = (GT | render) dilated) + lam * trimmed band-clipped r2g.
    trim_far > 0 (eval-res px): GT pixels farther than trim_far from the rendered silhouette are dropped from
    the union (far-trimmed IoU; cables along the arm, SAM3 blobs elsewhere, held objects beyond the pads).
    Identical to the plain IoU when the GT has no far pixels.  Diagnostics returned per step: iou_full
    (untrimmed), prec (|render & GT| / |render|), far_frac (fraction of GT pixels farther than trim_far
    or GT_TRIM_FAR_FULL*EVAL_SCALE from the render)."""
    area = float(mf.sum())
    if fd.get("gt") is None or fd.get("gt_px", 0) < MIN_GT_PX:
        return dict(valid=False, area=area, why="gt<min")
    gt = fd["gt"]
    b = (mf > 0.5).astype(np.uint8)
    r = int(roi_dil) if roi_dil else int(round(ROI_DIL_FULL * EVAL_SCALE))
    roi = fd["roi_gt"] | (cv2.dilate(b, _rect(r)) > 0)
    gtf = gt.astype(np.float32)
    inter = float(np.minimum(mf, gtf)[roi].sum())
    union = float(np.maximum(mf, gtf)[roi].sum())
    iou_full = inter / union if union > 0 else 0.0
    prec = inter / area if area > 0 else 0.0
    far_px = float(trim_far) if trim_far and trim_far > 0 else float(GT_TRIM_FAR_FULL * EVAL_SCALE)
    if b.any():
        dt_r = dist_to(b > 0)
        far = dt_r[gt] > far_px
        far_frac = float(far.mean()) if far.size else 0.0
    else:
        far_frac = 1.0
    iou = iou_full
    if trim_far and trim_far > 0 and far_frac > 0:
        if not b.any():
            iou = 0.0                       # empty render: nothing near the GT -> trimmed IoU 0 (plain IoU is 0 too)
        else:
            gtf_near = gtf.copy()
            gtf_near[gt & (dt_r > far_px)] = 0.0
            union_t = float(np.maximum(mf, gtf_near)[roi].sum())
            iou = inter / union_t if union_t > 0 else 0.0
    pts, n_edge = edge_points(mf)
    if n_edge == 0 or fd["DT_gt"] is None:
        r2g = float(band)
    else:
        r2g = tmean(np.minimum(sample_bilinear(fd["DT_gt"], pts), band))
    return dict(valid=True, loss=(1.0 - iou) + lam * r2g, iou=iou, iou_full=iou_full, prec=prec, far_frac=far_frac,
                r2g=r2g, n_edge=n_edge, area=area)


def loss_dark(fd, mf, min_edge, clip=BAND_PX, lam=LAMBDA_R2G):
    """Wrist fallback: gripper render vs dark pixels in the render ROI + render-edge -> real-edge chamfer,
    with a held-object guard."""
    area = float(mf.sum())
    b = (mf > 0.5).astype(np.uint8)
    n_b = int(b.sum())
    if n_b < 500:
        return dict(valid=False, area=area, why="render<500")
    roi = cv2.dilate(b, _rect(DARK_ROI_DIL)) > 0
    dark = (fd["gray"] < DARK_THR) & roi
    n_dark = int(dark.sum())
    if n_dark > DARK_GUARD_RATIO * n_b:
        return dict(valid=False, area=area, why="dark_guard", dark_ratio=n_dark / n_b)
    if n_dark < 0.2 * n_b:
        return dict(valid=False, area=area, why="too_few_dark", dark_ratio=n_dark / n_b)
    df = dark.astype(np.float32)
    inter = float(np.minimum(mf, df).sum())
    union = float(np.maximum(mf, df).sum())
    iou = inter / union if union > 0 else 0.0
    pts, n_edge = edge_points(mf)
    if n_edge < min_edge:
        return dict(valid=False, area=area, why="edge<min", n_edge=n_edge)
    r2r = tmean(np.minimum(sample_bilinear(fd["DT"], pts), clip))
    return dict(valid=True, loss=(1.0 - iou) + lam * r2r, iou=iou, r2r=r2r, n_edge=n_edge, area=area,
                dark_ratio=n_dark / n_b)


def aggregate(results, trim=TRIM_FRAC, penalty=None):
    """Camera loss over per-step results: trimmed mean of the step losses (worst 10 % dropped when
    >= 8 steps).  penalty=None: invalid steps are EXCLUDED (selection / start evaluations);
    penalty=<float>: a step that was valid at the stage start but became invalid (render shrank /
    left the view) counts with that loss, so an optimiser cannot gain by excluding steps.
    -> dict(loss, n_valid, n, mean_iou, mean_r2g, ...) or None when nothing is valid."""
    valid = [r for r in results if r.get("valid")]
    n_valid = len(valid)
    if n_valid == 0:
        return None
    vals = [r["loss"] for r in valid]
    if penalty is not None:
        vals += [float(penalty)] * (len(results) - n_valid)
    losses = np.sort(np.array(vals, dtype=float))
    n_l = len(losses)
    k = n_l - (int(np.ceil(trim * n_l)) if n_l >= 8 else 0)
    out = dict(loss=float(losses[:k].mean()), loss_mean=float(losses.mean()), n_valid=n_valid, n=len(results),
               n_penalized=0 if penalty is None else len(results) - n_valid)
    for key in ("iou", "iou_full", "prec", "far_frac", "r2g", "r2r", "real2r", "n_edge", "area"):
        vals = [r[key] for r in valid if key in r and r[key] is not None]
        if vals:
            out["mean_" + key] = float(np.mean(vals))
    ious = [r["iou"] for r in valid if r.get("iou") is not None]
    if ious:
        out["median_iou"] = float(np.median(ious))
        out["frac_iou_ge_0p5"] = float(np.mean([v >= 0.5 for v in ious]))
        out["n_iou_lt_0p5"] = int(sum(v < 0.5 for v in ious))
    n_dark = sum(1 for r in valid if r.get("mode") == "dark")
    if n_dark:
        out["n_dark_fallback"] = int(n_dark)
    return out


def invalid_penalty(mode, opts):
    """Loss assigned to a step that leaves the valid set during an optimisation stage."""
    if mode == "canny":
        return float(opts.get("clip", BAND_PX))
    lam = float(opts.get("lam", LAMBDA_R2G))
    return 1.0 + lam * float(opts.get("band", BAND_PX) if mode == "gt" else opts.get("clip", BAND_PX))


# ----------------------------------------------------------------------------- worker process

def _render_soft_mask(sess, serial, step, dt_total, K, wh, T=None, D=None, supersample=1, grip_only=False):
    """Set the state at cap_ts[serial][step] + dt_total and render -> float32 soft mask at wh."""
    q, g = sess.state_at(float(sess.cap_ts[serial][step]) + float(dt_total))
    sess.rr.set_state(q, g)
    if T is None:
        D = np.eye(4) if D is None else D
        T = D @ np.linalg.inv(sess.rr.T_l8 @ sess.X_handeye)
    w, h = int(wh[0]), int(wh[1])
    ss = int(supersample)
    if ss > 1:
        K2, wh2 = scale_K(K, ss), (w * ss, h * ss)
    else:
        K2, wh2 = K, (w, h)
    _, _, seg = sess.rr.render_raw(T, K2, wh2)
    if grip_only:
        valid = seg >= 0
        body = np.where(valid, seg & ((1 << 24) - 1), -1)
        m = body == sess.rr.gripper
    else:
        m = seg >= 0
    mf = m.astype(np.float32)
    if ss > 1:
        mf = cv2.resize(mf, (w, h), interpolation=cv2.INTER_AREA)
    return mf


def _worker_main(conn, ep_dir, wrist, worker_id):
    os.environ.setdefault("OMP_NUM_THREADS", "1")
    cv2.setNumThreads(1)
    RE.VERBOSE = False
    try:
        sess = RE.EpisodeSession(ep_dir, wrist=wrist, calib_v2=NO_V2)
    except Exception as e:  # report and die
        conn.send(("error", repr(e)))
        return
    conn.send(("ready", worker_id))
    frames = {}
    cams = {}  # serial -> (K_eval, wh_eval)
    while True:
        try:
            msg = conn.recv()
        except EOFError:
            break
        cmd = msg[0]
        try:
            if cmd == "quit":
                conn.send(("ok", None))
                break
            if cmd == "set_cam":
                _, serial, K, wh = msg
                cams[str(serial)] = (np.asarray(K, dtype=float), (int(wh[0]), int(wh[1])))
                conn.send(("ok", None))
            elif cmd == "frames":
                _, serial, fds = msg
                for st, fd in fds.items():
                    frames[(str(serial), int(st))] = fd
                conn.send(("ok", len(frames)))
            elif cmd == "area":
                _, serial, steps, dt_total, T, opts = msg
                K, wh = cams[str(serial)]
                out = []
                for st in steps:
                    mf = _render_soft_mask(sess, str(serial), int(st), dt_total, K, wh, T=None if T is None else np.asarray(T),
                                           D=None, supersample=1, grip_only=bool(opts.get("grip_only", False)))
                    b = mf > 0.5
                    out.append(dict(step=int(st), area=float(b.sum()), n_edge=int(edge_mask(b).sum())))
                conn.send(("ok", out))
            elif cmd == "eval":
                _, serial, steps, dt_total, T, D, mode, opts = msg
                K, wh = cams[str(serial)]
                Tm = None if T is None else np.asarray(T, dtype=float)
                Dm = None if D is None else np.asarray(D, dtype=float)
                ss = int(opts.get("supersample", 1))
                out = []
                for st in steps:
                    fd = frames.get((str(serial), int(st)))
                    if fd is None:
                        out.append(dict(step=int(st), valid=False, why="no_frame"))
                        continue
                    mf = _render_soft_mask(sess, str(serial), int(st), dt_total, K, wh, T=Tm, D=Dm, supersample=ss,
                                           grip_only=bool(opts.get("grip_only", False)))
                    if mode == "gt" and fd.get("gt") is None and opts.get("dark_fallback"):
                        # wrist: step without a GT mask scored with the dark-pixel objective (same scale)
                        r = loss_dark(fd, mf, opts.get("min_edge", MIN_EDGE_PX), clip=opts.get("clip", BAND_PX),
                                      lam=opts.get("lam", LAMBDA_R2G))
                        r["mode"] = "dark"
                    elif mode == "gt":
                        r = loss_gt(fd, mf, band=opts.get("band", BAND_PX), lam=opts.get("lam", LAMBDA_R2G),
                                    trim_far=float(opts.get("trim_far", 0.0) or 0.0))
                    elif mode == "dark":
                        r = loss_dark(fd, mf, opts.get("min_edge", MIN_EDGE_PX), clip=opts.get("clip", BAND_PX),
                                      lam=opts.get("lam", LAMBDA_R2G))
                    else:
                        r = loss_canny(fd, mf, opts.get("min_edge", MIN_EDGE_PX), clip=opts.get("clip", BAND_PX),
                                       band=opts.get("band", BAND_PX))
                    r["step"] = int(st)
                    out.append(r)
                conn.send(("ok", out))
            else:
                conn.send(("error", f"unknown command {cmd!r}"))
        except Exception as e:
            import traceback
            conn.send(("error", f"{e!r}\n{traceback.format_exc()}"))


class RenderPool:
    """N worker processes (spawn), each with its own EpisodeSession + renderer and a cache of
    FrameData for the steps it owns.  Steps of a camera are assigned to workers on first push
    (balanced), and every evaluation sends each worker only its own steps."""

    def __init__(self, ep_dir, n_workers=8, wrist=False):
        self.ctx = mp.get_context("spawn")
        self.n = max(1, int(n_workers))
        self.conns, self.procs = [], []
        for i in range(self.n):
            a, b = self.ctx.Pipe()
            p = self.ctx.Process(target=_worker_main, args=(b, str(ep_dir), bool(wrist), i), daemon=True)
            p.start()
            self.conns.append(a)
            self.procs.append(p)
        for c in self.conns:
            tag, payload = c.recv()
            if tag != "ready":
                raise RuntimeError(f"worker failed to start: {payload}")
        self.owner = {}      # (serial, step) -> worker index
        self.load = [0] * self.n
        self.n_eval = 0
        self.n_render = 0
        self.t_eval = 0.0

    # -- plumbing ------------------------------------------------------------------------
    def _send_recv(self, targets, msgs):
        for i, m in zip(targets, msgs):
            self.conns[i].send(m)
        outs = []
        for i in targets:
            tag, payload = self.conns[i].recv()
            if tag != "ok":
                raise RuntimeError(f"worker {i}: {payload}")
            outs.append(payload)
        return outs

    def broadcast(self, msg):
        return self._send_recv(list(range(self.n)), [msg] * self.n)

    def close(self):
        try:
            self.broadcast(("quit",))
        except Exception:
            pass
        for p in self.procs:
            p.join(timeout=5)
            if p.is_alive():
                p.terminate()

    # -- camera / frames -----------------------------------------------------------------
    def set_camera(self, serial, K_eval, wh_eval):
        self.broadcast(("set_cam", str(serial), np.asarray(K_eval, dtype=float), (int(wh_eval[0]), int(wh_eval[1]))))

    def push_frames(self, serial, fds):
        """fds: {step: FrameData}; assigns owners for new steps (least-loaded worker first)."""
        per = [dict() for _ in range(self.n)]
        for st, fd in fds.items():
            key = (str(serial), int(st))
            if key not in self.owner:
                i = int(np.argmin(self.load))
                self.owner[key] = i
                self.load[i] += 1
            per[self.owner[key]][int(st)] = fd
        targets = [i for i in range(self.n) if per[i]]
        if targets:
            self._send_recv(targets, [("frames", str(serial), per[i]) for i in targets])

    def has_frame(self, serial, step):
        return (str(serial), int(step)) in self.owner

    # -- evaluations ---------------------------------------------------------------------
    def areas(self, serial, steps, dt_total, T, grip_only=False):
        """Rendered area (px at eval res) and ring edge count for each step at pose T (exterior) or the
        h5 wrist pose (T=None).  -> {step: (area, n_edge)}"""
        steps = [int(s) for s in steps]
        if not steps:
            return {}
        chunks = [steps[i::self.n] for i in range(self.n)]
        targets = [i for i in range(self.n) if chunks[i]]
        outs = self._send_recv(targets, [("area", str(serial), chunks[i], float(dt_total),
                                          None if T is None else np.asarray(T), {"grip_only": grip_only}) for i in targets])
        res = {}
        for o in outs:
            for r in o:
                res[r["step"]] = (r["area"], r["n_edge"])
        self.n_render += len(steps)
        return res

    def evaluate(self, serial, steps, dt_total, T=None, D=None, mode="canny", opts=None):
        """Per-step loss records (in `steps` order).  T: base->cam 4x4 (exterior); D: camera-frame
        TOTAL wrist delta 4x4 (wrist, T=None)."""
        t0 = time.time()
        opts = dict(opts or {})
        steps = [int(s) for s in steps]
        per = [[] for _ in range(self.n)]
        for st in steps:
            i = self.owner.get((str(serial), st))
            if i is None:
                raise KeyError(f"no frame pushed for {serial}/{st}")
            per[i].append(st)
        targets = [i for i in range(self.n) if per[i]]
        outs = self._send_recv(targets, [("eval", str(serial), per[i], float(dt_total),
                                          None if T is None else np.asarray(T, dtype=float),
                                          None if D is None else np.asarray(D, dtype=float), mode, opts) for i in targets])
        by_step = {}
        for o in outs:
            for r in o:
                by_step[r["step"]] = r
        self.n_eval += 1
        self.n_render += len(steps)
        self.t_eval += time.time() - t0
        return [by_step[s] for s in steps]


# ----------------------------------------------------------------------------- step selection

def select_spread(cands, score, n, lo, hi):
    """Pick up to n steps from `cands` spread over [lo, hi]: the best-scoring candidate in each of n
    equal time bins, then the best remaining ones (never two within a minimum gap)."""
    cands = sorted(set(int(c) for c in cands))
    if not cands or n <= 0:
        return []
    edges = np.linspace(lo, hi + 1, n + 1)
    chosen = []
    for b in range(n):
        inb = [c for c in cands if edges[b] <= c < edges[b + 1]]
        if inb:
            chosen.append(max(inb, key=lambda c: score[c]))
    gap = max(1, (hi - lo + 1) // (3 * n))
    rest = sorted((c for c in cands if c not in chosen), key=lambda c: -score[c])
    for c in rest:
        if len(chosen) >= n:
            break
        if all(abs(c - k) >= gap for k in chosen):
            chosen.append(c)
    return sorted(chosen)


def select_ext_steps(area_frac, speed, n_steps, n_total, min_area=MIN_AREA_FRAC, min_speed=MIN_SPEED_MPS):
    """In-view / moving step selector (local re-implementation of the gt_masks_scale rule).
    area_frac: {step: rendered area fraction at the base pose}; speed: per-step EE speed (m/s).
    -> (steps, info)"""
    lo, hi = 2, n_total - 3
    inview = [s for s, a in area_frac.items() if a >= min_area and lo <= s <= hi]
    moving = [s for s in inview if speed[s] >= min_speed]
    score = {s: float(speed[s]) + 1e-3 * area_frac[s] for s in inview}
    sel = select_spread(moving, score, n_steps, lo, hi)
    if len(sel) < n_steps:
        static = [s for s in inview if s not in sel]
        sel = sorted(set(sel) | set(select_spread(static, {s: area_frac[s] for s in static}, n_steps - len(sel), lo, hi)))
    info = dict(n_inview=len(inview), n_moving=len(moving), n_selected=len(sel),
                n_selected_moving=sum(1 for s in sel if speed[s] >= min_speed), n_probed=len(area_frac))
    return sel, info


def select_wrist_steps(gs, n_total, n_steps=N_STEPS_WRIST, area_frac=None):
    """Steps spanning open (g < 0.3) and closed (g > 0.5) gripper, spread over the episode."""
    lo, hi = 2, n_total - 3
    valid = [s for s in range(lo, hi + 1) if area_frac is None or area_frac.get(s, 1.0) >= 0.02]
    g = np.asarray(gs, dtype=float)
    open_ = [s for s in valid if g[s] < 0.3]
    closed = [s for s in valid if g[s] > 0.5]
    mid = [s for s in valid if s not in open_ and s not in closed]
    half = n_steps // 2
    sel = select_spread(open_, {s: 1.0 - g[s] for s in open_}, half, lo, hi)
    sel += select_spread(closed, {s: g[s] for s in closed}, n_steps - len(sel), lo, hi)
    if len(sel) < n_steps:
        pool = [s for s in open_ + closed + mid if s not in sel]
        sel += select_spread(pool, {s: 1.0 for s in pool}, n_steps - len(sel), lo, hi)
    sel = sorted(set(sel))
    info = dict(n_open=len(open_), n_closed=len(closed), n_selected=len(sel),
                n_sel_open=sum(1 for s in sel if g[s] < 0.3), n_sel_closed=sum(1 for s in sel if g[s] > 0.5))
    return sel, info


# ----------------------------------------------------------------------------- sweep classification

def classify_sweep(curve, grid):
    """'V' | 'flat' | 'edge' | 'multi' | 'none' for a 1-D objective curve over `grid`."""
    c = np.asarray(curve, dtype=float)
    ok = np.isfinite(c)
    if ok.sum() < 3:
        return "none", dict(range_rel=float("nan"))
    cmax, cmin = float(np.nanmax(c)), float(np.nanmin(c))
    rng = cmax - cmin
    range_rel = rng / max(abs(cmax), 1e-9)
    info = dict(range_rel=float(range_rel), range=float(rng), argmin_ms=float(grid[int(np.nanargmin(c))]))
    if range_rel < FLAT_RANGE_REL:
        return "flat", info
    i0 = int(np.nanargmin(c))
    if i0 == 0 or i0 == len(c) - 1:
        return "edge", info
    # secondary minima separated from the global one by a barrier >= MULTI_PROMINENCE * range
    minima = [i for i in range(1, len(c) - 1) if ok[i] and c[i] <= c[i - 1] and c[i] <= c[i + 1] and i != i0]
    n_multi = 0
    for i in minima:
        a, b = sorted((i, i0))
        barrier = float(np.nanmax(c[a:b + 1])) - max(c[i], c[i0])
        if barrier >= MULTI_PROMINENCE * rng and (c[i] - cmin) <= 0.5 * rng:
            n_multi += 1
    info["n_secondary_minima"] = n_multi
    return ("multi" if n_multi > 0 else "V"), info


def parabolic_vertex(x, y):
    """Vertex of the parabola through three points (x[-1,0,1], y) clamped inside [x0, x2]."""
    x0, x1, x2 = x
    y0, y1, y2 = y
    denom = (y0 - 2 * y1 + y2)
    if not np.isfinite(denom) or abs(denom) < 1e-12:
        return float(x1)
    h = x1 - x0
    xv = x1 - h * (y2 - y0) / (2.0 * denom)
    return float(np.clip(xv, x0, x2))


# ----------------------------------------------------------------------------- Nelder-Mead wrapper

def run_nm(fun, x0, idx, scales, maxfev, xatol=1e-4, fatol=1e-5):
    """Nelder-Mead over the parameter subset `idx` of a 6-vector with an explicit initial simplex.
    Returns (x6, fun_value, nfev, message); never returns a point worse than the start."""
    x0 = np.asarray(x0, dtype=float).copy()
    idx = list(idx)
    sub0 = x0[idx]

    def f(sub):
        x = x0.copy()
        x[idx] = sub
        return fun(x)

    f0 = f(sub0)
    S = simplex_around(sub0, scales)
    res = minimize(f, sub0, method="Nelder-Mead",
                   options=dict(initial_simplex=S, xatol=xatol, fatol=fatol, maxfev=int(maxfev), maxiter=int(maxfev)))
    if res.fun <= f0:
        x = x0.copy()
        x[idx] = res.x
        return x, float(res.fun), int(res.nfev) + 1, str(res.message)
    return x0, float(f0), int(res.nfev) + 1, "start kept (" + str(res.message) + ")"


# ----------------------------------------------------------------------------- misc

def atomic_write_json(path, obj):
    path = Path(path)
    tmp = path.with_name(path.name + f".tmp{os.getpid()}")
    with open(tmp, "w") as f:
        json.dump(obj, f, indent=1, default=_json_default)
        f.flush()
        os.fsync(f.fileno())
    os.replace(tmp, path)


def _json_default(o):
    if isinstance(o, np.ndarray):
        return o.tolist()
    if isinstance(o, (np.floating, np.integer)):
        return o.item()
    if isinstance(o, (np.bool_,)):
        return bool(o)
    if isinstance(o, Path):
        return str(o)
    return str(o)


def eval_geometry(K_mp4, mp4_wh, scale=EVAL_SCALE):
    """(K_eval, wh_eval, min_edge) for a camera: half-res with the pixel-centre convention."""
    w, h = int(mp4_wh[0]), int(mp4_wh[1])
    wh_eval = (int(round(w * scale)), int(round(h * scale)))
    K_eval = scale_K_to(np.asarray(K_mp4, dtype=float), (w, h), wh_eval)
    min_edge = int(round(MIN_EDGE_PX * (wh_eval[0] * wh_eval[1]) / REF_EVAL_PX))
    return K_eval, wh_eval, min_edge