Skip to content

Integrations API

Thin bridges from the patcher core into operator-graph frameworks, each gated behind the matching extra. (JAX batching and the Dask bridge are runners: see Running at scale.)

pipekit operator bridge (geopatcher.integrations.pipekit, [pipekit] extra)

Operator wrappers that plug a SpatialPatcher into a pipekit Sequential / Graph pipeline:

from geopatcher.integrations.pipekit import GridSampler, ApplyToChips, MergePatches

geopatcher.integrations.pipekit.GridSampler

Bases: Operator

Operator: Field → list[Patch] — yields the Patcher's patches.

Materialises the iterator into a list so downstream operators don't need to know about lazy iteration; users who want streaming should consume patcher.split directly.

Parameters:

Name Type Description Default
patcher SpatialPatcher

The SpatialPatcher to drive.

required
Note

forbid_in_yaml = True — patcher is a runtime SpatialPatcher (not a pipekit_ops.Operator), so pipekit's from_state cannot rebuild it and pipekit_ops.check_pickleable cannot look inside it; the flag makes the lint report this operator, so a closure-bearing axis (e.g. spatial.window.Custom) is not hidden. get_config() nests the patcher as a {"class", "config"} envelope, which geopatcher.config.from_config rebuilds when the patcher is serialisable.

Source code in packages/geotoolz-patcher/src/geopatcher/integrations/pipekit.py
class GridSampler(Operator):
    """Operator: ``Field → list[Patch]`` — yields the Patcher's patches.

    Materialises the iterator into a list so downstream operators don't
    need to know about lazy iteration; users who want streaming should
    consume ``patcher.split`` directly.

    Args:
        patcher: The `SpatialPatcher` to drive.

    Note:
        ``forbid_in_yaml = True`` — `patcher` is a runtime `SpatialPatcher`
        (not a `pipekit_ops.Operator`), so pipekit's `from_state` cannot rebuild
        it and `pipekit_ops.check_pickleable` cannot look inside it; the flag
        makes the lint report this operator, so a closure-bearing axis
        (e.g. `spatial.window.Custom`) is not hidden. `get_config()` nests the
        patcher as a ``{"class", "config"}`` envelope, which
        `geopatcher.config.from_config` rebuilds when the patcher is serialisable.
    """

    forbid_in_yaml: ClassVar[bool] = True

    def __init__(self, *, patcher: SpatialPatcher) -> None:
        self.patcher = patcher

    def _apply(self, field: Any) -> list[Patch]:
        return list(self.patcher.split(field))

    def get_config(self) -> dict[str, Any]:
        return {"patcher": axis_envelope(self.patcher)}

geopatcher.integrations.pipekit.ApplyToChips

Bases: Operator

Operator: list[Patch] → list[Patch] — map operator over each patch.

The inner operator runs against each patch.data and the result replaces patch.data; anchor / indices / weights are preserved so downstream MergePatches can reconstruct the field.

When the operator declares a coupling (every geoops operator does; a pipekit Sequential combines its steps), the call warns with PatchReachWarning when patching changes the answer: an operator fitted over space (a scaler, a matched filter) fits per patch or reuses one patch's fit; a global operator (reach=None, such as a scene percentile stretch) gives a different result per patch whatever the overlap; and a local one with reach r pixels needs neighbouring raster patches to overlap by at least 2 r pixels, so every pixel lies at least r from the edge of a patch that keeps it. The check is necessary, not sufficient: MergePatches with spatial.aggregation.OverlapAdd still blends in edge pixels unless the window gives them zero weight.

Parameters:

Name Type Description Default
operator Operator

The per-chip operator (any pipekit_ops.Operator).

required
check_reach bool

Warn as above. False turns the check off.

