![]() |
The Open FUSION Toolkit 26.9
An open-source framework for fusion and plasma science and engineering
|
TokaMaker + TORAX Coupled Pulse Design and Simulation Workflow (TokaMaker_TORAX/tmtx).
TokaMaker (tm) = free-boundary equilibrium solver, part of OFT TORAX (tx) = Python Jax transport solver (developed by Google DeepMind) https://github.com/google-deepmind/torax
TokaMaker_TORAX workflow couples the two codes for pulse planning, predictive kinetic equilibria, and other integrated modeling applications.
Classes | |
| class | MyEncoder |
| JSON Encoder Object to store simulation results. More... | |
| class | TokaMaker_TORAX |
| TokaMaker + TORAX Coupled Pulse Simulation Code. More... | |
Functions | |
| _apply_coil_config (tmtx, tm_inputs) | |
| Apply the unified tm_inputs coil settings to a TokaMaker_TORAX object. | |
| _apply_tm_weight_config (tmtx, tm_inputs) | |
| Apply the tm_inputs GS constraint weights that hold at every timepoint. | |
| _bc_at (right_bc, t) | |
| Evaluate an edge (rho=1) BC at time t: a scalar as-is, or a {time: value} map linearly interpolated in time (constant-extrapolated past the ends). | |
| _coil_aturn_clim (tt) | |
| Return (min, max) colormap limits in A-turns from _coil_bounds (stored in A-turns). | |
| _coil_net_turns (tt, cname) | |
| Return net_turns for a coil set name, defaulting to 1. | |
| _core_transition_profile (rhos, ped_rho, ped, core, exp_a=2.0, exp_b=2.0) | |
| Smooth CORE-only H-mode-like profile over [0, ped_rho] that joins the pedestal top WITHOUT its own edge roll-off (so it doesn't create a second pedestal): | |
| _create_seed_eqdsks (tmtx_config, mygs, save_dir=None) | |
| Create the seed gEQDSK files that seed the TokaMaker_TORAX coupling. | |
| _draw_equil_from_dir (ax, tt, loop, idx, t_now, equil_dir) | |
| Draw equilibrium from pre-rendered PNG in equil_dir. | |
| _draw_info (ax, tt, loop, run_name) | |
| _draw_profiles_movie (axes, tt, idx) | |
| Draw the 6 radial profile panels for a movie frame. | |
| _draw_scalars_movie (axes, tt, times, t_now, flux_con_tm) | |
| Draw the 6 scalar time-series panels for a movie frame. | |
| _embed_video_jupyter (video_path) | |
| Embed an MP4 video in a Jupyter notebook. | |
| _encode_video_from_dir (frame_dir, out_path, fps=2, frame_times=None) | |
| Encode frames from a directory into an MP4 file. | |
| _eqdsk_shape_stats (rz) | |
| Geometric shape parameters (R_geo, a_geo, kappa, delta) from an LCFS contour [:,2]. | |
| _eval_ibc_at_time (spec, t) | |
| Evaluate a single-field IBC SparseTimeVaryingArray spec at time t -> (rhos, values), linearly interpolating each rho's value in time between listed times (matching TORAX). | |
| _fmt_saved_artifact_link (path) | |
| Absolute path as a file:// URI when possible (terminal / IDE hyperlink), else abs path. | |
| _in_jupyter () | |
| Return True if running inside a Jupyter notebook. | |
| _init_TM_object (tmtx_config) | |
| Initialize a TokaMaker object from a TMTX config dict. | |
| _init_TMTX_from_configs (tmtx_config, torax_config, mygs) | |
| Build a TokaMaker_TORAX object from the TMTX and TORAX config dicts. | |
| _interp_traj (traj, t) | |
| Linear interpolation of a {time: value} trajectory dict at time t. | |
| _last_solve_eqdsk_stats (tt, i) | |
| Scalars read back from the gEQDSK the previous loop's TM solve wrote at timestep i. | |
| _lcfs_shape_rms (targets, contour) | |
| RMS over each target point of its minimum distance to the achieved LCFS contour (treated as a polyline of segments). | |
| _load_config_file (config_file) | |
| Load tmtx_dict and torax_dict from a saved reproduction .py file. | |
| _make_temp_dir_viz () | |
| Create temp directory for visualization temporary files: RAM-backed on Linux, OS default elsewhere. | |
| _merge_ibc_specs (spec_a, spec_b) | |
| Merge two single-field IBC SparseTimeVaryingArrays that use DIFFERENT band locations (e.g. | |
| _mtanh_pedestal (rho, ped_top, foot, core_slope, knee, hwid, blend) | |
| Linear core gradient smoothly blended into a tanh pedestal. | |
| _output_mode_is_debug (output_mode) | |
| Whether a fly() output_mode value selects debug mode, using the same normalization as TokaMaker_TORAX.fly() (True -> 'normal'; strings stripped/lowercased). | |
| _ped_top_slope_at (shape_by_time, t, default) | |
| Interpolate (ped_top, slope) in time from a {tm_time: (ped_top, slope)} dict (constant-extrapolated past the ends). | |
| _pedestal_ibc (ped_rho, right_bc, shape_by_time, default_shape, transition, windows, knee, hwid, blend) | |
| Build a TORAX internal-boundary-condition SparseTimeVaryingArray for one field: {time: {(ped_rho, 1.0): {rho: value}}}. | |
| _prof (state_dict, idx) | |
| Return (x, y) arrays from a profile state dict, or (None, None). | |
| _render_equil_frames (tt, loop, equil_dir) | |
| Render equilibrium plots from stored equilibrium snapshots to PNG files. | |
| _render_frame (tt, loop, idx, t_now, times, flux_con_tm, out_path, run_name, equil_dir) | |
| Create a single movie frame. | |
| _rms_prof_diff (prof_a, prof_b) | |
| RMS of (prof_a - prof_b) after interpolating prof_b onto prof_a's x grid. | |
| _saddle_targets (tt) | |
| Every point given a saddle constraint: primary nulls plus any secondary nulls. | |
| _save_or_display (fig, save_path=None, display=True) | |
| Save figure and/or display it, then close. | |
| _seed_tm_profiles_for_failure_profile_plot (tt, i) | |
| Fill TM comparison fields for profile_plot from seed EQDSK/GS inputs when TM has not run at index i. | |
| _style (ax) | |
| Apply consistent styling to a matplotlib Axes. | |
| _tm_diag_coil_panel (tt, ax, i) | |
| Solved coil currents against the bounds enforced on this solve, in MA-turns. | |
| _tm_diag_equil_targets (tt, ax, i, equil) | |
| Draw the constraint targets this timestep's solve was given, plus what it achieved. | |
| _tm_diag_tm_column (tt, i, gs_ok, solve_succeeded, succeeded_profile) | |
| TokaMaker column values for the diagnostic table at timestep i. | |
| _trace_lcfs_for_evolution_plot (equil) | |
| Try successive normalized psi surfaces until tracing returns a non-empty contour. | |
| _transition_ibc (loc, lmode_profile, hmode_target, lh, transition) | |
| Build a CORE (rho 0 -> ped_rho) internal-boundary-condition SparseTimeVaryingArray for one field, active ONLY across the L->H transition window [lh, lh+transition]: {time: {loc: {rho: value}}} where loc = (0.0, ped_rho). | |
| _tx_profile_at_rho (tt, var_name, rho_val, rho_coord='rho_norm', scale=1.0) | |
| Return (times, values) for a profile variable at a fixed rho, full resolution. | |
| _tx_scalar (tt, var_name, scale=1.0) | |
| Return (times, values) arrays from data_tree.scalars at full TORAX resolution. | |
| _x_points_active (tt, i, t=None) | |
| Return True when X-point targets should be applied at timestep index i. | |
| _xpt_rms (targets, achieved) | |
| RMS over each target X-point of its distance to the nearest achieved X-point. | |
| IBC_debug (tt, i, t, save_path=None) | |
| Debug figure for the internal_manual IBC technique (debug mode, one per TM solve). | |
| log_redirect_setup () | |
| Step 1/3 of setup to redirect noisy outputs to log file. | |
| make_movie (tt, save_path=None, display=True, speed_factor=5.0, loop=None, notebook_mode=None) | |
| Create pulse movie from simulation data. | |
| plot_coil_current_tunnel (tt, save_path=None, display=True) | |
| Per-coil current vs time inside the rate-limited bounds "tunnel". | |
| plot_coils (tt, save_path=None, display=True) | |
| Plot coil current traces in MA-turns with limit bands (data stored in A-turns). | |
| plot_coupling_convergence (tt, save_path=None, display=True) | |
| Plot the flavor-2 coupling-convergence cost vs coupling loop — the loop-over-loop trend that is the whole point of the aggregate metric. | |
| plot_equil_interactive (tt, loop=None, notebook_mode=None, save_path=None) | |
| Equilibrium viewer — widget slider in notebook, saved PNGs otherwise. | |
| plot_errors (tt, save_path=None, display=True) | |
| Plot per-timestep TokaMaker-vs-TORAX coupling error metrics, one panel per channel in a 4-column grid (layout mirrors plot_scalars). | |
| plot_lcfs_evolution (tt, save_path=None, display=True, one_plot=False) | |
| Plot time evolution of the last closed flux surface for each phase. | |
| plot_PLH_components (tt, save_path=None, display=True) | |
| Decompose the L->H transition power into every ingredient, for the current loop's TORAX run. | |
| plot_profile_evolution (tt, save_path=None, display=True, one_plot=False) | |
| Plot profile evolution by pulse phase by default, or as one figure when one_plot=True. | |
| plot_profiles_interactive (tt) | |
| Interactive profile viewer with ipywidgets slider to scrub through timesteps. | |
| plot_scalars (tt, save_path=None, display=True) | |
| Plot 4x3 grid of time-series scalars plus a bottom row: power channels, sources, P_LH. | |
| plot_tx_relax_profiles (tt, data_tree, *, stage, t_final_relax, user_ref_curves=None, save_path=None, display=False) | |
| Plot psi, n_e, T_e, T_i vs rho_norm after a short TORAX relax. | |
| profile_plot (tt, i, t, save_path=None, display=True) | |
| Detailed profile comparison at a single timestep. | |
| redirect_outputs_to_log (filename) | |
| Step 2/3 of setup to redirect noisy outputs to log file. | |
| run_tmtx_from_config (tmtx_config=None, torax_config=None, config_file=None, save_dir=None) | |
| Full TokaMaker_TORAX run from config dicts: seed eqdsk creation, object initialization, and simulation. | |
| summary (tt) | |
| Print and return key physics figures of merit from the simulation. | |
| tm_diagnostic_plot (tt, i, t, level_attempts, solve_succeeded, save_path=None, display=True, tm_gs_ok=None, step_error=None) | |
| TokaMaker input/output diagnostic plot for a single timestep. | |
| tm_loop_summary_plot (tt, loop_level_log, save_path=None, display=True) | |
| Summary figure showing per-timestep GS solve outcomes. | |
Variables | |
| dict | _COIL_RATE_KEY_MAP |
| dict | _COIL_REG_KEY_MAP |
| dict | _COUPLING_COST_FLOORS |
| tuple | _COUPLING_COST_SPEC |
| dict | _COUPLING_COST_WEIGHTS |
| list | _ERROR_KEYS = [spec[0] for spec in _ERROR_SPECS] |
| list | _ERROR_SPECS |
| tuple | _LCFS_EVO_PSI_TRY = (1.0, 0.99, 0.98, 0.97) |
| int | _NBI_W_TO_MA = 1/16e6 |
| dict | _TM_WEIGHT_KEY_MAP |
| dict | BASE_CONFIG |
| str | COLOR_TM = 'steelblue' |
| str | COLOR_TX = 'crimson' |
| list | COLORS_MULTI |
| int | DEFAULT_LOOP0_TX_FACE_POINTS = 51 |
| int | DIAG_FS = 13 |
| tuple | EQDSK_SAVE_NR_NZ_SEQUENCE = (300, 900) |
| float | GRID_ALPHA = 0.2 |
| int | INFO_FS = 13 |
| int | LABEL_FS = 11 |
| float | LCFS_WEIGHT = 100.0 |
| int | LEGEND_FS = 9 |
| str | LS_PRI = '-' |
| str | LS_SEC = '--' |
| float | LW = 1.6 |
| int | MK_SZ = 3 |
| str | MK_TM = '.' |
| int | MOVIE_DPI = 300 |
| int | MOVIE_EQUIL_PSI_PLASMA_NLEVELS = 8 |
| MOVIE_FIG_H | |
| MOVIE_FIG_W | |
| float | mu_0 = 4.0 * np.pi * 1e-7 |
| int | N_PSI = 1000 |
| float | PED_GRAD_WINDOW = 0.1 |
| int | PED_N_SAMPLE = 24 |
| float | PSI_LCFS_WEIGHT = 1000.0 |
| int | TICK_FS = 10 |
| int | TITLE_FS = 13 |
| str | VLINE_COLOR = 'black' |
| str | VLINE_LS = ':' |
| float | VLINE_LW = 1.0 |
|
protected |
Apply the unified tm_inputs coil settings to a TokaMaker_TORAX object.
All coil configuration lives in tm_inputs under coil_* keys: the single global hard bounds (coil_bounds / coil_bounds_units), the regularization weights, and the optional rate limits. The same coil_bounds is used for seed-eqdsk generation (_init_TM_object), the coupled GS solves, and the rate-limit clip, so the hard limit is specified exactly once.
Absent keys fall back to the set_*() method defaults. Rate limiting is applied only if at least one of coil_dIdt / coil_V / coil_R is given.
| tmtx | TokaMaker_TORAX object. |
| tm_inputs | The tmtx_config['tm_inputs'] dict. |
|
protected |
Apply the tm_inputs GS constraint weights that hold at every timepoint.
Covers isoflux_weight (LCFS shape targets) and psi_lcfs_weight (the outboard-midplane psi value). The diverted-only weights are configured with their targets via set_diverted_shape_targets().
| tmtx | TokaMaker_TORAX object. |
| tm_inputs | The tmtx_config['tm_inputs'] dict. |
|
protected |
Evaluate an edge (rho=1) BC at time t: a scalar as-is, or a {time: value} map linearly interpolated in time (constant-extrapolated past the ends).
|
protected |
Return (min, max) colormap limits in A-turns from _coil_bounds (stored in A-turns).
|
protected |
Return net_turns for a coil set name, defaulting to 1.
|
protected |
Smooth CORE-only H-mode-like profile over [0, ped_rho] that joins the pedestal top WITHOUT its own edge roll-off (so it doesn't create a second pedestal):
f(rho) = ped + (core - ped) * (1 - (rho/ped_rho)^a)^b
With a>=2, b>=2 this has ~zero gradient at rho=0 (flat core), monotonically falls through mid-radius, and FLATTENS into ped at rho=ped_rho (zero gradient there too), so it hands off smoothly to the pedestal band (whose inner-edge slope is ~0). Unlike Hmode_profiles it has NO tanh edge inside the core grid – the drop ends exactly at ped_rho = ped_height, so the only pedestal is the [ped_rho,1] band. Looks like the H-mode core (steepest mid-radius, gentle at both ends).
| rhos | Normalized rho array over [0, ped_rho] to sample onto. |
| ped_rho | Inner pedestal edge (where the core meets the pedestal top). |
| ped | Pedestal-top value (= ped_height); the core endpoint at ped_rho. |
| core | On-axis (rho=0) value. |
| exp_a/exp_b | Core-shape exponents (a>=2, b>=2 for flat ends). Default 2/2. |
|
protected |
Create the seed gEQDSK files that seed the TokaMaker_TORAX coupling.
Uses the time-dependent trajectory paradigm: seed_eqdsk_config holds {time: value} trajectory dicts for the shape/flux quantities. At each requested seed time the trajectories are interpolated and a TokaMaker GS solve produces one gEQDSK.
create_seed_eqdsks : bool create files (True) or load existing (handled by caller). eq_times : list[float] seed solve times (s). If None/empty, evenly spaced num_seed_eqdsks points across [t_sim_start, t_sim_end]. num_seed_eqdsks : int used only when eq_times is None/empty. a, kappa, delta : {t: value} plasma minor radius / elongation / triangularity. R_mag : {t: value} magnetic-axis major radius (optional; if absent, R0 (geometry) is used as a constant). pax : {t: value} on-axis pressure target (Pa). psi_lcfs : {t: value} LCFS psi target (Wb/rad), enforced as a soft constraint. psi_lcfs_weight : float weight on the psi_lcfs constraint (default 10.0). diverted_window : (t0, t1) times where the plasma is diverted (X-points enforced, diverted_lcfs isoflux); limited otherwise. x_points : (n,2) array X-point [R,Z] targets used in the diverted window. diverted_lcfs : (n,2) array LCFS isoflux points used in the diverted window. n_isoflux : int isoflux points for the limited (analytic) LCFS (default 28). eqdsk_nr, eqdsk_nz : int gEQDSK grid resolution (default 900).
| tmtx_config | TMTX config dict. |
| mygs | Configured TokaMaker object (from _init_TM_object). |
| save_dir | Directory for the seed files. None -> a seed_eqdsks_{run_name}/ subfolder. In debug mode this subfolder is created in the cwd (so the seeds are visible during the run); otherwise it is placed inside a fresh temp dir. Either way the caller moves it into the run output dir (or cleans up the temp parent) after the run. |
|
protected |
Draw equilibrium from pre-rendered PNG in equil_dir.
|
protected |
|
protected |
Draw the 6 radial profile panels for a movie frame.
|
protected |
Draw the 6 scalar time-series panels for a movie frame.
TokaMaker traces are per-solve (at tm_times); TORAX traces are drawn straight from the data tree at full TORAX resolution, matching plot_scalars. Reading them from _state instead would show them subsampled onto tm_times and passed through the t_ave window averaging, which distorts ramps and hides sub-window structure.
|
protected |
Embed an MP4 video in a Jupyter notebook.
|
protected |
Encode frames from a directory into an MP4 file.
If frame_times is provided (array of simulated times, one per frame), each frame is given a wall-clock duration proportional to its simulated time gap so the movie plays at constant simulated-time rate regardless of frame clustering. fps is then interpreted as simulated-seconds per wall-clock-second. If frame_times is None, falls back to a fixed fps.
|
protected |
Geometric shape parameters (R_geo, a_geo, kappa, delta) from an LCFS contour [:,2].
Uses the LCFS-extrema convention, matching TokaMaker get_stats(geom_type='max'), so values derived here for an EQDSK are comparable to TokaMaker's own. Returns an empty dict for a contour that is missing or degenerate.
|
protected |
Evaluate a single-field IBC SparseTimeVaryingArray spec at time t -> (rhos, values), linearly interpolating each rho's value in time between listed times (matching TORAX).
Returns None if the band is OFF (all zero) at t.
|
protected |
Absolute path as a file:// URI when possible (terminal / IDE hyperlink), else abs path.
|
protected |
Return True if running inside a Jupyter notebook.
|
protected |
Initialize a TokaMaker object from a TMTX config dict.
Builds a fresh OFT_env + TokaMaker (independent per call, safe for parallel runs), loads the mesh, configures coils / VSC / bounds, sets seed GS profiles, and applies the standard coil regularization terms.
| tmtx_config | Dictionary (TMTX config format). |
|
protected |
Build a TokaMaker_TORAX object from the TMTX and TORAX config dicts.
tmtx_config carries everything that is TokaMaker-specific or shared between the two codes (Ip, time window, tm_times, seed eqdsk paths, pedestal, diverted_shape_targets, evolve flags). All coil settings — the single global hard bounds, regularization weights, and rate limits — live in tm_inputs under coil_* keys and are applied by _apply_coil_config(). torax_config is the raw TORAX config and is handed to load_TORAX_config() (which also picks up the TORAX grid from its geometry.n_rho / geometry.face_centers).
Required tmtx_config keys: 'R0', 'B0', 'Ip', 't_sim_start', 't_sim_end', 'tx_dt', and seed eqdsk paths in 'g_eqdsk_arr' with matching seed times in seed_eqdsk_config['eq_times'].
| tmtx_config | Dictionary (TMTX config format). |
| torax_config | Dictionary (raw TORAX config). |
| mygs | Configured TokaMaker object. |
|
protected |
Linear interpolation of a {time: value} trajectory dict at time t.
Times are sorted; t outside the range clamps to the endpoint value.
| traj | Dict mapping float time (s) -> float value. |
| t | Query time (s). |
|
protected |
Scalars read back from the gEQDSK the previous loop's TM solve wrote at timestep i.
That file is the geometry TORAX consumed for the current loop, so it is the "last solve" reference the diagnostic table compares against. Returns an empty dict on loop 1, or when the file is absent because the solve failed before it could be written.
|
protected |
RMS over each target point of its minimum distance to the achieved LCFS contour (treated as a polyline of segments).
targets is (K,2) [R,Z], contour is (M,2) [R,Z]. Returns NaN if either is missing/degenerate. Units: metres.
|
protected |
Load tmtx_dict and torax_dict from a saved reproduction .py file.
| config_file | Path to a tmtx_config_{run}_{ts}.py file. |
|
protected |
Create temp directory for visualization temporary files: RAM-backed on Linux, OS default elsewhere.
|
protected |
Merge two single-field IBC SparseTimeVaryingArrays that use DIFFERENT band locations (e.g.
the pedestal band (ped_rho,1) and the core band (0,core_hi)) into one {time: {(lo,hi): {rho: value}}}.
TORAX groups IBC entries BY LOCATION (interpolated_param_2d): each band (lo,hi) becomes its own TimeVaryingArray from only the times IT was listed at, interpolated independently of the other band. So we just take the per-time union of whatever each spec actually lists – a band absent at some time is NOT carried forward here (it doesn't need to be; TORAX interpolates it from its own listed times). This keeps each band sparse: e.g. the core band stays at its ~5 natural times even when the pedestal band is listed at every H-mode tm_time. Listing the absent band at every union time would bloat the spec with redundant all-zero entries and slow TORAX, with no effect on the result.
| spec_a/spec_b | {time: {(lo,hi): {rho: value}}} specs with distinct band keys. |
|
protected |
Linear core gradient smoothly blended into a tanh pedestal.
A line of slope core_slope through (ped_rho, ped_top) owns the core; a tanh dropping from ped_top to foot owns the edge; a sigmoid (centred at knee, width blend) hands off between them. Because the sigmoid weight is ~0 at the inner edge, the gradient there is exactly core_slope.
| rho | Normalized rho array. |
| ped_top | Value at the inner (left) edge. |
| foot | Separatrix value at rho=1. |
| core_slope | d(value)/d(rho_norm) imposed at the inner edge. |
| knee | Rho where the core hands off to the pedestal. |
| hwid | Pedestal (tanh) half-width. |
| blend | Sharpness of the core->pedestal handoff. |
|
protected |
Whether a fly() output_mode value selects debug mode, using the same normalization as TokaMaker_TORAX.fly() (True -> 'normal'; strings stripped/lowercased).
| output_mode | Raw output_mode value (as passed to fly()). |
|
protected |
Interpolate (ped_top, slope) in time from a {tm_time: (ped_top, slope)} dict (constant-extrapolated past the ends).
Returns default if the dict is empty.
|
protected |
Build a TORAX internal-boundary-condition SparseTimeVaryingArray for one field: {time: {(ped_rho, 1.0): {rho: value}}}.
Three band states:
PER-TM-TIME shape: the mtanh ped_top and inner-edge slope are taken from shape_by_time ({tm_time: (ped_top, slope)}, from the previous loop's evolved profile at each tm_time) and the band is listed at EVERY tm_time in the H-mode window, so the imposed pedestal tracks the evolving profile time-point by time-point. (A single time-averaged shape is wrong: the few transition-region tm_times have anomalous steep slopes that poison the average.) Before any smoothing exists, default_shape (ped_top, slope) is used at all times.
The transition ramps L-MODE EDGE -> ON (NOT OFF -> ON), so the foot stays at the edge BC throughout the ramp (only the pedestal height above the foot grows in); ramping from zeros instead would spike rho=1 and notch just inside.
| ped_rho | Inner edge rho of the imposed pedestal. |
| right_bc | Edge (rho=1) BC: scalar or {time: value} map; sets the foot per time. |
| shape_by_time | {tm_time: (ped_top, slope)} per-time mtanh shape (may be empty). |
| default_shape | (ped_top, slope) used when shape_by_time is empty / outside it. |
| transition | Ramp duration [s] at each L<->H edge. |
| windows | List of (lh_time, hl_time) H-mode windows; hl_time may be None (stays on). |
| knee/hwid/blend | mtanh shape parameters. |
|
protected |
Return (x, y) arrays from a profile state dict, or (None, None).
|
protected |
Render equilibrium plots from stored equilibrium snapshots to PNG files.
|
protected |
Create a single movie frame.
|
protected |
RMS of (prof_a - prof_b) after interpolating prof_b onto prof_a's x grid.
Each profile is a {'x','y'} dict (or None). Returns NaN if either is missing or empty, or no overlapping finite samples remain.
|
protected |
Every point given a saddle constraint: primary nulls plus any secondary nulls.
|
protected |
Save figure and/or display it, then close.
|
protected |
Fill TM comparison fields for profile_plot from seed EQDSK/GS inputs when TM has not run at index i.
|
protected |
Apply consistent styling to a matplotlib Axes.
|
protected |
Solved coil currents against the bounds enforced on this solve, in MA-turns.
Draws the per-step rate-limited box when one was recorded for this timestep, else the global bounds; the forbidden regions outside the box are shaded. Coils resting on a bound are circled – those are the ones the solve could not move further to hit its targets.
|
protected |
Draw the constraint targets this timestep's solve was given, plus what it achieved.
The targets come from _state, recorded as they were handed to TokaMaker, rather than from a TokaMaker equilibrium object – a failed solve leaves no equilibrium to read them back from, and reading the live object instead showed a different (untrimmed) set than the succeeded plots. Both paths therefore draw identical points.
| equil | Equilibrium for the achieved X-points, or None if the solve did not converge. |
|
protected |
TokaMaker column values for the diagnostic table at timestep i.
Everything is read from this timestep's equilibrium object rather than the *_tm state arrays, because _tm_update only runs once the EQDSK is also accepted – on a rejected EQDSK the state arrays still hold the previous loop's values for this index. Keys absent from the returned dict render blank, so a failed GS solve yields only the solver settings.
|
protected |
Try successive normalized psi surfaces until tracing returns a non-empty contour.
|
protected |
Build a CORE (rho 0 -> ped_rho) internal-boundary-condition SparseTimeVaryingArray for one field, active ONLY across the L->H transition window [lh, lh+transition]: {time: {loc: {rho: value}}} where loc = (0.0, ped_rho).
The band ramps (TORAX linearly interpolates in time) from the TORAX-evolved L-mode core at t=lh to the H-mode core at t=lh+transition, then retreats (OFF). The pedestal band owns [ped_rho,1] at all times, so the two bands meet at ped_rho with no overlap. NO H->L entry.
| loc | Band location (0.0, ped_rho). |
| lmode_profile | {rho: value} evolved L-mode core shape at ~lh (start of the ramp). |
| hmode_target | {rho: value} H-mode core profile (end of the ramp). |
| lh | L->H transition time [s]. |
| transition | Ramp duration [s]. |
|
protected |
Return (times, values) for a profile variable at a fixed rho, full resolution.
|
protected |
Return (times, values) arrays from data_tree.scalars at full TORAX resolution.
|
protected |
Return True when X-point targets should be applied at timestep index i.
|
protected |
RMS over each target X-point of its distance to the nearest achieved X-point.
targets is (n,2) [R,Z] (or None), achieved is (P,>=2) [R,Z,...] (or None). Returns NaN if either is missing/empty. Units: metres.
| IBC_debug | ( | tt, | |
| i, | |||
| t, | |||
| save_path = None ) |
Debug figure for the internal_manual IBC technique (debug mode, one per TM solve).
Always saved to save_path, never displayed. Three rows (T_e, T_i, n_e), all in rho_norm, zoomed on the pedestal region (or the whole domain during the L->H transition):
| log_redirect_setup | ( | ) |
Step 1/3 of setup to redirect noisy outputs to log file.
Performs the initial, minimal logging setup.
| make_movie | ( | tt, | |
| save_path = None, | |||
| display = True, | |||
| speed_factor = 5.0, | |||
| loop = None, | |||
| notebook_mode = None ) |
Create pulse movie from simulation data.
Renders equilibrium plots from stored equilibrium snapshots, generates composite frames in a temp directory, encodes to MP4, then cleans up.
tt : TokaMaker_TORAX Fully-populated TokaMaker_TORAX object (after fly()). save_path : str, optional Path to save the MP4 file. If None, uses a default in cwd. display : bool If True and running in Jupyter, embed the video in the notebook. speed_factor : float Playback speed relative to real time. loop : int, optional Loop to visualize. Default: last completed loop. notebook_mode : bool or None True → embed video in notebook after saving. False → save to file only, do not embed. None → auto-detect (embed if in Jupyter and display=True).
| plot_coil_current_tunnel | ( | tt, | |
| save_path = None, | |||
| display = True ) |
Per-coil current vs time inside the rate-limited bounds "tunnel".
One subplot per real coil: the solved coil current (dots connected by lines, MA-turns) overlaid on the per-solve bounds. Forbidden regions (above the upper limit and below the lower limit) are shaded gray; the allowed corridor between the limits is left white, so the current trace should ride through the white tunnel. The band at each solve time is the window [I_prev ± dIdt·dt] applied to that solve (centered on the previous good current, drawn at the current time).
A final subplot shows every coil's realized |dI/dt| (MA-turns/s) between consecutive solves, with each coil's configured rate limit as a dashed reference.
Requires set_coil_rate_limits() to have populated tt._coil_bounds_history during the solve loop; falls back to a message if no history is present.
| tt | TokaMaker_TORAX instance. |
| save_path | Output path (or None to display). |
| display | Show interactively instead of saving. |
| plot_coils | ( | tt, | |
| save_path = None, | |||
| display = True ) |
Plot coil current traces in MA-turns with limit bands (data stored in A-turns).
| plot_coupling_convergence | ( | tt, | |
| save_path = None, | |||
| display = True ) |
Plot the flavor-2 coupling-convergence cost vs coupling loop — the loop-over-loop trend that is the whole point of the aggregate metric.
Left panel: total cost (mean and max over time) per loop on a log axis. Right panel: the mean normalized error of each contributing channel per loop, so it is clear which channel dominates and whether the coupling is settling. Reads tt._coupling_cost_history (appended once per loop by _compute_coupling_cost).
| plot_equil_interactive | ( | tt, | |
| loop = None, | |||
| notebook_mode = None, | |||
| save_path = None ) |
Equilibrium viewer — widget slider in notebook, saved PNGs otherwise.
notebook_mode : bool or None True → ipywidgets slider (Jupyter). False → save PNG files to save_path. None → auto-detect (widget if in Jupyter, save files otherwise). save_path : str, optional Directory for PNG files when notebook_mode=False. Defaults to ./equil_loop<N>/ in the current directory.
| plot_errors | ( | tt, | |
| save_path = None, | |||
| display = True ) |
Plot per-timestep TokaMaker-vs-TORAX coupling error metrics, one panel per channel in a 4-column grid (layout mirrors plot_scalars).
Every completed coupling loop is overlaid (colour-coded oldest→newest via viridis, newest emphasized) so convergence over loops is visible in one figure; the RMS annotation and legend track the latest loop. Reads the per-loop snapshots in tt._error_history; if that is empty, falls back to the current-loop err_* arrays in state.
| plot_lcfs_evolution | ( | tt, | |
| save_path = None, | |||
| display = True, | |||
| one_plot = False ) |
Plot time evolution of the last closed flux surface for each phase.
Produces phase-split figures by default (rampup, flattop, rampdown), or one combined figure when one_plot=True.
| plot_PLH_components | ( | tt, | |
| save_path = None, | |||
| display = True ) |
Decompose the L->H transition power into every ingredient, for the current loop's TORAX run.
3x3 grid (all from tt._data_tree at full TORAX resolution; B_T is ~constant and printed in the title):
(0,0) line-avg n_e vs n_e_min (Ryter) — which density BRANCH is active. (0,1) Ip [MA] (drives n_min ∝ Ip^0.34). (0,2) S = g0_face[-1] [m^2] (LCFS surface area; P_LH ∝ S^0.941). (1,0) a_minor, R_major [m] (set n_min; a also via R/a). (1,1) P_LH branch decomposition (selected / high-n / low-n n^-2 / floor). (1,2) the governing equations (LaTeX). (2,0) f_GW (line-avg) — headroom to the density limit. (2,1) P_SOL vs P_LH (transition) — the transition gate, zoomed to L->H. (2,2) P_SOL vs P_LH (full pulse) — same gate over the whole pulse duration.
Isolates why the L->H transition can fire in one loop but not another even when geometry/Ip are nearly identical: the branch crossover is set by line-avg n_e vs n_min, and the low-density n^-2 branch is hypersensitive there.
| plot_profile_evolution | ( | tt, | |
| save_path = None, | |||
| display = True, | |||
| one_plot = False ) |
Plot profile evolution by pulse phase by default, or as one figure when one_plot=True.
| plot_profiles_interactive | ( | tt | ) |
Interactive profile viewer with ipywidgets slider to scrub through timesteps.
| plot_scalars | ( | tt, | |
| save_path = None, | |||
| display = True ) |
Plot 4x3 grid of time-series scalars plus a bottom row: power channels, sources, P_LH.
| plot_tx_relax_profiles | ( | tt, | |
| data_tree, | |||
| * | , | ||
| stage, | |||
| t_final_relax, | |||
| user_ref_curves = None, | |||
| save_path = None, | |||
| display = False ) |
Plot psi, n_e, T_e, T_i vs rho_norm after a short TORAX relax.
Shows main-run history (tt._relax_mainrun_profile_history), user kinetic profiles from flattened profile_conditions, init EQDSK psi at t_initial when psi is not prescribed (initial_psi_mode='geometry'), and the profile at t_final_relax. Used when TokaMaker_TORAX.fly(..., output_mode='debug').
| profile_plot | ( | tt, | |
| i, | |||
| t, | |||
| save_path = None, | |||
| display = True ) |
Detailed profile comparison at a single timestep.
| redirect_outputs_to_log | ( | filename | ) |
Step 2/3 of setup to redirect noisy outputs to log file.
A context manager to temporarily redirect stdout and stderr to a file.
| filename | Name of log file (self._log_file) |
| run_tmtx_from_config | ( | tmtx_config = None, | |
| torax_config = None, | |||
| config_file = None, | |||
| save_dir = None ) |
Full TokaMaker_TORAX run from config dicts: seed eqdsk creation, object initialization, and simulation.
Two ways to call:
tmtx_config holds everything needed to run the sim except TORAX-passthrough inputs (those go in torax_config and are handed to load_TORAX_config()).
Each call builds its own OFT_env + TokaMaker, so multiple invocations are fully independent and safe to run in parallel (e.g. for sweeps).
| tmtx_config | Dictionary (TMTX config format), or None to load from config_file. |
| torax_config | Dictionary (raw TORAX config), or None to load from config_file. |
| config_file | Path to a saved reproduction .py (see save_tmtx_config()). |
| save_dir | Base directory for the run (cwd is changed here so TokaMaker_TORAX outputs and seed staging land under it). None = current working directory. |
| summary | ( | tt | ) |
Print and return key physics figures of merit from the simulation.
| tm_diagnostic_plot | ( | tt, | |
| i, | |||
| t, | |||
| level_attempts, | |||
| solve_succeeded, | |||
| save_path = None, | |||
| display = True, | |||
| tm_gs_ok = None, | |||
| step_error = None ) |
TokaMaker input/output diagnostic plot for a single timestep.
Success and failure produce the same layout; cells with no value available (all TokaMaker results on a failed GS solve) render as an em dash.
| solve_succeeded | Whether the full TM timestep succeeded including EQDSK validation for TORAX (same flag as after _run_tm updates). |
| tm_gs_ok | Whether the Grad-Shafranov solve succeeded (independent of EQDSK). If None, inferred from level_attempts. |
| step_error | Optional failure string (e.g. TORAX EQDSK rejection); overrides parsing the last level attempt when provided. |
| tm_loop_summary_plot | ( | tt, | |
| loop_level_log, | |||
| save_path = None, | |||
| display = True ) |
Summary figure showing per-timestep GS solve outcomes.
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
|
protected |
| dict BASE_CONFIG |
| str COLOR_TM = 'steelblue' |
| str COLOR_TX = 'crimson' |
| list COLORS_MULTI |
| int DEFAULT_LOOP0_TX_FACE_POINTS = 51 |
| int DIAG_FS = 13 |
| tuple EQDSK_SAVE_NR_NZ_SEQUENCE = (300, 900) |
| float GRID_ALPHA = 0.2 |
| int INFO_FS = 13 |
| int LABEL_FS = 11 |
| float LCFS_WEIGHT = 100.0 |
| int LEGEND_FS = 9 |
| str LS_PRI = '-' |
| str LS_SEC = '--' |
| float LW = 1.6 |
| int MK_SZ = 3 |
| str MK_TM = '.' |
| int MOVIE_DPI = 300 |
| int MOVIE_EQUIL_PSI_PLASMA_NLEVELS = 8 |
| MOVIE_FIG_H |
| MOVIE_FIG_W |
| float mu_0 = 4.0 * np.pi * 1e-7 |
| int N_PSI = 1000 |
| float PED_GRAD_WINDOW = 0.1 |
| int PED_N_SAMPLE = 24 |
| float PSI_LCFS_WEIGHT = 1000.0 |
| int TICK_FS = 10 |
| int TITLE_FS = 13 |
| str VLINE_COLOR = 'black' |
| str VLINE_LS = ':' |
| float VLINE_LW = 1.0 |