File size: 34,782 Bytes
473c56f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
"""boundary2 designer B: ORACLE-LOCALISATION delineation scoring (shared protocol, BRIEF.md) + per-lesion style (dial) table.

Oracle localisation for every model: the binary mask (prob >= 0.5) is restricted to predicted components (26-conn) that touch
the GT dilated by 2 voxels (prompt2_score.draw_mask(prob, gt)); prompt/crop models are additionally prompted from GT
components. Then per case: Dice (case Dice = mean over cases with GT), pooled Dice; per detected GT lesion (>= 10 vox):
lesion Dice, vol ratio, surface Dice @1/@2 mm, signed mean surface distance (+ = outside GT) [boundary_audit.lesion_metrics,
verbatim], plus the GT lesion's dial a (boundary2_B_common.lesion_style on the raw T1).

Sets: devA_atlas (179), devA_acute (97) [DEV-A = D331 fold-0 val, official masks], atlas / north / lab (dev-test: scoring and
selection only, never training / fitting).

  boundary2_B_eval.py score --model M --set S [--procs N]        -> B/scores/rows_<M>__<S>.pkl
  boundary2_B_eval.py summary --models a,b --sets x,y [--md]      -> table (+ leaderboard-format lines)
Model prob sources: built-in baselines (d331, delbankconv, p2heat_or, p2ball_or, p2crop_or, ...) or B/pred/<M>/<set>/<cid>.nii.gz
(uint8 x250 on the raw grid).
"""
from __future__ import annotations
import argparse, json, os, pickle, sys
from multiprocessing import Pool
from pathlib import Path
import numpy as np
import scipy.ndimage as ndi

sys.path.insert(0, str(Path(__file__).resolve().parent))
import boundary2_B_common as BC   # noqa: E402

D2 = BC.WS / "outputs/direction2"
SETS = ("devA_atlas", "devA_acute", "atlas", "north", "lab")
F_EDGES = np.array([-np.inf, 0.2, 0.4, 0.5, 0.6, 0.7, 0.8, 1.0, np.inf])   # subtlety-curve bins of relative contrast f
D321R = BC.B / "nnunet_raw/Dataset321_Whisper_T1Large"
D943R = BC.B / "nnunet_raw/Dataset943_V10DesignS"


def set_cases(s):
    if s.startswith("devA"):
        keys = json.load(open(D2 / "devset/keys_devA.json"))["keys"]
        coh = s.split("_")[1]
        return [k for k in keys if k.startswith(coh + "_")]
    import cls2_common as Q
    return [c for c in Q.test_cids((s,))]


def t1_path(s, cid):
    if s.startswith("devA"):
        return BC.guard(D321R / "imagesTr" / f"{cid}_0000.nii.gz")
    return BC.guard(D943R / "imagesTs" / f"test_{cid}_0000.nii.gz")


def label_path(s, cid):
    if s.startswith("devA"):
        return BC.guard(D321R / "labelsTr" / f"{cid}.nii.gz")
    import cls2_common as Q
    return Q.label_path(cid)


def prob_path(model, s, cid):
    dev = s.startswith("devA")
    P = {
        "d331": (D2 / "devset/pred/d331/t1/prob" / f"{cid}.nii.gz") if dev else (D2 / "arch2stage/t1prob" / f"{cid}.nii.gz"),
        "delbankconv": (D2 / "devset/pred/delbankconv/mean_s1/prob" / f"{cid}.nii.gz") if dev else (D2 / "cascade2/pred/delbankconv_x/prob" / f"{cid}.nii.gz"),
        "p2heat_or": (D2 / "prompt2/dev/pred/p2heat/oracle" / f"{cid}.nii.gz") if dev else (D2 / "classifier2/drawer/p2heat/pred/oracle" / f"{cid}.nii.gz"),
    }
    for m in ("p2ball", "p2ballpo", "p2ballms", "p2crop", "p2ballk", "p2balloff"):
        P[f"{m}_or"] = None if dev else D2 / f"classifier2/drawer/{m}/pred/oracle" / f"{cid}.nii.gz"
    if model in P:
        return P[model]
    if model.startswith("A:"):                         # designer A harness outputs (raw uint8 x250 npz 'seg'), e.g. A:ENSv, A:A9
        return D2 / "boundary2/A/pred" / model[2:] / ("devArc__none" if dev else "testrc__none") / f"{cid}.npz"
    return BC.OUT / "pred" / model / s / f"{cid}.nii.gz"


def read(p, dt=np.float32):
    import SimpleITK as sitk
    if str(p).endswith(".npz"):
        return np.load(BC.guard(p))["seg"].astype(dt), None
    im = sitk.ReadImage(str(BC.guard(p)))
    return sitk.GetArrayFromImage(im).astype(dt), np.array(im.GetSpacing()[::-1], float)


FORCED = os.environ.get("B_FORCED", "1") == "1"
S26 = np.ones((3, 3, 3), bool)
BND_KEYS = ("nsd1", "nsd2", "under_mean", "under_p95", "over_mean", "over_p95", "surf_recall2", "surf_prec2", "biou2", "absvol_ml",
            "volerr_pct", "hd_max")


def _surf26(m):
    return m & ~ndi.binary_erosion(m, S26, border_value=0)