True
Source code in packages/geotoolz-patcher/src/geopatcher/integrations/pipekit.py
class ApplyToChips(Operator):
    """Operator: ``list[Patch] → list[Patch]`` — map ``operator`` over each patch.

    The inner operator runs against each ``patch.data`` and the result
    replaces ``patch.data``; ``anchor`` / ``indices`` / ``weights`` are
    preserved so downstream `MergePatches` can reconstruct the field.

    When the operator declares a ``coupling`` (every geoops operator does;
    a pipekit ``Sequential`` combines its steps), the call warns with
    `PatchReachWarning` when patching changes the answer: an operator fitted
    over space (a scaler, a matched filter) fits per patch or reuses one
    patch's fit; a global operator (``reach=None``, such as a scene
    percentile stretch) gives a different result per patch whatever the
    overlap; and a local one with reach ``r`` pixels needs neighbouring
    raster patches to overlap by at least ``2 r`` pixels, so every pixel
    lies at least ``r`` from the edge of a patch that keeps it. The check is necessary,
    not sufficient: `MergePatches` with `spatial.aggregation.OverlapAdd`
    still blends in edge pixels unless the window gives them zero weight.

    Args:
        operator: The per-chip operator (any `pipekit_ops.Operator`).
        check_reach: Warn as above. ``False`` turns the check off.
    """

    forbid_in_yaml: ClassVar[bool] = False

    def __init__(self, *, operator: Operator, check_reach: bool = True) -> None:
        self.operator = operator
        self.check_reach = check_reach

    def _apply(self, patches: list[Patch]) -> list[Patch]:
        if self.check_reach:
            self._warn_on_reach(patches)
        return [p.with_data(self.operator(p.data)) for p in patches]

    def _warn_on_reach(self, patches: list[Patch]) -> None:
        reach, fitted = _coupling_of(self.operator)
        if reach is _NOT_DECLARED:
            return
        name = type(self.operator).__name__
        if fitted:
            self._warn(
                f"{name} fits a state over the whole scene: on patches, each "
                "patch fits its own, or a fit on the first patch is reused; "
                "fit it on the whole scene first, or pass check_reach=False "
                "if per-patch fits are intended"
            )
        if reach == 0:
            return
        if reach is None:
            self._warn(
                f"{name} reads the whole scene: each patch gives a different "
                "answer whatever the overlap; run it on the whole scene, or "
                "pass check_reach=False if per-patch results are intended"
            )
            return
        overlaps = _overlaps(patches)
        if overlaps is None:
            return
        seams = [o for o in overlaps if o is not None]
        if seams and min(seams) // 2 < reach:
            self._warn(
                f"{name} has a spatial reach of {reach} px, but the patches "
                f"overlap by as little as {min(seams)} px: overlap them by at "
                f"least {2 * reach} px so every pixel is computed away from a seam"
            )

    @staticmethod
    def _warn(message: str) -> None:
        # _warn <- _warn_on_reach <- _apply <- pipekit's __call__ <- user code
        warnings.warn(message, PatchReachWarning, stacklevel=5)

    def get_config(self) -> dict[str, Any]:
        return {
            "operator": nested_config(self.operator),
            "check_reach": self.check_reach,
        }

geopatcher.integrations.pipekit.MergePatches

Bases: Operator

Operator: list[Patch] → field — wraps a spatial.aggregation.Aggregation.

Pairs with GridSampler + ApplyToChips to express split → operator → merge as a three-step Sequential. The domain argument is supplied at construction (commonly field.domain) so the resulting Operator has a single positional input (the list of patches) and slots into the linear pipeline.

