Quickstart¶
This page assumes LUCiD and the example data are installed. Run the examples from the repository root.
Simulate one event¶
python examples/hello_simulate.py
The script, in full:
"""hello_simulate — propagate one muon through SK-like water and draw the event.
The differentiable forward: ParticleParams (truth track) -> expected charge per PMT, shown with
LUCiD's canonical unrolled-cylinder event display (barrel rectangle + top/bottom cap discs).
Run: python examples/hello_simulate.py [--n-rays N] (writes hello_simulate.png)
"""
import argparse
import jax
import numpy as np
from lucid.detector_params import ParticleParams
from lucid.simulation import setup_event_simulator
from lucid.visualization import create_detector_display
GEOM, PHYS = "config/SK_like_geom_config.json", "config/SK_like_physics_config.json"
def main(n_rays=200_000, out="hello_simulate.png"):
# Explicit propagation-grid cell counts (a grid keyword, like max_candidates_per_ray); without
# them the grid is sized from the sensor spacing.
sim = setup_event_simulator(
GEOM,
n_rays,
source="particle",
K=4,
physics_config=PHYS,
default_detector_params=True,
particle="muon",
n_cap=150,
n_angular=250,
n_height=150,
)
track = ParticleParams.from_cartesian(
energy=1000.0, position=[0.0, 0.0, 0.0], direction=[1.0, 0.0, 0.0], t0=0.0
) # horizontal → barrel ring
charge = np.asarray(sim(track, jax.random.PRNGKey(0)).charge) # (n_sensors,) expected pe
print(f"expected charge: {charge.sum():.0f} pe over {charge.size} PMTs")
display = create_detector_display(GEOM, sparse=False) # unrolled cylinder
display(charge, np.zeros_like(charge), file_name=out, perc_min=0.0, perc_max=99.5)
print(f"wrote {out}")
if __name__ == "__main__":
ap = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
ap.add_argument("--n-rays", type=int, default=200_000, help="rays per event [200000]")
ap.add_argument("--out", default="hello_simulate.png", help="display file [hello_simulate.png]")
main(**vars(ap.parse_args()))
setup_event_simulatorreads the detector's geometry and physics configs and returns aSimulator, a callable wrapping the compiled forward model. Withdefault_detector_params=Truethe detector parameters are loaded from the physics config and fixed, so the call takes(track, key). Leave itFalseto pass (and differentiate with respect to) the detector parameters yourself, as calibration does.ParticleParams.from_cartesianbuilds the track: energy in MeV, start position in metres, a direction vector and a start time in ns.- For a particle the call returns a
PhotonList;.chargeis the expected charge per PMT in photoelectrons, shape(n_sensors,)(10764 forSK_like). K=4is the number of scattering iterations. The simulator reference lists every argument and what the call returns.
Differentiate it¶
The forward model is a JAX function, so jax.grad, jax.vmap and jax.jit apply to it.
examples/hello_gradient.py takes the gradient of the total expected charge with respect to
the energy, the gradient of a Poisson loss with respect to the vertex, and maps the forward over
a batch of energies (about a minute on a CPU):
sim = setup_event_simulator(
GEOM,
n_rays,
source="particle",
K=4,
physics_config=PHYS,
default_detector_params=True,
particle="muon",
**GRID,
)
key = jax.random.PRNGKey(0)
direction = jnp.array([1.0, 0.0, 0.0])
def expected_charge(energy, position):
"""Per-PMT expected charge: ``.charge`` of the track forward's ``PhotonList``."""
track = ParticleParams.from_cartesian(
energy=energy, position=position, direction=direction, t0=0.0
)
return sim(track, key).charge
vertex = jnp.array([0.0, 0.0, 0.0])
dq_de = jax.grad(lambda e: expected_charge(e, vertex).sum())(1000.0)
print(f"d(total expected charge)/dE at 1000 MeV: {float(dq_de):.2f} pe/MeV")
# An "event" at a vertex 0.5 m along +x, fitted from the origin: the descent direction
# -grad points toward the event's vertex.
observed = jax.lax.stop_gradient(expected_charge(1000.0, jnp.array([0.5, 0.0, 0.0])))
def poisson_loss(position):
mu = expected_charge(1000.0, position) + 1e-6
return jnp.sum(mu - observed * jnp.log(mu))
g = jax.grad(poisson_loss)(vertex)
print(
f"-d(Poisson loss)/d(vertex) at the origin: {np.round(-np.asarray(g), 1)} per m "
"(event vertex at +0.5 m in x)"
)
energies = jnp.array([500.0, 1000.0, 1500.0])
totals = jax.vmap(lambda e: expected_charge(e, vertex).sum())(energies)
print(
"total expected charge, vmapped over energy:",
", ".join(f"{float(e):.0f} MeV -> {float(q):.0f} pe" for e, q in zip(energies, totals)),
)
The other examples¶
| script | shows | time |
|---|---|---|
hello_calibrate.py |
seven optical parameters and 10764 per-PMT gains recovered from laser and flasher light, with the Cramér-Rao bound (Calibration) | ~4 min on a GPU |
hello_calibrate_own_optimiser.py |
one calibration problem solved by Gauss-Newton, Adam, a hand-written loop and scipy | GPU |
seed_reconstruct.py |
the published reconstruction of a muon or electron track (Reconstruction) | ~8 min on an 11 GB GPU |
hello_telescope.py |
a muon track and a cascade in the IceCube string array, in ice | CPU |
hello_multiparticle.py |
two GEANT4 muons from one vertex, drawn together and per particle (--split) |
CPU |
Each script prints its options with --help. The calibration and reconstruction examples are
much slower on a CPU; each has a small-size switch (--n-photons, --steps, --quick).
If something goes wrong¶
FileNotFoundErrorunderdata/: the example data is not installed; runpython scripts/download_data.py.- Zero total charge: the track sends no light at a sensor. Check that the vertex is inside the detector and that positions are in metres.
- The first call is slow: it compiles (tens of seconds on a CPU). Later calls with the same shapes are fast. A new sensor radius or temperature also builds an overlap table once (install).
- JAX probes a GPU you do not want: set
JAX_PLATFORMS=cpu. - Numbers differ from a colleague's: fix the PRNG key and the photon count. Bit-identical output also needs the same CPU type and thread count, because float32 reductions depend on both.
- No window opens: the display is written to
hello_simulate.png(--outfor another name).