API Reference

This page provides detailed API documentation for the main FIRM3D modules and classes.

Magnetic Field Classes

Trajectory Integration

Stopping Criteria

# Note: This module may not exist yet in the current codebase # .. automodule:: simsopt.field.stopping_criteria # :members: # :undoc-members: # :show-inheritance:

Shear Alfvén Wave Classes

# Note: This module may not exist yet in the current codebase # .. automodule:: simsopt.field.shear_alfven_waves # :members: # :undoc-members: # :show-inheritance:

Utility Functions

simsopt.util.functions.print(*args, **kwargs)[source]

Overloaded print function to force flushing of stdout. All procs prints to stdout.

simsopt.util.functions.proc0_print(*args, **kwargs)[source]

Overloaded print function to force flushing of stdout. Only proc0 prints to stdout.

simsopt.util.functions.setup_logging(filename)[source]

Setup logging to redirect output to a file while maintaining console output.

This function configures Python’s logging system to write all output to both the specified file and the console. It also redirects the built-in print() function to use logging, ensuring that all print statements are captured.

Parameters:

filename (str) – The path to the log file where output will be written. The file will be opened in append mode.

Example

>>> from simsopt.util.functions import setup_logging
>>> setup_logging("my_output.log")
>>> print("This will go to both console and file")
>>> proc0_print("This will also be captured")

Plotting Utilities

simsopt.plotting.plotting_helpers.plot_trajectory_poloidal(res_ty, helicity_M=1, helicity_N=0, ax=None)[source]

Given the trajectory of a single particle in Boozer coordinates, plot in the pseudo-poloidal plane (x,y) where x = sqrt(s) cos(chi) and y = sqrt(s) sin(chi), where chi = helicity_M * theta - helicity_N * zeta. If helicity_M and helicity_N correspond with the helicity of the field-strength contours, then this plot will visualize the “banana” trajectories of trapped particles. Circles in this plane correspond with flux surfaces. The dashed circle is the initial flux surface, and the solid circle is the plasma boundary.

Parameters:
  • res_ty – A 2D numpy array of shape (nsteps, 5) containing the trajectory of a single particle in Boozer coordinates (s, theta, zeta, vpar). Tracing should be performed with forget_exact_path=False to save the trajectory information.

  • helicity_M – Helicity M value for the transformation (default: 1)

  • helicity_N – Helicity N value for the transformation (default: 0)

  • ax – Optional matplotlib Axes object to plot on. If None, a new figure and axes will be created.

Returns:

The matplotlib Axes object containing the plot.

Return type:

ax

simsopt.plotting.plotting_helpers.plot_trajectory_overhead_cyl(res_ty, field, ax=None)[source]

Given the trajectory of a single particle in Boozer coordinates, plot in the overhead cylindrical plane (X,Y) where X = R cos(phi) and Y = R sin(phi). This plot visualizes an overhead view of the particle trajectory in cylindrical coordinates. The dashed circle corresponds to the magnetic axis.

Parameters:
  • res_ty – A 2D numpy array of shape (nsteps, 5) containing the trajectory of a single particle in Boozer coordinates (s, theta, zeta, vpar).

  • field – The BoozerMagneticField instance used to set the points for the field.

  • ax – Optional matplotlib Axes object to plot on. If None, a new figure and axes will be created.

Returns:

The matplotlib Axes object containing the plot.

Return type:

ax

Core Types and Utilities

This module contains small utility functions and classes.

This module contains small utility functions and classes needed by _core subpackage.

simsopt._core.util.isbool(val)[source]

Test whether val is any boolean type, either the native python bool or numpy’s bool_.

simsopt._core.util.isnumber(val)[source]

Test whether val is any kind of number, including both native python types or numpy types.

class simsopt._core.util.Struct[source]

Bases: object

This class is just a dummy mutable object to which we can add attributes.

simsopt._core.util.unique(inlist)[source]

Given a list or tuple, return a list in which all duplicate entries have been removed. Unlike a python set, the order of entries in the original list will be preserved. There is surely a faster algorithm than the one used here, but this function will not be used in performance-critical code.

class simsopt._core.util.ImmutableId(id: Integral)[source]

Bases: object

Immutable class with a single attribute id to represent instance ids. Used in conjuction with InstanceCounterMeta metaclass to generate immutable instance ids starting with 1 for each of the different classes sublcassing InstanceCounterMeta

