simind-python-connector 1.1.1__py3-none-any.whl → 1.1.2__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.
Files changed (23) hide show
  1. simind_python_connector/__init__.py +1 -1
  2. simind_python_connector/backends/__init__.py +4 -3
  3. simind_python_connector/backends/stir_backend.py +36 -17
  4. simind_python_connector/connectors/_spacing.py +124 -8
  5. simind_python_connector/connectors/python_connector.py +421 -91
  6. simind_python_connector/connectors/pytomography_adaptor.py +49 -7
  7. simind_python_connector/connectors/sirf_adaptor.py +54 -9
  8. simind_python_connector/connectors/stir_adaptor.py +54 -9
  9. simind_python_connector/converters/simind_to_stir.py +63 -31
  10. simind_python_connector/core/config.py +419 -108
  11. simind_python_connector/core/executor.py +264 -26
  12. simind_python_connector/core/types.py +21 -8
  13. simind_python_connector/data/__init__.py +5 -3
  14. simind_python_connector/utils/__init__.py +3 -3
  15. simind_python_connector/utils/geometry_phantom.py +42 -0
  16. simind_python_connector/utils/import_helpers.py +33 -5
  17. simind_python_connector/utils/interfile_numpy.py +15 -1
  18. simind_python_connector/utils/simind_utils.py +31 -1
  19. {simind_python_connector-1.1.1.dist-info → simind_python_connector-1.1.2.dist-info}/METADATA +27 -12
  20. {simind_python_connector-1.1.1.dist-info → simind_python_connector-1.1.2.dist-info}/RECORD +23 -22
  21. {simind_python_connector-1.1.1.dist-info → simind_python_connector-1.1.2.dist-info}/WHEEL +0 -0
  22. {simind_python_connector-1.1.1.dist-info → simind_python_connector-1.1.2.dist-info}/licenses/LICENSE +0 -0
  23. {simind_python_connector-1.1.1.dist-info → simind_python_connector-1.1.2.dist-info}/top_level.txt +0 -0
@@ -14,7 +14,7 @@ for _dist_name in ("simind-python-connector", __name__):
14
14
  except _meta.PackageNotFoundError:
15
15
  continue
16
16
  else: # editable / source checkout
17
- __version__ = "1.1.1"
17
+ __version__ = "1.1.2"
18
18
 
19
19
 
20
20
  def __getattr__(name: str) -> Any:
@@ -22,6 +22,7 @@ import logging
22
22
  import os
23
23
  from typing import TYPE_CHECKING, Any, Literal, Optional, Union
24
24
 
25
+ from ..utils.import_helpers import _import_stir_extra
25
26
  from .base import AcquisitionDataInterface, ImageDataInterface
26
27
 
27
28
 
@@ -150,7 +151,7 @@ def get_backend() -> str:
150
151
  except ImportError:
151
152
  try:
152
153
  importlib.import_module("stir")
153
- importlib.import_module("stirextra")
154
+ _import_stir_extra()
154
155
 
155
156
  _backend = "stir"
156
157
  logger.info("Auto-detected STIR Python backend")
@@ -159,7 +160,7 @@ def get_backend() -> str:
159
160
  "Neither SIRF nor STIR Python found. "
160
161
  "Please install one of: "
161
162
  "\n - SIRF (sirf.STIR)"
162
- "\n - STIR Python (stir + stirextra)"
163
+ "\n - STIR Python (stir + stir.extra)"
163
164
  )
164
165
 
165
166
  _backend_initialized = True
@@ -190,7 +191,7 @@ def set_backend(backend: Literal["sirf", "stir"]) -> None:
190
191
  elif backend == "stir":
191
192
  try:
192
193
  importlib.import_module("stir")
193
- importlib.import_module("stirextra")
194
+ _import_stir_extra()
194
195
  except ImportError:
195
196
  raise ImportError("STIR Python is not available")
196
197
 
@@ -12,7 +12,10 @@ import numpy as np
12
12
 
13
13
  try:
14
14
  import stir
15
- import stirextra
15
+
16
+ from ..utils.import_helpers import _import_stir_extra
17
+
18
+ _import_stir_extra()
16
19
 
