File size: 52,039 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
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
#!/usr/bin/env python
"""cascade2 renderer v2 ("render2"): confirmation-FLAIR renderer rebuilt for a FLAIR-ONLY stage-1 detector.

NEW module (2026-11-16). cascade2_render.py / confirmgen_fast.py are NOT modified (running jobs import them); v2 reuses
their per-case caches (cascade2/cg_cache/<patient>: tissue maps from the real T1, lesion signed distance, component
tables, decoy site lists) and their decoy stamping code (FastConfirmGen._negatives), and replaces everything else.

Why (render2/REPORT.md, forensics on real CONTRA, label-safe):
  v1 was designed for a T1+FLAIR "confirmation" network: amplitude-matched decoys that only T1 can veto, random
  (SynthSeg-style) contrast and lesion polarity, lesion CNR drawn from a real distribution with a hard tail (no floor),
  partial coverage. For a FLAIR-ONLY detector this gives (i) labelled-but-invisible lesions (training blob loss stays
  ~0.65-0.80 vs 0.33 for option ii), (ii) NO label-0 example of FLAIR-bright parenchyma at all (every bright
  parenchymal decoy is IGNORE under the 35n-addendum rule), so the detector learns "z >= 3 = lesion" and flags 18 % of
  all non-lesion z >= 3 tissue in real FLAIR (option ii: 2 %), and (iii) dark/random-polarity lesions -> dark FPs.

v2 changes (each behind a knob in R2Knobs; defaults = the screened v2):
  1. FLAIR-like contrast from pooled multi-cohort class statistics (library class_stats) with wide jitter; random
     contrast reduced to 15 % (v1: 50 %) and lesion polarity never flipped. Trainer GIN (p 0.6) unchanged.
  2. Bright-tissue appearance variety: periventricular lining / caps, diffuse deep-WM fields, patchy cortical ribbon
     (codes 20/21/22) -> IGNORE in stage 1 (user: recall-first, bright tissue never label 0). v1 decoys keep the 35n rule.
  3. Lesions: two-component chronic-stroke appearance, WM-relative and calibrated to real CONTRA (core contrast in
     NAWM-SD units, median ~2, p10-p90 ~0.6-5.5): bright gliosis (rim >= core) everywhere; where the real T1 shows a
     fluid cavity, a CSF-like cavity (incomplete suppression) with a bright gliotic rim; tiny lesions = bright focus or
     lacune (fluid core + rim). Internal heterogeneity, soft partial-volume edge, optional faint halo. No partial coverage.
  4. Contrast set AFTER acquisition: the lesion anomaly is blurred by the SAME acquisition operator and scaled so its
     post-acquisition contrast hits the sampled target (cap on the pre-blur amplitude = physical maximum).
  5. Visibility-gated labels: a component whose realised post-acquisition contrast is < vis_cnr (default 1.0 NAWM SD)
     is marked IGNORE (negmap code 250) instead of positive: the detector is never told that invisible tissue is lesion.
USER DIRECTION 2026-11-16 (applied): stage 1 is RECALL-FIRST. Objectives = in-lesion heat, no labelled-but-invisible or
dark-core lesions, tiny-lesion recall; FP volume secondary. Bright tissue (incl. the v2 lining / diffuse-WM / cortex
appearance) is IGNORE, never label 0 (35n rule kept). No fitting to CONTRA: real data only set broad ranges, pooled
over non-test sources; wide randomisation; some random contrast kept.
PARAMETER PROVENANCE (nothing from any test cohort; CONTRA sets NO point estimate):
  class intensities  library_production.json class_stats (536 cases pooled: BraTS 300, BMS 105, WMH-challenge 60,
                     CONTRA 58, ISLES2015 13; built by the confirmgen agent), ratio gm/nsd, csf/nsd x kappa ~ U(1, 2)
                     (generic std->robust-SD factor) + jitter; CSF capped at -2, 10 % incomplete suppression U(-3, -1.5)
  random contrast    15 % of renders: GM, CSF ~ N(0, 4) (lesion polarity NOT flipped: lesions stay hyperintense)
  texture / noise    defined in NAWM-SD units by construction (noise SD U(0.25, 0.7), texture fills to total ~1);
                     real-texture bank (bank2, non-test sources) at p 0.15; not fitted
  bias               generic: additive 50 mm field SD U(0.05, 0.8) + 20 % multiplicative scanner bias (as v1)
  lesion contrast    generic prior: post-acquisition core contrast log-uniform U(0.8, 6) NAWM SD; rim/core U(1, 1.8);
                     tiny lesions pre-blur U(1.5, 6); visibility gate 1.0 NAWM SD (below -> IGNORE)
  acquisition        v1 sampler (ref._sample_acq: thick 2D / 3D resolutions), unchanged
  T1-class fix       render2_classmeans.py: per-case robust 3-class GMM of the case's OWN T1 (no external data)
  CONTRA statistics  used only as a DIAGNOSTIC comparison (render2_forensics stats), not to set parameters.
API:
  make_renderer(knobs=None) -> Render2 ; Render2.render(cache, gen, axial_axis) -> (flair (D,H,W) tensor z, negmap uint8, info)
  make_online_hook2(return_negmap=True) -> DA-worker hook f(t1, les, key, bbox, rng) -> (flair, negmap) (same contract
  as cascade2_render.make_online_hook; negmap carries v1 decoy codes + 20/21 (label 0) + 250 (lesion -> ignore)).
"""
from __future__ import annotations
import os, sys
from dataclasses import dataclass, field
from pathlib import Path
import numpy as np

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

CODE_PV_LINING, CODE_WM_DIFFUSE, CODE_CORTEX, CODE_LES_IGNORE = 20, 21, 22, 250
# user 2026-11-16: stage 1 is recall-first; bright tissue is never label 0 -> the v2 bright-appearance codes are IGNORE
R2_IGNORE_CODES = {CODE_PV_LINING: "pv_lining", CODE_WM_DIFFUSE: "wm_diffuse", CODE_CORTEX: "cortex_bright"}
R2_LABEL0_CODES = {4: "flow", 5: "sulcal", 6: "edge"}      # 35n rule (CSF-space / brain-edge artefacts), unchanged


