xbout.boutdataarray.BoutDataArrayAccessor#

class xbout.boutdataarray.BoutDataArrayAccessor(da)[source]#

Bases: object

Contains BOUT-specific methods to use on BOUT++ dataarrays opened by selecting a variable from a BOUT++ dataset.

These BOUT-specific methods and attributes are accessed via the bout accessor, e.g. da.bout.options returns a BoutOptionsFile instance.

__init__(da)[source]#

Methods

__init__(da)

add_cartesian_coordinates()

Add Cartesian (X,Y,Z) coordinates.

animate1D([animate_over, animate, ...])

Plots a line plot which is animated over time over the specified coordinate.

animate2D([animate_over, x, y, animate, ...])

Plots a color plot which is animated with time over the specified coordinate.

contour([ax])

Contour-plot a radial-poloidal slice on the R-Z plane

contourf([ax])

Filled-contour-plot a radial-poloidal slice on the R-Z plane

ddx()

Special method for calculating a derivative in the "bout_xdim" direction (radial, x-direction), needed because the 1d coordinate in this direction is index number, not coordinate values (because psi can be different in core and PFR regions).

ddy([region])

Special method for calculating a derivative in the "bout_ydim" direction (parallel, y-direction), needed because we need to (a) do the calculation region-by-region to take account of the branch cuts in the y-direction and (b) transform to a field-aligned grid to take parallel derivatives.

ddz()

Special method for calculating a derivative in the "bout_zdim" direction (toroidal, z-direction), needed because xarray's differentiate method doesn't have an option to handle a periodic dimension (as of xarray-0.17.0).

from_field_aligned()

Transform DataArray from field-aligned coordinates, which are shifted with respect to the base coordinates by an angle zShift

from_region(name[, with_guards])

Get a logically-rectangular section of data from a certain region.

get_bounding_surfaces([coords])

Get bounding surfaces.

interpolate_from_unstructured(*[, ...])

Interpolate DataArray onto new grids of some existing coordinates

interpolate_parallel([region, n, ...])

Interpolate in the parallel direction to get a higher resolution version of the variable.

interpolate_to_cartesian(*args, **kwargs)

Interpolate the DataArray to a regular Cartesian grid.

pcolormesh([ax])

Colour-plot a radial-poloidal slice on the R-Z plane

plot3d([ax])

Make a 3d plot

plot_regions([ax])

Plot the regions into which xBOUT splits radial-poloidal arrays to handle tokamak topology.

remove_yboundaries([return_dataset, ...])

Remove y-boundary points, if present, from the DataArray

to_dataset()

Convert a DataArray to a Dataset, copying the attributes from the DataArray to the Dataset, and dropping attributes that only make sense for a DataArray

to_field_aligned()

Transform DataArray to field-aligned coordinates, which are shifted with respect to the base coordinates by an angle zShift

Attributes

fine_interpolation_factor

The default factor to increase resolution when doing parallel interpolation

add_cartesian_coordinates()[source]#

Add Cartesian (X,Y,Z) coordinates.

Returns:

  • DataArray with new coordinates added, which are named 'X_cartesian',

  • 'Y_cartesian', and 'Z_cartesian'

animate1D(animate_over=None, animate=True, axis_coords=None, fps=10, save_as=None, sep_pos=None, ax=None, **kwargs)[source]#

Plots a line plot which is animated over time over the specified coordinate.

Currently only supports 1D+1 data, which it plots with animatplot’s wrapping of matplotlib’s plot.

Parameters:
  • animate_over (str, optional) – Dimension over which to animate, defaults to the time dimension

  • axis_coords (None, str, dict) –

    Coordinates to use for axis labelling.

    • None: Use the dimension coordinate for each axis, if it exists.

    • ”index”: Use the integer index values.

    • dict: keys are dimension names, values set axis_coords for each axis separately. Values can be: None, “index”, the name of a 1d variable or coordinate (which must have the dimension given by ‘key’), or a 1d numpy array, dask array or DataArray whose length matches the length of the dimension given by ‘key’.

  • fps (int, optional) – Frames per second of resulting gif

  • save_as (True or str, optional) – If str is passed, save the animation as save_as+’.gif’. If True is passed, save the animation with a default name, ‘<variable name>_over_<animate_over>.gif’

  • sep_pos (int, optional) – Radial position at which to plot the separatrix

  • ax (Axes, optional) – A matplotlib axes instance to plot to. If None, create a new figure and axes, and plot to that

  • aspect (str or None, optional) – Argument to ax.set_aspect(), defaults to “auto”

  • kwargs (dict, optional) – Additional keyword arguments are passed on to the plotting function (animatplot.blocks.Line).

Returns:

If animate==True, returns an animatplot.Animation object, otherwise returns an animatplot.blocks.Line instance.

