Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions config/cubic_pixel_config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ volumes:
readout:
type: pixel
pixel_pitch: 0.432 # cm (= 4.32 mm → 432cm / 0.432 = 1000 pixels)
response_pixel_bin: 0.0432 # cm; response table scaled to this pitch (pitch / 10)
pixel_shape: [1000, 1000]

- id: 1
Expand All @@ -22,13 +23,14 @@ volumes:
readout:
type: pixel
pixel_pitch: 0.432 # cm
response_pixel_bin: 0.0432 # cm; response table scaled to this pitch (pitch / 10)
pixel_shape: [1000, 1000]

readout:
sampling_rate: 2.0 # MHz
electrons_per_adc: 182
pre_window_fraction: 0.0
post_window_fraction: 0.0
pre_window_fraction: 0.3 # fraction of max drift time before t=0
post_window_fraction: 0.3 # fraction of max drift time after max drift

simulation:
drift:
Expand Down
4 changes: 2 additions & 2 deletions config/production_cubic_pixel_doraemon_300micro.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ generated: '2026-06-02T01:18:21.660337'
total_pad: 450000
response_chunk: 1000
hits_chunk: 6250
max_keys: 11900000
maxg: 110000
max_keys: 24000000
maxg: 140000
maxg_medium: 50000
inter_thresh: 1.0
threshold_adc: 7.0
Expand Down
6 changes: 4 additions & 2 deletions profiler/estimate_max_keys.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,8 @@ def build_pixel_element_table(sim_config, vol_geom, num_s=32,
time_spacing=sim_config.time_step_us,
pixel_pitch_cm=vol_geom.pixel_pitch_cm,
max_sigma_trans_unitless=diff.max_sigma_trans_unitless,
max_sigma_long_unitless=diff.max_sigma_long_unitless)
max_sigma_long_unitless=diff.max_sigma_long_unitless,
pixel_bin_cm=vol_geom.pixel_response_bin_cm)

s_batch = jnp.linspace(0.0, 1.0, num_s)
zero = jnp.zeros(num_s, dtype=jnp.float32)
Expand Down Expand Up @@ -166,7 +167,8 @@ def build_pixel_value_table(sim_config, vol_geom, num_s=32,
pixel_kernel_path, num_s=num_s, time_spacing=sim_config.time_step_us,
pixel_pitch_cm=vol_geom.pixel_pitch_cm,
max_sigma_trans_unitless=diff.max_sigma_trans_unitless,
max_sigma_long_unitless=diff.max_sigma_long_unitless)
max_sigma_long_unitless=diff.max_sigma_long_unitless,
pixel_bin_cm=vol_geom.pixel_response_bin_cm)
s_batch = jnp.linspace(0.0, 1.0, num_s)
zero = jnp.zeros(num_s, dtype=jnp.float32)
output = apply_pixel_diffusion_response(
Expand Down
3 changes: 2 additions & 1 deletion profiler/find_optimal_maxg.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,8 @@ def find_optimal_maxg(data, config_path, group_size=5, gap=5.0, events_per_file=
pkp = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'config', 'pixel_response.npz')
pk = load_pixel_response_kernel(pkp, pixel_pitch_cm=sc.volumes[0].pixel_pitch_cm,
time_spacing=sc.time_step_us,
max_sigma_trans_unitless=1.0, max_sigma_long_unitless=1.0)
max_sigma_trans_unitless=1.0, max_sigma_long_unitless=1.0,
pixel_bin_cm=sc.volumes[0].pixel_response_bin_cm)
ker = (pk.kernel_py, pk.kernel_pz, pk.kernel_time)
else:
d = sc.volumes[0].diffusion
Expand Down
3 changes: 2 additions & 1 deletion tests/TESTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,8 @@ The modules above are documented test-by-test; the remaining suites are listed h
| test_pixel_post_response_truth.py | 16 | Pixel readout post-response truth (`tools/track_hits.py` pixel path) |
| test_pixel_kernel_grid.py | 2 | Pixel kernel lookup on the bin-centre grid: total charge over output pixels equals the pad-sum at every sub-pixel offset |
| test_pixel_kernel_timing.py | 7 | Pixel kernel sub-tick timing (`tools/kernels.py`): placed output equals the tick-averaged response at the true arrival time, centroid linearity, d/d(arrival) vs finite differences |
| test_pixel_response_bin.py | 4 | Pixel table applied at each preset's pitch (`response_pixel_bin`): full charge collected, bin = pitch / 10; cubic pixel and wire share the readout window |
| test_production_io.py | 14 | Production HDF5 writers/readers (`production/save.py`, `production/load.py`): CSR + delta encoding round-trips |
| test_box_track_hits.py | 2 | Box (group-as-bucket) track-hits path |
| test_box_track_hits.py | 4 | Box (group-as-bucket) track-hits path |
| test_qs_fractions.py | 5 | Per-deposit charge-share fractions (`qs_fractions`) |
| test_pixel_kernel_window.py | 3 | Pixel kernel output window is centred on the deposit pixel: mirror symmetry under u → −u |
14 changes: 14 additions & 0 deletions tests/test_box_track_hits.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,3 +118,17 @@ def test_maxg_overflow_raises(wire_config):
"""maxg below the group count raises (not silent clip); message classifiable."""
with pytest.raises(RuntimeError, match="maxg overflow"):
_run(wire_config, box_enabled=True, maxg=5)


