Skip to content

Mesh-to-Grid Interpolation#

Converts unstructured mesh data to regular grids using nearest-neighbor or linear interpolation. This module implements the bridge between UgridDataset and Dataset.

pyramids.netcdf.ugrid.interpolation.mesh_to_grid(mesh, data, location, cell_size, method='nearest', bounds=None, nodata=-9999.0, max_distance=None) #

Interpolate mesh data onto a regular grid.

This is the core bridge function. The result is a 2D numpy array and a GDAL-style geotransform that can be wrapped in a pyramids Dataset.

Parameters:

Name Type Description Default
mesh Mesh2d

Source mesh topology.

required
data ndarray

1D data array (n_faces, n_nodes, or n_edges).

required
location str

"face", "node", or "edge".

required
cell_size float

Target grid cell size in coordinate units.

required
method str

Interpolation method ("nearest" or "linear").

'nearest'
bounds tuple[float, float, float, float] | None

(xmin, ymin, xmax, ymax). Defaults to mesh bounds.

None
nodata float

Fill value for grid cells outside the mesh.

-9999.0
max_distance float | None

Maximum distance from a mesh element for a grid cell to receive a value. Defaults to 2 * cell_size.

None

Returns:

Type Description
ndarray

Tuple of (grid_array, geotransform) where grid_array is 2D

tuple[float, ...]

(rows, cols) and geotransform is a 6-element tuple

tuple[ndarray, tuple[float, ...]]

(x_origin, cell_size, 0, y_origin, 0, -cell_size).

Raises:

Type Description
ValueError

If location is unknown or edge coordinates are unavailable for edge-centered data.

Source code in src/pyramids/netcdf/ugrid/interpolation.py
def mesh_to_grid(
    mesh: Mesh2d,
    data: np.ndarray,
    location: str,
    cell_size: float,
    method: str = "nearest",
    bounds: tuple[float, float, float, float] | None = None,
    nodata: float = -9999.0,
    max_distance: float | None = None,
) -> tuple[np.ndarray, tuple[float, ...]]:
    """Interpolate mesh data onto a regular grid.

    This is the core bridge function. The result is a 2D numpy array
    and a GDAL-style geotransform that can be wrapped in a pyramids
    Dataset.

    Args:
        mesh: Source mesh topology.
        data: 1D data array (n_faces, n_nodes, or n_edges).
        location: "face", "node", or "edge".
        cell_size: Target grid cell size in coordinate units.
        method: Interpolation method ("nearest" or "linear").
        bounds: (xmin, ymin, xmax, ymax). Defaults to mesh bounds.
        nodata: Fill value for grid cells outside the mesh.
        max_distance: Maximum distance from a mesh element for a
            grid cell to receive a value. Defaults to 2 * cell_size.

    Returns:
        Tuple of (grid_array, geotransform) where grid_array is 2D
        (rows, cols) and geotransform is a 6-element tuple
        (x_origin, cell_size, 0, y_origin, 0, -cell_size).

    Raises:
        ValueError: If location is unknown or edge coordinates are
            unavailable for edge-centered data.
    """
    if bounds is None:
        bounds = mesh.bounds
    xmin, ymin, xmax, ymax = bounds

    if max_distance is None:
        max_distance = 2.0 * cell_size

    cols = int(np.ceil((xmax - xmin) / cell_size))
    rows = int(np.ceil((ymax - ymin) / cell_size))

    x_centers = xmin + (np.arange(cols) + 0.5) * cell_size
    y_centers = ymax - (np.arange(rows) + 0.5) * cell_size
    xx, yy = np.meshgrid(x_centers, y_centers)
    grid_points = np.column_stack([xx.ravel(), yy.ravel()])

    source_points, source_values = _get_source_data(mesh, data, location)

    if method == "nearest":
        grid_values = _interpolate_nearest(
            source_points, source_values, grid_points, nodata, max_distance
        )
    elif method == "linear":
        grid_values = _interpolate_linear(
            source_points, source_values, grid_points, nodata
        )
    else:
        raise ValueError(f"Unknown interpolation method: {method}")

    grid_array = grid_values.reshape(rows, cols)
    geotransform = (xmin, cell_size, 0.0, ymax, 0.0, -cell_size)

    result = (grid_array, geotransform)
    return result