Regridding Module

The nereus.regrid module provides tools for regridding unstructured mesh data to regular grids.

Interpolator

Regridding interpolator for unstructured to regular grid conversion.

This module provides the RegridInterpolator class for efficiently regridding unstructured data (like FESOM, ICON) to regular lat/lon grids.

class nereus.regrid.interpolator.RegridInterpolator(source_lon, source_lat, resolution=1.0, method='nearest', influence_radius=80000.0, lon_bounds=(-180.0, 180.0), lat_bounds=(-90.0, 90.0))[source]

Bases: object

Pre-computed interpolation for fast repeated regridding.

This class computes and stores interpolation weights for regridding unstructured data to a regular grid. The computation is done once during initialization, allowing fast repeated application.

Parameters:
  • source_lon (array_like) – Source grid longitude coordinates in degrees.

  • source_lat (array_like) – Source grid latitude coordinates in degrees.

  • resolution (float or tuple of int) – Target grid resolution. If float, specifies degrees per cell. If tuple (nlon, nlat), specifies number of grid points.

  • method ({"nearest", "idw", "linear", "cubic"}) – Interpolation method. “nearest” uses nearest-neighbor lookup via KDTree (fast). “idw” uses inverse distance weighting with 8 nearest neighbors (fast, smooth). “linear” uses Delaunay triangulation with barycentric interpolation (slower but smoother). “cubic” uses Clough-Tocher C1 interpolation for the smoothest results. Source longitudes are automatically normalized to match the target grid’s lon_bounds so that any input convention (0-360 or -180-180) works transparently.

  • influence_radius (float) – Maximum influence radius in meters. Points beyond this distance from any source point are masked. Default is 80 km.

  • lon_bounds (tuple of float) – Target grid longitude bounds. Default is (-180, 180).

  • lat_bounds (tuple of float) – Target grid latitude bounds. Default is (-90, 90).

target_lon

Target grid longitude coordinates (2D).

Type:

ndarray

target_lat

Target grid latitude coordinates (2D).

Type:

ndarray

indices

Source indices for each target point.

Type:

ndarray

distances

Distances from target to source points (in chord units).

Type:

ndarray

valid_mask

Boolean mask of valid target points within influence radius.

Type:

ndarray

Examples

>>> interpolator = RegridInterpolator(mesh_lon, mesh_lat, resolution=1.0)
>>> regridded = interpolator(data)
>>> regridded.shape
(180, 360)

Use linear interpolation for smoother results:

>>> interpolator = RegridInterpolator(
...     mesh_lon, mesh_lat, resolution=1.0, method="linear"
... )
source_lon: ndarray[tuple[Any, ...], dtype[floating]]
source_lat: ndarray[tuple[Any, ...], dtype[floating]]
resolution: float | tuple[int, int] = 1.0
method: Literal['nearest', 'idw', 'linear', 'cubic'] = 'nearest'
influence_radius: float = 80000.0
lon_bounds: tuple[float, float] = (-180.0, 180.0)
lat_bounds: tuple[float, float] = (-90.0, 90.0)
target_lon: ndarray[tuple[Any, ...], dtype[floating]]
target_lat: ndarray[tuple[Any, ...], dtype[floating]]
indices: ndarray[tuple[Any, ...], dtype[int64]]
distances: ndarray[tuple[Any, ...], dtype[floating]]
valid_mask: ndarray[tuple[Any, ...], dtype[bool]]
__post_init__()[source]

Initialize interpolation weights.

__call__(data, fill_value=nan)[source]

Apply interpolation to data.

Parameters:
  • data (array_like) – Data to interpolate. Can be: - 1D array of shape (npoints,) - 2D array of shape (nlevels, npoints) or (ntime, npoints) - ND array with last axis = npoints

  • fill_value (float) – Value for invalid points outside influence radius.

Returns:

Regridded data. Shape depends on input: - 1D input: (nlat, nlon) - 2D input: (extra_dim, nlat, nlon) - ND input: (*leading_dims, nlat, nlon)

