Skip to content

HELENA plugin

HELENA is a fixed boundary ideal MHD equilibrium code. The HELENA plugin provides a parser and runner for HELENA. You need a compiled HELENA executable to use this plugin. The plugin supports different input parameter types and can handle beta iteration to achieve a target normalized beta. Example configuration files can be found in the folder config/ in the helena plugin.

This module provides the HelenaRunner class, which extends the base Runner class from the enchanted-surrogates framework. It handles the execution of HELENA simulations, including various beta iteration methods to achieve target normalized beta values. The module also includes functionality for running related codes like MISHKA and performing stability checks.

The runner utilized two dataclasses for configuration and output:

  • HelenaRunnerDefaults: Defines default parameters for the runner.

  • HelenaRunnerOutput: Defines the structure of the output returned by the runner.

Configuration

A pre-compiled HELENA executable is required to use this runner. The path to the executable should be specified in the configuration file when setting up the runner. A path to a namelist file (fort.10) also needs to be provided. It serves as a base for the input file setup. The parameters that are not edited by the runner/parser will be taken from the base namelist. A minimal example:

    runner:
    type: HelenaRunner
    executable_path: "path/to/helena/executable"
    other_params:
        namelist_path: "path/to/fort.10"
        input_parameter_type: 0

Many other parameters can be configured to control the behavior of the runner, such as enabling beta iteration, pedestal width scanning, and post-processing with MISHKA and CHEASE. See the class docstring for detailed descriptions of all available parameters.

HelenaRunner

HelenaRunner(
    executable_path, other_params, *args, **kwargs
)

Bases: Runner

Runner class for executing HELENA ideal magnetohydrodynamic equilibrium simulations. This class provides comprehensive functionality for running HELENA simulations with various input parameter types, beta iteration methods, pedestal width scanning, and post-processing with MISHKA, CASTOR, and CHEASE codes.

Attributes:

Name Type Description
executable_path str

Path to the pre-compiled HELENA executable binary.

namelist_path str

Path to the HELENA namelist file containing constant parameters.

only_generate_files bool

If True, only generate input files without running HELENA.

beta_iteration int

Beta iteration mode: 0: No beta iteration 1: Iterate core temperature slope (at1) 2: Calculate at1 from Europed 3: Calculate at1 from Europed (Daniel edit) 4: Iterate fast ion pressure (afp)

beta_tolerance float

Tolerance for beta iteration convergence.

beta_n_target float

Target normalized beta value.

max_beta_iterations int

Maximum number of beta iteration attempts.

input_parameter_type int

Input parameter format: 0: EPED/MTANH profiles with direct HELENA parameters 1: Europed profiles with pedestal parameters 2: Scaling law profiles 3: No KBM constraint profiles

pedestal_width_scan bool

Enable pedestal width scanning.

run_mishka bool

Enable MISHKA stability analysis post-processing.

run_chease bool

Enable CHEASE equilibrium post-processing.

run_stability bool

Enable comprehensive stability analysis.

eigenvalue_tracing bool

Enable eigenvalue tracing for stability boundary detection.

Initialize the HelenaRunner object.

Parameters:

Name Type Description Default
executable_path str

Path to the pre-compiled HELENA executable binary.

required
other_params dict

Dictionary containing configuration parameters for the runner. See class docstring for detailed description of available parameters.

required

check_stability

check_stability(growthrates)

Evaluate stability based on growth rate values. Given a list of growthrates, check if at least one exceeds the defined stability threshold.

Parameters:

Name Type Description Default
growthrates list

List of growth rates.

required

Returns:

Name Type Description
tuple

(is_stable, max_gr) where is_stable is bool and max_gr is float.

linear_pred

linear_pred(ax, ay, bx, by, x)

Helper function for linear prediction.

Parameters:

Name Type Description Default
ax float

x-coordinate of point A

required
ay float

y-coordinate of point A

required
bx float

x-coordinate of point B

required
by float

y-coordinate of point B

required
x float

x-coordinate for which to predict y

required

Returns:

Name Type Description
float

Predicted y-coordinate.

pre_run_check

pre_run_check()

Performs pre-run checks to ensure necessary files exist before running the simulation.

Returns:

Type Description

None

Raises:

Type Description
FileNotFoundError

If the executable path or the namelist path is not found.

run_castor_for_ntors

run_castor_for_ntors(run_dir)

Execute CASTOR stability analysis using the CastorRunner for predefined toroidal mode numbers. The list of NTORs is defined in the config.

Parameters:

Name Type Description Default
run_dir str

Directory where the HELENA output is located.

required

Returns:

Type Description

None

run_chease_simulation

run_chease_simulation(run_dir)

Run CHEASE as a postprocessor to get a complete EQDSK file.

Parameters:

Name Type Description Default
run_dir str

Directory where HELENA is run.

required

Returns:

Type Description

None

run_helena

run_helena(run_dir)

Start HELENA run. Execute the HELENA binary and check for common error conditions.

Parameters:

Name Type Description Default
run_dir str

Directory where HELENA is run.

required

Returns:

Name Type Description
dict

Dictionary with 'success' and 'error' keys.

run_helena_beta_at1_iteration_until_tol

run_helena_beta_at1_iteration_until_tol(
    run_dir, beta_n_target
)

Iteratively adjust at1 until beta tolerance is met or max iterations reached. Calculate the at1 parameter for the temperature profile in order to get the correct normalized beta. Uses the Newton Method Will run helena repeatedly until the BetaN tolerance is reached or untill the max iterations is reached.

Parameters:

Name Type Description Default
run_dir str

