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
4 changes: 1 addition & 3 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,7 @@ JAXTPC/
│ ├── pixel_visualization.py # Pixel-readout signal visualization (sparse/dense projections)
│ ├── particle_generator.py # Differentiable muon track generation (PDG dE/dx tables)
│ ├── losses.py # Multi-scale spectral blur MSE loss for optimization
│ ├── nn_utils.py # NN inference utilities (symlog, kernel unfolding)
│ ├── sparse_utils.py # Dense ↔ truly sparse format conversion
│ ├── utils.py # Standalone HDF5 event I/O (save_event/load_event)
│ ├── utils.py # SCE map HDF5 I/O (save_sce_data/load_sce_data)
│ ├── responses/ # Pre-computed wire response kernels (NPZ per plane type)
│ └── data/ # PDG muon dE/dx table
├── production/ # Batch processing pipeline
Expand Down
6 changes: 2 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,7 @@ JAXTPC/
│ ├── losses.py # Sobolev / spectral loss functions
│ ├── coherent_noise.py # Tagged coherent (per-wire-group) noise model
│ ├── pixel_visualization.py # Pixel-readout signal visualization (sparse/dense projections)
│ ├── nn_utils.py # NN inference utilities
│ ├── sparse_utils.py # Dense ↔ truly-sparse format conversion
│ ├── utils.py # Misc shared helpers
│ ├── utils.py # SCE map HDF5 I/O
│ └── responses/ # Pre-computed wire response kernels (U/V/Y NPZ)
├── production/ # Batch production pipeline
│ ├── run_batch.py # Batch simulation with threaded save workers
Expand Down Expand Up @@ -239,7 +237,7 @@ Profiler-tuned `production_*.yaml` variants (including the doraemon wire/pixel c
| `iterate_mode` | `'scan'` | Volume iteration: `'scan'` or `'vmap'` |
| `use_bucketed` | False | Optional wire-only sparse bucket accumulation (memory saver; not required for pixel) |
| `max_active_buckets` | 1,000 | Max buckets per plane (bucketed mode) |
| `include_noise` | False | Enable intrinsic noise |
| `include_intrinsic_noise` | False | Enable intrinsic noise |
| `include_electronics` | False | Enable RC-RC electronics response |
| `include_digitize` | False | Enable ADC digitization |
| `include_track_hits` | True | Enable track correspondence |
Expand Down
18 changes: 9 additions & 9 deletions docs/PLAN.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ docs/
contributing/
development.md [dev] env, pytest -m "not slow", CI gates *tests/TESTS.md* [ ] new
adding-a-detector.md [dev] frame + uniformity invariants, config-authoring checklist ← code [ ] new
io-formats-internal.md [dev] tools/utils.py standalone HDF5 vs production format — when to use which *utils.py* [ ] new
io-formats-internal.md [dev] production event format pointer + SCE map I/O *utils.py* [ ] new
```

**Ordering rationale:** architecture spine + data-model come immediately after
Expand Down Expand Up @@ -198,10 +198,10 @@ each pulling `:::` directives from the relevant modules:
- **Data types** — all of `config.py` (the NamedTuples + factories) on one page (return types documented only here).
- **Loading & config** — `generate_detector`, `load_event`, `build_deposit_data`, `load_particle_step_data`, `create_sim_config`, `create_sim_params`.
- **Physics** — `recombination`, `drift`, the `physics` shared body.
- **Response & readout** — `kernels`, `wires`, `output`, `sparse_utils`.
- **Response & readout** — `kernels`, `wires`, `output`.
- **Post-processing** — `electronics`, `noise`, `coherent_noise`, `efield_distortions`.
- **Truth** — `track_hits`.
- **Differentiable** — `losses`, `particle_generator`, `nn_utils`.
- **Differentiable** — `losses`, `particle_generator`.
- **Visualization** — `visualization`, `pixel_visualization`.
- **Production** — `production/save.py`, `production/load.py` (format reference).

Expand All @@ -215,7 +215,7 @@ each pulling `:::` directives from the relevant modules:

Docstring health is otherwise good: `recombination`, `drift`, `wires`, `noise`,
`coherent_noise`, `efield_distortions`, `losses`, `particle_generator`,
`pixel_visualization`, `sparse_utils`, `utils`, `save`, `load` are essentially
`pixel_visualization`, `utils`, `save`, `load` are essentially
auto-gen-ready.

---
Expand Down Expand Up @@ -254,16 +254,16 @@ superseded cruft was removed (commit `ed85862`: `compute_gaussian_diffusion` +
| **Wire bucketed accumulation** (memory-saver) | `compute_plane_signal_bucketed`, `compute_bucket_maps`, `sparse_buckets_to_dense`, `generate_noise_bucketed`, `visualize_active_buckets`; compact reference `accumulate_response_signals_sparse_bucketed` | LIVE (`use_bucketed`/`--bucketed`) | `concepts/capacities.md` + `viz/plotting.md` + API |
| **`vmap` volume iteration** | `vmap_over`, `iterate_mode='vmap'` | LIVE (constructor flag) | `architecture/simulator.md` (scan vs vmap, D3) |
| **Merge track-hits path** | `merge_chunk_sensor_hits`, `box_enabled=False` branch | LIVE (non-default) | `truth/track-hits.md` (box vs merge) |
| **Legacy standalone track-hits** | `group_hits_by_track` / `label_hits` / `sparse_hits_to_dense` | test-only, marked legacy | `truth/track-hits.md` (mark legacy) |
| **Standalone sparse↔dense API** | `sparse_utils.py`; `sim.to_dense`/`to_sparse` | reference/API | `viz/plotting.md` + API |
| **Standalone single-file HDF5 I/O** | `utils.py` (`save_event`/`load_event`/…, SCE I/O) | utility/planned | `contributing/io-formats-internal.md` |
| **Legacy standalone track-hits** | removed (`group_hits_by_track` / `label_hits` / `sparse_hits_to_dense`, test-only) | removed | `truth/track-hits.md` (mark legacy) |
| **Standalone sparse↔dense API** | `sim.to_dense`/`to_sparse` (`output.py`; `sparse_utils.py` removed, it duplicated this in a second format) | reference/API | `viz/plotting.md` + API |
| **Standalone single-file HDF5 I/O** | `utils.py` (SCE map I/O only; single-file event I/O removed) | utility | `contributing/io-formats-internal.md` |
| **Toy generators** | `particle_generator` numpy muon gen; `efield_distortions.generate_toy_efield_map`, `compute_drift_corrections` | utility/planned (SCE port) | `differentiable/particle-generation.md`, `physics/sce.md` |
| **Extra viewers** | `visualize_single_plane`/`_waveforms`/`_wire_planes`; `visualize_pixel_3d`/`_buckets`/`_all_pixel_volumes` | utility | `viz/plotting.md`, `detector/wire-vs-pixel.md` |

**Needs-decision (documented, not yet resolved):**
- **Pixel bucketed mode** — `physics.compute_pixel_bucket_maps` / `compute_pixel_signal_bucketed` (+ `wires.scatter_contributions_to_pixel_buckets_batched`, `build_bucket_mapping_3d`, `pixel_visualization.visualize_pixel_buckets`) is a *complete* pixel analog of the wire bucketed mode whose output is already decoded (`output.py`), but `simulation.py`'s pixel branch never dispatches it. **Decision: keep, document as the pixel analog / reference** (not wired end-to-end yet). One dispatch site from working if ever wanted.
- **`nn_utils.py`** (`inv_symlog`/`unfold_kernel`/`normalize_positions`) — NN/SIREN response scaffolding with no in-repo consumer; keep as **planned** (tie to SCE-SIREN work), add a "not yet wired" marker.
- **Module-level `finalize_track_hits`** (`track_hits.py`) — a name-collision duplicate of the live `DetectorSimulator.finalize_track_hits` *method* (the method is the entry point; the module function is only stale-imported by one test). Resolve later: remove the duplicate, or de-dup by having the method call it.
- **`nn_utils.py`** — removed: scaffolding for a SIREN surrogate of the wire response kernel (extracted from an out-of-repo `siren_response_training/`), never wired in and unrelated to the SCE-SIREN.
- **Module-level `finalize_track_hits`** — removed (duplicate of the `DetectorSimulator.finalize_track_hits` method).

---

Expand Down
102 changes: 14 additions & 88 deletions docs/contributing/io-formats-internal.md
Original file line number Diff line number Diff line change
@@ -1,84 +1,21 @@
# Internal I/O: the standalone single-file format
# Internal I/O formats

JAXTPC has **two** HDF5 I/O paths. This page documents the smaller one —
`tools/utils.py` — and, crucially, when *not* to use it.
Event data has one HDF5 format: the production pipeline
(`production/save.py` writers, `production/load.py` readers; `sensor` / `step` /
`hits` [+ `labl`] files, any number of volumes, wire or pixel). The writers take an
open `h5py.File`, so they also work for saving a few events from a notebook. See
[Production data formats](../production/data-formats.md).

| | `tools/utils.py` | `production/save.py` + `load.py` |
|---|---|---|
| Files per run | **one** (events appended as groups) | **multiple** per batch (`sensor` / `step` / `hits` [+ `labl`]) |
| Audience | interactive, one-off, notebooks | batch production, downstream ML |
| Geometry support | **2-volume U/V/Y only** | any N volumes, wire or pixel |
| Encoding | plain gzip datasets | delta + CSR, configurable codecs |
| Truth machinery | flat per-track hits | group→track correspondence, `qs_fractions`, per-volume `group_to_track` |
For in-memory conversion use `sim.to_sparse(...)` / `sim.to_dense(...)`
(`tools/output.py`); `to_dense` accepts every format `to_sparse` returns.

!!! warning "Do not use `tools/utils.py` for production"
`tools/utils.py` is an interactive single-file *convenience* format. It is
**not** the production output format and is not interchangeable with it.
For batch runs, HDF5 schemas consumed by downstream tooling, or anything
beyond the default 2-volume wire detector, use the production pipeline
(`production/run_batch.py` → `production/save.py` / `load.py`).

## `save_event` / `load_event` — single-file event I/O

`tools/utils.py` saves both output paths (response + track hits) for an event
into **one** HDF5 file, appending events as `/event_{idx}/` groups, with the
detector config written once at the root:

```python
from tools.utils import save_event, load_event, list_events

# Save (creates the file, or appends this event to an existing one)
save_event('run.h5', event_idx, sparse_output, track_hits, detector_config)

# Load one event back
sparse_output, track_hits, config = load_event('run.h5', event_idx)

list_events('run.h5') # -> sorted event indices in the file
```

The file layout is:

```text
/config/
num_wires_actual (2, 3) int32
min_wire_indices (2, 3) int32
attrs: num_time_steps, electrons_per_adc
/event_{idx}/
response/{plane}/ indices (N,2), values (N,), signal (N_s,)
hits/{plane}/ hits_by_track (H,3), track_boundaries (T,), track_ids (T,)
```

This is a convenience wrapper for interactive work: quick single-file
save/reload of a handful of events without standing up the batch pipeline or its
threaded save workers, CSR encoding, and multi-file layout.

### The 2-volume U/V/Y limitation

Both `save_event` and `load_event` key planes through a hardcoded lookup,
`_PLANE_NAMES`, that only knows the standard **2-volume, 3-plane (U/V/Y)**
detector:

```python
_PLANE_NAMES = {
(0, 0): 'vol0_U', (0, 1): 'vol0_V', (0, 2): 'vol0_Y',
(1, 0): 'vol1_U', (1, 1): 'vol1_V', (1, 2): 'vol1_Y',
}
```

!!! warning "`save_event` KeyErrors on any non-U/V/Y geometry"
`save_event` looks up `_PLANE_NAMES[(vol_idx, plane_idx)]` for every plane
in its input. Any `(vol_idx, plane_idx)` outside the six pairs above — a
third volume, a pixel volume, a detector with more or fewer planes — raises
`KeyError`. `load_event` iterates the fixed name→key map, so it silently
reads back only U/V/Y planes even if others were somehow written. There is a
general `get_plane_name(vol_idx, plane_idx, plane_names)` helper in the same
module, but `save_event`/`load_event` do **not** use it — they are hardwired
to the 2-volume layout. For any other geometry, use the production pipeline.
The former single-file `tools.utils.save_event` / `load_event` / `list_events`
were removed: they expected keys no current output produces and only supported
the 2-volume U/V/Y detector.

## `save_sce_data` / `load_sce_data` — SCE map I/O

The same module carries a small per-volume space-charge-effect (SCE) map format,
independent of the event I/O above:
`tools/utils.py` carries a small per-volume space-charge-effect (SCE) map format:

```python
from tools.utils import save_sce_data, load_sce_data
Expand All @@ -89,21 +26,10 @@ volume_data = load_sce_data('sce.h5') # list of per-volume dicts

Each volume is stored under `volume_{i}/` with `efield_map` and
`drift_correction_map` (both `(Nx, Ny, Nz, 3)` float32), plus `origin_cm` and
`spacing_cm`. Optional `metadata` is written as file-level attributes. This
format is not tied to the 2-volume limitation of the event I/O — it stores an
arbitrary list of volumes.
`spacing_cm`. Optional `metadata` is written as file-level attributes. Any number of
volumes is supported.

`save_sce_data` / `load_sce_data` are used by the test suite
(`tests/test_efield_distortions.py`) and are the intended interchange format for
the planned SCE-map port. See [Space charge effects](../physics/sce.md).

## When to use which

- **`tools/utils.py` event I/O** — quick interactive save/reload of a few events
from the **default 2-volume wire detector**, in a notebook or script, when you
don't want the batch machinery. Never for production or non-U/V/Y geometry.
- **`tools/utils.py` SCE I/O** — reading/writing SCE map files (tests, SCE port).
- **`production/save.py` + `load.py`** — everything else: batch runs, the
`sensor`/`step`/`hits` schemas that downstream ML tooling reads, any N-volume
or pixel geometry, and compressed/CSR-encoded output. See
[Production data formats](../production/data-formats.md).
3 changes: 2 additions & 1 deletion docs/physics/electronics-noise.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,8 @@ the host `add_noise(..., coherent=True)`).

