Skip to content

geoarray.types

Readable names for the common carrier shapes: a dims pattern and a geometry kind any carrier can match (see Concepts).

geoarray.types

geoarray.types — readable names for the common carrier shapes.

A readable type is a name, a dims pattern and a geometry kind (GA-T5), not a subclass: any carrier whose dims and kind fit matches it (matches), and check_dims checks annotated arguments and returns at the call.

Type Kind and dims Typical data
GeoMap grid y x a matched-filter score, a mask, an XCH₄ map
GeoImage grid band y x one multispectral scene
GeoMapSeries grid time y x maps over time: SLA analyses, a daily MLD cube
GeoImageSeries grid time band y x frames over time: a Sentinel-2 stack
GeoVolume grid level y x gridded profiles on shared levels (EN4)
GeoPatches grid patch band y x a geopatcher batch
GeoSwathImage swath band row col EMIT or AVIRIS L1B in sensor geometry
GeoSwathProfile swath level row col TROPOMI averaging kernels and priors
GeoTimeSeries points time variable obs stations over shared times
GeoTracks points variable obs + time along-track altimetry, ship tracks
GeoProfiles points variable obs + z Argo, CTD, gliders

A time series is not a video: an image series is frames on a grid; a time series is values at fixed locations.

Each alias is Annotated[<carrier>, ReadableType(...)], so a type checker reads GeoImage as GeoArray.

Example

import numpy as np from geoarray import GeoArray from geoarray.types import GeoImage, check_dims @check_dims ... def brightest(scene: GeoImage) -> GeoArray["y x"]: ... return scene.isel(band=0) t = (1, 0, 0, 0, -1, 0) scene = GeoArray(np.zeros((2, 4, 4)), t, None, dims="band y x") brightest(scene).dims ('y', 'x')

Matching and checking

geoarray.types.matches(x, t)

Whether carrier x is a t: its kind, dims and required leaves.

Dims are read through x's pipekit adapter, with its horizontal dims renamed to the canonical ones (a CF cube's lat lon read as y x); nothing is renamed on x.

Example

import numpy as np from geoarray import GeoArray from geoarray.types import GeoImage, GeoMap stack = GeoArray(np.zeros((3, 2, 4, 4)), (1, 0, 0, 0, -1, 0), None, ... dims="time band y x") matches(stack.isel(time=0), GeoImage), matches(stack, GeoMap) (True, False)

Source code in packages/geotoolz-array/src/geoarray/_src/types.py
def matches(x: Any, t: Any) -> bool:
    """Whether carrier ``x`` is a ``t``: its kind, dims and required leaves.

    Dims are read through ``x``'s pipekit adapter, with its horizontal dims
    renamed to the canonical ones (a CF cube's ``lat lon`` read as ``y x``);
    nothing is renamed on ``x``.

    Example:
        >>> import numpy as np
        >>> from geoarray import GeoArray
        >>> from geoarray.types import GeoImage, GeoMap
        >>> stack = GeoArray(np.zeros((3, 2, 4, 4)), (1, 0, 0, 0, -1, 0), None,
        ...                  dims="time band y x")
        >>> matches(stack.isel(time=0), GeoImage), matches(stack, GeoMap)
        (True, False)
    """
    return _mismatch(x, as_readable(t)) is None

geoarray.types.check_dims(fn)

Check readable-type annotations at the call: arguments and the return.

Arguments annotated with a readable type (GeoImage, GeoArray["band y x"], or either | None) must match it (matches); so must the return value. Unannotated arguments pass. The checks read static dims only, so under jit they run once per trace and add nothing to the compiled program.

Raises:

Type Description
DimsError

At the call, naming the argument, the type and what the carrier has, with the fix when an extra leading dim is the difference.

Example

import numpy as np from geoarray import GeoArray from geoarray.types import GeoImage, GeoMap @check_dims ... def first_band(scene: GeoImage) -> GeoMap: ... return scene.isel(band=0) stack = GeoArray(np.zeros((3, 2, 4, 4)), (1, 0, 0, 0, -1, 0), None, ... dims="time band y x") first_band(stack) Traceback (most recent call last): ... geoarray._src.types.DimsError: first_band: scene is a GeoImage[grid: band y x], got dims ('time', 'band', 'y', 'x'). Map over time with geoarray.map_over(x, first_band, 'time').

