A Wasserstein GAN with gradient penalty (WGAN-GP) trained as a fast surrogate for the Monte Carlo simulation of particles crossing the midstream monitor plane (MonitorID 4) of the COMET Phase-I experiment. One generator is trained per particle species. The generators are then sampled together at the species abundances seen on the plane, and the resulting mixed synthetic sample is evaluated against the full simulation.
src/
├── preprocess_rootfiles.py ROOT (RooTracker) files -> parquet, one batch per job
├── merge_batches.py merge the batches into a single parquet file
├── data_loader.py feature extraction, selection, streaming loader, train/test split
├── models/wgan_gp_model.py WGAN-GP generator, critic and training loop
├── main.py train one species and evaluate it on its held-out test set
├── evaluate_saved_generator.py full offline evaluation of a saved generator
├── generate_by_pdg_distribution.py mix the per-species generators into one synthetic sample
├── evaluate_saved_data.py evaluate a synthetic parquet (e.g. the mix) against real data
└── utils.py metrics (KS, Wasserstein, MMD, C2ST, 1-NN, FPD, tail test), plots
condor/
├── run.sh job wrapper: activates .venv, runs a script from the repo root
├── preprocess.sub step 1
├── merge.sub step 2
├── train_wgan_gp.sub step 3
├── evaluate_generator.sub step 4
├── generate_and_evaluate.sub step 5 (runs generate_and_evaluate.sh)
└── generate_and_evaluate.sh
gan_results/confix_electron/ example output of a training run (electron generator)
requirements.txt
RooTracker ROOT files (/vols/comet/data/MC7/merged_rootracker/)
│ 1. preprocess_rootfiles.py condor/preprocess.sub (32 jobs)
▼
data/pdgNone_monitor4_batch{0..31}.parquet
│ 2. merge_batches.py condor/merge.sub
▼
data/pdgNone_monitor4.parquet every particle at MonitorID 4 (215M rows)
│ 3. main.py --pdg <code> condor/train_wgan_gp.sub (one job per species)
▼
gan_results/<run>/ generator.pth, metrics.json, plots
├── 4. evaluate_saved_generator.py condor/evaluate_generator.sub
└── 5. generate_by_pdg_distribution.py
└── evaluate_saved_data.py condor/generate_and_evaluate.sub
The input is the COMET Phase-I RooTracker simulation output (tree
RooTrackerTree; branches StdHepPdg, StdHepP4, StdHepX4, MonitorID).
Preprocessing keeps every particle recorded at MonitorID 4 and centres
positions on the plane origin, (x, y, z) = (3259, 0, 7655.5) mm. The merged
dataset is about 14 GB and is not tracked in the repository.
When a species is loaded for training, the loader keeps the particles lying on the plane itself with a beam radius r < 350.5 mm (191M of the 215M rows pass) and builds eight features:
| Feature | Description |
|---|---|
log_t |
log of the total energy E (MeV) |
sin_phi_s, cos_phi_s |
azimuth of the position about the beam axis |
log1p_r |
log(1 + r), r the distance from the beam axis (mm) |
sin_theta, cos_theta |
polar angle of the momentum, measured from a transverse axis |
phi_p |
azimuth of the momentum |
log1p_p_mag |
log(1 + |p|), momentum magnitude (MeV) |
Angles are stored as sin/cos pairs to avoid the ±π discontinuity. The polar axis of the momentum is a transverse direction, so the singular directions (θ = 0, π) lie away from the dense forward beam peak.
Defined in src/models/wgan_gp_model.py.
- Networks. Generator: MLP from a Gaussian latent vector (128-d for the results below) through 512 → 1024 → 1024 → 512 to the 8 features, with LayerNorm and LeakyReLU(0.2). Critic: same widths, LeakyReLU, no normalisation.
- Objective. Wasserstein loss with gradient penalty (λ = 10), 5 critic updates per generator update, Adam (β₁ = 0, β₂ = 0.9); both learning rates decay by a factor 0.9 every 5 epochs.
- Scaling. Each feature is robust-scaled (median / interquartile range).
- Physics constraints. A penalty keeps each sin/cos pair on the unit
circle, and generated pairs are projected onto it exactly. A per-sample
penalty couples energy and momentum through E² = p² + m² with the PDG mass of
the species, and at generation
log_tis rebuilt from the generated momentum so the relation holds exactly. Angles are clipped to their range. - Model selection. 20% of the training rows are held out for validation.
The mean per-feature Wasserstein distance to them is computed every epoch;
the best checkpoint is restored at the end, and training stops after
--patienceepochs without improvement (counted after a 15-epoch warm-up).
git clone https://github.com/JonaCassens/gan_particle_physics.git cd gan_particle_physics python3 -m venv .venv # tested with Python 3.9 source .venv/bin/activate pip install -r requirements.txt
The condor jobs expect this virtualenv at .venv/ in the repository root.
Training is meant for a CUDA GPU; every script also runs on CPU for small
tests. ROOT itself is not required (the files are read with uproot).
All scripts read and write data/ relative to the repository root. On the
Imperial HEP cluster the merged dataset of steps 1–2 already exists and can be
linked in instead of rebuilt:
ln -s /vols/comet/users/jcassens/cleaned_data data
Submit every file from the repository root: the submit files locate the
repository through $ENV(PWD). Job output goes to
condor/logs/<step>_<cluster>.<proc>.{out,err,log}; follow jobs with condor_q.
| Step | Command | Runs | Output |
|---|---|---|---|
| 1 | condor_submit condor/preprocess.sub |
preprocess_rootfiles.py, 32 jobs over the sorted ROOT file list |
data/pdgNone_monitor4_batch<N>.parquet |
| 2 | condor_submit condor/merge.sub |
merge_batches.py |
data/pdgNone_monitor4.parquet |
| 3 | condor_submit condor/train_wgan_gp.sub |
main.py, one job per species (six) |
gan_results/<run>/ |
| 4 | condor_submit condor/evaluate_generator.sub |
evaluate_saved_generator.py on each run |
gan_results/<run>/generator_external_test_metrics.{json,md} |
| 5 | condor_submit condor/generate_and_evaluate.sub |
generate_by_pdg_distribution.py, then evaluate_saved_data.py |
synthetic_data/optimal_mix_6pdg_n1000000.parquet, eval_results/optimal_mix_6pdg_n1000000/ |
Each step needs the previous one to have finished; steps 4 and 5 are independent of each other.
The training configuration lives in condor/train_wgan_gp.sub: the shared
options in TRAIN_CONFIG, and one row per run in the queue table (run name,
PDG code, epochs, patience). The six rows reproduce the generators behind the
results below; to train another species, add a row.
Step 4 reads each run's configuration (PDG code, training and test sizes,
split seed) back from its training log in condor/logs/, so it regenerates
exactly the test set that was held out during training. Keep those logs, or
pass the values on the command line (next section).
Run from the repository root; every script documents its options with --help.
# 1-2. Build the dataset (one of the 32 preprocessing batches shown) python src/preprocess_rootfiles.py \ --input-glob '/vols/comet/data/MC7/merged_rootracker/midstream_merged*.rootracker' \ --monitor-id 4 --batch-num 0 --total-batches 32 python src/merge_batches.py --monitor-id 4 # 3. Train one species (the electron configuration used for the results) python src/main.py --pdg 11 --output-name confix_electron \ --entries 10000000 --test-entries 500000 --epochs 70 --patience 35 \ --gp 10 --lr-g 2e-5 --lr-c 2e-5 --n-critic 5 --batch-size 1024 --latent-dim 128 # quick check on CPU (a few minutes) python src/main.py --pdg 22 --entries 20000 --test-entries 5000 --epochs 2 --device cpu # 4. Evaluate a saved generator (without a training log, give the sizes explicitly) python src/evaluate_saved_generator.py --run-dir confix_electron \ --pdg 11 --entries 10000000 --test-entries 500000 # 5. Mix the six generators and evaluate the mix python src/generate_by_pdg_distribution.py \ --folders confix_electron confix_long_positron confix_long_muon \ confix_muon_minus confix_long_neutron confix_long_photon \ --pdg-codes 11 -11 13 -13 2112 22 \ --n-particles 1000000 --output-parquet synthetic_data/mix.parquet python src/evaluate_saved_data.py --synthetic-parquet synthetic_data/mix.parquet \ --truth-pdg-allowlist 11,-11,13,-13,2112,22 \ --n-truth 500000 --n-synthetic 500000 --per-pdg
Main training options (src/main.py):
| Option | Default | Description |
|---|---|---|
--pdg |
required | signed PDG code of the species |
--data |
data/pdgNone_monitor4.parquet |
preprocessed dataset |
--entries, --test-entries |
all rows, split 90/10 | training and held-out test rows |
--output-name, --results-dir |
timestamped, ./gan_results |
run folder |
--epochs, --patience |
100, 15 | maximum epochs, early-stopping patience |
--batch-size, --latent-dim |
512, 256 | |
--lr-g, --lr-c |
5e-5, 5e-5 | generator and critic learning rates |
--gp, --n-critic |
10, 5 | gradient-penalty weight, critic steps per generator step |
--trig-constraint-weight |
0.01 | weight of the unit-circle penalty |
--split-seed |
42 | seed of the shuffled train/test split |
--device |
cuda if available |
|
--skip-c2st, --c2st-* |
classifier two-sample test settings |
Training run (gan_results/<run>/, written by main.py):
| File | Content |
|---|---|
generator.pth, critic.pth |
weights of the best validation checkpoint |
synthetic_samples.parquet |
synthetic sample the size of the test set |
metrics.json |
per-feature KS and Wasserstein, correlation difference, MMD, C2ST with feature importance, training curves |
training_loss.png |
critic and generator loss, validation Wasserstein and MMD per epoch |
gan_comparison.png |
pairwise 2D histograms, real test set vs synthetic |
Generator evaluation (added to the run folder by
evaluate_saved_generator.py): generator_external_test_metrics.json and
.md, with the metrics above plus 1-NN accuracy, the tail exceedance test and
a real-vs-real baseline; and tail_exceedance.png.
Mix evaluation (eval_results/<name>/, written by evaluate_saved_data.py):
eval_metrics.json and .md, eval_2d_comparisons.png, tail_exceedance.png
and, with --per-pdg, eval_metrics_per_pdg.json plus the same files per
species in pdg_<code>/.
The electron generator used in the results (70 epochs, best checkpoint at
epoch 67). The folder holds generator.pth, metrics.json,
training_loss.png and gan_comparison.png; critic.pth and
synthetic_samples.parquet are left out to keep the repository small. With
the dataset in place, the generator can be re-evaluated directly (step 4).
Test-set metrics of the six generators, from the metrics.json of each run.
C2ST trains an MLP classifier to separate up to 50k real from 50k synthetic
test particles: accuracy and ROC-AUC of 0.5 mean the two are
indistinguishable. MMD is the RBF-kernel maximum mean discrepancy on up to
100k particles (ideal 0).
| Species | PDG | Run | Epochs (best) | C2ST accuracy | C2ST ROC-AUC | MMD |
|---|---|---|---|---|---|---|
| electron e⁻ | 11 | confix_electron |
70 (67) | 0.5037 | 0.5098 | 0.00509 |
| positron e⁺ | −11 | confix_long_positron |
150 (92) | 0.5021 | 0.5046 | 0.00595 |
| muon μ⁻ | 13 | confix_long_muon |
150 (86) | 0.5031 | 0.5043 | 0.00349 |
| antimuon μ⁺ | −13 | confix_muon_minus¹ |
70 (68) | 0.5081 | 0.5147 | 0.00232 |
| neutron | 2112 | confix_long_neutron |
150 (122) | 0.5033 | 0.5061 | 0.00974 |
| photon | 22 | confix_long_photon |
150 (115) | 0.5081 | 0.5134 | 0.00318 |
¹ The run name refers to the negative PDG code. Only 98k antimuons reach the plane, so this run falls back to a 90/10 split and its test set has 9,820 particles instead of 500k.
A 1M-particle mix of the six generators at the monitor-plane abundances, evaluated against 500k real particles (step 5), gives C2ST accuracy 0.5049, ROC-AUC 0.5076 and MMD ≈ 0.
- KS / Wasserstein: per-feature distances between real and synthetic marginals.
- Correlation difference: mean and maximum absolute difference of the Pearson correlation matrices.
- MMD: kernel two-sample statistic on all features jointly (median-heuristic RBF bandwidth).
- C2ST: classifier two-sample test; permutation importance shows which features the classifier relies on.
- 1-NN leave-one-out: nearest-neighbour two-sample accuracy (0.5 ideal).
- Tail exceedance test: compares the fraction of events above the 90th, 99th, 99.9th and 99.99th percentiles of each real feature, as a pull per quantile. The global metrics weight every event equally and so are insensitive to the rate of rare events.
- Real-vs-real baseline: the same metrics on two disjoint real samples, the noise floor for the synthetic numbers.
- FPD (optional,
--fpd-model): Fréchet distance in the embedding of a supplied TorchScript network.
MIT; see LICENSE.
