Skip to content

Remapping

Remap gridded data to HEALPix with ESMF weights (grid_doctor.remap). regrid_to_healpix does everything in one call: it takes the weights from the weights store, or computes them, and applies them. The other two functions split these steps.

Remapping

regrid_to_healpix(ds, level=None, *, nest=True, method='conservative', source_units='auto', weights_path=None, missing_policy='renormalize', backend='auto', grid=None, source_kind='auto', ignore_unmapped=None, large_file=True, prefer_offline=None, nproc=1, esmf_regrid_weightgen='ESMF_RegridWeightGen', keep_intermediates=False, workdir=None, spectral_transform_command=None, cell_chunks='auto', ellipsoid=None)

Regrid ds to a HEALPix target grid.

Parameters:

Name Type Description Default
ds Dataset

Source dataset on a regular, curvilinear, or unstructured grid.

required
level int | None

HEALPix refinement level. Derived from the grid resolution when omitted.

None
nest bool

Use nested HEALPix ordering when True.

True
method RemapMethod

"nearest" or "conservative".

'conservative'
source_units SourceUnits

Coordinate units for the source grid.

'auto'
weights_path str | Path | None

Optional existing or target weight file. When omitted, the weights come from the default WeightsStore (see cached_weights): computed once, then reused.

None
missing_policy MissingPolicy

How NaN values in the source grid are treated. "renormalize" (default) excludes NaN source cells and rescales the remaining weights so that a target cell is valid whenever at least one source cell contributes, which suits most continuous fields. "propagate" sets a target cell to NaN if any contributing source cell is NaN, which is useful for strict budget-closure checks but very aggressive along coastlines and data edges. See apply_weight_file for a detailed description.

'renormalize'
backend ApplyBackend

Application backend ("auto", "scipy", "numba").

'auto'
grid Dataset | None

Optional external geometry dataset.

None
source_kind SourceKind

Explicit source representation or "auto".

'auto'
ignore_unmapped bool | None

Ignore unmapped destination cells.

None
large_file bool

Forwarded to the in-memory ESMPy workflow.

True
prefer_offline bool | None

Force or disable the offline ESMF path.

None
nproc int

Number of MPI ranks for the offline path.

1
esmf_regrid_weightgen str

Name or path of the offline ESMF executable.

'ESMF_RegridWeightGen'
keep_intermediates bool

Keep intermediate mesh files.

False
workdir str | Path | None

Working directory for offline intermediate files.

None
spectral_transform_command list[str] | tuple[str, ...] | None

External command for source_kind="spectral".

None
cell_chunks int | Literal['auto'] | None

Output chunk size along cell for dask-backed input, see apply_weight_file. Coarser pyramid levels keep the same chunk size.

'auto'
ellipsoid Ellipsoid | None

Ellipsoid of the HEALPix geometry, "sphere" or "WGS84". New weights are generated on it, by default on grid_doctor.config.ellipsoid. An existing weights_path keeps the ellipsoid it was generated on; a different explicit value raises ValueError.

None

Returns:

Type Description
Dataset

Regridded dataset on the HEALPix grid.

