grid_process.grid_interp#

Module for spatial interpolation of gridded datasets

Attributes#

Classes#

GridInterp

Xarray accessors class for spatial interpolation of gridded data

Functions#

interp_temp(→ numpy.ndarray)

Interpolation from grid to POIs for temperature data, based on local

interp_temp_fixgrad(→ numpy.ndarray)

Interpolation from grid to POIs for temperature data by taking the

interp_nearest_alt(→ numpy.ndarray)

Interpolation from grid to POIs for elevation dependent data. The method finds

interp_idw(→ numpy.ndarray)

Performs interpolations from grid to POIs using inverse distance

interp_upscaled(→ numpy.ndarray)

Perform interpolations from grid to POIs by computing a group statistic

interp_nearest(→ numpy.ndarray)

Performs nearest neighbor interpolation from grid to POIs.

interp_snowlim(→ numpy.ndarray)

Special interpolation routine for snow limit. Snow limits below model

interp2poi(→ xarray.Dataset)

Interpolates gridded spatial data to a set of Points of Interest (POIs).

nn_lookup(→ tuple[numpy.ndarray, numpy.ndarray])

Find the k nearest grid points and corresponding distances for a set of

nn_lookup_cached(→ tuple[numpy.ndarray, numpy.ndarray])

Wrapper to nn_lookup() function to use it with a cache

nn_lookup_regular(→ list[numpy.ndarray | xarray.DataArray])

Find the nearest grid point for a set of POIs when the source

interp2grid(→ xarray.Dataset)

Interpolates data from a source grid to a destination grid, supporting regular and unstructured grids.

slice_boundingbox(→ xarray.Dataset)

Slice input dataset spatial dimensions to the bounding box of the target POIs

slice_coarsen(→ xarray.Dataset)

Slice input dataset to the extend of the destination grid and coarsen it if the

Module Contents#

logger#
class GridInterp(ds: xarray.Dataset)[source]#

Xarray accessors class for spatial interpolation of gridded data

dataset_accessor#
POI_MODEL#
POI_DIM#
POI_COORD_COL#
SRC_ATTRS_KEEP = ('source', 'title', 'institution', 'history', 'references', 'comment')#
SWISS_CRS = ('EPSG:2056', 'EPSG:21781')#
InterpMethods#
interp_temp(coords_flat: numpy.ndarray, data_flat: numpy.ndarray, pois_coords: numpy.ndarray, z_fact: int = 25, k: int = 36, weight_power: float | None = None, grad_only: bool = False, chunk_size: int = 20) → numpy.ndarray[source]#

Interpolation from grid to POIs for temperature data, based on local soundings. The grid does not need to be regular. The sounding curves are fitted on the k nearest neighbors considering a distance that more heavily penalizes elevation differences for z_fact > 1.

Parameters:
  • coords_flat (numpy.ndarray, shape (n_grids, m)) – array of flattened grid coordinates. n_grids is the number of model grid points, m the number of coordinates dimensions (i.e. 3)

  • data_flat (numpy.ndarray, shape (n_grids, …)) – array containing the flattened model data with various trailing dimensions

  • pois_coords (numpy.ndarray , shape (n_pois, m)) – array of POI coordinates. n_pois is the number of POIs, m the number of coordinates dimensions (i.e. 3)

  • z_fact (positive int, optional) – factor to multiply the z coordinates to find nearest neighbors based on a non-euclidean distance that penalizes more altitude differences. Default value is 50. A value of 1 will use regular euclidean distances.

  • k (positive int, optional) – number of considered nearest neighbors for the local sounding. Default is 36

  • weight_power (positive float, optional) – a weight vector is passed to the sounding fit according to w = d^(-weight_power), with d being the (non-euclidean) distances between the considered POI and the k nearest grid points. The greater is the weight_power, the stronger is the penalization with distance. A weight_power of 0 is equivalent to None (i.e. same weights for all points). By default, gives same weight for all points

  • grad_only (bool, optional) – if True, only uses the local gradient to correct the nearest gridpoint temperature based on the altitude difference with the POI. Default is False

  • chunk_size (positive int, optional) – number of POIs processed per sounding batch. Smaller values reduce peak memory (dominant cost: chunk_size × k × n_trail × 12 bytes) and keep the working set in L3 cache, which is typically faster when n_trail is large. Larger values reduce loop overhead and are better for small trailing dimensions or when n_pois is small. Default is 20.

