Skip to content
Open
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
25 changes: 25 additions & 0 deletions docs/production/data-formats.md
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,31 @@ group indirection in `hits/`.

---

## Format 3 (step file input)

With an edep-sim step file as input, the batch writes `sensor`, `hits` and
`presupera` files. `config` has the same settings in each, with
`format_version = 3`, the thresholds, the detector YAML and what is needed to
recompute charge and photons from the steps. An event is one `entry_{NNNNNN}`
per file; all datasets are one chunk.

**Groups.** Group 1 is in the step file: consecutive steps of a track, event wide,
may cross a cathode. The simulation starts a new group 2 at every change of group 1
or volume, numbered from 1 in each volume (`production/stepfile.py:refine_groups`).
Hits use group 2. `--regroup` defines the groups in the simulation instead.

| File | Per volume (and plane) | |
|---|---|---|
| sensor | as format 2 | pixel `values` are `int32` |
| hits | `group_ids`, `group_sizes` | cells of group i are consecutive |
| | `group_center_<axis>`, `offset_<axis>` | cell = center of its group + offset |
| | `charge` (int32) | times its `scale_factor` (`hits_threshold` / 16), units in `units` |
| presupera | `group_to_track`, `group2_to_group1` | row g-1 is group g |
| | `deposit_to_group` | instead of `group2_to_group1`, with `--regroup` |

Axes are `wire`, `time` or `py`, `pz`, `time`. Read with `load_step3`, `load_hits3`
and `charge_and_photons` of `production/load.py`.

## See also

- [Capacities & overflow](../concepts/capacities.md) — the array budgets these
Expand Down
8 changes: 8 additions & 0 deletions production/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ production/
├── run_batch.py # Main batch simulation script
├── save.py # HDF5 save functions (sensor/step/hits encoding)
├── load.py # HDF5 load/decode functions
├── stepfile.py # read edep-sim step files, refine groups (format 3)
├── entries.py # entry naming + event identity attributes (format 2)
├── view_production.ipynb # Visualize production output (no simulation needed)
└── README.md # This file
Expand Down Expand Up @@ -121,6 +122,7 @@ See `profiler/` for individual scripts to tune each parameter separately.
| `--max-buckets` | 1,000 | Max active buckets per plane (bucketed mode) |
| `--group-size` | 5 | Deposits per hits (correspondence) group |
| `--gap-threshold` | 5.0 | Group split threshold in mm |
| `--regroup` | off | Step file input: define groups with the two options above instead of taking the file's |
| `--seed` | 42 | Random seed for noise generation |

## Pipeline
Expand Down Expand Up @@ -398,6 +400,12 @@ Runtime is trivial (<2 s per 20-event file). This script is explicitly
out of the simulation pipeline and **not JIT-compiled** — replace with
an edepsim-side integrated writer when productionizing.

## Format 3 (step file input)

If `--data` is an edep-sim step file (`/edep/db/set/stepTruth true`), the output
is `sensor`, `hits` and `presupera` (no `step`), and `--merge-output` is required.
See [docs/production/data-formats.md](../docs/production/data-formats.md).

## Bidirectional Correspondence

Correspondence between 3D deposits (step) and 2D pixels (sensor) is
Expand Down
57 changes: 56 additions & 1 deletion production/load.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ def build_viz_config(sensor_path):
n_volumes=n_vol,
num_time_steps=int(meta['num_time_steps']),
time_step_us=float(meta['time_step_us']),
electrons_per_adc=float(meta['electrons_per_adc']),
electrons_per_adc=float(meta.get('electrons_per_adc', np.nan)),
plane_names=plane_names,
)

Expand Down Expand Up @@ -587,3 +587,58 @@ def deposit_charge_per_plane(corr, plane_label):
grp_tot = np.bincount(d['gid'], weights=d['charge'],
minlength=corr['g2t'].size).astype(np.float32)
return corr['qs'] * grp_tot[corr['d2g']]


# =============================================================================
# Format 3 (step / hits / presupera / label; see production/stepfile.py)
# =============================================================================

def load_step3(step_path, event_idx, volume_ranges_cm=None):
"""Steps of one event. With volume_ranges_cm also 'volume' and 'group2'."""
from production import stepfile
with h5py.File(step_path, 'r') as f:
s = stepfile.read_step(f, event_idx)
if volume_ranges_cm is not None:
s['volume'] = stepfile.volume_of(s['positions_mm'].astype(np.float32),
volume_ranges_cm)
s['group2'], _ = stepfile.refine_groups(s['group1'], s['volume'],
len(volume_ranges_cm))
return s


