arraybridge 0.3.2__py3-none-any.whl → 0.3.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
arraybridge/__init__.py CHANGED
@@ -3,37 +3,49 @@ arraybridge: Unified API for NumPy, CuPy, PyTorch, TensorFlow, JAX, and pyclespe
3
3
 
4
4
  This package provides automatic memory type conversion, declarative decorators,
5
5
  and unified utilities for working with multiple array/tensor frameworks.
6
- """
7
6
 
8
- __version__ = "0.3.2"
7
+ Package-root imports stay lightweight: submodule exports load on first
8
+ attribute access instead of at import time. Declaration-only consumers
9
+ (memory-type tables, configuration modules) therefore do not pay the
10
+ NumPy/numcodecs import cost.
11
+ """
9
12
 
10
- from . import decorators as _decorators
11
- from .array_geometry import ArrayGeometry
12
- from .array_payload import ArrayPayload
13
- from .converters import convert_memory, detect_memory_type
14
- from .dtype_scaling import SCALING_FUNCTIONS
15
- from .exceptions import MemoryConversionError
16
- from .framework_config import _FRAMEWORK_CONFIG
17
- from .framework_ops import _FRAMEWORK_OPS
18
- from .gpu_cleanup import cleanup_all_gpu_frameworks
19
- from .oom_recovery import _execute_with_oom_recovery
20
- from .slice_processing import process_slices
21
- from .stack_utils import stack_slices, unstack_slices
22
- from .types import (
23
- CPU_MEMORY_TYPES,
24
- GPU_MEMORY_TYPES,
25
- SUPPORTED_MEMORY_TYPES,
26
- MemoryContractAttribute,
27
- MemoryType,
28
- )
29
- from .utils import _ensure_module, _get_device_id, _supports_dlpack
13
+ __version__ = "0.3.4"
30
14
 
31
- DtypeConversion = _decorators.DtypeConversion
32
- SliceBySliceRuntimeParameter = _decorators.SliceBySliceRuntimeParameter
33
- memory_types = _decorators.memory_types
34
- wrap_dtype_preserving_callable = _decorators.wrap_dtype_preserving_callable
35
- for _memory_type in MemoryType:
36
- globals()[_memory_type.value] = getattr(_decorators, _memory_type.value)
15
+ _LAZY_EXPORTS: dict[str, str] = {
16
+ "MemoryType": ".types",
17
+ "MemoryContractAttribute": ".types",
18
+ "ArrayPayload": ".array_payload",
19
+ "ArrayGeometry": ".array_geometry",
20
+ "CPU_MEMORY_TYPES": ".types",
21
+ "GPU_MEMORY_TYPES": ".types",
22
+ "SUPPORTED_MEMORY_TYPES": ".types",
23
+ "convert_memory": ".converters",
24
+ "detect_memory_type": ".converters",
25
+ "memory_types": ".decorators",
26
+ "DtypeConversion": ".decorators",
27
+ "SliceBySliceRuntimeParameter": ".decorators",
28
+ "wrap_dtype_preserving_callable": ".decorators",
29
+ "stack_slices": ".stack_utils",
30
+ "unstack_slices": ".stack_utils",
31
+ "process_slices": ".slice_processing",
32
+ "cleanup_all_gpu_frameworks": ".gpu_cleanup",
33
+ "MemoryConversionError": ".exceptions",
34
+ "SCALING_FUNCTIONS": ".dtype_scaling",
35
+ "_FRAMEWORK_CONFIG": ".framework_config",
36
+ "_FRAMEWORK_OPS": ".framework_ops",
37
+ "_execute_with_oom_recovery": ".oom_recovery",
38
+ "_ensure_module": ".utils",
39
+ "_supports_dlpack": ".utils",
40
+ "_get_device_id": ".utils",
41
+ # Decorator exports named after each memory type (numpy, cupy, torch, ...).
42
+ "numpy": ".decorators",
43
+ "cupy": ".decorators",
44
+ "torch": ".decorators",
45
+ "tensorflow": ".decorators",
46
+ "jax": ".decorators",
47
+ "pyclesperanto": ".decorators",
48
+ }
37
49
 
