Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Cache patch reads across runs

Skip the source reads when you rerun a patcher on the same data — while iterating on an operator, say. geopatcher.run.PatchCache is a content-addressed on-disk cache: the second process reads only the field’s domain metadata, never the pixels.

Cache a split

import numpy as np
import rasterio
from geoarray import GeoArray

import geopatcher as gp
from geopatcher.run import IndexedPatchView, PatchCache

field: gp.RasterField = gp.RasterField(
    GeoArray(
        np.random.default_rng(0).random((1, 256, 256), dtype=np.float32),  # (1, 256, 256) float32
        transform=rasterio.Affine(10, 0, 500_000, 0, -10, 4_300_000),
        crs="EPSG:32611",
    )
)
patcher: gp.SpatialPatcher = gp.SpatialPatcher(
    geometry=gp.spatial.geometry.Rectangular(size=(64, 64)),
    sampler=gp.spatial.sampler.RegularStride(step=(64, 64)),
    window=gp.spatial.window.Boxcar(),
    aggregation=gp.spatial.aggregation.OverlapAdd(),
)
cache: PatchCache = PatchCache(
    "./.geopatcher_cache",
    max_bytes=20 * 2**30,                               # 20 GiB, least recently used first out
    field_id="synthetic-scene",                         # in-memory fields need a stable name
)

run1: list[gp.Patch] = list(patcher.split(field, cache=cache))  # 16 reads, 16 entries written
run2: list[gp.Patch] = list(patcher.split(field, cache=cache))  # 16 hits, zero source reads
print(cache.stats())                                  # {'hits': 16, 'misses': 16, 'bytes': …, 'entries': 16}
view: IndexedPatchView = IndexedPatchView(patcher, field, cache=cache)  # random access, same cache

It composes with journal= and prefetch=, and with patcher.patch_at(field, anchor, cache=cache).

What the key covers

Each entry is keyed by sha256(field_id ‖ geometry and window config ‖ anchor). field_id covers everything the field reads:

A custom Field can define cache_id() -> str. It is trusted, not checked: it must change whenever the patches could. Raise geopatcher.run.UnstableIdentityError rather than return an identity that can change.

Pitfalls