imops 0.8.2__cp39-cp39-win32.whl → 0.8.3__cp39-cp39-win32.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.

Potentially problematic release.


This version of imops might be problematic. Click here for more details.

Files changed (48) hide show
  1. _build_utils.py +87 -0
  2. imops/__init__.py +1 -0
  3. imops/__version__.py +1 -1
  4. imops/backend.py +14 -10
  5. imops/crop.py +18 -2
  6. imops/interp1d.py +7 -4
  7. imops/measure.py +7 -7
  8. imops/morphology.py +6 -5
  9. imops/numeric.py +376 -0
  10. imops/pad.py +41 -5
  11. imops/radon.py +7 -5
  12. imops/src/_backprojection.c +83 -83
  13. imops/src/_backprojection.cp39-win32.pyd +0 -0
  14. imops/src/_fast_backprojection.c +96 -96
  15. imops/src/_fast_backprojection.cp39-win32.pyd +0 -0
  16. imops/src/_fast_measure.c +96 -96
  17. imops/src/_fast_measure.cp39-win32.pyd +0 -0
  18. imops/src/_fast_morphology.c +96 -96
  19. imops/src/_fast_morphology.cp39-win32.pyd +0 -0
  20. imops/src/_fast_numeric.c +20545 -4996
  21. imops/src/_fast_numeric.cp39-win32.pyd +0 -0
  22. imops/src/_fast_numeric.pyx +208 -30
  23. imops/src/_fast_radon.c +96 -96
  24. imops/src/_fast_radon.cp39-win32.pyd +0 -0
  25. imops/src/_fast_zoom.c +96 -96
  26. imops/src/_fast_zoom.cp39-win32.pyd +0 -0
  27. imops/src/_measure.c +83 -83
  28. imops/src/_measure.cp39-win32.pyd +0 -0
  29. imops/src/_morphology.c +83 -83
  30. imops/src/_morphology.cp39-win32.pyd +0 -0
  31. imops/src/_numeric.c +20532 -4983
  32. imops/src/_numeric.cp39-win32.pyd +0 -0
  33. imops/src/_numeric.pyx +208 -30
  34. imops/src/_radon.c +83 -83
  35. imops/src/_radon.cp39-win32.pyd +0 -0
  36. imops/src/_zoom.c +83 -83
  37. imops/src/_zoom.cp39-win32.pyd +0 -0
  38. imops/utils.py +65 -12
  39. imops/zoom.py +2 -2
  40. {imops-0.8.2.dist-info → imops-0.8.3.dist-info}/METADATA +3 -2
  41. imops-0.8.3.dist-info/RECORD +60 -0
  42. {imops-0.8.2.dist-info → imops-0.8.3.dist-info}/WHEEL +1 -1
  43. imops-0.8.3.dist-info/top_level.txt +2 -0
  44. _pyproject_build.py +0 -61
  45. imops/_numeric.py +0 -124
  46. imops-0.8.2.dist-info/RECORD +0 -60
  47. imops-0.8.2.dist-info/top_level.txt +0 -2
  48. {imops-0.8.2.dist-info → imops-0.8.3.dist-info}/LICENSE +0 -0
