ascot5io

Interface for accessing data in ASCOT5 HDF5 files.

a5py.ascot5io.bfield

Magnetic field input.

a5py.ascot5io.efield

Electric field input.

a5py.ascot5io.plasma

Input data representing plasma background species.

a5py.ascot5io.marker

Markers whose orbits are solved within the ASCOT5 code.

a5py.ascot5io.wall

Input representing first wall and other plasma facing components.

a5py.ascot5io.neutral

Input representing plasma neutral bakcground.

a5py.ascot5io.boozer

Input representing mapping from real-space to Boozer coordinates.

a5py.ascot5io.mhd

Input containing MHD eigenmodes.

a5py.ascot5io.asigma

Atomic reaction data HDF5 IO.

a5py.ascot5io.nbi

Input data representing NBI.

a5py.ascot5io.options

Simulation options input.

a5py.ascot5io.coreio

Low level API for HDF5 data access and building the treeview.

class a5py.ascot5io.Ascot5IO(ascot, **kwargs)

Bases: RootNode

Entry node for accessing data in the HDF5 file.

Initializing this node builds rest of the tree. This object and its child nodes act as container objects for the data in the HDF5 file. At top level (this node) run nodes containing simulation results can be accessed as well as the parent nodes (bfield, efield, etc.) that in turn contain the actual input groups.

The data can be accessed as

data.bfield.B_2DS_1234567890

or, equivalently,

data["bfield"]["B_2DS_1234567890"]

In each input group, one input is always set as “active” (meaning it would be used for the next simulation) and it can be accessed as

data.bfield.active

QID can be used as a reference as well

data.bfield.q1234567890

Run groups are accessed in a similar fashion, e.g.

data.run_1234567890 .

However, the easiest way to access the simulation output is via the methods in the RunNode. The active run (by default the most recent simulation) can be accessed with

data.active

and its inputs as

data.active.bfield

Most of these examples also work with dictionary-like reference but here we use only the attribute-like referencing for brevity.

You can even use user defined tag taken from description to refer to it

data.THATPRLRUN

However, there are few rules to this:

  • Tag is the first word in description converted to all caps for brevity.

  • Maximum length is ten characters.

  • Only letters and numbers are allowed (all special characters are removed).

  • First character must be a letter.

  • If two fields would have identical tags, they are changed to format <tag>_<i>, where i is running index starting from zero (corresponding to most recent data).

Finally, you can print the contents of a node with

data.ls()
create_input(inp, desc=None, activate=None, dryrun=False, **kwargs)

Create input and write the data to the HDF5 file.

This method can be used in two ways to write input data.

  1. From ascot5io choose the input type and find what is requested by the corresponding write_hdf5 function to write inputs explicitly.

  2. From template choose a template or import, and find what parameters are requested to write premade inputs or imported data.

Parameters:
inpstr

Type of the input e.g. “B_2DS” or name of the template/import e.g. “analytical ITER-like”.

descstr, optional

Input description.

activatebool, optional

Set created input as active.

dryrunbool, optional

If True, the data is not written to HDF5 but instead it is returned as a dictionary.

Only works for templates.

**kwargsdict

The parameters that are needed to create the requested input type or template.

If input type is given but kwargs is empty, dummy input of given type is created.

Returns:
datastr or dict

Name, i.e. “<type>_<qid>”, of the new input that was written or the data that was created but not written if dryrun is True.

destroy(repack=True)

Remove all results from the HDF5 file.

Parameters:
repackbool, optional

If True, repack the HDF5 file.

Removing data from the HDF5 file only removes references to it and repacking is required to free the disk space. Repacking makes a copy of the HDF5 file and destroys the original, and it also requires 3rd party tool h5repack which is why it’s use is optional here.

get_contents()

Return metadata for all childs sorted by date.

Returns:
qidsarray_like, str

QIDs.

datesarray_like, str

Dates.

descsarray_like, str

Descriptions.

typesarray_like, str

Data types.

get_runs(inputqid)

Fetch QIDs of runs using given input.

Parameters:
inputqidqid

QID of the input.

Returns:
qidslist [str]

List of run QIDs.

ls(show=True)

Get a string representation of the contents.

Parameters:
showstr, optional

If True, the contents are also printed on screen.

Returns:
contentsstr

Multiline string decorated with ANSI escape sequences that list all results and their meta data and currently active inputs.

templates(template)

Show information about a template.

Parameters:
templatestr

Name of the template.

If not given, all templates are listed.

class a5py.ascot5io.RunGroup(root, path, h5, inputqids, **kwargs)

Bases: ResultNode, RunMixin

Node containing results and methods to process them.

activate()

Set this group as active.

Active inputs are used when the simulation is run. Active groups are also used during post-processing.

destroy(repack=True)

Remove this group from the HDF5 file.

Parameters:
repackbool, optional

If True, repack the HDF5 file.

Removing data from the HDF5 file only removes references to it and repacking is required to free the disk space. Repacking makes a copy of the HDF5 file and destroys the original, and it also requires 3rd party tool h5repack which is why it’s use is optional here.

export(target_file, newgroup=False)

Copy this group with its contents to another HDF5 file.

Parameters:
target_filestr

Path to the file where the data is copied to.

newgroupbool, optional

If True, a new QID and date is generated for the copied group.

get_contents()

Return names of all childs.

Returns:
nameslist [str]

List of names.

get_date()

Get the date when this group was created.

Returns:
datestr

The date in YYYY-MM-DD hh:mm:ss format.

get_desc()

