Skip to content

Load — geocatalog.load

Materialise the pixels a catalog covers on a GeoSlice: raster mosaics (sync + async), daily time series, xarray cubes and vector layers.

Raster

geocatalog.load.load_raster(catalog, slice_, *, band_indexes=None, resampling=None, merge_method='last', nodata=None, retries=3, max_open_workers=8, storage_options=None)

Read + mosaic the catalog rows matching slice_ into one GeoArray.

Filters the catalog with catalog.query(slice_), opens every surviving row, and calls rasterio.merge.merge to produce a single array clipped to slice_.bounds at slice_.resolution. The returned geoarray.GeoArray is on the slice grid (slice_.grid), ready for downstream operators.

Sources whose CRS differs from slice_.crs are warped on the fly (rasterio.vrt.WarpedVRT with resampling), so the output is always on the slice grid in the slice CRS, and files in different CRSs mosaic together. Overlaps are resolved in catalog row order (with merge_method="last", later rows win). The output dtype is the common type of all sources.

Parameters:

Name Type Description Default
catalog InMemoryGeoCatalog

A raster-backend catalog.

required
slice_ GeoSlice

The window to read. Bounds may be in a different CRS than the catalog; the loader reprojects internally on the query.

required
band_indexes Sequence[int] | None

1-indexed bands to keep, in the order requested. None means all bands in their native order.

None
resampling Any | None

A rasterio.enums.Resampling enum value (e.g. Resampling.nearest for categorical labels). Defaults to bilinear.

None
merge_method _RasterMergeMethod

How to combine overlapping pixels from multiple source files. One of "first", "last", "min", "max", "sum" — exactly what rasterio.merge.merge accepts. The original snippet's "count" is not a valid rasterio mode and is rejected (§7.7 of the design plan).

'last'
nodata float | None

Override the nodata value used in the mosaic. None respects each source's declared _FillValue / nodata.

None
retries int

Number of retries for transient remote I/O failures. 0 disables retry/backoff.

3
max_open_workers int

Thread-pool width for the file-open phase. Remote (S3/HTTP) opens are latency-bound metadata round trips and rasterio releases the GIL during them, so opening concurrently cuts the open phase from N x latency to ceil(N / workers) x latency. The effective width is min(max_open_workers, n_files); 1 (or 0) keeps the serial behaviour. The merge phase is unchanged.

8
storage_options dict[str, Any] | None

obstore store options for cloud/HTTP URIs (e.g. {"skip_signature": True} for a public bucket), read through geocloud.fs (the [cloud] extra). None uses GDAL's native VSI handling for s3://-style paths.

None

Returns:

Type Description
GeoArray

A geoarray.GeoArray of shape (bands, H, W) on the slice grid

GeoArray

(its grid equals slice_.grid). fill_value is the

nodata value the mosaic actually used

nodata if supplied,

GeoArray

else the first source nodata found, else 0 (what the mosaic

GeoArray

writes where no source covers a pixel). Its dims are

GeoArray

("band", "y", "x"); when every source names its bands (the

GeoArray

GeoTIFF band descriptions) the same way, those names are a

GeoArray

SpectralAxis, so scene.sel(band="B04") works.

Example

The hits of a query, mosaicked onto the slice grid::

scene = load_raster(catalog, slice_, band_indexes=[1, 2, 3])
scene.shape, scene.grid == slice_.grid  # (3, H, W), True

Raises:

Type Description
ValueError

If no catalog rows match the slice, if merge_method is not one of the valid rasterio modes, or if nodata cannot be represented in the output dtype (e.g. -1 or NaN for uint16 sources).

TypeError

If the catalog's backend tag is not "raster".