_build_utils.py ADDED
@@ -0,0 +1,87 @@
1
+ import platform
2
+ import shutil
3
+ from pathlib import Path
4
+
5
+ from setuptools import Extension
6
+ from setuptools.command.build_py import build_py
7
+
8
+
9
+ class NumpyImport(dict):
10
+ """Hacky way to return Numpy's `include` path with lazy import."""
11
+
12
+ # Must be json-serializable due to
13
+ # https://github.com/cython/cython/blob/6ad6ca0e9e7d030354b7fe7d7b56c3f6e6a4bc23/Cython/Compiler/ModuleNode.py#L773
14
+ def __init__(self):
15
+ return super().__init__(self, description=self.__doc__)
16
+
17
+ # Must be hashable due to
18
+ # https://github.com/cython/cython/blob/6ad6ca0e9e7d030354b7fe7d7b56c3f6e6a4bc23/Cython/Compiler/Main.py#L307
19
+ def __hash__(self):
20
+ return id(self)
21
+
22
+ def __repr__(self):
23
+ import numpy as np
24
+
25
+ return np.get_include()
26
+
27
+ __fspath__ = __repr__
28
+
29
+
30
+ class NumpyLibImport(str):
31
+ """Hacky way to return Numpy's `lib` path with lazy import."""
32
+
33
+ # Exploit of https://github.com/pypa/setuptools/blob/1ef36f2d336e239bd8f83507cb9447e060b6ed60/setuptools/_distutils/
34
+ # unixccompiler.py#L276-L277
35
+ def __radd__(self, left):
36
+ import numpy as np
37
+
38
+ return left + str(Path(np.get_include()).parent / 'lib')
39
+
40
+ def __hash__(self):
41
+ return id(self)
42
+
43
+
44
+ class PyprojectBuild(build_py):
45
+ def run(self):
46
+ self.run_command('build_ext')
47
+ return super().run()
48
+
49
+ def initialize_options(self):
50
+ super().initialize_options()
51
+
52
+ self.distribution.ext_modules = get_ext_modules()
53
+
54
+
55
+ def get_ext_modules():
56
+ name = 'imops'
57
+ on_windows = platform.system() == 'Windows'
58
+ args = ['/openmp' if on_windows else '-fopenmp']
59
+
60
+ # Cython extension and .pyx source file names must be the same to compile
61
+ # https://stackoverflow.com/questions/8024805/cython-compiled-c-extension-importerror-dynamic-module-does-not-define-init-fu
62
+ modules = ['backprojection', 'measure', 'morphology', 'numeric', 'radon', 'zoom']
63
+ modules_to_link_against_numpy_core_math_lib = ['numeric']
64
+
65
+ for module in modules:
66
+ src_dir = Path(__file__).parent / name / 'src'
67
+ shutil.copyfile(src_dir / f'_{module}.pyx', src_dir / f'_fast_{module}.pyx')
68
+
69
+ return [
70
+ Extension(
71
+ f'{name}.src._{prefix}{module}',
72
+ [f'{name}/src/_{prefix}{module}.pyx'],
73
+ include_dirs=[NumpyImport()],
74
+ library_dirs=[NumpyLibImport()] if module in modules_to_link_against_numpy_core_math_lib else [],
75
+ libraries=['npymath'] + ['m'] * (not on_windows)
76
+ if module in modules_to_link_against_numpy_core_math_lib
77
+ else [],
78
+ extra_compile_args=args + additional_args,
79
+ extra_link_args=args + additional_args,
80
+ define_macros=[('NPY_NO_DEPRECATED_API', 'NPY_1_7_API_VERSION')],
81
+ )
82
+ for module in modules
83
+ # FIXME: import of `ffast-math` compiled modules changes global FPU state, so now `fast=True` will just
84
+ # fallback to standard `-O2` compiled versions until https://github.com/neuro-ml/imops/issues/37 is resolved
85
+ # for prefix, additional_args in zip(['', 'fast_'], [[], ['-ffast-math']])
86
+ for prefix, additional_args in zip(['', 'fast_'], [[], []])
87
+ ]
imops/__init__.py CHANGED
@@ -4,6 +4,7 @@ from .crop import crop_to_box, crop_to_shape
4
4
  from .interp1d import interp1d
5
5
  from .measure import label
6
6
  from .morphology import binary_closing, binary_dilation, binary_erosion, binary_opening
7
+ from .numeric import copy, fill_, full, pointwise_add
7
8
  from .pad import pad, pad_to_divisible, pad_to_shape, restore_crop
8
9
  from .radon import inverse_radon, radon
9
10
  from .zoom import _zoom, zoom, zoom_to_shape
imops/__version__.py CHANGED
@@ -1 +1 @@
1
- __version__ = '0.8.2'
1
+ __version__ = '0.8.3'
imops/backend.py CHANGED
@@ -1,14 +1,15 @@
1
- import contextlib
1
+ from contextlib import contextmanager
2
2
  from dataclasses import dataclass
3
3
  from typing import Dict, Type, Union
4
+ from warnings import warn
4
5
 
5
6
 
6
7
  class Backend:
7
8
  def __init_subclass__(cls, **kwargs):
8
9
  name = cls.__name__
9
- if name in AVAILABLE_BACKENDS:
10
+ if name in _AVAILABLE_BACKENDS:
10
11
  raise ValueError(f'The name "{name}" is already in use.')
11
- AVAILABLE_BACKENDS[name] = cls
12
+ _AVAILABLE_BACKENDS[name] = cls
12
13
  if not hasattr(Backend, name):
13
14
  setattr(Backend, name, cls)
14
15
 
@@ -22,18 +23,18 @@ class Backend:
22
23
 
23
24
 
