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,601 @@
1
+ """Helpers for loading and validating measured cone-beam geometries."""
2
+
3
+ from pathlib import Path
4
+ import re
5
+
6
+ import numpy as np
7
+
8
+ __all__ = [
9
+ "apply_upper_left_detector_transform",
10
+ "apply_detector_array_convention",
11
+ "apply_detector_geometry_convention",
12
+ "auto_voxel_spacing_from_detector",
13
+ "build_upper_left_detector_transform",
14
+ "diagnose_cone_geometry",
15
+ "estimate_cone_isocenter",
16
+ "load_tiff_projections",
17
+ "mu_to_hu",
18
+ "mu_to_uint16",
19
+ "normalize_volume",
20
+ "resize_volume_to_shape",
21
+ "shift_detector_center",
22
+ "transform_detector_offsets",
23
+ ]
24
+
25
+ _NATURAL_SORT_RE = re.compile(r"\d+|\D+")
26
+
27
+
28
+ def _get_first_present(mapping, *key_paths):
29
+ """Return the first value found for any candidate key path."""
30
+ for key_path in key_paths:
31
+ current = mapping
32
+ found = True
33
+ for key in key_path:
34
+ if not isinstance(current, dict) or key not in current:
35
+ found = False
36
+ break
37
+ current = current[key]
38
+ if found:
39
+ return current
40
+ return None
41
+
42
+
43
+ def _as_3d_float_array(value, name):
44
+ arr = np.asarray(value, dtype=np.float32)
45
+ if arr.ndim != 2 or arr.shape[1] != 3:
46
+ raise ValueError(f"{name} must have shape (n_views, 3), got {arr.shape}")
47
+ return arr
48
+
49
+
50
+ def _normalize_detector_vectors(vec_np, fallback):
51
+ norm = np.linalg.norm(vec_np, axis=1, keepdims=True)
52
+ out = vec_np.copy()
53
+ non_zero = norm[:, 0] >= 1e-6
54
+ out[non_zero] /= norm[non_zero]
55
+ out[~non_zero] = fallback
56
+ return out
57
+
58
+
59
+ def _read_tiff_2d(path):
60
+ try:
61
+ import tifffile
62
+
63
+ image = tifffile.imread(path)
64
+ except ImportError:
65
+ from PIL import Image
66
+
67
+ with Image.open(path) as img:
68
+ image = np.asarray(img)
69
+
70
+ image = np.asarray(image)
71
+ if image.ndim != 2:
72
+ raise ValueError(f"Projection at {path} must be 2D, got shape {image.shape}")
73
+ return image
74
+
75
+
76
+ def build_upper_left_detector_transform(
77
+ detector_pixels_u,
78
+ detector_pixels_v,
79
+ *,
80
+ detector_binning_u=1,
81
+ detector_binning_v=1,
82
+ flip_v_axis=True,
83
+ ):
84
+ """Build the legacy detector transform from centered detector coords to upper-left pixel coords.
85
+
86
+ The returned 3x3 homogeneous transform matches the legacy convention used in
87
+ `arbitrary_projection_matrix_vox2pix.py`, including the optional sign flip on
88
+ the second detector axis.
89
+ """
90
+ eff_u = max(1, int(detector_pixels_u) // max(1, int(detector_binning_u)))
91
+ eff_v = max(1, int(detector_pixels_v) // max(1, int(detector_binning_v)))
92
+
93
+ transform = np.eye(3, dtype=np.float64)
94
+ transform[0, 2] = (float(eff_v) - 1.0) / 2.0
95
+ transform[1, 2] = (float(eff_u) - 1.0) / 2.0
96
+ if flip_v_axis:
97
+ transform[1, 1] *= -1.0
98
+ return transform
99
+
100
+
101
+ def apply_upper_left_detector_transform(
102
+ projection_matrix,
103
+ detector_pixels_u,
104
+ detector_pixels_v,
105
+ *,
106
+ detector_binning_u=1,
107
+ detector_binning_v=1,
108
+ flip_v_axis=True,
109
+ ):
110
+ """Left-multiply a 3x4 projection matrix with the optional upper-left detector transform."""
111
+ projection_matrix = np.asarray(projection_matrix, dtype=np.float64)
112
+ if projection_matrix.shape != (3, 4):
113
+ raise ValueError(
114
+ f"projection_matrix must have shape (3, 4), got {projection_matrix.shape}"
115
+ )
116
+ transform = build_upper_left_detector_transform(
117
+ detector_pixels_u,
118
+ detector_pixels_v,
119
+ detector_binning_u=detector_binning_u,
120
+ detector_binning_v=detector_binning_v,
121
+ flip_v_axis=flip_v_axis,
122
+ )
123
+ return transform @ projection_matrix
124
+
125
+
126
+ def apply_detector_array_convention(
127
+ projections,
128
+ det_u_vec=None,
129
+ det_v_vec=None,
130
+ *,
131
+ du=None,
132
+ dv=None,
133
+ flip_u=False,
134
+ flip_v=False,
135
+ transpose_uv=False,
136
+ ):
137
+ """Apply detector-axis convention changes to image data and optional geometry.
138
+
139
+ This is the practical counterpart to the legacy projection-matrix transform:
140
+ it changes the detector array convention directly on the measured projections
141
+ and keeps detector basis vectors and pixel pitches consistent.
142
+
143
+ Parameters
144
+ ----------
145
+ projections : array-like
146
+ Projection stack with shape ``(n_views, det_u, det_v)``.
147
+ det_u_vec, det_v_vec : array-like or None
148
+ Optional detector basis vectors, each with shape ``(n_views, 3)``.
149
+ du, dv : float or None
150
+ Optional detector pixel pitches. Swapped when ``transpose_uv=True``.
151
+ flip_u, flip_v : bool
152
+ Mirror the detector data along the corresponding detector axis.
153
+ transpose_uv : bool
154
+ Swap the detector u/v axes in both the data and the geometry metadata.
155
+
156
+ Returns
157
+ -------
158
+ projections_out, det_u_vec_out, det_v_vec_out, du_out, dv_out
159
+ """
160
+ projections_out = np.asarray(projections)
161
+ if projections_out.ndim != 3:
162
+ raise ValueError(
163
+ f"projections must have shape (n_views, det_u, det_v), got {projections_out.shape}"
164
+ )
165
+
166
+ det_u_out = None if det_u_vec is None else _as_3d_float_array(det_u_vec, "det_u_vec").copy()
167
+ det_v_out = None if det_v_vec is None else _as_3d_float_array(det_v_vec, "det_v_vec").copy()
168
+ du_out = du
169
+ dv_out = dv
170
+
171
+ if flip_u:
172
+ projections_out = projections_out[:, ::-1, :]
173
+ if det_u_out is not None:
174
+ det_u_out *= -1.0
175
+
176
+ if flip_v:
177
+ projections_out = projections_out[:, :, ::-1]
178
+ if det_v_out is not None:
179
+ det_v_out *= -1.0
180
+
181
+ if transpose_uv:
182
+ projections_out = np.transpose(projections_out, (0, 2, 1))
183
+ det_u_out, det_v_out = det_v_out, det_u_out
184
+ du_out, dv_out = dv_out, du_out
185
+
186
+ return projections_out, det_u_out, det_v_out, du_out, dv_out
187
+
188
+
189
+ def apply_detector_geometry_convention(
190
+ det_u_vec=None,
191
+ det_v_vec=None,
192
+ *,
193
+ du=None,
194
+ dv=None,
195
+ det_u=None,
196
+ det_v=None,
197
+ flip_u=False,
198
+ flip_v=False,
199
+ transpose_uv=False,
200
+ ):
201
+ """Apply detector-axis convention changes to geometry metadata only."""
202
+ det_u_out = None if det_u_vec is None else _as_3d_float_array(det_u_vec, "det_u_vec").copy()
203
+ det_v_out = None if det_v_vec is None else _as_3d_float_array(det_v_vec, "det_v_vec").copy()
204
+ du_out = du
205
+ dv_out = dv
206
+ det_u_out_px = det_u
207
+ det_v_out_px = det_v
208
+
209
+ if flip_u and det_u_out is not None:
210
+ det_u_out *= -1.0
211
+
212
+ if flip_v and det_v_out is not None:
213
+ det_v_out *= -1.0
214
+
215
+ if transpose_uv:
216
+ det_u_out, det_v_out = det_v_out, det_u_out
217
+ du_out, dv_out = dv_out, du_out
218
+ det_u_out_px, det_v_out_px = det_v_out_px, det_u_out_px
219
+
220
+ return det_u_out, det_v_out, du_out, dv_out, det_u_out_px, det_v_out_px
221
+
222
+
223
+ def auto_voxel_spacing_from_detector(
224
+ volume_shape,
225
+ detector_shape_uv,
226
+ detector_pitch_u_mm,
227
+ detector_pitch_v_mm,
228
+ magnification,
229
+ fov_margin_mm=8.0,
230
+ ):
231
+ """Choose a voxel spacing whose object-space FOV fits inside the volume."""
232
+ eff_u, eff_v = detector_shape_uv
233
+ if magnification <= 0.0:
234
+ raise ValueError(f"Invalid magnification: {magnification}")
235
+
236
+ raw_fov_u_mm = (eff_u * detector_pitch_u_mm) / magnification
237
+ raw_fov_v_mm = (eff_v * detector_pitch_v_mm) / magnification
238
+ fov_u_mm = raw_fov_u_mm - 2.0 * float(fov_margin_mm)
239
+ fov_v_mm = raw_fov_v_mm - 2.0 * float(fov_margin_mm)
240
+ if fov_u_mm <= 0.0:
241
+ fov_u_mm = raw_fov_u_mm
242
+ if fov_v_mm <= 0.0:
243
+ fov_v_mm = raw_fov_v_mm
244
+
245
+ depth, height, width = volume_shape
246
+ return float(
247
+ min(
248
+ fov_u_mm / float(width),
249
+ fov_v_mm / float(height),
250
+ fov_v_mm / float(depth),
251
+ )
252
+ )
253
+
254
+
255
+ def transform_detector_offsets(horizontal_px, vertical_px, config):
256
+ """Map header pixel offsets into a detector convention."""
257
+ offset_u_px = float(horizontal_px)
258
+ offset_v_px = float(vertical_px)
259
+ if config["flip_u"]:
260
+ offset_u_px *= -1.0
261
+ if config["flip_v"]:
262
+ offset_v_px *= -1.0
263
+ if config["transpose_uv"]:
264
+ offset_u_px, offset_v_px = offset_v_px, offset_u_px
265
+ return offset_u_px, offset_v_px
266
+
267
+
268
+ def shift_detector_center(det_center, det_u_vec, det_v_vec, du, dv, offset_u_px=0.0, offset_v_px=0.0):
269
+ """Shift detector centers by pixel offsets along the detector basis vectors."""
270
+ det_center_np = np.asarray(det_center, dtype=np.float32)
271
+ det_u_np = np.asarray(det_u_vec, dtype=np.float32)
272
+ det_v_np = np.asarray(det_v_vec, dtype=np.float32)
273
+ return (
274
+ det_center_np
275
+ + float(offset_u_px * du) * det_u_np
276
+ + float(offset_v_px * dv) * det_v_np
277
+ ).astype(np.float32, copy=False)
278
+
279
+
280
+ def resize_volume_to_shape(volume, target_shape):
281
+ from scipy.ndimage import zoom
282
+
283
+ volume_np = np.asarray(volume, dtype=np.float32)
284
+ target_shape = tuple(int(x) for x in target_shape)
285
+ if volume_np.shape == target_shape:
286
+ return volume_np
287
+
288
+ zoom_factors = tuple(t / s for s, t in zip(volume_np.shape, target_shape))
289
+ return zoom(volume_np, zoom_factors, order=1).astype(np.float32, copy=False)
290
+
291
+
292
+ def mu_to_hu(mu, mu_water_mm: float = 0.02) -> np.ndarray:
293
+ """Convert linear attenuation coefficients (mm⁻¹) to Hounsfield Units (medical CT).
294
+
295
+ Reconstruction from log-transformed projections yields voxel values in mm⁻¹.
296
+ For medical CT, convert to HU: HU = 1000 × (μ / μ_water − 1).
297
+ For NDT with metals use mu_to_uint16() instead.
298
+
299
+ Reference: air ≈ −1000 HU, water ≈ 0 HU, bone ≈ 400–1000 HU.
300
+
301
+ Args:
302
+ mu: Array of linear attenuation coefficients in mm⁻¹.
303
+ mu_water_mm: Water attenuation for the beam energy (~0.020 mm⁻¹ at 70 keV).
304
+ """
305
+ return 1000.0 * (np.asarray(mu, dtype=np.float32) / float(mu_water_mm) - 1.0)
306
+
307
+
308
+ def mu_to_uint16(
309
+ mu,
310
+ mu_max_mm: float,
311
+ mu_min_mm: float = 0.0,
312
+ ) -> np.ndarray:
313
+ """Scale linear attenuation coefficients (mm⁻¹) to a uint16 grayscale volume.
314
+
315
+ NDT reconstruction from log-transformed projections yields voxel values in mm⁻¹.
316
+ Typical metal values at common industrial CT energies:
317
+ Al 100 keV: ~0.20 mm⁻¹ | 200 keV: ~0.14 mm⁻¹ | 300 keV: ~0.12 mm⁻¹
318
+ Fe 100 keV: ~0.72 mm⁻¹ | 200 keV: ~0.35 mm⁻¹ | 300 keV: ~0.26 mm⁻¹
319
+ Cu 100 keV: ~0.74 mm⁻¹ | 200 keV: ~0.39 mm⁻¹ | 300 keV: ~0.28 mm⁻¹
320
+
321
+ NOTE: If reconstructed values are unexpectedly small (below expected μ for the
322
+ material), check whether the object fills the detector FOV up to the border pixels
323
+ used for I₀ estimation (air_border_px). Attenuated border pixels cause I₀ to be
324
+ underestimated, which compresses projection values and suppresses reconstruction.
325
+ In that case set subtract_air_baseline=False in MeasuredConeDataConfig.
326
+
327
+ Args:
328
+ mu: Array of linear attenuation coefficients in mm⁻¹.
329
+ mu_max_mm: μ value that maps to 65535 (densest material in the scan).
330
+ mu_min_mm: μ value that maps to 0 (air/background). Default 0.0.
331
+ """
332
+ mu_np = np.asarray(mu, dtype=np.float32)
333
+ denom = float(mu_max_mm) - float(mu_min_mm)
334
+ if denom <= 0.0:
335
+ raise ValueError("mu_max_mm must be greater than mu_min_mm.")
336
+ scaled = (mu_np - float(mu_min_mm)) / denom * 65535.0
337
+ return np.clip(scaled, 0.0, 65535.0).astype(np.uint16)
338
+
339
+
340
+ def normalize_volume(volume, upper_percentile=None):
341
+ volume_np = np.asarray(volume, dtype=np.float32)
342
+ vol_min = float(np.min(volume_np))
343
+ if upper_percentile is None:
344
+ vol_max = float(np.max(volume_np))
345
+ else:
346
+ vol_max = float(np.percentile(volume_np, float(upper_percentile)))
347
+ scale = vol_max - vol_min
348
+ if scale <= 0.0:
349
+ return np.zeros_like(volume_np, dtype=np.float32)
350
+ normalized = (volume_np - vol_min) / scale
351
+ return np.clip(normalized, 0.0, 1.0).astype(np.float32, copy=False)
352
+
353
+
354
+ def _bin_mean_2d(image, bin_u=1, bin_v=1):
355
+ bin_u = max(1, int(bin_u))
356
+ bin_v = max(1, int(bin_v))
357
+ image = np.asarray(image, dtype=np.float32)
358
+ if bin_u == 1 and bin_v == 1:
359
+ return image
360
+
361
+ height, width = image.shape
362
+ eff_height = (height // bin_v) * bin_v
363
+ eff_width = (width // bin_u) * bin_u
364
+ if eff_height <= 0 or eff_width <= 0:
365
+ raise ValueError(
366
+ f"Invalid detector binning ({bin_u}, {bin_v}) for image shape {image.shape}"
367
+ )
368
+
369
+ if eff_height != height or eff_width != width:
370
+ off_v = (height - eff_height) // 2
371
+ off_u = (width - eff_width) // 2
372
+ image = image[off_v : off_v + eff_height, off_u : off_u + eff_width]
373
+
374
+ return image.reshape(
375
+ eff_height // bin_v,
376
+ bin_v,
377
+ eff_width // bin_u,
378
+ bin_u,
379
+ ).mean(axis=(1, 3), dtype=np.float32)
380
+
381
+
382
+ def _save_projection_debug_figure(before, after, view_indices, output_path):
383
+ import matplotlib
384
+
385
+ matplotlib.use("Agg")
386
+ import matplotlib.pyplot as plt
387
+
388
+ fig, axes = plt.subplots(2, len(view_indices), figsize=(4 * len(view_indices), 8))
389
+ axes = np.asarray(axes, dtype=object)
390
+ if axes.ndim == 1:
391
+ axes = axes[:, None]
392
+
393
+ for col, view_idx in enumerate(view_indices):
394
+ axes[0, col].imshow(before[col], cmap="gray")
395
+ axes[0, col].set_title(f"Raw view {view_idx}")
396
+ axes[0, col].axis("off")
397
+
398
+ axes[1, col].imshow(after[col], cmap="gray")
399
+ axes[1, col].set_title(f"Log view {view_idx}")
400
+ axes[1, col].axis("off")
401
+
402
+ fig.tight_layout()
403
+ fig.savefig(output_path, dpi=150, bbox_inches="tight")
404
+ plt.close(fig)
405
+
406
+
407
+ def _projection_sort_key(path):
408
+ return tuple(
409
+ int(part) if part[0].isdigit() else part.lower()
410
+ for part in _NATURAL_SORT_RE.findall(path.name)
411
+ )
412
+
413
+
414
+ def load_tiff_projections(
415
+ proj_dir,
416
+ log_transform=False,
417
+ revert=False,
418
+ i0_percentile=99.9,
419
+ viewwise_i0=True,
420
+ air_border_px=16,
421
+ subtract_air_baseline=True,
422
+ air_baseline_percentile=50.0,
423
+ view_stride=1,
424
+ detector_binning_u=1,
425
+ detector_binning_v=1,
426
+ debug_visualization=False,
427
+ debug_output_path=None,
428
+ ):
429
+ proj_path = Path(proj_dir)
430
+ projection_paths = sorted(
431
+ (
432
+ path
433
+ for path in proj_path.iterdir()
434
+ if path.is_file() and path.suffix.lower() in {".tif", ".tiff"}
435
+ ),
436
+ key=_projection_sort_key,
437
+ )
438
+ if not projection_paths:
439
+ raise FileNotFoundError(f"No TIFF projections found in {proj_path}")
440
+ projection_paths = projection_paths[:: max(1, int(view_stride))]
441
+ detector_binning_u = max(1, int(detector_binning_u))
442
+ detector_binning_v = max(1, int(detector_binning_v))
443
+
444
+ first_proj = np.asarray(
445
+ _bin_mean_2d(
446
+ _read_tiff_2d(projection_paths[0]),
447
+ bin_u=detector_binning_u,
448
+ bin_v=detector_binning_v,
449
+ ),
450
+ dtype=np.float32,
451
+ )
452
+ stack = np.empty((len(projection_paths),) + first_proj.shape, dtype=np.float32)
453
+ stack[0] = first_proj
454
+
455
+ for idx, path in enumerate(projection_paths[1:], start=1):
456
+ proj = np.asarray(
457
+ _bin_mean_2d(
458
+ _read_tiff_2d(path),
459
+ bin_u=detector_binning_u,
460
+ bin_v=detector_binning_v,
461
+ ),
462
+ dtype=np.float32,
463
+ )
464
+ if proj.shape != first_proj.shape:
465
+ raise ValueError(
466
+ f"Projection at {path} has shape {proj.shape}, expected {first_proj.shape}"
467
+ )
468
+ stack[idx] = proj
469
+
470
+ if log_transform:
471
+ debug_indices = None
472
+ debug_before = None
473
+ if debug_visualization:
474
+ debug_indices = sorted({0, len(stack) // 2, len(stack) - 1})
475
+ debug_before = stack[debug_indices].copy()
476
+
477
+ if viewwise_i0:
478
+ border_px = max(0, int(air_border_px))
479
+ if border_px > 0:
480
+ border_samples = [
481
+ stack[:, :border_px, :].reshape(len(stack), -1),
482
+ stack[:, -border_px:, :].reshape(len(stack), -1),
483
+ stack[:, :, :border_px].reshape(len(stack), -1),
484
+ stack[:, :, -border_px:].reshape(len(stack), -1),
485
+ ]
486
+ i0_source = np.concatenate(border_samples, axis=1)
487
+ else:
488
+ i0_source = stack.reshape(len(stack), -1)
489
+ i0 = np.percentile(i0_source, i0_percentile, axis=1, keepdims=True).reshape(len(stack), 1, 1)
490
+ i0 = np.maximum(i0, 1.0)
491
+ else:
492
+ i0 = max(float(np.percentile(stack, i0_percentile)), 1.0)
493
+ np.divide(stack, i0, out=stack)
494
+ np.clip(stack, 1e-6, 1.0, out=stack)
495
+ np.log(stack, out=stack)
496
+ stack *= -1.0
497
+ if subtract_air_baseline:
498
+ border_px = max(0, int(air_border_px))
499
+ if border_px > 0:
500
+ border_samples = [
501
+ stack[:, :border_px, :].reshape(len(stack), -1),
502
+ stack[:, -border_px:, :].reshape(len(stack), -1),
503
+ stack[:, :, :border_px].reshape(len(stack), -1),
504
+ stack[:, :, -border_px:].reshape(len(stack), -1),
505
+ ]
506
+ baseline_source = np.concatenate(border_samples, axis=1)
507
+ else:
508
+ baseline_source = stack.reshape(len(stack), -1)
509
+ air_baseline = np.percentile(
510
+ baseline_source,
511
+ float(air_baseline_percentile),
512
+ axis=1,
513
+ keepdims=True,
514
+ ).reshape(len(stack), 1, 1)
515
+ stack -= air_baseline
516
+ np.maximum(stack, 0.0, out=stack)
517
+ if debug_before is not None:
518
+ output_path = (
519
+ Path(debug_output_path)
520
+ if debug_output_path is not None
521
+ else proj_path / "projection_log_transform_debug.png"
522
+ )
523
+ _save_projection_debug_figure(
524
+ debug_before,
525
+ stack[debug_indices],
526
+ debug_indices,
527
+ output_path,
528
+ )
529
+
530
+ if revert:
531
+ np.subtract(65535.0, stack, out=stack)
532
+ i0 = max(float(np.percentile(stack, i0_percentile)), 1.0)
533
+ np.divide(stack, i0, out=stack)
534
+ np.clip(stack, 1e-6, 1.0, out=stack)
535
+
536
+ return stack
537
+
538
+
539
+ def estimate_cone_isocenter(src_pos, det_center):
540
+ """Estimate the common intersection point of the central rays."""
541
+ src_np = _as_3d_float_array(src_pos, "src_pos")
542
+ det_c_np = _as_3d_float_array(det_center, "det_center")
543
+
544
+ ray = det_c_np - src_np
545
+ ray_norm = np.linalg.norm(ray, axis=1, keepdims=True)
546
+ ray_unit = ray / np.maximum(ray_norm, 1e-6)
547
+
548
+ identity = np.eye(3, dtype=np.float64)
549
+ system = np.zeros((3, 3), dtype=np.float64)
550
+ rhs = np.zeros(3, dtype=np.float64)
551
+ for point, direction in zip(src_np.astype(np.float64), ray_unit.astype(np.float64)):
552
+ proj = identity - np.outer(direction, direction)
553
+ system += proj
554
+ rhs += proj @ point
555
+ return np.linalg.solve(system, rhs).astype(np.float32)
556
+
557
+
558
+ def diagnose_cone_geometry(src_pos, det_center, det_u_vec, det_v_vec):
559
+ """Return compact geometry diagnostics for debugging cone trajectories."""
560
+ src_np = _as_3d_float_array(src_pos, "src_pos")
561
+ det_c_np = _as_3d_float_array(det_center, "det_center")
562
+ det_u_np = _normalize_detector_vectors(
563
+ _as_3d_float_array(det_u_vec, "det_u_vec"),
564
+ np.array([1.0, 0.0, 0.0], dtype=np.float32),
565
+ )
566
+ det_v_np = _normalize_detector_vectors(
567
+ _as_3d_float_array(det_v_vec, "det_v_vec"),
568
+ np.array([0.0, 0.0, 1.0], dtype=np.float32),
569
+ )
570
+
571
+ src_norm = np.linalg.norm(src_np, axis=1)
572
+ ray = det_c_np - src_np
573
+ ray_norm = np.linalg.norm(ray, axis=1)
574
+ ray_unit = ray / np.maximum(ray_norm[:, None], 1e-6)
575
+ src_unit = src_np / np.maximum(src_norm[:, None], 1e-6)
576
+
577
+ normal = np.cross(det_u_np, det_v_np)
578
+ normal = _normalize_detector_vectors(
579
+ normal,
580
+ np.array([0.0, 0.0, 1.0], dtype=np.float32),
581
+ )
582
+ isocenter = estimate_cone_isocenter(src_np, det_c_np)
583
+ dist_to_iso = np.linalg.norm(np.cross(ray_unit, src_np - isocenter), axis=1)
584
+
585
+ return {
586
+ "n_views": int(src_np.shape[0]),
587
+ "sid_min_mm": float(src_norm.min()),
588
+ "sid_max_mm": float(src_norm.max()),
589
+ "sdd_min_mm": float(ray_norm.min()),
590
+ "sdd_max_mm": float(ray_norm.max()),
591
+ "det_u_dot_det_v_max_abs": float(np.abs(np.sum(det_u_np * det_v_np, axis=1)).max()),
592
+ "det_u_dot_ray_max_abs": float(np.abs(np.sum(det_u_np * ray_unit, axis=1)).max()),
593
+ "det_v_dot_ray_max_abs": float(np.abs(np.sum(det_v_np * ray_unit, axis=1)).max()),
594
+ "normal_dot_ray_mean": float(np.mean(np.sum(normal * ray_unit, axis=1))),
595
+ "ray_vs_minus_source_mean": float(np.mean(np.sum(ray_unit * (-src_unit), axis=1))),
596
+ "estimated_isocenter_x_mm": float(isocenter[0]),
597
+ "estimated_isocenter_y_mm": float(isocenter[1]),
598
+ "estimated_isocenter_z_mm": float(isocenter[2]),
599
+ "ray_to_isocenter_max_mm": float(dist_to_iso.max()),
600
+ "ray_to_isocenter_mean_mm": float(dist_to_iso.mean()),
601
+ }
@@ -0,0 +1,85 @@
1
+ """Iterative reconstruction algorithms built on user-supplied projectors."""
2
+
3
+ from .cases import (
4
+ MeasuredConeDataConfig,
5
+ NpyProjectionsConfig,
6
+ ReconstructionCase,
7
+ build_cone_3d_case,
8
+ build_fan_2d_case,
9
+ build_measured_cone_3d_case,
10
+ build_npy_cone_3d_case,
11
+ build_parallel_2d_case,
12
+ make_cone_3d_operators,
13
+ make_fan_2d_operators,
14
+ make_parallel_2d_operators,
15
+ )
16
+ from ._core import (
17
+ BackProjector,
18
+ ForwardProjector,
19
+ ReconstructionParameters,
20
+ RegularizationParameters,
21
+ )
22
+ from .asd_pocs import ASDPOCSParameters, ASD_POCS_Parameter, reconstruct_asd_pocs, run_asd_pocs
23
+ from .awtv_pocs import AwTVPOCSParameters, AwTV_POCS_Parameter, reconstruct_awtv_pocs, run_awtv_pocs
24
+ from .dart import DARTParameters, reconstruct_dart, run_dart
25
+ from .fbp import FBPParameters, reconstruct_fbp, run_fbp
26
+ from .fdk import FDKParameters, reconstruct_fdk, run_fdk
27
+ from .sart import SARTParameters, reconstruct_sart, run_sart
28
+ from .sirt import SIRTParameters, reconstruct_sirt, run_sirt
29
+ from .tv_pocs import TVPOCSParameters, TV_POCS_Parameter, reconstruct_tv_pocs, run_tv_pocs
30
+
31
+
32
+ Reconstruction_Parameter = ReconstructionParameters
33
+ Regularisation_Parameter = RegularizationParameters
34
+
35
+ __all__ = [
36
+ "MeasuredConeDataConfig",
37
+ "NpyProjectionsConfig",
38
+ "ReconstructionCase",
39
+ "build_parallel_2d_case",
40
+ "build_fan_2d_case",
41
+ "build_cone_3d_case",
42
+ "build_measured_cone_3d_case",
43
+ "build_npy_cone_3d_case",
44
+ "make_parallel_2d_operators",
45
+ "make_fan_2d_operators",
46
+ "make_cone_3d_operators",
47
+ "BackProjector",
48
+ "ForwardProjector",
49
+ "ReconstructionParameters",
50
+ "RegularizationParameters",
51
+ "Reconstruction_Parameter",
52
+ "Regularisation_Parameter",
53
+ "SARTParameters",
54
+ "run_sart",
55
+ "reconstruct_sart",
56
+ "SIRTParameters",
57
+ "run_sirt",
58
+ "reconstruct_sirt",
59
+ "SARTDiagnosticsResult",
60
+ "SARTProjectionSnapshot",
61
+ "default_projection_indices",
62
+ "diagnose_sart",
63
+ "plot_sart_projection_diagnostics",
64
+ "TVPOCSParameters",
65
+ "TV_POCS_Parameter",
66
+ "run_tv_pocs",
67
+ "reconstruct_tv_pocs",
68
+ "ASDPOCSParameters",
69
+ "ASD_POCS_Parameter",
70
+ "run_asd_pocs",
71
+ "reconstruct_asd_pocs",
72
+ "AwTVPOCSParameters",
73
+ "AwTV_POCS_Parameter",
74
+ "run_awtv_pocs",
75
+ "reconstruct_awtv_pocs",
76
+ "DARTParameters",
77
+ "run_dart",
78
+ "reconstruct_dart",
79
+ "FBPParameters",
80
+ "run_fbp",
81
+ "reconstruct_fbp",
82
+ "FDKParameters",
83
+ "run_fdk",
84
+ "reconstruct_fdk",
85
+ ]