Skip to content

v2.0.0

Latest

Choose a tag to compare

@theo-brown theo-brown released this 04 Nov 16:34

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.12 and JAX / jaxlib >=0.11.1.

  • run_simulation return signature: torax.run_simulation(torax_config) now returns StateHistory directly (call state_history.simulation_output_to_xr() for xr.DataTree output), and torax.experimental.run_simulation_jitted has been removed.

  • Core state, geometry & public API restructuring: CoreProfiles and torax.transport.CoreTransport now group profiles and transport coefficients into nested domain containers, SourceProfiles is replaced by torax.sources.CoreSources with tiered Source base classes, and GeometryProvider / geometry_overrides / Geometry.torax_mesh are replaced by GeometryModel, cross-timestep GeometryState (holding Phi_b_dot), and RuntimeParamsProvider.geometry, alongside a streamlined top-level torax namespace.

  • Configuration schema updates (no legacy shims): ToraxConfig strictly forbids unknown keys and standardizes all enum string literals and model discriminators to lower_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 numerics into time_step_calculator (dt, allow_backtracking, dt_backtracking_factor, and required max_steps on adaptive calculators to bound the JIT loop).

    • Current, flux & density conditions: Ip renamed to I_p; current and poloidal-flux source flags consolidated into profile_conditions.I_p_source, required psi_source, and psi_bc_source; and density/Greenwald keys standardized (nbar → n_e_bar, normalize_n_e_to_nbar → normalize_n_e, *fGW → *f_GW).

    • Transport & Pedestal: transport now takes named component dictionaries (core_transport_models, pedestal_transport_models) and smoothing_zones instead of single-model configs and inner/outer patches. pedestal nests structure_model, formation_model, and saturation_model, replacing ADAPTIVE_SOURCE with 'internal_boundary_condition', standardizing pedestal-top keys from *_ped / *_ped_top to *_top, and defaulting chi_max and D_e_max to None (unclipped).

    • Geometry: Flattened GeometryConfig onto '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_nn ICRH surrogate moved out of core TORAX into the external toric_surrogate package; built-in sources.icrh uses 'scaled_profile'.

    • Source parameters & prescribed channels: Parameterized sources require explicit amplitudes and profile shapes when mode='model_based' (removing arbitrary defaults), and prescribed_values (mode='prescribed') now takes named channel fields instead of positional tuples/arrays.

  • Output xr.DataTree variable renames:

    • Ip → I_p (and Ip_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_martin and P_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, and ei_exchange → p_ei_exchange_i / p_ei_exchange_e.

    • Impurity, Greenwald & status outputs: n_impurity / Z_impurity → n_impurity_{total,bundled} and Z_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 redundant numerics.sim_status in favor of numerics.sim_error.

Physics + numerics features

  • Transport

    • Unified TransportModel around named component dictionaries (core_transport_models and pedestal_transport_models) supporting 'add' and 'overwrite' radial merge_mode composition, localized smoothing_zones, and pedestal_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 (QualikizBasedTransportModel and TGLFBasedTransportModel).

    • 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 from mode='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), and saturation_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_conditions models on profile_conditions, including prescribed sparse arrays and beta_poloidal_prime (BetaPoloidalPrimeIBCConfig) supporting constant and PSOL-dependent L-mode edge profiles, as well as n_e_right_bc_mode='density_fraction'.

  • Edge & Divertor

    • Introduced a modular EdgeModel interface with custom model registration (torax.experimental.edge) and model_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-timestep EdgeState across 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_multiplier with numerics.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 source prescribed_values) and a stateful PID density-feedback model on sources.generic_particle with 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 fbt equilibrium loader to meq (MEQConfig, supporting FBT, FGE, and LIUQE equilibria) and added TokaMakerConfig (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_resolution on EQDSKConfig and 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 GeometryModel with host-side precomputation and cross-timestep GeometryState, computing Phi_b_dot as 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_correction toggle, 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, and beta_pol_prime.

Technical features

  • Default JIT run loop & bounded while_loop autodiff: Simulation execution now runs through a single jax.lax.while_loop engine 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_linesearch for 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_state NetCDF 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, and torax.experimental.{edge,neoclassical,geometry}) with registration hooks for custom models, ToraxConfig schemas, and xr.DataTree state serialization.

  • Vectorized output assembly & fast error checking: Vectorized xr.DataTree output 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_ukaea inference to float32 (fusion_surrogates==0.4.8), migrated standalone TGLF to direct f2py coupling via tglf_settings, eliminated redundant per-step pedestal evaluations, and optimized block-tridiagonal matrix assembly.

  • Lossless JSON config serialization: ToraxConfig JSON serialization now round-trips inf / nan bounds cleanly.

UX/QoL improvements

  • IMAS workflow improvements: IMASConfig now loads all equilibrium time slices automatically when slice_time=None, supports trapped_fraction ingestion from profiles_1d, adds neutral beam injection (nbi) loading and export in IMAS core_sources, and bundles IMAS test assets in pip distributions for out-of-the-box STEP examples.

  • CLI & run bounding: Added --max_steps to the run_torax CLI (and max_steps to torax.run_simulation and time_step_calculator).

  • Interactive plotting & lighter dependencies: Optimized plot_run Plotly time-slider frames (~2.3x lower latency, ~4.3x smaller payloads), added initial-condition-only plotting, and moved matplotlib out of core runtime dependencies into [dev] / [tutorial] extras.

  • Upfront physics & cross-model validation: Added upfront Pydantic validation for incompatible current/flux boundary settings, unsupported CircularGeometry options, 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), expanded docs/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_transport mode.

  • 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_multiplier scaling 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 ElectronCyclotronSource parallel current density; fixed Albajar cyclotron radiation to use scalar R_major and handle flat/hollow profiles without NaNs; excluded radiation sinks from input power in radially_constant_fraction_of_Pin; and corrected source power density unit metadata from MW/m^3 to W/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 fixed mtanh pedestal mask alignment, two-point gradient masking across the pedestal top, and face-grid mapping in epednn_mit; corrected the mtanh internal boundary condition width to Δ = (1 − ρnorm,top) / 1.5 to distinguish pedestal-top from knee coordinates, and defaulted PedestalConfig chi_max and D_e_max to None so adaptive_transport pedestals 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 updated A_impurity when Extended Lengyel rescales n_e_ratios in inverse mode.

  • Intra-step solver & initial-state consistency: Updated fast_ions, psidot, j_toroidal_total, and I_p_profile_face prior 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 & psidot boundary consistency: Applied the prescribed Neumann psi gradient rate consistently across intra-step and post-step evaluations under psi_bc_source='I_p', aligning saved LCFS transport coefficients with the PDE solve and matching v_loop_lcfs to the instantaneous LCFS v_loop at all steps (including t = 0).

  • tglfnn_ukaea ONNX numerical fidelity: Fixed tglfnn_ukaea per-output normalizations and rescaled predictive variances by std2 to match the reference ONNX models (fusion_surrogates==0.4.8).