Skip to content

Weights store

Remapping weights depend only on the source grid, the HEALPix target and the method, so grid-doctor computes them once and reuses them. Every weight file has one name, derived from what it describes, and lives in a weights store: a local (POSIX) directory. Callers only choose the store's root; everything below it is grid-doctor's layout.

Getting weights

cached_weights is the usual entry point. It returns a local weight file, looking it up in this order:

  1. the store,
  2. the local cache (weights computed while the store was read-only),
  3. otherwise the weights are computed into the store, or into the local cache when the store is read-only.
import grid_doctor as gd

weights_file = gd.cached_weights(ds, level=9)                    # default store
weights_file = gd.cached_weights(ds, level=9, store="/work/ab1234/weights")
pyramid = gd.create_healpix_pyramid(ds, max_level=9, weights_path=weights_file)

regrid_to_healpix and create_healpix_pyramid use the default store when no weights_path is given, so this is enough to compute the weights once and reuse them afterwards:

hp_ds = gd.regrid_to_healpix(ds)  # level derived from the grid resolution

The default store is the GRID_DOCTOR_WEIGHTS_STORE environment variable, or $XDG_CACHE_HOME/grid-doctor/weights (~/.cache/grid-doctor/weights) when it is unset. To compute into an explicit file instead, use compute_healpix_weights(weights_path=...).

Only these choices select a weight file: the source grid, the HEALPix level and the method. Options such as ignore_unmapped, large_file, nproc or prefer_offline change how weights are computed, not the weights themselves. With ignore_unmapped=False, a file found in the store is still checked: it fails if it leaves HEALPix cells unmapped.

Nested and ring order

Weight files are nested; their order is recorded in the grid_doctor_order attribute. Ring and nested weights differ only in how the HEALPix cells are numbered, so ring order is chosen when the weights are applied, and one file serves both:

ds_ring = gd.apply_weight_file(ds, weights_file, nest=False)
pyramid = gd.create_healpix_pyramid(ds, max_level=9, weights_path=weights_file, nest=False)

The target rows are then renumbered in memory (see nested_to_ring); no ESMF run and no second file are needed.

Sharing weights

Point several users or jobs at the same directory to share weights, e.g. GRID_DOCTOR_WEIGHTS_STORE=/work/ab1234/weights. Files are written atomically, so readers never see a partial file. A directory you cannot write to is used read-only: missing weights are computed into your local cache instead.

