Skip to content

Metadata

Every attribute, coordinate name and grid mapping that grid-doctor stores is defined in grid_doctor.metadata. Code that produces data builds a HealpixMetadata and calls apply; code that reads data calls from_dataset. The stored layout follows the CF-1.13 healpix grid mapping; see Technical decisions for the full description.

from grid_doctor.metadata import HealpixGrid, HealpixMetadata, Provenance

meta = HealpixMetadata(HealpixGrid(level=8), Provenance(method="conservative"))
ds = meta.apply(ds)

HealpixMetadata.from_dataset(ds).grid.level  # 8

grid_doctor.metadata

Metadata of grid-doctor datasets, written and read in one place.

Every attribute, coordinate name and grid mapping grid-doctor stores is defined in this package. Code that produces data builds a HealpixMetadata and calls apply; code that reads data calls HealpixMetadata.from_dataset. Changing the stored layout therefore never touches the write sites.

  • _grid: HealpixGrid, the grid itself (level, indexing scheme, figure of the earth).
  • _provenance: Provenance, how the values were produced.
  • _cf: the CF-1.13 healpix grid mapping spelling of a grid.
  • _dataset: HealpixMetadata, which combines the above and applies it to a dataset.
  • _multiscales: PyramidMetadata, the layout of a pyramid stored as one datatree, spelled with the Zarr multiscales and dggs conventions.
  • _pyramid: attributes of such a datatree's root group.
  • _keys: every stored name.

The written layout is CF-1.13: a scalar crs grid mapping variable (grid_mapping_name = "healpix", indexing_scheme, refinement_level), an integer cell index coordinate with standard_name = "healpix_index", and grid_mapping = "crs" on every variable along cell. xdggs.decode(ds, convention="cf") reads it. Pyramids written as one datatree additionally describe their levels on the root group (see PyramidMetadata).

HealpixMetadata(grid, provenance=Provenance(), sparse=False, implicit_coords=False) dataclass

Everything grid-doctor records about a HEALPix dataset.

Write sites build one of these and call apply; readers call from_dataset. Neither ever touches attribute names, so the stored layout can change here without touching any code that produces or consumes data.

Parameters:

Name Type Description Default
grid HealpixGrid

The HEALPix grid.

required
provenance Provenance

How the values were produced.

Provenance()
sparse bool

The cell coordinate holds a subset of global cell indices (output of the select_* functions and of bin_to_healpix(..., dense=False)). Otherwise the dataset is dense: position along cell equals the cell index.

False
implicit_coords bool

A dense store written without cell/latitude/longitude arrays because they are implied by position (see save_pyramid(write_coords=...)). Such stores are not identifiable by CF's healpix_index standard name.

False

Examples:

>>> meta = HealpixMetadata(HealpixGrid(level=2), Provenance(method="nearest"))
>>> ds = meta.apply(ds)
>>> HealpixMetadata.from_dataset(ds).grid.level
2

__post_init__()

Reject contradictory layouts.

Source code in grid_doctor/metadata/_dataset.py
def __post_init__(self) -> None:
    """Reject contradictory layouts."""
    if self.sparse and self.implicit_coords:
        raise ValueError("A sparse dataset needs its `cell` coordinate; it cannot have implicit coordinates.")

replace(**changes)

Return a copy with changes applied (see dataclasses.replace).

Source code in grid_doctor/metadata/_dataset.py
def replace(self, **changes: object) -> HealpixMetadata:
    """Return a copy with *changes* applied (see ``dataclasses.replace``)."""
    return dataclasses.replace(self, **changes)  # type: ignore[arg-type]

apply(ds)

Return ds with all grid-doctor metadata written.

Writes

  • a scalar crs grid mapping coordinate (replacing any existing one),
  • CF attributes on the cell index coordinate and the latitude/longitude coordinates, where present,
  • grid_mapping = "crs" on every variable along cell,
  • the global Conventions, provenance and layout attributes.

Global attributes owned by grid-doctor are rewritten from this object, so stale values copied from an input dataset never survive. Coordinate values are left to the caller.