def boundary_full(G, P, sp):
    """PI boundary metric set via the SHARED implementation int_boundary.boundary_metrics (integrator; agreed 2026-11-21): NSD@1/2,
    srec2 / sprec2, HD95 / HDmax on surface<->surface distances (26-connected erosion, EDT in mm); DIRECTIONAL under-draw
    (GT surface -> nearest predicted voxel) and over-draw (pred surface -> nearest GT voxel) region distances; BIoU (inner 2 mm band);
    |dV| mL and dV %. Keys renamed to B's names."""
    import int_boundary as IB
    m = IB.boundary_metrics(P, G, tuple(float(x) for x in sp))
    return {"nsd1": m["nsd1"], "nsd2": m["nsd2"], "under_mean": m["d_gt2pred_mean"], "under_p95": m["d_gt2pred_p95"],
            "over_mean": m["d_pred2gt_mean"], "over_p95": m["d_pred2gt_p95"], "surf_recall2": m["srec2"], "surf_prec2": m["sprec2"],
            "biou2": m["biou2"], "absvol_ml": m["vol_abs_ml"], "volerr_pct": m["vol_err_pct"], "hd_max": m["hdmax"], "hd95": m["hd95"]}


def per_lesion_boundary_full(gt, pr, sp, min_vox=10, cell_mm=10.0):
    """per GT lesion (26-conn, >= min_vox) that the prediction hits: prediction restricted to the lesion's Voronoi cell within cell_mm
    (nearer to this lesion than to any other GT lesion, and <= cell_mm from it); boundary_full on a crop. -> list of dicts."""
    import cc3d
    lab = cc3d.connected_components(gt.astype(np.uint8), connectivity=26)
    sz = np.bincount(lab.ravel()); objs = ndi.find_objects(lab)
    sp = np.asarray(sp, float); pad = [int(np.ceil(cell_mm / x)) + 2 for x in sp]
    vml = float(np.prod(sp)) / 1000
    out = []
    for k in range(1, len(sz)):
        if sz[k] < min_vox or objs[k - 1] is None:
            continue
        o = objs[k - 1]
        sl = tuple(slice(max(0, s_.start - a), min(n, s_.stop + a)) for s_, a, n in zip(o, pad, gt.shape))
        L = lab[sl]; G = L == k
        if not (pr[sl] & G).any():
            continue
        dk = ndi.distance_transform_edt(~G, sampling=sp)
        oth = (L > 0) & ~G
        do = ndi.distance_transform_edt(~oth, sampling=sp) if oth.any() else np.full(G.shape, np.inf)
        P = pr[sl] & (dk <= cell_mm) & (dk <= do)
        if not P.any():
            continue
        r = boundary_full(G, P, sp); r["gt_ml"] = float(sz[k] * vml)
        out.append(r)
    return out


def forced_draw(pr, prob, lab, sp, ids):
    """NO-VETO decoding at oracle prompts: for every GT component (prompt = its deepest voxel, as the oracle ball) that no kept
    prediction touches, draw the connected region around the prompt where prob >= 0.5 * (max prob in a ball of radius
    r_prompt + 3 voxels around it); if the drawer output there is ~0, draw the prompt ball itself. Never uses the GT shape."""
    import cc3d
    sized_ball_radius = lambda v: float(np.clip(0.6 * (3.0 * float(v) / (4.0 * np.pi)) ** (1.0 / 3.0), 2.0, 5.0))   # = cascade2_prompt rule
    pr = pr.copy(); n = 0; forced_ids = set()
    objs = ndi.find_objects(lab)
    for k in ids:
        o = objs[k - 1]
        m = lab[o] == k
        if (pr[o] & m).any():
            continue
        e = ndi.distance_transform_edt(np.pad(m, 1), sampling=sp)[1:-1, 1:-1, 1:-1]
        c = np.array(np.unravel_index(int(np.argmax(e)), e.shape)) + np.array([s_.start for s_ in o])
        r = sized_ball_radius(m.sum() * float(np.prod(sp)) * 1.5) / 1.0
        R = r + 3
        sl = tuple(slice(max(0, int(ci - R / s_) - 1), min(n_, int(ci + R / s_) + 2)) for ci, s_, n_ in zip(c, sp, lab.shape))
        g = np.meshgrid(*[(np.arange(a.start, a.stop) - ci) * s_ for a, ci, s_ in zip(sl, c, sp)], indexing="ij")
        d = np.sqrt(sum(x * x for x in g))
        reg = (d <= R) & ((lab[sl] == 0) | (lab[sl] == k))
        pl = prob[sl] * reg
        mx = float(pl.max())
        if mx >= 0.02:
            cand = pl >= 0.5 * mx
            cl = cc3d.connected_components(cand.astype(np.uint8), connectivity=26)
            am = np.unravel_index(int(np.argmax(pl)), pl.shape)
            draw = cl == cl[am]
        else:
            draw = (d <= r) & reg
        v = pr[sl]; v |= draw; pr[sl] = v
        n += 1; forced_ids.add(int(k))
    return pr, n, forced_ids