38
50
  __all__ = [
39
51
  # Types
@@ -72,4 +84,26 @@ __all__ = [
72
84
  "_ensure_module",
73
85
  "_supports_dlpack",
74
86
  "_get_device_id",
75
- ] + [memory_type.value for memory_type in MemoryType]
87
+ "numpy",
88
+ "cupy",
89
+ "torch",
90
+ "tensorflow",
91
+ "jax",
92
+ "pyclesperanto",
93
+ ]
94
+
95
+
96
+ def __getattr__(name: str):
97
+ module_name = _LAZY_EXPORTS.get(name)
98
+ if module_name is None:
99
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
100
+
101
+ import importlib
102
+
103
+ value = getattr(importlib.import_module(module_name, __name__), name)
104
+ globals()[name] = value
105
+ return value
106
+
107
+
108
+ def __dir__() -> list[str]:
109
+ return sorted(set(globals()) | set(_LAZY_EXPORTS))
arraybridge/types.py CHANGED
@@ -5,6 +5,8 @@ This module defines the MemoryType enum and related constants for managing
5
5
  different array/tensor frameworks.
6
6
  """
7
7
 
8
+ from __future__ import annotations
9
+
8
10
  import importlib
9
11
  import importlib.util
10
12
  import logging
@@ -14,17 +16,11 @@ from collections.abc import Callable, Iterator, Mapping, MutableMapping
14
16
  from contextlib import AbstractContextManager, contextmanager, nullcontext
15
17
  from dataclasses import dataclass
16
18
  from enum import Enum
17
- from typing import Any, TypeVar, cast
18
-
19
- from arraybridge.array_operations import (
20
- CUPY_OPERATIONS,
21
- JAX_OPERATIONS,
22
- NUMPY_OPERATIONS,
23
- PYCLESPERANTO_OPERATIONS,
24
- TENSORFLOW_OPERATIONS,
25
- TORCH_OPERATIONS,
26
- ArrayOperations,
27
- )
19
+ from pathlib import Path
20
+ from typing import TYPE_CHECKING, Any, TypeVar, cast
21
+
22
+ if TYPE_CHECKING:
23
+ from arraybridge.array_operations import ArrayOperations
28
24
 
29
25
  T = TypeVar("T")
30
26
  logger = logging.getLogger(__name__)
@@ -41,6 +37,55 @@ StreamScopeFactory = Callable[[Any, Any], AbstractContextManager[None]]
41
37
  DLPackExporter = Callable[[Any, Any], Any | None]
42
38
  DLPackValidator = Callable[[Any, Any], bool]
43
39
  OOMMatcher = Callable[[BaseException, Any | None], bool]
40
+ SubprocessEnvironmentResolver = Callable[[Mapping[str, str]], dict[str, str]]
41
+
42
+
43
+ def _identity_subprocess_environment(
44
+ environment: Mapping[str, str],
45
+ ) -> dict[str, str]:
46
+ return dict(environment)
47
+
48
+
49
+ def _nvidia_wheel_library_paths() -> tuple[str, ...]:
50
+ """Return native-library directories declared by installed NVIDIA wheels."""
51
+
52
+ try:
53
+ spec = importlib.util.find_spec("nvidia")
54
+ except (ImportError, ModuleNotFoundError, ValueError):
55
+ return ()
56
+ if spec is None or spec.submodule_search_locations is None:
57
+ return ()
58
+
59
+ paths: set[str] = set()
60
+ for package_root in map(Path, spec.submodule_search_locations):
61
+ try:
62
+ components = tuple(package_root.iterdir())
63
+ except OSError:
64
+ continue
65
+ for component in components:
66
+ for library_directory_name in ("lib", "bin"):
67
+ candidate = component / library_directory_name
68
+ if candidate.is_dir():
69
+ paths.add(str(candidate))
70
+ return tuple(sorted(paths))
71
+
72
+
73
+ def _nvidia_wheel_subprocess_environment(
74
+ environment: Mapping[str, str],
75
+ ) -> dict[str, str]:
76
+ """Prepend installed NVIDIA wheel libraries to a child environment."""
77
+
78
+ prepared = dict(environment)
79
+ library_paths = _nvidia_wheel_library_paths()
80
+ if not library_paths:
81
+ return prepared
82
+
83
+ search_variable = "PATH" if os.name == "nt" else "LD_LIBRARY_PATH"
84
+ existing_paths = tuple(
85
+ path for path in prepared.get(search_variable, "").split(os.pathsep) if path
86
+ )
87
+ prepared[search_variable] = os.pathsep.join(dict.fromkeys((*library_paths, *existing_paths)))
88
+ return prepared
44
89
 
45
90
 
46
91
  class MemoryContractAttribute(str, Enum):
@@ -501,6 +546,7 @@ class FrameworkRuntime:
501
546
  dlpack_exporter: DLPackExporter | None = None
502
547
  dlpack_validator: DLPackValidator = _protocol_dlpack
503
548
  oom_matcher: OOMMatcher = _never_oom
549
+ subprocess_environment: SubprocessEnvironmentResolver = _identity_subprocess_environment
504
550
 
505
551
 
506
552
  class _MemoryTypeFields:
@@ -510,7 +556,7 @@ class _MemoryTypeFields:
510
556
  module_aliases: tuple[str, ...]
511
557
  import_environment: tuple[tuple[str, str], ...]
512
558
  _runtime: FrameworkRuntime
513
- _operations: ArrayOperations
559
+ _operations_name: str
514
560
 
515
561
 
516
562
  class MemoryType(_MemoryTypeFields, Enum):
@@ -520,7 +566,7 @@ class MemoryType(_MemoryTypeFields, Enum):
520
566
  cls,
521
567
  value: str,
522
568
  *declaration: Any,
523
- ) -> "MemoryType":
569
+ ) -> MemoryType:
524
570
  (
525
571
  import_name,
526
572
  display_name,
@@ -538,9 +584,18 @@ class MemoryType(_MemoryTypeFields, Enum):
538
584
  member.module_aliases = cast(tuple[str, ...], module_aliases)
539
585
  member.import_environment = cast(tuple[tuple[str, str], ...], import_environment)
540
586
  member._runtime = cast(FrameworkRuntime, runtime)
541
- member._operations = cast(ArrayOperations, operations)
587
+ member._operations_name = cast(str, operations)
542
588
  return member
543
589
 
590
+ @property
591
+ def _operations(self) -> ArrayOperations:
592
+ """Resolve this declaration's operations registry on first access."""
593
+
594
+ from arraybridge import array_operations
595
+
596
+ operations: ArrayOperations = getattr(array_operations, self._operations_name)
597
+ return operations
598
+
544
599
  NUMPY = (
545
600
  "numpy",
546
601
  "numpy",
@@ -549,7 +604,7 @@ class MemoryType(_MemoryTypeFields, Enum):
549
604
  (),
550
605
  (),
551
606
  FrameworkRuntime(oom_matcher=_numpy_oom),
552
- NUMPY_OPERATIONS,
607
+ "NUMPY_OPERATIONS",
553
608
  )
