\mainpage ML_LWFA
# ML_LWFA Simulation – Plasma Beam Generation with Geant4 & ML Integration

**Project Authors:** Arnaud HUBER & Alexei SYTOV
**Date:** 2024–2025
**Collaboration:** GEANT4, PALLAS Project

---

## Table of Contents

- Introduction
- Features
- Dependencies
- Installation
- Building the Simulation
- Running the Simulation
- ML_LWFA Macro Configuration
- Primary Generator
- ONNX Model Inference for Plasma Beam Generation
- Geometry Utilities
- PALLAS Geometry Construction
- PALLAS MagneticField
- Physics List
- Quadrupole Utilities
- Step-Level Tracking and Data Extraction
- ROOT Output
- Architecture Diagram
- Automated Testing
- Documentation
- License

---

## Introduction

The ML_LWFA simulation framework is a Geant4-based toolkit for modeling plasma-accelerated particle beams.
It integrates traditional Monte Carlo methods with machine learning-based ONNX beam generation, allowing flexible, high-fidelity simulations of beam transport through dipole and quadrupole fields according to PALLAS experiment.

🎯 Audience: Physicists, accelerator scientists, ML/physics integration developers.

🧩 Applications: Plasma accelerators, beamline design, detector response studies.

⚡ Strength: Combines ML inference + Geant4 physics + ROOT data analysis in a single workflow.

---

## Features

- Primary particle generation via:
  - Geant4 General Particle Source (GPS) — always available
  - ONNX ML model — available when compiled with `-DML_LWFA_USE_ONNX=ON`
- Custom physics list optimized for plasma and nuclear physics:
  - High-precision hadronic and electromagnetic physics
  - Ion interactions and stopping physics
  - Decay and radioactive decay
- Magnetic field simulation:
  - Dipole and quadrupole contributions
  - Fitted field maps (error function + Gaussian)
- Quadrupole tracking utilities
- User interface commands for interactive parameter adjustment
- Multithreaded event generation with progress display
- Doxygen-documented codebase

---

## Dependencies

