![]() |
The Open FUSION Toolkit 26.9
An open-source framework for fusion and plasma science and engineering
|
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). | |
| __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.
| t_init | Start time (s). |
| t_final | End time (s). |
| eqtimes | Time points of each gEQDSK file. |
| g_eqdsk_arr | Filenames of each gEQDSK file. |
| tokamaker_obj | Preconfigured TokaMaker object. |
| tx_dt | Time step (s) of TORAX simulation. |
| tm_times | Time points where TokaMaker solves equilibrium. |
| last_surface_factor | Last surface factor for Torax. |
| truncate_eq | Whether 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()).
|
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).
|
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.
| i | Timestep index. |
| t | Current solve time [s]. |
|
protected |
Internal: build and apply reg_terms from stored config plus per-timestep targets.
| targets | Dict of {coil_name: current [A/turn]} to use as soft targets, or None for zeros. |
|
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.
| myconfig | Config dict (modified in place). |
|
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.
|
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.
|
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>
| i | Time index |
|
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.
| state_list | list[SimState] from _run_torax. |
|
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).
|
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.
|
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).
|
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).
|
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.
|
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').
|
protected |
True on the first TokaMaker_TORAX loop (TORAX uses the seed gEQDSK map).
|
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.
| arg | None, a scalar, or a {coil_name: value} dict. |
| name | Human-readable setting name for error messages. |
|
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.
| data_tree | TORAX output data tree. |
| var_name | Name of variable (e.g., 'T_i', 'j_ohmic', 'FFprime'). |
| time | Target time value. |
| load_into_state | 'state' → return dict; else return plain array. |
| normalize | If True, normalize profile by the core value. |
| profile_type | 'linterp' or 'jphi-linterp'. |
|
protected |
Extract a scalar value from TORAX with optional time-averaging.
| data_tree | TORAX output data tree. |
| var_name | Attribute name on data_tree.scalars (or .profiles). |
| time | Target time (seconds). |
| source | 'scalars' or 'profiles' — which subtree to read from. |
| scale | Multiplicative factor applied after extraction. |
|
protected |
Extract a profile value at a specific rho location as a scalar, with time-averaging.
| data_tree | TORAX output data tree. |
| var_name | Attribute name on data_tree.profiles. |
| time | Target time (seconds). |
| rho_val | Radial coordinate value to select. |
| rho_coord | Name of the rho coordinate ('rho_norm', 'rho_face_norm', etc.). |
| scale | Multiplicative factor applied after extraction. |
|
protected |
Extract a profile-at-fixed-rho time-series with time-averaging.
Returns dict {'x': times_list, 'y': values_array}.
|
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.
| data_tree | TORAX output data tree. |
| var_name | Attribute name on data_tree.scalars (or .profiles). |
| source | 'scalars' or 'profiles'. |
| scale | Multiplicative factor applied after extraction. |
|
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.
|
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.
|
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().
|
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).
| time | The target timepoint (seconds). |
| tx_times | Sorted numpy array of all available TORAX times. |
|
protected |
Generate config object for Torax simulation.
|
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.
|
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.
|
protected |
Write message to log file only.
|
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.
| flux_consumed | Consumed flux [Wb] from the last completed loop, or None. |
|
protected |
Apply loop-0 coarse TORAX grid for main _run_tx; restore after.
|
protected |
Apply loop-0 coarse TORAX grid during initial relax only; restore after.
|
staticprotected |
TokaMaker timestep indices for coupling loop 0 subsampling: endpoints plus every stride-th.
|
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.
|
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.
| coil_bounds | A [lo, hi] pair or a {coil_name: [lo, hi]} dict. |
|
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.
|
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.
|
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).
|
staticprotected |
Like _numpy_to_plain_python but leaves np.ndarray intact (for literal-repr save).
|
protected |
Restore TORAX grid from _push_tx_grid stack.
Used for reducing grid in loop0.
|
protected |
Write message to both stdout and log file.
|
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.
|
protected |
Save current TORAX grid onto stack for later _pop_tx_grid.
Used for reducing grid in loop0.
|
protected |
Context manager: redirect C/Fortran-level stdout+stderr to /dev/null.
|
staticprotected |
(rho_norm, y) from a profile_conditions value after merge + flatten.
Handles:
|
protected |
Populate self._results from TORAX data with time-averaging.
|
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).
| field | 'T_e', 'T_i', or 'n_e'. |
| set_value | The corresponding self._{field}_right_bc (may be None). |
|
protected |
Run the GS solve across n timesteps using TokaMaker.
|
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.
| config | TORAX config as a dict or a ToraxConfig. |
|
protected |
Run the TORAX transport simulation.
|
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).
| stage | 'initial' or 'interloop' (logging / output names only). |
| eqdsk_path | Path to gEQDSK for geometry_configs at t_initial. |
| prescribed_profiles | None, or dict with keys psi, n_e, T_e, T_i (3-tuples). |
|
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.
|
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.
|
protected |
Return whether TORAX accepts eqdsk as ToraxConfig geometry.
| quiet | If 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'. |
|
protected |
Edge smoothing with Gaussian filter: smooth p profile and take derivative for pp_prof.
|
protected |
Generic power-flux shape.
|
protected |
Raw TORAX profiles passed through unchanged.
|
protected |
Sign-flip clipping: clip each profile to its dominant sign.
|
protected |
Update internal state and coil current results based on results of GS solver.
| i | Timestep of the solve. |
|
staticprotected |
Recursively merge override into base TORAX config (in-place).
For every key in override:
| base | Dict to merge into (modified in-place). |
| override | Dict whose keys take precedence. |
|
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.
| i | Timestep index (TokaMaker time index; TM comparison fields in plots use this key). |
| data_tree | Result object from Torax. |
| tx_time | If 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). |
|
protected |
| configure_redirect_to_log | ( | self | ) |
Step 3/3 of setup to divert noisy outputs to log file.
Captures INFO-level and above.
| 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.
| convergence_threshold | Max fractional change in consumed flux between loops for convergence. |
| max_loop | Highest 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_name | Name for this run (used in output directory and log file). |
| output_mode | Output 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.
| skip_bad_init_eqdsks | If True, skip broken initial gEQDSK files instead of raising. |
| initial_relax | If 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. |
| relax | If 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_kinetics | If 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_duration | Duration (s) of each relax simulation. Default 1.0 s. |
| relax_dt | Fixed timestep (s) for each initial / inter-loop TORAX relax run (numerics.fixed_dt). Default 0.1 s. |
| t_ave_toggle | Time-averaging mode: 'off' (no averaging), 'flattop' (average only during flat-top), or 'on' (average over the whole pulse). |
| t_ave_window | Averaging window size in seconds. Default 0.5 s. |
| t_ave_causal | If True, window is entirely behind the timepoint (backward-looking). If False, window is centred on the timepoint. |
| t_ave_ignore_start | Ignore the first N seconds of the pulse when building the averaging window (avoids numerical transients). Default 0.25 s. |
| loop0 | If 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_mode | If 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 | ( | 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.
| eqdsk_save_dir | If 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. |
| load_pedestal_config | ( | self, | |
| pedestal_config ) |
Deprecated: use set_pedestal(config=...).
Fully replaces the TORAX pedestal section.
| pedestal_config | Dictionary in TORAX pedestal config format, or None to clear. |
| 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.
| config | Dictionary (TORAX config format). |
| make_movie | ( | self, | |
| save_path = None, | |||
| ** | kwargs ) |
Generate pulse movie from stored psi snapshots.
| save_path | Path to save MP4 file. If None, does not save. |
| plot_coil_current_tunnel | ( | self, | |
| save_path = None, | |||
| display = True, | |||
| ** | kwargs ) |
Plot coil currents inside their rate-limited bounds "tunnel" over the pulse.
| save_path | Path to save figure. If None, does not save. |
| display | Whether to show the plot. |
| plot_coils | ( | self, | |
| save_path = None, | |||
| display = True, | |||
| ** | kwargs ) |
Plot coil current traces over the pulse.
| save_path | Path to save figure. If None, does not save. |
| display | Whether to show the plot. |
| 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.
| save_path | Path to save figure. If None, does not save. |
| display | Whether to show the plot. |
| 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.
| save_path | Path to save figure. If None, does not save. |
| display | Whether to show the plot. |
| 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).
| save_path | Path prefix to save figures. If None, does not save. |
| display | Whether to show the plots. |
| one_plot | If True, combine all pulse phases into one figure. |
| 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.
| save_path | Path to save figure. If None, does not save. |
| display | Whether to show the plot. |
| plot_profile_evolution | ( | self, | |
| save_path = None, | |||
| display = True, | |||
| one_plot = False, | |||
| ** | kwargs ) |
Plot profile evolution over time.
| save_path | Path to save figure. If None, does not save. |
| display | Whether to show the plot. |
| one_plot | If True, combine all pulse phases into one figure. |
| 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_path | Path to save figure. If None, does not save. |
| display | Whether to show the plot. |
| save_res | ( | self | ) |
Save simulation results to JSON.
| save_state | ( | self, | |
| fname ) |
Save intermediate simulation state to JSON.
| fname | Filename to save to. |
| 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.
| save_path | Explicit 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. |
| 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.
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.
| dIdt | Max |dI/dt| per coil in dIdt_units; scalar or {coil: value}. |
| dIdt_units | Unit of dIdt: 'A-turns/s' (default, total winding rate) or 'A/turn/s' (per-winding rate). Does not affect the V/R path. |
| V | Max coil voltage [V]; scalar or {coil: value}. Requires matching R. |
| R | Coil resistance [Ohms]; scalar or {coil: value}. Used with V. |
| dt_floor | Minimum 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 | ( | 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().
| diverted_times | Tuple (t_start, t_end) defining the diverted plasma window. |
| x_point_targets | PRIMARY (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_weight | Weight for the PRIMARY saddle-point (X-point) constraints. Default 1000.0. |
| strike_point_targets | Strike point locations, shape (n_points, 2) with [R, Z] pairs, or None to disable. |
| trim_lcfs | When 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_limit | LCFS points above this fraction of max(|Z|) are trimmed near the X-point(s) when trim_lcfs is True. |
| secondary_x_point_targets | Optional 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_target | Optional 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_weight | Weight 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_weight | Weight 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 | ( | 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
| density | Evolve density. |
| Ti | Evolve ion temperature. |
| Te | Evolve electron temperature. |
| current | Evolve current. |
| 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
| gas_puff_S_total | Gas puff particle source (particles/s). |
| gas_puff_decay_length | Gas puff decay length from edge (normalized rho). |
| pellet_deposition_location | Pellet deposition location (normalized rho). |
| pellet_width | Pellet deposition width (normalized rho). |
| pellet_S_total | Pellet particle source (particles/s). |
| generic_particle_location | Generic particle source location (normalized rho). |
| generic_particle_width | Generic particle source width (normalized rho). |
| generic_particle_width | Generic particle source amount (particles/s). |
| 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
| generic_heat | Generic heating ({time: power_W}). |
| generic_heat_loc | Generic heating deposition location (normalized rho). |
| generic_heat_width | Generic heating deposition width (normalized rho). |
| generic_heat_absorption_fraction | Fraction of generic heating that is absorbed (default here 1.0, TORAX default is 0.0). |
| generic_heat_electron_heat_fraction | Fraction of generic heating that is converted to electron heat (default 0.4, from arc v3a config, TORAX default is 0.6). |
| nbi_current | Enable NBI current drive estimate from generic heating. |
| ecrh | ECRH heating ({time: power_W}). |
| ecrh_loc | ECRH deposition location (normalized rho). |
| ecrh_width | ECRH deposition width (normalized rho). |
| ohmic | Optional explicit ohmic power ({time: power_W}). |
| fusion | Enable fusion alpha heating source. |
| ei_exchange | Enable electron-ion energy exchange source. |
| set_Ip | ( | self, | |
| Ip ) |
Set plasma current (Amps), used for both codes and not evolved by either.
| ip | Plasma current. |
| 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
| n_e | Electron density (m^-3). |
| right_bc | Right boundary value at rho=1 (m^-3), scalar or time-varying map. |
| 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:
| config_mode | 'off', 'ADAPTIVE_SOURCE', 'ADAPTIVE_TRANSPORT', or 'internal_manual'. |
| config | Optional full pedestal-section dict (tx_adaptive modes only); overrides defaults. |
| ped_height_Te | Electron-temperature pedestal-top value (keV); all modes. |
| ped_height_Ti | Ion-temperature pedestal-top value (keV); all modes (defaults to Te). |
| ped_height_ne | Electron-density pedestal-top value (m^-3); all modes. |
| ped_width | Pedestal width in rho_norm; inner edge is at 1 - ped_width (internal_manual; the tx_adaptive modes use ped_top instead). |
| transition_time | Ramp 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_time | L->H transition time (s); required when timing='input'. |
| hl_time | H->L back-transition time (s); None means the pedestal stays on. |
| formation_model | L/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_prefactor | Stiffness 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_prefactor | Same for the n_e IBC (numerics.adaptive_n_source_prefactor; TORAX default 2e8). None = TORAX default. |
| core_height_Te | On-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_Ti | On-axis H-mode T_i target (keV); None disables it for T_i. |
| core_height_ne | On-axis H-mode n_e target (m^-3); None disables it for n_e. |
| core_exp_a/core_exp_b | Core-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_pedestal | Legacy tx_adaptive toggle (True=set_T_ped_n_ped, False=no_pedestal). |
| T_i_ped | Legacy ion-temperature pedestal (tx_adaptive). |
| T_e_ped | Legacy electron-temperature pedestal (tx_adaptive). |
| n_e_ped | Legacy electron-density pedestal (tx_adaptive). |
| ped_top | Legacy pedestal-top location rho_norm_ped_top (tx_adaptive). |
| 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
| Zeff | Effective charge target. |
| main_ion | Main ion species dict, e.g. {'D': 0.5, 'T': 0.5}. |
| impurity | Impurity species string, e.g. 'Ne', 'Ar', 'W'. |
| 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
| T_e | Electron temperature (keV). |
| right_bc | Right boundary value at rho=1 (keV), scalar or time-varying map. |
| 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
| T_i | Ion temperature (keV). |
| right_bc | Right boundary value at rho=1 (keV), scalar or time-varying map. |
| 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.
| coil_bounds | Hard 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_units | Unit of coil_bounds: 'A-turns' (default, total winding current) or 'A/turn' (per-winding current, TokaMaker's native unit). |
| updownsym | Enforce up-down symmetry for coil pairs (U/L naming convention). |
| default_weight | Regularization weight for normal coils (default 0.1). |
| disable_coils | List of coil name prefixes to disable (e.g. ['DV1', 'DV2']). |
| disable_weight | Regularization weight for disabled coils (default 1e4). |
| symmetry_weight | Regularization weight for symmetry constraints (default 1e3). |
| disable_virtual_vsc | Disable the virtual VSC coil (default True). |
| vsc_weight | Regularization weight for disabled VSC (default 1e4). |
| 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).
| isoflux_weight | Weight 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_weight | Weight on the LCFS psi-value constraint, applied at the single outboard-midplane point using the TORAX psi_lcfs. Default 1000.0. |
| 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
| grid_type | Grid type ('n_rho' or 'face_centers'). |
| grid | Grid points (integer or np.array). |
| 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
| chi_min | Minimum ion thermal diffusivity (m^2/s). |
| chi_max | Maximum ion thermal diffusivity (m^2/s). |
| De_min | Minimum electron diffusion coefficient (m^2/s). |
| De_max | Maximum electron diffusion coefficient (m^2/s). |
| Ve_min | Minimum electron thermal velocity (m/s). |
| Ve_max | Maximum electron thermal velocity (m/s). |
| 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 | ( | self, | |
| ** | kwargs ) |
Print/display a physics summary of the simulation.
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
| lcfs = lcfs |
| results = None |
Access simulation results dict.
| state = None |
Access simulation state dict.