def load_hits3(hits_path, entry):
"""Hits of one entry: {(volume, plane name): {coordinates..., group, charge}}."""
out = {}
with h5py.File(hits_path, 'r') as f:
e = f[entry]
for vk in e:
for plane in e[vk]:
g = e[vk][plane]
sizes = g['group_sizes'][()].astype(np.int64)
d = {'group': np.repeat(g['group_ids'][()], sizes),
'charge': g['charge'][()] * float(g['charge'].attrs['scale_factor'])}
for k in g:
if k.startswith('group_center_'):
c = k[len('group_center_'):]
d[c] = (np.repeat(g[k][()].astype(np.int32), sizes)
+ g[f'offset_{c}'][()])
out[(int(vk.split('_')[1]), plane)] = d
return out


def charge_and_photons(step, config_attrs):
"""Electrons and photons per step from step columns and the recombination settings
in a format 3 config group (uniform field along x; not valid with SCE)."""
from types import SimpleNamespace
from tools.recombination import XI_FN, compute_quanta
if config_attrs['include_sce']:
raise NotImplementedError('needs the field map of the simulation')
pars = SimpleNamespace(**{k[len('recomb_'):]: config_attrs[k] for k in config_attrs
if k.startswith('recomb_')})
model = config_attrs['recombination_model']
model = model.decode() if isinstance(model, bytes) else model
c = np.abs(np.sin(step['theta'].astype(np.float32)) * np.cos(step['phi'].astype(np.float32)))
q, l = compute_quanta(step['de'], step['dx'].astype(np.float32) / 10.0,
np.arccos(np.clip(c, 0.0, 1.0)), pars.field_strength_Vcm, pars,
XI_FN[model])
return np.asarray(q), np.asarray(l)
127 changes: 107 additions & 20 deletions production/run_batch.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,10 @@
set_codec,
)
from production.entries import entry_key
from production.save import (
encode_hits, save_event_hits3, save_event_presupera, write_config3,
)
from production.stepfile import StepFileExtractor, is_step_file

sys.stdout.reconfigure(line_buffering=True)

Expand Down Expand Up @@ -167,8 +171,22 @@ def load_deposit(extractor, event_idx, sim_config,
)


def open_extractor(path):
return StepFileExtractor(path) if is_step_file(path) else ParticleStepExtractor(path)


def load_any(extractor, event_idx, sim_config, group_size, gap_threshold, regroup):
"""(DepositData, group2_to_group1) of an event; the maps only for step files."""
if isinstance(extractor, StepFileExtractor):
return extractor.load(event_idx, sim_config,
(group_size, gap_threshold) if regroup else None)
return load_deposit(extractor, event_idx, sim_config, group_size, gap_threshold), None


def get_num_events(data_path):
with h5py.File(data_path, 'r') as f:
if 'schema' in f:
return f['event/geant4'].shape[0]
return f['pstep/lar_vol'].shape[0]


Expand Down Expand Up @@ -303,6 +321,9 @@ def main():
parser.add_argument('--group-size', type=int, default=5)
parser.add_argument('--gap-threshold', type=float, default=5.0,
help='Gap threshold in mm for group splitting')
parser.add_argument('--regroup', action='store_true',
help='Step file input: define groups here (--group-size, '
'--gap-threshold) instead of taking the file\'s')
parser.add_argument('--hits-threshold', type=float, default=1.0,
help='Charge threshold for per-particle hits at CSR encode '
'(YAML key: corr_threshold). Units: ENC for wire (signed, '
Expand Down Expand Up @@ -412,6 +433,26 @@ def main():
f'(range={args.file_range}). Total available: {len(source_files_all)}.')
return

# Step file input (format 3): outputs are sensor, hits and presupera, no step
kinds = {is_step_file(p) for p in source_files}
if len(kinds) > 1:
raise SystemExit('ERROR: step files and edep-sim files cannot be mixed')
step_input = kinds.pop()
if step_input and (args.no_track_hits or not args.merge_output):
raise SystemExit('ERROR: step file input needs track hits and --merge-output')
if step_input and not args.hits_threshold > 0:
raise SystemExit('ERROR: step file input needs --hits-threshold > 0: it sets the charge unit')
if step_input and not args.regroup:
# the group definition is the file's; it also sizes the per-group boxes
defs = set()
for p in source_files:
with h5py.File(p, 'r') as f:
a = f['schema'].attrs
defs.add((int(a['group_size']), float(a['group_gap_mm'])))
if len(defs) > 1:
raise SystemExit(f'ERROR: step files with different groups: {sorted(defs)}')
args.group_size, args.gap_threshold = defs.pop()

# Detect readout type early for pixel-specific defaults
detector_config = generate_detector(args.config)
readout_type = detector_config['volumes'][0].get('readout', {}).get('type', 'wire')
Expand All @@ -423,7 +464,8 @@ def main():

