Utility functions#

Module util provides a set of useful helpers which are currently not attributable to the other modules

from_to

Return a list of timesteps from <tstart> to <tend> of length <tdelta>

filter_window_polar

Apply a filter of an approximated square window of half size fsize on a given polar image img.

filter_window_cartesian

Apply a filter of square window size fsize on a given cartesian image img.

find_bbox_indices

Find min/max-indices for NxMx2 array coords using bbox-values.

get_raster_origin

Return raster origin

calculate_polynomial

Calculate Polynomial

derivate

Calculates derivative of data using window of length winlen.

despeckle

Remove floating pixels in between NaNs in a multidimensional array.

import_optional

Allowing for lazy loading of optional wradlib modules or dependencies.

vertical_interpolate_volume

Vertically interpolate volume data

cross_section_ppi

Cut a cross-section from PPI volume scans

UtilMethods

wradlib xarray SubAccessor methods for Util.

wradlib.util.from_to(tstart, tend, tdelta)[source]#

Return a list of timesteps from <tstart> to <tend> of length <tdelta>

Parameters
  • tstart (str or datetime.datetime) – datetime isostring (%Y%m%d %H:%M:%S), e.g. 2000-01-01 15:34:12 or datetime object

  • tend (str or datetime.datetime) – datetime isostring (%Y%m%d %H:%M:%S), e.g. 2000-01-01 15:34:12 or datetime object

  • tdelta (int) – representing time interval in SECONDS

Returns

output (list) – list of datetime.datetime objects

wradlib.util.filter_window_polar(img, wsize, fun, rscale, *, random=False)[source]#

Apply a filter of an approximated square window of half size fsize on a given polar image img.

Parameters
  • img (numpy.ndarray) – 2d array of values to which the filter is to be applied

  • wsize (float) – Half size of the window centred on the pixel [m]

  • fun (str) – name of the 1d filter from scipy.ndimage

  • rscale (float) – range [m] scale of the polar grid

  • random (bool) – True to use random azimuthal size to avoid long-term biases.

Returns

output (numpy.ndarray) – Array with the same shape as img, containing the filter’s results.

wradlib.util.filter_window_cartesian(img, wsize, fun, scale, **kwargs)[source]#

Apply a filter of square window size fsize on a given cartesian image img.

Parameters
  • img (numpy.ndarray) – 2d array of values to which the filter is to be applied

  • wsize (float) – Half size of the window centred on the pixel [m]

  • fun (str) – name of the 2d filter from scipy.ndimage

  • scale (tuple) – tuple of 2 floats x and y scale of the cartesian grid [m]

Returns

output (numpy.ndarray) – Array with the same shape as img, containing the filter’s results.

wradlib.util.find_bbox_indices(coords, bbox)[source]#

Find min/max-indices for NxMx2 array coords using bbox-values.

The bounding box is defined by two points (llx,lly and urx,ury) It finds the first indices before llx,lly and the first indices after urx,ury. If no index is found 0 and N/M is returned.

Parameters
  • coords (numpy.ndarray) – 3-dimensional array (ny, nx, lon/lat) of floats

  • bbox (numpy.ndarray | list | tuple) – 4-element (llx,lly,urx,ury)

Returns

bbind (tuple) – 4-element tuple of int (llx,lly,urx,ury)

wradlib.util.get_raster_origin(coords)[source]#

Return raster origin

Parameters

coords (numpy.ndarray) – 3-dimensional array (rows, cols, 2) of xy-coordinates

Returns

out (str) – ‘lower’ or ‘upper’

wradlib.util.calculate_polynomial(data, w)[source]#

Calculate Polynomial

The function calculate the following polynomial:

\[P = \sum_{n=0}^{N} w(n) \cdot data^{n}\]
Parameters
Returns

poly (numpy.ndarray) – Flat array of processed data.

wradlib.util.derivate(data, *, winlen=7, method='lanczos_conv', skipna=False, **kwargs)[source]#
wradlib.util.derivate(obj: DataArray, **kwargs)

Calculates derivative of data using window of length winlen.

In normal operation the method (‘lanczos_conv’) uses convolution to estimate the derivative using Low-noise Lanczos differentiators. The equivalent method (‘lanczos_dot’) uses dot-vector sum product.

