ingrid

Ingrid module for interfacing all grid generator capabilities.

This module contains the Ingrid class that drives all code functionality.

The Ingrid class is to encapsulate all functionality and allow the user to easily take advantage of advanced features of the code.

class INGRID.ingrid.Ingrid(settings: dict = {}, **kwargs)

Bases: INGRID.utils.IngridUtils

The driver class of the grid generator. A user will be able to load all experimental data, create patch maps, create grids, and export grids with the methods available. The GUI version of the Ingrid code is also accessed exclusively through this class.

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
  • settings (dict) – Dictionary representation of the settings file.

  • PlateData (dict) – Dictionary mapping target plates to their corresponding class ‘Line’ objects.

  • 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).

  • PsiNorm (EfitData) – ‘EfitData’ class object containing normalized psi data calculated from class attribute ‘PsiUNorm’.

  • CurrentTopology (Topology) – Tokamak magnetic configuration type currently being operated on. Class ‘Topology’ acts as thebase class for all magnetic configurations.

AnalyzeTopology() None

Perform analysis on normalized psi to determine magnetic topolgy.

AutoRefineMagAxis() None

Refine magnetic axis RZ coordinates.

Will apply a root_finder method to ‘rmagx’ and ‘zmagx’ float values stored in attribute “settings[‘grid_settings’]”.

AutoRefineXPoint() None

Refine primary x-point RZ coordinates.

Will apply a root_finder method to ‘rxpt’ and ‘zxpt’ float values stored in attribute “settings[‘grid_settings’]”.

AutoRefineXPoint2() None

Refine secondary x-point RZ coordinates.

Will apply a root_finder method to ‘rxpt2’ and ‘zxpt2’ float values stored in attribute “settings[‘grid_settings’]”.

CalcPsiNorm() None

Normalize psi data to a refined magnetic axis and primary x-point

ClearLegend(ax) None

Safely remove the legend form the normalized psi data.

ConstructGrid(NewFig: bool = True, ShowVertices: bool = False) None

Refine a generated patch map into a grid for exporting.

Parameters
  • NewFig (bool, optional) – Plot the created grid on a new figure.

  • ShowVertices (bool, optional) – Plot vertices in refined grid with bolded markers.

  • ListPatches (bool, optional) –

    Generate a grid for a particular patch. Requires the correct patch name associated with the ‘Patch’ object.

    Warning: Grid generation is order dependent. Specifying a particular patch to generate a grid would only be done in rare cases and require the user to know dependencies for the particular patch.

ConstructPatches() None

Create a patch map that can be refined into a grid.

This method assumes the user has either loaded patch data from a previous Ingrid session (see ‘LoadPatches’), or that the user has already successfully called method ‘AnalyzeTopology’.

Should the user want to automatically enable patch saving, the user should set the entry

‘settings[‘’patch_data’’][‘’preferences’’][‘’new_file’’]’

with a value of ‘True’.

CreatePatches() None

An alias for ConstructPatches. See ConstructPatches for more details.

CreateSubgrid(NewFig: bool = True, ShowVertices: bool = False) None

Alias for ConstructGrid. See ConstructGrid for documentation.

ExportGridue(fname: str = 'gridue', guard_cell_eps=0.001) None

Export a gridue file for the created grid.

Parameters

fname (str, optional) – Name of gridue file to save.

static ImportGridue(fname: str = 'gridue') dict

Import UEDGE grid file as dictionary.

Parameters

fname (str, optional) – Path/file name to gridue formatted file.

Returns

A dict containing header and body information from the gridue file.

LoadEFIT(fpath: str) None
LoadGeometryData(geo_items: dict) None

Load strike geometry RZ coordinates from external file.

Said external file must be of type ‘.txt’ or a properly formatted ‘.npy’ file.

Parameters

geo_items (dict) – The argument dict specifying which strike geometry to load data into.

Notes

geo_items is of the form: {geo_name: data_fname, ... }

where both geo_name and data_fname are of type str.

Multiple data_fname files can be loaded at once in a manner similar to method SetGeometry().

Raises
  • ValueError – If ‘geo_items’ is not type ‘dict’.

  • ValueError – If invalid ‘geo_items’ key provided.

  • ValueError – If data_fname entry is not of type ‘str’.

  • ValueError – If data_fname is not a file.

  • ValueError – If data_fname file is not of format ‘.txt’ or ‘.npy’