Raises:

Type Description
ValueError

When the cell dimension or coordinate contradicts the grid or the layout.

Source code in grid_doctor/metadata/_dataset.py
def apply(self, ds: xr.Dataset) -> xr.Dataset:
    """Return *ds* with all grid-doctor metadata written.

    Writes

    - a scalar ``crs`` grid mapping coordinate (replacing any
      existing one),
    - CF attributes on the ``cell`` index coordinate and the
      ``latitude``/``longitude`` coordinates, where present,
    - ``grid_mapping = "crs"`` on every variable along ``cell``,
    - the global ``Conventions``, provenance and layout attributes.

    Global attributes owned by grid-doctor are rewritten from this
    object, so stale values copied from an input dataset never
    survive.  Coordinate *values* are left to the caller.

    Raises
    ------
    ValueError
        When the ``cell`` dimension or coordinate contradicts the
        grid or the layout.
    """
    self._check_layout(ds)
    crs = xr.DataArray(np.float64(0.0), attrs=grid_mapping_attrs(self.grid))
    # A shallow copy owns its attribute dicts, so *ds* is left untouched.
    result = ds.copy(deep=False).drop_vars(CRS_VAR, errors="ignore")
    result = result.assign_coords({CRS_VAR: crs})

    coord_attrs = ((CELL_DIM, INDEX_ATTRS), (LAT_VAR, LAT_ATTRS), (LON_VAR, LON_ATTRS))
    for coord, attrs in coord_attrs:
        if coord in result.coords:
            result[coord].attrs.update(attrs)

    for var in result.data_vars.values():
        if CELL_DIM in var.dims:
            var.attrs["grid_mapping"] = CRS_VAR

    global_attrs: dict[Hashable, object] = {
        key: value for key, value in result.attrs.items() if key not in OWNED_GLOBAL_ATTRS
    }
    global_attrs["Conventions"] = merge_conventions(ds.attrs.get("Conventions"))
    global_attrs[METADATA_VERSION_ATTR] = METADATA_VERSION
    global_attrs.update(self.provenance.to_attrs())
    if self.sparse:
        global_attrs[SPARSE_ATTR] = 1
    if self.implicit_coords:
        global_attrs[IMPLICIT_COORDS_ATTR] = 1
    result.attrs = global_attrs
    return result

from_dataset(ds) classmethod

Read the metadata written by apply.

Only the CF grid mapping is required, so CF HEALPix datasets written by other tools (e.g. xdggs) are read as dense, with unknown provenance.

Raises:

Type Description
ValueError

When ds has no HEALPix grid mapping variable, or was written by a newer metadata layout than this grid-doctor understands.

Source code in grid_doctor/metadata/_dataset.py
@classmethod
def from_dataset(cls, ds: xr.Dataset) -> HealpixMetadata:
    """Read the metadata written by [`apply`][grid_doctor.metadata.HealpixMetadata.apply].

    Only the CF grid mapping is required, so CF HEALPix datasets
    written by other tools (e.g. ``xdggs``) are read as dense,
    with unknown provenance.

    Raises
    ------
    ValueError
        When *ds* has no HEALPix grid mapping variable, or was
        written by a newer metadata layout than this grid-doctor
        understands.
    """
    version = _int_attr(ds.attrs, METADATA_VERSION_ATTR)
    if version is not None and version > METADATA_VERSION:
        raise ValueError(
            f"Dataset uses metadata version {version}; this grid-doctor "
            f"understands up to {METADATA_VERSION}.  Upgrade grid-doctor."
        )
    return cls(
        grid=grid_from_mapping(_grid_mapping_attrs(ds)),
        provenance=Provenance.from_attrs(ds.attrs),
        sparse=_flag(ds.attrs, SPARSE_ATTR),
        implicit_coords=_flag(ds.attrs, IMPLICIT_COORDS_ATTR),
    )

HealpixGrid(level, indexing_scheme='nested', earth_radius=None, ellipsoid='sphere') dataclass

A HEALPix grid: refinement level, indexing scheme and figure of the earth.