@dataclass
class R2Knobs:
    # contrast, all in NAWM robust-SD units (WM = 0, NAWM texture + noise SD ~ 1). Calibrated on real CONTRA with the
    # render2_forensics measures (CSF_vent -6.5 [-8.3, -4.1], GM +0.3, band SDs 0.41/0.54/0.59, bias p95-p5 1.24)
    p_random_contrast: float = 0.15        # user 2026-11-16: reduce (v1 0.5), do not zero; lesions stay hyperintense vs WM
    p_class_stats: float = 0.85
    kappa: tuple = (1.0, 2.0)              # library nawm_sd (an SD incl. heterogeneity) -> robust NAWM SD: broad generic range
    gm_jitter: float = 0.3
    csf_jitter: float = 0.8
    csf_max: float = -2.0
    p_poor_suppression: float = 0.1       # CSF in U(-3, -1.5): incomplete suppression
    gamma_w_sd: float = 0.3
    noise_sd: tuple = (0.25, 0.7)          # thermal noise SD (NAWM units); texture fills the rest to total ~ 1
    tex_total: tuple = (0.85, 1.15)
    p_real_texture: float = 0.15
    bias_sd: tuple = (0.05, 0.8)           # additive smooth (50 mm) field in tissue, NAWM units (generic, wide)
    csf_floor: tuple = (0.3, 1.5)          # residual CSF signal above zero (Rician floor)
    p_sharp: tuple = (0.08, 0.16)          # CSF-fraction sharpening (T1 tissue model is too soft: ventricle p median 0.67)
    # negative realism (label 0)
    p_pv_lining: float = 0.85
    pv_amp: tuple = (0.5, 6.0)             # NAWM SD at the ventricle wall
    pv_lambda: tuple = (0.5, 2.5)          # mm decay
    p_wm_diffuse: float = 0.6
    wm_diffuse_amp: tuple = (0.3, 2.5)     # NAWM SD peak
    wm_diffuse_scale: tuple = (8.0, 25.0)  # mm correlation length
    p_cortex: float = 0.6                  # patchy cortical-ribbon hyperintensity (real: cortex z>=3 12 mL/case)
    cortex_amp: tuple = (0.3, 2.5)
    # v1 decoys (stamped with FastConfirmGen._negatives; pathology-like codes -> IGNORE in stage 1)
    neg_scale: float = 0.6
    # lesions
    core_range: tuple = (0.8, 6.0)         # post-acquisition core contrast, NAWM-SD units, LOG-UNIFORM (generic prior; no cohort fit)
    rim_ratio: tuple = (1.0, 1.8)          # rim / core
    rim_width: tuple = (0.7, 2.5)          # mm
    pre_cap: float = 7.0                   # max pre-blur amplitude (NAWM SD units)
    tiny_vox: int = 100
    tiny_pre: tuple = (1.5, 6.0)           # tiny lesions: pre-blur amplitude range
    p_lacune: float = 0.35                 # tiny with T1 cavity -> lacune
    cav_foff: tuple = (0.0, 0.4)
    les_tex: tuple = (0.0, 0.4)
    edge_tau: tuple = (0.3, 1.0)           # mm partial-volume edge
    edge_off: tuple = (-0.5, 0.8)          # mm (+ = anomaly extends beyond label)
    boundary_jitter_mm: float = 0.5
    p_halo: float = 0.3
    halo_frac: tuple = (0.05, 0.3)
    vis_cnr: float = 1.0
    # acquisition (v1 resolution sampling; noise level from noise_sd)
    gamma_sd: float = 0.15
    p_uncorrected_bias: float = 0.2        # extra multiplicative scanner bias (sites without bias correction)
    bias_max: float = 0.25
    p_ghost: float = 0.1
    p_gibbs: float = 0.1