Directory where HELENA is run.

required
beta_n_target float

Target normalized beta.

required

Returns:

Name Type Description
dict

Dictionary with 'success' and 'error' keys.

run_helena_beta_iteration_core_slope

run_helena_beta_iteration_core_slope(beta_target, run_dir)

Iteratively adjust the core temperature slope (at1) using a secant method to match a target normalized beta (beta_N).

The algorithm:

  1. Run HELENA at two initial values: at1_0 = 0.1, at1_1 = 1.0 producing: beta_N0, beta_N1

  2. Perform secant updates: at1_next = at1_1 + (beta_target - beta_N1) * (at1_1 - at1_0) / (beta_N1 - beta_N0)

  3. Repeat until: |beta_target - beta_N| < tolerance * beta_target or max iterations is reached.

Notes: - Current scaling (iscalejz) is disabled during iteration and restored at the end. - A lower bound (at1 >= 0.01) is enforced. - Iteration stops early if the beta slope becomes too small. - A final HELENA run is performed with the restored scaling.

Compared to simpler at1 iteration, this method is slower but typically achieves more accurate beta_N convergence.

Parameters:

Name Type Description Default
beta_target float

Target normalized beta.

required
run_dir str

Directory where HELENA is run.

required

Returns:

Name Type Description
dict

Dictionary with 'success' and 'error' keys.

run_helena_beta_iteration_core_slope_estimate

run_helena_beta_iteration_core_slope_estimate(
    run_dir, beta_target
)

This method reconstructs the pressure profile and iteratively adjusts the core temperature slope to reach the target beta_N, but without running HELENA multiple times. Calculation of an approximate core temperature slope. From Europed. Newton's method. Only needs to run HELENA twice.

Parameters:

Name Type Description Default
run_dir str

Directory where HELENA is run.

required
beta_target float

Target beta value.

required

Returns:

Name Type Description
dict

Dictionary with 'success' and 'error' keys.

run_helena_beta_iteration_fast_ions

run_helena_beta_iteration_fast_ions(run_dir, beta_target)

Iteratively adjust the fast-ion pressure scaling factor (apf) to match a target normalized beta (beta_N) using a secant method.

We solve the root-finding problem

f(apf) = beta_N(apf) - beta_target = 0

Algorithm:

  1. Initialization: Run HELENA at: apf_0 = 0.0, apf_1 = 1.0 obtaining: beta_N0, beta_N1

  2. Secant update: For each iteration, compute: slope = (beta_N2 - beta_N1) / (apf2 - apf1) apf_new = apf2 + (beta_target - beta_N2) / slope

  3. Stabilization (always applied):

  4. Damping: apf_new = (1 - lambda) * apf_new + lambda * apf2, with lambda = 0.3
  5. Step-size limit: |apf_new - apf2| <= 2.0

  6. HELENA evaluation: Run HELENA with apf_new to obtain beta_N_new.

  7. Convergence: Stop if: |beta_N_new - beta_target| < beta_tolerance * beta_target

Additional termination conditions: - If |beta_N2 - beta_N1| < 1e-4 (slope too small) - If beta_N_new < 1e-5 (HELENA run failure) - If max_beta_iterations is reached

Notes: - This method is more robust than simple iteration but requires multiple HELENA runs. - Damping and step-size limits improve stability for large apf updates.

Parameters:

Name Type Description Default
run_dir str

Directory where HELENA is run.

required
beta_target float

Target normalized beta.

required

Returns:

Name Type Description
dict

Dictionary with 'success' and 'error' keys.

run_mishka_for_ntors

run_mishka_for_ntors(run_dir)

Execute MISHKA stability analysis using the MishkaRunner for predefined toroidal mode numbers. The list of NTORs is defined in the config.

Parameters:

Name Type Description Default
run_dir str

Directory where the HELENA output is located.

required

Returns:

Type Description

None

run_stability_for_ntors

run_stability_for_ntors(run_dir, vshift_guesses=None)

Calculate the MHD stability with MISHKA or CASTOR or both.

Parameters:

Name Type Description Default
run_dir str

Directory where the HELENA output is located.

required
vshift_guesses dict

Optional guesses for vshift.

None

Returns:

Name Type Description
dict dict

Dictionary containing stability results.

scan_pedestal_width

scan_pedestal_width(
    run_dir, beta_target, d_ped_scans, params
)

Scan over pedestal width values (d_ped) and evaluate equilibrium and stability for each case.

For each value in d_ped_scans, a separate run directory is created and a HELENA equilibrium is computed with the pedestal width updated accordingly. Optionally, a beta iteration is performed to match a target normalized beta (beta_N), and MISHKA can be run to compute growth rates.

Parameters:

Name Type Description Default
run_dir str

Base directory containing the initial HELENA input files. New scan directories are created relative to this path.

required
beta_target float

Target normalized beta (beta_N) used if beta iteration is enabled.

required
d_ped_scans list

List of pedestal width values to scan.

required
params dict

Dictionary of parameters passed to the summary writer.

required

Returns:

Name Type Description
list

A list of results for each successful scan: (index, d_ped_value, growthrates). where: - index : int Index of the scan point - d_ped_value : float Pedestal width used in that run - growthrates : list Growth rates from MISHKA (empty if not computed)

scan_pedestal_width_binarysearch

scan_pedestal_width_binarysearch(
    run_dir, beta_target, params
)

Perform a randomized binary search over pedestal width (d_ped) to identify points near the stability boundary. The search is not a strict binary search; it uses randomized sampling within progressively shrinking bounds.