For further reading please see Differentiation by integration using orthogonal polynomials, a survey and Low-noise Lanczos differentiators.

The results are very similar to the moving window linear regression methods (cov, matrix_inv and lstsq), which are slower than the former (in order of appearance).

All methods will return NaNs in case at least one value in the moving window is NaN.

If skipna=True the locations of NaN results are treated by using local linear regression by method2 (default to cov_nan) where enough valid neighbouring data is available.

Before applying the actual derivation calculation the data is padded with mode=’reflect’ by default along the derivation dimension. Padding can be parametrized using kwargs.

Parameters
  • data (numpy.ndarray) – multidimensional array, note that the derivation dimension must be the last dimension of the input array.

  • winlen (int) – Width of the derivation window .

  • method (str) – Defaults to ‘lanczos_conv’. Can take one of ‘lanczos_dot’, ‘lstsq’, ‘cov’, ‘cov_nan’, ‘matrix_inv’.

  • skipna (bool) – Defaults to False. If True, treat NaN results by applying method2.

Keyword Arguments
  • method2 (str) – Defaults to ‘_nan’ methods.

  • min_periods (int) – Minimum number of valid values in moving window for linear regression. Defaults to winlen // 2 + 1.

  • pad_mode (str) – Defaults to reflect. See numpy.pad.

  • pad_kwargs (dict) – Keyword arguments for padding, see numpy.pad

Returns

out (numpy.ndarray) – array of derivates with the same shape as data

wradlib.util.despeckle(data, *, n=3, copy=False)[source]#
wradlib.util.despeckle(obj: DataArray, **kwargs)

Remove floating pixels in between NaNs in a multidimensional array.

Warning

This function changes the original input array if argument copy is set to False (default).

Parameters
  • data (numpy.ndarray) – Note that the range dimension must be the last dimension of the input array.

  • n (int) – (must be either 3 or 5, 3 by default), Width of the window in which we check for speckle

  • copy (bool) – If True, the input array will remain unchanged.

wradlib.util.import_optional(module)[source]#

Allowing for lazy loading of optional wradlib modules or dependencies.

This function removes the need to satisfy all dependencies of wradlib before being able to work with it.

Parameters

module (str) – name of the module

Returns

mod (object) – if module is present, returns the module object, on ImportError returns an instance of OptionalModuleStub which will raise an AttributeError as soon as any attribute is accessed.

Examples

Trying to import a module that exists makes the module available as normal. You can even use an alias. You cannot use the ‘*’ notation, or import only select functions, but you can simulate most of the standard import syntax behavior. >>> m = import_optional(‘math’) >>> m.log10(100) 2.0

Trying to import a module that does not exist, does not produce any errors. Only when some function is used, the code triggers an error >>> m = import_optional(‘nonexistentmodule’) # noqa >>> m.log10(100) #doctest: +ELLIPSIS Traceback (most recent call last): … AttributeError: Module ‘nonexistentmodule’ is not installed. <BLANKLINE> You tried to access function/module/attribute ‘log10’ from module ‘nonexistentmodule’. This module is optional right now in wradlib. You need to separately install this dependency. Please refer to https://docs.wradlib.org/en/stable/installation.html#optional-dependencies for further instructions.

wradlib.util.vertical_interpolate_volume(vol, *, elevs=None, method='nearest')[source]#

Vertically interpolate volume data

Parameters
  • vol (wradlib:wradlib.io.xarray.RadarVolume)

  • elevs (iterable, optional) – Elevations to which interpolate the data. Defaults to None, which does no interpolation and returns a stacked array of the data.

  • method (str, optional) – method for interpolation, defaults to “nearest”.

Returns

ds (xarray.Dataset)

wradlib.util.cross_section_ppi(obj, azimuth, **kwargs)[source]#

Cut a cross-section from PPI volume scans

New in version 1.18.

This function extracts cross-sections from a PPI volume scan along one or more azimuth angles, or along a line connecting two given points. Similar to PyArt’s cross_section_ppi function.