17
20
  STIR_AVAILABLE = True
18
21
  except ImportError:
@@ -92,7 +95,7 @@ class StirImageData(ImageDataInterface):
92
95
  def dimensions(self) -> Tuple[int, int, int]:
93
96
  """Get dimensions as (z, y, x)."""
94
97
  # Extract from numpy array shape
95
- arr = stirextra.to_numpy(self._obj)
98
+ arr = _import_stir_extra().to_numpy(self._obj)
96
99
  # STIR arrays are typically (z, y, x)
97
100
  return arr.shape
98
101
 
@@ -104,8 +107,8 @@ class StirImageData(ImageDataInterface):
104
107
  return (grid_spacing[1], grid_spacing[2], grid_spacing[3])
105
108
 
106
109
  def as_array(self) -> np.ndarray:
107
- """Convert to numpy array using stirextra."""
108
- return stirextra.to_numpy(self._obj)
110
+ """Convert to numpy array using stir.extra."""
111
+ return _import_stir_extra().to_numpy(self._obj)
109
112
 
110
113
  def sum(self) -> float:
111
114
  """Sum all values."""
@@ -169,19 +172,27 @@ class StirImageData(ImageDataInterface):
169
172
  return StirImageData(self._obj / float(other))
170
173
 
171
174
  def __radd__(self, other):
172
- return StirImageData(float(other) + self._obj)
175
+ if isinstance(other, stir.FloatVoxelsOnCartesianGrid):
176
+ return StirImageData(other) + self
177
+ return self + float(other)
173
178
 
174
179
  def __rsub__(self, other):
175
- return StirImageData(float(other) - self._obj)
180
+ if isinstance(other, stir.FloatVoxelsOnCartesianGrid):
181
+ return StirImageData(other) - self
182
+ return (self * -1.0) + float(other)
176
183
 
177
184
  def __rmul__(self, other):
178
- return StirImageData(float(other) * self._obj)
185
+ if isinstance(other, stir.FloatVoxelsOnCartesianGrid):
186
+ return StirImageData(other) * self
187
+ return self * float(other)
179
188
 
180
189
  def __rtruediv__(self, other):
181
- return StirImageData(float(other) / self._obj)
190
+ if isinstance(other, stir.FloatVoxelsOnCartesianGrid):
191
+ return StirImageData(other) / self
192
+ return self.get_uniform_copy(float(other)) / self
182
193
 
183
194
  def __neg__(self):
184
- return StirImageData(-self._obj)
195
+ return self * -1.0
185
196
 
186
197
  def sapyb(self, a: float, y: "StirImageData", b: float) -> "StirImageData":