This method iteratively samples pedestal widths within a shrinking interval, guided by MISHKA stability results, until both stable and unstable equilibria are identified or a maximum number of iterations is reached.

Algorithm
  1. Initialization:
  2. Define search bounds [min_width, max_width] from configuration.
  3. Start from an initial pedestal width (params["pedestal_delta"]).
  4. Initialize flags to track whether stable and unstable equilibria have been found.

  5. Iterative sampling: For each iteration:

  6. Create a new run directory (except for the first iteration).
  7. Update the pedestal width in HELENA input files.
  8. Run HELENA:
    • If beta_iteration == 1: use core slope iteration
    • If beta_iteration == 2: use estimated core slope iteration
    • Otherwise: run HELENA once
  9. Generate a summary and clean output files.

  10. Stability evaluation (requires MISHKA):

  11. If the equilibrium is successfully computed:

    • Run MISHKA and collect growth rates.
    • Determine stability using check_stability.
    • Store (d_ped, max_growth_rate).
    • Update search bounds:
      • If stable: set min_width = d_ped
      • If unstable: set max_width = d_ped
  12. Randomized interval update:

  13. Sample the next pedestal width uniformly: d_ped ~ U(min_width, max_width)

  14. Termination:

  15. Stop when both stable and unstable equilibria are found, or
  16. Maximum number of iterations is reached.

  17. Final refinement:

  18. If both stable and unstable points were found:
    • Identify two widths with growth rates closest to a target threshold (gr_target = 0.03), one below and one above.
    • Run a final simulation at their midpoint.
    • Recompute equilibrium and growth rates for improved resolution near the stability boundary.

Parameters:

Name Type Description Default
run_dir str

Base directory containing the initial HELENA input files.

required
beta_target float

Target normalized beta (beta_N) used in HELENA runs when beta iteration is enabled.

required
params dict

Dictionary of input parameters, must include initial pedestal_delta.

required

Returns:

Name Type Description
list

List of scan results for each iteration: (iteration_index, d_ped_value, growthrates).

single_code_run

single_code_run(run_dir, params=None)

Main entry point for running HELENA simulation with all configured options.

Parameters:

Name Type Description Default
run_dir str

Directory where HELENA is run.

required
params dict

Dictionary containing parameters for the simulation.

None

Returns:

Name Type Description
dict dict

Dictionary containing the results of the simulation.

trace_eigenvalues

trace_eigenvalues(run_dir, params, beta_target)

Run CASTOR over a number of pedestal widths. Use the eigenvalue from the previous run as input. Use the eigenvalue from MISHKA as input to CASTOR. NB MISHKA return gamma^2 and CASTOR returns gamma.

Parameters:

Name Type Description Default
run_dir str

Directory where HELENA is run.

required
params dict

Dictionary containing parameters.

required
beta_target float

Target beta value.

required

Returns:

Type Description

None

HelenaRunnerDefaults dataclass

HelenaRunnerDefaults(
    namelist_path=None,
    only_generate_files=False,
    beta_iteration=0,
    beta_tolerance=0.01,
    beta_n_target=None,
    max_beta_iterations=6,
    input_parameter_type=0,
    pedestal_width_scan=False,
    pedestal_width_scan_params=(
        lambda: {
            "min_width": 0.02,
            "max_width": 0.06,
            "max_iterations": 5,
        }
    )(),
    pedestal_width_sampling_method=1,
    constant_params=dict(),
    run_chease=False,
    chease_eqdsktochease_pyscript_path=None,
    chease_namelist_path=None,
    chease_executables_dir=None,
    run_stability=False,
    eigenvalue_tracing=False,
    mishka=(
        lambda: {
            "run_mishka": False,
            "executable_path": None,
            "ntor": None,
            "iterations": 20,
            "random_ntor": 0,
            "random_ntor_bounds": [],
            "other_params": {},
        }
    )(),
    castor=(
        lambda: {
            "run_castor": False,
            "executable_path": None,
            "ntor": None,
            "iterations": None,
            "other_params": {},
        }
    )(),
)

A dataclass holding the default values for the HelenaRunner.

HelenaRunnerOutput dataclass

HelenaRunnerOutput(
    success=False,
    error="",
    start_time=str(datetime.now()),
    end_time=None,
    helena_dir=None,
    helena_error="",
    max_growthrate_mishka=None,
    max_growthrate_castor=None,
)

A dataclass holding the values returned by the HelenaRunner.

biased_spaced_random

biased_spaced_random(
    x,
    low=1,
    high=50,
    min_dist=2,
    bias_until=20,
    bias_factor=3,
)

Generate x random integers between low and high with a minimum distance of min_dist between any two numbers. The function gives higher weight to numbers less than or equal to bias_until by multiplying their selection probability by bias_factor. The selection is done using weighted random sampling, and the available numbers are updated after each selection to maintain the minimum distance constraint.

Parameters:

Name Type Description Default
x int

Number of random integers to generate.

required
low int

Lower bound of the range (inclusive).

1
high int

Upper bound of the range (inclusive).

50
min_dist int

Minimum distance required between any two selected numbers.

2
bias_until int

Numbers less than or equal to this value receive higher weight.

20
bias_factor int

Factor by which to increase the weight of numbers <= bias_until.

3

Returns:

Name Type Description
list

List of selected random integers.

merge_params

merge_params(defaults, user)

Return a new HelenaRunnerDefaults object with user overrides applied.

Parameters:

Name Type Description Default
defaults HelenaRunnerDefaults

Default configuration object.

required
user dict

User-provided overrides.

required

Returns:

Name Type Description
HelenaRunnerDefaults HelenaRunnerDefaults