Source code in packages/geotoolz-catalog/src/geocatalog/_src/formats/raster.py
def load_raster(
    catalog: InMemoryGeoCatalog,
    slice_: GeoSlice,
    *,
    band_indexes: Sequence[int] | None = None,
    resampling: Any | None = None,
    merge_method: _RasterMergeMethod = "last",
    nodata: float | None = None,
    retries: int = 3,
    max_open_workers: int = 8,
    storage_options: dict[str, Any] | None = None,
) -> GeoArray:
    """Read + mosaic the catalog rows matching ``slice_`` into one `GeoArray`.

    Filters the catalog with ``catalog.query(slice_)``, opens every
    surviving row, and calls `rasterio.merge.merge` to produce a single
    array clipped to ``slice_.bounds`` at ``slice_.resolution``. The
    returned `geoarray.GeoArray` is on the slice grid (``slice_.grid``),
    ready for downstream operators.

    Sources whose CRS differs from ``slice_.crs`` are warped on the fly
    (`rasterio.vrt.WarpedVRT` with ``resampling``), so the output is
    always on the slice grid in the slice CRS, and files in different
    CRSs mosaic together. Overlaps are resolved in catalog row order
    (with ``merge_method="last"``, later rows win). The output dtype is
    the common type of all sources.

    Args:
        catalog: A raster-backend catalog.
        slice_: The window to read. Bounds may be in a different CRS
            than the catalog; the loader reprojects internally on the
            query.
        band_indexes: 1-indexed bands to keep, in the order requested.
            ``None`` means all bands in their native order.
        resampling: A ``rasterio.enums.Resampling`` enum value (e.g.
            ``Resampling.nearest`` for categorical labels). Defaults to
            bilinear.
        merge_method: How to combine overlapping pixels from multiple
            source files. One of ``"first"``, ``"last"``, ``"min"``,
            ``"max"``, ``"sum"`` — exactly what `rasterio.merge.merge`
            accepts. The original snippet's ``"count"`` is not a valid
            rasterio mode and is rejected (§7.7 of the design plan).
        nodata: Override the nodata value used in the mosaic. ``None``
            respects each source's declared ``_FillValue`` / ``nodata``.
        retries: Number of retries for transient remote I/O failures.
            ``0`` disables retry/backoff.
        max_open_workers: Thread-pool width for the file-*open* phase.
            Remote (S3/HTTP) opens are latency-bound metadata round
            trips and rasterio releases the GIL during them, so opening
            concurrently cuts the open phase from ``N x latency`` to
            ``ceil(N / workers) x latency``. The effective width is
            ``min(max_open_workers, n_files)``; ``1`` (or ``0``) keeps
            the serial behaviour. The merge phase is unchanged.
        storage_options: obstore store options for cloud/HTTP URIs
            (e.g. ``{"skip_signature": True}`` for a public bucket),
            read through `geocloud.fs` (the ``[cloud]`` extra). ``None``
            uses GDAL's native VSI handling for ``s3://``-style paths.

    Returns:
        A `geoarray.GeoArray` of shape ``(bands, H, W)`` on the slice grid
        (its ``grid`` equals ``slice_.grid``). ``fill_value`` is the
        nodata value the mosaic actually used: ``nodata`` if supplied,
        else the first source nodata found, else 0 (what the mosaic
        writes where no source covers a pixel). Its dims are
        ``("band", "y", "x")``; when every source names its bands (the
        GeoTIFF band descriptions) the same way, those names are a
        `SpectralAxis`, so ``scene.sel(band="B04")`` works.

    Example:
        The hits of a query, mosaicked onto the slice grid::

            scene = load_raster(catalog, slice_, band_indexes=[1, 2, 3])
            scene.shape, scene.grid == slice_.grid  # (3, H, W), True

    Raises:
        ValueError: If no catalog rows match the slice, if
            ``merge_method`` is not one of the valid rasterio modes, or
            if ``nodata`` cannot be represented in the output dtype
            (e.g. ``-1`` or ``NaN`` for ``uint16`` sources).
        TypeError: If the catalog's backend tag is not ``"raster"``.
    """
    if merge_method not in _VALID_MERGE_METHODS:
        raise ValueError(
            f"merge_method must be one of {_VALID_MERGE_METHODS}; got {merge_method!r}"
        )
    if catalog.kind != "raster":
        raise TypeError(
            f"load_raster requires a raster-backend catalog; got {catalog.kind!r}"
        )
    filtered = catalog.query(slice_)
    if len(filtered) == 0:
        raise ValueError("load_raster: no catalog rows match the slice")

    # `is None`, not truthiness: Resampling.nearest == 0 (#217).
    if resampling is None:
        resampling = Resampling.bilinear
    filepaths = filtered.gdf["filepath"].tolist()

    def _open_one(fp: str) -> tuple[Any, Any]:
        resolved = _resolve_uri(fp, storage_options=storage_options, prefer_gdal=True)
        try:
            src = retry_transient_io(rasterio.open, resolved, retries=retries)
        except BaseException:
            _close_resolved_uri(resolved)
            raise
        return resolved, src

    handles = []
    resolved_handles = []
    warped: list[WarpedVRT] = []
    try:
        n_workers = max(1, min(max_open_workers, len(filepaths)))
        if n_workers == 1:
            for fp in filepaths:
                resolved, src = _open_one(fp)
                resolved_handles.append(resolved)
                handles.append(src)
        else:
            with ThreadPoolExecutor(max_workers=n_workers) as executor:
                # Submit in row order and consume in the same order so
                # order-sensitive merge methods ("first" / "last") see
                # the same source sequence as the serial path. Track
                # every successfully opened handle even when an earlier
                # file failed, so the `finally` below closes them all.
                futures = [executor.submit(_open_one, fp) for fp in filepaths]
                first_exc: BaseException | None = None
                for future in futures:
                    try:
                        resolved, src = future.result()
                    except BaseException as exc:
                        if first_exc is None:
                            first_exc = exc
                        continue
                    resolved_handles.append(resolved)
                    handles.append(src)
                if first_exc is not None:
                    raise first_exc
        # The nodata value the mosaic uses: an explicit override, else the
        # first source that declares one (rasterio's own rule is "first
        # source", which silently becomes 0 when that one has none).
        out_nodata = (
            nodata
            if nodata is not None
            else next((s.nodata for s in handles if s.nodata is not None), None)
        )
        target_crs = pyproj.CRS.from_user_input(slice_.crs)
        sources = []
        for src in handles:
            if pyproj.CRS.from_user_input(src.crs.to_wkt()) == target_crs:
                sources.append(src)
                continue
            # Reproject into the slice CRS (#216). The VRT needs a nodata
            # value so pixels outside the source footprint are masked in
            # the merge instead of being written as data.
            vrt_nodata = (
                src.nodata
                if src.nodata is not None
                else out_nodata
                if out_nodata is not None
                else 0
            )
            vrt = WarpedVRT(
                src,
                crs=target_crs.to_wkt(),
                resampling=resampling,
                nodata=vrt_nodata,
            )
            warped.append(vrt)
            sources.append(vrt)
        bands = _band_axis(handles, band_indexes)
        out_dtype = np.result_type(*(np.dtype(s.dtypes[0]) for s in sources))
        if nodata is not None:
            _check_nodata_fits(nodata, out_dtype)
        merged, transform = rio_merge(
            sources,
            bounds=slice_.bounds,
            res=slice_.resolution,
            indexes=list(band_indexes) if band_indexes is not None else None,
            method=merge_method,
            nodata=out_nodata,
            dtype=out_dtype,
            resampling=resampling,
            dst_path=None,
        )
    finally:
        for vrt in warped:
            vrt.close()
        for h in handles:
            h.close()
        for h in resolved_handles:
            _close_resolved_uri(h)

    # rasterio.merge writes 0 where no source covers a pixel when no
    # source declares a nodata, so 0 is the fill the mosaic used.
    return GeoArray(
        merged,  # (bands, H, W)
        transform,
        slice_.crs,
        fill_value=out_nodata if out_nodata is not None else 0,
        dims=("band", "y", "x"),
        coords=() if bands is None else (bands,),
    )