Get this group’s description.

Returns:
descstr

Documentation the user has used to describe this group.

get_name()

Return name of this group.

Returns:
namestr

The name of the group as “<group type>_<group qid>”.

get_qid()

Get QID of this group.

Returns:
qidstr

String with 10 characters containing numbers from 0-9 which is an unique identifier for this group.

get_type()

Return type of this group.

Returns:
gtypestr

Group type.

getdist(dist, exi=False, ekin_edges=None, pitch_edges=None, plotexi=False)

Return distribution function.

Parameters:
dist{“5d”, “6d”, “rho5d”, “rho6d”, “com”}

Name of the distribution.

If dist is None, returns a list of available distributions.

exibool, optional

Convert the momentum space to energy-pitch.

The distribution is normalized to conserve the particle number.

Not applicable for dist = {“6d”, “rho6d”, “com”}.

ekin_edgesint or array_like, optional

Number of bins or bin edges in the energy abscissa if exi=True.

pitch_edgesint or array_like, optional

Number of bins or bin edges in the pitch abscissa if exi=True.

plotexibool, optional

Visualize the transformation from ppar-perp to energy-pitch if if exi=True.

Use this option to adjust energy and pitch abscissae to your liking.

Returns:
dataDistData or list [str]

The distribution data object or a list of available distributions if dist is None.

getdist_list(show=True)

List all available distributions and moments.

Parameters:
showbool, optional

Print the output.

Returns:
distslist [str]

List of available distributions.

momslist [(str, str)]

List of distribution moments that can be evaluated and their meaning.

getdist_moments(dist, *moments, volmethod='prism')

Calculate moments of distribution.

Parameters:
diststr or DistData

Distribution from which moments are calculated.

*momentsstr

Moments to be calculated.

volmethod{“mc”, “prism”}, optional

Method used to calculate the volume.

It is a good idea to verify that same results are obtained with both methods.

Returns:
outDistMoment

Distribution object containing moments as ordinates.

getorbit(*qnt, ids=None, pncrid=None, endcond=None)

Return orbit data.

Returns marker phase space coordinates and derived quantities along the recorded orbit, if the orbit recording was enabled.

Parameters:
*qntstr

Names of the quantities.

idsarray_like, optional

Filter markers by their IDs.

pncridarray_like, optional

Filter data points by the Poincaré plane they correspond to.

endcondstr or list [str], optional

Filter markers by their end conditions.

See getstate() for details on how this argument is parsed and for a list of end conditions present in the data.

Returns:
valarray_like

The queried quantity sorted first by marker ID and then by mileage.

If multiple quantities are queried, they are returned as a list in the order they were listed in *qnt.

Raises:
ValueError

Raised when the queried quantity could not be interpreted.

AscotNoDataException

Raised when data required for the operation is not present.

AscotInitException

If evaluating quantity required interpolating an input that was not initialized.

getorbit_average(qnt, ids)

Calculate average of a quantity during a single poloidal transit.

Parameters:
qntarray_like

The quantity to be averaged evaluated along the orbit.

idsint

ID of the marker whose orbit is used to compute the average.

Returns:
mileagearray_like

Time along the orbit trajectory starting from zero.

rarray_like

Marker R-coordinate along the orbit trajectory.

zarray_like

Marker z-coordinate along the orbit trajectory.

valarray_like

Value of ```qnt```along the orbit trajectory.

avgarray_like

Evaluated orbit average.

getorbit_list()

List quantities that can be evaluated with getorbit().

getorbit_poincareplanes()

Return a list of Poincaré planes that were present in the simulation and the corresponding pncrid.

Returns:
pollist [(float, int)]

List of tuples with a toroidal angle and pncrid for each poloidal plane or empty list if there are none.

torlist [float]

List of tuples with a poloidal angle and pncrid for each toroidal plane or empty list if there are none.

radlist [float]

List of tuples with radius and pncrid for radial surfaces or empty list if there are none.

getstate(*qnt, mode='gc', state='ini', ids=None, endcond=None)

Evaluate a marker quantity based on its ini/endstate.

Inistate is marker’s phase-space position right at the start of the simulation and endstate is the position at the end of the simulation.

This function not only returns the marker phase space coordinates but also other quantities that can be inferred from it and information that is stored along with coordinates. For a complete list of available quantities, see.

ASCOT5 stores both particle and guiding center phase-space position in all simulations. To differentiate these, quantities with suffix “prt”, e.g. “xprt”, return particle quantities and without suffix the guiding center quantity is returned.

Parameters:
*qntstr

Names of the quantities.

state{“ini”, “end”}, optional

Is the quantity evaluated at the ini- or endstate.

idsarray_like, optional

Filter markers by their IDs.

endcondstr or list [str], optional

Filter markers by their end conditions.

See for a list of all possible end conditions or to list end conditions that are currently present in the data.

Markers may have multiple end conditions active simultaneously. If just the name of the end condition e.g. “POLMAX” is passed, then all markers that have (at least) the POLMAX end condition are returned.

If the end condition is preceded by “NOT”, e.g. “NOT POLMAX”, then markers that don’t have that end condition are returned.

Passing multiple end conditions in a single string returns markers that have all listed end conditions active, e.g. “MAXPOL MAXTOR” returns markers that have both POLMAX and TORMAX active simultaneously.

Passing end condition strings as separate list items acts as a logical OR, e.g. [“POLMAX”, “TORMAX”] returns markers that have either POLMAX or TORMAX active.

Returns:
valarray_like

