diffct-mlx 1.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.
@@ -0,0 +1,431 @@
1
+ """Metal kernels for 2D parallel beam projections.
2
+
3
+ This module contains Metal kernel source strings implementing the Siddon
4
+ ray-tracing method for 2D parallel beam forward projection and backprojection,
5
+ optimized for Apple Silicon GPUs.
6
+ """
7
+
8
+ import mlx.core as mx
9
+
10
+ # ---------------------------------------------------------------------------
11
+ # Constants for Metal kernels
12
+ # ---------------------------------------------------------------------------
13
+ _EPSILON_STR = "1e-6f"
14
+ _INF_STR = "1e30f"
15
+
16
+ # ============================================================================
17
+ # 2D Parallel Beam Forward Projection Metal Kernel
18
+ # ============================================================================
19
+
20
+ _PARALLEL_2D_FORWARD_SOURCE = """
21
+ // Thread position: (iang, idet)
22
+ uint iang = thread_position_in_grid.x;
23
+ uint idet = thread_position_in_grid.y;
24
+
25
+ // Read scalar parameters from constant buffers
26
+ int n_ang = params[0];
27
+ int n_det = params[1];
28
+ int Nx = params[2];
29
+ int Ny = params[3];
30
+
31
+ float det_spacing = fparams[0];
32
+ float cx = fparams[1];
33
+ float cy = fparams[2];
34
+ float voxel_spacing = fparams[3];
35
+
36
+ if ((int)iang >= n_ang || (int)idet >= n_det) return;
37
+
38
+ // === 2D PARALLEL BEAM GEOMETRY SETUP ===
39
+ float dir_x = ray_dir[iang * 2 + 0];
40
+ float dir_y = ray_dir[iang * 2 + 1];
41
+
42
+ float det_ox = det_origin[iang * 2 + 0] / voxel_spacing;
43
+ float det_oy = det_origin[iang * 2 + 1] / voxel_spacing;
44
+
45
+ float u_vec_x = det_u_vec[iang * 2 + 0];
46
+ float u_vec_y = det_u_vec[iang * 2 + 1];
47
+
48
+ float u_offset = ((float)idet - (float)n_det * 0.5f) * det_spacing / voxel_spacing;
49
+
50
+ float pnt_x = det_ox + u_offset * u_vec_x;
51
+ float pnt_y = det_oy + u_offset * u_vec_y;
52
+
53
+ // === RAY-VOLUME INTERSECTION ===
54
+ float t_min = -""" + _INF_STR + """;
55
+ float t_max = """ + _INF_STR + """;
56
+
57
+ float eps = """ + _EPSILON_STR + """;
58
+
59
+ if (metal::abs(dir_x) > eps) {
60
+ float tx1 = (-cx - pnt_x) / dir_x;
61
+ float tx2 = ( cx - pnt_x) / dir_x;
62
+ t_min = metal::max(t_min, metal::min(tx1, tx2));
63
+ t_max = metal::min(t_max, metal::max(tx1, tx2));
64
+ } else if (pnt_x < -cx || pnt_x > cx) {
65
+ sino[iang * n_det + idet] = 0.0f;
66
+ return;
67
+ }
68
+
69
+ if (metal::abs(dir_y) > eps) {
70
+ float ty1 = (-cy - pnt_y) / dir_y;
71
+ float ty2 = ( cy - pnt_y) / dir_y;
72
+ t_min = metal::max(t_min, metal::min(ty1, ty2));
73
+ t_max = metal::min(t_max, metal::max(ty1, ty2));
74
+ } else if (pnt_y < -cy || pnt_y > cy) {
75
+ sino[iang * n_det + idet] = 0.0f;
76
+ return;
77
+ }
78
+
79
+ if (t_min >= t_max) {
80
+ sino[iang * n_det + idet] = 0.0f;
81
+ return;
82
+ }
83
+
84
+ // === SIDDON TRAVERSAL ===
85
+ float accum = 0.0f;
86
+ float t = t_min;
87
+
88
+ int ix = (int)metal::floor(pnt_x + t * dir_x + cx);
89
+ int iy = (int)metal::floor(pnt_y + t * dir_y + cy);
90
+
91
+ int step_x = (dir_x >= 0.0f) ? 1 : -1;
92
+ int step_y = (dir_y >= 0.0f) ? 1 : -1;
93
+
94
+ float inv_dir_x = (metal::abs(dir_x) > eps) ? (1.0f / dir_x) : 0.0f;
95
+ float inv_dir_y = (metal::abs(dir_y) > eps) ? (1.0f / dir_y) : 0.0f;
96
+ float dt_x = (metal::abs(dir_x) > eps) ? metal::abs(inv_dir_x) : """ + _INF_STR + """;
97
+ float dt_y = (metal::abs(dir_y) > eps) ? metal::abs(inv_dir_y) : """ + _INF_STR + """;
98
+
99
+ float tx = (metal::abs(dir_x) > eps) ? ((float)(ix + (step_x > 0 ? 1 : 0)) - cx - pnt_x) * inv_dir_x : """ + _INF_STR + """;
100
+ float ty = (metal::abs(dir_y) > eps) ? ((float)(iy + (step_y > 0 ? 1 : 0)) - cy - pnt_y) * inv_dir_y : """ + _INF_STR + """;
101
+
102
+ // Main traversal loop
103
+ while (t < t_max) {
104
+ if (ix >= 0 && ix < Nx && iy >= 0 && iy < Ny) {
105
+ float t_next = metal::min(metal::min(tx, ty), t_max);
106
+ float seg_len = t_next - t;
107
+
108
+ if (seg_len > eps) {
109
+ // Bilinear interpolation at midpoint
110
+ float t_mid = t + seg_len * 0.5f;
111
+ float mid_x = pnt_x + t_mid * dir_x + cx;
112
+ float mid_y = pnt_y + t_mid * dir_y + cy;
113
+
114
+ int ix0 = (int)metal::floor(mid_x);
115
+ int iy0 = (int)metal::floor(mid_y);
116
+ float dx = mid_x - (float)ix0;
117
+ float dy = mid_y - (float)iy0;
118
+
119
+ ix0 = metal::max(0, metal::min(ix0, Nx - 2));
120
+ iy0 = metal::max(0, metal::min(iy0, Ny - 2));
121
+
122
+ float omdx = 1.0f - dx;
123
+ float omdy = 1.0f - dy;
124
+
125
+ float v00 = image[iy0 * Nx + ix0];
126
+ float v10 = image[iy0 * Nx + ix0 + 1];
127
+ float v01 = image[(iy0 + 1) * Nx + ix0];
128
+ float v11 = image[(iy0 + 1) * Nx + ix0 + 1];
129
+
130
+ float val = (v00 * omdx + v10 * dx) * omdy +
131
+ (v01 * omdx + v11 * dx) * dy;
132
+ accum += val * seg_len;
133
+ }
134
+ }
135
+
136
+ // Advance to next voxel
137
+ if (tx <= ty) {
138
+ t = tx;
139
+ ix += step_x;
140
+ tx += dt_x;
141
+ } else {
142
+ t = ty;
143
+ iy += step_y;
144
+ ty += dt_y;
145
+ }
146
+ }
147
+
148
+ sino[iang * n_det + idet] = accum;
149
+ """
150
+
151
+ parallel_2d_forward_kernel = mx.fast.metal_kernel(
152
+ name="parallel_2d_forward",
153
+ input_names=["image", "ray_dir", "det_origin", "det_u_vec", "params", "fparams"],
154
+ output_names=["sino"],
155
+ source=_PARALLEL_2D_FORWARD_SOURCE,
156
+ )
157
+
158
+ # ============================================================================
159
+ # 2D Parallel Beam Backprojection Metal Kernel
160
+ # ============================================================================
161
+
162
+ _PARALLEL_2D_BACKWARD_SOURCE = """
163
+ // Thread position: (iang, idet)
164
+ uint iang = thread_position_in_grid.x;
165
+ uint idet = thread_position_in_grid.y;
166
+
167
+ // Read scalar parameters
168
+ int n_ang = params[0];
169
+ int n_det = params[1];
170
+ int Nx = params[2];
171
+ int Ny = params[3];
172
+
173
+ float det_spacing = fparams[0];
174
+ float cx = fparams[1];
175
+ float cy = fparams[2];
176
+ float voxel_spacing = fparams[3];
177
+
178
+ if ((int)iang >= n_ang || (int)idet >= n_det) return;
179
+
180
+ float val = sino[iang * n_det + idet];
181
+
182
+ // === 2D PARALLEL BEAM GEOMETRY SETUP ===
183
+ float dir_x = ray_dir[iang * 2 + 0];
184
+ float dir_y = ray_dir[iang * 2 + 1];
185
+
186
+ float det_ox = det_origin_arr[iang * 2 + 0] / voxel_spacing;
187
+ float det_oy = det_origin_arr[iang * 2 + 1] / voxel_spacing;
188
+
189
+ float u_vec_x = det_u_vec[iang * 2 + 0];
190
+ float u_vec_y = det_u_vec[iang * 2 + 1];
191
+
192
+ float u_offset = ((float)idet - (float)n_det * 0.5f) * det_spacing / voxel_spacing;
193
+
194
+ float pnt_x = det_ox + u_offset * u_vec_x;
195
+ float pnt_y = det_oy + u_offset * u_vec_y;
196
+
197
+ // === RAY-VOLUME INTERSECTION ===
198
+ float t_min = -""" + _INF_STR + """;
199
+ float t_max = """ + _INF_STR + """;
200
+ float eps = """ + _EPSILON_STR + """;
201
+
202
+ if (metal::abs(dir_x) > eps) {
203
+ float tx1 = (-cx - pnt_x) / dir_x;
204
+ float tx2 = ( cx - pnt_x) / dir_x;
205
+ t_min = metal::max(t_min, metal::min(tx1, tx2));
206
+ t_max = metal::min(t_max, metal::max(tx1, tx2));
207
+ } else if (pnt_x < -cx || pnt_x > cx) { return; }
208
+
209
+ if (metal::abs(dir_y) > eps) {
210
+ float ty1 = (-cy - pnt_y) / dir_y;
211
+ float ty2 = ( cy - pnt_y) / dir_y;
212
+ t_min = metal::max(t_min, metal::min(ty1, ty2));
213
+ t_max = metal::min(t_max, metal::max(ty1, ty2));
214
+ } else if (pnt_y < -cy || pnt_y > cy) { return; }
215
+
216
+ if (t_min >= t_max) return;
217
+
218
+ // === SIDDON TRAVERSAL ===
219
+ float t = t_min;
220
+ int ix = (int)metal::floor(pnt_x + t * dir_x + cx);
221
+ int iy = (int)metal::floor(pnt_y + t * dir_y + cy);
222
+
223
+ int step_x = (dir_x >= 0.0f) ? 1 : -1;
224
+ int step_y = (dir_y >= 0.0f) ? 1 : -1;
225
+
226
+ float inv_dir_x = (metal::abs(dir_x) > eps) ? (1.0f / dir_x) : 0.0f;
227
+ float inv_dir_y = (metal::abs(dir_y) > eps) ? (1.0f / dir_y) : 0.0f;
228
+ float dt_x = (metal::abs(dir_x) > eps) ? metal::abs(inv_dir_x) : """ + _INF_STR + """;
229
+ float dt_y = (metal::abs(dir_y) > eps) ? metal::abs(inv_dir_y) : """ + _INF_STR + """;
230
+
231
+ float tx = (metal::abs(dir_x) > eps) ? ((float)(ix + (step_x > 0 ? 1 : 0)) - cx - pnt_x) * inv_dir_x : """ + _INF_STR + """;
232
+ float ty = (metal::abs(dir_y) > eps) ? ((float)(iy + (step_y > 0 ? 1 : 0)) - cy - pnt_y) * inv_dir_y : """ + _INF_STR + """;
233
+
234
+ while (t < t_max) {
235
+ if (ix >= 0 && ix < Nx && iy >= 0 && iy < Ny) {
236
+ float t_next = metal::min(metal::min(tx, ty), t_max);
237
+ float seg_len = t_next - t;
238
+
239
+ if (seg_len > eps) {
240
+ float t_mid = t + seg_len * 0.5f;
241
+ float mid_x = pnt_x + t_mid * dir_x + cx;
242
+ float mid_y = pnt_y + t_mid * dir_y + cy;
243
+
244
+ int ix0 = (int)metal::floor(mid_x);
245
+ int iy0 = (int)metal::floor(mid_y);
246
+ float dx = mid_x - (float)ix0;
247
+ float dy = mid_y - (float)iy0;
248
+
249
+ ix0 = metal::max(0, metal::min(ix0, Nx - 2));
250
+ iy0 = metal::max(0, metal::min(iy0, Ny - 2));
251
+
252
+ float omdx = 1.0f - dx;
253
+ float omdy = 1.0f - dy;
254
+ float cval = val * seg_len;
255
+
256
+ // Atomic add for backprojection (thread safety)
257
+ atomic_fetch_add_explicit(&grad_image[iy0 * Nx + ix0], cval * omdx * omdy, memory_order_relaxed);
258
+ atomic_fetch_add_explicit(&grad_image[iy0 * Nx + ix0 + 1], cval * dx * omdy, memory_order_relaxed);
259
+ atomic_fetch_add_explicit(&grad_image[(iy0 + 1) * Nx + ix0], cval * omdx * dy, memory_order_relaxed);
260
+ atomic_fetch_add_explicit(&grad_image[(iy0 + 1) * Nx + ix0 + 1], cval * dx * dy, memory_order_relaxed);
261
+ }
262
+ }
263
+
264
+ if (tx <= ty) {
265
+ t = tx;
266
+ ix += step_x;
267
+ tx += dt_x;
268
+ } else {
269
+ t = ty;
270
+ iy += step_y;
271
+ ty += dt_y;
272
+ }
273
+ }
274
+ """
275
+
276
+ parallel_2d_backward_kernel = mx.fast.metal_kernel(
277
+ name="parallel_2d_backward",
278
+ input_names=["sino", "ray_dir", "det_origin_arr", "det_u_vec", "params", "fparams"],
279
+ output_names=["grad_image"],
280
+ source=_PARALLEL_2D_BACKWARD_SOURCE,
281
+ atomic_outputs=True,
282
+ )
283
+
284
+ # ============================================================================
285
+ # 2D Parallel Beam Footprint-Matched Projector Pair
286
+ # ============================================================================
287
+
288
+ _PARALLEL_2D_FOOTPRINT_FORWARD_SOURCE = """
289
+ // Thread position: (iang, iy)
290
+ uint iang = thread_position_in_grid.x;
291
+ uint iy = thread_position_in_grid.y;
292
+
293
+ int n_ang = params[0];
294
+ int n_det = params[1];
295
+ int Nx = params[2];
296
+ int Ny = params[3];
297
+
298
+ float det_spacing = fparams[0];
299
+ float cx = fparams[1];
300
+ float cy = fparams[2];
301
+ float voxel_spacing = fparams[3];
302
+
303
+ if ((int)iang >= n_ang || (int)iy >= Ny) return;
304
+
305
+ float eps = """ + _EPSILON_STR + """;
306
+ float det_spacing_vox = det_spacing / voxel_spacing;
307
+ float center_u = (float)n_det * 0.5f;
308
+
309
+ float dir_x = ray_dir[iang * 2 + 0];
310
+ float dir_y = ray_dir[iang * 2 + 1];
311
+ float det_ox = det_origin[iang * 2 + 0] / voxel_spacing;
312
+ float det_oy = det_origin[iang * 2 + 1] / voxel_spacing;
313
+ float u_vec_x = det_u_vec[iang * 2 + 0];
314
+ float u_vec_y = det_u_vec[iang * 2 + 1];
315
+
316
+ float l_phi = 1.0f / metal::max(metal::max(metal::abs(dir_x), metal::abs(dir_y)), eps);
317
+ float half_u = 0.5f * (metal::abs(u_vec_x) + metal::abs(u_vec_y));
318
+ half_u = metal::max(half_u, 0.5f * det_spacing_vox);
319
+ float width_u = metal::max(2.0f * half_u, det_spacing_vox);
320
+ float support_u = half_u + 0.5f * det_spacing_vox;
321
+ float py = ((float)iy + 0.5f) - cy;
322
+
323
+ for (int ix = 0; ix < Nx; ++ix) {
324
+ float val = image[(int)iy * Nx + ix];
325
+ if (metal::abs(val) <= eps) continue;
326
+
327
+ float px = ((float)ix + 0.5f) - cx;
328
+ float rel_x = px - det_ox;
329
+ float rel_y = py - det_oy;
330
+ float u0 = rel_x * u_vec_x + rel_y * u_vec_y;
331
+
332
+ int idet_min = (int)metal::floor(u0 / det_spacing_vox + center_u - support_u / det_spacing_vox);
333
+ int idet_max = (int)metal::ceil(u0 / det_spacing_vox + center_u + support_u / det_spacing_vox);
334
+ idet_min = metal::max(0, idet_min);
335
+ idet_max = metal::min(n_det - 1, idet_max);
336
+
337
+ float fp_lo = u0 - half_u;
338
+ float fp_hi = u0 + half_u;
339
+ float scaled_val = val * l_phi;
340
+
341
+ for (int idet = idet_min; idet <= idet_max; ++idet) {
342
+ float pixel_u = ((float)idet - center_u) * det_spacing_vox;
343
+ float pixel_lo = pixel_u - 0.5f * det_spacing_vox;
344
+ float pixel_hi = pixel_u + 0.5f * det_spacing_vox;
345
+ float overlap = metal::min(pixel_hi, fp_hi) - metal::max(pixel_lo, fp_lo);
346
+ if (overlap <= eps) continue;
347
+ float weight = overlap / width_u;
348
+ atomic_fetch_add_explicit(&sino[iang * n_det + idet], scaled_val * weight, memory_order_relaxed);
349
+ }
350
+ }
351
+ """
352
+
353
+ parallel_2d_footprint_forward_kernel = mx.fast.metal_kernel(
354
+ name="parallel_2d_footprint_forward",
355
+ input_names=["image", "ray_dir", "det_origin", "det_u_vec", "params", "fparams"],
356
+ output_names=["sino"],
357
+ source=_PARALLEL_2D_FOOTPRINT_FORWARD_SOURCE,
358
+ atomic_outputs=True,
359
+ )
360
+
361
+ _PARALLEL_2D_FOOTPRINT_BACKWARD_SOURCE = """
362
+ // Thread position: (ix, iy)
363
+ uint ix = thread_position_in_grid.x;
364
+ uint iy = thread_position_in_grid.y;
365
+
366
+ int n_ang = params[0];
367
+ int n_det = params[1];
368
+ int Nx = params[2];
369
+ int Ny = params[3];
370
+
371
+ float det_spacing = fparams[0];
372
+ float cx = fparams[1];
373
+ float cy = fparams[2];
374
+ float voxel_spacing = fparams[3];
375
+
376
+ if ((int)ix >= Nx || (int)iy >= Ny) return;
377
+
378
+ float eps = """ + _EPSILON_STR + """;
379
+ float det_spacing_vox = det_spacing / voxel_spacing;
380
+ float center_u = (float)n_det * 0.5f;
381
+ float px = ((float)ix + 0.5f) - cx;
382
+ float py = ((float)iy + 0.5f) - cy;
383
+
384
+ float accum = 0.0f;
385
+
386
+ for (int iang = 0; iang < n_ang; ++iang) {
387
+ float dir_x = ray_dir[iang * 2 + 0];
388
+ float dir_y = ray_dir[iang * 2 + 1];
389
+ float det_ox = det_origin_arr[iang * 2 + 0] / voxel_spacing;
390
+ float det_oy = det_origin_arr[iang * 2 + 1] / voxel_spacing;
391
+ float u_vec_x = det_u_vec[iang * 2 + 0];
392
+ float u_vec_y = det_u_vec[iang * 2 + 1];
393
+
394
+ float l_phi = 1.0f / metal::max(metal::max(metal::abs(dir_x), metal::abs(dir_y)), eps);
395
+ float half_u = 0.5f * (metal::abs(u_vec_x) + metal::abs(u_vec_y));
396
+ half_u = metal::max(half_u, 0.5f * det_spacing_vox);
397
+ float width_u = metal::max(2.0f * half_u, det_spacing_vox);
398
+ float support_u = half_u + 0.5f * det_spacing_vox;
399
+
400
+ float rel_x = px - det_ox;
401
+ float rel_y = py - det_oy;
402
+ float u0 = rel_x * u_vec_x + rel_y * u_vec_y;
403
+
404
+ int idet_min = (int)metal::floor(u0 / det_spacing_vox + center_u - support_u / det_spacing_vox);
405
+ int idet_max = (int)metal::ceil(u0 / det_spacing_vox + center_u + support_u / det_spacing_vox);
406
+ idet_min = metal::max(0, idet_min);
407
+ idet_max = metal::min(n_det - 1, idet_max);
408
+
409
+ float fp_lo = u0 - half_u;
410
+ float fp_hi = u0 + half_u;
411
+
412
+ for (int idet = idet_min; idet <= idet_max; ++idet) {
413
+ float pixel_u = ((float)idet - center_u) * det_spacing_vox;
414
+ float pixel_lo = pixel_u - 0.5f * det_spacing_vox;
415
+ float pixel_hi = pixel_u + 0.5f * det_spacing_vox;
416
+ float overlap = metal::min(pixel_hi, fp_hi) - metal::max(pixel_lo, fp_lo);
417
+ if (overlap <= eps) continue;
418
+ float weight = overlap / width_u;
419
+ accum += sino[iang * n_det + idet] * weight * l_phi;
420
+ }
421
+ }
422
+
423
+ grad_image[(int)iy * Nx + (int)ix] = accum;
424
+ """
425
+
426
+ parallel_2d_footprint_backward_kernel = mx.fast.metal_kernel(
427
+ name="parallel_2d_footprint_backward",
428
+ input_names=["sino", "ray_dir", "det_origin_arr", "det_u_vec", "params", "fparams"],
429
+ output_names=["grad_image"],
430
+ source=_PARALLEL_2D_FOOTPRINT_BACKWARD_SOURCE,
431
+ )
@@ -0,0 +1,5 @@
1
+ """Built-in phantom generators."""
2
+
3
+ from .shepp_logan import shepp_logan_2d, shepp_logan_3d
4
+
5
+ __all__ = ["shepp_logan_2d", "shepp_logan_3d"]
@@ -0,0 +1,118 @@
1
+ """Shepp-Logan phantom generators for 2D and 3D examples."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+
7
+
8
+ def _shape_2d(shape_or_nx, ny: int | None = None) -> tuple[int, int]:
9
+ """Accept `(ny, nx)` or `(nx, ny)` style input used in the examples."""
10
+ if ny is None:
11
+ if not isinstance(shape_or_nx, (tuple, list)) or len(shape_or_nx) != 2:
12
+ raise ValueError("Expected shape `(ny, nx)` or arguments `(nx, ny)`.")
13
+ ny, nx = shape_or_nx
14
+ else:
15
+ nx = shape_or_nx
16
+ ny = int(ny)
17
+ nx = int(nx)
18
+ if ny <= 0 or nx <= 0:
19
+ raise ValueError(f"Shape must be positive, got {(ny, nx)!r}.")
20
+ return ny, nx
21
+
22
+
23
+ def _shape_3d(shape_or_nz, ny: int | None = None, nx: int | None = None) -> tuple[int, int, int]:
24
+ """Accept `(nz, ny, nx)` or separate `nz, ny, nx` arguments."""
25
+ if ny is None or nx is None:
26
+ if not isinstance(shape_or_nz, (tuple, list)) or len(shape_or_nz) != 3:
27
+ raise ValueError("Expected shape `(nz, ny, nx)` or arguments `(nz, ny, nx)`.")
28
+ nz, ny, nx = shape_or_nz
29
+ else:
30
+ nz = shape_or_nz
31
+ nz = int(nz)
32
+ ny = int(ny)
33
+ nx = int(nx)
34
+ if nz <= 0 or ny <= 0 or nx <= 0:
35
+ raise ValueError(f"Shape must be positive, got {(nz, ny, nx)!r}.")
36
+ return nz, ny, nx
37
+
38
+
39
+ def shepp_logan_2d(shape_or_nx, ny: int | None = None) -> np.ndarray:
40
+ """Generate a 2D Shepp-Logan phantom as a NumPy array."""
41
+ ny, nx = _shape_2d(shape_or_nx, ny)
42
+ yy, xx = np.mgrid[:ny, :nx]
43
+ xx = (xx - (nx - 1) / 2) / ((nx - 1) / 2)
44
+ yy = (yy - (ny - 1) / 2) / ((ny - 1) / 2)
45
+
46
+ ellipses = np.array(
47
+ [
48
+ [0, 0, 0.69, 0.92, 0, 1],
49
+ [0, -0.0184, 0.6624, 0.874, 0, -0.8],
50
+ [0.22, 0, 0.11, 0.31, -np.pi / 10, -0.2],
51
+ [-0.22, 0, 0.16, 0.41, np.pi / 10, -0.2],
52
+ [0, 0.35, 0.21, 0.25, 0, 0.1],
53
+ [0, 0.1, 0.046, 0.046, 0, 0.1],
54
+ [0, -0.1, 0.046, 0.046, 0, 0.1],
55
+ [-0.08, -0.605, 0.046, 0.023, 0, 0.1],
56
+ [0, -0.605, 0.023, 0.023, 0, 0.1],
57
+ [0.06, -0.605, 0.023, 0.046, 0, 0.1],
58
+ ],
59
+ dtype=np.float32,
60
+ )
61
+
62
+ x0 = ellipses[:, 0][:, None, None]
63
+ y0 = ellipses[:, 1][:, None, None]
64
+ a = ellipses[:, 2][:, None, None]
65
+ b = ellipses[:, 3][:, None, None]
66
+ phi = ellipses[:, 4][:, None, None]
67
+ val = ellipses[:, 5][:, None, None]
68
+
69
+ c, s = np.cos(phi), np.sin(phi)
70
+ xc, yc = xx[None] - x0, yy[None] - y0
71
+ xp = c * xc - s * yc
72
+ yp = s * xc + c * yc
73
+ mask = (xp**2 / a**2 + yp**2 / b**2) <= 1.0
74
+ return np.clip(np.sum(mask * val, axis=0), 0.0, 1.0).astype(np.float32)
75
+
76
+
77
+ def shepp_logan_3d(shape_or_nz, ny: int | None = None, nx: int | None = None) -> np.ndarray:
78
+ """Generate a 3D Shepp-Logan phantom as a NumPy array."""
79
+ nz, ny, nx = _shape_3d(shape_or_nz, ny, nx)
80
+ zz, yy, xx = np.mgrid[:nz, :ny, :nx]
81
+ xx = (xx - (nx - 1) / 2) / ((nx - 1) / 2)
82
+ yy = (yy - (ny - 1) / 2) / ((ny - 1) / 2)
83
+ zz = (zz - (nz - 1) / 2) / ((nz - 1) / 2)
84
+
85
+ ellipsoids = np.array(
86
+ [
87
+ [0, 0, 0, 0.69, 0.92, 0.81, 0, 1],
88
+ [0, -0.0184, 0, 0.6624, 0.874, 0.78, 0, -0.8],
89
+ [0.22, 0, 0, 0.11, 0.31, 0.22, -np.pi / 10, -0.2],
90
+ [-0.22, 0, 0, 0.16, 0.41, 0.28, np.pi / 10, -0.2],
91
+ [0, 0.35, -0.15, 0.21, 0.25, 0.41, 0, 0.1],
92
+ [0, 0.1, 0.25, 0.046, 0.046, 0.05, 0, 0.1],
93
+ [0, -0.1, 0.25, 0.046, 0.046, 0.05, 0, 0.1],
94
+ [-0.08, -0.605, 0, 0.046, 0.023, 0.05, 0, 0.1],
95
+ [0, -0.605, 0, 0.023, 0.023, 0.02, 0, 0.1],
96
+ [0.06, -0.605, 0, 0.023, 0.046, 0.02, 0, 0.1],
97
+ ],
98
+ dtype=np.float32,
99
+ )
100
+
101
+ x0 = ellipsoids[:, 0][:, None, None, None]
102
+ y0 = ellipsoids[:, 1][:, None, None, None]
103
+ z0 = ellipsoids[:, 2][:, None, None, None]
104
+ a = ellipsoids[:, 3][:, None, None, None]
105
+ b = ellipsoids[:, 4][:, None, None, None]
106
+ c = ellipsoids[:, 5][:, None, None, None]
107
+ phi = ellipsoids[:, 6][:, None, None, None]
108
+ val = ellipsoids[:, 7][:, None, None, None]
109
+
110
+ cos_p, sin_p = np.cos(phi), np.sin(phi)
111
+ xc = xx[None] - x0
112
+ yc = yy[None] - y0
113
+ zc = zz[None] - z0
114
+ xp = cos_p * xc - sin_p * yc
115
+ yp = sin_p * xc + cos_p * yc
116
+
117
+ mask = (xp**2 / a**2 + yp**2 / b**2 + zc**2 / c**2) <= 1.0
118
+ return np.clip(np.sum(mask * val, axis=0), 0.0, 1.0).astype(np.float32)