Skip to content

Core — geocatalog

The names every catalog workflow touches: the GeoCatalog protocol every backend satisfies, the GeoSlice catalogs are queried with and loaders read on, the open_catalog factory, and cross-catalog set algebra.

Protocol

geocatalog.GeoCatalog

Bases: Protocol

A queryable spatiotemporal index over geospatial files.

Implementations carry a backend-specific store (in-memory GeoDataFrame; DuckDB+GeoParquet; future others) but expose the same query / intersect / union / iter-slices surface. Downstream code (loaders, the patch bridge, training loops) targets this Protocol, not a concrete class, so swapping the backend never touches the consumer.

Attributes:

Name Type Description
gdf GeoDataFrame

A geopandas.GeoDataFrame view of the catalog rows. For in-memory backends this is the canonical store; for out-of-core backends it's a materialised view of the rows most recently queried. Always non-None; may be empty. The geometry column is in CRS units; the row index is a pd.IntervalIndex (closed='both') over the time axis.

kind CatalogKind

One of "raster", "xarray", "vector" — the kind of data indexed. Drives the dispatching choice in the loaders (load_raster, load_xarray, load_vector).

crs CRS

The catalog CRS as a pyproj.CRS. Footprints and total_bounds are in its units. Reading it never materialises rows.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/base.py
@runtime_checkable
class GeoCatalog(Protocol, metaclass=_GeoCatalogMeta):
    """A queryable spatiotemporal index over geospatial files.

    Implementations carry a backend-specific store (in-memory
    GeoDataFrame; DuckDB+GeoParquet; future others) but expose the same
    query / intersect / union / iter-slices surface. Downstream code
    (loaders, the patch bridge, training loops) targets this Protocol,
    not a concrete class, so swapping the backend never touches the
    consumer.

    Attributes:
        gdf: A `geopandas.GeoDataFrame` view of the catalog rows. For
            in-memory backends this is the canonical store; for
            out-of-core backends it's a materialised view of the rows
            most recently queried. Always non-None; may be empty. The
            geometry column is in CRS units; the row index is a
            ``pd.IntervalIndex`` (``closed='both'``) over the time axis.
        kind: One of ``"raster"``, ``"xarray"``, ``"vector"`` — the
            kind of data indexed. Drives the dispatching choice in the
            loaders (`load_raster`, `load_xarray`, `load_vector`).
        crs: The catalog CRS as a ``pyproj.CRS``. Footprints and
            ``total_bounds`` are in its units. Reading it never
            materialises rows.
    """

    gdf: gpd.GeoDataFrame
    kind: CatalogKind
    crs: pyproj.CRS

    def query(
        self,
        slice_: GeoSlice | None = None,
        *,
        bounds: tuple[float, float, float, float] | None = None,
        crs: Any | None = None,
        time: tuple[Any, Any] | pd.Interval | None = None,
    ) -> GeoCatalog:
        """Spatial + temporal filter — return rows overlapping the query.

        Two call shapes are supported: pass a `GeoSlice` (carries bounds,
        time, and CRS together), or pass the parts. Bounds in a non-
        catalog CRS are reprojected internally so an AOI in the wrong
        CRS doesn't silently match zero rows.

        Args:
            slice_: A `GeoSlice` whose bbox + interval drive the filter.
                Mutually exclusive with the keyword args.
            bounds: ``(xmin, ymin, xmax, ymax)`` in ``crs`` units.
            crs: CRS of ``bounds``; defaults to the catalog CRS if
                ``None``.
            time: Either a ``(start, end)`` pair (`pd.Timestamp`-like)
                or a `pd.Interval`. ``None`` skips the temporal filter.

        Returns:
            A new catalog of the same backend tag containing only the
            matching rows. May be empty.

        Raises:
            TypeError: If both ``slice_`` and any of (``bounds``,
                ``time``) are passed.
        """
        ...

    def intersect(self, other: GeoCatalog, *, spatial_only: bool = False) -> GeoCatalog:
        """Cross-catalog AND — pair rows by spatial (+ temporal) overlap.

        For each pair of rows whose footprints intersect, the result
        contains one row with the clipped intersection footprint and the
        intersected time interval. Pairs with disjoint intervals are
        dropped unless ``spatial_only=True``.

        Args:
            other: The catalog to pair against. May use a different
                backend; reprojection to ``self``'s CRS happens
                internally if needed.
            spatial_only: If True, ignore the temporal axis. The right
                tool for pairing imagery with static labels (DEMs,
                land-cover maps) that have no meaningful time interval.

        Returns:
            A new catalog with ``self``'s backend tag — the result
            indexes the same kind of file as ``self``, just constrained
            to footprints where ``other`` agrees. May be empty.
        """
        ...

    def union(self, other: GeoCatalog) -> GeoCatalog:
        """Cross-catalog OR — concatenate rows.

        Useful when you want to treat two sensors as one virtual dataset
        (Landsat 7 + Landsat 8 for a long time series; S2A + S2B for
        better revisit). ``other`` is reprojected into ``self.crs`` if
        the CRSs differ; the result's backend tag is ``self``'s.
        Backend tags are *not* checked — unioning a raster catalog with
        a vector one will not raise, but the downstream loader you
        eventually call will reject the mismatch.

        Args:
            other: Catalog to concatenate. CRS is auto-reprojected.

        Returns:
            A new catalog containing every row of ``self`` followed by
            every (possibly reprojected) row of ``other``. No dedup is
            performed — call `query` afterwards if you want to filter.
        """
        ...

    def iter_rows(self, *, batch_size: int = 1024) -> Iterator[CatalogRow]:
        """Yield rows as backend-neutral `CatalogRow` instances.

        Consumed by loaders, the sampler, and the `geopatcher`
        bridge. Backends should stream — for the DuckDB backend this
        fetches in batches of ``batch_size``; the in-memory backend
        ignores ``batch_size`` and iterates the underlying gdf.

        Args:
            batch_size: Rows per fetch for streaming backends. Default
                1024. In-memory backends ignore this.

        Yields:
            `CatalogRow` instances in catalog order. Order is stable for
            in-memory backends; out-of-core backends should document
            their ordering explicitly.
        """
        ...

    def iter_slices(self, *, resolution: tuple[float, float]) -> Iterator[GeoSlice]:
        """Yield one `GeoSlice` per catalog row at the given resolution.

        Each row's footprint becomes the slice's bbox; the row's
        IntervalIndex entry becomes its interval. The slices are the
        unit of work consumed by loaders and the `CatalogDomain` bridge
        — emit them lazily so callers can short-circuit.

        Args:
            resolution: Target ``(x_res, y_res)`` in CRS units, baked
                into every emitted slice. Drives the pixel shape a
                loader will produce.

        Yields:
            `GeoSlice` instances in row order. Order is stable for
            in-memory backends; out-of-core backends should document
            their ordering explicitly.
        """
        ...

    @property
    def total_bounds(self) -> tuple[float, float, float, float]:
        """Union bbox over all rows.

        Returns:
            ``(xmin, ymin, xmax, ymax)`` in catalog-CRS units, or four
            NaNs if the catalog is empty.
        """
        ...

    @property
    def temporal_extent(self) -> pd.Interval | None:
        """Tightest interval that contains every row's time window.

        Returns:
            A ``pd.Interval(closed='both')`` from ``min(start_times)``
            to ``max(end_times)``, or ``None`` for an empty catalog.
        """
        ...

    def __len__(self) -> int:
        """Number of rows in the catalog."""
        ...

    def get_config(self) -> dict[str, Any]:
        """Return a JSON-serialisable summary — for logging / reproducibility audits.

        The exact shape is backend-specific but always includes the
        backend tag, the row count, and the catalog CRS so two catalogs
        can be compared at a glance.
        """
        ...

