tiamat-python 0.1.8__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.
@@ -0,0 +1,418 @@
1
+ """
2
+ Transforms manipulating individual axes of images
3
+ """
4
+
5
+ from dataclasses import replace
6
+ from typing import Any
7
+
8
+ import numpy as np
9
+
10
+ from tiamat.transformers.coordinates import resolve_coordinate_slice
11
+
12
+ from ..io import ImageAccessor
13
+ from ..metadata import ImageMetadata
14
+ from .protocol import Transformer
15
+
16
+
17
+ class ImageToVolumeTransformer(Transformer):
18
+ """
19
+ Transformer that adds a new Z-axis to 2D images, expanding (y, x) to (z, y, x).
20
+ """
21
+
22
+ def __init__(self, z_spacing: float = None) -> None:
23
+ """
24
+ Initialize an ImageToVolumeTransformer.
25
+
26
+ Args:
27
+ z_spacing: Spacing for the new Z-axis. Defaults to 0.0.
28
+ """
29
+ self.z_spacing = z_spacing
30
+
31
+ def transform_access(self, accessor: ImageAccessor, metadata: ImageMetadata) -> ImageAccessor:
32
+ """
33
+ No changes to accessor; only metadata and image shape are updated.
34
+
35
+ Args:
36
+ accessor: ImageAccessor to pass through.
37
+ metadata: Metadata of the image.
38
+
39
+ Returns:
40
+ The unchanged accessor.
41
+ """
42
+ # dimensional metadata has to be removed
43
+ accessor = replace(accessor)
44
+ accessor.z = None
45
+
46
+ if accessor.scale is not None and hasattr(accessor.scale, "__len__"):
47
+ accessor.scale = accessor.scale[:2]
48
+
49
+ if accessor.spacing is not None and hasattr(accessor.spacing, "__len__"):
50
+ accessor.spacing = accessor.spacing[:2]
51
+
52
+ return accessor
53
+
54
+ def transform_metadata(self, metadata: ImageMetadata) -> ImageMetadata:
55
+ """
56
+ Expand 2D metadata to 3D by inserting a Z-axis.
57
+
58
+ Args:
59
+ metadata: Original ImageMetadata.
60
+
61
+ Returns:
62
+ Updated ImageMetadata with new Z-axis.
63
+ """
64
+ from dataclasses import replace
65
+
66
+ from tiamat.metadata import dimensions
67
+ from tiamat.readers.processing import expand_to_length
68
+
69
+ metadata = replace(metadata)
70
+
71
+ # this transformer always expands y, x to z,y,x
72
+ # we search for the position of y, then prepend a 1-dimension
73
+ y_index = metadata.dimensions.index(dimensions.Y)
74
+ new_axis = max(y_index - 1, 0)
75
+
76
+ # Insert new spatial axis
77
+ new_shape = list(metadata.shape)
78
+ new_shape.insert(new_axis, 1)
79
+ metadata.shape = tuple(new_shape)
80
+
81
+ # Insert the axis to the dimensions
82
+ new_dimensions = list(metadata.dimensions)
83
+ new_dimensions.insert(new_axis, dimensions.Z)
84
+ metadata.dimensions = new_dimensions
85
+
86
+ metadata.additional_metadata["stack_dimension"] = dimensions.Z
87
+
88
+ # Do not provide downsampled versions in z direction
89
+ metadata.scales = [(*expand_to_length(s, 2), 1.0) for s in metadata.scales]
90
+
91
+ if self.z_spacing is None:
92
+ if hasattr(metadata.spacing, "__len__"):
93
+ raise Exception(f"Need provide z_spacing for non-uniform spacing {metadata.spacing}")
94
+ else:
95
+ if hasattr(metadata.spacing, "__len__"):
96
+ metadata.spacing = (*metadata.spacing, self.z_spacing)
97
+ else:
98
+ metadata.spacing = (*expand_to_length(metadata.spacing, 2), self.z_spacing)
99
+
100
+ return metadata
101
+
102
+ def transform_image(self, image: np.ndarray, metadata: ImageMetadata, accessor: ImageAccessor) -> np.ndarray:
103
+ """
104
+ Expand 2D image to 3D by adding a singleton Z dimension.
105
+
106
+ Args:
107
+ image: Original Image.
108
+ metadata: The images metadata.
109
+ accessor: The accessor of the image.
110
+
111
+ Returns:
112
+ Updated ImageResult with new Z-axis.
113
+ """
114
+ from tiamat.metadata import dimensions
115
+
116
+ # this transformer always expands y, x to z,y,x
117
+ # we search for the position of y, then prepend a 1-dimension
118
+ y_index = metadata.dimensions.index(dimensions.Y)
119
+ new_axis = max(y_index - 1, 0)
120
+ new_shape = list(image.shape)
121
+ new_shape.insert(new_axis, 1)
122
+
123
+ image = image.reshape(new_shape)
124
+
125
+ return image
126
+
127
+ @classmethod
128
+ def from_json(cls, args: dict[str, Any]) -> "ImageToVolumeTransformer":
129
+ """
130
+ Create an ImageToVolumeTransformer from JSON arguments.
131
+
132
+ Args:
133
+ args: Dictionary with optional key 'z_spacing'.
134
+
135
+ Returns:
136
+ ImageToVolumeTransformer instance.
137
+ """
138
+ return cls(
139
+ z_spacing=float(args.get("z_spacing", None)),
140
+ )
141
+
142
+
143
+ class ReorderCoordinatesTransformer(Transformer):
144
+ """
145
+ Transformer that reorders spatial axes of images and metadata.
146
+ """
147
+
148
+ def __init__(self, axes: tuple[str, ...] = ("x", "y", "z")) -> None:
149
+ """
150
+ Initialize a ReorderCoordinatesTransformer.
151
+
152
+ Args:
153
+ axes: Desired axis order, either 2D ('x', 'y') or 3D ('x', 'y', 'z').
154
+ """
155
+ from tiamat.metadata.dimensions import META_DIMENSIONS, SPATIAL_DIMENSIONS
156
+
157
+ assert len(axes) == 2 or len(axes) == 3
158
+
159
+ self.reorder_axes = axes
160
+
161
+ if len(axes) == 2:
162
+ in_axes = SPATIAL_DIMENSIONS[1:] # ('y', 'x')
163
+ meta_axes = META_DIMENSIONS[:-1] # ('x', 'y')
164
+ else:
165
+ in_axes = SPATIAL_DIMENSIONS # ('z', 'y', 'x')
166
+ meta_axes = META_DIMENSIONS # ('x', 'y', 'z')
167
+
168
+ # Determine forward and backward indices for z, y, x ordered
169
+ self.from_indices = tuple(in_axes.index(a) for a in self.reorder_axes)
170
+ self.to_indices = tuple(self.reorder_axes.index(a) for a in in_axes)
171
+
172
+ # Invert for x, y, z ordered values (scale, spacing, ...)
173
+ # Assume that the given axes have z, y, x ordering
174
+ self.from_indices_meta = tuple(meta_axes.index(a) for a in self.reorder_axes[::-1])
175
+ self.to_indices_meta = tuple(self.reorder_axes[::-1].index(a) for a in meta_axes)
176
+
177
+ def transform_access(self, accessor: ImageAccessor, metadata: ImageMetadata) -> ImageAccessor:
178
+ """
179
+ Reorder coordinates in accessor according to the specified axes.
180
+
181
+ Args:
182
+ accessor: ImageAccessor to transform.
183
+ metadata: The metadata.
184
+
185
+ Returns:
186
+ Updated ImageAccessor with reordered coordinates and scales.
187
+ """
188
+ from dataclasses import replace
189
+
190
+ from tiamat.readers.processing import expand_to_length
191
+
192
+ accessor = replace(accessor)
193
+
194
+ scale = expand_to_length(accessor.scale, 3)
195
+
196
+ if len(self.reorder_axes) == 2:
197
+ coord_slices = [accessor.y, accessor.x]
198
+ accessor.y = coord_slices[self.to_indices[0]]
199
+ accessor.x = coord_slices[self.to_indices[1]]
200
+
201
+ accessor.scale = (
202
+ scale[self.to_indices_meta[0]],
203
+ scale[self.to_indices_meta[1]],
204
+ )
205
+ else:
206
+ coord_slices = [accessor.z, accessor.y, accessor.x]
207
+ accessor.z = coord_slices[self.to_indices[0]]
208
+ accessor.y = coord_slices[self.to_indices[1]]
209
+ accessor.x = coord_slices[self.to_indices[2]]
210
+
211
+ accessor.scale = (
212
+ scale[self.to_indices_meta[0]],
213
+ scale[self.to_indices_meta[1]],
214
+ scale[self.to_indices_meta[2]],
215
+ )
216
+
217
+ return accessor
218
+
219
+ def transform_metadata(self, metadata: ImageMetadata) -> ImageMetadata:
220
+ """
221
+ Reorder metadata shape, spacing, and scales according to axes.
222
+
223
+ Args:
224
+ metadata: Original ImageMetadata.
225
+
226
+ Returns:
227
+ Updated ImageMetadata.
228
+ """
229
+ from dataclasses import replace
230
+
231
+ from tiamat.metadata.dimensions import SPATIAL_DIMENSIONS
232
+ from tiamat.readers.processing import expand_to_length
233
+
234
+ metadata = replace(metadata)
235
+
236
+ # Adjust shape of image
237
+ sp_dims = metadata.spatial_dimensions
238
+ assert len(sp_dims) == len(self.reorder_axes)
239
+
240
+ new_shape = list(metadata.shape)
241
+ for i, ix in enumerate(self.from_indices):
242
+ new_shape[sp_dims[i]] = metadata.shape[sp_dims[ix]]
243
+ metadata.shape = tuple(new_shape)
244
+
245
+ # Adjust stack dimension if present
246
+ if "stack_dimension" in metadata.additional_metadata.keys():
247
+ stack_dimension = metadata.additional_metadata["stack_dimension"]
248
+ stack_ix = self.reorder_axes.index(stack_dimension)
249
+ if len(self.reorder_axes) == 2:
250
+ metadata.additional_metadata["stack_dimension"] = SPATIAL_DIMENSIONS[1:][stack_ix]
251
+ else:
252
+ metadata.additional_metadata["stack_dimension"] = SPATIAL_DIMENSIONS[stack_ix]
253
+
254
+ # Adjust spacing and scale
255
+ spacing = list(expand_to_length(metadata.spacing, len(sp_dims)))
256
+ scales = [list(expand_to_length(s, len(sp_dims))) for s in metadata.scales]
257
+
258
+ new_spacing = spacing.copy()
259
+ new_scales = [s.copy() for s in scales]
260
+ for i, ix in enumerate(self.from_indices_meta):
261
+ new_spacing[i] = spacing[ix]
262
+
263
+ for j in range(len(scales)):
264
+ new_scales[j][i] = scales[j][ix]
265
+
266
+ metadata.spacing = tuple(new_spacing)
267
+ metadata.scales = [tuple(s) for s in new_scales]
268
+
269
+ return metadata
270
+
271
+ def transform_image(self, image: np.ndarray, metadata: ImageMetadata, accessor: ImageAccessor) -> np.ndarray:
272
+ """
273
+ Reorder axes of the image array.
274
+
275
+ Args:
276
+ image: Image to transform.
277
+ metadata: Metadata of the image.
278
+ accessor: Accessor of the image.
279
+
280
+ Returns:
281
+ Updated Image with axes reordered.
282
+ """
283
+ sp_dims = metadata.spatial_dimensions
284
+ assert len(sp_dims) == len(self.reorder_axes)
285
+
286
+ image = np.moveaxis(
287
+ image,
288
+ [sp_dims[i] for i in self.from_indices],
289
+ sp_dims,
290
+ )
291
+
292
+ return image
293
+
294
+ @classmethod
295
+ def from_json(cls, args: dict[str, Any]) -> "ReorderCoordinatesTransformer":
296
+ """
297
+ Create a ReorderCoordinatesTransformer from JSON arguments.
298
+
299
+ Args:
300
+ args: Dictionary with optional key 'axes'.
301
+
302
+ Returns:
303
+ ReorderCoordinatesTransformer instance.
304
+ """
305
+ return cls(
306
+ axes=tuple(args.get("axes", ("x", "y", "z"))),
307
+ )
308
+
309
+
310
+ class MirrorTransformer(Transformer):
311
+ """
312
+ Transformer that mirrors images along specified axes.
313
+ """
314
+
315
+ def __init__(self, mirror_x: bool = False, mirror_y: bool = False, mirror_z: bool = False):
316
+ """
317
+ Initialize a MirrorTransformer.
318
+
319
+ Args:
320
+ mirror_x: Whether to mirror along the X axis.
321
+ mirror_y: Whether to mirror along the Y axis.
322
+ mirror_z: Whether to mirror along the Z axis.
323
+ """
324
+ self.mirror_x = mirror_x
325
+ self.mirror_y = mirror_y
326
+ self.mirror_z = mirror_z
327
+
328
+ def transform_access(self, accessor: ImageAccessor, metadata: ImageMetadata) -> ImageAccessor:
329
+ """
330
+ Mirror accessor coordinates along specified axes.
331
+
332
+ Args:
333
+ accessor: ImageAccessor to transform.
334
+ metadata: Metadata from the image.
335
+
336
+ Returns:
337
+ Updated ImageAccessor with mirrored coordinates.
338
+ """
339
+ from dataclasses import replace
340
+
341
+ from tiamat.metadata import dimensions
342
+
343
+ accessor = replace(accessor)
344
+
345
+ if self.mirror_x:
346
+ x_ix = metadata.dimensions.index(dimensions.X)
347
+ x_size = metadata.shape[x_ix]
348
+ x_from, x_to = resolve_coordinate_slice(accessor.x, x_size)
349
+ accessor.x = (x_size - x_to, x_size - x_from)
350
+
351
+ if self.mirror_y:
352
+ y_ix = metadata.dimensions.index(dimensions.Y)
353
+ y_size = metadata.shape[y_ix]
354
+ y_from, y_to = resolve_coordinate_slice(accessor.y, y_size)
355
+ accessor.y = (y_size - y_to, y_size - y_from)
356
+
357
+ if len(metadata.spatial_dimensions) > 2 and self.mirror_z:
358
+ z_ix = metadata.dimensions.index(dimensions.Z)
359
+ z_size = metadata.shape[z_ix]
360
+ z_from, z_to = resolve_coordinate_slice(accessor.z, z_size)
361
+ accessor.z = (z_size - z_to, z_size - z_from)
362
+
363
+ return accessor
364
+
365
+ def transform_metadata(self, metadata: ImageMetadata) -> ImageMetadata:
366
+ """
367
+ Mirroring does not affect metadata.
368
+
369
+ Args:
370
+ metadata: Metadata of the image.
371
+
372
+ Returns:
373
+ The unchanged metadata.
374
+ """
375
+ from dataclasses import replace
376
+
377
+ metadata = replace(metadata)
378
+
379
+ return metadata
380
+
381
+ def transform_image(self, image: np.ndarray, metadata: ImageMetadata, accessor: ImageAccessor) -> np.ndarray:
382
+ """
383
+ Mirror the image along the specified axes.
384
+
385
+ Args:
386
+ image: ImageResult to transform.
387
+ metadata: Metadata of the image.
388
+ accessor: Accessor to the image.
389
+
390
+ Returns:
391
+ Mirrored Image.
392
+ """
393
+ s_dim = metadata.spatial_dimensions
394
+ if len(s_dim) == 2:
395
+ flip_axes = self.mirror_y * [s_dim[0]] + self.mirror_x * [s_dim[1]]
396
+ else:
397
+ flip_axes = self.mirror_z * [s_dim[0]] + self.mirror_y * [s_dim[1]] + self.mirror_x * [s_dim[2]]
398
+
399
+ image = np.flip(image, axis=flip_axes)
400
+
401
+ return image
402
+
403
+ @classmethod
404
+ def from_json(cls, args: dict[str, Any]) -> "MirrorTransformer":
405
+ """
406
+ Create a MirrorTransformer from JSON arguments.
407
+
408
+ Args:
409
+ args: Dictionary with optional keys 'mirror_x', 'mirror_y', 'mirror_z'.
410
+
411
+ Returns:
412
+ MirrorTransformer instance.
413
+ """
414
+ return cls(
415
+ mirror_x=bool(args.get("mirror_x", False)),
416
+ mirror_y=bool(args.get("mirror_y", False)),
417
+ mirror_z=bool(args.get("mirror_z", False)),
418
+ )