The Open FUSION Toolkit 26.9
An open-source framework for fusion and plasma science and engineering
Loading...
Searching...
No Matches
TokaMaker_TORAX Class Reference

Detailed Description

TokaMaker + TORAX Coupled Pulse Simulation Code.

Public Member Functions

 __init__ (self, t_init, t_final, eqtimes, g_eqdsk_arr, tokamaker_obj, tx_dt=0.1, tm_times=None, last_surface_factor=0.99, truncate_eq=False)
 Initialize the Coupled TokaMaker + TORAX object.
 configure_redirect_to_log (self)
 Step 3/3 of setup to divert noisy outputs to log file.
 fly (self, run_name='tmp', convergence_threshold=-1.0, max_loop=3, output_mode=False, skip_bad_init_eqdsks=False, initial_relax=True, relax=False, relax_kinetics=False, relax_duration=1.0, relax_dt=0.1, t_ave_toggle='off', t_ave_window=0.5, t_ave_causal=True, t_ave_ignore_start=0.25, loop0=False, steady_state_mode=False)
 Run TokaMaker_TORAX coupled pulse design loop.
 get_final_timepoint_results (self, eqdsk_save_dir=None)
 Profiles and scalars at the last TokaMaker timepoint of the last completed coupling loop.
 load_pedestal_config (self, pedestal_config)
 Deprecated: use set_pedestal(config=...).
 load_TORAX_config (self, config)
 Load a TORAX config dict.
 make_movie (self, save_path=None, **kwargs)
 Generate pulse movie from stored psi snapshots.
 plot_coil_current_tunnel (self, save_path=None, display=True, **kwargs)
 Plot coil currents inside their rate-limited bounds "tunnel" over the pulse.
 plot_coils (self, save_path=None, display=True, **kwargs)
 Plot coil current traces over the pulse.
 plot_coupling_convergence (self, save_path=None, display=True, **kwargs)
 Plot the coupling-convergence cost vs loop (the loop-over-loop trend of the flavor-2 aggregate).
 plot_errors (self, save_path=None, display=True, **kwargs)
 Plot per-timestep TokaMaker-vs-TORAX coupling error metrics (one figure per loop; layout mirrors plot_scalars).
 plot_lcfs_evolution (self, save_path=None, display=True, one_plot=False, **kwargs)
 Plot time evolution of the LCFS for each pulse phase (rampup, flattop, rampdown).
 plot_PLH_components (self, save_path=None, display=True, **kwargs)
 Plot the components of the PLH model (pedestal height, width, and core gradient) over time.
 plot_profile_evolution (self, save_path=None, display=True, one_plot=False, **kwargs)
 Plot profile evolution over time.
 plot_profiles (self, **kwargs)
 Interactive profile viewer (ipywidgets slider in Jupyter, static otherwise).
 plot_scalars (self, save_path=None, display=True, **kwargs)
 Plot scalar time traces (Ip, Q, Te, ne, power channels, etc.).
 save_res (self)
 Save simulation results to JSON.
 save_state (self, fname)
 Save intermediate simulation state to JSON.
 save_tmtx_config (self, save_path=None)
 Write a self-contained reproduction config file: tmtx_config_{run}_{ts}.py (tmtx_config_tmp.py with no timestamp when run_name='tmp', so it is overwritten each run).
 set_coil_rate_limits (self, dIdt=None, dIdt_units='A-turns/s', V=None, R=None, dt_floor=0.5)
 Constrain how fast each coil current may change between TokaMaker solves.
 set_diverted_shape_targets (self, diverted_times=None, x_point_targets=None, x_point_weight=1000.0, strike_point_targets=None, trim_lcfs=True, trim_lcfs_perc_limit=0.80, secondary_x_point_targets=None, shape_target=None, secondary_x_point_weight=None, strike_point_weight=None)
 Configure the diverted window: X-point targets, strike points, and the optional LCFS shape target — plus the weights of the constraints that only exist while diverted.
 set_evolve (self, density=True, Ti=True, Te=True, current=True)
 Set variables as either prescribed (False) or evolved (True) for TORAX.
 set_fueling (self, gas_puff_S_total=None, gas_puff_decay_length=None, pellet_deposition_location=None, pellet_width=None, pellet_S_total=None, generic_particle_location=None, generic_particle_width=None, generic_particle_S_total=None)
 Set gas puff and pellet fueling particle sources for TORAX.
 set_heating (self, generic_heat=None, generic_heat_loc=None, generic_heat_width=0.25, generic_heat_absorption_fraction=1.0, generic_heat_electron_heat_fraction=0.4, nbi_current=False, ecrh=None, ecrh_loc=None, ecrh_width=0.1, ohmic=None, fusion=True, ei_exchange=True)
 Set TORAX heating and source toggles.
 set_Ip (self, Ip)
 Set plasma current (Amps), used for both codes and not evolved by either.
 set_ne (self, n_e, right_bc=None)
 Set electron density profiles and optional right boundary condition.
 set_pedestal (self, config_mode='off', config=None, ped_height_Te=None, ped_height_Ti=None, ped_height_ne=None, ped_width=0.15, transition_time=0.5, timing='detect', lh_time=None, hl_time=None, formation_model='delabie_scaling', adaptive_T_source_prefactor=None, adaptive_n_source_prefactor=None, core_height_Te=None, core_height_Ti=None, core_height_ne=None, core_exp_a=2.0, core_exp_b=2.0, set_pedestal=None, T_i_ped=None, T_e_ped=None, n_e_ped=None, ped_top=0.90)
 Configure the TORAX pedestal model.
 set_plasma_composition (self, Zeff=None, main_ion=None, impurity=None)
 Set plasma effective charge and composition.
 set_Te (self, T_e, right_bc=None)
 Set electron temperature profiles and optional right boundary condition.
 set_Ti (self, T_i, right_bc=None)
 Set ion temperature profiles and optional right boundary condition.
 set_TokaMaker_coil_reg (self, coil_bounds=None, coil_bounds_units='A-turns', updownsym=False, default_weight=1.0E-1, disable_coils=None, disable_weight=1.0E4, symmetry_weight=1.0E3, disable_virtual_vsc=True, vsc_weight=1.0E4)
 Set coil regularization using the dict-based TokaMaker reg_terms API.
 set_TokaMaker_constraint_weights (self, isoflux_weight=LCFS_WEIGHT, psi_lcfs_weight=PSI_LCFS_WEIGHT)
 Set the GS constraint weights applied at EVERY timepoint of the coupled solve.
 set_TORAX_grid (self, grid_type, grid)
 Set TORAX grid type and grid points.
 set_transport_coefs (self, chi_min=None, chi_max=None, De_min=None, De_max=None, Ve_min=None, Ve_max=None)
 Set transport coefficient bounds for TORAX.
 set_x_points (self, *args, **kwargs)
 Deprecated: use set_diverted_shape_targets() instead.
 summary (self, **kwargs)
 Print/display a physics summary of the simulation.

Public Attributes

 lcfs = lcfs
 results = None
 Access simulation results dict.
 state = None
 Access simulation state dict.

Protected Member Functions

 _aperturn_bounds_to_aturn (self, coil_bounds_aperturn)
 Convert a {coil: [lo, hi]} bounds dict from A/turn to total A-turns.
 _apply_rate_limited_bounds (self, i, t)
 Tighten coil bounds around the last good solved currents for this solve.
 _apply_tm_coil_reg (self, targets=None)
 Internal: build and apply reg_terms from stored config plus per-timestep targets.
 _apply_tx_set_overrides (self, myconfig)
 Apply user set_*() overrides to a TORAX config dict (in place).
 _aturn_bounds_to_aperturn (self, coil_bounds_aturn)
 Convert a {coil: [lo, hi]} bounds dict from A-turns to A/turn for TokaMaker.
 _build_manual_ibc (self)
 Build the internal_boundary_conditions block for T_e, T_i, n_e from the MANUAL pedestal knobs.
 _calc_tx_ffp_ni (self, i)
 Calculate non-inductive FF' profile from TORAX current densities.
 _capture_confinement_mode (self, state_list)
 Map per-step pedestal confinement_mode to an H-mode bool series, store it per tm_time in _state['confinement_mode'], and record the H-mode start/end times.
 _capture_relax_tx_profiles_from_datatree (self, data_tree, time_val=None)
 Store psi, n_e, T_e, T_i at time_val for debug relax figures / history.
 _capture_steady_state_tx_seed (self, data_tree)
 Store psi, n_e, T_e, T_i at t_final for steady_state_mode next coupling loop.
 _coil_net_turns (self, cname)
 Number of turns for a coil set (from the mesh coil definition); 1 if unknown or zero.
 _compute_coupling_cost (self)
 Flavor-2 coupling-convergence cost: a single dimensionless scalar per timestep (stored in state['coupling_cost'], overwritten each loop) plus a per-loop aggregate appended to self._coupling_cost_history (the trend that is the point of this metric).
 _compute_errors (self)
 Compute per-timestep coupling error metrics (TokaMaker achieved vs TORAX target) and store them in the err_* state arrays.
 _convolve_prof (self, cur_prof, ref_prof, alpha, out_type='linterp')
 Convex convolution between the current TORAX profile (alpha=0) and a reference profile (alpha=1).
 _coupling_iteration_is_first (self)
 True on the first TokaMaker_TORAX loop (TORAX uses the seed gEQDSK map).
 _expand_coil_setting (self, arg, name)
 Normalize a scalar-or-dict per-coil setting to a {coil: value} dict.
 _extract_tx_profile (self, data_tree, var_name, time, load_into_state='state', normalize=False, profile_type='linterp')
 Extract a TORAX profile onto self._psi_N with optional time-averaging.
 _extract_tx_scalar (self, data_tree, var_name, time, source='scalars', scale=1.0)
 Extract a scalar value from TORAX with optional time-averaging.
 _extract_tx_scalar_at_rho (self, data_tree, var_name, time, rho_val, rho_coord='rho_norm', scale=1.0)
 Extract a profile value at a specific rho location as a scalar, with time-averaging.
 _extract_tx_scalar_at_rho_timeseries (self, data_tree, var_name, rho_val, rho_coord='rho_norm', scale=1.0)
 Extract a profile-at-fixed-rho time-series with time-averaging.
 _extract_tx_scalar_timeseries (self, data_tree, var_name, source='scalars', scale=1.0)
 Extract a full time-series scalar from TORAX with time-averaging applied at each point.
 _get_time_window (self, time, tx_times)
 Return the (t_start, t_end) averaging window for a given timepoint.
 _get_tx_config (self)
 Generate config object for Torax simulation.
 _global_bounds_dict (self)
 The configured per-coil hard bounds [A-turns], as set by set_TokaMaker_coil_reg().
 _interp_tx_profile_onto_psi (self, data_tree, var_name, time, profile_type='linterp')
 Interpolate a single TORAX profile snapshot onto self._psi_N.
 _log (self, msg)
 Write message to log file only.
 _log_flattop_summary (self, flux_consumed=None)
 Print a table of key physics parameters evaluated at the end of flattop.
 _loop0_coarse_tx_main_scope (self)
 Apply loop-0 coarse TORAX grid for main _run_tx; restore after.
 _loop0_coarse_tx_relax_scope (self, stage)
 Apply loop-0 coarse TORAX grid during initial relax only; restore after.
 _manual_ibc_active (self)
 True when the internal_manual pedestal IBC should be imposed this loop, i.e.
 _normalize_coil_bounds_dict (self, coil_bounds)
 Normalize a coil-bounds input to a {coil: [lo, hi]} dict (input units preserved).
 _pop_tx_grid (self)
 Restore TORAX grid from _push_tx_grid stack.
 _print (self, msg)
 Write message to both stdout and log file.
 _push_coil_bounds (self, coil_bounds_aturn)
 Store the currently active bounds (A-turns) and apply them to TokaMaker (A/turn).
 _push_tx_grid (self)
 Save current TORAX grid onto stack for later _pop_tx_grid.
 _quiet_tm (self)
 Context manager: redirect C/Fortran-level stdout+stderr to /dev/null.
 _res_update (self, data_tree)
 Populate self._results from TORAX data with time-averaging.
 _resolve_right_bc (self, field, set_value)
 Effective edge (rho=1) BC for an internal_manual pedestal foot.
 _run_tm (self)
 Run the GS solve across n timesteps using TokaMaker.
 _run_torax (self, config)
 Run TORAX via prepare_simulation + run_loop so we keep the raw list[SimState] (torax.run_simulation() drops the pedestal confinement_mode).
 _run_tx (self)
 Run the TORAX transport simulation.
 _run_tx_relax (self, *, stage, eqdsk_path, prescribed_profiles)
 Short TORAX relax: initial run on the seed EQDSK, or inter-loop on TM i=0 EQDSK.
 _set_confinement_from_window (self, end_fallback=None)
 Fill the per-tm-time H-mode flag from the known [lh, hl] window.
 _smooth_ibc_inner_edge (self)
 Match the imposed pedestal inner-edge value AND gradient to the TORAX-evolved core PER TM-TIME, so the next loop's IBC tracks the evolving profile time-point by time-point and joins the core smoothly (no kink/jog -> p' spike -> TM GS failure).
 _test_eqdsk_tx_config (self, eqdsk, *, quiet=False)
 Return whether TORAX accepts eqdsk as ToraxConfig geometry.
 _tm_prof_input_ped_smooth (self, ffp_prof, pp_prof, p_prof, transition_psi_N=0.6, gauss_sigma=8, blend_width=0.02, sav_window=41, sav_order=3)
 Edge smoothing with Gaussian filter: smooth p profile and take derivative for pp_prof.
 _tm_prof_input_power_flux (self, ffp_prof, pp_prof)
 Generic power-flux shape.
 _tm_prof_input_raw (self, ffp_prof, pp_prof)
 Raw TORAX profiles passed through unchanged.
 _tm_prof_input_sign_flip (self, ffp_prof, pp_prof)
 Sign-flip clipping: clip each profile to its dominant sign.
 _tm_update (self, i)
 Update internal state and coil current results based on results of GS solver.
 _tx_update (self, i, data_tree, tx_time=None)
 Update the simulation state from TORAX results at timestep i.
 _zz_doxygen_dummy (self)

