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.
diffct_mlx/geometry.py ADDED
@@ -0,0 +1,802 @@
1
+ """Geometry and trajectory generation for CT scanning.
2
+
3
+ This module provides functions for generating circular, spiral, sinusoidal,
4
+ saddle, and custom trajectories for CT scanning geometries, using MLX arrays
5
+ for Apple Silicon acceleration.
6
+ """
7
+
8
+ import math
9
+ import mlx.core as mx
10
+ from typing import Callable, Tuple
11
+ import json
12
+ import numpy as np
13
+ import warnings
14
+ from .real_measured_data_helper import (
15
+ _as_3d_float_array,
16
+ _get_first_present,
17
+ _normalize_detector_vectors,
18
+ diagnose_cone_geometry,
19
+ estimate_cone_isocenter,
20
+ )
21
+
22
+
23
+ # ============================================================================
24
+ # 3D Cone Beam Trajectory Generation
25
+ # ============================================================================
26
+
27
+ def circular_trajectory_3d(n_views, sid, sdd, start_angle=0.0, end_angle=None,
28
+ dtype=mx.float32):
29
+ """Generate circular trajectory geometry for cone-beam CT.
30
+
31
+ Parameters
32
+ ----------
33
+ n_views : int
34
+ Number of projection views.
35
+ sid : float
36
+ Source-to-Isocenter Distance (SID).
37
+ sdd : float
38
+ Source-to-Detector Distance (SDD).
39
+ start_angle : float, optional
40
+ Starting angle in radians (default: 0.0).
41
+ end_angle : float, optional
42
+ Ending angle in radians (default: 2*pi).
43
+ dtype : mx.Dtype, optional
44
+ Data type (default: mx.float32).
45
+
46
+ Returns
47
+ -------
48
+ src_pos, det_center, det_u_vec, det_v_vec : mx.array
49
+ Each of shape ``(n_views, 3)``.
50
+ """
51
+ if end_angle is None:
52
+ end_angle = 2 * math.pi
53
+
54
+ step = (end_angle - start_angle) / n_views
55
+ angles = start_angle + mx.arange(n_views, dtype=dtype) * step
56
+
57
+ cos_a = mx.cos(angles)
58
+ sin_a = mx.sin(angles)
59
+ zeros = mx.zeros(n_views, dtype=dtype)
60
+ ones = mx.ones(n_views, dtype=dtype)
61
+
62
+ src_pos = mx.stack([-sid * sin_a, sid * cos_a, zeros], axis=1)
63
+
64
+ idd = sdd - sid
65
+ det_center = mx.stack([idd * sin_a, -idd * cos_a, zeros], axis=1)
66
+
67
+ det_u_vec = mx.stack([cos_a, sin_a, zeros], axis=1)
68
+ det_v_vec = mx.stack([zeros, zeros, ones], axis=1)
69
+
70
+ return src_pos, det_center, det_u_vec, det_v_vec
71
+
72
+
73
+ def random_trajectory_3d(n_views, sid_mean, sdd_mean, sid_std=0.0, pos_std=0.0,
74
+ angle_std=0.0, dtype=mx.float32, seed=None):
75
+ """Generate random trajectory geometry for cone-beam CT.
76
+
77
+ Parameters
78
+ ----------
79
+ n_views : int
80
+ Number of projection views.
81
+ sid_mean : float
82
+ Mean Source-to-Isocenter Distance.
83
+ sdd_mean : float
84
+ Mean Source-to-Detector Distance.
85
+ sid_std : float, optional
86
+ Standard deviation for SID variations (default: 0.0).
87
+ pos_std : float, optional
88
+ Standard deviation for position offsets (default: 0.0).
89
+ angle_std : float, optional
90
+ Standard deviation for angular perturbations (default: 0.0).
91
+ dtype : mx.Dtype, optional
92
+ Data type (default: mx.float32).
93
+ seed : int, optional
94
+ Random seed for reproducibility.
95
+
96
+ Returns
97
+ -------
98
+ src_pos, det_center, det_u_vec, det_v_vec : mx.array
99
+ Each of shape ``(n_views, 3)``.
100
+ """
101
+ if seed is not None:
102
+ mx.random.seed(seed)
103
+
104
+ src_pos, det_center, det_u_vec, det_v_vec = circular_trajectory_3d(
105
+ n_views, sid_mean, sdd_mean, dtype=dtype
106
+ )
107
+
108
+ if sid_std > 0.0:
109
+ sid_pert = mx.random.normal(shape=(n_views,)) * sid_std
110
+ angles = mx.arctan2(-src_pos[:, 0], src_pos[:, 1])
111
+ cos_a = mx.cos(angles)
112
+ sin_a = mx.sin(angles)
113
+
114
+ sid_actual = sid_mean + sid_pert
115
+ src_x = -sid_actual * sin_a
116
+ src_y = sid_actual * cos_a
117
+ src_pos = mx.stack([src_x, src_y, src_pos[:, 2]], axis=1)
118
+
119
+ sdd_actual = sdd_mean + sid_pert
120
+ idd = sdd_actual - sid_actual
121
+ det_x = idd * sin_a
122
+ det_y = -idd * cos_a
123
+ det_center = mx.stack([det_x, det_y, det_center[:, 2]], axis=1)
124
+
125
+ if pos_std > 0.0:
126
+ src_pos = src_pos + mx.random.normal(shape=src_pos.shape) * pos_std
127
+ det_center = det_center + mx.random.normal(shape=det_center.shape) * pos_std
128
+
129
+ if angle_std > 0.0:
130
+ angle_pert = mx.random.normal(shape=(n_views,)) * angle_std
131
+ cos_p = mx.cos(angle_pert)
132
+ sin_p = mx.sin(angle_pert)
133
+
134
+ u_new_x = det_u_vec[:, 0] * cos_p - det_u_vec[:, 1] * sin_p
135
+ u_new_y = det_u_vec[:, 0] * sin_p + det_u_vec[:, 1] * cos_p
136
+ det_u_vec = mx.stack([u_new_x, u_new_y, det_u_vec[:, 2]], axis=1)
137
+
138
+ # Renormalize
139
+ det_u_vec = det_u_vec / mx.linalg.norm(det_u_vec, axis=1, keepdims=True)
140
+ det_v_vec = det_v_vec / mx.linalg.norm(det_v_vec, axis=1, keepdims=True)
141
+
142
+ return src_pos, det_center, det_u_vec, det_v_vec
143
+
144
+
145
+ def spiral_trajectory_3d(n_views, sid, sdd, z_range=100.0, n_turns=2.0,
146
+ start_angle=0.0, dtype=mx.float32):
147
+ """Generate spiral (helical) trajectory geometry for cone-beam CT.
148
+
149
+ Parameters
150
+ ----------
151
+ n_views : int
152
+ Number of projection views.
153
+ sid : float
154
+ Source-to-Isocenter Distance.
155
+ sdd : float
156
+ Source-to-Detector Distance.
157
+ z_range : float, optional
158
+ Total z-axis range (default: 100.0).
159
+ n_turns : float, optional
160
+ Number of complete rotations (default: 2.0).
161
+ start_angle : float, optional
162
+ Starting angle in radians (default: 0.0).
163
+ dtype : mx.Dtype, optional
164
+ Data type (default: mx.float32).
165
+
166
+ Returns
167
+ -------
168
+ src_pos, det_center, det_u_vec, det_v_vec : mx.array
169
+ Each of shape ``(n_views, 3)``.
170
+ """
171
+ end_angle = start_angle + 2 * math.pi * n_turns
172
+ step = (end_angle - start_angle) / n_views
173
+ angles = start_angle + mx.arange(n_views, dtype=dtype) * step
174
+ z_positions = mx.linspace(-z_range / 2, z_range / 2, n_views)
175
+
176
+ cos_a = mx.cos(angles)
177
+ sin_a = mx.sin(angles)
178
+ zeros = mx.zeros(n_views, dtype=dtype)
179
+ ones = mx.ones(n_views, dtype=dtype)
180
+
181
+ src_pos = mx.stack([-sid * sin_a, sid * cos_a, z_positions], axis=1)
182
+
183
+ idd = sdd - sid
184
+ det_center = mx.stack([idd * sin_a, -idd * cos_a, z_positions], axis=1)
185
+
186
+ det_u_vec = mx.stack([cos_a, sin_a, zeros], axis=1)
187
+ det_v_vec = mx.stack([zeros, zeros, ones], axis=1)
188
+
189
+ return src_pos, det_center, det_u_vec, det_v_vec
190
+
191
+
192
+ def sinusoidal_trajectory_3d(n_views, sid, sdd, amplitude=50.0, frequency=2.0,
193
+ start_angle=0.0, dtype=mx.float32):
194
+ """Generate sinusoidal trajectory geometry for cone-beam CT.
195
+
196
+ Parameters
197
+ ----------
198
+ n_views : int
199
+ Number of projection views.
200
+ sid : float
201
+ Mean Source-to-Isocenter Distance.
202
+ sdd : float
203
+ Source-to-Detector Distance.
204
+ amplitude : float, optional
205
+ Amplitude of radial variation (default: 50.0).
206
+ frequency : float, optional
207
+ Oscillation cycles per rotation (default: 2.0).
208
+ start_angle : float, optional
209
+ Starting angle in radians (default: 0.0).
210
+ dtype : mx.Dtype, optional
211
+ Data type (default: mx.float32).
212
+
213
+ Returns
214
+ -------
215
+ src_pos, det_center, det_u_vec, det_v_vec : mx.array
216
+ Each of shape ``(n_views, 3)``.
217
+ """
218
+ end_angle = start_angle + 2 * math.pi
219
+ step = (end_angle - start_angle) / n_views
220
+ angles = start_angle + mx.arange(n_views, dtype=dtype) * step
221
+
222
+ radial_var = amplitude * mx.sin(frequency * angles)
223
+ sid_varying = sid + radial_var
224
+
225
+ cos_a = mx.cos(angles)
226
+ sin_a = mx.sin(angles)
227
+ zeros = mx.zeros(n_views, dtype=dtype)
228
+ ones = mx.ones(n_views, dtype=dtype)
229
+
230
+ src_pos = mx.stack([-sid_varying * sin_a, sid_varying * cos_a, zeros], axis=1)
231
+
232
+ idd = sdd - sid_varying
233
+ det_center = mx.stack([idd * sin_a, -idd * cos_a, zeros], axis=1)
234
+
235
+ det_u_vec = mx.stack([cos_a, sin_a, zeros], axis=1)
236
+ det_v_vec = mx.stack([zeros, zeros, ones], axis=1)
237
+
238
+ return src_pos, det_center, det_u_vec, det_v_vec
239
+
240
+
241
+ def saddle_trajectory_3d(n_views, sid, sdd, z_amplitude=50.0, radial_amplitude=30.0,
242
+ start_angle=0.0, dtype=mx.float32):
243
+ """Generate saddle-shaped trajectory geometry for cone-beam CT.
244
+
245
+ Parameters
246
+ ----------
247
+ n_views : int
248
+ Number of projection views.
249
+ sid : float
250
+ Mean Source-to-Isocenter Distance.
251
+ sdd : float
252
+ Source-to-Detector Distance.
253
+ z_amplitude : float, optional
254
+ Amplitude of z-axis variation (default: 50.0).
255
+ radial_amplitude : float, optional
256
+ Amplitude of radial variation (default: 30.0).
257
+ start_angle : float, optional
258
+ Starting angle in radians (default: 0.0).
259
+ dtype : mx.Dtype, optional
260
+ Data type (default: mx.float32).
261
+
262
+ Returns
263
+ -------
264
+ src_pos, det_center, det_u_vec, det_v_vec : mx.array
265
+ Each of shape ``(n_views, 3)``.
266
+ """
267
+ end_angle = start_angle + 2 * math.pi
268
+ step = (end_angle - start_angle) / n_views
269
+ angles = start_angle + mx.arange(n_views, dtype=dtype) * step
270
+
271
+ z_positions = z_amplitude * mx.cos(2 * angles)
272
+ radial_var = radial_amplitude * mx.sin(2 * angles)
273
+ sid_varying = sid + radial_var
274
+
275
+ cos_a = mx.cos(angles)
276
+ sin_a = mx.sin(angles)
277
+ zeros = mx.zeros(n_views, dtype=dtype)
278
+ ones = mx.ones(n_views, dtype=dtype)
279
+
280
+ src_pos = mx.stack([-sid_varying * sin_a, sid_varying * cos_a, z_positions], axis=1)
281
+
282
+ idd = sdd - sid_varying
283
+ det_center = mx.stack([idd * sin_a, -idd * cos_a, z_positions], axis=1)
284
+
285
+ det_u_vec = mx.stack([cos_a, sin_a, zeros], axis=1)
286
+ det_v_vec = mx.stack([zeros, zeros, ones], axis=1)
287
+
288
+ return src_pos, det_center, det_u_vec, det_v_vec
289
+
290
+
291
+ def custom_trajectory_3d(n_views, sid, sdd,
292
+ source_path_fn: Callable,
293
+ start_angle=0.0, dtype=mx.float32):
294
+ """Generate custom trajectory geometry for cone-beam CT.
295
+
296
+ Parameters
297
+ ----------
298
+ n_views : int
299
+ Number of projection views.
300
+ sid : float
301
+ Source-to-Isocenter Distance.
302
+ sdd : float
303
+ Source-to-Detector Distance.
304
+ source_path_fn : callable
305
+ Function ``(angles, sid) -> src_pos`` with shape ``(n_views, 3)``.
306
+ start_angle : float, optional
307
+ Starting angle in radians (default: 0.0).
308
+ dtype : mx.Dtype, optional
309
+ Data type (default: mx.float32).
310
+
311
+ Returns
312
+ -------
313
+ src_pos, det_center, det_u_vec, det_v_vec : mx.array
314
+ Each of shape ``(n_views, 3)``.
315
+ """
316
+ end_angle = start_angle + 2 * math.pi
317
+ step = (end_angle - start_angle) / n_views
318
+ angles = start_angle + mx.arange(n_views, dtype=dtype) * step
319
+
320
+ src_pos = source_path_fn(angles, sid)
321
+ if src_pos.shape != (n_views, 3):
322
+ raise ValueError(f"source_path_fn must return shape ({n_views}, 3), got {src_pos.shape}")
323
+
324
+ src_norm = mx.linalg.norm(src_pos, axis=1)
325
+ mx.eval(src_norm)
326
+ min_src_norm = float(mx.min(src_norm))
327
+ max_src_norm = float(mx.max(src_norm))
328
+ if min_src_norm <= 1e-6:
329
+ raise ValueError("source_path_fn must keep the source away from the isocenter")
330
+ if max_src_norm >= sdd:
331
+ raise ValueError("source_path_fn must keep the source radius smaller than sdd")
332
+
333
+ det_center_list = []
334
+ det_u_list = []
335
+ det_v_list = []
336
+
337
+ for i in range(n_views):
338
+ src_vec = src_pos[i]
339
+ src_norm = mx.linalg.norm(src_vec)
340
+ src_unit = src_vec / src_norm
341
+
342
+ det_c = -src_unit * (sdd - src_norm)
343
+ det_center_list.append(det_c)
344
+
345
+ # u-direction: perpendicular to source in xy-plane
346
+ if abs(float(src_vec[0])) < 1e-6 and abs(float(src_vec[1])) < 1e-6:
347
+ u = mx.array([1.0, 0.0, 0.0], dtype=dtype)
348
+ else:
349
+ u_unnorm = mx.array([-float(src_vec[1]), float(src_vec[0]), 0.0], dtype=dtype)
350
+ u = u_unnorm / mx.linalg.norm(u_unnorm)
351
+ det_u_list.append(u)
352
+
353
+ # v-direction: cross product
354
+ v = mx.array([
355
+ float(src_unit[1]) * float(u[2]) - float(src_unit[2]) * float(u[1]),
356
+ float(src_unit[2]) * float(u[0]) - float(src_unit[0]) * float(u[2]),
357
+ float(src_unit[0]) * float(u[1]) - float(src_unit[1]) * float(u[0]),
358
+ ], dtype=dtype)
359
+ v = v / mx.linalg.norm(v)
360
+ det_v_list.append(v)
361
+
362
+ det_center = mx.stack(det_center_list, axis=0)
363
+ det_u_vec = mx.stack(det_u_list, axis=0)
364
+ det_v_vec = mx.stack(det_v_list, axis=0)
365
+
366
+ return src_pos, det_center, det_u_vec, det_v_vec
367
+
368
+
369
+
370
+ def _compute_detector_from_source_and_sdd(src_np, sdd):
371
+ src_norm = np.linalg.norm(src_np, axis=1, keepdims=True)
372
+ src_norm = np.maximum(src_norm, 1e-6)
373
+ src_unit = src_np / src_norm
374
+
375
+ sdd_np = np.asarray(sdd, dtype=np.float32)
376
+ if sdd_np.ndim == 0:
377
+ sdd_np = np.full((src_np.shape[0], 1), float(sdd_np), dtype=np.float32)
378
+ elif sdd_np.ndim == 1:
379
+ sdd_np = sdd_np[:, None]
380
+
381
+ det_c_np = -src_unit * (sdd_np - src_norm)
382
+
383
+ det_u_np = np.stack(
384
+ [-src_np[:, 1], src_np[:, 0], np.zeros(src_np.shape[0], dtype=np.float32)],
385
+ axis=1,
386
+ )
387
+ det_u_np = _normalize_detector_vectors(
388
+ det_u_np,
389
+ np.array([1.0, 0.0, 0.0], dtype=np.float32),
390
+ )
391
+
392
+ det_v_np = np.cross(src_unit, det_u_np)
393
+ det_v_np = _normalize_detector_vectors(
394
+ det_v_np,
395
+ np.array([0.0, 0.0, 1.0], dtype=np.float32),
396
+ )
397
+ return det_c_np, det_u_np, det_v_np
398
+
399
+
400
+
401
+
402
+ def load_arbitrary_cone_geometry_from_json(json_path, *, flip_det_u=False,
403
+ flip_det_v=False,
404
+ warn_on_inconsistency=True,
405
+ recenter_to_isocenter=False):
406
+ """Load arbitrary cone trajectory from JSON and return MLX geometry arrays.
407
+
408
+ If detector center and basis vectors are present in the JSON, they are used
409
+ directly. ``flip_det_v=True`` is useful for scanners whose protocol stores
410
+ the detector row direction with opposite sign.
411
+ """
412
+ with open(json_path, "r", encoding="utf-8") as f:
413
+ payload = json.load(f)
414
+
415
+ if isinstance(payload, dict):
416
+ src_raw = _get_first_present(
417
+ payload,
418
+ ("src_pos",),
419
+ ("source_positions",),
420
+ ("source_path",),
421
+ ("trajectory", "src_pos"),
422
+ ("trajectory", "source_positions_mm"),
423
+ )
424
+ if src_raw is None:
425
+ raise ValueError("Missing source positions in JSON.")
426
+ src_np = _as_3d_float_array(src_raw, "src_pos")
427
+
428
+ det_c = _get_first_present(
429
+ payload,
430
+ ("det_center",),
431
+ ("detector_center",),
432
+ ("trajectory", "det_center"),
433
+ ("trajectory", "detector_centers_mm"),
434
+ )
435
+ det_u = _get_first_present(
436
+ payload,
437
+ ("det_u_vec",),
438
+ ("detector_u_vec",),
439
+ ("trajectory", "det_u_vec"),
440
+ ("trajectory", "detector_u_vec"),
441
+ )
442
+ det_v = _get_first_present(
443
+ payload,
444
+ ("det_v_vec",),
445
+ ("detector_v_vec",),
446
+ ("trajectory", "det_v_vec"),
447
+ ("trajectory", "detector_v_vec"),
448
+ )
449
+ sdd = _get_first_present(
450
+ payload,
451
+ ("sdd",),
452
+ ("source", "source_to_detector_distance_mm"),
453
+ ("source", "source_to_detector_distance"),
454
+ )
455
+ else:
456
+ src_np = _as_3d_float_array(payload, "src_pos")
457
+ det_c = det_u = det_v = sdd = None
458
+
459
+ if det_c is None or det_u is None or det_v is None:
460
+ if sdd is None:
461
+ raise ValueError(
462
+ "Missing SDD in JSON. Provide detector geometry or 'sdd'."
463
+ )
464
+ det_c_np, det_u_np, det_v_np = _compute_detector_from_source_and_sdd(src_np, sdd)
465
+ if warn_on_inconsistency:
466
+ warnings.warn(
467
+ "Detector center/u/v missing in JSON; falling back to geometry "
468
+ "constructed from source positions and SDD.",
469
+ stacklevel=2,
470
+ )
471
+ else:
472
+ det_c_np = _as_3d_float_array(det_c, "det_center")
473
+ det_u_np = _normalize_detector_vectors(
474
+ _as_3d_float_array(det_u, "det_u_vec"),
475
+ np.array([1.0, 0.0, 0.0], dtype=np.float32),
476
+ )
477
+ det_v_np = _normalize_detector_vectors(
478
+ _as_3d_float_array(det_v, "det_v_vec"),
479
+ np.array([0.0, 0.0, 1.0], dtype=np.float32),
480
+ )
481
+
482
+ if flip_det_u:
483
+ det_u_np = -det_u_np
484
+ if flip_det_v:
485
+ det_v_np = -det_v_np
486
+
487
+ if recenter_to_isocenter:
488
+ # Measured geometries may be expressed in a world frame whose origin is
489
+ # not the reconstruction isocenter. We translate source and detector
490
+ # centers together so that the central rays intersect near (0, 0, 0)
491
+ # without changing the relative scanner geometry.
492
+ isocenter = estimate_cone_isocenter(src_np, det_c_np)
493
+ print(
494
+ "Recentering geometry: "
495
+ f"estimated isocenter = ({isocenter[0]:.3f}, "
496
+ f"{isocenter[1]:.3f}, {isocenter[2]:.3f}) mm -> (0.000, 0.000, 0.000) mm"
497
+ )
498
+ src_np = src_np - isocenter
499
+ det_c_np = det_c_np - isocenter
500
+
501
+ if warn_on_inconsistency and sdd is not None:
502
+ diag = diagnose_cone_geometry(src_np, det_c_np, det_u_np, det_v_np)
503
+ sdd_np = np.asarray(sdd, dtype=np.float32)
504
+ sdd_min = float(np.min(sdd_np))
505
+ sdd_max = float(np.max(sdd_np))
506
+ if (
507
+ abs(diag["sdd_min_mm"] - sdd_min) > 1e-3
508
+ or abs(diag["sdd_max_mm"] - sdd_max) > 1e-3
509
+ ):
510
+ warnings.warn(
511
+ "Loaded detector centers imply an effective SDD range "
512
+ f"[{diag['sdd_min_mm']:.3f}, {diag['sdd_max_mm']:.3f}] mm, "
513
+ f"but JSON metadata reports [{sdd_min:.3f}, {sdd_max:.3f}] mm.",
514
+ stacklevel=2,
515
+ )
516
+
517
+ return (
518
+ mx.array(src_np, dtype=mx.float32),
519
+ mx.array(det_c_np, dtype=mx.float32),
520
+ mx.array(det_u_np, dtype=mx.float32),
521
+ mx.array(det_v_np, dtype=mx.float32),
522
+ )
523
+
524
+
525
+
526
+ # ============================================================================
527
+ # 2D Fan Beam Trajectory Generation
528
+ # ============================================================================
529
+
530
+ def circular_trajectory_2d_fan(n_views, sid, sdd, start_angle=0.0, end_angle=None,
531
+ dtype=mx.float32):
532
+ """Generate circular trajectory for 2D fan-beam CT.
533
+
534
+ Parameters
535
+ ----------
536
+ n_views : int
537
+ Number of projection views.
538
+ sid : float
539
+ Source-to-Isocenter Distance.
540
+ sdd : float
541
+ Source-to-Detector Distance.
542
+ start_angle : float, optional
543
+ Starting angle in radians (default: 0.0).
544
+ end_angle : float, optional
545
+ Ending angle in radians (default: 2*pi).
546
+ dtype : mx.Dtype, optional
547
+ Data type (default: mx.float32).
548
+
549
+ Returns
550
+ -------
551
+ src_pos, det_center, det_u_vec : mx.array
552
+ Shapes ``(n_views, 2)``.
553
+ """
554
+ if end_angle is None:
555
+ end_angle = 2 * math.pi
556
+
557
+ step = (end_angle - start_angle) / n_views
558
+ angles = start_angle + mx.arange(n_views, dtype=dtype) * step
559
+
560
+ cos_a = mx.cos(angles)
561
+ sin_a = mx.sin(angles)
562
+
563
+ src_pos = mx.stack([-sid * sin_a, sid * cos_a], axis=1)
564
+
565
+ idd = sdd - sid
566
+ det_center = mx.stack([idd * sin_a, -idd * cos_a], axis=1)
567
+
568
+ det_u_vec = mx.stack([cos_a, sin_a], axis=1)
569
+
570
+ return src_pos, det_center, det_u_vec
571
+
572
+
573
+ def sinusoidal_trajectory_2d_fan(n_views, sid, sdd, amplitude=50.0, frequency=2.0,
574
+ start_angle=0.0, dtype=mx.float32):
575
+ """Generate sinusoidal trajectory for 2D fan-beam CT.
576
+
577
+ Parameters
578
+ ----------
579
+ n_views : int
580
+ Number of projection views.
581
+ sid : float
582
+ Mean Source-to-Isocenter Distance.
583
+ sdd : float
584
+ Source-to-Detector Distance.
585
+ amplitude : float, optional
586
+ Amplitude of radial variation (default: 50.0).
587
+ frequency : float, optional
588
+ Oscillation cycles per rotation (default: 2.0).
589
+ start_angle : float, optional
590
+ Starting angle in radians (default: 0.0).
591
+ dtype : mx.Dtype, optional
592
+ Data type (default: mx.float32).
593
+
594
+ Returns
595
+ -------
596
+ src_pos, det_center, det_u_vec : mx.array
597
+ Shapes ``(n_views, 2)``.
598
+ """
599
+ end_angle = start_angle + 2 * math.pi
600
+ step = (end_angle - start_angle) / n_views
601
+ angles = start_angle + mx.arange(n_views, dtype=dtype) * step
602
+
603
+ radial_var = amplitude * mx.sin(frequency * angles)
604
+ sid_varying = sid + radial_var
605
+
606
+ cos_a = mx.cos(angles)
607
+ sin_a = mx.sin(angles)
608
+
609
+ src_pos = mx.stack([-sid_varying * sin_a, sid_varying * cos_a], axis=1)
610
+
611
+ idd = sdd - sid_varying
612
+ det_center = mx.stack([idd * sin_a, -idd * cos_a], axis=1)
613
+
614
+ det_u_vec = mx.stack([cos_a, sin_a], axis=1)
615
+
616
+ return src_pos, det_center, det_u_vec
617
+
618
+
619
+ def custom_trajectory_2d_fan(n_views, sid, sdd,
620
+ source_path_fn: Callable,
621
+ start_angle=0.0, dtype=mx.float32):
622
+ """Generate custom trajectory for 2D fan-beam CT.
623
+
624
+ Parameters
625
+ ----------
626
+ n_views : int
627
+ Number of projection views.
628
+ sid : float
629
+ Source-to-Isocenter Distance.
630
+ sdd : float
631
+ Source-to-Detector Distance.
632
+ source_path_fn : callable
633
+ Function ``(angles, sid) -> src_pos`` with shape ``(n_views, 2)``.
634
+ start_angle : float, optional
635
+ Starting angle in radians (default: 0.0).
636
+ dtype : mx.Dtype, optional
637
+ Data type (default: mx.float32).
638
+
639
+ Returns
640
+ -------
641
+ src_pos, det_center, det_u_vec : mx.array
642
+ Shapes ``(n_views, 2)``.
643
+ """
644
+ end_angle = start_angle + 2 * math.pi
645
+ step = (end_angle - start_angle) / n_views
646
+ angles = start_angle + mx.arange(n_views, dtype=dtype) * step
647
+
648
+ src_pos = source_path_fn(angles, sid)
649
+ if src_pos.shape != (n_views, 2):
650
+ raise ValueError(f"source_path_fn must return shape ({n_views}, 2), got {src_pos.shape}")
651
+
652
+ src_norm = mx.linalg.norm(src_pos, axis=1)
653
+ mx.eval(src_norm)
654
+ min_src_norm = float(mx.min(src_norm))
655
+ max_src_norm = float(mx.max(src_norm))
656
+ if min_src_norm <= 1e-6:
657
+ raise ValueError("source_path_fn must keep the source away from the isocenter")
658
+ if max_src_norm >= sdd:
659
+ raise ValueError("source_path_fn must keep the source radius smaller than sdd")
660
+
661
+ det_center_list = []
662
+ det_u_list = []
663
+
664
+ for i in range(n_views):
665
+ src_vec = src_pos[i]
666
+ src_norm = mx.linalg.norm(src_vec)
667
+ src_unit = src_vec / src_norm
668
+
669
+ det_c = -src_unit * (sdd - src_norm)
670
+ det_center_list.append(det_c)
671
+
672
+ # u-direction: perpendicular (-y, x)
673
+ det_u_list.append(mx.array([-float(src_unit[1]), float(src_unit[0])], dtype=dtype))
674
+
675
+ det_center = mx.stack(det_center_list, axis=0)
676
+ det_u_vec = mx.stack(det_u_list, axis=0)
677
+
678
+ return src_pos, det_center, det_u_vec
679
+
680
+
681
+ # ============================================================================
682
+ # 2D Parallel Beam Trajectory Generation
683
+ # ============================================================================
684
+
685
+ def circular_trajectory_2d_parallel(n_views, detector_distance=0.0, start_angle=0.0,
686
+ end_angle=None, dtype=mx.float32):
687
+ """Generate circular trajectory for 2D parallel-beam CT.
688
+
689
+ Parameters
690
+ ----------
691
+ n_views : int
692
+ Number of projection views.
693
+ detector_distance : float, optional
694
+ Distance from isocenter to detector origin (default: 0.0).
695
+ start_angle : float, optional
696
+ Starting angle in radians (default: 0.0).
697
+ end_angle : float, optional
698
+ Ending angle in radians (default: pi).
699
+ dtype : mx.Dtype, optional
700
+ Data type (default: mx.float32).
701
+
702
+ Returns
703
+ -------
704
+ ray_dir, det_origin, det_u_vec : mx.array
705
+ Shapes ``(n_views, 2)``.
706
+ """
707
+ if end_angle is None:
708
+ end_angle = math.pi
709
+
710
+ step = (end_angle - start_angle) / n_views
711
+ angles = start_angle + mx.arange(n_views, dtype=dtype) * step
712
+
713
+ cos_a = mx.cos(angles)
714
+ sin_a = mx.sin(angles)
715
+
716
+ ray_dir = mx.stack([cos_a, sin_a], axis=1)
717
+ det_origin = mx.stack([-detector_distance * sin_a, detector_distance * cos_a], axis=1)
718
+ det_u_vec = mx.stack([-sin_a, cos_a], axis=1)
719
+
720
+ return ray_dir, det_origin, det_u_vec
721
+
722
+
723
+ def sinusoidal_trajectory_2d_parallel(n_views, amplitude=50.0, frequency=2.0,
724
+ start_angle=0.0, dtype=mx.float32):
725
+ """Generate sinusoidal trajectory for 2D parallel-beam CT.
726
+
727
+ Parameters
728
+ ----------
729
+ n_views : int
730
+ Number of projection views.
731
+ amplitude : float, optional
732
+ Amplitude of detector displacement (default: 50.0).
733
+ frequency : float, optional
734
+ Oscillation cycles per rotation (default: 2.0).
735
+ start_angle : float, optional
736
+ Starting angle in radians (default: 0.0).
737
+ dtype : mx.Dtype, optional
738
+ Data type (default: mx.float32).
739
+
740
+ Returns
741
+ -------
742
+ ray_dir, det_origin, det_u_vec : mx.array
743
+ Shapes ``(n_views, 2)``.
744
+ """
745
+ end_angle = start_angle + math.pi
746
+ step = (end_angle - start_angle) / n_views
747
+ angles = start_angle + mx.arange(n_views, dtype=dtype) * step
748
+
749
+ det_offset = amplitude * mx.sin(frequency * angles)
750
+
751
+ cos_a = mx.cos(angles)
752
+ sin_a = mx.sin(angles)
753
+
754
+ ray_dir = mx.stack([cos_a, sin_a], axis=1)
755
+ det_origin = mx.stack([-det_offset * sin_a, det_offset * cos_a], axis=1)
756
+ det_u_vec = mx.stack([-sin_a, cos_a], axis=1)
757
+
758
+ return ray_dir, det_origin, det_u_vec
759
+
760
+
761
+ def custom_trajectory_2d_parallel(n_views,
762
+ ray_dir_fn: Callable,
763
+ det_origin_fn: Callable,
764
+ start_angle=0.0, dtype=mx.float32):
765
+ """Generate custom trajectory for 2D parallel-beam CT.
766
+
767
+ Parameters
768
+ ----------
769
+ n_views : int
770
+ Number of projection views.
771
+ ray_dir_fn : callable
772
+ Function ``(angles) -> ray_dir`` with shape ``(n_views, 2)``.
773
+ det_origin_fn : callable
774
+ Function ``(angles) -> det_origin`` with shape ``(n_views, 2)``.
775
+ start_angle : float, optional
776
+ Starting angle in radians (default: 0.0).
777
+ dtype : mx.Dtype, optional
778
+ Data type (default: mx.float32).
779
+
780
+ Returns
781
+ -------
782
+ ray_dir, det_origin, det_u_vec : mx.array
783
+ Shapes ``(n_views, 2)``.
784
+ """
785
+ end_angle = start_angle + math.pi
786
+ step = (end_angle - start_angle) / n_views
787
+ angles = start_angle + mx.arange(n_views, dtype=dtype) * step
788
+
789
+ ray_dir = ray_dir_fn(angles)
790
+ det_origin = det_origin_fn(angles)
791
+
792
+ if ray_dir.shape != (n_views, 2):
793
+ raise ValueError(f"ray_dir_fn must return shape ({n_views}, 2), got {ray_dir.shape}")
794
+ if det_origin.shape != (n_views, 2):
795
+ raise ValueError(f"det_origin_fn must return shape ({n_views}, 2), got {det_origin.shape}")
796
+
797
+ ray_dir = ray_dir / mx.linalg.norm(ray_dir, axis=1, keepdims=True)
798
+
799
+ # u-direction: perpendicular to ray (rotate 90°)
800
+ det_u_vec = mx.stack([-ray_dir[:, 1], ray_dir[:, 0]], axis=1)
801
+
802
+ return ray_dir, det_origin, det_u_vec