From 58719bace64d6978d682aeef93b8c4d77aa504f0 Mon Sep 17 00:00:00 2001 From: Nicolo Valle Date: Thu, 3 Dec 2026 16:01:28 +0100 Subject: [PATCH] SIMULATION - adding external generator for LHC boundary flux --- Generators/share/external/README.md | 5 + Generators/share/external/flux/FluxData.h | 58 +++++++ .../share/external/flux/GeneratorFlux.C | 121 +++++++++++++++ Generators/share/external/flux/README.md | 136 +++++++++++++++++ .../share/external/flux/prepare_flux.py | 144 ++++++++++++++++++ 5 files changed, 464 insertions(+) create mode 100644 Generators/share/external/flux/FluxData.h create mode 100644 Generators/share/external/flux/GeneratorFlux.C create mode 100644 Generators/share/external/flux/README.md create mode 100755 Generators/share/external/flux/prepare_flux.py diff --git a/Generators/share/external/README.md b/Generators/share/external/README.md index 6eab4521b7faa..94084d09c4e81 100644 --- a/Generators/share/external/README.md +++ b/Generators/share/external/README.md @@ -30,3 +30,8 @@ For instance, to generate track defined at radius 500 cm, with maximal angle wrt See GenCosmicsParam class for available options. ------------ + +## External boundary flux: flux/GeneratorFlux.C + +This can be used to inject particles from an external FLUKA boundary-flux CSV through +O2's `extgen` interface. Details in [flux/README.md](flux/README.md). diff --git a/Generators/share/external/flux/FluxData.h b/Generators/share/external/flux/FluxData.h new file mode 100644 index 0000000000000..4544d0eda810e --- /dev/null +++ b/Generators/share/external/flux/FluxData.h @@ -0,0 +1,58 @@ +/// \author nicolo.valle@cern.ch + +#ifndef ALICE3_INPUT_FLUX_DATA_H +#define ALICE3_INPUT_FLUX_DATA_H +#include +#include +#include +#include +#include + + +namespace alice3flux +{ +struct Particle { + int pdg; + double px, py, pz, x, y, z; +}; +class Input +{ + public: + explicit Input(const char* filename) : stream(filename) + { + std::string version; + int nIons; + if (!(stream >> version) || version != "ALICE3_FLUX_V1" || + !(stream >> nEvents >> nIons >> bounds[0] >> bounds[1] >> bounds[2])) { + throw std::runtime_error("Invalid prepared flux file: " + std::string(filename)); + } + for (int i = 0, pdg; i < nIons; ++i) { + if (!(stream >> pdg)) { + throw std::runtime_error("Truncated flux ion header"); + } + ions.push_back(pdg); + } + } + std::vector next(long long& primID) + { + size_t n; + if (!(stream >> primID >> n)) { + throw std::runtime_error("Flux exhausted before requested event count"); + } + std::vector particles(n); + for (auto& p : particles) { + if (!(stream >> p.pdg >> p.px >> p.py >> p.pz >> p.x >> p.y >> p.z)) { + throw std::runtime_error("Truncated prepared flux event"); + } + } + return particles; + } + int nEvents = 0; + std::array bounds; + std::vector ions; + + private: + std::ifstream stream; +}; +} // namespace alice3flux +#endif diff --git a/Generators/share/external/flux/GeneratorFlux.C b/Generators/share/external/flux/GeneratorFlux.C new file mode 100644 index 0000000000000..6d7b1e3657ef2 --- /dev/null +++ b/Generators/share/external/flux/GeneratorFlux.C @@ -0,0 +1,121 @@ +/// \author nicolo.valle@cern.ch + +#include "FluxData.h" +#include "FairIon.h" +#include "FairModule.h" +#include "FairRunSim.h" +#include "Generators/Generator.h" +#include "Generators/PrimaryGenerator.h" +#include "SimulationDataFormat/MCEventHeader.h" +#include "SimulationDataFormat/MCUtils.h" +#include "TDatabasePDG.h" +#include "TGeoBBox.h" +#include "TGeoManager.h" +#include "TParticle.h" +#include "TSystem.h" +#include +#include + + +// Added last, before FairMCApplication closes/imports the TGeo geometry. +// Only the world air box grows; the detector geometry and primary positions stay fixed. +class FluxWorldEnvelope : public FairModule +{ + public: + explicit FluxWorldEnvelope(std::array bounds) + : FairModule("FluxWorldEnvelope", "World containing external flux"), mBounds(bounds) {} + void ConstructGeometry() override + { + auto* box = dynamic_cast(gGeoManager->GetTopVolume()->GetShape()); + if (!box) { + throw std::runtime_error("Expected O2's box-shaped cave volume"); + } + box->SetBoxDimensions(std::max(box->GetDX(), mBounds[0]), + std::max(box->GetDY(), mBounds[1]), + std::max(box->GetDZ(), mBounds[2])); + LOG(info) << "Flux world half-lengths [cm]: " << box->GetDX() << ", " + << box->GetDY() << ", " << box->GetDZ(); + } + + private: + std::array mBounds; +}; + +class GeneratorFlux final : public o2::eventgen::Generator +{ + public: + explicit GeneratorFlux(const char* filename) : mInput(filename) + { + setPositionUnit(1.); // Input already in cm; Generator defaults to mm. + setTimeUnit(1.); // Seconds. No boundary timestamps are supplied. + auto* run = FairRunSim::Instance(); + if (!run) { + throw std::runtime_error("GeneratorFlux requires an active FairRunSim"); + } + for (int pdg : mInput.ions) { + int z = (pdg / 10000) % 1000, a = (pdg / 10) % 1000; + std::string name = "flux_ion_" + std::to_string(z) + "_" + std::to_string(a); + run->AddNewIon(new FairIon(name.c_str(), z, a, z)); + } + run->AddModule(new FluxWorldEnvelope(mInput.bounds)); + } + bool Init() override + { + // The serial o2sim macro in this checkout does not pass --vertexMode to + // PrimaryGenerator. Enforce it here, after FairRunSim installs that object. + auto* primary = dynamic_cast( + FairRunSim::Instance()->GetPrimaryGenerator()); + if (!primary) { + throw std::runtime_error("Expected O2 PrimaryGenerator"); + } + primary->setVertexMode(o2::conf::VertexMode::kNoVertex); + primary->SmearVertexXY(false); + primary->SmearVertexZ(false); + primary->SmearGausVertexXY(false); + primary->SmearGausVertexZ(false); + return Generator::Init(); + } + bool generateEvent() override + { + if (mEvent++ >= mInput.nEvents) { + throw std::runtime_error("Requested too many flux events"); + } + mEventParticles = mInput.next(mPrimID); + return true; + } + bool importParticles() override + { + for (const auto& p : mEventParticles) { + auto* definition = TDatabasePDG::Instance()->GetParticle(p.pdg); + if (!definition) { + throw std::runtime_error("PDG not registered: " + std::to_string(p.pdg)); + } + double mass = definition->Mass(); + double energy = std::sqrt(p.px * p.px + p.py * p.py + p.pz * p.pz + mass * mass); + mParticles.emplace_back(p.pdg, 1, -1, -1, -1, -1, + p.px, p.py, p.pz, energy, p.x, p.y, p.z, 0.); + o2::mcutils::MCGenHelper::encodeParticleStatusAndTracking(mParticles.back(), true); + } + return true; + } + void updateHeader(o2::dataformats::MCEventHeader* header) override + { + header->putInfo("flux_PrimID", mPrimID); + header->putInfo("flux_nPrimaries", static_cast(mEventParticles.size())); + } + + private: + alice3flux::Input mInput; + std::vector mEventParticles; + long long mPrimID = -1; + int mEvent = 0; +}; + +FairGenerator* GeneratorFromFlux() +{ + const char* input = gSystem->Getenv("ALICE3_FLUX_DATA"); + if (!input) { + throw std::runtime_error("ALICE3_FLUX_DATA must point to events.dat"); + } + return new GeneratorFlux(input); +} diff --git a/Generators/share/external/flux/README.md b/Generators/share/external/flux/README.md new file mode 100644 index 0000000000000..dfe9d588a7203 --- /dev/null +++ b/Generators/share/external/flux/README.md @@ -0,0 +1,136 @@ + + +# External boundary flux + +------------ + +## External boundary flux: flux/GeneratorFlux.C + +This example injects particles from an external FLUKA boundary-flux CSV through +O2's `extgen` interface. Each populated `PrimID` group becomes one event. The +particles start at their supplied positions and momenta; O2 and Geant4 handle +transport and secondary production. No collision generator is added. + +The example consists of three files: + +- `prepare_flux.py`: validate the CSV and convert it to `events.dat`. +- `FluxData.h`: read the prepared event records. +- `GeneratorFlux.C`: provide the `GeneratorFromFlux()` factory and generator. + +Keep the macro and header in the same directory. The preparer requires Python 3 +and its standard library. The simulation requires an O2 environment with +Geant4 and ALICE 3 simulation support, including `o2-sim-serial-run5`. + +### Input format and interpretation + +The CSV must have this header: + +```csv +PrimID,PID,PLA,X,Y,Z,TXX,TYY,TZZ,LTRACK +``` + +| Column | Meaning | +| --- | --- | +| `PrimID` | Integer source-event identifier; rows belonging to an event must be contiguous. | +| `PID` | Integer FLUKA particle ID, translated to a PDG code by the preparer. | +| `PLA` | Nonnegative total momentum in GeV/c. | +| `X,Y,Z` | Boundary position in cm, in detector coordinates. | +| `TXX,TYY,TZZ` | Direction cosines; their norm must differ from 1 by at most `1e-6`. | +| `LTRACK` | Integer source generation number, retained as metadata. | + +The preparer calculates `(px,py,pz) = PLA * normalized(TXX,TYY,TZZ)`. +It preserves the coordinate origin and axes. Each accepted row becomes an +independent transport primary; `LTRACK` is not interpreted as a parent index. +All particles start at boundary time zero. +Physical event rates, exposure, weights, upstream ancestry and collisions with +no boundary crossings cannot be inferred from this file. + +The FLUKA-to-PDG mapping is defined in `prepare_flux.py`. Light ions with IDs +`-3` through `-6` are supported. The input's custom heavy-ion convention is +`PID = Z + 1000*A`, with `4 < A <= 300` and `0 < Z <= min(A,118)`. Required ions +are registered with FairRoot before transport. + +By default, the preparer excludes IDs `-7` and `82201`, as configured for the +original sample, and records the excluded rows in `rejected.csv`. Other +unsupported or ambiguous IDs cause preparation to fail. Pass `--skip-pids` +without values to disable these default exclusions, or provide an explicit +replacement list. + +### Minimal example + +Run the following in a loaded O2 environment. Use a new run directory for each simulation. + +```bash +flux_dir="$O2_ROOT/share/Generators/external/flux" +mkdir flux-example +cd flux-example + +cat > boundary.csv <<'EOF' +PrimID,PID,PLA,X,Y,Z,TXX,TYY,TZZ,LTRACK +1,11,10,0,0,-1900,0,0,1,1 +2,7,2,1,0,-1900,0,0,1,1 +EOF + +python3 "$flux_dir/prepare_flux.py" boundary.csv prepared_test --events 0 +export ALICE3_FLUX_DATA="$PWD/prepared_test/events.dat" + +# Use the number of prepared events, including any emptied by PID exclusions. +events=$(python3 -c 'import json; print(json.load(open("prepared_test/input_report.json"))["events"])') + +o2-sim-serial-run5 -n "$events" -g extgen -e TGeant4 -m TRK \ + --vertexMode kNoVertex --seed 12345 \ + --configKeyValues "GeneratorExternal.fileName=$flux_dir/GeneratorFlux.C;GeneratorExternal.funcName=GeneratorFromFlux();TRKBase.layoutMLOT=kSegmented;SimCutParams.tunnelZ=1e20;align-geom.mDetectors=none" +``` + +The example contains one muon event and one photon event. Replace `boundary.csv` +with your own input path to simulate an external sample. `--events 0` selects +all populated groups; `--events N` selects at most N groups, and `--skip-events N` +skips N populated groups. Groups emptied by exclusions remain events. Missing `PrimID` values do not +create empty events. The generator streams the prepared events in order and +throws an error if asked for more than the prepared count; it does not recycle +the input. + + +### Boundary coordinates and transport settings + +The generator explicitly sets position units to cm and disables collision +vertex shifting and smearing in `Init()`, preserving the boundary coordinates. +This also handles serial simulation configurations where `--vertexMode` is not +forwarded to the primary generator. + +Some boundary positions can lie outside O2's default world. The preparer +calculates world half-lengths containing all accepted starting positions with +a 1 cm margin, retaining minimum half-lengths of `(2000,2000,3000)` cm. The +generator enlarges the box-shaped world before geometry closure. + +`SimCutParams.tunnelZ=1e20` effectively disables the default longitudinal +tunnel-radius cut, which can otherwise discard these boundary particles. +Standard transport thresholds remain active, including the default neutron +transport cut; configure them explicitly e.g. for low-energy study. + +### Prepared files and simulation output + +The preparer writes: + +- `events.dat`: grouped PDG particle records consumed by the generator. +- `primaries.csv`: source event, source line, `PID`, `LTRACK`, and accepted + particle positions and momenta, indexed by prepared event and primary. +- `rejected.csv`: explicitly excluded source rows and their reason. +- `input_report.json`: selected event IDs, counts, ion species, world dimensions + and preparation settings. + +`events.dat` is a custom whitespace-delimited format. It starts with `ALICE3_FLUX_V1`, followed by the event count, ion count, +and three world half-lengths in cm. Next come the ion PDG codes. Each event then +contains its original `PrimID` and particle count, followed by records with +`PDG px py pz x y z` in GeV/c and cm. The generator consumes only this file; +keep the other prepared files for provenance. + +The simulation produces the standard native O2 outputs, including +`o2sim_Kine.root`, `o2sim_MCHeader.root` and `o2sim_HitsTRK.root` for the command +above. Event headers contain `flux_PrimID` and `flux_nPrimaries`. Standard O2 +primary handling still applies, including the projection of flavour neutral +kaons onto transported KS/KL states. Digitization, overlay and analysis are +separate downstream steps. + diff --git a/Generators/share/external/flux/prepare_flux.py b/Generators/share/external/flux/prepare_flux.py new file mode 100755 index 0000000000000..269e78069517c --- /dev/null +++ b/Generators/share/external/flux/prepare_flux.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Validate LHC FLUKA boundary particles and prepare event records for O2's extgen.""" +import argparse +import collections +import csv +import itertools +import json +import math +from pathlib import Path +import shutil + + +# FLUKA manual, section 5.1 (https://www.fluka.eu/Fluka/www/html/content/manuals/online/5.1.html). +PDG = dict(enumerate([ + 0, 2212, -2212, 11, -11, 12, -12, 22, 2112, -2112, -13, 13, + 130, 211, -211, 321, -321, 3122, -3122, 310, 3112, 3222, 3212, + 111, 311, -311, 0, 14, -14, 0, 0, -3222, -3212, -3112, + 3322, -3322, 3312, -3312, 3334, -3334, 0, -15, 15, 16, -16, + 411, -411, 421, -421, 431, -431, 4122, 4232, 4132, 4322, + 4312, 4332, -4122, -4232, -4132, -4322, -4312, -4332, +])) +PDG.update({-3: 1000010020, -4: 1000010030, -5: 1000020030, -6: 1000020040}) +HEADER = ['PrimID', 'PID', 'PLA', 'X', 'Y', 'Z', 'TXX', 'TYY', 'TZZ', 'LTRACK'] + + +def pdg_code(pid): + if pid in PDG and PDG[pid]: + return PDG[pid] + # Custom heavy-ion encoding: Z + A*1000. + a, z = divmod(pid, 1000) + if 4 < a <= 300 and 0 < z <= min(a, 118): + return 1000000000 + z * 10000 + a * 10 + raise ValueError(f'unsupported or ambiguous FLUKA PID {pid}') + + +def prepare(input_path, output, events=1, skip_events=0, skip_pids=(-7, 82201)): + output = Path(output) + output.mkdir(parents=True, exist_ok=True) + input_path = Path(input_path).resolve() + counts, rejected_counts = collections.Counter(), collections.Counter() + ions, seen, event_ids = set(), set(), [] + bounds = [2000., 2000., 3000.] + n_input = n_accepted = 0 + provenance_header = ['event', 'PrimID', 'primary', 'source_line', 'PID', 'LTRACK', + 'pdg', 'px_GeV', 'py_GeV', 'pz_GeV', 'x_cm', 'y_cm', 'z_cm'] + body_path = output / 'events.body' + with input_path.open(newline='') as source, body_path.open('w') as body, \ + (output / 'primaries.csv').open('w', newline='') as provenance, \ + (output / 'rejected.csv').open('w', newline='') as rejected: + reader = csv.reader(source) + if next(reader, None) != HEADER: + raise ValueError(f'expected CSV header {",".join(HEADER)}') + pw, rw = csv.writer(provenance), csv.writer(rejected) + pw.writerow(provenance_header) + rw.writerow(['source_line', 'reason'] + HEADER) + rows = enumerate(reader, start=2) + for ordinal, (key, group) in enumerate(itertools.groupby(rows, key=lambda item: int(item[1][0]))): + if key in seen: + raise ValueError(f'PrimID {key} is not contiguous; sort the input by PrimID first') + seen.add(key) + if ordinal < skip_events: + for _ in group: + pass + continue + if events and len(event_ids) >= events: + break + event = len(event_ids) + particles = [] + for line, row in group: + if len(row) != 10: + raise ValueError(f'line {line}: expected 10 columns, got {len(row)}') + pid, generation = int(row[1]), int(row[9]) + values = list(map(float, row[2:9])) + if not all(map(math.isfinite, values)) or values[0] < 0: + raise ValueError(f'line {line}: invalid momentum, position, or direction') + momentum, x, y, z, dx, dy, dz = values + norm = math.sqrt(dx*dx + dy*dy + dz*dz) + if abs(norm - 1.) > 1.e-6: + raise ValueError(f'line {line}: direction cosine norm {norm} differs from 1') + n_input += 1 + counts[pid] += 1 + if pid in skip_pids: + rw.writerow([line, 'explicitly excluded PID'] + row) + rejected_counts[pid] += 1 + continue + try: + pdg = pdg_code(pid) + except ValueError as exc: + raise ValueError(f'line {line}: {exc}') from exc + if pdg >= 1000000000: + ions.add(pdg) + # Normalization only removes rounding in the supplied direction cosines. + px, py, pz = (momentum * d / norm for d in (dx, dy, dz)) + primary = len(particles) + record = [pdg, px, py, pz, x, y, z] + particles.append(record) + pw.writerow([event, key, primary, line, pid, generation] + record) + for axis, coordinate in enumerate((x, y, z)): + bounds[axis] = max(bounds[axis], abs(coordinate) + 1.) + n_accepted += 1 + event_ids.append(key) + body.write(f'{key} {len(particles)}\n') + for record in particles: + body.write(' '.join(str(v) for v in record) + '\n') + if not event_ids: + raise ValueError('no events selected') + with (output / 'events.dat').open('w') as destination, body_path.open() as body: + destination.write('ALICE3_FLUX_V1\n') + destination.write(f'{len(event_ids)} {len(ions)} ' + ' '.join(map(str, bounds)) + '\n') + for ion in sorted(ions): + destination.write(f'{ion}\n') + shutil.copyfileobj(body, destination) + body_path.unlink() + report = dict(input=str(input_path), events=len(event_ids), prim_ids=event_ids, + input_particles=n_input, accepted_particles=n_accepted, + skipped_particles=n_input-n_accepted, pid_counts=dict(counts), + skipped_pid_counts=dict(rejected_counts), ion_pdgs=sorted(ions), + world_half_lengths_cm=bounds, skip_events=skip_events, + time_assumption='All boundary particles start at t=0; no times supplied.') + (output / 'input_report.json').write_text(json.dumps(report, indent=2) + '\n') + return report + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('input', type=Path) + parser.add_argument('output', type=Path) + parser.add_argument('--events', type=int, default=1, help='populated PrimID groups; 0 selects all') + parser.add_argument('--skip-events', type=int, default=0, help='skip this many populated groups') + parser.add_argument('--skip-pids', type=int, nargs='*', default=[-7, 82201], + help='explicit exclusions, recorded in rejected.csv; empty enables strict validation') + args = parser.parse_args() + if args.events < 0 or args.skip_events < 0: + parser.error('event counts must be nonnegative') + try: + report = prepare(args.input, args.output, args.events, args.skip_events, args.skip_pids) + except (OSError, ValueError) as exc: + parser.exit(1, f'Flux preparation failed: {exc}\n') + print(f"Prepared {report['events']} events, {report['accepted_particles']} particles; " + f"excluded {report['skipped_particles']} (see rejected.csv).") + + +if __name__ == '__main__': + main()