Source code in grid_doctor/remap/_regrid.py
def regrid_to_healpix(
    ds: xr.Dataset,
    level: int | None = None,
    *,
    nest: bool = True,
    method: RemapMethod = "conservative",
    source_units: SourceUnits = "auto",
    weights_path: str | Path | None = None,
    missing_policy: MissingPolicy = "renormalize",
    backend: ApplyBackend = "auto",
    grid: xr.Dataset | None = None,
    source_kind: SourceKind = "auto",
    ignore_unmapped: bool | None = None,
    large_file: bool = True,
    prefer_offline: bool | None = None,
    nproc: int = 1,
    esmf_regrid_weightgen: str = "ESMF_RegridWeightGen",
    keep_intermediates: bool = False,
    workdir: str | Path | None = None,
    spectral_transform_command: list[str] | tuple[str, ...] | None = None,
    cell_chunks: int | Literal["auto"] | None = "auto",
    ellipsoid: Ellipsoid | None = None,
) -> xr.Dataset:
    """Regrid *ds* to a HEALPix target grid.

    Parameters
    ----------
    ds:
        Source dataset on a regular, curvilinear, or unstructured grid.
    level:
        HEALPix refinement level. Derived from the grid resolution when
        omitted.
    nest:
        Use nested HEALPix ordering when ``True``.
    method:
        ``"nearest"`` or ``"conservative"``.
    source_units:
        Coordinate units for the source grid.
    weights_path:
        Optional existing or target weight file. When omitted, the
        weights come from the default
        [`WeightsStore`][grid_doctor.weights.WeightsStore] (see
        [`cached_weights`][grid_doctor.weights.cached_weights]): computed
        once, then reused.
    missing_policy:
        How NaN values in the source grid are treated.
        ``"renormalize"`` (default) excludes NaN source cells and
        rescales the remaining weights so that a target cell is valid
        whenever at least one source cell contributes, which suits
        most continuous fields.  ``"propagate"`` sets a target
        cell to NaN if any contributing source cell is NaN, which is
        useful for strict budget-closure checks but very aggressive along
        coastlines and data edges.  See
        [`apply_weight_file`][grid_doctor.remap.apply_weight_file]
        for a detailed description.
    backend:
        Application backend (``"auto"``, ``"scipy"``, ``"numba"``).
    grid:
        Optional external geometry dataset.
    source_kind:
        Explicit source representation or ``"auto"``.
    ignore_unmapped:
        Ignore unmapped destination cells.
    large_file:
        Forwarded to the in-memory ESMPy workflow.
    prefer_offline:
        Force or disable the offline ESMF path.
    nproc:
        Number of MPI ranks for the offline path.
    esmf_regrid_weightgen:
        Name or path of the offline ESMF executable.
    keep_intermediates:
        Keep intermediate mesh files.
    workdir:
        Working directory for offline intermediate files.
    spectral_transform_command:
        External command for ``source_kind="spectral"``.
    cell_chunks:
        Output chunk size along ``cell`` for dask-backed input, see
        [`apply_weight_file`][grid_doctor.remap.apply_weight_file].
        Coarser pyramid levels keep the same chunk size.
    ellipsoid:
        Ellipsoid of the HEALPix geometry, ``"sphere"`` or ``"WGS84"``.
        New weights are generated on it, by default on
        ``grid_doctor.config.ellipsoid``.  An existing
        *weights_path* keeps the ellipsoid it was generated on; a
        different explicit value raises ``ValueError``.

    Returns
    -------
    xarray.Dataset
        Regridded dataset on the HEALPix grid.
    """
    options: WeightOptions = {
        "grid": grid,
        "source_kind": source_kind,
        "prefer_offline": prefer_offline,
        "nproc": nproc,
        "esmf_regrid_weightgen": esmf_regrid_weightgen,
        "keep_intermediates": keep_intermediates,
        "workdir": workdir,
        "spectral_transform_command": spectral_transform_command,
        "ignore_unmapped": ignore_unmapped,
        "large_file": large_file,
    }
    if weights_path is None:
        weight_file = cached_weights(
            ds, level, method=method, source_units=source_units, ellipsoid=ellipsoid, **options
        )
    else:
        weight_file = Path(weights_path)
        if not weight_file.exists():
            if level is None:
                level = resolution_to_healpix_level(get_latlon_resolution(ds))
            weight_file = compute_healpix_weights(
                ds,
                level,
                method=method,
                nest=nest,
                source_units=source_units,
                weights_path=weight_file,
                ellipsoid=ellipsoid,
                **options,
            )
    return apply_weight_file(
        ds,
        weight_file,
        missing_policy=missing_policy,
        backend=backend,
        cell_chunks=cell_chunks,
        ellipsoid=ellipsoid,
        nest=nest,
    )

Weight files

cached_weights returns the weights for a grid from the weights store. compute_healpix_weights writes them to a file of your choice.

compute_healpix_weights(ds, level, *, method='conservative', nest=True, source_units='auto', weights_path=None, grid=None, source_kind='auto', ignore_unmapped=None, large_file=True, prefer_offline=None, nproc=1, esmf_regrid_weightgen='ESMF_RegridWeightGen', keep_intermediates=False, workdir=None, spectral_transform_command=None, ellipsoid=None, source_description=None)

Generate a reusable NetCDF weight file for HEALPix remapping.

Parameters:

Name Type Description Default
ds Dataset | str | Path

Source dataset or a source path.

required
level int

HEALPix refinement level. nside = 2**level.

required
method RemapMethod

"nearest" or "conservative".

'conservative'
nest bool

Use nested HEALPix ordering when True.

True
source_units SourceUnits

Unit convention of the source coordinates.

'auto'
weights_path str | Path | None

Output NetCDF file. Defaults to the local weights directory in the WeightsRef layout (see local_weights_dir), so the same weights always land at the same path.