id: Integral
__init__(id: Integral) None
class simsopt._core.util.InstanceCounterMeta(name, bases, attrs)[source]

Bases: type

Metaclass to make instance counter not share count with descendants

Ref: https://stackoverflow.com/questions/8628123/counting-instances-of-a-class Credits: https://stackoverflow.com/users/3246302/ratiotile

__init__(name, bases, attrs)[source]
class simsopt._core.util.RegisterMeta(name, bases, attrs)[source]

Bases: type

RegisterMeta class can be used to register functions with easy to identify names.

Note

The class is not used anymore, but kept to explore the idea 3 explained below

The functionality of RegisterMeta is explained with the Spec class defined in simsopt.mhd.spec module. Spec class, which is a subclass of Optimizable, implements two functions volume and iota, which are used by child Optimizables nodes.

One could register the two functions of Spec class in a couple of ways.

  1. Spec.return_fn_map = {'volume': Spec.volume, 'iota': Spec.iota}
    
  2. Spec.volume = Spec.register_return_fn("volume")(Spec.volume)
    Spec.iota = Spec.register_return_fn("iota")(Spec.iota)
    
  3. TO BE IMPLEMENTED

    class Spec
        ...
    
        @register_return_fn("volume")
        def volume(self, ...):
            ...
    
        @register_return_fn("iota")
        def iota(self, ...):
            ...
    
__init__(name, bases, attrs)[source]
simsopt._core.util.nested_lists_to_array(ll)[source]

Convert a ragged list of lists to a 2D numpy array. Any entries that are None are replaced by 0. This routine is useful for parsing fortran namelists that include 2D arrays using f90nml.

Parameters:

ll – A list of lists to convert.

class simsopt._core.util.WeakKeyDefaultDict(default_factory=None, *args, **kwargs)[source]

Bases: WeakKeyDictionary

A simple implementation of defaultdict that uses WeakKeyDictionary as its parent class instead of standard dictionary.

__init__(default_factory=None, *args, **kwargs)[source]
simsopt._core.util.parallel_loop_bounds(comm, n)[source]

Split up an array [0, 1, …, n-1] across an mpi communicator. Example: n = 8, comm with size=2 will return (0, 4) on core 0, (4, 8) on core 1, meaning that the array is split up as [0, 1, 2, 3] + [4, 5, 6, 7].

simsopt._core.util.align_and_pad(array, alignment=64, dtype=None)[source]
simsopt._core.util.allocate_aligned_and_padded_array(shape, alignment=64, dtype=None)[source]

SAW (Shear Alfvén Wave) Module

class simsopt.saw.ae3d.EigModeASCI(sim_dir: str)[source]

Bases: object

A class to handle the parsing and storage of eigenmode data from the AE3D output ‘eig_mode_asci.dat’, which includes eigenmode descriptions, Fourier modes, radial points, and eigenvectors.

sim_dir: str
file_path: str
num_eigenmodes: int
num_fourier_modes: int
num_radial_points: int
modes: ndarray
egn_values: ndarray
s_coords: ndarray
egn_vectors: ndarray
load_data()[source]

Loads the eigenmode data from the ‘eig_mode_asci.dat’ file into the class attributes.

get_nearest_eigenvector(target_eigenvalue)[source]

Finds and returns the eigenvector closest to a specified target eigenvalue, along with its corresponding eigenvalue and sorted mode numbers.

Parameters:

target_eigenvalue (float) – The target eigenvalue to find the closest match to.

Returns:

A tuple containing the closest eigenvalue, the normalized

eigenvector, and sorted mode numbers.

Return type:

tuple

condition_number()[source]

Computes the condition number, defined as the ratio of the largest to the smallest absolute eigenvalue.

Returns:

The condition number.

Return type:

float

__init__(sim_dir: str) None
class simsopt.saw.ae3d.AE3DEigenvector(eigenvalue: float, s_coords: ndarray, harmonics: list[Harmonic])[source]

Bases: object

Stores the details of a specific eigenvector from AE3D simulations, including the eigenvalue, radial coordinates, and a detailed breakdown of harmonics with their amplitudes.

eigenvalue: float
s_coords: ndarray
harmonics: list[Harmonic]
classmethod from_eig_mode_asci(eig_mode_asci: EigModeASCI, target_eigenvalue: float)[source]

Factory method to create an AE3DEigenvector instance from an EigModeASCI data class.

