# Georeferencing#

 GeorefMethods wradlib xarray SubAccessor methods for Georef.

## Miscellaneous#

 bin_altitude Calculates the height of a radar bin taking the refractivity of the atmosphere into account. bin_distance Calculates great circle distance from radar site to radar bin over spherical earth, taking the refractivity of the atmosphere into account. site_distance Calculates great circle distance from bin at certain altitude to the radar site over spherical earth, taking the refractivity of the atmosphere into account. GeorefMiscMethods wradlib xarray SubAccessor methods for Georef Misc Methods.
wradlib.georef.misc.bin_altitude(r, theta, sitealt, *, re=6371000, ke=1.3333333333333333)[source]#

Calculates the height of a radar bin taking the refractivity of the atmosphere into account.

Based on the bin altitude is calculated as

$h = \sqrt{r^2 + (k_e r_e)^2 + 2 r k_e r_e \sin\theta} - k_e r_e$
Parameters
Keyword Arguments
• re (float) – earth’s radius [m]

• ke (float) – adjustment factor to account for the refractivity gradient that affects radar beam propagation. In principle this is wavelength- dependend. The default of 4/3 is a good approximation for most weather radar wavelengths

Returns

altitude (numpy.ndarray) – Array of heights of the radar bins in [m]

wradlib.georef.misc.bin_distance(r, theta, sitealt, *, re=6371000, ke=1.3333333333333333)[source]#

Calculates great circle distance from radar site to radar bin over spherical earth, taking the refractivity of the atmosphere into account.

$s = k_e r_e \arctan\left( \frac{r \cos\theta}{r \cos\theta + k_e r_e + h}\right)$

where $$h$$ would be the radar site altitude amsl.

Parameters
• r (numpy.ndarray) – Array of ranges [m]

• theta (scalar or numpy.ndarray) – Array broadcastable to the shape of r elevation angles in degrees with 0° at horizontal and +90° pointing vertically upwards from the radar

• sitealt (float) – site altitude [m] amsl.

• re (float) – earth’s radius [m]

• ke (float) – adjustment factor to account for the refractivity gradient that affects radar beam propagation. In principle this is wavelength- dependend. The default of 4/3 is a good approximation for most weather radar wavelengths

Returns

distance (numpy.ndarray) – Array of great circle arc distances [m]

wradlib.georef.misc.site_distance(r, theta, binalt, *, re=6371000, ke=1.3333333333333333)[source]#

Calculates great circle distance from bin at certain altitude to the radar site over spherical earth, taking the refractivity of the atmosphere into account.

Based on the site distance may be calculated as

$s = k_e r_e \arcsin\left( \frac{r \cos\theta}{k_e r_e + h_n(r, \theta, r_e, k_e)}\right)$

where $$h_n$$ would be provided by bin_altitude.

Parameters
Keyword Arguments
• re (float) – earth’s radius [m]

• ke (float) – adjustment factor to account for the refractivity gradient that affects radar beam propagation. In principle this is wavelength- dependend. The default of 4/3 is a good approximation for most weather radar wavelengths

Returns

distance (numpy.ndarray) – Array of great circle arc distances [m]

Bases: object

wradlib xarray SubAccessor methods for Georef Misc Methods.

bin_altitude(**kwargs)[source]#

Calculates the height of a radar bin taking the refractivity of the atmosphere into account.

Based on the bin altitude is calculated as

$h = \sqrt{r^2 + (k_e r_e)^2 + 2 r k_e r_e \sin\theta} - k_e r_e$
Parameters

obj (xarray.DataArray | xarray.Dataset) – DataArray

Returns

z (xarray.DataArray) – DataArray

bin_distance(**kwargs)[source]#

Calculates great circle distance from radar site to radar bin over spherical earth, taking the refractivity of the atmosphere into account.

$s = k_e r_e \arctan\left( \frac{r \cos\theta}{r \cos\theta + k_e r_e + h}\right)$

where $$h$$ would be the radar site altitude amsl.

Parameters

obj (xarray.DataArray | xarray.Dataset) – DataArray or Dataset

Returns

bin_distance (xarray.DataArray) – DataArray

site_distance(**kwargs)[source]#

Calculates great circle distance from bin at certain altitude to the radar site over spherical earth, taking the refractivity of the atmosphere into account.

Based on the site distance may be calculated as

$s = k_e r_e \arcsin\left( \frac{r \cos\theta}{k_e r_e + h_n(r, \theta, r_e, k_e)}\right)$

where $$h_n$$ would be provided by bin_altitude.

Parameters

obj (xarray.DataArray | xarray.Dataset) – DataArray or Dataset

Returns

z (xarray.DataArray) – DataArray

## Polar Grid Functions#

 georeference Georeference Dataset/DataArray. spherical_to_xyz Transforms spherical coordinates (r, phi, theta) to cartesian coordinates (x, y, z) centered at site (aeqd). spherical_to_proj Transforms spherical coordinates (r, phi, theta) to projected coordinates centered at site in given projection. spherical_to_polyvert Generate 3-D polygon vertices directly from spherical coordinates (r, phi, theta). spherical_to_centroids Generate 3-D centroids of the radar bins from the sperical coordinates (r, phi, theta). centroid_to_polyvert Calculates the 2-D Polygon vertices necessary to form a rectangular polygon around the centroid's coordinates. sweep_centroids Construct sweep centroids native coordinates. maximum_intensity_projection Computes the maximum intensity projection along an arbitrary cut through the ppi from polar data. GeorefPolarMethods wradlib xarray SubAccessor methods for Georef Polar Methods.

Georeference Dataset/DataArray.

New in version 1.5.

This function adds georeference data to xarray Dataset/DataArray obj.

Parameters
Keyword Arguments
Returns
wradlib.georef.polar.spherical_to_xyz(r, phi, theta, site, *, re=None, ke=1.3333333333333333, squeeze=False, strict_dims=False)[source]#

Transforms spherical coordinates (r, phi, theta) to cartesian coordinates (x, y, z) centered at site (aeqd).

It takes the shortening of the great circle distance with increasing elevation angle as well as the resulting increase in height into account.

Parameters
Keyword Arguments
• re (float) – earth’s radius [m], defaults to None (calculating from given latitude)

• ke (float) – adjustment factor to account for the refractivity gradient that affects radar beam propagation. In principle this is wavelength- dependend. The default of 4/3 is a good approximation for most weather radar wavelengths.

• squeeze (bool) – If True, returns squeezed array. Defaults to False.

• strict_dims (bool) – If True, generates output of (theta, phi, r, 3) in any case. If False, dimensions with same length are “merged”.

Returns

wradlib.georef.polar.spherical_to_proj(r, phi, theta, site, *, crs=None, re=None, ke=1.3333333333333333)[source]#

Transforms spherical coordinates (r, phi, theta) to projected coordinates centered at site in given projection.

It takes the shortening of the great circle distance with increasing elevation angle as well as the resulting increase in height into account.

Parameters
Keyword Arguments
• crs (osgeo.osr.SpatialReference) – Destination Spatial Reference System (Projection). Defaults to wgs84 (epsg 4326).

• re (float) – earth’s radius [m]

• ke (float) – adjustment factor to account for the refractivity gradient that affects radar beam propagation. In principle this is wavelength- dependend. The default of 4/3 is a good approximation for most weather radar wavelengths.

Returns

coords (numpy.ndarray) – Array of shape (…, 3). Contains projected map coordinates.

Examples

A few standard directions (North, South, North, East, South, West) with different distances (amounting to roughly 1°) from a site located at 48°N 9°E

>>> r  = np.array([0.,   0., 111., 111., 111., 111.,])*1000
>>> az = np.array([0., 180.,   0.,  90., 180., 270.,])
>>> th = np.array([0.,   0.,   0.,   0.,   0.,  0.5,])
>>> csite = (9.0, 48.0, 0)
>>> coords = spherical_to_proj(r, az, th, csite)
>>> for coord in coords:
...     print( '{0:7.4f}, {1:7.4f}, {2:7.4f}'.format(*coord))
...
9.0000, 48.0000,  0.0000
9.0000, 48.0000,  0.0000
9.0000, 48.9981, 725.7160
10.4872, 47.9904, 725.7160
9.0000, 47.0017, 725.7160
7.5131, 47.9904, 1694.2234


Here, the coordinates of the east and west directions won’t come to lie on the latitude of the site because the beam doesn’t travel along the latitude circle but along a great circle.

wradlib.georef.polar.spherical_to_polyvert(r, phi, theta, site, *, crs=None)[source]#

Generate 3-D polygon vertices directly from spherical coordinates (r, phi, theta).

This is an alternative to centroid_to_polyvert which does not use centroids, but generates the polygon vertices by simply connecting the corners of the radar bins.

Both azimuth and range arrays are assumed to be equidistant and to contain only unique values. For further information refer to the documentation of spherical_to_xyz.

Parameters
• r (numpy.ndarray) – Array of ranges [m]; r defines the exterior boundaries of the range bins! (not the centroids). Thus, values must be positive!

• phi (numpy.ndarray) – Array of azimuth angles containing values between 0° and 360°. The angles are assumed to describe the pointing direction fo the main beam lobe! The first angle can start at any values, but make sure the array is sorted continuously positively clockwise and the angles are equidistant. An angle if 0 degree is pointing north.

• theta (float) – Elevation angle of scan

• site (sequence) – the lon/lat/alt coordinates of the radar location

• crs (osgeo.osr.SpatialReference) – Destination Projection

Returns

• output (numpy.ndarray) – A 3-d array of polygon vertices with shape(num_vertices, num_vertex_nodes, 2). The last dimension carries the xyz-coordinates either in aeqd or given crs.

• aeqd (gdal:osgeo.aeqosr.SpatialReference) – only returned if crs is None

Examples

>>> import wradlib.georef as georef  # noqa
>>> import numpy as np
>>> from matplotlib import collections
>>> import matplotlib.pyplot as pl
>>> #pl.interactive(True)
>>> # define the polar coordinates and the site coordinates in lat/lon
>>> r = np.array([50., 100., 150., 200.]) * 1000
>>> # _check_polar_coords fails in next line
>>> # az = np.array([0., 45., 90., 135., 180., 225., 270., 315., 360.])
>>> az = np.array([0., 45., 90., 135., 180., 225., 270., 315.])
>>> el = 1.0
>>> site = (9.0, 48.0, 0)
>>> polygons, aeqd = georef.spherical_to_polyvert(r, az, el, site)
>>> # plot the resulting mesh
>>> fig = pl.figure()
>>> #polycoll = mpl.collections.PolyCollection(vertices,closed=True, facecolors=None)  # noqa
>>> polycoll = collections.PolyCollection(polygons[...,:2], closed=True, facecolors='None')  # noqa
>>> pl.autoscale()
>>> pl.show()

wradlib.georef.polar.spherical_to_centroids(r, phi, theta, site, *, crs=None)[source]#

Generate 3-D centroids of the radar bins from the sperical coordinates (r, phi, theta).

Both azimuth and range arrays are assumed to be equidistant and to contain only unique values. The ranges are assumed to define the exterior boundaries of the range bins (thus they must be positive). The angles are assumed to describe the pointing direction fo the main beam lobe.

For further information refer to the documentation of spherical_to_xyz.

Parameters
• r (numpy.ndarray) – Array of ranges [m]; r defines the exterior boundaries of the range bins! (not the centroids). Thus, values must be positive!

• phi (numpy.ndarray) – Array of azimuth angles containing values between 0° and 360°. The angles are assumed to describe the pointing direction fo the main beam lobe! The first angle can start at any values, but make sure the array is sorted continuously positively clockwise and the angles are equidistant. An angle if 0 degree is pointing north.

• theta (float) – Elevation angle of scan

• site (sequence) – the lon/lat/alt coordinates of the radar location

• crs (osgeo.osr.SpatialReference) – Destination Projection

Returns

Note

Azimuth angles of 360 deg are internally converted to 0 deg.

Calculates the 2-D Polygon vertices necessary to form a rectangular polygon around the centroid’s coordinates.

The vertices order will be clockwise, as this is the convention used by ESRI’s shapefile format for a polygon.

Parameters
• centroid (array-like) – List of 2-D coordinates of the center point of the rectangle.

• delta (scalar or numpy.ndarray) – Symmetric distances of the vertices from the centroid in each direction. If delta is scalar, it is assumed to apply to both dimensions.

Returns

vertices (numpy.ndarray) – An array with 5 vertices per centroid.

Note

The function can currently only deal with 2-D data (If you come up with a higher dimensional version of ‘clockwise’ you’re welcome to add it). The data is then assumed to be organized within the centroid array with the last dimension being the 2-D coordinates of each point.

Examples

>>> centroid_to_polyvert([0., 1.], [0.5, 1.5])
array([[-0.5, -0.5],
[-0.5,  2.5],
[ 0.5,  2.5],
[ 0.5, -0.5],
[-0.5, -0.5]])
>>> centroid_to_polyvert(np.arange(4).reshape((2,2)), 0.5)
array([[[-0.5,  0.5],
[-0.5,  1.5],
[ 0.5,  1.5],
[ 0.5,  0.5],
[-0.5,  0.5]],

[[ 1.5,  2.5],
[ 1.5,  3.5],
[ 2.5,  3.5],
[ 2.5,  2.5],
[ 1.5,  2.5]]])


Construct sweep centroids native coordinates.

Parameters
Returns

coordinates (numpy.ndarray) – array of shape (nrays,nbins,3) containing native centroid radar coordinates (slant range, azimuth, elevation)

wradlib.georef.polar.maximum_intensity_projection(data, *, r=None, az=None, angle=None, elev=None, autoext=True)[source]#

Computes the maximum intensity projection along an arbitrary cut through the ppi from polar data.

Parameters

data (numpy.ndarray) – Array containing polar data (azimuth, range)

Keyword Arguments
Returns

Bases: object

wradlib xarray SubAccessor methods for Georef Polar Methods.

georeference(**kwargs)[source]#

Georeference Dataset/DataArray.

New in version 1.5.

This function adds georeference data to xarray Dataset/DataArray obj.

Parameters
Keyword Arguments
Returns
spherical_to_xyz(**kwargs)[source]#

Transforms spherical coordinates (r, phi, theta) to cartesian coordinates (x, y, z) centered at site (aeqd).

It takes the shortening of the great circle distance with increasing elevation angle as well as the resulting increase in height into account.

Parameters
Keyword Arguments
• re (float) – earth’s radius [m], defaults to None (calculating from given latitude)

• ke (float) – adjustment factor to account for the refractivity gradient that affects radar beam propagation. In principle this is wavelength- dependend. The default of 4/3 is a good approximation for most weather radar wavelengths.

Returns

spherical_to_proj(**kwargs)[source]#

Transforms spherical coordinates (r, phi, theta) to projected coordinates centered at site in given projection.

It takes the shortening of the great circle distance with increasing elevation angle as well as the resulting increase in height into account.

Parameters
Keyword Arguments
• crs (osgeo.osr.SpatialReference) – Destination Spatial Reference System (Projection). Defaults to wgs84 (epsg 4326).

• ke (float) – adjustment factor to account for the refractivity gradient that affects radar beam propagation. In principle this is wavelength- dependend. The default of 4/3 is a good approximation for most weather radar wavelengths.

Returns

coords (xarray.DataArray) – Array of shape (…, 3). Contains projected map coordinates.

spherical_to_polyvert(**kwargs)[source]#

Generate 3-D polygon vertices directly from spherical coordinates (r, phi, theta).

This is an alternative to centroid_to_polyvert which does not use centroids, but generates the polygon vertices by simply connecting the corners of the radar bins.

Both azimuth and range arrays are assumed to be equidistant and to contain only unique values. For further information refer to the documentation of spherical_to_xyz.

Currently only works for PPI.

Parameters
Keyword Arguments
• crs (osgeo.osr.SpatialReference) – Destination Spatial Reference System (Projection). Defaults to wgs84 (epsg 4326).

• ke (float) – adjustment factor to account for the refractivity gradient that affects radar beam propagation. In principle this is wavelength- dependend. The default of 4/3 is a good approximation for most weather radar wavelengths.

Returns

spherical_to_centroids(**kwargs)[source]#

Generate 3-D centroids of the radar bins from the sperical coordinates (r, phi, theta).

Both azimuth and range arrays are assumed to be equidistant and to contain only unique values. The ranges are assumed to define the exterior boundaries of the range bins (thus they must be positive). The angles are assumed to describe the pointing direction fo the main beam lobe.

For further information refer to the documentation of spherical_to_xyz.

Parameters
Keyword Arguments
• crs (osgeo.osr.SpatialReference) – Destination Spatial Reference System (Projection). Defaults to wgs84 (epsg 4326).

• ke (float) – adjustment factor to account for the refractivity gradient that affects radar beam propagation. In principle this is wavelength- dependend. The default of 4/3 is a good approximation for most weather radar wavelengths.

• PPI. (Currently only works for) –

Returns

Note

Azimuth angles of 360 deg are internally converted to 0 deg.

## Projection Functions#

 reproject Transform coordinates from a source projection to a target projection. create_osr Conveniently supports the construction of osr spatial reference objects projstr_to_osr Transform a PROJ string to an osr spatial reference object epsg_to_osr Create osr spatial reference object from EPSG number wkt_to_osr Create osr spatial reference object from WKT string get_default_projection Create a default projection object (wgs84) get_earth_radius Get the radius of the Earth (in km) for a given Spheroid model (sr) at a given position. get_radar_projection Get the native radar projection which is an azimuthal equidistant projection centered at the site using WGS84. get_earth_projection Get a default earth projection based on WGS get_extent Get the extent of 2d coordinates GeorefProjectionMethods wradlib xarray SubAccessor methods for Georef Projection Methods.

Transform coordinates from a source projection to a target projection.

Call signatures:

reproject(C, **kwargs)
reproject(X, Y, **kwargs)
reproject(X, Y, Z, **kwargs)


C is the np array of source coordinates. X, Y and Z specify arrays of x, y, and z coordinate values

Parameters
Keyword Arguments
Returns

Examples

Conveniently supports the construction of osr spatial reference objects

Currently, the following projection names (argument projname) are supported:

“aeqd”: Azimuthal Equidistant

needs the following keyword arguments:

• lat_0 (latitude at projection center),

• lon_0 (longitude at projection center),

• x_0 (false Easting, also known as x-offset),

• y_0 (false Northing, also known as y-offset)

Polar stereographic projection used by the German Weather Service (DWD) for all Radar composite products. See the final report on the RADOLAN project for details.

Parameters
Returns

output (osgeo.osr.SpatialReference) – GDAL/OSR object defining projection

Examples

Transform a PROJ string to an osr spatial reference object

Parameters

projstr (str) – PROJ string describing projection

Returns

crs (osgeo.osr.SpatialReference) – GDAL OSR SRS object defining projection

Examples

See PROJ.

Create osr spatial reference object from EPSG number

Parameters

epsg (int) – EPSG-Number defining the coordinate system

Returns

crs (osgeo.osr.SpatialReference) – GDAL/OSR object defining projection

Create osr spatial reference object from WKT string

Parameters

wkt (str) – WTK string defining the coordinate reference system

Returns

crs (osgeo.osr.SpatialReference) – GDAL/OSR object defining projection

Create a default projection object (wgs84)

Get the radius of the Earth (in km) for a given Spheroid model (sr) at a given position.

$R^2 = \frac{a^4 \cos(f)^2 + b^4 \sin(f)^2} {a^2 \cos(f)^2 + b^2 \sin(f)^2}$
Parameters
Returns

radius (float) – earth radius in meter

Get the native radar projection which is an azimuthal equidistant projection centered at the site using WGS84.

Parameters

site (sequence) – the WGS84 lon / lat coordinates of the radar location

Returns

crs (osgeo.osr.SpatialReference) – projection definition

Get a default earth projection based on WGS

Parameters

model (str) – earth model used, defaults to ellipsoid:

• ‘ellipsoid’ - WGS84 with ellipsoid heights -> EPSG 4979

• ‘geoid’ - WGS84 with egm96 geoid heights -> EPSG 4326 + 5773

• ‘sphere’ - GRS 1980 authalic sphere -> EPSG 4047

Returns

crs (osgeo.osr.SpatialReference) – projection definition

Get the extent of 2d coordinates

Parameters

coords (numpy.ndarray) – coordinates array with shape (…,(x,y))

Returns

extent (tuple) – (xmin, xmax, ymin, ymax)

Bases: object

wradlib xarray SubAccessor methods for Georef Projection Methods.

Get the radius of the Earth (in km) for a given Spheroid model (sr) at a given position.

$R^2 = \frac{a^4 \cos(f)^2 + b^4 \sin(f)^2} {a^2 \cos(f)^2 + b^2 \sin(f)^2}$
Parameters
Returns

radius (float) – earth radius in meter

reproject(**kwargs)[source]#

Transform coordinates from current projection to a target projection.

Parameters
Keyword Arguments
Returns

obj (xarray.DataArray | xarray.Dataset) – reprojected Dataset/DataArray

Examples

## Raster Functions#

 read_gdal_values Read values from a gdal object. read_gdal_projection Get a projection (OSR object) from a GDAL dataset. read_gdal_coordinates Get the projected coordinates from a GDAL dataset. extract_raster_dataset Extract data, coordinates and projection information get_raster_extent Get the coordinates of the 4 corners of the raster dataset get_raster_elevation Return surface elevation corresponding to raster dataset reproject_raster_dataset Reproject/Resample given dataset according to keyword arguments merge_raster_datasets Merge rasters. create_raster_dataset Create In-Memory Raster Dataset set_raster_origin Converts Data and Coordinates Origin set_raster_indexing Sets Data and Coordinates Indexing Scheme set_coordinate_indexing Sets Coordinates Indexing Scheme raster_to_polyvert Get raster polygonal vertices from gdal dataset.

Read values from a gdal object.

Parameters
Returns

values (numpy.ndarray) – Array of shape (nrows, ncols) or (nbands, nrows, ncols) containing the data values.

Examples

Get a projection (OSR object) from a GDAL dataset.

Parameters

dataset (osgeo.gdal.Dataset) – raster image with georeferencing

Returns

crs (osgeo.osr.SpatialReference) – dataset projection object

Examples

Get the projected coordinates from a GDAL dataset.

Parameters
Returns

coordinates (numpy.ndarray) – Array of shape (nrows,ncols,2) containing xy coordinates. The array indexing follows image convention with origin at upper left pixel. The shape is (nrows+1,ncols+1,2) if mode == edge.

Examples

Extract data, coordinates and projection information

Parameters
Returns

• values (numpy.ndarray) – Array of shape (nrows, ncols) or (nbands, nrows, ncols) containing the data values.

• coords (numpy.ndarray) – Array of shape (nrows,ncols,2) containing xy coordinates. The array indexing follows image convention with origin at the upper left pixel (northup). The shape is (nrows+1,ncols+1,2) if mode == edge.

• projection (osgeo.osr.SpatialReference) – Spatial reference system of the used coordinates.

Get the coordinates of the 4 corners of the raster dataset

Parameters
Returns

extent (numpy.ndarray) – corner coordinates [ul,ll,lr,ur] or window extent [xmin, xmax, ymin, ymax]

Return surface elevation corresponding to raster dataset

The resampling algorithm is chosen based on scale ratio

Parameters
• dataset (osgeo.gdal.Dataset) – raster image with georeferencing (GeoTransform at least)

• resample (gdal:osgeo.gdalconst.ResampleAlg) – If None the best algorithm is chosen based on scales. GRA_NearestNeighbour = 0, GRA_Bilinear = 1, GRA_Cubic = 2, GRA_CubicSpline = 3, GRA_Lanczos = 4, GRA_Average = 5, GRA_Mode = 6, GRA_Max = 8, GRA_Min = 9, GRA_Med = 10, GRA_Q1 = 11, GRA_Q3 = 12

• kwargs (dict) – keyword arguments passed to wradlib.io.dem.get_srtm

Returns

elevation (numpy.ndarray) – Array of shape (rows, cols, 2) containing elevation

Reproject/Resample given dataset according to keyword arguments

Parameters

src_ds (osgeo.gdal.Dataset) – raster image with georeferencing (GeoTransform at least)

Keyword Arguments
• spacing (float) – float or tuple of two floats pixel spacing of destination dataset, same unit as pixel coordinates

• size (int) – tuple of two ints X/YRasterSize of destination dataset

• resample (gdal:osgeo.gdalconst.ResampleAlg) – defaults to GRA_Bilinear GRA_NearestNeighbour = 0, GRA_Bilinear = 1, GRA_Cubic = 2, GRA_CubicSpline = 3, GRA_Lanczos = 4, GRA_Average = 5, GRA_Mode = 6, GRA_Max = 8, GRA_Min = 9, GRA_Med = 10, GRA_Q1 = 11, GRA_Q3 = 12

• projection_source (osgeo.osr.SpatialReference) – source dataset projection, defaults to None (get projection from src_ds)

• projection_target (osgeo.osr.SpatialReference) – destination dataset projection, defaults to None

• align (bool or tuple) – If False, there is no destination grid aligment. If True, aligns the destination grid to the next integer multiple of destination grid. If tuple (upper-left x,y-coordinate), the destination grid is aligned to this point.

Returns

dst_ds (osgeo.gdal.Dataset) – reprojected/resampled raster dataset

Merge rasters.

Parameters
Returns

dataset (osgeo.gdal.Dataset) – merged raster dataset

Create In-Memory Raster Dataset

Parameters
Returns

dataset (osgeo.gdal.Dataset) – In-Memory raster dataset

Note

The origin of the provided data and coordinates is UPPER LEFT.

Converts Data and Coordinates Origin

Parameters
Returns

Sets Data and Coordinates Indexing Scheme

This converts data and coordinate layout from row-major to column major indexing.

Parameters
Returns

Sets Coordinates Indexing Scheme

This converts coordinate layout from row-major to column major indexing.

Parameters
Returns

coords (numpy.ndarray) – Array of shape (…, N, M, 2) containing xy-coordinates.

Get raster polygonal vertices from gdal dataset.

Parameters

dataset (osgeo.gdal.Dataset) – raster image with georeferencing (GeoTransform at least)

Returns

polyvert (numpy.ndarray) – A N-d array of polygon vertices with shape (…, 5, 2).

## Rectangular Grid Functions#

 get_radolan_coords Calculates x,y coordinates of radolan grid from lon, lat get_radolan_coordinates Calculates x/y coordinates of radolan projection of the German Weather Service get_radolan_grid Calculates x/y coordinates of radolan grid of the German Weather Service xyz_to_spherical grid_to_polyvert Get polygonal vertices from rectangular grid coordinates. GeorefRectMethods wradlib xarray SubAccessor methods for Georef Rect Methods.

Calculates x,y coordinates of radolan grid from lon, lat

Parameters
Keyword Arguments

crs (osgeo.osr.SpatialReference | str) – projection of the DWD grid with spheroid model or string trig to use trigonometric formulas for calculation (only for earth model - sphere). Defaults to None (earth model - sphere).

Calculates x/y coordinates of radolan projection of the German Weather Service

Returns the 1D x,y coordinates of the radolan projection for the given grid layout.

Parameters
Keyword Arguments
• wgs84 (bool) – if True, output coordinates are in wgs84 lonlat format (default: False)

• mode (str) – ‘radolan’ - lower left pixel coordinates ‘center’ - pixel center coordinates ‘edge’ - pixel edge coordinates

• crs (osgeo.osr.SpatialReference | str) – projection of the DWD grid with spheroid model or string trig to use trigonometric formulas for calculation (only for earth model - sphere). Defaults to None (earth model - sphere).

Returns

radolan_ccords (tuple) – tuple x and y 1D coordinate numpy.ndarray shape is (nrows,) and (ncols,) if mode=’radolan’ shape is (nrows,) and (ncols,) if mode=’center’ shape is (nrows+1,) and (ncols+1,) if mode=’edge’

Calculates x/y coordinates of radolan grid of the German Weather Service

Returns the x,y coordinates of the radolan grid positions (lower left corner of every pixel). The radolan grid is a polarstereographic projection, the projection information was taken from RADOLAN-RADVOR-OP Kompositformat_2.2.2

Coordinates for 900km x 900km grid#

Coordinate

lon

lat

x

y

LowerLeft

3.5889E

46.9526N

-523.4622

-4658.645

LowerRight

14.6209E

47.0705N

376.5378

-4658.645

UpperRight

15.7208E

54.7405N

376.5378

-3758.645

UpperLeft

2.0715E

54.5877N

-523.4622

-3758.645

Coordinates for 1100km x 900km grid#

Coordinate

lon

lat

x

y

LowerLeft

4.6759E

46.1929N

-443.4622

-4758.645

LowerRight

15.4801E

46.1827N

456.5378

-4758.645

UpperRight

17.1128E

55.5342N

456.5378

-3658.645

UpperLeft

3.0889E

55.5482N

-443.4622

-3658.645

Coordinates for 1500km x 1400km grid#

Coordinate

lon

lat

x

y

LowerLeft

2.3419E

43.9336N

-673.4622

-5008.645

Parameters
Keyword Arguments
• wgs84 (bool) – if True, output coordinates are in wgs84 lonlat format (default: False)

• mode (str) – ‘radolan’ - lower left pixel coordinates ‘center’ - pixel center coordinates ‘edge’ - pixel edge coordinates

• crs (osgeo.osr.SpatialReference | str) – projection of the DWD grid with spheroid model or string trig to use trigonometric formulas for calculation (only for earth model - sphere). Defaults to None (earth model - sphere).

Returns

radolan_grid (numpy.ndarray) – Array of xy- or lonlat-grid. shape is (nrows, ncols, 2) if mode=’radolan’ shape is (nrows, ncols, 2) if mode=’center’ shape is (nrows+1, ncols+1, 2) if mode=’edge’

Examples

>>> # using osr spatial reference transformation
>>> import wradlib.georef as georef  # noqa
(900, 900, 2), (-523.4622, -4658.6447)

>>> # using pure trigonometric transformations
(900, 900, 2), (-523.4622, -4658.6447)

>>> # using osr spatial reference transformation
(1500, 1400, 2), (-673.4622, -5008.6447)

>>> # using osr spatial reference transformation
(900, 900, 2), (3.5889, 46.9526)

Raises
wradlib.georef.rect.xyz_to_spherical(xyz: ndarray, *, altitude=0, crs=None, ke=1.3333333333333333)

Get polygonal vertices from rectangular grid coordinates.

Parameters

grid (numpy.ndarray) – grid edge coordinates

Keyword Arguments

ravel (bool) – option to flatten the grid

Returns

polyvert (numpy.ndarray) – A 3-d array of polygon vertices with shape (…, 5, 2).

Bases: object

wradlib xarray SubAccessor methods for Georef Rect Methods.

xyz_to_spherical(**kwargs)[source]#

Returns spherical representation (r, theta, phi) of given cartesian coordinates (x, y, z) with respect to the reference altitude (asl) considering earth’s geometry (crs).

Parameters
Keyword Arguments
• crs (osgeo.osr.SpatialReference) – projection of the source coordinates (aeqd) with spheroid model defaults to None.

• ke (float) – Adjustment factor to account for the refractivity gradient that affects radar beam propagation. In principle this is wavelength- dependend. The default of 4/3 is a good approximation for most weather radar wavelengths

Returns

obj (xarray.Dataset) – obj with added spherical coordinates.

## Satellite Functions#

 correct_parallax dist_from_orbit GeorefSatelliteMethods wradlib xarray SubAccessor methods for Georef Satellite Methods.
wradlib.georef.satellite.dist_from_orbit(sr_alt: float, alpha, beta, r_sr_inv, *, re=6371000)

Bases: object

wradlib xarray SubAccessor methods for Georef Satellite Methods.

correct_parallax(drt, **kwargs)[source]#

Adjust the geo-locations of the SR pixels

With SR, we refer to precipitation radars based on space-born platforms such as TRMM or GPM.

The sr_xy coordinates of the SR beam footprints need to be in the azimuthal equidistant projection of the ground radar. This ensures that the ground radar is fixed at xy-coordinate (0, 0), and every SR bin has its relative xy-coordinates with respect to the ground radar site.

Parameters
Returns

obj (xarray.Dataset) – obj with added coordinates in ground radar projection and range

dist_from_orbit(bw_sr, freq, re)[source]#

Returns range distances of SR bins (in meters) as seen from the orbit

With SR, we refer to precipitation radars based on space-born platforms such as TRMM or GPM.

Parameters
Returns

obj (xarray.Dataset) – obj with added PR bin range distances from SR platform in orbit.

## Vector Functions (GDAL)#

 get_vector_coordinates Function iterates over gdal ogr layer features and packs extracted vector coordinate points into nested ndarray get_vector_points Extract coordinate points from given ogr geometry as generator object transform_geometry Perform geotransformation to given destination SpatialReferenceSystem ogr_create_layer Creates OGR.Layer objects in gdal.Dataset object. ogr_copy_layer Copy OGR.Layer object. ogr_copy_layer_by_name Copy OGR.Layer object. ogr_reproject_layer Reproject src_lyr to dst_lyr. ogr_add_feature Creates OGR.Feature objects in OGR.Layer object. ogr_add_geometry Copies single OGR.Geometry object to an OGR.Layer object. numpy_to_ogr Convert a vertex array to gdal/ogr geometry. ogr_to_numpy Backconvert a gdal/ogr geometry to a numpy vertex array. ogr_geocol_to_numpy Backconvert a gdal/ogr geometry Collection to a numpy vertex array. get_centroid Return centroid of a polygon

Function iterates over gdal ogr layer features and packs extracted vector coordinate points into nested ndarray

It transforms coordinates to a given destination osr spatial reference if trg_crs is given and a geotransform is necessary.

Parameters

layer (osgeo.ogr.Layer)

Keyword Arguments
Returns

Extract coordinate points from given ogr geometry as generator object

If geometries are nested, function recurses.

Parameters
Yields

result (numpy.ndarray) – expands to Nx2 dimensional nested point arrays

Perform geotransformation to given destination SpatialReferenceSystem

It transforms coordinates to a given destination osr spatial reference if a geotransform is neccessary.

Parameters
Keyword Arguments

src_crs (osgeo.osr.SpatialReference) – Source Projection

Returns

geom (osgeo.ogr.Geometry) – Transformed Geometry

wradlib.georef.vector.ogr_create_layer(ds, name, *, crs=None, geom_type=None, fields=None)[source]#

Creates OGR.Layer objects in gdal.Dataset object.

Creates one OGR.Layer with given name in given gdal.Dataset object using given OGR.GeometryType and FieldDefinitions

Parameters
Returns

out (osgeo.ogr.Layer) – object

Copy OGR.Layer object.

Copy OGR.Layer object from src_ds gdal.Dataset to dst_ds gdal.Dataset

Parameters

Copy OGR.Layer object.

Copy OGR.Layer object from src_ds gdal.Dataset to dst_ds gdal.Dataset

Parameters

Reproject src_lyr to dst_lyr.

Creates one OGR.Layer with given name in given gdal.Dataset object using given OGR.GeometryType and FieldDefinitions

Parameters
Returns

dst_lyr (osgeo.ogr.Layer) – OGRLayer destination layer

Creates OGR.Feature objects in OGR.Layer object.

OGR.Features are built from numpy src points or polygons.

OGR.Features ‘FID’ and ‘index’ corresponds to source data element

Parameters

Copies single OGR.Geometry object to an OGR.Layer object.

Given OGR.Geometry is copied to new OGR.Feature and written to given OGR.Layer by given index. Attributes are attached.

Parameters

Convert a vertex array to gdal/ogr geometry.

Using JSON as a vehicle to efficiently deal with numpy arrays.

Parameters
Returns

out (osgeo.ogr.Geometry) – object of type geom_name

Backconvert a gdal/ogr geometry to a numpy vertex array.

Using JSON as a vehicle to efficiently deal with numpy arrays.

Parameters

ogrobj (osgeo.ogr.Geometry) – object

Returns

out (numpy.ndarray) – a nested ndarray of vertices of shape (num vertices, 2)

Backconvert a gdal/ogr geometry Collection to a numpy vertex array.

This extracts only Polygon geometries!

Using JSON as a vehicle to efficiently deal with numpy arrays.

Parameters

ogrobj (osgeo.ogr.Geometry) – Collection object

Returns

out (numpy.ndarray) – a nested ndarray of vertices of shape (num vertices, 2)

Return centroid of a polygon

Parameters

polyg (numpy.ndarray) – of shape (num vertices, 2) or ogr.Geometry object

Returns

out (tuple) – x and y coordinate of the centroid

## Xarray Functions#

 as_xarray_dataarray Create Xarray DataArray from NumPy Array create_xarray_dataarray Create Xarray DataArray from Polar Radar Data

Create Xarray DataArray from NumPy Array

New in version 1.3.

Parameters
Returns

dataset (xarray.DataArray) – DataArray

wradlib.georef.xarray.create_xarray_dataarray(data, *, r=None, phi=None, theta=None, site=None, sweep_mode='azimuth_surveillance', rf=1.0, **kwargs)[source]#

Create Xarray DataArray from Polar Radar Data

New in version 1.3.

Parameters
Keyword Arguments
• re (float) – effective earth radius

• ke (float) – adjustment factor to account for the refractivity gradient that affects radar beam propagation. Defaults to 4/3.

• dim0 (str) – Name of the first dimension. Defaults to ‘azimuth’.

• dim1 (str) – Name of the second dimension. Defaults to ‘range’.

Returns

dataset (xarray.DataArray) – DataArray

wradlib xarray SubAccessor methods for Georef.

Bases: object

wradlib xarray SubAccessor methods for Georef Misc Methods.

bin_altitude(**kwargs)[source]#

Calculates the height of a radar bin taking the refractivity of the atmosphere into account.

Based on the bin altitude is calculated as

$h = \sqrt{r^2 + (k_e r_e)^2 + 2 r k_e r_e \sin\theta} - k_e r_e$
Parameters

obj (xarray.DataArray | xarray.Dataset) – DataArray

Returns

z (xarray.DataArray) – DataArray

bin_distance(**kwargs)[source]#

Calculates great circle distance from radar site to radar bin over spherical earth, taking the refractivity of the atmosphere into account.

$s = k_e r_e \arctan\left( \frac{r \cos\theta}{r \cos\theta + k_e r_e + h}\right)$

where $$h$$ would be the radar site altitude amsl.

Parameters

obj (xarray.DataArray | xarray.Dataset) – DataArray or Dataset

Returns

bin_distance (xarray.DataArray) – DataArray

site_distance(**kwargs)[source]#

Calculates great circle distance from bin at certain altitude to the radar site over spherical earth, taking the refractivity of the atmosphere into account.

Based on the site distance may be calculated as

$s = k_e r_e \arcsin\left( \frac{r \cos\theta}{k_e r_e + h_n(r, \theta, r_e, k_e)}\right)$

where $$h_n$$ would be provided by bin_altitude.

Parameters

obj (xarray.DataArray | xarray.Dataset) – DataArray or Dataset

Returns

z (xarray.DataArray) – DataArray

Bases: object

wradlib xarray SubAccessor methods for Georef Polar Methods.

georeference(**kwargs)[source]#

Georeference Dataset/DataArray.

New in version 1.5.

This function adds georeference data to xarray Dataset/DataArray obj.

Parameters
Keyword Arguments
Returns
spherical_to_xyz(**kwargs)[source]#

Transforms spherical coordinates (r, phi, theta) to cartesian coordinates (x, y, z) centered at site (aeqd).

It takes the shortening of the great circle distance with increasing elevation angle as well as the resulting increase in height into account.

Parameters
Keyword Arguments
• re (float) – earth’s radius [m], defaults to None (calculating from given latitude)

• ke (float) – adjustment factor to account for the refractivity gradient that affects radar beam propagation. In principle this is wavelength- dependend. The default of 4/3 is a good approximation for most weather radar wavelengths.

Returns

spherical_to_proj(**kwargs)[source]#

Transforms spherical coordinates (r, phi, theta) to projected coordinates centered at site in given projection.

It takes the shortening of the great circle distance with increasing elevation angle as well as the resulting increase in height into account.

Parameters
Keyword Arguments
• crs (osgeo.osr.SpatialReference) – Destination Spatial Reference System (Projection). Defaults to wgs84 (epsg 4326).

• ke (float) – adjustment factor to account for the refractivity gradient that affects radar beam propagation. In principle this is wavelength- dependend. The default of 4/3 is a good approximation for most weather radar wavelengths.

Returns

coords (xarray.DataArray) – Array of shape (…, 3). Contains projected map coordinates.

spherical_to_polyvert(**kwargs)[source]#

Generate 3-D polygon vertices directly from spherical coordinates (r, phi, theta).

This is an alternative to centroid_to_polyvert which does not use centroids, but generates the polygon vertices by simply connecting the corners of the radar bins.

Both azimuth and range arrays are assumed to be equidistant and to contain only unique values. For further information refer to the documentation of spherical_to_xyz.

Currently only works for PPI.

Parameters
Keyword Arguments
• crs (osgeo.osr.SpatialReference) – Destination Spatial Reference System (Projection). Defaults to wgs84 (epsg 4326).

• ke (float) – adjustment factor to account for the refractivity gradient that affects radar beam propagation. In principle this is wavelength- dependend. The default of 4/3 is a good approximation for most weather radar wavelengths.

Returns

spherical_to_centroids(**kwargs)[source]#

Generate 3-D centroids of the radar bins from the sperical coordinates (r, phi, theta).

Both azimuth and range arrays are assumed to be equidistant and to contain only unique values. The ranges are assumed to define the exterior boundaries of the range bins (thus they must be positive). The angles are assumed to describe the pointing direction fo the main beam lobe.

For further information refer to the documentation of spherical_to_xyz.

Parameters
Keyword Arguments
• crs (osgeo.osr.SpatialReference) – Destination Spatial Reference System (Projection). Defaults to wgs84 (epsg 4326).

• ke (float) – adjustment factor to account for the refractivity gradient that affects radar beam propagation. In principle this is wavelength- dependend. The default of 4/3 is a good approximation for most weather radar wavelengths.

• PPI. (Currently only works for) –

Returns

Note

Azimuth angles of 360 deg are internally converted to 0 deg.

Bases: object

wradlib xarray SubAccessor methods for Georef Projection Methods.

Get the radius of the Earth (in km) for a given Spheroid model (sr) at a given position.

$R^2 = \frac{a^4 \cos(f)^2 + b^4 \sin(f)^2} {a^2 \cos(f)^2 + b^2 \sin(f)^2}$
Parameters
Returns

radius (float) – earth radius in meter

reproject(**kwargs)[source]#

Transform coordinates from current projection to a target projection.

Parameters
Keyword Arguments
Returns

obj (xarray.DataArray | xarray.Dataset) – reprojected Dataset/DataArray

Examples

Bases: object

wradlib xarray SubAccessor methods for Georef Rect Methods.

xyz_to_spherical(**kwargs)[source]#

Returns spherical representation (r, theta, phi) of given cartesian coordinates (x, y, z) with respect to the reference altitude (asl) considering earth’s geometry (crs).

Parameters
Keyword Arguments
• crs (osgeo.osr.SpatialReference) – projection of the source coordinates (aeqd) with spheroid model defaults to None.

• ke (float) – Adjustment factor to account for the refractivity gradient that affects radar beam propagation. In principle this is wavelength- dependend. The default of 4/3 is a good approximation for most weather radar wavelengths

Returns

obj (xarray.Dataset) – obj with added spherical coordinates.

Bases: object

wradlib xarray SubAccessor methods for Georef Satellite Methods.

correct_parallax(drt, **kwargs)[source]#

Adjust the geo-locations of the SR pixels

With SR, we refer to precipitation radars based on space-born platforms such as TRMM or GPM.

The sr_xy coordinates of the SR beam footprints need to be in the azimuthal equidistant projection of the ground radar. This ensures that the ground radar is fixed at xy-coordinate (0, 0), and every SR bin has its relative xy-coordinates with respect to the ground radar site.

Parameters
Returns

obj (xarray.Dataset) – obj with added coordinates in ground radar projection and range

dist_from_orbit(bw_sr, freq, re)[source]#

Returns range distances of SR bins (in meters) as seen from the orbit

With SR, we refer to precipitation radars based on space-born platforms such as TRMM or GPM.

Parameters
Returns

obj (xarray.Dataset) – obj with added PR bin range distances from SR platform in orbit.

Create Xarray DataArray from NumPy Array

New in version 1.3.

Parameters
Returns

dataset (xarray.DataArray) – DataArray

wradlib.georef.bin_altitude(r, theta, sitealt, *, re=6371000, ke=1.3333333333333333)[source]#

Calculates the height of a radar bin taking the refractivity of the atmosphere into account.

Based on the bin altitude is calculated as

$h = \sqrt{r^2 + (k_e r_e)^2 + 2 r k_e r_e \sin\theta} - k_e r_e$
Parameters
Keyword Arguments
• re (float) – earth’s radius [m]

• ke (float) – adjustment factor to account for the refractivity gradient that affects radar beam propagation. In principle this is wavelength- dependend. The default of 4/3 is a good approximation for most weather radar wavelengths

Returns

altitude (numpy.ndarray) – Array of heights of the radar bins in [m]

wradlib.georef.bin_distance(r, theta, sitealt, *, re=6371000, ke=1.3333333333333333)[source]#

Calculates great circle distance from radar site to radar bin over spherical earth, taking the refractivity of the atmosphere into account.

$s = k_e r_e \arctan\left( \frac{r \cos\theta}{r \cos\theta + k_e r_e + h}\right)$

where $$h$$ would be the radar site altitude amsl.

Parameters
• r (numpy.ndarray) – Array of ranges [m]

• theta (scalar or numpy.ndarray) – Array broadcastable to the shape of r elevation angles in degrees with 0° at horizontal and +90° pointing vertically upwards from the radar

• sitealt (float) – site altitude [m] amsl.

• re (float) – earth’s radius [m]

• ke (float) – adjustment factor to account for the refractivity gradient that affects radar beam propagation. In principle this is wavelength- dependend. The default of 4/3 is a good approximation for most weather radar wavelengths

Returns

distance (numpy.ndarray) – Array of great circle arc distances [m]

Calculates the 2-D Polygon vertices necessary to form a rectangular polygon around the centroid’s coordinates.

The vertices order will be clockwise, as this is the convention used by ESRI’s shapefile format for a polygon.

Parameters
• centroid (array-like) – List of 2-D coordinates of the center point of the rectangle.

• delta (scalar or numpy.ndarray) – Symmetric distances of the vertices from the centroid in each direction. If delta is scalar, it is assumed to apply to both dimensions.

Returns

vertices (numpy.ndarray) – An array with 5 vertices per centroid.

Note

The function can currently only deal with 2-D data (If you come up with a higher dimensional version of ‘clockwise’ you’re welcome to add it). The data is then assumed to be organized within the centroid array with the last dimension being the 2-D coordinates of each point.

Examples

>>> centroid_to_polyvert([0., 1.], [0.5, 1.5])
array([[-0.5, -0.5],
[-0.5,  2.5],
[ 0.5,  2.5],
[ 0.5, -0.5],
[-0.5, -0.5]])
>>> centroid_to_polyvert(np.arange(4).reshape((2,2)), 0.5)
array([[[-0.5,  0.5],
[-0.5,  1.5],
[ 0.5,  1.5],
[ 0.5,  0.5],
[-0.5,  0.5]],

[[ 1.5,  2.5],
[ 1.5,  3.5],
[ 2.5,  3.5],
[ 2.5,  2.5],
[ 1.5,  2.5]]])


Conveniently supports the construction of osr spatial reference objects

Currently, the following projection names (argument projname) are supported:

“aeqd”: Azimuthal Equidistant

needs the following keyword arguments:

• lat_0 (latitude at projection center),

• lon_0 (longitude at projection center),

• x_0 (false Easting, also known as x-offset),

• y_0 (false Northing, also known as y-offset)

Polar stereographic projection used by the German Weather Service (DWD) for all Radar composite products. See the final report on the RADOLAN project for details.

Parameters
Returns

output (osgeo.osr.SpatialReference) – GDAL/OSR object defining projection

Examples

Create In-Memory Raster Dataset

Parameters
Returns

dataset (osgeo.gdal.Dataset) – In-Memory raster dataset

Note

The origin of the provided data and coordinates is UPPER LEFT.

wradlib.georef.create_xarray_dataarray(data, *, r=None, phi=None, theta=None, site=None, sweep_mode='azimuth_surveillance', rf=1.0, **kwargs)[source]#

Create Xarray DataArray from Polar Radar Data

New in version 1.3.

Parameters
Keyword Arguments
• re (float) – effective earth radius

• ke (float) – adjustment factor to account for the refractivity gradient that affects radar beam propagation. Defaults to 4/3.

• dim0 (str) – Name of the first dimension. Defaults to ‘azimuth’.

• dim1 (str) – Name of the second dimension. Defaults to ‘range’.

Returns

dataset (xarray.DataArray) – DataArray

wradlib.georef.dist_from_orbit(sr_alt: float, alpha, beta, r_sr_inv, *, re=6371000)

Create osr spatial reference object from EPSG number

Parameters

epsg (int) – EPSG-Number defining the coordinate system

Returns

crs (osgeo.osr.SpatialReference) – GDAL/OSR object defining projection

Extract data, coordinates and projection information

Parameters
Returns

• values (numpy.ndarray) – Array of shape (nrows, ncols) or (nbands, nrows, ncols) containing the data values.

• coords (numpy.ndarray) – Array of shape (nrows,ncols,2) containing xy coordinates. The array indexing follows image convention with origin at the upper left pixel (northup). The shape is (nrows+1,ncols+1,2) if mode == edge.

• projection (osgeo.osr.SpatialReference) – Spatial reference system of the used coordinates.

Georeference Dataset/DataArray.

New in version 1.5.

This function adds georeference data to xarray Dataset/DataArray obj.

Parameters
Keyword Arguments
Returns

Return centroid of a polygon

Parameters

polyg (numpy.ndarray) – of shape (num vertices, 2) or ogr.Geometry object

Returns

out (tuple) – x and y coordinate of the centroid

Create a default projection object (wgs84)

Get a default earth projection based on WGS

Parameters

model (str) – earth model used, defaults to ellipsoid:

• ‘ellipsoid’ - WGS84 with ellipsoid heights -> EPSG 4979

• ‘geoid’ - WGS84 with egm96 geoid heights -> EPSG 4326 + 5773

• ‘sphere’ - GRS 1980 authalic sphere -> EPSG 4047

Returns

crs (osgeo.osr.SpatialReference) – projection definition

Get the radius of the Earth (in km) for a given Spheroid model (sr) at a given position.

$R^2 = \frac{a^4 \cos(f)^2 + b^4 \sin(f)^2} {a^2 \cos(f)^2 + b^2 \sin(f)^2}$
Parameters
Returns

radius (float) – earth radius in meter

Get the extent of 2d coordinates

Parameters

coords (numpy.ndarray) – coordinates array with shape (…,(x,y))

Returns

extent (tuple) – (xmin, xmax, ymin, ymax)

Get the native radar projection which is an azimuthal equidistant projection centered at the site using WGS84.

Parameters

site (sequence) – the WGS84 lon / lat coordinates of the radar location

Returns

crs (osgeo.osr.SpatialReference) – projection definition

Calculates x/y coordinates of radolan projection of the German Weather Service

Returns the 1D x,y coordinates of the radolan projection for the given grid layout.

Parameters
Keyword Arguments
• wgs84 (bool) – if True, output coordinates are in wgs84 lonlat format (default: False)

• mode (str) – ‘radolan’ - lower left pixel coordinates ‘center’ - pixel center coordinates ‘edge’ - pixel edge coordinates

• crs (osgeo.osr.SpatialReference | str) – projection of the DWD grid with spheroid model or string trig to use trigonometric formulas for calculation (only for earth model - sphere). Defaults to None (earth model - sphere).

Returns

radolan_ccords (tuple) – tuple x and y 1D coordinate numpy.ndarray shape is (nrows,) and (ncols,) if mode=’radolan’ shape is (nrows,) and (ncols,) if mode=’center’ shape is (nrows+1,) and (ncols+1,) if mode=’edge’

Calculates x,y coordinates of radolan grid from lon, lat

Parameters
Keyword Arguments

crs (osgeo.osr.SpatialReference | str) – projection of the DWD grid with spheroid model or string trig to use trigonometric formulas for calculation (only for earth model - sphere). Defaults to None (earth model - sphere).

Calculates x/y coordinates of radolan grid of the German Weather Service

Returns the x,y coordinates of the radolan grid positions (lower left corner of every pixel). The radolan grid is a polarstereographic projection, the projection information was taken from RADOLAN-RADVOR-OP Kompositformat_2.2.2

Coordinates for 900km x 900km grid#

Coordinate

lon

lat

x

y

LowerLeft

3.5889E

46.9526N

-523.4622

-4658.645

LowerRight

14.6209E

47.0705N

376.5378

-4658.645

UpperRight

15.7208E

54.7405N

376.5378

-3758.645

UpperLeft

2.0715E

54.5877N

-523.4622

-3758.645

Coordinates for 1100km x 900km grid#

Coordinate

lon

lat

x

y

LowerLeft

4.6759E

46.1929N

-443.4622

-4758.645

LowerRight

15.4801E

46.1827N

456.5378

-4758.645

UpperRight

17.1128E

55.5342N

456.5378

-3658.645

UpperLeft

3.0889E

55.5482N

-443.4622

-3658.645

Coordinates for 1500km x 1400km grid#

Coordinate

lon

lat

x

y

LowerLeft

2.3419E

43.9336N

-673.4622

-5008.645

Parameters
Keyword Arguments
• wgs84 (bool) – if True, output coordinates are in wgs84 lonlat format (default: False)

• mode (str) – ‘radolan’ - lower left pixel coordinates ‘center’ - pixel center coordinates ‘edge’ - pixel edge coordinates

• crs (osgeo.osr.SpatialReference | str) – projection of the DWD grid with spheroid model or string trig to use trigonometric formulas for calculation (only for earth model - sphere). Defaults to None (earth model - sphere).

Returns

radolan_grid (numpy.ndarray) – Array of xy- or lonlat-grid. shape is (nrows, ncols, 2) if mode=’radolan’ shape is (nrows, ncols, 2) if mode=’center’ shape is (nrows+1, ncols+1, 2) if mode=’edge’

Examples

>>> # using osr spatial reference transformation
>>> import wradlib.georef as georef  # noqa
(900, 900, 2), (-523.4622, -4658.6447)

>>> # using pure trigonometric transformations
(900, 900, 2), (-523.4622, -4658.6447)

>>> # using osr spatial reference transformation
(1500, 1400, 2), (-673.4622, -5008.6447)

>>> # using osr spatial reference transformation
(900, 900, 2), (3.5889, 46.9526)

Raises
Return surface elevation corresponding to raster dataset

The resampling algorithm is chosen based on scale ratio

Parameters
• dataset (osgeo.gdal.Dataset) – raster image with georeferencing (GeoTransform at least)

• resample (gdal:osgeo.gdalconst.ResampleAlg) – If None the best algorithm is chosen based on scales. GRA_NearestNeighbour = 0, GRA_Bilinear = 1, GRA_Cubic = 2, GRA_CubicSpline = 3, GRA_Lanczos = 4, GRA_Average = 5, GRA_Mode = 6, GRA_Max = 8, GRA_Min = 9, GRA_Med = 10, GRA_Q1 = 11, GRA_Q3 = 12

• kwargs (dict) – keyword arguments passed to wradlib.io.dem.get_srtm

Returns

elevation (numpy.ndarray) – Array of shape (rows, cols, 2) containing elevation

Get the coordinates of the 4 corners of the raster dataset

Parameters
Returns

extent (numpy.ndarray) – corner coordinates [ul,ll,lr,ur] or window extent [xmin, xmax, ymin, ymax]

Function iterates over gdal ogr layer features and packs extracted vector coordinate points into nested ndarray

It transforms coordinates to a given destination osr spatial reference if trg_crs is given and a geotransform is necessary.

Parameters

layer (osgeo.ogr.Layer)

Keyword Arguments
Returns

Extract coordinate points from given ogr geometry as generator object

If geometries are nested, function recurses.

Parameters
Yields

result (numpy.ndarray) – expands to Nx2 dimensional nested point arrays

Get polygonal vertices from rectangular grid coordinates.

Parameters

grid (numpy.ndarray) – grid edge coordinates

Keyword Arguments

ravel (bool) – option to flatten the grid

Returns

polyvert (numpy.ndarray) – A 3-d array of polygon vertices with shape (…, 5, 2).

wradlib.georef.maximum_intensity_projection(data, *, r=None, az=None, angle=None, elev=None, autoext=True)[source]#

Computes the maximum intensity projection along an arbitrary cut through the ppi from polar data.

Parameters

data (numpy.ndarray) – Array containing polar data (azimuth, range)

Keyword Arguments
Returns

Merge rasters.

Parameters
Returns

dataset (osgeo.gdal.Dataset) – merged raster dataset

Convert a vertex array to gdal/ogr geometry.

Using JSON as a vehicle to efficiently deal with numpy arrays.

Parameters
Returns

out (osgeo.ogr.Geometry) – object of type geom_name

Creates OGR.Feature objects in OGR.Layer object.

OGR.Features are built from numpy src points or polygons.

OGR.Features ‘FID’ and ‘index’ corresponds to source data element

Parameters

Copies single OGR.Geometry object to an OGR.Layer object.

Given OGR.Geometry is copied to new OGR.Feature and written to given OGR.Layer by given index. Attributes are attached.

Parameters

Copy OGR.Layer object.

Copy OGR.Layer object from src_ds gdal.Dataset to dst_ds gdal.Dataset

Parameters

Copy OGR.Layer object.

Copy OGR.Layer object from src_ds gdal.Dataset to dst_ds gdal.Dataset

Parameters
wradlib.georef.ogr_create_layer(ds, name, *, crs=None, geom_type=None, fields=None)[source]#

Creates OGR.Layer objects in gdal.Dataset object.

Creates one OGR.Layer with given name in given gdal.Dataset object using given OGR.GeometryType and FieldDefinitions

Parameters
Returns

out (osgeo.ogr.Layer) – object

Backconvert a gdal/ogr geometry Collection to a numpy vertex array.

This extracts only Polygon geometries!

Using JSON as a vehicle to efficiently deal with numpy arrays.

Parameters

ogrobj (osgeo.ogr.Geometry) – Collection object

Returns

out (numpy.ndarray) – a nested ndarray of vertices of shape (num vertices, 2)

Reproject src_lyr to dst_lyr.

Creates one OGR.Layer with given name in given gdal.Dataset object using given OGR.GeometryType and FieldDefinitions

Parameters
Returns

dst_lyr (osgeo.ogr.Layer) – OGRLayer destination layer

Backconvert a gdal/ogr geometry to a numpy vertex array.

Using JSON as a vehicle to efficiently deal with numpy arrays.

Parameters

ogrobj (osgeo.ogr.Geometry) – object

Returns

out (numpy.ndarray) – a nested ndarray of vertices of shape (num vertices, 2)

Transform a PROJ string to an osr spatial reference object

Parameters

projstr (str) – PROJ string describing projection

Returns

crs (osgeo.osr.SpatialReference) – GDAL OSR SRS object defining projection

Examples

See PROJ.

Get raster polygonal vertices from gdal dataset.

Parameters

dataset (osgeo.gdal.Dataset) – raster image with georeferencing (GeoTransform at least)

Returns

polyvert (numpy.ndarray) – A N-d array of polygon vertices with shape (…, 5, 2).

Get the projected coordinates from a GDAL dataset.

Parameters
Returns

coordinates (numpy.ndarray) – Array of shape (nrows,ncols,2) containing xy coordinates. The array indexing follows image convention with origin at upper left pixel. The shape is (nrows+1,ncols+1,2) if mode == edge.

Examples

Get a projection (OSR object) from a GDAL dataset.

Parameters

dataset (osgeo.gdal.Dataset) – raster image with georeferencing

Returns

crs (osgeo.osr.SpatialReference) – dataset projection object

Examples

Read values from a gdal object.

Parameters
Returns

values (numpy.ndarray) – Array of shape (nrows, ncols) or (nbands, nrows, ncols) containing the data values.

Examples

Transform coordinates from a source projection to a target projection.

Call signatures:

reproject(C, **kwargs)
reproject(X, Y, **kwargs)
reproject(X, Y, Z, **kwargs)


C is the np array of source coordinates. X, Y and Z specify arrays of x, y, and z coordinate values

Parameters
Keyword Arguments
Returns

Examples

Reproject/Resample given dataset according to keyword arguments

Parameters

src_ds (osgeo.gdal.Dataset) – raster image with georeferencing (GeoTransform at least)

Keyword Arguments
• spacing (float) – float or tuple of two floats pixel spacing of destination dataset, same unit as pixel coordinates

• size (int) – tuple of two ints X/YRasterSize of destination dataset

• resample (gdal:osgeo.gdalconst.ResampleAlg) – defaults to GRA_Bilinear GRA_NearestNeighbour = 0, GRA_Bilinear = 1, GRA_Cubic = 2, GRA_CubicSpline = 3, GRA_Lanczos = 4, GRA_Average = 5, GRA_Mode = 6, GRA_Max = 8, GRA_Min = 9, GRA_Med = 10, GRA_Q1 = 11, GRA_Q3 = 12

• projection_source (osgeo.osr.SpatialReference) – source dataset projection, defaults to None (get projection from src_ds)

• projection_target (osgeo.osr.SpatialReference) – destination dataset projection, defaults to None

• align (bool or tuple) – If False, there is no destination grid aligment. If True, aligns the destination grid to the next integer multiple of destination grid. If tuple (upper-left x,y-coordinate), the destination grid is aligned to this point.

Returns

dst_ds (osgeo.gdal.Dataset) – reprojected/resampled raster dataset

Sets Coordinates Indexing Scheme

This converts coordinate layout from row-major to column major indexing.

Parameters
Returns

coords (numpy.ndarray) – Array of shape (…, N, M, 2) containing xy-coordinates.

Sets Data and Coordinates Indexing Scheme

This converts data and coordinate layout from row-major to column major indexing.

Parameters
Returns

Converts Data and Coordinates Origin

Parameters
Returns

wradlib.georef.site_distance(r, theta, binalt, *, re=6371000, ke=1.3333333333333333)[source]#

Calculates great circle distance from bin at certain altitude to the radar site over spherical earth, taking the refractivity of the atmosphere into account.

Based on the site distance may be calculated as

$s = k_e r_e \arcsin\left( \frac{r \cos\theta}{k_e r_e + h_n(r, \theta, r_e, k_e)}\right)$

where $$h_n$$ would be provided by bin_altitude.

Parameters
Keyword Arguments
• re (float) – earth’s radius [m]

• ke (float) – adjustment factor to account for the refractivity gradient that affects radar beam propagation. In principle this is wavelength- dependend. The default of 4/3 is a good approximation for most weather radar wavelengths

Returns

distance (numpy.ndarray) – Array of great circle arc distances [m]

wradlib.georef.spherical_to_centroids(r, phi, theta, site, *, crs=None)[source]#

Generate 3-D centroids of the radar bins from the sperical coordinates (r, phi, theta).

Both azimuth and range arrays are assumed to be equidistant and to contain only unique values. The ranges are assumed to define the exterior boundaries of the range bins (thus they must be positive). The angles are assumed to describe the pointing direction fo the main beam lobe.

For further information refer to the documentation of spherical_to_xyz.

Parameters
• r (numpy.ndarray) – Array of ranges [m]; r defines the exterior boundaries of the range bins! (not the centroids). Thus, values must be positive!

• phi (numpy.ndarray) – Array of azimuth angles containing values between 0° and 360°. The angles are assumed to describe the pointing direction fo the main beam lobe! The first angle can start at any values, but make sure the array is sorted continuously positively clockwise and the angles are equidistant. An angle if 0 degree is pointing north.

• theta (float) – Elevation angle of scan

• site (sequence) – the lon/lat/alt coordinates of the radar location

• crs (osgeo.osr.SpatialReference) – Destination Projection

Returns

Note

Azimuth angles of 360 deg are internally converted to 0 deg.

wradlib.georef.spherical_to_polyvert(r, phi, theta, site, *, crs=None)[source]#

Generate 3-D polygon vertices directly from spherical coordinates (r, phi, theta).

This is an alternative to centroid_to_polyvert which does not use centroids, but generates the polygon vertices by simply connecting the corners of the radar bins.

Both azimuth and range arrays are assumed to be equidistant and to contain only unique values. For further information refer to the documentation of spherical_to_xyz.

Parameters
• r (numpy.ndarray) – Array of ranges [m]; r defines the exterior boundaries of the range bins! (not the centroids). Thus, values must be positive!

• phi (numpy.ndarray) – Array of azimuth angles containing values between 0° and 360°. The angles are assumed to describe the pointing direction fo the main beam lobe! The first angle can start at any values, but make sure the array is sorted continuously positively clockwise and the angles are equidistant. An angle if 0 degree is pointing north.

• theta (float) – Elevation angle of scan

• site (sequence) – the lon/lat/alt coordinates of the radar location

• crs (osgeo.osr.SpatialReference) – Destination Projection

Returns

• output (numpy.ndarray) – A 3-d array of polygon vertices with shape(num_vertices, num_vertex_nodes, 2). The last dimension carries the xyz-coordinates either in aeqd or given crs.

• aeqd (gdal:osgeo.aeqosr.SpatialReference) – only returned if crs is None

Examples

>>> import wradlib.georef as georef  # noqa
>>> import numpy as np
>>> from matplotlib import collections
>>> import matplotlib.pyplot as pl
>>> #pl.interactive(True)
>>> # define the polar coordinates and the site coordinates in lat/lon
>>> r = np.array([50., 100., 150., 200.]) * 1000
>>> # _check_polar_coords fails in next line
>>> # az = np.array([0., 45., 90., 135., 180., 225., 270., 315., 360.])
>>> az = np.array([0., 45., 90., 135., 180., 225., 270., 315.])
>>> el = 1.0
>>> site = (9.0, 48.0, 0)
>>> polygons, aeqd = georef.spherical_to_polyvert(r, az, el, site)
>>> # plot the resulting mesh
>>> fig = pl.figure()
>>> #polycoll = mpl.collections.PolyCollection(vertices,closed=True, facecolors=None)  # noqa
>>> polycoll = collections.PolyCollection(polygons[...,:2], closed=True, facecolors='None')  # noqa
>>> pl.autoscale()
>>> pl.show()

wradlib.georef.spherical_to_proj(r, phi, theta, site, *, crs=None, re=None, ke=1.3333333333333333)[source]#

Transforms spherical coordinates (r, phi, theta) to projected coordinates centered at site in given projection.

It takes the shortening of the great circle distance with increasing elevation angle as well as the resulting increase in height into account.

Parameters
Keyword Arguments
• crs (osgeo.osr.SpatialReference) – Destination Spatial Reference System (Projection). Defaults to wgs84 (epsg 4326).

• re (float) – earth’s radius [m]

• ke (float) – adjustment factor to account for the refractivity gradient that affects radar beam propagation. In principle this is wavelength- dependend. The default of 4/3 is a good approximation for most weather radar wavelengths.

Returns

coords (numpy.ndarray) – Array of shape (…, 3). Contains projected map coordinates.

Examples

A few standard directions (North, South, North, East, South, West) with different distances (amounting to roughly 1°) from a site located at 48°N 9°E

>>> r  = np.array([0.,   0., 111., 111., 111., 111.,])*1000
>>> az = np.array([0., 180.,   0.,  90., 180., 270.,])
>>> th = np.array([0.,   0.,   0.,   0.,   0.,  0.5,])
>>> csite = (9.0, 48.0, 0)
>>> coords = spherical_to_proj(r, az, th, csite)
>>> for coord in coords:
...     print( '{0:7.4f}, {1:7.4f}, {2:7.4f}'.format(*coord))
...
9.0000, 48.0000,  0.0000
9.0000, 48.0000,  0.0000
9.0000, 48.9981, 725.7160
10.4872, 47.9904, 725.7160
9.0000, 47.0017, 725.7160
7.5131, 47.9904, 1694.2234


Here, the coordinates of the east and west directions won’t come to lie on the latitude of the site because the beam doesn’t travel along the latitude circle but along a great circle.

wradlib.georef.spherical_to_xyz(r, phi, theta, site, *, re=None, ke=1.3333333333333333, squeeze=False, strict_dims=False)[source]#

Transforms spherical coordinates (r, phi, theta) to cartesian coordinates (x, y, z) centered at site (aeqd).

It takes the shortening of the great circle distance with increasing elevation angle as well as the resulting increase in height into account.

Parameters
Keyword Arguments
• re (float) – earth’s radius [m], defaults to None (calculating from given latitude)

• ke (float) – adjustment factor to account for the refractivity gradient that affects radar beam propagation. In principle this is wavelength- dependend. The default of 4/3 is a good approximation for most weather radar wavelengths.

• squeeze (bool) – If True, returns squeezed array. Defaults to False.

• strict_dims (bool) – If True, generates output of (theta, phi, r, 3) in any case. If False, dimensions with same length are “merged”.

Returns

Construct sweep centroids native coordinates.

Parameters
Returns

coordinates (numpy.ndarray) – array of shape (nrays,nbins,3) containing native centroid radar coordinates (slant range, azimuth, elevation)

Perform geotransformation to given destination SpatialReferenceSystem

It transforms coordinates to a given destination osr spatial reference if a geotransform is neccessary.

Parameters
Keyword Arguments

src_crs (osgeo.osr.SpatialReference) – Source Projection

Returns

geom (osgeo.ogr.Geometry) – Transformed Geometry

Create osr spatial reference object from WKT string

Parameters

wkt (str) – WTK string defining the coordinate reference system

Returns

crs (osgeo.osr.SpatialReference) – GDAL/OSR object defining projection