!!! note "`include_noise` is a deprecated alias"
The live flags are `include_intrinsic_noise` and `include_coherent_noise`.
`include_noise` remains only as a back-compat alias — prefer the explicit
`include_noise` remains only as a back-compat alias and emits a
`DeprecationWarning` — use the explicit
flags so the two components are toggled independently.

## Digitization
Expand Down
4 changes: 0 additions & 4 deletions docs/reference/api/differentiable.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,3 @@ gradient-based fits (see [Differentiable](../../differentiable/overview.md)).
## Particle generation

::: tools.particle_generator

## NN utilities

::: tools.nn_utils
4 changes: 0 additions & 4 deletions docs/reference/api/response.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,3 @@ format conversion.
## Output formats

::: tools.output

## Sparse utilities

::: tools.sparse_utils
16 changes: 0 additions & 16 deletions docs/truth/track-hits.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,22 +121,6 @@ track)`, and finds the dominant track per sensor cell — returning
Doing the label step off-GPU keeps peak device memory down (call it after moving
`response_signals` off the GPU).

!!! note "Name collision: method vs module function"
There is **also** a module-level `finalize_track_hits`
(`tools/track_hits.py:572`). It is a **name-collision duplicate** — only
stale-imported by one test, *not* the production entry point. Always use the
`DetectorSimulator.finalize_track_hits` **method**. (PLAN §8b flags this for
later de-duplication.)

## Legacy standalone trio (reference / test-only)

`track_hits.py` also carries an older, self-contained labeling path:
`group_hits_by_track` (`:85`) / `label_hits` (`:206`) / `sparse_hits_to_dense`
(`:384`). This trio uses a `K_wire × K_time` neighbor system and is **not used
by the simulator** — the module docstring marks it kept "for out-of-pipeline use
and tests." Do not mistake it for the production API; the box/merge +
`label_from_groups` path above is what `process_event` actually runs.

## End to end

```python
Expand Down
2 changes: 1 addition & 1 deletion production/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ Sparse thresholded raw readout after full detector simulation.
attrs: dataset_name, source_file, n_events, global_event_offset,
num_time_steps, time_step_us, electrons_per_adc,
velocity_cm_us, lifetime_us, recombination_model,
include_noise, include_electronics, include_digitize,
include_intrinsic_noise, include_electronics, include_digitize,
threshold_adc, n_bits (if digitized)
num_wires (2, 3) int32
pedestals (2, 3) int32 per-plane pedestal (if digitized)
Expand Down
23 changes: 0 additions & 23 deletions tests/TESTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,29 +96,6 @@ Detector geometry parsing (`tools/geometry.py`).
| Missing YAML returns None | Non-existent file handled gracefully |
| Incomplete YAML returns None | Missing required keys handled gracefully |