Parameters:
  • eig_mode_asci (EigModeASCI) – The EigModeASCI instance to process.

  • target_eigenvalue (float) – Target eigenvalue to identify the nearest eigenvector.

Returns:

An instance containing the eigenvector data.

Return type:

AE3DEigenvector

export_to_numpy(filename: str, num_harmonics: int | None = None, resolution_step: int = 1)[source]

Exports the harmonics to a NumPy file.

Parameters:
  • filename (str) – The name of the file to export to.

  • num_harmonics (int, optional) – The number of harmonics to export. If None, all harmonics are exported.

export_to_csv(filename: str, num_harmonics: int | None = None)[source]

Export the eigenvector data to a CSV file.

Parameters:
  • filename (str) – The name of the file to export to.

  • num_harmonics (int, optional) – The number of harmonics to export. If None, all harmonics are exported.

classmethod load_from_numpy(filename: str)[source]

Loads harmonics from a NumPy file into an AE3DEigenvector instance.

Parameters:

filename (str) – The name of the file to load from.

Returns:

An instance of AE3DEigenvector with loaded data.

Return type:

AE3DEigenvector

__init__(eigenvalue: float, s_coords: ndarray, harmonics: list[Harmonic]) None
simsopt.saw.ae3d.plot_ae3d_eigenmode(mode: AE3DEigenvector, harmonics: int = 5)[source]

Creates an interactive plot of the top ‘harmonics’ number of harmonics for a given AE3DEigenvector.

Parameters:
  • mode (AE3DEigenvector) – An instance of AE3DEigenvector containing the eigenmode data to plot.

  • harmonics (int) – The number of top harmonics to plot (default is 5).

Returns:

A Plotly Figure object displaying the harmonics.

Return type:

fig

simsopt.saw.ae3d.continuum_from_ae3d(ae3d: EigModeASCI, minevalue=0.0, maxevalue=360000)[source]

Given an AE3D EigModeASCI object, this function extracts the set of eigenvalues between minevalue and maxevalue, and returns a list of ModeContinuum objects. This is used for visualization of the spectral content, which includes the continuum modes.

Parameters:
  • ae3d (EigModeASCI) – An instance of EigModeASCI containing the eigenmode data.

  • minevalue (float) – Minimum eigenvalue to consider (default is 0.0).

  • maxevalue (float) – Maximum eigenvalue to consider (default is 600**2).

Returns:

A list of ModeContinuum objects representing the modes within the specified eigenvalue range.

Return type:

List[ModeContinuum]

class simsopt.saw.stellgap.Harmonic(m: int, n: int, amplitudes: ndarray)[source]

Bases: object

Represents a harmonic in the Fourier decomposition of an eigenvector.

m

Poloidal mode number.

Type:

int

n

Toroidal mode number.

Type:

int

amplitudes

Array of amplitudes corresponding to radial points.

Type:

np.ndarray

m: int
n: int
amplitudes: ndarray
__init__(m: int, n: int, amplitudes: ndarray) None
class simsopt.saw.stellgap.ModeContinuum(m: int, n: int, s=None, freq=None)[source]

Bases: object

__init__(m: int, n: int, s=None, freq=None)[source]

Initialize a ModeContinuum instance. s and frequencies can be specified but are not necessary to initialize.

Parameters:
  • m (int) – Poloidal mode number.

  • n (int) – Toroidal mode number.

  • s (np.array, optional) – Array of flux surfaces. Defaults to None.

  • freq (np.array, optional) – Array of frequencies corresponding to the flux surfaces. Defaults to None.

Raises:

Exception – If a negative flux label is provided.

set_poloidal_mode(m: int)[source]

Set the poloidal mode number. :param m: Poloidal mode number. :type m: int

set_toroidal_mode(n: int)[source]

Set the toroidal mode number. :param n: Toroidal mode number. :type n: int

set_points(s: array, freq: array)[source]

Set the flux surfaces and frequencies. :param s: Array of flux surfaces. :type s: np.array :param freq: Array of frequencies corresponding to the flux surfaces. :type freq: np.array

get_poloidal_mode()[source]

Get the poloidal mode number.

Returns:

Poloidal mode number.

Return type:

int

get_toroidal_mode()[source]

Get the toroidal mode number. :returns: Toroidal mode number. :rtype: int

get_flux_surfaces()[source]

Get the flux surfaces.

Returns:

Array of flux surfaces.

Return type:

np.array

get_frequencies()[source]

Get the frequencies.

Returns:

Array of frequencies.

