|
1 | 1 | from collections.abc import Callable, Sequence |
2 | | -from typing import Any, Protocol, TypeVar |
| 2 | +from typing import Any, Protocol, TypeVar, runtime_checkable |
3 | 3 |
|
4 | 4 | import numpy as np |
5 | 5 | from pydantic import ( |
@@ -34,6 +34,7 @@ def _wrap_validator( |
34 | 34 | return np.array(value, dtype=np.float64) |
35 | 35 |
|
36 | 36 |
|
| 37 | +@runtime_checkable |
37 | 38 | class SpaceProtocol(Protocol): |
38 | 39 | @property |
39 | 40 | def axes(self) -> tuple[str, ...]: ... |
@@ -72,6 +73,39 @@ def coords(self: SpaceProtocol) -> dict[str, FloatArray]: |
72 | 73 | class _AxesSpace(_Space): |
73 | 74 | axes: tuple[Axis, ...] = (Axis.Z, Axis.Y, Axis.X) |
74 | 75 |
|
| 76 | + def _get_scale_ratios(self, img_space: Any) -> dict[str, int]: |
| 77 | + """Calculate integer scale ratios between two spaces for coarsening.""" |
| 78 | + if not ( |
| 79 | + isinstance(img_space, SpaceProtocol) and isinstance(self, SpaceProtocol) |
| 80 | + ): # pragma: no cover |
| 81 | + raise NotImplementedError( |
| 82 | + f"Rescaling from {type(img_space)} to {type(self)} is not implemented." |
| 83 | + ) |
| 84 | + |
| 85 | + if set(self.axes) != set(img_space.axes): # pragma: no cover |
| 86 | + raise ValueError( |
| 87 | + f"Spaces must have the same axes. Got {self.axes} and {img_space.axes}." |
| 88 | + ) |
| 89 | + # Create axis->scale mappings |
| 90 | + self_scales = dict(zip(self.axes, self.scale, strict=True)) |
| 91 | + img_scales = dict(zip(img_space.axes, img_space.scale, strict=True)) |
| 92 | + return { |
| 93 | + ax: int(self_scales[ax] / img_scales[ax]) |
| 94 | + for ax in self.axes |
| 95 | + if ax in img_scales |
| 96 | + } |
| 97 | + |
| 98 | + def rescale(self, img: xrDataArray) -> xrDataArray: |
| 99 | + if not (img_space := getattr(img, "space", None)): # pragma: no cover |
| 100 | + raise ValueError("Input image must have a 'space' attribute.") |
| 101 | + |
| 102 | + dims = self._get_scale_ratios(img_space) |
| 103 | + if any(d < 1 for d in dims.values()): # pragma: no cover |
| 104 | + raise NotImplementedError( |
| 105 | + f"Can only downscale an image. Got downscale factors {dims}." |
| 106 | + ) |
| 107 | + return img.coarsen(dims).sum() # type: ignore |
| 108 | + |
75 | 109 | @field_validator("axes", mode="before") |
76 | 110 | def _cast_axes(cls, value: Any) -> tuple[Axis, ...]: |
77 | 111 | return tuple(value) |
|
0 commit comments