Source code in packages/geotoolz-array/src/geoarray/_src/types.py
def check_dims[F: Callable[..., Any]](fn: F) -> F:
    """Check readable-type annotations at the call: arguments and the return.

    Arguments annotated with a readable type (``GeoImage``,
    ``GeoArray["band y x"]``, or either ``| None``) must match it
    (`matches`); so must the return value. Unannotated arguments pass.
    The checks read static dims only, so under ``jit`` they run once per
    trace and add nothing to the compiled program.

    Raises:
        DimsError: At the call, naming the argument, the type and what the
            carrier has, with the fix when an extra leading dim is the
            difference.

    Example:
        >>> import numpy as np
        >>> from geoarray import GeoArray
        >>> from geoarray.types import GeoImage, GeoMap
        >>> @check_dims
        ... def first_band(scene: GeoImage) -> GeoMap:
        ...     return scene.isel(band=0)
        >>> stack = GeoArray(np.zeros((3, 2, 4, 4)), (1, 0, 0, 0, -1, 0), None,
        ...                  dims="time band y x")
        >>> first_band(stack)
        Traceback (most recent call last):
        ...
        geoarray._src.types.DimsError: first_band: scene is a GeoImage[grid: band y x], got dims ('time', 'band', 'y', 'x'). Map over time with geoarray.map_over(x, first_band, 'time').
    """  # noqa: E501
    hints = typing.get_type_hints(fn, include_extras=True)
    signature = inspect.signature(fn)
    specs = {
        name: spec
        for name in signature.parameters
        if name in hints and (spec := spec_of(hints[name])) is not None
    }
    returned = spec_of(hints["return"]) if "return" in hints else None
    name = getattr(fn, "__qualname__", repr(fn))

    @functools.wraps(fn)
    def wrapper(*args: Any, **kwargs: Any) -> Any:
        bound = signature.bind(*args, **kwargs)
        for arg, spec in specs.items():
            if arg not in bound.arguments or bound.arguments[arg] is None:
                continue
            value = bound.arguments[arg]
            why = _mismatch(value, spec)
            if why is not None:
                raise DimsError(
                    f"{name}: {arg} is a {spec!r}, got {why}."
                    + _hint(name, value, spec)
                )
        out = fn(*args, **kwargs)
        if returned is not None and out is not None:
            why = _mismatch(out, returned)
            if why is not None:
                raise DimsError(f"{name} returns a {returned!r}, but returned {why}.")
        return out

    return typing.cast(F, wrapper)

geoarray.types.ReadableType dataclass

A name for a common carrier shape.

Parameters:

Name Type Description Default
name str

"GeoImage".

required
pattern str

The dims in canonical names: "band y x" for a grid, "band row col" for a swath, "variable obs" for points; ... for any dims ("... y x").

required
kind str

"grid", "swath" or "points".

required
leaves tuple[str, ...]

Geometry a point set must carry: ("time",) for tracks, ("z",) for profiles.

()
Example

GeoImage = ReadableType("GeoImage", "band y x", "grid") GeoImage GeoImage[grid: band y x]

