diff --git a/docs/production/data-formats.md b/docs/production/data-formats.md index 62fdde3..ffb0f46 100644 --- a/docs/production/data-formats.md +++ b/docs/production/data-formats.md @@ -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_`, `offset_` | 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 diff --git a/production/README.md b/production/README.md index cb1be2e..e7b40f2 100644 --- a/production/README.md +++ b/production/README.md @@ -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 @@ -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 @@ -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 diff --git a/production/load.py b/production/load.py index 2ef28da..00e1fcb 100644 --- a/production/load.py +++ b/production/load.py @@ -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, ) @@ -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) diff --git a/production/run_batch.py b/production/run_batch.py index 75f7365..c403442 100644 --- a/production/run_batch.py +++ b/production/run_batch.py @@ -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) @@ -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] @@ -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, ' @@ -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') @@ -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 @@ -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): @@ -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)) @@ -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() @@ -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, @@ -667,15 +731,19 @@ 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: @@ -683,10 +751,15 @@ def save_one_event(f_sensor, f_step, f_hits, item, locks): 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 @@ -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, @@ -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)) @@ -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) @@ -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: @@ -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: @@ -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} @@ -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'] diff --git a/production/save.py b/production/save.py index cf51f83..3f9b6ab 100644 --- a/production/save.py +++ b/production/save.py @@ -73,6 +73,17 @@ def set_codec(name): _COMPRESSION = codec_kwargs(name) +def _put(g, name, data): + data = np.asarray(data) + return g.create_dataset(name, data=data, **_filters(data)) + + +def _filters(data): + """Dataset keywords: compressed as one chunk (an event is read whole; h5py's + default guess makes hundreds of small chunks).""" + return dict(chunks=data.shape, **_COMPRESSION) if data.size else {} + + _PLANE_LABELS = {0: 'U', 1: 'V', 2: 'Y'} @@ -276,16 +287,16 @@ def _save_wire_plane(g, arr, threshold_adc, digitized, pedestals, vol_idx, plane time_s = time_idx[order].astype(np.int32) values_s = values[order] - g.create_dataset('delta_wire', data=np.diff(wire_s, prepend=wire_s[0]).astype(np.int16), **_COMPRESSION) - g.create_dataset('delta_time', data=np.diff(time_s, prepend=time_s[0]).astype(np.int16), **_COMPRESSION) + _put(g, 'delta_wire', np.diff(wire_s, prepend=wire_s[0]).astype(np.int16)) + _put(g, 'delta_time', np.diff(time_s, prepend=time_s[0]).astype(np.int16)) if digitized and pedestals is not None: ped = int(pedestals[vol_idx, plane_idx]) values_unsigned = np.round(values_s + ped).clip(0, 65535).astype(np.uint16) - g.create_dataset('values', data=values_unsigned, **_COMPRESSION) + _put(g, 'values', values_unsigned) g.attrs['pedestal'] = ped else: - g.create_dataset('values', data=values_s.astype(np.float32), **_COMPRESSION) + _put(g, 'values', values_s.astype(np.float32)) g.attrs['wire_start'] = int(wire_s[0]) g.attrs['time_start'] = int(time_s[0]) @@ -306,23 +317,23 @@ def _save_wire_plane_sparse(g, sparse_dict, digitized, pedestals, vol_idx, plane time_s = time_s[order] values_s = values_s[order] - g.create_dataset('delta_wire', data=np.diff(wire_s, prepend=wire_s[0]).astype(np.int16), **_COMPRESSION) - g.create_dataset('delta_time', data=np.diff(time_s, prepend=time_s[0]).astype(np.int16), **_COMPRESSION) + _put(g, 'delta_wire', np.diff(wire_s, prepend=wire_s[0]).astype(np.int16)) + _put(g, 'delta_time', np.diff(time_s, prepend=time_s[0]).astype(np.int16)) if digitized and pedestals is not None: ped = int(pedestals[vol_idx, plane_idx]) values_unsigned = np.round(values_s + ped).clip(0, 65535).astype(np.uint16) - g.create_dataset('values', data=values_unsigned, **_COMPRESSION) + _put(g, 'values', values_unsigned) g.attrs['pedestal'] = ped else: - g.create_dataset('values', data=values_s, **_COMPRESSION) + _put(g, 'values', values_s) g.attrs['wire_start'] = int(wire_s[0]) g.attrs['time_start'] = int(time_s[0]) g.attrs['n_pixels'] = len(wire_s) -def _save_pixel_plane(g, sparse_dict): +def _save_pixel_plane(g, sparse_dict, as_int=False): """Save one pixel plane's sparse signal as delta-encoded arrays. Parameters @@ -347,10 +358,14 @@ def _save_pixel_plane(g, sparse_dict): time_s = time_idx[order].astype(np.int32) values_s = values[order] - g.create_dataset('delta_py', data=np.diff(py_s, prepend=py_s[0]).astype(np.int16), **_COMPRESSION) - g.create_dataset('delta_pz', data=np.diff(pz_s, prepend=pz_s[0]).astype(np.int16), **_COMPRESSION) - g.create_dataset('delta_time', data=np.diff(time_s, prepend=time_s[0]).astype(np.int16), **_COMPRESSION) - g.create_dataset('values', data=values_s.astype(np.float32), **_COMPRESSION) + _put(g, 'delta_py', np.diff(py_s, prepend=py_s[0]).astype(np.int16)) + _put(g, 'delta_pz', np.diff(pz_s, prepend=pz_s[0]).astype(np.int16)) + _put(g, 'delta_time', np.diff(time_s, prepend=time_s[0]).astype(np.int16)) + if as_int: + values_s = np.round(values_s).astype(np.int32) + else: + values_s = values_s.astype(np.float32) + _put(g, 'values', values_s) g.attrs['py_start'] = int(py_s[0]) g.attrs['pz_start'] = int(pz_s[0]) @@ -358,9 +373,126 @@ def _save_pixel_plane(g, sparse_dict): g.attrs['n_pixels'] = len(py_s) +def _offsets(values, centers): + """Entry minus group center in the smallest signed type that holds it.""" + d = values.astype(np.int32) - centers.astype(np.int32) + lim = int(np.abs(d).max()) if len(d) else 0 + return d.astype(np.int8 if lim <= 127 else np.int16) + + +def encode_hits(gids, coords, charges, threshold): + """One plane's hits: entries above threshold, sorted by group (format 3). + + coords: {name: index array} e.g. wire/time or py/pz/time. Charges are stored as + signed integers in units of threshold/16 (``charge_scale``). Each group has a + reference cell (its largest entry); the entries are offsets from it. + """ + if not threshold > 0: + raise ValueError('hits need a threshold > 0: it sets the charge unit') + keep = np.abs(charges) > threshold + gids, charges = gids[keep], charges[keep] + coords = {k: v[keep] for k, v in coords.items()} + order = np.argsort(gids, kind='stable') + gids, charges = gids[order], charges[order] + coords = {k: v[order] for k, v in coords.items()} + ids, start, count = np.unique(gids, return_index=True, return_counts=True) + label = np.repeat(np.arange(len(ids)), count) + out = {'group_ids': ids.astype(np.int32), 'group_sizes': _group_sizes(count)} + if len(ids): + mag = np.abs(charges) + peak = np.maximum.reduceat(mag, start) + where = np.flatnonzero(mag == peak[label]) + ref = where[np.searchsorted(where, start)] + else: + ref = np.zeros(0, dtype=np.int64) + for k, v in coords.items(): + c = v[ref].astype(np.int16) + out[f'group_center_{k}'] = c + out[f'offset_{k}'] = _offsets(v, c[label]) + unit = threshold / 16.0 + out['charge'] = np.round(charges.astype(np.float64) / unit).astype(np.int32) + return out + + +def save_event_hits3(f, event_key, hits_data, deposits, source_event_idx, threshold, + cfg, event_id=None, attrs=None): + """Hits of one event (format 3): per plane the cells of each group.""" + evt = f.create_group(event_key) + _write_entry_attrs(evt, source_event_idx, event_id, attrs) + evt.attrs['n_volumes'] = len(deposits.volumes) + evt.attrs['threshold'] = threshold + for v in range(len(deposits.volumes)): + vg = evt.create_group(f'volume_{v}') + for (vi, pi), enc in hits_data.items(): + if vi != v: + continue + g = vg.create_group(_plane_label(pi, vi, cfg)) + for k, arr in enc.items(): + d = _put(g, k, arr) + if k == 'charge': + d.attrs['scale_factor'] = threshold / 16.0 + d.attrs['units'] = ('electron' if cfg.volumes[vi].readout_type == 'wire' + else 'electron/us') + g.attrs['n_entries'] = len(enc['charge']) + + +def save_event_presupera(f, event_key, deposits, group2_to_group1, source_event_idx, + cfg, event_id=None, attrs=None): + """What pysupera needs besides hits (format 3), per volume: group_to_track and + group2_to_group1 (row g-1 is group g), or deposit_to_group if the simulation + defined its own groups.""" + evt = f.create_group(event_key) + _write_entry_attrs(evt, source_event_idx, event_id, attrs) + evt.attrs['n_volumes'] = len(deposits.volumes) + for v, vol in enumerate(deposits.volumes): + n = int(vol.n_actual) + vg = evt.create_group(f'volume_{v}') + vg.attrs['n_steps'] = n + def put(name, x): + d = _put(vg, name, x) + d.attrs['id_base'] = 1 + put('group_to_track', np.asarray(deposits.group_to_track[v])[1:].astype(np.int32)) + if group2_to_group1 is not None: + put('group2_to_group1', group2_to_group1[v]) + else: + put('deposit_to_group', np.asarray(vol.group_ids[:n]).astype(np.int32)) + + +def write_config3(f, role, cfg, params, recomb_model, dataset_name, sources, n_events, + thresholds, group_attrs, detector_yaml, digitization_config=None, + provenance=None, pixel_units=None): + """Config group of a format 3 sensor, hits or presupera file: the same settings in + each, including what is needed to recompute charge and photons from step.""" + write_config_sensor(f, cfg, params, recomb_model, dataset_name, 0, sources, n_events, + 0, thresholds['sensor'], digitization_config=digitization_config, + provenance=provenance) + g = f['config'] + g.attrs['format_version'] = 3 + g.attrs['role'] = role + g.attrs['sensor_threshold'] = thresholds['sensor'] + g.attrs['hits_threshold'] = thresholds['hits'] + g.attrs['inter_thresh'] = thresholds['inter'] + for k, v in group_attrs.items(): + g.attrs[k] = v + g.attrs['include_sce'] = thresholds['sce'] is not None + if thresholds['sce'] is not None: + g.attrs['sce_path'] = thresholds['sce'] + g.attrs['detector_config_yaml'] = detector_yaml + for k, v in params.recomb_params._asdict().items(): + g.attrs[f'recomb_{k}'] = float(v) + g.attrs['drift_direction'] = np.array([v.drift_direction for v in cfg.volumes], np.int32) + if cfg.volumes[0].readout_type == 'pixel': + # values are mean induced current, not counts: no electrons_per_adc + del g.attrs['electrons_per_adc'] + g.attrs['pixel_shape'] = np.array([v.pixel_shape for v in cfg.volumes], np.int32) + for k, v in (pixel_units or {}).items(): + g.attrs[k] = v + + def save_event_sensor(f, event_key, response_signals, threshold_adc, source_event_idx, deposits, cfg=None, - digitized=False, event_id=None, attrs=None): + digitized=False, event_id=None, attrs=None, + pixel_as_int=False): """Save one event's raw sensor readout (sparse, delta-encoded). Handles both wire (2D) and pixel (3D) output formats. @@ -389,7 +521,7 @@ def save_event_sensor(f, event_key, response_signals, threshold_adc, if isinstance(signal, dict) and 'pixel_y' in signal: # Pixel sparse from to_sparse - _save_pixel_plane(g, signal) + _save_pixel_plane(g, signal, as_int=pixel_as_int) elif isinstance(signal, dict) and 'wire' in signal: # Wire sparse from to_sparse _save_wire_plane_sparse(g, signal, digitized, pedestals, diff --git a/production/stepfile.py b/production/stepfile.py new file mode 100644 index 0000000..e9c207d --- /dev/null +++ b/production/stepfile.py @@ -0,0 +1,105 @@ +""" +edep-sim step files (format 3) as simulation input. + +A step file has one group per event (``entry_NNNNNN``) with flat arrays, rows +track by track: positions, t, de, dx, theta, phi, p, track_id and +``group_run_lengths`` (group 1: runs of consecutive rows, 1-based ids over the +whole event). Positions are cells of a fixed grid: ``(cumsum(k) + cell_offset) * +scale_factor``; every reader must use these decoded values, also to assign steps +to volumes. + +The simulation refines group 1 into group 2: a new group at every change of +group 1 or volume in row order, numbered 1, 2, ... in each volume. hits use group +2; presupera stores group2_to_group1, so step -> group 2 can be rebuilt. +""" + +import h5py +import numpy as np + +from production.entries import entry_key + +FORMAT_VERSION = 3 + + +def is_step_file(path): + with h5py.File(path, 'r') as f: + return 'schema' in f and f['schema'].attrs.get('role') in ('step', b'step') + + +def decode_cells(ds): + k = np.cumsum(ds[()].astype(np.int64), axis=0) + return (k + float(ds.attrs['cell_offset'])) * float(ds.attrs['scale_factor']) + + +def read_step(f, index): + """Columns of one event; positions in mm (float64), group1 per row.""" + g = f[entry_key(index)] + out = {k: g[k][()] for k in ('t', 'de', 'dx', 'theta', 'phi', 'p', 'track_id')} + out['positions_mm'] = decode_cells(g['positions']) + runs = g['group_run_lengths'][()].astype(np.int64) + out['group1'] = np.repeat(np.arange(1, len(runs) + 1, dtype=np.int32), runs) + return out + + +def volume_of(positions_mm, ranges_cm): + """Volume index per row (-1 outside), as build_deposit_data assigns it.""" + pos_cm = np.asarray(positions_mm, dtype=np.float32) / 10.0 + out = np.full(len(pos_cm), -1, dtype=np.int32) + for v, r in enumerate(ranges_cm): + m = np.ones(len(pos_cm), dtype=bool) + for ax in range(3): + m &= (pos_cm[:, ax] >= r[ax][0]) & (pos_cm[:, ax] < r[ax][1]) + out[m] = v + return out + + +def refine_groups(group1, volume, n_volumes): + """Group 2 per row (0 outside all volumes) and, per volume, group2 -> group1 + (row g-1 is group g).""" + n = len(group1) + start = np.ones(n, dtype=bool) + start[1:] = (group1[1:] != group1[:-1]) | (volume[1:] != volume[:-1]) + group2 = np.zeros(n, dtype=np.int32) + maps = [] + for v in range(n_volumes): + m = volume == v + group2[m] = np.cumsum(start[m]) + maps.append(group1[m & start].astype(np.int32)) + return group2, maps + + +class StepFileExtractor: + """Open step file; the counterpart of ParticleStepExtractor.""" + + def __init__(self, path): + self.file = h5py.File(path, 'r') + + def close(self): + self.file.close() + + def __enter__(self): + return self + + def __exit__(self, *exc): + self.close() + + def load(self, index, sim_config, regroup=None): + """DepositData of one event and the per-volume group2 -> group1 maps. + + regroup: (group_size, gap_threshold_mm) to define groups per volume here + instead of refining the step file's; the maps are then None. + """ + from tools.loader import build_deposit_data + s = read_step(self.file, index) + pos = s['positions_mm'].astype(np.float32) + kw = dict(theta=s['theta'], phi=s['phi'], track_ids=s['track_id'], + t0_us=s['t'] / np.float32(1000.0)) + maps = None + if regroup is None: + ranges = [v.ranges_cm for v in sim_config.volumes] + vol = volume_of(pos, ranges) + group2, maps = refine_groups(s['group1'], vol, len(ranges)) + kw['group_ids'] = group2 + else: + kw.update(group_size=regroup[0], gap_threshold_mm=regroup[1]) + return build_deposit_data(pos, s['de'], s['dx'], sim_config, **kw), maps diff --git a/tests/test_format3.py b/tests/test_format3.py new file mode 100644 index 0000000..a1a7edb --- /dev/null +++ b/tests/test_format3.py @@ -0,0 +1,101 @@ +"""Format 3: step file reading, group refinement, hits encoding, presupera.""" +from types import SimpleNamespace + +import h5py +import numpy as np +import pytest + +from production import stepfile +from production.load import load_hits3, load_step3 +from production.save import encode_hits, save_event_hits3, save_event_presupera + +RANGES = (((-20., 0.), (-20., 20.), (-20., 20.)), ((0., 20.), (-20., 20.), (-20., 20.))) + + +def write_step(path, pos, track, runs): + k = np.floor(pos / 0.01).astype(np.int64) + with h5py.File(path, 'w') as f: + f.create_group('schema').attrs.update(dict(role='step', group_size=5, group_gap_mm=3.0)) + g = f.create_group('entry_000000') + d = g.create_dataset('positions', data=np.diff(k, axis=0, prepend=np.zeros((1, 3), int)).astype('i4')) + d.attrs.update(dict(scale_factor=0.01, cell_offset=0.5)) + for c, t in (('t', 'f4'), ('de', 'f4'), ('dx', 'f2'), ('theta', 'f2'), ('phi', 'f2'), ('p', 'f4')): + g[c] = np.full(len(pos), 0.25, t) + g['track_id'] = np.asarray(track, 'i4') + g['group_run_lengths'] = np.asarray(runs, 'u2') + + +def test_step_roundtrip_and_groups(tmp_path): + # one track: 3 steps at x < 0, 1 at x > 0, back to x < 0 (one group 1 of 5), then a second track + x = np.array([-0.9, -0.6, -0.3, 0.2, -0.1, 5.0, 5.3]) + pos = np.stack([x, x * 0 + 1., x * 0 + 2.], 1) + p = str(tmp_path / 's.h5') + write_step(p, pos, [0] * 5 + [3] * 2, [5, 2]) + assert stepfile.is_step_file(p) + s = load_step3(p, 0, RANGES) + assert np.abs(s['positions_mm'] - pos).max() <= 0.005 + 1e-9 + assert s['group1'].tolist() == [1] * 5 + [2] * 2 + assert s['volume'].tolist() == [0, 0, 0, 1, 0, 1, 1] + # the pieces before and after the excursion are different groups + assert s['group2'].tolist() == [1, 1, 1, 1, 2, 2, 2] + _, maps = stepfile.refine_groups(s['group1'], s['volume'], 2) + assert [m.tolist() for m in maps] == [[1, 1], [1, 2]] + + +@pytest.mark.parametrize('side', [-1, 1]) +def test_boundary_side_is_kept(tmp_path, side): + x = side * np.array([1e-7, 1e-4, 0.004999, 0.005, 0.00999, 0.01]) + if side > 0: + x = np.r_[0.0, x] + p = str(tmp_path / 's.h5') + write_step(p, np.stack([x, x * 0, x * 0], 1), [0] * len(x), [len(x)]) + assert (load_step3(p, 0, RANGES)['volume'] == (0 if side < 0 else 1)).all() + + +def deposits(n_groups): + vol = SimpleNamespace(n_actual=4, group_ids=np.array([1, 1, 2, 3])) + return SimpleNamespace(volumes=(vol,), group_to_track=(np.r_[0, np.arange(10, 10 + n_groups)],)) + + +@pytest.mark.parametrize('readout', ['wire', 'pixel']) +def test_hits_roundtrip(tmp_path, readout): + rng = np.random.default_rng(0) + n, T = 4000, 10.0 + names = ('wire', 'time') if readout == 'wire' else ('py', 'pz', 'time') + gid = rng.integers(1, 40, n) + co = {k: (gid * 20 + rng.integers(-200, 200, n)).astype(np.int32) for k in names} # offsets > int8 + q = rng.normal(0, 60, n).astype(np.float32) + enc = encode_hits(gid, co, q, T) + assert enc['offset_time'].dtype == np.int16 + cfg = SimpleNamespace(plane_names=((('U',) if readout == 'wire' else ('Pixel',)),), + volumes=(SimpleNamespace(readout_type=readout),)) + p = str(tmp_path / 'h.h5') + with h5py.File(p, 'w') as f: + save_event_hits3(f, 'entry_000000', {(0, 0): enc}, deposits(3), 0, T, cfg, event_id=7, + attrs={'job_id': 0, 'job_event': 7}) + got = load_hits3(p, 'entry_000000')[(0, cfg.plane_names[0][0])] + keep = np.abs(q) > T + o = np.argsort(gid[keep], kind='stable') + assert np.array_equal(got['group'], gid[keep][o]) + for k in names: + assert np.array_equal(got[k], co[k][keep][o]) + assert np.abs(got['charge'] - q[keep][o]).max() <= T / 32 + 1e-4 + + +def test_hits_empty_and_threshold(): + e = np.zeros(0, np.int32) + enc = encode_hits(e, {'wire': e, 'time': e}, e.astype(np.float32), 10.0) + assert all(len(v) == 0 for v in enc.values()) + with pytest.raises(ValueError): + encode_hits(e, {'wire': e, 'time': e}, e.astype(np.float32), 0.0) + + +def test_presupera(tmp_path): + p = str(tmp_path / 'p.h5') + with h5py.File(p, 'w') as f: + save_event_presupera(f, 'entry_000000', deposits(3), [np.array([1, 1, 2], 'i4')], 0, None) + save_event_presupera(f, 'entry_000001', deposits(3), None, 0, None) + g = f['entry_000000/volume_0'] + assert g['group_to_track'][()].tolist() == [10, 11, 12] + assert g['group2_to_group1'][()].tolist() == [1, 1, 2] and 'deposit_to_group' not in g + assert f['entry_000001/volume_0/deposit_to_group'][()].tolist() == [1, 1, 2, 3] diff --git a/tools/simulation.py b/tools/simulation.py index a3363af..bb652ec 100644 --- a/tools/simulation.py +++ b/tools/simulation.py @@ -242,6 +242,7 @@ def __init__( pixlar_path = '/tmp/pixlar-detsim-jax/pixlar/data/pixel_response_shielded.npz' if not os.path.exists(pixel_response_path) and os.path.exists(pixlar_path): pixel_response_path = pixlar_path + self.pixel_response_path = pixel_response_path self.response_kernels = load_pixel_response_kernel( pixel_response_path, num_s=d.num_s,