@pytest.mark.parametrize("readout,dims", [
("pixel", dict(box_bpy=10, box_bpz=10, box_bt=95)),
("wire", dict(box_bw=16, box_btw=96))])
def test_box_index_limit(readout, dims):
"""A box beyond int32 indexing raises at construction, not silently wraps."""
from tools.track_hits import check_box_capacity
cells = int(np.prod(list(dims.values())))
ok = (2**31 - 1) // cells
check_box_capacity(create_track_hits_config(maxg=ok, box_enabled=True, **dims), readout)
with pytest.raises(ValueError, match="int32"):
check_box_capacity(
create_track_hits_config(maxg=ok + 1, box_enabled=True, **dims), readout)
49 changes: 49 additions & 0 deletions tests/test_pixel_response_bin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
"""Pixel response table applied at a pitch other than its own (response_pixel_bin)."""

import numpy as np
import jax.numpy as jnp
import pytest

from tools.config import create_sim_config
from tools.geometry import generate_detector
from tools.kernels import apply_pixel_diffusion_response, load_pixel_response_kernel

pytestmark = [pytest.mark.requires_kernels, pytest.mark.requires_config]

NPZ = "config/pixel_response.npz"
DT = 0.5


def _charge(config):
"""Charge collected over all pixels, at 16 sub-pixel offsets, unit deposits."""
vol = create_sim_config(generate_detector(config), total_pad=100).volumes[0]
k = load_pixel_response_kernel(
NPZ, num_s=4, time_spacing=DT, pixel_pitch_cm=vol.pixel_pitch_cm,
max_sigma_trans_unitless=0.2, max_sigma_long_unitless=0.5,
pixel_bin_cm=vol.pixel_response_bin_cm)
u = np.linspace(-0.45, 0.45, 16)
out = apply_pixel_diffusion_response(
k.DKernel, jnp.ones(16), jnp.array(u), jnp.array(u[::-1]),
jnp.full(16, 0.3), k.pixel_spacing, k.kernel_py, k.kernel_pz, k.rebin_factor)
return vol, np.asarray(out.sum(axis=(1, 2, 3)) * DT)


@pytest.mark.parametrize("config", ["config/cubic_pixel_config.yaml",
"config/dune_ndlar_config.yaml"])
def test_all_charge_is_collected(config):
_, q = _charge(config)
np.testing.assert_allclose(q, 1.0, atol=2e-3)


def test_table_bin_matches_pitch():
for config in ("config/cubic_pixel_config.yaml", "config/dune_ndlar_config.yaml"):
vol, _ = _charge(config)
bin_cm = vol.pixel_response_bin_cm or float(np.load(NPZ)["pixel_bin_size"])
assert vol.pixel_pitch_cm / bin_cm == pytest.approx(10.0)


def test_cubic_pixel_and_wire_share_the_readout_window():
pix, wire = (create_sim_config(generate_detector(f"config/{c}_config.yaml"), total_pad=100)
for c in ("cubic_pixel", "cubic_wireplane"))
for f in ("num_time_steps", "time_step_us", "pre_window_us", "post_window_us"):
assert getattr(pix, f) == getattr(wire, f), f
4 changes: 4 additions & 0 deletions tools/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,8 @@ def create_sim_config(detector_config, total_pad=200_000, response_chunk_size=50
if readout_type == 'pixel':
# Pixel volume — no wire planes
pixel_pitch = float(readout_cfg['pixel_pitch'])
response_bin = readout_cfg.get('response_pixel_bin')
response_bin = None if response_bin is None else float(response_bin)
pixel_shape_cfg = readout_cfg['pixel_shape']
num_py, num_pz = int(pixel_shape_cfg[0]), int(pixel_shape_cfg[1])
# Pixel grid origin in the volume-LOCAL frame. Deposits are
Expand Down Expand Up @@ -388,6 +390,7 @@ def create_sim_config(detector_config, total_pad=200_000, response_chunk_size=50
pixel_shape=(num_py, num_pz),
pixel_pitch_cm=pixel_pitch,
pixel_origins_cm=(y_origin, z_origin),
pixel_response_bin_cm=response_bin,
))
else:
# Wire volume
Expand Down Expand Up @@ -604,6 +607,7 @@ class VolumeGeometry(NamedTuple):
pixel_shape: Any # (num_py, num_pz) or None
pixel_pitch_cm: Any # float or None
pixel_origins_cm: Any # (y_origin_cm, z_origin_cm) or None
pixel_response_bin_cm: Any = None # response-table bin size (cm); None = use the NPZ's


