diff --git a/tests/TESTS.md b/tests/TESTS.md index 834cabe..fe09a84 100644 --- a/tests/TESTS.md +++ b/tests/TESTS.md @@ -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 @@ -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 -v` for the per-test breakdown. @@ -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 | diff --git a/tests/conftest.py b/tests/conftest.py index dcfb185..91bdb2e 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -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 diff --git a/tests/gradient_checks.py b/tests/gradient_checks.py new file mode 100644 index 0000000..179917d --- /dev/null +++ b/tests/gradient_checks.py @@ -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 diff --git a/tests/test_deposit_data.py b/tests/test_deposit_data.py index 5e5adf4..0fdd29a 100644 --- a/tests/test_deposit_data.py +++ b/tests/test_deposit_data.py @@ -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 diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py index 07649d8..657e799 100644 --- a/tests/test_pipeline.py +++ b/tests/test_pipeline.py @@ -1,33 +1,29 @@ """ -Production pipeline integration tests. +Production pipeline integration tests (synthetic deposits). -One simulator (dense + track_hits) shared across all tests via module scope. -Plus one bucketed simulator for dense==bucketed comparison. +One dense + track-hits simulator on a compact detector is shared by the module, +plus one bucketed simulator for the dense == bucketed comparison. -Tests: signal shapes, track hits, qs_fractions, warm_up, -custom sim_params, edge cases, bucketed equivalence, -synthetic deterministic pipeline. +Tests: output layout, track-hit charge and labels, qs_fractions, SimParams response, +recompilation, warm_up, volume mirror symmetry, bucketed equivalence, +hand-placed deposits on the full-size detector. """ import os -import time import numpy as np -import jax import jax.numpy as jnp import pytest +from tools.config import create_track_hits_config from tools.geometry import generate_detector from tools.simulation import DetectorSimulator -from tools.loader import load_event, build_deposit_data -from tools.wires import sparse_buckets_to_dense +from tools.loader import build_deposit_data +from tools.output import to_dense CONFIG_PATH = 'config/cubic_wireplane_config.yaml' -DATA_PATH = 'out.h5' -EVENT_IDX = 2 - -needs_data = pytest.mark.skipif( - not os.path.exists(DATA_PATH), reason="out.h5 not found") +PAD = 64 +PLANES = [(v, p) for v in range(2) for p in range(3)] # --------------------------------------------------------------------------- @@ -35,22 +31,18 @@ # --------------------------------------------------------------------------- @pytest.fixture(scope="module") -def detector_config(): - return generate_detector(CONFIG_PATH) - - -@pytest.fixture(scope="module") -def sim(detector_config): +def sim(compact_detector): """Dense + track_hits simulator. Shared across all tests.""" return DetectorSimulator( - detector_config, total_pad=200_000, response_chunk_size=50_000, - use_bucketed=False, include_intrinsic_noise=False, include_electronics=False, - include_track_hits=True, include_digitize=False) + compact_detector(), total_pad=PAD, response_chunk_size=PAD // 2, + include_track_hits=True, + track_config=create_track_hits_config( + max_keys=50_000, hits_chunk_size=PAD // 2, maxg=64, inter_thresh=0.01)) @pytest.fixture(scope="module") -def deposits(sim): - return load_event(DATA_PATH, sim.config, event_idx=EVENT_IDX) +def deposits(sim, synthetic_tracks): + return synthetic_tracks(sim.config) @pytest.fixture(scope="module") @@ -60,160 +52,170 @@ def sim_results(sim, deposits): # --------------------------------------------------------------------------- -# Signal shapes +# Output layout # --------------------------------------------------------------------------- -@needs_data -class TestSignalShapes: +class TestOutputLayout: - def test_signal_shapes(self, sim, sim_results): - signals, _, _ = sim_results + def test_planes_and_shapes(self, sim, sim_results): + """Exactly one (num_wires, num_time) signal and one hit tuple per plane.""" + signals, hits, _ = sim_results cfg = sim.config - for vi in range(cfg.n_volumes): - for pi in range(cfg.volumes[vi].n_planes): - assert signals[(vi, pi)].shape == ( - cfg.volumes[vi].num_wires[pi], cfg.num_time_steps) - - def test_all_planes_present(self, sim, sim_results): - signals, _, _ = sim_results - cfg = sim.config - for vi in range(cfg.n_volumes): - for pi in range(cfg.volumes[vi].n_planes): - assert (vi, pi) in signals + assert cfg.volumes[0].num_wires[0] != cfg.volumes[0].num_wires[2] + assert set(signals) == set(PLANES) + assert set(hits) == set(PLANES) | {'group_to_track'} + for v, p in PLANES: + assert signals[(v, p)].shape == ( + cfg.volumes[v].num_wires[p], cfg.num_time_steps) # --------------------------------------------------------------------------- # Track hits # --------------------------------------------------------------------------- -@needs_data class TestTrackHits: - def test_track_hits_keys(self, sim, sim_results): - _, track_hits_raw, _ = sim_results - cfg = sim.config - for vi in range(cfg.n_volumes): - for pi in range(cfg.volumes[vi].n_planes): - assert (vi, pi) in track_hits_raw + @pytest.mark.parametrize("vol,plane", PLANES) + def test_charge_per_track(self, sim, sim_results, vol, plane): + """Hits of each track on each plane sum to its attenuated charge.""" + _, hits, filled = sim_results + sk, tk, gk, ch, count, _ = hits[(vol, plane)] + count = int(count) + assert 0 < count < sim.config.track_hits.max_keys + hit_tracks = np.asarray(hits['group_to_track'][vol])[np.asarray(gk[:count])] + ch = np.asarray(ch[:count], dtype=np.float64) + + d = filled.volumes[vol] + n = int(d.n_actual) + geom, params = sim.config.volumes[vol], sim.default_sim_params + dist = np.asarray(d.positions_mm[:n, 0]) / 10 - geom.plane_distances_cm[plane] + arriving = np.asarray(d.charge[:n], np.float64) * np.exp( + -dist / float(params.velocity_cm_us) / float(params.lifetime_us)) + tracks = np.asarray(d.track_ids[:n]) + assert set(hit_tracks) == set(tracks) == {1, 2, 3} + for t in (1, 2, 3): + assert ch[hit_tracks == t].sum() == pytest.approx( + arriving[tracks == t].sum(), rel=1e-2) def test_qs_fractions(self, sim, sim_results): - _, _, filled_deposits = sim_results - for v in range(sim.config.n_volumes): - vol = filled_deposits.volumes[v] - qs = vol.qs_fractions[:vol.n_actual] - assert float(jnp.sum(jnp.abs(qs))) > 0, f"Volume {v}: qs_fractions should be non-zero" + """qs_fractions is each deposit's share of its group's charge, 0 on padding.""" + _, _, filled = sim_results + for d in filled.volumes: + n = int(d.n_actual) + assert 0 < n < PAD + q, g = np.asarray(d.charge[:n]), np.asarray(d.group_ids[:n]) + assert np.all(q > 0) + total = np.bincount(g, weights=q) + assert np.sum(np.bincount(g) > 1) >= 2 # several multi-deposit groups + np.testing.assert_allclose(np.asarray(d.qs_fractions[:n]), q / total[g], + rtol=1e-5) + assert np.all(np.asarray(d.qs_fractions[n:]) == 0) # --------------------------------------------------------------------------- # SimParams # --------------------------------------------------------------------------- -@needs_data class TestSimParams: - def test_different_velocity_changes_output(self, sim, deposits, sim_results): - signals_default, _, _ = sim_results - s1 = float(signals_default[(1, 2)].sum()) - - params2 = sim.default_sim_params._replace(velocity_cm_us=jnp.array(0.17)) - sigs2, _, _ = sim.process_event(deposits, sim_params=params2) - s2 = float(sigs2[(1, 2)].sum()) - assert abs(s1 - s2) > 1.0 - - def test_no_recompile(self, sim, deposits): - """Second call with same params should be ~same speed as first (no recompile).""" - params2 = sim.default_sim_params._replace(velocity_cm_us=jnp.array(0.17)) - # First timed call - t0 = time.time() - sigs1, _, _ = sim.process_event(deposits, sim_params=params2) - jax.block_until_ready(sigs1[(1, 2)]) - t_first = time.time() - t0 - - # Second timed call — should be similar speed (no recompile) - t0 = time.time() - sigs2, _, _ = sim.process_event(deposits, sim_params=params2) - jax.block_until_ready(sigs2[(1, 2)]) - t_second = time.time() - t0 - - # Second call should not be dramatically slower (recompile would 10x+ it) - assert t_second < t_first * 2.0, \ - f"Second call ({t_second:.1f}s) much slower than first ({t_first:.1f}s)" - - def test_default_params_accessible(self, sim): + def test_velocity_shifts_arrival_time(self, sim): + """A slower drift delays the Y pulse by d(1/v2 - 1/v1) and attenuates it.""" + params = sim.default_sim_params + x_mm, v2 = -500.0, 0.17 + deps = build_deposit_data( + np.array([[x_mm, 0.0, 0.0]], np.float32), np.array([2.0], np.float32), + np.array([3.0], np.float32), sim.config) + pulse = [] + for p in (params, params._replace(velocity_cm_us=jnp.array(v2))): + y = np.asarray(sim.process_event(deps, sim_params=p)[0][(0, 2)], np.float64) + t = np.arange(y.shape[1]) + pulse.append((y.sum(), (y.sum(0) * t).sum() / y.sum())) + (q1, t1), (q2, t2) = pulse + dt_us = (216.0 + x_mm / 10) * (1 / v2 - 1 / float(params.velocity_cm_us)) + assert (t2 - t1) * sim.config.time_step_us == pytest.approx(dt_us, abs=0.05) + assert q2 / q1 == pytest.approx( + np.exp(-dt_us / float(params.lifetime_us)), rel=1e-4) + + def test_defaults_match_config(self, sim): + """Default SimParams are the YAML values in cm, us units.""" p = sim.default_sim_params - assert p.velocity_cm_us is not None - assert p.recomb_params is not None + got = [p.velocity_cm_us, p.lifetime_us, p.diffusion_trans_cm2_us, + p.diffusion_long_cm2_us, p.recomb_params.alpha, + p.recomb_params.beta_90, p.recomb_params.R] + np.testing.assert_allclose( + np.array(got, np.float64), + [0.16, 1.0e4, 12.0e-6, 7.2e-6, 0.904, 0.204, 1.25], rtol=1e-6) # --------------------------------------------------------------------------- -# Warm-up +# Compilation # --------------------------------------------------------------------------- -@needs_data -class TestWarmUp: - def test_completes(self, sim): - sim.warm_up() +class TestCompilation: + + def test_params_change_without_recompile(self, sim, deposits, sim_results): + n = sim._calculator_jit._cache_size() + assert n == 1 + p = sim.default_sim_params._replace(velocity_cm_us=jnp.array(0.17), + lifetime_us=jnp.array(5000.0)) + sim.process_event(deposits, sim_params=p) + assert sim._calculator_jit._cache_size() == n + + def test_warm_up_covers_process_event(self, compact_detector, synthetic_tracks): + """After warm_up() the first real event triggers no compilation.""" + fresh = DetectorSimulator( + compact_detector(), total_pad=PAD, response_chunk_size=PAD, + include_track_hits=False) + assert fresh._calculator_jit._cache_size() == 0 + fresh.warm_up() + assert fresh._calculator_jit._cache_size() == 1 + fresh.process_event(synthetic_tracks(fresh.config)) + assert fresh._calculator_jit._cache_size() == 1 # --------------------------------------------------------------------------- -# Edge cases +# Volumes # --------------------------------------------------------------------------- -@needs_data -class TestEdgeCases: - - def test_single_volume_deposits(self, sim): - pos = np.ones((100, 3), dtype=np.float32) * 500 - deps = build_deposit_data(pos, np.ones(100, dtype=np.float32) * 2.0, - np.ones(100, dtype=np.float32) * 0.5, - sim.config) - sigs, _, _ = sim.process_event(deps) +class TestVolumes: + + def test_mirrored_deposits(self, sim): + """x -> -x moves the signal to the other volume unchanged, the rest is zero.""" + rng = np.random.RandomState(5) + pos = rng.uniform([200, -250, -250], [2000, 250, 250], (60, 3)).astype(np.float32) + out = {} + for sign in (-1, 1): + p = pos * np.array([sign, 1, 1], np.float32) + deps = build_deposit_data(p, np.full(60, 2.0, np.float32), + np.full(60, 3.0, np.float32), sim.config) + out[sign], _, _ = sim.process_event(deps) for p in range(3): - assert float(jnp.abs(sigs[(0, p)]).sum()) < 1e-3 - assert float(jnp.abs(sigs[(1, p)]).sum()) > 0 - - def test_zero_energy_zero_signal(self, sim): - pos = np.ones((50, 3), dtype=np.float32) * -500 - deps = build_deposit_data(pos, np.zeros(50, dtype=np.float32), - np.ones(50, dtype=np.float32) * 0.5, sim.config) - sigs, _, _ = sim.process_event(deps) - total = sum(float(jnp.abs(v).sum()) for v in sigs.values()) - assert total < 1e-3 + east, west = np.asarray(out[-1][(0, p)]), np.asarray(out[1][(1, p)]) + assert np.abs(east).max() > 1.0 + # x_local = +-(x_anode - x) rounds identically for both signs + np.testing.assert_array_equal(east, west) + assert not np.any(np.asarray(out[-1][(1, p)])) + assert not np.any(np.asarray(out[1][(0, p)])) # --------------------------------------------------------------------------- # Bucketed equivalence (2nd JIT compile) # --------------------------------------------------------------------------- -@needs_data class TestBucketed: - @pytest.fixture(scope="class") - def sim_bucketed(self, detector_config): - return DetectorSimulator( - detector_config, total_pad=200_000, response_chunk_size=50_000, - use_bucketed=True, max_active_buckets=1000, - include_intrinsic_noise=False, include_electronics=False, - include_track_hits=False, include_digitize=False) - - def test_dense_equals_bucketed(self, sim, sim_bucketed, sim_results): + def test_dense_equals_bucketed(self, compact_detector, deposits, sim_results): signals_dense, _, _ = sim_results - - deps_b = load_event(DATA_PATH, sim_bucketed.config, event_idx=EVENT_IDX) - sig_bucketed, _, _ = sim_bucketed.process_event(deps_b) - - cfg = sim.config - for vi in range(cfg.n_volumes): - for pi in range(cfg.volumes[vi].n_planes): - d = np.asarray(signals_dense[(vi, pi)]) - b_tuple = sig_bucketed[(vi, pi)] - buckets, num_active, ctk, B1, B2 = b_tuple - nw = cfg.volumes[vi].num_wires[pi] - nt = cfg.num_time_steps - b = np.asarray(sparse_buckets_to_dense( - buckets, ctk, num_active, int(B1), int(B2), nw, nt, 1000)) - max_diff = float(np.max(np.abs(d - b))) - assert max_diff < 0.01, f"({vi},{pi}): {max_diff:.4f}" + sim_b = DetectorSimulator( + compact_detector(), total_pad=PAD, response_chunk_size=PAD // 2, + use_bucketed=True, max_active_buckets=1000, include_track_hits=False) + signals_b, _, _ = sim_b.process_event(deposits) + dense_b = to_dense(signals_b, sim_b.config) + for key in PLANES: + d, b = np.asarray(signals_dense[key]), np.asarray(dense_b[key]) + peak = np.abs(d).max() + assert peak > 1.0 + assert np.abs(d - b).max() < 1e-5 * peak, key # --------------------------------------------------------------------------- @@ -230,7 +232,7 @@ def test_dense_equals_bucketed(self, sim, sim_bucketed, sim_results): @pytest.mark.requires_kernels @pytest.mark.skipif(not has_kernels, reason="Response kernel files not found") class TestSyntheticPipeline: - """Full pipeline test with hand-placed deposits — no out.h5 needed. + """Full pipeline test with hand-placed deposits. Five deposits placed at known positions in volume 0 (east). Validates physics invariants rather than comparing to frozen snapshots. diff --git a/tests/test_pipeline_forward.py b/tests/test_pipeline_forward.py index 3e6d05e..90d5b6a 100644 --- a/tests/test_pipeline_forward.py +++ b/tests/test_pipeline_forward.py @@ -1,348 +1,159 @@ """ -Differentiable forward path integration tests. +Differentiable forward path integration tests (synthetic deposits). -One diff simulator shared across all tests via module scope. - -Tests: signals, baseline match, gradients, no-recompile, -edge cases, forward vs production consistency. +- forward() reproduces the production response on every plane, at uniform and at + mixed wire pitch +- every SimParams gradient matches a finite difference +- forward() does not recompile when SimParams change """ -import os -import time import numpy as np import jax import jax.numpy as jnp import pytest -from tools.geometry import generate_detector +from gradient_checks import check_param_gradient, param_gradients +from tools.loader import build_deposit_data from tools.simulation import DetectorSimulator -from tools.loader import load_particle_step_data, build_deposit_data -from tools.config import pad_deposit_data - -CONFIG_PATH = 'config/cubic_wireplane_config.yaml' -DATA_PATH = 'out.h5' -N = 1000 -needs_data = pytest.mark.skipif( - not os.path.exists(DATA_PATH), reason="out.h5 not found") +N = 64 +PLANES = [(v, p) for v in range(2) for p in range(3)] # --------------------------------------------------------------------------- -# Module-scoped fixtures (1 JIT compile) +# Forward vs production consistency # --------------------------------------------------------------------------- -@pytest.fixture(scope="module") -def detector_config(): - return generate_detector(CONFIG_PATH) - - -@pytest.fixture(scope="module") -def sim(detector_config): - return DetectorSimulator(detector_config, differentiable=True, n_segments=N) - - -@pytest.fixture(scope="module") -def raw(): - return load_particle_step_data(DATA_PATH, event_idx=2) +def _run_both(detector, synthetic_tracks): + prod = DetectorSimulator( + detector, total_pad=N, response_chunk_size=N // 2, + include_track_hits=False) + diff = DetectorSimulator(detector, differentiable=True, n_segments=N) + deposits = synthetic_tracks(prod.config) + sig_prod, _, _ = prod.process_event(deposits) + sig_diff = diff.forward(diff.default_sim_params, deposits) + return diff, deposits, sig_prod, sig_diff -@pytest.fixture(scope="module") -def deposits(raw, sim): - return build_deposit_data( - raw['positions_mm'][:N], raw['de'][:N], raw['dx'][:N], sim.config, - theta=raw['theta'][:N], phi=raw['phi'][:N]) +def _rel_l2(prod, diff): + """||prod - diff|| / ||prod||: independent of the number of deposits or ticks.""" + return float(np.linalg.norm(prod - diff) / np.linalg.norm(prod)) @pytest.fixture(scope="module") -def signals(sim, deposits): - """Run forward once, reuse across tests.""" - return sim.forward(sim.default_sim_params, deposits) +def uniform(compact_detector, synthetic_tracks): + return _run_both(compact_detector(), synthetic_tracks) @pytest.fixture(scope="module") -def grads(sim, deposits): - """Compute gradients once, reuse across tests.""" - def loss(params): - sigs = sim.forward(params, deposits) - return sum(jnp.sum(s ** 2) for s in sigs) - return jax.grad(loss)(sim.default_sim_params) - - -# --------------------------------------------------------------------------- -# Basic forward -# --------------------------------------------------------------------------- - -@needs_data -class TestForwardBasic: - - def test_six_signals(self, signals): - assert len(signals) == 6 - - def test_shapes(self, sim, signals): - cfg = sim.config - expected = [(cfg.volumes[v].num_wires[p], cfg.num_time_steps) - for v in range(cfg.n_volumes) - for p in range(cfg.volumes[v].n_planes)] - for i, sig in enumerate(signals): - assert sig.shape == expected[i] - - def test_nonzero_signal(self, signals): - total = sum(float(jnp.sum(jnp.abs(s))) for s in signals) - assert total > 0 - - -# --------------------------------------------------------------------------- -# Gradients -# --------------------------------------------------------------------------- - -@needs_data -class TestGradients: +def mixed(compact_detector, synthetic_tracks): + """ICARUS-like pitches: plane 0 at half the pitch of the other two.""" + return _run_both(compact_detector((0.15, 0.3, 0.3)), synthetic_tracks) - def test_velocity_nonzero(self, grads): - assert float(grads.velocity_cm_us) != 0.0 - def test_lifetime_nonzero(self, grads): - assert float(grads.lifetime_us) != 0.0 - - def test_recomb_alpha_nonzero(self, grads): - assert float(grads.recomb_params.alpha) != 0.0 - - def test_gradients_finite(self, grads): - """All gradient fields should be finite (no NaN/Inf).""" - assert np.isfinite(float(grads.velocity_cm_us)) - assert np.isfinite(float(grads.lifetime_us)) - assert np.isfinite(float(grads.diffusion_trans_cm2_us)) - assert np.isfinite(float(grads.diffusion_long_cm2_us)) +class TestForwardVsProduction: + @pytest.mark.parametrize("vol,plane", PLANES) + def test_uniform_pitch(self, uniform, vol, plane): + _, _, sig_prod, sig_diff = uniform + prod = np.asarray(sig_prod[(vol, plane)]) + diff = np.asarray(sig_diff[PLANES.index((vol, plane))]) + assert len(sig_diff) == len(PLANES) + assert prod.shape == diff.shape + assert np.abs(prod).max() > 1.0 # electrons; not a comparison of zeros + assert _rel_l2(prod, diff) < 1e-5 + + @pytest.mark.parametrize("vol,plane", [ + pytest.param(v, p, marks=[] if p == 0 else pytest.mark.xfail( + strict=True, raises=AssertionError, + reason="production scales every plane's transverse diffusion by " + "wire_spacings_cm[0] (tools/simulation.py): sigma_T on Y is " + "0.363 cm, analytic 0.180 cm. Relative L2 vs forward() is " + + {1: "0.28-0.31 on V", 2: "0.39-0.42 on Y"}[p])) + for v, p in PLANES]) + def test_mixed_pitch(self, mixed, vol, plane): + _, _, sig_prod, sig_diff = mixed + prod = np.asarray(sig_prod[(vol, plane)]) + diff = np.asarray(sig_diff[PLANES.index((vol, plane))]) + if prod.shape != diff.shape or np.abs(prod).max() <= 1.0: + pytest.fail("unexpected shape or empty plane") # not the known bug + assert _rel_l2(prod, diff) < 1e-5 + + +class TestForwardSegments: + + def test_matches_forward(self, uniform): + """Global positions through forward_segments == the same deposits via forward. + + forward_segments fixes theta = phi = 0 (track along z), so forward gets the + same angles. + """ + sim = uniform[0] + rng = np.random.RandomState(11) + n = 40 + pos = rng.uniform([-2000, -250, -250], [2000, 250, 250], (n, 3)).astype(np.float32) + de = np.linspace(0.5, 1.5, n, dtype=np.float32) + deposits = build_deposit_data( + pos, de, np.full(n, 3.0, np.float32), sim.config) + params = sim.default_sim_params + reference = sim.forward(params, deposits) + segments = sim.forward_segments(params, jnp.asarray(pos), jnp.asarray(de), 3.0) + for ref, seg in zip(reference, segments, strict=True): + assert np.abs(np.asarray(ref)).max() > 1.0 + assert _rel_l2(np.asarray(ref), np.asarray(seg)) < 1e-5 -# --------------------------------------------------------------------------- -# No recompile -# --------------------------------------------------------------------------- -@needs_data class TestNoRecompile: - def test_second_call_fast(self, sim, deposits): - sim.forward(sim.default_sim_params, deposits) # warm - t0 = time.time() - sim.forward(sim.default_sim_params, deposits) - assert time.time() - t0 < 2.0 - - def test_different_velocity_different_output(self, sim, deposits): - params2 = sim.default_sim_params._replace(velocity_cm_us=jnp.array(0.17)) - sigs1 = sim.forward(sim.default_sim_params, deposits) - sigs2 = sim.forward(params2, deposits) - diff = sum(float(jnp.sum(jnp.abs(s1 - s2))) - for s1, s2 in zip(sigs1, sigs2)) - assert diff > 0 - - -# --------------------------------------------------------------------------- -# Edge cases -# --------------------------------------------------------------------------- - -@needs_data -class TestEdgeCases: - - def test_single_volume_zeros_other(self, sim): - pos = np.ones((N, 3), dtype=np.float32) * 500 - deps = build_deposit_data(pos, np.ones(N, dtype=np.float32) * 2.0, - np.ones(N, dtype=np.float32) * 0.5, sim.config) - sigs = sim.forward(sim.default_sim_params, deps) - vol0 = sum(float(jnp.abs(sigs[i]).sum()) for i in range(3)) - vol1 = sum(float(jnp.abs(sigs[i]).sum()) for i in range(3, 6)) - assert vol0 < 1e-6 - assert vol1 > 0 - - def test_zero_energy_zero_signal(self, sim): - pos = np.ones((N, 3), dtype=np.float32) * -500 - deps = build_deposit_data(pos, np.zeros(N, dtype=np.float32), - np.ones(N, dtype=np.float32) * 0.5, sim.config) - sigs = sim.forward(sim.default_sim_params, deps) - total = sum(float(jnp.abs(s).sum()) for s in sigs) - assert total < 1e-6 + def test_params_change_without_recompile(self, uniform, count_compiles): + sim, deposits, _, reference = uniform + fwd = jax.jit(sim.forward) + # Positive control: the first call must be seen to compile + assert count_compiles( + lambda: jax.block_until_ready(fwd(sim.default_sim_params, deposits))) > 0 + params = sim.default_sim_params + params2 = params._replace(velocity_cm_us=params.velocity_cm_us * 1.06, + lifetime_us=params.lifetime_us * 0.5) + out = {} + assert count_compiles( + lambda: out.update(s=jax.block_until_ready(fwd(params2, deposits)))) == 0 + # ... and the new values were used, not baked in + for new, old in zip(out['s'], reference): + assert _rel_l2(np.asarray(old), np.asarray(new)) > 0.1 + + def test_eager_forward_does_not_recompile(self, uniform, count_compiles): + sim, deposits, _, _ = uniform + p2 = sim.default_sim_params._replace(lifetime_us=jnp.array(5000.0)) + jax.block_until_ready(sim.forward(p2, deposits)) + p3 = sim.default_sim_params._replace(lifetime_us=jnp.array(7000.0)) + assert count_compiles( + lambda: jax.block_until_ready(sim.forward(p3, deposits))) == 0 # --------------------------------------------------------------------------- -# Forward vs production consistency +# Every SimParams gradient vs finite differences # --------------------------------------------------------------------------- -@needs_data -class TestForwardVsProduction: - - def test_signals_match(self, detector_config, raw): - sim_prod = DetectorSimulator( - detector_config, total_pad=N, response_chunk_size=N, - include_track_hits=False, include_intrinsic_noise=False, - include_electronics=False, include_digitize=False) - - deps_prod = build_deposit_data( - raw['positions_mm'][:N], raw['de'][:N], raw['dx'][:N], sim_prod.config, - theta=raw['theta'][:N], phi=raw['phi'][:N]) - sigs_prod, _, _ = sim_prod.process_event(deps_prod) - - sim_diff = DetectorSimulator( - detector_config, differentiable=True, n_segments=N) - deps_diff = build_deposit_data( - raw['positions_mm'][:N], raw['de'][:N], raw['dx'][:N], sim_diff.config, - theta=raw['theta'][:N], phi=raw['phi'][:N]) - deps_diff = pad_deposit_data(deps_diff, sim_diff.config.total_pad) - sigs_diff = sim_diff.forward(sim_diff.default_sim_params, deps_diff) - - cfg = sim_prod.config - plane_order = [(v, p) - for v in range(cfg.n_volumes) - for p in range(cfg.volumes[v].n_planes)] - for i, (vol, plane) in enumerate(plane_order): - prod = np.asarray(sigs_prod[(vol, plane)]) - diff = np.asarray(sigs_diff[i]) - prod_sum = float(np.sum(np.abs(prod))) - if prod_sum < 1e-6: - continue - rel = float(np.max(np.abs(prod - diff))) / prod_sum - assert rel < 0.01, f"({vol},{plane}): rel={rel:.4f}" - +@pytest.fixture(scope="class") +def emb_gradients(compact_detector, synthetic_tracks): + """Gradients in float64; + In float32 the difference of two nearly equal losses is rounding noise.""" + was_enabled = jax.config.jax_enable_x64 + jax.config.update("jax_enable_x64", True) + try: + sim = DetectorSimulator(compact_detector(), differentiable=True, n_segments=N, + recombination_model='emb') + yield param_gradients(sim, synthetic_tracks(sim.config)) + finally: + jax.config.update("jax_enable_x64", was_enabled) -# --------------------------------------------------------------------------- -# Finite-difference gradient verification (no external data) -# --------------------------------------------------------------------------- -RESPONSE_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)), - 'tools', 'responses') -has_kernels = all( - os.path.exists(os.path.join(RESPONSE_PATH, f'{p}_plane_kernel.npz')) - for p in ['U', 'V', 'Y']) - - -@pytest.mark.requires_kernels -@pytest.mark.skipif(not has_kernels, reason="Response kernel files not found") -class TestFiniteDifferenceGradients: - """Verify AD gradients match finite-difference approximation. - - Uses forward_segments with a tiny synthetic track — no out.h5 needed. - This catches gradient correctness, not just "gradients are nonzero." - """ - - @pytest.fixture(scope="class") - def _x64(self): - """Run these gradient checks in float64. - - Comparing an AD gradient to a CENTRAL finite difference of a float32 - loss suffers catastrophic cancellation: e.g. lifetime ~10000 us with a - small eps makes loss(+eps) and loss(-eps) agree to within float32 - rounding, so the FD value is platform/JAX-version-dependent noise (it - passed on jax 0.5.3 / py3.10 but produced a garbage FD=1000.0 on the - CI py3.11 runner). In float64 the FD converges to the true gradient - (rel_err ~ 0) regardless of platform, so the comparison is sound. - """ - was_enabled = jax.config.jax_enable_x64 - jax.config.update("jax_enable_x64", True) - yield - jax.config.update("jax_enable_x64", was_enabled) +class TestParamGradients: - @pytest.fixture(scope="class") - def fd_sim(self, _x64): - det = generate_detector(CONFIG_PATH) - return DetectorSimulator( - det, differentiable=True, n_segments=50) - - @pytest.fixture(scope="class") - def fd_track(self, _x64): - """Straight track at x=-500mm, spanning y/z = [-50, 50]mm.""" - N = 50 - t = jnp.linspace(0, 1, N) - positions = jnp.stack([ - jnp.full(N, -500.0), - t * 100.0 - 50.0, - t * 100.0 - 50.0, - ], axis=-1) - de = jnp.ones(N) * 2.0 - return positions, de - - def _loss(self, sim, params, positions, de): - sigs = sim.forward_segments(params, positions, de, 5.0) - return sum(float(jnp.sum(s ** 2)) for s in sigs) - - def _loss_jax(self, sim, params, positions, de): - sigs = sim.forward_segments(params, positions, de, 5.0) - return sum(jnp.sum(s ** 2) for s in sigs) - - def test_velocity_gradient_sign_and_order(self, fd_sim, fd_track): - """AD and FD velocity gradients should agree in sign and order of magnitude. - - Velocity shifts signals across discrete time bins, so the AD gradient - through kernel interpolation has inherent discretization error (~2x). - We check sign agreement and same order of magnitude, not tight match. - """ - positions, de = fd_track - params = fd_sim.default_sim_params - v0 = float(params.velocity_cm_us) - eps = v0 * 1e-5 - - ad_grad = jax.grad( - lambda p: self._loss_jax(fd_sim, p, positions, de) - )(params) - ad_val = float(ad_grad.velocity_cm_us) - - params_plus = params._replace( - velocity_cm_us=params.velocity_cm_us + eps) - params_minus = params._replace( - velocity_cm_us=params.velocity_cm_us - eps) - fd_val = (self._loss(fd_sim, params_plus, positions, de) - - self._loss(fd_sim, params_minus, positions, de)) / (2 * eps) - - assert abs(ad_val) > 0, "AD gradient should be nonzero" - assert abs(fd_val) > 0, "FD gradient should be nonzero" - assert np.sign(ad_val) == np.sign(fd_val), \ - f"Sign mismatch: AD={ad_val:.2e}, FD={fd_val:.2e}" - ratio = abs(ad_val / fd_val) - assert 0.1 < ratio < 10, \ - f"Order of magnitude mismatch: AD={ad_val:.2e}, FD={fd_val:.2e}, ratio={ratio:.2f}" - - def test_lifetime_gradient(self, fd_sim, fd_track): - """AD gradient of lifetime should match finite-difference.""" - positions, de = fd_track - params = fd_sim.default_sim_params - eps = 1e-3 - - ad_grad = jax.grad( - lambda p: self._loss_jax(fd_sim, p, positions, de) - )(params) - ad_val = float(ad_grad.lifetime_us) - - params_plus = params._replace( - lifetime_us=params.lifetime_us + eps) - params_minus = params._replace( - lifetime_us=params.lifetime_us - eps) - fd_val = (self._loss(fd_sim, params_plus, positions, de) - - self._loss(fd_sim, params_minus, positions, de)) / (2 * eps) - - assert abs(ad_val) > 0, "AD gradient should be nonzero" - rel_err = abs(ad_val - fd_val) / max(abs(ad_val), abs(fd_val), 1e-10) - assert rel_err < 0.05, \ - f"lifetime grad: AD={ad_val:.6f}, FD={fd_val:.6f}, rel_err={rel_err:.4f}" - - def test_recomb_alpha_gradient(self, fd_sim, fd_track): - """AD gradient of recombination alpha should match finite-difference.""" - positions, de = fd_track - params = fd_sim.default_sim_params - eps = 1e-4 - - ad_grad = jax.grad( - lambda p: self._loss_jax(fd_sim, p, positions, de) - )(params) - ad_val = float(ad_grad.recomb_params.alpha) - - rp = params.recomb_params - params_plus = params._replace( - recomb_params=rp._replace(alpha=rp.alpha + eps)) - params_minus = params._replace( - recomb_params=rp._replace(alpha=rp.alpha - eps)) - fd_val = (self._loss(fd_sim, params_plus, positions, de) - - self._loss(fd_sim, params_minus, positions, de)) / (2 * eps) - - assert abs(ad_val) > 0, "AD gradient should be nonzero" - rel_err = abs(ad_val - fd_val) / max(abs(ad_val), abs(fd_val)) - assert rel_err < 0.05, \ - f"alpha grad: AD={ad_val:.4f}, FD={fd_val:.4f}, rel_err={rel_err:.4f}" + @pytest.mark.parametrize("field", [ + 'velocity_cm_us', 'lifetime_us', + 'diffusion_trans_cm2_us', 'diffusion_long_cm2_us', + 'recomb_params.alpha', 'recomb_params.beta_90', 'recomb_params.R']) + def test_matches_finite_difference(self, emb_gradients, field): + check_param_gradient(emb_gradients, field) diff --git a/tests/test_pipeline_forward_slow.py b/tests/test_pipeline_forward_slow.py index d47239e..1634660 100644 --- a/tests/test_pipeline_forward_slow.py +++ b/tests/test_pipeline_forward_slow.py @@ -1,195 +1,116 @@ """ -Slow differentiable tests: multi-model gradients, all-field SimParams, -muon optimization through position generation. +Slow differentiable tests: Modified Box gradients, recombination model selection, +gradients with respect to deposit positions. Synthetic deposits only. Skip with: pytest -m "not slow" - -2 diff simulators (modified_box + emb) shared via module scope. """ -import os import numpy as np import jax import jax.numpy as jnp import pytest -from tools.geometry import generate_detector +from gradient_checks import check_param_gradient, param_gradients +from tools.loader import build_deposit_data from tools.simulation import DetectorSimulator -from tools.loader import load_particle_step_data, build_deposit_data - - -CONFIG_PATH = 'config/cubic_wireplane_config.yaml' -DATA_PATH = 'out.h5' -N = 500 - -needs_data = pytest.mark.skipif( - not os.path.exists(DATA_PATH), reason="out.h5 not found") pytestmark = pytest.mark.slow - -@pytest.fixture(scope="module") -def detector_config(): - return generate_detector(CONFIG_PATH) - - -@pytest.fixture(scope="module") -def raw(): - return load_particle_step_data(DATA_PATH, event_idx=2) +N = 64 @pytest.fixture(scope="module") -def sim_box(detector_config): - return DetectorSimulator( - detector_config, differentiable=True, n_segments=N, - recombination_model='modified_box') +def x64(): + was_enabled = jax.config.jax_enable_x64 + jax.config.update("jax_enable_x64", True) + yield + jax.config.update("jax_enable_x64", was_enabled) @pytest.fixture(scope="module") -def sim_emb(detector_config): - return DetectorSimulator( - detector_config, differentiable=True, n_segments=N, - recombination_model='emb') +def sims(x64, compact_detector): + return {m: DetectorSimulator(compact_detector(), differentiable=True, + n_segments=N, recombination_model=m) + for m in ('modified_box', 'emb')} # --------------------------------------------------------------------------- -# Multi-model recombination +# Recombination model selection and Modified Box gradients # --------------------------------------------------------------------------- -@needs_data -class TestRecombModels: - - def test_different_models_different_output(self, sim_box, sim_emb, raw): - deps_box = build_deposit_data( - raw['positions_mm'][:N], raw['de'][:N], raw['dx'][:N], sim_box.config, - theta=raw['theta'][:N], phi=raw['phi'][:N]) - deps_emb = build_deposit_data( - raw['positions_mm'][:N], raw['de'][:N], raw['dx'][:N], sim_emb.config, - theta=raw['theta'][:N], phi=raw['phi'][:N]) - - sigs_box = sim_box.forward(sim_box.default_sim_params, deps_box) - sigs_emb = sim_emb.forward(sim_emb.default_sim_params, deps_emb) - - box_sum = sum(float(jnp.sum(jnp.abs(s))) for s in sigs_box) - emb_sum = sum(float(jnp.sum(jnp.abs(s))) for s in sigs_emb) - assert abs(box_sum - emb_sum) > 1.0 - - def test_box_alpha_beta_gradients(self, sim_box, raw): - deps = build_deposit_data( - raw['positions_mm'][:N], raw['de'][:N], raw['dx'][:N], sim_box.config, - theta=raw['theta'][:N], phi=raw['phi'][:N]) - - def loss(params): - return sum(jnp.sum(s ** 2) for s in sim_box.forward(params, deps)) - - grads = jax.grad(loss)(sim_box.default_sim_params) - assert float(grads.recomb_params.alpha) != 0.0 - assert float(grads.recomb_params.beta) != 0.0 +def _survival(model, dedx, cos_drift): + """Survival fraction written out independently of tools/recombination.py.""" + field_density = 1.396 * 0.5 # g/cm3 * kV/cm + if model == 'modified_box': + alpha, beta = 0.93, 0.212 + else: + alpha, r = 0.904, 1.25 + beta = 0.204 / np.sqrt(1 - cos_drift ** 2 + cos_drift ** 2 / r ** 2) + xi = beta * dedx / field_density + return np.log(alpha + xi) / xi - def test_emb_alpha_beta90_R_gradients(self, sim_emb, raw): - deps = build_deposit_data( - raw['positions_mm'][:N], raw['de'][:N], raw['dx'][:N], sim_emb.config, - theta=raw['theta'][:N], phi=raw['phi'][:N]) - def loss(params): - return sum(jnp.sum(s ** 2) for s in sim_emb.forward(params, deps)) - - grads = jax.grad(loss)(sim_emb.default_sim_params) - assert float(grads.recomb_params.alpha) != 0.0 - assert float(grads.recomb_params.beta_90) != 0.0 - assert float(grads.recomb_params.R) != 0.0 - - -# --------------------------------------------------------------------------- -# All SimParams fields (uses EMB — has more recomb params) -# --------------------------------------------------------------------------- +class TestRecombModels: -@needs_data -class TestAllSimParamsGradients: + def test_signal_ratio_is_survival_ratio(self, sims): + """emb / box signals differ by exactly the ratio of survival fractions.""" + dedx, cos_drift = 8.0, np.cos(0.4) + sigs = {} + for model, sim in sims.items(): + pos = np.stack([np.full(N, -700.0), np.linspace(-150, 150, N), + np.linspace(-120, 200, N)], axis=1).astype(np.float32) + # track along x rotated by 0.4 rad about z + deps = build_deposit_data( + pos, np.full(N, dedx * 0.3, np.float32), np.full(N, 3.0, np.float32), + sim.config, theta=np.full(N, np.pi / 2, np.float32), + phi=np.full(N, 0.4, np.float32)) + sigs[model] = sim.forward(sim.default_sim_params, deps) + expected = _survival('emb', dedx, cos_drift) / _survival('modified_box', dedx, cos_drift) + assert abs(expected - 1) > 0.05 # the models must be distinguishable here + for p in range(3): # volume 0 holds all the charge + box, emb = (np.asarray(sigs[m][p]) for m in ('modified_box', 'emb')) + scale = np.vdot(box, emb) / np.vdot(box, box) + assert scale == pytest.approx(expected, rel=1e-4) + assert np.linalg.norm(emb - scale * box) < 1e-5 * np.linalg.norm(emb) + + +class TestBoxGradients: @pytest.fixture(scope="class") - def grads(self, sim_emb, raw): - deps = build_deposit_data( - raw['positions_mm'][:N], raw['de'][:N], raw['dx'][:N], sim_emb.config, - theta=raw['theta'][:N], phi=raw['phi'][:N]) - - def loss(params): - return sum(jnp.sum(s ** 2) for s in sim_emb.forward(params, deps)) - - return jax.grad(loss)(sim_emb.default_sim_params) + def box_gradients(self, sims, synthetic_tracks): + return param_gradients(sims['modified_box'], synthetic_tracks(sims['modified_box'].config)) - def test_velocity(self, grads): - assert float(grads.velocity_cm_us) != 0.0 - - def test_lifetime(self, grads): - assert float(grads.lifetime_us) != 0.0 - - def test_diffusion_trans(self, grads): - assert float(grads.diffusion_trans_cm2_us) != 0.0 - - def test_diffusion_long(self, grads): - assert float(grads.diffusion_long_cm2_us) != 0.0 - - def test_recomb_alpha(self, grads): - assert float(grads.recomb_params.alpha) != 0.0 - - def test_recomb_beta90(self, grads): - assert float(grads.recomb_params.beta_90) != 0.0 - - def test_recomb_R(self, grads): - assert float(grads.recomb_params.R) != 0.0 + @pytest.mark.parametrize("field", ['recomb_params.alpha', 'recomb_params.beta']) + def test_matches_finite_difference(self, box_gradients, field): + check_param_gradient(box_gradients, field) # --------------------------------------------------------------------------- -# Muon optimization (gradient through position generation) +# Gradients through deposit positions # --------------------------------------------------------------------------- -@needs_data -class TestMuonOptimization: - - @pytest.fixture(scope="class") - def sim_muon(self, detector_config): - return DetectorSimulator( - detector_config, differentiable=True, n_segments=200) - - def test_gradient_flows_through_positions(self, sim_muon): - def generate(start_x, angle, n): - t = jnp.linspace(0, 100, n) - x = start_x + t * jnp.cos(angle) - y = t * jnp.sin(angle) * 0.5 - z = t * jnp.sin(angle) * 0.866 - return jnp.stack([x, y, z], axis=-1), jnp.ones(n) * 0.5 - - params = sim_muon.default_sim_params - pp = jnp.array([500.0, 0.3]) - - def fwd(pp): - pos, de = generate(pp[0], pp[1], 200) - return sum(jnp.sum(s ** 2) for s in - sim_muon.forward_segments(params, pos, de, 5.0)) - - grads = jax.grad(fwd)(pp) - assert not jnp.any(jnp.isnan(grads)) - assert jnp.any(grads != 0) - - def test_optimization_step_reduces_loss(self, sim_muon): - def generate(start_x, angle, n): - t = jnp.linspace(0, 100, n) - x = start_x + t * jnp.cos(angle) - y = t * jnp.sin(angle) * 0.5 - z = t * jnp.sin(angle) * 0.866 - return jnp.stack([x, y, z], axis=-1), jnp.ones(n) * 0.5 - - params = sim_muon.default_sim_params - pp = jnp.array([500.0, 0.3]) - - def fwd(pp): - pos, de = generate(pp[0], pp[1], 200) - return sum(jnp.sum(s ** 2) for s in - sim_muon.forward_segments(params, pos, de, 5.0)) - - loss0 = float(fwd(pp)) - grads = jax.grad(fwd)(pp) - pp_new = pp - 1e-6 * grads - loss1 = float(fwd(pp_new)) - assert loss1 <= loss0 + 1e-6 +class TestPositionGradients: + + def test_track_parameter_gradients(self, sims): + """d loss / d (x0, y0, z0, angle) through forward_segments == central FD.""" + sim = sims['emb'] + params = sim.default_sim_params + t = jnp.linspace(0.0, 100.0, N) + + @jax.jit + def loss(q): + x = q[0] + t * jnp.cos(q[3]) + y = q[1] + t * jnp.sin(q[3]) * 0.5 + z = q[2] + t * jnp.sin(q[3]) * 0.866 + pos = jnp.stack([x, y, z], axis=-1) + sigs = sim.forward_segments(params, pos, jnp.full(N, 0.5), 5.0) + return sum(jnp.sum(s ** 2) for s in sigs) + + q0 = jnp.array([503.17, 3.1, -7.3, 0.3]) + ad = np.asarray(jax.grad(loss)(q0)) + fd = np.empty(4) + for i, eps in enumerate([1e-5, 1e-5, 1e-5, 1e-7]): + d = jnp.zeros(4).at[i].set(eps) + fd[i] = float(loss(q0 + d) - loss(q0 - d)) / (2 * eps) + assert np.all(np.abs(fd) > 0), fd + np.testing.assert_allclose(ad, fd, rtol=1e-3)