Source code in packages/geotoolz-array/src/geoarray/_src/types.py
@dataclasses.dataclass(frozen=True)
class ReadableType:
    """A name for a common carrier shape.

    Args:
        name: ``"GeoImage"``.
        pattern: The dims in canonical names: ``"band y x"`` for a grid,
            ``"band row col"`` for a swath, ``"variable obs"`` for points;
            ``...`` for any dims (``"... y x"``).
        kind: ``"grid"``, ``"swath"`` or ``"points"``.
        leaves: Geometry a point set must carry: ``("time",)`` for tracks,
            ``("z",)`` for profiles.

    Example:
        >>> GeoImage = ReadableType("GeoImage", "band y x", "grid")
        >>> GeoImage
        GeoImage[grid: band y x]
    """

    name: str
    pattern: str
    kind: str
    leaves: tuple[str, ...] = ()

    def __post_init__(self) -> None:
        if self.kind not in CANONICAL:
            raise ValueError(f"kind is one of {sorted(CANONICAL)}, got {self.kind!r}")
        horizontal = CANONICAL[self.kind]
        names = self.pattern.split()
        if tuple(names[len(names) - len(horizontal) :]) != horizontal:
            raise ValueError(
                f"a {self.kind} pattern ends in {' '.join(horizontal)!r}, got "
                f"{self.pattern!r}"
            )

    @property
    def dims(self) -> tuple[str, ...]:
        """The pattern's names (``...`` included)."""
        return tuple(self.pattern.split())

    def __repr__(self) -> str:
        extra = f" + {', '.join(self.leaves)}" if self.leaves else ""
        return f"{self.name}[{self.kind}: {self.pattern}{extra}]"

dims property

The pattern's names (... included).

geoarray.types.kind_of(x)

The Kind of x, or None (a raw array, a DimArray).

Example

import numpy as np from geoarray import GeoArray g = GeoArray(np.zeros((2, 2)), (1, 0, 0, 0, -1, 0), None, dims="y x") kind_of(g) Kind(kind='grid', horizontal=('y', 'x'), leaves=frozenset())

Source code in packages/geotoolz-array/src/geoarray/_src/types.py
def kind_of(x: Any) -> Kind | None:
    """The `Kind` of ``x``, or ``None`` (a raw array, a `DimArray`).

    Example:
        >>> import numpy as np
        >>> from geoarray import GeoArray
        >>> g = GeoArray(np.zeros((2, 2)), (1, 0, 0, 0, -1, 0), None, dims="y x")
        >>> kind_of(g)
        Kind(kind='grid', horizontal=('y', 'x'), leaves=frozenset())
    """
    cls = type(x)
    reader = _lookup(cls)
    if reader is None:
        for prefix in list(_LAZY):
            if cls.__module__.startswith(prefix):
                _LAZY.pop(prefix)()
                reader = _lookup(cls)
                break
    return None if reader is None else reader(x)

geoarray.types.Kind

Bases: NamedTuple

What a kind reader says about a carrier.

Attributes:

Name Type Description
kind str

"grid", "swath" or "points".

horizontal tuple[str, ...]

The carrier's own names for the horizontal dims (("lat", "lon") on a CF cube), read as the kind's canonical ones in patterns.

leaves frozenset[str]

The optional geometry a point set carries ("z", "time"), which GeoProfiles / GeoTracks require.

Source code in packages/geotoolz-array/src/geoarray/_src/types.py
class Kind(NamedTuple):
    """What a kind reader says about a carrier.

    Attributes:
        kind: ``"grid"``, ``"swath"`` or ``"points"``.
        horizontal: The carrier's own names for the horizontal dims
            (``("lat", "lon")`` on a CF cube), read as the kind's canonical
            ones in patterns.
        leaves: The optional geometry a point set carries (``"z"``,
            ``"time"``), which `GeoProfiles` / `GeoTracks` require.
    """

    kind: str
    horizontal: tuple[str, ...]
    leaves: frozenset[str] = frozenset()

geoarray.types.register_kind_reader(carrier_type, reader)

Register how carriers of carrier_type (and subclasses) read as a kind.

reader(x) returns a Kind, or None when this x has no georeference a readable type can name.

Source code in packages/geotoolz-array/src/geoarray/_src/types.py
def register_kind_reader(carrier_type: type, reader: KindReader) -> None:
    """Register how carriers of ``carrier_type`` (and subclasses) read as a kind.

    ``reader(x)`` returns a `Kind`, or ``None`` when this ``x`` has no
    georeference a readable type can name.
    """
    _READERS[carrier_type] = reader

geoarray.types.DimsError

Bases: GeoArrayError, TypeError

A carrier's dims (or kind) do not fit the readable type a function declares.

Source code in packages/geotoolz-array/src/geoarray/_src/types.py
class DimsError(GeoArrayError, TypeError):
    """A carrier's dims (or kind) do not fit the readable type a function declares."""