24
25
  BackendLike = Union[str, Backend, Type[Backend], None]
25
- AVAILABLE_BACKENDS: Dict[str, Type[Backend]] = {}
26
+ _AVAILABLE_BACKENDS: Dict[str, Type[Backend]] = {}
26
27
 
27
28
 
28
- def resolve_backend(value: BackendLike) -> Backend:
29
+ def resolve_backend(value: BackendLike, warn_stacklevel: int = 1) -> Backend:
29
30
  if value is None:
30
31
  return DEFAULT_BACKEND
31
32
 
32
33
  if isinstance(value, str):
33
- if value not in AVAILABLE_BACKENDS:
34
- raise ValueError(f'"{value}" is not in the list of available backends: {tuple(AVAILABLE_BACKENDS)}.')
34
+ if value not in _AVAILABLE_BACKENDS:
35
+ raise ValueError(f'"{value}" is not in the list of available backends: {tuple(_AVAILABLE_BACKENDS)}.')
35
36
 
36
- return AVAILABLE_BACKENDS[value]()
37
+ return _AVAILABLE_BACKENDS[value]()
37
38
 
38
39
  if isinstance(value, type):
39
40
  value = value()
@@ -41,6 +42,9 @@ def resolve_backend(value: BackendLike) -> Backend:
41
42
  if not isinstance(value, Backend):
42
43
  raise ValueError(f'Expected a `Backend` instance, got {value}.')
43
44
 
45
+ if isinstance(value, Cython) and value.fast:
46
+ warn('`fast=True` has no effect for `Cython` backend for now.', stacklevel=warn_stacklevel)
47
+
44
48
  return value
45
49
 
46
50
 
@@ -51,7 +55,7 @@ def set_backend(backend: BackendLike) -> Backend:
51
55
  return current
52
56
 
53
57
 
54
- @contextlib.contextmanager
58
+ @contextmanager
55
59
  def imops_backend(backend: BackendLike):
56
60
  previous = set_backend(backend)
57
61
  try:
@@ -87,5 +91,5 @@ class Scipy(Backend):
87
91
 
88
92
  DEFAULT_BACKEND = Cython()
89
93
 
90
- BACKEND2NUM_THREADS_VAR_NAME = {Cython.__name__: 'OMP_NUM_THREADS', Numba.__name__: 'NUMBA_NUM_THREADS'}
94
+ BACKEND_NAME2ENV_NUM_THREADS_VAR_NAME = {Cython.__name__: 'OMP_NUM_THREADS', Numba.__name__: 'NUMBA_NUM_THREADS'}
91
95
  SINGLE_THREADED_BACKENDS = (Scipy.__name__,)
imops/crop.py CHANGED
@@ -1,5 +1,7 @@
1
1
  import numpy as np
2
2
 
3
+ from .backend import BackendLike
4
+ from .numeric import _NUMERIC_DEFAULT_NUM_THREADS
3
5
  from .pad import pad
4
6
  from .utils import AxesLike, AxesParams, broadcast_axis, fill_by_indices
5
7
 