Holds facts only; how they are spelled in a dataset is up to HealpixMetadata. Values are validated and normalised on construction, so a HealpixGrid is always a valid grid (NumPy integers from Zarr attributes are accepted and converted).

Parameters:

Name Type Description Default
level int

Refinement level (CF refinement_level), 0 to 29. nside = 2**level.

required
indexing_scheme IndexingScheme

"nested" (default) or "ring".

'nested'
earth_radius float | None

Radius of the spherical earth in metres, if it should be recorded. Only valid on a sphere.

None
ellipsoid Ellipsoid

Ellipsoid the cell geometry is computed on, as a healpix_geo name: "sphere" (default) or "WGS84". Grids whose metadata records no ellipsoid, such as those written before it was recorded, are spherical.

'sphere'

Examples:

>>> grid = HealpixGrid(level=3)
>>> grid.nside, grid.npix, grid.nest
(8, 768, True)

nside property

Number of cells along a base-cell side, 2**level.

npix property

Number of cells on the full sphere, 12 * nside**2.

nest property

True for nested indexing (healpy's nest flag).

__post_init__()

Validate and normalise the fields.

Source code in grid_doctor/metadata/_grid.py
def __post_init__(self) -> None:
    """Validate and normalise the fields."""
    object.__setattr__(self, "level", _as_level(self.level))
    scheme = str(self.indexing_scheme)
    if scheme not in INDEXING_SCHEMES:
        raise ValueError(
            f"indexing_scheme must be one of {sorted(INDEXING_SCHEMES)}, not {self.indexing_scheme!r}."
        )
    object.__setattr__(self, "indexing_scheme", scheme)
    object.__setattr__(self, "earth_radius", _as_radius(self.earth_radius))
    object.__setattr__(self, "ellipsoid", _as_ellipsoid(self.ellipsoid))
    if self.earth_radius is not None and self.ellipsoid != "sphere":
        raise ValueError(
            f"earth_radius describes a sphere and cannot be combined with ellipsoid={self.ellipsoid!r}."
        )

from_nest(level, *, nest, ellipsoid='sphere') classmethod

Build a grid from the healpy-style nest flag.

Source code in grid_doctor/metadata/_grid.py
@classmethod
def from_nest(cls, level: int, *, nest: bool, ellipsoid: Ellipsoid = "sphere") -> HealpixGrid:
    """Build a grid from the healpy-style ``nest`` flag."""
    return cls(level=level, indexing_scheme="nested" if nest else "ring", ellipsoid=ellipsoid)

Provenance(version=_package_version(), method=None, coarsened_from_level=None, coarsen_mode=None, min_valid_fraction=None) dataclass

Provenance attributes of a grid-doctor dataset.

Parameters:

Name Type Description Default
version str

grid-doctor version that produced the values. Defaults to the running version.

_package_version()
method str | None

How the finest values were produced: a remapping method ("conservative", "nearest", ...) or a binning method ("binned-mean", "binned-mode"). Drives coarsen_mode="auto".

None
coarsened_from_level int | None

Level the values were coarsened from (coarsened levels only).

None
coarsen_mode str | None

"mean" or "mode" (coarsened levels only).

None
min_valid_fraction float | None

Threshold below which coarsened cells were set to NaN (coarsened levels only).

None

to_attrs()

Return the provenance as global attributes, skipping unset fields.

Source code in grid_doctor/metadata/_provenance.py
def to_attrs(self) -> dict[str, str | int | float]:
    """Return the provenance as global attributes, skipping unset fields."""
    attrs: dict[str, str | int | float] = {VERSION_ATTR: self.version}
    if self.method is not None:
        attrs[METHOD_ATTR] = self.method
    if self.coarsened_from_level is not None:
        attrs[COARSENED_FROM_ATTR] = int(self.coarsened_from_level)
    if self.coarsen_mode is not None:
        attrs[COARSEN_MODE_ATTR] = self.coarsen_mode
    if self.min_valid_fraction is not None:
        attrs[MIN_VALID_FRACTION_ATTR] = float(self.min_valid_fraction)
    return attrs

from_attrs(attrs) classmethod

Read provenance from global attributes; missing fields stay unset.

A missing version is reported as "unknown" rather than the running version, which would misattribute foreign data.

Source code in grid_doctor/metadata/_provenance.py
@classmethod
def from_attrs(cls, attrs: Mapping[Hashable, object]) -> Provenance:
    """Read provenance from global attributes; missing fields stay unset.

    A missing version is reported as ``"unknown"`` rather than the
    running version, which would misattribute foreign data.
    """
    return cls(
        version=str(attrs.get(VERSION_ATTR, "unknown")),
        method=_optional_str(attrs.get(METHOD_ATTR)),
        coarsened_from_level=_optional_int(attrs.get(COARSENED_FROM_ATTR)),
        coarsen_mode=_optional_str(attrs.get(COARSEN_MODE_ATTR)),
        min_valid_fraction=_optional_float(attrs.get(MIN_VALID_FRACTION_ATTR)),
    )

PyramidMetadata(levels) dataclass

Layout of a HEALPix pyramid stored as one datatree.

Build it with from_pyramid and write to_attrs to the root group; read it back with from_attrs.

Parameters:

Name Type Description Default
levels tuple[PyramidLevel, ...]

The levels, finest first.

required

__post_init__()

Check that every derived_from points to a described level.

Source code in grid_doctor/metadata/_multiscales.py
def __post_init__(self) -> None:
    """Check that every ``derived_from`` points to a described level."""
    assets = {level.asset: level for level in self.levels}
    if len(assets) != len(self.levels):
        raise ValueError("Pyramid levels must have unique assets.")
    for level in self.levels:
        if level.derived_from is None:
            continue
        source = assets.get(level.derived_from)
        if source is None or source.grid is None or level.grid is None:
            raise ValueError(
                f"Level {level.asset!r} is derived from {level.derived_from!r}, "
                "which is not a HEALPix level of this pyramid."
            )
        if source.grid.level <= level.grid.level:
            raise ValueError(f"Level {level.asset!r} must be coarser than {level.derived_from!r}.")

from_pyramid(pyramid) classmethod

Describe pyramid ({level: dataset}) from its levels' metadata.

A level is derived from the level its provenance names in coarsened_from_level, when that level is part of the pyramid. Levels without HEALPix metadata are listed by path.

Source code in grid_doctor/metadata/_multiscales.py
@classmethod
def from_pyramid(cls, pyramid: Mapping[int, xr.Dataset]) -> PyramidMetadata:
    """Describe *pyramid* (``{level: dataset}``) from its levels' metadata.

    A level is derived from the level its provenance names in
    ``coarsened_from_level``, when that level is part of the
    pyramid.  Levels without HEALPix metadata are listed by path.
    """
    levels: list[PyramidLevel] = []
    for level in sorted(pyramid, reverse=True):
        ds = pyramid[level]
        asset = level_group(level)
        if not has_healpix_metadata(ds):
            levels.append(PyramidLevel(asset=asset, grid=None, coordinate=None))
            continue
        metadata = HealpixMetadata.from_dataset(ds)
        source = metadata.provenance.coarsened_from_level
        derived = source is not None and source != level and source in pyramid
        mode = metadata.provenance.coarsen_mode
        levels.append(
            PyramidLevel(
                asset=asset,
                grid=metadata.grid,
                coordinate=CELL_DIM if CELL_DIM in ds.variables else None,
                derived_from=(level_group(source) if derived and source is not None else None),
                resampling_method=(RESAMPLING_METHODS.get(mode, mode) if derived and mode else None),
            )
        )
    return cls(levels=tuple(levels))

to_attrs()

Return the zarr_conventions and multiscales attributes.

Source code in grid_doctor/metadata/_multiscales.py
def to_attrs(self) -> dict[str, object]:
    """Return the ``zarr_conventions`` and ``multiscales`` attributes."""
    assets = {level.asset: level for level in self.levels}
    methods = {level.resampling_method for level in self.levels if level.derived_from is not None}
    shared_method = methods.pop() if len(methods) == 1 else None

    layout: list[dict[str, object]] = []
    for level in self.levels:
        entry: dict[str, object] = {"asset": level.asset}
        if level.derived_from is not None and level.grid is not None:
            source = assets[level.derived_from]
            assert source.grid is not None  # checked in __post_init__
            entry["derived_from"] = level.derived_from
            entry["transform"] = {"scale": [float(2 ** (source.grid.level - level.grid.level))]}
            if level.resampling_method is not None and shared_method is None:
                entry["resampling_method"] = level.resampling_method
            entry["dggs"] = _changed_dggs(_dggs_object(source), _dggs_object(level))
        elif level.grid is not None:
            entry["dggs"] = _dggs_object(level)
        layout.append(entry)

    multiscales: dict[str, object] = {"layout": layout}
    if shared_method is not None:
        multiscales["resampling_method"] = shared_method
    conventions = [MULTISCALES_CONVENTION.to_dict()]
    if any(level.grid is not None for level in self.levels):
        conventions.append(DGGS_CONVENTION.to_dict())
    return {"zarr_conventions": conventions, "multiscales": multiscales}

from_attrs(attrs) classmethod

Read the layout written by to_attrs.

Raises:

Type Description
ValueError

When attrs have no multiscales layout or describe a grid other than HEALPix.

Source code in grid_doctor/metadata/_multiscales.py
@classmethod
def from_attrs(cls, attrs: Mapping[Hashable, object]) -> PyramidMetadata:
    """Read the layout written by [`to_attrs`][grid_doctor.metadata.PyramidMetadata.to_attrs].

    Raises
    ------
    ValueError
        When *attrs* have no ``multiscales`` layout or describe a
        grid other than HEALPix.
    """
    multiscales = attrs.get("multiscales")
    if not isinstance(multiscales, Mapping) or not isinstance(multiscales.get("layout"), list):
        raise ValueError("Attributes have no `multiscales` layout.")
    entries: dict[str, Mapping[str, object]] = {}
    for entry in multiscales["layout"]:
        if not isinstance(entry, Mapping) or not isinstance(entry.get("asset"), str):
            raise ValueError(f"Invalid multiscales layout entry: {entry!r}.")
        entries[entry["asset"]] = entry
    default_method = multiscales.get("resampling_method")

    resolved: dict[str, dict[str, object] | None] = {}

    def resolve(asset: str, seen: frozenset[str] = frozenset()) -> dict[str, object] | None:
        if asset in resolved:
            return resolved[asset]
        if asset in seen or asset not in entries:
            raise ValueError(f"Cannot resolve the dggs object of level {asset!r}.")
        entry = entries[asset]
        dggs = entry.get("dggs")
        source = entry.get("derived_from")
        if not isinstance(dggs, Mapping):
            result = None
        elif isinstance(source, str) and "name" not in dggs:
            base = resolve(source, seen | {asset})
            result = None if base is None else {**base, **dggs}
        else:
            result = dict(dggs)
        resolved[asset] = result
        return result

    levels = []
    for asset, entry in entries.items():
        dggs = resolve(asset)
        source = entry.get("derived_from")
        method = entry.get("resampling_method", default_method if source else None)
        levels.append(
            PyramidLevel(
                asset=asset,
                grid=None if dggs is None else _grid_from_dggs(dggs),
                coordinate=None if dggs is None else _optional_str(dggs.get("coordinate")),
                derived_from=source if isinstance(source, str) else None,
                resampling_method=_optional_str(method),
            )
        )
    return cls(levels=tuple(levels))

asset(level)

Return the group path that holds HEALPix level.

Source code in grid_doctor/metadata/_multiscales.py
def asset(self, level: int) -> str:
    """Return the group path that holds HEALPix *level*."""
    for entry in self.levels:
        if entry.grid is not None and entry.grid.level == level:
            return entry.asset
    raise KeyError(f"Pyramid has no level {level}.")

PyramidLevel(asset, grid, coordinate=CELL_DIM, derived_from=None, resampling_method=None) dataclass

One level of a multiscales pyramid.

Parameters:

Name Type Description Default
asset str

Path of the level's group, relative to the root.

required
grid HealpixGrid | None

The level's HEALPix grid, None for a level without HEALPix metadata (it is then listed by path only).

required
coordinate str | None

Name of the cell-index coordinate, None when the level covers the full sphere without one (implicit coordinates).

CELL_DIM
derived_from str | None

Asset the level was coarsened from, if any.

None
resampling_method str | None

How it was coarsened ("average", "mode", ...).

None

Helpers

has_healpix_metadata(ds)

Whether ds carries a HEALPix grid mapping variable.

Source code in grid_doctor/metadata/_dataset.py
def has_healpix_metadata(ds: xr.Dataset) -> bool:
    """Whether *ds* carries a HEALPix grid mapping variable."""
    return any(is_healpix_grid_mapping(var.attrs) for var in ds.variables.values())

variable_method(attrs)

Return the per-variable production method, if recorded.

Variables binned with different aggregations carry their own method next to the dataset-level one in Provenance.

Source code in grid_doctor/metadata/_provenance.py
def variable_method(attrs: Mapping[Hashable, object]) -> str | None:
    """Return the per-variable production method, if recorded.

    Variables binned with different aggregations carry their own method
    next to the dataset-level one in [`Provenance`][grid_doctor.metadata.Provenance].
    """
    return _optional_str(attrs.get(METHOD_ATTR))

variable_method_attrs(method)

Return the attributes recording a per-variable production method.

Source code in grid_doctor/metadata/_provenance.py
def variable_method_attrs(method: str) -> dict[str, str]:
    """Return the attributes recording a per-variable production method."""
    return {METHOD_ATTR: method}

grid_mapping_attrs(grid)

Return the attributes of the CF grid mapping variable for grid.

refinement_level is always written: CF requires it for the nested and ring schemes, including level 0.

Source code in grid_doctor/metadata/_cf.py
def grid_mapping_attrs(grid: HealpixGrid) -> dict[str, str | int | float]:
    """Return the attributes of the CF grid mapping variable for *grid*.

    ``refinement_level`` is always written: CF requires it for the
    ``nested`` and ``ring`` schemes, including level 0.
    """
    attrs: dict[str, str | int | float] = {
        "grid_mapping_name": GRID_MAPPING_NAME,
        "indexing_scheme": grid.indexing_scheme,
        "refinement_level": grid.level,
    }
    if grid.earth_radius is not None:
        attrs["earth_radius"] = grid.earth_radius
    if grid.ellipsoid == "WGS84":
        attrs["reference_ellipsoid_name"] = WGS84_CF_NAME
        attrs["semi_major_axis"] = WGS84_SEMI_MAJOR_AXIS
        attrs["inverse_flattening"] = WGS84_INVERSE_FLATTENING
    return attrs

merge_conventions(existing)

Merge the CF version into an existing Conventions attribute.

Any CF-x.y token is replaced by the version grid-doctor writes; other conventions (CMIP-6.2, ACDD-1.3, ...) are kept in order.

Source code in grid_doctor/metadata/_cf.py
def merge_conventions(existing: object) -> str:
    """Merge the CF version into an existing ``Conventions`` attribute.

    Any ``CF-x.y`` token is replaced by the version grid-doctor writes;
    other conventions (``CMIP-6.2``, ``ACDD-1.3``, ...) are kept in
    order.
    """
    tokens = str(existing).replace(",", " ").split() if existing else []
    kept = [token for token in tokens if not _CF_TOKEN.match(token)]
    return " ".join([CF_VERSION, *kept])

level_group(level)

Return the datatree group (multiscales asset) of level.

Source code in grid_doctor/metadata/_multiscales.py
def level_group(level: int) -> str:
    """Return the datatree group (``multiscales`` asset) of *level*."""
    return f"level_{int(level)}"

IndexingScheme = Literal['nested', 'ring'] module-attribute

HEALPix indexing schemes grid-doctor produces.

CF also defines nuniq and zuniq; grid-doctor does not write them, so they are rejected rather than half supported.