utils

Helper classes for the ingrid module and topologies package.

This module contains classes IngridUtils and TopologyUtils. These classes encapsulate much of the critical methods for handling file I/O, topology analysis, generating patch maps, and generating grids.

class INGRID.utils.IngridUtils(settings: dict = {}, **kwargs)

Bases: object

The base class for ingrid.Ingrid that handles backend management of key Ingrid capabilities. This class can be directly utilized by advanced users and developers of the Ingrid code.

Class IngridUtils encapsulates implementation details of file I/O, keyword parsing, sorting of geometry, and managing of other helper classes such as line_tracing.LineTracing and interpol.EfitData.

Parameters
  • settings (optional) – Dictionary representation of the settings file. The dictionary is obtained via a YAML dump while operating in gui mode. Providing no dictionary will populate the Ingrid object with a default value settings attribute. Any missing entries provided by a user will be populated with default values by Ingrid. (Refer to the Ingrid “Settings File Format” for a complete descri ption of the settings dictionary)

  • **kwargs – Keyword arguments for processing of input data. (See method ‘ProcessKeywords’ in class ‘IngridUtils’ for a list of supported keywords)

Variables
  • InputFile (str) – Path to the parameter file.

  • config (str) – The configuration of the topology.

  • settings (dict) – Core settings dictionary containing all data used for generating patches and grids.

  • settings_lookup (dict) – Top level entries of the parameter file and convenience attribute for later accessing of entries.

  • default_values_lookup (dict) – General structure of YAML settings file in dictionary form.

  • default_grid_settings (dict) – Default entries for key grid_settings in the YAML settings file.

  • default_integrator_settings (dict) – Default entries for key integrator_settings in the YAML settings file.

  • default_target_plate_settings (dict) – Default entries for key target_plates in the YAML settings file.

  • default_limiter_settings (dict) – Default entries for key limiter in the YAML settings file.

  • default_patch_data_settings (dict) – Default entries for key patch_data in the YAML settings file.

  • default_DEBUG_settings (dict) – Default entries for key DEBUG in the YAML settings file.

  • PlateData (dict) – Dictionary containing Line objects that correspond to target plates loaded by the user.

  • OMFIT_psi (OMFITgeqdsk) – Instance of class used to interface G files generated by EFIT.

  • PsiUNorm (EfitData) – EfitData class object containing unormalized psi data from provided neqdsk file in settings.

  • LimiterData (Line) – Line class object representing tokamak limiter.

  • magx (tuple) – (R, Z) coordinates of magnetic-axis (float entries).

  • xpt1 (tuple) – (R, Z) coordinates of primary x-point (float entries).

  • xpt2 (tuple) – (R, Z) coordinates of secondary x-point (float entries).

  • LineTracer (LineTracing) – LineTracing instance that for topology analysis and poloidal/radial tracing.

CheckPatches(verbose: bool = False) None

Check that Patch objects adjacent to target plates are monotonic in psi.

This method is a wrapper for the CheckPatches method specific to the current topology being operated on.

Parameters

verbose (bool, optional) – Flag for printing full output to terminal. Defaults to False.

ClassifyTopology(visual=False) None

Determine the topology that is being operated on.

Inspects the settings['grid_settings']['num_xpt'] entry to determine which classification scheme to employ.

Parameters

visual (bool, optional) – Flag for activating the analysis of x-points in a visual DEBUG mode. Default is False.

Raises

ValueError – If user specifies settings['grid_settings']['num_xpt'] with value other than 1 (int) or 2 (int).

FindMagAxis(r: float, z: float) None

Refine the entries and assign to the magnetic-axis in settings.

Parameters
  • r (float) – R coordinate of magnetic-axis guess.

  • z (float) – Z coordinate of magnetic-axis guess.

FindXPoint(r: float, z: float) None

Refine the entries and assign to the primary x-point in settings.

Parameters
  • r (float) – R coordinate of primary x-point guess.

  • z (float) – Z coordinate of primary x-point guess.

FindXPoint2(r: float, z: float) None

Refine the entries and assign to the secondary x-point in settings.

Parameters
  • r (float) – R coordinate of secondary x-point guess.

  • z (float) – Z coordinate of secondary x-point guess.

GetMagxData() tuple

Return the magnetic-axis (r,z) coordinates and associated un-normalized psi value.

Returns

A 3-tuple of r-z coordinates and scalar psi value

GetPatchTagMap(config: str) dict

Get the Patch-Tag mapping for a particular configuration.

This mapping is used to identify patch names with a particular patch tag code.

Parameters

config (str) – The configuration to get the patch tag map for.

Returns

A dictionary containing the tag to patch name mappings.

GetXptData() dict

Return all x-point (r,z) coordinates and associated un-normalized psi values.

Returns

A dict containing an (r, z, psi) entry for each x-point