The evaluated quantity sorted by marker ID.

If multiple quantities are queried, they are returned as a list in

the order they were listed in *qnt.

Raises:
ValueError

Raised when the queried quantity could not be interpreted.

AscotNoDataException

Raised when data required for the operation is not present.

AscotInitException

If evaluating quantity required interpolating an input that was not initialized.

getstate_list()

List quantities that can be evaluated with getstate().

getstate_losssummary()

Return a summary of lost markers.

getstate_markers(mrktype, ids=None)

Convert endstate to marker input.

Parameters:
mrktype{“prt”, “gc”, “fl”}

Type of marker input to be created.

idsarray_like, optional

Select only these markers for the output.

Returns:
mrkdict

Markers parameters that can be supplied to Prt.write_hdf5(), GC.write_hdf5() or FL.write_hdf5() depending on mrktype value.

getstate_markersummary()

Return a summary of marker end conditions and errors present in the data.

Returns:
econdslist [(int, str)]

List of present end conditions.

Each list member is a tuple, where first item is the number of markers with the end condition specified in the second item.

emsglist [(str, int, str)]

List of present errors.

Each list member is a tuple, where first item is the error message, second the line number where error was raised, and third is the name of the file.

Raises:
AscotNoDataException

Raised when data required for the operation is not present.

getstate_pointcloud(endcond=None)

Return marker endstate (x,y,z) coordinates in single array.

Parameters:
endcondstr, optional

Only return markers that have given end condition.

getwall_3dmesh(w_indices=None, p_ids=None)

Return 3D mesh representation of 3D wall and associated loads

Parameters:
w_indicesarray_like, optional

List of triangle indecies for which the 3D mesh is made.

p_idsarray_like, optional

List of particle ids for which the wall loads are calculated.

Returns:
wallmeshPolydata

Mesh representing the wall.

The mesh cell data has fields:

  • “pload” particle load in units of prt/m^2 or prt/m^2s,

  • “eload” power/energy load in units of W/m^2 or J/m^2

  • “mload” marker load in units of markers

  • “iangle” angle of incidence (the angle between power flux and the surface normal) in deg

getwall_figuresofmerit()

Get peak power load and other 0D quantities related to wall loads.

Returns:
wareafloat

Total wetted area.

ploadfloat

Peak power load.

getwall_loads(weights=True, p_ids=None)

Get wall loads and associated quantities.

This method does not return loads on all wall elements (as usually most of them receive no loads) but only those that are affected and their IDs.

For 2D walls, iangle, angle of incidence is not calculated.

Parameters:
weightsbool, optional

Include marker weights to get physical results (otherwise particle deposition would be just the number of markers that hit the tile).

Dropping weights is useful to check how many markers hit a tile which tells us how good the statistics are.

p_idsarray_like, optional

Calculate wall loads only for the particles with the given indices.

Returns:
idsarray_like

Indices of loaded wall tiles.

areaarray_like

Area of each tile.

edepoarray_like

Energy/power deposition per tile.

pdepoarray_like

Particle/flux deposition per tile.

ianglearray_like

Angle of incidence i.e. the angle between particle velocity and the surface normal.

When weights are included, the angle of incidence is the average of all markers that hit the tile weighted by the marker energy and weight. Otherwise it is the mean value of all markers without any weights.

ls(show=True)

Get a string representation of the contents.

Parameters:
showstr, optional

If True, the contents are also printed on screen.

Returns:
contentsstr

Multiline string decorated with ANSI escape sequences that list this node’s meta data, all output data within this node, and inputs that were used.

plotorbit_poincare(plane, connlen=True, markersize=2, alternative_coords=False, axes=None, cax=None)

Create a Poincaré plot where the color separates different markers or shows the connection length.

Parameters:
planestr

The Poincaré plane to be plotted.

The argument is expected to have format “pol/tor/rad i” where the first part specifies the type of the plane (poloidal, toroidal, radial) and the second argument is the plane index. For example, plane="pol 2" plots the second poloidal plane. The order of the planes is same as given by getorbit_poincareplanes().

connlenbool, optional

Show connection length and separated lost and confined markers with color.

If true, trajectories of lost markers are colored (in blue shades) where the color shows the connection length at that position. Confined (or all if conlen=False) markers are shown with shades of red where color separates subsequent trajectories.

markersizeint, optional

Marker size on plot.

alternative_coordsbool, optional

Use alternative coordinate axes to visualize the plot.

The default axes are (R,z) for the poloidal plot and (rho,phi) for the toroidal plot. If `alternative_coords`=True, these are changed to (rho,theta) and (R,phi), respectively.

axesAxes, optional

The axes where figure is plotted or otherwise new figure is created.

caxAxes, optional

The color bar axes or otherwise taken from the main axes.

Raises:
ValueError

Raised when the plane is unknown.

plotorbit_trajectory(x, y, z=None, c=None, endcond=None, ids=None, cmap=None, axesequal=False, axes=None, cax=None)

Plot orbit trajectories in arbitrary coordinates.

The plot is either 2D+1D or 3D+1D, where the extra coordinate is color, depending on the number of queried coordinates. The color scale is discrete, not continuous.

The quantity (“qnt”) must have one of the following formats:

  • “diff qnt” plots the difference between inistate and current value.

  • “reldiff qnt” plots the relative difference (x1/x0 - 1).

  • “log <diff/reldiff> qnt” plots the logarithmic value.

Parameters:
xstr

Name of the quantity on x-axis.

ystr

Name of the quantity on y-axis.

zstr, optional