Merged configuration object.

weight

weight(n)

Weight function that gives higher weight to numbers <= 20.

Parameters:

Name Type Description Default
n int

Input number.

required

Returns:

Name Type Description
int

Weight value.

HelenaParser

HelenaParser()

Bases: Parser

An I/O parser for HELENA.

calculate_alpha

calculate_alpha(psi, volume, pressure, r=2.9)

Calculate the pressure gradient alpha parameter.

Parameters:

Name Type Description Default
psi array_like

Psi coordinate values.

required
volume array_like

Volume values corresponding to psi.

required
pressure array_like

Pressure values corresponding to psi.

required
r float

Reference major radius in meters.

2.9

Returns:

Name Type Description
ndarray

Alpha parameter values computed from the gradients.

clean_output_files

clean_output_files(run_dir)

Removes unnecessary files except for fort.10, fort.20, and fort.12. (fort.30 is an input-output file which can be useful)

Parameters:

Name Type Description Default
run_dir str

Path to the run directory.

required

Returns:

Type Description

None

europed_tanh_profile

europed_tanh_profile(
    psi,
    psi_mid,
    psi_ped,
    a_0,
    a_1,
    sep,
    alpha_1,
    alpha_2,
    delta,
)

Calculates the Europed tanh profile for temperature and density profiles.

Parameters:

Name Type Description Default
psi float

Psi value.

required
psi_mid float

Mid psi value.

required
psi_ped float

Pedestal psi value.

required
a_0 float

Coefficient a_0.

required
a_1 float

Coefficient a_1.

required
sep float

Separatrix value.

required
alpha_1 float

Alpha 1 value.

required
alpha_2 float

Alpha 2 value.

required
delta float

Delta value.

required

Returns:

Name Type Description
float

Calculated tanh profile value.

extract_resistivity

extract_resistivity(run_dir, resistivity_type='spitzer')

author = "Hampus Nyström"

Parameters:

Name Type Description Default
run_dir str

Path to the HELENA output directory containing fort.20.

required
resistivity_type str

Type of resistivity to extract. Options are "spitzer" and "neoclassical".

'spitzer'

Returns:

Name Type Description
ndarray

Normalized resistivity values computed from the HELENA output.

Notes

The output file fort.14 is written to the same directory, and the resistivity data is also saved in numpy format as resistivity.npy.

find_max_and_outermost_jphi

find_max_and_outermost_jphi(filepath, namelist)

Find max J_phi, J_phi of the last radial point, and from HELENA output file.

Parameters:

Name Type Description Default
filepath str

Path to the HELENA output file.

required
namelist dict

Namelist dictionary containing physical

required

Returns:

Name Type Description
float

Maximum normalized j_phi value.

find_new_at1

find_new_at1(output_dir, beta_target, h)

Use a Newton method to find the next at1 value for a HELENA output.

Parameters:

Name Type Description Default
output_dir str

Path to the HELENA output directory.

required
beta_target float

Target normalized beta value.

required
h float

Step size used in finite-difference derivative estimation.

required

Returns:

Name Type Description
float

Updated at1 value.

get_betapolped

get_betapolped(pedestal_delta)

Poloidal beta at the pedestal depends on the pedestal width according to the KBM constraint.

Parameters:

Name Type Description Default
pedestal_delta float

Pedestal width.

required

Returns:

Name Type Description
float

Poloidal beta at the pedestal.

get_bt_from_ip

get_bt_from_ip(ip)

y = a*x + b where a and b are fit to the JET pedestal database.

Parameters:

Name Type Description Default
ip float

Plasma current.

required

Returns:

Name Type Description
ndarray

Toroidal magnetic field.

get_circumference

get_circumference(theta, ellip, tria, quad, rvac, a)

Calculate the circumference of the parametrised shape.

Parameters:

Name Type Description Default
theta array

Array of poloidal angles.

required
ellip float

Ellipticity.

required
tria float

Triangularity.

required
quad float

Squareness.

required
rvac float

Vacuum radius.

required
a float

Minor radius.

required

Returns:

Name Type Description
float

The circumference of the shape.

get_delta_ne_eped_from_namelist

get_delta_ne_eped_from_namelist(namelist)

Get the density pedestal delta from a HELENA namelist.

Parameters:

Name Type Description Default
namelist dict

HELENA namelist dictionary.

required

Returns:

Type Description

float or None: Pedestal delta for density, or None if IDETE is unsupported.

get_delta_te_eped_from_namelist

get_delta_te_eped_from_namelist(namelist)

Get the electron pedestal delta from a HELENA namelist.

Parameters:

Name Type Description Default
namelist dict

HELENA namelist dictionary.

required

Returns:

Type Description

float or None: Pedestal delta for electron temperature, or None if IDETE is unsupported.

get_europed_profiles

get_europed_profiles(run_dir)

Retrieves Europed electron density and temperature profiles from the output file fort.10.

Parameters:

Name Type Description Default
run_dir str

Path to the run directory.

required

Returns:

Name Type Description
tuple

Tuple containing electron density profile and electron

temperature profile.

get_ip_and_btor_from_q95

get_ip_and_btor_from_q95(
    d_ped,
    teped,
    circumference,
    neped,
    q95,
    major_R,
    minor_a,
    tesep=0.1,
    zimp=4.0,
    zeff=1.2,
    z_main_ion=1.0,
)

Calculate Ip and Btor based on q95.

Parameters:

Name Type Description Default
d_ped float

Pedestal width.

required
teped float

Pedestal electron temperature.

required
circumference float