temporal_extent property

Tightest interval that contains every row's time window.

Returns:

Type Description
Interval | None

A pd.Interval(closed='both') from min(start_times)

Interval | None

to max(end_times), or None for an empty catalog.

total_bounds property

Union bbox over all rows.

Returns:

Type Description
float

(xmin, ymin, xmax, ymax) in catalog-CRS units, or four

float

NaNs if the catalog is empty.

__len__()

Number of rows in the catalog.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/base.py
def __len__(self) -> int:
    """Number of rows in the catalog."""
    ...

get_config()

Return a JSON-serialisable summary — for logging / reproducibility audits.

The exact shape is backend-specific but always includes the backend tag, the row count, and the catalog CRS so two catalogs can be compared at a glance.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/base.py
def get_config(self) -> dict[str, Any]:
    """Return a JSON-serialisable summary — for logging / reproducibility audits.

    The exact shape is backend-specific but always includes the
    backend tag, the row count, and the catalog CRS so two catalogs
    can be compared at a glance.
    """
    ...

intersect(other, *, spatial_only=False)

Cross-catalog AND — pair rows by spatial (+ temporal) overlap.

For each pair of rows whose footprints intersect, the result contains one row with the clipped intersection footprint and the intersected time interval. Pairs with disjoint intervals are dropped unless spatial_only=True.

Parameters:

Name Type Description Default
other GeoCatalog

The catalog to pair against. May use a different backend; reprojection to self's CRS happens internally if needed.

required
spatial_only bool

If True, ignore the temporal axis. The right tool for pairing imagery with static labels (DEMs, land-cover maps) that have no meaningful time interval.

False

Returns:

Type Description
GeoCatalog

A new catalog with self's backend tag — the result

GeoCatalog

indexes the same kind of file as self, just constrained

GeoCatalog

to footprints where other agrees. May be empty.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/base.py
def intersect(self, other: GeoCatalog, *, spatial_only: bool = False) -> GeoCatalog:
    """Cross-catalog AND — pair rows by spatial (+ temporal) overlap.

    For each pair of rows whose footprints intersect, the result
    contains one row with the clipped intersection footprint and the
    intersected time interval. Pairs with disjoint intervals are
    dropped unless ``spatial_only=True``.

    Args:
        other: The catalog to pair against. May use a different
            backend; reprojection to ``self``'s CRS happens
            internally if needed.
        spatial_only: If True, ignore the temporal axis. The right
            tool for pairing imagery with static labels (DEMs,
            land-cover maps) that have no meaningful time interval.

    Returns:
        A new catalog with ``self``'s backend tag — the result
        indexes the same kind of file as ``self``, just constrained
        to footprints where ``other`` agrees. May be empty.
    """
    ...

iter_rows(*, batch_size=1024)

Yield rows as backend-neutral CatalogRow instances.

Consumed by loaders, the sampler, and the geopatcher bridge. Backends should stream — for the DuckDB backend this fetches in batches of batch_size; the in-memory backend ignores batch_size and iterates the underlying gdf.

Parameters:

Name Type Description Default
batch_size int

Rows per fetch for streaming backends. Default 1024. In-memory backends ignore this.

1024

Yields:

Type Description
CatalogRow

CatalogRow instances in catalog order. Order is stable for

CatalogRow

in-memory backends; out-of-core backends should document

CatalogRow

their ordering explicitly.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/base.py
def iter_rows(self, *, batch_size: int = 1024) -> Iterator[CatalogRow]:
    """Yield rows as backend-neutral `CatalogRow` instances.

    Consumed by loaders, the sampler, and the `geopatcher`
    bridge. Backends should stream — for the DuckDB backend this
    fetches in batches of ``batch_size``; the in-memory backend
    ignores ``batch_size`` and iterates the underlying gdf.

    Args:
        batch_size: Rows per fetch for streaming backends. Default
            1024. In-memory backends ignore this.

    Yields:
        `CatalogRow` instances in catalog order. Order is stable for
        in-memory backends; out-of-core backends should document
        their ordering explicitly.
    """
    ...

