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
5 changes: 5 additions & 0 deletions Generators/share/external/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
58 changes: 58 additions & 0 deletions Generators/share/external/flux/FluxData.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/// \author nicolo.valle@cern.ch

#ifndef ALICE3_INPUT_FLUX_DATA_H
#define ALICE3_INPUT_FLUX_DATA_H
#include <array>
#include <fstream>
#include <stdexcept>
#include <string>
#include <vector>


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<Particle> next(long long& primID)
{
size_t n;
if (!(stream >> primID >> n)) {
throw std::runtime_error("Flux exhausted before requested event count");
}
std::vector<Particle> 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<double, 3> bounds;
std::vector<int> ions;

private:
std::ifstream stream;
};
} // namespace alice3flux
#endif
121 changes: 121 additions & 0 deletions Generators/share/external/flux/GeneratorFlux.C
Original file line number Diff line number Diff line change
@@ -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 <algorithm>
#include <cmath>


// 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<double, 3> bounds)
: FairModule("FluxWorldEnvelope", "World containing external flux"), mBounds(bounds) {}
void ConstructGeometry() override
{
auto* box = dynamic_cast<TGeoBBox*>(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<double, 3> 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<o2::eventgen::PrimaryGenerator*>(
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<int>(mEventParticles.size()));
}

private:
alice3flux::Input mInput;
std::vector<alice3flux::Particle> 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);
}
136 changes: 136 additions & 0 deletions Generators/share/external/flux/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
<!-- doxy
\page refGeneratorsshareexternalflux External boundary flux
/doxy -->

# 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.

Loading