Plasma circumference.

required
neped float

Pedestal electron density.

required
q95 float

Safety factor at 95% flux.

required
major_R float

Major radius.

required
minor_a float

Minor radius.

required
tesep float

Separatrix electron temperature.

0.1
zimp float

Impurity charge.

4.0
zeff float

Effective charge.

1.2
z_main_ion float

Main ion charge.

1.0

Returns:

Name Type Description
tuple

(ip, btor) where ip is plasma current and btor is toroidal magnetic field.

get_ip_from_namelist

get_ip_from_namelist(namelist)

Helper function to get ip from namelist.

Parameters:

Name Type Description Default
namelist dict

Namelist dictionary.

required

Returns:

Name Type Description
float

Plasma current ip.

get_ip_from_teped

get_ip_from_teped(
    d_ped,
    teped,
    circumference,
    neped,
    tesep=0.1,
    zimp=4.0,
    zeff=1.2,
    z_main_ion=1.0,
)

Calculate Ip based on T_eped.

Parameters:

Name Type Description Default
d_ped float

Pedestal width.

required
teped float

Pedestal electron temperature.

required
circumference float

Plasma circumference.

required
neped float

Pedestal electron density.

required
tesep float

Separatrix electron temperature.

0.1
zimp float

Impurity charge.

4.0
zeff float

Effective charge.

1.2
z_main_ion float

Main ion charge.

1.0

Returns:

Name Type Description
float

Plasma current Ip.

get_ip_from_xiab

get_ip_from_xiab(xiab, bvac, eps, rvac)

Current value from normalized current.

Parameters:

Name Type Description Default
xiab float

Normalized current.

required
bvac float

Vacuum magnetic field.

required
eps float

Inverse aspect ratio.

required
rvac float

Vacuum radius.

required

Returns:

Name Type Description
float

Plasma current ip.

get_neped_from_namelist

get_neped_from_namelist(namelist)

Get the pedestal density from a HELENA namelist.

Parameters:

Name Type Description Default
namelist dict

HELENA namelist dictionary.

required

Returns:

Name Type Description
float

Pedestal density neped computed from electron density profile parameters.

get_polar_from_rz

get_polar_from_rz(r_vals, z_vals, symmetric=False)

Convert (R, Z) boundary coordinates to polar coordinates (rho, theta) relative to the boundary center (r0, z0).

Handles both symmetric and asymmetric boundaries:

  • If symmetric (self.symmetric=True): input contains only the top half, and the function mirrors it to produce a full 0-2Ï€ contour.

  • If asymmetric: uses the full input directly.

Parameters:

Name Type Description Default
r_vals array_like

R (major radius) coordinates of the boundary.

required
z_vals array_like

Z (vertical) coordinates of the boundary.

required
symmetric bool

Whether the boundary is symmetric.

False

Returns:

Name Type Description
tuple

(rho, theta) where rho is normalized radius and theta is

poloidal angle.

get_q_from_fort20

get_q_from_fort20(run_dir)

Parser file fort.20 to get q on axis and at the boundary.

get_real_world_geometry_factors_from_f20

get_real_world_geometry_factors_from_f20(f20_fort)

Function copy paste from tokamak_sampler by A. Kit Get Geometry factors from fort.20

The first loop is looking for $PHYS EPS = 0.320, ALFA = 2.438, B = 0.006, C = 1.000, XIAB = 1.350, BETAP = -1.0000,COREP = 43259.3989

The second loop is looking for MAJOR RADIUS : 2.9031 [m] MAGNETIC FIELD : 1.9891 [T] TOTAL CURRENT : 1982.873 [kA] RADIUS (a) : 0.9277 [m] PSI ON BOUNDARY : 0.7022 [Wb/rad] CENTRAL DENSITY : 1.0000 10^19 [m^-3] ZEFF : 1.1372 TE/(TE+TI) : 0.5000

Parameters:

Name Type Description Default
f20_fort str

Path to the fort.20 file

required

Returns:

Name Type Description
dict

Dictionary with parameter names below:

Read

BVAC, RVAC, EPS, XAXIS, CPSURF, ALFA, BETAP, BETAT, BETAN, XIAB

Derived

RADIUS (minor radius), RMAGAXIS, CURRENT

  • XIAB: normalized total current: XIAB = MU0 I / (aB0)) -> CURRENT = (XIAB / MU0) * (aB0)

get_relevant_data_from_f12_f10

get_relevant_data_from_f12_f10(run_dir)

By Adam. Get profiles rescaled.

get_teped

get_teped(
    d_ped,
    ip,
    circumference,
    neped,
    tesep=0.1,
    zimp=4.0,
    zeff=1.2,
    z_main_ion=1.0,
)

Calculate teped according to the KBM constraint.

Parameters:

Name Type Description Default
d_ped float

Pedestal width.

required
ip float

Plasma current.

required
circumference float

Plasma circumference.

required
neped float

Pedestal electron density.

required
tesep float

Separatrix electron temperature.

0.1
zimp float

Impurity charge.

4.0
zeff float

Effective charge.

1.2
z_main_ion float

Main ion charge.

1.0

Returns:

Name Type Description
float

Pedestal electron temperature.

get_teped_from_namelist

get_teped_from_namelist(namelist)

Get the pedestal temperature from a HELENA namelist.

Parameters:

Name Type Description Default
namelist dict

HELENA namelist dictionary.

required

Returns:

Name Type Description
float

Pedestal temperature teped computed from electron temperature and separatrix temperature.

get_xiab_from_ip

get_xiab_from_ip(ip, bvac, eps, rvac)

