Skip to content

Commit 5fd98c4

Browse files
committed
perf: normalize image planes into one owned mutable buffer
1 parent ee4c0e9 commit 5fd98c4

4 files changed

Lines changed: 74 additions & 3 deletions

File tree

‎src/arraybridge/__init__.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
NumPy/numcodecs import cost.
1111
"""
1212

13-
__version__ = "0.3.7"
13+
__version__ = "0.3.8"
1414

1515
_LAZY_EXPORTS: dict[str, str] = {
1616
"MemoryType": ".types",

‎src/arraybridge/array_operations.py‎

Lines changed: 44 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -114,8 +114,50 @@ def broadcast_to(data: Any, shape: tuple[int, ...], module: Any) -> Any:
114114
def ones_like(reference: Any, shape: tuple[int, ...], dtype: Any, module: Any) -> Any:
115115
return module.ones(shape, dtype=dtype)
116116

117+
@classmethod
118+
def normalize_planes(
119+
cls,
120+
data: Any,
121+
dtype: Any,
122+
scales: Sequence[float | None],
123+
module: Any,
124+
) -> Any:
125+
"""Cast and scale each plane before assembling its owned output."""
126+
return cls.stack(
127+
tuple(
128+
(
129+
cls.cast(plane, dtype, module)
130+
if scale is None
131+
else cls.cast(plane, dtype, module) / float(scale)
132+
)
133+
for plane, scale in zip(data, scales, strict=True)
134+
),
135+
module,
136+
)
137+
138+
139+
class MutableArrayOperations(ArrayOperations):
140+
"""Arrays whose allocated output supports native in-place arithmetic."""
141+
142+
@classmethod
143+
def normalize_planes(
144+
cls,
145+
data: Any,
146+
dtype: Any,
147+
scales: Sequence[float | None],
148+
module: Any,
149+
) -> Any:
150+
# Integer division promotes the output dtype in the original recipe.
151+
if not np.issubdtype(np.dtype(dtype), np.inexact) or len(data) == 0:
152+
return super().normalize_planes(data, dtype, scales, module)
153+
normalized = module.array(data, dtype=dtype, copy=True)
154+
for index, scale in enumerate(scales):
155+
if scale is not None:
156+
normalized[index] /= float(scale)
157+
return normalized
158+
117159

118-
class NumpyArrayOperations(ArrayOperations):
160+
class NumpyArrayOperations(MutableArrayOperations):
119161
"""Numpy native operation leaves."""
120162

121163
@staticmethod
@@ -148,7 +190,7 @@ def scale_dtype(result: Any, target_dtype: Any, module: Any) -> Any:
148190
return scaled.astype(target_dtype)
149191

150192

151-
class CupyArrayOperations(ArrayOperations):
193+
class CupyArrayOperations(MutableArrayOperations):
152194
"""Cupy native operation leaves."""
153195

154196
@staticmethod

‎src/arraybridge/types.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -804,6 +804,20 @@ def stack_arrays(
804804
with self.device_scope(device_id, framework):
805805
return self._operations.stack(arrays, framework)
806806

807+
def normalize_planes(
808+
self,
809+
data: Any,
810+
dtype: Any,
811+
scales: Sequence[float | None],
812+
module: Any | None = None,
813+
) -> Any:
814+
"""Normalize one owned plane stack through its native operation owner."""
815+
if len(scales) != len(data):
816+
raise ValueError("Normalization scales must match the leading plane axis.")
817+
framework = module if module is not None else self.import_module()
818+
with self._array_device_scope(data, framework):
819+
return self._operations.normalize_planes(data, dtype, scales, framework)
820+
807821
def scale_dtype(
808822
self,
809823
data: Any,

‎tests/test_native_geometry.py‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,3 +63,18 @@ def __array__(self):
6363
PYCLESPERANTO_OPERATIONS.broadcast_to(source, (4, 2, 3), None)
6464
with pytest.raises(NotImplementedError, match="dtype"):
6565
PYCLESPERANTO_OPERATIONS.ones_like(source, (2, 3), bool, None)
66+
67+
68+
@pytest.mark.parametrize("dtype", (np.float32, np.complex64, np.int32))
69+
def test_normalize_planes_preserves_source_and_division_dtype(dtype):
70+
source = np.arange(24, dtype=dtype).reshape(2, 3, 4)[:, :, ::-1]
71+
original = source.copy()
72+
expected = np.stack((source[0] / 3.0, source[1]))
73+
actual = MemoryType.NUMPY.normalize_planes(source, dtype, (3.0, None))
74+
np.testing.assert_array_equal(actual, expected)
75+
np.testing.assert_array_equal(source, original)
76+
assert actual.dtype == expected.dtype
77+
assert not np.shares_memory(actual, source)
78+
for scales in ((3.0,), (3.0, None, 2.0)):
79+
with pytest.raises(ValueError, match="leading plane axis"):
80+
MemoryType.NUMPY.normalize_planes(source, dtype, scales)

0 commit comments

Comments
 (0)