Skip to content

Grid — geocatalog.grid

Pixel grids: convert between a GeoSlice and a pixel window, check and snap slices to a raster's grid, and count the whole pixels in a length.

Windows

geocatalog.grid.slice_to_window(slice_, transform)

Convert a CRS-unit GeoSlice to a pixel-space Window.

Lossy in the time / CRS axes — the returned Window carries neither.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/geoslice.py
def slice_to_window(slice_: GeoSlice, transform: Affine) -> Window:
    """Convert a CRS-unit ``GeoSlice`` to a pixel-space ``Window``.

    Lossy in the time / CRS axes — the returned ``Window`` carries
    neither.
    """
    return from_bounds(*slice_.bounds, transform=transform)

geocatalog.grid.window_to_slice(window, transform, crs, interval, resolution)

Inverse of slice_to_window. Mostly useful in tests and debugging.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/geoslice.py
def window_to_slice(
    window: Window,
    transform: Affine,
    crs: Any,
    interval: pd.Interval,
    resolution: tuple[float, float],
) -> GeoSlice:
    """Inverse of `slice_to_window`. Mostly useful in tests and debugging."""
    b = window_bounds(window, transform)
    return GeoSlice(bounds=b, interval=interval, resolution=resolution, crs=crs)

geocatalog.grid.PIXEL_PRECISION = 3 module-attribute

Grid alignment

geocatalog.grid.Align = Literal['off', 'warn', 'error', 'snap'] module-attribute

