xarray accessors

NDAccessor

This accessor provides direct access to much of the functionality of the whole nd package from xarray objects.

class nd._xarray.NDAccessor(xarray_obj)[source]

Bases: object

apply(fn, signature=None, njobs=1)[source]

Apply a function to a Dataset that operates on a defined subset of dimensions.

Parameters
  • fn (function) – The function to apply to the Dataset.

  • signature (str, optional) – The signature of the function in dimension names, e.g. ‘(time,var)->(time)’. If ‘var’ is included, the Dataset variables will be converted into a new dimension and the result will be a DataArray.

  • njobs (int, optional) – The number of jobs to run in parallel.

Returns

The output dataset with changed dimensions according to the function signature.

Return type

xr.Dataset

as_complex(inplace=False)[source]

Reassemble complex valued data.

NOTE: Changes the dataset (view) in place!

Parameters

inplace (bool, optional) – Whether to modify the dataset inplace (default: False).

Returns

If inplace, returns None. Otherwise, returns a dataset where the real and imaginary parts have been combined into the respective complex variables.

Return type

xarray.Dataset or None

as_real(inplace=False)[source]

Disassemble complex valued data into real and imag parts.

Parameters

inplace (bool, optional) – Whether to modify the dataset inplace (default: False).

Returns

If inplace, returns None. Otherwise, returns a dataset where all complex variables have been split into their real and imaginary parts.

Return type

xarray.Dataset or None

change_omnibus(ml=None, n=1, alpha=0.01, *args, **kwargs)[source]

Wrapper for nd.change.OmnibusTest.

OmnibusTest

This class implements the change detection algorithm by Conradsen et al. (2015).

Parameters
  • ml (int, optional) – Multilooking window size. By default, no multilooking is performed and the dataset is assumed to already be multilooked.

  • n (int, optional) – The number of looks in ds. If ml is specified this parameter is ignored (default: 1).

  • alpha (float (0. ... 1.), optional) – The significance level (default: 0.01).

  • kwargs (dict, optional) – Extra keyword arguments to be applied to ChangeDetection.__init__.

plot_map(buffer=None, background='_default', imscale=6, gridlines=True, coastlines=True, scalebar=True, gridlines_kwargs={})[source]

Show the boundary of the dataset on a visually appealing map.

Parameters
  • buffer (float, optional) – Margin around the bounds polygon to plot, relative to the polygon dimension. By default, add around 20% on each side.

  • background (cartopy.io.img_tiles image tiles, optional) – The basemap to plot in the background (default: Stamen terrain). If None, do not plot a background map.

  • imscale (int, optional) – The zoom level of the background image (default: 6).

  • gridlines (bool, optional) – Whether to plot gridlines (default: True).

  • coastlines (bool, optional) – Whether to plot coastlines (default: True).

  • scalebar (bool, optional) – Whether to add a scale bar (default: True).

  • gridlines_kwargs (dict, optional) – Additional keyword arguments for gridlines_with_labels().

Returns

The corresponding GeoAxes object.

Return type

cartopy.mpl.geoaxes.GeoAxes

reproject(target=None, src_crs=None, dst_crs=None, crs=None, extent=None, res=None, width=None, height=None, transform=None, *, njobs=1, **kwargs)[source]

Wrapper for nd.warp.Reprojection.

Reprojection of the dataset to the given coordinate reference system (CRS) and extent.

Parameters
  • target (xarray.Dataset or xarray.DataArray, optional) – A reference to which a dataset will be aligned.

  • src_crs (dict or str, optional) – The coordinate system of the input data (default: infer from data).

  • dst_crs (dict or str, optional) – The output coordinate reference system as dictionary or proj-string

  • crs (dict or str, optional) – Alias for dst_crs for backwards compatiblity.

  • extent (tuple, optional) – The output extent. By default this is inferred from the input data.

  • res (tuple, optional) – The output resolution. By default this is inferred from the input data.

  • width (tuple, optional) – The output width. By default this is inferred from the input data.

  • height (tuple, optional) – The output height. By default this is inferred from the input data.

  • transform (tuple, optional) – The output coordinate transform. By default this is inferred from the input data.

  • njobs (int, optional) – Number of jobs to run in parallel. Setting njobs to -1 uses the number of available cores. Disable parallelism by setting njobs to 1 (default).

  • **kwargs (dict, optional) – Extra keyword arguments for rasterio.warp.reproject.