def score_arrays(gt, prob, t1, sp, brain=None):
    import cc3d, prompt2_score as PS, boundary_audit as BA
    vml = float(np.prod(sp)) / 1000
    pr = (prob >= 0.5) & PS.draw_mask(prob, gt) if gt.any() else np.zeros_like(gt)
    styles, lab = BC.case_styles(t1, gt, brain)
    n_forced = 0; forced_ids = set()
    if FORCED and gt.any():                                       # NO-VETO (user directive 2026-11-19): forced draw at every prompt
        pr, n_forced, forced_ids = forced_draw(pr, prob, lab, sp, [r["id"] for r in styles])
    tp = int((gt & pr).sum()); fp = int((pr & ~gt).sum()); fn = int((gt & ~pr).sum())
    # DRAWER_GAP_TO_90 rim classes: FN rim = missed GT voxel 26-adjacent to the drawing; FP rim = extra voxel 26-adjacent to GT
    S26 = np.ones((3, 3, 3), bool)
    fn_rim = int((gt & ~pr & ndi.binary_dilation(pr, S26)).sum()) if pr.any() else 0
    fp_rim = int((pr & ~gt & ndi.binary_dilation(gt, S26)).sum()) if gt.any() else 0
    sty = {r["id"]: r for r in styles}
    LP = cc3d.connected_components(pr.astype(np.uint8), connectivity=26)
    brain = t1 > 0
    z = (t1 - t1[brain].mean()) / (t1[brain].std() + 1e-6)
    sub_n = np.zeros(len(F_EDGES) - 1); sub_hit = np.zeros(len(F_EDGES) - 1)     # SUBTLETY CURVE (user decision 3)
    # CSF / ventricle SPILL (PI 2026-11-21: generosity must not spill into CSF): FP voxels that are CSF-dark (darkest 7 % of brain T1)
    csf_dark = brain & (z <= np.percentile(z[brain], 7)) if brain.any() else np.zeros_like(gt)
    csf_spill = int((pr & ~gt & csf_dark).sum())
    objs = ndi.find_objects(lab)
    les = []
    for k, r in sty.items():
        o = objs[k - 1]; pad = [int(np.ceil(6 / s_)) + 1 for s_ in sp]
        sl = tuple(slice(max(0, s_.start - a), min(n, s_.stop + a)) for s_, a, n in zip(o, pad, gt.shape))
        gl = lab[sl] == k
        ptl = np.unique(LP[sl][gl & (LP[sl] > 0)])
        row = {"id": k, "gt_ml": r["vox"] * vml, "a": r.get("a", np.nan), "contrast": r.get("contrast", np.nan), "det": bool(len(ptl))}
        if np.isfinite(r.get("contrast", np.nan)) and abs(r["contrast"]) > 1e-6:
            fv = (z[sl][gl] - r["i_core"]) / r["contrast"]                       # relative T1 contrast f: core 0 -> tissue 1
            hv = pr[sl][gl]
            sub_n += np.histogram(fv, F_EDGES)[0]; sub_hit += np.histogram(fv[hv], F_EDGES)[0]
        if len(ptl):
            pl = np.isin(LP[sl], ptl) & ~((lab[sl] > 0) & ~gl)
            row.update(BA.lesion_metrics(gl, pl, sp))
            # boundary_audit's 'signed' is biased ~ -1 voxel (identical masks -> -1 mm); use devset_score.boundary_pair's
            # symmetric surface-voxel offset (identical masks -> 0) as THE signed offset; keep the old value for reference.
            import devset_score as DS
            row["signed_ba"] = row["signed"]
            row["signed"] = DS.boundary_pair(gl, pl, sp)["offset"]
            # DRAWER_FINDINGS item 1: thick missed chunk = largest connected FN chunk >= 3 voxels thick (max EDT >= 2 mm) and > 10 % of lesion
            fnm = gl & ~pl
            row["chunk_frac"] = 0.0; row["thick_chunk"] = False
            if fnm.any():
                lc = cc3d.connected_components(fnm.astype(np.uint8), connectivity=26)
                bc = np.bincount(lc.ravel()); bc[0] = 0; kk = int(np.argmax(bc))
                ch = lc == kk
                row["chunk_frac"] = float(bc[kk] / gl.sum())
                thick = float(ndi.distance_transform_edt(np.pad(ch, 1), sampling=sp).max())
                row["thick_chunk"] = bool(thick >= 2.0 and row["chunk_frac"] > 0.10)
        row["forced"] = int(k) in forced_ids
        les.append(row)
    bnd = per_lesion_boundary_full(gt, pr, sp)
    return {"bnd": bnd, "csf_spill": csf_spill, "_final_mask": pr, "fn_rim": fn_rim, "fp_rim": fp_rim, "gt_vox": int(gt.sum()), "n_forced": n_forced, "sub_n": sub_n, "sub_hit": sub_hit, "tp": tp, "fp": fp, "fn": fn, "dice": 2 * tp / (2 * tp + fp + fn) if tp + fp + fn else np.nan,
            "gt_ml": float(gt.sum() * vml), "pred_ml": float(pr.sum() * vml), "les": les}


def hybrid_prob(gt, sp, p_crop, p_whole, cut_ml):
    """SIZE-ROUTED hybrid (DRAWER_FINDINGS item 1): per GT-component Voronoi territory, use the whole-volume drawer when ITS OWN drawn
    volume there (p >= .5) is >= cut_ml, else the crop drawer (routing never uses the GT size; the cut is chosen on DEV-A only)."""
    import cc3d
    lab = cc3d.connected_components(gt.astype(np.uint8), connectivity=26)
    if lab.max() == 0:
        return p_crop
    _, ind = ndi.distance_transform_edt(lab == 0, sampling=sp, return_indices=True)
    cell = lab[tuple(ind)]; del ind
    vml = float(np.prod(sp)) / 1000
    wv = np.bincount(cell[p_whole >= 0.5].ravel(), minlength=lab.max() + 1) * vml
    use_w = wv >= cut_ml; use_w[0] = False
    return np.where(use_w[cell], p_whole, p_crop).astype(np.float32)