# Top-level output dirs (per-source subfolders by run_id added inside loop)
base_sensor_dir = os.path.join(args.outdir, 'sensor')
base_step_dir = os.path.join(args.outdir, 'step')
second_role = 'presupera' if step_input else 'step'
base_step_dir = os.path.join(args.outdir, second_role)
base_hits_dir = os.path.join(args.outdir, 'hits') if include_track_hits else None
logs_dir = os.path.join(args.outdir, 'logs')
# Per-file done markers (resume): written only after an output file's HDF5
Expand Down Expand Up @@ -560,9 +602,9 @@ def _build_sim(tc):
print(" Real-data warmup...", end='', flush=True)
t0 = time.time()
try:
warmup_dep = load_deposit(
ParticleStepExtractor(source_files[0]), 0, cfg,
args.group_size, args.gap_threshold)
warmup_dep, _ = load_any(
open_extractor(source_files[0]), 0, cfg,
args.group_size, args.gap_threshold, args.regroup)
warmup_r, _, warmup_dep = simulator.process_event(warmup_dep, key=jax.random.PRNGKey(0))
for a in warmup_r.values():
if isinstance(a, dict):
Expand All @@ -579,6 +621,19 @@ def _build_sim(tc):
gc.collect()
print(f" {time.time() - t0:.1f}s\n")

# Pixel value unit, from the response file itself
pixel_units = None
if step_input and readout_type == 'pixel':
import hashlib
npz_path = simulator.pixel_response_path
with np.load(npz_path) as z, open(npz_path, 'rb') as fb:
full = float((z['response'].sum(-1) * float(z['time_bin_size'])).max())
pixel_units = {
'pixel_units': 'electron/us (mean induced current over the tick)',
'pixel_units_per_electron_full_collection': full / float(cfg.time_step_us),
'pixel_response_src': str(z['src']),
'pixel_response_sha256': hashlib.sha256(fb.read()).hexdigest()}