On a raster domain (a RasterDomain, such as a RasterField's) the merged array comes back as a geoarray.GeoArray on the domain's grid — the carrier the patches went in as — with the band count the patches carry: a per-patch operator that turns four bands into one index gives (1, H, W), with the source's stale per-band attrs dropped and a NaN fill. Other outputs (a dict, a streaming zarr array, a non-georeferenced domain) are returned as the aggregation produced them.

Parameters:

Name Type Description Default
aggregation Aggregation

The spatial.aggregation.Aggregation to apply.

required
domain Any

The Domain the patches were drawn from. Required because it fixes the output grid.

required

Raises:

Type Description
TypeError

When applied, if domain or a patch's data is a georeader object (convert it with geoarray.interop.georeader.from_georeader).

Note

forbid_in_yaml = True — domain is a runtime Domain protocol object (a grid and a shape) and isn't in general JSON-serialisable, so the constructor cannot be round-tripped from get_config() alone. get_config() emits a debug record (class names + nested configs) for introspection / logging, not for replay.

Source code in packages/geotoolz-patcher/src/geopatcher/integrations/pipekit.py
class MergePatches(Operator):
    """Operator: ``list[Patch] → field`` — wraps a `spatial.aggregation.Aggregation`.

    Pairs with `GridSampler` + `ApplyToChips` to express ``split →
    operator → merge`` as a three-step `Sequential`. The ``domain``
    argument is supplied at construction (commonly ``field.domain``) so
    the resulting `Operator` has a single positional input (the list of
    patches) and slots into the linear pipeline.

    On a raster domain (a `RasterDomain`, such as a `RasterField`'s) the
    merged array comes back as a `geoarray.GeoArray` on the domain's grid —
    the carrier the patches went in as — with the band count the patches
    carry: a per-patch
    operator that turns four bands into one index gives ``(1, H, W)``,
    with the source's stale per-band ``attrs`` dropped and a NaN fill.
    Other outputs (a ``dict``, a streaming zarr array, a non-georeferenced
    domain) are returned as the aggregation produced them.

    Args:
        aggregation: The `spatial.aggregation.Aggregation` to apply.
        domain: The `Domain` the patches were drawn from. Required
            because it fixes the output grid.

    Raises:
        TypeError: When applied, if ``domain`` or a patch's data is a
            georeader object (convert it with
            ``geoarray.interop.georeader.from_georeader``).

    Note:
        ``forbid_in_yaml = True`` — `domain` is a runtime `Domain`
        protocol object (a grid and a shape) and isn't in
        general JSON-serialisable, so the constructor cannot be
        round-tripped from `get_config()` alone. `get_config()` emits a
        debug record (class names + nested configs) for introspection /
        logging, not for replay.
    """

    forbid_in_yaml: ClassVar[bool] = True

    def __init__(self, *, aggregation: SpatialAggregation, domain: Any) -> None:
        self.aggregation = aggregation
        self.domain = domain

    def _apply(self, patches: list[Patch]) -> Any:
        reject_georeader(self.domain, "MergePatches")
        patches = refusing_georeader(patches, "MergePatches")
        merged = self.aggregation.merge(patches, self.domain)
        return on_domain_grid(merged, self.aggregation, self.domain)

    def get_config(self) -> dict[str, Any]:
        return {
            "aggregation": axis_envelope(self.aggregation),
            "domain": {"class": type(self.domain).__name__},
        }

geopatcher.integrations.pipekit.PatchReachWarning

Bases: UserWarning

Patching changes the answer: the patches overlap by less than the operator's spatial reach, or the operator reads the whole scene.

Source code in packages/geotoolz-patcher/src/geopatcher/integrations/pipekit.py
class PatchReachWarning(UserWarning):
    """Patching changes the answer: the patches overlap by less than the
    operator's spatial reach, or the operator reads the whole scene."""

pipekit-train dataset (geopatcher.integrations.train, [train] extra)

XarrayWindowDataset: a pipekit-train TrainingDataset that samples (input, target) windows along a dimension from lazy xarray / Zarr stores, using the temporal stencils in geopatcher.temporal.stencils. It rides the Equinox adapter's Grain path (shuffle, checkpoint and resume), and with block_reader=True reads coalesced blocks with window shuffling and multi-host sharding. It moved here from pipekit_train.xarray_window, so pipekit does not depend on geopatcher.

from geopatcher.integrations.train import XarrayWindowDataset

geopatcher.integrations.train.XarrayWindowDataset

Bases: TrainingDataset

Lazy, indexable (input, target) windows sampled from a Zarr store.

Parameters:

Name Type Description Default
source dict[str, Dataset]

dict of lazy xarray.Datasets, e.g. {"input": ds, "target": ds}, opened with chunks=None.

required
stencils dict[str, Any]

matching dict of stencils (one per source leaf).

required
sample_origins ArrayLike | None

coordinate values to anchor windows on. None → derived via valid_origin_points (intersection across leaves).

None
sample_dim str

dimension to sample along (default "time").

'time'
store_version str

opaque token identifying the store contents for hashing (Zarr .zmetadata token or user-supplied). Required for a stable content-recipe hash.

required
block_reader bool

when True, the dataset advertises build_batch_iter so the adapter drives the cloud-scale block reader (coalesced reads + window shuffle + sharding). Default False (per-example path).

False
buffer_size_in_bytes float

shuffle-buffer byte budget for the block reader (ignored unless block_reader=True).

10000000000.0
buffer_diversity int

blocks represented in the shuffle buffer (ignored unless block_reader=True).

10
shard_index int | None

this host's shard for the block reader. When it and shard_count are both None and block_reader=True, both are auto-detected from JAX (process_index / process_count) at build time.

None
shard_count int | None

number of shards for the block reader (see shard_index).

None
split_guard int | None

origins to drop on the interior side of each split boundary. None → auto-derive from the widest stencil span.

None
seed int

RNG seed, the standard TrainingDataset knob.

0
split Split

"train", "val" or "test", the standard TrainingDataset knob.

'train'
Source code in packages/geotoolz-patcher/src/geopatcher/integrations/train.py
class XarrayWindowDataset(TrainingDataset):
    """Lazy, indexable ``(input, target)`` windows sampled from a Zarr store.

    Args:
        source: dict of lazy ``xarray.Dataset``s, e.g.
            ``{"input": ds, "target": ds}``, opened with ``chunks=None``.
        stencils: matching dict of stencils (one per source leaf).
        sample_origins: coordinate values to anchor windows on. ``None`` →
            derived via ``valid_origin_points`` (intersection across leaves).
        sample_dim: dimension to sample along (default ``"time"``).
        store_version: opaque token identifying the store contents for hashing
            (Zarr ``.zmetadata`` token or user-supplied). Required for a stable
            content-recipe hash.
        block_reader: when ``True``, the dataset advertises ``build_batch_iter``
            so the adapter drives the cloud-scale block reader (coalesced reads
            + window shuffle + sharding). Default ``False`` (per-example path).
        buffer_size_in_bytes: shuffle-buffer byte budget for the block reader
            (ignored unless ``block_reader=True``).
        buffer_diversity: blocks represented in the shuffle buffer (ignored
            unless ``block_reader=True``).
        shard_index: this host's shard for the block reader. When it and
            ``shard_count`` are both ``None`` and ``block_reader=True``, both
            are auto-detected from JAX (``process_index`` / ``process_count``)
            at build time.
        shard_count: number of shards for the block reader (see
            ``shard_index``).
        split_guard: origins to drop on the interior side of each split
            boundary. ``None`` → auto-derive from the widest stencil span.
        seed: RNG seed, the standard `TrainingDataset` knob.
        split: ``"train"``, ``"val"`` or ``"test"``, the standard
            `TrainingDataset` knob.
    """

    forbid_in_yaml: ClassVar[bool] = True  # source carries an open store
    __config_mixin_auto__ = False

    def __init__(
        self,
        source: dict[str, xarray.Dataset],
        stencils: dict[str, Any],
        sample_origins: np.typing.ArrayLike | None = None,
        *,
        sample_dim: str = "time",
        store_version: str,
        block_reader: bool = False,
        buffer_size_in_bytes: float = 1e10,
        buffer_diversity: int = 10,
        shard_index: int | None = None,
        shard_count: int | None = None,
        split_guard: int | None = None,
        seed: int = 0,
        split: Split = "train",
    ) -> None:
        super().__init__(seed=seed, split=split)
        if set(source) != set(stencils):
            raise ValueError(
                "source and stencils must have matching keys; got "
                f"{sorted(source)} vs {sorted(stencils)}."
            )
        if set(source) != _LEAVES:
            raise ValueError(
                "source and stencils must have exactly the keys "
                f"{sorted(_LEAVES)}; got {sorted(source)}."
            )
        if split_guard is not None and (
            isinstance(split_guard, bool)
            or not isinstance(split_guard, (int, np.integer))
            or split_guard < 0
        ):
            raise ValueError(
                f"split_guard must be a non-negative integer or None; got "
                f"{split_guard!r}."
            )
        if shard_index is not None or shard_count is not None:
            _xreader.check_shards(shard_index, shard_count)
        # Prepare each leaf (drop static vars + lead with sample_dim). The
        # resulting data_vars order is the channel order we collate + hash.
        self.source = {
            name: _xreader._prepare_xarray_source(ds, sample_dim)
            for name, ds in source.items()
        }
        self.stencils = stencils
        self.sample_dim = sample_dim
        self.store_version = store_version
        self.var_order = {name: list(ds.data_vars) for name, ds in self.source.items()}
        self.block_reader = block_reader
        self.buffer_size_in_bytes = buffer_size_in_bytes
        self.buffer_diversity = buffer_diversity
        self.shard_index = shard_index
        self.shard_count = shard_count
        # Block-reader sources handed out by build_batch_iter; close() shuts
        # their loader pools down too.
        self._block_sources: list[_xreader._PytreeSource] = []

        if sample_origins is not None:
            # A private copy: a caller mutating their array later must not
            # change the origins, the hash or the block reader's slices out
            # from under the per-example slices already built.
            self._all_origins = np.array(sample_origins, copy=True)
        else:
            self._all_origins = _intersect_valid_origins(
                self.source, stencils, sample_dim
            )
        self._all_origins.flags.writeable = False
        self._split_guard = (
            split_guard
            if split_guard is not None
            else _default_guard(self.source, stencils, sample_dim)
        )
        self.sample_origins = _split_origins(
            self._all_origins, split, self._split_guard
        )
        self._grain_source = self._build_grain_source()

    # --- construction helpers ----------------------------------------------

    def _build_grain_source(self) -> _xreader._PytreeSource:
        def _slices(ds: xarray.Dataset, stencil: Any) -> list[slice]:
            # A degenerate split (e.g. a guard band wider than a narrow band)
            # yields no origins; build_sampling_slices indexes origins[0], so
            # short-circuit to a length-0 source instead of crashing.
            if len(self.sample_origins) == 0:
                return []
            return build_sampling_slices(
                ds[self.sample_dim].values, self.sample_origins, stencil
            )

        return _xreader._PytreeSource(
            {
                name: _xreader._XarraySliceSource(
                    ds, _slices(ds, self.stencils[name]), self.sample_dim
                )
                for name, ds in self.source.items()
            }
        )

    def _collate_pair(self, pair: dict[str, Any]) -> tuple[Any, Any]:
        return (
            _xreader.collate(pair["input"], self.var_order["input"]),
            _xreader.collate(pair["target"], self.var_order["target"]),
        )

    def _resolve_shards(self) -> tuple[int, int]:
        if self.shard_index is not None and self.shard_count is not None:
            return self.shard_index, self.shard_count
        if self.shard_index is not None or self.shard_count is not None:
            raise ValueError("set both or neither of shard_index and shard_count")
        try:  # auto-detect a multi-host JAX setup
            import jax
        except ImportError:  # no JAX: a single host reads everything
            return 0, 1
        # A JAX that is installed but fails to report its processes is a
        # broken distributed setup; let it raise rather than have every host
        # read the full dataset.
        return jax.process_index(), jax.process_count()

    # --- indexable contract → rides the adapter's Grain path ---------------

    def __len__(self) -> int:
        return len(self._grain_source)

    def __getitem__(self, index: int) -> tuple[Any, Any]:
        return self._collate_pair(self._grain_source[index])

    def __iter__(self) -> Any:
        for i in range(len(self)):
            yield self[i]

    # --- cloud-scale path, reachable via the adapter hook ------------------

    def build_batch_iter(self, batch_size: int, seed: int) -> Any:
        """Adapter hook (see ``adapters/equinox.py`` ``_BatchSource``).

        Returns a checkpointable Grain *iterator* yielding collated, batched
        ``(X, Y)`` pairs via the block reader, or ``None`` to decline so the
        adapter falls back to the per-example indexable path. Declines unless
        ``block_reader=True``.
        """
        if not self.block_reader:
            return None
        shard_index, shard_count = self._resolve_shards()
        iter_ds, block_source = _xreader.training_iterator(
            self.source,
            self.stencils,
            self.sample_origins,
            sample_dim=self.sample_dim,
            num_epochs=None,
            buffer_size_in_bytes=self.buffer_size_in_bytes,
            buffer_diversity=self.buffer_diversity,
            shard_index=shard_index,
            shard_count=shard_count,
            seed=seed,
        )
        self._block_sources.append(block_source)
        iter_ds = iter_ds.map(self._collate_pair).batch(batch_size, drop_remainder=True)
        return iter(iter_ds)

    # --- split handling -----------------------------------------------------

    def with_split(self, split: Split) -> XarrayWindowDataset:
        """Return a clone of this dataset restricted to ``split``.

        The clone builds its own reader sources (and, lazily, its own
        loader thread pools); the parent keeps its own. Call `close`
        on datasets you no longer iterate to release their pools.
        """
        clone = XarrayWindowDataset.__new__(XarrayWindowDataset)
        clone.__dict__.update(self.__dict__)
        clone.split = split
        clone.sample_origins = _split_origins(
            self._all_origins, split, self._split_guard
        )
        clone._grain_source = clone._build_grain_source()
        clone._block_sources = []
        return clone

    def close(self) -> None:
        """Release the loader thread pools held by this dataset's sources.

        Each reader source lazily creates a large `ThreadPoolExecutor` on
        first read; without an explicit close those threads are only
        reclaimed by the garbage collector. This covers the per-example
        source and every block-reader source `build_batch_iter` handed
        out. Safe to call repeatedly; the pools are rebuilt on the next
        read if the dataset is used again.
        """
        self._grain_source.close()
        for source in self._block_sources:
            source.close()

    # --- reproducibility ----------------------------------------------------

    def content_hash(self) -> str:
        # NB: block_reader / buffer / shard params are deliberately NOT hashed —
        # they change iteration order / sharding, not the logical (x, y) set.
        return hash_config(
            "XarrayWindowDataset",
            {
                "store_version": self.store_version,
                "stencils": {k: s.get_config() for k, s in self.stencils.items()},
                "var_order": self.var_order,
                "views": {
                    name: _source_view(ds, self.sample_dim)
                    for name, ds in self.source.items()
                },
                "origins_sha": array_digest(self.sample_origins),
                "sample_dim": self.sample_dim,
                "seed": self.seed,
                "split": self.split,
            },
        )

    def get_config(self) -> dict[str, Any]:
        return {
            "sample_dim": self.sample_dim,
            "store_version": self.store_version,
            "stencils": {k: s.get_config() for k, s in self.stencils.items()},
            "var_order": self.var_order,
            "n_origins": len(self.sample_origins),
            "block_reader": self.block_reader,
            "seed": self.seed,
            "split": self.split,
        }

build_batch_iter(batch_size, seed)

Adapter hook (see adapters/equinox.py _BatchSource).

Returns a checkpointable Grain iterator yielding collated, batched (X, Y) pairs via the block reader, or None to decline so the adapter falls back to the per-example indexable path. Declines unless block_reader=True.

Source code in packages/geotoolz-patcher/src/geopatcher/integrations/train.py
def build_batch_iter(self, batch_size: int, seed: int) -> Any:
    """Adapter hook (see ``adapters/equinox.py`` ``_BatchSource``).

    Returns a checkpointable Grain *iterator* yielding collated, batched
    ``(X, Y)`` pairs via the block reader, or ``None`` to decline so the
    adapter falls back to the per-example indexable path. Declines unless
    ``block_reader=True``.
    """
    if not self.block_reader:
        return None
    shard_index, shard_count = self._resolve_shards()
    iter_ds, block_source = _xreader.training_iterator(
        self.source,
        self.stencils,
        self.sample_origins,
        sample_dim=self.sample_dim,
        num_epochs=None,
        buffer_size_in_bytes=self.buffer_size_in_bytes,
        buffer_diversity=self.buffer_diversity,
        shard_index=shard_index,
        shard_count=shard_count,
        seed=seed,
    )
    self._block_sources.append(block_source)
    iter_ds = iter_ds.map(self._collate_pair).batch(batch_size, drop_remainder=True)
    return iter(iter_ds)

close()

Release the loader thread pools held by this dataset's sources.

Each reader source lazily creates a large ThreadPoolExecutor on first read; without an explicit close those threads are only reclaimed by the garbage collector. This covers the per-example source and every block-reader source build_batch_iter handed out. Safe to call repeatedly; the pools are rebuilt on the next read if the dataset is used again.

Source code in packages/geotoolz-patcher/src/geopatcher/integrations/train.py
def close(self) -> None:
    """Release the loader thread pools held by this dataset's sources.

    Each reader source lazily creates a large `ThreadPoolExecutor` on
    first read; without an explicit close those threads are only
    reclaimed by the garbage collector. This covers the per-example
    source and every block-reader source `build_batch_iter` handed
    out. Safe to call repeatedly; the pools are rebuilt on the next
    read if the dataset is used again.
    """
    self._grain_source.close()
    for source in self._block_sources:
        source.close()

with_split(split)

Return a clone of this dataset restricted to split.

The clone builds its own reader sources (and, lazily, its own loader thread pools); the parent keeps its own. Call close on datasets you no longer iterate to release their pools.

Source code in packages/geotoolz-patcher/src/geopatcher/integrations/train.py
def with_split(self, split: Split) -> XarrayWindowDataset:
    """Return a clone of this dataset restricted to ``split``.

    The clone builds its own reader sources (and, lazily, its own
    loader thread pools); the parent keeps its own. Call `close`
    on datasets you no longer iterate to release their pools.
    """
    clone = XarrayWindowDataset.__new__(XarrayWindowDataset)
    clone.__dict__.update(self.__dict__)
    clone.split = split
    clone.sample_origins = _split_origins(
        self._all_origins, split, self._split_guard
    )
    clone._grain_source = clone._build_grain_source()
    clone._block_sources = []
    return clone