Return type:

ndarray

property shape: tuple[int, int]

Shape of target grid (nlat, nlon).

__init__(source_lon, source_lat, resolution=1.0, method='nearest', influence_radius=80000.0, lon_bounds=(-180.0, 180.0), lat_bounds=(-90.0, 90.0))
nereus.regrid.interpolator.regrid(data, lon=None, lat=None, resolution=1.0, method='nearest', influence_radius=80000.0, fill_value=nan, lon_bounds=(-180.0, 180.0), lat_bounds=(-90.0, 90.0), as_xarray=False)[source]

Regrid unstructured data to regular grid.

This is a convenience function that creates a RegridInterpolator and applies it. For repeated regridding with the same source grid, create a RegridInterpolator once and reuse it.

Supports multi-dimensional data where the last axis contains the spatial points. For example:

  • 1D data (npoints,): single field

  • 2D data (nlevels, npoints): multi-level unstructured data (e.g., FESOM, ICON)

  • ND data (*dims, npoints): arbitrary leading dimensions

Coordinate arrays can be:

  • 1D arrays of same size: unstructured mesh coordinates (used directly)

  • 1D arrays of different sizes: regular grid side coordinates (meshgrid created)

  • 2D arrays of same shape: full coordinate arrays (raveled to 1D)

A warning is issued whenever coordinate transformations are applied.

If lon/lat are not provided and data is an xarray DataArray, the function will attempt to extract coordinates automatically by looking for common coordinate names (lon/lat, longitude/latitude, x/y, etc.).

Parameters:
  • data (array_like) – Data to interpolate. Last axis must be npoints (matching coordinates). Can be 1D (npoints,), 2D (nlevels, npoints), or ND (*dims, npoints). If xarray DataArray, coordinates may be extracted automatically.

  • lon (array_like, optional) – Source grid longitude coordinates. Can be 1D or 2D array. If None, will attempt to extract from data (xarray only).

  • lat (array_like, optional) – Source grid latitude coordinates. Can be 1D or 2D array. If None, will attempt to extract from data (xarray only).

  • resolution (float or tuple of int) – Target grid resolution.

  • method ({"nearest", "idw", "linear", "cubic"}) – Interpolation method. “nearest” uses nearest-neighbor lookup. “idw” uses inverse distance weighting (fast, smooth). “linear” uses Delaunay triangulation with barycentric interpolation. “cubic” uses Clough-Tocher C1 interpolation (smoothest).

  • influence_radius (float) – Maximum influence radius in meters.

  • fill_value (float) – Value for invalid points.

  • lon_bounds (tuple of float) – Target grid longitude bounds.

  • lat_bounds (tuple of float) – Target grid latitude bounds.

  • as_xarray (bool, default False) – If True, wrap the regridded array in an xr.DataArray with lat and lon as 1-D dimension coordinates. Leading dimensions (e.g. time, depth) and their coordinates are preserved when the input is an xr.DataArray. The return type of the tuple’s first element changes from NDArray to xr.DataArray.

Returns:

  • regridded (ndarray or xr.DataArray) – Regridded data. Returns xr.DataArray when as_xarray=True, otherwise ndarray.

  • interpolator (RegridInterpolator) – The interpolator used (can be reused for other variables).

Return type:

tuple[NDArray[np.floating], RegridInterpolator]

class nereus.regrid.interpolator.RegridInterpolator(source_lon, source_lat, resolution=1.0, method='nearest', influence_radius=80000.0, lon_bounds=(-180.0, 180.0), lat_bounds=(-90.0, 90.0))[source]

Bases: object

Pre-computed interpolation for fast repeated regridding.

This class computes and stores interpolation weights for regridding unstructured data to a regular grid. The computation is done once during initialization, allowing fast repeated application.