187
198
  """Compute self * a + y * b (element-wise), modifying self in place.
@@ -281,12 +292,12 @@ class StirAcquisitionData(AcquisitionDataInterface):
281
292
  def dimensions(self) -> Tuple:
282
293
  """Get dimensions."""
283
294
  # Extract from numpy array
284
- arr = stirextra.to_numpy(self._obj)
295
+ arr = _import_stir_extra().to_numpy(self._obj)
285
296
  return arr.shape
286
297
 
287
298
  def as_array(self) -> np.ndarray:
288
- """Convert to numpy array using stirextra."""
289
- return stirextra.to_numpy(self._obj)
299
+ """Convert to numpy array using stir.extra."""
300
+ return _import_stir_extra().to_numpy(self._obj)
290
301
 
291
302
  def sum(self) -> float:
292
303
  """Sum all values."""
@@ -363,19 +374,27 @@ class StirAcquisitionData(AcquisitionDataInterface):
363
374
  return StirAcquisitionData(self._obj / float(other))
364
375
 
365
376
  def __radd__(self, other):
366
- return StirAcquisitionData(float(other) + self._obj)
377
+ if isinstance(other, stir.ProjData):
378
+ return StirAcquisitionData(other) + self
379
+ return self + float(other)
367
380
 
368
381
  def __rsub__(self, other):
369
- return StirAcquisitionData(float(other) - self._obj)
382
+ if isinstance(other, stir.ProjData):
383
+ return StirAcquisitionData(other) - self
384
+ return (self * -1.0) + float(other)
370
385
 
371
386
  def __rmul__(self, other):
372
- return StirAcquisitionData(float(other) * self._obj)
387
+ if isinstance(other, stir.ProjData):
388
+ return StirAcquisitionData(other) * self
389
+ return self * float(other)
373
390
 
374
391
  def __rtruediv__(self, other):
375
- return StirAcquisitionData(float(other) / self._obj)
392
+ if isinstance(other, stir.ProjData):
393
+ return StirAcquisitionData(other) / self
394
+ return self.get_uniform_copy(float(other)) / self
376
395
 
377
396
  def __neg__(self):
378
- return StirAcquisitionData(-self._obj)
397
+ return self * -1.0
379
398
 
380
399
  def sapyb(
381
400
  self, a: float, y: "StirAcquisitionData", b: float
@@ -4,6 +4,33 @@ from __future__ import annotations
4
4
 
5
5
  from typing import Any, Optional
6
6
 
7
+ import numpy as np
8
+
9
+
10
+ def normalize_voxel_size_mm(voxel_size_mm: Any) -> tuple[float, float, float]:
11
+ """Return positive voxel spacing in canonical ``(z, y, x)`` order."""
12
+ try:
13
+ values = np.asarray(voxel_size_mm, dtype=float)
14
+ except (TypeError, ValueError) as exc:
15
+ raise ValueError(
16
+ "voxel_size_mm must be a scalar or a (z, y, x) sequence"
17
+ ) from exc
18
+ if values.ndim == 0:
19
+ z = y = x = float(values)
20
+ elif values.ndim == 1 and values.size == 3:
21
+ z, y, x = (float(value) for value in values)
22
+ else:
23
+ raise ValueError("voxel_size_mm must be a scalar or a (z, y, x) sequence")
24
+ if not np.isfinite((z, y, x)).all() or min(z, y, x) <= 0:
25
+ raise ValueError(
26
+ "voxel_size_mm must be > 0 and all spacing values must be finite"
27
+ )
28
+ if abs(y - x) > 1e-3:
29
+ raise ValueError(
30
+ f"SIMIND requires square in-plane voxels; got y={y} mm and x={x} mm"
31
+ )
32
+ return z, y, x
33
+
7
34
 
8
35
  def _call_or_value(value: Any) -> Any:
9
36
  return value() if callable(value) else value
@@ -45,11 +72,13 @@ def _spacing_zyx(spacing: Any) -> Optional[tuple[float, float, float]]:
45
72
  return None
46
73
 
47
74
 
48
- def extract_voxel_size_mm(image: Any, backend_name: str) -> float:
49
- """Return the voxel size in mm from backend image metadata.
75
+ def extract_voxel_spacing_mm(
76
+ image: Any, backend_name: str
77
+ ) -> tuple[float, float, float]:
78
+ """Return voxel spacing in mm from backend image metadata, in (z, y, x).
50
79
 
51
- Backend images report spacing in ``(z, y, x)`` order. The connector takes a
52
- single voxel size, so the voxels must be cubic.
80
+ SIMIND supports axial spacing distinct from the in-plane image spacing;
81
+ the in-plane dimensions must remain square.
53
82
  """
54
83
  zyx = None
55
84
  if hasattr(image, "voxel_sizes"):
@@ -72,12 +101,99 @@ def extract_voxel_size_mm(image: Any, backend_name: str) -> float:
72
101
  f"{backend_name} source object must expose voxel_sizes() or "
73
102
  "get_grid_spacing()."
74
103
  )
