File size: 24,319 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
#!/usr/bin/env python
"""cascade2 renderer v3 ("render3"): render2-B + a PROCEDURAL LESION FIELD (extreme breadth for the renderer-only detector).

NEW module (2026-11-18, renderer designer). cascade2_render2.py / confirmgen_fast.py are NOT modified (running jobs import
them). Render3 = Render2B (v1 engine at widened breadth, T1-class fix, size-aware visibility gate, small-component family)
plus procedurally generated synthetic lesions that are independent of any real lesion mask.

Why (render3/LOG.md, descriptive dev-test diagnosis, nothing fitted):
  * the renderer-only (iv) vs mix (ii) LAB gap is entirely lesions < 0.1 mL (t0.3 recall .57 vs .77, n 470), with heat ~0
    on the misses (flat over t 0.1-0.5); >= 0.1 mL iv >= ii everywhere.
  * the renderer's lesions are the T1-family patients' OWN masks: ~0.8 components of 10-100 voxels per patient, one
    location distribution (stroke territories), and 40-55 % of small ones invisible in v1. A detector trained on it has
    almost never been told that a tiny, multifocal, periventricular / juxtacortical focus is a lesion.
Design principle (user): BREADTH, NOT REALISM. Every distribution below is a wide generic prior (sizes, shapes, locations,
counts, contrasts); nothing is estimated from any test cohort, nothing is copied from a real lesion.

Procedural lesion field (per rendered crop, inserted into the crop cache BEFORE the v1 engine renders, so each synthetic
lesion goes through the engine's full appearance families (bright / gliosis / cavity+rim / profile library / random-knot
family, texture, halo, partial volume, edge jitter) and through the SAME acquisition operator (thick slice / 3D, noise,
bias), then through Render2B's small-component family and visibility gate):
  count     mixture: p_multifocal -> Poisson(U(mf_lambda)) (burden-like clusters), else Poisson(U(lambda))
  size      log-uniform voxels; p_tiny -> tiny_vox (8-150 voxels ~ uL), else big_vox (150-4000)
  shape     ellipsoid | elongated (ovoid / tubular) | irregular (noise-modulated radius) | lobulated (2-5 sub-ellipsoids)
  location  mixture over site classes computed from the crop's own tissue maps (no atlas): any tissue, periventricular
            band, juxtacortical (WM next to GM), deep WM, cortical GM, plus "cluster" satellites around a previous focus
  contrast  the engine's own priors (library CNR with hard tail, random family) + Render2B's small family (1.5-6 local
            SD, random type) -> wide, including faint; invisible components -> IGNORE (gate), never labelled positive
  labels    visible synthetic lesion -> label 1 (negmap code 251, C2R2DataLoader); invisible -> ignore (250)
Voronoi update of the engine's per-voxel (cid, sd) fields, so foci can sit 2-15 mm apart (multifocal) without
overwriting each other's lesion voxels.
Env C2_R3_KNOBS="k=v,..." overrides R3Knobs (screen variants; printed to the training log).
"""
from __future__ import annotations
import os, sys
from dataclasses import dataclass
from pathlib import Path
import numpy as np

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

CODE_INSERTED = R2.CODE_INSERTED     # 251 -> label 1 in C2R2DataLoader
CODE_LES_IGNORE = R2.CODE_LES_IGNORE