Name of the quantity on z-axis.

If not None, the plot will be in 3D.

cstr, optional

The color used to plot the markers or name of the quantity shown with color.

If None, markers are plotted with different colors.

endcondstr, array_like, optional

Endcond of those markers which are plotted.

idsarray_like

IDs of the markers to be plotted.

cmapstr, optional

Colormap.

axesequalbool, optional

Flag whether to set aspect ratio for x and y (and z) axes equal.

axesAxes, optional

The axes where figure is plotted or otherwise new figure is created.

caxAxes, optional

The color bar axes or otherwise taken from the main axes.

plotstate_histogram(x, y=None, xbins=10, ybins=10, xmode='gc', ymode='gc', endcond=None, ids=None, weight=False, logscale=False, cmap=None, axesequal=False, axes=None, cax=None)

Make a histogram plot of marker state coordinates.

The histogram is either 1D or 2D depending on if the y coordinate is provided. In the 1D histogram the markers with different endstate are separated by color if the endcond argument is None.

The quantity (“qnt”) must have one of the following formats:

  • “ini qnt” plots inistate of quantity qnt.

  • “end qnt” plots endstate of quantity qnt.

  • “diff qnt” plots the difference between ini and endstate.

  • “reldiff qnt” plots the relative difference (x1/x0 - 1).

  • “log ini/end/diff/reldiff qnt” plots the logarithmic value.

Parameters:
xstr

Name of the quantity on x-axis.

ystr, optional

Name of the quantity on y-axis.

If not None, the histogram will be in 2D.

xbinsint or array_like, optional

Bin edges for the x coordinate or the number of bins.

ybinsint or array_like, optional

Bin edges for the y coordinate or the number of bins.

xmode{“prt”, “gc”}, optional

Evaluate x quantity in particle or guiding-center phase space.

ymode{“prt”, “gc”}, optional

Evaluate y quantity in particle or guiding-center phase space.

endcondstr, array_like, optional

Endcond of those markers which are plotted.

If None and the plot is in 1D, the histogram will be stacked with different colors indicating different end conditions.

idsarray_like

IDs of the markers to be plotted.

weightbool

Whether to weight markers when they are binned to the histogram.

The weighted histogram represents physical particles whereas the unweighted histogram corresponds to markers.

cmapstr, optional

Name of the colormap used in the 2D histogram.

axesequalbool, optional

Flag whether to set aspect ratio for x and y axes equal in 2D.

axesAxes, optional

The axes where figure is plotted or otherwise new figure is created.

caxAxes, optional

The color bar axes or otherwise taken from the main axes.

plotstate_scatter(x, y, z=None, c=None, xmode='gc', ymode='gc', zmode='gc', cmode='gc', endcond=None, ids=None, cint=9, cmap=None, axesequal=False, axes=None, cax=None)

Make a scatter plot of marker state coordinates.

The plot is either 2D+1D or 3D+1D, where the extra coordinate is color, depending on the number of queried coordinates. The color scale is discrete, not continuous.

The quantity (“qnt”) must have one of the following formats:

  • “ini qnt” plots inistate of quantity qnt.

  • “end qnt” plots endstate of quantity qnt.

  • “diff qnt” plots the difference between ini and endstate.

  • “reldiff qnt” plots the relative difference (x1/x0 - 1).

  • “log ini/end/diff/reldiff qnt” plots the logarithmic value.

Parameters:
xstr

Name of the quantity on x-axis.

ystr

Name of the quantity on y-axis.

zstr, optional

Name of the quantity on z-axis.

If not None, the plot will be in 3D.

cstr, optional

Name of the quantity shown with color scale or name of a color to plot all markers with same color.

xmode{“prt”, “gc”}, optional

Evaluate x quantity in particle or guiding-center phase space.

ymode{“prt”, “gc”}, optional

Evaluate y quantity in particle or guiding-center phase space.

zmode{“prt”, “gc”}, optional

Evaluate z quantity in particle or guiding-center phase space.

cmode{“prt”, “gc”}, optional

Evaluate color quantity in particle or guiding-center phase space.

endcondstr, array_like, optional

Endcond of those markers which are plotted.

idsarray_like

IDs of the markers to be plotted.

cintint or array_like optional

Number of colors to be used or bin edges.

All markers that have cint[i] < c <= cint[i+1] are plotted with same color. If cint array is not given explicitly, cint = np.linspace(min(c), max(c), cint).

cmapstr, optional

Name of the colormap where colors are picked.

axesequalbool, optional

Flag whether to set aspect ratio for x and y (and z) axes equal.

axesAxes, optional

The axes where figure is plotted or otherwise new figure is created.

caxAxes, optional

The color bar axes or otherwise taken from the main axes.

Raises:
AscotNoDataException

Raised when data required for the opreation is not present.

ValueError

If argument could not be parsed.

plotwall_2D_contour(axes=None, particle_load=False, ref_indices=None, colors=None, clog='linear', cmap=None, ref_cmap='jet', xlabel=None, ylabel=None, clabel=None)

Plot heat loads as in the 2D wall contour with a colorbar.

Parameters:
axesAxes, optional

The axes where figure is plotted or otherwise new figure is created.

particle_loadbool, optional

Plot particle fluxes instead of powerloads.

ref_indices{array_like, int}, optional

Plot 2D wall points given by ref_indices.

colorsarraylike, optional

Colors of all drawn indices. Must be same length as ref_indices.

clog{“linear”, “log”, “symlog”}, optional

color-axis scaling.

cmapstr, optional