Parameters:
  • source_lon (array_like) – Source grid longitude coordinates in degrees.

  • source_lat (array_like) – Source grid latitude coordinates in degrees.

  • resolution (float or tuple of int) – Target grid resolution. If float, specifies degrees per cell. If tuple (nlon, nlat), specifies number of grid points.

  • method ({"nearest", "idw", "linear", "cubic"}) – Interpolation method. “nearest” uses nearest-neighbor lookup via KDTree (fast). “idw” uses inverse distance weighting with 8 nearest neighbors (fast, smooth). “linear” uses Delaunay triangulation with barycentric interpolation (slower but smoother). “cubic” uses Clough-Tocher C1 interpolation for the smoothest results. Source longitudes are automatically normalized to match the target grid’s lon_bounds so that any input convention (0-360 or -180-180) works transparently.

  • influence_radius (float) – Maximum influence radius in meters. Points beyond this distance from any source point are masked. Default is 80 km.

  • lon_bounds (tuple of float) – Target grid longitude bounds. Default is (-180, 180).

  • lat_bounds (tuple of float) – Target grid latitude bounds. Default is (-90, 90).

target_lon

Target grid longitude coordinates (2D).

Type:

ndarray

target_lat

Target grid latitude coordinates (2D).

Type:

ndarray

indices

Source indices for each target point.

Type:

ndarray

distances

Distances from target to source points (in chord units).

Type:

ndarray

valid_mask

Boolean mask of valid target points within influence radius.

Type:

ndarray

Examples

>>> interpolator = RegridInterpolator(mesh_lon, mesh_lat, resolution=1.0)
>>> regridded = interpolator(data)
>>> regridded.shape
(180, 360)

Use linear interpolation for smoother results:

>>> interpolator = RegridInterpolator(
...     mesh_lon, mesh_lat, resolution=1.0, method="linear"
... )

Attributes

source_lon: NDArray[np.floating]

Source grid longitude coordinates.

source_lat: NDArray[np.floating]

Source grid latitude coordinates.

resolution: float | tuple[int, int]

Target grid resolution (degrees or grid dimensions).

method: Literal['nearest', 'idw', 'linear', 'cubic']

Interpolation method. "nearest" uses KDTree nearest-neighbor lookup (fast). "idw" uses inverse distance weighting with 8 nearest neighbors (fast, smooth). "linear" uses Delaunay triangulation with barycentric interpolation (slower but smoother). "cubic" uses Clough-Tocher C1 interpolation (smoothest).

influence_radius: float

Maximum influence radius in meters.

lon_bounds: tuple[float, float]

Target grid longitude bounds.

lat_bounds: tuple[float, float]

Target grid latitude bounds.

target_lon: NDArray

2D array of target grid longitudes.

target_lat: NDArray

2D array of target grid latitudes.

indices: NDArray

Pre-computed source indices for each target point.

distances: NDArray

Pre-computed distances from target to source points.

valid_mask: NDArray

Boolean mask indicating valid target points.

source_lon: ndarray[tuple[Any, ...], dtype[floating]]
source_lat: ndarray[tuple[Any, ...], dtype[floating]]
resolution: float | tuple[int, int] = 1.0
method: Literal['nearest', 'idw', 'linear', 'cubic'] = 'nearest'
influence_radius: float = 80000.0
lon_bounds: tuple[float, float] = (-180.0, 180.0)
lat_bounds: tuple[float, float] = (-90.0, 90.0)
target_lon: ndarray[tuple[Any, ...], dtype[floating]]
target_lat: ndarray[tuple[Any, ...], dtype[floating]]
indices: ndarray[tuple[Any, ...], dtype[int64]]
distances: ndarray[tuple[Any, ...], dtype[floating]]
valid_mask: ndarray[tuple[Any, ...], dtype[bool]]
__post_init__()[source]

Initialize interpolation weights.

__call__(data, fill_value=nan)[source]

Apply interpolation to data.

Parameters:
  • data (array_like) – Data to interpolate. Can be: - 1D array of shape (npoints,) - 2D array of shape (nlevels, npoints) or (ntime, npoints) - ND array with last axis = npoints

  • fill_value (float) – Value for invalid points outside influence radius.