Returns:

poi_data – array containing the interpolated values and the same trailing dimensions as the input data_flat array

Return type:

numpy.ndarray, shape (n_pois, …)

:raises ValueError : Raised if the orography is flat, as no sounding can be estimated.:

See also

interp2poi()

Note

For POIs with altitude higher than 300m above the highest gridpoint or lower than 500m below the lowest gridpoint in the local neighborhood used for the fit, the fixgrad method is used with default gradient of 0.006 [K / m].

interp_temp_fixgrad(coords_flat: numpy.ndarray, data_flat: numpy.ndarray, pois_coords: numpy.ndarray, r_search: float = 2, z_weight: int = 200, grad: float = 0.006) → numpy.ndarray[source]#

Interpolation from grid to POIs for temperature data by taking the surrounding gridpoint with the most similar altitude and further correct for altitude difference with a fixed gradient.

Parameters:
  • coords_flat (numpy.ndarray, shape (n_grids, m)) – array of flattened grid coordinates. n_grids is the number of model grid points, m the number of coordinates dimensions (i.e. 3)

  • data_flat (numpy.ndarray, shape (n_grids, …)) – array containing the flattened model data with various trailing dimensions

  • pois_coords (numpy.ndarray , shape (n_pois, m)) – array of POI coordinates. n_pois is the number of POIs, m the number of coordinates dimensions (i.e. 3)

  • r_search (positive float, optional) – radius in model gridpoints that define the number of neighbors included in the search. Default is 4

  • z_weight (positive int, optional) – weight for the z axis in the distance computation of the “most adequat” gridpoint. d = horizontal_dist + z_weight * vertical_dist. Default value is 200

  • grad (positive float) – gradient in [K / m] to correct for altitude difference between POI and nearest grid point. Default is 0.006 [K / m]

Returns:

poi_data – array containing the interpolated values and the same trailing dimensions as the input data_flat array.

Return type:

numpy.ndarray, shape (n_pois, …)

See also

interp2poi()

interp_nearest_alt(coords_flat: numpy.ndarray, data_flat: numpy.ndarray, pois_coords: numpy.ndarray, r_search: float = 2, z_weight: int = 500) → numpy.ndarray[source]#

Interpolation from grid to POIs for elevation dependent data. The method finds the nearest grid point according to a distance that use a much larger weight along the z axis. For wind data for instance, grid points at similar altitudes are preferred. The grid does not need to be regular.

Parameters:
  • coords_flat (numpy.ndarray, shape (n_grids, m)) – array of flattened grid coordinates. n_grids is the number of model grid points, m the number of coordinates dimensions (i.e. 3)

  • data_flat (numpy.ndarray, shape (n_grids, …)) – array containing the flattened model data with various trailing dimensions

  • pois_coords (numpy.ndarray , shape (n_pois, m)) – array of POI coordinates. n_pois is the number of POIs, m the number of coordinates dimensions (i.e. 3)

  • r_search (positive float, optional) – radius in model gridpoints that define the number of neighbors included in the search. Default is 4

  • z_weight (positive int, optional) – weight for the z axis in the distance computation of the “most adequat” gridpoint. d = horizontal_dist + z_weight * vertical_dist. Default value is 500

Returns:

poi_data – array containing the interpolated values and the same trailing dimensions as the input data_flat array

Return type:

numpy.ndarray, shape (n_pois, …)

See also

interp2poi()