def shrink_prob(prob, sp, s_mm):
    """fixed inward SDF shift of every drawn component by s_mm (sub-voxel: 2x linear upsample -> EDT at half spacing -> erode by s ->
    block-mean back); removed voxels get p <= .49, kept voxels p >= .51. s from DEV-A / PI only, never from test."""
    import cc3d
    if s_mm <= 0:
        return prob
    m = prob >= 0.5
    if not m.any():
        return prob
    out = prob.copy()
    lab = cc3d.connected_components(m.astype(np.uint8), connectivity=26)
    for o in ndi.find_objects(lab):
        if o is None:
            continue
        sl = tuple(slice(max(0, a.start - 2), min(n, a.stop + 2)) for a, n in zip(o, prob.shape))
        pc = prob[sl]
        up = ndi.zoom(pc, 2, order=1, mode="nearest") >= 0.5
        din = ndi.distance_transform_edt(up, sampling=np.asarray(sp) / 2.0) - 0.25 * float(np.mean(sp))   # surface at half a sub-voxel
        keep_up = din > s_mm
        shp = [d * 2 for d in pc.shape]
        ku = np.zeros(shp, bool); ku[tuple(slice(0, min(a, b)) for a, b in zip(shp, keep_up.shape))] = keep_up[tuple(slice(0, min(a, b)) for a, b in zip(shp, keep_up.shape))]
        keep = ku.reshape(pc.shape[0], 2, pc.shape[1], 2, pc.shape[2], 2).mean((1, 3, 5)) >= 0.5
        oc = out[sl]
        oc[(pc >= 0.5) & ~keep] = np.minimum(oc[(pc >= 0.5) & ~keep], 0.49)
        out[sl] = oc
    return out


def _one(args):
    model, s, cid = args
    gt, sp = read(label_path(s, cid)); gt = gt > 0
    if model.startswith("rule:"):                    # rule:<model>:<i>  r-dial CONTROL: the nested rule applied post hoc to a drawing
        mb, li = model[len("rule:"):].rsplit(":", 1); li = int(li)
        pb = prob_path(mb, s, cid)
        if pb is None or not Path(pb).exists():
            return None
        prob, _ = read(pb); prob = prob / 250.0 if prob.max() > 1.5 else prob
        import SimpleITK as sitk
        import boundary2_B_mirror as BM, boundary2_B_rdial as BR
        im = sitk.ReadImage(str(t1_path(s, cid))); t1r = sitk.GetArrayFromImage(im).astype(np.float32)
        br = t1r > 0
        zr = np.where(br, (t1r - t1r[br].mean()) / (t1r[br].std() + 1e-6), 0).astype(np.float32)
        Mr, _m = BM.mirror_pp(zr, im.GetDirection(), tuple(im.GetSpacing()[::-1]))
        lv = BR.rule_levels(zr, prob >= 0.5, Mr)
        Li = BR.level_mask(lv, li) if li >= 0 else (prob >= 0.5)
        prob = np.maximum(prob, Li.astype(np.float32) * 0.51)
    elif model.startswith("shrink:"):                  # shrink:<model>:<mm>  (fixed inward SDF shift, b-check)
        _, mb, mm = model.split(":", 2)
        mm = float(mm.split(":")[-1]); mb = model[len("shrink:"):].rsplit(":", 1)[0]
        pb = prob_path(mb, s, cid)
        if pb is None or not Path(pb).exists():
            return None
        prob, _ = read(pb); prob = prob / 250.0 if prob.max() > 1.5 else prob
        prob = shrink_prob(prob, sp, mm)
    elif model.startswith("hyb:"):                     # hyb:<crop model>:<whole model>:<cut mL>
        _, mc, mw, cut = model.split(":")
        pc, pw = prob_path(mc, s, cid), prob_path(mw, s, cid)
        if pc is None or pw is None or not Path(pc).exists() or not Path(pw).exists():
            return None
        a_, _ = read(pc); b_, _ = read(pw)
        a_ = a_ / 250.0 if a_.max() > 1.5 else a_; b_ = b_ / 250.0 if b_.max() > 1.5 else b_
        prob = hybrid_prob(gt, sp, a_, b_, float(cut))
    else:
        pp = prob_path(model, s, cid)
        if pp is None or not Path(pp).exists():
            return None
        prob, _ = read(pp)
        if prob.max() > 1.5:
            prob = prob / 250.0
    t1, _ = read(t1_path(s, cid))
    if prob.shape != gt.shape:
        return {"cid": cid, "error": f"shape {prob.shape} vs {gt.shape}"}
    r = score_arrays(gt, prob, t1, sp)
    r.update(cid=cid, set=s, model=model)
    if s == "atlas":                                 # ATLAS-43 second reference: Boyd-lab masks (TEST, evaluation only; PI target style)
        try:
            bp = boyd_path(cid)
            bo, _ = read(bp); bo = bo > 0
            pr = r.pop("_final_mask")
            tp = int((pr & bo).sum()); fp = int((pr & ~bo).sum()); fn = int((bo & ~pr).sum())
            r["boyd"] = {"tp": tp, "fp": fp, "fn": fn, "dice": 2 * tp / max(1, 2 * tp + fp + fn), "vox": int(bo.sum()), "pred": int(pr.sum())}
            r["boyd_bnd"] = per_lesion_boundary_full(bo, pr, sp)
        except Exception as e:
            r["boyd_err"] = repr(e)
    r.pop("_final_mask", None)
    return r


