From 55e0eb26d45a6e56a1d0a798fb1c97fb858d55d1 Mon Sep 17 00:00:00 2001 From: Omar Alterkait Date: Sat, 22 Aug 2026 19:32:55 -0700 Subject: [PATCH 1/5] fix(N2): sub-tick time placement by 4-point Lagrange, not linear blend The 2-tap linear blend in interpolate_diffusion_kernel is not a pure fractional shift -- it is a shift CONVOLVED WITH A TRIANGLE, so it injects t_alpha*(1-t_alpha) ticks^2 of extra pulse width. That depends only on where the deposit happens to land inside its tick, not on any physics: identical deposits at different sub-tick phases come out with longitudinal widths differing by up to 0.25 tick^2 (0.39 mm). Cubic Lagrange matches the first three moments, so it places the pulse without inflating its width. Measured against physics truth -- the continuous convolution (gaussian arrival density) * (band-limited response), POINT-SAMPLED at ticks, which is what the ADC does -- worst-case waveform error over sub-tick phase: plane drift linear (before) Lagrange-4 (after) Y 2 cm 2.088% 0.313% Y 32 cm 1.888% 0.241% Y 200 cm 1.725% 0.135% U 2 cm 4.646% 0.661% U 32 cm 3.995% 0.505% U 200 cm 3.229% 0.330% Registration is deliberately identical to the blend it replaces (t_alpha=1 -> v[i], t_alpha=0 -> v[i+1], both exact), so the output length stays kernel_height-1 and time_zero_bin_out = time_zero_bin - 1 remains correct. B2, the electronics/noise FFT sizes and every profiled max_keys/max_buckets are unchanged. Verified against an independent numpy implementation to 3.5e-7 (float32), with the two endpoints bit-exact. Lagrange-6/8 were also measured: better at the extremes but WORSE at mid drift (0.566%/0.599% vs 0.505% on U at 32 cm), so 4 points is the robust choice. Deliberately NOT changed: - The build-time blur stays point-sampled. Its discrete variance does collapse for sigma_L below ~0.6 ticks, but the physical sigma_L^2 there (0.067 tick^2 at 8 cm) sits inside a pulse of variance ~25 tick^2 that is dominated by the 2.2 us shaping, so correcting it changes the waveform by ~0.1% -- and measured end-to-end it is neutral-to-slightly-worse (2.088% -> 2.209% at 2 cm). - The pixel path keeps its 2-tap blend: it interpolates on the FINE 0.1 us grid and then averages over the coarse tick, so its residual triangle variance is ~25x smaller. Tests: 195 passed, 23 skipped (fast suite, CPU). --- tools/kernels.py | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/tools/kernels.py b/tools/kernels.py index 4bf69fa..3f51954 100644 --- a/tools/kernels.py +++ b/tools/kernels.py @@ -339,9 +339,34 @@ def interpolate_diffusion_kernel(DKernel, s_observed, w_offset, t_offset, values_s_interp_right = (1 - s_alpha) * values_s_n_right + s_alpha * values_s_n_plus_1_right values_w_interp = (1 - w_alpha) * values_s_interp_left + w_alpha * values_s_interp_right - # Time interpolation: linear blend between adjacent time bins - # As t_alpha increases (later arrival), the kernel peak shifts RIGHT (later time) - interpolated = t_alpha * values_w_interp[:-1] + (1 - t_alpha) * values_w_interp[1:] + # Sub-tick time placement: 4-point Lagrange fractional delay. + # + # A 2-tap linear blend is not a pure shift -- it is a shift CONVOLVED WITH A + # TRIANGLE, so it injects t_alpha*(1-t_alpha) ticks^2 of extra width that depends + # only on the deposit's sub-tick arrival phase, not on any physics. Cubic Lagrange + # matches the first three moments, so it shifts without inflating the width. + # Measured vs the exact continuous convolution point-sampled at ticks (which is + # what the ADC does): worst-case waveform error over sub-tick phase drops from + # 2.1%/1.9%/1.7% to 0.31%/0.24%/0.14% of peak on Y at 2/32/200 cm drift, and from + # 4.6%/4.0%/3.2% to 0.66%/0.51%/0.33% on U. + # + # Registration is deliberately IDENTICAL to the linear blend it replaces: at + # t_alpha=1 it returns v[i] and at t_alpha=0 it returns v[i+1], so the output + # length stays kernel_height-1 and time_zero_bin_out = time_zero_bin - 1 remains + # correct. That keeps B2, the electronics/noise FFT sizes and every profiled + # max_keys/max_buckets unchanged. + v = values_w_interp + n_out = v.shape[0] - 1 + i0 = jnp.arange(n_out) + im1 = jnp.clip(i0 - 1, 0, v.shape[0] - 1) # kernel is ~0 at both time edges, + ip2 = jnp.clip(i0 + 2, 0, v.shape[0] - 1) # so clamping there is harmless + u = 1.0 - t_alpha + Lm1 = -u * (u - 1.0) * (u - 2.0) / 6.0 + L0 = (u + 1.0) * (u - 1.0) * (u - 2.0) / 2.0 + L1 = -(u + 1.0) * u * (u - 2.0) / 2.0 + L2 = (u + 1.0) * u * (u - 1.0) / 6.0 + interpolated = (Lm1 * v[im1] + L0 * v[i0] + + L1 * v[i0 + 1] + L2 * v[ip2]) output_values = output_values.at[wire_idx, :].set(interpolated) return output_values From c594cb62f291ce980ade17b228e522b27d89d492 Mon Sep 17 00:00:00 2001 From: Omar Alterkait Date: Mon, 24 Aug 2026 03:39:09 -0700 Subject: [PATCH 2/5] fix(N4): enforce the wire-tiling invariant on the collection response Wires tile the pitch, so every drift electron is collected by exactly one of them: S(x) = sum_n R(x - n) must be CONSTANT in x A collection response is R = C * 1[|Delta| < 1/2] + induction, and that boxcar's edge falls EXACTLY on a grid sample. A step landing on a sample must carry HALF weight, so the two half-contributions from the wires either side sum to one; linear interpolation in Delta then tiles exactly (home wire C(1-a)+(C/2)a, neighbour 0(1-a)+(C/2)a, sum = C for every a). The shipped default Y kernel stores the NON-COLLECTING branch there instead (column integral 7e-6 against 0.060 one sample inside), so the collection boxcar is 0.9 pitch wide and the tiling has a hole. Measured on the Y kernel: residue-class tiling spread 112.15% -> 0.93% mean tiling sum 0.053929 -> 0.059963 (on-wire column 0.060318) which is a UNIFORM 10.6% under-collection at every drift -- independently confirmed in the full simulator, absolute ratio 0.8412 at mid-drift / 0.935 attenuation = 0.900 -- plus an offset-dependent loss, worst case over sub-pitch offset per sigma_T (pitch): 0.05: 20.9% -> 99.5% 0.15: 73.3% -> 99.7% 0.30: 92.7% -> 99.9% 0.45: 99.2% -> 100.0% Applied at load time because the default kernels have no builder in the repo. It is IDEMPOTENT -- a kernel that already tiles (the SBND kernels store the mean, which is exactly the half weight) is returned unchanged. Collection planes only, and that scope is measured rather than assumed: on Y the separatrix step is 81.6% of peak, 3.3x the largest step anywhere else, and the stored value sits 25.4% from the outside branch but 87.9% from the inside one. On U/V the separatrix step (9.1%, 20.0%) is SMALLER than the largest step elsewhere (32.9%, 27.3%) and the stored value is within ~2%/~15% of the inside branch, outside branch and their mean alike, so nothing there is identifiable as a mishandled discontinuity -- and the induction tiling invariant is only approximate (sum_n psi_n = psi_plane, which is not transversally uniform near a wire grid), so it could not derive a correction anyway. Settling U/V would need the garfield source. Cost: none. Two columns, at load. No memory or runtime change. --- tools/kernels.py | 69 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/tools/kernels.py b/tools/kernels.py index 3f51954..35096eb 100644 --- a/tools/kernels.py +++ b/tools/kernels.py @@ -72,9 +72,78 @@ def load_kernel(filename): wire_zero_bin = int(data['wire_zero_bin']) if 'wire_zero_bin' in data else int(np.argmin(np.abs(kernel_x_coords))) time_zero_bin = int(data['time_zero_bin']) if 'time_zero_bin' in data else int(np.argmin(np.abs(kernel_y_coords))) + kernel = _enforce_wire_tiling(kernel, wire_zero_bin, dx, plane) + return kernel, kernel_x_coords, kernel_y_coords, plane, dx, dy, wire_zero_bin, time_zero_bin +def _enforce_wire_tiling(kernel, wire_zero_bin, dx, plane, rtol=1e-3): + """Enforce the wire-tiling invariant on a COLLECTION-plane response. + + Wires tile the pitch, so every drift electron is collected by exactly one of them: + + S(x) = sum_n R(x - n) must be CONSTANT in x. + + On the kernel's sub-pitch grid that means the per-column time-integrals, summed over + every bins_per_wire-th column, must give the same total for each residue class. + + A collection response is R = C * 1[|Delta| < 1/2] + induction, and that boxcar's edge + falls EXACTLY on a grid sample (Delta = +-1/2). A step landing on a sample must carry + HALF weight, so that the two half-contributions from the wires either side sum to one; + linear interpolation in Delta then tiles exactly. The shipped default kernels instead + store the NON-COLLECTING branch there, leaving a hole: measured on Y, the residue-class + spread is 112% and the mean tiling sum is 89.4% of the on-wire column, i.e. a uniform + ~10.6% under-collection plus an offset-dependent loss reaching 79% at small sigma_T. + + The correction restores the deficit onto the two Delta = +-1/2 columns using the shape + of the adjacent interior column. It is IDEMPOTENT -- a kernel that already tiles (the + SBND kernels store the mean, which is exactly the half weight) is returned unchanged -- + and it is skipped entirely for induction planes, whose net integral is ~0 so the + invariant carries no information. + """ + bpw = int(round(1.0 / dx)) if dx else 0 + if bpw < 2 or bpw % 2 or kernel.ndim != 2: + return kernel + I = kernel.sum(axis=0) + ncol = I.shape[0] + on_wire = abs(I[wire_zero_bin]) if 0 <= wire_zero_bin < ncol else 0.0 + if on_wire <= 0: + return kernel + # Collection plane test: charge is concentrated inside |Delta| < 1/2, so the on-wire + # column dwarfs anything a full pitch away. Induction planes fail this and are skipped. + far = [c for c in range(ncol) if abs(c - wire_zero_bin) >= bpw] + if not far or on_wire < 10.0 * max(abs(I[c]) for c in far): + return kernel + + sep = bpw // 2 + classes = {} + for c in range(ncol): + classes.setdefault((c - wire_zero_bin) % bpw, []).append(c) + sums = {r: float(sum(I[c] for c in cols)) for r, cols in classes.items()} + others = [v for r, v in sums.items() if r != sep % bpw] + if not others: + return kernel + target = float(np.median(others)) + deficit = target - sums[sep % bpw] + if abs(deficit) <= rtol * abs(target): + return kernel # already tiles -- idempotent, nothing to do + + kernel = np.array(kernel, copy=True) + for sign in (+1, -1): + c_sep = wire_zero_bin + sign * sep + c_adj = wire_zero_bin + sign * (sep - 1) + if not (0 <= c_sep < ncol and 0 <= c_adj < ncol): + continue + shape = kernel[:, c_adj] + norm = shape.sum() + if norm == 0: + continue + kernel[:, c_sep] = kernel[:, c_sep] + 0.5 * deficit * (shape / norm) + print(f" Response {plane}: wire-tiling enforced " + f"(residue-class deficit {deficit / target * 100:+.1f}% restored at Delta=+-1/2)") + return kernel + + def calculate_wire_count(kernel_width, wire_spacing=0.1): """ Calculate how many wire positions we can represent given kernel width. From b6752a492e2add933b38841e60e539612b1e105d Mon Sep 17 00:00:00 2001 From: Omar Alterkait Date: Mon, 24 Aug 2026 04:41:14 -0700 Subject: [PATCH 3/5] docs: response representation -- why each axis is handled the way it is Documents the pitch/time asymmetry that gives each axis exactly one failure mode, the tiling invariant behind _enforce_wire_tiling (and why it is collection-plane only, from the garfield branch data), the band-limited fractional delay on the time axis, and the list of things deliberately NOT done with the measurement that ruled each out. --- docs/physics/response_representation.md | 92 +++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 docs/physics/response_representation.md diff --git a/docs/physics/response_representation.md b/docs/physics/response_representation.md new file mode 100644 index 0000000..7576d63 --- /dev/null +++ b/docs/physics/response_representation.md @@ -0,0 +1,92 @@ +# Response representation: what the kernel means and why it is handled this way + +The simulator must compute, for a deposit of charge `q` at transverse position `u0` +arriving at `t0` with diffusion `(sigma_T, sigma_L)`: + + S_n(tau_k) = q * INT INT G_sigmaT(y - u0) G_sigmaL(t - t0) R(y - n, tau_k - t) dy dt + +`R` is the single-wire response (field response convolved with the electronics), stored in +`tools/responses/*_plane_kernel.npz` on a grid of 0.1 pitch x 0.5 us. + +## The two axes are not the same kind of thing + +| | pitch (Delta) | time (tau) | +|---|---|---| +| what it is | an **integral** over the charge distribution | a **sample** of a continuous waveform | +| why | wires are physical objects -- evaluation points, nothing is sampled transversally | the ADC point-samples; the 2.2 us shaping is the anti-alias filter | +| R's behaviour | **discontinuous** at \|Delta\| = 1/2 on the collection plane | smooth and band-limited (3e-4 of power above 40% of Nyquist) | +| what can go wrong | representing the discontinuity | the sub-grid **shift operator** | + +That asymmetry is why each axis has exactly one failure mode, and why the fixes differ. + +## Pitch: the tiling invariant (`_enforce_wire_tiling`, kernels.py) + +Wires tile the pitch, so every drift electron is collected by exactly one of them: + + S(x) = sum_n R(x - n) must be CONSTANT in x + +A collection response is `R = C * 1[|Delta| < 1/2] + induction`, and that boxcar's edge +falls **exactly on a grid sample**. A step landing on a sample must carry **half weight**, +so the two half-contributions from the wires either side sum to one. Then linear +interpolation in Delta tiles exactly: + + x in (0.4, 0.5): home wire C(1-a) + (C/2)a = C(1 - a/2) + neighbour 0(1-a) + (C/2)a = C a/2 + sum = C, for every a + +The shipped default Y kernel stores the **non-collecting** branch there instead (column +integral 7e-6 against 0.060 one sample inside), so the boxcar is 0.9 pitch wide and the +tiling has a hole: residue-class spread 112%, mean tiling sum 89.4% of the on-wire column. + +**Collection planes only, and that is physics, not convenience.** From the garfield +branches (the same physical position seen from the two adjacent regions): + +| plane | branch L integral | branch R integral | \|L-R\| as % of on-wire peak | +|---|---|---|---| +| U | +0.00056 | +0.00053 | 1.0% | +| V | +0.00069 | +0.00027 | 3.2% | +| Y | -0.07869 (collected) | +0.00013 (not) | **104.7%** | + +Only the collection plane bifurcates. Applying a half weight on U/V would corrupt a +legitimate sample of a smooth function, and measurement confirms it changes nothing there. +The detector (on-wire integral vs the largest integral a pitch away) is 101x on Y against +0.9x / 0.4x on U / V -- not marginal. The correction is **idempotent**, so kernels that +already tile (SBND stores the mean, which IS the half weight) are returned unchanged. + +## Time: the sub-tick shift (`interpolate_diffusion_kernel`, kernels.py) + +The ADC point-samples a band-limited waveform, so the correct sub-tick operation is a +band-limited **fractional delay**. A 2-tap linear blend is not one: it is a shift +CONVOLVED WITH A TRIANGLE, injecting `a(1-a)` ticks^2 of width that depends only on where +the deposit lands inside its tick. Cubic Lagrange matches the first three moments, so it +places the pulse without inflating it, and is charge-neutral (weights sum to 1). + +There is no half-weight analogue here: the response has no discontinuity in time, so there +is no representation error -- only the operator. + +## Deliberately NOT done, with reasons + +- **Do not "fix the blur".** Replacing the point-sampled gaussian with a band-limited or + bin-integrated one measures neutral-to-worse on both axes. On pitch it cannot even affect + charge: for any normalised g, `sum_n (g conv R)(x-n) = S * sum(g) = S`. +- **Do not raise the Delta interpolation order.** It rings on the discontinuity (Y is worse + at short drift) and the gain elsewhere is below the reference's own model uncertainty. +- **Do not bin-integrate in time.** That is WireCell's quadrature, not the physics; it + places the pulse half a tick early. JAXTPC's timing is already exact (centroid error + +0.001 tick vs physics truth, where WireCell is -0.500). +- **Shift-aware Delta interpolation**: tried, much worse (aligning centroids of two nearly + identical blurred columns is noise-driven). + +## Known remaining limits + +- **Exact-phase evaluation** (`sum_i R_i T_sigma(Delta - x_i)` at the deposit's actual + Delta, instead of interpolating a phase-0 table) is the only variant that reaches the + floor, matching WireCell to 4 significant figures. Its gain over the tiling fix is + resolvable only at short drift: 4.7x the reference uncertainty at 2 cm, 2.3x at 8 cm, + 1.2x at 32 cm, 0.9x at 128 cm. Not implemented. +- **The floor itself** (2.9e-2 at 2 cm, ~5e-3 at long drift, shared exactly with WireCell) + is set by garfield's 0.1-pitch sampling of a response whose pulse TRANSLATES in time with + impact position (+2.61 bins over half a pitch against a 3.50-bin width). That is a data + limitation; no algorithm change reaches below it. +- **`pre_window_us = 0`** truncates the response near the anode and currently masks the + short-drift transverse behaviour. Coupled to the above -- assess together. From 97193f823aa4957e31254abc878898a4091a509d Mon Sep 17 00:00:00 2001 From: Omar Alterkait Date: Mon, 24 Aug 2026 04:42:11 -0700 Subject: [PATCH 4/5] fix(N4): raise the tiling tolerance so correct kernels are left untouched rtol=1e-3 was tight enough to nudge kernels that already tile: the SBND Y kernel tiles to 1.25% and stores the mean at the separatrix (which IS the half weight), yet still picked up a -0.4% 'correction' -- fitting noise. The defect being targeted is a MISSING BRANCH, which shows up as a ~100% deficit (default Y: +100.5%). rtol=0.05 sits far from both, so only a genuine hole is corrected and already-correct kernels are returned unchanged. --- tools/kernels.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/tools/kernels.py b/tools/kernels.py index 35096eb..992a671 100644 --- a/tools/kernels.py +++ b/tools/kernels.py @@ -77,7 +77,7 @@ def load_kernel(filename): return kernel, kernel_x_coords, kernel_y_coords, plane, dx, dy, wire_zero_bin, time_zero_bin -def _enforce_wire_tiling(kernel, wire_zero_bin, dx, plane, rtol=1e-3): +def _enforce_wire_tiling(kernel, wire_zero_bin, dx, plane, rtol=0.05): """Enforce the wire-tiling invariant on a COLLECTION-plane response. Wires tile the pitch, so every drift electron is collected by exactly one of them: @@ -125,6 +125,10 @@ def _enforce_wire_tiling(kernel, wire_zero_bin, dx, plane, rtol=1e-3): return kernel target = float(np.median(others)) deficit = target - sums[sep % bpw] + # Only a genuine hole is corrected. A real kernel tiles to a few percent (finite grid, + # induction tails); the defect this targets is a MISSING BRANCH, which shows up as a + # ~100% deficit. Measured: default Y +100.5%, SBND Y -0.4% (it already stores the mean). + # rtol sits far from both, so correct kernels are returned untouched rather than nudged. if abs(deficit) <= rtol * abs(target): return kernel # already tiles -- idempotent, nothing to do From ab8d5a26f62d70ea46eeacfde451abb93750aab9 Mon Sep 17 00:00:00 2001 From: Omar Alterkait Date: Mon, 24 Aug 2026 08:39:30 -0700 Subject: [PATCH 5/5] test: physics invariants for the response path Every existing kernel test is structural (shape, finiteness, batch == sequential, JIT-compat) or self-referential -- they compare the code to itself. 195 of them passed while the collection response was losing 10.6% of its charge, while the sub-tick shift was injecting phase-dependent pulse width, and while the dense and bucketed paths disagreed on the time index. These assert what the PHYSICS requires instead. Each test was checked to FAIL on the unfixed code, which is the only thing that makes a regression test worth having: width swing across sub-tick phase unfixed 0.2500 ticks^2 -> fixed 0.0000 (0.25 is exactly max a(1-a), as predicted) charge variation vs sub-pitch offset unfixed 25.9% -> fixed 0.0% Covered: - the wire-tiling invariant sum_n R(x-n) = const, plus a companion test asserting the DEFECT is detectable (so the invariant test cannot silently become vacuous) - _enforce_wire_tiling repairs, is idempotent, leaves correct kernels untouched, and skips induction planes - collected charge independent of the sub-pitch offset, driven from a BROKEN kernel through the load-time repair so it guards the whole chain (using an already-correct kernel would test nothing -- it passes with or without the fix) - pulse width independent of the sub-tick phase - the dense/bucketed time-index convention, which test_dense_equals_bucketed structurally cannot catch because it passes the SAME time_indices array to both accumulators, making them equal by construction Tests: 205 passed, 23 skipped (was 195; +10). --- tests/test_response_invariants.py | 187 ++++++++++++++++++++++++++++++ 1 file changed, 187 insertions(+) create mode 100644 tests/test_response_invariants.py diff --git a/tests/test_response_invariants.py b/tests/test_response_invariants.py new file mode 100644 index 0000000..b4c8f96 --- /dev/null +++ b/tests/test_response_invariants.py @@ -0,0 +1,187 @@ +"""Physics INVARIANTS of the response path. + +Every other kernel test in this suite is structural (shape, finiteness, +batch == sequential, JIT-compat) or self-referential -- they compare the code to +itself. A full suite of them passed while the collection response was losing 10.6% +of its charge, while the sub-tick shift was injecting phase-dependent pulse width, +and while the dense and bucketed paths disagreed on the time index. These tests +assert properties the PHYSICS requires, so they fail when the physics is wrong +rather than when the code changes shape. + +Files under test: tools/kernels.py, tools/wires.py, tools/physics.py +""" + +import numpy as np +import jax.numpy as jnp +import pytest + +from tools.kernels import ( + generate_dkernel_table, + interpolate_diffusion_kernel, + _enforce_wire_tiling, +) + + +BPW = 10 # sub-pitch bins per wire (wire_spacing = 0.1 pitch) + + +def _collection_kernel(H=41, npitch=5, half_weight=True): + """A synthetic COLLECTION response: charge is collected by whichever wire is + nearest, so R is a boxcar of exactly one pitch, plus a small induction tail. + + The boxcar's edge lands exactly on a sample. With half_weight=True the edge + sample carries C/2, which is what makes the wires tile; with False it carries + the non-collecting value, which is the defect the shipped Y kernel had. + """ + W = 2 * npitch * BPW + 1 + wz = W // 2 + t = np.arange(H) - H // 2 + pulse = np.exp(-0.5 * (t / 3.0) ** 2) + pulse = pulse / pulse.sum() + k = np.zeros((H, W)) + for c in range(W): + d = (c - wz) / BPW # Delta in pitch units + if abs(d) < 0.5 - 1e-9: + k[:, c] = pulse # collected + elif abs(abs(d) - 0.5) < 1e-9: + k[:, c] = 0.5 * pulse if half_weight else 0.0 + return k, wz + + +def _tiling_sums(kernel, wz): + """Per-residue-class tiling sums: sum_n R(x - n) for each x on the sub-pitch grid.""" + integ = kernel.sum(axis=0) + out = [] + for r in range(BPW): + out.append(sum(integ[c] for c in range(len(integ)) if (c - wz) % BPW == r)) + return np.array(out) + + +class TestWireTilingInvariant: + """sum_n R(x - n) must be CONSTANT in x -- every drift electron is collected by + exactly one wire, so the total collected charge cannot depend on where between + the wires the charge happens to sit.""" + + def test_half_weighted_edge_tiles(self): + k, wz = _collection_kernel(half_weight=True) + T = _tiling_sums(k, wz) + assert np.ptp(T) < 1e-9 * abs(T.mean()), ( + f"a correctly half-weighted collection kernel must tile exactly; " + f"got per-class sums {T}") + + def test_missing_branch_breaks_tiling(self): + """Guards the test itself: the defect must actually be detectable.""" + k, wz = _collection_kernel(half_weight=False) + T = _tiling_sums(k, wz) + assert np.ptp(T) > 0.5 * abs(T.mean()), ( + "storing the non-collecting branch should leave a ~100% hole in the tiling") + + def test_enforce_repairs_and_is_idempotent(self): + broken, wz = _collection_kernel(half_weight=False) + fixed = _enforce_wire_tiling(broken, wz, 1.0 / BPW, 'Y') + T = _tiling_sums(fixed, wz) + assert np.ptp(T) < 0.05 * abs(T.mean()), f"tiling not repaired: {T}" + again = _enforce_wire_tiling(fixed, wz, 1.0 / BPW, 'Y') + np.testing.assert_array_equal( + again, fixed, err_msg="_enforce_wire_tiling must be idempotent") + + def test_leaves_a_correct_kernel_untouched(self): + good, wz = _collection_kernel(half_weight=True) + out = _enforce_wire_tiling(good, wz, 1.0 / BPW, 'Y') + np.testing.assert_array_equal( + out, good, err_msg="a kernel that already tiles must not be nudged") + + def test_skips_induction_planes(self): + """An induction response has no collection bifurcation and no meaningful + tiling sum; it must not be 'corrected'.""" + H, npitch = 41, 5 + W = 2 * npitch * BPW + 1 + wz = W // 2 + t = np.arange(H) - H // 2 + bipolar = np.gradient(np.exp(-0.5 * (t / 3.0) ** 2)) + k = np.zeros((H, W)) + for c in range(W): + d = (c - wz) / BPW + k[:, c] = bipolar * np.exp(-0.5 * (d / 1.5) ** 2) + out = _enforce_wire_tiling(k, wz, 1.0 / BPW, 'U') + np.testing.assert_array_equal( + out, k, err_msg="induction planes must be left alone") + + +class TestChargeIndependentOfSubPitchOffset: + """End-to-end consequence of the tiling invariant, through the real runtime: + the interpolated (num_wires x ntime) patch must carry the same total charge + wherever the deposit sits between the wires.""" + + @pytest.mark.parametrize("sigma_T", [0.05, 0.15, 0.45]) + def test_patch_sum_flat_in_offset(self, sigma_T): + """Driven from a BROKEN kernel through the load-time repair, so this guards the + whole chain. Using an already-correct kernel here would test nothing: it passes + with or without the fix (verified -- unfixed tree gives 25.9% variation, fixed + gives 0.0%).""" + broken, wz = _collection_kernel(half_weight=False) + base = _enforce_wire_tiling(broken, wz, 1.0 / BPW, 'Y') + dk = generate_dkernel_table(sigma_T, 0.3, jnp.asarray(base, dtype=jnp.float32), + 1.0 / BPW, 0.5, jnp.linspace(0, 1, 16)) + sums = [float(jnp.sum(interpolate_diffusion_kernel( + dk, 1.0, off, 0.0, 1.0 / BPW, 6))) + for off in (0.0, 0.1, 0.2, 0.3, 0.4, 0.49)] + rel = (max(sums) - min(sums)) / abs(sums[0]) + assert rel < 0.02, ( + f"collected charge varies {rel*100:.1f}% with the sub-pitch offset at " + f"sigma_T={sigma_T}; the wires are not tiling ({sums})") + + +class TestSubTickPhaseDoesNotChangeWidth: + """The sub-tick shift must PLACE the pulse, not broaden it. A 2-tap linear blend + is a shift convolved with a triangle and injects a(1-a) ticks^2 of width that + depends only on where the deposit lands inside its tick -- not on any physics.""" + + def test_width_stable_across_phase(self): + base, wz = _collection_kernel(H=61, half_weight=True) + dk = generate_dkernel_table(0.2, 1.0, jnp.asarray(base, dtype=jnp.float32), + 1.0 / BPW, 0.5, jnp.linspace(0, 1, 16)) + + def width(t_off): + p = np.asarray(interpolate_diffusion_kernel(dk, 1.0, 0.0, t_off, + 1.0 / BPW, 6)) + prof = np.abs(p).sum(axis=0) + i = np.arange(len(prof)) + mu = (i * prof).sum() / prof.sum() + return ((i - mu) ** 2 * prof).sum() / prof.sum() + + w = [width(a) for a in (0.0, 0.25, 0.5, 0.75)] + swing = max(w) - min(w) + assert swing < 0.10, ( + f"pulse width varies by {swing:.3f} ticks^2 with the sub-tick phase " + f"(a 2-tap linear blend injects up to 0.25); widths {w}") + + +class TestIndexConventionsAgree: + """The dense and bucketed accumulators must agree on a deposit's time index. + + compute_plane_physics computes its own time_map and feeds it to build_bucket_mapping + (which assigns each deposit's HOME bucket) while the scatter uses the index from + prepare_deposit_for_response. If the two expressions ever diverge, a deposit whose + difference straddles a bucket boundary has its ENTIRE patch written one bucket late + -- B2 = 2 * kernel_height ticks. That happened once in this repo's history and the + existing test_dense_equals_bucketed could not catch it, because it passes the SAME + time_indices array to both accumulators, making them equal by construction. + """ + + def test_prepare_matches_the_bucket_mapping_expression(self): + from tools.wires import prepare_deposit_for_response + dt = 0.5 + rng = np.random.RandomState(0) + ticks = rng.uniform(0.0, 1400.0, 500).astype(np.float32) + for tk in ticks[:50]: + _idx, _woff, tidx, _toff, _inten = prepare_deposit_for_response( + jnp.float32(1.0), jnp.float32(tk), jnp.int32(10), jnp.float32(0.0), + jnp.float32(1.0), jnp.bool_(True), 0.3, dt, 100) + # physics.compute_plane_physics builds time_map with this expression; the two + # MUST match or the bucketed home bucket disagrees with the scatter. + expected = int(np.floor(float(tk) / dt)) + assert int(tidx) == expected, ( + f"prepare_deposit_for_response time_index ({int(tidx)}) disagrees with " + f"compute_plane_physics' time_map expression ({expected}) at tick_us={tk}. " + f"Both sites must be changed together -- see tools/physics.py time_map.")