interp_idw(coords_flat: numpy.ndarray, data_flat: numpy.ndarray, pois_coords: numpy.ndarray, k: int = 4, weight_power: float = 1.0) → numpy.ndarray[source]#

Performs interpolations from grid to POIs using inverse distance weightning.

Parameters:
  • coords_flat (numpy.ndarray, shape (n_grids,m)) – array of flattened grid coordinates. n_grids is the number of model grid points, m the number of coordinates dimensions (i.e. 2 or 3)

  • data_flat (numpy.ndarray, shape (n_grids, …)) – array containing the flattened model data with various trailing dimensions

  • pois_coords (numpy.ndarray , shape (n_pois, m)) – array of POI coordinates. n_pois is the number of POIs, m the number of coordinates dimensions (i.e. 2 or 3)

  • k (positive int, optional) – number of considered nearest neighbors. Default is 4

  • weight_power (positive float, optional) – the interpolated value is the weighted average of the k nearest grid points accordi g to w = d^(-weight_power), with d being the distance between the considered POI and the gird points. The greater is the weight_power, the stronger is the penalization with distance. A weight_power of 0 produces a normal average of the k nearest grid points

Returns:

poi_data – array containing the interpolated values and the same trailing dimensions as the input data_flat array

Return type:

numpy.ndarray, shape (n_pois, …)

See also

interp2poi()

interp_upscaled(coords_flat: numpy.ndarray, data_flat: numpy.ndarray, pois_coords: numpy.ndarray, k: int = 4, agg_func: collections.abc.Callable = np.max) → numpy.ndarray[source]#

Perform interpolations from grid to POIs by computing a group statistic over the k nearest neighbors (e.g. upscaling).

Parameters:
  • coords_flat (numpy.ndarray, shape (n_grids, m)) – array of flattened grid coordinates. n_grids is the number of model grid points, m the number of coordinates dimensions (i.e. 2 or 3)

  • data_flat (numpy.ndarray, shape (n_grids, …)) – array containing the flattened model data with various trailing dimensions

  • pois_coords (numpy.ndarray , shape (n_pois, m)) – array of POI coordinates. n_pois is the number of POIs, m the number of coordinates dimensions (i.e. 2 or 3).

  • k (positive int, optional) – number of considered nearest neighbors. Default is 4

  • agg_func (callable, optional) – specify the spatial aggregation function to use (i.e. numpy.mean, numpy.max, numpy.min, numpy.std). Default is numpy.max.

Returns:

poi_data – array containing the interpolated values and the same trailing dimensions as the input data_flat array

Return type:

numpy.ndarray, shape (n_pois, …)

See also

interp2poi()

interp_nearest(coords_flat: numpy.ndarray, data_flat: numpy.ndarray, pois_coords: numpy.ndarray) → numpy.ndarray[source]#

Performs nearest neighbor interpolation from grid to POIs.

Parameters:
  • coords_flat (numpy.ndarray, shape (n_grids, m)) – array of flattened grid coordinates. n_grids is the number of model grid points, m the number of coordinates dimensions (i.e. 2 or 3).

  • data_flat (numpy.ndarray, shape (n_grids, …)) – array containing the flattened model data with various trailing dimensions

  • pois_coords (numpy.ndarray , shape (n_pois, m)) – array of POI coordinates. n_pois is the number of POIs, m the number of coordinates dimensions (i.e. 2 or 3).

Returns:

poi_data – array containing the interpolated values and the same trailing dimensions as the input data_flat array

Return type:

numpy.ndarray, shape (n_pois, …)

See also

interp2poi()

interp_snowlim(coords_flat: numpy.ndarray, data_flat: numpy.ndarray, pois_coords: numpy.ndarray, k: int = 36, d_max: float = 40000) → numpy.ndarray[source]#

Special interpolation routine for snow limit. Snow limits below model topography are undefined, resulting in datasets with randomly distributed NaNs. This routine checks for the nearest non-NaN grid points. If this point is further away than d_max, the snowlimit is set to a value between 0 and 200 [m] depending on the POI altitude. Otherwise, the minimum between the nearest non-NaN grid point and the minimum altitude of NaN grid points among the k nearest neighbors is taken.