75
- if max(zyx) - min(zyx) > 1e-3:
104
+ try:
105
+ return normalize_voxel_size_mm(zyx)
106
+ except ValueError as exc:
107
+ raise ValueError(
108
+ f"{backend_name} voxel spacing is invalid (z, y, x) = {tuple(zyx)} mm: "
109
+ f"{exc}"
110
+ ) from exc
111
+
112
+
113
+ def extract_voxel_size_mm(image: Any, backend_name: str) -> float:
114
+ """Return a scalar for legacy callers when backend voxels are cubic."""
115
+ z, y, x = extract_voxel_spacing_mm(image, backend_name)
116
+ if max(z, y, x) - min(z, y, x) > 1e-3:
76
117
  raise ValueError(
77
118
  f"{backend_name} images must have cubic voxels; got (z, y, x) = "
78
- f"{tuple(zyx)} mm"
119
+ f"{(z, y, x)} mm"
79
120
  )
80
- return float(zyx[0])
121
+ return z
122
+
123
+
124
+ def _numeric_array(value: Any) -> Optional[np.ndarray]:
125
+ try:
126
+ return np.asarray(value, dtype=float).reshape(-1)
127
+ except (TypeError, ValueError):
128
+ return None
129
+
130
+
131
+ def _spatial_geometry(image: Any) -> Optional[tuple[Any, ...]]:
132
+ """Read native geometry where the backend exposes a documented API.
133
+
134
+ SIRF's ImageData returns a GeometricalInfo from
135
+ ``get_geometrical_info()``, with offset, spacing, and direction-matrix getters.
136
+ STIR's VoxelsOnCartesianGrid exposes origin and signed grid spacing.
137
+ """
138
+ native_object = getattr(image, "native_object", image)
139
+ image = native_object() if callable(native_object) else native_object
140
+
141
+ get_geometrical_info = getattr(image, "get_geometrical_info", None)
142
+ if callable(get_geometrical_info):
143
+ info = get_geometrical_info()
144
+ getters = ("get_offset", "get_spacing", "get_direction_matrix")
145
+ if not all(callable(getattr(info, name, None)) for name in getters):
146
+ raise ValueError(
147
+ "Unable to read SIRF geometry from get_geometrical_info()."
148
+ )
149
+ arrays = [_numeric_array(getattr(info, name)()) for name in getters]
150
+ if any(array is None or not array.size for array in arrays):
151
+ raise ValueError(
152
+ "Unable to read SIRF geometry from get_geometrical_info()."
153
+ )
154
+ if any(not np.isfinite(array).all() for array in arrays if array is not None):
155
+ raise ValueError("SIRF geometry values must be finite.")
156
+ return ("sirf", np.concatenate(arrays))
157
+
158
+ get_origin = getattr(image, "get_origin", None)
159
+ get_grid_spacing = getattr(image, "get_grid_spacing", None)
160
+ if callable(get_origin) and callable(get_grid_spacing):
161
+ origin = _spacing_zyx(get_origin())
162
+ spacing = _spacing_zyx(get_grid_spacing())
163
+ if origin is None or spacing is None:
164
+ return None
165
+ minimum_indices = []
166
+ for axis in "zyx":
167
+ getter = getattr(image, f"get_min_{axis}", None)
168
+ if not callable(getter):
169
+ return None
170
+ minimum_indices.append(float(getter()))
171
+ physical_start = np.asarray(origin) + np.asarray(minimum_indices) * np.asarray(
172
+ spacing
173
+ )
174
+ return (
175
+ "stir",
176
+ physical_start,
177
+ )
178
+ return None
81
179
 
82
180
 
83
- __all__ = ["extract_voxel_size_mm"]
181
+ def same_spatial_geometry(source: Any, mu_map: Any) -> bool:
182
+ """Compare origins, spacing, and axis directions when both APIs expose them."""
183
+ source_geometry = _spatial_geometry(source)
184
+ mu_geometry = _spatial_geometry(mu_map)
185
+ if source_geometry is None and mu_geometry is None:
186
+ return True
187
+ if source_geometry is None or mu_geometry is None:
188
+ return False
189
+ return source_geometry[0] == mu_geometry[0] and np.allclose(
190
+ source_geometry[1], mu_geometry[1], rtol=0.0, atol=1e-3
191
+ )
192
+
193
+
194
+ __all__ = [
195
+ "extract_voxel_size_mm",
196
+ "extract_voxel_spacing_mm",
197
+ "normalize_voxel_size_mm",
198
+ "same_spatial_geometry",
199
+ ]