@dataclass
class R3Knobs:
    p_field: float = 0.85                 # P(a crop gets a procedural field at all)
    lam: tuple = (0.0, 8.0)               # sparse mode: Poisson(U(a, b)) foci per crop
    p_multifocal: float = 0.35            # burden mode
    mf_lambda: tuple = (8.0, 40.0)
    p_tiny: float = 0.7
    tiny_vox: tuple = (8.0, 150.0)
    big_vox: tuple = (150.0, 4000.0)
    shape_p: tuple = (0.3, 0.2, 0.3, 0.2)            # ellipsoid / elongated / irregular / lobulated
    loc_p: tuple = (0.2, 0.25, 0.25, 0.1, 0.05, 0.15)  # any / periventricular / juxtacortical / deep WM / cortex / cluster
    cluster_mm: tuple = (3.0, 15.0)
    p_lacunar: float = 0.25               # fluid core flag (engine cavity patterns use it)
    gap_mm: float = 1.0                   # keep >= this from any existing lesion voxel
    max_tries: int = 3
    # ---- 2026-11-19 additions (detector analyst dispatch); defaults OFF so R3a/b/c/d are unchanged
    # loc_p may carry a 7th entry = posterior fossa (needs render3/pfossa/<pid>.npz; falls back to "any") and an 8th =
    # CSF-adjacent tissue (next to ventricle / sulcus)
    p_conspic: float = 0.0                # (1) conspicuous tiny: repaint procedural foci < conspic_vox at conspic_amp local SD
    conspic_vox: float = 150.0
    conspic_amp: tuple = (2.5, 8.0)
    conspic_types: tuple = (0.7, 0.15, 0.05, 0.1)   # bright / dark-core+bright-rim / dark / random-knot
    band_p: float = 0.0                   # (2) faint perilesional band (LABEL 0): P per labelled component
    band_amp: tuple = (0.5, 1.5)          #     brain-z units added in a shell band_r mm outside the lesion, noise-modulated
    band_r: tuple = (1.5, 6.0)
    bg_lambda: tuple = (0.0, 0.0)         # (2) faint background patches (LABEL 0): Poisson(U(a, b)) per crop
    bg_amp: tuple = (0.5, 1.5)
    bg_r: tuple = (3.0, 12.0)
    p_cavity: float = 0.0                 # (4) P(procedural focus >= cavity_vox is a CSF-isointense cavity, painted post-render)
    cavity_vox: float = 60.0
    cavity_p_rim: float = 0.6             #     bright 1-voxel rim with this probability, else none (ex-vacuo look)
    cavity_p_csfsite: float = 0.6         #     cavity foci placed next to CSF (ventricle / sulcus) with this probability


def _box(mask, pad=4):
    idx = np.argwhere(mask)
    lo = np.maximum(idx.min(0) - pad, 0); hi = np.minimum(idx.max(0) + pad + 1, mask.shape)
    return tuple(slice(int(a), int(b)) for a, b in zip(lo, hi))


def _smooth_noise(shape, rng, corr=6.0):
    """unit-range smooth noise (coarse grid + linear upsampling), values in [0, 1]."""
    import scipy.ndimage as ndi
    lo = tuple(max(2, int(np.ceil(s / corr))) for s in shape)
    f = ndi.zoom(rng.random(lo).astype(np.float32), [a / b for a, b in zip(shape, lo)], order=1)
    f = np.pad(f, [(0, max(0, a - b)) for a, b in zip(shape, f.shape)], mode="edge")[:shape[0], :shape[1], :shape[2]]
    return f


def _knobs_from_env():
    kw = {}
    env = os.environ.get("C2_R3_KNOBS", "").strip()
    for it in [x for x in env.split(",") if x]:
        a, b = it.split("=")
        cur = getattr(R3Knobs, a)
        kw[a] = (tuple(float(x) for x in b.split(":")) if isinstance(cur, tuple) else type(cur)(float(b)))
    return R3Knobs(**kw)