Name of the colormap.

ref_cmapstr, optional

Name of the colormap for ref_indices.

xlabelstr, optional

Label for the x-axis.

ylabelstr, optional

Label for the y-axis.

clabelstr, optional

Label for the color axis.

plotwall_2D_parametrized(axes=None, particle_load=False, ref_indices=None, colors=None, xlabel=None, ylabel=None, ref_cmap='jet')

Plot heat loads as a function of the parametrized wall contour.

Parameters:
axesAxes, optional

The axes where figure is plotted or otherwise new figure is created.

particle_loadbool, optional

Plot particle fluxes instead of powerloads.

ref_indices{array_like, int}, optional

Plot 2D wall points given by ref_indices.

colorsarraylike, optional

Colors of all drawn indices. Must be same length as ref_indices.

xlabelstr, optional

Label for the x-axis.

ylabelstr, optional

Label for the y-axis.

ref_cmapstr, optional

Name of the colormap for ref_indices.

plotwall_3dinteractive(wallmesh=None, *args, points=None, orbit=None, data=None, log=False, clim=None, cpos=None, cfoc=None, cang=None, p_ids=None, w_indices=None, **kwargs)

Open vtk window to display interactive view of the wall mesh.

Parameters:
wallmesh, optionalPolydata

Mesh representing the wall. If not given then construct the mesh from the wall data.

*argstuple (str, method), optional

Key (str) method pairs. When key is pressed when the plot is displayed, the associated method is called. The method should take Plotter instance as an argument.

pointsarray_like, optional

Array Npoint x 3 defining points (markers) to be shown. For each point [x, y, z] coordinates are given. If boolean True is given, then markers are read from the endstate.

orbitint, optional

ID of a marker whose orbit is plotted.

datastr, optional

Name of the cell data in the wall mesh that is shown in color.

logbool, optional

Color range is logarithmic if True.

clim[float, float], optional

Color [min, max] limits.

cposarray_like, optional

Camera position coordinates [x, y, z].

cfocarray_like, optional

Camera focal point coordinates [x, y, z].

cangarray_like, optional

Camera angle [azimuth, elevation, roll].

p_idsarray_like, optional

List of ids of the particles for which the heat load is shown.

w_indicesarray_like, optional

List of wall indices which are included in the wall mesh.

**kwargs

Keyword arguments passed to Plotter.

plotwall_3dstill(wallmesh=None, points=None, orbit=None, data=None, log=False, clim=None, cpos=None, cfoc=None, cang=None, p_ids=None, w_indices=None, axes=None, cax=None, **kwargs)

Take a still shot of the mesh and display it using matplotlib backend.

The rendering is done using vtk but the vtk (interactive) window is not displayed. It is recommended to use the interactive plot to find desired camera position and produce the actual plot using this method. The plot is shown using imshow and acts as a regular matplotlib plot.

Parameters:
wallmeshPolydata

Mesh representing the wall. If not given then construct the mesh from the wall data.

points{array_like, bool}, optional

Array Npoint x 3 defining points (markers) to be shown. For each point [x, y, z] coordinates are given. If boolean True is given, then markers are read from the endstate.

orbitint, optional

ID of a marker whose orbit is plotted.

datastr, optional

Name of the cell data in the wall mesh that is shown in color.

logbool, optional

Color range is logarithmic if True.

clim[float, float], optional

Color [min, max] limits.

cposarray_like, optional

Camera position coordinates [x, y, z].

cfocarray_like, optional

Camera focal point coordinates [x, y, z].

cangarray_like, optional

Camera angle [azimuth, elevation, roll].

p_idsarray_like, optional

List of ids of the particles for which the heat load is shown.

w_indicesarray_like, optional

List of wall indices which are included in the wall mesh.

axesAxes, optional

The axes where figure is plotted or otherwise new figure is created.

caxAxes, optional

The color bar axes or otherwise taken from the main axes.

**kwargs

Keyword arguments passed to Plotter.

plotwall_convergence(qnt, nmin=1000, nsample=10, axes=None)

Plot convergence of losses by subsampling the results.

This function works by picking randomly a subset of n (< Total number of markers) from the results, and reweighting those so that the total weight of the subset is equal to the original. The subset is then used to calculate the figure of merit. Several samples are taken with n = np.logspace(nmin, ntotal, nsample) to show how the results converge.

Parameters:
qnt{“lostpower”, “peakload”}

The name of the quantity for which the converge is plotted.

nminint, optional

Number of markers in the smallest sample.

nsampleint, optional

Number of samples.

axesAxes, optional

The axes where figure is plotted or otherwise new figure is created.

plotwall_loadvsarea(axes=None)

Plot histogram showing area affected by at least a given load.

Parameters:
axesAxes, optional

The axes where figure is plotted or otherwise new figure is created.

plotwall_torpol(qnt='eload', getaxis=None, log=True, clim=None, cmap=None, axes=None, cax=None)

Plot the toroidal-poloidal projection of the wall loads.

Note that the resulting doesn’t present the areas accurately and even the locations are approximate. The purpose of the plot is to roughly illustrate how the losses are distributed.

Parameters:
qnt{‘eload’, ‘pload’, ‘iangle’}, optional

Quantity to plot.

getaxis(float, float) or callable()

Location of the magnetic or geometrical axis which is used to determine the poloidal angle.

If this parameter is None (default), the magnetic axis evaluated via libascot is used (requires that bfield is initialized).

For tokamaks, a tuple of two floats corresponding to the axis (R,z) coordinates can be given explicitly.