geocatalog.load.aload_raster(catalog, slice_, *, band_indexes=None, resampling=None, merge_method='last', nodata=None, retries=3, max_open_workers=8, storage_options=None) async

Async mirror of load_raster for event-loop consumers.

Runs load_raster in a worker thread via asyncio.to_thread so the event loop stays responsive during rasterio I/O (which releases the GIL), with the file-open phase parallelised to max_open_workers threads inside the worker. Same arguments and return value as load_raster. (concurrency is the deprecated name of max_open_workers; concurrency names the build strategy.)

Source code in packages/geotoolz-catalog/src/geocatalog/_src/formats/raster.py
@renamed_kwargs(concurrency="max_open_workers")
async def aload_raster(
    catalog: InMemoryGeoCatalog,
    slice_: GeoSlice,
    *,
    band_indexes: Sequence[int] | None = None,
    resampling: Any | None = None,
    merge_method: _RasterMergeMethod = "last",
    nodata: float | None = None,
    retries: int = 3,
    max_open_workers: int = 8,
    storage_options: dict[str, Any] | None = None,
) -> GeoArray:
    """Async mirror of `load_raster` for event-loop consumers.

    Runs `load_raster` in a worker thread via `asyncio.to_thread` so the
    event loop stays responsive during rasterio I/O (which releases the
    GIL), with the file-open phase parallelised to ``max_open_workers``
    threads inside the worker. Same arguments and return value as
    `load_raster`. (``concurrency`` is the deprecated name of
    ``max_open_workers``; ``concurrency`` names the build strategy.)
    """
    return await asyncio.to_thread(
        functools.partial(
            load_raster,
            catalog,
            slice_,
            band_indexes=band_indexes,
            resampling=resampling,
            merge_method=merge_method,
            nodata=nodata,
            retries=retries,
            max_open_workers=max_open_workers,
            storage_options=storage_options,
        )
    )