class VolumeIntermediates(NamedTuple):
Expand Down
10 changes: 8 additions & 2 deletions tools/kernels.py
Original file line number Diff line number Diff line change
Expand Up @@ -754,7 +754,8 @@ def apply_pixel_diffusion_response(DKernel, s_values, py_offsets, pz_offsets,
def load_pixel_response_kernel(npz_path, num_s=32, time_spacing=0.5,
pixel_pitch_cm=0.4,
max_sigma_trans_unitless=None,
max_sigma_long_unitless=None):
max_sigma_long_unitless=None,
pixel_bin_cm=None):
"""Load pixel response kernel from NPZ and build 3D DKernel table.

The DKernel table is kept at native NPZ resolution (fine spatial and time
Expand Down Expand Up @@ -784,6 +785,11 @@ def load_pixel_response_kernel(npz_path, num_s=32, time_spacing=0.5,
Max transverse sigma in pixel pitch units.
max_sigma_long_unitless : float, optional
Max longitudinal sigma in simulation time step units.
pixel_bin_cm : float, optional
Table bin size in cm, overriding the NPZ's ``pixel_bin_size``. Used to
apply a table computed for one pitch to another (bin = pitch / 10 for
the shipped table). Scales the transverse axes only; the time axis is
unchanged. None uses the NPZ's value.

Returns
-------
Expand All @@ -793,7 +799,7 @@ def load_pixel_response_kernel(npz_path, num_s=32, time_spacing=0.5,

data = np.load(npz_path)
response = jnp.array(data['response'], dtype=jnp.float32) # (Hpy, Hpz, Ht)
npz_pixel_bin = float(data['pixel_bin_size'])
npz_pixel_bin = float(data['pixel_bin_size'] if pixel_bin_cm is None else pixel_bin_cm)
npz_time_bin = float(data['time_bin_size'])

# pixel_spacing: NPZ bin / pixel pitch (unitless ratio, like wire_spacing)
Expand Down
4 changes: 3 additions & 1 deletion tools/simulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,7 @@ def __init__(
pixel_pitch_cm=vol_geom.pixel_pitch_cm,
max_sigma_trans_unitless=d.max_sigma_trans_unitless,
max_sigma_long_unitless=d.max_sigma_long_unitless,
pixel_bin_cm=vol_geom.pixel_response_bin_cm,
)
else:
_, _, global_sigma_trans, global_sigma_long = calculate_max_diffusion_sigmas(
Expand All @@ -266,7 +267,7 @@ def __init__(
# pixel kernel window) and freeze them into cfg.track_hits. Explicit
# dims passed by the caller (tests / SCE margin) are left untouched.
if include_track_hits and cfg.track_hits is not None and cfg.track_hits.box_enabled:
from tools.track_hits import compute_box_dims
from tools.track_hits import check_box_capacity, compute_box_dims
tc = cfg.track_hits
box_kw = compute_box_dims(
cfg.volumes, cfg.time_step_us, self._readout_type,
Expand All @@ -278,6 +279,7 @@ def __init__(
cfg = cfg._replace(track_hits=tc._replace(**updates))
self._sim_config = cfg
print(f" Box dims (analytic): {updates}")
check_box_capacity(cfg.track_hits, self._readout_type)

# Build shared factories
sce_factory, _build_response_fn, _build_response_fn_diff, _recomb_fn = \
Expand Down
18 changes: 18 additions & 0 deletions tools/track_hits.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,24 @@ def compute_box_dims(volumes, time_step_us, readout_type, group_size,
return {'box_bw': int(bw), 'box_btw': int(bt)}


def check_box_capacity(track_hits, readout_type):
"""Raise if the group box has more cells than an int32 index can address.

The box is flattened to ``maxg * cells`` and scanned with int32 indices
(JAX default); beyond 2**31 - 1 they wrap and hits are silently wrong.
"""
tc = track_hits
dims = ((tc.box_bpy, tc.box_bpz, tc.box_bt) if readout_type == 'pixel'
else (tc.box_bw, tc.box_btw))
cells = math.prod(dims)
limit = 2**31 - 1
if tc.maxg * cells > limit:
raise ValueError(
f"track-hits box too large: maxg={tc.maxg:,} x {cells:,} cells/group "
f"{dims} exceeds the int32 index limit. maxg can be at most "
f"{limit // cells:,} with these box dims.")


from tools.wires import (
compute_angular_scaling_vmap,
compute_deposit_wire_angles_vmap,
Expand Down
Loading