Normalized current value from current.

Parameters:

Name Type Description Default
ip float

Plasma current.

required
bvac float

Vacuum magnetic field.

required
eps float

Inverse aspect ratio.

required
rvac float

Vacuum radius.

required

Returns:

Name Type Description
float

Normalized current xiab.

hel2eqdsk

hel2eqdsk(helena_output_dir, eqdsk_output_path, NR, NZ)

Convert HELENA output into an EQDSK-format file and write it to disk.

Parameters:

Name Type Description Default
helena_output_dir str

Directory containing HELENA output files.

required
eqdsk_output_path str

Path to the generated EQDSK output file.

required
NR int

Number of radial grid points in the EQDSK grid.

required
NZ int

Number of vertical grid points in the EQDSK grid.

required

Returns:

Type Description
None

None

interpolate_psi_profile

interpolate_psi_profile(x_0, y_0, x_1)

Interpolate profile values at new psi locations.

Parameters:

Name Type Description Default
x_0 array_like

Original psi coordinate locations.

required
y_0 array_like

Values corresponding to x_0.

required
x_1 array_like

New psi locations to interpolate.

required

Returns:

Name Type Description
ndarray

Interpolated values at x_1.

make_init_zjz_profile

make_init_zjz_profile(
    pedestal_delta,
    npts,
    pzjzmultip=0.5,
    max_pres_grad_loc=0.97,
)

Makes the initial ZJZ profile based on the pressure profile according to Europed implementation.

Parameters:

Name Type Description Default
pedestal_delta float

Pedestal delta value.

required
npts int

Number of points.

required
pzjzmultip float

ZJZ multiplier.

0.5
max_pres_grad_loc float

Location of maximum pressure gradient.

0.97

Returns:

Name Type Description
array_like

Array representing the initial ZJZ profile.

modify_at1

modify_at1(namelist_path, at1_mult)

Changes the core temperature (cte & cti) value in the input file fort.10.

Parameters:

Name Type Description Default
namelist_path str

Path to the namelist file.

required
at1_mult float

Multiplier for the core temperature value in the parameterized core profile.

required

Returns:

Type Description

None

Raises:

Type Description
FileNotFoundError

If the specified run directory is not found.

modify_fast_ion_pressure

modify_fast_ion_pressure(namelist_path, apf, iteration=0)

Changes the fast ion pressure (apf) value in the input file fort.10.

Parameters:

Name Type Description Default
namelist_path str

Path to the namelist file.

required
apf float

Value for the fast ion pressure parameter.

required
iteration int

Iteration number for backup files.

0

Returns:

Type Description

None

Raises:

Type Description
FileNotFoundError

If the specified run directory is not found.

namelist_to_lowercase_with_defualt_values

namelist_to_lowercase_with_defualt_values(
    namelist, default_namelist
)

Convert a HELENA namelist to lower-case keys and apply default values.

Parameters:

Name Type Description Default
namelist dict

Input namelist dictionary.

required
default_namelist dict

Default namelist dictionary to use for missing keys.

required

Returns:

Type Description

f90nml.Namelist: New namelist with lower-case key names and default values applied.

read_alphamax_from_fort20

read_alphamax_from_fort20(filepath, profile_delta)

From Europed. TODO: rewrite

read_eliteinput

read_eliteinput(filepath)

Reads the following parameters: 1D: Psi, dp/dpsi, d2p/dpsi, fpol, ffp, dffp, q, ne, dne/dpsi, Te, dTe/dpsi, Ti, dTi/dpsi, nMainIon, nZ 2D: R, z, Bp Calculates PsiN from Psi returns dictionary with above keys

read_final_zjz

read_final_zjz(output_dir)

zjz( 1)= 1.00000, zjz( 2)= 1.01337, zjz( 3)= 0.83545,

read_fort20_NUM

read_fort20_NUM(output_dir)

Find the numerical parameters

Returns NR: number of radial grid points NP: number of poloidal grid points NRMAP: number of radial grid points in mapping to flux surface grid (should be 2NR) NPMAP: number of poloidal grid points in mapping (should be 2NP) NCHI: number of poloidal grid points written to output file (should be 2*NMAP, NCHI must be 2^n + 1) NRCUR: number of radial grid points for iteration current profile (should be NR) NPCUR: number of poloidal grid points (should be NP) NITER: (ICUR≠0) or 1 (ICUR=0) maximum number of iterations over current profile

read_fort20_beta_section

read_fort20_beta_section(output_dir)

MAGNETIC AXIS : 0.01908 0.00000 POLOIDAL BETA : 0.1198E+00 TOROIDAL BETA : 0.3802E-02 BETA STAR : 0.4250E-02 NORM. BETA : 0.00335 TOTAL CURRENT : 0.1428E+01 TOTAL AREA : 0.5115E+01 TOTAL VOLUME : 0.3110E+02 INT. INDUCTANCE : 0.685990E+00 POL. FLUX : 0.2130E+01 A,B,C : 0.4176E+01 0.1522E-01 0.1000E+01


read_fort20_inputprofiles

read_fort20_inputprofiles(output_dir, nrmap)

  • INPUT PROFILES : *

  • PSI, dP/dPSI, FdF/dPSI, J_phi *

0.0000E+00 0.0000E+00 0.1000E+01 0.1000E+01 0.1000E-01 0.1940E+01 0.1000E+01 0.9789E+00 0.2000E-01 0.2193E+01 0.1000E+01 0.9573E+00 ...

read_fort20_realworld

read_fort20_realworld(output_dir)

S,   P [Pa], Ne [10^19m^-3], Te [eV],  Ti [eV],