Return type:

np.array

add_point(s: float, freq: float)[source]

Add a point to the flux surfaces and frequencies. :param s: Flux surface value to add. :type s: float :param freq: Frequency value to add. :type freq: float

Raises:

Exception – If the flux surface value is negative.

class simsopt.saw.stellgap.AlfvenSpecData(filenames: list[str])[source]

Bases: ndarray

Subclass of numpy.ndarray with dtype specific to STELLGAP output in alfven_spec files.

static __new__(cls, filenames: list[str])[source]

Create a new instance of AlfvenSpecData from a list of filenames.

Parameters:

filenames (List[str]) – List of filenames containing alfven_spec data.

Returns:

An instance of AlfvenSpecData containing the loaded data.

Return type:

AlfvenSpecData

classmethod from_dir(directory: str)[source]

Load all alfven_spec data from a specified directory.

Parameters:

directory (str) – Path to the directory containing alfven_spec files.

Returns:

An instance of AlfvenSpecData containing the loaded data.

Return type:

AlfvenSpecData

nonzero_beta()[source]

Filter entries where beta is not zero.

Returns:

An instance of AlfvenSpecData containing the filtered data.

Return type:

AlfvenSpecData

sort_by_s()[source]

Sort the array based on the ‘s’ field.

Returns:

An instance of AlfvenSpecData sorted by the ‘s’ field.

Return type:

AlfvenSpecData

get_modes() list[ModeContinuum][source]

Extract modes from the AlfvenSpecData, creating ModeContinuum instances for each unique combination of poloidal (n) and toroidal (m) mode numbers.

Returns:

A list of ModeContinuum instances, each representing a unique mode with its corresponding flux surfaces (s) and frequencies.

Return type:

List[ModeContinuum]

condition_number()[source]

For each s, compute the condition number as the ratio of largest to smallest eigenvalue return the array of s and corresponding condition numbers.

Returns:

A tuple containing:
  • s (np.array): Unique flux surface values.

  • condition_numbers (np.array): Condition numbers for each unique flux surface.

Return type:

tuple

Class Hierarchy

# .. inheritance-diagram:: simsopt.field.stopping_criteria # :parts: 1

# Function Index # ————- # # .. autosummary:: # :toctree: _autosummary # :template: function.rst # :recursive: # # simsopt.field.trajectory_helpers.trace_particles_boozer # simsopt.field.trajectory_helpers.trace_particles_boozer_perturbed # simsopt.field.boozermagneticfield.BoozerAnalytic # simsopt.field.boozermagneticfield.BoozerRadialInterpolant # simsopt.field.boozermagneticfield.InterpolatedBoozerField # # Class Index # ———- # # .. autosummary:: # :toctree: _autosummary # :template: class.rst # :recursive: # # simsopt.field.boozermagneticfield.BoozerMagneticField # simsopt.field.boozermagneticfield.BoozerAnalytic # simsopt.field.boozermagneticfield.BoozerRadialInterpolant # simsopt.field.boozermagneticfield.InterpolatedBoozerField # # simsopt.field.shear_alfven_waves.ShearAlfvenHarmonic # # simsopt.field.shear_alfven_waves.ShearAlfvenWavesSuperposition # # simsopt.field.stopping_criteria.StoppingCriterion # # simsopt.field.stopping_criteria.MaxToroidalFluxStoppingCriterion # # simsopt.field.stopping_criteria.MinToroidalFluxStoppingCriterion # # simsopt.field.stopping_criteria.ZetaStoppingCriterion # # simsopt.field.stopping_criteria.VparStoppingCriterion # # simsopt.field.stopping_criteria.ToroidalTransitStoppingCriterion # # simsopt.field.stopping_criteria.IterationStoppingCriterion # # simsopt.field.stopping_criteria.StepSizeStoppingCriterion # # Module Index # ———– # # .. autosummary:: # :toctree: _autosummary # :template: module.rst # :recursive: # # simsopt.field # simsopt.field.boozermagneticfield # simsopt.field.coordinates # simsopt.field.trajectory_helpers # # simsopt.field.stopping_criteria # # simsopt.field.shear_alfven_waves # simsopt.util # simsopt.util.constants # simsopt.util.functions # simsopt.plotting # simsopt.plotting.plotting_helpers # simsopt._core # simsopt._core.types # simsopt._core.util # simsopt.saw # simsopt.saw.ae3d # simsopt.saw.stellgap