Static Protected Member Functions

 _first_sustained (times, flags, target, start, dwell)
 Index of the first step at/after start where flags == target and that value holds continuously for at least dwell seconds.
 _flatten_time_dependent (config)
 Recursively flatten time-dependent config values to their initial value only.
 _format_config_literal (obj, indent=0)
 Render a config dict as a runnable Python literal, emitting numpy arrays as np.array([...]) so the saved file re-runs identically.
 _loop0_tm_solve_indices (n_tm, stride)
 TokaMaker timestep indices for coupling loop 0 subsampling: endpoints plus every stride-th.
 _normalize_coil_bounds_units (units)
 Validate/normalize a coil-bounds units string to 'A-turns' or 'A/turn'.
 _normalize_coil_rate_units (units)
 Validate/normalize a dI/dt units string to 'A-turns/s' or 'A/turn/s'.
 _numpy_to_plain_python (obj)
 Recursively convert numpy scalars/arrays to plain Python types.
 _numpy_to_plain_python_keep_arrays (obj)
 Like _numpy_to_plain_python but leaves np.ndarray intact (for literal-repr save).
 _relax_flat_profile_to_rho_y (profile_val)
 (rho_norm, y) from a profile_conditions value after merge + flatten.
 _tx_config_merge (base, override)
 Recursively merge override into base TORAX config (in-place).

Protected Attributes

 _chi_max = None
 _chi_min = None
int _cocos = 2
 _coil_bounds = copy.deepcopy(coil_bounds_aturn)
 _coil_bounds_global = copy.deepcopy(coil_bounds)
dict _coil_bounds_history = {}
 _coil_dIdt = coil_dIdt
 _coil_rate_dt_floor = max(0.0, float(dt_floor))
dict _coil_rate_limit_config
dict _coil_reg_config
float _core_exp_a = 2.0
float _core_exp_b = 2.0
 _core_height_ne = None
 _core_height_Te = None
 _core_height_Ti = None
list _coupling_cost_history = []
int _current_loop = 0
 _data_tree = data_tree
 _De_max = None
 _De_min = None
bool _debug_mode = False
bool _diagnostics = False
dict _diverted_flags = {}
 _diverted_lcfs_shape = None
 _diverted_times = None
 _ecrh_heating = None
 _ecrh_loc = None
 _ecrh_width = None
bool _enable_ei_exchange = True
bool _enable_fusion = True
 _eqdsk_dir = None
bool _eqdsk_dir_is_temp = False
list _eqdsk_skip = []
dict _eqdsk_topology = {}
 _eqtimes = eqtimes
list _error_history = []
 _evolve_current = None
 _evolve_density = None
 _evolve_Te = None
 _evolve_Ti = None
 _flattop
 _fly_loop0 = bool(loop0)
 _fname_out
 _generic_heat = None
 _generic_heat_absorption_fraction = None
 _generic_heat_electron_heat_fraction = None
 _generic_heat_loc = None
 _generic_heat_width = None
 _generic_particle_location = None
 _generic_particle_s_total = None
 _generic_particle_width = None
 _gp_dl = None
 _gp_s = None
 _hl_time = None
 _impurity = None
 _init_files = g_eqdsk_arr
 _Ip = None
dict _Ip_seed = self._state['Ip'].copy()
 _isoflux_weight = LCFS_WEIGHT
 _last_good_coil_currents = None
list _last_good_t = None
 _last_surface_factor = last_surface_factor
 _lh_time = None
 _loaded_config = None
 _log_file = None
bool _logging_configured = False
 _loop0_coarse_tx = self._fly_loop0
 _loop0_relax_coarse_tx = self._fly_loop0
int _loop0_tm_stride = 2 if self._fly_loop0 else 1
 _loop0_tx_face_points = int(DEFAULT_LOOP0_TX_FACE_POINTS)
 _main_ion = None
 _n_e = None
 _n_e_init = None
 _n_e_ped = None
 _nbar = None
 _nbi_heating = None
 _nbi_loc = None
 _ne_right_bc = None
 _normalize_to_nbar = None
 _ohmic_power = None
 _out_dir = None
str _output_file_tag = None
bool _output_mode = False
dict _pax_seed = self._state['pax'].copy()
dict _ped_core_relaxed = {}
bool _ped_formation_model = False
str _ped_formation_model_name = 'delabie_scaling'
 _ped_height_ne = None
 _ped_height_Te = None
 _ped_height_Ti = None
dict _ped_ibc_snapshot = None
dict _ped_lmode_profile = {}
str _ped_mode = 'off'
 _ped_n_source_prefactor = None
dict _ped_smoothed = {}
 _ped_T_source_prefactor = None
str _ped_timing = 'detect'
 _ped_top = None
float _ped_transition_time = 0.5
float _ped_width = 0.15
 _pedestal_config = None
 _pellet_deposition_location = None
 _pellet_s_total = None
 _pellet_width = None
dict _psi_axis_seed = self._state['psi_axis_tm'].copy()
tuple _psi_init = None
tuple _psi_init_seed = None
dict _psi_lcfs_seed = self._state['psi_lcfs_tm'].copy()
 _psi_lcfs_weight = PSI_LCFS_WEIGHT
 _psi_N = np.linspace(0.0, 1.0, N_PSI)
dict _psi_warm_start = {}
 _rate_limit_active = bool(coil_dIdt)
dict _rate_ref_for = {}
 _relax = bool(relax)
 _relax_dt = _relax_dt
 _relax_duration = float(relax_duration)
 _relax_kinetics = bool(relax_kinetics)
list _relax_mainrun_profile_history = []
 _relax_profiles_snapshot = None
dict _results = {}
 _run_name = run_name
str _run_timestamp = None
bool _save_outputs = False
tuple _secondary_x_point_targets = None
tuple _secondary_x_point_weight = None
bool _set_pedestal = None
 _skip_bad_init_eqdsks
dict _state = {}
bool _steady_state_mode = False
 _steady_state_tm_psi_seed = None
 _steady_state_tx_seed = None
 _strike_point_targets = None
tuple _strike_point_weight = None
 _t_ave_causal
 _t_ave_ignore_start = t_ave_ignore_start
str _t_ave_toggle = 'off':
 _t_ave_window = t_ave_window
 _T_e = None
 _T_e_init = None
 _T_e_ped = None
 _t_final = t_final
 _T_i = None
 _T_i_init = None
 _T_i_ped = None
 _t_init = t_init
 _Te_right_bc = None
 _Ti_right_bc = None
 _tm = tokamaker_obj
dict _tm_psi_on_nodes = {}
list _tm_times = sorted(eqtimes)
int _torax_run_count = 0
bool _trim_lcfs = True
 _trim_lcfs_perc_limit = trim_lcfs_perc_limit
 _truncate_eq = truncate_eq
 _tx_config_snapshot = None
 _tx_dt = tx_dt
list _tx_grid = None
list _tx_grid_stash = []
str _tx_grid_type = None
bool _use_nbi_current = False
 _Ve_max = None
 _Ve_min = None
 _x_point_targets = None
float _x_point_weight = 1000.0
 _Zeff = None

Constructor & Destructor Documentation

◆ __init__()

__init__ ( self,
t_init,
t_final,
eqtimes,
g_eqdsk_arr,
tokamaker_obj,
tx_dt = 0.1,
tm_times = None,
last_surface_factor = 0.99,
truncate_eq = False )

Initialize the Coupled TokaMaker + TORAX object.

Parameters
t_initStart time (s).
t_finalEnd time (s).
eqtimesTime points of each gEQDSK file.
g_eqdsk_arrFilenames of each gEQDSK file.
tokamaker_objPreconfigured TokaMaker object.
tx_dtTime step (s) of TORAX simulation.
tm_timesTime points where TokaMaker solves equilibrium.
last_surface_factorLast surface factor for Torax.
truncate_eqWhether to truncate equilibrium when saving TokaMaker output to EQDSK.

Coupling fly() option loop0: if True, the first coupling pass uses a coarse TORAX grid and subsampled TokaMaker times; if False, that pass is skipped (see fly()).

Member Function Documentation

◆ _aperturn_bounds_to_aturn()

_aperturn_bounds_to_aturn ( self,
coil_bounds_aperturn )
protected

Convert a {coil: [lo, hi]} bounds dict from A/turn to total A-turns.

Inverse of _aturn_bounds_to_aperturn: I[A-turns] = I[A/turn] * net_turns. Lets a user specify coil bounds in the per-winding current TokaMaker uses natively; they are stored internally in A-turns (the single source of truth).

◆ _apply_rate_limited_bounds()

_apply_rate_limited_bounds ( self,
i,
t )
protected

Tighten coil bounds around the last good solved currents for this solve.

No-op (leaves the current bounds in place) when rate limiting is inactive or there is no last-good current yet (first solve / no prior success). The per-step bounds [A-turns] are recorded in self._coil_bounds_history[i] for the tunnel diagnostic.