geocatalog.load.load_raster_timeseries(catalog, slice_, *, band_indexes=None, resampling=None, nodata=None, n_workers=4, on_missing_day='skip', storage_options=None)

Stack daily mosaics across the slice's interval into (time, b, h, w).

For each distinct day on which a matching row's time window begins inside slice_.interval (a row that began earlier counts from the slice start), runs load_raster for that day's sub-slice, clipped to the slice interval, and stacks the results along a new leading time axis in chronological order. Rows of time-invariant files (the 1900-2100 sentinel interval) create no step of their own but are mosaicked into every step; if only such rows match, there is one step at the slice start. By default, days whose per-day load raises ValueError are dropped — the time axis is the observed day count, not a dense calendar. The transform / CRS come from the chronologically last successful day's load (same for every day since the slice is fixed).

Parameters:

Name Type Description Default
catalog InMemoryGeoCatalog

A raster-backend catalog with at least one row in slice_.interval.

required
slice_ GeoSlice

Window to read for each day. The same bounds / resolution / crs apply to every time step.

required
band_indexes Sequence[int] | None

Forwarded to per-day load_raster; see that function for semantics.

None
resampling Any | None

Forwarded to per-day load_raster.

None
nodata float | None

Forwarded to per-day load_raster.

None
n_workers int

Thread-pool size for per-day load_raster calls. 1 preserves serial execution.

4
on_missing_day Literal['skip', 'raise']

"skip" preserves the historical behavior of dropping days whose per-day load raises ValueError; "raise" propagates the first such error.

'skip'

Returns:

Type Description
GeoArray

A geoarray.GeoArray of shape (T, bands, H, W) on the slice

GeoArray

grid, where T is the number of distinct days with coverage;

GeoArray

its fill_value is the last day's. Its dims are

GeoArray

("time", "band", "y", "x") and its time coordinate holds

each step's start

the earliest matching row's time that day,

GeoArray

