diff --git a/CLAUDE.md b/CLAUDE.md index 8d4b301..ea89dd7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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 diff --git a/README.md b/README.md index 5b08add..aa51151 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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 | diff --git a/docs/PLAN.md b/docs/PLAN.md index bad1adc..27b127a 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -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 @@ -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). @@ -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. --- @@ -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). --- diff --git a/docs/contributing/io-formats-internal.md b/docs/contributing/io-formats-internal.md index c2cf29d..aa9e072 100644 --- a/docs/contributing/io-formats-internal.md +++ b/docs/contributing/io-formats-internal.md @@ -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 @@ -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). diff --git a/docs/physics/electronics-noise.md b/docs/physics/electronics-noise.md index 4c56661..2243d62 100644 --- a/docs/physics/electronics-noise.md +++ b/docs/physics/electronics-noise.md @@ -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 diff --git a/docs/reference/api/differentiable.md b/docs/reference/api/differentiable.md index 63c1df9..2457053 100644 --- a/docs/reference/api/differentiable.md +++ b/docs/reference/api/differentiable.md @@ -10,7 +10,3 @@ gradient-based fits (see [Differentiable](../../differentiable/overview.md)). ## Particle generation ::: tools.particle_generator - -## NN utilities - -::: tools.nn_utils diff --git a/docs/reference/api/response.md b/docs/reference/api/response.md index b5bf008..468536b 100644 --- a/docs/reference/api/response.md +++ b/docs/reference/api/response.md @@ -14,7 +14,3 @@ format conversion. ## Output formats ::: tools.output - -## Sparse utilities - -::: tools.sparse_utils diff --git a/docs/truth/track-hits.md b/docs/truth/track-hits.md index e91486d..0523ea6 100644 --- a/docs/truth/track-hits.md +++ b/docs/truth/track-hits.md @@ -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 diff --git a/production/README.md b/production/README.md index 2275b6b..dd9bf1a 100644 --- a/production/README.md +++ b/production/README.md @@ -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) diff --git a/tests/TESTS.md b/tests/TESTS.md index bdd4f21..834cabe 100644 --- a/tests/TESTS.md +++ b/tests/TESTS.md @@ -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`). diff --git a/tests/test_noise.py b/tests/test_noise.py index f90a5d2..b757083 100644 --- a/tests/test_noise.py +++ b/tests/test_noise.py @@ -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 @@ -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 diff --git a/tests/test_output.py b/tests/test_output.py index 1930619..170ba50 100644 --- a/tests/test_output.py +++ b/tests/test_output.py @@ -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.""" diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py index cc04aa7..07649d8 100644 --- a/tests/test_pipeline.py +++ b/tests/test_pipeline.py @@ -44,7 +44,7 @@ def sim(detector_config): """Dense + track_hits simulator. Shared across all tests.""" return DetectorSimulator( detector_config, total_pad=200_000, response_chunk_size=50_000, - use_bucketed=False, include_noise=False, include_electronics=False, + use_bucketed=False, include_intrinsic_noise=False, include_electronics=False, include_track_hits=True, include_digitize=False) @@ -193,7 +193,7 @@ def sim_bucketed(self, detector_config): return DetectorSimulator( detector_config, total_pad=200_000, response_chunk_size=50_000, use_bucketed=True, max_active_buckets=1000, - include_noise=False, include_electronics=False, + include_intrinsic_noise=False, include_electronics=False, include_track_hits=False, include_digitize=False) def test_dense_equals_bucketed(self, sim, sim_bucketed, sim_results): @@ -241,7 +241,7 @@ def synthetic_sim(self): det = generate_detector(CONFIG_PATH) return DetectorSimulator( det, total_pad=500, response_chunk_size=500, - include_track_hits=False, include_noise=False, + include_track_hits=False, include_intrinsic_noise=False, include_electronics=False, include_digitize=False) @pytest.fixture(scope="class") diff --git a/tests/test_pipeline_forward.py b/tests/test_pipeline_forward.py index 5616a90..3e6d05e 100644 --- a/tests/test_pipeline_forward.py +++ b/tests/test_pipeline_forward.py @@ -174,7 +174,7 @@ class TestForwardVsProduction: def test_signals_match(self, detector_config, raw): sim_prod = DetectorSimulator( detector_config, total_pad=N, response_chunk_size=N, - include_track_hits=False, include_noise=False, + include_track_hits=False, include_intrinsic_noise=False, include_electronics=False, include_digitize=False) deps_prod = build_deposit_data( diff --git a/tests/test_pixel_post_response_truth.py b/tests/test_pixel_post_response_truth.py index 5b20671..e05d9b7 100644 --- a/tests/test_pixel_post_response_truth.py +++ b/tests/test_pixel_post_response_truth.py @@ -19,7 +19,6 @@ from tools.loader import build_deposit_data from tools.config import create_track_hits_config from tools.output import to_sparse, _detect_format -from tools.track_hits import finalize_track_hits # Heavy integration test: runs a full native-resolution (1000x1000) pixel diff --git a/tests/test_sparse_utils.py b/tests/test_sparse_utils.py deleted file mode 100644 index c991587..0000000 --- a/tests/test_sparse_utils.py +++ /dev/null @@ -1,61 +0,0 @@ -""" -Tests for dense/sparse conversion utilities. - -File under test: tools/sparse_utils.py -""" - -import numpy as np -import jax.numpy as jnp -import pytest -from tools.sparse_utils import dense_to_sparse, sparse_to_dense - - -class TestDenseToSparseRoundtrip: - """Tests for dense ↔ sparse conversions.""" - - def test_roundtrip(self): - """dense → sparse → dense should reproduce the original array.""" - rng = np.random.RandomState(10) - num_wires, num_time = 50, 100 - dense = jnp.array(rng.randn(num_wires, num_time).astype(np.float32)) - - indices, values = dense_to_sparse(dense, threshold=0.0) - reconstructed = sparse_to_dense(indices, values, num_wires, num_time) - - np.testing.assert_allclose(np.array(reconstructed), np.array(dense), rtol=1e-5) - - def test_threshold_filtering(self): - """Threshold should filter by absolute value but preserve sign.""" - dense = jnp.array([[0.5, 1.0, 2.5, 3.0, -2.5]], dtype=jnp.float32) - - indices, values = dense_to_sparse(dense, threshold=2.0) - - # Only |v| > 2.0 kept: 2.5, 3.0, -2.5 - assert len(values) == 3, f"Expected 3 entries above threshold, got {len(values)}" - # Verify sign is preserved - vals_sorted = np.sort(np.array(values)) - assert vals_sorted[0] < 0, "Negative value should be preserved" - - -class TestSparseAccumulation: - """Tests for sparse_to_dense accumulation behavior.""" - - def test_duplicate_index_accumulation(self): - """Duplicate (wire, time) indices should have values summed.""" - indices = jnp.array([[1, 2], [1, 2], [3, 4]], dtype=jnp.int32) - values = jnp.array([1.0, 2.0, 5.0], dtype=jnp.float32) - - dense = sparse_to_dense(indices, values, num_wires=5, num_time_steps=6) - - assert float(dense[1, 2]) == 3.0, "Duplicate indices should sum: 1.0 + 2.0 = 3.0" - assert float(dense[3, 4]) == 5.0 - - def test_empty_sparse_array(self): - """Empty sparse arrays should produce all-zero dense output.""" - indices = jnp.empty((0, 2), dtype=jnp.int32) - values = jnp.empty((0,), dtype=jnp.float32) - - dense = sparse_to_dense(indices, values, num_wires=10, num_time_steps=20) - - assert jnp.all(dense == 0.0), "Empty sparse should give all-zero dense" - assert dense.shape == (10, 20) diff --git a/tests/test_track_hits.py b/tests/test_track_hits.py deleted file mode 100644 index bfd9431..0000000 --- a/tests/test_track_hits.py +++ /dev/null @@ -1,116 +0,0 @@ -""" -Tests for track hit labeling module. - -File under test: tools/track_hits.py -""" - -import numpy as np -import jax -import jax.numpy as jnp -import pytest -from tools.track_hits import group_hits_by_track, label_hits, sparse_hits_to_dense - - -class TestGroupHitsByTrack: - """Tests for group_hits_by_track.""" - - def test_single_track_aggregation(self): - """5 hits at same (wire, time) from same track → one entry, charge=sum.""" - wire_time = jnp.array([[10, 20]] * 5, dtype=jnp.int32) - track_ids = jnp.array([1, 1, 1, 1, 1], dtype=jnp.int32) - charges = jnp.array([1.0, 2.0, 3.0, 4.0, 5.0]) - - hits, num_hits, boundaries, num_tracks, track_ids_out = group_hits_by_track( - wire_time, track_ids, charges, - min_charge_threshold=0.0, - max_tracks=100, max_wires=100, max_time=100, max_keys=1000) - jax.block_until_ready(hits) - - # Should have exactly 1 unique entry - assert int(num_hits) == 1 - # Total charge should be sum - np.testing.assert_allclose(float(hits[0, 2]), 15.0, rtol=1e-4) - - def test_threshold_filtering(self): - """Hits with total charge below threshold should be removed.""" - wire_time = jnp.array([[10, 20], [30, 40]], dtype=jnp.int32) - track_ids = jnp.array([1, 2], dtype=jnp.int32) - charges = jnp.array([0.5, 5.0]) # First below threshold=1.0 - - hits, num_hits, _, _, _ = group_hits_by_track( - wire_time, track_ids, charges, - min_charge_threshold=1.0, - max_tracks=100, max_wires=100, max_time=100, max_keys=1000) - jax.block_until_ready(hits) - - assert int(num_hits) == 1, f"Expected 1 hit above threshold, got {int(num_hits)}" - - def test_multiple_tracks_separated(self): - """3 tracks at distinct locations should produce num_tracks=3.""" - wire_time = jnp.array([ - [10, 20], [10, 20], # Track 1 - [30, 40], [30, 40], # Track 2 - [50, 60], # Track 3 - ], dtype=jnp.int32) - track_ids = jnp.array([1, 1, 2, 2, 3], dtype=jnp.int32) - charges = jnp.array([1.0, 2.0, 3.0, 4.0, 5.0]) - - hits, num_hits, boundaries, num_tracks, track_ids_out = group_hits_by_track( - wire_time, track_ids, charges, - min_charge_threshold=0.0, - max_tracks=100, max_wires=100, max_time=100, max_keys=1000) - jax.block_until_ready(hits) - - assert int(num_tracks) == 3, f"Expected 3 tracks, got {int(num_tracks)}" - assert int(num_hits) == 3, f"Expected 3 unique hits, got {int(num_hits)}" - - -class TestLabelHits: - """Tests for label_hits (dominant track labeling).""" - - def test_dominant_track_labeling(self): - """Two tracks at same location → label = highest charge track.""" - wire_time = jnp.array([ - [10, 20], # Track 1, charge 2.0 - [10, 20], # Track 2, charge 5.0 (dominant) - ], dtype=jnp.int32) - track_ids = jnp.array([1, 2], dtype=jnp.int32) - charges = jnp.array([2.0, 5.0]) - - hits, num_hits, boundaries, num_tracks, track_ids_out = group_hits_by_track( - wire_time, track_ids, charges, - min_charge_threshold=0.0, - max_tracks=100, max_wires=100, max_time=100, max_keys=1000) - jax.block_until_ready(hits) - - labeled, num_labeled = label_hits( - hits, int(num_hits), track_ids_out, boundaries, int(num_tracks), - max_keys=1000, max_time=100) - jax.block_until_ready(labeled) - - # Should have 1 unique (wire, time) with track_id = 2 (dominant) - assert int(num_labeled) == 1 - assert int(labeled[0, 0]) == 2, f"Expected track 2 as dominant, got {int(labeled[0, 0])}" - - -class TestSparseHitsToDense: - """Tests for sparse_hits_to_dense.""" - - def test_sparse_hits_to_dense(self): - """Known hits should produce correct dense array values.""" - hits_by_track = jnp.zeros((100, 3)) - hits_by_track = hits_by_track.at[0].set(jnp.array([5, 10, 3.0])) - hits_by_track = hits_by_track.at[1].set(jnp.array([7, 15, 2.0])) - hits_by_track = hits_by_track.at[2].set(jnp.array([5, 10, 1.0])) # Same location - - track_result = { - 'hits_by_track': hits_by_track, - 'num_hits': 3, - } - - dense = sparse_hits_to_dense(track_result, num_wires=20, num_time_steps=30) - - # (5, 10) should have 3.0 + 1.0 = 4.0 - np.testing.assert_allclose(float(dense[5, 10]), 4.0, rtol=1e-4) - np.testing.assert_allclose(float(dense[7, 15]), 2.0, rtol=1e-4) - assert float(dense[0, 0]) == 0.0 diff --git a/tools/config.py b/tools/config.py index 95f1d83..a88ed77 100644 --- a/tools/config.py +++ b/tools/config.py @@ -79,7 +79,6 @@ class TrackHitsConfig(NamedTuple): ``corr_threshold``) are interpreted in ENC for wire and ADC for pixel — same field, different units. """ - threshold: float # Minimum charge to keep (legacy; not used in production) max_tracks: int # Max tracks for array pre-allocation max_keys: int # Max unique (track, wire, time) combinations (merge path) hits_chunk_size: int # Deposits per fori_loop chunk (must divide padding tiers) @@ -223,7 +222,6 @@ def create_digitization_config( def create_track_hits_config( - threshold: float = 1.0, max_tracks: int = 10000, max_keys: int = 4000000, hits_chunk_size: int = 25000, @@ -243,7 +241,6 @@ def create_track_hits_config( (see tools.track_hits.compute_box_dims). Pass explicit ints to override. """ return TrackHitsConfig( - threshold=threshold, max_tracks=max_tracks, max_keys=max_keys, hits_chunk_size=hits_chunk_size, diff --git a/tools/loader.py b/tools/loader.py index 67be3f2..1ef90bf 100644 --- a/tools/loader.py +++ b/tools/loader.py @@ -505,33 +505,6 @@ def load_event(file_path, sim_config, event_idx=0, verbose=False, group_size=group_size, gap_threshold_mm=gap_threshold_mm) -def main(): - """Example usage of the particle step extractor.""" - import argparse - - parser = argparse.ArgumentParser(description='Extract particle step data from HDF5 files') - parser.add_argument('file_path', help='Path to the HDF5 file') - parser.add_argument('--event', '-e', type=int, default=0, help='Event index (default: 0)') - parser.add_argument('--verbose', '-v', action='store_true', help='Print verbose information') - - args = parser.parse_args() - - raw = load_particle_step_data(args.file_path, args.event, args.verbose) - - n_segments = raw['positions_mm'].shape[0] - n_tracks = len(np.unique(raw['track_ids'])) - total_de = float(np.sum(raw['de'])) - - print(f"\nLoaded particle step data:") - print(f" Segments: {n_segments:,}") - print(f" Unique tracks: {n_tracks}") - print(f" Total dE: {total_de:.2f} MeV") - print(f"\nFields:") - for key, arr in raw.items(): - if hasattr(arr, 'shape'): - print(f" {key}: shape={arr.shape}, dtype={arr.dtype}") - - # ============================================================================= # GROUP ID ASSIGNMENT (numpy host-side, before split) # ============================================================================= @@ -822,7 +795,3 @@ def _pad(arr, n_use, pad_val=0): group_to_track=tuple(vol_group_to_track), original_indices=tuple(vol_original_indices), ) - - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/tools/nn_utils.py b/tools/nn_utils.py deleted file mode 100644 index c660512..0000000 --- a/tools/nn_utils.py +++ /dev/null @@ -1,52 +0,0 @@ -""" -NN inference utilities for JAXTPC simulation. - -Extracted from siren_response_training/ to avoid runtime dependency on -training code. Contains transforms and kernel operations needed at inference. -""" - -import jax.numpy as jnp - - -def inv_symlog(x, eps=1e-10): - """Inverse symlog transform: symlog(y) = sign(y) * log(|y| + eps). - - inv_symlog(x) = sign(x) * (exp(|x|) - eps) - """ - return jnp.sign(x) * (jnp.exp(jnp.abs(x)) - eps) - - -def unfold_kernel(folded): - """Mirror folded kernel to full width using wire symmetry. - - Parameters - ---------- - folded : (N, H, half_W) or (H, half_W) - Folded kernel (right half including center wire). - - Returns - ------- - full : (N, H, 2*half_W - 1) or (H, 2*half_W - 1) - Full symmetric kernel. - """ - # Left half is the mirror of folded[:, :, 1:] (excluding center to avoid duplication) - left_half = jnp.flip(folded[..., 1:], axis=-1) - return jnp.concatenate([left_half, folded], axis=-1) - - -def normalize_positions(positions_cm, origin_cm, extent_cm): - """Map physical coordinates to [0,1]^3 for NN input. - - Parameters - ---------- - positions_cm : (N, 3) positions in cm - origin_cm : (3,) or tuple, lower corner of normalization box - extent_cm : (3,) or tuple, size of normalization box - - Returns - ------- - normalized : (N, 3) in [0,1]^3 - """ - origin = jnp.array(origin_cm) - extent = jnp.array(extent_cm) - return (positions_cm - origin) / extent diff --git a/tools/output.py b/tools/output.py index 4c0202e..e76e8f1 100644 --- a/tools/output.py +++ b/tools/output.py @@ -99,6 +99,14 @@ def to_dense(response_signals, config): np.add.at(dense, (py, pz, t), v_arr) output[(vol_idx, plane_idx)] = dense + elif fmt == 'wire_sparse_dict': + # The wire output of to_sparse(); duplicate (wire, time) entries sum. + num_wires = vol.num_wires[plane_idx] + dense = np.zeros((num_wires, num_time), dtype=np.float32) + np.add.at(dense, (np.asarray(signal['wire']), np.asarray(signal['time'])), + np.asarray(signal['values'])) + output[(vol_idx, plane_idx)] = dense + elif fmt == 'wire_sparse': active_signals, wire_indices, n_active = signal num_wires = vol.num_wires[plane_idx] diff --git a/tools/simulation.py b/tools/simulation.py index e525d2b..774659c 100644 --- a/tools/simulation.py +++ b/tools/simulation.py @@ -108,6 +108,9 @@ def __init__( print("--- Creating DetectorSimulator ---") if include_noise is not None: + import warnings + warnings.warn("include_noise is deprecated; use include_intrinsic_noise", + DeprecationWarning, stacklevel=2) include_intrinsic_noise = include_noise # Detect readout type early (needed for pixel-specific defaults) @@ -419,7 +422,10 @@ def response_fn(positions_cm, drift_distance_cm, dkernel, s_values, py_offsets, pz_offsets, time_offsets, pk.pixel_spacing, pk.kernel_py, pk.kernel_pz, pk.rebin_factor) return response_fn - _build_response_fn_diff = _build_response_fn # TODO: pixel diff response + def _build_response_fn_diff(sim_params, plane_type): + # Unreachable: __init__ rejects differentiable=True for pixel readout. + raise NotImplementedError( + "differentiable=True is not supported for pixel readout") else: def _build_response_fn(sim_params, plane_type): kernel = kernels[plane_type] diff --git a/tools/sparse_utils.py b/tools/sparse_utils.py deleted file mode 100644 index 1af061a..0000000 --- a/tools/sparse_utils.py +++ /dev/null @@ -1,143 +0,0 @@ -""" -Sparse utilities for converting between dense, bucket, and truly sparse formats. - -This module provides functions for converting wire signals between different -storage formats: dense arrays, sparse buckets, and truly sparse (indices, values). - -Truly sparse format: - - indices: (N, 2) int32 array with [wire_idx, time_idx] per row - - values: (N,) float32 array with signal values -""" - -import jax.numpy as jnp -import numpy as np - - -def dense_to_sparse(dense_array, threshold=0.0): - """ - Convert dense (num_wires, num_time_steps) array to sparse format. - - Parameters - ---------- - dense_array : jnp.ndarray - Array of shape (num_wires, num_time_steps) containing signal values. - threshold : float, optional - Only include values with |value| > threshold (keeps sign), by default 0.0. - - Returns - ------- - indices : jnp.ndarray - Array of shape (N, 2) with [wire_idx, time_idx] per row. - values : jnp.ndarray - Array of shape (N,) with signal values (preserves sign). - """ - # Use absolute value for threshold check, but keep original signed values - mask = jnp.abs(dense_array) > threshold - wire_indices, time_indices = jnp.where(mask) - indices = jnp.stack([wire_indices, time_indices], axis=1) - values = dense_array[mask] - return indices.astype(jnp.int32), values.astype(jnp.float32) - - -def sparse_buckets_to_sparse(buckets, compact_to_key, num_active, - B1, B2, num_wires, num_time_steps, - threshold=0.0): - """ - Convert sparse buckets format directly to truly sparse (indices, values). - - Parameters - ---------- - buckets : jnp.ndarray - Array of shape (max_buckets, B1, B2) containing bucket data. - compact_to_key : jnp.ndarray - Array of shape (max_buckets,) mapping compact index to bucket keys. - num_active : int - Number of active buckets. - B1 : int - Bucket dimension in wire direction. - B2 : int - Bucket dimension in time direction. - num_wires : int - Total number of wires in detector. - num_time_steps : int - Total number of time steps in detector. - threshold : float, optional - Only include values with |value| > threshold (keeps sign), by default 0.0. - - Returns - ------- - indices : jnp.ndarray - Array of shape (N, 2) with [wire_idx, time_idx] per row. - values : jnp.ndarray - Array of shape (N,) with signal values (preserves sign). - """ - NUM_BUCKETS_T = (num_time_steps + B2 - 1) // B2 - - all_indices = [] - all_values = [] - - for i in range(int(num_active)): - key = int(compact_to_key[i]) - bucket_w = key // NUM_BUCKETS_T - bucket_t = key % NUM_BUCKETS_T - - w_start = bucket_w * B1 - t_start = bucket_t * B2 - - bucket_data = np.array(buckets[i]) - # Use absolute value for threshold check, but keep original signed values - mask = np.abs(bucket_data) > threshold - local_w, local_t = np.where(mask) - - global_w = w_start + local_w - global_t = t_start + local_t - - # Filter to valid detector range - valid = (global_w < num_wires) & (global_t < num_time_steps) - - if np.any(valid): - all_indices.append(np.stack([global_w[valid], global_t[valid]], axis=1)) - all_values.append(bucket_data[mask][valid]) - - if all_indices: - indices = np.concatenate(all_indices, axis=0) - values = np.concatenate(all_values, axis=0) - else: - indices = np.empty((0, 2), dtype=np.int32) - values = np.empty((0,), dtype=np.float32) - - return jnp.array(indices, dtype=jnp.int32), jnp.array(values, dtype=jnp.float32) - - -def sparse_to_dense(indices, values, num_wires, num_time_steps): - """ - Convert sparse (indices, values) format to dense array using .at.add. - - Parameters - ---------- - indices : jnp.ndarray - Array of shape (N, 2) with [wire_idx, time_idx] per row. - values : jnp.ndarray - Array of shape (N,) with signal values. - num_wires : int - Number of wires in output array. - num_time_steps : int - Number of time steps in output array. - - Returns - ------- - dense : jnp.ndarray - Array of shape (num_wires, num_time_steps) with accumulated values. - """ - dense = jnp.zeros((num_wires, num_time_steps), dtype=jnp.float32) - - if len(indices) == 0: - return dense - - wire_idx = indices[:, 0] - time_idx = indices[:, 1] - - # Use .at.add to handle duplicate indices (sum contributions) - dense = dense.at[wire_idx, time_idx].add(values) - - return dense diff --git a/tools/track_hits.py b/tools/track_hits.py index bdb8d39..11424f2 100644 --- a/tools/track_hits.py +++ b/tools/track_hits.py @@ -11,9 +11,6 @@ box mode (``create_track_hits_fn``) scatter-adds into the box and labels host-side via ``label_from_groups``; the non-default merge mode instead runs ``merge_chunk_sensor_hits`` before ``label_from_groups``. -A legacy standalone path (``group_hits_by_track`` / ``label_hits`` / -``sparse_hits_to_dense``, using a K_wire x K_time neighbor system) is kept for -out-of-pipeline use and tests; it is NOT used by the simulator. The track labeling runs alongside the main simulation to provide particle attribution data for physics analysis. @@ -81,219 +78,6 @@ def compute_box_dims(volumes, time_step_us, readout_type, group_size, ) -@partial(jax.jit, static_argnames=['max_tracks', 'max_wires', 'max_time', 'max_keys']) -def group_hits_by_track(wire_time_indices, track_ids, charge_deposits, - min_charge_threshold=0.0, - max_tracks=10000, max_wires=2000, max_time=2000, - max_keys=1000000): - """ - Aggregate charge deposits by track and location for LArTPC simulation data. - - Standalone function for direct use outside the simulation pipeline. - NOT used by create_track_hits_fn (which uses the chunk-merge path instead). - - IMPORTANT: All static sizes must be set correctly by the caller: - - max_tracks: must be >= number of unique track IDs in the input - - max_wires: must be >= max wire index in wire_time_indices - - max_time: must be >= max time index in wire_time_indices - - max_keys: must be >= number of unique (track, wire, time) combinations - If any are too small, results will be silently truncated. Check num_hits - and num_tracks in the output against these limits. - - Parameters - ---------- - wire_time_indices : jnp.ndarray, shape (N, 2) - Wire and time indices for each charge deposit. - track_ids : jnp.ndarray, shape (N,) - Track ID for each charge deposit. - charge_deposits : jnp.ndarray, shape (N,) - Charge value for each deposit. - min_charge_threshold : float - Minimum charge to keep a hit (default: 0.0). - max_tracks : int - Maximum number of tracks (static). Must be >= unique track count. - max_wires : int - Maximum number of wires (static). Must be >= max wire index. - max_time : int - Maximum time bins (static). Must be >= max time index. - max_keys : int - Maximum number of unique (track, wire, time) combinations (static). - - Returns - ------- - hits_by_track : jnp.ndarray, shape (max_keys, 3) - Aggregated hits [wire, time, charge]. - num_hits : int - Number of unique (track, wire, time) combinations found. - track_boundaries : jnp.ndarray, shape (max_tracks,) - Indices where track boundaries occur in sorted data. - num_tracks : int - Number of track boundaries found. - track_ids_at_boundaries : jnp.ndarray, shape (max_tracks,) - Track IDs at each boundary position. - """ - N = wire_time_indices.shape[0] - - # Step 1: Sort by (track, wire, time) via two-pass stable sort (int32) - # Single composite key overflows int32 when max_wires*max_time*max_tracks > 2^31 - wire_time_key = (wire_time_indices[:, 0].astype(jnp.int32) * max_time + - wire_time_indices[:, 1].astype(jnp.int32)) - _, idx = jax.lax.sort_key_val(wire_time_key, jnp.arange(N, dtype=jnp.int32)) - _, sort_indices = jax.lax.sort_key_val(track_ids[idx], idx) - - sorted_wires = wire_time_indices[sort_indices, 0] - sorted_times = wire_time_indices[sort_indices, 1] - sorted_tracks = track_ids[sort_indices] - sorted_charges = charge_deposits[sort_indices] - - # Step 2: Find boundaries and aggregate - # Boundary when track or (wire,time) changes — avoids int32 overflow in composite key - sorted_wt = sorted_wires.astype(jnp.int32) * max_time + sorted_times.astype(jnp.int32) - key_boundaries = jnp.ones(N, dtype=bool) - key_boundaries = key_boundaries.at[1:].set( - (sorted_tracks[1:] != sorted_tracks[:-1]) | - (sorted_wt[1:] != sorted_wt[:-1]) - ) - - segment_ids = jnp.cumsum(key_boundaries) - 1 - summed_charges = jax.ops.segment_sum(sorted_charges, segment_ids, num_segments=N) - aggregated_charges = summed_charges[segment_ids] - - # Step 3: Apply threshold and extract unique entries - segment_ends = jnp.roll(key_boundaries, -1).at[-1].set(True) - threshold_mask = segment_ends & (aggregated_charges > min_charge_threshold) - - unique_indices = jnp.where(threshold_mask, size=max_keys, fill_value=0)[0] - num_unique = jnp.sum(threshold_mask) - - num_stored = jnp.minimum(num_unique, max_keys) - valid_mask = jnp.arange(max_keys) < num_stored - - # Step 4: Build hits_by_track array (without track column) - hits_by_track = jnp.stack([ - jnp.where(valid_mask, sorted_wires[unique_indices], 0), - jnp.where(valid_mask, sorted_times[unique_indices], 0), - jnp.where(valid_mask, aggregated_charges[unique_indices], 0) - ], axis=1) - - # Step 5: Key boundaries count - num_hits = num_unique - - # Step 6: Track boundaries and track IDs - # Build temporary track array for boundary detection - temp_track_array = jnp.where(valid_mask, sorted_tracks[unique_indices], 0) - track_changes = jnp.ones(max_keys, dtype=bool) - track_changes = track_changes.at[1:].set( - (temp_track_array[1:] != temp_track_array[:-1]) & - (jnp.arange(1, max_keys) < num_stored) - ) - track_boundaries = jnp.where(track_changes, size=max_tracks, fill_value=max_keys)[0] - num_tracks = jnp.sum(track_changes & (jnp.arange(max_keys) < num_stored)) - - # Extract track IDs at boundary positions - track_ids_at_boundaries = jnp.where( - jnp.arange(max_tracks) < num_tracks, - temp_track_array[track_boundaries], - 0 - ) - - return (hits_by_track, num_hits, - track_boundaries, num_tracks, - track_ids_at_boundaries) - - -@partial(jax.jit, static_argnames=['max_keys', 'max_time']) -def label_hits(hits_by_track, num_stored, track_ids_at_boundaries, - track_boundaries, num_tracks, - max_keys=1000000, max_time=2000): - """ - Determine which track owns each pixel based on maximum charge. - - Standalone function — companion to group_hits_by_track. - NOT used by the simulation pipeline's create_track_hits_fn. - - IMPORTANT: max_keys and max_time must match the values used in - group_hits_by_track. If num_stored >= max_keys, the input was - already truncated and results may be incomplete. - - Parameters - ---------- - hits_by_track : jnp.ndarray, shape (max_keys, 3) - Array of aggregated hits [wire, time, total_charge]. - num_stored : int - Number of valid entries in hits_by_track. - track_ids_at_boundaries : jnp.ndarray, shape (max_tracks,) - Track IDs at each boundary position. - track_boundaries : jnp.ndarray, shape (max_tracks,) - Indices where track boundaries occur. - num_tracks : int - Number of valid track boundaries. - max_keys : int - Maximum size of arrays (must match hits_by_track shape). - max_time : int - Maximum time index for creating composite keys. - - Returns - ------- - labeled_hits : jnp.ndarray, shape (max_keys, 4) - Array of labeled hits with highest charge per (wire,time) [track_id, wire, time, charge]. - num_labeled : int - Number of unique (wire,time) locations. - """ - # Rebroadcast track IDs from boundaries using searchsorted - # Each entry belongs to the track segment it falls into - # Use masking to avoid dynamic slicing in JIT - max_tracks_arr = track_boundaries.shape[0] - valid_boundaries_mask = jnp.arange(max_tracks_arr) < num_tracks - masked_boundaries = jnp.where(valid_boundaries_mask, track_boundaries, 1e9) - - boundary_idx = jnp.searchsorted(masked_boundaries, - jnp.arange(max_keys), - side='right') - 1 - boundary_idx = jnp.clip(boundary_idx, 0, jnp.maximum(num_tracks - 1, 0)) - - # Only assign track IDs to valid entries - rebroadcast_track_ids = jnp.where( - jnp.arange(max_keys) < num_stored, - track_ids_at_boundaries[boundary_idx], - 0 - ) - - # Create composite key for (wire, time, -charge) sorting - wire_time_key = hits_by_track[:, 0].astype(jnp.int32) * max_time + hits_by_track[:, 1].astype(jnp.int32) - sort_keys = jnp.stack([wire_time_key, -hits_by_track[:, 2]], axis=1) - sorted_indices = jnp.lexsort((sort_keys[:, 1], sort_keys[:, 0])) - - sorted_hits_by_track = hits_by_track[sorted_indices] - sorted_track_ids = rebroadcast_track_ids[sorted_indices] - - # Mark first occurrence of each (wire, time) - wire_time_first = jnp.ones(max_keys, dtype=bool) - wire_time_first = wire_time_first.at[1:].set( - (sorted_hits_by_track[1:, 0] != sorted_hits_by_track[:-1, 0]) | - (sorted_hits_by_track[1:, 1] != sorted_hits_by_track[:-1, 1]) - ) - - # Only consider valid entries - is_valid_entry = (jnp.arange(max_keys) < num_stored)[sorted_indices] - wire_time_first = wire_time_first & is_valid_entry - - # Extract labeled hits - labeled_indices = jnp.where(wire_time_first, size=max_keys, fill_value=0)[0] - num_labeled = jnp.sum(wire_time_first) - - valid_labeled_mask = jnp.arange(max_keys) < num_labeled - - labeled_hits = jnp.stack([ - jnp.where(valid_labeled_mask, sorted_track_ids[labeled_indices], 0), - jnp.where(valid_labeled_mask, sorted_hits_by_track[labeled_indices, 0], 0), - jnp.where(valid_labeled_mask, sorted_hits_by_track[labeled_indices, 1], 0), - jnp.where(valid_labeled_mask, sorted_hits_by_track[labeled_indices, 2], 0) - ], axis=1) - - return labeled_hits, num_labeled - - def merge_chunk_sensor_hits(state_sk, state_tk, state_gk, state_ch, chunk_sk, chunk_tk, chunk_gk, chunk_ch, inter_thresh): @@ -381,57 +165,6 @@ def merge_chunk_sensor_hits(state_sk, state_tk, state_gk, state_ch, return new_sk, new_tk, new_gk, new_ch, count -def sparse_hits_to_dense(track_hit_result, num_wires, num_time_steps): - """ - Convert sparse track hits to dense 2D array. - - Part of the legacy standalone track-hit path (group_hits_by_track / - label_hits / sparse_hits_to_dense); NOT used by the simulator. - - Uses hits_by_track which contains [wire, time, charge] per hit. - This function should be called OUTSIDE the simulation when dense - hit signals are needed for visualization. - - Parameters - ---------- - track_hit_result : dict - Output from track labeling containing: - - 'hits_by_track': jnp.ndarray, shape (max_keys, 3) with [wire, time, charge] - - 'num_hits': int, number of valid entries - num_wires : int - Number of wires in the output array. - num_time_steps : int - Number of time steps in the output array. - - Returns - ------- - dense : jnp.ndarray, shape (num_wires, num_time_steps) - Dense 2D array of accumulated charges. - """ - hits_by_track = track_hit_result['hits_by_track'] - num_hits = track_hit_result['num_hits'] - - # Initialize dense array - dense = jnp.zeros((num_wires, num_time_steps), dtype=jnp.float32) - - # Get valid hits - num_valid = int(num_hits) - if num_valid > 0: - valid_hits = hits_by_track[:num_valid] - wire_indices = valid_hits[:, 0].astype(jnp.int32) - time_indices = valid_hits[:, 1].astype(jnp.int32) - charges = valid_hits[:, 2] - - # Clip indices to valid range - wire_indices = jnp.clip(wire_indices, 0, num_wires - 1) - time_indices = jnp.clip(time_indices, 0, num_time_steps - 1) - - # Accumulate charges - dense = dense.at[wire_indices, time_indices].add(charges) - - return dense - - def label_from_groups(state_sk, state_tk, state_gk, state_ch, state_count, group_to_track, decode_spatial_fn=None): """Derive track hits from group merge state (postprocessing, outside JIT). @@ -569,59 +302,6 @@ def label_from_groups(state_sk, state_tk, state_gk, state_ch, state_count, } -def finalize_track_hits(track_hits, decode_fns=None): - """Derive track labels from raw group merge state. - - NOTE: the production entry point is the ``DetectorSimulator.finalize_track_hits`` - method (tools/simulation.py), which is what callers use. This module-level - function is standalone (test-only) and not invoked by the simulator. - - Applies label_from_groups to each plane's raw - (sk, tk, gk, ch, count, row_sums) 6-tuple. The group_to_track - lookup is stored in track_hits['group_to_track']. - - Call after moving response_signals off GPU to avoid memory pressure. - - Parameters - ---------- - track_hits : dict - From process_event(). Plane keys map to raw 6-tuples. - Contains 'group_to_track' metadata key. - decode_fns : dict, optional - Maps plane_key → decode_spatial_fn for label_from_groups. - If None, uses default wire decode (spatial_key = wire_idx). - - Returns - ------- - track_hits : dict - Keyed by (vol, plane) with labeled_hits, hits_by_track, - group_correspondence, row_sums per plane. - """ - group_to_track = track_hits.pop('group_to_track') - max_keys = None - - for plane_key, raw in list(track_hits.items()): - state_sk, state_tk, state_gk, state_ch, state_count, row_sums = raw - decode_fn = decode_fns.get(plane_key) if decode_fns else None - result = label_from_groups( - state_sk, state_tk, state_gk, state_ch, state_count, - group_to_track, decode_spatial_fn=decode_fn) - result['row_sums'] = row_sums - track_hits[plane_key] = result - - # Validate - gp = result.get('group_correspondence') - if gp is not None: - count_val = int(gp[-1]) - if max_keys is None: - max_keys = state_sk.shape[0] - if count_val >= max_keys: - print(f"ERROR: Plane {plane_key}: group merge count ({count_val:,}) >= " - f"max_keys ({max_keys:,}). Correspondence data TRUNCATED!") - - return track_hits - - # ============================================================================= # Q_s FRACTIONS (inside JIT, per-side) # ============================================================================= diff --git a/tools/utils.py b/tools/utils.py index daac77d..aeef243 100644 --- a/tools/utils.py +++ b/tools/utils.py @@ -1,180 +1,14 @@ """ -HDF5 I/O for saving and loading simulation events. - -Saves both output paths (response + hits) per event into a single file. -Events are stored under /event_{idx}/ groups. Detector config is written -once at the root level on first event. - -Schema: - /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) int32 - values (N,) float32 - signal (N_s,) float32 - attrs: n_signal, threshold_adc - hits/{plane}/ - hits_by_track (H,3) float32 - track_boundaries (T,) int32 - track_ids (T,) int32 - attrs: num_hits, num_tracks +HDF5 I/O for space-charge-effect (SCE) maps. + +Event I/O lives in production/save.py and production/load.py (any number of +volumes, wire or pixel). The former single-file save_event/load_event here +expected keys that no current output produces and only knew the 2-volume U/V/Y +detector, so it was removed. """ import h5py import numpy as np -import os - -def get_plane_name(vol_idx, plane_idx, plane_names=None): - """Get a string label for a (volume, plane) pair.""" - if plane_names and vol_idx < len(plane_names): - ptype = plane_names[vol_idx][plane_idx] if plane_idx < len(plane_names[vol_idx]) else str(plane_idx) - else: - ptype = str(plane_idx) - return f"vol{vol_idx}_{ptype}" - -# Default names for the standard 2-volume 3-plane detector -_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', -} -_NAME_TO_KEY = {v: k for k, v in _PLANE_NAMES.items()} - - -def save_event(filepath, event_idx, sparse_output, track_hits, detector_config): - """ - Save one event's simulation output to HDF5 (creates or appends). - - Parameters - ---------- - filepath : str - Path to the HDF5 file. - event_idx : int - Event index (used as group name: event_0, event_1, ...). - sparse_output : dict - Output from process_response(), keyed by (vol_idx, plane_idx). - track_hits : dict - Output from DetectorSimulator(), keyed by (vol_idx, plane_idx). - detector_config : dict - Detector configuration from generate_detector(). - """ - mode = 'a' if os.path.exists(filepath) else 'w' - - with h5py.File(filepath, mode) as f: - # Write config once - if 'config' not in f: - cfg = f.create_group('config') - cfg.create_dataset('num_wires_actual', - data=np.array(detector_config['num_wires_actual'], dtype=np.int32)) - cfg.create_dataset('min_wire_indices', - data=np.array(detector_config['min_wire_indices_abs'], dtype=np.int32)) - cfg.attrs['num_time_steps'] = int(detector_config['num_time_steps']) - cfg.attrs['electrons_per_adc'] = float(detector_config['electrons_per_adc']) - - event_key = f'event_{event_idx}' - if event_key in f: - del f[event_key] - evt = f.create_group(event_key) - - # --- Response path --- - resp_grp = evt.create_group('response') - for (si, pi), data in sparse_output.items(): - name = _PLANE_NAMES[(si, pi)] - g = resp_grp.create_group(name) - g.create_dataset('indices', data=np.asarray(data['indices']), compression='gzip') - g.create_dataset('values', data=np.asarray(data['values']), compression='gzip') - g.create_dataset('signal', data=np.asarray(data['signal']), compression='gzip') - g.attrs['n_signal'] = int(data['n_signal']) - g.attrs['threshold_adc'] = float(data['threshold_adc']) - - # --- Hits path --- - hits_grp = evt.create_group('hits') - for (si, pi), data in track_hits.items(): - name = _PLANE_NAMES[(si, pi)] - g = hits_grp.create_group(name) - # All arrays already sliced to valid length by process_event - g.create_dataset('hits_by_track', - data=np.asarray(data['hits_by_track']), - compression='gzip') - g.create_dataset('track_boundaries', - data=np.asarray(data['track_boundaries']), - compression='gzip') - g.create_dataset('track_ids', - data=np.asarray(data['track_ids']), - compression='gzip') - g.attrs['num_hits'] = int(data['num_hits']) - g.attrs['num_tracks'] = int(data['num_tracks']) - - -def load_event(filepath, event_idx): - """ - Load one event from HDF5. - - Parameters - ---------- - filepath : str - Path to the HDF5 file. - event_idx : int - Event index to load. - - Returns - ------- - sparse_output : dict - Keyed by (side_idx, plane_idx), matching process_response() output. - track_hits : dict - Keyed by (side_idx, plane_idx), matching DetectorSimulator() output. - config : dict - Detector config subset needed for downstream use. - """ - with h5py.File(filepath, 'r') as f: - # Config - cfg = f['config'] - config = { - 'num_wires_actual': np.array(cfg['num_wires_actual']), - 'min_wire_indices_abs': np.array(cfg['min_wire_indices']), - 'num_time_steps': int(cfg.attrs['num_time_steps']), - 'electrons_per_adc': float(cfg.attrs['electrons_per_adc']), - } - - evt = f[f'event_{event_idx}'] - - # Response - sparse_output = {} - for name, key in _NAME_TO_KEY.items(): - if name in evt['response']: - g = evt['response'][name] - sparse_output[key] = { - 'indices': np.array(g['indices']), - 'values': np.array(g['values']), - 'signal': np.array(g['signal']), - 'n_signal': int(g.attrs['n_signal']), - 'threshold_adc': float(g.attrs['threshold_adc']), - } - - # Hits - track_hits = {} - for name, key in _NAME_TO_KEY.items(): - if name in evt['hits']: - g = evt['hits'][name] - track_hits[key] = { - 'hits_by_track': np.array(g['hits_by_track']), - 'track_boundaries': np.array(g['track_boundaries']), - 'track_ids': np.array(g['track_ids']), - 'num_hits': int(g.attrs['num_hits']), - 'num_tracks': int(g.attrs['num_tracks']), - } - - return sparse_output, track_hits, config - - -def list_events(filepath): - """Return sorted list of event indices stored in the file.""" - with h5py.File(filepath, 'r') as f: - return sorted( - int(k.split('_')[1]) for k in f.keys() if k.startswith('event_') - ) # ========================================================================= @@ -248,4 +82,6 @@ def load_sce_data(filepath): 'origin_cm', 'spacing_cm'. """ with h5py.File(filepath, 'r') as f: - return [_load_side(f[k]) for k in sorted(f.keys())] + keys = sorted((k for k in f.keys() if k.startswith('volume_')), + key=lambda k: int(k.split('_')[1])) # volume_10 after volume_9 + return [_load_side(f[k]) for k in keys]