554
609
  CUPY = (
555
610
  "cupy",
@@ -571,8 +626,9 @@ class MemoryType(_MemoryTypeFields, Enum):
571
626
  dlpack_importer=_cupy_from_dlpack,
572
627
  dlpack_exporter=_protocol_dlpack_export,
573
628
  oom_matcher=_cupy_oom,
629
+ subprocess_environment=_nvidia_wheel_subprocess_environment,
574
630
  ),
575
- CUPY_OPERATIONS,
631
+ "CUPY_OPERATIONS",
576
632
  )
577
633
  TORCH = (
578
634
  "torch",
@@ -595,7 +651,7 @@ class MemoryType(_MemoryTypeFields, Enum):
595
651
  dlpack_exporter=_protocol_dlpack_export,
596
652
  oom_matcher=_torch_oom,
597
653
  ),
598
- TORCH_OPERATIONS,
654
+ "TORCH_OPERATIONS",
599
655
  )
600
656
  TENSORFLOW = (
601
657
  "tensorflow",
@@ -614,7 +670,7 @@ class MemoryType(_MemoryTypeFields, Enum):
614
670
  dlpack_validator=_tensorflow_dlpack,
615
671
  oom_matcher=_tensorflow_oom,
616
672
  ),
617
- TENSORFLOW_OPERATIONS,
673
+ "TENSORFLOW_OPERATIONS",
618
674
  )
619
675
  JAX = (
620
676
  "jax",
@@ -632,7 +688,7 @@ class MemoryType(_MemoryTypeFields, Enum):
632
688
  dlpack_exporter=_protocol_dlpack_export,
633
689
  oom_matcher=_jax_oom,
634
690
  ),
635
- JAX_OPERATIONS,
691
+ "JAX_OPERATIONS",
636
692
  )
637
693
  PYCLESPERANTO = (
638
694
  "pyclesperanto",
@@ -649,7 +705,7 @@ class MemoryType(_MemoryTypeFields, Enum):
649
705
  move_to_active_device=_pyclesperanto_device_move,
650
706
  oom_matcher=_pyclesperanto_oom,
651
707
  ),
652
- PYCLESPERANTO_OPERATIONS,
708
+ "PYCLESPERANTO_OPERATIONS",
653
709
  )
654
710
 
655
711
  @property
@@ -682,6 +738,20 @@ class MemoryType(_MemoryTypeFields, Enum):
682
738
  for name, value in self.import_environment:
683
739
  os.environ.setdefault(name, value)
684
740
 