Only local directories and in-memory filesystems (memory://, for tests) are supported for now.

grid-doctor does not manage permissions: directories and weight files are created as the user's umask, or the directory's default ACL, allows. A store shared between users needs a default ACL on its root, set once by whoever administers it, e.g. for the group ab1234:

setfacl -m g:ab1234:rwx -d -m g:ab1234:rwx /work/ab1234/weights

Every directory and file created below the root then inherits it, whatever each user's umask. A PermissionError on a shared store therefore points at the store's setup, not at grid-doctor.

The same grid is recognised whatever its conventions: coordinates in radians or degrees, longitudes in 0..360 or [-180, 180) and differing variable names all lead to the same weight file.

Layout

Weight files are stored under Hive-style directories, followed by the digest of the source grid:

<root>/version=1/grid=healpix/ellipsoid=sphere/level=9/method=conservative/<digest>.nc
<root>/version=1/grid=healpix/ellipsoid=wgs84/level=9/method=conservative/<digest>.nc

Tools such as pyarrow, DuckDB or Polars read the directory names as columns. One grid has the same digest at every level and method, so WeightsStore.find lists all targets of a grid, or all grids of a target:

from grid_doctor.weights import WeightsStore

store = WeightsStore("/work/ab1234/weights")
store.find(level=9, method="conservative")

Each file also records its identity (source digest, level, indexing scheme, ellipsoid, method, grid-doctor and layout version), the ESMF version and the number of unmapped HEALPix cells as global attributes, so a store can be checked from the files alone.

Source digest

The file name is the SHA-256 digest of the source grid's geometry. It depends only on the cells and their order, so other tools can compute the same digest and share weight files with grid-doctor:

  1. Coordinates. Take the cell-centre latitude and longitude and, if present, the cell-vertex latitude and longitude, in degrees.
  2. Quantise. Round every value to integer micro-degrees, round(value * 1_000_000) (round half to even). Wrap longitudes into [-180_000_000, 180_000_000), so 180 and -180 are equal. Missing vertices (NaN) become -2**63.
  3. Dimensions. Number the dimensions by first appearance, in the order of step 4. A regular grid has lat on (0,) and lon on (1,). An unstructured grid has both on (0,), and its vertices on (0, 1).
  4. Hash. For centre latitude, centre longitude, vertex latitude and vertex longitude in that order, add dims=<dims>;shape=<shape>; (Python tuple notation, e.g. dims=(0, 1);shape=(2, 2);), followed by the integers as little-endian 64-bit values in C (row-major) order.

Variable names, dtypes, units (radians are converted first) and the longitude convention do not change the digest. Cell order does, because it defines the columns of the weight matrix. Vertex coordinates are hashed instead of a node/connectivity list (face_nodes): they describe the same cells and need no shared node numbering between tools.

API

cached_weights(ds, level=None, *, method='conservative', source_units='auto', store=None, ellipsoid=None, **kwargs)

Return a local HEALPix weight file, reusing it through a store.

Weights are identified by their WeightsDescription: the normalised source geometry, the HEALPix target and the method. The lookup is done by WeightsStore.fetch_or_compute.

Parameters:

Name Type Description Default
ds Dataset

Source dataset whose grid geometry defines the weights.

required
level int | None

HEALPix level. Derived from the grid resolution when omitted.

None
method RemapMethod

Weight-generation method. Supported values are "nearest" and "conservative".

'conservative'
source_units SourceUnits

Unit convention of the source coordinates.

'auto'
store WeightsStore | str | Path | None

Weights store, or its location (see WeightsStore). Defaults to grid_doctor.config.weights_store, else the local weights directory.

None
ellipsoid Ellipsoid | None

Ellipsoid of the HEALPix target, "sphere" or "WGS84". Defaults to grid_doctor.config.ellipsoid. Part of the weights' identity, so weights are never reused across ellipsoids.

None
**kwargs Unpack[WeightOptions]

Any additional keyword arguments for compute_healpix_weights

{}

Returns:

Type Description
Path

Path to the local NetCDF weight file.

Examples:

weight_file = cached_weights(ds, level=8, store="/work/ab1234/weights")
Source code in grid_doctor/weights.py
def cached_weights(
    ds: xr.Dataset,
    level: int | None = None,
    *,
    method: RemapMethod = "conservative",
    source_units: SourceUnits = "auto",
    store: WeightsStore | str | Path | None = None,
    ellipsoid: Ellipsoid | None = None,
    **kwargs: Unpack[WeightOptions],
) -> Path:
    """Return a local HEALPix weight file, reusing it through a store.

    Weights are identified by their
    [`WeightsDescription`][grid_doctor.weights.WeightsDescription]: the
    normalised source geometry, the HEALPix target and the method. The
    lookup is done by
    [`WeightsStore.fetch_or_compute`][grid_doctor.weights.WeightsStore.fetch_or_compute].

    Parameters
    ----------
    ds:
        Source dataset whose grid geometry defines the weights.
    level:
        HEALPix level. Derived from the grid resolution when omitted.
    method:
        Weight-generation method. Supported values are `"nearest"` and
        `"conservative"`.
    source_units:
        Unit convention of the source coordinates.
    store:
        Weights store, or its location (see
        [`WeightsStore`][grid_doctor.weights.WeightsStore]). Defaults to
        [`grid_doctor.config.weights_store`][grid_doctor.config.weights_store],
        else the local weights directory.
    ellipsoid:
        Ellipsoid of the HEALPix target, ``"sphere"`` or ``"WGS84"``.
        Defaults to ``grid_doctor.config.ellipsoid``.  Part of
        the weights' identity, so weights are never reused across ellipsoids.
    **kwargs:
        Any additional keyword arguments for
        [`compute_healpix_weights`][grid_doctor.remap.compute_healpix_weights]

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

    Examples
    --------
    ```python
    weight_file = cached_weights(ds, level=8, store="/work/ab1234/weights")
    ```
    """
    from .remap import compute_healpix_weights  # remap builds on this module

    ellipsoid = _ellipsoid_or_config(ellipsoid)
    if not isinstance(store, WeightsStore):
        store = WeightsStore(store)
    if level is None:
        level = resolution_to_healpix_level(get_latlon_resolution(ds))

    describe_kwargs = {k: kwargs[k] for k in ("grid", "source_kind", "spectral_transform_command") if k in kwargs}
    source = describe_source(ds, source_units=source_units, **describe_kwargs)  # type: ignore[arg-type]
    target = HealpixGrid(level=level, ellipsoid=ellipsoid)  # stored weights are nested
    desc = WeightsDescription(source, target, method)

    def compute(path: Path) -> Path:  # the store holds nested weights; ring is derived from them
        return compute_healpix_weights(
            ds,
            level,
            method=method,
            nest=True,
            source_units=source_units,
            weights_path=path,
            source_description=source,
            ellipsoid=ellipsoid,
            **kwargs,
        )

    path = store.fetch_or_compute(desc, compute)
    if kwargs.get("ignore_unmapped") is False:
        check_coverage(path)  # the stored weights may have been computed ignoring unmapped cells
    return path

WeightsStore(location=None, *, cache_dir=None, read_only=None)

Store of HEALPix weight files, laid out by WeightsRef.

Callers pass a root; everything below it is grid-doctor's layout. The root is a local (POSIX) directory, or an in-memory fsspec filesystem (memory://, mainly for tests). ESMF and the weight readers need local files, so files of in-memory stores are copied once into a local cache that mirrors the same layout.

Args: location: Root of the store: a local path, a file:// or memory:// URL, or an fsspec mapper of either. Defaults to grid_doctor.config.weights_store (environment variable GRID_DOCTOR_WEIGHTS_STORE), else $XDG_CACHE_HOME/grid-doctor/weights. cache_dir: Local directory for copies of in-memory weights and for weights computed while the store is read-only. Defaults to $XDG_CACHE_HOME/grid-doctor/weights. read_only: Forbid publish. When omitted, local stores are read-only if their directory is not writable.

Raises: ValueError: For filesystems other than local and in-memory ones.

Examples:

store = WeightsStore("/work/ab1234/weights")
if store.exists(desc):
    path = store.fetch(desc)

Source code in grid_doctor/weights.py
def __init__(  # noqa: D107
    self,
    location: str | Path | FSMap | None = None,
    *,
    cache_dir: str | Path | None = None,
    read_only: bool | None = None,
) -> None:
    from fsspec.core import url_to_fs
    from fsspec.mapping import FSMap

    if location is None:
        location = config.weights_store or local_weights_dir()
    fs: AbstractFileSystem
    if isinstance(location, FSMap):
        fs, root = location.fs, location.root
    elif isinstance(location, (str, os.PathLike)):
        fs, root = url_to_fs(str(location))
    else:
        raise TypeError(
            f"Unsupported weights store location {type(location).__name__!r}; "
            "expected a path, an fsspec URL or an fsspec mapper."
        )
    self.fs = fs
    self.root = str(root).rstrip("/")
    protocols = fs.protocol
    protocols = (protocols,) if isinstance(protocols, str) else tuple(protocols)
    if not _SUPPORTED_PROTOCOLS.intersection(protocols):
        raise ValueError(
            f"Unsupported weights store filesystem {protocols[0]!r}; "
            f"expected one of {sorted(_SUPPORTED_PROTOCOLS)}."
        )
    self.is_local = bool(_LOCAL_PROTOCOLS.intersection(protocols))
    self._protocol = protocols[0]
    if read_only is None:
        read_only = self.is_local and not _is_writable(Path(self.root))
    self.read_only = read_only
    self.cache_dir = Path(cache_dir) if cache_dir is not None else local_weights_dir()

url_root property

URL of the store root.

url(item)

Return the full URL (file:// or memory://) of a weight file.

Source code in grid_doctor/weights.py
def url(self, item: WeightsDescription | WeightsRef | str) -> str:
    """Return the full URL (``file://`` or ``memory://``) of a weight file."""
    return f"{self._protocol}://{self._path(item)}"

local_path(item)

Return where the local copy of a weight file lives.

The file itself for local stores, its place in the local cache for in-memory ones. The file need not exist.

Source code in grid_doctor/weights.py
def local_path(self, item: WeightsDescription | WeightsRef | str) -> Path:
    """Return where the local copy of a weight file lives.

    The file itself for local stores, its place in the local cache
    for in-memory ones. The file need not exist.
    """
    if self.is_local:
        return Path(self._path(item))
    return self.cache_dir / self._ref(item).path

exists(item)

Return whether the store holds the weight file.

Source code in grid_doctor/weights.py
def exists(self, item: WeightsDescription | WeightsRef | str) -> bool:
    """Return whether the store holds the weight file."""
    return bool(self.fs.exists(self._path(item)))

fetch(item)

Return a local path to the weight file, downloading it if needed.

Raises: FileNotFoundError: If the store does not hold the file.

Source code in grid_doctor/weights.py
def fetch(self, item: WeightsDescription | WeightsRef | str) -> Path:
    """Return a local path to the weight file, downloading it if needed.

    Raises:
        FileNotFoundError: If the store does not hold the file.
    """
    path = self._path(item)
    if self.is_local:
        if not self.fs.exists(path):
            raise FileNotFoundError(self.url(item))
        return Path(path)
    local = self.local_path(item)
    if local.exists():
        return local
    if not self.fs.exists(path):
        raise FileNotFoundError(self.url(item))
    logger.info("Copying weight file %s", self.url(item))
    _atomic_write(local, lambda tmp: self.fs.get_file(path, tmp))
    return local

publish(desc, local_file)

Store local_file as the weights of desc and return its reference.

Readers never see a partial file: local stores write a temporary file and rename it.

Raises: PermissionError: If the store is read-only.

Source code in grid_doctor/weights.py
def publish(self, desc: WeightsDescription, local_file: str | Path) -> WeightsRef:
    """Store *local_file* as the weights of *desc* and return its reference.

    Readers never see a partial file: local stores write a temporary
    file and rename it.

    Raises:
        PermissionError: If the store is read-only.
    """
    if self.read_only:
        raise PermissionError(f"{self!r} is read-only")
    ref = desc.ref
    path = self._path(ref)
    logger.info("Publishing weight file %s", self.url(ref))
    if self.is_local:
        _atomic_write(Path(path), lambda tmp: shutil.copyfile(local_file, tmp))
    else:
        self.fs.makedirs(path.rsplit("/", 1)[0], exist_ok=True)
        self.fs.put_file(str(local_file), path)
    return ref

fetch_or_compute(desc, compute)

Return a local copy of the weights of desc, computing them if needed.

Looks for the local copy, then the store; otherwise calls compute(path) and publishes the result to a writable in-memory store. Weights for a read-only store are computed into and kept in cache_dir only.

The store holds nested-order weights, so compute must write those, whatever the indexing scheme of desc.

Source code in grid_doctor/weights.py
def fetch_or_compute(self, desc: WeightsDescription, compute: Callable[[Path], Path]) -> Path:
    """Return a local copy of the weights of *desc*, computing them if needed.

    Looks for the local copy, then the store; otherwise calls
    ``compute(path)`` and publishes the result to a writable in-memory
    store. Weights for a read-only store are computed into and kept in
    ``cache_dir`` only.

    The store holds nested-order weights, so *compute* must write
    those, whatever the indexing scheme of *desc*.
    """
    local = self.local_path(desc)
    cached = self.cache_dir / desc.ref.path
    for path in dict.fromkeys((local, cached)):
        if path.exists():
            return path
    if self.exists(desc):
        return self.fetch(desc)
    target = local if (self.is_local and not self.read_only) else cached
    logger.info("Computing HEALPix weight file %s", target)
    target = compute(target)
    if not self.is_local and not self.read_only:
        self.publish(desc, target)
    return target

find(**filters)

List the weight files whose reference fields match filters.

Args: **filters: Field values of WeightsRef, e.g. level, method or key.

Raises: TypeError: For unknown filter names.

Examples:

store.find(level=10, method="conservative")

Source code in grid_doctor/weights.py
def find(self, **filters: Any) -> list[WeightsRef]:
    """List the weight files whose reference fields match *filters*.

    Args:
        **filters: Field values of [`WeightsRef`][grid_doctor.weights.WeightsRef],
            e.g. ``level``, ``method`` or ``key``.

    Raises:
        TypeError: For unknown filter names.

    Examples:
        ```python
        store.find(level=10, method="conservative")
        ```
    """
    fields = set(WeightsRef.__dataclass_fields__)
    unknown = set(filters) - fields
    if unknown:
        raise TypeError(f"Unknown filters: {sorted(unknown)}; expected {sorted(fields)}")
    filters = {k: v.lower() if isinstance(v, str) else v for k, v in filters.items()}
    dirs = (f"{name}={filters.get(name, '*')}" for name in WeightsRef.HIERARCHY)
    pattern = "/".join((*dirs, f"{filters.get('key', '*')}.nc"))
    found = []
    for path in sorted(self.fs.glob(f"{self.root}/{pattern}")):
        try:
            found.append(WeightsRef.parse(str(path).removeprefix(self.root)))
        except ValueError:
            continue
    return found

WeightsDescription(source, target, method) dataclass

Description of the weights of a remapping problem.

Two descriptions are equal when they describe the same source geometry (by digest), target and method.

Attributes: source: Source description. target: HEALPix target grid. method: Remapping method.

ref property

WeightsRef under which these weights are stored.

Weight files are nested; ring order is chosen when the weights are applied (see apply_weight_file), so both indexing schemes share one reference.

describe_source(source, *, grid=None, source_kind='auto', source_units='auto', spectral_transform_command=None, workdir=None)

Describe a source for HEALPix weight generation.

Normalises the source geometry and classifies the grid. The mesh and the weight-file metadata are built lazily, so describing a source to look its weights up does not mesh it.

Args: source: Source dataset or source path. A path is mainly useful for spectral inputs that need an external transform. grid: Optional grid dataset that supplies geometry when the data file itself only contains values on dimensions such as cell. source_kind: Explicit source representation. Use "auto" to infer it from the available coordinates. source_units: Angular unit convention of the source coordinates, used to normalise the geometry to degrees. spectral_transform_command: External command used when source_kind="spectral". The command may use {input} and {output} placeholders. workdir: Working directory for the spectral transform; a temporary directory when omitted.

Raises: ValueError: When the geometry cannot be normalised (see normalise_dataset). In particular, cell centres with NaN coordinates (masked grids) are rejected.

Source code in grid_doctor/weights.py
def describe_source(
    source: xr.Dataset | str | Path,
    *,
    grid: xr.Dataset | None = None,
    source_kind: SourceKind = "auto",
    source_units: SourceUnits = "auto",
    spectral_transform_command: list[str] | tuple[str, ...] | None = None,
    workdir: Path | None = None,
) -> SourceDescription:
    """Describe a source for HEALPix weight generation.

    Normalises the source geometry and classifies the grid. The mesh
    and the weight-file metadata are built lazily, so describing a
    source to look its weights up does not mesh it.

    Args:
        source: Source dataset or source path. A path is mainly
            useful for spectral inputs that need an external transform.
        grid: Optional grid dataset that supplies geometry when the
            data file itself only contains values on dimensions such
            as ``cell``.
        source_kind: Explicit source representation. Use ``"auto"``
            to infer it from the available coordinates.
        source_units: Angular unit convention of the source
            coordinates, used to normalise the geometry to degrees.
        spectral_transform_command: External command used when
            ``source_kind="spectral"``. The command may use
            ``{input}`` and ``{output}`` placeholders.
        workdir: Working directory for the spectral transform;
            a temporary directory when omitted.

    Raises:
        ValueError: When the geometry cannot be normalised (see
            ``normalise_dataset``). In particular, cell centres with
            NaN coordinates (masked grids) are rejected.
    """
    dataset = source if isinstance(source, xr.Dataset) else xr.load_dataset(source)
    kind = source_kind
    if kind == "spectral":
        with tempfile.TemporaryDirectory(prefix="grid_doctor_source_") as scratch:
            dataset = _materialise_spectral_source(  # loads eagerly, scratch can go
                source,
                transform_command=spectral_transform_command,
                workdir=workdir or Path(scratch),
            )
        kind = "auto"

    # Only the geometry source is normalised: grid if given, else dataset.
    geometry = normalise_dataset(grid if grid is not None else dataset, source_units)
    kind = _classify_source_kind(geometry, explicit_kind=kind)
    return SourceDescription(dataset=dataset, geometry=geometry, kind=kind)

SourceDescription(dataset, geometry, kind) dataclass

Resolved description of the source representation.

Built by describe_source and consumed by the weight-generation entry point and WeightsDescription.

Two descriptions are equal when their digest is, i.e. when they describe the same normalised geometry.

Attributes: dataset: Materialised gridpoint dataset used for weight generation. geometry: Normalised geometry dataset (degrees, longitudes in [-180, 180)) the mesh is built from. kind: Source representation class.

The source mesh and everything derived from it are built lazily on first access, so describing a source to look its weights up is cheap.

source_mesh property

Source mesh stored as compact node/connectivity arrays.

source_dims property

Source dimensions in flattening order.

looks_global cached property

Whether the source appears to cover the whole sphere (diagnostic only).

ignore_unmapped property

Recommended default for ESMF unmapped handling; always True.

The HEALPix target tiles the whole sphere, so a source that does not (masked, regional, polar gaps) leaves destination cells without overlap. They must become missing values rather than abort weight generation; callers can pass ignore_unmapped=False to require full coverage. A source that looks global yet leaves cells unmapped may point at a grid problem (see looks_global).

metadata cached property

Source attributes to persist into the weight file.

digest cached property

Hash (sha256 hex digest) of the normalised source geometry.

Independent of the target and the method, so one grid has one digest at every level, indexing scheme and method.

WeightsRef(method, level, key, grid=GRID_MAPPING_NAME, ellipsoid='sphere', version=WEIGHTS_VERSION) dataclass

Reference to a weight file, as a Hive-style relative path.

Lowercase throughout. One name=value directory per entry of HIERARCHY, followed by the source digest as file name::

version=1/grid=healpix/ellipsoid=sphere/level=10/method=conservative/<key>.nc

Every part that changes the weights is a directory, so the path is unique per weight file and the fields used for searching can be read from a listing without opening files. version is the version of the path scheme itself. Files hold nested-order weights; ring order is a renumbering of their rows when they are applied, so it needs no file of its own.

Attributes: method: Remapping method. level: HEALPix level. key: Source digest (sha256 hex digest); see SourceDescription.digest. grid: Target grid; always "healpix". ellipsoid: Ellipsoid of the HEALPix cell vertices, lowercased ("sphere" or "wgs84"). version: Version of the path scheme.

HIERARCHY = ('version', 'grid', 'ellipsoid', 'level', 'method') class-attribute

Directory levels, outermost first.

path property

Relative (store-root) path of the weight file.

__post_init__()

Lowercase every string field, so one set of weights has one path, and validate them.

Raises: ValueError: If a field cannot appear in a weight reference.

Source code in grid_doctor/weights.py
def __post_init__(self) -> None:
    """Lowercase every string field, so one set of weights has one path, and validate them.

    Raises:
        ValueError: If a field cannot appear in a weight reference.
    """
    for name in self.__dataclass_fields__:
        value = getattr(self, name)
        if isinstance(value, str):
            object.__setattr__(self, name, value.lower())
    valid = {
        "method": self.method in get_args(RemapMethod),
        "level": type(self.level) is int and 0 <= self.level <= MAX_LEVEL,
        "key": isinstance(self.key, str) and _SHA256_HEX.fullmatch(self.key) is not None,
        "grid": self.grid == GRID_MAPPING_NAME,
        "ellipsoid": self.ellipsoid in _REF_ELLIPSOIDS,
        "version": self.version == WEIGHTS_VERSION,
    }
    for name, ok in valid.items():
        if not ok:
            raise ValueError(f"Invalid weight reference {name}: {getattr(self, name)!r}")

parse(path) classmethod

Parse a relative weight file path, the inverse of path.

Raises: ValueError: If path does not follow the layout.

Source code in grid_doctor/weights.py
@classmethod
def parse(cls, path: str) -> WeightsRef:
    """Parse a relative weight file path, the inverse of [`path`][grid_doctor.weights.WeightsRef.path].

    Raises:
        ValueError: If *path* does not follow the layout.
    """
    *dirs, file = path.strip("/").split("/")
    pairs = [d.partition("=") for d in dirs]
    values = {name: value for name, _, value in pairs}
    if (
        tuple(name for name, _, _ in pairs) != cls.HIERARCHY
        or any(sep != "=" for _, sep, _ in pairs)
        or not (values["version"].isdigit() and values["level"].isdigit())
        or not file.endswith(".nc")
    ):
        raise ValueError(f"Not a weight reference: {path!r}")
    try:
        return cls(
            method=cast(RemapMethod, values["method"]),
            level=int(values["level"]),
            key=file.removesuffix(".nc"),
            grid=values["grid"],
            ellipsoid=values["ellipsoid"],
            version=int(values["version"]),
        )
    except ValueError as exc:
        raise ValueError(f"Not a weight reference: {path!r} ({exc})") from None

nested_to_ring(cells, level)

Return the ring-order numbers of nested HEALPix cells (0-based) at level.

Weight files are stored in nested order; their rows are renumbered with this when ring order is wanted, instead of computing the weights again.

Source code in grid_doctor/weights.py
def nested_to_ring(cells: npt.ArrayLike, level: int) -> npt.NDArray[np.int64]:
    """Return the ring-order numbers of nested HEALPix cells (0-based) at *level*.

    Weight files are stored in nested order; their rows are renumbered
    with this when ring order is wanted, instead of computing the weights
    again.
    """
    from healpix_geo.nested import to_ring

    return np.asarray(to_ring(np.asarray(cells, dtype=np.uint64), depth=level), dtype=np.int64)

ring_to_nested(cells, level)

Return the nested-order numbers of ring HEALPix cells (0-based) at level.

Source code in grid_doctor/weights.py
def ring_to_nested(cells: npt.ArrayLike, level: int) -> npt.NDArray[np.int64]:
    """Return the nested-order numbers of ring HEALPix cells (0-based) at *level*."""
    from healpix_geo.ring import to_nested

    return np.asarray(to_nested(np.asarray(cells, dtype=np.uint64), depth=level), dtype=np.int64)

local_weights_dir()

Local directory holding weight files in the WeightsRef layout.

$XDG_CACHE_HOME/grid-doctor/weights, where XDG_CACHE_HOME defaults to ~/.cache. Generated weights land here by default and remote WeightsStores download into it, so one set of weights has one local path.

Source code in grid_doctor/weights.py
def local_weights_dir() -> Path:
    """Local directory holding weight files in the [`WeightsRef`][grid_doctor.weights.WeightsRef] layout.

    ``$XDG_CACHE_HOME/grid-doctor/weights``, where ``XDG_CACHE_HOME``
    defaults to ``~/.cache``. Generated weights land here by default and
    remote [`WeightsStore`][grid_doctor.weights.WeightsStore]s download
    into it, so one set of weights has one local path.
    """
    cache_home = os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache"
    return Path(cache_home) / "grid-doctor" / "weights"

check_coverage(path)

Raise when weight file path leaves HEALPix target cells unmapped.

Repeats the check of ignore_unmapped=False for weights that were generated (and stored) with unmapped cells ignored. Files without the unmapped-cells attribute (older files) pass.

Raises: ValueError: If the file records unmapped target cells.

Source code in grid_doctor/weights.py
def check_coverage(path: str | Path) -> None:
    """Raise when weight file *path* leaves HEALPix target cells unmapped.

    Repeats the check of ``ignore_unmapped=False`` for weights that were
    generated (and stored) with unmapped cells ignored. Files without the
    unmapped-cells attribute (older files) pass.

    Raises:
        ValueError: If the file records unmapped target cells.
    """
    with xr.open_dataset(path) as ds:
        unmapped = int(ds.attrs.get(keys.UNMAPPED_CELLS_ATTR, 0))
    if unmapped:
        raise ValueError(
            f"{unmapped} HEALPix target cells of {path} are not covered by the source grid; "
            "pass ignore_unmapped=True to accept them as missing values."
        )