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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 92 additions & 0 deletions docs/physics/response_representation.md
Original file line number Diff line number Diff line change
@@ -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.
187 changes: 187 additions & 0 deletions tests/test_response_invariants.py
Original file line number Diff line number Diff line change
@@ -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.")
Loading
Loading