def boyd_path(cid):
    import cls2_common as Q
    tm = json.load(open(Q.D943R / "test_label_map.json"))
    return BC.guard(tm[f"test_{cid}"])


def score(a):
    cids = set_cases(a.set)
    with Pool(a.procs) as pool:
        rows = [r for r in pool.map(_one, [(a.model, a.set, c) for c in cids], chunksize=1) if r is not None]
    out = BC.OUT / "scores" / f"rows_{a.model.replace(':', '~')}__{a.set}.pkl"
    BC.guard_write(out); pickle.dump(rows, open(out, "wb"))
    print("SCORED", a.model, a.set, len(rows), "of", len(cids), flush=True)


def summarise_rows(rows):
    rows = [r for r in rows if "error" not in r]
    if not rows:
        return None
    withgt = [r for r in rows if r["gt_ml"] > 0]
    L = [l for r in rows for l in r["les"]]
    D = [l for l in L if l["det"]]
    def med(sel, q):
        v = np.array([l[q] for l in sel if q in l and np.isfinite(l[q])], float)
        return float(np.median(v)) if len(v) else np.nan
    def iqr(sel, q):
        v = np.array([l[q] for l in sel if q in l and np.isfinite(l[q])], float)
        return (float(np.percentile(v, 25)), float(np.percentile(v, 75))) if len(v) else (np.nan, np.nan)

    def binrow(lo, hi):
        sel = [l for l in L if lo <= l["gt_ml"] < hi]; d = [l for l in sel if l["det"]]
        g = sum(l["gt_ml"] for l in sel) or 1e-9
        fpb = fnb = 0.0
        for l in sel:
            if l["det"]:
                gv, pv = l["gt_vox"], l["pred_vox"]; it = l["dice"] * (gv + pv) / 2
                fpb += (pv - it) / gv * l["gt_ml"]; fnb += (gv - it) / gv * l["gt_ml"]
            else:
                fnb += l["gt_ml"]
        return {"n": len(sel), "det": len(d) / max(1, len(sel)), "dice_med": med(d, "dice"), "vol_med": med(d, "vol_ratio"),
                "signed_med": med(d, "signed"), "sd1_med": med(d, "sdice1"), "hd95_med": med(d, "hd95"), "assd_med": med(d, "assd"),
                "hd95_iqr": iqr(d, "hd95"), "fpb": fpb / g, "fnb": fnb / g}
    tp = sum(r["tp"] for r in rows); fp = sum(r["fp"] for r in rows); fn = sum(r["fn"] for r in rows)
    nv = np.array([0.0 if l.get("forced") else l.get("dice", 0.0) for l in L], float)      # no-veto lesion Dice: undrawn = 0
    med_l = [l for l in D if 1.0 <= l["gt_ml"] < 30.0 and not l.get("forced")]
    return {"n_cases": len(rows), "case_dice": float(np.mean([r["dice"] for r in withgt])), "pooled_dice": 2 * tp / (2 * tp + fp + fn),
            "n_les": len(L), "det_rate": len(D) / max(1, len(L)), "les_dice_med": med(D, "dice"), "sd1_med": med(D, "sdice1"),
            "sd2_med": med(D, "sdice2"), "signed_med": med(D, "signed"), "signed_mean": float(np.mean([l["signed"] for l in D])) if D else np.nan,
            "vol_med": med(D, "vol_ratio"), "vol_pooled": sum(r["pred_ml"] for r in rows) / max(1e-9, sum(r["gt_ml"] for r in rows)),
            "subtlety": _subtlety(rows),
            "b5_30": binrow(5, 30), "lt1": binrow(0, 1), "b1_5": binrow(1, 5), "ge30": binrow(30, 1e9), "all": binrow(0, 1e9),
            "lt0.1": binrow(0, 0.1), "b0.1_1": binrow(0.1, 1), "hd95_med": med(D, "hd95"), "assd_med": med(D, "assd"),
            "n_forced": int(sum(r.get("n_forced", 0) for r in rows)),
            "undrawn": int(sum(1 for l in L if l.get("forced") or not l["det"])), "nv_les_dice_med": float(np.median(nv)) if len(nv) else np.nan,
            "thick_chunk_rate": (sum(1 for l in med_l if l.get("thick_chunk")) / len(med_l)) if med_l else np.nan, "n_med_drawn": len(med_l),
            "thick_by_bin": {nm: _rate([l for l in D if lo <= l["gt_ml"] < hi and not l.get("forced")]) for nm, lo, hi in
                             (("1-5", 1, 5), ("5-30", 5, 30), (">=30", 30, 1e9))},
            "fn_rim_frac": sum(r.get("fn_rim", 0) for r in rows) / max(1, sum(r.get("gt_vox", 0) for r in rows)),
            "fp_rim_frac": sum(r.get("fp_rim", 0) for r in rows) / max(1, sum(r.get("gt_vox", 0) for r in rows)),
            # per-case (each case weighs equally; pooled is dominated by large lesions)
            "fn_rim_case_med": float(np.median([r["fn_rim"] / r["gt_vox"] for r in rows if r.get("gt_vox")])) if any(r.get("gt_vox") for r in rows) else np.nan,
            "fp_rim_case_med": float(np.median([r["fp_rim"] / r["gt_vox"] for r in rows if r.get("gt_vox")])) if any(r.get("gt_vox") for r in rows) else np.nan,
            "vol_off_pooled": sum(r["pred_ml"] for r in rows) / max(1e-9, sum(r["gt_ml"] for r in rows)),
            "vol_off_case_med": float(np.median([r["pred_ml"] / r["gt_ml"] for r in rows if r["gt_ml"] > 0])) if any(r["gt_ml"] > 0 for r in rows) else np.nan,
            "boyd": _boyd(rows),
            "csf_spill_frac": sum(r.get("csf_spill", 0) for r in rows) / max(1, sum(r.get("gt_vox", 0) for r in rows)),
            "rim_ratio_case_med": float(np.median([(r["fn_rim"] + 1) / (r["fp_rim"] + 1) for r in rows if r.get("gt_vox")])) if any(r.get("gt_vox") for r in rows) else np.nan}