- Geant4 >= 11.5 with GDML option **ACTIVATED**
```
cmake -DGEANT4_USE_GDML=ON
```
- CLHEP (units & constants)
- ONNX Runtime 1.17.1 (**optional** — required only for ML-based beam generation; see [Building the Simulation](#building-the-simulation))
- ROOT (for output TTrees)
- CMake >= 3.16
- C++17 or later
- Standard libraries: `<atomic>`, `<chrono>`, `<vector>`, `<string>`, `<cmath>`, `<memory>`

---

## Building the Simulation

ONNX support is **disabled by default**. Two build modes are available:

### Default build — GPS mode (no ONNX)

```bash
mkdir build && cd build
cmake -DGeant4_DIR=$G4COMP ../
make -j$(nproc)
```

Beam generation uses the Geant4 General Particle Source (GPS) only.
The macro command `/ML_LWFA/gun/setStatusONNX 1` has no effect in this mode.

### Build with ONNX support — ML mode

```bash
mkdir build && cd build
cmake -DGeant4_DIR=$G4COMP -DML_LWFA_USE_ONNX=ON -DOnnxRuntime_ROOT=/path/to/onnxruntime-linux-x64-1.17.1 ../
make -j$(nproc)
```

ONNX Runtime must be installed by the user (see https://onnxruntime.ai). The version
tested with `model2.onnx` is 1.17.1. CMake searches for it in this order:

1. **User hint**: `OnnxRuntime_ROOT`, the root of a local installation
   (it must contain `lib/` and `include/`).
2. **System install**: if `libonnxruntime` is found on the standard system paths,
   it is used directly.

If ONNX Runtime is not found, the configuration stops with an explicit error message.
There is no automatic download.

Example of installation (Linux x86\_64, CPU version):

```bash
wget https://github.com/microsoft/onnxruntime/releases/download/v1.17.1/onnxruntime-linux-x64-1.17.1.tgz
tar xzf onnxruntime-linux-x64-1.17.1.tgz
```

For another platform, architecture or a GPU version, choose the matching archive on
https://onnxruntime.ai.

### GDML geometry files

The detector components are described by GDML files (about 10 MB, 24 files) that are
**not stored in the repository**. They are downloaded automatically at configure time
(CMake `FetchContent`) from the Geant4 data area:

```
https://cern.ch/geant4-data/datasets/examples/advanced/ML_LWFA/0/ML_LWFA_geometry.tar.gz
```

- Internet access is required the first time the project is configured (in both build modes).
- The archive integrity is checked with an MD5 checksum.
- The files are copied to `gdml_models/` in the build directory, next to the executable.
  The program loads them with a path relative to the current directory, so run
  `ML_LWFA` from the build directory.

### Output

The executable `ML_LWFA` is placed in the build directory, together with the macros
(`macro_high_charge_divergence.mac`, `macro_low_charge_divergence.mac`, `vis.mac`),
`model2.onnx` and the `gdml_models/` directory.

---

## Running the Simulation

- **With visualization:**

```bash
./ML_LWFA
```

It will generate particles according to the macro (e.g., `vis.mac`) and produce a ROOT file named visu.root.

- **Without visualization (statistics only) Single-Thread:**

```bash
./ML_LWFA [name_of_ROOT_file] [number_of_events] [macro_file]
```

- **Without visualization (statistics only) Multi-Thread:**

```bash
./ML_LWFA [name_of_ROOT_file] [number_of_events] [macro_file] [Number_of_Thread]
```

**Notes:**
- In multi-threaded mode, the temporary ROOT files of each thread are merged at the end
  into `<outputFile>.root`. In sequential mode, a single file is written and simply
  renamed to `<outputFile>.root`.
- You can use any macro file. Two macros using the Geant4 GPS source are provided,
  each reproducing the beam that the ONNX model would generate for a given set of
  parameters (`Ekin`, `dEkin`, `Q`, `epsb`):

| Macro | Beam | Description |
|-------|------|-------------|
| `macro_high_charge_divergence.mac` | `Ekin = 211.63 MeV`, `dEkin = 0.053`, `Q = 2.045e-10`, `epsb = 5.38e-6` | Relatively high pressure and strong intensity at upstream focus, leading to strong self-focusing and a very high injected charge, even for a low dopant concentration. This high charge induces a high emittance. Interesting for high energy physics and radiation therapy applications. This is the macro used by the CTest. |
| `macro_low_charge_divergence.mac` | `Ekin = 201.34 MeV`, `dEkin = 0.036`, `Q = 3.33e-11`, `epsb = 9.3e-7` | Moderate pressure, relatively low intensity, and a downstream focus leading to mild self-focusing in a medium dopant concentration, hence a quite low injected charge. Very small energy spread and emittance. Interesting candidate for XFEL generation. |

- In both macros, the transverse phase space is Gaussian with Twiss parameters
  `alpha = 0`, `beta = 1`, `eps_x = epsb / 2.5` and `eps_z = epsb`, so that
  `sigma_position = sigma_angle = sqrt(eps)`. The bunch charge `Q` is not used by GPS.
- `vis.mac` is used in visualization mode (`./ML_LWFA` without argument).

---

## ML_LWFA Macro Configuration

This macro configures geometry, magnetic fields, tracking, and particle sources for ML_LWFA simulations. It allows full customization of quadrupole setup, dipole fields, and particle generation methods.

**Geometry Configuration:**

- Quadrupole lengths: Q1-Q4 individually configurable.
- Distances: between source, quadrupoles and collimators.
- Display options: toggle full geometry, quadrupoles and collimators for visualization.
- Changes are applied with `/run/reinitializeGeometry`.

**Magnetic Fields Configuration:**

- Quadrupole gradients: individually set for Q1-Q4.
- B-field map mode: can be enabled/disabled for dipole spectrometer

**Tracking options Configuration:**

- Particle tracking can be enabled/disabled globally or for collimators interaction.
- Verbosity controls for both tracking and run output.

**Particle Sources Configuration:**

- ONNX-based Particle Gun:
  - Particle type, laser focus, normalized vector potential, dopant fraction and chamber pressure configurable.
- GEANT4 GPS (General Particle Source):
  - Number, type, position, direction and energy of particles.

This macro provides a ready-to-use setup for simulations with either the particle gun or GPS, including full control over magnetic fields and geometry.

**User Interface Commands:**

- `/ML_LWFA/geometry/...` – Geometry configuration
- `/ML_LWFA/display/...` – Geometry visualization options
- `/ML_LWFA/field/...` – Magnetic field configuraiton
- `/ML_LWFA/step/...` – Particle tracking settings
- `/ML_LWFA/gun/...` – Particle generation
- `/ML_LWFA/laser/...` – ML laser parameters

**Controls:**
- ONNX particle gun: enable/disable (`/gun/setStatusONNX`)
- Particle type: set particle name (`/gun/setParticleName`)
- Laser parameters:
  - focus offset: `/laser/setOffsetLaserFocus`  [-399.824698 ; 1798.325132]
  - normalized vector potential: `/laser/setNormVecPotential` [1.100516 ; 1.849792]
  - dopant fraction: `/laser/setFracDopTargetChamber` [0.002064 ; 0.119983]
  - chamber pressure: `/laser/setPressure`  [10.094508 ; 9.957409]
- Quadrupoles:
  - lengths: `/geometry/setQnLength`
  - positions and distances between quadrupoles or source: `/geometry/setSourceQ1Distance`, `/geometry/setQnQn+1Distance`
- Magnetic fields:
  - quadrupole gradients: `/field/setQnGradient`
  - dipole field value: `/field/setConstantDipoleBField`
- Collimators:
  - Horizontal slit opening (total opening): `/geometry/setHorizontalSlitOpening`
  - Vertical slit opening (total opening): `/geometry/setVerticalSlitOpening`
- Tracking:
  - enable/disable globally: `/step/SetTrackingStatus`
  - enable/disable for collimators: `/step/SetTrackingStatusCollimators`
- Display:
  - enable/disable dump : `/display/setStatusDisplayDump`
  - enable/disable quadrupoles: `/display/setStatusDisplayQuadrupoles`
  - enable/disable collimators: `/display/setStatusDisplayCollimators`
- GPS (alternative to particle gun):
  - particle number: `/gps/number`
  - particle type: `/gps/particle`
  - particle position: `/gps/pos`
  - particle direction: `/gps/direction`
  - particle energy: `/gps/energy`

---

## Primary Generator

**Class:** `PrimaryGeneratorAction`

The PrimaryGeneratorAction class handles the generation of primary particles for the ML_LWFA simulation. It supports two generation modes:

**Modes:**
- ONNX ML-based beam generation:
  - Uses a neural network to predict beam parameters (energy, charge, emittance, transverse positions and momenta).
  - Configures the particle gun based on the predicted parameters.
  - Energy smearing with Gaussian fluctuations is applied.
- GPS particle source:
  - Standard particle generation using the Geant4 GPS

**Features:**

- Thread-safe generation using Mutex.
- Automatic particle definition lookup in the Geant4 particle table.

**Usage:**

- Instantiate the class and assign it to Geant4 run manager using `SetUserAction`
- Configure ONNX or GPS parameters via the messenger before starting the run.

---

## ONNX Model Inference for Plasma Beam Generation

**Class:** `OnnxInference`

The `OnnxInference` class provides a mechanism to generate physically realistic beam parameters using a pre-trained ONNX neural network model. It is used to configure the primary particle gun in the ML_LWFA simulation.

**Functionality:**

- Initializes the ONNX runtime environnment and loads the specific model.
- Prepares input tensors from simulation parameters:
  - Laser focal offset `fXof`
  - Laser normalized amplitude `fA0`
  - Fraction Dopant in Chamber `fCN2`
  - Gas pressure in Chamber `fPressure`
- Runs inference and converts model outputs to physical units.
- Samples transverse beam coordinates (`x`, `z`) and angles (`xp`, `zp`) using Gaussian/Twiss-based distributions
- Produces a `BeamParameters` structure containing:
  - Kinetic energy `Ekin` and energy spread `dEkin`
  - Beam charge `Q`
  - Normalized emittance `epsb`
  - Transverse positions (`x`, `z`) and angles (`xp`, `zp`)

**Purpose:**

- To generate ONNX-predicted particle beams with realistic physical characteristics for use in Geant4 simulations.
- Integrates seamlessly with the primary generator action (`PrimaryGeneratorAction`) for ONNX-based particle generation.

**Conditional compilation:**

- The entire class is guarded by `#ifdef ML_LWFA_USE_ONNX` / `#endif`.
- If the simulation is compiled **without** `-DML_LWFA_USE_ONNX=ON`, this class is not compiled
  and the ONNX particle gun is silently unavailable at runtime.

**Units:**

- All physical quantities are expressed using CLHEP units.

---

## Geometry Utilities

**File:** `Geometry.cc`

The `Geometry` class provides tools to define and load geometrical volumes for the ML_LWFA simulation.
It centralizes the construction of detector and beamline components, either from GDML descriptions or via simplified Geant4 primitives.

**Features:**

- GDML Import: Load volumes from GDML files and assign materials dynamically.
- Quadrupole Construction: Generate simplified quadrupole magnets as vacuum-filled box volumes.
- Diagnostics Chambers: Create cylindrical chambers by subtracting tubular volumes, useful for fast detector prototyping.

**Example:**

```cpp
// Load a GDML-defined volume
auto* vol = geometry.GetGDMLVolume("beamline.gdml", "Target", material);

// Create a simple quadrupole
auto* quad = geometry.GetQuadrupoleVolume("Q1", 50, 50, 200);

// Build a diagnostic chamber
auto* chamber = geometry.GetFakeDiagsChamber();
```

This utility simplifies beamline setup and makes it easier to switch between realistic GDML-based geometries and fast approximations for testing.

---

## ML_LWFA Geometry Construction

**File:**: `GeometryConstruction.cc`

This module handles the full PALLAS experimental geometry in Geant4, including CAD/GDML model imports, definition of logical and physical volumes, and magnetic field configuration for simulations.

**Overall Structure:**

- World and Holder: global empty volume serving as the main container for all components. Holder is here to count and stop particles which are going to the World volume.
- Plasma Cells: assembly of two connected plasma cells
- LIF (Laser-Induced Fluorescence): optical components (windows, crosses, breadbords, ...).
- Quadrupoles:
  - Simplified: parametrized volumes for production runs.
  - Full: GDML imported from CAD models for detailed visualization.
- Experimental Sections:
  - Section 1: ISO chamber, base and plasma cell supports.
  - Section 2: Removal chambers and ISO tubes.
  - Section 3: ASM and YAG station.
  - Section 4: Dipole chamber, dipole magnet and associated diagnostics.
  - Section 4 Dump: shielding, chassis and protection components.
- Collimators:
  - GDML : horizontal and vertical collimators from GDML files, manually aligned with the beam axis.
  - Fake Collimators with G4Box in order to vary the slit openings (vertical & horiizontal)

**Magnetic Fields:**

- Complete magnetic field configuration:
  - Constant dipole field.
  - Quadrupole gradients (Q1-Q4).
  - Drift distances and quadrupole lengths.
- Uses `G4FieldManager`and `G4ChordFinder` with a classical RK4 stepper for accurate particle tracking.

**Construction Modes:**

- Full Geometry: all sections and GDML volumes for complete visualization.
- Simplified Geometry: only Section 4, avoiding potential stuck tracks from complex GDML during production simulations.

**Visualization:**

-Logical volumes are color-coded for easier inspection:
  - Red: quadrupoles and ISO chambers.
  - Cyan: Sections 2 and 4.
  - Orange: Section 3.
  - Green: LIF components.
  - Yellow: collimators and some diagnostics chambers

**Notes:**

- Some GDML files (e.g. ISO chamber) may require adjustements for stable operation.
- Manual offsets are applied to quadrupoles and collimators to align components precisely with the beam.

---

## ML_LWFA MagneticField

**File:**: `MagneticField.cc`

This class provides the magnetic field configuration for the ML_LWFA simulation in Geant4, combining dipole and quadrupole contributions with optional mapped-field profiles. It includes both field computation and parameter management.

**Features:**

- Dipole Field:
  - Constant.
  - Can be enabled/disabled at runtime

- Quadrupoles Fields:
  - Configurable gradients, lengths and drift distances.
  - Contributions automatically applied in the relevant spatial regions.

**Magnetic Field Computation:**

- `GetFieldValue(point, bField)`: computes the total magnetic field at any point in space.
- Quadrupole contributions are added only if the particle is within their defined range.

**Configuration Methods:**

- `SetDipoleField(value)`: set constant dipole field in Tesla.
- `SetGradient(index, value)`, `SetQLength(index, value)`, `SetQDrift(index, value)`: configure quadrupoles individually.
- Corresponding getters are provided for all quadrupole parameters.

**Units:**

- Compatible with GEANT4 and CLHEP units for length, field and gradient.

---

## Physics List

**Class:** `Physics`
Derived from `G4VModularPhysicsList`

**Includes:**
- High-precision hadronic and elastic models
- Electromagnetic physics (`G4EmStandardPhysics_option3`)
- Stopping physics
- Decay and radioactive decay

---

## Quadrupole Utilities

**File:** `QuadrupoleUtils.cc`

Update individual vector components of quadrupoles (position or momentum, start or end).

**Example:**

```cpp
SetQuadrupoleValue(stats, QuadID::Q1, PositionType::Begin, VectorType::Position, Axis::X, 0.1f);
```

---

## Step-Level Tracking and Data Extraction

**File:** `SteppingAction.cc`

The `SteppingAction` class handles fine-grained particle tracking at each simulation step in the ML_LWFA project. It collects particle data, manages quadrupole interactions, collimator events, and YAG screen statistics.

**Functionality:**

- Extracts positions, momentum directions, kinetic energy and deposited energy at each Geant4 step.
- Stores initial beam parameters for primary particles at the first step.
- Tracks particle crossings through quadrupoles and records entry/exit statistics.
- Updates collimator interactions: records positions and energies, optionally terminates tracks if collimator tracking is disabled.
- Updates YAG screen statistics: exit positions, deposited energy, particle IDs and total deposited energy.
- Automatically kills particles leaving the world volume.

**Purpose:**

- Provides detailed per-step data collection for beamline analysis.
- Enables statistics for quadrupoles, collimators and diagnostics screens.
- Integrates with `EventAction` for storing and tallying simulation results.

---

## ROOT Output

- `BeginOfRunAction` creates 7 trees:

    - `Tree_GlobalInput` – Simulation and ML parameters - filled 1 time per file
      - `NEvents`- Total number of events simulated
      - `Display_Dump`- Dump volumes created (1=yes ; 0=no)
      - `Display_Collimators`- Collimators volumes created (1=yes ; 0=no)
      - `Display_Quadrupoles`- Quadrupoles volumes created (1=yes ; 0=no)
      - `Q1_Length`- Quadrupole Q1 Length
      - `Q2_Length`- Quadrupole Q2 Length
      - `Q3_Length`- Quadrupole Q3 Length
      - `Q4_Length`- Quadrupole Q4 Length
      - `SourceQ1Distance`- Distance from the source to Q1
      - `Q1Q2_Distance`- Distance between Q1 & Q2
      - `Q2Q3_Distance`- Distance between Q2 & Q3
      - `Q3Q4_Distance`- Distance between Q3 & Q4
      - `Q1_Grad`- Constant Q1 gradient field
      - `Q2_Grad`- Constant Q2 gradient field
      - `Q3_Grad`- Constant Q3 gradient field
      - `Q4_Grad`- Constant Q4 gradient field
      - `B_Dipole`- Constant Dipole field
      - `Xoff`- Laser focus offset input parameter for ML model
      - `A0`- Normalized vector potential input parameter for ML model
      - `cN2`- Dopant fraction in target chamber input parameter for ML model
      - `p`- Chamber pressure input parameter for ML model
      - `Ekin`- Mean kinetic energy output parameter from ML model
      - `dEkin`- Sigma kinetic energy output parameter from ML model
      - `Q`- Bea charge output parameter from ML model
      - `Epsb`- Normalized emittance output parameter from ML model

    - `Tree_Input` – Particle initial positions, momenta, offsets - filled at primary particle creation
      - `x`- Position x for the primary particle
      - `y`- Position y for the primary particle
      - `z`- Position z for the primary particle
      - `xp`- Momentum xp for the primary particle
      - `yp`- Momentum yp for the primary particle
      - `zp`- Momentum zp for the primary particle
      - `energy`- Energy of the primary particle

    - `Tree_Quadrupoles` – Particle tracking in quadrupoles - filled when volume transition
      - `Q1BeginPos_x`- Entrance x position on Q1
      - `Q1BeginPos_y`- Entrance y position on Q1
      - `Q1BeginPos_z`- Entrance z position on Q1
      - `Q1EndPos_x`- Exit x position on Q1
      - `Q1EndPos_y`- Exit y position on Q1
      - `Q1EndPos_z`- Exit z position on Q1
      - `Q2BeginPos_x`- Entrance x position on Q2
      - `Q2BeginPos_y`- Entrance y position on Q2
      - `Q2BeginPos_z`- Entrance z position on Q2
      - `Q2EndPos_x`- Exit x position on Q2
      - `Q2EndPos_y`- Exit y position on Q2
      - `Q2EndPos_z`- Exit z position on Q2
      - `Q3BeginPos_x`- Entrance x position on Q3
      - `Q3BeginPos_y`- Entrance y position on Q3
      - `Q3BeginPos_z`- Entrance z position on Q3
      - `Q3EndPos_x`- Exit x position on Q3
      - `Q3EndPos_y`- Exit y position on Q3
      - `Q3EndPos_z`- Exit z position on Q3
      - `Q4BeginPos_x`- Entrance x position on Q4
      - `Q4BeginPos_y`- Entrance y position on Q4
      - `Q4BeginPos_z`- Entrance z position on Q4
      - `Q4EndPos_x`- Exit x position on Q4
      - `Q4EndPos_y`- Exit y position on Q4
      - `Q4EndPos_z`- Exit z position on Q4
      - `energy`- Energy of the primary particle

    - `Tree_HorizontalColl` – Particle tracking in Horizontal collimator - filled for primary particle interaction
      - `x_interaction`- Position x interaction
      - `y_interaction`- Position y interaction
      - `z_interaction`- Position z interaction
      - `energy`- Energy of the primary particle

    - `Tree_VerticalColl` – Particle tracking in Vertical collimator - filled for primary particle interaction
      - `x_interaction`- Position x interaction
      - `y_interaction`- Position y interaction
      - `z_interaction`- Position z interaction
      - `energy`- Energy of the primary particle

    - `Tree_BSYAG` – Particles interacting with YAG, magnet OFF - filled when particle interaction with YAG (all because we use vectors)
      - `x_exit`- Exit x position YAG
      - `y_exit`- Exit y position YAG
      - `z_exit`- Exit z position YAG
      - `parentID`- ParentID particle
      - `particleID`- ParticleID particle (https://epos4learn.docs.cern.ch/docs/Execution/tableid/)
      - `energy`- Energy of the particle at YAG entrance
      - `deposited_energy`- Deposited energy on YAG

    - `Tree_BSPECYAG` – Particles interacting with YAG, magnet ON - filled when particle interaction with YAG (all because we use vectors)
      - `x_exit`- Exit x position YAG
      - `y_exit`- Exit y position YAG
      - `z_exit`- Exit z position YAG
      - `parentID`- ParentID particle
      - `particleID`- ParticleID particle (https://epos4learn.docs.cern.ch/docs/Execution/tableid/)
      - `energy`- Energy of the particle at YAG entrance
      - `deposited_energy`- Deposited energy on YAG

- Variables are initialized in `BeginOfEventAction` and filled in `EndOfEventAction`.
- Particle propagation and interaction info is collected in `SteppingAction.cc`.

---

## Architecture Diagram

```
+------------------------------+
|        ML_LWFA Simulation     |
+------------------------------+
            |
            v
+------------------------------+
|  PrimaryGeneratorAction      |
|  - GPS / ONNX ML Beam        |
+------------------------------+
            |
            v
+------------------------------+
|   ONNXInference (optional)   |
|  - GenerateBeam(params)      |
|  - requires ONNX=ON at build |
+------------------------------+
            |
            v
+------------------------------+      +-------------------------+
|         MagneticField        |<---->| Quadrupole Utilities    |
|     (Dipole + Quadrupoles)   |      |  - Set/Update Vectors   |
+------------------------------+      +-------------------------+
            |
            v
+------------------------------+
|    Physics List (EM + Had)   |
|  - G4EmStandardPhysics_option3|
|  - G4HadronPhysicsQGSP_BIC_HP|
|  - Ion, Stopping, Decay      |
+------------------------------+
            |
            v
+------------------------------+
|   Event Generation & Output  |
+------------------------------+
```

---

## Tests

The example provides two CTest tests, defined in
`tests/ctests_examples/CMakeLists.txt`:

| Test | Role |
|------|------|
| `example-adv-ML_LWFA` | Runs the simulation (100000 events, `macro_high_charge_divergence.mac`, No MT, GPS source) and produces `output.root`. |
| `example-adv-ML_LWFA-check` | Runs `ML_LWFA_check` on `output.root` and fails if the results are not as expected. It only runs if the first test succeeded. |

Run them from the build directory:

```bash
ctest -R ML_LWFA -V
```

### What is checked

`ML_LWFA_check` (source: `check_output.cc`) reads the ROOT file with the ROOT
C++ API only (no extra dependency) and returns `0` if all checks pass, `1`
otherwise. Each check prints one `OK:` or `FAIL:` line.

1. **File structure**: the file can be opened and contains the trees
   `GlobalInput`, `Input`, `QuadrupolesTracking`, `Horizontal_Coll`,
   `Vertical_Coll`, `BSYAG` and `BSPECYAG`.
2. **Number of events**: `NEvents` is read from `GlobalInput` (the maximum
   over its entries, since multi-threaded files contain one entry per thread).
3. **Input beam**: the `Input` tree has between 99% and 100% of `NEvents`
   entries, all values are finite, and the mean and standard deviation of
   `energy`, `x`, `z`, `xp`, `zp` agree with the beam defined by the GPS
   commands of `macro_high_charge_divergence.mac` (see below).
4. **Collimators**: the percentage of simulated events recorded in
   `Horizontal_Coll` and `Vertical_Coll` (entries / `NEvents`) lies in a
   fixed range.
5. **Quadrupoles**: the 24 position and momentum branches of
   `QuadrupolesTracking` are readable and finite.
6. **YAG detectors** (`BSYAG`, `BSPECYAG`): the per-particle vectors
   (`x_exit`, `y_exit`, `z_exit`, `energy`, `particleID`, `parentID`) have the
   same size, values are finite, and no particle exceeds the maximum input
   energy.

### Expected beam (GPS)

The GPS parameters in `macro_high_charge_divergence.mac` are chosen to reproduce the beam that the ONNX
model would generate with `Ekin = 211.63 MeV`, `dEkin = 0.053`,
`epsb = 5.38e-6` (the bunch charge `Q = 2.045e-10` is not used by GPS). In the
model, the transverse phase space is Gaussian with Twiss parameters
`alpha = 0`, `beta = 1`, `eps_x = epsb / 2.5` and `eps_z = epsb`, so that
`sigma_position = sigma_angle = sqrt(eps)`.

| Branch | Expected mean | Expected sigma |
|--------|---------------|----------------|
| `energy` | 211.63 MeV | 11.22 MeV (= 0.053 x 211.63) |
| `x` | 0 | 0.001467 mm |
| `z` | 0 | 0.002320 mm |
| `xp` | 0 | 1.467e-3 rad |
| `zp` | 0 | 2.320e-3 rad |

### Statistical tolerance

The random seed depends on the clock, so each run is different. The checks use
tolerances of 5 statistical standard deviations (`k = 5`), for N entries:

- mean: `5 * sigma / sqrt(N)`
- sigma: `5 * sigma / sqrt(2 N)`

With 100000 events, the false-failure probability is of the order of 1e-6 per
check. The collimator ranges are set from measurements; they should also span
about 5 standard deviations of a binomial distribution
(`100 * sqrt(p (1 - p) / N)` percentage points).

### Updating the test

- If you change the beam in `macro_high_charge_divergence.mac` (energy, emittance, ...), update the
  expected values in `check_output.cc`: they are not read from the macro.
- If you change the number of events in the test, the tolerances adapt
  automatically, but the collimator ranges should be re-measured.
- To run the check by hand:

```bash
./ML_LWFA output 100000 macro_high_charge_divergence.mac
./ML_LWFA_check output.root
```

### Limitations

- The check validates consistency and agreement with the configured beam; it
  is not a comparison with an independent physics reference.
- The test uses the GPS source. The ONNX source is not tested (ONNX Runtime is an optional dependency).

---

## License

ML_LWFA Project – GEANT4 Collaboration

See the Geant4 LICENSE file for details - https://geant4.org/download/license
