Repository navigation
This release delivers a major architectural and physics upgrade across TORAX, with over 500 changes since v1.4.3.
What's Changed
Simulation execution now runs through a fully JIT-compiled bounded while_loop by default—supporting both forward-mode and reverse-mode automatic differentiation as well as implicit differentiation through the Newton-Raphson solver—while torax.run_simulation() now returns StateHistory directly for low-overhead optimization and parameter sweeps.
Across physics modules, transport, pedestal, internal boundary conditions, edge, and neoclassical models have been refactored into composable, pluggable hierarchies with public custom-model registration APIs. New physics capabilities include: decoupled pedestal structure/formation/saturation models with dynamic L–H–L transitions, the Delabie (2026) metal-wall scaling law, and mtanh prescribed pedestal structure; power-dependent p′ constrained L-mode edge boundary conditions, composite multi-model edge and transport configurations, generalized MEQ and TokaMaker equilibrium support, exact bounce-averaged 2D trapped-particle fractions, Redl (2021) neoclassical conductivity, an overhauled Angioni–Sauter neoclassical transport implementation benchmarked against NCLASS and NEO, and exact Dirichlet matrix row replacement for internal boundary conditions as opposed to an adaptive source term.
Documentation has been overhauled for improved readability and maintainability.
For step-by-step upgrade instructions and before/after configuration examples, see the TORAX v1-to-v2 Migration Guide.
Breaking API changes and config highlights
-
Minimum Python & JAX versions: Dropped Python 3.11 support; TORAX now requires Python
>=3.12and JAX / jaxlib>=0.11.1. -
run_simulationreturn signature:torax.run_simulation(torax_config)now returnsStateHistorydirectly (callstate_history.simulation_output_to_xr()forxr.DataTreeoutput), andtorax.experimental.run_simulation_jittedhas been removed. -
Core state, geometry & public API restructuring:
CoreProfilesandtorax.transport.CoreTransportnow group profiles and transport coefficients into nested domain containers,SourceProfilesis replaced bytorax.sources.CoreSourceswith tieredSourcebase classes, andGeometryProvider/geometry_overrides/Geometry.torax_meshare replaced byGeometryModel, cross-timestepGeometryState(holdingPhi_b_dot), andRuntimeParamsProvider.geometry, alongside a streamlined top-leveltoraxnamespace. -
Configuration schema updates (no legacy shims):
ToraxConfigstrictly forbids unknown keys and standardizes all enum string literals and model discriminators tolower_snake_case(e.g.,'prescribed','bohm_gyrobohm','internal_boundary_condition','model_based'), including time-series interpolation modes ('step','piecewise_linear').-
Timestepping: Time-stepping bounds and adaptive step controls moved from
numericsintotime_step_calculator(dt,allow_backtracking,dt_backtracking_factor, and requiredmax_stepson adaptive calculators to bound the JIT loop). -
Current, flux & density conditions:
Iprenamed toI_p; current and poloidal-flux source flags consolidated intoprofile_conditions.I_p_source, requiredpsi_source, andpsi_bc_source; and density/Greenwald keys standardized (nbar→n_e_bar,normalize_n_e_to_nbar→normalize_n_e,*fGW→*f_GW). -
Transport & Pedestal:
transportnow takes named component dictionaries (core_transport_models,pedestal_transport_models) andsmoothing_zonesinstead of single-model configs and inner/outer patches.pedestalnestsstructure_model,formation_model, andsaturation_model, replacingADAPTIVE_SOURCEwith'internal_boundary_condition', standardizing pedestal-top keys from*_ped/*_ped_topto*_top, and defaultingchi_maxandD_e_maxtoNone(unclipped). -
Geometry: Flattened
GeometryConfigonto'model_name'('circular','chease','meq','eqdsk','tokamaker','imas'), replacing'geometry_type'and nested'geometry_configs'slice dicts with direct{time: ...}field/file mappings and requiring explicit equilibrium inputs on CHEASE and MEQ configs. -
Externalized ICRH surrogate: The
toric_nnICRH surrogate moved out of core TORAX into the externaltoric_surrogatepackage; built-insources.icrhuses'scaled_profile'. -
Source parameters & prescribed channels: Parameterized sources require explicit amplitudes and profile shapes when
mode='model_based'(removing arbitrary defaults), andprescribed_values(mode='prescribed') now takes named channel fields instead of positional tuples/arrays.
-
-
Output
xr.DataTreevariable renames:-
Ip→I_p(andIp_profile→I_p_profile). -
Toroidal current densities
j_total,j_ohmic,j_bootstrap,j_ecrh,j_generic_current,j_external,j_non_inductive→j_toroidal_*. -
Martin L–H threshold outputs
P_LH→P_LH_martinandP_LH_{high_density,low_density,min}→P_LH_martin_{high_density,low_density,min}. -
Source power, current & heat-exchange outputs unified with config names:
P_aux_generic_{i,e,total}→P_generic_heat_{i,e,total},I_aux_generic→I_generic_current,P_cyclotron_e→P_cyclotron_radiation_e,P_radiation_e→P_impurity_radiation_e, andei_exchange→p_ei_exchange_i/p_ei_exchange_e. -
Impurity, Greenwald & status outputs:
n_impurity/Z_impurity→n_impurity_{total,bundled}andZ_impurity_{average,bundled};fgw_n_e_{volume,line}_avg→f_GW_n_e_{volume,line}_avg;vloop_lcfs→v_loop_lcfs;n_e_min_P_LH→n_e_min_P_LH_martin; and removed redundantnumerics.sim_statusin favor ofnumerics.sim_error.
-
Physics + numerics features
-
Transport
-
Unified
TransportModelaround named component dictionaries (core_transport_modelsandpedestal_transport_models) supporting'add'and'overwrite'radialmerge_modecomposition, localizedsmoothing_zones, andpedestal_smoothing_width. -
Replaced the empirical Patankar power-law FVM convection discretization with the exact exponential (Scharfetter–Gummel) scheme using a degree-7 Bernoulli expansion at small Péclet numbers for float32/float64 precision.
-
Added smooth C1 particle flux splitting (
DV_effective_smooth_width) and upper collisionality clamping (max_normalized_collisionality) to quasilinear transport models (QualikizBasedTransportModelandTGLFBasedTransportModel). -
Integrated neural surrogate fast-ion ITG threshold stabilization into quasilinear transport models and exposed optional
output_mode_contributions(ITG/TEM/ETG) in QLKNN.
-
-
Pedestal & Internal Boundary Conditions (IBC)
-
Replaced penalty-based adaptive source terms with exact Dirichlet internal boundary conditions via tridiagonal matrix row replacement (
mode='internal_boundary_condition'), cleanly separated frommode='adaptive_transport'. -
Factored pedestal physics into modular
structure_model(no_pedestal,set_T_top_n_top,set_p_top_n_top,epednn_mit),formation_model(prescribed,martin_scaling,delabie_scaling), andsaturation_model(profile_value) components. -
Added a dynamic L–H–L confinement mode state machine supporting explicit
initial_confinement_mode('l_mode'or'h_mode'), smooth transition ramps (transition_time_width), hysteresis (P_LH_hysteresis_factor), optional dWth/dt inclusion in PSOL, and tracked L-mode pedestal-top baselines. -
Implemented the Delabie et al. (2026) metal-wall L–H threshold power scaling law (
delabie_scaling) with horizontal and vertical divertor target factors. -
Added standalone
internal_boundary_conditionsmodels onprofile_conditions, includingprescribedsparse arrays andbeta_poloidal_prime(BetaPoloidalPrimeIBCConfig) supporting constant and PSOL-dependent L-mode edge profiles, as well asn_e_right_bc_mode='density_fraction'.
-
-
Edge & Divertor
-
Introduced a modular
EdgeModelinterface with custom model registration (torax.experimental.edge) andmodel_name='combined'allowing distinct sub-models to supply individual core right boundary conditions (T_e,T_i,n_e,n_impurities). -
Added independent per-channel core BC update toggles, divertor impurity enrichment modeling, fixed-point under-relaxation and previous-step warm-starting across detachment transitions, limiter-phase (
diverted=False) BC bypass, and persistent cross-timestepEdgeStateacross file restarts.
-
-
Sources, Fast Ions & Radiation
-
Reformulated Ohmic heating as flux-surface-averaged inductive Joule dissipation Pohm = ⟨E · B⟩2/⟨B2⟩, accounting for moving-grid toroidal flux evolution (b).
-
Replaced
numerics.resistivity_multiplierwithnumerics.current_diffusion_time_reduction_factor, accelerating /t relaxation without artificially scaling physical conductivity, loop voltage, Ware pinch, or Ohmic heating. -
Integrated Mavrin (2017) non-coronal atomic radiation and charge-state tables.
-
Added prescribed fast-ion species support (
torax.experimental.fast_ion,profile_conditions.fast_ions, and sourceprescribed_values) and a stateful PID density-feedback model onsources.generic_particlewith anti-windup clamping and configurable deposition profiles. -
Added a prescribed neutral beam injection (
nbi) source supporting ion/electron heating, current drive, particle fueling, and prescribed fast-ion species.
-
-
Geometry & Equilibrium
-
Generalized the
fbtequilibrium loader tomeq(MEQConfig, supporting FBT, FGE, and LIUQE equilibria) and addedTokaMakerConfig(model_name='tokamaker'). -
Added
trapped_fraction_source('sauter','file','exact'), including exact bounce-averaged 2D numerical pitch-angle integration for EQDSK and IMAS equilibria. -
Added configurable
target_psi_grid_resolutiononEQDSKConfigand anchored asymptotic polynomial smoothing near the magnetic axis. -
Enabled dynamic per-step updates of prescribed poloidal flux from time-dependent equilibrium geometry (
psi_source='geometry') in interpretive current mode (evolve_current=False). -
Unified equilibrium evaluation under
GeometryModelwith host-side precomputation and cross-timestepGeometryState, computingPhi_b_dotas a backward interval secant across solver steps without restart override spikes.
-
-
Neoclassical & MHD
-
Consolidated analytical neoclassical models around shared precomputed collisional and geometric intermediates.
-
Added the Redl (2021) neoclassical conductivity model (
model_name='redl'),conductivity_multiplier,neoclassical_correctiontoggle, configurable neoclassical poloidal velocity sub-models ('kim'and'zeros'), and Shaing near-axis ion neoclassical transport blending. -
Replaced iterative sawtooth crash redistribution with a direct analytical volume-conserving formulation using smoothstep core flattening and cubic Hermite spline matching at the mixing radius.
-
Added MHD stability post-processed outputs:
alpha_mhd,alpha_mhd_miller,beta_pol_profile, andbeta_pol_prime.
-
Technical features
-
Default JIT run loop & bounded
while_loopautodiff: Simulation execution now runs through a singlejax.lax.while_loopengine supporting early termination alongside custom forward-mode (JVP) and reverse-mode (VJP) differentiation rules and stacked trajectory outputs. -
Implicit differentiation & GPU solver acceleration: Added implicit differentiation through the Newton-Raphson solver, custom JVP rules removing axis singularities in Sauter/Redl neoclassical models, residual row scaling, and
vmap_linesearchfor parallel backtracking step evaluation on GPUs. -
Unified state evaluation & stateful file restarts: Separated minimal PDE unknowns from derived plasma profiles in a single functional evaluation pipeline, and added
/model_stateNetCDF serialization across geometry, pedestal, edge, sources, and transport for seamless stateful restarts. -
Public plugin & custom-model API: Added public extension subpackages (
torax.transport,torax.pedestal,torax.sources,torax.output, andtorax.experimental.{edge,neoclassical,geometry}) with registration hooks for custom models,ToraxConfigschemas, andxr.DataTreestate serialization. -
Vectorized output assembly & fast error checking: Vectorized
xr.DataTreeoutput construction (~5.5x faster overall, >95% faster on 10,000-step trajectories) and fused post-step NaN/error checks into a single JIT kernel. -
Surrogate & coupling performance: Switched
tglfnn_ukaeainference tofloat32(fusion_surrogates==0.4.8), migrated standalone TGLF to direct f2py coupling viatglf_settings, eliminated redundant per-step pedestal evaluations, and optimized block-tridiagonal matrix assembly. -
Lossless JSON config serialization:
ToraxConfigJSON serialization now round-tripsinf/nanbounds cleanly.
UX/QoL improvements
-
IMAS workflow improvements:
IMASConfignow loads all equilibrium time slices automatically whenslice_time=None, supportstrapped_fractioningestion fromprofiles_1d, adds neutral beam injection (nbi) loading and export in IMAScore_sources, and bundles IMAS test assets inpipdistributions for out-of-the-box STEP examples. -
CLI & run bounding: Added
--max_stepsto therun_toraxCLI (andmax_stepstotorax.run_simulationandtime_step_calculator). -
Interactive plotting & lighter dependencies: Optimized
plot_runPlotly time-slider frames (~2.3x lower latency, ~4.3x smaller payloads), added initial-condition-only plotting, and movedmatplotlibout of core runtime dependencies into[dev]/[tutorial]extras. -
Upfront physics & cross-model validation: Added upfront Pydantic validation for incompatible current/flux boundary settings, unsupported
CircularGeometryoptions, edge–core impurity mismatches, overlapping'overwrite'transport zones, degenerate Zeff mixtures, and missing source or equilibrium parameters. -
Documentation & migration guide: Migrated ReadTheDocs to
sphinx-book-theme, split configuration docs into 13 dedicated section pages (docs/configuration/*.rst), expandeddocs/physics_models/*.rst, and updated all tutorial notebooks; added automated Pydantic config reference docs and a TORAX v1-to-v2 Migration Guide.
Bugfixes
-
Angioni–Sauter neoclassical transport: Resolved multiple analytical and metric bugs verified against EPFL's NEOS code, NCLASS and NEO, including an uncancelled B02 factor, Lmni and collisionless banana-limit H220 sign errors, missing Kmne friction matrix elements, using main-ion charge Zi (instead of Zeff) in i*, 1/2 poloidal flux-per-radian normalization, missing ⟨||^2⟩ and ⟨||⟩ flux-surface metrics, and I impurity strength scaling.
-
Pereverzev–Corrigan stabilization: Fixed discrete face interpolation so artificial diffusion and counter-convection cancel identically on stationary profiles over arbitrary non-uniform meshes (GitHub #2610), and prevented Pereverzev terms from corrupting Dirichlet internal boundary conditions or being clipped in
adaptive_transportmode. -
Turbulent ExB shear & radial electric field: Normalized ExB shear to Bpol in TGLF-based models per GACODE conventions, resolved magnetic-axis 0/0 singularities in QuaLiKiz and TGLF ExB shear and Bunit, removed duplicate
rotation_multiplierscaling in QuaLiKiz, and fixed the poloidal/toroidal velocity sign convention in radial force balance for Er. -
Collisions & scaling laws: Fixed logarithmic and Zi4 charge factors in the single-species ion–ion collision time ii, and corrected the effective mass exponent in the Delabie L–H threshold scaling law (2.0/Meff0.975).
-
Edge & Extended Lengyel: Fixed separatrix ion temperature BC in Extended Lengyel to scale with Ti/Teseparatrix rather than assuming Ti = Te, fixed target sound speed post-processing to include 1 + Ti/Tetarget, and fixed an under-relaxation state-aliasing bug in the forward fixed-point solver.
-
Moving-grid, current drive & radiation: Fixed double-counting of moving-grid b terms in FVM coefficient assembly; prevented division-by-zero NaNs in Lin–Liu counter-current ECCD; fixed a missing 1/B0 factor in
ElectronCyclotronSourceparallel current density; fixed Albajar cyclotron radiation to use scalarR_majorand handle flat/hollow profiles without NaNs; excluded radiation sinks from input power inradially_constant_fraction_of_Pin; and corrected source power density unit metadata fromMW/m^3toW/m^3. -
Equilibrium & pedestal geometry: Fixed contour seam double-counting in EQDSK geometry loading; prepended norm = 0 when external equilibria start off-axis; regularized g1/V′2 and g2/V′2 near = 0 to eliminate spiky initial on-axis
j_toroidal_total; weighted Gaussian transport smoothing by on non-uniform grids; and fixedmtanhpedestal mask alignment, two-point gradient masking across the pedestal top, and face-grid mapping inepednn_mit; corrected themtanhinternal boundary condition width to Δ = (1 − ρnorm,top) / 1.5 to distinguish pedestal-top from knee coordinates, and defaultedPedestalConfigchi_maxandD_e_maxtoNonesoadaptive_transportpedestals no longer clip core transport to 1.0 m2/s before applying suppression multipliers. -
Impurity dilution, bundling & dynamic mass: Fixed pure-plasma ion dilution and quasineutrality guards for non-hydrogenic main ions (
Z_eff == Z_i); separated true multi-impurity density and mean charge (n_impurity_total,Z_impurity_average) from 2-ion quasineutral/Zeff bundled quantities (n_impurity_bundled,Z_impurity_bundled) used by TGLF, QuaLiKiz, QLKNN, and collisional exchange; and dynamically updatedA_impuritywhen Extended Lengyel rescalesn_e_ratiosin inverse mode. -
Intra-step solver & initial-state consistency: Updated
fast_ions,psidot,j_toroidal_total, andI_p_profile_faceprior to intra-step neoclassical and turbulent transport evaluations (and source fast ions during t = 0 initialization) so bootstrap current, Ware pinch, and transport models evaluate on consistent iterate profiles rather than stale start-of-step values. -
Edge loop voltage &
psidotboundary consistency: Applied the prescribed Neumannpsigradient rate consistently across intra-step and post-step evaluations underpsi_bc_source='I_p', aligning saved LCFS transport coefficients with the PDE solve and matchingv_loop_lcfsto the instantaneous LCFSv_loopat all steps (including t = 0). -
tglfnn_ukaeaONNX numerical fidelity: Fixedtglfnn_ukaeaper-output normalizations and rescaled predictive variances by std2 to match the reference ONNX models (fusion_surrogates==0.4.8).