OMFIT_read_psi() None

Python class to read the psi data in from an ascii file.

Saves the boundary information and generates an EfitData instance.

OrderLimiter() None

Ensures the limiter points are oriented clockwise around the magnetic axis (per INGRID convention).

This method requires the limiter geometry to have been defined as well as the magnetic axis to be refined.

Notes

Ordering of limiter is crucial when using limiter for creating a patch map. This occurs for all cases with two x-points.

OrderTargetPlate(plate_key: str) None

Ensures the target plate points are oriented clockwise around the magnetic axis (per INGRID convention).

Parameters

plate_key (str) – The key corresponding to target plate Line object to sort.

Notes

Ordering of target plates is crucial when using target plates for creating a patch map.

Valid plate keys are as follows:

Plate

Accepted Keys (str)

Plate W1

plate_W1, W1

Plate E1

plate_E1, E1

Plate W2

plate_W2, W2

Plate E2

plate_E2, E2

OrderTargetPlates() None

Convenience method for ordering target plate Point objects.

ParseTxtCoordinates(fpath: str, rshift: float = 0.0, zshift: float = 0.0) tuple

Extract the (R,Z) coordinates from a .txt file.

Files of types .txt must conform to the following format:

\[ \begin{align}\begin{aligned}r_0, z_0\\r_1, z_1\\r_2, z_2\\.....\\r_n, z_n\end{aligned}\end{align} \]

Put otherwise, r and z values are differentiated by a comma and each coordinate must appear on a new line withing the file.

If a line starts with the character ‘#’, it will be skipped.

Parameters
  • fpath (str) – The path to the text file containing (R, Z) coordinate entries.

  • rshift (float, optional) – Applies a translation to the R coordinate of the text file entries.

  • zshift (float, optional) – Applies a translation to the Z coordinate of the text file entries.

Returns

A 2-tuple (R, Z) with list entries containing R and Z data respectively.

Raises
  • IOError – If error occurs while reading text file.

  • ValueError – If fpath string provided leads to an invalid file.

PopulateSettings(settings: dict, verbose: bool = True) None

Populate a settings dict with any missing entries that INGRID may need.

This should be used to screen for any illegal parameter file entries and to ensure clean data entry.

Parameters
  • settings (dict) – Dictionary object conforming to structure of settings dictionary

  • verbose (bool, optional) – Print full output to terminal. Defaults to False.

PrepGridue(guard_cell_eps=0.001) None

Prepare the gridue for writing.

This method calls topology specific implementations of methods that concatenate the Patch object subgrids into a global grid.

PrepLineTracing()

Initializes the line tracing class for the construction of the grid.

ProcessKeywords(**kwargs) None

Process kwargs and set all file paths accordingly.

ProcessPaths() None

Update settings by pre-pending path entries to all file entries.

ReconstructPatches(raw_patch_list: list) dict

Reconstruct a Patch objects from a saved file.

This method takes in an Ingrid formatted .npy file that contains the information needed to reconstruct a patch map from a past INGRID session.

Parameters

fname (str) – The file path to the patch data file obtained after a call to Ingrid class method SavePatches

Returns

A dict of reconstructed Patch objects.

SetDefaultSettings() None

Set all default values that will populate the settings dict.

This instantiates the following entries within the settings file:

  • ‘grid_settings’

  • ‘integrator_settings’

  • ‘target_plates’

  • ‘limiter’

  • ‘patch_data’

  • ‘DEBUG’

Additional entries may be added here as development continues.

SetLimiter(fpath: str = '', coordinates: list = [], rshift: float = 0.0, zshift: float = 0.0) None

Instantiate the class Line object that represents the tokamak limiter.

This method accepts either coordinates or a valid file path to coordinate data.

If fpath and coordinates are at their default values, then the EFIT data will be searched for it’s default limiter values.

Parameters
  • fpath (str, optional) – A file path to a ‘.txt’ or ‘.npy’ file containing (R, Z) data.

  • coordinates (list, optional) – A list with two entries containing R and Z entries respectively.

  • rshift (float, optional) – Apply a translation to the R coordinate of the limiter entries.

  • zshift (float, optional) – Apply a translation to the Z coordinate of the limiter entries.

SetTargetPlate(settings: dict, rshift: float = 0.0, zshift: float = 0.0) None

Initialize a target plate Line object.

This method can initialize target plates:

  • plate_W1

  • plate_E1

  • plate_W2

  • plate_E2

with explicit (R, Z) coordinates.

Parameters
  • settings (dict) – Argument dict specifying which plate to define and with what (R,Z). See notes for more details.

  • rshift (float, optional) – Translate the (R, Z) coordinates by a float value.

  • zshift (float, optional) – Translate the (R, Z) coordinates by a float value.

Notes

Parameter settings is in the following form: {plate_name: rz_data}