Return type:

animation or block

animate2D(animate_over=None, x=None, y=None, animate=True, axis_coords=None, fps=10, save_as=None, ax=None, poloidal_plot=False, logscale=None, **kwargs)[source]#

Plots a color plot which is animated with time over the specified coordinate.

Currently only supports 2D+1 data, which it plots with animatplot’s wrapping of matplotlib’s pcolormesh.

Parameters:
  • animate_over (str, optional) – Dimension over which to animate, defaults to the time dimension

  • x (str, optional) – Dimension to use on the x axis, default is None - then use the first spatial dimension of the data

  • y (str, optional) – Dimension to use on the y axis, default is None - then use the second spatial dimension of the data

  • animate (bool, optional) – If set to false, do not create the animation, just return the block or blocks

  • axis_coords (None, str, dict) –

    Coordinates to use for axis labelling.

    • None: Use the dimension coordinate for each axis, if it exists.

    • ”index”: Use the integer index values.

    • dict: keys are dimension names, values set axis_coords for each axis separately. Values can be: None, “index”, the name of a 1d variable or coordinate (which must have the dimension given by ‘key’), or a 1d numpy array, dask array or DataArray whose length matches the length of the dimension given by ‘key’.

    Only affects time coordinate for plots with poloidal_plot=True.

  • fps (int, optional) – Frames per second of resulting gif

  • save_as (True or str, optional) – If str is passed, save the animation as save_as+’.gif’. If True is passed, save the animation with a default name, ‘<variable name>_over_<animate_over>.gif’

  • ax (matplotlib.pyplot.axes object, optional) – Axis on which to plot the gif

  • poloidal_plot (bool, optional) – Use animate_poloidal to make a plot in R-Z coordinates (input field must be (t,x,y))

  • logscale (bool or float, optional) – If True, default to a logarithmic color scale instead of a linear one. If a non-bool type is passed it is treated as a float used to set the linear threshold of a symmetric logarithmic scale as linthresh=min(abs(vmin),abs(vmax))*logscale, defaults to 1e-5 if True is passed.

  • aspect (str or None, optional) – Argument to set_aspect(). Defaults to “equal” for poloidal plots and “auto” for others.

  • kwargs (dict, optional) – Additional keyword arguments are passed on to the plotting function (animatplot.blocks.Pcolormesh).

Returns:

If animate==True, returns an animatplot.Animation object, otherwise returns a list of animatplot.blocks.Pcolormesh instances.

Return type:

animation or blocks

contour(ax=None, **kwargs)[source]#

Contour-plot a radial-poloidal slice on the R-Z plane

contourf(ax=None, **kwargs)[source]#

Filled-contour-plot a radial-poloidal slice on the R-Z plane

ddx()[source]#

Special method for calculating a derivative in the “bout_xdim” direction (radial, x-direction), needed because the 1d coordinate in this direction is index number, not coordinate values (because psi can be different in core and PFR regions).

This method uses a second-order accurate central finite difference method to calculate the derivative.

Note values at the boundaries will be NaN - if Dataset was loaded with keep_xboundaries=True, these should only ever be in boundary cells.

ddy(region=None)[source]#

Special method for calculating a derivative in the “bout_ydim” direction (parallel, y-direction), needed because we need to (a) do the calculation region-by-region to take account of the branch cuts in the y-direction and (b) transform to a field-aligned grid to take parallel derivatives.

This method uses a second-order accurate central finite difference method to calculate the derivative. It transforms to a globally field-aligned grid to calculate the derivative - there is currently no option to use the same method as the BOUT++ approach using ‘yup’ and ‘ydown’ fields.

Note values at the boundaries will be NaN - if Dataset was loaded with keep_yboundaries=True, these should only ever be in boundary cells.

Warning

Depending on how parallel boundary conditions were applied in the BOUT++ PhysicsModel, the y-boundary cells may not contain valid data, in which case the result may be incorrect in the grid cell closest to the boundary.

Parameters:

region (str, optional) – By default, return a result with the derivative calculated in all regions separately and then combined. If an explicit region argument is passed, then return the result from only that region.

Return type:

A new DataArray containing the y-derivative of the variable.

ddz()[source]#

Special method for calculating a derivative in the “bout_zdim” direction (toroidal, z-direction), needed because xarray’s differentiate method doesn’t have an option to handle a periodic dimension (as of xarray-0.17.0).

This method uses a second-order accurate central finite difference method to calculate the derivative.

property fine_interpolation_factor#

The default factor to increase resolution when doing parallel interpolation

from_field_aligned()[source]#

Transform DataArray from field-aligned coordinates, which are shifted with respect to the base coordinates by an angle zShift