Returns

The reprojected dataset.

Return type

xarray.Dataset

resample(res=None, width=None, height=None, *, njobs=1, **kwargs)[source]

Wrapper for nd.warp.Resample.

Resample a dataset to the specified resolution or width and height.

Parameters
  • res (float or tuple, optional) – The desired resolution in the dataset coordinates.

  • width (int, optional) – The desired output width. Ignored if the resolution is specified. If only the height is given, the width is calculated automatically.

  • height (int, optional) – The desired output height. Ignored if the resolution is specified. If only the width is given, the height is calculated automatically.

  • njobs (int, optional) – Number of jobs to run in parallel. Setting njobs to -1 uses the number of available cores. Disable parallelism by setting njobs to 1 (default).

  • **kwargs (dict, optional) – Extra keyword arguments for rasterio.warp.reproject.

Returns

The resampled dataset.

Return type

xarray.Dataset or xarray.DataArray

to_netcdf(path, *args, **kwargs)[source]

Write an xarray Dataset to disk.

In addition to xarray.to_netcdf, this function allows to store complex valued data by converting it to a a pair of reals. This process is reverted when reading the file via from_netcdf.

Parameters
  • path (str) – The path of the target NetCDF file.

  • *args (list) – Extra positional arguments for xr.Dataset.to_netcdf.

  • **kwargs (dict) – Extra keyword arguments for xr.Dataset.to_netcdf.

to_rgb(output=None, vmin=None, vmax=None, pmin=2, pmax=98, categorical=False, mask=None, shape=None, cmap=None, rgb=None)[source]

Turn some data into a numpy array representing an RGB image.

Parameters
  • output (str) – file path

  • vmin (float or list of float) – minimum value, or list of values per channel (default: None).

  • vmax (float or list of float) – maximum value, or list of values per channel (default: None).

  • pmin (float) – lowest percentile to plot (default: 2). Ignored if vmin is passed.

  • pmax (float) – highest percentile to plot (default: 98). Ignored if vmax is passed.

  • categorical (bool, optional) – Whether the data is categorical. If True, return a randomly colorized image according to the data value (default: False).

  • mask (np.ndarray, optional) – If specified, parts of the image outside of the mask will be black.

  • shape (tuple, optional) – The output height and width (either or both may be None)

  • cmap (opencv colormap, optional) – The colormap used to colorize grayscale data

  • rgb (callable) – Ignored if ds is a DataArray. A function returning an RGB tuple from the dataset, e.g., lambda d: [d.B4, d.B3, d.B2]

Returns

Returns the generate RGB image if output is None, else returns None.

Return type

np.ndarray or None

to_video(path, timestamp='upper left', fontcolor=(0, 0, 0), width=None, height=None, fps=1, codec=None, rgb=<function <lambda>>, cmap=None, mask=None, **kwargs)[source]

Create a video from an xarray.Dataset.