LoadPatches(fname: str = '') None

Load patches stored in an Ingrid generated ‘.npy’ file.

Parameters

fname (str, optional) –

Path to patch data.

If no fname is provided to method ‘LoadPatches’, Ingrid code will check the settings ‘dict’ for a file under entry settings['patch_data']['file']

PlotEastWestXpt1Ref(ax: Optional[object] = None) None

Plot midplane line through magnetic axis with any applied transformations specified in settings.

This method can be used to inspect the effects of ‘magx_tilt_1’, ‘magx_tilt_2’, ‘rmagx_shift’, and ‘zmagx_shift’.

PlotEastWestXpt2Ref(ax: Optional[object] = None) None

Plot midplane line through magnetic axis with any applied transformations specified in settings.

This method can be used to inspect the effects of ‘magx_tilt_1’, ‘magx_tilt_2’, ‘rmagx_shift’, and ‘zmagx_shift’.

PlotGrid() None

Plot the grid that was generated with method ‘ConstructGrid’.

static PlotGridue(GridueParams: dict, edgecolor='black', ax: Optional[object] = None)

Plot UEDGE grid from ‘dict’ obtained from method ‘ImportGridue’

Parameters
  • GridueParams (dict) – Gridue header and body information as a dictionary. (See method ImportGridue)

  • edgecolor (str, optional) – Color of grid.

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

PlotLimiter(ax: Optional[object] = None) None

Plot limiter geometry.

PlotMidplane(ax: Optional[object] = None) None

Plot midplane line through magnetic axis with any applied transformations specified in settings.

This method can be used to inspect the effects of ‘magx_tilt_1’, ‘magx_tilt_2’, ‘rmagx_shift’, and ‘zmagx_shift’.

PlotPatches() None

Plot the patch map that was generated with method ‘CreatePatches’

PlotPsiLevel(efit_psi: object, level: float, Label: str = '') None

Plot a contour corresponding to a psi level.

Parameters
  • efit_psi (EfitData) – The ‘EfitData’ object to get the psi data from.

  • level (float) – The psi value to plot.

  • Label (str, optional) – Label to provide to matplotlib.pyplot.contour.

PlotPsiNorm(view_mode: str = 'filled') None

Plot normalized psi data.

PlotPsiNormBounds() None

Plot contour lines associated with psi boundary values provided.

This method extracts psi values from the ‘settings’ dict and plots the psi level. In addition to the psi values in ‘settings’, the primary and, if applicable, secondary separatrix are plotted as well.

If the user is operating on a single null configuration, the psi values plotted are ‘psi_1’, ‘psi_core’, ‘psi_pf_1’.

If the user is operating on a case with two x-points, the psi values are the same as above but with ‘psi_1’, ‘psi_2’, and ‘psi_pf_2’ also included in the plot.

PlotPsiNormMagReference(ax: Optional[object] = None) None

Plot a marker on the magnetic axis and all x-points of interest.

PlotPsiUNorm() None

Plot unnormalized psi data.

PlotStrikeGeometry(ax: Optional[object] = None) None

Plot all strike geometry to be used for drawing the Patch Map.

Checks the central INGRID settings attribute for whether settings['patch_generation']['strike_pt_loc'] is True or if settings['grid_settings']['num_xpt'] is equal to 2 in order to determine whether or not to plot the limiter geometry.

Otherwise only any loaded target plates will be plotted.

PlotSubgrid() None

Alias for method PlotGrid. See PlotGrid for documentation.

PlotTargetPlate(plate_key: str, color: str = 'red', ax: Optional[object] = None) None

Plot a target plate corresponding to a plate key.

Parameters
  • plate_key (str) – An Ingrid supported target plate key (see method SetGeometry for supported plate keys)

  • color (str, optional) – Color to provide to matplotlib

PlotTargetPlates(ax: Optional[object] = None) None

Plot all PlateData and remove outdated plate line artists.

PlotTopologyAnalysis() None

Shade the private flux, core, and show where the secondary x-point travels.

This method can be used to interpret which type of configuration the user is handling.

PrintSummaryInput() None

Print a summary of the currently loaded data files