Parameters:
  • coords_flat (numpy.ndarray, shape (n_grids, m)) – array of flattened grid coordinates. n_grids is the number of model grid points, m the number of coordinates dimensions (i.e. 3)

  • data_flat (numpy.ndarray, shape (n_grids, …)) – Array containing the flattened model data with various trailing dimension.

  • pois_coords (numpy.ndarray , shape (n_pois, m)) – array of POI coordinates. n_pois is the number of POIs, m the number of coordinates dimensions (i.e. 3)

  • k (positive int) – Number of considered nearest neighbors to check for altitude of NaN grid points.

  • d_max (positive float) – if all grid points within a radius of d_max meter from the POI are NaNs the snow limit is set to a value between 0 and 200 [m] depending on the POI altitude

Returns:

poi_data – array containing the interpolated values and the same trailing dimensions as the input data_flat array

Return type:

numpy.ndarray, shape (n_pois, …)

See also

interp2poi()

interp2poi(data: xarray.Dataset, poi_info: geopandas.GeoDataFrame, method: InterpMethods, try_reg: bool = True, **kwargs: Any) → xarray.Dataset[source]#

Interpolates gridded spatial data to a set of Points of Interest (POIs).

This function provides a unified interface for interpolating values from regular or unstructured spatial grids to arbitrary POI locations, supporting a variety of interpolation methods and data models. It replaces the original spatial grid dimensions in data with a POI dimension, containing interpolated values for each POI.

Parameters:
  • data (xarray.Dataset) –

    The source grid dataset. Supported data models include:

    Typical spatial dimension and coordinate names are supported, and can be extended via environment variables:

    • Y coordinate: export GRID_PROCESS__data_model__grid__y (e.g., ‘[“y”, “latitude”, “lat”, “dummy_y”]’)

    • X coordinate: export GRID_PROCESS__data_model__grid__x (e.g., ‘[“x”, “longitude”, “lon”, “dummy_x”]’)

    • Unstructured dimension: export GRID_PROCESS__data_model__grid__unstructured_dim (e.g., ‘[“dummy_cell”]’)

    • When the spatial coordinates variables have a CF compliant standard_name attribute, arbitrary names can be used directly.

    Spatial CRS must be referenced via one of:

    • Global attribute ‘crs’ (e.g., “EPSG:2056” or anything accepted by pyproj.CRS.from_user_input())

    • Global attribute ‘grid_mapping’ (internal grid database convention)

    • CF-convention grid mapping variable

    • If coordinates are named ‘latitude’/’longitude’ or ‘lat’/’lon’, WGS84 (EPSG:4326) is assumed.

    For methods requiring altitude, ensure a surface altitude coordinate is present; extend supported names via GRID_PROCESS__data_model__grid__surf_alt.

  • poi_info (geopandas.GeoDataFrame) – POI locations and attributes. Must have geometry and a defined CRS. For methods requiring altitude, a POI altitude column or z-component in geometry (in units of meters) is needed. Extend supported POI altitude column names via:

    • export GRID_PROCESS__data_model__poi__alt_from (e.g., ‘[“height_masl”, “altitude”, “dummy_height”]’)

    The column name is used for the output POI coordinate by default; override via:

    • export GRID_PROCESS__data_model__poi__coord_from (e.g., dummy_name)

  • method (str) –

    Interpolation method. Supported options include:

    {‘nearest’, ‘linear’, ‘cubic’, ‘idw’, ‘temp’, ‘temp_fixgrad’, ‘nearest_alt’, ‘snowlim’, ‘nearest_3D’, ‘linear_3D’, ‘idw_3D’, ‘upscaled’, ‘upscaled_3D’}.

    3D methods include altitude in neighbor selection. For unstructured grids, prefer ‘idw’ with k=4 and weight_power=2 over ‘linear’ for performence reasons.

  • try_reg (bool, default True) – If True, attempts regular grid interpolation for structured grids with 1D coordinates when method is ‘nearest’ or ‘linear’. Regular grid interpolation is typically more efficient for large grids, but may be less so for small grids with many trailing dimensions.

  • **kwargs (Any) – Additional arguments passed to the specific interpolation sub-function, named interp_<method>.