class Render3(R2.Render2B):
    def __init__(self, knobs3: R3Knobs | None = None, knobs2: R2.R2BKnobs | None = None, device="cpu"):
        super().__init__(knobs2, device=device)
        self.k3 = knobs3 or R3Knobs()
        # C2_R3_VK="snr=3:100,bias_max=0.9,..." : overrides on the v1 engine knobs (acquisition / appearance breadth);
        # FastConfirmGen and its scalar reference share this Knobs object.
        self.vk_over = {}
        for it in [x for x in os.environ.get("C2_R3_VK", "").split(",") if x]:
            a_, b_ = it.split("=")
            cur = getattr(self.vk, a_)
            val = tuple(float(x) for x in b_.split(":")) if isinstance(cur, tuple) else type(cur)(float(b_))
            setattr(self.vk, a_, val); self.vk_over[a_] = val

    # ------------------------------------------------------------------ site classes from the crop's own maps
    def _sites(self, cc):
        import scipy.ndimage as ndi
        brain = cc["brain"].astype(bool)
        p = cc["p"].astype(np.float32) / 255.0                 # CSF probability
        w = cc["w"].astype(np.float32) / 200.0                 # 0 = GM .. 1 = WM
        dv = cc["dvent"].astype(np.float32)                    # mm to ventricle (uint8, capped)
        tis = brain & (p < 0.5)
        wm = tis & (w > 0.7); gm = tis & (w < 0.35)
        gmf = ndi.uniform_filter(gm.astype(np.float32), 5)
        S = {"any": tis, "pv": wm & (dv >= 1) & (dv <= 10), "jx": wm & (gmf > 0.08), "deep": wm & (dv > 10) & (gmf <= 0.02), "ctx": gm}
        csf = brain & (p > 0.6)
        S["csf"] = tis & (ndi.uniform_filter(csf.astype(np.float32), 5) > 0.06)
        if cc.get("pf") is not None:
            S["pf"] = tis & cc["pf"].astype(bool)
        return {k: np.flatnonzero(v) for k, v in S.items()}

    # ------------------------------------------------------------------ one procedural mask in a local box
    def _shape(self, c, vox, sp, sh, rng):
        import scipy.ndimage as ndi
        r0 = (vox * 3 / (4 * np.pi)) ** (1 / 3)               # mm (sp ~ 1 mm)
        st = int(rng.choice(4, p=np.asarray(self.k3.shape_p) / np.sum(self.k3.shape_p)))
        subs = []
        if st == 1:
            ax = np.array([0.6, 0.6, rng.uniform(1.8, 3.5)]); subs.append((np.zeros(3), r0 * ax / np.cbrt(np.prod(ax))))
        elif st == 3:
            n = int(rng.integers(2, 6)); rs = r0 / np.cbrt(n) * 1.1
            for _ in range(n):
                off = rng.standard_normal(3); off = off / (np.linalg.norm(off) + 1e-6) * rng.uniform(0, 1.2) * r0
                ax = rng.uniform(0.7, 1.3, 3); subs.append((off, rs * ax / np.cbrt(np.prod(ax))))
        else:
            ax = rng.uniform(0.6, 1.4, 3); subs.append((np.zeros(3), r0 * ax / np.cbrt(np.prod(ax))))
        ext = max(np.linalg.norm(o) + r.max() for o, r in subs) * (1.6 if st == 2 else 1.2)
        pad = np.ceil(ext / sp).astype(int) + 2
        lo = np.maximum(c - pad, 0); hi = np.minimum(c + pad + 1, sh)
        if (hi - lo < 1).any():
            return None, None
        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.full(g.shape[:3], np.inf, np.float32)
        for off, r in subs:
            Q, _ = np.linalg.qr(rng.standard_normal((3, 3)))
            qq = np.sqrt(((((g - off) @ Q) / np.maximum(r, 0.5)) ** 2).sum(-1))
            q = np.minimum(q, qq)
        if st == 2:                                              # irregular: smooth-noise radius modulation
            nz = ndi.gaussian_filter(rng.standard_normal(q.shape).astype(np.float32), rng.uniform(1.0, 2.5))
            nz = nz / (nz.std() + 1e-6)
            q = q * (1 + rng.uniform(0.2, 0.6) * nz)
        else:
            q = q * (1 + 0.1 * rng.standard_normal(q.shape))
        return tuple(slice(int(a), int(b)) for a, b in zip(lo, hi)), q <= 1.0

    # ------------------------------------------------------------------ insert the field into the crop cache
    def _insert_field(self, cc, rng):
        import scipy.ndimage as ndi
        k3 = self.k3
        self._cav_ids = []
        if rng.random() >= k3.p_field:
            return cc, []
        lam = rng.uniform(*k3.mf_lambda) if rng.random() < k3.p_multifocal else rng.uniform(*k3.lam)
        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 = self._sites(cc)
        names = ["any", "pv", "jx", "deep", "ctx", "cluster", "pf", "csf"][:len(k3.loc_p)]
        lp = np.asarray(k3.loc_p, float); lp = lp / lp.sum()
        cav_ids = []
        brain = cc["brain"].astype(bool)
        les = cc["les"].astype(bool).copy(); cid = cc["cid"].astype(np.int16).copy()
        sd = cc["sd"].astype(np.int16).copy()                    # quarter-mm, signed (int8 range on write-back)
        cav = cc["cav"].astype(np.uint8).copy()
        n0 = len(cc["comp_ml"])
        ml = list(np.asarray(cc["comp_ml"], np.float32)); dep = list(np.asarray(cc["comp_depth"], np.float32))
        ret = list(np.asarray(cc["comp_ret"], np.float32).reshape(-1, 3, len(self.CF.SIG_GRID))); cvf = list(np.asarray(cc["comp_cav"], np.float32))
        sdist = np.where(cid > 0, sd.astype(np.float32) / 4.0, 1e3)   # distance (mm) to the nearest existing lesion (cid>0 zone)
        added = []; centres = []
        for _ in range(nins):
            lo_, hi_ = (k3.tiny_vox if rng.random() < k3.p_tiny else k3.big_vox)
            vox = float(np.exp(rng.uniform(np.log(lo_), np.log(hi_))))
            is_cav = vox >= k3.cavity_vox and rng.random() < k3.p_cavity
            for _try in range(k3.max_tries):
                nm = names[int(rng.choice(len(names), p=lp))]
                if is_cav and rng.random() < k3.cavity_p_csfsite:
                    nm = "csf"
                if nm == "cluster" and centres:
                    c0 = centres[int(rng.integers(len(centres)))]
                    d = rng.standard_normal(3); d = d / (np.linalg.norm(d) + 1e-6) * rng.uniform(*k3.cluster_mm)
                    c = np.clip(np.round(c0 + d / sp).astype(int), 0, np.array(sh) - 1)
                    if not (brain[tuple(c)] and cc["p"][tuple(c)] < 128):
                        continue
                else:
                    s = sites.get(nm if nm != "cluster" else "any")
                    if s is None or len(s) == 0:
                        s = sites["any"]
                    if len(s) == 0:
                        break
                    c = np.array(np.unravel_index(int(s[rng.integers(len(s))]), sh))
                if les[tuple(c)] or sdist[tuple(c)] < k3.gap_mm + 1.0:
                    continue
                box, m = self._shape(c, vox, sp, sh, rng)
                if box is None:
                    continue
                m = m & brain[box] & ~les[box] & (sdist[box] > k3.gap_mm)
                if m.sum() < 3:
                    continue
                lab, nl = ndi.label(m, structure=np.ones((3, 3, 3)))
                if nl > 1:                                       # keep the largest piece (one component per id)
                    m = lab == (np.argmax(np.bincount(lab.ravel())[1:]) + 1)
                j = n0 + len(added) + 1
                if j > 32000:
                    break
                din = ndi.distance_transform_edt(m, sampling=sp); dout = ndi.distance_transform_edt(~m, sampling=sp)
                sdn = np.where(m, -(din - 0.5), dout - 0.5)
                upd = m | ((dout <= 10.0) & ~les[box] & (sdn < sdist[box]))       # Voronoi: nearer to this focus
                cid[box] = np.where(upd, j, cid[box])
                sd[box] = np.where(upd, np.clip(np.round(sdn * 4), -127, 127), sd[box])
                sdist[box] = np.where(upd, np.maximum(sdn, 0.0), sdist[box])
                les[box] |= m
                if rng.random() < k3.p_lacunar and m.sum() >= 3:
                    cav[box] = np.where(m & (din >= min(1.0, float(din.max()))), 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); centres.append(c.astype(float))
                if is_cav:
                    cav_ids.append(j)
                break
        if added:
            cc = dict(cc)
            cc.update(les=les.astype(np.uint8), cid=cid, sd=np.clip(sd, -127, 127).astype(np.int8), 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))
        self._cav_ids = cav_ids
        return cc, added

    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)
        cc, added = self._insert_field(cc, rng)
        # Render2B.render without its own (disabled) insertion path; T1 fix already applied
        out, nm, info = super().render(cc, gen, axial_axis, t1z=None, key=None, rng=rng)
        les = cc["les"].astype(bool); cid = cc["cid"]
        post = self._post(out, nm, cc, added, rng, bool(info.get("realistic", True)))
        info.update(post)
        if added:
            ins = les & np.isin(cid, added) & (nm != CODE_LES_IGNORE)
            nm = np.where(ins, CODE_INSERTED, nm).astype(np.uint8)
        info.update(v="render3", t1_fixed=fixed, field_n=len(added), field_ids=added,
                    field_ignored=int(len(set(added) & set(info.get("ignored_ids", [])))))
        return out, nm, info