Returns:

Regridded data. Shape depends on input: - 1D input: (nlat, nlon) - 2D input: (extra_dim, nlat, nlon) - ND input: (*leading_dims, nlat, nlon)

Return type:

ndarray

property shape: tuple[int, int]

Shape of target grid (nlat, nlon).

__init__(source_lon, source_lat, resolution=1.0, method='nearest', influence_radius=80000.0, lon_bounds=(-180.0, 180.0), lat_bounds=(-90.0, 90.0))
nereus.regrid.interpolator.regrid(data, lon=None, lat=None, resolution=1.0, method='nearest', influence_radius=80000.0, fill_value=nan, lon_bounds=(-180.0, 180.0), lat_bounds=(-90.0, 90.0), as_xarray=False)[source]

Regrid unstructured data to regular grid.

This is a convenience function that creates a RegridInterpolator and applies it. For repeated regridding with the same source grid, create a RegridInterpolator once and reuse it.

Supports multi-dimensional data where the last axis contains the spatial points. For example:

  • 1D data (npoints,): single field

  • 2D data (nlevels, npoints): multi-level unstructured data (e.g., FESOM, ICON)

  • ND data (*dims, npoints): arbitrary leading dimensions

Coordinate arrays can be:

  • 1D arrays of same size: unstructured mesh coordinates (used directly)

  • 1D arrays of different sizes: regular grid side coordinates (meshgrid created)

  • 2D arrays of same shape: full coordinate arrays (raveled to 1D)

A warning is issued whenever coordinate transformations are applied.

If lon/lat are not provided and data is an xarray DataArray, the function will attempt to extract coordinates automatically by looking for common coordinate names (lon/lat, longitude/latitude, x/y, etc.).

Parameters:
  • data (array_like) – Data to interpolate. Last axis must be npoints (matching coordinates). Can be 1D (npoints,), 2D (nlevels, npoints), or ND (*dims, npoints). If xarray DataArray, coordinates may be extracted automatically.

  • lon (array_like, optional) – Source grid longitude coordinates. Can be 1D or 2D array. If None, will attempt to extract from data (xarray only).

  • lat (array_like, optional) – Source grid latitude coordinates. Can be 1D or 2D array. If None, will attempt to extract from data (xarray only).

  • resolution (float or tuple of int) – Target grid resolution.

  • method ({"nearest", "idw", "linear", "cubic"}) – Interpolation method. “nearest” uses nearest-neighbor lookup. “idw” uses inverse distance weighting (fast, smooth). “linear” uses Delaunay triangulation with barycentric interpolation. “cubic” uses Clough-Tocher C1 interpolation (smoothest).

  • influence_radius (float) – Maximum influence radius in meters.

  • fill_value (float) – Value for invalid points.

  • lon_bounds (tuple of float) – Target grid longitude bounds.

  • lat_bounds (tuple of float) – Target grid latitude bounds.

  • as_xarray (bool, default False) – If True, wrap the regridded array in an xr.DataArray with lat and lon as 1-D dimension coordinates. Leading dimensions (e.g. time, depth) and their coordinates are preserved when the input is an xr.DataArray. The return type of the tuple’s first element changes from NDArray to xr.DataArray.

Returns:

  • regridded (ndarray or xr.DataArray) – Regridded data. Returns xr.DataArray when as_xarray=True, otherwise ndarray.

  • interpolator (RegridInterpolator) – The interpolator used (can be reused for other variables).

Return type:

tuple[NDArray[np.floating], RegridInterpolator]

Cache

Caching for RegridInterpolator instances.

This module provides in-memory LRU caching with optional disk persistence for RegridInterpolator objects.

class nereus.regrid.cache.InterpolatorCache(max_memory_items=10, disk_path=None)[source]

Bases: object

In-memory LRU cache with optional disk persistence.

This cache stores RegridInterpolator instances keyed by a hash of their source coordinates and parameters. It uses LRU (Least Recently Used) eviction policy.

