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
15 changes: 11 additions & 4 deletions tests/TESTS.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# JAXTPC Test Suite

264 tests covering software correctness and physics validation across all simulation modules. All tests run on CPU with synthetic data. The per-module tables below highlight representative checks; the test counts in each heading are the authoritative totals.
Tests covering software correctness and physics validation across all simulation modules. All tests run on CPU with synthetic data; none needs a file outside the repo. The per-module tables below highlight representative checks; the test counts in each heading are the authoritative totals.

## Running Tests

Expand Down Expand Up @@ -138,6 +138,13 @@ Integration tests and physics validation (`tools/simulation.py`). Tests marked `
| Y-plane signal polarity | Collection plane has net positive signal |
| Diffusion broadens with distance | Longer drift gives wider signal spread |

### Pipeline fixtures

`tests/conftest.py` provides `compact_detector` (cubic_wireplane with the full 216 cm drift but
a 60 x 60 cm readout, optional per-plane pitch), `synthetic_tracks` (80 deterministic deposits,
three tracks, both volumes) and `count_compiles`. `tests/gradient_checks.py` holds the
AD-vs-finite-difference helpers.

### Additional modules

The modules above are documented test-by-test; the remaining suites are listed here with their totals and focus. Run `pytest <file> -v` for the per-test breakdown.
Expand All @@ -148,9 +155,9 @@ The modules above are documented test-by-test; the remaining suites are listed h
| test_efield_distortions.py | 40 | Space charge effects (`tools/efield_distortions.py`): SCE maps, trilinear interpolation, E-field + spatial displacement |
| test_electronics.py | 21 | RC⊗RC electronics shaping (`tools/electronics.py`) and ADC digitization |
| test_output.py | 8 | Output format conversion (`tools/output.py`): dense ↔ sparse ↔ bucketed, threshold application |
| test_pipeline.py | 17 | End-to-end production-path integration (`process_event`) |
| test_pipeline_forward.py | 15 | Differentiable-path forward + finite-difference gradient checks (`forward`/`forward_segments`) |
| test_pipeline_forward_slow.py | 12 | Kernel-dependent differentiable-path integration (marked `slow`) |
| test_pipeline.py | 20 | Production path (`process_event`) on a compact detector: output layout, track-hit charge per track = attenuated charge, `qs_fractions`, velocity response, default SimParams, compile-cache counts, mirror symmetry of the volumes, dense == bucketed; plus hand-placed deposits on the full detector |
| test_pipeline_forward.py | 22 (4 xfail) | Differentiable path: relative L2 against production per plane at uniform pitch, and at mixed pitch (V, Y strict xfail: production uses plane 0's pitch for every plane's transverse diffusion); `forward_segments` == `forward`; XLA compile counts; every EMB SimParams gradient vs float64 finite differences |
| test_pipeline_forward_slow.py | 4 | EMB / Modified Box signal ratio = survival ratio, Modified Box gradients, gradients through deposit positions (marked `slow`) |
| test_pixel_post_response_truth.py | 16 | Pixel readout post-response truth (`tools/track_hits.py` pixel path) |
| 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 |
Expand Down
84 changes: 84 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,3 +199,87 @@ def small_deposit_data():
positions_mm, de, dx, sim_config,
theta=theta, phi=phi, track_ids=track_ids,
)


# ---------------------------------------------------------------------------
# Compact wire detector + synthetic tracks (pipeline tests)
# ---------------------------------------------------------------------------

_CONFIG = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
'config', 'cubic_wireplane_config.yaml')


@pytest.fixture(scope="session")
def compact_detector():
"""Factory: cubic_wireplane with the full 216 cm drift but a 60 x 60 cm readout.

``pitches`` overrides the U, V, Y wire spacing (cm). The drift length is kept so
that diffusion and attenuation are as large as in the real detector.
"""
from tools.geometry import generate_detector

def make(pitches=(0.3, 0.3, 0.3)):
det = generate_detector(_CONFIG)
for vol in det['volumes']:
ranges = vol['geometry']['ranges']
ranges[1], ranges[2] = [-30.0, 30.0], [-30.0, 30.0]
for plane, pitch in zip(vol['planes'], pitches):
plane['wire_spacing'] = pitch
return det
return make


@pytest.fixture(scope="session")
def synthetic_tracks():
"""Factory: deterministic deposits of three tracks, each with charge in both volumes.

Tracks 1 and 2 span 5-210 cm of |x| with one deposit per group; track 3 is two short
stubs with deposits 3 mm apart, i.e. groups of five. dE is non-uniform, angles are
the true ones. Leaves padding entries in every volume for total_pad >= 64.
Coordinates are irregular on purpose: a deposit arriving exactly on a tick edge sits
on a kink of the sub-tick interpolation, where finite differences are one-sided.
"""
from tools.loader import build_deposit_data

def make(sim_config):
ends = [((-2103.3, -201.3, -151.9), (2097.1, 148.3, 221.7)),
((-51.3, 152.1, -218.9), (-2047.9, -251.7, 101.3)),
((2001.9, -218.3, 181.7), (83.3, 191.9, -58.7)),
((-903.1, 40.3, 60.7), (-890.2, 62.9, 69.4)),
((1203.3, -70.9, -30.1), (1219.7, -52.8, -18.3))]
counts = [40, 20, 20, 10, 10]
tracks = [1, 2, 2, 3, 3]
pos, theta, phi, tid = [], [], [], []
for (a, b), n, t in zip(ends, counts, tracks):
a, b = np.array(a), np.array(b)
d = (b - a) / np.linalg.norm(b - a)
pos.append(a + np.linspace(0, 1, n)[:, None] * (b - a))
theta.append(np.full(n, np.arccos(d[2])))
phi.append(np.full(n, np.arctan2(d[1], d[0])))
tid.append(np.full(n, t, dtype=np.int32))
n = sum(counts)
return build_deposit_data(
np.concatenate(pos).astype(np.float32),
np.linspace(0.5, 1.5, n, dtype=np.float32),
np.full(n, 3.0, dtype=np.float32), sim_config,
theta=np.concatenate(theta).astype(np.float32),
phi=np.concatenate(phi).astype(np.float32),
track_ids=np.concatenate(tid))
return make


@pytest.fixture
def count_compiles():
"""Factory: number of XLA compilations triggered while running ``fn``."""
def count(fn):
events = []

def listen(event, duration, **kwargs):
if event.endswith('backend_compile_duration'):
events.append(event)
jax.monitoring.register_event_duration_secs_listener(listen)
fn()
# Listeners cannot be removed through the public API in every supported
# JAX; copy the count so later events are ignored.
return len(events)
return count
45 changes: 45 additions & 0 deletions tests/gradient_checks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
"""AD-vs-finite-difference checks of SimParams gradients (not a test module)."""

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


def param_gradients(sim, deposits):
# Grouping ids stay integer; only the physics columns are promoted
to64 = lambda a: (a.astype(jnp.float64)
if hasattr(a, 'dtype') and jnp.issubdtype(a.dtype, jnp.floating)
else a)
deposits = deposits._replace(volumes=jax.tree.map(to64, deposits.volumes))
params = jax.tree.map(to64, sim.default_sim_params)

@jax.jit
def loss(p):
return sum(jnp.sum(s ** 2) for s in sim.forward(p, deposits))
return loss, jax.jit(jax.grad(loss))(params), params, float(loss(params))


def check_param_gradient(result, field, eps=1e-8, tol=1e-3, min_sensitivity=1e-4):
"""AD == central FD for one (possibly nested) SimParams field.

The logarithmic sensitivity p/L dL/dp must exceed ``min_sensitivity``, so a
parameter that has dropped out of the model (both gradients zero) fails. ``eps`` is
relative and small so that no arrival time crosses a tick edge within the step.
"""
loss, grads, params, value = result
if field.startswith('recomb_params.'):
name = field.split('.')[1]
get = lambda t: getattr(t.recomb_params, name)
put = lambda v: params._replace(
recomb_params=params.recomb_params._replace(**{name: v}))
else:
get = lambda t: getattr(t, field)
put = lambda v: params._replace(**{field: v})
p0 = get(params)
ad = float(get(grads))
fd = float(loss(put(p0 * (1 + eps))) - loss(put(p0 * (1 - eps)))) / float(2 * eps * p0)
sens = float(p0) * fd / value
msg = f"{field}: AD={ad:.6e} FD={fd:.6e} dlnL/dlnp={sens:.3e}"
assert np.isfinite(ad), msg
assert abs(sens) > min_sensitivity, msg
assert abs(ad - fd) < tol * abs(fd), msg
2 changes: 1 addition & 1 deletion tests/test_deposit_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def raw_data():
Each track is a contiguous run of deposits spanning x = -180 -> +180 cm, so
every track crosses the x=0 volume boundary: this populates BOTH volumes and
keeps per-track deposits contiguous (needed for group-id computation). Mirrors
what load_particle_step_data('out.h5') used to provide.
the layout returned by load_particle_step_data.
"""
rng = np.random.RandomState(1234)
n_tracks = 8
Expand Down
Loading
Loading