Construction-time alignment policy for GeoSlice.

  • "off": skip the check entirely (today's behaviour).
  • "warn": emit a GridAlignmentWarning via the standard library warnings module and continue with the original bounds.
  • "error": raise ValueError on the first misaligned axis.
  • "snap": round outward while preserving the affine origin (xmin and ymax for north-up rasters).

geocatalog.grid.is_grid_aligned(a, b, *, tol=None, explain=False)

Are a and b on the same pixel lattice?

Two slices are co-registered iff their resolutions match (within tol) and their per-axis origin offsets are congruent modulo resolution.

CRS mismatch returns False — the lattice question is undefined across CRSs. Reproject one side first via GeoSlice.to_crs if that's the intent.

Parameters:

Name Type Description Default
a GeoSlice

First slice.

required
b GeoSlice

Second slice.

required
tol float | None

Absolute tolerance (CRS units) for the resolution and origin checks. None (default) uses resolution * 10 ** -PIXEL_PRECISION per axis, i.e. a fixed fraction of one pixel.

None
explain bool

If True, return a dict with per-axis residuals and resolution-match booleans instead of a plain bool.

False

Returns:

Type Description
bool | dict[str, Any]

bool (or a diagnostic dict if explain=True).

Source code in packages/geotoolz-catalog/src/geocatalog/_src/grid.py
def is_grid_aligned(
    a: GeoSlice,
    b: GeoSlice,
    *,
    tol: float | None = None,
    explain: bool = False,
) -> bool | dict[str, Any]:
    """Are ``a`` and ``b`` on the same pixel lattice?

    Two slices are co-registered iff their resolutions match (within
    ``tol``) and their per-axis origin offsets are congruent modulo
    resolution.

    CRS mismatch returns ``False`` — the lattice question is undefined
    across CRSs. Reproject one side first via `GeoSlice.to_crs` if
    that's the intent.

    Args:
        a: First slice.
        b: Second slice.
        tol: Absolute tolerance (CRS units) for the resolution and
            origin checks. ``None`` (default) uses
            ``resolution * 10 ** -PIXEL_PRECISION`` per axis, i.e. a
            fixed fraction of one pixel.
        explain: If ``True``, return a dict with per-axis residuals
            and resolution-match booleans instead of a plain bool.

    Returns:
        ``bool`` (or a diagnostic dict if ``explain=True``).
    """
    rx_a, ry_a = a.resolution
    rx_b, ry_b = b.resolution
    # North-up affine origin is (xmin, ymax) — the top-left corner
    # — so the lattice question is about congruence of xmin and ymax
    # modulo resolution, not ymin.
    xmin_a, _, _, ymax_a = a.bounds
    xmin_b, _, _, ymax_b = b.bounds

    x_tol = tol if tol is not None else _default_tol(max(rx_a, rx_b))
    y_tol = tol if tol is not None else _default_tol(max(ry_a, ry_b))

    crs_match = a.crs == b.crs
    x_res_match = abs(rx_a - rx_b) <= x_tol
    y_res_match = abs(ry_a - ry_b) <= y_tol

    if x_res_match:
        x_off = (xmin_a - xmin_b) / rx_a
        x_origin_residual = (x_off - round(x_off)) * rx_a
        x_origin_match = abs(x_origin_residual) <= x_tol
    else:
        x_origin_residual = float("nan")
        x_origin_match = False

    if y_res_match:
        y_off = (ymax_a - ymax_b) / ry_a
        y_origin_residual = (y_off - round(y_off)) * ry_a
        y_origin_match = abs(y_origin_residual) <= y_tol
    else:
        y_origin_residual = float("nan")
        y_origin_match = False

    aligned = bool(
        crs_match and x_res_match and y_res_match and x_origin_match and y_origin_match
    )

    if explain:
        return {
            "aligned": aligned,
            "crs_match": crs_match,
            "x_res_match": x_res_match,
            "y_res_match": y_res_match,
            "x_origin_residual": float(x_origin_residual),
            "y_origin_residual": float(y_origin_residual),
        }
    return aligned

geocatalog.grid.GridAlignmentWarning

Bases: UserWarning

Emitted by GeoSlice for align="warn" and align="snap".

A dedicated subclass so applications can filter alignment notices independently of other UserWarning\ s — e.g. via warnings.simplefilter("error", GridAlignmentWarning) in tests or "ignore" in pipelines that have audited their slice sites.

Inherits from UserWarning so it is visible by default; unlike a loguru log record it is not silenced by the library's logger.disable("geocatalog") import-time hygiene.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/grid.py
class GridAlignmentWarning(UserWarning):
    """Emitted by `GeoSlice` for ``align="warn"`` and ``align="snap"``.

    A dedicated subclass so applications can filter alignment notices
    independently of other ``UserWarning``\\ s — e.g. via
    ``warnings.simplefilter("error", GridAlignmentWarning)`` in tests
    or ``"ignore"`` in pipelines that have audited their slice sites.

    Inherits from `UserWarning` so it is visible by default; unlike a
    loguru log record it is not silenced by the library's
    ``logger.disable("geocatalog")`` import-time hygiene.
    """

geocatalog.grid.count_steps(length, step, *, tol=None, label='length')

round(length/step), raising if not within tol of exact.

The "loud" counterpart to a bare round(L / r) — useful when a subpixel residual would silently shift a grid by a fraction of a pixel and surface much later as an off-by-one elsewhere.

Parameters:

Name Type Description Default
length float

numerator in CRS units (e.g. xmax - xmin).

required
step float

denominator in CRS units (e.g. x_res).

required
tol float | None

absolute tolerance (CRS units) on the residual q*step - length; None (default) uses step * 10 ** -PIXEL_PRECISION, i.e. a fixed fraction of one pixel.

None
label str

name of the dividend, surfaced in the error message.

'length'

Returns:

Type Description
int

Integer pixel count q.

Raises:

Type Description
ValueError

if |q*step - length| > tol.

Source code in packages/geotoolz-catalog/src/geocatalog/_src/grid.py
def count_steps(
    length: float,
    step: float,
    *,
    tol: float | None = None,
    label: str = "length",
) -> int:
    """``round(length/step)``, raising if not within ``tol`` of exact.

    The "loud" counterpart to a bare ``round(L / r)`` — useful when a
    subpixel residual would silently shift a grid by a fraction of a
    pixel and surface much later as an off-by-one elsewhere.

    Args:
        length: numerator in CRS units (e.g. ``xmax - xmin``).
        step: denominator in CRS units (e.g. ``x_res``).
        tol: absolute tolerance (CRS units) on the residual
            ``q*step - length``; ``None`` (default) uses
            ``step * 10 ** -PIXEL_PRECISION``, i.e. a fixed fraction of
            one pixel.
        label: name of the dividend, surfaced in the error message.

    Returns:
        Integer pixel count ``q``.

    Raises:
        ValueError: if ``|q*step - length| > tol``.
    """
    if tol is None:
        tol = _default_tol(step)
    q = int(np.round(length / step))
    residual = q * step - length
    if abs(residual) > tol:
        raise ValueError(
            f"{label}={length!r} is not an integer multiple of "
            f"step={step!r} (nearest is {q} -> residual "
            f"{residual:.6g}). Use align='snap' to round outward, or "
            f"fix the bounds/resolution."
        )
    return q