from_region(name, with_guards=None)[source]#

Get a logically-rectangular section of data from a certain region. Includes guard cells from neighbouring regions.

Parameters:
  • name (str) – Region to get data for

  • with_guards (int or dict of int, optional) – Number of guard cells to include, by default use MXG and MYG from BOUT++. Pass a dict to set different numbers for different coordinates.

get_bounding_surfaces(coords=('R', 'Z'))[source]#

Get bounding surfaces. Surfaces are returned as arrays of points describing a polygon, assuming the third spatial dimension is a symmetry direction.

Parameters:

coords ((str, str), default (``”R”, ``"Z")) – Pair of names of coordinates whose values are used to give the positions of the points in the result

Returns:

result – Each DataArray in the list contains points on a boundary, with size (<number of points in the bounding polygon>, 2). Points wind clockwise around the outside domain, and anti-clockwise around the inside (if there is an inner boundary).

Return type:

list of DataArrays

interpolate_from_unstructured(*, fill_value=nan, structured_output=True, unstructured_dim_name='unstructured_dim', **kwargs)[source]#

Interpolate DataArray onto new grids of some existing coordinates

Parameters:
  • **kwargs ((str, array)) – Each keyword is the name of a coordinate in the DataArray, the argument is a 1d array giving the values of that coordinate on the output grid

  • fill_value (float, default np.nan) – fill_value passed through to scipy.interpolation.griddata

  • structured_output (bool, default True) – If True, treat output coordinates values as a structured grid. If False, output coordinate values must all have the same length and are not broadcast together.

  • unstructured_dim_name (str, default "unstructured_dim") – Name used for the dimension in the output that replaces the dimensions of the interpolated coordinates. Only used if structured_output=False.

Returns:

Data interpolated onto a new, structured grid

Return type:

DataArray

interpolate_parallel(region=None, *, n=None, toroidal_points=None, method='cubic', return_dataset=False)[source]#

Interpolate in the parallel direction to get a higher resolution version of the variable.

Parameters:
  • region (str, optional) – By default, return a result with all regions interpolated separately and then combined. If an explicit region argument is passed, then return the variable from only that region.

  • n (int, optional) – The factor to increase the resolution by. Defaults to the value set by BoutDataset.setupParallelInterp(), or 10 if that has not been called.

  • toroidal_points (int or sequence of int, optional) – If int, number of toroidal points to output, applies a stride to toroidal direction to save memory usage. If sequence of int, the indexes of toroidal points for the output.

  • method (str, optional) – The interpolation method to use. Options from xarray.DataArray.interp(), currently: linear, nearest, zero, slinear, quadratic, cubic. Default is ‘cubic’.

  • return_dataset (bool, optional) – If this is set to True, return a Dataset containing this variable as a member (by default returns a DataArray). Only used when region=None.

Returns:

  • A new DataArray containing a high-resolution version of the variable. (If

  • return_dataset=True, instead returns a Dataset containing the DataArray.)

interpolate_to_cartesian(*args, **kwargs)[source]#

Interpolate the DataArray to a regular Cartesian grid.

This method is intended to be used to produce data for visualisation, which normally does not require double-precision values, so by default the data is converted to numpy.float32. Pass use_float32=False to retain the original precision.

Parameters:
  • nX (int (default 300)) – Number of grid points in the X direction

  • nY (int (default 300)) – Number of grid points in the Y direction

  • nZ (int (default 100)) – Number of grid points in the Z direction

  • use_float32 (bool (default True)) – Downgrade precision to numpy.float32?

  • fill_value (float (default np.nan)) – Value to use for points outside the interpolation domain (passed to scipy.interpolate.RegularGridInterpolator)

See also

BoutDataset.interpolate_to_cartesian

pcolormesh(ax=None, **kwargs)[source]#

Colour-plot a radial-poloidal slice on the R-Z plane

plot3d(ax=None, **kwargs)[source]#

Make a 3d plot

Warning

3d plotting functionality is still a bit of a work in progress. Bugs are likely, and help developing is welcome!

Parameters:

plotfuncs.plot3d() (See) –

plot_regions(ax=None, **kwargs)[source]#

Plot the regions into which xBOUT splits radial-poloidal arrays to handle tokamak topology.

remove_yboundaries(return_dataset=False, remove_extra_upper=False)[source]#

Remove y-boundary points, if present, from the DataArray

Parameters:

return_dataset (bool, default False) – Return the result as a Dataset containing the new DataArray.

to_dataset()[source]#

Convert a DataArray to a Dataset, copying the attributes from the DataArray to the Dataset, and dropping attributes that only make sense for a DataArray

to_field_aligned()[source]#

Transform DataArray to field-aligned coordinates, which are shifted with respect to the base coordinates by an angle zShift