def _boyd(rows):
    b = [r["boyd"] for r in rows if "boyd" in r]
    if not b:
        return None
    tp = sum(x["tp"] for x in b); fp = sum(x["fp"] for x in b); fn = sum(x["fn"] for x in b)
    return {"n": len(b), "case_dice": float(np.mean([x["dice"] for x in b if x["vox"] > 0])), "pooled_dice": 2 * tp / max(1, 2 * tp + fp + fn),
            "vol_pooled": sum(x["pred"] for x in b) / max(1, sum(x["vox"] for x in b)),
            "vol_case_med": float(np.median([x["pred"] / x["vox"] for x in b if x["vox"] > 0]))}


def bnd_summary(rows, key="bnd"):
    """per-lesion boundary metrics: cohort median + IQR over lesions, and median over cases of the per-case median."""
    L = [b for r in rows for b in r.get(key, [])]
    if not L:
        return None
    out = {"n_les": len(L)}
    for q in BND_KEYS:
        v = np.array([b[q] for b in L], float)
        pc = [float(np.median([b[q] for b in r[key]])) for r in rows if r.get(key)]
        out[q] = {"med": float(np.median(v)), "q25": float(np.percentile(v, 25)), "q75": float(np.percentile(v, 75)),
                  "case_med": float(np.median(pc)) if pc else float("nan")}
    return out


def _rate(sel):
    return (sum(1 for l in sel if l.get("thick_chunk")) / len(sel), len(sel)) if sel else (float("nan"), 0)


def _subtlety(rows):
    sub = [r for r in rows if "sub_n" in r]
    if not sub:
        return {"edges": F_EDGES.tolist(), "n": [0] * (len(F_EDGES) - 1), "recall": [float("nan")] * (len(F_EDGES) - 1)}
    n = np.sum([r["sub_n"] for r in sub], 0); h = np.sum([r["sub_hit"] for r in sub], 0)
    return {"edges": F_EDGES.tolist(), "n": n.tolist(), "recall": (h / np.maximum(1, n)).tolist()}


def load_rows(model, s):
    p = BC.OUT / "scores" / f"rows_{model.replace(':', '~')}__{s}.pkl"
    return pickle.load(open(p, "rb")) if p.exists() else None


def summary(a):
    import datetime
    for s in a.sets.split(","):
        for m in a.models.split(","):
            rows = load_rows(m, s)
            if rows is None:
                continue
            if a.common:      # restrict to cases every listed model has
                common = set.intersection(*[set(r["cid"] for r in (load_rows(mm, s) or [])) for mm in a.models.split(",")])
                rows = [r for r in rows if r["cid"] in common]
            st = summarise_rows(rows)
            if st is None:
                continue
            b, t = st["b5_30"], st["lt1"]
            if a.md:
                print(f"| {datetime.date.today()} | B | {m} | {s} (n={st['n_cases']}) | {st['case_dice']:.3f} | {st['pooled_dice']:.3f} | {st['les_dice_med']:.3f} | "
                      f"{st['sd1_med']:.3f} | {st['sd2_med']:.3f} | {st['signed_med']:+.2f} | {st['vol_med']:.2f} (pooled {st['vol_pooled']:.2f}) | "
                      f"{b['dice_med']:.3f} / {b['vol_med']:.2f} | {t['dice_med']:.3f} / {t['vol_med']:.2f} | {a.note} |")
            else:
                print(f"{s:11s} {m:22s} n={st['n_cases']:3d} caseD {st['case_dice']:.3f} poolD {st['pooled_dice']:.3f} lesD {st['les_dice_med']:.3f} "
                      f"SD1 {st['sd1_med']:.3f} SD2 {st['sd2_med']:.3f} off {st['signed_med']:+.2f} vol {st['vol_med']:.2f}/{st['vol_pooled']:.2f} "
                      f"det {st['det_rate']:.2f} | 5-30 {b['dice_med']:.3f}/{b['vol_med']:.2f} (n{b['n']}) | <1 {t['dice_med']:.3f}/{t['vol_med']:.2f} (n{t['n']})")
                if a.subtlety:
                    sb = st["subtlety"]; e = sb["edges"]
                    print("      subtlety recall by f: " + " ".join(f"[{e[i]:.1f},{e[i+1]:.1f}):{sb['recall'][i]:.3f}(n{int(sb['n'][i])})" for i in range(len(sb['n']))))
                if a.bins:
                    for nm in ("lt0.1", "b0.1_1", "b1_5", "b5_30", "ge30", "all"):
                        r = st[nm]
                        print(f"      {nm:6s} n{r['n']:4d} det {r['det']:.2f} dice {r['dice_med']:.3f} vol {r['vol_med']:.2f} off {r['signed_med']:+.2f} "
                              f"SD1 {r['sd1_med']:.3f} HD95 {r['hd95_med']:.2f} ASSD {r['assd_med']:.2f} FPb {r['fpb']:.3f} FNb {r['fnb']:.3f}")