For stellarators, one can provide a function that takes one positional argument phi (float), which is the toroidal angle in degress, and returns a tuple of axis (R,z) coordinates at that toroidal angle.

logbool, optional

Make the color scale logarithmic.

clim[float, float], optional

Minimum and maximum values in the color scale.

cmapstr, optional

Colormap to be used.

Defaults to ‘Reds’ for ‘eload’ and ‘pload’ and ‘viridis’ for ‘iangle’.

axesAxes, optional

The axes where figure is plotted or otherwise new figure is created.

caxAxes, optional

The color bar axes or otherwise taken from the main axes.

set_desc(desc)

Set description for this group.

Note that the first word in the description is this group’s tag which can be used to refer to this group.

Parameters:
descstr

Short description for the user to document this group.

class a5py.ascot5io.AfsiGroup(root, path, h5, inputqids, **kwargs)

Bases: ResultNode, AfsiMixin

Node containing AFSI results and methods to process them.

activate()

Set this group as active.

Active inputs are used when the simulation is run. Active groups are also used during post-processing.

destroy(repack=True)

Remove this group from the HDF5 file.

Parameters:
repackbool, optional

If True, repack the HDF5 file.

Removing data from the HDF5 file only removes references to it and repacking is required to free the disk space. Repacking makes a copy of the HDF5 file and destroys the original, and it also requires 3rd party tool h5repack which is why it’s use is optional here.

export(target_file, newgroup=False)

Copy this group with its contents to another HDF5 file.

Parameters:
target_filestr

Path to the file where the data is copied to.

newgroupbool, optional

If True, a new QID and date is generated for the copied group.

get_contents()

Return names of all childs.

Returns:
nameslist [str]

List of names.

get_date()

Get the date when this group was created.

Returns:
datestr

The date in YYYY-MM-DD hh:mm:ss format.

get_desc()

Get this group’s description.

Returns:
descstr

Documentation the user has used to describe this group.

get_name()

Return name of this group.

Returns:
namestr

The name of the group as “<group type>_<group qid>”.

get_qid()

Get QID of this group.

Returns:
qidstr

String with 10 characters containing numbers from 0-9 which is an unique identifier for this group.

get_type()

Return type of this group.

Returns:
gtypestr

Group type.

getdist(dist, exi=False, ekin_edges=None, pitch_edges=None, plotexi=False)

Return 5D distribution function of one of the fusion products.

Parameters:
dist{“prod1”, “prod2”}

Which product to return.

exibool, optional

Convert the momentum space to energy-pitch.

The distribution is normalized to conserve the particle number.

ekin_edgesint or array_like, optional

Number of bins or bin edges in the energy abscissa if exi=True.

pitch_edgesint or array_like, optional

Number of bins or bin edges in the pitch abscissa if exi=True.

plotexibool, optional

Visualize the transformation from ppar-perp to energy-pitch if if exi=True.

Use this option to adjust energy and pitch abscissae to your liking.

Returns:
dataDistData

The distribution data object.

ls(show=True)

Get a string representation of the contents.

Parameters:
showstr, optional

If True, the contents are also printed on screen.

Returns:
contentsstr

Multiline string decorated with ANSI escape sequences that list this node’s meta data, all output data within this node, and inputs that were used.

set_desc(desc)

Set description for this group.

Note that the first word in the description is this group’s tag which can be used to refer to this group.

Parameters:
descstr

Short description for the user to document this group.

class a5py.ascot5io.BBNBIGroup(root, path, h5, inputqids, **kwargs)

Bases: ResultNode, BBNBIMixin

Node containing BBNBI results and methods to process them.

activate()

Set this group as active.

Active inputs are used when the simulation is run. Active groups are also used during post-processing.

destroy(repack=True)

Remove this group from the HDF5 file.

Parameters:
repackbool, optional

If True, repack the HDF5 file.

Removing data from the HDF5 file only removes references to it and repacking is required to free the disk space. Repacking makes a copy of the HDF5 file and destroys the original, and it also requires 3rd party tool h5repack which is why it’s use is optional here.

export(target_file, newgroup=False)

Copy this group with its contents to another HDF5 file.

Parameters:
target_filestr

Path to the file where the data is copied to.

newgroupbool, optional

If True, a new QID and date is generated for the copied group.

get_contents()

Return names of all childs.

Returns:
nameslist [str]

List of names.

get_date()

Get the date when this group was created.

Returns:
datestr

The date in YYYY-MM-DD hh:mm:ss format.

get_desc()

Get this group’s description.

Returns:
descstr

Documentation the user has used to describe this group.

get_name()

Return name of this group.

Returns:
namestr

The name of the group as “<group type>_<group qid>”.

get_qid()

Get QID of this group.

Returns:
qidstr

String with 10 characters containing numbers from 0-9 which is an unique identifier for this group.

get_type()

Return type of this group.

Returns:
gtypestr

Group type.

getdist(dist, exi=False, ekin_edges=None, pitch_edges=None, plotexi=False)

Return distribution function.

Parameters:
dist{“5d”, “6d”, “rho5d”, “rho6d”, “com”}

Name of the distribution.

If dist is None, returns a list of available distributions.

exibool, optional

Convert the momentum space to energy-pitch.

The distribution is normalized to conserve the particle number.

Not applicable for dist = {“6d”, “rho6d”, “com”}.

ekin_edgesint or array_like, optional

Number of bins or bin edges in the energy abscissa if exi=True.

pitch_edgesint or array_like, optional

