1- """Native array operations carried by MemoryType declarations ."""
1+ """Native array operations, one family leaf per MemoryType declaration ."""
22
3- from abc import ABC , abstractmethod
4- from collections .abc import Sequence
5- from typing import Any
3+ from __future__ import annotations
4+
5+ from abc import abstractmethod
6+ from collections .abc import Mapping , Sequence
7+ from functools import cache , cached_property
8+ from typing import TYPE_CHECKING , Any , ClassVar
69
710import numpy as np
11+ from metaclass_registry import AutoRegisterMeta
12+
13+ from arraybridge .array_payload import ArrayPayload
14+
15+ if TYPE_CHECKING :
16+ from arraybridge .types import MemoryType
817
918_SCALING_RANGES : dict [str , float | tuple [float , float ]] = {
1019 "uint8" : 255.0 ,
@@ -68,8 +77,84 @@ def _mapped_dtype(target_dtype: Any, module: Any) -> Any:
6877 return mapped
6978
7079
71- class ArrayOperations (ABC ):
72- """Native array semantics selected by the existing MemoryType declaration."""
80+ @cache
81+ def _leaf_instance (leaf : type [ArrayOperations ]) -> ArrayOperations :
82+ return leaf ()
83+
84+
85+ class ArrayOperations (metaclass = AutoRegisterMeta ):
86+ """Native array semantics, one registered leaf per ``MemoryType`` value.
87+
88+ Static leaves take the framework module from their caller (``MemoryType``).
89+ Instance primitives are the namespace array-library-neutral code is written
90+ against: each leaf supplies only what its library genuinely does differently.
91+ """
92+
93+ __registry_key__ = "memory_type"
94+ # Leaves are declared in this module, without lazy discovery.
95+ __registry__ : ClassVar [Mapping [str , type [ArrayOperations ]]] = {}
96+ memory_type : ClassVar [str | None ] = None
97+
98+ @classmethod
99+ def for_memory (cls , memory_type : MemoryType ) -> ArrayOperations :
100+ """Return the operations leaf declared for ``memory_type``."""
101+ return _leaf_instance (cls .__registry__ [memory_type .value ])
102+
103+ @cached_property
104+ def module (self ) -> Any :
105+ """The framework module, imported on first use."""
106+ from arraybridge .types import MemoryType
107+
108+ return MemoryType (self .memory_type ).import_module ()
109+
110+ @property
111+ def array_module (self ) -> Any :
112+ """The module holding the framework's array functions."""
113+ return self .module
114+
115+ # ----- primitives for array-library-neutral operations -----
116+
117+ def accepts (self , value : Any ) -> bool :
118+ """Whether ``value`` is a native array of this framework."""
119+ return isinstance (value , self .module .ndarray )
120+
121+ def astype (self , data : Any , dtype : Any ) -> Any :
122+ return self .cast (data , dtype , self .module )
123+
124+ def max (self , data : Any , axis : int | tuple [int , ...]) -> Any :
125+ return self .array_module .max (data , axis = axis )
126+
127+ def min (self , data : Any , axis : int | tuple [int , ...]) -> Any :
128+ return self .array_module .min (data , axis = axis )
129+
130+ def mean (self , data : Any , axis : int | tuple [int , ...]) -> Any :
131+ return self .array_module .mean (data , axis = axis )
132+
133+ def sum (self , data : Any , axis : int | tuple [int , ...]) -> Any :
134+ return self .array_module .sum (data , axis = axis )
135+
136+ def prepend_axis (self , data : Any ) -> Any :
137+ """Add a leading axis of length one."""
138+ return self .reshape (data , (1 , * data .shape ), self .module )
139+
140+ def linspace (self , start : float , stop : float , num : int , * , endpoint : bool ) -> Any :
141+ return self .array_module .linspace (start , stop , num , endpoint = endpoint )
142+
143+ def ones (self , shape : int | tuple [int , ...], dtype : Any ) -> Any :
144+ """Allocate ones on the framework's default device."""
145+ return self .array_module .ones (shape , dtype = _mapped_dtype (dtype , self .array_module ))
146+
147+ def assign (self , data : Any , index : slice , values : Any ) -> Any :
148+ """Return ``data`` with ``data[index]`` replaced by ``values``."""
149+ data [index ] = values
150+ return data
151+
152+ def outer (self , left : Any , right : Any ) -> Any :
153+ return self .array_module .outer (left , right )
154+
155+ def floor (self , value : float ) -> Any :
156+ """Floor a host scalar in the framework's default precision."""
157+ return self .array_module .floor (value )
73158
74159 @staticmethod
75160 @abstractmethod
@@ -160,6 +245,11 @@ def normalize_planes(
160245class NumpyArrayOperations (MutableArrayOperations ):
161246 """Numpy native operation leaves."""
162247
248+ memory_type = "numpy"
249+
250+ def accepts (self , value : Any ) -> bool :
251+ return isinstance (value , (np .ndarray , ArrayPayload ))
252+
163253 @staticmethod
164254 def to_numpy (data : Any , module : Any ) -> Any :
165255 del module
@@ -193,6 +283,8 @@ def scale_dtype(result: Any, target_dtype: Any, module: Any) -> Any:
193283class CupyArrayOperations (MutableArrayOperations ):
194284 """Cupy native operation leaves."""
195285
286+ memory_type = "cupy"
287+
196288 @staticmethod
197289 def to_numpy (data : Any , module : Any ) -> Any :
198290 del module
@@ -226,6 +318,35 @@ def scale_dtype(result: Any, target_dtype: Any, module: Any) -> Any:
226318class TorchArrayOperations (ArrayOperations ):
227319 """Torch native operation leaves."""
228320
321+ memory_type = "torch"
322+
323+ def accepts (self , value : Any ) -> bool :
324+ return isinstance (value , self .module .Tensor )
325+
326+ def max (self , data : Any , axis : int | tuple [int , ...]) -> Any :
327+ # CUDA has no uint16 reduction; float32 holds every uint16 exactly.
328+ values = data .float () if data .dtype == self .module .uint16 else data
329+ return self .module .amax (values , dim = axis ).to (data .dtype )
330+
331+ def min (self , data : Any , axis : int | tuple [int , ...]) -> Any :
332+ values = data .float () if data .dtype == self .module .uint16 else data
333+ return self .module .amin (values , dim = axis ).to (data .dtype )
334+
335+ def mean (self , data : Any , axis : int | tuple [int , ...]) -> Any :
336+ return self .module .mean (data .float (), dim = axis )
337+
338+ def sum (self , data : Any , axis : int | tuple [int , ...]) -> Any :
339+ return self .module .sum (data , dim = axis )
340+
341+ def linspace (self , start : float , stop : float , num : int , * , endpoint : bool ) -> Any :
342+ float32 = self .module .float32
343+ if endpoint :
344+ return self .module .linspace (start , stop , num , dtype = float32 )
345+ return self .module .linspace (start , stop , num + 1 , dtype = float32 )[:- 1 ]
346+
347+ def floor (self , value : float ) -> Any :
348+ return self .module .floor (self .module .tensor (value ))
349+
229350 @staticmethod
230351 def to_numpy (data : Any , module : Any ) -> Any :
231352 del module
@@ -264,11 +385,12 @@ def stack(values: Sequence[Any], module: Any) -> Any:
264385
265386 @staticmethod
266387 def cast (data : Any , dtype : Any , module : Any ) -> Any :
267- return data .to (dtype = _mapped_dtype (dtype , module ))
388+ native = dtype if isinstance (dtype , module .dtype ) else _mapped_dtype (dtype , module )
389+ return data .to (dtype = native )
268390
269391 @staticmethod
270392 def dtype_name (dtype : Any ) -> str :
271- return str (dtype ). rsplit ( "." , maxsplit = 1 )[ - 1 ]
393+ return _torch_dtype_name (dtype )
272394
273395 @staticmethod
274396 def broadcast_to (data : Any , shape : tuple [int , ...], module : Any ) -> Any :
@@ -282,6 +404,44 @@ def ones_like(reference: Any, shape: tuple[int, ...], dtype: Any, module: Any) -
282404class TensorflowArrayOperations (ArrayOperations ):
283405 """Tensorflow native operation leaves."""
284406
407+ memory_type = "tensorflow"
408+
409+ def accepts (self , value : Any ) -> bool :
410+ return isinstance (value , self .module .Tensor )
411+
412+ def max (self , data : Any , axis : int | tuple [int , ...]) -> Any :
413+ return self .module .reduce_max (data , axis = axis )
414+
415+ def min (self , data : Any , axis : int | tuple [int , ...]) -> Any :
416+ return self .module .reduce_min (data , axis = axis )
417+
418+ def mean (self , data : Any , axis : int | tuple [int , ...]) -> Any :
419+ return self .module .reduce_mean (self .module .cast (data , self .module .float32 ), axis = axis )
420+
421+ def sum (self , data : Any , axis : int | tuple [int , ...]) -> Any :
422+ return self .module .reduce_sum (data , axis = axis )
423+
424+ def linspace (self , start : float , stop : float , num : int , * , endpoint : bool ) -> Any :
425+ if endpoint :
426+ return self .module .linspace (float (start ), float (stop ), num )
427+ return self .module .linspace (float (start ), float (stop ), num + 1 )[:- 1 ]
428+
429+ def assign (self , data : Any , index : slice , values : Any ) -> Any :
430+ rows = self .module .range (* index .indices (int (data .shape [0 ])))
431+ return self .module .tensor_scatter_nd_update (
432+ data , self .module .reshape (rows , [- 1 , 1 ]), values
433+ )
434+
435+ def outer (self , left : Any , right : Any ) -> Any :
436+ return self .module .tensordot (left , right , axes = 0 )
437+
438+ def floor (self , value : float ) -> Any :
439+ return self .module .math .floor (value )
440+
441+ @staticmethod
442+ def dtype_name (dtype : Any ) -> str :
443+ return _tensorflow_dtype_name (dtype )
444+
285445 @staticmethod
286446 def to_numpy (data : Any , module : Any ) -> Any :
287447 del module
@@ -312,7 +472,8 @@ def scale_dtype(result: Any, target_dtype: Any, module: Any) -> Any:
312472
313473 @staticmethod
314474 def cast (data : Any , dtype : Any , module : Any ) -> Any :
315- return module .cast (data , _mapped_dtype (dtype , module ))
475+ native = dtype if isinstance (dtype , module .dtypes .DType ) else _mapped_dtype (dtype , module )
476+ return module .cast (data , native )
316477
317478 @staticmethod
318479 def reshape (data : Any , shape : tuple [int , ...], module : Any ) -> Any :
@@ -327,6 +488,22 @@ def ones_like(reference: Any, shape: tuple[int, ...], dtype: Any, module: Any) -
327488class JaxArrayOperations (ArrayOperations ):
328489 """Jax native operation leaves."""
329490
491+ memory_type = "jax"
492+
493+ @property
494+ def array_module (self ) -> Any :
495+ return self .module .numpy
496+
497+ def accepts (self , value : Any ) -> bool :
498+ return isinstance (value , self .module .numpy .ndarray )
499+
500+ def mean (self , data : Any , axis : int | tuple [int , ...]) -> Any :
501+ jnp = self .module .numpy
502+ return jnp .mean (data .astype (jnp .float32 ), axis = axis )
503+
504+ def assign (self , data : Any , index : slice , values : Any ) -> Any :
505+ return data .at [index ].set (values )
506+
330507 @staticmethod
331508 def to_numpy (data : Any , module : Any ) -> Any :
332509 del module
@@ -388,6 +565,33 @@ def ones_like(reference: Any, shape: tuple[int, ...], dtype: Any, module: Any) -
388565class PyclesperantoArrayOperations (ArrayOperations ):
389566 """Pyclesperanto native operation leaves."""
390567
568+ memory_type = "pyclesperanto"
569+
570+ def accepts (self , value : Any ) -> bool :
571+ # pyclesperanto kernels push any host array they receive.
572+ return hasattr (value , "shape" )
573+
574+ def max (self , data : Any , axis : int | tuple [int , ...]) -> Any :
575+ _require_z_axis (axis )
576+ return self .module .maximum_z_projection (data )
577+
578+ def min (self , data : Any , axis : int | tuple [int , ...]) -> Any :
579+ _require_z_axis (axis )
580+ return self .module .minimum_z_projection (data )
581+
582+ def mean (self , data : Any , axis : int | tuple [int , ...]) -> Any :
583+ _require_z_axis (axis )
584+ return self .module .mean_z_projection (data )
585+
586+ def sum (self , data : Any , axis : int | tuple [int , ...]) -> Any :
587+ _require_z_axis (axis )
588+ return self .module .sum_z_projection (data )
589+
590+ def prepend_axis (self , data : Any ) -> Any :
591+ result = self .module .create ((1 , * data .shape ), dtype = data .dtype )
592+ result [0 ] = data
593+ return result
594+
391595 @staticmethod
392596 def to_numpy (data : Any , module : Any ) -> Any :
393597 return module .pull (data )
@@ -484,9 +688,8 @@ def ones_like(reference: Any, shape: tuple[int, ...], dtype: Any, module: Any) -
484688 return result
485689
486690
487- NUMPY_OPERATIONS = NumpyArrayOperations ()
488- CUPY_OPERATIONS = CupyArrayOperations ()
489- TORCH_OPERATIONS = TorchArrayOperations ()
490- TENSORFLOW_OPERATIONS = TensorflowArrayOperations ()
491- JAX_OPERATIONS = JaxArrayOperations ()
492- PYCLESPERANTO_OPERATIONS = PyclesperantoArrayOperations ()
691+ def _require_z_axis (axis : int | tuple [int , ...]) -> None :
692+ if axis != 0 :
693+ raise NotImplementedError (
694+ f"pyclesperanto reduces only along the leading (z) axis, not axis { axis !r} "
695+ )
0 commit comments