iter_slices(*, resolution)

Yield one GeoSlice per catalog row at the given resolution.

Each row's footprint becomes the slice's bbox; the row's IntervalIndex entry becomes its interval. The slices are the unit of work consumed by loaders and the CatalogDomain bridge — emit them lazily so callers can short-circuit.

Parameters:

Name Type Description Default
resolution tuple[float, float]

Target (x_res, y_res) in CRS units, baked into every emitted slice. Drives the pixel shape a loader will produce.

required

Yields:

Type Description
GeoSlice

GeoSlice instances in row order. Order is stable for

GeoSlice

in-memory backends; out-of-core backends should document

GeoSlice

their ordering explicitly.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/base.py
def iter_slices(self, *, resolution: tuple[float, float]) -> Iterator[GeoSlice]:
    """Yield one `GeoSlice` per catalog row at the given resolution.

    Each row's footprint becomes the slice's bbox; the row's
    IntervalIndex entry becomes its interval. The slices are the
    unit of work consumed by loaders and the `CatalogDomain` bridge
    — emit them lazily so callers can short-circuit.

    Args:
        resolution: Target ``(x_res, y_res)`` in CRS units, baked
            into every emitted slice. Drives the pixel shape a
            loader will produce.

    Yields:
        `GeoSlice` instances in row order. Order is stable for
        in-memory backends; out-of-core backends should document
        their ordering explicitly.
    """
    ...

query(slice_=None, *, bounds=None, crs=None, time=None)

Spatial + temporal filter — return rows overlapping the query.

Two call shapes are supported: pass a GeoSlice (carries bounds, time, and CRS together), or pass the parts. Bounds in a non- catalog CRS are reprojected internally so an AOI in the wrong CRS doesn't silently match zero rows.

Parameters:

Name Type Description Default
slice_ GeoSlice | None

A GeoSlice whose bbox + interval drive the filter. Mutually exclusive with the keyword args.

None
bounds tuple[float, float, float, float] | None

(xmin, ymin, xmax, ymax) in crs units.

None
crs Any | None

CRS of bounds; defaults to the catalog CRS if None.

None
time tuple[Any, Any] | Interval | None

Either a (start, end) pair (pd.Timestamp-like) or a pd.Interval. None skips the temporal filter.

None

Returns:

Type Description
GeoCatalog

A new catalog of the same backend tag containing only the

GeoCatalog

matching rows. May be empty.

Raises:

Type Description
TypeError

If both slice_ and any of (bounds, time) are passed.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/base.py
def query(
    self,
    slice_: GeoSlice | None = None,
    *,
    bounds: tuple[float, float, float, float] | None = None,
    crs: Any | None = None,
    time: tuple[Any, Any] | pd.Interval | None = None,
) -> GeoCatalog:
    """Spatial + temporal filter — return rows overlapping the query.

    Two call shapes are supported: pass a `GeoSlice` (carries bounds,
    time, and CRS together), or pass the parts. Bounds in a non-
    catalog CRS are reprojected internally so an AOI in the wrong
    CRS doesn't silently match zero rows.

    Args:
        slice_: A `GeoSlice` whose bbox + interval drive the filter.
            Mutually exclusive with the keyword args.
        bounds: ``(xmin, ymin, xmax, ymax)`` in ``crs`` units.
        crs: CRS of ``bounds``; defaults to the catalog CRS if
            ``None``.
        time: Either a ``(start, end)`` pair (`pd.Timestamp`-like)
            or a `pd.Interval`. ``None`` skips the temporal filter.

    Returns:
        A new catalog of the same backend tag containing only the
        matching rows. May be empty.

    Raises:
        TypeError: If both ``slice_`` and any of (``bounds``,
            ``time``) are passed.
    """
    ...

union(other)

Cross-catalog OR — concatenate rows.

Useful when you want to treat two sensors as one virtual dataset (Landsat 7 + Landsat 8 for a long time series; S2A + S2B for better revisit). other is reprojected into self.crs if the CRSs differ; the result's backend tag is self's. Backend tags are not checked — unioning a raster catalog with a vector one will not raise, but the downstream loader you eventually call will reject the mismatch.

Parameters:

Name Type Description Default
other GeoCatalog

Catalog to concatenate. CRS is auto-reprojected.

required

Returns:

Type Description
GeoCatalog

A new catalog containing every row of self followed by

GeoCatalog

every (possibly reprojected) row of other. No dedup is

GeoCatalog

performed — call query afterwards if you want to filter.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/base.py
def union(self, other: GeoCatalog) -> GeoCatalog:
    """Cross-catalog OR — concatenate rows.

    Useful when you want to treat two sensors as one virtual dataset
    (Landsat 7 + Landsat 8 for a long time series; S2A + S2B for
    better revisit). ``other`` is reprojected into ``self.crs`` if
    the CRSs differ; the result's backend tag is ``self``'s.
    Backend tags are *not* checked — unioning a raster catalog with
    a vector one will not raise, but the downstream loader you
    eventually call will reject the mismatch.

    Args:
        other: Catalog to concatenate. CRS is auto-reprojected.

    Returns:
        A new catalog containing every row of ``self`` followed by
        every (possibly reprojected) row of ``other``. No dedup is
        performed — call `query` afterwards if you want to filter.
    """
    ...

GeoSlice

geocatalog.GeoSlice dataclass

A bounded request for data — produced by samplers, consumed by loaders.

Carries everything a loader needs to fetch a chip without consulting the catalog: bbox in CRS units, time interval, target resolution, CRS.

Parameters:

Name Type Description Default
bounds tuple[float, float, float, float]

(xmin, ymin, xmax, ymax) in crs units.