read_fort20_s_j_vol_area

read_fort20_s_j_vol_area(output_dir)

  • I PSI S ERROR LENGTH BUSSAC VOL VOLP AREA *

300 0.000159 0.012600 1.0029 3.95E-03 0.0809 0.0035 0.0032 19.9232 0.0005 299 0.000635 0.025200 1.0115 1.58E-02 0.1614 0.0137 0.0126 19.7961 0.0020

read_fortran_ascii

read_fortran_ascii(file_path, keywords, N)

Reads data from a Fortran ASCII file and extracts arrays following specified keywords.

Parameters:

Name Type Description Default
file_path str

Path to the ASCII file.

required
keywords list of str

List of strings to search for in the file.

required
N int

Number of floats to extract for each keyword.

required

Returns:

Name Type Description
dict dict[str, ndarray]

A dictionary where keys are keywords and values are 1D NumPy arrays of floats.

read_fortran_repeated_arrays

read_fortran_repeated_arrays(file_path, keywords, N, M)

Reads data from a Fortran ASCII file and extracts repeated arrays of length N following a keyword.

Parameters:

Name Type Description Default
file_path str

Path to the ASCII file.

required
keyword str

String to search for in the file to start reading data.

required
N int

Number of floats in each array.

required
M int

Number of arrays of length N to extract.

required

Returns:

Type Description
dict[str, ndarray]

np.ndarray: A 2D NumPy array of shape (M, N) containing the extracted data.

read_helena_fort12

read_helena_fort12(
    fort_12_file,
    B0=1.0,
    RVAC=2.9043,
    CPSURF=0.7022,
    RADIUS=0.9269,
)

Reads the mapping file for MISHKA produced by HELENA.

  • B0 is the on axis toroidal field strength (B_m below)
  • Rvac is vaccum geometric radius [Rvac below]
  • CPSURF is the poloidal flux on the surface of the plasma
  • RADIUS is the minor radius of the plasma

NOTE: the P0_SCALED matches that of fort.20 real world output

From toon's PB3D !! The variales in the HELENA mapping file are globalized in two ways: !! - X and Y are normalized w.r.t. vacuum geometric axis \c R_vac and !! toroidal field at the geometric axis \c B_vac. !! - R[m] = R_vac[m] (1 + eps X[]) , !! - Z[m] = R_vac[m] eps Y[] . !! !! The covariant toroidal field \c F_H, \c pres_H and poloidal flux are !! normalized w.r.t magnetic axis \c R_m and total toroidal field at !! magnetic axis \c B_m: !! - RBphi[Tm] = F_H[] R_m[m] B_m[T] , !! - pres[N/m^2] = pres_H[] (B_m[T])^2/MU0[N/A^2] , !! - flux_p[Tm^2] = 2pi (s[])^2 cpsurf[] B_m[T] (R_m[m])^2 .

The result of the mapping is a dictionary with the following keys: - CS: 1D array of floats, the flux coordinate - QS: 1D array of floats, the safety factor - DQS: 1D array of floats, the safety factor gradient - DQEC: float, the safety factor gradient at the edge - CURJ: 1D array of floats, the current density - DJ0: float, the current density at the edge - DJE: float, the current density at the edge - CHI: 1D array of floats, the chi values - GEM11: 2D array of floats, the mapping matrix - GEM12: 2D array of floats, the mapping matrix - GEM33: 2D array of floats, the mapping matrix - CPSURF: float, the poloidal flux on the surface of the plasma - RADIUS: float, the minor radius - RAXIS: float, the major radius of the plasma - P0: 1D array of floats, the pressure - DP0: float, the pressure gradient - DPE: float, the pressure gradient at the edge - RBPHI: 1D array of floats, the toroidal field flux function (F) - DRBPHI0: float, the toroidal field flux function gradient at the axis - DRBPHIE: float, the toroidal field flux function gradient at the edge - VX: 1D array of floats, the r on the surface - VY: 1D array of floats, the z on the surface - EPS: float, the inverse aspect ratio - XOUT: 2D array of floats, the r mapping - YOUT: 2D array of floats, the z mapping - XOUT_SCALED: 2D array of floats, the scaled r mapping - YOUT_SCALED: 2D array of floats, the scaled z mapping - CS_SCALED: 1D array of floats, the scaled flux coordinate - P0_SCALED: 1D array of floats, the scaled pressure -> NB: If the file contains B0, then the pressure scaled with that instead of what is passed above

read_helena_output_fort12

read_helena_output_fort12(run_dir)

USE THIS ONE FOR FORT.12 Read the HELENA output file fort.12 which is used as input by MISHKA.

read_helena_output_fort12_old

read_helena_output_fort12_old(filename)

USE THIS ONE FOR FORT.12 Read the HELENA output file fort.12 which is used as input by MISHKA.

read_output_file

read_output_file(run_dir)

Reads the main output file fort.20. Crashed: if 'ALPHA1' is not found or 'MERCIER' is not found.

Mercier stability Ballooning stability NeoClassical Stability Condition

Parameters:

Name Type Description Default
run_dir str

Path to the run directory.

required

Returns:

Name Type Description
tuple

A tuple indicating success (bool),

Mercier criterion presence (bool),

and ballooning criterion presence (bool).

read_output_fort12

read_output_fort12(output_dir)

Read the output file fort.12 which is used as input by MISHKA.