class Render2:
    def __init__(self, knobs: R2Knobs | None = None, library=None, device="cpu"):
        import torch
        import confirmgen_core as CG
        import confirmgen_fast as CF
        self.k = knobs or R2Knobs()
        self.lib = library if library is not None else _load_lib()
        self.dev = torch.device(device)
        vk = CG.production_knobs(neg_scale=self.k.neg_scale)
        self.F = CF.FastConfirmGen(vk, self.lib, device=device, skip_gin=True)   # helpers, texture bank, decoy stamping
        self.CF = CF
        import json as _json
        cp = C.WS / "outputs/direction2/render2/t1_classes.json"     # render2_classmeans.py (robust T1 GMM per case)
        self.t1cls = _json.load(open(cp)) if cp.exists() else {}

    # ------------------------------------------------------------------ helpers
    def _noise(self, shape, corr):
        return self.F._noise_field(None, shape, corr)

    def _acq(self, x, acq, sp, add_noise=False, wm=None):
        """area-resample onto the coarse acquisition grid (+ Rician noise), trilinear back (v1 operator)."""
        import torch, torch.nn.functional as Fn
        stv = [st / s_ for st, s_ in zip(acq["step"], sp)]
        sz = list(x.shape[2:])
        lo = [max(4, int(round(n / st))) if st > 1.05 else n for n, st in zip(sz, stv)]
        y = Fn.interpolate(x, size=lo, mode="area") if lo != sz else x
        if add_noise:
            sn = wm                                   # render2: noise SD in NAWM units (acq["snr"] unused)
            g = self.F._gd
            y = torch.sqrt((y + sn * torch.randn(y.shape, generator=g, device=self.dev)) ** 2 + (sn * torch.randn(y.shape, generator=g, device=self.dev)) ** 2)
        return y, lo, sz

    def _up(self, y, lo, sz):
        import torch.nn.functional as Fn
        return Fn.interpolate(y, size=sz, mode="trilinear", align_corners=True) if lo != sz else y

    def _t1_maps(self, t1z, brain, les, w_old, cls, sp):
        """CSF fraction p, GM..WM axis (uint8 index) and ventricle distance (mm, 2 mm quantised, 99 = none within 12 mm)
        from the z-scored T1 crop and the case's robust class means (mCSF, mGM, mWM, sdCSF, sdGM, sdWM)."""
        import torch, torch.nn.functional as Fn
        mC, mG, mW, sC, sG, sW = cls
        x = Fn.avg_pool3d(t1z[None, None], 3, 1, 1)[0, 0]
        lo = mG - 0.75 * sG
        pr = ((lo - x) / max(lo - mC, 1e-3)).clamp(0, 1) * brain
        lesd = Fn.max_pool3d(les[None, None].float(), 3, 1, 1)[0, 0] > 0
        cav = les & (pr > 0.5)
        p = torch.where(les, torch.zeros_like(pr), pr)                    # healed background (fluid via the cavity logic)
        w = ((x - mG) / max(mW - mG, 1e-3)).clamp(0, 1.25)
        wi = torch.where(lesd, w_old, (w * 200).round().long().clamp(0, 255))
        # ventricles: deep CSF (>= 12 mm inside the brain), on a 2 mm grid
        sh = brain.shape
        bh = Fn.avg_pool3d(brain[None, None].float(), 2, 2, ceil_mode=True)
        ph = Fn.avg_pool3d(p[None, None], 2, 2, ceil_mode=True)
        outside = (bh < 0.5).float()
        for _ in range(6):
            outside = Fn.max_pool3d(outside, 3, 1, 1)
        vent = ((ph > 0.6) & (outside < 0.5)).float()
        d = torch.full_like(vent, 99.0); d[vent > 0] = 0.0
        cur = vent
        for k in range(1, 6):
            nxt = Fn.max_pool3d(cur, 3, 1, 1)
            d[(nxt > 0) & (cur == 0)] = 2.0 * k
            cur = nxt
        dv = Fn.interpolate(d, size=list(sh), mode="trilinear", align_corners=False)[0, 0]
        return p, wi, dv, cav

    # ------------------------------------------------------------------ main
    def render(self, cache, gen=None, axial_axis=2, seed=None):
        import torch
        k = self.k; dev = self.dev; F = self.F
        g = gen if gen is not None else torch.Generator().manual_seed(int(seed if seed is not None else np.random.randint(1 << 30)))
        rng = np.random.default_rng(int(torch.randint(1 << 30, (1,), generator=g)))
        F._gd = torch.Generator(device=dev).manual_seed(int(torch.randint(1 << 30, (1,), generator=g)))
        sh = tuple(int(x) for x in cache["shape"]); sp = np.asarray(cache["sp"], float)
        T = lambda a, dt=torch.float32: torch.from_numpy(np.ascontiguousarray(a)).to(dev).to(dt)
        brain = T(cache["brain"], torch.bool); les = T(cache["les"], torch.bool)
        p = T(cache["p"]) / 255.0; w_u8 = T(cache["w"], torch.long); dvent = T(cache["dvent"])
        cls = self.t1cls.get(str(cache.get("clskey", ""))) if "t1z" in cache else None
        cav_fix = None
        if cls is not None:                           # T1-class fix: CSF fraction / GM-WM axis / ventricle distance from the T1
            p, w_u8, dvent, cav_fix = self._t1_maps(T(cache["t1z"]), brain, les, w_u8, cls, sp)
        tau = float(rng.uniform(*self.k.p_sharp))
        lo_s, hi_s = 1 / (1 + np.exp(0.5 / tau)), 1 / (1 + np.exp(-0.5 / tau))
        p = ((torch.sigmoid((p - 0.5) / tau) - lo_s) / (hi_s - lo_s)).clamp(0, 1)
        info = dict(comps=[], negs=[], v="render2")
        negmap = torch.zeros(sh, dtype=torch.uint8, device=dev)
        # ---- 1. contrast (FLAIR physics; WM = 0)
        cs = (self.lib or {}).get("class_stats")
        realistic = rng.random() >= k.p_random_contrast
        if realistic and cs and rng.random() < k.p_class_stats:
            gmF, csfF, nsd = cs[rng.integers(len(cs))]
            kap = float(rng.uniform(*k.kappa))
            I_gm = float(kap * gmF / nsd + k.gm_jitter * rng.standard_normal())
            I_csf = float(min(kap * csfF / nsd + k.csf_jitter * rng.standard_normal(), k.csf_max))
            if rng.random() < k.p_poor_suppression:
                I_csf = float(rng.uniform(-3.0, -1.5))
        elif realistic:
            I_gm = float(rng.uniform(-0.3, 1.2))
            I_csf = float(rng.uniform(-10.0, -2.0)) if rng.random() > k.p_poor_suppression else float(rng.uniform(-3.0, -1.5))
        else:
            while True:
                I_gm, I_csf = (float(x) for x in rng.normal(0, 4, 2))
                if min(abs(I_gm), abs(I_csf), abs(I_gm - I_csf)) > 1.0:
                    break
        I_wm = 0.0
        sig_n = float(rng.uniform(*k.noise_sd)); sig_t = float(np.sqrt(max(0.25, 1.0 - sig_n ** 2)) * rng.uniform(*k.tex_total))
        info.update(realistic=bool(realistic), I_gm=I_gm, I_csf=I_csf, sig_n=sig_n, sig_t=sig_t)
        gam = float(np.exp(rng.normal(0, k.gamma_w_sd)))
        lut = I_gm + (I_wm - I_gm) * (torch.arange(256, device=dev, dtype=torch.float32) / 200.0).clamp(0, 1.1) ** gam
        tissue_I = lut[w_u8]
        if F.tex is not None and rng.random() < k.p_real_texture:
            t = F.tex[int(rng.integers(len(F.tex)))]
            fl_ = [a for a in range(3) if rng.random() < 0.5]
            if fl_:
                t = torch.flip(t, fl_)
            t = t.permute(*[int(a) for a in rng.permutation(3)])
            reps = [int(np.ceil(s / 64)) + 1 for s in sh]; o = [int(rng.integers(64)) for _ in sh]
            tex = t.repeat(*reps)[o[0]:o[0] + sh[0], o[1]:o[1] + sh[1], o[2]:o[2] + sh[2]]; info["texture"] = "real"
        else:
            tex = 0.6 * self._noise(sh, float(rng.uniform(1.0, 2.0))) + 0.4 * self._noise(sh, float(rng.uniform(2.0, 4.0)))
            info["texture"] = "gauss"
        tis = (p < 0.5) & brain
        tex = tex / (F._sub(tex, tis).std() + 1e-6) * sig_t
        bias_sd = float(rng.uniform(*k.bias_sd))
        bg = p * I_csf + (1 - p) * (tissue_I + tex + bias_sd * self._noise(sh, 50.0 / sp.mean()))
        s0 = 1.0                                                          # amplitude unit = NAWM SD
        # ---- 2. negative realism (label 0, physiological)
        if rng.random() < k.p_pv_lining and float(dvent.max()) > 0:
            lam = float(rng.uniform(*k.pv_lambda)); amp = float(rng.uniform(*k.pv_amp)) * s0
            near = (dvent > 0) & (dvent <= 10) & tis
            nf = self._noise(sh, 12.0 / sp.mean())[near]                                  # caps vary along the walls
            mod = (0.5 + 0.5 * nf).clamp(0, 1.5); lamf = lam * (0.6 + 0.8 * (0.5 - 0.5 * nf).clamp(0, 1.2))
            Lv = amp * mod * torch.exp(-(dvent[near] - 0.5).clamp(min=0) / lamf.clamp(min=0.3))
            bg[near] = bg[near] + Lv
            nmv = negmap[near]; nmv[Lv > 0.7 * s0] = CODE_PV_LINING; negmap[near] = nmv
            info["pv_lining"] = dict(lam=lam, amp=amp / s0)
        if rng.random() < k.p_wm_diffuse:
            sc = float(rng.uniform(*k.wm_diffuse_scale)); amp = float(rng.uniform(*k.wm_diffuse_amp)) * s0
            fld = self._noise(sh, sc / sp.mean())
            fld = (fld - 0.8).clamp(min=0)                                                   # sparse smooth bumps
            fld = fld / (fld.max() + 1e-6) * amp
            wmm = (w_u8.float() / 200.0).clamp(0, 1) ** 2 * tis.float()
            Dw = fld * wmm
            bg = bg + Dw
            negmap = torch.where((Dw > 0.7 * s0) & (negmap == 0), torch.full_like(negmap, CODE_WM_DIFFUSE), negmap)
            info["wm_diffuse"] = dict(scale=sc, amp=amp / s0)
        if rng.random() < k.p_cortex:
            gmm = (w_u8 < 90) & tis
            amp = float(rng.uniform(*k.cortex_amp))
            mod = (self._noise(sh, float(rng.uniform(6.0, 15.0)) / sp.mean())[gmm] - 0.3).clamp(min=0)
            Cv = amp * mod / (float(mod.max()) + 1e-6)
            bg[gmm] = bg[gmm] + Cv
            nmv = negmap[gmm]; nmv[(Cv > 0.7) & (nmv == 0)] = CODE_CORTEX; negmap[gmm] = nmv
            info["cortex"] = amp
        # ---- acquisition sample (needed for decoy blur compensation and the lesion operator)
        acq = F.ref._sample_acq(rng, sp, axial_axis)
        F._acq_sig = [float(np.sqrt((st / s_) ** 2 / 12 + (st / s_) ** 2 / 6)) if st / s_ > 1.05 else 0.0 for st, s_ in zip(acq["step"], sp)]
        # ---- 3. v1 decoys (pathology-like -> IGNORE in stage 1; flow/sulcal/edge -> label 0)
        N = torch.zeros(sh, device=dev); NF = torch.zeros(sh, device=dev)
        F._negmap = torch.zeros(sh, dtype=torch.uint8, device=dev)
        F._negatives(cache, sh, sp, rng, g, N, NF, p, dvent, True, float(rng.uniform(0.9, 1.4)), (I_wm - I_csf) / s0, info)
        N = N * s0
        negmap = torch.where(F._negmap > 0, F._negmap, negmap)
        img = bg + N
        img = (1 - NF) * img + NF * I_csf
        # ---- 4. lesions: cavity (pre-acquisition, fluid level) + gliotic anomaly (post-acquisition, calibrated)
        cid = T(cache["cid"], torch.long); sd = T(cache["sd"]) / 4.0
        ncomp = len(cache["comp_ml"])
        G = None; spec = []
        if ncomp and bool((cid > 0).any()):
            nzc = np.argwhere(cache["cid"] > 0); bl = nzc.min(0); bh = nzc.max(0) + 1
            bb = tuple(slice(int(a_), int(b_)) for a_, b_ in zip(bl, bh)); bsh = tuple(int(b_ - a_) for a_, b_ in zip(bl, bh))
            cidb = cid[bb]; sdb = sd[bb]; lesb = les[bb]
            cavb = cav_fix[bb] if cav_fix is not None else T(cache["cav"][bb], torch.bool)
            if cav_fix is not None:                   # component cavity fraction from the corrected CSF map
                lab_ = torch.where(lesb, cidb, torch.zeros_like(cidb)).reshape(-1)
                cnt_ = torch.bincount(lab_, minlength=ncomp + 1).float().clamp(min=1)
                cavfrac = (torch.bincount(lab_, weights=cavb.reshape(-1).float(), minlength=ncomp + 1) / cnt_).cpu().numpy()
            else:
                cavfrac = np.concatenate([[0.0], np.asarray(cache["comp_cav"], np.float32)])
            jit = k.boundary_jitter_mm * self._noise(bsh, 4.0 / sp.mean())
            par = {nm: np.zeros(ncomp + 1, np.float32) for nm in ("amp", "rim", "w", "tau", "off", "halo", "lam", "tex", "cav", "foff", "on")}
            present = set(np.unique(cache["cid"][bb]).tolist()) - {0}
            for j in range(1, ncomp + 1):
                if j not in present:
                    continue
                vox = float(cache["comp_ml"][j - 1]) * 1000.0 / float(np.prod(sp)); depth = float(cache["comp_depth"][j - 1])
                cavf = float(cavfrac[j])
                tiny = vox < k.tiny_vox
                if tiny:
                    typ = "lacune" if (cavf > 0.2 and rng.random() < k.p_lacune) else "focus"
                    pre = float(rng.uniform(*k.tiny_pre)); tgt = None
                else:
                    typ = "cavity_rim" if cavf >= 0.05 else "gliosis"
                    tgt = float(np.exp(rng.uniform(np.log(k.core_range[0]), np.log(k.core_range[1])))); pre = None
                par["on"][j] = 1.0
                par["rim"][j] = float(rng.uniform(*k.rim_ratio)); par["w"][j] = float(rng.uniform(*k.rim_width))
                par["tau"][j] = float(rng.uniform(*k.edge_tau)); par["off"][j] = float(rng.uniform(*k.edge_off)) if depth >= 1.5 else min(0.3, float(rng.uniform(*k.edge_off)))
                par["halo"][j] = float(rng.uniform(*k.halo_frac)) if rng.random() < k.p_halo else 0.0
                par["lam"][j] = float(rng.uniform(0.8, 2.0)); par["tex"][j] = float(rng.uniform(*k.les_tex))
                par["cav"][j] = 1.0 if typ in ("cavity_rim", "lacune") else 0.0
                par["foff"][j] = float(rng.uniform(*k.cav_foff))
                spec.append(dict(comp=j, vox=vox, type=typ, target=tgt, pre=pre))
            ridx = torch.nonzero((cidb > 0).reshape(-1)).squeeze(1)              # voxel list of the lesion neighbourhood
            cv = cidb.reshape(-1)[ridx]
            Pv = {nm: torch.from_numpy(v).to(dev)[cv] for nm, v in par.items()}
            keep = Pv["on"] > 0
            ridx, cv = ridx[keep], cv[keep]; Pv = {nm: v[keep] for nm, v in Pv.items()}
            sv = sdb.reshape(-1)[ridx]; lv = lesb.reshape(-1)[ridx]
            dd = sv - jit.reshape(-1)[ridx] - Pv["off"]                          # anomaly coordinate (mm, - inside)
            inside = torch.sigmoid(-dd / Pv["tau"].clamp(min=0.2))               # soft partial-volume edge
            prof = 1.0 + (Pv["rim"] - 1.0) * torch.exp(-(-dd).clamp(min=0) / Pv["w"].clamp(min=0.3))   # rim >= core
            a = inside * prof
            hm = (dd > 0) & (dd <= 5) & (Pv["halo"] > 0)
            a = a + torch.where(hm, Pv["halo"] * torch.exp(-dd.clamp(min=0) / Pv["lam"].clamp(min=0.3)), torch.zeros_like(a))
            if float(par["tex"].max()) > 0:
                a = a * (1 + Pv["tex"] * self._noise(bsh, 1.5 / sp.mean()).reshape(-1)[ridx]).clamp(min=0)
            # cavity: fluid core where the real T1 shows CSF-like tissue inside the lesion (lacune: deep core too)
            lac = torch.zeros(ncomp + 1, dtype=torch.bool, device=dev)
            for s_ in spec:
                if s_["type"] == "lacune":
                    lac[s_["comp"]] = True
            cavm = (Pv["cav"] > 0) & lv & (cavb.reshape(-1)[ridx] | (lac[cv] & (sv < -1.0)))
            if bool(cavm.any()):
                ci = ridx[cavm]
                sub = img[bb].reshape(-1)
                ti = tissue_I[bb].reshape(-1)[ci]
                sub[ci] = I_csf + Pv["foff"][cavm] * (ti - I_csf)
                img[bb] = sub.view(bsh)
                a = torch.where(cavm, torch.zeros_like(a), a)                    # gliosis lives in the rim, not in the fluid
            Gb_ = torch.zeros(int(np.prod(bsh)), device=dev); Gb_[ridx] = a
            G = torch.zeros(sh, device=dev); G[bb] = Gb_.view(bsh)
            info["lesion_bbox"] = [[int(x), int(y)] for x, y in zip(bl, bh)]
        img = img * brain
        # ---- 5. global: positive magnitude frame (CSF near the Rician floor), gamma, optional scanner bias, acquisition + noise
        m = brain[None, None]
        floor = float(rng.uniform(*k.csf_floor))
        S = torch.where(m, (img[None, None] - I_csf + floor).clamp(min=0.05), torch.zeros_like(img[None, None]))
        hi_ = float(torch.quantile(F._sub(S, m), 0.995))
        gm = float(np.exp(rng.normal(0, k.gamma_sd)))
        if abs(gm - 1) > 1e-3:
            S = torch.where(m, hi_ * (S / hi_).clamp(min=0) ** gm, S)
        bias = None
        if rng.random() < k.p_uncorrected_bias:
            b = float(rng.uniform(0.05, k.bias_max))
            bias = torch.exp(b * self._noise(sh, 50.0 / sp.mean()))[None, None]
            S = S * bias
        info["gamma"] = gm
        Sl, lo_sz, sz = self._acq(S, acq, sp, add_noise=True, wm=sig_n)
        if rng.random() < k.p_ghost:
            ax = int(rng.integers(0, 3)); Sl = Sl + float(rng.uniform(0.02, 0.08)) * torch.roll(Sl, Sl.shape[2 + ax] // 2, dims=2 + ax)
        if rng.random() < k.p_gibbs:
            ax = int(rng.integers(0, 3)); n_ = Sl.shape[2 + ax]; keep = int(n_ * rng.uniform(0.6, 0.85))
            Fk = torch.fft.fftshift(torch.fft.fft(Sl, dim=2 + ax), dim=2 + ax)
            msk = torch.zeros(n_, device=dev); msk[(n_ - keep) // 2:(n_ - keep) // 2 + keep] = 1
            shp = [1] * 5; shp[2 + ax] = n_
            Sl = torch.fft.ifft(torch.fft.ifftshift(Fk * msk.view(shp), dim=2 + ax), dim=2 + ax).abs()
        S = self._up(Sl, lo_sz, sz)
        # NAWM noise level of the final image (robust SD in deep WM away from lesions)
        nawm = m & (w_u8 > 180)[None, None] & (p < 0.05)[None, None] & (dvent > 6)[None, None]
        if G is not None:
            nawm = nawm & (cid == 0)[None, None]
        nv = F._sub(S, nawm) if bool(nawm.any()) else F._sub(S, m)
        qn = torch.quantile(nv, torch.tensor([0.25, 0.5, 0.75], device=dev))
        sigN = max(float(0.7413 * (qn[2] - qn[0])), 1e-4); medN = float(qn[1])
        info["acq"] = {a_: b_ for a_, b_ in acq.items() if a_ not in ("res", "step")}; info["sigN"] = sigN
        # ---- 6. lesion gliosis added post-acquisition with the SAME blur, scaled to the target contrast
        if G is not None:
            Gm = G[None, None] * (bias if bias is not None else 1.0)
            Gb, _, _ = self._acq(Gm, acq, sp)
            Gb = self._up(Gb, lo_sz, sz)[0, 0]
            Gpre = Gm[0, 0]
            # fluid realised contrast (relative to the final NAWM level, SD units)
            cb = cid[bb]; Sb = S[0, 0][bb]; Gbb = Gb[bb]; Gpb = Gpre[bb]
            lab = torch.where(les[bb], cb, torch.zeros_like(cb)).reshape(-1)
            nl = ncomp + 1
            cnt = torch.bincount(lab, minlength=nl).float().clamp(min=1)
            labg = torch.where(Gpb.reshape(-1) > 0.2, lab, torch.zeros_like(lab))          # gliotic part only (not the fluid)
            gmean = torch.bincount(labg, weights=Gbb.reshape(-1), minlength=nl) / torch.bincount(labg, minlength=nl).float().clamp(min=1)
            gpk = torch.zeros(nl, device=dev).scatter_reduce(0, lab, Gpb.reshape(-1), reduce="amax")
            smean = torch.bincount(lab, weights=Sb.reshape(-1), minlength=nl) / cnt
            # ring (1-3 mm outside) mean of the final background for each component
            sdb2 = sd[bb]
            ring = (cb > 0) & (~les[bb]) & (sdb2 > 1.0) & (sdb2 <= 3.0) & brain[bb]
            labr = torch.where(ring, cb, torch.zeros_like(cb)).reshape(-1)
            cr = torch.bincount(labr, minlength=nl).float()
            rmean = torch.bincount(labr, weights=Sb.reshape(-1), minlength=nl) / cr.clamp(min=1)
            scl = np.zeros(nl, np.float32)
            gmean_n = gmean.cpu().numpy(); gpk_n = gpk.cpu().numpy(); smean_n = smean.cpu().numpy(); rmean_n = rmean.cpu().numpy(); cr_n = cr.cpu().numpy()
            ign = []
            for s in spec:
                j = s["comp"]
                if gmean_n[j] <= 1e-6 or gpk_n[j] <= 1e-6:
                    scl[j] = 0.0
                else:
                    cap = k.pre_cap * sigN / gpk_n[j]                  # pre-blur peak <= pre_cap NAWM SD
                    want = (s["target"] * sigN / gmean_n[j]) if s["target"] is not None else (s["pre"] * sigN / gpk_n[j])
                    scl[j] = float(min(want, cap))
                ref = rmean_n[j] if cr_n[j] >= 5 else medN
                real_c = (smean_n[j] - ref + scl[j] * gmean_n[j]) / sigN        # realised contrast vs the local ring
                fl_c = (smean_n[j] - medN) / sigN
                vis = max(abs(real_c), abs((smean_n[j] + scl[j] * gmean_n[j] - medN) / sigN))
                s.update(realised=round(float(real_c), 2), vs_nawm=round(float((smean_n[j] + scl[j] * gmean_n[j] - medN) / sigN), 2),
                         fluid_part=round(float(fl_c), 2), visible=bool(vis >= k.vis_cnr))
                if vis < k.vis_cnr:
                    ign.append(j)
            S = S + (torch.from_numpy(scl).to(dev)[cid] * Gb)[None, None]
            if ign:
                igt = torch.zeros(nl, dtype=torch.bool, device=dev); igt[ign] = True
                im = les[bb] & igt[cb]
                nb = negmap[bb]; nb[im] = CODE_LES_IGNORE; negmap[bb] = nb
            info["comps"] = spec; info["n_ignored_lesions"] = len(ign)
        v = F._sub(S, m)
        q = torch.quantile(v, torch.tensor([0.25, 0.5, 0.75], device=dev))
        z = ((S - q[1]) / (0.7413 * (q[2] - q[0]) + 1e-6)).clamp(-8, 12)
        out = torch.where(m, z, torch.zeros_like(z))[0, 0]
        negmap = torch.where(brain, negmap, torch.zeros_like(negmap))
        return out, negmap.cpu().numpy(), info

    def render_full(self, cache, gen=None, axial_axis=2):
        fl, nm, info = self.render(cache, gen=gen, axial_axis=axial_axis)
        return fl.cpu().numpy(), nm, info


def _load_lib():
    import cascade2_render as R
    return R.load_library(os.environ.get("C2_CG_LIBRARY", R.PRODUCTION_LIB))


def make_renderer(knobs=None, device="cpu"):
    kw = {}
    env = os.environ.get("C2_R2_KNOBS", "").strip()        # e.g. "vis_cnr=0.8,p_wm_diffuse=0" (screen variants; logged)
    if env:
        for it in env.split(","):
            a, b = it.split("=")
            cur = getattr(R2Knobs, a)
            kw[a] = type(cur)(float(b)) if not isinstance(cur, tuple) else tuple(float(x) for x in b.split(":"))
    k = knobs or R2Knobs(**kw)
    return Render2(k, device=device)


def make_online_hook2(return_negmap=True):
    """DA-worker hook (same contract as cascade2_render.make_online_hook): f(t1, les, key, bbox, rng) -> (flair z, negmap)."""
    import torch
    import cascade2_render as R
    Rn = make_renderer()
    store = R._CacheStore()

    def hook(t1, les, key, bbox, rng):
        pid = C.patient(key)
        meta, _ = store.get(pid)
        sh = tuple(int(x) for x in meta["shape"])
        lo = np.array([b[0] for b in bbox]); hi = np.array([b[1] for b in bbox])
        vlo = np.maximum(lo, 0); vhi = np.minimum(hi, sh)
        out = np.zeros(tuple(hi - lo), np.float32); nm = np.zeros(tuple(hi - lo), np.uint8)
        if (vhi <= vlo).any():
            return (out, nm) if return_negmap else out
        cc, ax, _ = store.crop(pid, tuple(slice(int(a), int(b)) for a, b in zip(vlo, vhi)))
        if int(cc["brain"].sum()) < 100:
            return (out, nm) if return_negmap else out
        g = torch.Generator().manual_seed(int(rng.integers(1 << 62)))
        dst = tuple(slice(int(a - l), int(b - l)) for a, b, l in zip(vlo, vhi, lo))
        cc = dict(cc); cc["t1z"] = np.ascontiguousarray(t1[dst], np.float32); cc["clskey"] = pid
        fl, negm, _info = Rn.render(cc, gen=g, axial_axis=ax)
        out[dst] = fl.detach().cpu().numpy().astype(np.float32); nm[dst] = negm
        br = np.zeros(out.shape, bool); br[dst] = cc["brain"].astype(bool)
        out[~br] = 0
        fl = R._zscore_np(out, br)
        return (fl, nm) if return_negmap else fl
    return hook


# ======================================================================================================================
# RENDER2-B ("breadth"; user re-scope 2026-11-16, supersedes the realism-oriented Render2 above, which is kept for the
# record only). The renderer's goal is NOT realism: stage 1 must read ANY FLAIR, so training appearance stays at least as
# broad as v1 (random contrast >= 50 %, random-anomaly family, lesion polarity/appearance as diverse as v1, extremes
# beyond real ranges). v1's engine (confirmgen_fast.FastConfirmGen, production knobs + library) renders everything;
# render2-B only adds changes that serve breadth or label correctness:
#   (a) BUG FIX: confirmgen's cached CSF fraction / GM-WM axis / ventricle distance come from a GMM that includes the dark
#       brain-edge rim (ventricle p ~ 0.3; often no ventricle found, dvent = 99). Replaced per crop from the case's OWN
#       z-scored T1 and a robust per-case GMM (render2_classmeans.py; no external data).
#   (b) LABEL CONSISTENCY: a labelled component must carry a detectable anomaly IN THIS RENDER, judged against the render's
#       own local contrast (polarity-free): max(|core - ring|, |edge - ring|, |shell - ring|) / ring robust SD. Below
#       vis_local -> IGNORE (code 250), never positive.
#   (c) SMALL-COMPONENT APPEARANCE FAMILY (revised 2026-11-16 at the coordinator's / user's request; NO lesions are inserted
#       at new locations): the patient's OWN components < 100 voxels get, with p 0.5, a clearly visible tiny-focus / lacune
#       (dark core + bright rim) / dark / random-knot look at 1.5-6 local robust SD (random polarity in random-contrast
#       renders, blur 0-1 voxel); components still invisible after that are repainted with p 0.5. Labels unchanged; the
#       visibility gate (b) still applies to every component.
#   (d) bright-tissue patterns stay IGNORE (all v1 bright decoys; 35n rule unchanged).
#   (e) breadth widened beyond v1 (knob B_WIDE): p_realistic 0.4 (60 % random contrast), random-anomaly family 0.25,
#       SNR 5-80, bias up to 0.5, thick slices up to 7 mm.
# ======================================================================================================================
CODE_INSERTED = 251


@dataclass
class R2BKnobs:
    fix_t1: bool = True
    vis_local: float = 1.5          # size-aware gate: score >= max(vis_floor, vis_local / sqrt(vox / 8))  (ring robust SD units;
    vis_floor: float = 0.4          #   a mean shift over n voxels is detectable at ~1/sqrt(n_eff), n_eff = vox / 8 for ~2 mm noise grain)
    ring_sd_floor: float = 0.1      # z units (render is z-scored, brain SD ~ 1)
    tiny_lambda: tuple = (0.0, 6.0) # inserted tiny lesions per crop ~ Poisson(U(a, b))
    tiny_vox: tuple = (2.0, 150.0)  # log-uniform volume (voxels ~ uL)
    p_elongated: float = 0.3
    p_lacunar: float = 0.3          # (engine mode only)
    insert_mode: str = "none"       # coordinator/user 2026-11-16: NO inserted lesions (copy-paste-like; would teach stage 2 to veto
                                    # tiny FLAIR-only heat). "post"/"engine" kept only for the record.
                                    # "post": tiny anomalies painted on the finished render, amplitude relative to the render's
                                    # own local SD (independent of v1's CNR library, whose small class has 8 values);
                                    # "engine": inserted into the cache and rendered by v1's lesion engine
    tiny_amp: tuple = (1.5, 6.0)    # post mode: peak |amplitude| in local robust-SD units
    tiny_types: tuple = (0.5, 0.2, 0.15, 0.15)   # bright / dark-core+bright-rim / dark / random-knot
    p_rescue: float = 0.5           # small components still invisible after the family draw: repaint (label kept) with this prob.
    small_vox: int = 100            # SMALL-COMPONENT APPEARANCE FAMILY: the patient's own components < small_vox voxels (0.1 mL)
    p_small_family: float = 0.5     #   get, with this raised probability, a clearly visible tiny-focus / lacune (dark core + bright
                                    #   rim) / dark / random-knot look at tiny_amp local SD (random polarity in random contrast)
    wide: bool = True


B_WIDE = dict(p_realistic=0.4, p_random=0.25, snr=(5.0, 80.0), bias_max=0.5, thick_mm=(2.0, 7.0),
              # internal lesion heterogeneity widened (v1 0-0.5): GPU probe 2026-11-16, iv detector on real CONTRA: real lesion
              # in real background -> in-lesion heat 0.46; v1-rendered lesion pasted into the same real background -> 0.87; real
              # lesions are ~2x more heterogeneous inside than v1 lesions (p90-p10 6.1 vs 2.8 NAWM SD, >= 1 mL). Breadth, not a fit.
              lesion_texture=(0.0, 1.2))


class Render2B:
    def __init__(self, knobs: R2BKnobs | None = None, device="cpu"):
        import json as _json
        import confirmgen_core as CG
        import confirmgen_fast as CF
        self.k = knobs or R2BKnobs()
        self.lib = _load_lib()
        vk = CG.production_knobs(**(B_WIDE if self.k.wide else {}))
        self.vk = vk
        self.F = CF.FastConfirmGen(vk, self.lib, device=device, skip_gin=True)     # GIN stays on the GPU (trainer)
        self.helper = Render2.__new__(Render2); self.helper.F = self.F; self.helper.dev = self.F.dev   # _t1_maps only
        cp = C.WS / "outputs/direction2/render2/t1_classes.json"
        self.t1cls = _json.load(open(cp)) if cp.exists() else {}
        self.CF = CF

    # ---- (a)
    def _fix(self, cc, t1z, key):
        import torch
        cls = self.t1cls.get(str(key))
        if cls is None or not self.k.fix_t1:
            return cc, False
        T = lambda a, dt=torch.float32: torch.from_numpy(np.ascontiguousarray(a)).to(dt)
        brain = T(cc["brain"], torch.bool); les = T(cc["les"], torch.bool)
        p, wi, dv, cav = self.helper._t1_maps(T(t1z), brain, les, T(cc["w"], torch.long), cls, np.asarray(cc["sp"], float))
        cc["p"] = (p * 255).round().clamp(0, 255).to(torch.uint8).numpy()
        cc["w"] = wi.clamp(0, 255).to(torch.uint8).numpy()
        cc["dvent"] = dv.round().clamp(0, 255).to(torch.uint8).numpy()
        cc["cav"] = cav.to(torch.uint8).numpy()
        n = len(cc["comp_ml"])
        if n:
            cid = cc["cid"]; m = cc["les"].astype(bool)
            cnt = np.bincount(cid[m], minlength=n + 1).astype(float); cv = np.bincount(cid[m], weights=cc["cav"][m].astype(float), minlength=n + 1)
            frac = np.where(cnt > 0, cv / np.maximum(cnt, 1), np.concatenate([[0.0], np.asarray(cc["comp_cav"], float)]))
            cc["comp_cav"] = frac[1:].astype(np.float32)
        return cc, True

    # ---- (c)
    def _insert_tiny(self, cc, rng, avoid=None):
        import scipy.ndimage as ndi
        lam = float(rng.uniform(*self.k.tiny_lambda)); nins = int(rng.poisson(lam))
        if nins == 0:
            return cc, []
        sh = tuple(int(x) for x in cc["shape"]); sp = np.asarray(cc["sp"], float)
        sites = cc.get("site_tissue", np.zeros(0, np.int32))
        if len(sites) == 0:
            return cc, []
        les = cc["les"].astype(bool).copy(); cid = cc["cid"].astype(np.int16).copy(); sd = cc["sd"].astype(np.int8).copy()
        cav = cc["cav"].astype(np.uint8).copy(); brain = cc["brain"].astype(bool)
        n0 = len(cc["comp_ml"]); ml, dep, ret, cvf = list(cc["comp_ml"]), list(cc["comp_depth"]), list(np.asarray(cc["comp_ret"]).reshape(-1, 3, len(self.CF.SIG_GRID))), list(cc["comp_cav"])
        added = []
        for _ in range(nins):
            c = np.array(np.unravel_index(int(sites[rng.integers(len(sites))]), sh))
            if cid[tuple(c)] != 0 or les[tuple(c)] or (avoid is not None and avoid[tuple(c)]):
                continue
            vox = float(np.exp(rng.uniform(np.log(self.k.tiny_vox[0]), np.log(self.k.tiny_vox[1]))))
            r0 = (vox * 3 / (4 * np.pi)) ** (1 / 3)
            ax = rng.uniform(0.7, 1.3, 3)
            if rng.random() < self.k.p_elongated:
                ax = np.array([0.6, 0.6, rng.uniform(1.8, 3.0)])
            radii = r0 * ax / np.cbrt(np.prod(ax))
            pad = int(np.ceil(radii.max())) + 12
            lo = np.maximum(c - pad, 0); hi = np.minimum(c + pad + 1, sh)
            g = np.stack(np.meshgrid(*[(np.arange(a, b) - ci) * s for a, b, ci, s in zip(lo, hi, c, sp)], indexing="ij"), -1)
            Q, _ = np.linalg.qr(rng.standard_normal((3, 3)))
            q = np.sqrt((((g @ Q) / np.maximum(radii, 0.5)) ** 2).sum(-1))
            q = q * (1 + 0.15 * rng.standard_normal(q.shape))
            box = tuple(slice(int(a), int(b)) for a, b in zip(lo, hi))
            m = (q <= 1.0) & brain[box] & (cid[box] == 0) & ~les[box]
            if avoid is not None:
                m &= ~avoid[box]
            if m.sum() < 1:
                continue
            j = n0 + len(added) + 1
            din = ndi.distance_transform_edt(m, sampling=sp); dout = ndi.distance_transform_edt(~m, sampling=sp)
            sdv = np.clip(np.round(np.where(m, -(din - 0.5), dout - 0.5) * 4), -127, 127).astype(np.int8)
            near = (dout <= 10.0) & (cid[box] == 0)
            cid[box] = np.where(m | near, j, cid[box]); sd[box] = np.where(m | near, sdv, sd[box])
            les[box] |= m
            lac = rng.random() < self.k.p_lacunar and m.sum() >= 3
            if lac:
                core = m & (din >= min(1.0, float(din.max())))
                cav[box] = np.where(core, 1, cav[box])
            cpad = np.pad(m.astype(np.float32), 8); mpad = np.pad(m, 8)
            rt = np.ones((3, len(self.CF.SIG_GRID)), np.float32)
            for a_ in range(3):
                for gi, s_ in enumerate(self.CF.SIG_GRID[1:], 1):
                    rt[a_, gi] = float(ndi.gaussian_filter1d(cpad, s_, axis=a_)[mpad].mean())
            ml.append(float(m.sum() * np.prod(sp) / 1000)); dep.append(float(din.max())); ret.append(rt)
            cvf.append(float((cav[box][m] > 0).mean()))
            added.append(j)
        if added:
            cc.update(les=les.astype(np.uint8), cid=cid, sd=sd, cav=cav, comp_ml=np.array(ml, np.float32), comp_depth=np.array(dep, np.float32),
                      comp_ret=np.array(ret, np.float32), comp_cav=np.array(cvf, np.float32))
        return cc, added

    # ---- (c, post mode) paint an anomaly of random type on the finished render over mask m (box), amplitude vs local SD
    def _paint(self, out, box, m, rng, realistic):
        import scipy.ndimage as ndi
        o = out[box]
        loc = o[~m]
        med = float(np.median(loc)) if loc.size else 0.0
        lsd = max(float(1.4826 * np.median(np.abs(loc - med))) if loc.size else 1.0, 0.15)
        amp = float(rng.uniform(*self.k.tiny_amp)) * lsd
        t = rng.choice(4, p=np.asarray(self.k.tiny_types) / np.sum(self.k.tiny_types))
        sgn = 1.0 if (realistic or rng.random() < 0.5) else -1.0
        din = ndi.distance_transform_edt(m)
        if t == 0:
            prof = m.astype(np.float32)
        elif t == 1:
            prof = np.where(m, np.where(din >= 1.5, -0.8, 1.0), 0.0).astype(np.float32)
            if not (din >= 1.5).any():
                prof = m.astype(np.float32)
        elif t == 2:
            prof = -m.astype(np.float32)
        else:
            k_ = rng.uniform(-1, 1, 3); k_[np.argmax(np.abs(k_))] = np.sign(k_[np.argmax(np.abs(k_))]) or 1.0
            dmax = max(float(din.max()), 1.0)
            prof = np.where(m, np.interp(din / dmax, [0.0, 0.5, 1.0], k_), 0.0).astype(np.float32)
        prof = prof * (1 + rng.uniform(0, 0.4) * rng.standard_normal(prof.shape)).astype(np.float32)
        sig = float(rng.uniform(0.0, 1.0))
        if sig > 0.25:
            prof = ndi.gaussian_filter(prof, sig)
        out[box] = o + sgn * amp * prof

    def _post_tiny(self, out, nm, cc, rng, realistic):
        """insert tiny lesions on the finished render (masks + cid/sd via _insert_tiny's geometry), and rescue-paint
        invisible real tiny components. Returns updated (out, cc, added_ids)."""
        cc2, added = self._insert_tiny(dict(cc), rng, avoid=nm > 0)
        if added:
            les = cc2["les"].astype(bool); cid = cc2["cid"]
            for j in added:
                m_full = les & (cid == j)
                idx = np.argwhere(m_full); lo = np.maximum(idx.min(0) - 4, 0); hi = np.minimum(idx.max(0) + 5, out.shape)
                box = tuple(slice(int(a), int(b)) for a, b in zip(lo, hi))
                self._paint(out, box, m_full[box], rng, realistic)
        return out, cc2, added

    # ---- (b)
    def _gate(self, out, cc):
        les = cc["les"].astype(bool); cid = cc["cid"].astype(np.int64); sd = cc["sd"].astype(np.float32) / 4.0
        n = len(cc["comp_ml"])
        if n == 0 or not les.any():
            return [], {}
        nz = np.argwhere(cid > 0); lo = nz.min(0); hi = nz.max(0) + 1
        bb = tuple(slice(int(a), int(b)) for a, b in zip(lo, hi))
        o = out[bb]; c = cid[bb]; L = les[bb]; s = sd[bb]; br = cc["brain"][bb].astype(bool)
        core = L & (s <= -1.5); edge = L & (s > -1.5); shell = (~L) & (s > 0) & (s <= 1.0) & br
        ring = (~L) & (s > 1.0) & (s <= 3.5) & br
        res = {}
        ign = []
        N = n + 1

        def grp_median(vals, labs):
            """per-label median (vectorised): sort by (label, value)."""
            if vals.size == 0:
                return np.full(N, np.nan), np.zeros(N, int)
            o_ = np.lexsort((vals, labs)); v_ = vals[o_]; l_ = labs[o_]
            cnt = np.bincount(l_, minlength=N); st = np.concatenate([[0], np.cumsum(cnt)[:-1]])
            med = np.full(N, np.nan); ok = cnt > 0
            med[ok] = v_[st[ok] + cnt[ok] // 2]
            return med, cnt
        rl = c[ring]; rv = o[ring]
        med, rc = grp_median(rv, rl)
        # fallback ring (0-6 mm) for components with < 5 ring voxels
        fb = (~L) & br & (s > 0) & (s <= 6.0)
        med2, rc2 = grp_median(o[fb], c[fb])
        use2 = rc < 5
        med = np.where(use2, med2, med); cntr = np.where(use2, rc2, rc)
        ring_eff = np.where(use2[c] & fb, True, ring & ~use2[c])
        ad = np.abs(o[ring_eff] - med[c[ring_eff]])
        mad, _ = grp_median(ad, c[ring_eff])
        rsd = np.maximum(1.4826 * np.nan_to_num(mad, nan=0.0), self.k.ring_sd_floor)
        nvox = np.bincount(c[L], minlength=N)
        best = np.zeros(N)
        for mk in (core, edge, shell, L):
            cn = np.bincount(c[mk], minlength=N); sm = np.bincount(c[mk], weights=o[mk], minlength=N)
            with np.errstate(invalid="ignore", divide="ignore"):
                dv = np.abs(sm / np.maximum(cn, 1) - np.nan_to_num(med))
            best = np.where(cn >= 1, np.maximum(best, dv), best)
        for j in range(1, N):
            if nvox[j] == 0 or cntr[j] < 5 or not np.isfinite(med[j]):
                continue
            score = float(best[j] / rsd[j])
            thr = max(self.k.vis_floor, self.k.vis_local / np.sqrt(max(nvox[j] / 8.0, 1.0)))
            res[j] = (round(score, 2), int(nvox[j]), round(thr, 2))
            if score < thr:
                ign.append(j)
        return ign, res

    def render(self, cc, gen, axial_axis, t1z=None, key=None, rng=None):
        import torch
        rng = rng if rng is not None else np.random.default_rng(int(torch.randint(1 << 30, (1,), generator=gen)))
        cc = dict(cc)
        fixed = False
        if t1z is not None:
            cc, fixed = self._fix(cc, t1z, key)
        added = []
        if self.k.insert_mode == "engine":
            cc, added = self._insert_tiny(cc, rng)
        out, info = self.F.render(cc, gen=gen, axial_axis=axial_axis, return_negmap=True)
        out = out.detach().cpu().numpy().astype(np.float32)
        nm = np.asarray(info.pop("negmap"), np.uint8)
        rescued = []; family = []
        realistic = bool(info.get("realistic", True))
        les0 = cc["les"].astype(bool); cid0 = cc["cid"]
        n0 = len(cc["comp_ml"])
        if n0 and les0.any():
            szs = np.bincount(cid0[les0].astype(np.int64), minlength=n0 + 1)

            def paint_comp(j):
                mf = les0 & (cid0 == j)
                idx = np.argwhere(mf); lo = np.maximum(idx.min(0) - 4, 0); hi = np.minimum(idx.max(0) + 5, out.shape)
                box = tuple(slice(int(a_), int(b_)) for a_, b_ in zip(lo, hi))
                self._paint(out, box, mf[box], rng, realistic)
            for j in range(1, n0 + 1):                       # small-component appearance family (patient's own masks)
                if 0 < szs[j] < self.k.small_vox and rng.random() < self.k.p_small_family:
                    paint_comp(j); family.append(j)
            ign0, _ = self._gate(out, cc)
            for j in ign0:                                   # still invisible small components: rescue repaint (label kept)
                if 0 < szs[j] < self.k.small_vox and j not in family and rng.random() < self.k.p_rescue:
                    paint_comp(j); rescued.append(j)
        if self.k.insert_mode == "post":                      # record only (default "none")
            out, cc, added = self._post_tiny(out, nm, cc, rng, realistic)
        ign, scores = self._gate(out, cc)
        les = cc["les"].astype(bool); cid = cc["cid"]
        if added:
            nm = np.where(les & np.isin(cid, added), CODE_INSERTED, nm).astype(np.uint8)
        if ign:
            nm = np.where(les & np.isin(cid, ign), CODE_LES_IGNORE, nm).astype(np.uint8)
        info.update(v="render2B", t1_fixed=fixed, inserted=len(added), ignored=len(ign), vis_scores=scores, inserted_ids=added,
                    ignored_ids=ign, rescued_ids=rescued, small_family_ids=family)
        return out, nm, info

    def render_full(self, cache, gen=None, axial_axis=2):
        import torch
        g = gen if gen is not None else torch.Generator().manual_seed(0)
        t1z = cache.get("t1z"); key = cache.get("clskey")
        out, nm, info = self.render({k: v for k, v in cache.items() if k not in ("t1z", "clskey")}, g, axial_axis, t1z, key)
        return out, nm, info


def make_renderer_b(device="cpu"):
    kw = {}
    env = os.environ.get("C2_R2B_KNOBS", "").strip()        # e.g. "vis_local=0.7,wide=0" (screen variants; logged)
    if env:
        for it in env.split(","):
            a, b = it.split("=")
            cur = getattr(R2BKnobs, a)
            kw[a] = ((b not in ("0", "false")) if isinstance(cur, bool) else b if isinstance(cur, str)
                     else tuple(float(x) for x in b.split(":")) if isinstance(cur, tuple) else type(cur)(float(b)))
    return Render2B(R2BKnobs(**kw), device=device)


def make_online_hook2b(return_negmap=True):
    """DA-worker hook, render2-B (same contract as cascade2_render.make_online_hook): f(t1, les, key, bbox, rng) -> (flair z, negmap).
    negmap: v1 decoy codes, 250 (labelled lesion invisible in this render -> ignore), 251 (inserted tiny lesion -> label 1)."""
    import torch
    import cascade2_render as R
    Rn = make_renderer_b()
    store = R._CacheStore()

    def hook(t1, les, key, bbox, rng):
        pid = C.patient(key)
        meta, _ = store.get(pid)
        sh = tuple(int(x) for x in meta["shape"])
        lo = np.array([b[0] for b in bbox]); hi = np.array([b[1] for b in bbox])
        vlo = np.maximum(lo, 0); vhi = np.minimum(hi, sh)
        out = np.zeros(tuple(hi - lo), np.float32); nm = np.zeros(tuple(hi - lo), np.uint8)
        if (vhi <= vlo).any():
            return (out, nm) if return_negmap else out
        cc, ax, _ = store.crop(pid, tuple(slice(int(a), int(b)) for a, b in zip(vlo, vhi)))
        if int(cc["brain"].sum()) < 100:
            return (out, nm) if return_negmap else out
        g = torch.Generator().manual_seed(int(rng.integers(1 << 62)))
        dst = tuple(slice(int(a - l), int(b - l)) for a, b, l in zip(vlo, vhi, lo))
        fl, negm, _info = Rn.render(cc, g, ax, t1z=np.ascontiguousarray(t1[dst], np.float32), key=pid, rng=rng)
        out[dst] = fl; nm[dst] = negm
        br = np.zeros(out.shape, bool); br[dst] = cc["brain"].astype(bool)
        out[~br] = 0
        fl = R._zscore_np(out, br)
        return (fl, nm) if return_negmap else fl
    return hook