Number of bins or bin edges in the pitch abscissa if exi=True.

plotexibool, optional

Visualize the transformation from ppar-perp to energy-pitch if if exi=True.

Use this option to adjust energy and pitch abscissae to your liking.

Returns:
dataDistData or list [str]

The distribution data object or a list of available distributions if dist is None.

getstate(*qnt, mode='gc', ids=None, endcond=None)

Evaluate a marker quantity based on its state.

Parameters:
*qntstr

Names of the quantities.

idsarray_like, optional

Filter markers by their IDs.

endcondstr or list [str], optional

Filter markers by their end conditions.

Returns:
valarray_like

The evaluated quantity sorted by marker ID.

If multiple quantities are queried, they are returned as a list in

the order they were listed in *qnt.

Raises:
ValueError

Raised when the queried quantity could not be interpreted.

AscotNoDataException

Raised when data required for the operation is not present.

AscotInitException

If evaluating quantity required interpolating an input that was not initialized.

getstate_markers(mrktype, ids=None)

Convert state to marker input.

Parameters:
mrktype{“prt”, “gc”, “fl”}

Type of marker input to be created.

idsarray_like, optional

Select only these markers for the output.

Returns:
mrkdict

Markers parameters that can be supplied to Prt.write_hdf5(), GC.write_hdf5() or FL.write_hdf5() depending on mrktype value.

getstate_markersummary()

Return a summary of marker end conditions and errors present in the data.

Returns:
econdslist [(int, str)]

List of present end conditions.

Each list member is a tuple, where first item is the number of markers with the end condition specified in the second item.

emsglist [(str, int, str)]

List of present errors.

Each list member is a tuple, where first item is the error message, second the line number where error was raised, and third is the name of the file.

Raises:
AscotNoDataException

Raised when data required for the operation is not present.

getwall_3dmesh()

Return 3D mesh representation of 3D wall and associated loads.

Returns:
wallmeshPolydata

Mesh representing the wall.

The mesh cell data has fields:

  • “pload” particle load in units of prt/m^2 or prt/m^2s,

  • “eload” power/energy load in units of W/m^2 or J/m^2

getwall_figuresofmerit()

Get peak power load and other 0D quantities related to wall loads.

Returns:
wareafloat

Total wetted area.

ploadfloat

Peak power load.

getwall_loads(weights=True)

Get wall loads and associated quantities.

This method does not return loads on all wall elements (as usually most of them receive no loads) but only those that are affected and their IDs.

Parameters:
weightsbool, optional

Include marker weights to get physical results (otherwise particle deposition would be just the number of markers that hit the tile).

Dropping weights is useful to check how many markers hit a tile which tells us how good the statistics are.

Returns:
idsarray_like

Indices of loaded wall tiles.

areaarray_like

Area of each tile.

edepoarray_like

Energy/power deposition per tile.

pdepoarray_like

Particle/flux deposition per tile.

ianglearray_like

Angle of incidence (TODO).

ls(show=True)

Get a string representation of the contents.

Parameters:
showstr, optional

If True, the contents are also printed on screen.

Returns:
contentsstr

Multiline string decorated with ANSI escape sequences that list this node’s meta data, all output data within this node, and inputs that were used.

plotwall_3dinteractive(wallmesh=None, *args, points=None, orbit=None, data=None, log=False, cpos=None, cfoc=None, cang=None, **kwargs)

Open vtk window to display interactive view of the wall mesh.

Parameters:
wallmesh, optionalPolydata

Mesh representing the wall. If not given then construct the mesh from the wall data.

*argstuple (str, method), optional

Key (str) method pairs. When key is pressed when the plot is displayed, the associated method is called. The method should take Plotter instance as an argument.

pointsarray_like, optional

Array Npoint x 3 defining points (markers) to be shown. For each point [x, y, z] coordinates are given. If boolean True is given, then markers are read from the endstate.

datastr, optional

Name of the cell data in the wall mesh that is shown in color.

cposarray_like, optional

Camera position coordinates [x, y, z].

cfocarray_like, optional

Camera focal point coordinates [x, y, z].

cangarray_like, optional

Camera angle [azimuth, elevation, roll].

**kwargs

Keyword arguments passed to Plotter.

plotwall_3dstill(wallmesh=None, points=None, data=None, log=False, cpos=None, cfoc=None, cang=None, axes=None, cax=None, **kwargs)

Take a still shot of the mesh and display it using matplotlib backend.

The rendering is done using vtk but the vtk (interactive) window is not displayed. It is recommended to use the interactive plot to find desired camera position and produce the actual plot using this method. The plot is shown using imshow and acts as a regular matplotlib plot.

Parameters:
wallmeshPolydata

Mesh representing the wall. If not given then construct the mesh from the wall data.

points{array_like, bool}, optional

Array Npoint x 3 defining points (markers) to be shown. For each point [x, y, z] coordinates are given. If boolean True is given, then markers are read from the endstate.

datastr, optional

Name of the cell data in the wall mesh that is shown in color.

cposarray_like, optional

Camera position coordinates [x, y, z].

cfocarray_like, optional

Camera focal point coordinates [x, y, z].

cangarray_like, optional

Camera angle [azimuth, elevation, roll].

axesAxes, optional

The axes where figure is plotted or otherwise new figure is created.

caxAxes, optional

The color bar axes or otherwise taken from the main axes.

**kwargs

Keyword arguments passed to Plotter.

plotwall_torpol(log=True, clim=None, axes=None, cax=None)

Plot the toroidal-poloidal projection of the wall loads.