@@ -43,10 +45,18 @@ def crop_to_shape(x: np.ndarray, shape: AxesLike, axis: AxesLike = None, ratio:
43
45
  ratio = fill_by_indices(np.zeros(ndim), ratio, axis)
44
46
  start = ((old_shape - new_shape) * ratio).astype(int)
45
47
 
48
+ # TODO: Create contiguous array?
46
49
  return x[tuple(map(slice, start, start + new_shape))]
47
50
 
48
51
 
49
- def crop_to_box(x: np.ndarray, box: np.ndarray, axis: AxesLike = None, padding_values: AxesParams = None) -> np.ndarray:
52
+ def crop_to_box(
53
+ x: np.ndarray,
54
+ box: np.ndarray,
55
+ axis: AxesLike = None,
56
+ padding_values: AxesParams = None,
57
+ num_threads: int = _NUMERIC_DEFAULT_NUM_THREADS,
58
+ backend: BackendLike = None,
59
+ ) -> np.ndarray:
50
60
  """
51
61
  Crop `x` according to `box` along `axis`.
52
62
 
@@ -60,6 +70,11 @@ def crop_to_box(x: np.ndarray, box: np.ndarray, axis: AxesLike = None, padding_v
60
70
  axis along which `x` will be cropped
61
71
  padding_values: AxesParams
62
72
  values to pad with if box exceeds the input's limits
73
+ num_threads: int
74
+ the number of threads to use for computation. Default = 4. If negative value passed
75
+ cpu count + num_threads + 1 threads will be used
76
+ backend: BackendLike
77
+ which backend to use. `cython` and `scipy` are available, `cython` is used by default
63
78
 
64
79
  Returns
65
80
  -------
@@ -86,9 +101,10 @@ def crop_to_box(x: np.ndarray, box: np.ndarray, axis: AxesLike = None, padding_v
86
101
 
87
102
  slice_start = fill_by_indices(np.zeros(x.ndim, int), slice_start, axis)
88
103
  slice_stop = fill_by_indices(x.shape, slice_stop, axis)
104
+ # TODO: Create contiguous array?
89
105
  x = x[tuple(map(slice, slice_start, slice_stop))]
90
106
 
91
107
  if padding_values is not None and padding.any():
92
- x = pad(x, padding, axis, padding_values)
108
+ x = pad(x, padding, axis, padding_values, num_threads=num_threads, backend=backend)
93
109
 
94
110
  return x
imops/interp1d.py CHANGED
@@ -5,6 +5,7 @@ import numpy as np
5
5
  from scipy.interpolate import interp1d as scipy_interp1d
6
6
 
7
7
  from .backend import BackendLike, resolve_backend
8
+ from .numeric import copy as _copy
8
9
  from .src._fast_zoom import _interp1d as cython_fast_interp1d
9
10
  from .src._zoom import _interp1d as cython_interp1d
10
11
  from .utils import normalize_num_threads
@@ -74,7 +75,7 @@ class interp1d:
74
75
  num_threads: int = -1,
75
76
  backend: BackendLike = None,
76
77
  ) -> None:
77
- backend = resolve_backend(backend)
78
+ backend = resolve_backend(backend, warn_stacklevel=3)
78
79
  if backend.name not in ('Scipy', 'Numba', 'Cython'):
79
80
  raise ValueError(f'Unsupported backend "{backend.name}".')
80
81
 
@@ -88,6 +89,7 @@ class interp1d:
88
89
  warn(
89
90
  "Fast interpolation is only supported for ndim<=3, dtype=float32 or float64, order=1 or 'linear'. "
90
91
  "Falling back to scipy's implementation.",
92
+ stacklevel=2,
91
93
  )
92
94
  self.scipy_interp1d = scipy_interp1d(x, y, kind, axis, copy, bounds_error, fill_value, assume_sorted)
93
95
  else:
@@ -114,12 +116,13 @@ class interp1d:
114
116
 
115
117
  self.fill_value = fill_value
116
118
  self.scipy_interp1d = None
117
- self.x = np.copy(x) if copy else x
119
+ # FIXME: how to accurately pass `num_threads` and `backend` arguments to `copy`?
120
+ self.x = _copy(x, order='C') if copy else x
118
121
  self.n_dummy = 3 - y.ndim
119
122
  self.y = y[(None,) * self.n_dummy] if self.n_dummy else y
120
123
 
121
124
  if copy:
122
- self.y = np.copy(self.y)
125
+ self.y = _copy(self.y, order='C')
123
126
 
124
127
  self.assume_sorted = assume_sorted
125
128
 
@@ -149,7 +152,7 @@ class interp1d:
149
152
  interpolated values. Shape is determined by replacing the interpolation axis in the original array with
150
153
  the shape of x
151
154
  """
152
- num_threads = normalize_num_threads(self.num_threads, self.backend)
155
+ num_threads = normalize_num_threads(self.num_threads, self.backend, warn_stacklevel=3)
153
156
 
154
157
  if self.scipy_interp1d is not None:
155
158
  return self.scipy_interp1d(x_new)
imops/measure.py CHANGED
@@ -19,7 +19,7 @@ from .utils import normalize_num_threads
19
19
 
20
20
 
21
21
  # (ndim, skimage_connectivity) -> cc3d_connectivity
22
- skimage2cc3d = {
22
+ _SKIMAGE2CC3D = {
23
23
  (1, 1): 4,
24
24
  (2, 1): 4,
25
25
  (2, 2): 8,
@@ -90,7 +90,7 @@ def label(
90
90
  raise ValueError(f'Connectivity for {ndim}D image should be in [1, ..., {ndim}]. Got {connectivity}.')
91
91
 
92
92
  if ndim > 3:
93
- warn("Fast label is only supported for ndim<=3, Falling back to scikit-image's implementation.")
93
+ warn("Fast label is only supported for ndim<=3, Falling back to scikit-image's implementation.", stacklevel=2)
94
94
  labeled_image, num_components = skimage_label(
95
95
  label_image, background=background, return_num=True, connectivity=connectivity
96
96
  )
@@ -110,7 +110,7 @@ def label(
110
110
 
111
111
  labeled_image, num_components = connected_components(
112
112
  label_image,
113
- connectivity=skimage2cc3d[(ndim, connectivity)],
113
+ connectivity=_SKIMAGE2CC3D[(ndim, connectivity)],
114
114
  return_N=True,
115
115
  **{'out_dtype': dtype} if python_version()[:3] != '3.6' else {},
116
116
  )
@@ -174,19 +174,19 @@ def center_of_mass(
174
174
  if (labels is None) ^ (index is None):
175
175
  raise ValueError('`labels` and `index` should be both specified or both not specified.')
176
176
 
177
- backend = resolve_backend(backend)
177
+ backend = resolve_backend(backend, warn_stacklevel=3)
178
178
 
179
179
  if backend.name not in ('Scipy', 'Cython'):
180
180
  raise ValueError(f'Unsupported backend "{backend.name}".')
181
181
 
182
- num_threads = normalize_num_threads(num_threads, backend)
182
+ num_threads = normalize_num_threads(num_threads, backend, warn_stacklevel=3)
183
183
 
184
184
  if backend.name == 'Scipy':
185
185
  return scipy_center_of_mass(array, labels, index)
186
186
 
187
187
  ndim = array.ndim
188
188
  if ndim > 3:
189
- warn("Fast center-of-mass is only supported for ndim<=3. Falling back to scipy's implementation.")
189
+ warn("Fast center-of-mass is only supported for ndim<=3. Falling back to scipy's implementation.", stacklevel=2)
190
190
  return scipy_center_of_mass(array, labels, index)
191
191
 
192
192
  if labels is None:
@@ -205,7 +205,7 @@ def center_of_mass(
205
205
  raise ValueError('`index` should consist of unique values.')
206
206
 
207
207
  if num_threads > 1:
208
- warn('Using single-threaded implementation as `labels` and `index` are specified.')
208
+ warn('Using single-threaded implementation as `labels` and `index` are specified.', stacklevel=2)
209
209
 
210
210
  src_center_of_mass = _fast_labeled_center_of_mass if backend.fast else _labeled_center_of_mass
211
211
 
imops/morphology.py CHANGED
@@ -28,12 +28,12 @@ def morphology_op_wrapper(
28
28
  num_threads: int = -1,
29
29
  backend: BackendLike = None,
30
30
  ) -> np.ndarray:
31
- backend = resolve_backend(backend)
31
+ backend = resolve_backend(backend, warn_stacklevel=4)
32
32
  if backend.name not in {x.name for x in backend2src_op.keys()}:
33
33
  raise ValueError(f'Unsupported backend "{backend.name}".')
34
34
 
35
35
  ndim = image.ndim
36
- num_threads = normalize_num_threads(num_threads, backend)
36
+ num_threads = normalize_num_threads(num_threads, backend, warn_stacklevel=4)
37
37
 
38
38
  if footprint is None:
39
39
  footprint = generate_binary_structure(ndim, 1)
@@ -60,7 +60,8 @@ def morphology_op_wrapper(
60
60
  if ndim > 3:
61
61
  warn(
62
62
  f"Fast {' '.join(op_name.split('_'))} is only supported for ndim<=3. "
63
- "Falling back to scipy's implementation."
63
+ "Falling back to scipy's implementation.",
64
+ stacklevel=3,
64
65
  )
65
66
  output = backend2src_op[Scipy()](image, footprint)
66
67
 
@@ -70,13 +71,13 @@ def morphology_op_wrapper(
70
71
  raise ValueError('Input image and footprint number of dimensions must be the same.')
71
72
 
72
73
  if not image.any():
73
- warn(f'{op_name} is applied to the fully False mask (mask.any() == False).')
74
+ warn(f'{op_name} is applied to the fully False mask (mask.any() == False).', stacklevel=3)
74
75
  output.fill(False)
75
76
 
76
77
  return output
77
78
 
78
79
  if image.all():
79
- warn(f'{op_name} is applied to the fully True mask (mask.all() == True).')
80
+ warn(f'{op_name} is applied to the fully True mask (mask.all() == True).', stacklevel=3)
80
81
  output.fill(True)
81
82
 
82
83
  return output