Will print relevant EQDSK, patch data files, target plate files, and limiter files.

PrintSummaryParams() None

Print a summary of key settings values.

static ReadYamlFile(FileName: str) dict

Read a yaml file and return a dictionary

Parameters

FileName (str) – Path/file name of ‘.yml’ parameter file represented as dictionary.

Returns

Settings file represented as a dictionary

Raises

IOError – If error occurs while loading yml file.:

RefreshSettings()
RemovePlotLine(label: str, ax: Optional[object] = None) None
RemovePlotPatch(label: str, ax: Optional[object] = None) None
RemovePlotPoint(label: str, ax: Optional[object] = None) None
SaveGeometryData(geo_items: dict, timestamp: bool = False) None

Save strike geometry Line object RZ coordinates as ‘.npy’ file.

Geometry data files created with this method can be used in the INGRID parameter file.

Parameters
  • geo_items (dict) –

    A dictionary specifying which target plate to save and the file name/path. Said dictionary takes the following form:

    {geo_name: data_fname, ... }

    Where both geo_name and data_fname are of type str. Multiple data_fname files can be saved at once in a manner similar to method ‘SetGeometry’ (see documentation for ‘SetGeometry’).

  • timestamp (bool, optional) – Append a time stamp to the end of the files.

Raises
  • ValueError – If ‘geo_items’ is not type ‘dict’.

  • ValueError – If invalid ‘geo_items’ key provided.

  • ValueError – If data_fname entry is not of type ‘str’.

  • ValueError – If data_fname entry is an empty string.

  • ValueError – If requested strike geometry Line to save has no data.

SavePatches(fname: str = '') None

Save patches as ‘.npy’ file for later reconstruction in Ingrid.

This file contains the information required to reconstruct patches at a later time and bypass the line_tracing.

Parameters

fname (str, optional) – Name of file/location for patch data.

SaveSettingsFile(fname: str = '', settings: dict = {}) pathlib.Path

Save a new settings .yml file.

Parameters
  • fname (optional) – Name of new settings ‘.yml’ file. If default value of ‘’, then Ingrid will generate a ‘.yml’ file named ‘INGRID_Session’ appended with a timestamp.

  • settings (optional) – Ingrid settings dictionary to dump into the ‘.yml’ file. Defaults to empty dict which produces a template settings file.

Returns

A Path instance representing the saved YAML file.

SetGeometry(geo_items: dict, rshift: float = 0.0, zshift: float = 0.0) None

Define and load the tokamak strike geometry into the Ingrid object. Allows the user to set target plate data and/or limiter data that will be used to generate a patch map.

Parameters
  • geo_items (dict) – Argument dict specifying which item(s) to set and by what way.

  • rshift (float, optional) – Translate ‘geo_items’ to coordinate R’, with R’ = R + rshift. Will override all ‘rshift’ provided entries in ‘geo_items’.

  • zshift (float, optional) – Translate ‘geo_items’ to coordinate Z’, with Z’ = Z + zshift. Will override all ‘zshift’ provided entries in ‘geo_items’.

Notes

Multiple geometry items can be set at once, but the following key-value format must be obeyed for any number of entries:

{geo_key: geo_item}

All keys for ‘geo_items’ are type ‘str’. Accepted key values are as follows:

Geometry

Accepted Keys (str)

Plate W1

plate_W1, W1

Plate E1

plate_E1, W1

Plate W2

plate_W2, W1

Plate E2

plate_E2, W1

Limiter

limiter, wall

The above keys are NOT case sensitive.

Corresponding key values can vary in data type depending on means of setting geometry. The types and their usage are as follows:

‘str’: Path to ‘.txt’ file containing coordinate data or to Ingrid generated ‘.npy’ file (obtained via methods

‘SaveLimiterData’ and ‘SaveTargetPlateData’). Note: When setting Limiter geometry, the user can provide the value ‘default’ to set limiter data to that which is contained in the loaded neqdsk file.

‘list’, ‘tuple’: Iterables provided as values must be of length == 2. The first entry corresponds to R coordinate information, and the second entry corresponds to Z coordinate information. This information can be in the form of a list or NumPy array with shape == (N,).

‘dict’: One can map to a dictionary taking on a variety of formats depending on need.