where plate_name is a valid key string (see table below), and rz_data is an iterable structure with two iterable entries containing R and Z entries (see examples for usage).

Most users should use the Ingrid class method SetGeometry rather than interface directly with the IngridUtils method since SetGeometry calls this IngridUtils method after processing the user input.

Valid plate keys are as follows:

Plate

Accepted Keys (str)

Plate W1

plate_W1, W1

Plate E1

plate_E1, E1

Plate W2

plate_W2, W2

plate_E2

plate_E2, E2

Example

Defining target plate plate_W1 with coordinates [(1,2), (2, 3), (3, 4)]

>>> MyIG = IngridUtils()
>>> r_entries = [1, 2, 3]
>>> z_entries = [2, 3, 4]
>>> rz_data = (r_entries, z_entries)
>>> MyIG.SetTargetPlate({'plate_W1': rz_data})
WriteGridueDNL(gridue_settings: dict, fname: str = 'gridue') bool

Write a gridue file for a double-null configuration.

Parameters
  • gridue_settings (dict) – A dictionary containing grid data to be written to the gridue file.

  • fname (str, optional) – The file name/path to save the gridue file to. Defaults to ‘gridue’.

Returns

True if file was written with no errors

WriteGridueSNL(gridue_settings: dict, fname: str = 'gridue') bool

Write a gridue file for a single-null configuration.

Parameters
  • gridue_settings (dict) – A dictionary containing grid data to be written to the gridue file.

  • fname (str, optional) – The file name/path to save the gridue file to. Defaults to ‘gridue’.

Returns

True if file was written with no errors

get_config() str

Get the configuration obtained during analysis of x-points.

Returns

A string identifying the configuration contained within LineTracing attribute LineTracer.

class INGRID.utils.TopologyUtils(Ingrid_obj: object, config: str)

Bases: object

The base class for all INGRID topologies.

Encapsulates key methods generating patch maps, visualizing data, generating grids, and exporting of grids.

These methods are to be interfaced by the child ingrid.Ingrid or can be used by advanced users of the code.

Variables
  • parent (Ingrid) – Ingrid object the topology is being managed by.

  • settings (dict) – Core settings dict of parent.

  • CurrentListPatch (dict) – Lookup dict of Patches that have been refined (populated during Patch refinement).

  • ConnexionMap (dict) – A mapping describing how Patch objects are connected to each other (see notes).

  • CorrectDistortion (dict) – The settings to be used for correcting grid shearing.

  • config (str) – Configuration of topology.

  • PlateData (dict) – Parent target plate data dict.

  • PatchTagMap (dict) – A dictionary containing the tag to patch name mappings for this topology.

  • LineTracer (LineTracing) – Parent LineTracing instance.

  • PsiUNorm (EfitData) – Parent PsiUNorm instance.

  • PsiNorm (EfitData) – Parent PsiNorm instance.

CheckFunction(expression: str, Verbose: bool = False) bool

Check if a str is in the correct format for method get_func

Parameters
  • expression (str) – Expression to check.

  • Verbose (bool, optional) – Print full output to terminal. Default to False

Returns

True if expression is valid. False otherwise.

CheckPatches(verbose: bool = False) None

Convenience method for calling the Patch class method CheckPatch.

Checks to make sure Patch objects stored in the TopologyUtils patches dictionary are monotonic in psi along strike geometry (if applicable).

Parameters

verbose (bool, optional) – Print full output to terminal. Defaults to False.

GetBoundaryPoints(AdjacentPatchInfo: tuple) list

Get the points along a boundary for a particular Patch.

Parameters

AdjacentPatchInfo (tuple) – A 2-tuple containing the tag of the Patch to obtain boundary points from (str value), and a character indicating which boundary to access (‘N’, ‘S’, ‘E’, ‘W’).

Returns

A list containing the Points along the specified boundary for a Patch.

GetDistortionCorrectionSettings() dict

Get settings associated with the CorrectDistortion capability.

Returns

A dictionary containing CorrectDistortion settings.

GetFunctions(Patch: INGRID.geometry.Patch, Verbose: bool = False) tuple

Get the poloidal and radial transformations for a Patch.

Poloidal and radial transformations affect more than a single Patch in the index space. This method ensures that the same transformations are applied to dependent Patches (e.g. radial transformation T is applied to all Patch objects in the same radial level).

Parameters
  • Patch (Patch) – The Patch to get the functions for.

  • Verbose (bool, optional) – Print all output to terminal. Default to False.

Returns

2-tuple containing functions for radial and poloidal direction respectively.

GetNpoints(Patch: INGRID.geometry.Patch) tuple

Get the number of poloidal and radial grid cells to be generated for a Patch.

Because of index space dependence and formatting, this method ensures adjacent patches in the index space are matching in dimensions.

Parameters

Patch (Patch) – Patch object to get the np and nr values for.