required
interval Interval

A pd.Interval (closed='both') over the time axis. tz-aware timestamp endpoints are converted to naive UTC, the catalog's stored time form.

required
resolution tuple[float, float]

(x_res, y_res) in CRS units. Both positive.

required
crs CRS

A pyproj.CRS. String / EPSG-int inputs are coerced.

required
Source code in packages/geotoolz-catalog/src/geocatalog/_src/geoslice.py
@dataclass(frozen=True)
class GeoSlice:
    """A bounded request for data — produced by samplers, consumed by loaders.

    Carries everything a loader needs to fetch a chip without consulting
    the catalog: bbox in CRS units, time interval, target resolution, CRS.

    Args:
        bounds: ``(xmin, ymin, xmax, ymax)`` in ``crs`` units.
        interval: A ``pd.Interval`` (``closed='both'``) over the time axis.
            tz-aware timestamp endpoints are converted to naive UTC, the
            catalog's stored time form.
        resolution: ``(x_res, y_res)`` in CRS units. Both positive.
        crs: A ``pyproj.CRS``. String / EPSG-int inputs are coerced.
    """

    bounds: tuple[float, float, float, float]
    interval: pd.Interval
    resolution: tuple[float, float]
    crs: pyproj.CRS
    # Construction-time alignment policy. NOT part of identity:
    # two slices with the same bounds/interval/resolution/crs compare
    # equal and hash equal regardless of ``align`` (see
    # docs/catalog/design/exact-grid-alignment.md).
    align: Align = field(
        default="off",
        compare=False,
        hash=False,
        repr=False,
    )

    def __post_init__(self) -> None:
        # Normalise to tuples of Python floats: lists would make the slice
        # unhashable and compare unequal to the tuple form, and numpy
        # scalars would leak into repr / get_config.
        bounds = _float_tuple(self.bounds, 4, "bounds")
        resolution = _float_tuple(self.resolution, 2, "resolution")
        object.__setattr__(self, "bounds", bounds)
        object.__setattr__(self, "resolution", resolution)
        xmin, ymin, xmax, ymax = self.bounds
        if not (xmin < xmax and ymin < ymax):
            raise ValueError(
                f"GeoSlice.bounds must satisfy xmin < xmax and ymin < ymax; "
                f"got {self.bounds!r}"
            )
        if not isinstance(self.interval, pd.Interval):
            raise TypeError(
                "GeoSlice.interval must be a pd.Interval; "
                f"got {type(self.interval).__name__}"
            )
        if self.interval.closed != "both":
            raise ValueError(
                "GeoSlice.interval must be closed='both' for consistency with "
                f"the catalog IntervalIndex; got closed={self.interval.closed!r}"
            )
        # Catalog time contract: naive UTC. A tz-aware slice becomes the
        # equal (and equally hashed) naive-UTC slice.
        object.__setattr__(self, "interval", naive_utc_interval(self.interval))
        x_res, y_res = self.resolution
        if x_res <= 0 or y_res <= 0:
            raise ValueError(
                f"GeoSlice.resolution must be positive on both axes; "
                f"got {self.resolution!r}"
            )
        # Coerce string / EPSG-int CRS to pyproj.CRS so equality + serialisation
        # are well-defined. Frozen dataclasses forbid normal assignment;
        # object.__setattr__ is the standard escape hatch in __post_init__.
        if not isinstance(self.crs, pyproj.CRS):
            object.__setattr__(self, "crs", pyproj.CRS.from_user_input(self.crs))
        # Reject unknown modes at construction so a typo like
        # ``align="warning"`` doesn't silently disable validation.
        # The `Literal` annotation is documentation, not runtime
        # enforcement.
        if self.align not in _VALID_ALIGN_MODES:
            raise ValueError(
                f"GeoSlice.align must be one of "
                f"{sorted(_VALID_ALIGN_MODES)!r}; got {self.align!r}"
            )
        if self.align != "off":
            self._check_or_snap_alignment()

    def __hash__(self) -> int:
        # Consistent with the dataclass __eq__: equal slices have equal
        # bounds/interval/resolution. The CRS is excluded because pyproj
        # hashes its WKT while equality is PROJ equivalence (#227).
        return hash((self.bounds, self.interval, self.resolution))

    def _check_or_snap_alignment(self) -> None:
        """Validate or snap ``bounds`` against the alignment policy.

        Dispatches per-axis on the current ``align`` mode:

        - ``"error"`` — raise on the first misaligned axis.
        - ``"warn"`` — emit a `GridAlignmentWarning` per misaligned
          axis, leave bounds alone.
        - ``"snap"`` — round outward, **preserving the affine origin**
          for that axis. For north-up rasters the affine maps pixel
          ``(0,0)`` to ``(xmin, ymax)``, so snap holds ``xmin`` and
          ``ymax`` fixed and extends ``xmax`` rightward / ``ymin``
          downward. The resulting bounds fully cover the original AOI.
        """
        xmin, ymin, xmax, ymax = self.bounds
        rx, ry = self.resolution
        # For north-up rasters the affine origin is (xmin, ymax). To
        # preserve it under snap, hold those fixed and move xmax
        # rightward / ymin downward.
        new_xmax, new_ymin = xmax, ymin
        axes = (
            (xmax - xmin, rx, "x"),
            (ymax - ymin, ry, "y"),
        )
        for length, step, axis in axes:
            try:
                count_steps(length, step, label=f"{axis}-extent")
            except ValueError as exc:
                if self.align == "error":
                    raise
                if self.align == "warn":
                    warnings.warn(
                        f"GeoSlice grid misalignment: {exc}",
                        GridAlignmentWarning,
                        stacklevel=4,
                    )
                    continue
                if self.align == "snap":
                    n_up = int(np.ceil(length / step))
                    if axis == "x":
                        old = xmax
                        new_xmax = xmin + n_up * step
                        new = new_xmax
                    else:
                        old = ymin
                        new_ymin = ymax - n_up * step
                        new = new_ymin
                    warnings.warn(
                        f"GeoSlice snap: {axis}-extent edge "
                        f"{old:.6g} -> {new:.6g} (n={n_up}, "
                        f"step={step:.6g})",
                        GridAlignmentWarning,
                        stacklevel=4,
                    )
        if self.align == "snap" and (new_xmax != xmax or new_ymin != ymin):
            object.__setattr__(self, "bounds", (xmin, new_ymin, new_xmax, ymax))

    @property
    def shape(self) -> tuple[int, int]:
        """Output grid shape ``(height, width)`` from bounds + resolution.

        Each axis is ``extent / resolution`` rounded half up, so an
        extent of 10.5 pixels gives 11 on either axis. (Python's
        built-in ``round`` is half-to-even and would give 10 on one
        axis and 12 for 11.5 on the other.) Use `aligned_shape` to
        reject non-integer extents instead.
        """
        x_res, y_res = self.resolution
        xmin, ymin, xmax, ymax = self.bounds
        return (
            int(np.floor((ymax - ymin) / y_res + 0.5)),
            int(np.floor((xmax - xmin) / x_res + 0.5)),
        )

    @property
    def height(self) -> int:
        return self.shape[0]

    @property
    def width(self) -> int:
        return self.shape[1]

    def aligned_shape(self) -> tuple[int, int]:
        """Strict ``shape``: raises on misalignment regardless of mode.

        Use this when you need a guaranteed-exact pixel count without
        flipping the constructor's default ``align`` mode. ``.shape``
        stays rounding-based (half up) for backwards compatibility with
        existing loaders.

        Raises:
            ValueError: if either axis's extent is not an integer
                multiple of its resolution (within tolerance).
        """
        rx, ry = self.resolution
        xmin, ymin, xmax, ymax = self.bounds
        return (
            count_steps(ymax - ymin, ry, label="y-extent"),
            count_steps(xmax - xmin, rx, label="x-extent"),
        )

    @property
    def transform(self) -> Affine:
        """North-up affine from bounds + resolution."""
        x_res, y_res = self.resolution
        xmin, _ymin, _xmax, ymax = self.bounds
        return Affine(x_res, 0.0, xmin, 0.0, -y_res, ymax)

    @property
    def grid(self) -> Grid:
        """The output pixel grid: `transform`, ``crs`` and `shape`.

        The grid every loader returns its `geoarray.GeoArray` on, so
        ``load_raster(catalog, s).grid == s.grid``.

        Example:
            >>> import pandas as pd
            >>> s = GeoSlice(
            ...     bounds=(500000.0, 4000000.0, 500640.0, 4000320.0),
            ...     interval=pd.Interval(
            ...         pd.Timestamp("2024-01-01"), pd.Timestamp("2024-01-31"),
            ...         closed="both",
            ...     ),
            ...     resolution=(10.0, 10.0),
            ...     crs="EPSG:32629",
            ... )
            >>> s.grid.shape, s.grid.bounds == s.bounds
            ((32, 64), True)
        """
        return Grid(self.transform, self.crs, self.shape)

    def to_crs(self, target_crs: Any) -> GeoSlice:
        """Reproject this slice's bounds into ``target_crs``.

        The resolution is conservatively rescaled by the ratio of the
        projected-vs-source bbox widths so the output ``shape`` stays
        roughly stable.

        Raises:
            NotImplementedError: The reprojection produces a degenerate
                or non-finite box — a pole-wrapping, antimeridian-adjacent,
                or out-of-domain transform. Split or clip the slice first.
                (Antimeridian-*crossing* input bounds are already rejected
                at construction: ``__post_init__`` requires
                ``xmin < xmax``.)
        """
        target = (
            target_crs
            if isinstance(target_crs, pyproj.CRS)
            else pyproj.CRS.from_user_input(target_crs)
        )
        if target == self.crs:
            return self
        xmin, ymin, xmax, ymax = self.bounds
        transformer = pyproj.Transformer.from_crs(self.crs, target, always_xy=True)
        new_bounds = transformer.transform_bounds(xmin, ymin, xmax, ymax)
        if not all(np.isfinite(b) for b in new_bounds) or not (
            new_bounds[0] < new_bounds[2] and new_bounds[1] < new_bounds[3]
        ):
            raise NotImplementedError(
                f"GeoSlice.to_crs produced a degenerate box reprojecting "
                f"bounds={self.bounds} from {self.crs} to {target}: got "
                f"{tuple(new_bounds)}. This usually means the bounds wrap a "
                f"pole or leave the target CRS's domain — split or clip the "
                f"slice first."
            )
        # Preserve output shape: scale resolution by the bbox width ratio.
        old_w = xmax - xmin
        new_w = new_bounds[2] - new_bounds[0]
        old_h = ymax - ymin
        new_h = new_bounds[3] - new_bounds[1]
        x_res = self.resolution[0] * (new_w / old_w)
        y_res = self.resolution[1] * (new_h / old_h)
        # Reprojected bounds are *generically* non-integer multiples
        # of the rescaled resolution; force align="off" so a strict
        # parent's policy doesn't cause to_crs to raise on its own
        # output. Callers wanting validation can reconstruct.
        return GeoSlice(
            bounds=new_bounds,
            interval=self.interval,
            resolution=(x_res, y_res),
            crs=target,
            align="off",
        )