def _post_impl(self, out, nm, cc, added, rng, realistic):
    """post-render families (in place on out / nm). Returns info dict."""
    import scipy.ndimage as ndi
    k3 = self.k3; info = {}
    les = cc["les"].astype(bool); cid = cc["cid"].astype(np.int64); brain = cc["brain"].astype(bool)
    sp = np.asarray(cc["sp"], float)
    # (1) conspicuous tiny repaint of procedural foci (label kept; gate decision overridden: they are visible now)
    nc = 0
    if added and k3.p_conspic > 0:
        old = (self.k.tiny_amp, self.k.tiny_types)
        self.k.tiny_amp, self.k.tiny_types = k3.conspic_amp, k3.conspic_types
        try:
            for j in added:
                mf = les & (cid == j)
                n = int(mf.sum())
                if 0 < n < k3.conspic_vox and rng.random() < k3.p_conspic and j not in self._cav_ids:
                    bx = _box(mf); self._paint(out, bx, mf[bx], rng, realistic)
                    nm[mf & (nm == CODE_LES_IGNORE)] = 0; nc += 1
        finally:
            self.k.tiny_amp, self.k.tiny_types = old
    info["conspic_n"] = nc
    # (4) CSF-isointense cavities (procedural foci flagged at insertion)
    ncav = 0
    p = cc["p"].astype(np.float32) / 255.0
    csfv = out[brain & (p > 0.8)]
    if self._cav_ids and csfv.size > 50:
        csf_level = float(np.median(csfv))
        for j in self._cav_ids:
            mf = les & (cid == j)
            if mf.sum() < 3:
                continue
            bx = _box(mf, 6); m = mf[bx]
            d = ndi.distance_transform_edt(~m, sampling=sp)
            ring = (d > 1) & (d <= 4) & brain[bx] & ~les[bx]
            if ring.sum() < 5:
                continue
            rv = out[bx][ring]; rmed = float(np.median(rv)); rsd = max(float(1.4826 * np.median(np.abs(rv - rmed))), 0.15)
            if abs(csf_level - rmed) < 1.5 * rsd:
                continue                                           # CSF not distinguishable from tissue in this render
            din = ndi.distance_transform_edt(m, sampling=sp)
            core = m & (din > 1.0) if (din > 1.0).sum() >= 2 else m
            o = out[bx].copy()
            o[core] = csf_level + 0.3 * rsd * rng.standard_normal(int(core.sum()))
            if rng.random() < k3.cavity_p_rim:
                rim = m & ~core if (m & ~core).any() else ((d > 0) & (d <= 1.0) & brain[bx] & ~les[bx])
                o[rim] = o[rim] + float(rng.uniform(1.0, 3.0)) * rsd * np.sign(rmed - csf_level + 1e-6)
            sig = float(rng.uniform(0.0, 0.8))
            if sig > 0.3:
                o = np.where(brain[bx], ndi.gaussian_filter(o, sig), o)
            out[bx] = np.where(m | ndi.binary_dilation(m), o, out[bx])
            nm[bx][m & (nm[bx] == CODE_LES_IGNORE)] = 0; ncav += 1
    info["cavity_n"] = ncav
    # (2a) faint perilesional band, LABEL 0 (outside every lesion; no decoy code)
    nb = 0
    if k3.band_p > 0 and les.any():
        sd = cc["sd"].astype(np.float32) / 4.0
        mod = None
        for j in np.unique(cid[les]):
            if j == 0 or rng.random() >= k3.band_p:
                continue
            r1 = float(rng.uniform(max(k3.band_r[0] + 1.0, 3.0), k3.band_r[1]))
            sh_ = (cid == j) & (sd > k3.band_r[0]) & (sd <= r1) & brain & ~les & (p < 0.5)
            if not sh_.any():
                continue
            if mod is None:
                mod = 0.3 + 0.7 * _smooth_noise(out.shape, rng, 6.0)
            taper = np.clip((r1 - sd[sh_]) / max(r1 - k3.band_r[0], 1e-3) * 1.5, 0, 1)
            out[sh_] += float(rng.uniform(*k3.band_amp)) * mod[sh_] * taper; nb += 1
    info["band_n"] = nb
    # (2b) faint background patches, LABEL 0, >= 6 mm from any lesion
    ng = 0
    lam = float(rng.uniform(*k3.bg_lambda)) if k3.bg_lambda[1] > 0 else 0.0
    if lam > 0:
        far = brain & (p < 0.5) & ~ndi.binary_dilation(les, iterations=6) if les.any() else brain & (p < 0.5)
        cand = np.flatnonzero(far)
        for _ in range(int(rng.poisson(lam))):
            if cand.size == 0:
                break
            c = np.array(np.unravel_index(int(cand[rng.integers(cand.size)]), out.shape))
            r = rng.uniform(*k3.bg_r, 3)
            pad = np.ceil(2 * r.max() / sp).astype(int) + 1
            lo = np.maximum(c - pad, 0); hi = np.minimum(c + pad + 1, out.shape)
            bx = tuple(slice(int(a), int(b)) for a, b in zip(lo, hi))
            g = np.meshgrid(*[(np.arange(a, b) - ci) * s for a, b, ci, s in zip(lo, hi, c, sp)], indexing="ij")
            q = sum((gi / ri) ** 2 for gi, ri in zip(g, r))
            f = np.exp(-q) * far[bx] * (0.5 + 0.5 * _smooth_noise(q.shape, rng, 3.0))
            out[bx] += float(rng.uniform(*k3.bg_amp)) * f; ng += 1
    info["bg_n"] = ng
    return info