Returns:

Dataset where original spatial dimensions are replaced with a POI dimension containing interpolated values. The output POI dimension name can be overridden via GRID_PROCESS__data_model__poi__dim (e.g. station).

Return type:

xr.Dataset

See also

interp_temp(), interp_temp_fixgrad(), interp_nearest_alt(), interp_idw(), interp_upscaled(), interp_nearest(), interp_snowlim(), scipy.interpolate.griddata(), xarray.Dataset.interp()

Notes

  • Grid points containing only NaNs across all dimensions are excluded from interpolation, enabling easy masking (e.g., excluding water pixels with ds.where(ds.fr_land > 0.5).interp2poi(…, try_reg=False)).

  • For regular grid interpolation, all NaN grid points are kept.

  • Environment variables allow flexible support for custom grid and POI data models.

nn_lookup(grid_coords: numpy.ndarray, points: numpy.ndarray, k: int) → tuple[numpy.ndarray, numpy.ndarray][source]#

Find the k nearest grid points and corresponding distances for a set of POIs.

Parameters:
  • grid_coords (numpy.ndarray, shape (n, m)) – array of flattened grid coordinates. N is the number of model grid points, m the number of coordinates dimensions (i.e. 2 or 3)

  • points (numpy.ndarray, shape (p, m)) – array of POIs coordinates. P is the number of POIs, m the number of coordinates dimensions (i.e. 2 or 3)

  • k (positive int) – number of considered nearest neighbors

Returns:

  • dd (numpy.ndarray, shape (p, k)) – array of nearest neighbor distances.

  • ii (numpy.ndarray, shape (p, k)) – array of nearest neighbor grid indexes

nn_lookup_cached(grid_coords: numpy.ndarray, points: numpy.ndarray, k: int) → tuple[numpy.ndarray, numpy.ndarray][source]#

Wrapper to nn_lookup() function to use it with a cache

nn_lookup_regular(grid_coords: tuple[numpy.ndarray, numpy.ndarray], grid_spacing: tuple[float, float], points: tuple[numpy.ndarray | xarray.DataArray, numpy.ndarray | xarray.DataArray]) → list[numpy.ndarray | xarray.DataArray][source]#

Find the nearest grid point for a set of POIs when the source grid is regular and the spacing constant along each dimension.

Parameters:
  • grid_coords (tuple of m 1-D arrays) – contains flattened grid coordinates arrays for all m dimensions

  • grid_spacing (tuple of m floats) – contains the grid spacing for all m dimensions

  • points (tuple of m 1-D arrays (or xarray.DataArray with dim poi)) – contains POIs coordinates for all m dimensions. It assumes the same order of dimensions as in grid_coords

Returns:

index – Used to index the dataset in each spatial dimension. The output indexes have length equals to the number of points

Return type:

list of m 1-D arrays (or xarray DataArray with dimension poi)

interp2grid(data: xarray.Dataset, dst_grid: xarray.Dataset, method: InterpMethods, try_reg: bool = True, **kwargs: Any) → xarray.Dataset[source]#

Interpolates data from a source grid to a destination grid, supporting regular and unstructured grids.

This function provides a unified interface for grid-to-grid interpolation, supporting a variety of interpolation methods and data models. The output dataset contains the data of the source grid mapped onto the destination grid coordinates.