clipped to the slice (the row's own time when a day has one row).

Raises:

Type Description
ValueError

If no catalog rows match the slice, or if every matching day failed to produce a usable mosaic.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/formats/raster.py
def load_raster_timeseries(
    catalog: InMemoryGeoCatalog,
    slice_: GeoSlice,
    *,
    band_indexes: Sequence[int] | None = None,
    resampling: Any | None = None,
    nodata: float | None = None,
    n_workers: int = 4,
    on_missing_day: Literal["skip", "raise"] = "skip",
    storage_options: dict[str, Any] | None = None,
) -> GeoArray:
    """Stack daily mosaics across the slice's interval into ``(time, b, h, w)``.

    For each distinct day on which a matching row's time window begins
    inside ``slice_.interval`` (a row that began earlier counts from the
    slice start), runs `load_raster` for that day's sub-slice, clipped to
    the slice interval, and stacks the results along a new leading time
    axis in chronological order. Rows of time-invariant files (the
    1900-2100 sentinel interval) create no step of their own but are
    mosaicked into every step; if only such rows match, there is one
    step at the slice start. By
    default, days whose per-day load raises `ValueError` are dropped —
    the time axis is the *observed* day count, not a dense calendar.
    The transform / CRS come from the chronologically last successful
    day's load (same for every day since the slice is fixed).

    Args:
        catalog: A raster-backend catalog with at least one row in
            ``slice_.interval``.
        slice_: Window to read for each day. The same ``bounds`` /
            ``resolution`` / ``crs`` apply to every time step.
        band_indexes: Forwarded to per-day `load_raster`; see that
            function for semantics.
        resampling: Forwarded to per-day `load_raster`.
        nodata: Forwarded to per-day `load_raster`.
        n_workers: Thread-pool size for per-day `load_raster` calls.
            ``1`` preserves serial execution.
        on_missing_day: ``"skip"`` preserves the historical behavior of
            dropping days whose per-day load raises `ValueError`; ``"raise"``
            propagates the first such error.

    Returns:
        A `geoarray.GeoArray` of shape ``(T, bands, H, W)`` on the slice
        grid, where ``T`` is the number of distinct days with coverage;
        its ``fill_value`` is the last day's. Its dims are
        ``("time", "band", "y", "x")`` and its ``time`` coordinate holds
        each step's start: the earliest matching row's time that day,
        clipped to the slice (the row's own time when a day has one row).

    Raises:
        ValueError: If no catalog rows match the slice, or if every
            matching day failed to produce a usable mosaic.
    """
    if n_workers < 1:
        raise ValueError(f"n_workers must be >= 1; got {n_workers!r}")
    if on_missing_day not in ("skip", "raise"):
        raise ValueError(
            f"on_missing_day must be one of {{'skip', 'raise'}}; got {on_missing_day!r}"
        )

    filtered = catalog.query(slice_)
    if len(filtered) == 0:
        raise ValueError("load_raster_timeseries: no catalog rows match the slice")

    days = _timeseries_days(filtered.gdf.index, slice_.interval)
    starts = _step_starts(filtered.gdf.index, slice_.interval, days)

    def load_day(day: pd.Timestamp) -> tuple[pd.Timestamp, GeoArray] | None:
        # Clip the day to the slice: a sub-day slice stays sub-day (#219).
        day_interval = pd.Interval(
            max(day, slice_.interval.left),
            min(
                day + pd.Timedelta(days=1) - pd.Timedelta(microseconds=1),
                slice_.interval.right,
            ),
            closed="both",
        )
        day_slice = dataclasses.replace(slice_, interval=day_interval)
        try:
            return day, load_raster(
                catalog,
                day_slice,
                band_indexes=band_indexes,
                resampling=resampling,
                nodata=nodata,
                storage_options=storage_options,
            )
        except ValueError:
            if on_missing_day == "skip":
                return None
            raise

    results: list[tuple[pd.Timestamp, GeoArray]] = []
    if n_workers == 1:
        for day in days:
            result = load_day(day)
            if result is not None:
                results.append(result)
    else:
        with ThreadPoolExecutor(max_workers=n_workers) as executor:
            # Submit in day order and consume results in the same order so
            # that, with on_missing_day="raise", the earliest failing day
            # raises deterministically regardless of completion order.
            futures = [executor.submit(load_day, day) for day in days]
            try:
                for future in futures:
                    result = future.result()
                    if result is not None:
                        results.append(result)
            except BaseException:
                # Cancel any pending work before propagating so large
                # intervals do not block on already-submitted tasks.
                for pending in futures:
                    pending.cancel()
                executor.shutdown(wait=False, cancel_futures=True)
                raise

    if not results:
        raise ValueError("load_raster_timeseries: no usable days in interval")

    ordered = sorted(results, key=lambda item: item[0])
    scenes = [scene for _, scene in ordered]
    # (T, bands, H, W); not `geoarray.stack`, which refuses days whose
    # mosaics declare different nodata values: the last day's is kept.
    stacked = np.stack([np.asarray(scene) for scene in scenes], axis=0)
    times = TimeAxis(
        np.array([starts[day] for day, _ in ordered], dtype="datetime64[ns]")
    )
    last = scenes[-1]
    # a band axis labels every step only when every day names its bands
    # the same way; otherwise the bands stay positional
    agreed = all(scene.coords == last.coords for scene in scenes)
    return last.with_data(
        stacked,
        dims=("time", *last.dims),
        coords=(times, *(last.coords if agreed else ())),
    )

Xarray (extras: [xarray-raster])

geocatalog.load.load_xarray(catalog, slice_, *, data_vars=None, storage_options=None)

Load + concat the catalog rows matching slice_ into an xr.Dataset.

For each matching file, opens it inside a context manager, clips to slice_.bounds along the spatial coords and to slice_.interval along the time coord, .load()s the clipped piece so the data persists after the file handle closes, and concatenates the pieces along the time coordinate. Single-file results skip the concat.

The time-clip is what makes this loader honest for files that span many years — without it, a query for one month against a multi-year NetCDF would return every timestep in the file.

Parameters:

Name Type Description Default
catalog InMemoryGeoCatalog

An xarray-backend catalog.

required
slice_ GeoSlice

Window to read. Bounds may be in a different CRS than the catalog; they are reprojected into the catalog CRS for both the row query and the coordinate selection. Ascending and descending coordinate axes are both handled.

required
data_vars Sequence[str] | None

Subset of data variables to keep per file. None preserves the dataset's full variable set.

None

Returns:

Type Description
Dataset

An xr.Dataset concatenated along the time coordinate (sorted,

Dataset

duplicate timesteps dropped), or a single-file Dataset if only

Dataset

one row matched.

Raises:

Type Description
ImportError

If xarray is not installed ([xarray-raster] extra missing).

TypeError

If the catalog's backend tag is not "xarray".

ValueError

If no catalog rows match the slice.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/formats/xarray_backend.py
def load_xarray(
    catalog: InMemoryGeoCatalog,
    slice_: GeoSlice,
    *,
    data_vars: Sequence[str] | None = None,
    storage_options: dict[str, Any] | None = None,
) -> xr.Dataset:
    """Load + concat the catalog rows matching ``slice_`` into an ``xr.Dataset``.

    For each matching file, opens it inside a context manager, clips to
    ``slice_.bounds`` along the spatial coords *and* to
    ``slice_.interval`` along the time coord, ``.load()``s the clipped
    piece so the data persists after the file handle closes, and
    concatenates the pieces along the time coordinate. Single-file
    results skip the concat.

    The time-clip is what makes this loader honest for files that span
    many years — without it, a query for one month against a multi-year
    NetCDF would return every timestep in the file.

    Args:
        catalog: An xarray-backend catalog.
        slice_: Window to read. Bounds may be in a different CRS than
            the catalog; they are reprojected into the catalog CRS for
            both the row query and the coordinate selection. Ascending
            and descending coordinate axes are both handled.
        data_vars: Subset of data variables to keep per file. ``None``
            preserves the dataset's full variable set.

    Returns:
        An ``xr.Dataset`` concatenated along the time coordinate (sorted,
        duplicate timesteps dropped), or a single-file Dataset if only
        one row matched.

    Raises:
        ImportError: If xarray is not installed (``[xarray-raster]``
            extra missing).
        TypeError: If the catalog's backend tag is not ``"xarray"``.
        ValueError: If no catalog rows match the slice.
    """
    if xr is None:
        raise missing_extra("`load_xarray`", "xarray-raster")
    if catalog.kind != "xarray":
        raise TypeError(
            f"load_xarray requires an xarray-backend catalog; got {catalog.kind!r}"
        )
    filtered = catalog.query(slice_)
    if len(filtered) == 0:
        raise ValueError("load_xarray: no catalog rows match the slice")

    # Coordinates are in the catalog CRS (the builder doesn't reproject
    # them), so the selection box must be too (#218).
    xmin, ymin, xmax, ymax = _reproject_bounds(
        slice_.bounds, slice_.crs, filtered.gdf.crs
    )
    t_start, t_end = slice_.interval.left, slice_.interval.right
    time_vars = (
        filtered.gdf["time_var"]
        if "time_var" in filtered.gdf.columns
        else pd.Series(["time"] * len(filtered.gdf))
    )
    pieces: list[xr.Dataset] = [
        _read_clipped(
            fp,
            bounds=(xmin, ymin, xmax, ymax),
            interval=(t_start, t_end),
            time_var=row_time_var,
            data_vars=data_vars,
            storage_options=storage_options,
        )
        for fp, row_time_var in zip(filtered.gdf["filepath"], time_vars, strict=True)
    ]
    if len(pieces) == 1:
        return pieces[0]
    time_var = time_vars.iloc[0]
    if time_var in pieces[0].coords:
        # Catalog row order is arbitrary: sort along time and drop
        # timesteps repeated across overlapping files (first one wins).
        out = xr.concat(pieces, dim=time_var).sortby(time_var)
        keep = ~out.indexes[time_var].duplicated()
        return out.isel({time_var: keep})
    return xr.merge(pieces)

Vector

geocatalog.load.load_vector(catalog, slice_, *, task='semantic_segmentation', label_field=None, burn_value=None, fill=0, storage_options=None, retries=3)

Rasterise the catalog's vector rows matching slice_ into a GeoArray.

Filters the catalog with catalog.query(slice_), opens every matching vector file, clips its features to slice_.bounds (in slice_.crs), and burns them into a single-channel int64 raster via rasterio.features.rasterize. The output's transform / CRS come straight from slice_, so the result aligns pixel-for-pixel with whatever the matching imagery loader produces for the same slice.

Parameters:

Name Type Description Default
catalog InMemoryGeoCatalog

A vector-backend catalog.

required
slice_ GeoSlice

Window to rasterise into. The result is on slice_.grid: slice_.shape, with the slice's transform and CRS.

required
task _VectorTask

Which ML target shape to produce:

  • "semantic_segmentation": a map of class IDs read from label_field. With label_field=None each feature burns as burn_value (default 1).
  • "instance_segmentation": one integer per feature (1..N) — distinct values for distinct objects.
  • "object_detection": not implemented; build the bbox tensor yourself from the filtered features.
'semantic_segmentation'
label_field str | None

Column in the vector file to read class IDs from for "semantic_segmentation". Must be integer-valued. None falls back to burn_value.

None
burn_value int | None

The value burnt in for "semantic_segmentation" when label_field is None. Default 1.

None
fill int

Background value written outside any feature, and the result's fill_value. Default 0.

0
storage_options dict[str, Any] | None

obstore store options for cloud/HTTP URIs, read through geocloud.fs (the [cloud] extra).

None
retries int

Retries for transient I/O failures per file open. 0 disables retry/backoff.

3

Returns:

Type Description
A `GeoMap`

a geoarray.GeoArray of shape (H, W), dims

GeoArray

("y", "x"), dtype=int64, on the slice grid (its grid

GeoArray

equals slice_.grid), with fill_value=fill. One layer of

GeoArray

labels is a map, not an image, so there is no band axis.

Example

Class labels aligned with the imagery of the same slice::

labels = load_vector(catalog, slice_, label_field="class_id")
labels.shape, labels.grid == slice_.grid  # (H, W), True

Raises:

Type Description
TypeError

If the catalog's backend tag is not "vector".

NotImplementedError

For task="object_detection".

ValueError

If no catalog rows match the slice.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/formats/vector.py
def load_vector(
    catalog: InMemoryGeoCatalog,
    slice_: GeoSlice,
    *,
    task: _VectorTask = "semantic_segmentation",
    label_field: str | None = None,
    burn_value: int | None = None,
    fill: int = 0,
    storage_options: dict[str, Any] | None = None,
    retries: int = 3,
) -> GeoArray:
    """Rasterise the catalog's vector rows matching ``slice_`` into a `GeoArray`.

    Filters the catalog with ``catalog.query(slice_)``, opens every
    matching vector file, clips its features to ``slice_.bounds`` (in
    ``slice_.crs``), and burns them into a single-channel int64 raster
    via `rasterio.features.rasterize`. The output's transform / CRS
    come straight from ``slice_``, so the result aligns pixel-for-pixel
    with whatever the matching imagery loader produces for the same
    slice.

    Args:
        catalog: A vector-backend catalog.
        slice_: Window to rasterise into. The result is on
            ``slice_.grid``: ``slice_.shape``, with the slice's transform
            and CRS.
        task: Which ML target shape to produce:

            - ``"semantic_segmentation"``: a map of class IDs read from
              ``label_field``. With ``label_field=None`` each
              feature burns as ``burn_value`` (default 1).
            - ``"instance_segmentation"``: one integer per feature
              (1..N) — distinct values for distinct objects.
            - ``"object_detection"``: not implemented; build
              the bbox tensor yourself from the filtered features.
        label_field: Column in the vector file to read class IDs from
            for ``"semantic_segmentation"``. Must be integer-valued.
            ``None`` falls back to ``burn_value``.
        burn_value: The value burnt in for ``"semantic_segmentation"``
            when ``label_field`` is ``None``. Default 1.
        fill: Background value written outside any feature, and the
            result's ``fill_value``. Default 0.
        storage_options: obstore store options for cloud/HTTP URIs, read
            through `geocloud.fs` (the ``[cloud]`` extra).
        retries: Retries for transient I/O failures per file open. ``0``
            disables retry/backoff.

    Returns:
        A `GeoMap`: a `geoarray.GeoArray` of shape ``(H, W)``, dims
        ``("y", "x")``, ``dtype=int64``, on the slice grid (its ``grid``
        equals ``slice_.grid``), with ``fill_value=fill``. One layer of
        labels is a map, not an image, so there is no band axis.

    Example:
        Class labels aligned with the imagery of the same slice::

            labels = load_vector(catalog, slice_, label_field="class_id")
            labels.shape, labels.grid == slice_.grid  # (H, W), True

    Raises:
        TypeError: If the catalog's backend tag is not ``"vector"``.
        NotImplementedError: For ``task="object_detection"``.
        ValueError: If no catalog rows match the slice.
    """
    if catalog.kind != "vector":
        raise TypeError(
            f"load_vector requires a vector-backend catalog; got {catalog.kind!r}"
        )
    if task == "object_detection":
        raise NotImplementedError(
            "load_vector(task='object_detection') is not implemented; build the "
            "bounding-box tensor yourself from the matched features for now."
        )

    filtered = catalog.query(slice_)
    if len(filtered) == 0:
        raise ValueError("load_vector: no catalog rows match the slice")

    height, width = slice_.shape
    transform = slice_.transform
    features = []
    instance_id = 1
    # `layer` is always set by `_vector_row` for catalogs built here, but
    # externally constructed catalogs (or `from_geoparquet` of foreign
    # files) may not carry the column. Fall back to a same-length sequence
    # of `None`s so the zip below never crashes on a missing column.
    if "layer" in filtered.gdf.columns:
        layers: Sequence[Any] = filtered.gdf["layer"].tolist()
    else:
        layers = [None] * len(filtered.gdf)
    for fp, layer in zip(filtered.gdf["filepath"], layers, strict=True):
        # Clip to the slice bbox. Passing it (with its CRS) to the reader
        # lets the driver skip features outside it instead of loading the
        # whole file; geopandas reprojects the box into the file CRS (#220).
        xmin, ymin, xmax, ymax = slice_.bounds
        bbox = shapely.geometry.box(xmin, ymin, xmax, ymax)
        resolved = _resolve_uri(fp, storage_options=storage_options)
        try:
            sub = retry_transient_io(
                gpd.read_file,
                resolved,
                layer=layer,
                bbox=gpd.GeoSeries([bbox], crs=slice_.crs),
                retries=retries,
            )
        finally:
            _close_resolved_uri(resolved)
        if sub.crs is not None and sub.crs != slice_.crs:
            sub = sub.to_crs(slice_.crs)
        sub = sub[sub.intersects(bbox)]
        for _, row in sub.iterrows():
            if task == "semantic_segmentation":
                value = (
                    int(row[label_field])
                    if label_field is not None
                    else (burn_value if burn_value is not None else 1)
                )
            else:  # instance_segmentation
                value = instance_id
                instance_id += 1
            features.append((row.geometry, value))

    if not features:
        raster = np.full((height, width), fill, dtype=np.int64)
    else:
        burned = rasterize(
            features,
            out_shape=(height, width),
            transform=transform,
            fill=fill,
            dtype=np.int64,
        )
        raster = burned

    # (H, W) int64: one layer of labels is a map (GeoMap), no band axis
    return GeoArray(raster, transform, slice_.crs, fill_value=fill, dims=("y", "x"))