Parameters
  • path (str) – The output file path of the video.

  • timestamp (str, optional) – Location to print the timestamp: [‘upper left’, ‘lower left’, ‘upper right’, ‘lower right’, ‘ul’, ‘ll’, ‘ur’, ‘lr’] Set to None to disable (default: ‘upper left’).

  • fontcolor (tuple, optional) – RGB tuple for timestamp font color (default: (0, 0, 0), i.e., black).

  • width (int, optional) – The width of the video (default: ds.dim[‘x’])

  • height (int, optional) – The height of the video (default: ds.dim[‘y’])

  • fps (int, optional) – Frames per second (default: 1).

  • codec (str, optional) – fourcc codec (see http://www.fourcc.org/codecs.php)

  • rgb (callable, optional) – A callable that takes a Dataset as input and returns a list of R, G, B channels. By default will compute the C11, C22, C11/C22 representation. For a DataArray, use cmap.

  • cmap (str, optional) – For DataArrays only. Colormap used to colorize univariate data.

  • mask (np.ndarray, optional) – If specified, parts of the image outside of the mask will be black.

FilterAccessor

This separate accessor provides direct access to the filters implemented in nd.filters.

class nd._xarray.FilterAccessor(xarray_obj)[source]

Bases: object

boxcar(inplace=False, dims='y', 'x', w=3, *, njobs=1, **kwargs)[source]

Wrapper for nd.filters.BoxcarFilter.

A boxcar filter.

Parameters
  • inplace (bool, optional) – If True, overwrite the input data inplace (default: False).

  • dims (tuple of str, optional) – The dimensions along which to apply the filter (default: (‘y’, ‘x’)).

  • w (int) – The width of the boxcar window. Should be an odd integer in order to ensure symmetry.

  • njobs (int, optional) – Number of jobs to run in parallel. Setting njobs to -1 uses the number of available cores. Disable parallelism by setting njobs to 1 (default).

  • kwargs (dict, optional) – Extra keyword arguments passed on to scipy.ndimage.filters.convolve.

Returns

The filtered dataset

Return type

xarray.Dataset

convolve(inplace=False, dims='y', 'x', kernel=None, *, njobs=1, **kwargs)[source]

Wrapper for nd.filters.ConvolutionFilter.

Kernel-convolution of an xarray.Dataset.

Parameters
  • inplace (bool, optional) – If True, overwrite the input data inplace (default: False).

  • dims (tuple, optional) – The dataset dimensions corresponding to the kernel axes (default: (‘y’, ‘x’)). The length of the tuple must match the number of dimensions of the kernel.

  • kernel (ndarray) – The convolution kernel.

  • njobs (int, optional) – Number of jobs to run in parallel. Setting njobs to -1 uses the number of available cores. Disable parallelism by setting njobs to 1 (default).

  • kwargs (dict, optional) – Extra keyword arguments passed on to scipy.ndimage.filters.convolve.

Returns

The filtered dataset

Return type

xarray.Dataset

gaussian(inplace=False, dims='y', 'x', sigma=1, *, njobs=1, **kwargs)[source]

Wrapper for nd.filters.GaussianFilter.

A Gaussian filter.

Parameters
  • inplace (bool, optional) – If True, overwrite the input data inplace (default: False).

  • dims (tuple of str, optional) – The dimensions along which to apply the Gaussian filtering (default: (‘y’, ‘x’)).

  • sigma (float or sequence of float) – The standard deviation for the Gaussian kernel. If sequence, this is set individually for each dimension.

  • njobs (int, optional) – Number of jobs to run in parallel. Setting njobs to -1 uses the number of available cores. Disable parallelism by setting njobs to 1 (default).

  • kwargs (dict, optional) – Extra keyword arguments passed on to scipy.ndimage.filters.gaussian_filter.

Returns

The filtered dataset

Return type

xarray.Dataset

nlmeans(inplace=False, dims='y', 'x', r=1, sigma=1, h=1, f=1, n_eff=- 1, *, njobs=1)[source]

Wrapper for nd.filters.NLMeansFilter.

Non-Local Means (Buades2011).

Buades, A., Coll, B., & Morel, J.-M. (2011). Non-Local Means Denoising. Image Processing On Line, 1, 208–212. https://doi.org/10.5201/ipol.2011.bcm_nlm

Parameters
  • inplace (bool, optional) – If True, overwrite the input data inplace (default: False).

  • dims (tuple of str) – The dataset dimensions along which to filter.

  • r ({int, sequence}) – The radius

  • sigma (float) – The standard deviation of the noise present in the data.

  • h (float) –

  • f (int) –

  • n_eff (float, optional) – The desired effective sample size. If given, must be greater than 1 and should be no larger than about half the pixels in the window. -1 means no fixed effective sample size (default: -1).

  • njobs (int, optional) – Number of jobs to run in parallel. Setting njobs to -1 uses the number of available cores. Disable parallelism by setting njobs to 1 (default).

Returns

The filtered dataset

Return type

xarray.Dataset