Carrier helpers and contract checks¶
The helpers every geotoolz operator uses to keep the GeoArray carrier
contract, public so an operator written on top of the stack keeps it the same
way, and check_operator, which runs the package's own contract checks on any
operator. The rules are in Concepts and
Define an operator.
geoops.carrier
¶
The GeoArray carrier contract, as public helpers.
Every geotoolz operator keeps the same carrier rules: a geoarray.GeoArray
in comes back as a GeoArray on the input's grid (a plain array as a
plain array), with per-band metadata that matches the output bands and a
fill_value that marks its nodata; a georeader GeoTensor is refused,
naming geoarray.interop.georeader.from_georeader. These are the
helpers the built-in operators use to keep them; an operator you write on
top of the stack uses the same ones, so it composes with everything else.
The rules themselves are in the repository's AGENTS.md ("The two
contracts") and docs/operators/concepts.md.
Rewrap
wrap_like puts a result back on the input's carrier (transform=
for a new grid); INHERIT is its "take the input's fill" default.
Nodata
valid_pixels / invalid_values (a pixel is invalid when any band is
non-finite or equals the fill), mask_invalid_to_nan before NaN-aware
statistics, restore_fill / wrap_filled to write the output's fill
back, and carried_fill for an output that carries the input's values.
Bands
resolve_band / resolve_bands (an integer position or a name looked
up in band_names, descriptions, bands), band_names;
BandRef (the type of a band reference) and SENTINEL2_L2A_BANDS
(the canonical Sentinel-2 L2A band order).
Shape
band_axis, band_dim / dim_axis (an operator's dim=, and
where that dim sits in a carrier), require_ndim, map_frames /
over_frames (run a
per-scene function on each frame of a (T, C, H, W) stack),
keep_band_axis (a band-collapsing result keeps its time axis) and
single_band (pick one band as a 2-D plane).
Samples
cube_to_samples / samples_to_cube turn a (c, h, w) cube into
an (n, c) sample matrix for a per-pixel estimator and back;
sample_layout / SampleLayout describe the round trip.
Grids
require_geoarray, reject_geotensor (a georeader GeoTensor
carrier), reject_georeader (any georeader object, e.g. a raster an
operator holds in its constructor), require_projected_crs,
require_grid_match, grid_matches, affine_of (the transform as an
affine.Affine) and pixel_xy (map coordinates of pixel centres).
Dtypes and fitting
as_float (promote integer DNs before arithmetic) and fit_once
(fit on first call, once, without races).
Config
The operator side of the contract: jsonable coerces a
get_config() value to JSON builtins, as_tuple turns lists back
into tuples on reload, mapping_to_pairs / mapping_from_pairs
carry non-string-keyed mappings, nested_config / callable_name
describe a nested operator or a callable, and reject_config_summary
refuses a debug summary passed back to a constructor.
Coupling
Coupling is the record an operator class declares as coupling:
the dims its output reads across (band, level, space,
time), what it does to each, its spatial reach and the dims a fit
reads. reach_of gives an operator's reach (spatial_reach() when
it depends on an argument). geoops.testing.measure_coupling and
geoops.testing.assert_coupling check a declaration.
Optional dependencies
optional_module imports an extra's module inside the function that
needs it, with an error naming the extra; optional_name is the
from a import b form and optional_root the import a.b one.
Example
An operator that keeps the carrier contract::
import numpy as np
from pipekit_ops import Operator
from geoops.carrier import mask_invalid_to_nan, over_frames, wrap_like
class ZScore(Operator):
backends = ("numpy",) # refuses JAX carriers (pipekit's check)
def __init__(self, *, mean: float, std: float) -> None:
self.mean = mean
self.std = std
@over_frames # (T, C, H, W) stacks run frame by frame
def _apply(self, gt): # (C, H, W) -> (C, H, W) float
values = mask_invalid_to_nan(gt) # nodata -> NaN, whole pixel
out = (values - self.mean) / self.std
return wrap_like(gt, out, fill_value=np.nan)
Check it with geoops.testing.check_operator.
Coupling
dataclass
¶
Which dims an operator's output reads across, and what it does to each.
An operator class declares it as coupling, beside backends.
geoops.testing.assert_coupling checks it against a measurement.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
couples
|
Iterable[str]
|
The dims along which an output depends on two or more input values once any state is fitted (K_apply). |
()
|
effects
|
Mapping[str, str] | Iterable[tuple[str, str]]
|
What the operator does to each dim it changes ( |
()
|
reach
|
int | None
|
The spatial reach in pixels at the default settings: the
largest distance between an output pixel and an input pixel it
depends on. |
0
|
fit
|
Iterable[str]
|
The further dims a fitted state is estimated over, beyond
|
()
|
kind
|
str
|
|
'transform'
|
reads_values
|
bool
|
|
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
An unknown dim, effect or kind; a dim both coupled and fitted; a reach that does not fit the coupled dims. |
Example
ndvi = Coupling(couples={"band"}, effects={"band": "reduce"}) ndvi.name, ndvi.effect("band"), ndvi.effect("space") ('spectral', 'reduce', 'keep') Coupling(fit={"space"}).name 'pointwise'
Source code in packages/geotoolz-ops/src/geoops/_src/coupling.py
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 | |
name
property
¶
The class name of couples: "pointwise", "spectral", …
SampleLayout
dataclass
¶
How a cube was flattened by :func:cube_to_samples.
Attributes:
| Name | Type | Description |
|---|---|---|
shape |
tuple[int, ...]
|
Shape of the original cube. |
sample_axes |
tuple[int, ...]
|
Axes (non-negative) flattened into rows, in row-major order. |
band_axes |
tuple[int, ...]
|
Axes (non-negative) flattened into columns, in order; empty when the cube has no band axis (one column). |
Source code in packages/geotoolz-ops/src/geoops/_src/samples.py
affine_of(x)
¶
The transform of x as an affine.Affine (~T, T * (c, r)).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
A |
required |
Returns:
| Type | Description |
|---|---|
Affine
|
The |
Example
import numpy as np from geoarray import GeoArray g = GeoArray(np.zeros((2, 2)), (10, 0, 500000, 0, -10, 4e6), 32629) affine_of(g).c 500000.0
Source code in packages/geotoolz-ops/src/geoops/_src/geo.py
as_float(arr, min_dtype=np.float32)
¶
Promote integer / boolean arr to floating point before arithmetic.
Floating-point (and complex) input is returned unchanged, without a
copy. Anything else is cast to np.result_type(arr, min_dtype):
with the default float32 floor, (u)int8 / (u)int16 /
bool become float32 and wider integers become float64.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
Num[ndarray, '*dims'] | Shaped[ndarray, '*dims']
|
Any numeric array-like. |
required |
min_dtype
|
DTypeLike
|
Smallest float dtype integer input is promoted to.
Default |
float32
|
JAX and dask arrays (an Array API array with a dtype) stay on their
backend, so a kernel can promote its input under jax.jit; anything
without a dtype goes through np.asarray first.
Returns:
| Type | Description |
|---|---|
Float[ndarray, '*dims']
|
A floating-point array with the same shape and values, on the |
Float[ndarray, '*dims']
|
input's backend. |
Source code in packages/geotoolz-ops/src/geoops/_src/dtype.py
as_tuple(value)
¶
Normalise a list or tuple constructor argument to a tuple.
JSON and YAML have no tuple type, so a config reloaded through
Operator.from_state hands the constructor a list where a tuple
was emitted. Constructors call this on tuple-typed parameters so the
reloaded operator is identical; scalars and None pass through.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
The constructor argument. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
|
Any
|
|
Source code in packages/geotoolz-ops/src/geoops/_src/config.py
band_axis(arr)
¶
Axis holding the bands of a 3-D or 4-D carrier: always -3.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
Any
|
A |
required |
Returns:
| Type | Description |
|---|---|
int
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> band_axis(np.zeros((2, 3, 4, 4)))
-3
>>> np.zeros((2, 3, 4, 4)).shape[band_axis(np.zeros((2, 3, 4, 4)))]
3
Source code in packages/geotoolz-ops/src/geoops/_src/shape.py
band_dim(dim, axis, name, *, legacy=(BAND_AXIS,))
¶
The dim an operator works over, from dim= or the deprecated axis=.
axis= keeps working for one release: a band position in legacy
(-3, or 0 for the per-frame skimage wrappers) maps to
"band" with a DeprecationWarning.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dim
|
str | None
|
The |
required |
axis
|
int | None
|
The deprecated |
required |
name
|
str
|
Operator name for the messages. |
required |
legacy
|
tuple[int, ...]
|
The old band positions that map to |
(BAND_AXIS,)
|
Returns:
| Type | Description |
|---|---|
str | None
|
The dim name, or |
Raises:
| Type | Description |
|---|---|
ValueError
|
|
Examples:
Source code in packages/geotoolz-ops/src/geoops/_src/shape.py
band_names(gt, *, keys=DEFAULT_BAND_KEYS)
¶
The carrier's band names, read from the first usable attrs key.
Keys are consulted in keys order (default
:data:DEFAULT_BAND_KEYS: band_names, then descriptions, then
bands); the first one holding a sequence or a {name: index}
mapping wins. A mapping keeps its declared positions: entry i is
the name mapped to band i, or None for a band the mapping
does not name, and the list is padded to the carrier's band count.
When several names map to one band (aliases), the first one wins.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gt
|
GeoArray | ndarray | Any
|
A GeoArray-like carrier with |
required |
keys
|
tuple[str, ...]
|
Attribute keys to consult, in precedence order. |
DEFAULT_BAND_KEYS
|
Returns:
| Type | Description |
|---|---|
list[str | None] | None
|
The names as |
list[str | None] | None
|
has no |
list[str | None] | None
|
band names. |
Examples:
>>> import numpy as np
>>> class Carrier:
... attrs = {"descriptions": ("red", "nir"), "band_names": ["B04", "B08"]}
>>> band_names(Carrier())
['B04', 'B08']
>>> band_names(np.zeros((2, 3, 3))) is None
True
Source code in packages/geotoolz-ops/src/geoops/_src/bands.py
carried_fill(ref, dtype)
¶
Fill value for an output that carries ref's values in dtype.
For value-preserving operators (filters, scalings, resampling, casts)
whose output may change dtype. Operators whose output means
something new pass the canonical fill for that meaning instead
(False / 0 / NaN; see the module docstring).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ref
|
Any
|
The operator's input carrier. |
required |
dtype
|
Any
|
The output dtype. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
|
Any
|
|
Any
|
(the integer fill would collide with promoted real data, e.g. |
Any
|
|
Any
|
integer output, |
Any
|
|
Examples:
>>> carried_fill(np.zeros(2, dtype=np.uint16), np.float32) is None
True
>>> carried_fill(np.zeros(2), bool)
False
Source code in packages/geotoolz-ops/src/geoops/_src/valid.py
cube_to_samples(arr, *, band_axis=-3, sample_axes=None, dtype=None)
¶
Flatten a cube into an (n_samples, n_bands) matrix.
For a canonical (c, h, w) cube this is einx.id("c h w -> (h w)
c"); a (t, c, h, w) stack with the default band_axis=-3
yields t * h * w rows. Nodata is not dropped: NaN / fill pixels
stay in their rows so :func:samples_to_cube can put per-row
results back in place (filter rows with e.g.
np.isfinite(samples).all(axis=1)).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
Shaped[ndarray, '*dims']
|
Input array (any array-like), at least 1-D. |
required |
band_axis
|
int | tuple[int, ...]
|
The band (feature) axis, or a tuple of axes flattened
together into the columns in the given order. |
-3
|
sample_axes
|
tuple[int, ...] | None
|
Axes flattened into rows, in row-major order. Defaults to every non-band axis in ascending order. |
None
|
dtype
|
DTypeLike | None
|
Optional dtype to coerce |
None
|
Returns:
| Type | Description |
|---|---|
``(samples, layout)``
|
the |
SampleLayout
|
class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the axes are out of range, repeated, or do not
cover every axis of |
Source code in packages/geotoolz-ops/src/geoops/_src/samples.py
dim_axis(x, dim, *, name)
¶
The (negative) position of dim in x.
A GeoArray answers from its stored dims; a plain array is read in the
0.2 layout, DIMS[-ndim:]. A 2-D input without a band dim (a
single-band map) answers -3, the 0.2 band position, as before.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
The carrier, or a plain array. |
required |
dim
|
str
|
The dim name. |
required |
name
|
str
|
Operator name for the message. |
required |
Returns:
| Type | Description |
|---|---|
int
|
The axis, counted from the end ( |
int
|
|
int
|
stack. |
Raises:
| Type | Description |
|---|---|
ValueError
|
No |
Examples:
Source code in packages/geotoolz-ops/src/geoops/_src/shape.py
fit_once(op, x, is_fitted)
¶
Call op.fit(x) unless is_fitted(); at most once across threads.
Double-checked: the cheap unlocked check keeps already-fitted calls
lock-free; the locked re-check makes concurrent first calls fit once.
op.fit must publish its state only after computing all of it.
Source code in packages/geotoolz-ops/src/geoops/_src/fitted.py
grid_matches(a, b, *, atol=0.0, spatial_only=True)
¶
Return whether two rasters share a pixel grid.
Semantics (the one definition used package-wide):
- Shape -- the spatial shape
shape[-2:]must be equal; withspatial_only=Falsethe full shape must be equal (band / time axes included), for per-pixel reductions over a stack. - Georeferencing -- only when both sides carry a
transform(plain arrays have no georeferencing, so the check degrades to the shape comparison). Then the CRS must compare equal and the six affine coefficients must agree withinatol(absolute, no relative term):np.allclose(a.transform, b.transform, rtol=0, atol=atol).
The default atol=0.0 is exact equality: sub-pixel grid drift is a
real bug source and fails loudly. Pass a small atol explicitly
where float round-off in derived transforms must be tolerated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
Any
|
First raster (GeoArray or plain array). |
required |
b
|
Any
|
Second raster. |
required |
atol
|
float
|
Absolute tolerance on each transform coefficient, in CRS
units. |
0.0
|
spatial_only
|
bool
|
Compare only the trailing |
True
|
Returns:
| Type | Description |
|---|---|
bool
|
|
Raises:
| Type | Description |
|---|---|
TypeError
|
Either side is a georeader |
Source code in packages/geotoolz-ops/src/geoops/_src/geo.py
invalid_values(x, *, fill_value=INHERIT)
¶
Elementwise invalid mask: non-finite, or equal to the fill value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
A carrier (GeoArray or plain array) of any shape. |
required |
fill_value
|
FillValue
|
Fill value to match. :data: |
INHERIT
|
Returns:
| Type | Description |
|---|---|
Bool[ndarray, '*dims']
|
A boolean array shaped like |
Source code in packages/geotoolz-ops/src/geoops/_src/valid.py
jsonable(value, *, strict=False)
¶
Recursively coerce a config value into JSON/YAML-safe builtins.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Any |
required |
strict
|
bool
|
What to do with anything left over. |
False
|
Returns:
| Type | Description |
|---|---|
Any
|
A structure of dicts, lists, and JSON-safe scalars. |
Source code in packages/geotoolz-ops/src/geoops/_src/config.py
keep_band_axis(out, ref)
¶
Keep the time axis of a band-collapsing result on a 4-D input.
Operators that collapse the band axis (a spectral index, a score map)
turn (C, H, W) into (H, W). The same reduction over a
(T, C, H, W) stack gives (T, H, W), which every carrier would
read as (band, y, x); re-inserting a singleton band axis keeps it a
time series of single-band maps.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
out
|
Any
|
The reduced result. |
required |
ref
|
Any
|
The operator input. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
|
Any
|
4-D and |
Examples:
>>> keep_band_axis(np.zeros((2, 4, 4)), np.zeros((2, 3, 4, 4))).shape
(2, 1, 4, 4)
>>> keep_band_axis(np.zeros((4, 4)), np.zeros((3, 4, 4))).shape
(4, 4)
Source code in packages/geotoolz-ops/src/geoops/_src/shape.py
map_frames(fn, x, *, name)
¶
Apply a per-scene function to every frame of a (T, C, H, W) stack.
For operators whose semantics are per scene (a segmentation, a QA
decode, a colour composite): the result is exactly the per-frame
results restacked along a new leading time axis. A time series is a
GeoArray whose first dim is named time (("time", "band", "y",
"x") or a single-band ("time", "y", "x")), or a 4-D plain array.
On a stack with bands, a 2-D per-frame result gains a singleton band
axis ((T, 1, H, W), see :func:keep_band_axis); a single-band
series stays ("time", "y", "x").
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
Callable[[Any], Any]
|
Function of one |
required |
x
|
Any
|
The input. Only a time series is split; anything else is passed
to |
required |
name
|
str
|
Operator name for error messages. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The |
Any
|
like the first frame's result, with its attrs and fill value) when |
Any
|
the per-frame results are GeoArrays, else an ndarray. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a per-frame result is not a 2-D / 3-D array, or the frames' results differ in shape or grid. |
Source code in packages/geotoolz-ops/src/geoops/_src/shape.py
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 | |
mapping_from_pairs(value)
¶
Accept a mapping or its [[key, value], ...] config form.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Mapping[Any, Any] | Iterable[Any] | None
|
A mapping, an iterable of |
required |
Returns:
| Type | Description |
|---|---|
dict[Any, Any] | None
|
A |
Raises:
| Type | Description |
|---|---|
ValueError
|
if an item of the iterable form is not a pair. |
Source code in packages/geotoolz-ops/src/geoops/_src/config.py
mapping_to_pairs(mapping)
¶
Emit a mapping config value as [[key, value], ...].
Operator.from_state rejects dict config values (they are reserved
for nested-operator payloads) and JSON would stringify non-string
keys, so mapping-valued parameters are emitted as a list of pairs.
Constructors accept that form back through :func:mapping_from_pairs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mapping
|
Mapping[Any, Any] | None
|
The mapping to emit, or |
required |
Returns:
| Type | Description |
|---|---|
list[list[Any]] | None
|
A JSON-safe list of |
Source code in packages/geotoolz-ops/src/geoops/_src/config.py
mask_invalid_to_nan(x, *, fill_value=INHERIT, valid=None, dtype=None)
¶
Float copy of x with every invalid pixel set to NaN in all bands.
The result feeds np.nan* reductions (and NaN-propagating filters)
so fill pixels never enter a statistic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
A carrier (GeoArray or plain array) with >= 2 dims. |
required |
fill_value
|
FillValue
|
Fill value override (see :func: |
INHERIT
|
valid
|
ndarray | None
|
Precomputed validity mask -- |
None
|
dtype
|
Any
|
Float dtype of the result. |
None
|
Returns:
| Type | Description |
|---|---|
Float[ndarray, '*dims']
|
A new float ndarray shaped like |
Source code in packages/geotoolz-ops/src/geoops/_src/valid.py
optional_module(module, extra, *, feature)
¶
Import module, or raise an ImportError naming the extra.
It is pipekit_ops.import_optional with geotoolz-ops's install command. A module
that is installed and fails while it is imported raises its own error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
module
|
str
|
Dotted module name to import (e.g. |
required |
extra
|
str
|
The geotoolz extra that provides it (e.g. |
required |
feature
|
str
|
What needs it, for the message (e.g. |
required |
Returns:
| Type | Description |
|---|---|
ModuleType
|
The imported module. |
Raises:
| Type | Description |
|---|---|
ImportError
|
|
Source code in packages/geotoolz-ops/src/geoops/_src/optional.py
optional_name(module, name, extra, *, feature)
¶
from module import name lazily, with the extra's install hint.
name may be an attribute of module or one of its submodules
(from georeader import read).
Example
optional_name("json", "decoder", "base", feature="doc").name 'json.decoder'
Source code in packages/geotoolz-ops/src/geoops/_src/optional.py
optional_root(module, extra, *, feature)
¶
import a.b lazily: import module and return its top package a.
Example
optional_root("json.decoder", "base", feature="doc").name 'json'
Source code in packages/geotoolz-ops/src/geoops/_src/optional.py
over_frames(apply)
¶
Decorate an operator's _apply to run per frame on a time series.
@over_frames on def _apply(self, x, ...) routes a time series
(a carrier led by a time dim, or a 4-D plain array) through
:func:map_frames (each frame handled by the undecorated _apply,
named after the operator class in errors); other inputs are
unaffected. The wrapper keeps the
wrapped signature, so pipekit's input introspection is unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
apply
|
Callable[..., Any]
|
The |
required |
Returns:
| Type | Description |
|---|---|
Callable[..., Any]
|
The wrapped method. |
Source code in packages/geotoolz-ops/src/geoops/_src/shape.py
pixel_xy(transform, rows, cols)
¶
Return CRS coordinates of pixel centres, vectorised.
Pixel (row, col) covers [row, row + 1) x [col, col + 1) in
pixel space, so its centre is (row + 0.5, col + 0.5). Fractional
rows / cols (e.g. sub-pixel contour vertices) are offset the
same way.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transform
|
Any
|
The geotransform mapping |
required |
rows
|
Any
|
Row indices (scalar or array). |
required |
cols
|
Any
|
Column indices, broadcastable against |
required |
Returns:
| Type | Description |
|---|---|
Float[ndarray, ...]
|
|
Float[ndarray, ...]
|
|
Source code in packages/geotoolz-ops/src/geoops/_src/geo.py
reach_of(op)
¶
op's spatial reach in pixels; None for a global one.
op.spatial_reach() when the operator defines it (a reach that depends
on a constructor argument), else op.coupling.reach.
Raises:
| Type | Description |
|---|---|
TypeError
|
|
Example
class Box3: ... coupling = Coupling(couples={"space"}, reach=1) reach_of(Box3()) 1
Source code in packages/geotoolz-ops/src/geoops/_src/coupling.py
reject_config_summary(value, name)
¶
Refuse a debug summary passed back as a runtime constructor argument.
Operators with an optional runtime argument (an array, a callable)
stay reloadable when it is unset, and summarise it as a dict in
get_config when it is set. Operator.from_state refuses dict
values, but a YAML / Hydra loader would hand the summary back to the
constructor; this turns that into a clear error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
The constructor argument. |
required |
name
|
str
|
Parameter name for the error message. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
|
Raises:
| Type | Description |
|---|---|
TypeError
|
if |
Source code in packages/geotoolz-ops/src/geoops/_src/config.py
reject_georeader(x, op_name='geotoolz')
¶
Raise TypeError for any georeader object; pass anything else.
A GeoTensor gets reject_geotensor's message (convert it with
from_georeader); any other georeader object (a reader, a
GeoData) is told to wrap it with source_from_georeader.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
The value to check. |
required |
op_name
|
str
|
Who refuses it, for the message. |
'geotoolz'
|
Raises:
| Type | Description |
|---|---|
TypeError
|
|
Source code in packages/geotoolz-ops/src/geoops/_src/geo.py
reject_geotensor(x, op_name='geotoolz')
¶
Raise TypeError for a georeader GeoTensor; pass anything else.
A GeoTensor is an np.ndarray subclass, so np.asarray would
take it silently as a plain array and the output would lose its
georeferencing. geotoolz takes geoarray.GeoArray instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
The value to check. |
required |
op_name
|
str
|
Who refuses it, for the message. |
'geotoolz'
|
Raises:
| Type | Description |
|---|---|
TypeError
|
|
Source code in packages/geotoolz-ops/src/geoops/_src/geotensor.py
require_geoarray(x, op_name, *, arg='input', hint='')
¶
Return x if it is a GeoArray, else raise a clear TypeError.
Geo-dependent operators (reprojection, rasterisation, metre-based
measurements, ...) are only meaningful with an affine transform
attached, so a plain array is refused (and a GeoTensor is refused
naming from_georeader).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
The carrier to check. |
required |
op_name
|
str
|
Operator name, used as the message prefix. |
required |
arg
|
str
|
Which argument |
'input'
|
hint
|
str
|
Optional extra sentence appended to the message (e.g. how to call the plain-array primitive instead). |
''
|
Returns:
| Type | Description |
|---|---|
GeoArray
|
|
Raises:
| Type | Description |
|---|---|
TypeError
|
|
Source code in packages/geotoolz-ops/src/geoops/_src/geo.py
require_grid_match(a, b, op_name, *, names=('input', 'other'), atol=0.0, spatial_only=True)
¶
Raise unless two carriers of a multi-input operator share a pixel grid.
The one guard behind every multi-input operator (#141): the carriers
are combined pixel by pixel, so a second carrier on another grid (a
20 m mask against a 10 m enhancement, a DEM over a neighbouring
tile) would give a silently wrong answer. Semantics are those of
:func:grid_matches.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
Any
|
The primary carrier. |
required |
b
|
Any
|
The second carrier. |
required |
op_name
|
str
|
Operator name for the error message. |
required |
names
|
tuple[str, str]
|
How the message refers to |
('input', 'other')
|
atol
|
float
|
Absolute tolerance on each transform coefficient. |
0.0
|
spatial_only
|
bool
|
Compare only the trailing |
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
The grids differ; the message names the operator and both grids. |
Source code in packages/geotoolz-ops/src/geoops/_src/geo.py
require_ndim(arr, allowed, name)
¶
Raise a clear ValueError unless arr has an accepted rank.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
Any
|
The operator input (any array-like; only its rank is read). |
required |
allowed
|
int | Iterable[int]
|
Accepted number(s) of dimensions. |
required |
name
|
str
|
Operator name, placed at the start of the message so the
failure is attributable (e.g. |
required |
Returns:
| Type | Description |
|---|---|
int
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> require_ndim(np.zeros((3, 4, 4)), (2, 3), "PhaseAlign")
3
>>> require_ndim(np.zeros((2, 3, 4, 4)), (2, 3), "PhaseAlign")
Traceback (most recent call last):
...
ValueError: PhaseAlign accepts 2-D (H, W) or 3-D (C, H, W) input; ...
Source code in packages/geotoolz-ops/src/geoops/_src/shape.py
require_projected_crs(gt, op_name, *, what='areas and distances', metres=True)
¶
Raise unless gt is in a projected CRS (with metre units).
Operators that treat the affine transform as a length (pixel areas, distances, slopes) would silently work in degrees on a geographic CRS, so it is rejected with a hint to reproject first. A carrier without a CRS is accepted as-is: its transform is then assumed to be linear.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gt
|
Any
|
Georeferenced carrier (anything exposing |
required |
op_name
|
str
|
Operator name used in the error message. |
required |
what
|
str
|
What the operator computes, for the message ( |
'areas and distances'
|
metres
|
bool
|
Also require metre linear units (default). Pass
|
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the CRS is geographic (or otherwise not
projected), or -- with |
Source code in packages/geotoolz-ops/src/geoops/_src/geo.py
resolve_band(gt, ref, *, keys=DEFAULT_BAND_KEYS, fallback=None)
¶
Resolve a band reference to an integer band-axis index.
This is the one band-name resolver every operator family uses, so
"B04" means the same band in indices, spectral, qa,
augment, viz, compositing and plume.
Integer references (any :class:numbers.Integral except bool,
so np.int64 works) pass through as int for any carrier —
plain ndarrays included. String references are looked up against
gt.attrs[key] for each key in keys (in order). The first
key whose names contain the requested one wins; a key that exists
but doesn't contain the name hands over to the next key. Each value
may be a sequence of names (position = band index) or a
{name: index} mapping. Missing keys, None values and
non-iterable values are skipped silently.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gt
|
GeoArray | ndarray | Any
|
Carrier |
required |
ref
|
BandRef
|
An integer index (returned as |
required |
keys
|
tuple[str, ...]
|
Attribute keys to consult, in precedence order. Defaults
to :data: |
DEFAULT_BAND_KEYS
|
fallback
|
Sequence[str] | None
|
Band names in array order, used only when |
None
|
Returns:
| Type | Description |
|---|---|
int
|
The integer position of the band along the carrier's band axis. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If |
Examples:
>>> import numpy as np
>>> from geoarray import GeoArray
>>> gt = GeoArray(
... np.zeros((4, 2, 2), dtype=np.float32),
... (1.0, 0.0, 0.0, 0.0, -1.0, 0.0),
... "EPSG:4326",
... attrs={"band_names": ("B02", "B03", "B04", "B08")},
... )
>>> resolve_band(gt, "B04")
2
>>> resolve_band(gt, np.int64(7)) # integers pass through as int
7
Source code in packages/geotoolz-ops/src/geoops/_src/bands.py
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 | |
resolve_bands(gt, refs, *, keys=DEFAULT_BAND_KEYS, fallback=None)
¶
Resolve several band references with :func:resolve_band.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gt
|
GeoArray | ndarray | Any
|
Carrier whose |
required |
refs
|
Iterable[BandRef]
|
Integer indices and/or band names, in output order. |
required |
keys
|
tuple[str, ...]
|
Attribute keys to consult, in precedence order. |
DEFAULT_BAND_KEYS
|
fallback
|
Sequence[str] | None
|
Plain-array fallback names (see :func: |
None
|
Returns:
| Type | Description |
|---|---|
list[int]
|
One integer index per reference, in |
Examples:
>>> class Carrier:
... attrs = {"band_names": ["B02", "B03", "B04"]}
>>> resolve_bands(Carrier(), ["B04", 0, "B03"])
[2, 0, 1]
Source code in packages/geotoolz-ops/src/geoops/_src/bands.py
restore_fill(out, valid, fill_value)
¶
Write fill_value into every invalid pixel of an operator output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
out
|
Any
|
The operator's computed output, |
required |
valid
|
ndarray
|
Validity mask from :func: |
required |
fill_value
|
Any
|
The output's fill value. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
A copy of |
ndarray
|
fill value. When every pixel is valid, |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in packages/geotoolz-ops/src/geoops/_src/valid.py
sample_layout(shape, *, band_axis=-3, sample_axes=None)
¶
The :class:SampleLayout :func:cube_to_samples uses for shape.
Lets a caller that only kept the cube's shape rebuild the layout for
:func:samples_to_cube. Arguments as in :func:cube_to_samples.
Raises:
| Type | Description |
|---|---|
ValueError
|
If the axes are out of range, repeated, or do not cover every axis exactly once. |
Source code in packages/geotoolz-ops/src/geoops/_src/samples.py
samples_to_cube(samples, layout)
¶
Inverse of :func:cube_to_samples for per-row results.
samples may have any number of columns k (e.g. scores,
components, cluster probabilities), not only the original band
count. The sample axes are restored in their original (ascending)
order and the k columns become a single axis at the position of
the first band axis -- the leading axis when the layout had no band
axis. A 1-D samples restores just the sample axes. For a
single-band-axis layout and k equal to the band count this is the
exact inverse of :func:cube_to_samples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
samples
|
Shaped[ndarray, ' n'] | Shaped[ndarray, 'n k']
|
|
required |
layout
|
SampleLayout
|
The layout returned by :func: |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
The reshaped array. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in packages/geotoolz-ops/src/geoops/_src/samples.py
single_band(values, *, name='input')
¶
Return the 2-D view of a single-band array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
Shaped[ndarray, 'h w'] | Shaped[ndarray, '1 h w']
|
A |
required |
name
|
str
|
Label used in the error message so callers can attribute
the failure to their own operator (e.g. |
'input'
|
Returns:
| Type | Description |
|---|---|
Shaped[ndarray, 'h w']
|
The |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in packages/geotoolz-ops/src/geoops/_src/shape.py
valid_pixels(x, *, fill_value=INHERIT, keep_time=False)
¶
Boolean validity mask over the spatial grid of x.
A pixel is valid when every band at that location is finite and
differs from the fill value (see the module docstring for why "any
band invalid" invalidates the pixel). Like GeoArray.valid_mask,
this recognises NaN fills and non-finite values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
|
required |
fill_value
|
FillValue
|
Fill value override; defaults to
|
INHERIT
|
keep_time
|
bool
|
For a 4-D input, return a per-frame |
False
|
Returns:
| Type | Description |
|---|---|
Bool[ndarray, '*spatial']
|
|
Bool[ndarray, '*spatial']
|
input); |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> cube = np.array([[[1.0, np.nan]], [[2.0, 3.0]]]) # (2, 1, 2)
>>> valid_pixels(cube).tolist()
[[True, False]]
Source code in packages/geotoolz-ops/src/geoops/_src/valid.py
wrap_filled(ref, out, *, fill_value, valid=None, **wrap_kwargs)
¶
Write an explicit fill into ref's invalid pixels and rewrap out.
The one-call form of restore_fill + wrap_like that keeps the
declared fill_value in step with the values written.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ref
|
Any
|
The operator's input carrier. |
required |
out
|
Any
|
The computed output, on |
required |
fill_value
|
Any
|
The output's fill value ( |
required |
valid
|
ndarray | None
|
Validity mask (see :func: |
None
|
**wrap_kwargs
|
Any
|
Forwarded to :func: |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
|
Source code in packages/geotoolz-ops/src/geoops/_src/valid.py
wrap_like(ref, out, *, fill_value=INHERIT, attrs=None, transform=None, band_names=None, coords=None, crs=INHERIT, dims=None)
¶
Rewrap a computed array to match the carrier of ref.
On a JAX carrier a JAX result stays JAX (under jax.jit too); every
other result becomes a NumPy array, as on a NumPy carrier.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ref
|
GeoArray | ndarray
|
The operator's input carrier -- a |
required |
out
|
ndarray
|
The result array produced by a Tier-A primitive. Unless
|
required |
fill_value
|
FillValue
|
Fill value for the returned GeoArray. The default,
:data: |
INHERIT
|
attrs
|
Mapping[str, Any] | None
|
Attributes for the output. |
None
|
transform
|
Affine | Any | None
|
Transform for the output (an |
None
|
band_names
|
Sequence[str] | None
|
Names of the output bands, written under
|
None
|
coords
|
Sequence[Any] | None
|
Coordinates for the output's non-spatial dims. |
None
|
crs
|
Any
|
CRS for the output (anything |
INHERIT
|
dims
|
Sequence[str] | None
|
The output's dims, for an output whose non-spatial dims come
from another carrier than |
None
|
Returns:
| Type | Description |
|---|---|
GeoArray | ndarray
|
A new GeoArray with |
GeoArray | ndarray
|
otherwise |
Raises:
| Type | Description |
|---|---|
TypeError
|
|
ValueError
|
If |
Source code in packages/geotoolz-ops/src/geoops/_src/wrap.py
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 | |
geoops.testing
¶
Check that an operator keeps the stack's contracts.
check_operator runs, on one operator and one sample scene, the checks
geotoolz runs on every built-in operator (tests/test_operator_contract.py):
the pipekit Operator contract (keyword-only constructor, JSON config that
round-trips, graph mode) and the GeoArray carrier contract (same carrier
out, consistent per-band attrs, a fill that suits the output, the input
left untouched, (T, C, H, W) stacks handled or rejected, a georeader
GeoTensor refused, backends declared and kept). Use it in the
tests of an operator you write on top of the stack.
measure_coupling (and measure_frames for an N-ary reducer) measure
which dims an operator's output reads across by perturbing a sample, and
assert_coupling holds the operator's declared coupling to that
measurement.
Example
::
from geoops.testing import check_operator
def test_zscore(scene): # scene: GeoArray (C, H, W) with some nodata
out = check_operator(ZScore(mean=0.3, std=0.1), scene)
assert out.shape == scene.shape
Measured
dataclass
¶
What a perturbation probe saw. A lower bound on the true coupling.
Attributes:
| Name | Type | Description |
|---|---|---|
couples |
frozenset[str]
|
The dims an output moved across, with a fresh operator per run (a fit on first call fits on the perturbed input). |
frozen_space |
bool | None
|
Whether a change far from the centre still moved the
centre output through an operator fitted once on the unperturbed
input ( |
reach |
int | None
|
The largest pixel distance at which a one-pixel change moved
an output; |
regrids |
bool
|
The output is on another grid than the input. |
kind |
str
|
What came out: |
reads_values |
bool
|
Whether any perturbation moved the output. |
effects |
Mapping[str, str]
|
The measured effect on each dim that is not kept. |
time |
str | None
|
The time probe: |
stochastic |
bool
|
Two identical runs differ, so nothing above is reliable. |
notes |
tuple[str, ...]
|
Free-form remarks (bands not read, …). |
Source code in packages/geotoolz-ops/src/geoops/_src/coupling.py
name
property
¶
The class name of the measured couples.
assert_coupling(op, measured, *, exact=False)
¶
Assert that op's declared Coupling contains what was measured.
The rules, each a lower bound the declaration must meet:
- every measured coupled dim is declared, in
couplesorfit; - a change far away that moved the centre output needs a global
declaration (
reach=None), orspaceinfitwhen only a fresh operator moved; - a measured reach needs a declared reach at least as large (from
reach_of), unlessspaceis fitted; - a grid change needs
effects={"space": "regrid"}; - the declared
kindis the measured one (sourceandsinkare not measured); - an output that moved with the input's values is not declared
reads_values=False.
With exact=True the declared couples | fit must also equal the
measured couples. A stochastic measurement checks nothing, and neither
does a declared source: its output comes from its configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
op
|
Any
|
The operator (an instance; a class attribute is read through it). |
required |
measured
|
Measured
|
From |
required |
exact
|
bool
|
Require equality, not just containment. |
False
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
Naming the operator and every rule it breaks. |
Source code in packages/geotoolz-ops/src/geoops/_src/coupling.py
check_operator(op, sample, *others, gap_filler=False)
¶
Assert that op keeps the pipekit Operator and GeoArray contracts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
op
|
Any
|
The operator instance to check. |
required |
sample
|
Any
|
A |
required |
*others
|
Any
|
Further carriers of a multi-input operator, on |
()
|
gap_filler
|
bool
|
|
False
|
Returns:
| Type | Description |
|---|---|
Any
|
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
Naming the first broken rule. |
Source code in packages/geotoolz-ops/src/geoops/testing.py
measure_coupling(build, sample, *others, call=None)
¶
Measure which dims build()'s output reads across, on sample.
Four probes, each on a fresh operator from build (so a fit on first
call fits on the perturbed input):
- bump one band at the centre pixel, for each band: which outputs move gives the band dependence and the spatial reach;
- bump, darken and brighten a 3 x 3 block in the far corner: if the centre output moves, the operator reads the whole scene;
- probe 2 through an operator called once on
samplefirst, so a state fitted on first call is frozen (frozen_space); - on a two-frame
(T, C, H, W)stack of a 3-D GeoArraysample, bump frame 0: if frame 1's output moves, the operator pools overtime.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
build
|
Callable[[], Any]
|
Builds the operator, with no arguments (a lambda). |
required |
sample
|
Any
|
A raster the operator accepts, at least 12 x 12. A local
reach is read up to half the sample's side, so a larger sample
tells a longer reach from a global one. A |
required |
*others
|
Any
|
Further carriers of a multi-input operator, passed unchanged on every call. |
()
|
call
|
Callable[[Any, Any], Any] | None
|
|
None
|
Returns:
| Type | Description |
|---|---|
The `Measured` coupling
|
a lower bound. |
Example
import numpy as np from geoarray import GeoArray scene = GeoArray(np.ones((2, 16, 16)), (10, 0, 0, 0, -10, 0), 32629, ... dims="band y x") measure_coupling(lambda: (lambda x: x.map(np.sqrt)), scene).name 'pointwise'
Source code in packages/geotoolz-ops/src/geoops/_src/coupling.py
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 | |
measure_frames(build, frames, *, as_list=False)
¶
Measure an N-ary reducer: which input frames reach its output.
Each frame in turn gets its centre pixel bumped. Two or more frames
reaching the output is a time coupling; one is a selection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
build
|
Callable[[], Any]
|
Builds the operator, with no arguments. |
required |
frames
|
Sequence[Any]
|
The inputs, one per frame; an item may be a tuple whose
first element is the raster ( |
required |
as_list
|
bool
|
Call |
False
|
Returns:
| Type | Description |
|---|---|
Measured
|
The |
Example
import numpy as np frames = [np.full((16, 16), float(t)) for t in range(3)] mean = lambda: (lambda *xs: np.mean(np.stack(xs), axis=0)) measure_frames(mean, frames).name 'temporal'