741
+ @classmethod
742
+ def subprocess_environment(
743
+ cls,
744
+ environment: Mapping[str, str] | None = None,
745
+ ) -> dict[str, str]:
746
+ """Project framework import requirements into a child environment."""
747
+
748
+ prepared = dict(os.environ if environment is None else environment)
749
+ for memory_type in cls:
750
+ for name, value in memory_type.import_environment:
751
+ prepared.setdefault(name, value)
752
+ prepared = memory_type._runtime.subprocess_environment(prepared)
753
+ return prepared
754
+
685
755
  def loaded_module(self) -> Any | None:
686
756
  """Return an already-loaded framework without causing an import."""
687
757
 
@@ -887,7 +957,7 @@ class MemoryType(_MemoryTypeFields, Enum):
887
957
  payload = data if isinstance(data, DLPackPayload) else DLPackPayload(data, data)
888
958
  return importer(payload, framework)
889
959
 
890
- def convert_to(self, data: Any, target: "MemoryType", device_id: int) -> Any:
960
+ def convert_to(self, data: Any, target: MemoryType, device_id: int) -> Any:
891
961
  """Convert one array through the source and target declarations."""
892
962
 
893
963
  if self is target:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: arraybridge
3
- Version: 0.3.2
3
+ Version: 0.3.4
4
4
  Summary: Unified API for NumPy, CuPy, PyTorch, TensorFlow, JAX, and pyclesperanto with automatic memory type conversion
5
5
  Project-URL: Homepage, https://github.com/OpenHCSDev/arraybridge
6
6
  Project-URL: Documentation, https://arraybridge.readthedocs.io
@@ -1,4 +1,4 @@
1
- arraybridge/__init__.py,sha256=xFy8ESRzsIy8ydjdPQs33C5Ed6HH6YUsn65HSmQTtzM,2326
1
+ arraybridge/__init__.py,sha256=a27ES1ItSBsT77vP3f12ILNu0MzrvQfcpCBVDXwi-Sg,3184
2
2
  arraybridge/array_geometry.py,sha256=CopfGmFVKwV5l-lOTImhm1YVh18weUng0ReEF58qlPI,1689
3
3
  arraybridge/array_operations.py,sha256=fp69o9BYcCzfhmLcWrH68SVGSfPL3nb6Cty-Amd_oQM,13082
4
4
  arraybridge/array_payload.py,sha256=6_jJwPRya0MHrUNSA9kXPlTISpLa0G74rqDValGXKx4,1079
@@ -13,9 +13,9 @@ arraybridge/gpu_cleanup.py,sha256=ADI4wMLk9GIO9rJ6BJuNk3uZIyANoAqJ7VFTnLJzrbE,25
13
13
  arraybridge/oom_recovery.py,sha256=hGvOuJHVSopiIqblzoMFlqW8_oK6ZlAGF_l4pfEljeI,2403
14
14
  arraybridge/slice_processing.py,sha256=5R10OmHW8BSbJFwT1URd2Sz3P15o5EhaI2VnVUUIvkQ,4450
15
15
  arraybridge/stack_utils.py,sha256=FVikN0XG-Xryw-1p9MaSRUTZet7kLcy0gTEERSjc9r4,6915
16
- arraybridge/types.py,sha256=1otpHqFJfGc9RY40VCzNCkqpTnR8cfckhY44HnuGudI,33191
16
+ arraybridge/types.py,sha256=e5R2DVflQAjXrfTk033KRdiiwoip3IQAvgDCYUjPdiQ,35807
17
17
  arraybridge/utils.py,sha256=RqThtYScPEOEQG491dA8b_VvUTjgcFhwLbh0erQu5Ns,4833
18
- arraybridge-0.3.2.dist-info/METADATA,sha256=tX2dNiYptc7DpXQUqV8x5BX5RzVSMLOD9wM-4xQmg5o,5275
19
- arraybridge-0.3.2.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
20
- arraybridge-0.3.2.dist-info/licenses/LICENSE,sha256=xagEoeTAj1WT64RmyR3E6HH-eTGdgXN6gqPMUUt7L_Y,1070
21
- arraybridge-0.3.2.dist-info/RECORD,,
18
+ arraybridge-0.3.4.dist-info/METADATA,sha256=jq9-ULcNwbZo7cMtZlhhqj4F2QlV-8PrpdM1Tv0tLCE,5275
19
+ arraybridge-0.3.4.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
20
+ arraybridge-0.3.4.dist-info/licenses/LICENSE,sha256=xagEoeTAj1WT64RmyR3E6HH-eTGdgXN6gqPMUUt7L_Y,1070
21
+ arraybridge-0.3.4.dist-info/RECORD,,