Render3._post = _post_impl
Render3._cav_ids = []


def _r2b_knobs_from_env():
    """same parsing as cascade2_render2.make_renderer_b (C2_R2B_KNOBS), without building a second renderer."""
    kw = {}
    env = os.environ.get("C2_R2B_KNOBS", "").strip()
    for it in [x for x in env.split(",") if x]:
        a, b = it.split("=")
        cur = getattr(R2.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 R2.R2BKnobs(**kw)


def make_renderer3(device="cpu"):
    return Render3(_knobs_from_env(), _r2b_knobs_from_env(), device=device)


def make_online_hook3(return_negmap=True):
    """DA-worker hook (same contract as cascade2_render2.make_online_hook2b): f(t1, les, key, bbox, rng) -> (flair z, negmap).
    negmap: v1 decoy codes, 250 (labelled lesion invisible -> ignore), 251 (visible procedural lesion -> label 1)."""
    import torch
    import cascade2_render as R
    Rn = make_renderer3()
    store = R._CacheStore()
    PF = C.WS / "outputs/direction2/render3/pfossa"
    pf_cache = {}

    def pf_mask(pid, sh):
        if pid not in pf_cache:
            f = PF / f"{pid}.npz"
            m = None
            if f.exists():
                z = np.load(f); m = np.unpackbits(z["bits"])[:int(np.prod(sh))].reshape(sh).astype(bool)
            if len(pf_cache) > 64:
                pf_cache.pop(next(iter(pf_cache)))
            pf_cache[pid] = m
        return pf_cache[pid]

    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
        csl = tuple(slice(int(a), int(b)) for a, b in zip(vlo, vhi))
        cc, ax, _ = store.crop(pid, csl)
        if int(cc["brain"].sum()) < 100:
            return (out, nm) if return_negmap else out
        if len(Rn.k3.loc_p) > 6 and Rn.k3.loc_p[6] > 0:
            pm = pf_mask(pid, sh)
            cc["pf"] = pm[csl] if pm is not None else None
        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