grid property

The output pixel grid: transform, crs and shape.

The grid every loader returns its geoarray.GeoArray on, so load_raster(catalog, s).grid == s.grid.

Example

import pandas as pd s = GeoSlice( ... bounds=(500000.0, 4000000.0, 500640.0, 4000320.0), ... interval=pd.Interval( ... pd.Timestamp("2024-01-01"), pd.Timestamp("2024-01-31"), ... closed="both", ... ), ... resolution=(10.0, 10.0), ... crs="EPSG:32629", ... ) s.grid.shape, s.grid.bounds == s.bounds ((32, 64), True)

shape property

Output grid shape (height, width) from bounds + resolution.

Each axis is extent / resolution rounded half up, so an extent of 10.5 pixels gives 11 on either axis. (Python's built-in round is half-to-even and would give 10 on one axis and 12 for 11.5 on the other.) Use aligned_shape to reject non-integer extents instead.

transform property

North-up affine from bounds + resolution.

aligned_shape()

Strict shape: raises on misalignment regardless of mode.

Use this when you need a guaranteed-exact pixel count without flipping the constructor's default align mode. .shape stays rounding-based (half up) for backwards compatibility with existing loaders.

Raises:

Type Description
ValueError

if either axis's extent is not an integer multiple of its resolution (within tolerance).

Source code in packages/geotoolz-catalog/src/geocatalog/_src/geoslice.py
def aligned_shape(self) -> tuple[int, int]:
    """Strict ``shape``: raises on misalignment regardless of mode.

    Use this when you need a guaranteed-exact pixel count without
    flipping the constructor's default ``align`` mode. ``.shape``
    stays rounding-based (half up) for backwards compatibility with
    existing loaders.

    Raises:
        ValueError: if either axis's extent is not an integer
            multiple of its resolution (within tolerance).
    """
    rx, ry = self.resolution
    xmin, ymin, xmax, ymax = self.bounds
    return (
        count_steps(ymax - ymin, ry, label="y-extent"),
        count_steps(xmax - xmin, rx, label="x-extent"),
    )

to_crs(target_crs)

Reproject this slice's bounds into target_crs.

The resolution is conservatively rescaled by the ratio of the projected-vs-source bbox widths so the output shape stays roughly stable.

Raises:

Type Description
NotImplementedError

The reprojection produces a degenerate or non-finite box — a pole-wrapping, antimeridian-adjacent, or out-of-domain transform. Split or clip the slice first. (Antimeridian-crossing input bounds are already rejected at construction: __post_init__ requires xmin < xmax.)

Source code in packages/geotoolz-catalog/src/geocatalog/_src/geoslice.py
def to_crs(self, target_crs: Any) -> GeoSlice:
    """Reproject this slice's bounds into ``target_crs``.

    The resolution is conservatively rescaled by the ratio of the
    projected-vs-source bbox widths so the output ``shape`` stays
    roughly stable.

    Raises:
        NotImplementedError: The reprojection produces a degenerate
            or non-finite box — a pole-wrapping, antimeridian-adjacent,
            or out-of-domain transform. Split or clip the slice first.
            (Antimeridian-*crossing* input bounds are already rejected
            at construction: ``__post_init__`` requires
            ``xmin < xmax``.)
    """
    target = (
        target_crs
        if isinstance(target_crs, pyproj.CRS)
        else pyproj.CRS.from_user_input(target_crs)
    )
    if target == self.crs:
        return self
    xmin, ymin, xmax, ymax = self.bounds
    transformer = pyproj.Transformer.from_crs(self.crs, target, always_xy=True)
    new_bounds = transformer.transform_bounds(xmin, ymin, xmax, ymax)
    if not all(np.isfinite(b) for b in new_bounds) or not (
        new_bounds[0] < new_bounds[2] and new_bounds[1] < new_bounds[3]
    ):
        raise NotImplementedError(
            f"GeoSlice.to_crs produced a degenerate box reprojecting "
            f"bounds={self.bounds} from {self.crs} to {target}: got "
            f"{tuple(new_bounds)}. This usually means the bounds wrap a "
            f"pole or leave the target CRS's domain — split or clip the "
            f"slice first."
        )
    # Preserve output shape: scale resolution by the bbox width ratio.
    old_w = xmax - xmin
    new_w = new_bounds[2] - new_bounds[0]
    old_h = ymax - ymin
    new_h = new_bounds[3] - new_bounds[1]
    x_res = self.resolution[0] * (new_w / old_w)
    y_res = self.resolution[1] * (new_h / old_h)
    # Reprojected bounds are *generically* non-integer multiples
    # of the rescaled resolution; force align="off" so a strict
    # parent's policy doesn't cause to_crs to raise on its own
    # output. Callers wanting validation can reconstruct.
    return GeoSlice(
        bounds=new_bounds,
        interval=self.interval,
        resolution=(x_res, y_res),
        crs=target,
        align="off",
    )

Opening a catalog

geocatalog.open_catalog(source, *, kind=None, engine='auto', crs=None, storage_options=None, strict=False)

Open a GeoParquet artifact as a GeoCatalog.

The factory picks an engine. "auto" prefers the DuckDB backend (lazy, scales) when the [duckdb] extra is installed; otherwise it falls back to the in-memory backend via from_geoparquet. Pass engine="memory" to force the eager path even with DuckDB present.

The artifact's stored kind (the _backend column written by to_geoparquet) is honoured by default — pass kind=... only to override a wrong tag or to tag an externally produced artifact that lacks the column. Forcing a default would silently miscategorise xarray / vector catalogs and break loader dispatch.

Parameters:

Name Type Description Default
source str | Path

Path or URI to a GeoParquet file. A directory of shards (shards/) or a glob (shards/*.parquet) is read as one virtual table by the DuckDB engine; the in-memory engine requires a single file.

required
kind CatalogKind | None

Loader dispatch tag ("raster" / "xarray" / "vector"). None reads the _backend column from the artifact (default "raster" if missing).

None
engine _ENGINE_T

"auto" (DuckDB if available, else memory), "memory" (force from_geoparquet), or "duckdb" (force DuckDBGeoCatalog.open; raises if the extra is not installed).

'auto'
crs Any | None

Optional CRS override for either engine. It relabels the footprints (no reprojection) — use it for artifacts whose GeoParquet metadata lacks or misstates the CRS.

None
storage_options dict[str, Any] | None

obstore store options for reading cloud URIs through the in-memory engine (geocloud.store.get_obstore, over the credentials registered in geocloud.credentials). A non-empty mapping makes "auto" pick that engine; {} counts as no options.

None
strict bool

If True, raise CatalogMetadataError instead of warning-and-falling-back when the artifact is missing the _backend column (and kind= was not passed) or — on the DuckDB engine — its geo metadata is unreadable (and crs= was not passed).

False

Returns:

Type Description
GeoCatalog

A GeoCatalog over source. The concrete class is either

GeoCatalog

DuckDBGeoCatalog or InMemoryGeoCatalog depending on the

GeoCatalog

resolved engine.

"auto" also falls back to the in-memory engine, with a warning, when DuckDB is installed but its spatial extension cannot be loaded (e.g. offline), since every spatial query would fail.

Raises:

Type Description
ImportError

engine="duckdb" with the extra missing.

ValueError

engine is not one of "auto", "memory", "duckdb".

Source code in packages/geotoolz-catalog/src/geocatalog/_src/factory.py
@renamed_kwargs(backend="kind")
def open_catalog(
    source: str | Path,
    *,
    kind: CatalogKind | None = None,
    engine: _ENGINE_T = "auto",
    crs: Any | None = None,
    storage_options: dict[str, Any] | None = None,
    strict: bool = False,
) -> GeoCatalog:
    """Open a GeoParquet artifact as a `GeoCatalog`.

    The factory picks an engine. ``"auto"`` prefers the DuckDB backend
    (lazy, scales) when the ``[duckdb]`` extra is installed; otherwise it
    falls back to the in-memory backend via `from_geoparquet`. Pass
    ``engine="memory"`` to force the eager path even with DuckDB present.

    The artifact's stored kind (the ``_backend`` column written
    by `to_geoparquet`) is honoured by default — pass ``kind=...``
    only to override a wrong tag or to tag an externally produced
    artifact that lacks the column. Forcing a default would silently
    miscategorise xarray / vector catalogs and break loader dispatch.

    Args:
        source: Path or URI to a GeoParquet file. A directory of shards
            (``shards/``) or a glob (``shards/*.parquet``) is read as one
            virtual table by the DuckDB engine; the in-memory engine
            requires a single file.
        kind: Loader dispatch tag (``"raster"`` / ``"xarray"`` /
            ``"vector"``). ``None`` reads the ``_backend`` column from
            the artifact (default ``"raster"`` if missing).
        engine: ``"auto"`` (DuckDB if available, else memory),
            ``"memory"`` (force `from_geoparquet`), or ``"duckdb"``
            (force `DuckDBGeoCatalog.open`; raises if the extra is not
            installed).
        crs: Optional CRS override for either engine. It relabels the
            footprints (no reprojection) — use it for artifacts whose
            GeoParquet metadata lacks or misstates the CRS.
        storage_options: obstore store options for reading cloud URIs
            through the in-memory engine (`geocloud.store.get_obstore`,
            over the credentials registered in `geocloud.credentials`).
            A non-empty mapping makes ``"auto"`` pick that engine; ``{}``
            counts as no options.
        strict: If ``True``, raise `CatalogMetadataError` instead of
            warning-and-falling-back when the artifact is missing the
            ``_backend`` column (and ``kind=`` was not passed) or —
            on the DuckDB engine — its ``geo`` metadata is unreadable
            (and ``crs=`` was not passed).

    Returns:
        A `GeoCatalog` over ``source``. The concrete class is either
        `DuckDBGeoCatalog` or `InMemoryGeoCatalog` depending on the
        resolved engine.

    ``"auto"`` also falls back to the in-memory engine, with a warning,
    when DuckDB is installed but its ``spatial`` extension cannot be
    loaded (e.g. offline), since every spatial query would fail.

    Raises:
        ImportError: ``engine="duckdb"`` with the extra missing.
        ValueError: ``engine`` is not one of ``"auto"``, ``"memory"``,
            ``"duckdb"``.
    """
    if engine not in get_args(_ENGINE_T):
        raise ValueError(
            f"open_catalog engine must be one of {list(get_args(_ENGINE_T))}; "
            f"got {engine!r}."
        )
    # `{}` carries no options; don't let it switch engines (#225).
    storage_options = storage_options or None
    if engine == "memory":
        return _memory_engine(
            source, kind, crs=crs, storage_options=storage_options, strict=strict
        )
    if engine == "duckdb":
        from geocatalog._src.backends.duckdb_backend import DuckDBGeoCatalog

        return DuckDBGeoCatalog.open(
            source,
            kind=kind,
            crs=crs,
            storage_options=storage_options,
            strict=strict,
        )
    # engine == "auto"
    if storage_options is not None:
        return _memory_engine(
            source, kind, crs=crs, storage_options=storage_options, strict=strict
        )
    try:
        from geocatalog._src.backends.duckdb_backend import DuckDBGeoCatalog
    except ImportError:
        return _memory_engine(source, kind, crs=crs, strict=strict)
    try:
        catalog = DuckDBGeoCatalog.open(
            source,
            kind=kind,
            crs=crs,
            storage_options=storage_options,
            strict=strict,
        )
    except ImportError:
        return _memory_engine(source, kind, crs=crs, strict=strict)
    if not catalog._spatial_available:
        catalog.close()
        warnings.warn(
            f"open_catalog({str(source)!r}): DuckDB's spatial extension is "
            "unavailable, so spatial queries would fail; using the in-memory "
            "engine instead. Pass engine='duckdb' to keep DuckDB anyway.",
            UserWarning,
            stacklevel=2,
        )
        return _memory_engine(source, kind, crs=crs, strict=strict)
    return catalog

Set algebra

geocatalog.query(catalog, slice_=None, *, bounds=None, crs=None, time=None)

Filter catalog by space + time and return the matching rows.

Two call shapes: pass a GeoSlice (carries bounds, time, and CRS together) or pass the parts. Bounds in a non-catalog CRS are reprojected internally — the canonical anti-footgun path (§10.1 of the design plan) for AOIs in the wrong projection.

Parameters:

Name Type Description Default
catalog GeoCatalog

Any GeoCatalog — backend-agnostic.

required
slice_ GeoSlice | None

A GeoSlice whose bbox + interval drive the filter. Mutually exclusive with the keyword args.

None
bounds tuple[float, float, float, float] | None

(xmin, ymin, xmax, ymax) in crs units.

None
crs Any | None

CRS of bounds; defaults to the catalog CRS if None.

None
time tuple[Any, Any] | Interval | None

(start, end) pair (pd.Timestamp-like) or a pd.Interval. None skips the temporal filter.

None

Returns:

Type Description
GeoCatalog

A new catalog of the same backend tag, possibly empty.

Raises:

Type Description
TypeError

If both slice_ and any of (bounds, time) are passed.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/ops.py
def query(
    catalog: GeoCatalog,
    slice_: GeoSlice | None = None,
    *,
    bounds: tuple[float, float, float, float] | None = None,
    crs: Any | None = None,
    time: tuple[Any, Any] | pd.Interval | None = None,
) -> GeoCatalog:
    """Filter ``catalog`` by space + time and return the matching rows.

    Two call shapes: pass a `GeoSlice` (carries bounds, time, and CRS
    together) or pass the parts. Bounds in a non-catalog CRS are
    reprojected internally — the canonical anti-footgun path (§10.1 of
    the design plan) for AOIs in the wrong projection.

    Args:
        catalog: Any `GeoCatalog` — backend-agnostic.
        slice_: A `GeoSlice` whose bbox + interval drive the filter.
            Mutually exclusive with the keyword args.
        bounds: ``(xmin, ymin, xmax, ymax)`` in ``crs`` units.
        crs: CRS of ``bounds``; defaults to the catalog CRS if ``None``.
        time: ``(start, end)`` pair (``pd.Timestamp``-like) or a
            `pd.Interval`. ``None`` skips the temporal filter.

    Returns:
        A new catalog of the same backend tag, possibly empty.

    Raises:
        TypeError: If both ``slice_`` and any of (``bounds``, ``time``)
            are passed.
    """
    return catalog.query(slice_, bounds=bounds, crs=crs, time=time)

geocatalog.intersect(left, right, *, spatial_only=False)

Cross-catalog AND — rows from left paired with overlapping rows in right.

For each pair of rows whose footprints intersect, the result has one row with the clipped intersection geometry and the intersected time interval. Disjoint-time pairs are dropped unless spatial_only=True.

Parameters:

Name Type Description Default
left GeoCatalog

Catalog whose backend tag the result will carry. The "imagery side" of an imagery / labels pairing.

required
right GeoCatalog

Catalog to pair against. Auto-reprojected to left's CRS if needed.

required
spatial_only bool

Skip the temporal filter — the right tool for pairing imagery with static labels (DEMs, land cover) that have no meaningful time interval.

False

Returns:

Type Description
GeoCatalog

A new catalog with left's backend tag, containing the

GeoCatalog

clipped-and-time-aligned rows. May be empty.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/ops.py
def intersect(
    left: GeoCatalog, right: GeoCatalog, *, spatial_only: bool = False
) -> GeoCatalog:
    """Cross-catalog AND — rows from ``left`` paired with overlapping rows in ``right``.

    For each pair of rows whose footprints intersect, the result has
    one row with the clipped intersection geometry and the intersected
    time interval. Disjoint-time pairs are dropped unless
    ``spatial_only=True``.

    Args:
        left: Catalog whose backend tag the result will carry. The
            "imagery side" of an imagery / labels pairing.
        right: Catalog to pair against. Auto-reprojected to ``left``'s
            CRS if needed.
        spatial_only: Skip the temporal filter — the right tool for
            pairing imagery with static labels (DEMs, land cover) that
            have no meaningful time interval.

    Returns:
        A new catalog with ``left``'s backend tag, containing the
        clipped-and-time-aligned rows. May be empty.
    """
    return left.intersect(right, spatial_only=spatial_only)

geocatalog.union(left, right)

Cross-catalog OR — concatenate left and right into one catalog.

The typical use is treating two sensors as one virtual dataset (Landsat 7 + Landsat 8, S2A + S2B). right is reprojected into left.crs if the CRSs differ; the result's backend tag comes from left.

Parameters:

Name Type Description Default
left GeoCatalog

Catalog whose backend tag + CRS win.

required
right GeoCatalog

Catalog to concatenate; auto-reprojected if needed.

required

Returns:

Type Description
GeoCatalog

A new catalog with every row of left followed by every

GeoCatalog

(possibly reprojected) row of right. No deduplication is

GeoCatalog

performed — call query afterwards if you want to filter.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/ops.py
def union(left: GeoCatalog, right: GeoCatalog) -> GeoCatalog:
    """Cross-catalog OR — concatenate ``left`` and ``right`` into one catalog.

    The typical use is treating two sensors as one virtual dataset
    (Landsat 7 + Landsat 8, S2A + S2B). ``right`` is reprojected into
    ``left.crs`` if the CRSs differ; the result's backend tag comes
    from ``left``.

    Args:
        left: Catalog whose backend tag + CRS win.
        right: Catalog to concatenate; auto-reprojected if needed.

    Returns:
        A new catalog with every row of ``left`` followed by every
        (possibly reprojected) row of ``right``. No deduplication is
        performed — call `query` afterwards if you want to filter.
    """
    return left.union(right)