NuGenFlow samples neutrino-nucleus event kinematics with conditional normalizing flows trained on inclusive and exclusive cross-section models. It is an extensible framework that:
- wraps external (Fortran) and internal (analytic, tabulated) cross-section models behind one interface;
- generates importance-weighted kinematic datasets from them, either from an external generator or from internal samplers;
- trains conditional normalizing flows on these datasets;
- iteratively refines the flow and regenerates training samples with the flow as an improved proposal;
- conditions the flows on the neutrino energy and, optionally, on model parameters (axial mass, CRPA damping, potential, missing energy, form-factor coefficients, Delta width), so one flow covers a band of model variations;
- exports the trained flows to ONNX / ORT, so any event generator or analysis can sample them from C++ (ONNX Runtime) or Python; NEUT already does.
The codebase uses:
- PyTorch for the normalizing flows and the optimisation;
- Hydra for configuration and experiment management;
- NumPy / Matplotlib / mplhep for data handling and diagnostics;
- ONNX Runtime for the C++ sampler;
- optional Docker / Apptainer environments for reproducible GPU workflows.
Only the normalizing-flows submodule is required (git submodule update --init). The Fortran model codes are optional submodules (update = none), fetched only when their cross section is used:
git submodule update --init --checkout submodules/Ghent-mean-field-1p1h # or Ghent-mean-field, Ghent-mean-field-1p1h-CRPA- Overview
- Installation
- Repository layout
- Cross-section models
- Conditional models
- Dataset handling
- Flows
- Training
- Example commands
- Sampling in Python
- Export and the C++ sampler
- NEUT integration
- Environment variables
- Citation
- Contributing
- Licence
cross-section model src/cross_section/ d sigma / dx (x, context)
| initial proposal (uniform, VEGAS, or a trained flow)
v
weighted dataset src/dataset/ x_nf, context, log dsigma, log q, sigma(E_nu) fit
|
v
flow training src/trainer/ standard, or iterative (the flow regenerates data)
|
+--> Python sampling src/sampler/, apps/sample/
|
+--> ONNX / ORT export apps_cpp/export_x_nf_onnx.py
|
v
C++ sampler src/sampler_cpp/ ONNX Runtime, one-by-one events, used by NEUT
Every model maps its physical kinematics
The flow learns the conditional density
with the context
Python >= 3.10 with numpy, torch, hydra-core, omegaconf, matplotlib, mplhep, vegas (the pyproject.toml dependencies), plus:
| package | needed for |
|---|---|
onnx, onnxscript, onnxruntime |
ONNX export (torch.onnx.export(dynamo=True)) and the .ort conversion |
The code imports both src.<package> (from the repository root) and top-level cross_section, flow, trainer, ... (the Hydra _target_ strings), so both directories must be on the path:
export NUGENFLOW_ROOT=/path/to/NuGenFlow # used by the configs: ${oc.env:NUGENFLOW_ROOT}
export NUGENFLOW_REPO=$NUGENFLOW_ROOT # only cross_section/mean_field_2p2h.yaml uses this name
export PYTHONPATH="$NUGENFLOW_ROOT:$NUGENFLOW_ROOT/src:$PYTHONPATH"pip install -e . installs the src/ packages as nugenflow-srcroot; the repository root must still be on PYTHONPATH for the src. imports. Because of the two paths, a module can be imported under two names (cross_section.mean_field_1p1h by Hydra, src.cross_section.mean_field_1p1h by direct imports); code that patches a module at run time must patch both.
| submodule | required | binary / package | what it is |
|---|---|---|---|
submodules/normalizing-flows |
yes | normflows |
NuGenFlow fork of normflows (circular rational-quadratic splines written for ONNX export) |
submodules/Ghent-mean-field-1p1h |
no | Fortran src/main |
Ghent HF mean-field exclusive 1p1h |
submodules/Ghent-mean-field-1p1h-CRPA |
no | Fortran xcrpa |
Ghent HF-CRPA exclusive 1p1h, pinned on the dev/conditionalCRPA commit (parameter inputs) |
submodules/Ghent-mean-field |
no | Fortran src/main |
Ghent mean-field exclusive 2p2h, pinned on the dev/conditional commit (parameter inputs) |
src/flow/flow.py puts the fork first on sys.path. Do not use a pip-installed normflows instead: its splines differ numerically from the fork, and the exported ONNX graphs are built from the fork. Check which one is imported with python -c "import sys; sys.path.insert(0, 'submodules/normalizing-flows'); import normflows; print(normflows.__file__)".
The bash wrappers in bash/ use the binaries inside the submodules, so build them in place (gfortran and GSL):
make -C submodules/Ghent-mean-field-1p1h/src # -> main (HF mean-field 1p1h)
make -C submodules/Ghent-mean-field/src # -> main (exclusive 2p2h, dev/conditional)
(cd submodules/Ghent-mean-field-1p1h-CRPA && sh exclcomp.sh) # -> xcrpaThe CRPA model uses two binaries. xcrpa_path reads the original input deck; xcrpa_conditional_path must be built from the dev/conditionalCRPA commit, whose deck has two extra lines (M_A Lambda g_inf T0 and dE1 dE2 dE3). The conditional binary is used only when parameter columns are passed. Since the submodule is pinned on the conditional commit, a binary built from it is the conditional one; set cross_section.cfg.xcrpa_conditional_path to it. The 2p2h wrapper always writes the parameter lines (nominal values by default), so its binary must come from dev/conditional.
Two table-based models read precomputed data that is not in the repository. Point the config key to your copy of the tables:
| data | config key | content |
|---|---|---|
| semi-exclusive 2p2h response grid | cross_section.cfg.production_root |
results/<NUC>_<iso>[_anu][_w<iwidth>]_s<shell>.dat and points/master_<channel>.txt (read once, about 1 GB of text and 300 MB of memory per Delta-width store) |
| ED-RMF overlap matrices | cross_section.cfg.overlap_root |
<NUC>/S_lev<L>_N<1,2> and highTS_lev<L>_N<1,2> from the factorised RDWIA code; a .npz cache is written next to each file on first use (30-100 s) |
The HF and PR data files of the Fortran models come with their submodules; the bash wrappers link the files of the requested nucleus.
env/Dockerfile and env/Apptainer.def build a CUDA 12.4 / PyTorch 2.6 image on top of ROOT 6.32 with gfortran, GSL and the Python dependencies. The Docker image does not install vegas (the Apptainer one does): add pip install vegas for the 1p1h models. Neither image contains ONNX Runtime. docs/env.md describes both workflows in detail.
Typical Docker workflow:
-
Build the image:
docker build -t nugenflow-cu124 -f env/Dockerfile . -
Run a GPU-enabled container with the repository mounted at
/workspace:docker run --gpus all -it --rm -v /path/to/NuGenFlow:/workspace -w /workspace nugenflow-cu124 bash
Drop
--rmand add--name nugenflow-devto keep the container, then reattach withdocker start -ai nugenflow-dev. -
Inside the container, set the paths of section 2.1 and launch a training:
export NUGENFLOW_ROOT=/workspace NUGENFLOW_REPO=/workspace export PYTHONPATH=/workspace:/workspace/src python apps/train/train.py
Apptainer / Singularity is analogous:
apptainer build --fakeroot nugenflow-cu124.sif env/Apptainer.def
apptainer shell --nv --bind /path/to/NuGenFlow:/workspace --pwd /workspace nugenflow-cu124.sifapps/
train/train.py Hydra training entry point
train/configs/ train_*.yaml + groups cross_section/ dataset/ flow/ trainer/ loss/ optim/ scheduler/
sample/ Python sampling and total-cross-section apps (+ configs/)
apps_cpp/
export_x_nf_onnx.py export a trained run to ONNX
sample_one.cpp, sample_batch.cpp, test_multi_model_sampler.cpp, plot_corner_kinematics.cpp
bash/ wrappers around the Fortran generators (compute_*.sh)
src/
cross_section/ the models (section 4)
dataset/ CrossSectionDataset, sigma(E_nu) fit, corner plots
flow/ build_model, build_conditional_model
loss/ kl_symmetric, exp_symmetric, weight diagnostics
trainer/ Trainer, IterativeTrainer
sampler/ SingleModelSampler, ReweightSampler, OverlapModelSampler
sampler_cpp/ C++ ONNX Runtime sampler library (single and multi-model)
analysis/ comparison scripts (compare_two_models.py, compare_two_model_mixtures.py)
env/, docs/env.md container definitions and instructions
submodules/ see 2.2
CMakeLists.txt builds src/sampler_cpp and apps_cpp
.gitignore ignores *.yaml, *.sh, submodules/, trained_models/, outputs/ and apps_cpp/configs/; tracked configs and scripts are added with git add -f, and a new config must be too.
All models live in src/cross_section/, subclass CrossSection (src/cross_section/base.py) and are built by Hydra from apps/train/configs/cross_section/<name>.yaml (_target_ plus a cfg: block). The common config keys (BaseConfig) are x_min, x_max (the flow box, -1, 1), e_min, e_max (the energy window in GeV) and init_model_run_dir, init_model_checkpoint, init_model_device (section 8.6).
| method / attribute | role |
|---|---|
to_nf_space(x, y) |
map physical kinematics into the flow box |
to_physics_space(x_nf, y) |
inverse mapping from the flow box back to physical variables |
log_differential(x, y) |
log of the differential cross section in physical variables, for the kinematics x and the context y |
log_det_jacobian(x_nf, y) |
log|dx_phys/dx_nf| of the flow-to-physics map |
initial_sampler(n, dim) |
first proposal: dict with x (flow-space samples), y (contexts), log_p (the raw, unnormalised log dsigma/dx_nf), log_q (the proposal log-density of x given the context) and n_attempted |
initial_sampler_from_flow(n, dim) |
same, with a trained flow as the proposal (used when init_model_run_dir is set) |
kinematics_mask(enu_gev, x_phys) |
physical-support mask; the iterative trainer and the samplers require it |
particles_from_kinematics(enu_gev, x_phys, frame, phi0) |
particle blocks (N, 5) = [pdg, E, px, py, pz] plus a per-event boolean mask |
dim, dim_name |
number of kinematic variables and their plot labels |
n_conditional, conditional_name |
number and labels of the context columns (conditional models) |
sample_conditional(n), conditional_bounds() |
draw training contexts (uniform box) and return the parameter box |
inclusive_sigma_samples(n) |
inclusive estimator of sigma(E_nu) (HF mean-field and CRPA 1p1h) |
The initial proposal can be as simple as a uniform distribution in the flow box (the base-class initial_sampler).
| model | class (module) | cross_section= |
kinematics x (D) |
needs | conditional parameters |
|---|---|---|---|---|---|
| Gaussian-mixture toy | ToyCrossSection (toy.py) |
toy |
x1..x7 (7) |
nothing | none |
| Global Fermi gas CCQE | GFGCrossSection (gfg.py) |
gfg |
E_mu, theta_mu, p_N (3) |
nothing | none |
| Ghent HF mean-field 1p1h | OnePOneH (mean_field_1p1h.py) |
mean_field_1p1h |
theta_mu, omega, theta_N, phi_N (4) |
Ghent-mean-field-1p1h |
none |
| Ghent HF-CRPA 1p1h | OnePOneH (mean_field_1p1h_CRPA.py) |
mean_field_1p1h_crpa, mean_field_1p1h_crpa_conditional, mean_field_1p1h_crpa_{numu,numubar}_{1s,1p} |
same (4) | xcrpa |
M_A, Lambda, g_inf, T0, Delta E_m |
| ED-RMF factorised RDWIA 1p1h | OnePOneHEDRMF (mean_field_1p1h_edrmf.py) |
mean_field_1p1h_edrmf, ..._edrmf_dipole, ..._edrmf_zexp_genie |
same (4) | overlap tables | E_m (always), z-expansion coefficients or M_A, g_P scale |
| Ghent exclusive 2p2h | TwoPTwoH (mean_field_2p2h.py) |
mean_field_2p2h, mean_field_2p2h_conditional |
theta_mu, omega, theta_N1, phi_N1, T_b, theta_N2, phi_N2 (7) |
Ghent-mean-field |
M_A, M_A^Delta, delta, g_inf, T0, Delta E_m |
| Ghent semi-exclusive 2p2h | TwoPTwoHSemiExcl (mean_field_2p2h_semiexcl.py) |
mean_field_2p2h_semiexcl |
theta_mu, omega, theta_N, phi_N, T_b (5) |
response grid | M_A, delta |
Nucleon angles are measured from the momentum-transfer direction. Energies are in MeV and angles in degrees in x_phys; E_nu is in GeV. In the flow box every polar angle is mirrored (theta = 180 |t|, the sign drawn at random when encoding), and the azimuths and polar angles are the circular dimensions of the flow. Every model computes log dsigma/dx_nf = log_differential(x_phys, y) + log_det_jacobian(x_nf, y).
Toy and GFG. A Gaussian-mixture toy for rapid debugging, and a quasi-elastic inclusive cross section in a global Fermi-gas picture. Neither needs external code; both are meant for kinematic-space sampling and training and implement neither kinematics_mask nor particles_from_kinematics.
HF mean-field 1p1h (OnePOneH in mean_field_1p1h.py). Interface to the Ghent mean-field exclusive 1p1h model. It writes a kinematics file per batch and runs bash/compute_mf_1p1h.sh on it (temporary run directories under runroot or $MF1P1H_RUNROOT); the wrapper links the HF / PR data files of the nucleus.
-
nucleus:C12orO16(the binding-energy table covers these two; the wrapper also knowsCa40). -
particle:nuornubar;lepton:muore(withm_mu,m_e). -
shell: [s, s]: the Ghent shell id, passed to the wrapper as<SHELL_OCC> <SHELL_EXC>:nucleus nunubarC12 3 = 1s, 4 = 1p 1 = 1s, 2 = 1p O16 4 = 1s, 5 = 1p3/2, 6 = 1p1/2 1 = 1s, 2 = 1p3/2, 3 = 1p1/2 -
omegaruns from the shell binding energy tomin(E_nu - m_lep, 1900 MeV)(OMEGA_MAX_CAP_MEV);omega_lepton_energy_mevcan replacem_lepin that ceiling. -
Distorted waves below
omega_pw_blend_start_mev(1500), plane waves aboveomega_pw_blend_end_mev(1700), linear blend in between. -
Initial proposal: uniform box with a truncated normal in
theta_N(initial_thetaN_sigma, 0.3), then a VEGAS map per energy bin after the firstvegas_start_fracof the samples (use_vegas,vegas_bins).initial_batch_sizepoints are sent to the generator per call;pedestalreplaces a non-finite cross section. -
generator_inclusive(bash/compute_mf_1p1h_inclusive.sh) is the inclusive code used byinclusive_sigma_samples.
HF-CRPA 1p1h (OnePOneH in mean_field_1p1h_CRPA.py). Same kinematics, mapping, cuts and plane-wave blend as the mean-field model, with the CRPA residual interaction. shell_id selects the shell passed to xcrpa (same ids as the table above); shell must list the same shell (it sets the binding energy). The model runs bash/compute_crpa.sh, one xcrpa call per point ($CRPA_POINT_TIMEOUT seconds each, 0 written for a point that fails). The mean_field_1p1h_crpa_{numu,numubar}_{1s,1p} configs bootstrap the initial dataset from the trained HF mean-field flow of the same window and shell (init_model_run_dir, section 8.6).
ED-RMF factorised RDWIA 1p1h (OnePOneHEDRMF). Relativistic distorted-wave impulse approximation with the ED-RMF potential, evaluated from precomputed overlap matrices (no generator run; the tables are interpolated in vectorised batches). The cross section is bilinear in the nucleon form factors, so form-factor parameters are cheap to condition on.
nucleusC12orO16;levelis the struck-nucleon level of the tables:nuuses neutron levels (C12: 4 = 1s1/2, 5 = 1p3/2; O16 adds 6 = 1p1/2),nubarproton levels (1, 2, and 3 for O16).- The missing energy
E_mis always the second context column.T_N = omega - E_m(no recoil) andomegaruns per event over[E_m, min(E_nu - m_lep, E_m + T_N,max)]. The tables stop atT_N,max = 260 MeV. rho(E_m) = occupancy x Normal(E_kappa, em_sigma_mev)within+-em_nsigmasigma, with NEUT's RMF widths and occupancies whenem_sigma_mev,occupancyare <= 0.rhois not inlog_differentialand no flow learns it: drawE_mwithsample_em(n)when generating.- Vector form factors: Kelly isovector. Axial:
axial_ff: zexp(default;zexp_kmax,zexp_t0_gev2,zexp_tcut_gev2, free coefficientszexp_coeff, the rest fixed bygaand the sum rules) ordipole(ma_gev). Pseudoscalar: pion pole scaled bygp_scale. log_differentialreturnsd sigma / dE_mu dOmega_mu dOmega_Nin1e-38 cm^2 / MeV / sr^2, occupancy included.- The three configs:
mean_field_1p1h_edrmf(z expansion,kmax = 6,(a1, a2)conditioned),..._dipole(M_Aconditioned),..._zexp_genie(kmax = 8, four coefficients conditioned).
Exclusive 2p2h (TwoPTwoH). Two-nucleon knockout from a hole pair, through bash/compute_mf_2p2h.sh (temporary run directories under runroot or $MF2P2H_RUNROOT).
nucleus(C12,O16;Ca40in the wrapper) selects theHF/PRfiles linked by the wrapper.isospin(pn,np,pp,nn): the natures of the two holes, mapped by the wrapper to the two integers of the input lineNature of particles h and h'.shell: the hole-pair index, written into the last column of the kinematics file.multipole:J_maxof the multipole expansion, written into the multipole selection lines of the input stream.particle(nu,nubar),generator_args(eight integer switches; the first six arejacen jaten jaspi i_sea i_pif i_delta),iwidth(Delta in-medium width prescription, 2 by default),tb_min.- With parameter columns the wrapper is called once per event. Set
MF2P2H_STRICT=1to raise instead of returning NaN when the generator output is missing. - Particle output is structured by process (
nu,mu,N1,N2) with a per-eventmaskof the retained events.
Semi-exclusive 2p2h (TwoPTwoHSemiExcl). One nucleon detected, the other integrated out, evaluated by interpolating the precomputed response grid (no generator run). nucleus, isospin, shell (pair string such as "11"), particle (nu or anu), production_root. omega starts at the grid's first stored layer (or omega_min_mev), T_b runs from the first stored node (or tb_min) to the analytic support edge. sampler_workers parallelises the initial sampling with fork workers sharing the grid.
kinematics_mask(enu_gev, x_phys) removes points outside the physical support. It is applied by the initial samplers, by the iterative trainer before every cross-section call, and by the samplers (filter_unphysical). For the HF mean-field and CRPA 1p1h models it also contains:
- a Fermi cut: the smallest initial-nucleon momentum compatible with
(q, omega)must be <= 400 MeV/c (PI_MIN_MAX_MEV); being part of the mask, it applies both when generating training data and when sampling; - for antineutrinos,
p_lep >= 45 MeV/c($NUGENFLOW_P_LEP_MIN_MEV), also used by the ED-RMF model.
particles_from_kinematics(enu_gev, x_phys, frame="interaction"|"lab", phi0=...) returns one (N, 5) block per particle (nu, mu, N for 1p1h; nu, mu, N1, N2 for exclusive 2p2h) and a boolean mask. frame="interaction" keeps q along z; frame="lab" puts the neutrino along z, and phi0 sets the global azimuth of the final state (the samplers can draw it at random per event). It is implemented by the HF mean-field, CRPA and ED-RMF 1p1h models and by the exclusive 2p2h model.
The context is y = [E_nu, c_1, ..., c_k] in physical units. The flow, the dataset (enu column block) and log_differential all take the full context; the columns after E_nu are the enabled parameters in a fixed order. A parameter is enabled with its condition_* flag in the cross-section config; when disabled, its nominal value is used.
| parameter | flag | nominal key (value) | box keys (default) | units | models |
|---|---|---|---|---|---|
nucleon axial mass M_A |
condition_ma |
ma_gev (1.032) |
ma_min_gev, ma_max_gev (0.9, 1.2) |
GeV | CRPA, 2p2h |
CRPA damping scale Lambda |
condition_lambda |
lambda_gev (0.455) |
lambda_min_gev, lambda_max_gev (0.3, 1.0) |
GeV | CRPA |
Delta axial mass M_A^Delta |
condition_ma_delta |
ma_delta_gev (1.030) |
ma_delta_min_gev, ma_delta_max_gev (0.9, 1.2) |
GeV | 2p2h |
Delta-width coordinate delta |
condition_delta |
iwidth (fixed prescription) |
delta_min, delta_max (0, 1) |
- | 2p2h, semi-exclusive 2p2h |
potential energy dependence g_inf, T0 |
condition_potential |
g_inf (1.0), t0_gev (0.1164) |
g_inf_min, g_inf_max (0.2, 1.0), t0_min_gev, t0_max_gev (0.05, 0.3) |
-, GeV | CRPA, 2p2h |
missing-energy shift Delta E_m |
condition_de |
de_mev (0) |
de_min_mev, de_max_mev (-10, 10) |
MeV | CRPA, 2p2h |
Column order: CRPA [E_nu, M_A, Lambda, g_inf, T0, Delta E_m]; exclusive 2p2h [E_nu, M_A, M_A^Delta, delta, g_inf, T0, Delta E_m]; semi-exclusive 2p2h [E_nu, M_A, delta] (ma_min_gev, ma_max_gev default 0.8, 1.4); ED-RMF [E_nu, E_m, a_1..a_(kmax-4) or M_A, g_P].
What the parameters do:
-
Lambdais the scale of the CRPA residual-interaction damping$(1 + Q^2/\Lambda^2)^{-2}$ . -
g_inf,T0scale the mean-field potential with the outgoing-nucleon kinetic energy$T$ :$r(T) = g_\infty + (1 - g_\infty) / (1 + (T/T_0)^2)$ .g_inf = 1is no energy dependence (nominal). -
Delta E_mmakes the struck shell more bound (positive values) and moves theomegafloor with it. In the 2p2h model half of it is applied to each hole of the pair. -
deltamixes the Delta in-medium width prescriptionsiwidth = 1, 2, 3, 5: weight 1 on one prescription within +-0.05 of its centre (0.2, 0.4, 0.6, 0.8), linear interpolation between neighbouring plateaus. Each prescription is a separate cross-section call. -
M_Ain the semi-exclusive model reweights the stored VV / VA / AA parts with a dipole ratio relative toma_ref_gev. - ED-RMF:
condition_zexp(the free z-expansion coefficients, boxzexp_min,zexp_max),condition_ma(dipole only),condition_gp(gp_min,gp_max).
The box is the prior: training contexts are drawn uniformly on it (sample_conditional) and the stored log_q is the kinematic proposal only, so a non-uniform prior would bias the weights. The box sets the coverage of the flows.
| model | how the parameters reach the Fortran code |
|---|---|
| CRPA 1p1h | the parameter columns are appended to the kinematics file and bash/compute_crpa.sh runs xcrpa_conditional_path with the extended deck |
| exclusive 2p2h |
bash/compute_mf_2p2h.sh writes the parameter lines from $MF2P2H_KNOBS and the width prescription from $MF2P2H_IWIDTH, one call per event |
With every flag off and the nominal values, no parameter columns are passed: the CRPA model then runs xcrpa_path with the original deck, and the 2p2h wrapper writes the nominal parameter lines.
flow.flow.build_conditional_model returns a ConditionalCrossSectionFlow made of two flows:
flow_kin: the kinematic flow, context[E_nu, c](num_context_channels=n_conditional);flow_cond: a flow with a uniform base over the parameters mapped affinely from the box to[-1, 1]^k, context the firstcond_num_context_channelscolumns (1, or 2 for ED-RMF whereE_mis a leading column). Its box isconditional_bounds()of the model whencond_low/cond_higharenull.
Training fits both together (log_prob(x, context) is the sum). Since the data are uniform in c and normalised by sigma(E_nu), p_cond(c | E_nu) learns sigma(E_nu, c) divided by its average over the box: the total cross section as a function of the parameters can be read back from the model.
Two ways to sample:
- fixed parameters:
flow.flow_kin.sample(n, context=[E_nu, c])(this is also whatflow.sample(...)does); - parameters drawn with the kinematics:
flow.sample_joint(n, lead)whereleadholds the leading columns ([E_nu], or[E_nu, E_m]for ED-RMF). It returns(x_nf, context, log_prob).
import numpy as np, torch, hydra
from pathlib import Path
from src.sampler.single_model_sampler import load_run_cfg, latest_dataset_npz
from src.dataset.dataset import CrossSectionDataset, DatasetConfig
run_dir = Path("outputs/<date>/<time>") # an ED-RMF run
cfg = load_run_cfg(run_dir)
cs = hydra.utils.instantiate(cfg.cross_section)
ds = CrossSectionDataset(DatasetConfig(path=str(latest_dataset_npz(run_dir))))
ds.cs_model = cs
flow = hydra.utils.instantiate(cfg.flow, dataset=ds)
flow.load_state_dict(torch.load(run_dir / "checkpoints/model_best.pt", map_location="cpu")["state_dict"])
flow = flow.cpu().eval()
n = 1000
lead = np.stack([np.full(n, 0.3, np.float32), cs.sample_em(n)], axis=1) # [E_nu, E_m]
with torch.no_grad():
x_nf, ctx, log_q = flow.sample_joint(n, torch.from_numpy(lead))
x_phys = cs.to_physics_space(x_nf.numpy(), ctx.numpy())
keep = cs.kinematics_mask(ctx.numpy()[:, 0], x_phys)Datasets are managed by src/dataset/dataset.py, which defines CrossSectionDataset and DatasetConfig; src/dataset/dataset_plot_utils.py provides corner_plot.
A CrossSectionDataset holds, per event:
| field | meaning |
|---|---|
x |
flow-space samples, shape (N, D) |
enu |
the full context, shape (N, n_conditional): E_nu in GeV, then the parameters (shape (N, 1) for single-context models) |
log_ds_phys |
log differential cross section in physics space, log dsigma/dx_phys |
log_jac |
log absolute Jacobian determinant of the flow-to-physics map, log|dx_phys/dx_nf| |
log_ds |
log_ds_phys + log_jac: the raw, unnormalised flow-space density log dsigma/dx_nf |
log_q |
log proposal density of x given the context |
log_p |
training log-density: log_ds - log sigma_fit(E_nu) with normalisation, log_ds without |
weight |
exp(log_p - log_q), the importance weights used for training |
n_attempted_total |
number of attempted draws behind the stored events (rejected points are not stored) |
sigma_coeff |
coefficients of the sigma(E_nu) fit (optional), evaluated by dataset.sigma(E) / dataset.sigma_fit |
__getitem__ returns (x, context, log_p, log_q), the tuple the losses consume.
Datasets are loaded from .npz files only (this is the only format read, for loading and for resuming):
- required arrays:
x,enu,log_ds_phys,log_jac,log_q,n_attempted_total; - optional:
sigma_coeff(thelog sigma(E_nu)polynomial, highest degree first).
dataset.save(path) writes exactly these arrays.
Datasets are constructed by
CrossSectionDataset.build(model, cfg)where model is a CrossSection instance and cfg a DatasetConfig, filled by apps/train/train.py from the Hydra dataset group (apps/train/configs/dataset/<name>.yaml).
DatasetConfig key |
default | meaning |
|---|---|---|
path |
"" |
existing .npz to load; empty = generate. train.py resolves a relative path from the repository root |
n_samples |
0 | number of events to generate when path is empty |
num_threads |
1 | CPU threads for the generation (each on a deep copy of the model) |
normalize |
true | fit sigma(E_nu) and subtract log sigma_fit(E_nu) from log_ds |
sigma_fit_mode |
importance |
how sigma(E_nu) is obtained: importance, external or inclusive_importance (section 6.4) |
sigma_fit_path |
"" |
.npz with sigma_coeff, or a two-column .txt (external mode) |
fit_deg |
8 | degree of the polynomial fitted to log sigma |
n_sigma_bins |
5 | number of equal-width energy bins used to estimate sigma(E_nu) before fitting |
quantile |
none | at generation, drop the events whose weight exp(log_ds - log_q) lies above this quantile |
weight_cap |
none | cap on the per-event weights entering the sigma(E_nu) estimate |
n_inclusive_samples |
0 | number of inclusive draws for inclusive_importance |
Two modes exist.
- Loads
x,enu,log_ds_phys,log_jac,log_q,n_attempted_totalfrom the.npzand rebuildslog_ds = log_ds_phys + log_jac. - With
normalize, fitssigma(E_nu)again from the loaded events with the configuredsigma_fit_mode, and setslog_p = log_ds - log sigma_fit(E_nu); otherwiselog_p = log_ds. - Writes the dataset back to the run directory under the same index (
dataset_<k>.npzfor a loadeddataset_<k>.npz).
The constructor CrossSectionDataset(DatasetConfig(path=...)) is a lighter loader, used by the samplers: it reads the same arrays and takes the normalisation from the stored sigma_coeff instead of re-fitting it (log_p = log_ds when there is none).
- Calls
model.initial_sampler(n, dim), split overnum_threadsthreads, untiln_samplesevents are collected (the firstn_samplesare kept). - Interprets the sampler outputs as
log_p= rawlog dsigma/dx_nfandlog_q= conditionallog q(x_nf | y);n_attemptedof the sampler, summed over threads, becomesn_attempted_total. - Non-finite
log dsigma/dx_nfvalues are floored to-1e30and non-finitelog_qset to 0; the optionalquantilecut is applied. - Computes and stores
log_jac = model.log_det_jacobian(x_nf, y),log_ds_phys = log dsigma/dx_nf - log_jacandlog_ds = log_ds_phys + log_jac.
With normalize: true, the dataset builds (or loads) a smooth approximation of the total cross section
with fit_deg, and saved as sigma_coeff in the .npz. It normalises the exclusive differential density into a conditional density in the kinematics:
Only the E_nu column enters the fit, so for a conditional model
The default:
Per-event importance weight
where log_ds_k is the log of the exclusive differential cross section in flow space (log_ds_phys + log_jac) and log_q_k the proposal log-density the event was drawn from. The weights are capped at weight_cap when it is set.
Binning in energy. The energy is binned into n_sigma_bins equal-width bins over [e_min, e_max].
No stored rejects. Rejected or invalid points are not stored (the Ghent codes return nothing for them), so the number n_attempted_total, the initial draw plus every later addition) instead. Assuming [e_min, e_max] and the bins have equal widths, for each energy bin
Finally a polynomial of degree fit_deg is fitted to
sigma_fit_path points to:
-
a
.npzfile containingsigma_coeff: the polynomial coefficients are used directly assigma_fit; -
a
.txtfile with pre-fit sigma points in the format the code writes (lines starting with#are ignored):# E_nu[GeV] sigma(E_nu) (pre-fit points) 4.2000000000e-01 2.2069371005e+01 4.6000000000e-01 2.5446458405e+01 5.0000000000e-01 2.7443829066e+01 ...The two columns
(E, sigma)are read and a polynomial of degreefit_degis fitted tolog sigma.
This mode is meant for a stable
Available for the HF mean-field and CRPA 1p1h models, the ones implementing inclusive_sigma_samples(n). It draws n_inclusive_samples inclusive points, uniform in generator_inclusive), and returns per-event log-weights $\log w^{(\text{incl})}k$ whose binned sum estimates $\sigma(E\nu)$:
The same polynomial fit of degree fit_deg then gives sigma_fit. In contrast to the importance mode, it does not use the exclusive proposal log_q; it is intended to stabilise the normalisation when the exclusive sampling has poor coverage.
In every mode the normalised training log-density is
log_p = log_ds - log sigma_fit(E_nu)
and with normalize: false, log_p = log_ds and no fit is made. The pre-fit points of every fit are written to img/sigma_points_prefit_dataset_<k>.txt.
Datasets are written to the active Hydra output directory (HydraConfig.get().runtime.output_dir), or to the working directory when Hydra is not initialised.
CrossSectionDataset.build(...)saves a snapshot asdataset_<index>.npz: the next free index for a generated dataset, the index of the source file for a loaded one.- When
pathis empty and the output directory already holdsdataset_*.npzfiles, the new draw is appended to the one with the highest index and the combined set keeps its most recent 100000 rows. Generate in a clean directory to get only the new draw. - During iterative training, new samples are appended in memory (section 8.3). The dataset can then:
- recompute the
sigma(E_nu)fit after each append (importance mode,recompute_sigma_fit), updatinglog_p,weight,img/dataset_sigma.pngandimg/sigma_points_recompute.txt; - enforce a maximum size (
max_dataset_size) by dropping the oldest samples.
- recompute the
- At the end of an iterative run the enlarged dataset is saved as the next
dataset_<k>.npz, ready for reuse.
Dataset creation produces, under <hydra_run_dir>/img/ (or ./img without Hydra):
dataset_corner_nf.png: weighted corner plot of the flow-space samples and the context columns;dataset_corner_phys.png: the same in physics variables;dataset_sigma.png: the fittedsigma(E_nu)on an 80-point energy grid, with the binned fit points;sigma_points_prefit_dataset_<k>.txt: the fit points.
src/flow/flow.py, built from apps/train/configs/flow/<name>.yaml:
flow.flow.build_model: aCrossSectionFlow(normflows.ConditionalNormalizingFlow) with aUniformGaussianbase (uniform on the circular dimensionsind_circ, Gaussian of widthsigmaon the others) andn_layersCircularAutoregressiveRationalQuadraticSplinelayers.flow.flow.build_conditional_model: the pair of section 5.3.
| key | meaning |
|---|---|
dim |
number of kinematic variables |
ind_circ |
circular dimensions (angles) |
sigma |
base widths per dimension |
n_layers, hidden_channels, num_bins, tail_bound, permute_mask |
spline flow size |
num_context_channels |
context columns of the kinematic flow; must equal the model's n_conditional |
cond_low, cond_high |
parameter box (null = from the cross-section model) |
cond_n_layers, cond_hidden_channels, cond_num_bins |
parameter-flow size |
cond_num_context_channels |
leading context columns the parameter flow sees (1, or 2 for ED-RMF) |
The single-context 1p1h configs use 25 layers, 512 hidden channels and 31 bins; the conditional 1p1h configs use 4 layers, 64 channels and 8 bins for both flows (15 / 512 / 11 and 6 / 128 / 11 for 2p2h). When a parameter is switched off, lower num_context_channels to match (for example flow.num_context_channels=3 for cross_section=mean_field_1p1h_edrmf_dipole).
The training logic is in src/trainer/ and the application entry point in apps/:
apps/train/train.py: Hydra entry point for training runs;src/trainer/trainer.py: standard trainer on a fixed dataset;src/trainer/iterative_trainer.py: iterative trainer with asynchronous dataset generation.
python apps/train/train.py --config-name <train_config> [group=option ...] [key=value ...]apps/train/train.py instantiates, in order, the cross section, the dataset (CrossSectionDataset.build), the flow, the loss (as a partial), the optimiser, the scheduler and the trainer, then calls trainer.fit(). The configs live in apps/train/configs/; the default train.yaml is the toy model. Each top-level config picks one option per group:
--config-name |
cross_section | dataset | flow | trainer |
|---|---|---|---|---|
train |
toy |
toy |
toy |
default |
train_iterative_toy |
toy |
toy |
toy |
iterative |
train_gfg |
gfg |
gfg |
gfg |
default |
train_iterative_gfg |
gfg |
gfg |
gfg |
iterative |
train_mf_1p1h |
mean_field_1p1h |
mf_1p1h |
mf_1p1h |
iterative_1p1h |
train_mf_1p1h_crpa |
mean_field_1p1h_crpa |
mf_1p1h_crpa |
mf_1p1h_crpa |
iterative_1p1h_crpa |
train_mf_1p1h_crpa_conditional |
mean_field_1p1h_crpa_conditional |
mf_1p1h_crpa_conditional |
mf_1p1h_crpa_conditional |
iterative_1p1h_crpa_conditional |
train_mf_1p1h_edrmf |
mean_field_1p1h_edrmf |
mf_1p1h_edrmf |
mf_1p1h_edrmf_conditional |
iterative_1p1h_edrmf |
train_mf_2p2h |
mean_field_2p2h |
mf_2p2h |
mf_2p2h |
iterative_2p2h |
train_mf_2p2h_conditional |
mean_field_2p2h_conditional |
mf_2p2h_conditional |
mf_2p2h_conditional |
iterative_2p2h_conditional |
train_mf_2p2h_semiexcl |
mean_field_2p2h_semiexcl |
mf_2p2h_semiexcl |
mf_2p2h_semiexcl_conditional |
iterative_2p2h_semiexcl |
All use loss: kl_symmetric, optim: adam (lr 1e-5; 5e-4 in train_mf_1p1h_crpa_conditional, train_mf_1p1h_edrmf and train_mf_2p2h_conditional) and scheduler: steplr. Any group can be swapped on the command line (for example trainer=default to train a model on a fixed dataset). The composed config is in struct mode: to set a key that the YAML does not contain, prefix it with ++ (for example ++trainer.early_stopping_patience=0, ++dataset.path=...). Several trainer configs select a specific GPU (device: cuda:0 or cuda:1); set trainer.device for your machine.
Trainer (trainer=default, src/trainer/trainer.py) runs a straightforward optimisation loop on a fixed dataset:
- wraps the
CrossSectionDatasetin a shuffledDataLoader; - before the first epoch, samples the flow at the first
sample_sizedataset contexts, keeps the points inside the box, maps them to physics variables withdataset.cs_model.to_physics_spaceand writes the corner plotimg/samples_base.png; - for each epoch:
- draws mini-batches
(x, context, log_p, log_q); - computes the configured loss
loss_fn(model, x, context, log_p, log_q); - backpropagates and updates the flow parameters;
- steps the scheduler (once per epoch);
- draws mini-batches
- every
sample_everyepochs:- evaluates the loss of the last mini-batch in validation mode (weight statistics printed, weight histogram
img/kl_log_weight.png); - writes
checkpoints/model_last.ptand, when that loss improves,checkpoints/model_best.pt; - samples the flow conditioned on the dataset contexts, maps the samples to physics space and writes the corner plot
img/samples_nf.png;
- evaluates the loss of the last mini-batch in validation mode (weight statistics printed, weight histogram
- stops early after
early_stopping_patienceepochs without improvement of the monitored loss (0 = off); - at the end writes
img/training_loss.png(mean loss per epoch) and a finalmodel_last.pt.
IterativeTrainer (trainer=iterative*, src/trainer/iterative_trainer.py) extends the standard loop with asynchronous data generation: the flow regenerates its own training data while it trains. The main loop is the same as in 8.2 (mini-batches indexed as whole batches, optional gradient clipping grad_clip_norm, validation and checkpoints every sample_every epochs, samples_nf.png drawn at fresh contexts from sample_conditional). In addition, every update_every epochs:
- Collect. If a background job has finished, its samples are appended to the dataset (step 3).
-
Launch. A new background job starts from a copy of
checkpoints/model_best.pt(no job starts before the first checkpoint exists). The job:- moves the flow copy to the CPU;
- draws contexts with
sample_conditional(orE_nuuniform on[e_min, e_max]for single-context models); - samples the kinematic flow (
flow_kinfor a conditional flow) at these contexts and evaluates its log-density; - replaces a fraction
$r$ =ratio_pedestalof the points by uniform points in the box, so that the proposal covers the whole box; the proposal density of every point is the mixture$q(x_\text{nf} \mid y) = (1 - r), f(x_\text{nf} \mid y) + r, 2^{-D}$ , with$f$ the flow density and$D$ the kinematic dimension; - maps the points to physics space and drops those failing
kinematics_mask; - evaluates
log_differentialandlog_det_jacobianinn_threadsthreads, and buildslog dsigma/dx_nf = log_ds_phys + log_jac; - uses the current dataset fit
sigma_fit(E_nu)to producelog_p = log dsigma/dx_nf - log sigma_fit(E_nu); - returns the new samples and the number of attempted draws.
-
Append. When the samples are appended, they are:
- optionally filtered by a
quantilecut on their weightsexp(log_p - log_q); - appended to the in-memory dataset (
n_attempted_totalgrows by the attempted draws); - truncated to
max_dataset_sizeby dropping the oldest samples; - followed by a recomputation of
sigma_fit(E_nu),log_pand the weights whenrecompute_sigma_fitis true (importance mode only; section 6.5).
- optionally filtered by a
At the end, the trainer waits for a pending job, appends it, writes img/training_loss.png and saves the final dataset as the next dataset_<k>.npz. A dataset larger than max_dataset_size at start is truncated the same way. The iterative trainer calls kinematics_mask on every regenerated batch, so it needs a model that implements it (every model except the toy and GFG).
All keys are set under trainer. (for example trainer.n_epochs=2000). Defaults are those of the class; the YAML files of apps/train/configs/trainer/ override most of them.
| key | Trainer default |
IterativeTrainer default |
meaning |
|---|---|---|---|
n_epochs |
10 | 10 | number of epochs |
batch_size |
1024 | 1024 | mini-batch size |
device |
cuda |
cuda |
training device |
sample_every |
5 | 0 | period (epochs) of the validation loss, checkpoints and sample plots; checkpoints are only written here, and the iterative trainer regenerates from model_best.pt, so with 0 no checkpoint is written and no data is regenerated |
sample_size |
20000 | 1000 | number of flow samples in the corner plots |
sample_bins |
30 | 50 | bins of the corner plots |
min_log_weight_plot |
-20 | -20 | lower edge of the weight histograms |
early_stopping_patience |
0 | 100 | stop after that many epochs without improvement of the monitored loss (0 = off) |
early_stopping_min_delta |
0 | 0 | minimum improvement counted by early stopping |
update_every |
- | 5 | period (epochs) of the data regeneration |
new_sample_size |
- | 1000 | points drawn by each background job (before the mask) |
n_threads |
- | 1 | threads for the cross-section evaluations of a job |
ratio_pedestal |
- | 0.05 | fraction of uniform points in each job |
quantile |
- | none | drop appended samples above this weight quantile |
max_dataset_size |
- | 1000000 | keep at most this many samples (oldest dropped) |
recompute_sigma_fit |
- | true | re-fit sigma(E_nu) after every append |
grad_clip_norm |
- | none | gradient-norm clipping |
The early-stopping monitor is the mean training loss of the epoch, replaced by the validation loss on the epochs where it is computed; that validation loss (evaluated on the last mini-batch of the epoch) also selects model_best.pt. trainer/iterative_1p1h_edrmf.yaml is the only config that sets early_stopping_patience: 0.
The losses (src/loss/importance_losses.py) combine forward and reverse terms on the proposal samples. With the target log_p), the flow model.log_prob(x, context)) and the proposal log_q):
where kl_symmetric (config loss/kl_symmetric.yaml, keys a, b) is used by all top-level configs; exp_symmetric is the second function of the module. In validation mode both write a histogram of img/kl_log_weight.png or img/exp_log_weight.png).
The optimiser is torch.optim.Adam (optim/adam.yaml, key lr). scheduler/steplr.yaml is StepLR(step_size=1, gamma=0.99), stepped every epoch, so the learning rate is 5% of its start value at epoch 300; train_mf_1p1h_crpa_conditional, train_mf_1p1h_edrmf and train_mf_2p2h_conditional set scheduler.gamma: 1.0. Set scheduler.gamma=1.0 for any long run.
cross_section.cfg.init_model_run_dir(+init_model_checkpoint,init_model_device): the initial dataset is drawn from that trained flow instead of the model's own proposal. Any run with the same kinematic dimension works (for example a mean-field flow for a CRPA or conditional CRPA run; only its first context columns are used).cross_section.cfg.init_model_weights: true(withinit_model_run_dir): also load that run's weights into the new flow, which then must have the same architecture. Use++cross_section.cfg.init_model_weights=truefor configs that do not list the key.dataset.path: train on an existing dataset instead of generating one (section 6.3).
Each training run writes to a dedicated Hydra output directory (outputs/<date>/<time>/ by default; set hydra.run.dir=...):
.hydra/config.yaml, overrides.yaml frozen snapshot of the composed config (the samplers and the exporter read it)
checkpoints/model_best.pt, model_last.pt {epoch, val_loss, state_dict, optimizer, scheduler}
dataset_<k>.npz initial and final (enlarged) datasets, ready for reuse in later runs
img/
dataset_corner_nf.png, dataset_corner_phys.png, dataset_sigma.png dataset (section 6.6)
sigma_points_prefit_dataset_<k>.txt, sigma_points_recompute.txt sigma(E_nu) fit points
samples_base.png flow samples before training (standard trainer)
samples_nf.png flow samples at the last check
kl_log_weight.png weight histogram of the last validation
training_loss.png mean loss per epoch
Indicative commands; adjust the Hydra overrides as needed. Set the environment of section 2.1 first.
# toy model on CPU (runs in a minute)
python apps/train/train.py trainer.device=cpu
# Global Fermi gas, standard training
python apps/train/train.py --config-name train_gfg \
dataset.n_samples=50000 trainer.n_epochs=200# iterative training, O16, numu, 1s shell, one energy window
python apps/train/train.py --config-name train_mf_1p1h \
cross_section.cfg.nucleus=O16 cross_section.cfg.particle=nu cross_section.cfg.shell='[4,4]' \
cross_section.cfg.e_min=0.5 cross_section.cfg.e_max=0.72 \
trainer.device=cuda:0 trainer.n_epochs=2000 trainer.update_every=20 \
scheduler.gamma=1.0 ++trainer.early_stopping_patience=0
# standard training on a fixed dataset, C12, 1p shell
python apps/train/train.py --config-name train_mf_1p1h trainer=default \
cross_section.cfg.nucleus=C12 cross_section.cfg.shell='[4,4]' \
dataset.n_samples=5000 trainer.n_epochs=200python apps/train/train.py --config-name train_mf_2p2h \
cross_section.cfg.nucleus=C12 cross_section.cfg.multipole=5 \
cross_section.cfg.isospin=pn cross_section.cfg.shell=1 \
dataset.n_samples=50 trainer.n_epochs=200# CRPA 1p1h conditional on (M_A, Lambda, g_inf, T0, Delta E_m); initial data drawn
# from a trained HF mean-field flow of the same window and shell
python apps/train/train.py --config-name train_mf_1p1h_crpa_conditional \
cross_section.cfg.xcrpa_conditional_path=/path/to/xcrpa_conditional \
cross_section.cfg.init_model_run_dir=/path/to/hf_mean_field_run trainer.device=cuda:0
# same without the Lambda parameter: 5 context columns
python apps/train/train.py --config-name train_mf_1p1h_crpa_conditional \
cross_section.cfg.condition_lambda=false flow.num_context_channels=5
# ED-RMF 1p1h, z-expansion (a1, a2) conditioned
python apps/train/train.py --config-name train_mf_1p1h_edrmf \
cross_section.cfg.overlap_root=/path/to/edrmf/Overlaps cross_section.cfg.level=4 \
cross_section.cfg.e_min=0.2 cross_section.cfg.e_max=0.4
# exclusive 2p2h conditional on (M_A, M_A^Delta, delta, g_inf, T0, Delta E_m)
python apps/train/train.py --config-name train_mf_2p2h_conditional trainer.device=cuda:0
# semi-exclusive 2p2h from the response grid
python apps/train/train.py --config-name train_mf_2p2h_semiexcl \
cross_section.cfg.production_root=/path/to/semiexclpython apps/train/train.py --config-name train_mf_1p1h \
trainer.n_epochs=20 trainer.update_every=5 trainer.recompute_sigma_fit=trueIf you already have a dataset file, train on it instead of generating a new one:
python apps/train/train.py --config-name train_mf_1p1h \
++dataset.path=outputs/<date>/<time>/dataset_<k>.npz trainer.n_epochs=20src/sampler/single_model_sampler.py loads a run directory (.hydra/config.yaml, a checkpoint, and the newest dataset_*.npz or dataset_path for the sigma(E_nu) fit), samples energies, samples the flow, optionally rejects points failing kinematics_mask, and builds particles with particles_from_kinematics. It handles models whose context is E_nu alone; for conditional flows use section 5.3. apps/sample/sample_single_model.py wraps it as a command-line app and as an importable API.
Command line (defaults in apps/sample/configs/single_model_sampler.yaml, which turns on plots, particles and filtering):
python apps/sample/sample_single_model.py run_dir=<run_dir> n_samples=10000 +mono_enu=0.6 device=cpu
python apps/sample/sample_single_model.py run_dir=<run_dir> n_samples=10000 flux_path=/path/to/flux.txtPython API (its defaults are off: no plots, particles or filtering unless requested):
from apps.sample.sample_single_model import sample_array
arr = sample_array(
run_dir="outputs/<date>/<time>",
n_samples=10000,
mono_enu=0.6,
make_particles=False,
filter_unphysical=True,
device="cpu",
)
print(arr.shape)Energy choice in sample_array(...):
-
mono_enu=<float>: mono-energetic sampling; -
flux_path="..."(+ optionalflux_scale): flux-weighted sampling. The flux file has two columnsE_nu phi; energies are drawn by accept-reject on$\phi(E),\sigma_\text{fit}(E)$ over the flux range; - if neither is given, it samples at
cross_section.cfg.e_maxof the run config.
Output format of sample_array(...):
return_particles=False(default):float32array of shape(N, 1 + D)with columns[E_nu, x_phys...];return_particles=True(requiresmake_particles=True):float32array of shape(N, 5K), the particle blocks(N, 5)concatenated in a stable key order (nu,mu,Nfor 1p1h;nu,mu,N1,N2for 2p2h).
Other options: checkpoint (default checkpoints/model_best.pt), dataset_path, seed, particle_frame (lab or interaction, section 4.4), randomize_lab_phi (random phi0 per event in the lab frame), filter_unphysical with oversample_factor and max_oversample_rounds (each round draws oversample_factor times the missing events and keeps those passing the mask; events whose particle mask is false are removed too).
Saved outputs under <run_dir>/<out_subdir>/ (out_subdir defaults to sampler):
samples/samples.npzwithx_nf,x_phys,enu,log_qifsave_samples=True;samples/particles_lab.npzorsamples/particles_interaction.npzifsave_particles=True;- corner plots in
img/ifmake_plot=True:corner_nf.png,corner_phys.pngand, with particles,corner_particles_<frame>.png.
The particle frame, the lab azimuth, the unphysical-event filter and the particle masks are implemented by each cross-section model, not by a model-independent rule (section 4.3, 4.4): the HF mean-field, CRPA and ED-RMF 1p1h models and the exclusive 2p2h model provide them; the toy, GFG and semi-exclusive models do not expose particle output. Check the model implementation under src/cross_section/ and its config before enabling particle output or filtering.
| app | config | what it does |
|---|---|---|
apps/sample/sampling_overlap_model.py |
sampling_overlap_model.yaml |
samples a mixture of several runs (OverlapModelSampler, per-model importance and sigma points) |
analysis/compare_two_models.py, compare_two_model_mixtures.py |
analysis/configs/ |
comparison plots of two runs or two mixtures |
| app | method | output |
|---|---|---|
apps/sample/calculate_total_cs_multi_model.py |
importance estimate from the flow, sigma(E) = mean(dsigma/dx_phys / q_phys) at each point of energy_points, over several energy windows of one shell: a model list with emin, emax, linear mixing where two windows overlap (at most two), weight_trim_quantile, n_reweight_threads |
E_nu, sigma, sigma_err in 1e-38 cm^2 |
The multi-model table is what the C++ sampler reads as sigma_points_path: one table per nucleus, flavour and shell over all energy windows, per nucleus (the whole shell), linearly interpolated. NEUT divides it by the number of active nucleons. Replacing the model of any window makes the table of that shell stale. calculate_total_cs_multi_model.yaml is empty in the repository: pass the models list (name, run_dir, checkpoint, dataset_path, emin, emax), energy_points, output_dir, output_file, plot_file, n_samples_per_point, device, seed, filter_unphysical, oversample_factor, max_oversample_rounds, make_plot, save_npz and the optional keys above.
python -m apps_cpp.export_x_nf_onnx --run-dir <run_dir> --onnx-out model.onnx [--ckpt path.pt]
python -m onnxruntime.tools.convert_onnx_models_to_ort model.onnx # -> model.ortThe exporter rebuilds the flow from the run's Hydra config and exports the decoder (z, context) -> (x_nf, log_q) with torch.onnx.export(dynamo=True, opset_version=18). Weights may go to a sibling .onnx.data file; keep it next to the .onnx. The graph has a fixed batch of 1 and a [1, 1] context: set max_nn_batch_size=1 in the C++ config; only single-context (E_nu) flows are exported this way. The .ort format skips graph parsing at load.
The top-level CMakeLists.txt builds the library nugenflow_sampler_cpp (src/sampler_cpp/) and four executables. It needs C++17 and ONNX Runtime's CMake package:
cmake -S . -B build -Donnxruntime_DIR=/path/to/onnxruntime/lib64/cmake/onnxruntime
cmake --build build -j
./build/sample_one <multi_config.ini> <output.txt>
./build/sample_batch <multi_config.ini> <output.txt>
./build/test_multi_model_sampler <multi_config.ini> <n_samples> <output_prefix> # timing, one-by-one vs batch
./build/plot_corner_kinematics <multi_config.ini> [n_samples]SingleModelSampler: one exported flow and its energy window. It drawszfrom the base distribution, runs ONNX Runtime (one session per file, shared, created lazily at the first sample, basic graph optimisation, 1 intra-op thread), maps to physics variables, applies the kinematic mask with oversampling, and builds the particle blocks (nu,Nifor the initial nucleon at rest,lep,N).MultiModelSampler: a list of single-model configs. It samplesE_nu(mono, or flux x total sigma), picks for each event a model among those whose window coversE_nuwith probability proportional to theirsigma(E_nu), and samples it.total_sigma(E)sums the models coveringE, counting eachsigma_points_pathonce.- The kinematics implemented in C++ is
cs_utils_name=mf_1p1h(the 4-variable 1p1h layout of the HF mean-field and CRPA models).
Multi-model file (key=value, # comments):
| key | meaning |
|---|---|
model_configs |
comma-separated single-model .ini files (relative paths resolve from this file) |
n_samples, energy_mode (mono / flux), mono_energy |
event count and energy mode |
flux_path, flux_scale, ar_grid, ar_trials_factor |
two-column flux file and accept-reject settings |
seed |
random seed |
Single-model file:
| key | meaning |
|---|---|
onnx_path |
.onnx or .ort file |
energy_min, energy_max |
the window in GeV |
sigma_points_path or sigma_coeff_desc |
two-column E_nu sigma table (linear interpolation), or log sigma polynomial coefficients, highest degree first |
cs_utils_name, particle (nu, nubar), lepton (mu, e), nucleus, shell |
kinematics and binding energy (shell ids as in 4.2) |
omega_cap_mev (1900), fermi_cut_mev (400, <= 0 disables), delt_mev (0) |
mask settings, matching the Python model |
base_ind_circ, base_sigma |
the flow's ind_circ and sigma (they define the base distribution) |
filter_unphysical, oversample_factor, max_oversample_rounds |
rejection settings |
make_particles, particle_frame, randomize_lab_phi |
particle output |
seed |
random seed |
max_nn_batch_size |
1 for the batch-1 exports |
input_z_name, input_context_name, output_x_nf_name, output_log_q_name |
ONNX tensor names (z, context, x_nf, log_q) |
Example single-model file:
onnx_path=/path/to/model_0p50_0p72_1p.ort
energy_min=0.5
energy_max=0.72
base_ind_circ=0,2,3
base_sigma=2,0.35,2,2
sigma_points_path=/path/to/C12_numu_1p.txt
cs_utils_name=mf_1p1h
particle=nu
lepton=mu
nucleus=C12
shell=4
filter_unphysical=true
oversample_factor=1.2
max_oversample_rounds=200
max_nn_batch_size=1
make_particles=true
particle_frame=lab
randomize_lab_phi=trueNEUT links the C++ library of section 11.2 (NuGenFlow branches of NEUT, dev/nugenflow*, code in src/models/contrib/nugenflow/). In the NEUT card:
[neut.interaction_model.QE]
model = "hfmf_1p1h" # MDLQE = 9300: QE sampled by NuGenFlow
[neut.interaction_model.QE.nugenflow]
nugenflow_models_dir = "/path/to/configs" # parent of the config trees
model = "HFMF_1p1h" # config subdirectory (defaults to "hfmf_1p1h")For each event NEUT builds <nugenflow_models_dir>/<model>/<Nucleus>/<species>.ini from the target (C12, O16, Ar40) and the neutrino (numu, numubar, nue, nuebar, nutau, nutaubar), and keeps one MultiModelSampler per file, so mixed-flavour runs use the right models. That file is a multi-model config listing one single-model .ini per energy window and shell. The total cross section comes from the models' sigma tables (per nucleus), divided by NEUT by the number of active nucleons; above the last trained window it is zero and NEUT does not select the channel. Events are generated one at a time.
The chain from trained runs to NEUT inputs is: compute the sigma table of every nucleus, flavour and shell with calculate_total_cs_multi_model (section 10.3), export each run to .onnx and .ort (section 11.1), and write the single-model and multi-model .ini files (section 11.3) in the <model>/<Nucleus>/<species>.ini layout.
| variable | used by | effect |
|---|---|---|
NUGENFLOW_ROOT |
configs (${oc.env:NUGENFLOW_ROOT}) |
repository root for generator, run-root, model and table (tables/) paths |
NUGENFLOW_REPO |
cross_section/mean_field_2p2h.yaml |
same, older name |
MF1P1H_RUNROOT |
HF mean-field and CRPA 1p1h | temporary run directories (default cfg.runroot) |
MF2P2H_RUNROOT |
exclusive 2p2h | same |
MF2P2H_STRICT |
exclusive 2p2h | 1: raise on missing generator output instead of returning NaN |
MF2P2H_KNOBS, MF2P2H_IWIDTH |
compute_mf_2p2h.sh |
parameter lines and Delta-width prescription (set by the model) |
NUGENFLOW_P_LEP_MIN_MEV |
1p1h models | antineutrino lepton-momentum cut (45 MeV/c) |
CRPA_POINT_TIMEOUT |
compute_crpa.sh |
seconds per xcrpa point (60) |
CRPA_GEN_TIMEOUT |
CRPA model | timeout of one wrapper call |
CRPA_DEBUG_KEEP, CRPA_KEEP_RUN |
CRPA | keep temporary directories |
If you use NuGenFlow in scientific work, please cite the associated publication so that the methodology and implementation can be properly acknowledged:
- M. El Baz et al., Phys. Rev. D, https://journals.aps.org/prd/abstract/10.1103/v7sz-vn3b
- the software: 10.5281/zenodo.24568765 (all versions; each release on Zenodo also has its own DOI, e.g. v1.0.0: 10.5281/zenodo.24568766)
When publishing results obtained with this software, please include a citation to the paper above and mention NuGenFlow explicitly in the methods or software section, with the version you used. CITATION.cff holds both references; GitHub's "Cite this repository" button formats them.
NuGenFlow is a research-oriented codebase. To extend the cross-section models, flows or training strategies:
- keep new cross sections compatible with the
CrossSectioninterface: subclass it and implement the mappings,log_differentialandlog_det_jacobian; addkinematics_mask(needed by the iterative trainer and the samplers) andparticles_from_kinematics(needed for particle output); - for a conditional model, set
n_conditionalandconditional_name, and implementsample_conditionalandconditional_bounds(uniform box, section 5.1); - add the corresponding Hydra configs under
apps/train/configs/(cross_section/,dataset/,flow/,trainer/, a top-leveltrain_*.yaml) and force-add them (git add -f, since*.yamlis ignored).
Bug reports, feature requests and contributions, especially new physics models, are very welcome.
NuGenFlow is released under the MIT licence (LICENSE). The optional Fortran model codes in submodules/ are separate projects with their own terms.