Parameters
  • obj (wradlib:wradlib.io.xarray.RadarVolume - Radar volume containing PPI sweeps) – from which azimuthal cross-sections will be extracted.

  • azimuth (int, float, slice, tuple or list) – Value of azimuth to extract the cross-section. It can be multiple values in the form of a slice, or a tuple or list of values. Alternatively, it can be given a tuple or list containing coordinates of two arbitrary points in the x,y space of the georeferenced object: [ (x1, y1), (x2,y2) ]. In case two points are given, a cross-section along the line connecting the points will be generated by selecting the nearest-neighbor values of data. No interpolation of data is performed. If more than two points are given, only the first two are used. The resulting dataset has dimensions xyi (which is just an index along the line connecting the points) and elevation, and coordinates xy (distance along the line from p1) and z. The xy and z coordinates should be used for plotting.

Keyword Arguments
  • method ({None, "nearest", "pad", "ffill", "backfill", "bfill"}, optional) – Method for inexact matches from xarray:xarray.Dataset.sel. Defaults to None (only exact matches).

  • tolerance (float, optional) – Maximum distance between original and new labels for inexact matches from xarray:xarray.Dataset.sel.

  • bw (float, optional) – Beam width in degrees (defaults to None). Option meant for plotting beams with their true beamwidth instead of filling the empty space by stretching the beams (because of how matplotlib pcolormesh works). Defaults to None, which returns a Dataset of cross-sections in the specified azimuth(s). If set to a certain beamwidth, it will return the same Dataset with additional “fake” beams (extra elevations) so that when plotting with matplotlib pcolormesh the beamwidths are correctly represented according to their width.

  • crs (osgeo.osr.SpatialReference, cartopy.crs.CRS, optional) – Projection to use with wradlib.georef.xarray.georeference_dataset. If GDAL OSR SRS, output is in this projection, defaults to AEQD.

  • npl (int, optional) – Number of points to make up the line between p1 and p2, in case the user gives two arbitrary points instead of an azimuth value. npl should be high enough to accomodate more points along the line that points of data available (i.e., higher that the resolution of the data). The default value 1000 should be enough for most cases, but in case the result looks low resolution try increasing npl.

Returns

obj (xarray.Dataset or xarray.DataArray) – Dataset of cross-section(s) in the specified azimuth(s) or along the line connecting the given points.

class wradlib.util.UtilMethods(obj)[source]#

Bases: XarrayMethods

wradlib xarray SubAccessor methods for Util.

despeckle(**kwargs)[source]#

Remove floating pixels in between NaNs in a multidimensional array.

Parameters

obj (xarray.DataArray) – input array

Keyword Arguments

n (int) – (must be either 3 or 5, 3 by default), Width of the window in which we check for speckle

Returns

out (xarray.DataArray) – output array

derivate(**kwargs)[source]#

Calculates derivative of data using window of length winlen.

In normal operation the method (‘lanczos_conv’) uses convolution to estimate the derivative using Low-noise Lanczos differentiators. The equivalent method (‘lanczos_dot’) uses dot-vector sum product.

For further reading please see Differentiation by integration using orthogonal polynomials, a survey and Low-noise Lanczos differentiators.

The results are very similar to the moving window linear regression methods (cov, matrix_inv and lstsq), which are slower than the former (in order of appearance).

All methods will return NaNs in case at least one value in the moving window is NaN.

If skipna=True the locations of NaN results are treated by using local linear regression by method2 (default to cov_nan) where enough valid neighbouring data is available.

Before applying the actual derivation calculation the data is padded with mode=’reflect’ by default along the derivation dimension. Padding can be parametrized using kwargs.

Parameters

obj (xarray.DataArray) – input array

Keyword Arguments
  • winlen (int) – Width of the derivation window .

  • method (str) – Defaults to ‘lanczos_conv’. Can take one of ‘lanczos_dot’, ‘lstsq’, ‘cov’, ‘cov_nan’, ‘matrix_inv’.

  • skipna (bool) – Defaults to False. If True, treat NaN results by applying method2.

  • method2 (str) – Defaults to ‘_nan’ methods.

  • min_periods (int) – Minimum number of valid values in moving window for linear regression. Defaults to winlen // 2 + 1.

  • pad_mode (str) – Defaults to reflect. See numpy.pad.

  • pad_kwargs (dict) – Keyword arguments for padding, see numpy.pad

Returns

out (xarray.DataArray) – array of derivates

dim0()[source]#

Return major dimension (azimuth/elevation) of xarray object.