Parameters:
  • data (xarray.Dataset) –

    The source grid dataset. Supported data models include:

    Typical spatial dimension and coordinate names are supported, and can be extended via environment variables:

    • Y coordinate: export GRID_PROCESS__data_model__grid__y (e.g., ‘[“y”, “latitude”, “lat”, “dummy_y”]’)

    • X coordinate: export GRID_PROCESS__data_model__grid__x (e.g., ‘[“x”, “longitude”, “lon”, “dummy_x”]’)

    • Unstructured dimension: export GRID_PROCESS__data_model__grid__unstructured_dim (e.g., ‘[“dummy_cell”]’)

    • When the spatial coordinates variables have a CF compliant standard_name attribute, arbitrary names can be used directly.

    Spatial CRS must be referenced via one of:

    • Global attribute ‘crs’ (e.g., “EPSG:2056” or anything accepted by pyproj.CRS.from_user_input())

    • Global attribute ‘grid_mapping’ (internal grid database convention)

    • CF-convention grid mapping variable

    • If coordinates are named ‘latitude’/’longitude’ or ‘lat’/’lon’, WGS84 (EPSG:4326) is assumed.

    For methods requiring altitude, ensure a surface altitude coordinate is present; extend supported names via GRID_PROCESS__data_model__grid__surf_alt.

  • dst_grid (xarray.Dataset) – The destination grid to interpolate to. Same supported data models as the source grid, including conventions for dimensions and coordinates as well as spatial CRS. For methods requiring altitude, ensure a surface altitude coordinate is also present. The destination dataset may contain only spatial coordinates or also data variables which will be ignored.

  • method (str) –

    Interpolation method. Supported options include:

    {‘nearest’, ‘linear’, ‘cubic’, ‘idw’, ‘temp’, ‘temp_fixgrad’, ‘nearest_alt’, ‘snowlim’, ‘nearest_3D’, ‘linear_3D’, ‘idw_3D’, ‘upscaled’, ‘upscaled_3D’}.

    3D methods include altitude in neighbor selection. For unstructured grids, prefer ‘idw’ with k=4 and weight_power=2 over ‘linear’ for performence reasons.

  • try_reg (bool, default True) – If True, attempts regular grid interpolation for structured source grids with 1D coordinates when method is ‘nearest’ or ‘linear’. Regular grid interpolation is typically more efficient for large grids, but may be less so for small grids with many trailing dimensions.

  • **kwargs (Any) – Additional arguments passed to the specific interpolation sub-function, named interp_<method>.

Returns:

Dataset with values from data interpolated onto the coordinates of dst_grid.

Return type:

xr.Dataset

See also

interp_temp(), interp_temp_fixgrad(), interp_nearest_alt(), interp_idw(), interp_upscaled(), interp_nearest(), interp_snowlim(), scipy.interpolate.griddata(), xarray.Dataset.interp()

Notes

  • Not all interpolation methods scale efficiently with large input datasets or and/or destination grids.

  • Recommended methods: ‘nearest’, ‘linear’ (if the source grid is regular with 1D coordinates), ‘idw’ (with k=4), ‘temp_fixgrad’, ‘nearest_3D’, ‘nearest_alt’.

  • Environment variables allow flexible support for custom grid data models.

slice_boundingbox(data: xarray.Dataset, poi_info: geopandas.GeoDataFrame, method: str, spatial_dims: tuple[str, ...] | None = None, **kwargs: Any) → xarray.Dataset[source]#

Slice input dataset spatial dimensions to the bounding box of the target POIs plus a buffer depending on the interpolation method and corresponding kwargs.

slice_coarsen(data: xarray.Dataset, dst_grid: xarray.Dataset, method: str, spatial_dims: tuple[str, ...] | None = None, dst_spatial_dims: tuple[str, ...] | None = None, **kwargs: Any) → xarray.Dataset[source]#

Slice input dataset to the extend of the destination grid and coarsen it if the destination grid has lower resolution (downsampling).

HEIGHT_METHODS = ('temp', 'temp_fixgrad', 'snowlim', 'nearest_alt', 'idw_3D', 'nearest_3D', 'linear_3D', 'upscaled_3D')#
INTERP_FUNC#