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. 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.") diff --git a/tools/kernels.py b/tools/kernels.py index 4bf69fa..992a671 100644 --- a/tools/kernels.py +++ b/tools/kernels.py @@ -72,9 +72,82 @@ 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=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: + + 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] + # 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 + + 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. @@ -339,9 +412,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