Parameters
iTimestep index.
tCurrent solve time [s].

◆ _apply_tm_coil_reg()

_apply_tm_coil_reg ( self,
targets = None )
protected

Internal: build and apply reg_terms from stored config plus per-timestep targets.

Parameters
targetsDict of {coil_name: current [A/turn]} to use as soft targets, or None for zeros.

◆ _apply_tx_set_overrides()

_apply_tx_set_overrides ( self,
myconfig )
protected

Apply user set_*() overrides to a TORAX config dict (in place).

Only applied when the corresponding attribute is not None (i.e. the user called the setter explicitly; None means fall through to the loaded/base config). Used by both _get_tx_config (coupling loop 0+) and _run_tx_relax so each relax simulation sees the same plasma conditions as the main sim.

Does NOT touch geometry, numerics.{t_initial, t_final, fixed_dt}, or profile_conditions.{psi, initial_psi_mode, initial_psi_from_j} — those are loop-specific and set by the calling method.

Parameters
myconfigConfig dict (modified in place).

◆ _aturn_bounds_to_aperturn()

_aturn_bounds_to_aperturn ( self,
coil_bounds_aturn )
protected

Convert a {coil: [lo, hi]} bounds dict from A-turns to A/turn for TokaMaker.

TokaMaker's set_coil_bounds expects the per-winding current [A/turn]; the public TokaMaker_TORAX API works in total A-turns. I[A/turn] = I[A-turns] / net_turns.

◆ _build_manual_ibc()

_build_manual_ibc ( self)
protected

Build the internal_boundary_conditions block for T_e, T_i, n_e from the MANUAL pedestal knobs.

The pedestal foot (rho=1) is the edge BC from set_ne/set_Te/set_Ti (so n_e_right_bc and the IBC agree there); the inner-edge gradient uses the smoothed slope from _smooth_ibc_inner_edge when available, else a straight line from ped_top down to foot.

If a core_height is set for a field, a CORE band (rho 0->just inside ped_rho) is merged in that ramps the evolved L-mode core into a smooth H-mode-like core shape over the L->H transition, then retreats. The two bands are disjoint (the pedestal band owns [ped_rho,1] at all times); they meet at ped_rho with the same value.

Returns
{field: SparseTimeVaryingArray} for the fields with a height set.

◆ _calc_tx_ffp_ni()

_calc_tx_ffp_ni ( self,
i )
protected

Calculate non-inductive FF' profile from TORAX current densities.

The full GS relation is: FF'_total = 2 * mu_0 * (j_tor + p' * <R>) / <1/R>

To avoid double-counting p' when decomposing into inductive/non-inductive: FF'_NI = 2 * mu_0 * j_NI / <1/R> FF'_I = 2 * mu_0 * (j_I + p' * <R>) / <1/R>

Parameters
iTime index
Returns
FF'_NI profile array

◆ _capture_confinement_mode()

_capture_confinement_mode ( self,
state_list )
protected

Map per-step pedestal confinement_mode to an H-mode bool series, store it per tm_time in _state['confinement_mode'], and record the H-mode start/end times.

H_MODE and TRANSITIONING_TO_H_MODE -> True; L_MODE and TRANSITIONING_TO_L_MODE -> False. No-op (leaves all False) if the L/H state machine is inactive.

The confinement_mode can dither around a transition, so a transition is only accepted once the new state persists for at least the pedestal transition_time (dwell debounce): a brief L dip inside H-mode is not read as the back-transition, and a brief H blip in L-mode is not read as the L->H transition.

Parameters
state_listlist[SimState] from _run_torax.

◆ _capture_relax_tx_profiles_from_datatree()

_capture_relax_tx_profiles_from_datatree ( self,
data_tree,
time_val = None )
protected

Store psi, n_e, T_e, T_i at time_val for debug relax figures / history.

Updates _relax_profiles_snapshot temporarily so the caller can append a copy to _relax_mainrun_profile_history. Not used to seed inter-loop relax runs (those profiles come from the user config each time).

◆ _capture_steady_state_tx_seed()

_capture_steady_state_tx_seed ( self,
data_tree )
protected

Store psi, n_e, T_e, T_i at t_final for steady_state_mode next coupling loop.

Profile tuples use t_init as the time key (TORAX profile_conditions convention), matching _psi_init / relax snapshots.

◆ _coil_net_turns()

_coil_net_turns ( self,
cname )
protected

Number of turns for a coil set (from the mesh coil definition); 1 if unknown or zero.

A virtual coil (e.g. the vertical-stability VS coil) has net_turns = 0 in the mesh; for the A-turns <-> A/turn conversion there is no physical winding count to divide by, so treat it as 1 turn (total A-turns == A/turn for such a coil).

◆ _compute_coupling_cost()

_compute_coupling_cost ( self)
protected

Flavor-2 coupling-convergence cost: a single dimensionless scalar per timestep (stored in state['coupling_cost'], overwritten each loop) plus a per-loop aggregate appended to self._coupling_cost_history (the trend that is the point of this metric).

Requires _compute_errors() to have run first.

Each physics channel's error is normalized by a characteristic TORAX scale to a dimensionless fraction, then channels are combined as a weight- normalized RMS. Weights live in _COUPLING_COST_WEIGHTS and floors in _COUPLING_COST_FLOORS (both module-level; see the tuning notes there).

◆ _compute_errors()

_compute_errors ( self)
protected

Compute per-timestep coupling error metrics (TokaMaker achieved vs TORAX target) and store them in the err_* state arrays.

Called once per loop, after all TM solves, just before plotting. All error arrays have one entry per tm_time and are overwritten each loop (they reflect the latest loop only). NaN marks a time where the channel is undefined: no TM/TX data yet for that time, or X-points outside the diverted window.

Sign convention for the raw scalar differences is (TM - TX). RMS profile errors are in the profiles' native (real) units on the TM psi_N grid. LCFS and X-point errors are geometric distances in metres.

◆ _convolve_prof()

_convolve_prof ( self,
cur_prof,
ref_prof,
alpha,
out_type = 'linterp' )
protected

Convex convolution between the current TORAX profile (alpha=0) and a reference profile (alpha=1).

Convolution is in normalized shape space (peak abs = 1) so the reference never adds amplitude — only smooths shape. The result is rescaled to the current profile's amplitude and sign. The caller chooses which current/reference profiles to convolve (FF', p', FF'_NI, or jphi) and the output out_type ('linterp' or 'jphi-linterp').

◆ _coupling_iteration_is_first()

_coupling_iteration_is_first ( self)
protected

True on the first TokaMaker_TORAX loop (TORAX uses the seed gEQDSK map).

◆ _expand_coil_setting()

_expand_coil_setting ( self,
arg,
name )
protected

Normalize a scalar-or-dict per-coil setting to a {coil: value} dict.

