Coverage for stems/gis/conventions.py : 88%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
""" CF conventions for referencing xarray/NetCDF data
Includes functions useful for managing CF conventions (variable and coordinating naming, grid mapping variables, etc) """
# ============================================================================= # DATA # Names of x/y dimensions, ordered with some preference
#: dict: CF coordinate attribute metadata # http://cfconventions.org/cf-conventions/v1.6.0/cf-conventions.html#coordinate-types 'longitude': { 'standard_name': 'longitude', 'long_name': 'longitude', 'units': 'degrees_east', }, 'latitude': { 'standard_name': 'latitude', 'long_name': 'latitude', 'units': 'degrees_north', }, 'x': { 'standard_name': 'projection_x_coordinate', 'long_name': 'x coordinate of projection', }, 'y': { 'standard_name': 'projection_y_coordinate', 'long_name': 'y coordinate of projection', }, 'time': { 'standard_name': 'time', 'long_name': 'Time, unix time-stamp', 'axis': 'T', 'calendar': 'standard' } }
#: dict: CF NetCDF attributes # http://cfconventions.org/cf-conventions/v1.6.0/cf-conventions.html#identification-of-conventions ('Conventions', 'CF-1.7'), ))
# ============================================================================ # Georeferencing grid_mapping='crs', inplace=False): """ Georeference XArray data with the CRS and Affine transform
Parameters ---------- xarr : xarray.DataArray or xarray.Dataset XArray data to georeference crs : rasterio.crs.CRS Rasterio CRS transform : affine.Affine, optional Affine transform of the data. Will be calculated using :py:func:`stems.gis.coords.coords_to_transform` if not provided grid_mapping : str, optional Name to use for grid mapping variable inplace : bool, optional If ``False``, returns a modified shallow copy of ``xarr``
Returns ------- xarray.DataArray or xarray.Dataset Georeferenced data (type depending on input) """
# Copy as needed
# "Georeference" 2D data (variables)
# Create y/x with attributes
# Calculate transform if needed # TODO(?): don't just hardcode these coords_to_transform_kwds = {'center': True, 'assume_unique': False} transform = coords_to_transform(y, x, **coords_to_transform_kwds)
# Create grid mapping grid_mapping=grid_mapping)
# Add additional CF related attributes
""" Determine if XArray data is georeferenced
Parameters ---------- xarr : xarray.DataArray or xarray.Dataset XArray data to check for georeferencing grid_mapping : str, optional Name to use for grid mapping variable require_gdal : bool, optional Require presence of attributes GDAL uses to georeference as backup ("spatial_ref" and "GeoTransform")
Returns ------- bool True if is georeferenced """
# Retrieve grid_mapping else: # Needs to have require information
return False return False
return False else: return False
else: logger.debug(f'Not georeferencing "{x.name}" because it lacks x/y ' f'dimensions ("{dim_x}" and "{dim_y}")')
quote = lambda s: f'"{s}"' missing = ", ".join([quote(a) for ok_, a in zip(ok, attrs) if not ok_]) logger.debug('Cannot find required grid mapping attributes on ' f'"{xarr.name}": {missing}') return False
# ============================================================================= # Projection """ Return grid mapping variable
Parameters ---------- xarr : xarray.Dataset or xarray.DataArray XArray data
Returns ------- xarray.Variable XArray grid mapping variable
Raises ------ KeyError Raised if grid mapping variable does not exist """ else:
gdal_compat=True): """ Return an :py:class:`xarray.DataArray` of CF-compliant CRS info
Parameters ---------- crs : rasterio.crs.CRS Coordinate reference system information transform : affine.Affine, optional Affine transform. Will be written if writing GDAL compatibility attributes and if provided grid_mapping : str, optional Name of grid mapping variable. Defaults to 'crs' gdal_compat : bool, optional Write GDAL compatibility attribute data ("spatial_ref" and "GeoTransform")
Returns ------- xarray.DataArray "crs" variable holding CRS information """
# This part is entirely unnecessary! else:
# For GDAL in case CF doesn't work # http://www.gdal.org/frmt_netcdf.html
# Fixup - every list/tuple should be np.ndarray to look like CRS variables # that have been written to disk (otherwise comparisons fail)
# ============================================================================= # Coordinates """ Return ``y`` and ``x`` as coordinates variables given the ``crs``
Parameters ---------- y : np.ndarray Y coordinate x : np.ndarray X coordinate crs : rasterio.crs.CRS Coordinate reference system of ``y`` and ``x``
Returns ------- xr.Variable : y_coord X coordinate xr.Variable : x_coord Y coordinate
References ---------- .. [1] http://cfconventions.org/cf-conventions/v1.6.0/cf-conventions.html#coordinate-types """ # 1. Extract data
# 2. Names # Determine name according to projection
# 3. Coord name -- keep existing if possible else: dim_y = var_y
else: dim_x = var_x
# 4. Coords are either same coordinate or whatever was on y/x else: coords_y = {dim_y: y.coords[dim_y]} else: coords_x = {dim_x: x.coords[dim_x]}
# 5. Get copies of attributes
# If projected we add a few extra definitions
# Lastly, create DataArrays
name=var_y, attrs=attrs_y) name=var_x, attrs=attrs_x)
|