def table(a):
    """cohort x metric markdown table for several models (COMPONENT_METRICS 'Additions'): DEV-A ATLAS, DEV-A acute, ATLAS-43,
    NORTH, LAB, primary (ATLAS-43 + NORTH pooled rows), worst OOD cohort; generalisation gap = DEV-A ATLAS - worst OOD."""
    models = a.models.split(",")
    hdr = ("| model | cohort | n | case Dice | pooled Dice | lesion Dice med | SD@1 | offset mm | vol ratio | HD95 med | ASSD med | det | "
           "<0.1 mL D/vol | 0.1-1 D/vol | 1-5 D/vol | 5-30 D/vol | >30 D/vol | FPb / FNb | subtlety f .2-.4/.4-.5/.5-.6/.6-.7/.7-.8 | undrawn | no-veto lesion Dice | thick-chunk rate 1-30 mL | thick-chunk 1-5/5-30/>=30 | FN rim / FP rim (x GT vox) pooled | per-case med FN / FP; FN:FP | vol vs official pooled / case-med | vs BOYD case / pooled Dice; vol pooled / case-med | CSF spill (FP CSF-dark vox / GT vox) |")
    out = [hdr, "|" + "|".join(["---"] * (hdr.count("|") - 1)) + "|"]
    for m in models:
        per = {}
        for s in SETS:
            r = load_rows(m, s)
            if r:
                per[s] = r
        if "atlas" in per and "north" in per:
            per["primary"] = per["atlas"] + per["north"]
        stats = {s: summarise_rows(r) for s, r in per.items()}
        stats = {k: v for k, v in stats.items() if v}
        ood = [s for s in ("devA_acute", "atlas", "north", "lab") if s in stats]
        if ood:
            w = min(ood, key=lambda s: stats[s]["les_dice_med"]); stats["worst=" + w] = stats[w]
        for s, st in stats.items():
            b = lambda k: f"{st[k]['dice_med']:.3f}/{st[k]['vol_med']:.2f}"
            sb = st["subtlety"]["recall"]
            out.append(f"| {m} | {s} | {st['n_cases']} | {st['case_dice']:.3f} | {st['pooled_dice']:.3f} | {st['les_dice_med']:.3f} | {st['sd1_med']:.3f} | "
                       f"{st['signed_med']:+.2f} | {st['vol_med']:.2f} | {st['hd95_med']:.2f} | {st['assd_med']:.2f} | {st['det_rate']:.2f} | "
                       f"{b('lt0.1')} | {b('b0.1_1')} | {b('b1_5')} | {b('b5_30')} | {b('ge30')} | {st['all']['fpb']:.3f} / {st['all']['fnb']:.3f} | "
                       f"{'/'.join(f'{x:.2f}' for x in sb[1:6])} | {st['undrawn']}/{st['n_les']} | {st['nv_les_dice_med']:.3f} | "
                       f"{st['thick_chunk_rate']:.2f} ({st['n_med_drawn']}) | "
                       f"{'/'.join(f'{v[0]:.2f}' for v in st['thick_by_bin'].values())} | {st['fn_rim_frac']:.3f} / {st['fp_rim_frac']:.3f} | "
                       f"{st['fn_rim_case_med']:.3f} / {st['fp_rim_case_med']:.3f}; {st['rim_ratio_case_med']:.2f} | "
                       f"{st['vol_off_pooled']:.2f} / {st['vol_off_case_med']:.2f} | "
                       + (f"{st['boyd']['case_dice']:.3f} / {st['boyd']['pooled_dice']:.3f}; {st['boyd']['vol_pooled']:.2f} / {st['boyd']['vol_case_med']:.2f} |" if st.get('boyd') else "– |") + f" {st['csf_spill_frac']:.4f} |")
        if "devA_atlas" in stats and ood:
            gap = stats["devA_atlas"]["les_dice_med"] - min(stats[s]["les_dice_med"] for s in ood)
            out.append(f"| {m} | GAP lesion Dice DEV-A ATLAS - worst OOD | | | | {gap:+.3f} |" + " |" * 22)
    txt = "\n".join(out)
    print(txt)
    if a.out:
        op = BC.OUT / "scores" / a.out
        BC.guard_write(op); open(op, "w").write(txt + "\n")