A bare scalar is applied to every (real) coil set; a dict is validated against the known coil names. The virtual VSC coil (#VSC) is excluded.

Parameters
argNone, a scalar, or a {coil_name: value} dict.
nameHuman-readable setting name for error messages.
Returns
Dict {coil_name: float} (empty if arg is None).

◆ _extract_tx_profile()

_extract_tx_profile ( self,
data_tree,
var_name,
time,
load_into_state = 'state',
normalize = False,
profile_type = 'linterp' )
protected

Extract a TORAX profile onto self._psi_N with optional time-averaging.

Replaces the former _pull_tx_onto_psi. When time-averaging is active the profile is interpolated at every TORAX timestep inside the window and the results are averaged pointwise on the psi_N grid.

Parameters
data_treeTORAX output data tree.
var_nameName of variable (e.g., 'T_i', 'j_ohmic', 'FFprime').
timeTarget time value.
load_into_state'state' → return dict; else return plain array.
normalizeIf True, normalize profile by the core value.
profile_type'linterp' or 'jphi-linterp'.

◆ _extract_tx_scalar()

_extract_tx_scalar ( self,
data_tree,
var_name,
time,
source = 'scalars',
scale = 1.0 )
protected

Extract a scalar value from TORAX with optional time-averaging.

Parameters
data_treeTORAX output data tree.
var_nameAttribute name on data_tree.scalars (or .profiles).
timeTarget time (seconds).
source'scalars' or 'profiles' — which subtree to read from.
scaleMultiplicative factor applied after extraction.
Returns
float — the (optionally averaged) scalar value.

◆ _extract_tx_scalar_at_rho()

_extract_tx_scalar_at_rho ( self,
data_tree,
var_name,
time,
rho_val,
rho_coord = 'rho_norm',
scale = 1.0 )
protected

Extract a profile value at a specific rho location as a scalar, with time-averaging.

Parameters
data_treeTORAX output data tree.
var_nameAttribute name on data_tree.profiles.
timeTarget time (seconds).
rho_valRadial coordinate value to select.
rho_coordName of the rho coordinate ('rho_norm', 'rho_face_norm', etc.).
scaleMultiplicative factor applied after extraction.
Returns
float — the (optionally averaged) scalar value.

◆ _extract_tx_scalar_at_rho_timeseries()

_extract_tx_scalar_at_rho_timeseries ( self,
data_tree,
var_name,
rho_val,
rho_coord = 'rho_norm',
scale = 1.0 )
protected

Extract a profile-at-fixed-rho time-series with time-averaging.

Returns dict {'x': times_list, 'y': values_array}.

◆ _extract_tx_scalar_timeseries()

_extract_tx_scalar_timeseries ( self,
data_tree,
var_name,
source = 'scalars',
scale = 1.0 )
protected

Extract a full time-series scalar from TORAX with time-averaging applied at each point.

Returns dict {'x': times_list, 'y': values_array} suitable for self._results.

Parameters
data_treeTORAX output data tree.
var_nameAttribute name on data_tree.scalars (or .profiles).
source'scalars' or 'profiles'.
scaleMultiplicative factor applied after extraction.

◆ _first_sustained()

_first_sustained ( times,
flags,
target,
start,
dwell )
staticprotected

Index of the first step at/after start where flags == target and that value holds continuously for at least dwell seconds.

Returns None if never sustained.

◆ _flatten_time_dependent()

_flatten_time_dependent ( config)
staticprotected

Recursively flatten time-dependent config values to their initial value only.

A dict whose keys are ALL numeric (int/float) is treated as time-dependent: only the entry with the smallest key is retained. Structural dicts (with any string keys) are recursed into. Tuples of form (times_array, values_array) are flattened to the first entry.

◆ _format_config_literal()

_format_config_literal ( obj,
indent = 0 )
staticprotected

Render a config dict as a runnable Python literal, emitting numpy arrays as np.array([...]) so the saved file re-runs identically.

Used by save_tmtx_config().

◆ _get_time_window()

_get_time_window ( self,
time,
tx_times )
protected

Return the (t_start, t_end) averaging window for a given timepoint.

Respects self._t_ave_toggle, self._t_ave_window, self._t_ave_causal, and self._t_ave_ignore_start. If averaging is disabled for this timepoint the returned window collapses to (time, time).

Parameters
timeThe target timepoint (seconds).
tx_timesSorted numpy array of all available TORAX times.
Returns
(t_start, t_end) — inclusive bounds for the averaging window.

◆ _get_tx_config()

_get_tx_config ( self)
protected

Generate config object for Torax simulation.

Build order

  1. Deep-copy BASE_CONFIG.
  2. Deep-merge the loaded config on top (if load_TORAX_config() was called). Every key in the loaded config overwrites the matching base key; keys only in BASE_CONFIG are kept as-is.
  3. Override geometry (always set to use TokaMaker equilibria). For loop 1+ with injected psi and relax=False, the seed EQDSK is forced at t_initial (psi from initial TORAX relax on seed); if relax=True, loop N relax keeps psi on the TM i=0 surface so TM EQDSK is used.
  4. Override t_initial / t_final / fixed_dt from init params.
  5. Use psi profile from initial TORAX relax (if available) from profile_conditions.
  6. Apply any explicit set_*() overrides (only when the attribute is not None, i.e. the user called the setter after load_TORAX_config).
  7. If relax_kinetics was True for the last relax, override n_e, T_e, T_i with profiles taken from the end of that relax simulation.
  8. If fly(..., steady_state_mode=True) and this is not the first loop, override psi and kinetic profiles with profiles saved from the previous main TORAX run at t_final (see _capture_steady_state_tx_seed).
Returns
Torax config object.

◆ _global_bounds_dict()

_global_bounds_dict ( self)
protected

The configured per-coil hard bounds [A-turns], as set by set_TokaMaker_coil_reg().

Read fresh on each use rather than snapshotted, so it does not matter whether the bounds or the rate limits were configured first. Coils absent from the configured dict are absent here too, leaving them unbounded in TokaMaker. Falls back to +/-45 MA-turns for every coil if bounds were never configured.

◆ _interp_tx_profile_onto_psi()

_interp_tx_profile_onto_psi ( self,
data_tree,
var_name,
time,
profile_type = 'linterp' )
protected

Interpolate a single TORAX profile snapshot onto self._psi_N.

No averaging, just one timeslice. Returns a plain numpy array on self._psi_N.

◆ _log()

_log ( self,
msg )
protected

Write message to log file only.

◆ _log_flattop_summary()

_log_flattop_summary ( self,
flux_consumed = None )
protected

Print a table of key physics parameters evaluated at the end of flattop.

Always emitted to both the terminal and the log file (via _print). Values are taken from the last TORAX timepoint that falls inside the detected flattop window (and a flattop-window average is shown alongside for context). Fusion energy is cumulative, so its end-of-flattop value is the energy gained up to that point. Flux consumed is the last completed loop's TORAX consumed flux.

Parameters
flux_consumedConsumed flux [Wb] from the last completed loop, or None.

◆ _loop0_coarse_tx_main_scope()

_loop0_coarse_tx_main_scope ( self)
protected

Apply loop-0 coarse TORAX grid for main _run_tx; restore after.

◆ _loop0_coarse_tx_relax_scope()

_loop0_coarse_tx_relax_scope ( self,
stage )
protected

Apply loop-0 coarse TORAX grid during initial relax only; restore after.

◆ _loop0_tm_solve_indices()

_loop0_tm_solve_indices ( n_tm,
stride )
staticprotected

TokaMaker timestep indices for coupling loop 0 subsampling: endpoints plus every stride-th.

◆ _manual_ibc_active()

_manual_ibc_active ( self)
protected

True when the internal_manual pedestal IBC should be imposed this loop, i.e.

the L/H timing is known: timing='input' (always), or timing='detect' once the detection loop (loop 1) has run and found an L->H time.

◆ _normalize_coil_bounds_dict()

_normalize_coil_bounds_dict ( self,
coil_bounds )
protected

Normalize a coil-bounds input to a {coil: [lo, hi]} dict (input units preserved).

Accepts either a single [lo, hi] pair — the usual form, broadcast to every coil set, matching tm_inputs['coil_bounds'] — or an explicit {coil_name: [lo, hi]} dict for per-coil limits.

Parameters
coil_boundsA [lo, hi] pair or a {coil_name: [lo, hi]} dict.
Returns
Dict {coil_name: [lo, hi]}.

◆ _normalize_coil_bounds_units()

_normalize_coil_bounds_units ( units)
staticprotected

Validate/normalize a coil-bounds units string to 'A-turns' or 'A/turn'.

Accepts common spellings (case/spacing insensitive, optional 'M' magnitude prefix): 'A-turns', 'Aturns', 'MA-turns', ... map to 'A-turns' (total winding current); 'A/turn', 'A-per-turn', 'MA/turn', ... map to 'A/turn' (per-winding current, TokaMaker's native unit). The 'M' prefix is cosmetic — values are always plain Amps; only the total vs per-turn distinction changes the math.

◆ _normalize_coil_rate_units()

_normalize_coil_rate_units ( units)
staticprotected

Validate/normalize a dI/dt units string to 'A-turns/s' or 'A/turn/s'.

Accepts the same spellings as _normalize_coil_bounds_units plus an optional per-second suffix ('/s', '/sec', 'ps', ...): 'A-turns/s' is the total winding rate; 'A/turn/s' is the per-winding rate, which is multiplied by each coil's turn count and so gives a different A-turns/s budget per coil.

◆ _numpy_to_plain_python()

_numpy_to_plain_python ( obj)
staticprotected

Recursively convert numpy scalars/arrays to plain Python types.

Used before pformat-saving config dicts so the saved .py files are loadable without numpy (no array([...]) references).

◆ _numpy_to_plain_python_keep_arrays()

_numpy_to_plain_python_keep_arrays ( obj)
staticprotected

Like _numpy_to_plain_python but leaves np.ndarray intact (for literal-repr save).

◆ _pop_tx_grid()

_pop_tx_grid ( self)
protected

Restore TORAX grid from _push_tx_grid stack.

Used for reducing grid in loop0.

◆ _print()

_print ( self,
msg )
protected

Write message to both stdout and log file.

◆ _push_coil_bounds()

_push_coil_bounds ( self,
coil_bounds_aturn )
protected

Store the currently active bounds (A-turns) and apply them to TokaMaker (A/turn).

These are the bounds in force for the next solve, which the rate limiter tightens per step. The configured hard limit they are derived from lives in self._coil_bounds_global and is never overwritten here.

◆ _push_tx_grid()

_push_tx_grid ( self)
protected

Save current TORAX grid onto stack for later _pop_tx_grid.

Used for reducing grid in loop0.

◆ _quiet_tm()

_quiet_tm ( self)
protected

Context manager: redirect C/Fortran-level stdout+stderr to /dev/null.

◆ _relax_flat_profile_to_rho_y()

_relax_flat_profile_to_rho_y ( profile_val)
staticprotected

(rho_norm, y) from a profile_conditions value after merge + flatten.

Handles:

  • nested {time: inner} (TORAX time-sliced profiles; flatten keeps one key);
  • (rho, y) static radial tuples;
  • (times, rho, [profiles]) including a single time index.

◆ _res_update()

_res_update ( self,
data_tree )
protected

Populate self._results from TORAX data with time-averaging.

◆ _resolve_right_bc()

_resolve_right_bc ( self,
field,
set_value )
protected

Effective edge (rho=1) BC for an internal_manual pedestal foot.

Returns the value passed to set_ne/set_Te/set_Ti when one was given; otherwise falls back to the loaded TORAX config's profile_conditions.{field}_right_bc (so a raw-dict BC, via load_TORAX_config, still drives the pedestal foot). Returns None if neither source defines it (the IBC then uses a 0 foot, as before).

Parameters
field'T_e', 'T_i', or 'n_e'.
set_valueThe corresponding self._{field}_right_bc (may be None).
Returns
Scalar, {time: value} map, or None.

◆ _run_tm()

_run_tm ( self)
protected

Run the GS solve across n timesteps using TokaMaker.

Returns
Tuple (consumed_flux, consumed_flux_integral).

◆ _run_torax()

_run_torax ( self,
config )
protected

Run TORAX via prepare_simulation + run_loop so we keep the raw list[SimState] (torax.run_simulation() drops the pedestal confinement_mode).

Returns the same (data_tree, history) that run_simulation() would, plus the SimState list.

Parameters
configTORAX config as a dict or a ToraxConfig.
Returns
Tuple (data_tree, state_history, state_list).

◆ _run_tx()

_run_tx ( self)
protected

Run the TORAX transport simulation.

Returns
Tuple (consumed_flux, consumed_flux_integral).

◆ _run_tx_relax()

_run_tx_relax ( self,
* ,
stage,
eqdsk_path,
prescribed_profiles )
protected

Short TORAX relax: initial run on the seed EQDSK, or inter-loop on TM i=0 EQDSK.

Uses flattened user inputs (_apply_tx_set_overrides + _flatten_time_dependent). If prescribed_profiles is None, psi follows EQDSK initial_psi_mode='geometry' and n_e, T_e, T_i stay as already merged from base / loaded config and _apply_tx_set_overrides (user inputs). If a dict is passed, it must supply psi, n_e, T_e, T_i tuples (advanced; loop N relax uses None so kinetics are always user-specified).

Parameters
stage'initial' or 'interloop' (logging / output names only).
eqdsk_pathPath to gEQDSK for geometry_configs at t_initial.
prescribed_profilesNone, or dict with keys psi, n_e, T_e, T_i (3-tuples).

◆ _set_confinement_from_window()

_set_confinement_from_window ( self,
end_fallback = None )
protected

Fill the per-tm-time H-mode flag from the known [lh, hl] window.

Used by both the detection path and timing='input' (where there is no detection state machine, so the flag would otherwise stay all-False and the IBC smoothing would skip every point). No-op if no L->H time is known.

◆ _smooth_ibc_inner_edge()

_smooth_ibc_inner_edge ( self)
protected

Match the imposed pedestal inner-edge value AND gradient to the TORAX-evolved core PER TM-TIME, so the next loop's IBC tracks the evolving profile time-point by time-point and joins the core smoothly (no kink/jog -> p' spike -> TM GS failure).

For each H-mode tm_time: takes a window of the TORAX profile just inside ped_rho (width PED_GRAD_WINDOW), fits a cubic polynomial to smooth it, then evaluates the smoothed curve at ped_rho to obtain the inner-edge value and gradient. The smoothed profile chunk is stored for plotting in IBC_debug.

Stored as {field: {tm_time: (value, slope, rho_chunk, y_chunk_smoothed)}}. L-mode tm_times are skipped. Slope clamped to <= 0.

◆ _test_eqdsk_tx_config()

_test_eqdsk_tx_config ( self,
eqdsk,
* ,
quiet = False )
protected

Return whether TORAX accepts eqdsk as ToraxConfig geometry.

Parameters
quietIf True, do not print or append to the coupling log on failure (used for intermediate-resolution retries in _run_tm). If False, failure is only reported when output_mode is 'debug'.

◆ _tm_prof_input_ped_smooth()

_tm_prof_input_ped_smooth ( self,
ffp_prof,
pp_prof,
p_prof,
transition_psi_N = 0.6,
gauss_sigma = 8,
blend_width = 0.02,
sav_window = 41,
sav_order = 3 )
protected

Edge smoothing with Gaussian filter: smooth p profile and take derivative for pp_prof.

◆ _tm_prof_input_power_flux()

_tm_prof_input_power_flux ( self,
ffp_prof,
pp_prof )
protected

Generic power-flux shape.

◆ _tm_prof_input_raw()

_tm_prof_input_raw ( self,
ffp_prof,
pp_prof )
protected

Raw TORAX profiles passed through unchanged.

◆ _tm_prof_input_sign_flip()

_tm_prof_input_sign_flip ( self,
ffp_prof,
pp_prof )
protected

Sign-flip clipping: clip each profile to its dominant sign.

◆ _tm_update()

_tm_update ( self,
i )
protected

Update internal state and coil current results based on results of GS solver.

Parameters
iTimestep of the solve.

◆ _tx_config_merge()

_tx_config_merge ( base,
override )
staticprotected

Recursively merge override into base TORAX config (in-place).

For every key in override:

  • If both values are dicts, recurse.
  • Otherwise the override value wins. Keys in base that are absent from override are kept as-is.
Parameters
baseDict to merge into (modified in-place).
overrideDict whose keys take precedence.
Returns
base (for convenience).

◆ _tx_update()

_tx_update ( self,
i,
data_tree,
tx_time = None )
protected

Update the simulation state from TORAX results at timestep i.

If sawtooth averaging is enabled, all profile and scalar extractions use time-averaged methods to smooth sawtooth oscillations.

Parameters
iTimestep index (TokaMaker time index; TM comparison fields in plots use this key).
data_treeResult object from Torax.
tx_timeIf not None, use this time (s) for all TORAX extractions instead of self._tm_times[i] (e.g. last TORAX output time after a failed run).

◆ _zz_doxygen_dummy()

_zz_doxygen_dummy ( self)
protected

◆ configure_redirect_to_log()

configure_redirect_to_log ( self)

Step 3/3 of setup to divert noisy outputs to log file.

Captures INFO-level and above.

◆ fly()

fly ( self,
run_name = 'tmp',
convergence_threshold = -1.0,
max_loop = 3,
output_mode = False,
skip_bad_init_eqdsks = False,
initial_relax = True,
relax = False,
relax_kinetics = False,
relax_duration = 1.0,
relax_dt = 0.1,
t_ave_toggle = 'off',
t_ave_window = 0.5,
t_ave_causal = True,
t_ave_ignore_start = 0.25,
loop0 = False,
steady_state_mode = False )

Run TokaMaker_TORAX coupled pulse design loop.

Parameters
convergence_thresholdMax fractional change in consumed flux between loops for convergence.
max_loopHighest counted coupling index to run (inclusive): full-resolution passes use indices 1 … max_loop. The optional cheap pass at index 0 (when loop0=True) is always attempted first and does not count toward this limit. Example: max_loop=3 runs loop 0 (if enabled) then loops 1, 2, and 3 before stopping unless convergence ends earlier.
run_nameName for this run (used in output directory and log file).
output_modeOutput level selector: False (or None), True (alias for 'normal'), 'minimal', 'normal', or 'debug'. String values 'false'/'none'/'off'/'no' map to False. When not False, artifacts go under ./TokaMaker_TORAX_outputs/ (tmp/ for run_name='tmp', else {run_name}_{timestamp}/). Unless run_name='tmp', saved filenames are prefixed {run_name}_{timestamp}_. A log file is always written (into the output directory when one exists, otherwise the current working directory). results.json path is set on the instance (self._fname_out) but is not written automatically; call save_res() to persist it. In-memory self._results is updated after each successful TORAX pass for any non-False mode. End-of-run PNG/MP4 saves are skipped inside Jupyter notebooks.

False / None — No output directory. Log only (TokaMaker_TORAX_log_tmp.log or TokaMaker_TORAX_log_{run_name}_{timestamp}.log in cwd). No plots or config files. TokaMaker gEQDSK files use a temporary directory and are deleted at exit.

'minimal' — Per completed coupling loop: scalars_loop{N}.png, PLH_components_loop{N}.png. At end of run (non-Jupyter): profile_evolution.png, lcfs_evolution.png, movie_loop{N}.mp4 (N = last completed loop index). On TokaMaker GS failure at a timestep: tm_diag_loop{N}_tidx{i}.png. On TORAX failure: scalars_loop{N}_torax_failed.png and, if partial TORAX data exist, profile_loop{N}_torax_failed_tfinal.png. No TORAX config .py files, no per-timestep profile plots, no relax-profile figures, no persisted gEQDSK files (temporary EQDSK dir removed at exit).

'normal' (also output_mode=True) — Per loop: scalars_loop{N}.png, PLH_components_loop{N}.png; tx_config_loop{N}.py; initial / inter-loop relax configs tx_config_relax000_initial.py and tx_config_relax_inter_{N}.py; each successful TokaMaker timestep profile_loop{N}_tidx{i}.png. At end (non-Jupyter): profile_evolution.png and movie_loop{N}.mp4 (no lcfs_evolution.png). Same failure plots as minimal. No tm_diag on successful solves, no relax-profile figures, no tm_summary_loop{N}.png, no persisted gEQDSK files.

'debug' — All normal artifacts plus lcfs_evolution.png at end of run. gEQDSK files {loop:03d}.{i:03d}.eqdsk are kept in the output directory (not deleted). Initial / inter-loop relax: tx_relax_profiles_initial.png, tx_relax_profiles_inter_loop{N}.png. Every TokaMaker timestep (success or fail): tm_diag_loop{N}_tidx{i}.png (successful solves also get profile_loop{N}_tidx{i}.png). After each loop: tm_summary_loop{N}.png. Python logging (TORAX, JAX, etc.) is redirected to the log file; per-loop wall time is printed.

Parameters
skip_bad_init_eqdsksIf True, skip broken initial gEQDSK files instead of raising.
initial_relaxIf True (default), run a short TORAX relax on the seed EQDSK before the first coupling TM-TORAX pass (flattened user inputs; psi from geometry unless an inter-loop relax already set psi). If False, skip and start from EQDSK psi / loaded config. When relax is True, this is forced True so initial relax establishes psi before later coupling iterations.
relaxIf True, run an additional short TORAX relax before each coupling iteration with index ≥1, on TM-solved EQDSK (previous_loop).000.eqdsk (fallback: seed), with user n_e, T_e, T_i from loaded config and set_*() and psi from geometry on that EQDSK— avoiding drift from previous TORAX outputs between loops. Default False (backward compatible). Implies initial_relax=True.
relax_kineticsIf False (default), each relax only evolves current; density and ion/electron heat stay fixed at the profiles present before that relax. If True, relax uses the same evolve_* flags as set_evolve() / loaded config. When True, relaxed n_e, T_e, T_i are injected into main TORAX after set_*() like psi.
relax_durationDuration (s) of each relax simulation. Default 1.0 s.
relax_dtFixed timestep (s) for each initial / inter-loop TORAX relax run (numerics.fixed_dt). Default 0.1 s.
t_ave_toggleTime-averaging mode: 'off' (no averaging), 'flattop' (average only during flat-top), or 'on' (average over the whole pulse).
t_ave_windowAveraging window size in seconds. Default 0.5 s.
t_ave_causalIf True, window is entirely behind the timepoint (backward-looking). If False, window is centred on the timepoint.
t_ave_ignore_startIgnore the first N seconds of the pulse when building the averaging window (avoids numerical transients). Default 0.25 s.
loop0If True, run a first coupling pass at index 0 with reduced cost: coarse TORAX radial grid (face_centers linspace, DEFAULT_LOOP0_TX_FACE_POINTS), the same coarse grid on the optional initial relax, and subsampled TokaMaker times (stride 2). If False (default), skip that pass and start coupling at index 1 at full resolution (initial relax is unchanged and controlled only by initial_relax / relax).
steady_state_modeIf False (default), each coupling loop after the first reuses the time-dependent TokaMaker EQDSK sequence from the previous loop (existing behavior). If True, after each completed loop the next loop seeds TORAX with psi and kinetics from the previous main run at t_final, uses the final TokaMaker EQDSK from the previous loop for all TORAX geometry times (flat equilibrium shape in time), warm-starts TokaMaker at i=0 from the previous loop's final psi grid, and runs inter-loop relax on that final EQDSK when relax is True.

◆ get_final_timepoint_results()

get_final_timepoint_results ( self,
eqdsk_save_dir = None )

Profiles and scalars at the last TokaMaker timepoint of the last completed coupling loop.

Call after fly() when TokaMaker has populated state['equil'] at every timestep index.

Profiles use the usual TokaMaker_TORAX flux-surface dict form {'x', 'y', 'type'} (x = normalized poloidal flux when applicable). TokaMaker p_prime and FF_prime are P' and F F' from get_profiles(npsi=...) on the same grid as stored in state. Kinetic profiles and eta come from the TORAX-updated state at that timestep; current densities j_* are TORAX flux-surface profiles (sources for the GS solve).

Scalars: fusion Q from TORAX (last save or live data tree); q95 and q0 from TokaMaker get_q (l_i likewise from get_stats); V_loop from TORAX v_loop_lcfs; Ip is the TokaMaker equilibrium value.

Parameters
eqdsk_save_dirIf set (non-empty str or path-like), write the final TokaMaker equilibrium gEQDSK with save_eqdsk into this directory (created if needed). If None (default), no file is written.
Returns
dict with time, simulation_loop, tm_time_index, profile keys, nested j current profiles, scalar values, coil_currents, coil_currents_by_region, tokamaker_equilibrium (TokaMaker equilibrium instance at this timestep — same reference as state['equil'][tm_time_index]), and eqdsk_path (absolute path string when saved, else None).

◆ load_pedestal_config()

load_pedestal_config ( self,
pedestal_config )

Deprecated: use set_pedestal(config=...).

Fully replaces the TORAX pedestal section.

Parameters
pedestal_configDictionary in TORAX pedestal config format, or None to clear.

◆ load_TORAX_config()

load_TORAX_config ( self,
config )

Load a TORAX config dict.

TORAX input config documentation: https://torax.readthedocs.io/en/latest/configuration.html The loaded config is deep-merged on top of BASE_CONFIG when the simulation config is built. Any key present in the loaded config will override the corresponding BASE_CONFIG key; keys only in BASE_CONFIG are kept as-is. Geometry is always overwritten (eqdsk-based).

Explicit set_*() calls made AFTER load_TORAX_config() will override both the base and the loaded config.

The TORAX radial grid is normally set with set_TORAX_grid(); as a convenience this method also accepts it inline via the loaded config's geometry section (geometry.n_rho or geometry.face_centers), so a fully raw TORAX dict can drive the grid without a separate set_TORAX_grid() call. An explicit set_TORAX_grid() call (before or after) still wins.

Parameters
configDictionary (TORAX config format).

◆ make_movie()

make_movie ( self,
save_path = None,
** kwargs )

Generate pulse movie from stored psi snapshots.

Parameters
save_pathPath to save MP4 file. If None, does not save.

◆ plot_coil_current_tunnel()

plot_coil_current_tunnel ( self,
save_path = None,
display = True,
** kwargs )

Plot coil currents inside their rate-limited bounds "tunnel" over the pulse.

Parameters
save_pathPath to save figure. If None, does not save.
displayWhether to show the plot.

◆ plot_coils()

plot_coils ( self,
save_path = None,
display = True,
** kwargs )

Plot coil current traces over the pulse.

Parameters
save_pathPath to save figure. If None, does not save.
displayWhether to show the plot.

◆ plot_coupling_convergence()

plot_coupling_convergence ( self,
save_path = None,
display = True,
** kwargs )

Plot the coupling-convergence cost vs loop (the loop-over-loop trend of the flavor-2 aggregate).

Reads _coupling_cost_history, populated once per loop during fly(); does nothing if no loops have completed.

Parameters
save_pathPath to save figure. If None, does not save.
displayWhether to show the plot.

◆ plot_errors()

plot_errors ( self,
save_path = None,
display = True,
** kwargs )

Plot per-timestep TokaMaker-vs-TORAX coupling error metrics (one figure per loop; layout mirrors plot_scalars).

Reads the err_* arrays populated by _compute_errors(); call fly() (or _compute_errors()) first.

Parameters
save_pathPath to save figure. If None, does not save.
displayWhether to show the plot.

◆ plot_lcfs_evolution()

plot_lcfs_evolution ( self,
save_path = None,
display = True,
one_plot = False,
** kwargs )

Plot time evolution of the LCFS for each pulse phase (rampup, flattop, rampdown).

Parameters
save_pathPath prefix to save figures. If None, does not save.
displayWhether to show the plots.
one_plotIf True, combine all pulse phases into one figure.

◆ plot_PLH_components()

plot_PLH_components ( self,
save_path = None,
display = True,
** kwargs )

Plot the components of the PLH model (pedestal height, width, and core gradient) over time.

Parameters
save_pathPath to save figure. If None, does not save.
displayWhether to show the plot.

◆ plot_profile_evolution()

plot_profile_evolution ( self,
save_path = None,
display = True,
one_plot = False,
** kwargs )

Plot profile evolution over time.

Parameters
save_pathPath to save figure. If None, does not save.
displayWhether to show the plot.
one_plotIf True, combine all pulse phases into one figure.

◆ plot_profiles()

plot_profiles ( self,
** kwargs )

Interactive profile viewer (ipywidgets slider in Jupyter, static otherwise).

◆ plot_scalars()

plot_scalars ( self,
save_path = None,
display = True,
** kwargs )

Plot scalar time traces (Ip, Q, Te, ne, power channels, etc.).

Parameters
save_pathPath to save figure. If None, does not save.
displayWhether to show the plot.

◆ save_res()

save_res ( self)

Save simulation results to JSON.

◆ save_state()

save_state ( self,
fname )

Save intermediate simulation state to JSON.

Parameters
fnameFilename to save to.

◆ save_tmtx_config()

save_tmtx_config ( self,
save_path = None )

Write a self-contained reproduction config file: tmtx_config_{run}_{ts}.py (tmtx_config_tmp.py with no timestamp when run_name='tmp', so it is overwritten each run).

The file defines two plain dicts, tmtx_dict and torax_dict, that can be fed straight back into run_tmtx_from_config(tmtx_dict, torax_dict) — or loaded with run_tmtx_from_config(config_file=...) — to reproduce this run.

  • torax_dict is the loop-1 merged TORAX config (BASE_CONFIG deep-merged with the loaded config and every set_*() override, i.e. with all applied defaults), captured in get_tx_config(). Loop-specific geometry and the relax-seeded psi are stripped so it is portable.
  • tmtx_dict is rebuilt from the TokaMaker_TORAX object's state (self.*): Ip, time window, tx_dt, tm_times, pedestal, x_points, evolve, etc. If the object was built by run_tmtx_from_config() the original tmtx_config was stashed (self._tmtx_config) and is used as the base (so seed-eqdsk trajectories and TM mesh inputs survive); the rebuilt values are layered on top. Seeds replay exactly as the original run made them: if this run CREATED its seeds (create_seed_eqdsks=True), the flag stays True and no file paths are embedded, so replay regenerates them from the trajectories. If the seeds were PASSED in (loaded), create_seed_eqdsks stays False and the absolute seed file paths used this run are embedded for reuse.
Parameters
save_pathExplicit output path. Default: tmtx_config_{run}_{ts}.py (tmtx_config_tmp.py, no timestamp, for run_name='tmp') in self._out_dir if a run output dir exists, else the cwd.
Returns
Path to the written file.

◆ set_coil_rate_limits()

set_coil_rate_limits ( self,
dIdt = None,
dIdt_units = 'A-turns/s',
V = None,
R = None,
dt_floor = 0.5 )

Constrain how fast each coil current may change between TokaMaker solves.

Before each GS solve the coil's hard bounds are tightened to a window around the last successfully solved current:

bound = I_prev_good ± (dIdt * max(dt, dt_floor)),
dt = t[i] - t[last good solve]

then clipped to that coil's global bounds. This caps the realized dI/dt of every coil so the pulse stays within power-supply / engineering limits.

The clip is NOT a separate limit and cannot be set here: each coil is clipped to its own entry in the coil_bounds configured by set_TokaMaker_coil_reg() / tm_inputs['coil_bounds'], so the hard limit is defined exactly once and per-coil bounds are preserved.

dt_floor avoids an unenforceably narrow bound box when two solves are very close in time: at tiny dt the box [I_ref ± dIdt*dt] becomes so small that TokaMaker's bounded solve can overshoot it, producing a spurious large realized dI/dt. Flooring dt keeps the box wide enough to enforce; the price is that across a sub-floor gap the realized rate may exceed the nominal limit by up to dt_floor/dt. Set dt_floor=0 to disable.

Rates are stored internally in total A-turns/s, matching the rest of the TokaMaker_TORAX coil API. For each coil supply EITHER a dI/dt limit OR a voltage limit (with a resistance) — never both for the same coil.

  • dI/dt path: dIdt, in the unit given by dIdt_units. Set dIdt_units='A/turn/s' to give the per-winding rate instead; it is multiplied by each coil's turn count (dIdt[A-turns/s] = dIdt[A/turn/s] * n_turns), so even a single scalar then yields a different A-turns/s budget for every coil, which is expected.
  • Voltage path: V [Volts] and R [Ohms] for that coil. The per-winding current rate is V/R [A/turn/s]; multiplied by n_turns this gives the A-turns/s rate: dIdt = (V / R) * n_turns. dIdt_units does not apply here — this path is always per-winding by construction.

Each of dIdt, V, R may be a single scalar (applied to all coils) or a {coil_name: value} dict (per coil). Coils not given any limit keep the global bounds (unconstrained rate). The virtual VSC coil is not rate limited.

Parameters
dIdtMax |dI/dt| per coil in dIdt_units; scalar or {coil: value}.
dIdt_unitsUnit of dIdt: 'A-turns/s' (default, total winding rate) or 'A/turn/s' (per-winding rate). Does not affect the V/R path.
VMax coil voltage [V]; scalar or {coil: value}. Requires matching R.
RCoil resistance [Ohms]; scalar or {coil: value}. Used with V.
dt_floorMinimum dt [s] used in the budget so close-spaced solves get an enforceable bound box. Default 0.5 s; set 0 to disable.

◆ set_diverted_shape_targets()

set_diverted_shape_targets ( self,
diverted_times = None,
x_point_targets = None,
x_point_weight = 1000.0,
strike_point_targets = None,
trim_lcfs = True,
trim_lcfs_perc_limit = 0.80,
secondary_x_point_targets = None,
shape_target = None,
secondary_x_point_weight = None,
strike_point_weight = None )

Configure the diverted window: X-point targets, strike points, and the optional LCFS shape target — plus the weights of the constraints that only exist while diverted.

The always-on weights (LCFS shape isoflux and the outboard-midplane psi value) are set separately by set_TokaMaker_constraint_weights().

Parameters
diverted_timesTuple (t_start, t_end) defining the diverted plasma window.
x_point_targetsPRIMARY (active) X-point target locations, shape (n_xpoints, 2) with [R, Z] pairs. These are the nulls that sit on the plasma boundary and define the topology (1 = single null, 2 = double null); only these drive the trim_lcfs geometry below.
x_point_weightWeight for the PRIMARY saddle-point (X-point) constraints. Default 1000.0.
strike_point_targetsStrike point locations, shape (n_points, 2) with [R, Z] pairs, or None to disable.
trim_lcfsWhen True (default) and X-points are active, LCFS isoflux targets near the X-point(s) are removed. When False, all defined isoflux (LCFS) points are used together with the defined X-point(s).
trim_lcfs_perc_limitLCFS points above this fraction of max(|Z|) are trimmed near the X-point(s) when trim_lcfs is True.
secondary_x_point_targetsOptional SECONDARY X-point locations, shape (n_points, 2) with [R, Z] pairs. These get saddle constraints like the primaries, but are deliberately EXCLUDED from the trim_lcfs calculation: they are nulls out in the divertor corners, far off the plasma boundary, so they must not change which LCFS isoflux points get trimmed nor which single/double-null branch is taken.
shape_targetOptional LCFS shape target, shape (n_points, 2) with [R, Z] pairs. When given, it OVERRIDES the seed-gEQDSK LCFS isoflux (shape) targets for timepoints inside the diverted window; timepoints outside the window are unaffected and still use the seed shape. The isoflux weights are unchanged (the same isoflux_weight as the seed targets), and X-point trimming plus any strike points still apply on top of the overridden shape. None (default) keeps the back-compatible behavior of pulling the shape from the seed gEQDSKs everywhere.
secondary_x_point_weightWeight for the SECONDARY saddle-point constraints. None (default) reuses x_point_weight, matching the previous single-weight behavior; set it to weight the far-corner nulls independently of the primaries.
strike_point_weightWeight for the strike-point isoflux constraints. None (default) reuses the isoflux_weight applied to the LCFS shape targets, matching the previous behavior (strike points are appended to the shape targets); set it to pull on the strike points independently of the shape.

◆ set_evolve()

set_evolve ( self,
density = True,
Ti = True,
Te = True,
current = True )

Set variables as either prescribed (False) or evolved (True) for TORAX.

TORAX input config documentation: https://torax.readthedocs.io/en/latest/configuration.html#numerics

Parameters
densityEvolve density.
TiEvolve ion temperature.
TeEvolve electron temperature.
currentEvolve current.

◆ set_fueling()

set_fueling ( self,
gas_puff_S_total = None,
gas_puff_decay_length = None,
pellet_deposition_location = None,
pellet_width = None,
pellet_S_total = None,
generic_particle_location = None,
generic_particle_width = None,
generic_particle_S_total = None )

Set gas puff and pellet fueling particle sources for TORAX.

TORAX input config documentation: https://torax.readthedocs.io/en/latest/configuration.html#sources

Parameters
gas_puff_S_totalGas puff particle source (particles/s).
gas_puff_decay_lengthGas puff decay length from edge (normalized rho).
pellet_deposition_locationPellet deposition location (normalized rho).
pellet_widthPellet deposition width (normalized rho).
pellet_S_totalPellet particle source (particles/s).
generic_particle_locationGeneric particle source location (normalized rho).
generic_particle_widthGeneric particle source width (normalized rho).
generic_particle_widthGeneric particle source amount (particles/s).

◆ set_heating()

set_heating ( self,
generic_heat = None,
generic_heat_loc = None,
generic_heat_width = 0.25,
generic_heat_absorption_fraction = 1.0,
generic_heat_electron_heat_fraction = 0.4,
nbi_current = False,
ecrh = None,
ecrh_loc = None,
ecrh_width = 0.1,
ohmic = None,
fusion = True,
ei_exchange = True )

Set TORAX heating and source toggles.

TORAX input config documentation: https://torax.readthedocs.io/en/latest/configuration.html#sources

Parameters
generic_heatGeneric heating ({time: power_W}).
generic_heat_locGeneric heating deposition location (normalized rho).
generic_heat_widthGeneric heating deposition width (normalized rho).
generic_heat_absorption_fractionFraction of generic heating that is absorbed (default here 1.0, TORAX default is 0.0).
generic_heat_electron_heat_fractionFraction of generic heating that is converted to electron heat (default 0.4, from arc v3a config, TORAX default is 0.6).
nbi_currentEnable NBI current drive estimate from generic heating.
ecrhECRH heating ({time: power_W}).
ecrh_locECRH deposition location (normalized rho).
ecrh_widthECRH deposition width (normalized rho).
ohmicOptional explicit ohmic power ({time: power_W}).
fusionEnable fusion alpha heating source.
ei_exchangeEnable electron-ion energy exchange source.

◆ set_Ip()

set_Ip ( self,
Ip )

Set plasma current (Amps), used for both codes and not evolved by either.

Parameters
ipPlasma current.

◆ set_ne()

set_ne ( self,
n_e,
right_bc = None )

Set electron density profiles and optional right boundary condition.

TORAX input config documentation: https://torax.readthedocs.io/en/latest/configuration.html#profile-conditions

Parameters
n_eElectron density (m^-3).
right_bcRight boundary value at rho=1 (m^-3), scalar or time-varying map.

◆ set_pedestal()

set_pedestal ( self,
config_mode = 'off',
config = None,
ped_height_Te = None,
ped_height_Ti = None,
ped_height_ne = None,
ped_width = 0.15,
transition_time = 0.5,
timing = 'detect',
lh_time = None,
hl_time = None,
formation_model = 'delabie_scaling',
adaptive_T_source_prefactor = None,
adaptive_n_source_prefactor = None,
core_height_Te = None,
core_height_Ti = None,
core_height_ne = None,
core_exp_a = 2.0,
core_exp_b = 2.0,
set_pedestal = None,
T_i_ped = None,
T_e_ped = None,
n_e_ped = None,
ped_top = 0.90 )

Configure the TORAX pedestal model.

TORAX input config documentation: https://torax.readthedocs.io/en/latest/configuration.html#pedestal

Three modes via config_mode:

  • 'off' : no pedestal (default).
  • 'ADAPTIVE_SOURCE' : TORAX set_T_ped_n_ped pedestal in ADAPTIVE_SOURCE mode. ped_height_* are the H-mode pedestal-top targets and use_formation_model_with_adaptive_source is enabled, so TORAX's L/H state machine owns the timing: the pedestal appears when P_SOL > P_LH and is removed when P_SOL < 0.8*P_LH, ramped over transition_time. Passing the legacy set_pedestal toggle instead prescribes the on/off schedule by hand and disables the formation model.
  • 'ADAPTIVE_TRANSPORT' : same pedestal model in ADAPTIVE_TRANSPORT mode.
  • 'internal_manual' : pedestal imposed by us as a TORAX internal boundary condition (IBC), not a TORAX pedestal model. The pedestal top sits at rho = 1 - ped_width and an mtanh shape is imposed out to rho=1, ramped over transition_time across each L<->H edge. Edge (rho=1) values come from set_ne/set_Te/set_Ti. If a core_height_* is given, the IBC additionally spans the CORE (rho 0->ped_rho) during the L->H transition only, ramping the TORAX-evolved L-mode core into a smooth H-mode-like core shape, then retreating to the pedestal band.
Parameters
config_mode'off', 'ADAPTIVE_SOURCE', 'ADAPTIVE_TRANSPORT', or 'internal_manual'.
configOptional full pedestal-section dict (tx_adaptive modes only); overrides defaults.
ped_height_TeElectron-temperature pedestal-top value (keV); all modes.
ped_height_TiIon-temperature pedestal-top value (keV); all modes (defaults to Te).
ped_height_neElectron-density pedestal-top value (m^-3); all modes.
ped_widthPedestal width in rho_norm; inner edge is at 1 - ped_width (internal_manual; the tx_adaptive modes use ped_top instead).
transition_timeRamp duration (s) over which the pedestal rises from L-mode (TORAX transition_time_width in the tx_adaptive modes).
timing'detect' (find L/H times from a loop-1 ADAPTIVE_SOURCE run) or 'input'.
lh_timeL->H transition time (s); required when timing='input'.
hl_timeH->L back-transition time (s); None means the pedestal stays on.
formation_modelL/H formation-model name driving the transitions in ADAPTIVE_SOURCE mode and the internal_manual 'detect' loop (e.g. 'delabie_scaling', 'martin_scaling').
adaptive_T_source_prefactorStiffness of the internal_manual T_e/T_i IBC (TORAX numerics.adaptive_T_source_prefactor). The IBC is a soft penalty, not a hard BC: higher = the evolved T tracks the imposed pedestal more exactly; lower = TORAX transport smooths the imposed shape more. None = TORAX default (2e10).
adaptive_n_source_prefactorSame for the n_e IBC (numerics.adaptive_n_source_prefactor; TORAX default 2e8). None = TORAX default.
core_height_TeOn-axis (rho=0) H-mode T_e target (keV) for the full-domain L->H transition IBC; None disables the full-domain ramp for T_e. Loop 1 uses this value; loops 2+ use the relaxed evolved core.
core_height_TiOn-axis H-mode T_i target (keV); None disables it for T_i.
core_height_neOn-axis H-mode n_e target (m^-3); None disables it for n_e.
core_exp_a/core_exp_bCore-shape exponents for the transition core profile f = ped + (core-ped)*(1-(rho/ped_rho)^a)^b. a>=2,b>=2 (default 2,2) give a flat core and a flat hand-off into the pedestal top.
set_pedestalLegacy tx_adaptive toggle (True=set_T_ped_n_ped, False=no_pedestal).
T_i_pedLegacy ion-temperature pedestal (tx_adaptive).
T_e_pedLegacy electron-temperature pedestal (tx_adaptive).
n_e_pedLegacy electron-density pedestal (tx_adaptive).
ped_topLegacy pedestal-top location rho_norm_ped_top (tx_adaptive).

◆ set_plasma_composition()

set_plasma_composition ( self,
Zeff = None,
main_ion = None,
impurity = None )

Set plasma effective charge and composition.

TORAX input config documentation: https://torax.readthedocs.io/en/latest/configuration.html#profile-conditions

Parameters
ZeffEffective charge target.
main_ionMain ion species dict, e.g. {'D': 0.5, 'T': 0.5}.
impurityImpurity species string, e.g. 'Ne', 'Ar', 'W'.

◆ set_Te()

set_Te ( self,
T_e,
right_bc = None )

Set electron temperature profiles and optional right boundary condition.

TORAX input config documentation: https://torax.readthedocs.io/en/latest/configuration.html#profile-conditions

Parameters
T_eElectron temperature (keV).
right_bcRight boundary value at rho=1 (keV), scalar or time-varying map.

◆ set_Ti()

set_Ti ( self,
T_i,
right_bc = None )

Set ion temperature profiles and optional right boundary condition.

TORAX input config documentation: https://torax.readthedocs.io/en/latest/configuration.html#profile-conditions

Parameters
T_iIon temperature (keV).
right_bcRight boundary value at rho=1 (keV), scalar or time-varying map.

◆ set_TokaMaker_coil_reg()

set_TokaMaker_coil_reg ( self,
coil_bounds = None,
coil_bounds_units = 'A-turns',
updownsym = False,
default_weight = 1.0E-1,
disable_coils = None,
disable_weight = 1.0E4,
symmetry_weight = 1.0E3,
disable_virtual_vsc = True,
vsc_weight = 1.0E4 )

Set coil regularization using the dict-based TokaMaker reg_terms API.

Coil bounds are the one definition of the hard current limit: the same bounds are used for seed-eqdsk generation, the coupled GS solves, and as the per-coil clip for set_coil_rate_limits(). By default they are given in total Amp-turns (A-turns) — the public TokaMaker_TORAX unit for everything coil-current related. Set coil_bounds_units='A/turn' to instead supply the per-winding current TokaMaker uses natively; such inputs are multiplied by the mesh turn count and stored internally in A-turns (I[A-turns] = I[A/turn] * n_turns), so all downstream state, plots, and rate limits stay in A-turns. Whatever the input unit, the bound pushed to TokaMaker is A/turn.

From a config, these are set via the coil_* keys of tm_inputs rather than by calling this method directly (see run_tmtx_from_config).

During the pulse, coil current targets are set automatically: the initial equilibrium currents seed i=0, and each subsequent timestep uses the previous timestep's solved currents as loose targets.

Parameters
coil_boundsHard current bounds in the unit given by coil_bounds_units: either a single [min, max] pair applied to every coil (the usual form) or a {coil_name: [min, max]} dict for per-coil limits. Default ±45 MA-turns for every coil.
coil_bounds_unitsUnit of coil_bounds: 'A-turns' (default, total winding current) or 'A/turn' (per-winding current, TokaMaker's native unit).
updownsymEnforce up-down symmetry for coil pairs (U/L naming convention).
default_weightRegularization weight for normal coils (default 0.1).
disable_coilsList of coil name prefixes to disable (e.g. ['DV1', 'DV2']).
disable_weightRegularization weight for disabled coils (default 1e4).
symmetry_weightRegularization weight for symmetry constraints (default 1e3).
disable_virtual_vscDisable the virtual VSC coil (default True).
vsc_weightRegularization weight for disabled VSC (default 1e4).

◆ set_TokaMaker_constraint_weights()

set_TokaMaker_constraint_weights ( self,
isoflux_weight = LCFS_WEIGHT,
psi_lcfs_weight = PSI_LCFS_WEIGHT )

Set the GS constraint weights applied at EVERY timepoint of the coupled solve.

These two constraints exist for both limited and diverted plasmas, so they are configured here rather than on set_diverted_shape_targets(), which owns the weights of the diverted-only constraints (primary/secondary X-points and strike points).

From a config, set these via the tm_inputs keys of the same name rather than calling this method directly (see run_tmtx_from_config).

Parameters
isoflux_weightWeight on the LCFS shape (isoflux) targets — the seed-gEQDSK boundary, or the set_diverted_shape_targets() shape_target override while diverted. Also the fallback weight for strike points. Default 100.0.
psi_lcfs_weightWeight on the LCFS psi-value constraint, applied at the single outboard-midplane point using the TORAX psi_lcfs. Default 1000.0.

◆ set_TORAX_grid()

set_TORAX_grid ( self,
grid_type,
grid )

Set TORAX grid type and grid points.

TORAX grid documentation: https://torax.readthedocs.io/en/latest/configuration.html#geometry

Parameters
grid_typeGrid type ('n_rho' or 'face_centers').
gridGrid points (integer or np.array).

◆ set_transport_coefs()

set_transport_coefs ( self,
chi_min = None,
chi_max = None,
De_min = None,
De_max = None,
Ve_min = None,
Ve_max = None )

Set transport coefficient bounds for TORAX.

TORAX input config documentation: https://torax.readthedocs.io/en/latest/configuration.html#transport

Parameters
chi_minMinimum ion thermal diffusivity (m^2/s).
chi_maxMaximum ion thermal diffusivity (m^2/s).
De_minMinimum electron diffusion coefficient (m^2/s).
De_maxMaximum electron diffusion coefficient (m^2/s).
Ve_minMinimum electron thermal velocity (m/s).
Ve_maxMaximum electron thermal velocity (m/s).

◆ set_x_points()

set_x_points ( self,
* args,
** kwargs )

Deprecated: use set_diverted_shape_targets() instead.

This name is retained only to emit a clear error; it no longer configures anything. set_diverted_shape_targets() is a drop-in superset (same X-point, strike-point, and trim arguments) plus the new shape_target override.

◆ summary()

summary ( self,
** kwargs )

Print/display a physics summary of the simulation.

Member Data Documentation

◆ _chi_max

_chi_max = None
protected

◆ _chi_min

_chi_min = None
protected

◆ _cocos

int _cocos = 2
protected

◆ _coil_bounds

_coil_bounds = copy.deepcopy(coil_bounds_aturn)
protected

◆ _coil_bounds_global

_coil_bounds_global = copy.deepcopy(coil_bounds)
protected

◆ _coil_bounds_history

dict _coil_bounds_history = {}
protected

◆ _coil_dIdt

_coil_dIdt = coil_dIdt
protected

◆ _coil_rate_dt_floor

_coil_rate_dt_floor = max(0.0, float(dt_floor))
protected

◆ _coil_rate_limit_config

dict _coil_rate_limit_config
protected
Initial value:
= {
'dIdt': dIdt, 'dIdt_units': dIdt_units, 'V': V, 'R': R,
'dt_floor': self._coil_rate_dt_floor,
}

◆ _coil_reg_config

dict _coil_reg_config
protected
Initial value:
= {
'coil_bounds': coil_bounds,
'updownsym': updownsym, 'default_weight': default_weight,
'disable_coils': disable_coils, 'disable_weight': disable_weight,
'symmetry_weight': symmetry_weight,
'disable_virtual_vsc': disable_virtual_vsc, 'vsc_weight': vsc_weight,
}

◆ _core_exp_a

float _core_exp_a = 2.0
protected

◆ _core_exp_b

float _core_exp_b = 2.0
protected

◆ _core_height_ne

_core_height_ne = None
protected

◆ _core_height_Te

_core_height_Te = None
protected

◆ _core_height_Ti

_core_height_Ti = None
protected

◆ _coupling_cost_history

list _coupling_cost_history = []
protected

◆ _current_loop

_current_loop = 0
protected

◆ _data_tree

_data_tree = data_tree
protected

◆ _De_max

_De_max = None
protected

◆ _De_min

_De_min = None
protected

◆ _debug_mode

bool _debug_mode = False
protected

◆ _diagnostics

bool _diagnostics = False
protected

◆ _diverted_flags

dict _diverted_flags = {}
protected

◆ _diverted_lcfs_shape

_diverted_lcfs_shape = None
protected

◆ _diverted_times

_diverted_times = None
protected

◆ _ecrh_heating

_ecrh_heating = None
protected

◆ _ecrh_loc

_ecrh_loc = None
protected

◆ _ecrh_width

_ecrh_width = None
protected

◆ _enable_ei_exchange

bool _enable_ei_exchange = True
protected

◆ _enable_fusion

bool _enable_fusion = True
protected

◆ _eqdsk_dir

_eqdsk_dir = None
protected

◆ _eqdsk_dir_is_temp

bool _eqdsk_dir_is_temp = False
protected

◆ _eqdsk_skip

list _eqdsk_skip = []
protected

◆ _eqdsk_topology

dict _eqdsk_topology = {}
protected

◆ _eqtimes

_eqtimes = eqtimes
protected

◆ _error_history

list _error_history = []
protected

◆ _evolve_current

_evolve_current = None
protected

◆ _evolve_density

_evolve_density = None
protected

◆ _evolve_Te

_evolve_Te = None
protected

◆ _evolve_Ti

_evolve_Ti = None
protected

◆ _flattop

_flattop
protected

◆ _fly_loop0

_fly_loop0 = bool(loop0)
protected

◆ _fname_out

_fname_out
protected

◆ _generic_heat

_generic_heat = None
protected

◆ _generic_heat_absorption_fraction

_generic_heat_absorption_fraction = None
protected

◆ _generic_heat_electron_heat_fraction

_generic_heat_electron_heat_fraction = None
protected

◆ _generic_heat_loc

_generic_heat_loc = None
protected

◆ _generic_heat_width

_generic_heat_width = None
protected

◆ _generic_particle_location

_generic_particle_location = None
protected

◆ _generic_particle_s_total

_generic_particle_s_total = None
protected

◆ _generic_particle_width

_generic_particle_width = None
protected

◆ _gp_dl

_gp_dl = None
protected

◆ _gp_s

_gp_s = None
protected

◆ _hl_time

_hl_time = None
protected

◆ _impurity

_impurity = None
protected

◆ _init_files

_init_files = g_eqdsk_arr
protected

◆ _Ip

_Ip = None
protected

◆ _Ip_seed

dict _Ip_seed = self._state['Ip'].copy()
protected

◆ _isoflux_weight

_isoflux_weight = LCFS_WEIGHT
protected

◆ _last_good_coil_currents

_last_good_coil_currents = None
protected

◆ _last_good_t

list _last_good_t = None
protected

◆ _last_surface_factor

_last_surface_factor = last_surface_factor
protected

◆ _lh_time

_lh_time = None
protected

◆ _loaded_config

_loaded_config = None
protected

◆ _log_file

_log_file = None
protected

◆ _logging_configured

bool _logging_configured = False
protected

◆ _loop0_coarse_tx

_loop0_coarse_tx = self._fly_loop0
protected

◆ _loop0_relax_coarse_tx

_loop0_relax_coarse_tx = self._fly_loop0
protected

◆ _loop0_tm_stride

int _loop0_tm_stride = 2 if self._fly_loop0 else 1
protected

◆ _loop0_tx_face_points

_loop0_tx_face_points = int(DEFAULT_LOOP0_TX_FACE_POINTS)
protected

◆ _main_ion

_main_ion = None
protected

◆ _n_e

_n_e = None
protected

◆ _n_e_init

_n_e_init = None
protected

◆ _n_e_ped

_n_e_ped = None
protected

◆ _nbar

_nbar = None
protected

◆ _nbi_heating

_nbi_heating = None
protected

◆ _nbi_loc

_nbi_loc = None
protected

◆ _ne_right_bc

_ne_right_bc = None
protected

◆ _normalize_to_nbar

_normalize_to_nbar = None
protected

◆ _ohmic_power

_ohmic_power = None
protected

◆ _out_dir

_out_dir = None
protected

◆ _output_file_tag

str _output_file_tag = None
protected

◆ _output_mode

bool _output_mode = False
protected

◆ _pax_seed

dict _pax_seed = self._state['pax'].copy()
protected

◆ _ped_core_relaxed

dict _ped_core_relaxed = {}
protected

◆ _ped_formation_model

bool _ped_formation_model = False
protected

◆ _ped_formation_model_name

str _ped_formation_model_name = 'delabie_scaling'
protected

◆ _ped_height_ne

_ped_height_ne = None
protected

◆ _ped_height_Te

_ped_height_Te = None
protected

◆ _ped_height_Ti

_ped_height_Ti = None
protected

◆ _ped_ibc_snapshot

dict _ped_ibc_snapshot = None
protected

◆ _ped_lmode_profile

dict _ped_lmode_profile = {}
protected

◆ _ped_mode

str _ped_mode = 'off'
protected

◆ _ped_n_source_prefactor

_ped_n_source_prefactor = None
protected

◆ _ped_smoothed

dict _ped_smoothed = {}
protected

◆ _ped_T_source_prefactor

_ped_T_source_prefactor = None
protected

◆ _ped_timing

str _ped_timing = 'detect'
protected

◆ _ped_top

_ped_top = None
protected

◆ _ped_transition_time

float _ped_transition_time = 0.5
protected

◆ _ped_width

float _ped_width = 0.15
protected

◆ _pedestal_config

_pedestal_config = None
protected

◆ _pellet_deposition_location

_pellet_deposition_location = None
protected

◆ _pellet_s_total

_pellet_s_total = None
protected

◆ _pellet_width

_pellet_width = None
protected

◆ _psi_axis_seed

dict _psi_axis_seed = self._state['psi_axis_tm'].copy()
protected

◆ _psi_init

tuple _psi_init = None
protected

◆ _psi_init_seed

tuple _psi_init_seed = None
protected

◆ _psi_lcfs_seed

dict _psi_lcfs_seed = self._state['psi_lcfs_tm'].copy()
protected

◆ _psi_lcfs_weight

_psi_lcfs_weight = PSI_LCFS_WEIGHT
protected

◆ _psi_N

_psi_N = np.linspace(0.0, 1.0, N_PSI)
protected

◆ _psi_warm_start

dict _psi_warm_start = {}
protected

◆ _rate_limit_active

_rate_limit_active = bool(coil_dIdt)
protected

◆ _rate_ref_for

dict _rate_ref_for = {}
protected

◆ _relax

_relax = bool(relax)
protected

◆ _relax_dt

_relax_dt = _relax_dt
protected

◆ _relax_duration

_relax_duration = float(relax_duration)
protected

◆ _relax_kinetics

_relax_kinetics = bool(relax_kinetics)
protected

◆ _relax_mainrun_profile_history

list _relax_mainrun_profile_history = []
protected

◆ _relax_profiles_snapshot

_relax_profiles_snapshot = None
protected

◆ _results

_results = {}
protected

◆ _run_name

_run_name = run_name
protected

◆ _run_timestamp

str _run_timestamp = None
protected

◆ _save_outputs

bool _save_outputs = False
protected

◆ _secondary_x_point_targets

tuple _secondary_x_point_targets = None
protected

◆ _secondary_x_point_weight

tuple _secondary_x_point_weight = None
protected

◆ _set_pedestal

bool _set_pedestal = None
protected

◆ _skip_bad_init_eqdsks

_skip_bad_init_eqdsks
protected

◆ _state

_state = {}
protected

◆ _steady_state_mode

_steady_state_mode = False
protected

◆ _steady_state_tm_psi_seed

_steady_state_tm_psi_seed = None
protected

◆ _steady_state_tx_seed

_steady_state_tx_seed = None
protected

◆ _strike_point_targets

_strike_point_targets = None
protected

◆ _strike_point_weight

tuple _strike_point_weight = None
protected

◆ _t_ave_causal

_t_ave_causal
protected

◆ _t_ave_ignore_start

_t_ave_ignore_start = t_ave_ignore_start
protected

◆ _t_ave_toggle

str _t_ave_toggle = 'off':
protected

◆ _t_ave_window

_t_ave_window = t_ave_window
protected

◆ _T_e

_T_e = None
protected

◆ _T_e_init

_T_e_init = None
protected

◆ _T_e_ped

_T_e_ped = None
protected

◆ _t_final

_t_final = t_final
protected

◆ _T_i

_T_i = None
protected

◆ _T_i_init

_T_i_init = None
protected

◆ _T_i_ped

_T_i_ped = None
protected

◆ _t_init

_t_init = t_init
protected

◆ _Te_right_bc

_Te_right_bc = None
protected

◆ _Ti_right_bc

_Ti_right_bc = None
protected

◆ _tm

_tm = tokamaker_obj
protected

◆ _tm_psi_on_nodes

dict _tm_psi_on_nodes = {}
protected

◆ _tm_times

_tm_times = sorted(eqtimes)
protected

◆ _torax_run_count

int _torax_run_count = 0
protected

◆ _trim_lcfs

bool _trim_lcfs = True
protected

◆ _trim_lcfs_perc_limit

_trim_lcfs_perc_limit = trim_lcfs_perc_limit
protected

◆ _truncate_eq

_truncate_eq = truncate_eq
protected

◆ _tx_config_snapshot

_tx_config_snapshot = None
protected

◆ _tx_dt

_tx_dt = tx_dt
protected

◆ _tx_grid

list _tx_grid = None
protected

◆ _tx_grid_stash

list _tx_grid_stash = []
protected

◆ _tx_grid_type

_tx_grid_type = None
protected

◆ _use_nbi_current

bool _use_nbi_current = False
protected

◆ _Ve_max

_Ve_max = None
protected

◆ _Ve_min

_Ve_min = None
protected

◆ _x_point_targets

_x_point_targets = None
protected

◆ _x_point_weight

float _x_point_weight = 1000.0
protected

◆ _Zeff

_Zeff = None
protected

◆ lcfs

lcfs = lcfs

◆ results

results = None

Access simulation results dict.

◆ state

state = None

Access simulation state dict.


The documentation for this class was generated from the following file: