xarray powered Cf/Radial and ODIM_H5

In this example, we read and write Cf/Radial (NetCDF) and ODIM_H5 (HDF5) data files from different sources using an xarray powered data structure.

Note

The following functionality is deprecated. Please use the xarray backend loaders instead.

[ ]:
import wradlib as wrl
import warnings
warnings.filterwarnings('ignore')
import matplotlib.pyplot as pl
import numpy as np
import xarray as xr
try:
    get_ipython().magic("matplotlib inline")
except:
    pl.ion()
from wradlib.io.xarray_depr import CfRadial, OdimH5

Load ODIM_H5 Volume Data

[ ]:
fpath = 'hdf5/knmi_polar_volume.h5'
f = wrl.util.get_wradlib_data_file(fpath)
cf1 = OdimH5(f, standard='cf', georef=True)

Inspect root group

You can use the object dictionary using cf1[‘root’] or the property cf1.root.

The sweep dimension contains the number of scans in this radar volume. Further the dataset consists of variables (location coordinates, time_coverage) and attributes (Conventions, metadata).

[ ]:
cf1.root

Inspect sweep group(s)

The sweep-groups can be accessed via their respective keys. The dimensions consist of range and time with added coordinates azimuth, elevation, range and time. There will be variables like radar moments (DBZH etc.) and sweep-dependend metadata (like fixed_angle, sweep_mode etc.).

[ ]:
cf1['sweep_1']
[ ]:
cf1['sweep_1'].DBZH

Plotting

[ ]:
cf1['sweep_1'].DBZH.plot.pcolormesh(x='x', y='y')
pl.gca().set_aspect('equal')
[ ]:
fig = pl.figure(figsize=(10,8))
cf1['sweep_1'].DBZH.sortby('azimuth').wradlib.plot_ppi(proj='cg', fig=fig)
[ ]:
import cartopy
import cartopy.crs as ccrs
import cartopy.feature as cfeature

map_trans = ccrs.AzimuthalEquidistant(central_latitude=cf1['sweep_1'].latitude.values,
                                      central_longitude=cf1['sweep_1'].longitude.values)
[ ]:
map_proj = ccrs.AzimuthalEquidistant(central_latitude=cf1['sweep_1'].latitude.values,
                                      central_longitude=cf1['sweep_1'].longitude.values)
pm = cf1['sweep_1'].DBZH.wradlib.plot_ppi(proj=map_proj)
ax = pl.gca()
ax.gridlines(crs=map_proj)
print(ax)
[ ]:
map_proj = ccrs.Mercator(central_longitude=cf1['sweep_1'].longitude.values)
fig = pl.figure(figsize=(10,8))
ax = fig.add_subplot(111, projection=map_proj)
pm = cf1['sweep_1'].DBZH.wradlib.plot_ppi(ax=ax)
ax.gridlines(draw_labels=True)
[ ]:
import cartopy.feature as cfeature
def plot_borders(ax):
    borders = cfeature.NaturalEarthFeature(category='physical',
                                           name='coastline',
                                           scale='10m',
                                           facecolor='none')
    ax.add_feature(borders, edgecolor='black', lw=2, zorder=4)

map_proj = ccrs.Mercator(central_longitude=cf1['sweep_1'].longitude.values)
fig = pl.figure(figsize=(10,8))
ax = fig.add_subplot(111, projection=map_proj)

DBZH = cf1['sweep_1'].DBZH
pm = DBZH.where(DBZH > 0).wradlib.plot_ppi(ax=ax)
plot_borders(ax)
ax.gridlines(draw_labels=True)
[ ]:
import matplotlib.path as mpath
theta = np.linspace(0, 2*np.pi, 100)
center, radius = [0.5, 0.5], 0.5
verts = np.vstack([np.sin(theta), np.cos(theta)]).T
circle = mpath.Path(verts * radius + center)

map_proj = ccrs.AzimuthalEquidistant(central_latitude=cf1['sweep_1'].latitude.values,
                                     central_longitude=cf1['sweep_1'].longitude.values,
                                    )
fig = pl.figure(figsize=(10,8))
ax = fig.add_subplot(111, projection=map_proj)
ax.set_boundary(circle, transform=ax.transAxes)

pm = cf1['sweep_1'].DBZH.wradlib.plot_ppi(proj=map_proj, ax=ax)
ax = pl.gca()
ax.gridlines(crs=map_proj)
[ ]:
fig = pl.figure(figsize=(10, 8))
proj=ccrs.AzimuthalEquidistant(central_latitude=cf1['sweep_1'].latitude.values,
                               central_longitude=cf1['sweep_1'].longitude.values)
ax = fig.add_subplot(111, projection=proj)
pm = cf1['sweep_1'].DBZH.wradlib.plot_ppi(ax=ax)
ax.gridlines()
[ ]:
dbz = cf1['sweep_1']
dbz.DBZH.wradlib.plot_ppi()

Inspect radar moments

The dataarrays can be accessed by key or by attribute. Each dataarray has the datasets dimensions and coordinates of it’s parent dataset. There are attributes connected which are defined by Cf/Radial and/or ODIM_H5 standard.

[ ]:
cf1['sweep_1'].DBZH
[ ]:
cf1['sweep_1']

Create simple plot

Using xarray features a simple plot can be created like this. Note the sortby('time') method, which sorts the radials by time.

[ ]:
cf1['sweep_1'].DBZH.copy().sortby('time').plot(add_labels=False)
[ ]:
pm = cf1['sweep_1'].DBZH.wradlib.plot_ppi(proj={'latmin': 33e3})
[ ]:
cf1.to_odim('knmi_odim.h5')
cf1.to_cfradial2('knmi_odim_as_cfradial.nc')

Import again

[ ]:
cf1a = OdimH5('knmi_odim.h5', standard='cf', georef=True)
cf1b = CfRadial('knmi_odim_as_cfradial.nc', georef=True)
[ ]:
cf1a['sweep_1']

Check equality

[ ]:
xr.testing.assert_equal(cf1.root, cf1a.root)
xr.testing.assert_equal(cf1['sweep_1'], cf1a['sweep_1'].sortby("azimuth"))
xr.testing.assert_equal(cf1.root, cf1b.root)
xr.testing.assert_allclose(cf1['sweep_1'], cf1b['sweep_1'].sortby("azimuth"))

Mask some values

[ ]:
cf1['sweep_1']['DBZH'] = cf1['sweep_1']['DBZH'].where(cf1['sweep_1']['DBZH'] >= 0)
cf1['sweep_1']['DBZH'].sortby('time').plot()

Load Cf/Radial1 Volume Data

[ ]:
fpath = 'netcdf/cfrad.20080604_002217_000_SPOL_v36_SUR.nc'
f = wrl.util.get_wradlib_data_file(fpath)
cf2 = CfRadial(f)#, georef=True)

Fix duplicate rays

[ ]:
for i, key in enumerate(cf2):
    num_rays = int(360 // cf2[key].azimuth.diff("time").median())
    start_rays = cf2[key].dims["time"] - num_rays
    cf2[key] = cf2[key].sortby("time").isel(time=slice(start_rays, start_rays + num_rays ))

Inspect root group

[ ]:
cf2.root

Inspect sweep group(s)

[ ]:
cf2['sweep_1']

Inspect radar moments

[ ]:
cf2['sweep_1'].DBZ

Create simple plot

[ ]:
cf2['sweep_1'].DBZ.plot()
[ ]:
cf2['sweep_1'].DBZ.pipe(wrl.georef.georeference_dataset).plot.pcolormesh(x='x', y='y', add_labels=False)
pl.gca().set_aspect('equal')

Use wradlib DataArray connector

[ ]:
pm = cf2['sweep_1'].DBZ.pipe(wrl.georef.georeference_dataset).wradlib.plot_ppi()
[ ]:
pm = cf2['sweep_1'].DBZ.pipe(wrl.georef.georeference_dataset).wradlib.plot_ppi(proj='cg')

Export data to Cf/Radial2 and ODIM_H5

[ ]:
cf2.to_cfradial2('timrex_cfradial2.nc')
cf2.to_odim('timrex_cfradial_as_odim.h5')
[ ]:
cf2["sweep_1"]

Import again

[ ]:
cf2a = CfRadial('timrex_cfradial2.nc')
cf2b = OdimH5('timrex_cfradial_as_odim.h5', standard='cf')
[ ]:
cf2a['sweep_1'].DBZ.pipe(wrl.georef.georeference_dataset).plot.pcolormesh(x='x', y='y', add_labels=False)
pl.gca().set_aspect('equal')
[ ]:
cf2b['sweep_1'].DBZ.pipe(wrl.georef.georeference_dataset).plot.pcolormesh(x='x', y='y', add_labels=False)
pl.gca().set_aspect('equal')

Check equality

For Cf/Radial there are issues with nan, which need to be fixed. For the ODIM_H5 intercomparison there are too problems with nan and issues with attributes.

[ ]:
xr.testing.assert_equal(cf2.root, cf2a.root)
xr.testing.assert_allclose(cf2['sweep_1'], cf2a['sweep_1'])
xr.testing.assert_allclose(cf2.root.drop_vars(["volume_number", "status_xml"]),
                           cf2b.root.drop_vars(["volume_number", "status_xml", "altitude_agl", "frequency"]))
drop = set(cf2['sweep_1']) ^ set(cf2b['sweep_1']) | set(["prt_mode", "follow_mode", "time"])
xr.testing.assert_allclose(cf2['sweep_1'].drop_vars(drop).sortby("azimuth"),
                           cf2b['sweep_1'].drop_vars(drop, errors="ignore").sortby("azimuth"))