Skip to content

Config round-trips — geopatcher.config

Every axis, stencil and patcher exposes get_config(). Nested components serialise as {"class": ..., "config": ...} envelopes whose "class" is the component's public path — "spatial.window.Hann", "temporal.aggregation.Mean", "SpatialPatcher" (a user-defined axis records its module.qualname). from_config(axis_envelope(obj)) rebuilds obj, unless its type is forbid_in_yaml (closures, polygons, backend-native anchors), whose config is a debug summary from_config refuses.

import json

from geopatcher import spatial
from geopatcher.config import axis_envelope, from_config

window = spatial.window.Tukey(alpha=0.25)
saved = json.dumps(axis_envelope(window))      # '{"class": "spatial.window.Tukey", ...}'
assert from_config(json.loads(saved)).get_config() == window.get_config()

geopatcher.config.axis_envelope(obj)

Wrap one component as {"class": <config_name>, "config": <get_config()>}.

Parameters:

Name Type Description Default
obj Any

An axis, stencil or patcher instance exposing get_config().

required

Returns:

Type Description
dict[str, Any]

The class-name + config envelope used by every nested config.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/_serialize.py
def axis_envelope(obj: Any) -> dict[str, Any]:
    """Wrap one component as ``{"class": <config_name>, "config": <get_config()>}``.

    Args:
        obj: An axis, stencil or patcher instance exposing ``get_config()``.

    Returns:
        The class-name + config envelope used by every nested config.
    """
    return {"class": config_name(type(obj)), "config": obj.get_config()}

geopatcher.config.from_config(envelope)

Rebuild an axis, stencil or patcher from its axis_envelope.

Nested envelopes (the axes inside a patcher, the stencil inside a stencil axis, the per-source aggregators of a matched patcher) are rebuilt recursively. The class is looked up by name among the loaded geopatcher component classes and their subclasses.

Parameters:

Name Type Description Default
envelope Mapping[str, Any]

{"class": <name>, "config": <get_config()>} — e.g. axis_envelope(obj) after a JSON / YAML round-trip.

required

Returns:

Type Description
Any

A new instance equivalent to the one the envelope was taken from.

Raises:

Type Description
TypeError

if the envelope is malformed or names an unknown or ambiguous class.

RuntimeError

if the class is marked forbid_in_yaml.

Examples:

>>> geom = spatial.geometry.Rectangular(size=(64, 64), boundary="pad")
>>> from_config(axis_envelope(geom)).get_config() == geom.get_config()
True
>>> stencil = TimeStencil("-9h", "3h", "1h", closed="both")
>>> from_config(json.loads(json.dumps(axis_envelope(stencil)))) == stencil
True
>>> from_config({"class": "spatial.window.Custom", "config": {}})
Traceback (most recent call last):
RuntimeError: from_config cannot rebuild spatial.window.Custom: ...
Source code in packages/geotoolz-patcher/src/geopatcher/_src/_serialize.py
def from_config(envelope: Mapping[str, Any]) -> Any:
    """Rebuild an axis, stencil or patcher from its `axis_envelope`.

    Nested envelopes (the axes inside a patcher, the stencil inside a
    stencil axis, the per-source aggregators of a matched patcher) are
    rebuilt recursively. The class is looked up by name among the loaded
    geopatcher component classes and their subclasses.

    Args:
        envelope: ``{"class": <name>, "config": <get_config()>}`` — e.g.
            ``axis_envelope(obj)`` after a JSON / YAML round-trip.

    Returns:
        A new instance equivalent to the one the envelope was taken from.

    Raises:
        TypeError: if the envelope is malformed or names an unknown or
            ambiguous class.
        RuntimeError: if the class is marked ``forbid_in_yaml``.

    Examples:
        >>> geom = spatial.geometry.Rectangular(size=(64, 64), boundary="pad")
        >>> from_config(axis_envelope(geom)).get_config() == geom.get_config()
        True
        >>> stencil = TimeStencil("-9h", "3h", "1h", closed="both")
        >>> from_config(json.loads(json.dumps(axis_envelope(stencil)))) == stencil
        True
        >>> from_config({"class": "spatial.window.Custom", "config": {}})
        Traceback (most recent call last):
        RuntimeError: from_config cannot rebuild spatial.window.Custom: ...
    """
    if not _is_envelope(envelope):
        raise TypeError(
            "from_config expects a {'class': <name>, 'config': {...}} envelope, "
            f"got {envelope!r}."
        )
    return _build(envelope, _registry())

geopatcher.config.config_name(cls)

The name an envelope records for cls.

geopatcher's own classes are named by their public path, relative to the package ("spatial.window.Hann", "temporal.aggregation.Mean", "SpatialPatcher"); any other class — a user-defined axis — by its module.qualname.

Examples:

>>> from geopatcher import spatial
>>> config_name(spatial.window.Hann)
'spatial.window.Hann'
Source code in packages/geotoolz-patcher/src/geopatcher/_src/_serialize.py
def config_name(cls: type) -> str:
    """The name an envelope records for ``cls``.

    geopatcher's own classes are named by their public path, relative to
    the package (``"spatial.window.Hann"``, ``"temporal.aggregation.Mean"``,
    ``"SpatialPatcher"``); any other class — a user-defined axis — by its
    ``module.qualname``.

    Examples:
        >>> from geopatcher import spatial
        >>> config_name(spatial.window.Hann)
        'spatial.window.Hann'
    """
    return _public_paths().get(cls) or f"{cls.__module__}.{cls.__qualname__}"

geopatcher.config.config_from_fields(obj, *, exclude=())

Serialise a dataclass axis into its get_config dict.

Walks the dataclass's init fields in declaration order (private init=False accumulator state is skipped automatically) and coerces each value with jsonable_scalar; tuples, lists and arrays are rebuilt as lists and mappings as dicts, with every element coerced recursively.

Parameters:

Name Type Description Default
obj Any

A dataclass instance.

required
exclude tuple[str, ...]

Field names to omit (e.g. fields needing custom handling).

()

Returns:

Type Description
``{field_name

coerced_value}`` in field declaration order.

Source code in packages/geotoolz-patcher/src/geopatcher/_src/_serialize.py
def config_from_fields(obj: Any, *, exclude: tuple[str, ...] = ()) -> dict[str, Any]:
    """Serialise a dataclass axis into its ``get_config`` dict.

    Walks the dataclass's init fields in declaration order (private
    ``init=False`` accumulator state is skipped automatically) and coerces
    each value with `jsonable_scalar`; tuples, lists and arrays are
    rebuilt as lists and mappings as dicts, with every element coerced
    recursively.

    Args:
        obj: A dataclass instance.
        exclude: Field names to omit (e.g. fields needing custom handling).

    Returns:
        ``{field_name: coerced_value}`` in field declaration order.
    """
    return {
        f.name: _jsonable(getattr(obj, f.name))
        for f in dataclasses.fields(obj)
        if f.init and f.name not in exclude
    }