None
grid Dataset | None

Optional external geometry dataset.

None
source_kind SourceKind

Explicit source representation or "auto".

'auto'
ignore_unmapped bool | None

Ignore unmapped destination cells.

None
large_file bool

Forwarded to the in-memory ESMPy workflow.

True
prefer_offline bool | None

Force or disable the offline ESMF path.

None
nproc int

Number of MPI ranks for the offline path.

1
esmf_regrid_weightgen str

Name or path of the offline ESMF executable.

'ESMF_RegridWeightGen'
keep_intermediates bool

Keep intermediate mesh files.

False
workdir str | Path | None

Working directory for offline intermediate files.

None
spectral_transform_command list[str] | tuple[str, ...] | None

External command for source_kind="spectral".

None
ellipsoid Ellipsoid | None

Ellipsoid of the HEALPix geometry, "sphere" or "WGS84". Defaults to grid_doctor.config.ellipsoid.

None
source_description SourceDescription | None

Description of ds from describe_source, e.g. when the caller already built one to look the weights up; skips describing the source again.

None

Returns:

Type Description
Path

Path to the generated NetCDF weight file.

See Also

apply_weight_file: Apply a previously generated weight file.

Source code in grid_doctor/remap/_regrid.py
def compute_healpix_weights(
    ds: xr.Dataset | str | Path,
    level: int,
    *,
    method: RemapMethod = "conservative",
    nest: bool = True,
    source_units: SourceUnits = "auto",
    weights_path: str | Path | None = None,
    grid: xr.Dataset | None = None,
    source_kind: SourceKind = "auto",
    ignore_unmapped: bool | None = None,
    large_file: bool = True,
    prefer_offline: bool | None = None,
    nproc: int = 1,
    esmf_regrid_weightgen: str = "ESMF_RegridWeightGen",
    keep_intermediates: bool = False,
    workdir: str | Path | None = None,
    spectral_transform_command: list[str] | tuple[str, ...] | None = None,
    ellipsoid: Ellipsoid | None = None,
    source_description: SourceDescription | None = None,
) -> Path:
    """Generate a reusable NetCDF weight file for HEALPix remapping.

    Parameters
    ----------
    ds:
        Source dataset or a source path.
    level:
        HEALPix refinement level.  ``nside = 2**level``.
    method:
        ``"nearest"`` or ``"conservative"``.
    nest:
        Use nested HEALPix ordering when `True`.
    source_units:
        Unit convention of the source coordinates.
    weights_path:
        Output NetCDF file. Defaults to the local weights directory in the
        [`WeightsRef`][grid_doctor.weights.WeightsRef] layout (see
        [`local_weights_dir`][grid_doctor.weights.local_weights_dir]), so
        the same weights always land at the same path.
    grid:
        Optional external geometry dataset.
    source_kind:
        Explicit source representation or ``"auto"``.
    ignore_unmapped:
        Ignore unmapped destination cells.
    large_file:
        Forwarded to the in-memory ESMPy workflow.
    prefer_offline:
        Force or disable the offline ESMF path.
    nproc:
        Number of MPI ranks for the offline path.
    esmf_regrid_weightgen:
        Name or path of the offline ESMF executable.
    keep_intermediates:
        Keep intermediate mesh files.
    workdir:
        Working directory for offline intermediate files.
    spectral_transform_command:
        External command for ``source_kind="spectral"``.
    ellipsoid:
        Ellipsoid of the HEALPix geometry, ``"sphere"`` or
        ``"WGS84"``.  Defaults to ``grid_doctor.config.ellipsoid``.
    source_description:
        Description of *ds* from
        [`describe_source`][grid_doctor.weights.describe_source],
        e.g. when the caller already built one to look the weights up;
        skips describing the source again.

    Returns
    -------
    pathlib.Path
        Path to the generated NetCDF weight file.

    See Also
    --------
    [`apply_weight_file`][grid_doctor.remap.apply_weight_file]:
        Apply a previously generated weight file.
    """
    offline = OfflineWeightConfig(
        enabled=bool(prefer_offline) if prefer_offline is not None else False,
        nproc=nproc,
        esmf_regrid_weightgen=esmf_regrid_weightgen,
        keep_intermediates=keep_intermediates,
        workdir=Path(workdir) if workdir is not None else None,
    )
    return compute_healpix_weights_backend(
        ds,
        level,
        method=method,
        nest=nest,
        source_units=source_units,
        weights_path=weights_path,
        grid=grid,
        source_kind=source_kind,
        ignore_unmapped=ignore_unmapped,
        large_file=large_file,
        offline=offline,
        spectral_transform_command=spectral_transform_command,
        ellipsoid=_ellipsoid_or_config(ellipsoid),
        source_description=source_description,
    )