JS0: NRMAP - 1 CS: sqrt(psi) QS: DQS_1, DQEC DQS: derivative of QS CURJ DJ0, DJE NCHI: number of poloidal grid points written to output file CHI GEM11 GEM12 CPSURF, RADIUS GEM33 RAXIS P0 DP0, DPE RBPHI DRBPHI0, DRBPHIE VX, VY EPS

shape_function

shape_function(theta, ellip, tria, quad, rvac, a)

EUROPED returns the R and Z values given the boundary parameters (HELENA equation 11) ellip = ellipticity (input) tria = triangularity (input) quad = squareness (input) theta = the poloidal angle, can be a vector or a scalar (input)

Parameters:

Name Type Description Default
theta float or array

The poloidal angle.

required
ellip float

Ellipticity.

required
tria float

Triangularity.

required
quad float

Squareness.

required
rvac float

Vacuum radius.

required
a float

Minor radius.

required

Returns:

Name Type Description
tuple

(r, z) where r and z are arrays of R and Z coordinates.

update_at1

update_at1(namelist_path, at1)

Changes the core temperature (cte & cti) value in the input file fort.10.

Parameters:

Name Type Description Default
namelist_path str

Path to the namelist file.

required
at1 float

Multiplier for the core temperature value in the parameterized core

required

Raises:

Type Description
FileNotFoundError

If the specified run directory is not found.

update_pedestal_delta

update_pedestal_delta(
    new_pedestal_delta, beta_target, run_dir, scan_dir
)

Update HELENA namelist parameters for a new pedestal delta.

Parameters:

Name Type Description Default
new_pedestal_delta float

New pedestal delta value.

required
beta_target float

Target normalized beta value.

required
run_dir str

Directory containing the original HELENA run files.

required
scan_dir str

Directory to write the updated fort.10 file.

required

Returns:

Type Description

None

write_input_file

write_input_file(params, run_dir, namelist_path)

Writes input file fort.10. The sample parameters should be directly from the HELENA fort.10 file.

Parameters:

Name Type Description Default
params dict

Dictionary containing input parameters.

required
run_dir str

Path to the run directory.

required
namelist_path str

Path to the namelist file.

required

Returns:

Name Type Description
dict

Dictionary with 'success' and 'error' keys.

Raises:

Type Description
FileNotFoundError

If the specified run directory is not found.

write_input_file_europed

write_input_file_europed(params, run_dir, namelist_path)

Writes input file fort.10.

Parameters:

Name Type Description Default
params dict

Dictionary containing input parameters.

required
run_dir str

Path to the run directory.

required
namelist_path str

Path to the namelist file.

required

Returns:

Name Type Description
dict

Dictionary with 'success' and 'error' keys.

Raises:

Type Description
FileNotFoundError

If the specified run directory is not found.

write_input_file_europed2

write_input_file_europed2(
    params, run_dir, namelist_path, constant_params
)

Writes input file fort.10. Assuming IDETE = 7.

In config

"input_parameter_type": 3

Parameters needed
  • pedestal_delta
  • ip
  • bvac

Optional - n_eped - n_esep - T_esep = 0.1

Parameters:

Name Type Description Default
params dict

Dictionary containing input parameters.

required
run_dir str

Path to the run directory.

required
namelist_path str

Path to the namelist file.

required
constant_params dict

Dictionary containing constant parameters.

required

Returns:

Name Type Description
dict

Dictionary with 'success' and 'error' keys.

Raises:

Type Description
FileNotFoundError

If the specified run directory is not found.

write_input_file_noKBMconstraint

write_input_file_noKBMconstraint(
    params, run_dir, namelist_path, idete=None
)

Writes input file fort.10. In config: "input_parameter_type": 4

The function inherits the setup provided in the basenamelist, given by the namelist_path. Parameters that this function presently expects to be given are - d_n_ped - Pedestal density width - d_T_ped - Pedestal temperature width - T_eped - Pedestal top temperature Other parameters that user very likely is interested in giving are - n_eped - Pedestal top electron density - n_esep - Separatrix electron density - density_shift - Relative shift between the electron density and temperature pedestals

Parameters:

Name Type Description Default
params dict

Dictionary containing input parameters.

required
run_dir str

Path to the run directory.

required
namelist_path str

Path to the namelist file.

required
idete int

Optional IDETE value.

None

Returns:

Name Type Description
dict

Dictionary with 'success' and 'error' keys.

Raises:

Type Description
FileNotFoundError

If the specified run directory is not found.

write_input_file_scaling

write_input_file_scaling(params, run_dir, namelist_path)

Writes input file fort.10. 2: using a scaling law for changing ATE and CTE, requires input parameter "scaling_factor"

Parameters:

Name Type Description Default
params dict

Dictionary containing input parameters.

required
run_dir str

Path to the run directory.

required
namelist_path str

Path to the namelist file.

required

Returns:

Name Type Description
dict

Dictionary with 'success' and 'error' keys.

Raises:

Type Description
FileNotFoundError

If the specified run directory is not found.

write_iterbd_profiles

write_iterbd_profiles(
    helena_output_dir, iterdb_output_path
)

Write an ITERDB file from HELENA elite input data.

Parameters:

Name Type Description Default
helena_output_dir str

Directory containing HELENA output files.

required
iterdb_output_path str

Path to the generated ITERDB file.

required

Returns:

Type Description
None

None

write_summary

write_summary(run_dir, params)

Generates a summary file with run directory and parameters, along with success and stability criteria.

Parameters:

Name Type Description Default
run_dir str

Path to the run directory.

required
params dict

Dictionary containing input parameters.

required

Returns:

Name Type Description
dict

Summary dictionary containing run directory, parameters,

success status, Mercier criterion presence, and ballooning

criterion presence.