API reference¶
xbout.boutdataarray module¶
- 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 aBoutOptionsFile
instance.- 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 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
- 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.
- Returns
- 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.)
- 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.
xbout.boutdataset module¶
- class xbout.boutdataset.BoutDatasetAccessor(ds)[source]¶
Bases:
object
Contains BOUT-specific methods to use on BOUT++ datasets opened using
open_boutdataset()
.These BOUT-specific methods and attributes are accessed via the bout accessor, e.g.
ds.bout.options
returns aBoutOptionsFile
instance.- animate_list(variables, animate_over=None, save_as=None, show=False, fps=10, nrows=None, ncols=None, poloidal_plot=False, axis_coords=None, subplots_adjust=None, vmin=None, vmax=None, logscale=None, titles=None, aspect=None, extend=None, controls='both', tight_layout=True, **kwargs)[source]¶
- Parameters
variables (list of str or BoutDataArray) – The variables to plot. For any string passed, the corresponding variable in this DataSet is used - then the calling DataSet must have only 3 dimensions. It is possible to pass BoutDataArrays to allow more flexible plots, e.g. with different variables being plotted against different axes.
animate_over (str, optional) – Dimension over which to animate, defaults to the time dimension
save_as (str, optional) – If passed, a gif is created with this filename
show (bool, optional) – Call pyplot.show() to display the animation
fps (float, optional) – Indicates the number of frames per second to play
nrows (int, optional) – Specify the number of rows of plots
ncols (int, optional) – Specify the number of columns of plots
poloidal_plot (bool or sequence of bool, optional) – If set to True, make all 2D animations in the poloidal plane instead of using grid coordinates, per variable if sequence is given
axis_coords (None, str, dict or list of None, str or 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. If a list is passed, it must have the same length as ‘variables’ and gives the axis_coords setting for each plot individually. The setting to use for the ‘animate_over’ coordinate can be passed in one or more dict values, but must be the same in all dicts if given more than once.
subplots_adjust (dict, optional) – Arguments passed to fig.subplots_adjust()()
vmin (float or sequence of floats) – Minimum value for color scale, per variable if a sequence is given
vmax (float or sequence of floats) – Maximum value for color scale, per variable if a sequence is given
logscale (bool or float, sequence of 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. Per variable if sequence is given.
titles (sequence of str or None, optional) – Custom titles for each plot. Pass None in the sequence to use the default for a certain variable
aspect (str or None, or sequence of str or None, optional) – Argument to set_aspect() for each plot. Defaults to “equal” for poloidal plots and “auto” for others.
extend (str or None, optional) – Passed to fig.colorbar()
controls (string or None, default "both") – By default, add both the timeline and play/pause toggle to the animation. If “timeline” is passed add only the timeline, if “toggle” is passed add only the play/pause toggle. If None or an empty string is passed, add neither.
tight_layout (bool or dict, optional) – If set to False, don’t call tight_layout() on the figure. If a dict is passed, the dict entries are passed as arguments to tight_layout()
**kwargs (dict, optional) – Additional keyword arguments are passed on to each animation function, per variable if a sequence is given.
- Returns
An animatplot.Animation object.
- Return type
animation
- property fine_interpolation_factor¶
The default factor to increase resolution when doing parallel interpolation
- from_field_aligned()[source]¶
Create a new Dataset with all 3d variables transformed to non-field-aligned coordinates
- 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
- get_field_aligned(name, caching=True)[source]¶
Get a field-aligned version of a variable, calculating (and caching in the Dataset) if necessary
- Parameters
name (str) – Name of the variable to get field-aligned version of
caching (bool, optional) – Save the field-aligned variable in the Dataset (default: True)
- integrate_midpoints(variable, *, dims=None, cumulative_t=False)[source]¶
Integrate using the midpoint rule for spatial dimensions, and trapezium rule for time.
The quantity being integrated is assumed to be a scalar variable.
When doing a 1d integral in the ‘y’ dimension, the integral is calculated as a poloidal integral if the variable is on the standard grid (‘direction_y’ attribute is “Standard”), or as a parallel-to-B integral if the variable is on the field-aligned grid (‘direction_y’ attribute is “Aligned”).
When doing a 2d integral over ‘x’ and ‘y’ dimensions, the integral will be over poloidal cross-sections if the variable is not field-aligned (direction_y == “Standard”) and over field-aligned surfaces if the variable is field-aligned (direction_ == “Aligned”). The latter seems unlikely to be useful as the surfaces depend on the arbitrary origin used for zShift.
Is a method of BoutDataset accessor rather than of BoutDataArray so we can use other variables like
J
,g11
,g_22
for the integration.Note the xarray.DataArray.integrate() method uses the trapezium rule, which is not consistent with the way BOUT++ defines grid spacings as cell widths. Also, this way for example:
inner = da.isel(x=slice(i)).bout.integrate_midpoints() outer = da.isel(x=slice(i, None).bout.integrate_midpoints() total = da.bout.integrate_midpoints() inner + outer == total
while with the trapezium rule you would have to select
radial=slice(i+1)
for inner to get a similar relation to be true.- Parameters
variable (str or DataArray) – Name of the variable to integrate, or the variable itself as a DataArray.
dims (str, list of str or ...) – Dimensions to integrate over. Can be any combination of of the dimensions of the Dataset. Defaults to integration over all spatial dimensions. If
...
is passed, integrate over all dimensions including time.cumulative_t (bool, default False) – If integrating in time, return the cumulative integral (integral from the beginning up to each point in the time dimension) instead of the definite integral.
- interpolate_from_unstructured(variables, *, fill_value=nan, structured_output=True, unstructured_dim_name='unstructured_dim', **kwargs)[source]¶
Interpolate Dataset onto new grids of some existing coordinates
- Parameters
variables (str or sequence of str or ...) – The names of the variables to interpolate. If ‘variables=…’ is passed explicitly, then interpolate all variables in the Dataset.
**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) – 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
Dataset interpolated onto a new, structured grid
- Return type
Dataset
- interpolate_parallel(variables, **kwargs)[source]¶
Interpolate in the parallel direction to get a higher resolution version of a subset of variables.
Note that the high-resolution variables are all loaded into memory, so most likely it is necessary to select only a small number. The toroidal_points argument can also be used to reduce the memory demand.
- Parameters
variables (str or sequence of str or ...) – The names of the variables to interpolate. If ‘variables=…’ is passed explicitly, then interpolate all variables in the Dataset.
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’.
- Returns
A new Dataset containing a high-resolution versions of the variables. The new
Dataset is a valid BoutDataset, although containing only the specified variables.
- save(savepath='./boutdata.nc', filetype='NETCDF4', variables=None, save_dtype=None, separate_vars=False, pre_load=False)[source]¶
Save data variables to a netCDF file.
- Parameters
savepath (str, optional) –
filetype (str, optional) –
variables (list of str, optional) – Variables from the dataset to save. Default is to save all of them.
separate_vars (bool, optional) – If this is true then every variable which depends on time (but not solely on time) will be saved into a different output file. The files are labelled by the name of the variable. Variables which don’t meet this criterion will be present in every output file.
pre_load (bool, optional) – When saving separate variables, will load each variable into memory before saving to file, which can be considerably faster.
Examples
If
separate_vars=True
, then multiple files will be created. These can all be opened and merged in one go using a call of the form:ds = xr.open_mfdataset(‘boutdata_*.nc’, combine=’nested’, concat_dim=None)
- to_field_aligned()[source]¶
Create a new Dataset with all 3d variables transformed to field-aligned coordinates, which are shifted with respect to the base coordinates by an angle zShift
- to_restart(variables=None, *, savepath='.', nxpe=None, nype=None, tind=- 1, prefix='BOUT.restart', overwrite=False)[source]¶
Write out a timestep as a set of netCDF BOUT.restart files.
If processor decomposition is not specified then data will be saved using the decomposition it had when loaded.
- Parameters
variables (str or sequence of str, optional) – The evolving variables needed in the restart files. If not given explicitly, all time-evolving variables in the Dataset will be used, which may result in larger restart files than necessary.
savepath (str, default '.') – Directory to save the created restart files under
nxpe (int, optional) – Number of processors in the x-direction. If not given, keep the number used for the original simulation
nype (int, optional) – Number of processors in the y-direction. If not given, keep the number used for the original simulation
tind (int, default -1) – Time-index of the slice to write to the restart files
prefix (str, default "BOUT.restart") – Prefix to use for names of restart files
overwrite (bool, default False) – By default, raises if restart file already exists. Set to True to overwrite existing files
xbout.load module¶
- xbout.load.collect(varname, xind=None, yind=None, zind=None, tind=None, path='.', yguards=False, xguards=True, info=True, prefix='BOUT.dmp')[source]¶
Extract the data pertaining to a specified variable in a BOUT++ data set
- Parameters
varname (str) – Name of the variable
xind (int, slice or list of int, optional) – Range of X, Y, Z or time indices to collect. Either a single index to collect, a list containing [start, end] (inclusive end), or a slice object (usual python indexing). Default is to fetch all indices
yind (int, slice or list of int, optional) – Range of X, Y, Z or time indices to collect. Either a single index to collect, a list containing [start, end] (inclusive end), or a slice object (usual python indexing). Default is to fetch all indices
zind (int, slice or list of int, optional) – Range of X, Y, Z or time indices to collect. Either a single index to collect, a list containing [start, end] (inclusive end), or a slice object (usual python indexing). Default is to fetch all indices
tind (int, slice or list of int, optional) – Range of X, Y, Z or time indices to collect. Either a single index to collect, a list containing [start, end] (inclusive end), or a slice object (usual python indexing). Default is to fetch all indices
path (str, optional) – Path to data files (default: “.”)
prefix (str, optional) – File prefix (default: “BOUT.dmp”)
yguards (bool, optional) – Collect Y boundary guard cells? (default: False)
xguards (bool, optional) – Collect X boundary guard cells? (default: True) (Set to True to be consistent with the definition of nx)
info (bool, optional) – Print information about collect? (default: True)
Notes
- strictThis option found in boutdata.collect() is not present in this function
it is assumed that the varname given is correct, if variable does not exist the function will fail
- tind_autoThis option is not required when using _auto_open_mfboutdataset as an
automatic failure if datasets are different lengths is included
- Returns
ds
- Return type
numpy.ndarray
- xbout.load.open_boutdataset(datapath='./BOUT.dmp.*.nc', inputfilepath=None, geometry=None, gridfilepath=None, chunks=None, keep_xboundaries=True, keep_yboundaries=False, run_name=None, info=True, **kwargs)[source]¶
Load a dataset from a set of BOUT output files, including the input options file. Can also load from a grid file.
Note that when reloading a Dataset that was saved by xBOUT, the state of the saved Dataset is restored, and the values of
keep_xboundaries
,keep_yboundaries
, andrun_name
are ignored.geometry
is treated specially, and can be passed when reloading a Dataset (along withgridfilepath
if needed).Variable conflicts: sometimes, for example when loading data from multiple restarts, some variables may have conflicts (e.g. a source term was changed between some of the restarts, but the source term is saved as time-independent, without a t-dimension). In this case one workaround is to pass a list of variable names to the keyword argument
drop_vars
to ignore the variables with conflicts, e.g. if"S1"
and"S2"
have conflicts` ds = open_boutdataset("data*/boutdata.nc", drop_vars=["S1", "S2"]) `
will open a Dataset which is missing"S1"
and"S2"
. [drop_vars
is an argument ofxarray.open_dataset()
that is passed down throughkwargs
.]- Parameters
datapath (str or (list or tuple of xr.Dataset), optional) –
Path to the data to open. Can point to either a set of one or more dump files, or a single grid file.
To specify multiple dump files you must enter the path to them as a single glob, e.g. ‘./BOUT.dmp.*.nc’, or for multiple consecutive runs in different directories (in order) then ‘./run*/BOUT.dmp.*.nc’.
If a list or tuple of xr.Dataset is passed, they will be combined with xr.combine_nested() instead of loading data from disk (intended for unit testing).
chunks (dict, optional) –
inputfilepath (str, optional) –
geometry (str, optional) –
The geometry type of the grid data. This will specify what type of coordinates to add to the dataset, e.g. ‘toroidal’ or ‘cylindrical’.
If not specified then will attempt to read it from the file attrs. If still not found then a warning will be thrown, which can be suppressed by passing `info`=False.
To define a new type of geometry you need to use the
register_geometry
decorator. You are encouraged to do this for your own BOUT++ physics module, to apply relevant normalisations.gridfilepath (str, optional) – The path to a grid file, containing any variables needed to apply the geometry specified by the ‘geometry’ option, which are not contained in the dump files.
keep_xboundaries (bool, optional) – If true, keep x-direction boundary cells (the cells past the physical edges of the grid, where boundary conditions are set); increases the size of the x dimension in the returned data-set. If false, trim these cells.
keep_yboundaries (bool, optional) – If true, keep y-direction boundary cells (the cells past the physical edges of the grid, where boundary conditions are set); increases the size of the y dimension in the returned data-set. If false, trim these cells.
run_name (str, optional) – Name to give to the whole dataset, e.g. ‘JET_ELM_high_resolution’. Useful if you are going to open multiple simulations and compare the results.
info (bool or "terse", optional) –
kwargs (optional) – Keyword arguments are passed down to
xarray.open_mfdataset
, which in turn passes extra kwargs down toxarray.open_dataset
.
- Returns
ds
- Return type
xarray.Dataset
xbout.plotting.animate module¶
- xbout.plotting.animate.animate_line(data, animate_over=None, animate=True, axis_coords=None, vmin=None, vmax=None, fps=10, save_as=None, sep_pos=None, ax=None, aspect=None, controls='both', **kwargs)[source]¶
Plots a line plot which is animated with time.
Currently only supports 1D+1 data, which it plots with animatplot’s Line animation.
- Parameters
data (xarray.DataArray) –
animate_over (str, optional) – Dimension over which to animate, defaults to the time dimension
animate (bool, optional) – If set to false, do not create the animation, just return the block
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’.
vmin (float, optional) – Minimum value to use for colorbar. Default is to use minimum value of data across whole timeseries.
vmax (float, optional) – Maximum value to use for colorbar. Default is to use maximum value of data across whole timeseries.
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 set_aspect(), defaults to “auto”
controls (string or None, default "both") – By default, add both the timeline and play/pause toggle to the animation. If “timeline” is passed add only the timeline, if “toggle” is passed add only the play/pause toggle. If None or an empty string is passed, add neither.
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
- xbout.plotting.animate.animate_pcolormesh(data, animate_over=None, x=None, y=None, animate=True, axis_coords=None, vmin=None, vmax=None, vsymmetric=False, logscale=False, fps=10, save_as=None, ax=None, cax=None, aspect=None, extend=None, controls='both', **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 animatplotlib’s wrapping of matplotlib’s pcolormesh.
- Parameters
data (xarray.DataArray) –
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
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’.
vmin (float, optional) – Minimum value to use for colorbar. Default is to use minimum value of data across whole timeseries.
vmax (float, optional) – Maximum value to use for colorbar. Default is to use maximum value of data across whole timeseries.
vsymmetric (bool, optional) – If set to true, make the color-scale symmetric
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.
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 (Axes, optional) – A matplotlib axes instance to plot to. If None, create a new figure and axes, and plot to that
cax (Axes, optional) – Matplotlib axes instance where the colorbar will be plotted. If None, the default position created by matplotlab.figure.Figure.colorbar() will be used.
aspect (str or None, optional) – Argument to set_aspect(), defaults to “auto”
extend (str or None, optional) – Passed to fig.colorbar()
controls (string or None, default "both") – By default, add both the timeline and play/pause toggle to the animation. If “timeline” is passed add only the timeline, if “toggle” is passed add only the play/pause toggle. If None or an empty string is passed, add neither.
kwargs (dict, optional) – Additional keyword arguments are passed on to the animation function animatplot.blocks.Pcolormesh
- Returns
If animate==True, returns an animatplot.Animation object, otherwise returns an animatplot.blocks.Pcolormesh instance.
- Return type
animation or block
- xbout.plotting.animate.animate_poloidal(da, *, ax=None, cax=None, animate_over=None, separatrix=True, targets=True, add_limiter_hatching=True, cmap=None, axis_coords=None, vmin=None, vmax=None, logscale=False, animate=True, save_as=None, fps=10, controls='both', aspect=None, extend=None, **kwargs)[source]¶
Make a 2D plot in R-Z coordinates using animatplotlib’s Pcolormesh, taking into account branch cuts (X-points).
- Parameters
da (xarray.DataArray) – A 2D (x,y) DataArray of data to plot
ax (Axes, optional) – A matplotlib axes instance to plot to. If None, create a new figure and axes, and plot to that
cax (Axes, optional) – Matplotlib axes instance where the colorbar will be plotted. If None, the default position created by matplotlab.figure.Figure.colorbar() will be used.
animate_over (str, optional) – Dimension over which to animate, defaults to the time dimension
separatrix (bool, optional) – Add dashed lines showing separatrices
targets (bool, optional) – Draw solid lines at the target surfaces
add_limiter_hatching (bool, optional) – Draw hatched areas at the targets
cmap (matplotlib.colors.Colormap instance, optional) – Colors to use for the plot
axis_coords (None, str, dict) –
Coordinates to use for axis labelling. Only affects time coordinate. - 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’.
vmin (float, optional) – Minimum value for the color scale
vmax (float, optional) – Maximum value for the color scale
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.
animate (bool, optional) – If set to false, do not create the animation, just return the blocks
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’
fps (float, optional) – Frame rate for the animation
controls (string or None, default "both") – By default, add both the timeline and play/pause toggle to the animation. If “timeline” is passed add only the timeline, if “toggle” is passed add only the play/pause toggle. If None or an empty string is passed, add neither.
aspect (str or None, optional) – Argument to set_aspect(), defaults to “equal”
extend (str or None, optional) – Passed to fig.colorbar()
**kwargs (optional) – Additional arguments are passed on to the animation method 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
xbout.plotting.utils module¶
- xbout.plotting.utils.plot_separatrix(da, sep_pos, ax, radial_coord='x')[source]¶
Plots the separatrix as a black dotted line.
Should plot in the correct place regardless of the choice of coordinates for the plot axes, and the type of plot. sep_x needs to be supplied as the integer index of the grid point location of the separatrix.