Setting geometry with explicit RZ coordinates: {‘R’: R_data, ‘Z’: z_data} Where R_data and Z_data are in the form of a list or NumPy array with shape == (N,) as above.

Setting geometry with data from external file: {‘file’: str}

Notes: The above dict option support keys ‘rshift’ and ‘zshift’ for the user to provide transformations to individual geometry items (see examples).

Because the core ‘settings’ attribute contained by the Ingrid class contains dict structures itself, the user can also provide settings[‘limiter’] and settings[‘target_plates’][k] to method ‘SetGeometry’ (where k corresponds to a plate key).

Examples

Setting default limiter data contained in loaded neqdsk file:

>>> MyIG = Ingrid()
>>> MyIG.SetGeometry({'limiter': 'default'})

Setting target plate ‘E1’ with numpy array:

>>> MyIG = Ingrid()
>>> MyIG.SetGeometry({'E1': 'E1_data.npy'})

Setting limiter data with Ingrid ‘.npy’ file:

>>> MyIG = Ingrid()
>>> MyIG.SetGeometry({'limiter': 'LimiterData.npy'})

Setting both target plates ‘W1’ and ‘E1’ with ‘.txt’ and ‘.npy’ files while only applying rshift and zshift to target plate ‘E1’ (Note the dict structure used for specifying ‘E1’):

>>> MyIG = Ingrid()
>>> geometry_dict = {
... 'W1': 'W1_data.txt',
... 'E1': {
... 'file': 'E1_data.npy',
... 'rshift': 1.23, 'zshift': 3.14
... }
... }
>>> MyIG.SetGeometry(geometry_dict)

Setting plate ‘W2’ with user provided NumPy array for RZ coordinates:

>>> MyIG = Ingrid()
>>> R_data = my_numpy_array_1
>>> Z_data = my_numpy_array_2
>>> RZ_dict = {'R': my_numpy_array_1, 'Z': my_numpy_array_2}
>>> MyIG.SetGeometry({'plate_W1': RZ_dict})
Raises
  • ValueError – If file path provided does not lead to actual file.

  • ValueError – If file provided is not of suffix ‘.txt’ or ‘.npy’.

  • ValueError – If invalid ‘geo_items’ key provided.

  • ValueError – If ‘geo_items’ dict value contains invalid key.

  • ValueError – If value associated with ‘geo_items’ key is not of supported data type.

SetMagReference() None

Set the appropriate reference points in the domain. Namely the magnetic-axis, primary x-point, and (if applicable), secondary x-point.

SetTargetPlates() None

Define target plate geometries based off of settings dict specifications.

This is a convenience method that calls SetGeometry.

SetTopology(topology: str) None

Initialize the current topology to a particular magnetic topology.

Parameters

topology (str) –

String literal corresponding to which magnetic topology to initialize.

Values can be:

’LSN’: Lower Single Null ‘USN’: Upper Single Null ‘UDN’: Unbalanced Double Null ‘SF15’: Snowflake-15 ‘SF45’: Snowflake-45 ‘SF75’: Snowflake-75 ‘SF105’: Snowflake-105 ‘SF135’: Snowflake-135 ‘SF165’: Snowflake-165

Raises

ValueError – If user provided unrecognized string entry.

ShowSetup(view_mode: str = 'filled') None

Show Ingrid setup that a patch map will be generated from.

This method plots normalized psi data, psi boundaries, strike geometry, and midplane lines through the magnetic axis.

StartGUI() None

Start GUI for Ingrid.

Will assume usage on a machine with tk GUI capabilities. No prior settings file is required as the user will be prompted with an option to generate a new file.

StartSetup(**kwargs) None

A collection of essential tasks before generating a patch map from scratch.

The user should ensure that the ‘settings’ dict is populated with the correct paths to relevant neqdsk data and geometry files.

The user should ensure ‘settings[‘’grid_settings’’][‘’num_xpt’] is set with the correct integer value.

INGRID.ingrid.QuickStart() None

Start Ingrid in gui mode with default settings.

Rather than providing data to the class constructor, a user can opt to start Ingrid immediately in it’s gui form. This is useful for users who are not familiar with the Ingrid class and it’s capabiliites. Advanced users may still find QuickStart useful, but would also use the code in self-authored scripts.