# ---- Batch timestamp + git provenance (shared across all sources) ----
batch_timestamp = int(time.time())
batch_ts_str = time.strftime('%Y-%m-%dT%H:%M:%S', time.gmtime(batch_timestamp))
Expand Down Expand Up @@ -619,7 +674,7 @@ def save_one_event(f_sensor, f_step, f_hits, item, locks):
# to_sparse runs here (off the main thread), pulling the dense device
# result to host and thresholding it.
(event_key, response_payload, track_hits_raw, deposits,
source_idx, ev_id, entry_attrs) = item
source_idx, ev_id, entry_attrs, g2g1) = item
if _PROFILE_SAVE:
_tid = threading.get_ident() & 0xFFFF
_t_enter = time.time()
Expand All @@ -644,7 +699,16 @@ def save_one_event(f_sensor, f_step, f_hits, item, locks):
continue
vol_idx, plane_idx = plane_key
sk, tk, gid, ch, count, _ = raw
if cfg.volumes[vol_idx].readout_type == 'pixel':
if step_input:
P = int(count)
s, t, g_, q = (np.asarray(x[:P]) for x in (sk, tk, gid, ch))
if cfg.volumes[vol_idx].readout_type == 'pixel':
num_pz = cfg.volumes[vol_idx].pixel_shape[1]
coords = {'py': s // num_pz, 'pz': s % num_pz, 'time': t}
else:
coords = {'wire': s, 'time': t}
hits_data[plane_key] = encode_hits(g_, coords, q, args.hits_threshold)
elif cfg.volumes[vol_idx].readout_type == 'pixel':
num_pz = cfg.volumes[vol_idx].pixel_shape[1]
hits_data[plane_key] = encode_correspondence_csr_pixel(
sk, tk, gid, ch, count, num_pz,
Expand All @@ -667,26 +731,35 @@ def save_one_event(f_sensor, f_step, f_hits, item, locks):
save_event_sensor(f_sensor, event_key, response_np, threshold_adc,
source_idx, deposits, cfg=cfg,
digitized=include_digitize, event_id=ev_id,
attrs=entry_attrs)
attrs=entry_attrs, pixel_as_int=step_input)
if _PROFILE_SAVE: _t_sen = time.time() - _t0

if _PROFILE_SAVE: _t0 = time.time()
with locks[1]:
if _PROFILE_SAVE:
_lw_step = time.time() - _t0; _t0 = time.time()
save_event_step(f_step, event_key, deposits, source_idx, cfg=cfg,
event_id=ev_id, attrs=entry_attrs)
if step_input:
save_event_presupera(f_step, event_key, deposits, g2g1, source_idx,
cfg, event_id=ev_id, attrs=entry_attrs)
else:
save_event_step(f_step, event_key, deposits, source_idx, cfg=cfg,
event_id=ev_id, attrs=entry_attrs)
if _PROFILE_SAVE: _t_step = time.time() - _t0

if hits_data is not None and f_hits is not None:
if _PROFILE_SAVE: _t0 = time.time()
with locks[2]:
if _PROFILE_SAVE:
_lw_hits = time.time() - _t0; _t0 = time.time()
save_event_hits(f_hits, event_key, hits_data, deposits,
source_idx,
hits_threshold=args.hits_threshold, cfg=cfg,
event_id=ev_id, attrs=entry_attrs)
if step_input:
save_event_hits3(f_hits, event_key, hits_data, deposits, source_idx,
args.hits_threshold, cfg, event_id=ev_id,
attrs=entry_attrs)
else:
save_event_hits(f_hits, event_key, hits_data, deposits,
source_idx,
hits_threshold=args.hits_threshold, cfg=cfg,
event_id=ev_id, attrs=entry_attrs)
if _PROFILE_SAVE: _t_hits = time.time() - _t0
elif _PROFILE_SAVE:
_lw_hits = 0.0; _t_hits = 0.0
Expand Down Expand Up @@ -793,6 +866,20 @@ def _open_outputs(paths, sources, n_events, event_start, file_index, provenance)
trio.append(h5py.File(pe, 'w'))
trio.append(h5py.File(ph, 'w') if ph else None)
fs, fe, fh = trio
if step_input:
thr = dict(sensor=threshold_adc, hits=args.hits_threshold,
inter=args.inter_thresh, sce=args.sce)
grp = dict(group_size=args.group_size,
gap_threshold_mm=args.gap_threshold,
groups_from='simulation' if args.regroup else 'step file')
with open(args.config) as fy:
det_yaml = fy.read()
for fo, role in ((fs, 'sensor'), (fe, 'presupera'), (fh, 'hits')):
write_config3(fo, role, cfg, params, simulator.recomb_model,
dataset_name, sources, n_events, thr, grp, det_yaml,
digitization_config=dig_config, provenance=provenance,
pixel_units=pixel_units)
continue
write_config_sensor(
fs, cfg, params, simulator.recomb_model, dataset_name,
file_index, sources, n_events, event_start, threshold_adc,
Expand Down Expand Up @@ -875,9 +962,9 @@ def _read_loop(ex, rank):
for r_idx in range(event_start + rank, event_end, n_read):
try:
t0 = time.time()
d = load_deposit(
d = load_any(
ex, r_idx, cfg,
args.group_size, args.gap_threshold)
args.group_size, args.gap_threshold, args.regroup)
read_q.put((r_idx, d, time.time() - t0))
except Exception as exc:
read_q.put((r_idx, exc, 0.0))
Expand All @@ -886,7 +973,7 @@ def _reader(rank):
if rank == 0:
_read_loop(extractor, rank)
else:
with ParticleStepExtractor(source_path) as ex:
with open_extractor(source_path) as ex:
_read_loop(ex, rank)
read_q.put(None)

Expand Down Expand Up @@ -916,7 +1003,7 @@ def _reader(rank):
try:
if isinstance(deposits_or_exc, Exception):
raise deposits_or_exc
deposits = deposits_or_exc
deposits, g2g1 = deposits_or_exc
n_deposits = sum(v.n_actual for v in deposits.volumes)

if use_tiered:
Expand Down Expand Up @@ -945,7 +1032,7 @@ def _reader(rank):
# Hand off the raw device result; the workers do
# to_sparse (the dense host pull) off the main thread.
item = (event_key, response_signals, track_hits,
deposits, idx, event_id, entry_attrs)
deposits, idx, event_id, entry_attrs, g2g1)

t_save = time.time()
if num_workers > 0:
Expand Down Expand Up @@ -1010,7 +1097,7 @@ def _print_source(src):
if any(s is None for s in srcs):
raise SystemExit('ERROR: --merge-output needs every input; see above')
paths = (os.path.join(base_sensor_dir, f'{dataset_name}_sensor_{args.merge_output}.h5'),
os.path.join(base_step_dir, f'{dataset_name}_step_{args.merge_output}.h5'),
os.path.join(base_step_dir, f'{dataset_name}_{second_role}_{args.merge_output}.h5'),
os.path.join(base_hits_dir, f'{dataset_name}_hits_{args.merge_output}.h5')
if base_hits_dir else None)
run_ids = {s['run_id'] for s in srcs}
Expand All @@ -1026,7 +1113,7 @@ def _print_source(src):
for src in srcs:
_print_source(src)
print(f' Entries: {entry_base}–{entry_base + src["num_events"] - 1}')
with ParticleStepExtractor(src['path']) as extractor:
with open_extractor(src['path']) as extractor:
_run_events(extractor, src, 0, src['num_events'], entry_base,
src['pos'], wsets, save_queue)
entry_base += src['num_events']
Expand Down
Loading
Loading