def table_boundary(a):
    """one row per drawer x cohort with the PI boundary metric set (lesion medians [IQR]; per-case medians for NSD); ATLAS-43 also vs Boyd."""
    hdr = ("| drawer | cohort | n les | NSD@1 | NSD@2 (case-med) | under mean / p95 mm | over mean / p95 mm | surf recall@2 | surf prec@2 | "
           "BIoU@2 | |dV| mL | dV % | HD max (flag) |")
    out = [hdr, "|" + "|".join(["---"] * (hdr.count("|") - 1)) + "|"]
    def fmt(m, st, coh):
        f = lambda q: f"{st[q]['med']:.3f} [{st[q]['q25']:.2f}-{st[q]['q75']:.2f}]"
        return (f"| {m} | {coh} | {st['n_les']} | {f('nsd1')} | {f('nsd2')} ({st['nsd2']['case_med']:.3f}) | "
                f"{st['under_mean']['med']:.2f} / {st['under_p95']['med']:.2f} | {st['over_mean']['med']:.2f} / {st['over_p95']['med']:.2f} | "
                f"{f('surf_recall2')} | {f('surf_prec2')} | {f('biou2')} | {st['absvol_ml']['med']:.2f} | {st['volerr_pct']['med']:+.1f} | "
                f"{st['hd_max']['med']:.1f} |")
    for m in a.models.split(","):
        per = {s_: load_rows(m, s_) for s_ in SETS}
        per = {k: v for k, v in per.items() if v}
        if "atlas" in per and "north" in per:
            per["primary"] = per["atlas"] + per["north"]
        for coh, rows in per.items():
            st = bnd_summary(rows)
            if st:
                out.append(fmt(m, st, coh))
            if coh == "atlas":
                sb = bnd_summary(rows, "boyd_bnd")
                if sb:
                    out.append(fmt(m, sb, "ATLAS-43 vs BOYD"))
    txt = "\n".join(out); print(txt)
    if a.out:
        op = BC.OUT / "scores" / a.out; BC.guard_write(op); open(op, "w").write(txt + "\n")


def score_dir(a):
    """score an ARBITRARY drawing dir (e.g. cascade drawings on c2t(b) accepts; no oracle restriction, no forced draw): every file
    <cid>.nii.gz (uint8 x250 or bool) on the raw test grid -> rows_<name>__<cohort>.pkl with Dice, volume, Boyd and the full boundary set."""
    global FORCED
    FORCED = False
    files = sorted(f for f in os.listdir(a.pred_dir) if f.endswith(".nii.gz"))
    by = {}
    for f in files:
        by.setdefault(a.set or f.split("_")[0], []).append(f[:-7])
    for coh, cids in by.items():
        with Pool(a.procs) as pool:
            rows = [r for r in pool.map(_one_dir, [(a.pred_dir, coh, c, a.name) for c in cids], chunksize=1) if r is not None]
        op = BC.OUT / "scores" / f"rows_{a.name}__{coh}.pkl"; BC.guard_write(op); pickle.dump(rows, open(op, "wb"))
        print("SCORED_DIR", a.name, coh, len(rows), flush=True)


def _one_dir(args):
    d, coh, cid, name = args
    global FORCED
    FORCED = False
    gt, sp = read(label_path(coh, cid)); gt = gt > 0
    prob, _ = read(os.path.join(d, f"{cid}.nii.gz")); prob = prob / 250.0 if prob.max() > 1.5 else prob
    t1, _ = read(t1_path(coh, cid))
    import prompt2_score as PS
    _dm = PS.draw_mask
    PS.draw_mask = lambda p, g: np.ones_like(g, dtype=bool)        # no oracle restriction for cascade drawings
    try:
        r = score_arrays(gt, prob, t1, sp)
    finally:
        PS.draw_mask = _dm
    r.update(cid=cid, set=coh, model=name)
    if coh == "atlas":
        try:
            bo, _ = read(boyd_path(cid)); bo = bo > 0
            pr = r["_final_mask"]
            tp = int((pr & bo).sum()); fp = int((pr & ~bo).sum()); fn = int((bo & ~pr).sum())
            r["boyd"] = {"tp": tp, "fp": fp, "fn": fn, "dice": 2 * tp / max(1, 2 * tp + fp + fn), "vox": int(bo.sum()), "pred": int(pr.sum())}
            r["boyd_bnd"] = per_lesion_boundary_full(bo, pr, sp)
        except Exception as e:
            r["boyd_err"] = repr(e)
    r.pop("_final_mask", None)
    return r


def main():
    ap = argparse.ArgumentParser(); sp = ap.add_subparsers(dest="cmd", required=True)
    p = sp.add_parser("score"); p.add_argument("--model", required=True); p.add_argument("--set", required=True); p.add_argument("--procs", type=int, default=8)
    p = sp.add_parser("summary"); p.add_argument("--models", required=True); p.add_argument("--sets", default=",".join(SETS))
    p.add_argument("--md", action="store_true"); p.add_argument("--common", action="store_true"); p.add_argument("--note", default=""); p.add_argument("--bins", action="store_true"); p.add_argument("--subtlety", action="store_true")
    p = sp.add_parser("table"); p.add_argument("--models", required=True); p.add_argument("--out", default="")
    p = sp.add_parser("table_boundary"); p.add_argument("--models", required=True); p.add_argument("--out", default="")
    p = sp.add_parser("score_dir"); p.add_argument("--pred_dir", required=True); p.add_argument("--name", required=True)
    p.add_argument("--procs", type=int, default=8); p.add_argument("--set", default="")
    a = ap.parse_args()
    {"score": score, "summary": summary, "table": table, "table_boundary": table_boundary, "score_dir": score_dir}[a.cmd](a)


if __name__ == "__main__":
    main()