### test_track_hits.py (5 tests)

Track hit labeling (`tools/track_hits.py`).

| Test | What it checks |
|------|----------------|
| Single track aggregation | 5 hits same location sum to total charge |
| Threshold filtering | Hits below threshold removed |
| Multiple tracks separated | 3 distinct tracks counted correctly |
| Dominant track labeling | Highest-charge track wins at shared location |
| Sparse hits to dense | Known hits produce correct dense array |

### test_sparse_utils.py (4 tests)

Dense/sparse conversion (`tools/sparse_utils.py`).

| Test | What it checks |
|------|----------------|
| Dense-sparse-dense roundtrip | Exact reconstruction |
| Threshold filtering | Only |value| > threshold kept, sign preserved |
| Duplicate index accumulation | Same (wire, time) values summed |
| Empty sparse array | Produces all-zero dense output |

### test_noise.py (11 tests)

Noise generation and threshold analysis (`tools/noise.py`).
Expand Down
4 changes: 2 additions & 2 deletions tests/test_noise.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ def sim_config(self):
from tools.geometry import generate_detector
from tools.simulation import DetectorSimulator
det = generate_detector(config_path)
sim = DetectorSimulator(det, include_noise=False, include_electronics=False,
sim = DetectorSimulator(det, include_intrinsic_noise=False, include_electronics=False,
include_track_hits=False)
return sim.config

Expand Down Expand Up @@ -227,7 +227,7 @@ def test_add_noise_coherent_tag(self, ):
from tools.simulation import DetectorSimulator
from tools.noise import add_noise
det = generate_detector(config_path)
sim = DetectorSimulator(det, include_noise=False,
sim = DetectorSimulator(det, include_intrinsic_noise=False,
include_electronics=False,
include_track_hits=False)
cfg = sim.config
Expand Down
22 changes: 19 additions & 3 deletions tests/test_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,12 +104,28 @@ def test_dense_sparse_roundtrip(self, mock_config):
sparse = to_sparse(signals, mock_config)

# Reconstruct dense from sparse
sp = sparse[(0, 0)]
reconstructed = np.zeros_like(arr)
reconstructed[sp['wire'], sp['time']] = sp['values']
reconstructed = to_dense(sparse, mock_config)[(0, 0)]

np.testing.assert_array_equal(reconstructed, arr)

def test_threshold_keeps_sign(self, mock_config):
"""threshold_adc filters on |value| (inclusive) and keeps the sign."""
arr = np.zeros((100, 200), dtype=np.float32)
arr[0, :5] = [0.5, 1.0, 2.0, 3.0, -2.5]
sp = to_sparse({(0, 0): arr}, mock_config, threshold_adc=2.0)[(0, 0)]
np.testing.assert_array_equal(np.sort(sp['values']), [-2.5, 2.0, 3.0])

def test_wire_sparse_dict_to_dense_sums_duplicates(self, mock_config):
"""Duplicate (wire, time) entries accumulate; empty input gives zeros."""
sp = {'wire': np.array([1, 1, 3], np.int32), 'time': np.array([2, 2, 4], np.int32),
'values': np.array([1.0, 2.0, 5.0], np.float32)}
d = to_dense({(0, 2): sp}, mock_config)[(0, 2)]
assert d.shape == (80, 200)
assert d[1, 2] == 3.0 and d[3, 4] == 5.0 and d.sum() == 8.0
empty = {'wire': np.array([], np.int32), 'time': np.array([], np.int32),
'values': np.array([], np.float32)}
assert not to_dense({(0, 0): empty}, mock_config)[(0, 0)].any()


class TestBucketedToDense:
"""Test to_dense conversion from bucketed 5-tuple format."""
Expand Down
Loading
Loading