ngio 0.3.4__py3-none-any.whl → 0.4.0__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 (73) hide show
  1. ngio/__init__.py +7 -2
  2. ngio/common/__init__.py +5 -52
  3. ngio/common/_dimensions.py +270 -55
  4. ngio/common/_masking_roi.py +38 -10
  5. ngio/common/_pyramid.py +51 -30
  6. ngio/common/_roi.py +269 -82
  7. ngio/common/_synt_images_utils.py +101 -0
  8. ngio/common/_zoom.py +49 -19
  9. ngio/experimental/__init__.py +5 -0
  10. ngio/experimental/iterators/__init__.py +15 -0
  11. ngio/experimental/iterators/_abstract_iterator.py +390 -0
  12. ngio/experimental/iterators/_feature.py +189 -0
  13. ngio/experimental/iterators/_image_processing.py +130 -0
  14. ngio/experimental/iterators/_mappers.py +48 -0
  15. ngio/experimental/iterators/_rois_utils.py +127 -0
  16. ngio/experimental/iterators/_segmentation.py +235 -0
  17. ngio/hcs/_plate.py +41 -36
  18. ngio/images/__init__.py +22 -1
  19. ngio/images/_abstract_image.py +403 -176
  20. ngio/images/_create.py +31 -15
  21. ngio/images/_create_synt_container.py +138 -0
  22. ngio/images/_image.py +452 -63
  23. ngio/images/_label.py +56 -30
  24. ngio/images/_masked_image.py +387 -129
  25. ngio/images/_ome_zarr_container.py +237 -67
  26. ngio/{common → images}/_table_ops.py +41 -41
  27. ngio/io_pipes/__init__.py +75 -0
  28. ngio/io_pipes/_io_pipes.py +361 -0
  29. ngio/io_pipes/_io_pipes_masked.py +488 -0
  30. ngio/io_pipes/_io_pipes_roi.py +152 -0
  31. ngio/io_pipes/_io_pipes_types.py +56 -0
  32. ngio/io_pipes/_match_shape.py +376 -0
  33. ngio/io_pipes/_ops_axes.py +344 -0
  34. ngio/io_pipes/_ops_slices.py +446 -0
  35. ngio/io_pipes/_ops_slices_utils.py +196 -0
  36. ngio/io_pipes/_ops_transforms.py +104 -0
  37. ngio/io_pipes/_zoom_transform.py +175 -0
  38. ngio/ome_zarr_meta/__init__.py +4 -2
  39. ngio/ome_zarr_meta/ngio_specs/__init__.py +4 -10
  40. ngio/ome_zarr_meta/ngio_specs/_axes.py +186 -175
  41. ngio/ome_zarr_meta/ngio_specs/_channels.py +55 -18
  42. ngio/ome_zarr_meta/ngio_specs/_dataset.py +48 -122
  43. ngio/ome_zarr_meta/ngio_specs/_ngio_hcs.py +6 -15
  44. ngio/ome_zarr_meta/ngio_specs/_ngio_image.py +38 -87
  45. ngio/ome_zarr_meta/ngio_specs/_pixel_size.py +17 -1
  46. ngio/ome_zarr_meta/v04/_v04_spec_utils.py +34 -31
  47. ngio/resources/20200812-CardiomyocyteDifferentiation14-Cycle1_B03/mask.png +0 -0
  48. ngio/resources/20200812-CardiomyocyteDifferentiation14-Cycle1_B03/nuclei.png +0 -0
  49. ngio/resources/20200812-CardiomyocyteDifferentiation14-Cycle1_B03/raw.jpg +0 -0
  50. ngio/resources/__init__.py +55 -0
  51. ngio/resources/resource_model.py +36 -0
  52. ngio/tables/backends/_abstract_backend.py +5 -6
  53. ngio/tables/backends/_anndata.py +1 -2
  54. ngio/tables/backends/_anndata_utils.py +3 -3
  55. ngio/tables/backends/_non_zarr_backends.py +1 -1
  56. ngio/tables/backends/_table_backends.py +0 -1
  57. ngio/tables/backends/_utils.py +3 -3
  58. ngio/tables/v1/_roi_table.py +165 -70
  59. ngio/transforms/__init__.py +5 -0
  60. ngio/transforms/_zoom.py +19 -0
  61. ngio/utils/__init__.py +2 -3
  62. ngio/utils/_datasets.py +5 -0
  63. ngio/utils/_logger.py +19 -0
  64. ngio/utils/_zarr_utils.py +6 -6
  65. {ngio-0.3.4.dist-info → ngio-0.4.0.dist-info}/METADATA +24 -22
  66. ngio-0.4.0.dist-info/RECORD +85 -0
  67. ngio/common/_array_pipe.py +0 -288
  68. ngio/common/_axes_transforms.py +0 -64
  69. ngio/common/_common_types.py +0 -5
  70. ngio/common/_slicer.py +0 -96
  71. ngio-0.3.4.dist-info/RECORD +0 -61
  72. {ngio-0.3.4.dist-info → ngio-0.4.0.dist-info}/WHEEL +0 -0
  73. {ngio-0.3.4.dist-info → ngio-0.4.0.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,376 @@
1
+ from collections.abc import Sequence
2
+ from enum import Enum
3
+
4
+ import dask.array as da
5
+ import numpy as np
6
+
7
+ from ngio.utils import NgioValueError, ngio_logger
8
+
9
+
10
+ class Action(str, Enum):
11
+ NONE = "none"
12
+ PAD = "pad"
13
+ TRIM = "trim"
14
+ RESCALING = "rescaling"
15
+
16
+
17
+ def _compute_pad_widths(
18
+ array_shape: tuple[int, ...],
19
+ actions: list[Action],
20
+ target_shape: tuple[int, ...],
21
+ ) -> tuple[tuple[int, int], ...]:
22
+ pad_def = []
23
+ for act, s, ts in zip(actions, array_shape, target_shape, strict=True):
24
+ if act == Action.PAD:
25
+ total_pad = ts - s
26
+ before = total_pad // 2
27
+ after = total_pad - before
28
+ pad_def.append((before, after))
29
+ else:
30
+ pad_def.append((0, 0))
31
+ ngio_logger.warning(
32
+ f"Images have a different shape ({array_shape} vs {target_shape}). "
33
+ f"Resolving by padding: {pad_def}",
34
+ stacklevel=2,
35
+ )
36
+ return tuple(pad_def)
37
+
38
+
39
+ def _numpy_pad(
40
+ array: np.ndarray,
41
+ actions: list[Action],
42
+ target_shape: tuple[int, ...],
43
+ pad_mode: str = "constant",
44
+ constant_values: int | float = 0,
45
+ ) -> np.ndarray:
46
+ if all(act != Action.PAD for act in actions):
47
+ return array
48
+ pad_widths = _compute_pad_widths(array.shape, actions, target_shape)
49
+ return np.pad(array, pad_widths, mode=pad_mode, constant_values=constant_values) # type: ignore
50
+
51
+
52
+ def _dask_pad(
53
+ array: da.Array,
54
+ actions: list[Action],
55
+ target_shape: tuple[int, ...],
56
+ pad_mode: str = "constant",
57
+ constant_values: int | float = 0,
58
+ ) -> da.Array:
59
+ if all(act != Action.PAD for act in actions):
60
+ return array
61
+ shape = tuple(int(s) for s in array.shape)
62
+ pad_widths = _compute_pad_widths(shape, actions, target_shape)
63
+ return da.pad(array, pad_widths, mode=pad_mode, constant_values=constant_values)
64
+
65
+
66
+ def _compute_trim_slices(
67
+ array_shape: tuple[int, ...],
68
+ actions: list[Action],
69
+ target_shape: tuple[int, ...],
70
+ ) -> tuple[slice, ...]:
71
+ slices = []
72
+ for act, s, ts in zip(actions, array_shape, target_shape, strict=True):
73
+ if act == Action.TRIM:
74
+ slices.append(slice(0, ts))
75
+ else:
76
+ slices.append(slice(0, s))
77
+
78
+ ngio_logger.warning(
79
+ f"Images have a different shape ({array_shape} vs {target_shape}). "
80
+ f"Resolving by trimming: {slices}",
81
+ stacklevel=2,
82
+ )
83
+ return tuple(slices)
84
+
85
+
86
+ def _numpy_trim(
87
+ array: np.ndarray, actions: list[Action], target_shape: tuple[int, ...]
88
+ ) -> np.ndarray:
89
+ if all(act != Action.TRIM for act in actions):
90
+ return array
91
+ slices = _compute_trim_slices(array.shape, actions, target_shape)
92
+ return array[tuple(slices)]
93
+
94
+
95
+ def _dask_trim(
96
+ array: da.Array, actions: list[Action], target_shape: tuple[int, ...]
97
+ ) -> da.Array:
98
+ if all(act != Action.TRIM for act in actions):
99
+ return array
100
+ shape = tuple(int(s) for s in array.shape)
101
+ slices = _compute_trim_slices(shape, actions, target_shape)
102
+ return array[tuple(slices)]
103
+
104
+
105
+ def _compute_rescaling_shape(
106
+ array_shape: tuple[int, ...],
107
+ actions: list[Action],
108
+ target_shape: tuple[int, ...],
109
+ ) -> tuple[int, ...]:
110
+ rescaling_shape = []
111
+ factor = []
112
+ for act, s, ts in zip(actions, array_shape, target_shape, strict=True):
113
+ if act == Action.RESCALING:
114
+ rescaling_shape.append(ts)
115
+ factor.append(ts / s)
116
+ else:
117
+ rescaling_shape.append(s)
118
+ factor.append(1.0)
119
+
120
+ ngio_logger.warning(
121
+ f"Images have a different shape ({array_shape} vs {target_shape}). "
122
+ f"Resolving by scaling with factors {factor}.",
123
+ stacklevel=2,
124
+ )
125
+ return tuple(rescaling_shape)
126
+
127
+
128
+ def _numpy_rescaling(
129
+ array: np.ndarray, actions: list[Action], target_shape: tuple[int, ...]
130
+ ) -> np.ndarray:
131
+ if all(act != Action.RESCALING for act in actions):
132
+ return array
133
+ from ngio.common._zoom import numpy_zoom
134
+
135
+ rescaling_shape = _compute_rescaling_shape(array.shape, actions, target_shape)
136
+ return numpy_zoom(source_array=array, target_shape=rescaling_shape, order="nearest")
137
+
138
+
139
+ def _dask_rescaling(
140
+ array: da.Array, actions: list[Action], target_shape: tuple[int, ...]
141
+ ) -> da.Array:
142
+ if all(act != Action.RESCALING for act in actions):
143
+ return array
144
+ from ngio.common._zoom import dask_zoom
145
+
146
+ shape = tuple(int(s) for s in array.shape)
147
+ rescaling_shape = _compute_rescaling_shape(shape, actions, target_shape)
148
+ return dask_zoom(source_array=array, target_shape=rescaling_shape, order="nearest")
149
+
150
+
151
+ def _check_axes(array_shape, reference_shape, array_axes, reference_axes):
152
+ if len(array_shape) != len(array_axes):
153
+ raise NgioValueError(
154
+ f"Array shape {array_shape} and reference axes {array_axes} "
155
+ "must have the same number of dimensions."
156
+ )
157
+ if len(reference_shape) != len(reference_axes):
158
+ raise NgioValueError(
159
+ f"Reference shape {reference_shape} and reference axes {reference_axes} "
160
+ "must have the same number of dimensions."
161
+ )
162
+
163
+ # Check if the array axes are a subset of the target axes
164
+ diff = set(array_axes) - set(reference_axes)
165
+ if diff:
166
+ raise NgioValueError(
167
+ f"Array axes {array_axes} are not a subset "
168
+ f"of reference axes {reference_axes}"
169
+ )
170
+
171
+ # Array must be smaller or equal in number of dimensions
172
+ if len(array_axes) > len(reference_axes):
173
+ raise NgioValueError(
174
+ f"Array has more dimensions ({len(array_axes)}) "
175
+ f"than reference ({len(reference_axes)}). "
176
+ "Cannot match shapes if the array has more dimensions."
177
+ )
178
+
179
+
180
+ def _compute_reshape_and_actions(
181
+ array_shape: tuple[int, ...],
182
+ reference_shape: tuple[int, ...],
183
+ array_axes: list[str],
184
+ reference_axes: list[str],
185
+ tolerance: int = 1,
186
+ allow_rescaling: bool = True,
187
+ ) -> tuple[tuple[int, ...], list[Action]]:
188
+ # Reshape array to match reference shape
189
+ # And determine actions to be taken
190
+ # to match the shapes
191
+ reshape_tuple = []
192
+ actions = []
193
+ errors = []
194
+ left_pointer = 0
195
+ for ref_ax, ref_shape in zip(reference_axes, reference_shape, strict=True):
196
+ if ref_ax not in array_axes:
197
+ reshape_tuple.append(1)
198
+ actions.append(Action.NONE)
199
+ elif ref_ax == array_axes[left_pointer]:
200
+ s2 = array_shape[left_pointer]
201
+ reshape_tuple.append(s2)
202
+ left_pointer += 1
203
+
204
+ if s2 == ref_shape or s2 == 1:
205
+ actions.append(Action.NONE)
206
+ elif s2 < ref_shape:
207
+ if (ref_shape - s2) <= tolerance:
208
+ actions.append(Action.PAD)
209
+ elif allow_rescaling:
210
+ actions.append(Action.RESCALING)
211
+ else:
212
+ errors.append(
213
+ f"Cannot pad axis={ref_ax}:{s2}->{ref_shape} "
214
+ "because shape difference is outside tolerance "
215
+ f"{tolerance}."
216
+ )
217
+ elif s2 > ref_shape:
218
+ if (s2 - ref_shape) <= tolerance:
219
+ actions.append(Action.TRIM)
220
+ elif allow_rescaling:
221
+ actions.append(Action.RESCALING)
222
+ else:
223
+ errors.append(
224
+ f"Cannot trim axis={ref_ax}:{s2}->{ref_shape} "
225
+ "because shape difference is outside tolerance "
226
+ f"{tolerance}."
227
+ )
228
+ else:
229
+ raise RuntimeError("Unreachable code reached.")
230
+ else:
231
+ raise NgioValueError(
232
+ f"Axes order mismatch {array_axes} -> {reference_axes}. "
233
+ "Cannot match shapes if the order is different."
234
+ )
235
+ if errors:
236
+ raise NgioValueError(
237
+ "Array shape cannot be matched to reference shape:\n\n".join(errors)
238
+ )
239
+ return tuple(reshape_tuple), actions
240
+
241
+
242
+ def numpy_match_shape(
243
+ array: np.ndarray,
244
+ reference_shape: tuple[int, ...],
245
+ array_axes: Sequence[str],
246
+ reference_axes: Sequence[str],
247
+ tolerance: int = 1,
248
+ pad_mode: str = "constant",
249
+ pad_values: int | float = 0,
250
+ allow_rescaling: bool = True,
251
+ ):
252
+ """Match the shape of a numpy array to a reference shape.
253
+
254
+ This function will reshape, pad, trim and broadcast the input array
255
+ to match the reference shape. If the shapes cannot be matched within
256
+ the specified tolerance, an error is raised.
257
+
258
+ The reference axes must be a superset of the array axes, and the order
259
+ of the axes must be the same.
260
+
261
+ Args:
262
+ array (np.ndarray): The input array to be reshaped.
263
+ reference_shape (tuple[int, ...]): The target shape to match.
264
+ array_axes (Sequence[str]): The axes names of the input array.
265
+ reference_axes (Sequence[str]): The axes names of the reference shape.
266
+ tolerance (int): The maximum number of pixels by which dimensions
267
+ can differ when matching shapes.
268
+ allow_broadcast (bool): If True, allow broadcasting new dimensions to
269
+ match the reference shape. If False, single-dimension axes will
270
+ be left as is.
271
+ pad_mode (str): The mode to use for padding. See numpy.pad for options.
272
+ pad_values (int | float): The constant value to use for padding if
273
+ pad_mode is 'constant'.
274
+ allow_rescaling (bool): If True, when the array differs more than the
275
+ tolerance, it will be rescalingd to the reference shape. If False,
276
+ an error will be raised.
277
+ """
278
+ _check_axes(
279
+ array_shape=array.shape,
280
+ reference_shape=reference_shape,
281
+ array_axes=array_axes,
282
+ reference_axes=reference_axes,
283
+ )
284
+ if array.shape == reference_shape:
285
+ # Shapes already match
286
+ return array
287
+
288
+ array_axes = list(array_axes)
289
+ reference_axes = list(reference_axes)
290
+
291
+ reshape_tuple, actions = _compute_reshape_and_actions(
292
+ array_shape=array.shape,
293
+ reference_shape=reference_shape,
294
+ array_axes=array_axes,
295
+ reference_axes=reference_axes,
296
+ tolerance=tolerance,
297
+ allow_rescaling=allow_rescaling,
298
+ )
299
+ array = array.reshape(reshape_tuple)
300
+ array = _numpy_rescaling(array=array, actions=actions, target_shape=reference_shape)
301
+ array = _numpy_pad(
302
+ array=array,
303
+ actions=actions,
304
+ target_shape=reference_shape,
305
+ pad_mode=pad_mode,
306
+ constant_values=pad_values,
307
+ )
308
+ array = _numpy_trim(array=array, actions=actions, target_shape=reference_shape)
309
+ return array
310
+
311
+
312
+ def dask_match_shape(
313
+ array: da.Array,
314
+ reference_shape: tuple[int, ...],
315
+ array_axes: Sequence[str],
316
+ reference_axes: Sequence[str],
317
+ tolerance: int = 1,
318
+ pad_mode: str = "constant",
319
+ pad_values: int | float = 0,
320
+ allow_rescaling: bool = True,
321
+ ) -> da.Array:
322
+ """Match the shape of a dask array to a reference shape.
323
+
324
+ This function will reshape, pad, trim and broadcast the input array
325
+ to match the reference shape. If the shapes cannot be matched within
326
+ the specified tolerance, an error is raised.
327
+
328
+ The reference axes must be a superset of the array axes, and the order
329
+ of the axes must be the same.
330
+
331
+ Args:
332
+ array (da.Array): The input array to be reshaped.
333
+ reference_shape (tuple[int, ...]): The target shape to match.
334
+ array_axes (Sequence[str]): The axes names of the input array.
335
+ reference_axes (Sequence[str]): The axes names of the reference shape.
336
+ tolerance (int): The maximum number of pixels by which dimensions
337
+ can differ when matching shapes.
338
+ pad_mode (str): The mode to use for padding. See numpy.pad for options.
339
+ pad_values (int | float): The constant value to use for padding if
340
+ pad_mode is 'constant'.
341
+ allow_rescaling (bool): If True, when the array differs more than the
342
+ tolerance, it will be rescalingd to the reference shape. If False,
343
+ an error will be raised.
344
+ """
345
+ array_shape = tuple(int(s) for s in array.shape)
346
+ _check_axes(
347
+ array_shape=array_shape,
348
+ reference_shape=reference_shape,
349
+ array_axes=array_axes,
350
+ reference_axes=reference_axes,
351
+ )
352
+ if array_shape == reference_shape:
353
+ # Shapes already match
354
+ return array
355
+ array_axes = list(array_axes)
356
+ reference_axes = list(reference_axes)
357
+
358
+ reshape_tuple, actions = _compute_reshape_and_actions(
359
+ array_shape=tuple(int(s) for s in array.shape),
360
+ reference_shape=reference_shape,
361
+ array_axes=array_axes,
362
+ reference_axes=reference_axes,
363
+ tolerance=tolerance,
364
+ allow_rescaling=allow_rescaling,
365
+ )
366
+ array = da.reshape(array, reshape_tuple)
367
+ array = _dask_rescaling(array=array, actions=actions, target_shape=reference_shape)
368
+ array = _dask_pad(
369
+ array=array,
370
+ actions=actions,
371
+ target_shape=reference_shape,
372
+ pad_mode=pad_mode,
373
+ constant_values=pad_values,
374
+ )
375
+ array = _dask_trim(array=array, actions=actions, target_shape=reference_shape)
376
+ return array