# enclosure: fraction of 3D ray directions from the spot that hit material (CT > 100) within L L2 vx before
# leaving the CT mask (zero) or the 64-vx box; inter-layer gaps are enclosed, degraded/open space is not
import numpy as np, zarr, csv
ct = zarr.open('/media/djosey/nvme4/20251211183505-2.399um-0.2m-78keV-masked.zarr', mode='r')['2']
W = 64; n = 200; k = np.arange(n) + .5
ph = np.arccos(1 - 2 * k / n); th = np.pi * (1 + 5 ** .5) * k
dirs = np.stack([np.cos(ph), np.sin(ph) * np.sin(th), np.sin(ph) * np.cos(th)], 1)   # z, y, x
steps = np.arange(1, W)
with open('enclosure.tsv', 'w') as f:
    f.write('id\tenc16\tenc32\tenc64\n')
    for r in csv.DictReader(open('spots.tsv'), delimiter='\t'):
        x, y, z = (int(r[c]) // 4 for c in ('x_L0', 'y_L0', 'z_L0'))
        a = np.asarray(ct[z-W:z+W+1, y-W:y+W+1, x-W:x+W+1])
        p = np.rint(W + dirs[:, None, :] * steps[None, :, None]).astype(int)
        v = a[p[..., 0], p[..., 1], p[..., 2]]                       # (dirs, steps)
        hitm = v > 100; hitz = v == 0
        fm = np.where(hitm.any(1), hitm.argmax(1), 999); fz = np.where(hitz.any(1), hitz.argmax(1), 999)
        ok = fm < fz
        f.write(f"{r['id']}\t" + '\t'.join(f'{(ok & (fm < L)).mean():.2f}' for L in (16, 32, 64)) + '\n')
print('ok')