Parameters:
  • max_memory_items (int) – Maximum number of interpolators to keep in memory.

  • disk_path (str or Path, optional) – Directory for disk cache. If None, disk caching is disabled.

Examples

>>> cache = InterpolatorCache(max_memory_items=5)
>>> interp = cache.get_or_create(lon, lat, resolution=1.0)
>>> # Second call returns cached interpolator
>>> interp2 = cache.get_or_create(lon, lat, resolution=1.0)
>>> interp is interp2
True
__init__(max_memory_items=10, disk_path=None)[source]
get_or_create(source_lon, source_lat, **kwargs)[source]

Get cached interpolator or create new one.

Parameters:
  • source_lon (array_like) – Source grid longitude coordinates.

  • source_lat (array_like) – Source grid latitude coordinates.

  • **kwargs (Any) – Additional parameters passed to RegridInterpolator.

Returns:

Cached or newly created interpolator.

Return type:

RegridInterpolator

clear()[source]

Clear all cached interpolators.

__len__()[source]

Number of interpolators in memory cache.

nereus.regrid.cache.get_cache()[source]

Get the global interpolator cache.

Returns:

The global cache instance.

Return type:

InterpolatorCache

nereus.regrid.cache.set_cache_options(max_memory_items=10, disk_path=None)[source]

Configure the global interpolator cache.

Parameters:
  • max_memory_items (int) – Maximum number of interpolators to keep in memory.

  • disk_path (str or Path, optional) – Directory for disk cache. If None, disk caching is disabled.

nereus.regrid.cache.clear_cache()[source]

Clear the global interpolator cache.

class nereus.regrid.cache.InterpolatorCache(max_memory_items=10, disk_path=None)[source]

Bases: object

In-memory LRU cache with optional disk persistence.

This cache stores RegridInterpolator instances keyed by a hash of their source coordinates and parameters. It uses LRU (Least Recently Used) eviction policy.

Parameters:
  • max_memory_items (int) – Maximum number of interpolators to keep in memory.

  • disk_path (str or Path, optional) – Directory for disk cache. If None, disk caching is disabled.

Examples

>>> cache = InterpolatorCache(max_memory_items=5)
>>> interp = cache.get_or_create(lon, lat, resolution=1.0)
>>> # Second call returns cached interpolator
>>> interp2 = cache.get_or_create(lon, lat, resolution=1.0)
>>> interp is interp2
True

Methods

get_or_create(source_lon, source_lat, **kwargs)[source]

Get cached interpolator or create new one.

Parameters:
  • source_lon (array_like) – Source grid longitude coordinates.

  • source_lat (array_like) – Source grid latitude coordinates.

  • **kwargs (Any) – Additional parameters passed to RegridInterpolator.

Returns:

Cached or newly created interpolator.

Return type:

RegridInterpolator

clear()[source]

Clear all cached interpolators.

__init__(max_memory_items=10, disk_path=None)[source]
get_or_create(source_lon, source_lat, **kwargs)[source]

Get cached interpolator or create new one.

Parameters:
  • source_lon (array_like) – Source grid longitude coordinates.

  • source_lat (array_like) – Source grid latitude coordinates.

  • **kwargs (Any) – Additional parameters passed to RegridInterpolator.

Returns:

Cached or newly created interpolator.

Return type:

RegridInterpolator

clear()[source]

Clear all cached interpolators.

__len__()[source]

Number of interpolators in memory cache.

nereus.regrid.cache.get_cache()[source]

Get the global interpolator cache.

Returns:

The global cache instance.

Return type:

InterpolatorCache

nereus.regrid.cache.set_cache_options(max_memory_items=10, disk_path=None)[source]

Configure the global interpolator cache.

Parameters:
  • max_memory_items (int) – Maximum number of interpolators to keep in memory.

  • disk_path (str or Path, optional) – Directory for disk cache. If None, disk caching is disabled.

nereus.regrid.cache.clear_cache()[source]

Clear the global interpolator cache.