Note that the resulting doesn’t present the areas accurately and even the locations are approximate. The purpose of the plot is to roughly illustrate how the losses are distributed.

Parameters:
logbool, optional

Make the color scale logarithmic.

clim[float, float], optional

Minimum and maximum values in the color scale.

axesAxes, optional

The axes where figure is plotted or otherwise new figure is created.

caxAxes, optional

The color bar axes or otherwise taken from the main axes.

set_desc(desc)

Set description for this group.

Note that the first word in the description is this group’s tag which can be used to refer to this group.

Parameters:
descstr

Short description for the user to document this group.

class a5py.ascot5io.InputGroup(root, path, h5, **kwargs)

Bases: InputNode

Node containing input data groups.

destroy(repack=True)

Remove this group from the HDF5 file.

Parameters:
repackbool, optional

If True, repack the HDF5 file.

Removing data from the HDF5 file only removes references to it and repacking is required to free the disk space. Repacking makes a copy of the HDF5 file and destroys the original, and it also requires 3rd party tool h5repack which is why it’s use is optional here.

get_contents()

Return metadata for all childs sorted by date.

Returns:
qidsarray_like, str

QIDs.

datesarray_like, str

Dates.

descsarray_like, str

Descriptions.

typesarray_like, str

Data types.

ls(show=True)

Get a string representation of the contents.

Parameters:
showstr, optional

If True, the contents are also printed on screen.

Returns:
contentsstr

Multiline string decorated with ANSI escape sequences that list all data groups within this node.

class a5py.ascot5io.dist.DistData(histogram, **abscissa_edges)

Bases: object

Distribution data object.

Attributes:
abscissaelist [str]

Name of each abscissa in same order as they appear in the distribution.

_distributionarray_like

N-dimensional array, where N is the number of abscissae, containing the distribution data.

**abscissa_edgesarray_like

Edges of each abscissa stored as attributes with name “_<name of the abscissa>” e.g. “_r”.

abscissa(name)

Return abscissa values.

Parameters:
namestr

Name of the abscissa.

Returns:
abscissaarray_like

Abscissa values, i.e., the values at the center of each bin.

Raises:
ValueError

If name does not correspond to any abscissa.

abscissa_edges(name)

Return abscissa edges.

Parameters:
namestr

Name of the abscissa.

Returns:
abscissaarray_like

Abscissa bin edges.

Raises:
ValueError

If name does not correspond to any abscissa.

distribution()

Return the distribution function.

Returns:
distarray_like

N-dimensional array, where N is the number of abscissae, containing the distribution data.

histogram()

Return the distribution as a histogram (particles per bin).

Returns:
distarray_like

N-dimensional array, where N is the number of abscissae, containing the distribution data as a histogram.

integrate(copy=False, **abscissae)

Integrate distribution along the given dimension.

Parameters:
copybool, optional

Retain original distribution and return a copy which is integrated.

**abscissaeslice or array_like

Name of the coordinate and corresponding slice which is integrated.

If argument is an array, it must have the same size as the corresponding dimension. The integration is then performed as int f(x,…) * array(x) * dx.

Returns:
distDistData

The integrated distribution if copy=True.

interpolate(**coordinates)

Perform (N-dim) linear interpolation on the distribution.

Parameters:
**coordinatesslice

Name of the coordinate and value at which the distribution is interpolated.

Returns:
distarray_like

The distribution interpolated at given point.

phasespacevolume()

Calculate phase-space volume of each bin.

Returns:
volarray_like

Phase space volumes with units and same shape as the distribution.

plot(axes=None, cax=None, logscale=False)

Plot distribution in 1D or 2D.

This method assumes that the input distribution has been integrated, sliced, and interpolated so that only one or two dimensions have a size above one.

Parameters:
axesAxes, optional

The axes where figure is plotted or otherwise new figure is created.

caxAxes, optional

The color bar axes or otherwise taken from the main axes.

logscale: bool, optional

Whether the plot is in logarithmic scale.

slice(copy=False, **abscissae)

Take slices of distribution.

Parameters:
copybool, optional

Retain original distribution and return a copy which is sliced.

**abscissaeslice

Name of the coordinate and corresponding slice to be taken.

Returns:
distDistData

The sliced distribution if copy=True.

class a5py.ascot5io.dist.DistMoment(x1, x2, x3, r, phi, z, area, volume, rhodist)

Bases: object

Class that stores moments calculated from a distribution.

add_ordinates(**ordinates)

Add moments.

Parameters:
**ordinatesarray_like

Names and data for each ordinate to be added.

list_ordinates()

List all moments

ordinate(ordinate, toravg=False, polavg=False)

Return stored moment.

Parameters:
ordinatestr

Name of the moment.

toravgbool, optional

Return toroidal average of the ordinate.

polavgbool, optional

Return poloidal average of the ordinate.

Only valid if rhodist=True. Both toravg and polavg can be set simultaneously, in which a radial profile is returned.

Returns:
dataarray_like

Ordinate data.

plot(ordinate, axes=None, cax=None, logscale=False)

Plot radial or (R,z) profile of a distribution moment.

The plotted profile is the average of (theta, phi) or phi depending on whether the input is calculated from a rho distribution or not.

Parameters:
ordinatestr

Name of the moment to be plotted.

axesAxes, optional

The axes where figure is plotted or otherwise new figure is created.

caxAxes, optional

The color bar axes or otherwise taken from the main axes.

logscale: bool, optional

Whether the plot is in logarithmic scale.