Applying weights

apply_weight_file(ds, weights_path, *, missing_policy='renormalize', grid=None, source_dims=None, source_units='auto', backend='auto', cell_chunks='auto', ellipsoid=None, nest=None)

Apply a previously generated ESMF weight file to ds.

Uses the batched engine in grid_doctor.remap._sparse which replaces per-slice vectorize=True with a single batched sparse matmul for a typical 10–50× speedup.

Parameters:

Name Type Description Default
ds Dataset

Source dataset to remap.

required
weights_path str | Path

Path to the NetCDF weight file.

required
missing_policy MissingPolicy

Strategy for handling NaN (missing) values in the source grid during weight application.

"renormalize" (default) Source cells that are NaN are excluded from the weighted sum and the weights of the remaining valid source cells are rescaled so they sum to 1. A target cell receives a valid value as long as at least one contributing source cell is valid. This is the right choice for most climate fields: for instance, a HEALPix cell on a coastline that partly overlaps land (NaN) and partly ocean still receives a valid SST from the ocean fraction.

"propagate" If any contributing source cell is NaN, the target cell is set to NaN: no partial averages. Use this when completeness of the source coverage matters more than spatial coverage of the output, for example when computing area-integrated flux budgets where a partial average would bias the integral. Note that this is very aggressive: a single NaN source cell at the edge of a target cell's footprint is enough to discard it. For conservative remapping where a HEALPix cell can overlap dozens of source cells, large portions of the output along coastlines, swath edges, and orbit gaps will be NaN.

'renormalize'
grid Dataset | None

Optional grid dataset with source geometry.

None
source_dims tuple[str, ...] | None

Optional explicit source dimensions.

None
source_units SourceUnits

Unit convention for geometry-based inference.

'auto'
backend ApplyBackend

Application backend ("auto", "scipy", "numba").

'auto'
cell_chunks int | Literal['auto'] | None

Chunk size of the output along cell for dask-backed input. Each output chunk is computed from its own slice of weight-matrix rows, so no task holds the whole HEALPix field. "auto" uses DEFAULT_CELL_CHUNK cells (rounded to a multiple of 4), None produces a single chunk. NumPy-backed input is always computed in one piece.

'auto'
ellipsoid Ellipsoid | None

Ellipsoid the weights must have been generated on. None (default) takes the one recorded in the weight file (a sphere for files that record none); the HEALPix cell centres are computed on it.

None
nest bool | None

HEALPix order of the output: nested when True, ring when False. None (default) keeps the order of the weight file. Stored weight files are nested; their rows are renumbered for ring output, so one file serves both orders.

None

Returns:

Type Description
Dataset

Dataset on the HEALPix target grid with a cell dimension.

Examples:

