warpfield 0.0.1__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.
warpfield/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """
2
+ .. include:: ../../README.md
3
+ """
4
+
5
+ from . import register, recipes, utils
6
+ from .register import register_volumes, Recipe
warpfield/__main__.py ADDED
@@ -0,0 +1,75 @@
1
+ import argparse
2
+ import os
3
+ import logging
4
+ import numpy as np
5
+ import h5py
6
+ import hdf5plugin
7
+
8
+ from .utils import import_data
9
+ from .register import register_volumes, Recipe
10
+
11
+ # Configure logging
12
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
13
+
14
+
15
+ def main():
16
+ parser = argparse.ArgumentParser(description="GPU-accelerated volumetric image registration tool.")
17
+ parser.add_argument("--fixed", required=True, help="Path to the fixed image/volume file.")
18
+ parser.add_argument("--moving", required=True, help="Path to the moving image/volume file.")
19
+ parser.add_argument("--recipe", required=True, help="Path to the recipe YAML file for registration.")
20
+ parser.add_argument("--output", help="Path to save the registered image/volume.")
21
+ parser.add_argument(
22
+ "--compression",
23
+ type=str,
24
+ default="gzip",
25
+ help="Compression method for saving the registered volume (default: gzip).",
26
+ )
27
+ parser.add_argument(
28
+ "--invert", action="store_true", help="Invert the warp map and register the moving image to the fixed image."
29
+ )
30
+ args = parser.parse_args()
31
+ output_path = args.output or f"{os.path.splitext(args.moving)[0]}_registered.h5"
32
+
33
+ # load
34
+ logging.info(f"Loading fixed image from {args.fixed}...")
35
+ fixed_image, _ = import_data(args.fixed)
36
+ logging.info(f"Loading moving image from {args.moving}...")
37
+ moving_image, _ = import_data(args.moving)
38
+ if fixed_image.ndim != 3 or moving_image.ndim != 3:
39
+ raise ValueError("Both fixed and moving images must be 3D volumes.")
40
+ if fixed_image.shape != moving_image.shape:
41
+ raise ValueError("Fixed and moving images must have the same shape.")
42
+ # report shape
43
+ logging.info(f"Volume shapes: {fixed_image.shape}")
44
+ recipe = Recipe.from_yaml(args.recipe)
45
+
46
+ # register
47
+ logging.info("Registering the moving image to the fixed image...")
48
+ registered_image, warp_map, _ = register_volumes(fixed_image, moving_image, recipe, verbose=True)
49
+
50
+ if args.invert:
51
+ logging.info("Inverting the warp map...")
52
+ warp_map_inv = warp_map.invert_fast()
53
+ logging.info("Registering the fixed image to the moving image...")
54
+ fixed_reg_inv = warp_map_inv.unwarp(moving_image)
55
+
56
+ # save
57
+ # consider args.invert when logging and reporting fixed_reg_inv:
58
+ logging.info(
59
+ f"Saving to {output_path}:/moving_reg, {'...:/fixed_reg_inv, ' if args.invert else ''}and :/warp_map..."
60
+ )
61
+ with h5py.File(output_path, "w") as f:
62
+ f.create_dataset("moving_reg", data=registered_image, compression=args.compression)
63
+ f.create_dataset("recipe_json", data=recipe.model_dump_json().encode("utf-8"))
64
+ warp_map_group = f.create_group("warp_map")
65
+ warp_map_group.create_dataset("warp_field", data=warp_map.warp_field.get(), compression=args.compression)
66
+ warp_map_group.create_dataset("block_size", data=warp_map.block_size.get())
67
+ warp_map_group.create_dataset("block_stride", data=warp_map.block_stride.get())
68
+ if args.invert:
69
+ f.create_dataset("fixed_reg_inv", data=fixed_reg_inv, compression=args.compression)
70
+
71
+ logging.info("Done!")
72
+
73
+
74
+ if __name__ == "__main__":
75
+ main()
warpfield/ndimage.py ADDED
@@ -0,0 +1,240 @@
1
+ import numpy as np
2
+ import cupy as cp
3
+ import cupyx
4
+
5
+
6
+ def dogfilter_gpu(vol, sigma_low=1, sigma_high=4, mode="reflect"):
7
+ """Diffference of Gaussians filter
8
+
9
+ Args:
10
+ vol (array_like): data to be filtered
11
+ sigma_low (scalar or sequence of scalar): standard deviations
12
+ sigma_high (scalar or sequence of scalar): standard deviations
13
+ mode (str): The array borders are handled according to the given mode
14
+
15
+ Returns:
16
+ (array_like): filtered data
17
+
18
+ See also:
19
+ cupyx.scipy.ndimage.gaussian_filter
20
+ skimage.filters.difference_of_gaussians
21
+ """
22
+ in_module = vol.__class__.__module__
23
+ vol = cp.array(vol, "float32", copy=False)
24
+ out = cupyx.scipy.ndimage.gaussian_filter(vol, sigma_low, mode=mode)
25
+ out -= cupyx.scipy.ndimage.gaussian_filter(vol, sigma_high, mode=mode)
26
+ if in_module == "numpy":
27
+ out = out.get()
28
+ return out
29
+
30
+
31
+ def periodic_smooth_decomposition_nd_rfft(img):
32
+ """
33
+ Decompose ND real images into periodic and smooth components using rfftn/irfftn.
34
+ Last two axes are treated as the image dimensions.
35
+ """
36
+ # compute border-difference
37
+ B = cp.zeros_like(img)
38
+ B[..., 0, :] = img[..., -1, :] - img[..., 0, :]
39
+ B[..., -1, :] = -B[..., 0, :]
40
+ B[..., :, 0] += img[..., :, -1] - img[..., :, 0]
41
+ B[..., :, -1] -= img[..., :, -1] - img[..., :, 0]
42
+
43
+ # real FFT of border difference
44
+ B_rfft = cp.fft.rfftn(B, axes=(-2, -1))
45
+ del B
46
+
47
+ # build denom for full grid then slice to half-spectrum
48
+ M, N = img.shape[-2:]
49
+ q = cp.arange(M, dtype='float32').reshape(M, 1)
50
+ r = cp.arange(N, dtype='float32').reshape(1, N)
51
+ denom_full = 2 * cp.cos(2 * np.pi * q / M) + 2 * cp.cos(2 * np.pi * r / N) - 4
52
+ # take only first N//2+1 columns
53
+ denom_half = denom_full[:, : (N // 2 + 1)]
54
+ denom_half[0, 0] = 1 # avoid divide by zero
55
+
56
+ # compute smooth in freq domain (half-spectrum)
57
+ B_rfft /= denom_half
58
+ B_rfft[..., 0, 0] = 0
59
+
60
+ # invert real FFT back to spatial
61
+ # smooth = cp.fft.irfftn(B_rfft, s=(M, N), axes=(-2, -1))
62
+ # periodic = img - smooth
63
+ tmp = cp.fft.irfftn(B_rfft, s=(M, N), axes=(-2, -1))
64
+ tmp *= -1
65
+ tmp += img
66
+ return tmp
67
+
68
+
69
+ def gausswin(shape, sigma):
70
+ """Create Gaussian window of a given shape and sigma
71
+
72
+ Args:
73
+ shape (list or tuple): shape along each dimension
74
+ sigma (list or tuple): sigma along each dimension
75
+
76
+ Returns:
77
+ (array_like): Gauss window
78
+ """
79
+ grid = np.indices(shape).astype("float32")
80
+ for dim in range(len(grid)):
81
+ grid[dim] -= shape[dim] // 2
82
+ grid[dim] /= sigma[dim]
83
+ out = np.exp(-(grid**2).sum(0) / 2)
84
+ out /= out.sum()
85
+ # out = np.fft.fftshift(out)
86
+ return out
87
+
88
+
89
+ def gausskernel_sheared(sigma, shear=0, truncate=3):
90
+ """Create Gaussian window of a given shape and sigma. The window is sheared along the first two axes.
91
+
92
+ Args:
93
+ sigma (float or tuple of float): Standard deviation for Gaussian kernel.
94
+ shear (float): Shear factor in d_axis0 / d_axis1
95
+ truncate (float): Truncate the filter at this many standard deviations.
96
+
97
+ Returns:
98
+ window (array_like): n-dimensional window
99
+ """
100
+ # TODO: consider moving to .unshear
101
+
102
+ shape = (np.r_[sigma] * truncate * 2).astype("int")
103
+ shape[0] = np.maximum(shape[0], int(np.ceil(shape[1] * np.abs(shear))))
104
+ shape = (shape // 2) * 2 + 1
105
+ grid = np.indices(shape).astype("float32")
106
+ for dim in range(len(grid)):
107
+ grid[dim] -= shape[dim] // 2
108
+ grid[dim] /= sigma[dim]
109
+ grid[0] = grid[0] + shear * grid[1] * sigma[1] / sigma[0]
110
+ out = np.exp(-(grid**2).sum(0) / 2)
111
+ out /= out.sum()
112
+ return out
113
+
114
+
115
+ def ndwindow(shape, window_func):
116
+ """Create a n-dimensional window function
117
+
118
+ Args:
119
+ shape (tuple): shape of the window
120
+ window_func (function): window function to be applied to each dimension
121
+
122
+ Returns:
123
+ window (array_like): n-dimensional window
124
+ """
125
+ out = 1
126
+ for i in range(len(shape)):
127
+ newshape = np.ones(len(shape), dtype="int")
128
+ newshape[i] = shape[i]
129
+ w = window_func(shape[i])
130
+ out = out * np.reshape(w, newshape)
131
+ return out
132
+
133
+
134
+ def richardson_lucy_blind(img, psf=None, num_iter=5, update_psf=False):
135
+ """Richardson-Lucy deconvolution (regular and blind)
136
+
137
+ Args:
138
+ img (ndarray): input image or volume
139
+ psf (ndarray): known psf or initial estimate (before fftshift)
140
+ num_iter (int): number of iterations
141
+ update_psf (bool): True for blind deconvolution
142
+
143
+ Returns:
144
+ ndarray: deconvolved image
145
+ ndarray: psf
146
+ """
147
+
148
+ if psf is None and update_psf:
149
+ psf = cp.ones(img.shape, dtype="float32") / img.size
150
+ psf = cp.array(psf, "float32")
151
+ psf /= psf.sum()
152
+ psf = cp.fft.ifftshift(psf)
153
+ psf_ft = cp.fft.rfftn(psf)
154
+ img = cp.array(img, dtype="float32", copy=False)
155
+ img_decon = img.copy()
156
+ img_decon_ft = cp.fft.rfftn(img_decon)
157
+ ratio = cp.ones_like(img_decon)
158
+ ratio_ft = cp.fft.rfftn(ratio)
159
+
160
+ for _ in range(num_iter):
161
+ ratio[:] = img / cp.fft.irfftn(img_decon_ft * psf_ft)
162
+ ratio_ft[:] = cp.fft.rfftn(ratio)
163
+ img_decon *= cp.fft.irfftn(ratio_ft * psf_ft.conj())
164
+ img_decon_ft[:] = cp.fft.rfftn(img_decon)
165
+ if update_psf:
166
+ psf *= cp.fft.irfftn(ratio_ft * img_decon_ft.conj())
167
+ psf /= psf.sum()
168
+ psf_ft[:] = cp.fft.rfftn(psf)
169
+
170
+ return img_decon, cp.fft.fftshift(psf)
171
+
172
+
173
+ def richardson_lucy_generic(img, convolve_psf, correlate_psf=None, num_iter=5, epsilon=1 / 100):
174
+ """Richardson-Lucy deconvolution using arbitrary convolution operations
175
+
176
+ Args:
177
+ img (ndarray): input image or volume
178
+ convolve_psf (function): function that convolves an image with a psf
179
+ correlate_psf (function): function that correlates an image with a psf. If None, it is assumed that the psf is symmetric and the correlation is computed using the convolution.
180
+ num_iter (int): number of iterations
181
+
182
+ Returns:
183
+ ndarray: deconvolved image
184
+ """
185
+ img = cp.clip(cp.array(img, dtype="float32", copy=False), 0, None) + np.float32(epsilon)
186
+ if num_iter < 1:
187
+ return img
188
+ if correlate_psf is None:
189
+ correlate_psf = convolve_psf
190
+ img_decon = img.copy()
191
+
192
+ for _ in range(num_iter):
193
+ img_decon *= correlate_psf(img / convolve_psf(img_decon))
194
+
195
+ return img_decon
196
+
197
+
198
+ def richardson_lucy_gaussian(img, sigmas, num_iter=5):
199
+ """Richardson-Lucy deconvolution using Gaussian convolution operations
200
+
201
+ Args:
202
+ img (ndarray): input image or volume
203
+ sigmas (list or ndarray): list of Gaussian sigmas along each dimension
204
+ num_iter (int): number of iterations
205
+
206
+ Returns:
207
+ ndarray: deconvolved image
208
+ """
209
+ import cupyx
210
+
211
+ conv_with_gauss = lambda x: cupyx.scipy.ndimage.gaussian_filter(x, sigmas)
212
+ return richardson_lucy_generic(img, conv_with_gauss, conv_with_gauss, num_iter)
213
+
214
+
215
+ def richardson_lucy_gaussian_shear(img, sigmas, shear, num_iter=5):
216
+ """Richardson-Lucy deconvolution using a sheared Gaussian psf
217
+
218
+ Args:
219
+ img (ndarray): input image or volume
220
+ sigmas (list or ndarray): list of Gaussian sigmas along each dimension
221
+ shear (scalar): shear ratio
222
+ num_iter (int): number of iterations
223
+
224
+ Returns:
225
+ ndarray: deconvolved image
226
+ """
227
+ if shear == 0:
228
+ return richardson_lucy_gaussian(img, sigmas, num_iter)
229
+
230
+ import cupyx
231
+
232
+ sigmas = np.array(sigmas)
233
+ gw = cp.array(gausskernel_sheared(sigmas, shear=shear, truncate=4), "float32")
234
+ gw01 = gw.sum(2)[:, :, None]
235
+ gw01 /= gw01.sum()
236
+ gw2 = gw.sum(axis=(0, 1))[None, None, :]
237
+ gw2 /= gw2.sum()
238
+ conv_shear = lambda vol: cupyx.scipy.ndimage.convolve(cupyx.scipy.ndimage.convolve(vol, gw01), gw2)
239
+ dec = richardson_lucy_generic(img, conv_shear, num_iter=num_iter)
240
+ return dec