Returns

A 2-tuple containing the number of radial and poloidal cells to generate, respectively.

OrderPatches()
RefreshSettings()
SetPatchBoundaryPoints(Patch: INGRID.geometry.Patch, verbose: bool = False) None

Set the Patch BoundaryPoints dict based off TopologyUtils ConnexionMap.

Parameters
  • Patch (Patch) – The Patch to set the boundary points for.

  • verbose (bool) – Print full output to terminal.

Notes

The ConnexionMap represents the layout of adjacent patches and will lookup what is adjacent to the Patch parameter being operated on.

SetupPatchMatrix() list

Instantiate the list representation of the Patch layout in index space.

Method concat_grid uses this structure when combining refined Patches into a global grid.

Returns

The ‘PatchMatrix’ list

concat_grid(guard_cell_eps: float = 0.001) None

Concatenate a refined Patch map into a global grid.

This method take grid data and represents it into Fortran formatted arrays that will be written to gridue.

Adding of guard cells is done in this method as well.

Parameters

guard_cell_eps (float, optional) – Determines the size of guard cell padding.

construct_grid(np_cells: int = 1, nr_cells: int = 1, Verbose: bool = False, ShowVertices: bool = False, RestartScratch: bool = False, ListPatches: str = 'all') None

Construct a grid by refining a Patch map.

This method gathers transformation and dimension information to apply to each Patch. In addition, this applies any CorrectDistortion settings the user may want to apply.

Assumes a Patch map has been generated or that Patches have been loaded (equivalent).

Parameters
  • np_cells (int, optional) – Number of poloidal cells to create in the local Patch grid. Defaults to 1.

  • nr_cells (int, optional) – Number of radial cells to create in the local Patch grid. Defaults to 1.

  • Verbose (bool, optional) – Print all output to terminal. Defaults to False

  • ShowVertices (bool, optional) – Emphasize spline vertices on grid figure with bold markers. Defaults to False.

  • RestartScratch (bool, optional) – Flag for repeating the Patch refinement process for an already refined Patch. Defaults to False.

  • ListPatches (str, optional) – Specify which Patches to generate a grid for (see notes). Defaults to ‘all’.

Examples

Parameter ListPatches can be used to specify which Patches to refine into a grid. The default value of all instructs TopologyUtils to refine the entire Patch map. To specify Patches, the user is to provide a list containing names of Patches to refine.

Refining only the outer-most psi boundary (SOL) for a lower single-null configuration:

>>> patch_names = ['A2', 'B2', 'C2', 'D2', 'E2', 'F2']
>>> MyTopologyUtils.construct_grid(np_cells=3, nr_cells=3, ListPatches=patch_names)

Refining only the inboard and outboard psi boundary for an unbalanced double-null configuration:

>>> patch_names = ['A3', 'B3', 'C3', 'D3', 'E3', 'F3', 'G3', 'H3']
>>> MyTopologyUtils.construct_grid(np_cells=3, nr_cells=3, ListPatches=patch_names)

Notes

The Patch refinement process is often order-dependent. This is to ensure alignment of grid with minimal editing.

Because of this, parameters such as ListPatches is suggested to be used by a user or developer who is sure of what they are doing.

get_config() str

Return the configuration string stored in the TopologyUtils class

Returns

A string indicating the topology

get_func(func: str) function

Create a function from a string input.

Will be used to generate a poloidal or radial transformation function.

Parameters

func (str) – An expression to generate a function from.

Returns

A function generated from the str input.

Examples

When calling method get_func the user must provide a string with the following general format:

\[x, f(x)\]

That is, the dependent variable and expression to evaluate are separated with a comma character.

The Sympy library supports most expressions that can be generated with Python natively. See the Sympy documentation for advanced features.

Defining a function representing f(x) = x ^ 2:

>>> func = 'x, x ** 2'
>>> f = MyTopologyUtils.get_func(func)
>>> f(np.array([0, 1, 2, 3]))
array([0, 1, 4, 9])

Defining a function representing f(x) = exp(x)

>>> func = 'x, exp(x)'
>>> f = MyTopologyUtils.get_func(func)
>>> f(np.array([0, 1, 2, 3]))
array([ 1.        ,  2.71828183,  7.3890561 , 20.08553692])
grid_diagram(fig: Optional[object] = None, ax: Optional[object] = None) None

Generates the grid diagram for a given configuration.

Parameters
  • fig (object, optional) – Matplotlib figure to show the grid diagram on.

  • ax (object, optional) – Matplotlib axes to plot the grid diagram on.

patch_diagram(fig: Optional[object] = None, ax: Optional[object] = None) None

Generate the patch diagram for a given configuration.

Parameters
  • fig (object, optional) – Matplotlib figure to show the Patch map on.

  • ax (object, optional) – Matplotlib axes to plot the Patch map on.