ds_hp = apply_weight_file(ds_icon, "icon_to_healpix_d8.nc")
Source code in grid_doctor/remap/_apply.py
def apply_weight_file(
    ds: xr.Dataset,
    weights_path: str | Path,
    *,
    missing_policy: MissingPolicy = "renormalize",
    grid: xr.Dataset | None = None,
    source_dims: tuple[str, ...] | None = None,
    source_units: SourceUnits = "auto",
    backend: ApplyBackend = "auto",
    cell_chunks: int | Literal["auto"] | None = "auto",
    ellipsoid: Ellipsoid | None = None,
    nest: bool | None = None,
) -> xr.Dataset:
    """Apply a previously generated ESMF weight file to *ds*.

    Uses the batched engine in
    `grid_doctor.remap._sparse` which replaces per-slice
    ``vectorize=True`` with a single batched sparse matmul for a
    typical 10–50× speedup.

    Parameters
    ----------
    ds:
        Source dataset to remap.
    weights_path:
        Path to the NetCDF weight file.
    missing_policy:
        Strategy for handling NaN (missing) values in the source
        grid during weight application.

        ``"renormalize"`` (default)
            Source cells that are NaN are excluded from the
            weighted sum and the weights of the remaining valid
            source cells are rescaled so they sum to 1.  A target
            cell receives a valid value as long as **at least one**
            contributing source cell is valid.  This is the right
            choice for most climate fields: for instance, a
            HEALPix cell on a coastline that partly overlaps land
            (NaN) and partly ocean still receives a valid SST from
            the ocean fraction.

        ``"propagate"``
            If **any** contributing source cell is NaN, the target
            cell is set to NaN: no partial averages.  Use this
            when completeness of the source coverage matters more
            than spatial coverage of the output, for example when
            computing area-integrated flux budgets where a partial
            average would bias the integral.  Note that this is
            very aggressive: a single NaN source cell at the edge
            of a target cell's footprint is enough to discard it.
            For conservative remapping where a HEALPix cell can
            overlap dozens of source cells, large portions of the
            output along coastlines, swath edges, and orbit gaps
            will be NaN.
    grid:
        Optional grid dataset with source geometry.
    source_dims:
        Optional explicit source dimensions.
    source_units:
        Unit convention for geometry-based inference.
    backend:
        Application backend (``"auto"``, ``"scipy"``, ``"numba"``).

    cell_chunks:
        Chunk size of the output along ``cell`` for dask-backed input.
        Each output chunk is computed from its own slice of weight-matrix
        rows, so no task holds the whole HEALPix field.  ``"auto"`` uses
        ``DEFAULT_CELL_CHUNK`` cells (rounded to a multiple of 4), ``None``
        produces a single chunk.  NumPy-backed input is always computed
        in one piece.
    ellipsoid:
        Ellipsoid the weights must have been generated on.  ``None``
        (default) takes the one recorded in the weight file (a sphere
        for files that record none); the HEALPix cell centres are
        computed on it.
    nest:
        HEALPix order of the output: nested when ``True``, ring when
        ``False``. ``None`` (default) keeps the order of the weight file.
        Stored weight files are nested; their rows are renumbered for
        ring output, so one file serves both orders.

    Returns
    -------
    xarray.Dataset
        Dataset on the HEALPix target grid with a ``cell`` dimension.

    Examples
    --------
    ```python
    ds_hp = apply_weight_file(ds_icon, "icon_to_healpix_d8.nc")
    ```
    """
    if missing_policy not in {"renormalize", "propagate"}:
        raise ValueError("missing_policy must be 'renormalize' or 'propagate'.")

    matrix, n_target, n_source, level, order, method, stored_sd, stored_ellipsoid = _read_weight_file(
        weights_path, nest=nest
    )
    # Checked before regridding, so a mismatch fails fast.
    ellipsoid = _weights_ellipsoid(ellipsoid, stored_ellipsoid, weights_path)

    resolved_sd = _resolve_source_dims_for_weight_application(
        ds,
        n_source=n_source,
        grid=grid,
        source_dims=source_dims,
        source_units=source_units,
        stored_source_dims=stored_sd,
    )
    n_src_dims = len(resolved_sd)
    cell_chunk = _resolve_cell_chunk(cell_chunks, n_target)
    row_blocks: list[csr_matrix] | None = None

    regridded: dict[str, xr.DataArray] = {}
    for name, data in ds.data_vars.items():
        if not set(resolved_sd).issubset(map(str, data.dims)):
            regridded[str(name)] = data
            continue

        if cell_chunk is not None and data.chunks is not None:
            if row_blocks is None:
                row_blocks = _row_blocks(matrix, cell_chunk)
            regridded[str(name)] = _apply_weights_rowblocked(
                data,
                resolved_sd,
                row_blocks,
                missing_policy=missing_policy,
                backend=backend,
                parallel=False,
            )
            continue

        regridded[str(name)] = cast(
            xr.DataArray,
            xr.apply_ufunc(
                apply_weights_nd,
                data,
                input_core_dims=[list(resolved_sd)],
                output_core_dims=[["cell"]],
                exclude_dims=set(resolved_sd),
                dask="parallelized",
                kwargs={
                    "matrix": matrix,
                    "n_source_dims": n_src_dims,
                    "missing_policy": missing_policy,
                    "backend": backend,
                    # dask already runs tasks in parallel threads; nested
                    # thread teams exhaust the process thread limit.
                    "parallel": data.chunks is None,
                },
                output_dtypes=[np.float64],
                dask_gufunc_kwargs={"output_sizes": {"cell": n_target}},
            ),
        )

    result = xr.Dataset(regridded, attrs=ds.attrs.copy())
    if level >= 0:
        target_grid = HealpixGrid.from_nest(
            level,
            nest=(order == "nested"),
            ellipsoid=ellipsoid,
        )
        result = _attach_healpix_coords(result, target_grid, method=method)
    return result