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/__about__.py +3 -0
- diffct_mlx/__init__.py +223 -0
- diffct_mlx/constants.py +38 -0
- diffct_mlx/geometry.py +802 -0
- diffct_mlx/kernels/__init__.py +39 -0
- diffct_mlx/kernels/cone_beam.py +708 -0
- diffct_mlx/kernels/fan_beam.py +502 -0
- diffct_mlx/kernels/parallel_beam.py +431 -0
- diffct_mlx/phantoms/__init__.py +5 -0
- diffct_mlx/phantoms/shepp_logan.py +118 -0
- diffct_mlx/projectors.py +1084 -0
- diffct_mlx/real_measured_data_helper.py +601 -0
- diffct_mlx/reconstruction_algorithms/__init__.py +85 -0
- diffct_mlx/reconstruction_algorithms/_analytic.py +101 -0
- diffct_mlx/reconstruction_algorithms/_core.py +872 -0
- diffct_mlx/reconstruction_algorithms/asd_pocs.py +114 -0
- diffct_mlx/reconstruction_algorithms/awtv_pocs.py +106 -0
- diffct_mlx/reconstruction_algorithms/cases.py +988 -0
- diffct_mlx/reconstruction_algorithms/dart.py +424 -0
- diffct_mlx/reconstruction_algorithms/fbp.py +69 -0
- diffct_mlx/reconstruction_algorithms/fdk.py +67 -0
- diffct_mlx/reconstruction_algorithms/sart.py +66 -0
- diffct_mlx/reconstruction_algorithms/sirt.py +64 -0
- diffct_mlx/reconstruction_algorithms/tv_pocs.py +85 -0
- diffct_mlx/regularizers.py +122 -0
- diffct_mlx/tv_gradients.py +74 -0
- diffct_mlx/utils.py +64 -0
- diffct_mlx-1.0.1.dist-info/METADATA +315 -0
- diffct_mlx-1.0.1.dist-info/RECORD +31 -0
- diffct_mlx-1.0.1.dist-info/WHEEL +4 -0
- diffct_mlx-1.0.1.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,988 @@
|
|
|
1
|
+
"""Reusable reconstruction-case builders for example and benchmark scripts."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Callable
|
|
10
|
+
|
|
11
|
+
import mlx.core as mx
|
|
12
|
+
import numpy as np
|
|
13
|
+
|
|
14
|
+
from ..geometry import (
|
|
15
|
+
circular_trajectory_2d_fan,
|
|
16
|
+
circular_trajectory_2d_parallel,
|
|
17
|
+
circular_trajectory_3d,
|
|
18
|
+
load_arbitrary_cone_geometry_from_json,
|
|
19
|
+
)
|
|
20
|
+
from ..phantoms import shepp_logan_2d, shepp_logan_3d
|
|
21
|
+
from ..projectors import (
|
|
22
|
+
fan_backward_footprint,
|
|
23
|
+
cone_backward,
|
|
24
|
+
cone_backward_footprint,
|
|
25
|
+
fan_forward_footprint,
|
|
26
|
+
cone_forward,
|
|
27
|
+
cone_forward_footprint,
|
|
28
|
+
fan_backward,
|
|
29
|
+
fan_forward,
|
|
30
|
+
parallel_backward_footprint,
|
|
31
|
+
parallel_backward,
|
|
32
|
+
parallel_forward_footprint,
|
|
33
|
+
parallel_forward,
|
|
34
|
+
)
|
|
35
|
+
from ..real_measured_data_helper import (
|
|
36
|
+
apply_detector_geometry_convention,
|
|
37
|
+
auto_voxel_spacing_from_detector,
|
|
38
|
+
load_tiff_projections,
|
|
39
|
+
normalize_volume,
|
|
40
|
+
resize_volume_to_shape,
|
|
41
|
+
shift_detector_center,
|
|
42
|
+
transform_detector_offsets,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
Array = mx.array
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass
|
|
50
|
+
class ReconstructionCase:
|
|
51
|
+
"""Container describing one reconstruction problem instance."""
|
|
52
|
+
|
|
53
|
+
name: str
|
|
54
|
+
sinogram: Array
|
|
55
|
+
volume_shape: tuple[int, ...]
|
|
56
|
+
forward_single: Callable[[Array, int], Array]
|
|
57
|
+
back_single: Callable[[Array, int], Array]
|
|
58
|
+
back_project_all: Callable[[Array], Array]
|
|
59
|
+
reference: Array | None = None
|
|
60
|
+
reference_title: str | None = None
|
|
61
|
+
supports_fbp: bool = False
|
|
62
|
+
supports_fdk: bool = False
|
|
63
|
+
fbp_normalization_scale: float | None = None
|
|
64
|
+
iterative_iteration_count: int = 5
|
|
65
|
+
sirt_iteration_count: int = 15
|
|
66
|
+
iterative_sart_iteration_count: int = 2
|
|
67
|
+
iterative_projection_subset_count: int = 1
|
|
68
|
+
iterative_normalized_sart_relaxation: float = 0.9
|
|
69
|
+
iterative_backprojection_scale: float | None = 0.215
|
|
70
|
+
pocs_iterative_update_method: str = "sart"
|
|
71
|
+
iterative_positivity_mode: str = "per_iteration"
|
|
72
|
+
iterative_detector_border_u: int = 0
|
|
73
|
+
iterative_detector_border_v: int = 0
|
|
74
|
+
iterative_volume_border_width: int = 0
|
|
75
|
+
iterative_volume_support_mask: Array | None = None
|
|
76
|
+
iterative_volume_support_mask_mode: str = "always"
|
|
77
|
+
iterative_voxel_sensitivity_normalization: bool = False
|
|
78
|
+
iterative_preserve_unmasked_computed_projection: bool = False
|
|
79
|
+
iterative_projection_weights: tuple[float, ...] | None = None
|
|
80
|
+
tv_reg_iteration_count: int = 6
|
|
81
|
+
tv_alpha: float = 0.12
|
|
82
|
+
asd_reg_iteration_count: int = 6
|
|
83
|
+
asd_alpha: float = 0.12
|
|
84
|
+
asd_epsilon: float = 0.05
|
|
85
|
+
awtv_reg_iteration_count: int = 6
|
|
86
|
+
awtv_alpha: float = 0.12
|
|
87
|
+
awtv_epsilon: float = 0.08
|
|
88
|
+
awtv_delta: float = 0.6e-2
|
|
89
|
+
fdk_normalization_scale: float | None = None
|
|
90
|
+
fbp_weight: Callable[[Array], Array] | None = None
|
|
91
|
+
fdk_weight: Callable[[Array], Array] | None = None
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
@dataclass
|
|
95
|
+
class MeasuredConeDataConfig:
|
|
96
|
+
"""Configuration for loading measured cone-beam data."""
|
|
97
|
+
|
|
98
|
+
data_dir: str | Path
|
|
99
|
+
volume_shape: tuple[int, int, int] = (128, 128, 128)
|
|
100
|
+
voxel_spacing_mm: float | None = None
|
|
101
|
+
target_view_count: int = 360
|
|
102
|
+
target_detector_shape: tuple[int, int] = (256, 256)
|
|
103
|
+
trajectory_json_path: str | Path | None = None
|
|
104
|
+
reference_volume_path: str | Path | None = None
|
|
105
|
+
reference_meta_path: str | Path | None = None
|
|
106
|
+
recenter_to_isocenter: bool = True
|
|
107
|
+
flip_det_u: bool = False
|
|
108
|
+
flip_det_v: bool = False
|
|
109
|
+
transpose_uv: bool = True
|
|
110
|
+
flip_u: bool = False
|
|
111
|
+
flip_v: bool = False
|
|
112
|
+
log_transform: bool = True
|
|
113
|
+
revert: bool = False
|
|
114
|
+
viewwise_i0: bool = True
|
|
115
|
+
air_border_px: int = 16
|
|
116
|
+
subtract_air_baseline: bool = True
|
|
117
|
+
air_baseline_percentile: float = 50.0
|
|
118
|
+
measured_fov_margin_mm: float = 8.0
|
|
119
|
+
use_leap_fov_support_mask: bool = True
|
|
120
|
+
support_mask_sensitivity_threshold_ratio: float = 1e-3
|
|
121
|
+
iterative_volume_support_mask_mode: str = "final"
|
|
122
|
+
iterative_projection_subset_count: int = 1
|
|
123
|
+
iterative_normalized_sart_relaxation: float = 0.9
|
|
124
|
+
iterative_backprojection_scale: float | None = None
|
|
125
|
+
projector_mode: str = "footprint"
|
|
126
|
+
normalize_reference: bool = True
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _center_crop_or_pad_volume(volume, target_shape):
|
|
130
|
+
"""Match a volume to a target shape without changing its voxel spacing."""
|
|
131
|
+
volume_np = np.asarray(volume, dtype=np.float32)
|
|
132
|
+
target_shape = tuple(int(x) for x in target_shape)
|
|
133
|
+
if volume_np.shape == target_shape:
|
|
134
|
+
return volume_np
|
|
135
|
+
|
|
136
|
+
result = volume_np
|
|
137
|
+
for axis, target_size in enumerate(target_shape):
|
|
138
|
+
current_size = result.shape[axis]
|
|
139
|
+
if current_size > target_size:
|
|
140
|
+
start = (current_size - target_size) // 2
|
|
141
|
+
stop = start + target_size
|
|
142
|
+
slices = [slice(None)] * result.ndim
|
|
143
|
+
slices[axis] = slice(start, stop)
|
|
144
|
+
result = result[tuple(slices)]
|
|
145
|
+
|
|
146
|
+
if result.shape == target_shape:
|
|
147
|
+
return result.astype(np.float32, copy=False)
|
|
148
|
+
|
|
149
|
+
pad_width = []
|
|
150
|
+
for current_size, target_size in zip(result.shape, target_shape):
|
|
151
|
+
total_pad = max(0, target_size - current_size)
|
|
152
|
+
before = total_pad // 2
|
|
153
|
+
after = total_pad - before
|
|
154
|
+
pad_width.append((before, after))
|
|
155
|
+
return np.pad(result, pad_width, mode="constant").astype(np.float32, copy=False)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _trajectory_quadrature_weights(src_pos) -> tuple[float, ...]:
|
|
159
|
+
"""Approximate LEAP-style view quadrature weights from source-direction spacing."""
|
|
160
|
+
src_np = np.asarray(src_pos, dtype=np.float32)
|
|
161
|
+
if src_np.ndim != 2 or src_np.shape[0] <= 1:
|
|
162
|
+
return tuple(1.0 for _ in range(max(1, int(src_np.shape[0]) if src_np.ndim == 2 else 1)))
|
|
163
|
+
|
|
164
|
+
norms = np.linalg.norm(src_np, axis=1, keepdims=True)
|
|
165
|
+
directions = src_np / np.maximum(norms, 1e-6)
|
|
166
|
+
pairwise = np.sum(directions[:-1] * directions[1:], axis=1)
|
|
167
|
+
pairwise = np.clip(pairwise, -1.0, 1.0)
|
|
168
|
+
arc = np.arccos(pairwise).astype(np.float32)
|
|
169
|
+
|
|
170
|
+
weights = np.empty(src_np.shape[0], dtype=np.float32)
|
|
171
|
+
weights[0] = arc[0]
|
|
172
|
+
weights[-1] = arc[-1]
|
|
173
|
+
if src_np.shape[0] > 2:
|
|
174
|
+
weights[1:-1] = 0.5 * (arc[:-1] + arc[1:])
|
|
175
|
+
|
|
176
|
+
positive = weights > 0.0
|
|
177
|
+
if not np.any(positive):
|
|
178
|
+
return tuple(1.0 for _ in range(src_np.shape[0]))
|
|
179
|
+
mean_weight = float(np.mean(weights[positive]))
|
|
180
|
+
if mean_weight <= 0.0:
|
|
181
|
+
return tuple(1.0 for _ in range(src_np.shape[0]))
|
|
182
|
+
weights = weights / mean_weight
|
|
183
|
+
return tuple(float(value) for value in weights)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _build_sensitivity_support_mask(
|
|
187
|
+
back_project_all: Callable[[Array], Array],
|
|
188
|
+
sinogram_shape: tuple[int, ...],
|
|
189
|
+
*,
|
|
190
|
+
threshold_ratio: float = 1e-3,
|
|
191
|
+
) -> np.ndarray:
|
|
192
|
+
"""Build a soft reconstruction-support mask from the cone-beam sensitivity map."""
|
|
193
|
+
detector_coverage = mx.ones(sinogram_shape, dtype=mx.float32)
|
|
194
|
+
sensitivity = np.asarray(back_project_all(detector_coverage), dtype=np.float32)
|
|
195
|
+
positive = sensitivity[sensitivity > 0.0]
|
|
196
|
+
if positive.size == 0:
|
|
197
|
+
return np.ones(sensitivity.shape, dtype=bool)
|
|
198
|
+
|
|
199
|
+
threshold_ratio = max(float(threshold_ratio), 0.0)
|
|
200
|
+
threshold = max(float(np.max(positive)) * threshold_ratio, np.finfo(np.float32).eps)
|
|
201
|
+
support_mask = sensitivity >= threshold
|
|
202
|
+
if not np.any(support_mask):
|
|
203
|
+
return np.ones(sensitivity.shape, dtype=bool)
|
|
204
|
+
return support_mask.astype(bool, copy=False)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _build_leap_style_circular_fov_mask(
|
|
208
|
+
volume_shape: tuple[int, int, int],
|
|
209
|
+
voxel_spacing_mm: float,
|
|
210
|
+
detector_shape_uv: tuple[int, int],
|
|
211
|
+
detector_pitch_u_mm: float,
|
|
212
|
+
src_pos,
|
|
213
|
+
det_center,
|
|
214
|
+
*,
|
|
215
|
+
fov_margin_mm: float = 0.0,
|
|
216
|
+
) -> np.ndarray:
|
|
217
|
+
"""Build LEAP-style circular XY support from the smallest in-plane detector coverage."""
|
|
218
|
+
src_np = np.asarray(src_pos, dtype=np.float32)
|
|
219
|
+
det_center_np = np.asarray(det_center, dtype=np.float32)
|
|
220
|
+
sid = np.linalg.norm(src_np, axis=1)
|
|
221
|
+
sdd = np.linalg.norm(det_center_np - src_np, axis=1)
|
|
222
|
+
magnification_inv = sid / np.maximum(sdd, 1e-6)
|
|
223
|
+
|
|
224
|
+
det_u_count, _ = detector_shape_uv
|
|
225
|
+
half_fov_u_mm = 0.5 * float(det_u_count) * float(detector_pitch_u_mm) * magnification_inv
|
|
226
|
+
radius_xy_mm = float(np.min(half_fov_u_mm)) - float(fov_margin_mm)
|
|
227
|
+
radius_xy_mm = max(radius_xy_mm, float(voxel_spacing_mm))
|
|
228
|
+
|
|
229
|
+
nz, ny, nx = (int(value) for value in volume_shape)
|
|
230
|
+
y_coords = (np.arange(ny, dtype=np.float32) - 0.5 * (ny - 1)) * float(voxel_spacing_mm)
|
|
231
|
+
x_coords = (np.arange(nx, dtype=np.float32) - 0.5 * (nx - 1)) * float(voxel_spacing_mm)
|
|
232
|
+
|
|
233
|
+
yy, xx = np.meshgrid(y_coords, x_coords, indexing="ij")
|
|
234
|
+
radial_keep = (xx * xx + yy * yy) <= (radius_xy_mm * radius_xy_mm)
|
|
235
|
+
return np.broadcast_to(radial_keep[None, :, :], (nz, ny, nx)).astype(bool, copy=False)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def make_parallel_2d_operators(
|
|
239
|
+
ray_dir: Array,
|
|
240
|
+
det_origin: Array,
|
|
241
|
+
det_u_vec: Array,
|
|
242
|
+
*,
|
|
243
|
+
image_shape: tuple[int, int],
|
|
244
|
+
num_detectors: int,
|
|
245
|
+
detector_spacing: float = 1.0,
|
|
246
|
+
voxel_spacing: float = 1.0,
|
|
247
|
+
projector_mode: str = "footprint",
|
|
248
|
+
) -> tuple[Callable[[Array, int], Array], Callable[[Array, int], Array], Callable[[Array], Array]]:
|
|
249
|
+
"""Create single-view and all-view parallel-beam projector wrappers."""
|
|
250
|
+
ny, nx = image_shape
|
|
251
|
+
projector_key = str(projector_mode).strip().lower()
|
|
252
|
+
if projector_key == "siddon":
|
|
253
|
+
forward_op = parallel_forward
|
|
254
|
+
backward_op = parallel_backward
|
|
255
|
+
elif projector_key == "footprint":
|
|
256
|
+
forward_op = parallel_forward_footprint
|
|
257
|
+
backward_op = parallel_backward_footprint
|
|
258
|
+
else:
|
|
259
|
+
raise ValueError(f"Unknown parallel projector_mode: {projector_mode!r}")
|
|
260
|
+
|
|
261
|
+
def forward_single(volume: Array, projection_index: int) -> Array:
|
|
262
|
+
return forward_op(
|
|
263
|
+
volume,
|
|
264
|
+
ray_dir[projection_index : projection_index + 1],
|
|
265
|
+
det_origin[projection_index : projection_index + 1],
|
|
266
|
+
det_u_vec[projection_index : projection_index + 1],
|
|
267
|
+
num_detectors=num_detectors,
|
|
268
|
+
detector_spacing=detector_spacing,
|
|
269
|
+
voxel_spacing=voxel_spacing,
|
|
270
|
+
)[0]
|
|
271
|
+
|
|
272
|
+
def forward_slice(volume: Array, start: int, stop: int) -> Array:
|
|
273
|
+
return forward_op(
|
|
274
|
+
volume,
|
|
275
|
+
ray_dir[start:stop],
|
|
276
|
+
det_origin[start:stop],
|
|
277
|
+
det_u_vec[start:stop],
|
|
278
|
+
num_detectors=num_detectors,
|
|
279
|
+
detector_spacing=detector_spacing,
|
|
280
|
+
voxel_spacing=voxel_spacing,
|
|
281
|
+
)
|
|
282
|
+
|
|
283
|
+
def back_single(projection: Array, projection_index: int) -> Array:
|
|
284
|
+
return backward_op(
|
|
285
|
+
mx.array(projection, dtype=mx.float32)[None, :],
|
|
286
|
+
ray_dir[projection_index : projection_index + 1],
|
|
287
|
+
det_origin[projection_index : projection_index + 1],
|
|
288
|
+
det_u_vec[projection_index : projection_index + 1],
|
|
289
|
+
detector_spacing=detector_spacing,
|
|
290
|
+
H=ny,
|
|
291
|
+
W=nx,
|
|
292
|
+
voxel_spacing=voxel_spacing,
|
|
293
|
+
)
|
|
294
|
+
|
|
295
|
+
def back_slice(projection: Array, start: int, stop: int) -> Array:
|
|
296
|
+
return backward_op(
|
|
297
|
+
mx.array(projection, dtype=mx.float32),
|
|
298
|
+
ray_dir[start:stop],
|
|
299
|
+
det_origin[start:stop],
|
|
300
|
+
det_u_vec[start:stop],
|
|
301
|
+
detector_spacing=detector_spacing,
|
|
302
|
+
H=ny,
|
|
303
|
+
W=nx,
|
|
304
|
+
voxel_spacing=voxel_spacing,
|
|
305
|
+
)
|
|
306
|
+
|
|
307
|
+
def back_project_all(filtered_sinogram: Array) -> Array:
|
|
308
|
+
return backward_op(
|
|
309
|
+
filtered_sinogram,
|
|
310
|
+
ray_dir,
|
|
311
|
+
det_origin,
|
|
312
|
+
det_u_vec,
|
|
313
|
+
detector_spacing=detector_spacing,
|
|
314
|
+
H=ny,
|
|
315
|
+
W=nx,
|
|
316
|
+
voxel_spacing=voxel_spacing,
|
|
317
|
+
)
|
|
318
|
+
|
|
319
|
+
forward_single.project_slice = forward_slice # type: ignore[attr-defined]
|
|
320
|
+
back_single.project_slice = back_slice # type: ignore[attr-defined]
|
|
321
|
+
return forward_single, back_single, back_project_all
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def make_fan_2d_operators(
|
|
325
|
+
src_pos: Array,
|
|
326
|
+
det_center: Array,
|
|
327
|
+
det_u_vec: Array,
|
|
328
|
+
*,
|
|
329
|
+
image_shape: tuple[int, int],
|
|
330
|
+
num_detectors: int,
|
|
331
|
+
detector_spacing: float = 1.0,
|
|
332
|
+
voxel_spacing: float = 1.0,
|
|
333
|
+
projector_mode: str = "footprint",
|
|
334
|
+
) -> tuple[Callable[[Array, int], Array], Callable[[Array, int], Array], Callable[[Array], Array]]:
|
|
335
|
+
"""Create single-view and all-view fan-beam projector wrappers."""
|
|
336
|
+
ny, nx = image_shape
|
|
337
|
+
projector_key = str(projector_mode).strip().lower()
|
|
338
|
+
if projector_key == "siddon":
|
|
339
|
+
forward_op = fan_forward
|
|
340
|
+
backward_op = fan_backward
|
|
341
|
+
elif projector_key == "footprint":
|
|
342
|
+
forward_op = fan_forward_footprint
|
|
343
|
+
backward_op = fan_backward_footprint
|
|
344
|
+
else:
|
|
345
|
+
raise ValueError(f"Unknown fan projector_mode: {projector_mode!r}")
|
|
346
|
+
|
|
347
|
+
def forward_single(volume: Array, projection_index: int) -> Array:
|
|
348
|
+
return forward_op(
|
|
349
|
+
volume,
|
|
350
|
+
src_pos[projection_index : projection_index + 1],
|
|
351
|
+
det_center[projection_index : projection_index + 1],
|
|
352
|
+
det_u_vec[projection_index : projection_index + 1],
|
|
353
|
+
num_detectors=num_detectors,
|
|
354
|
+
detector_spacing=detector_spacing,
|
|
355
|
+
voxel_spacing=voxel_spacing,
|
|
356
|
+
)[0]
|
|
357
|
+
|
|
358
|
+
def forward_slice(volume: Array, start: int, stop: int) -> Array:
|
|
359
|
+
return forward_op(
|
|
360
|
+
volume,
|
|
361
|
+
src_pos[start:stop],
|
|
362
|
+
det_center[start:stop],
|
|
363
|
+
det_u_vec[start:stop],
|
|
364
|
+
num_detectors=num_detectors,
|
|
365
|
+
detector_spacing=detector_spacing,
|
|
366
|
+
voxel_spacing=voxel_spacing,
|
|
367
|
+
)
|
|
368
|
+
|
|
369
|
+
def back_single(projection: Array, projection_index: int) -> Array:
|
|
370
|
+
return backward_op(
|
|
371
|
+
mx.array(projection, dtype=mx.float32)[None, :],
|
|
372
|
+
src_pos[projection_index : projection_index + 1],
|
|
373
|
+
det_center[projection_index : projection_index + 1],
|
|
374
|
+
det_u_vec[projection_index : projection_index + 1],
|
|
375
|
+
detector_spacing=detector_spacing,
|
|
376
|
+
H=ny,
|
|
377
|
+
W=nx,
|
|
378
|
+
voxel_spacing=voxel_spacing,
|
|
379
|
+
)
|
|
380
|
+
|
|
381
|
+
def back_slice(projection: Array, start: int, stop: int) -> Array:
|
|
382
|
+
return backward_op(
|
|
383
|
+
mx.array(projection, dtype=mx.float32),
|
|
384
|
+
src_pos[start:stop],
|
|
385
|
+
det_center[start:stop],
|
|
386
|
+
det_u_vec[start:stop],
|
|
387
|
+
detector_spacing=detector_spacing,
|
|
388
|
+
H=ny,
|
|
389
|
+
W=nx,
|
|
390
|
+
voxel_spacing=voxel_spacing,
|
|
391
|
+
)
|
|
392
|
+
|
|
393
|
+
def back_project_all(filtered_sinogram: Array) -> Array:
|
|
394
|
+
return backward_op(
|
|
395
|
+
filtered_sinogram,
|
|
396
|
+
src_pos,
|
|
397
|
+
det_center,
|
|
398
|
+
det_u_vec,
|
|
399
|
+
detector_spacing=detector_spacing,
|
|
400
|
+
H=ny,
|
|
401
|
+
W=nx,
|
|
402
|
+
voxel_spacing=voxel_spacing,
|
|
403
|
+
)
|
|
404
|
+
|
|
405
|
+
forward_single.project_slice = forward_slice # type: ignore[attr-defined]
|
|
406
|
+
back_single.project_slice = back_slice # type: ignore[attr-defined]
|
|
407
|
+
return forward_single, back_single, back_project_all
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def make_cone_3d_operators(
|
|
411
|
+
src_pos: Array,
|
|
412
|
+
det_center: Array,
|
|
413
|
+
det_u_vec: Array,
|
|
414
|
+
det_v_vec: Array,
|
|
415
|
+
*,
|
|
416
|
+
volume_shape: tuple[int, int, int],
|
|
417
|
+
detector_shape: tuple[int, int],
|
|
418
|
+
du: float = 1.0,
|
|
419
|
+
dv: float = 1.0,
|
|
420
|
+
voxel_spacing: float = 1.0,
|
|
421
|
+
projector_mode: str = "footprint",
|
|
422
|
+
) -> tuple[Callable[[Array, int], Array], Callable[[Array, int], Array], Callable[[Array], Array]]:
|
|
423
|
+
"""Create single-view and all-view cone-beam projector wrappers."""
|
|
424
|
+
nz, ny, nx = volume_shape
|
|
425
|
+
det_u_count, det_v_count = detector_shape
|
|
426
|
+
projector_key = str(projector_mode).strip().lower()
|
|
427
|
+
if projector_key == "siddon":
|
|
428
|
+
forward_op = cone_forward
|
|
429
|
+
backward_op = cone_backward
|
|
430
|
+
elif projector_key == "footprint":
|
|
431
|
+
forward_op = cone_forward_footprint
|
|
432
|
+
backward_op = cone_backward_footprint
|
|
433
|
+
else:
|
|
434
|
+
raise ValueError(f"Unknown cone projector_mode: {projector_mode!r}")
|
|
435
|
+
|
|
436
|
+
def forward_single(volume: Array, projection_index: int) -> Array:
|
|
437
|
+
return forward_op(
|
|
438
|
+
volume,
|
|
439
|
+
src_pos[projection_index : projection_index + 1],
|
|
440
|
+
det_center[projection_index : projection_index + 1],
|
|
441
|
+
det_u_vec[projection_index : projection_index + 1],
|
|
442
|
+
det_v_vec[projection_index : projection_index + 1],
|
|
443
|
+
det_u=det_u_count,
|
|
444
|
+
det_v=det_v_count,
|
|
445
|
+
du=du,
|
|
446
|
+
dv=dv,
|
|
447
|
+
voxel_spacing=voxel_spacing,
|
|
448
|
+
)[0]
|
|
449
|
+
|
|
450
|
+
def forward_slice(volume: Array, start: int, stop: int) -> Array:
|
|
451
|
+
return forward_op(
|
|
452
|
+
volume,
|
|
453
|
+
src_pos[start:stop],
|
|
454
|
+
det_center[start:stop],
|
|
455
|
+
det_u_vec[start:stop],
|
|
456
|
+
det_v_vec[start:stop],
|
|
457
|
+
det_u=det_u_count,
|
|
458
|
+
det_v=det_v_count,
|
|
459
|
+
du=du,
|
|
460
|
+
dv=dv,
|
|
461
|
+
voxel_spacing=voxel_spacing,
|
|
462
|
+
)
|
|
463
|
+
|
|
464
|
+
def back_single(projection: Array, projection_index: int) -> Array:
|
|
465
|
+
return backward_op(
|
|
466
|
+
mx.array(projection, dtype=mx.float32)[None, :, :],
|
|
467
|
+
src_pos[projection_index : projection_index + 1],
|
|
468
|
+
det_center[projection_index : projection_index + 1],
|
|
469
|
+
det_u_vec[projection_index : projection_index + 1],
|
|
470
|
+
det_v_vec[projection_index : projection_index + 1],
|
|
471
|
+
D=nz,
|
|
472
|
+
H=ny,
|
|
473
|
+
W=nx,
|
|
474
|
+
du=du,
|
|
475
|
+
dv=dv,
|
|
476
|
+
voxel_spacing=voxel_spacing,
|
|
477
|
+
)
|
|
478
|
+
|
|
479
|
+
def back_slice(projection: Array, start: int, stop: int) -> Array:
|
|
480
|
+
return backward_op(
|
|
481
|
+
mx.array(projection, dtype=mx.float32),
|
|
482
|
+
src_pos[start:stop],
|
|
483
|
+
det_center[start:stop],
|
|
484
|
+
det_u_vec[start:stop],
|
|
485
|
+
det_v_vec[start:stop],
|
|
486
|
+
D=nz,
|
|
487
|
+
H=ny,
|
|
488
|
+
W=nx,
|
|
489
|
+
du=du,
|
|
490
|
+
dv=dv,
|
|
491
|
+
voxel_spacing=voxel_spacing,
|
|
492
|
+
)
|
|
493
|
+
|
|
494
|
+
def back_project_all(filtered_sinogram: Array) -> Array:
|
|
495
|
+
return backward_op(
|
|
496
|
+
filtered_sinogram,
|
|
497
|
+
src_pos,
|
|
498
|
+
det_center,
|
|
499
|
+
det_u_vec,
|
|
500
|
+
det_v_vec,
|
|
501
|
+
D=nz,
|
|
502
|
+
H=ny,
|
|
503
|
+
W=nx,
|
|
504
|
+
du=du,
|
|
505
|
+
dv=dv,
|
|
506
|
+
voxel_spacing=voxel_spacing,
|
|
507
|
+
)
|
|
508
|
+
|
|
509
|
+
forward_single.project_slice = forward_slice # type: ignore[attr-defined]
|
|
510
|
+
back_single.project_slice = back_slice # type: ignore[attr-defined]
|
|
511
|
+
return forward_single, back_single, back_project_all
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
def build_parallel_2d_case(
|
|
515
|
+
*,
|
|
516
|
+
image_shape: tuple[int, int] = (96, 96),
|
|
517
|
+
num_views: int = 180,
|
|
518
|
+
num_detectors: int = 160,
|
|
519
|
+
detector_spacing: float = 1.0,
|
|
520
|
+
voxel_spacing: float = 1.0,
|
|
521
|
+
) -> ReconstructionCase:
|
|
522
|
+
"""Build a Shepp-Logan 2D parallel-beam case."""
|
|
523
|
+
ny, nx = image_shape
|
|
524
|
+
reference = mx.array(shepp_logan_2d((ny, nx)))
|
|
525
|
+
ray_dir, det_origin, det_u_vec = circular_trajectory_2d_parallel(num_views)
|
|
526
|
+
sinogram = parallel_forward_footprint(
|
|
527
|
+
reference,
|
|
528
|
+
ray_dir,
|
|
529
|
+
det_origin,
|
|
530
|
+
det_u_vec,
|
|
531
|
+
num_detectors=num_detectors,
|
|
532
|
+
detector_spacing=detector_spacing,
|
|
533
|
+
voxel_spacing=voxel_spacing,
|
|
534
|
+
)
|
|
535
|
+
|
|
536
|
+
forward_single, back_single, back_project_all = make_parallel_2d_operators(
|
|
537
|
+
ray_dir,
|
|
538
|
+
det_origin,
|
|
539
|
+
det_u_vec,
|
|
540
|
+
image_shape=(ny, nx),
|
|
541
|
+
num_detectors=num_detectors,
|
|
542
|
+
detector_spacing=detector_spacing,
|
|
543
|
+
voxel_spacing=voxel_spacing,
|
|
544
|
+
projector_mode="footprint",
|
|
545
|
+
)
|
|
546
|
+
|
|
547
|
+
return ReconstructionCase(
|
|
548
|
+
name="Parallel 2D",
|
|
549
|
+
sinogram=sinogram,
|
|
550
|
+
volume_shape=(ny, nx),
|
|
551
|
+
forward_single=forward_single,
|
|
552
|
+
back_single=back_single,
|
|
553
|
+
back_project_all=back_project_all,
|
|
554
|
+
reference=reference,
|
|
555
|
+
reference_title="Phantom",
|
|
556
|
+
supports_fbp=True,
|
|
557
|
+
fbp_normalization_scale=math.pi / (2.0 * num_views),
|
|
558
|
+
iterative_voxel_sensitivity_normalization=True,
|
|
559
|
+
)
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
def build_fan_2d_case(
|
|
563
|
+
*,
|
|
564
|
+
image_shape: tuple[int, int] = (256, 256),
|
|
565
|
+
num_views: int = 360,
|
|
566
|
+
num_detectors: int = 600,
|
|
567
|
+
detector_spacing: float = 1.0,
|
|
568
|
+
voxel_spacing: float = 1.0,
|
|
569
|
+
sid: float = 500.0,
|
|
570
|
+
sdd: float = 800.0,
|
|
571
|
+
) -> ReconstructionCase:
|
|
572
|
+
"""Build a Shepp-Logan 2D fan-beam case."""
|
|
573
|
+
ny, nx = image_shape
|
|
574
|
+
reference = mx.array(shepp_logan_2d((ny, nx)))
|
|
575
|
+
src_pos, det_center, det_u_vec = circular_trajectory_2d_fan(num_views, sid, sdd)
|
|
576
|
+
sinogram = fan_forward_footprint(
|
|
577
|
+
reference,
|
|
578
|
+
src_pos,
|
|
579
|
+
det_center,
|
|
580
|
+
det_u_vec,
|
|
581
|
+
num_detectors=num_detectors,
|
|
582
|
+
detector_spacing=detector_spacing,
|
|
583
|
+
voxel_spacing=voxel_spacing,
|
|
584
|
+
)
|
|
585
|
+
|
|
586
|
+
detector_coords = (mx.arange(num_detectors) - (num_detectors - 1) / 2) * detector_spacing
|
|
587
|
+
cosine_weights = mx.cos(mx.arctan(detector_coords / sdd)).reshape(1, -1)
|
|
588
|
+
|
|
589
|
+
forward_single, back_single, back_project_all = make_fan_2d_operators(
|
|
590
|
+
src_pos,
|
|
591
|
+
det_center,
|
|
592
|
+
det_u_vec,
|
|
593
|
+
image_shape=(ny, nx),
|
|
594
|
+
num_detectors=num_detectors,
|
|
595
|
+
detector_spacing=detector_spacing,
|
|
596
|
+
voxel_spacing=voxel_spacing,
|
|
597
|
+
projector_mode="footprint",
|
|
598
|
+
)
|
|
599
|
+
|
|
600
|
+
return ReconstructionCase(
|
|
601
|
+
name="Fan 2D",
|
|
602
|
+
sinogram=sinogram,
|
|
603
|
+
volume_shape=(ny, nx),
|
|
604
|
+
forward_single=forward_single,
|
|
605
|
+
back_single=back_single,
|
|
606
|
+
back_project_all=back_project_all,
|
|
607
|
+
reference=reference,
|
|
608
|
+
reference_title="Phantom",
|
|
609
|
+
supports_fbp=True,
|
|
610
|
+
fbp_normalization_scale=math.pi / (2.0 * num_views),
|
|
611
|
+
fbp_weight=lambda raw: raw * cosine_weights,
|
|
612
|
+
iterative_voxel_sensitivity_normalization=True,
|
|
613
|
+
)
|
|
614
|
+
|
|
615
|
+
|
|
616
|
+
def build_cone_3d_case(
|
|
617
|
+
*,
|
|
618
|
+
volume_shape: tuple[int, int, int] = (128, 128, 128),
|
|
619
|
+
num_views: int = 360,
|
|
620
|
+
detector_shape: tuple[int, int] = (256, 256),
|
|
621
|
+
du: float = 1.0,
|
|
622
|
+
dv: float = 1.0,
|
|
623
|
+
voxel_spacing: float = 1.0,
|
|
624
|
+
sid: float = 600.0,
|
|
625
|
+
sdd: float = 900.0,
|
|
626
|
+
) -> ReconstructionCase:
|
|
627
|
+
"""Build a Shepp-Logan 3D cone-beam case."""
|
|
628
|
+
nz, ny, nx = volume_shape
|
|
629
|
+
det_u_count, det_v_count = detector_shape
|
|
630
|
+
reference = mx.array(shepp_logan_3d((nz, ny, nx)))
|
|
631
|
+
src_pos, det_center, det_u_vec, det_v_vec = circular_trajectory_3d(num_views, sid, sdd)
|
|
632
|
+
sinogram = cone_forward_footprint(
|
|
633
|
+
reference,
|
|
634
|
+
src_pos,
|
|
635
|
+
det_center,
|
|
636
|
+
det_u_vec,
|
|
637
|
+
det_v_vec,
|
|
638
|
+
det_u=det_u_count,
|
|
639
|
+
det_v=det_v_count,
|
|
640
|
+
du=du,
|
|
641
|
+
dv=dv,
|
|
642
|
+
voxel_spacing=voxel_spacing,
|
|
643
|
+
)
|
|
644
|
+
|
|
645
|
+
u_coords = (mx.arange(det_u_count) - (det_u_count - 1) / 2) * du
|
|
646
|
+
v_coords = (mx.arange(det_v_count) - (det_v_count - 1) / 2) * dv
|
|
647
|
+
fdk_weights = sdd / mx.sqrt(
|
|
648
|
+
sdd**2 + u_coords.reshape(1, det_u_count, 1) ** 2 + v_coords.reshape(1, 1, det_v_count) ** 2
|
|
649
|
+
)
|
|
650
|
+
cone_weight = lambda raw: raw * fdk_weights
|
|
651
|
+
|
|
652
|
+
forward_single, back_single, back_project_all = make_cone_3d_operators(
|
|
653
|
+
src_pos,
|
|
654
|
+
det_center,
|
|
655
|
+
det_u_vec,
|
|
656
|
+
det_v_vec,
|
|
657
|
+
volume_shape=(nz, ny, nx),
|
|
658
|
+
detector_shape=(det_u_count, det_v_count),
|
|
659
|
+
du=du,
|
|
660
|
+
dv=dv,
|
|
661
|
+
voxel_spacing=voxel_spacing,
|
|
662
|
+
projector_mode="footprint",
|
|
663
|
+
)
|
|
664
|
+
|
|
665
|
+
normalization = (math.pi * sid) / (2.0 * sdd * num_views)
|
|
666
|
+
return ReconstructionCase(
|
|
667
|
+
name="Cone 3D",
|
|
668
|
+
sinogram=sinogram,
|
|
669
|
+
volume_shape=(nz, ny, nx),
|
|
670
|
+
forward_single=forward_single,
|
|
671
|
+
back_single=back_single,
|
|
672
|
+
back_project_all=back_project_all,
|
|
673
|
+
reference=reference,
|
|
674
|
+
reference_title="Phantom",
|
|
675
|
+
supports_fbp=True,
|
|
676
|
+
supports_fdk=True,
|
|
677
|
+
fbp_normalization_scale=normalization,
|
|
678
|
+
fdk_normalization_scale=normalization,
|
|
679
|
+
fbp_weight=cone_weight,
|
|
680
|
+
fdk_weight=cone_weight,
|
|
681
|
+
)
|
|
682
|
+
|
|
683
|
+
|
|
684
|
+
def build_measured_cone_3d_case(config: MeasuredConeDataConfig) -> ReconstructionCase:
|
|
685
|
+
"""Build a 3D cone-beam case from measured TIFF projections and geometry."""
|
|
686
|
+
data_dir = Path(config.data_dir)
|
|
687
|
+
trajectory_json_path = Path(config.trajectory_json_path)
|
|
688
|
+
reference_volume_path = None if config.reference_volume_path is None else Path(config.reference_volume_path)
|
|
689
|
+
reference_meta_path = None if config.reference_meta_path is None else Path(config.reference_meta_path)
|
|
690
|
+
explicit_voxel_spacing = None if config.voxel_spacing_mm is None else float(config.voxel_spacing_mm)
|
|
691
|
+
|
|
692
|
+
nz, ny, nx = config.volume_shape
|
|
693
|
+
target_det_u, target_det_v = config.target_detector_shape
|
|
694
|
+
|
|
695
|
+
with trajectory_json_path.open("r", encoding="utf-8") as handle:
|
|
696
|
+
geometry_payload = json.load(handle)
|
|
697
|
+
|
|
698
|
+
src_pos, det_center, det_u_vec, det_v_vec = load_arbitrary_cone_geometry_from_json(
|
|
699
|
+
trajectory_json_path,
|
|
700
|
+
flip_det_u=config.flip_det_u,
|
|
701
|
+
flip_det_v=config.flip_det_v,
|
|
702
|
+
recenter_to_isocenter=config.recenter_to_isocenter,
|
|
703
|
+
)
|
|
704
|
+
|
|
705
|
+
view_stride = max(1, int(np.ceil(src_pos.shape[0] / config.target_view_count)))
|
|
706
|
+
det_v_binning = max(1, int(np.ceil(geometry_payload["detector"]["num_pixels"]["v"] / target_det_v)))
|
|
707
|
+
det_u_binning = max(1, int(np.ceil(geometry_payload["detector"]["num_pixels"]["u"] / target_det_u)))
|
|
708
|
+
|
|
709
|
+
measured_sino_np = load_tiff_projections(
|
|
710
|
+
data_dir,
|
|
711
|
+
log_transform=config.log_transform,
|
|
712
|
+
revert=config.revert,
|
|
713
|
+
viewwise_i0=config.viewwise_i0,
|
|
714
|
+
air_border_px=config.air_border_px,
|
|
715
|
+
subtract_air_baseline=config.subtract_air_baseline,
|
|
716
|
+
air_baseline_percentile=config.air_baseline_percentile,
|
|
717
|
+
view_stride=view_stride,
|
|
718
|
+
detector_binning_u=det_u_binning,
|
|
719
|
+
detector_binning_v=det_v_binning,
|
|
720
|
+
debug_visualization=False,
|
|
721
|
+
)
|
|
722
|
+
|
|
723
|
+
src_pos = src_pos[::view_stride]
|
|
724
|
+
det_center = det_center[::view_stride]
|
|
725
|
+
det_u_vec = det_u_vec[::view_stride]
|
|
726
|
+
det_v_vec = det_v_vec[::view_stride]
|
|
727
|
+
|
|
728
|
+
measured_du = float(geometry_payload["detector"]["pixel_size_mm"]["u"]) * det_u_binning
|
|
729
|
+
measured_dv = float(geometry_payload["detector"]["pixel_size_mm"]["v"]) * det_v_binning
|
|
730
|
+
header_offset_u_px = float(geometry_payload["detector"]["offset_px"].get("horizontal", 0.0) or 0.0) / det_u_binning
|
|
731
|
+
header_offset_v_px = float(geometry_payload["detector"]["offset_px"].get("vertical", 0.0) or 0.0) / det_v_binning
|
|
732
|
+
measured_det_v = measured_sino_np.shape[1]
|
|
733
|
+
measured_det_u = measured_sino_np.shape[2]
|
|
734
|
+
|
|
735
|
+
det_u_vec, det_v_vec, measured_du, measured_dv, measured_det_u, measured_det_v = apply_detector_geometry_convention(
|
|
736
|
+
det_u_vec,
|
|
737
|
+
det_v_vec,
|
|
738
|
+
du=measured_du,
|
|
739
|
+
dv=measured_dv,
|
|
740
|
+
det_u=measured_det_u,
|
|
741
|
+
det_v=measured_det_v,
|
|
742
|
+
flip_u=config.flip_u,
|
|
743
|
+
flip_v=config.flip_v,
|
|
744
|
+
transpose_uv=config.transpose_uv,
|
|
745
|
+
)
|
|
746
|
+
header_offset_u_px, header_offset_v_px = transform_detector_offsets(
|
|
747
|
+
header_offset_u_px,
|
|
748
|
+
header_offset_v_px,
|
|
749
|
+
{
|
|
750
|
+
"flip_u": config.flip_u,
|
|
751
|
+
"flip_v": config.flip_v,
|
|
752
|
+
"transpose_uv": config.transpose_uv,
|
|
753
|
+
},
|
|
754
|
+
)
|
|
755
|
+
det_center = shift_detector_center(
|
|
756
|
+
det_center,
|
|
757
|
+
det_u_vec,
|
|
758
|
+
det_v_vec,
|
|
759
|
+
measured_du,
|
|
760
|
+
measured_dv,
|
|
761
|
+
offset_u_px=header_offset_u_px,
|
|
762
|
+
offset_v_px=header_offset_v_px,
|
|
763
|
+
)
|
|
764
|
+
|
|
765
|
+
reference_np = None
|
|
766
|
+
reference_title = None
|
|
767
|
+
resized_reference_voxel_spacing = None
|
|
768
|
+
reference_meta = None
|
|
769
|
+
reference_voxel_spacing = None
|
|
770
|
+
source_shape = None
|
|
771
|
+
if reference_meta_path is not None and reference_meta_path.exists():
|
|
772
|
+
reference_meta = json.loads(reference_meta_path.read_text())
|
|
773
|
+
source_shape = tuple(int(value) for value in reference_meta["shape_zyx"])
|
|
774
|
+
reference_voxel_spacing = float(reference_meta["voxel_size_mm"])
|
|
775
|
+
if explicit_voxel_spacing is None:
|
|
776
|
+
resize_factors = tuple(src / dst for src, dst in zip(source_shape, config.volume_shape))
|
|
777
|
+
if max(resize_factors) - min(resize_factors) > 1e-6:
|
|
778
|
+
raise ValueError(
|
|
779
|
+
f"Reference volume resize must stay isotropic, got factors {resize_factors}."
|
|
780
|
+
)
|
|
781
|
+
resized_reference_voxel_spacing = reference_voxel_spacing * resize_factors[0]
|
|
782
|
+
|
|
783
|
+
if reference_volume_path is not None and reference_meta is not None and reference_volume_path.exists():
|
|
784
|
+
reference_volume_np = np.load(reference_volume_path)
|
|
785
|
+
if explicit_voxel_spacing is None:
|
|
786
|
+
reference_np = resize_volume_to_shape(reference_volume_np, config.volume_shape)
|
|
787
|
+
else:
|
|
788
|
+
if reference_voxel_spacing is not None and source_shape is not None:
|
|
789
|
+
spacing_scale = reference_voxel_spacing / explicit_voxel_spacing
|
|
790
|
+
if abs(spacing_scale - 1.0) > 1e-6:
|
|
791
|
+
resampled_shape = tuple(max(1, int(round(dim * spacing_scale))) for dim in source_shape)
|
|
792
|
+
reference_volume_np = resize_volume_to_shape(reference_volume_np, resampled_shape)
|
|
793
|
+
reference_np = _center_crop_or_pad_volume(reference_volume_np, config.volume_shape)
|
|
794
|
+
if config.normalize_reference:
|
|
795
|
+
reference_np = normalize_volume(reference_np, upper_percentile=None)
|
|
796
|
+
reference_title = "Reference Volume"
|
|
797
|
+
|
|
798
|
+
if explicit_voxel_spacing is not None:
|
|
799
|
+
measured_voxel_spacing = explicit_voxel_spacing
|
|
800
|
+
elif resized_reference_voxel_spacing is not None:
|
|
801
|
+
measured_voxel_spacing = float(resized_reference_voxel_spacing)
|
|
802
|
+
else:
|
|
803
|
+
measured_voxel_spacing = auto_voxel_spacing_from_detector(
|
|
804
|
+
config.volume_shape,
|
|
805
|
+
(measured_det_u, measured_det_v),
|
|
806
|
+
measured_du,
|
|
807
|
+
measured_dv,
|
|
808
|
+
magnification=float(geometry_payload["source"]["magnification"]),
|
|
809
|
+
fov_margin_mm=config.measured_fov_margin_mm,
|
|
810
|
+
)
|
|
811
|
+
|
|
812
|
+
forward_single, back_single, back_project_all = make_cone_3d_operators(
|
|
813
|
+
src_pos,
|
|
814
|
+
det_center,
|
|
815
|
+
det_u_vec,
|
|
816
|
+
det_v_vec,
|
|
817
|
+
volume_shape=(nz, ny, nx),
|
|
818
|
+
detector_shape=(measured_det_u, measured_det_v),
|
|
819
|
+
du=measured_du,
|
|
820
|
+
dv=measured_dv,
|
|
821
|
+
voxel_spacing=measured_voxel_spacing,
|
|
822
|
+
projector_mode=config.projector_mode,
|
|
823
|
+
)
|
|
824
|
+
|
|
825
|
+
iterative_projection_weights = _trajectory_quadrature_weights(src_pos)
|
|
826
|
+
iterative_volume_support_mask = None
|
|
827
|
+
if config.use_leap_fov_support_mask:
|
|
828
|
+
sensitivity_support_mask = _build_sensitivity_support_mask(
|
|
829
|
+
back_project_all,
|
|
830
|
+
tuple(int(value) for value in measured_sino_np.shape),
|
|
831
|
+
threshold_ratio=float(config.support_mask_sensitivity_threshold_ratio),
|
|
832
|
+
)
|
|
833
|
+
circular_fov_mask = _build_leap_style_circular_fov_mask(
|
|
834
|
+
config.volume_shape,
|
|
835
|
+
measured_voxel_spacing,
|
|
836
|
+
(measured_det_u, measured_det_v),
|
|
837
|
+
measured_du,
|
|
838
|
+
src_pos,
|
|
839
|
+
det_center,
|
|
840
|
+
fov_margin_mm=config.measured_fov_margin_mm,
|
|
841
|
+
)
|
|
842
|
+
iterative_volume_support_mask = mx.array(
|
|
843
|
+
sensitivity_support_mask & circular_fov_mask,
|
|
844
|
+
)
|
|
845
|
+
|
|
846
|
+
reference = None if reference_np is None else mx.array(reference_np, dtype=mx.float32)
|
|
847
|
+
sinogram = mx.array(measured_sino_np, dtype=mx.float32)
|
|
848
|
+
return ReconstructionCase(
|
|
849
|
+
name="Measured Cone 3D",
|
|
850
|
+
sinogram=sinogram,
|
|
851
|
+
volume_shape=config.volume_shape,
|
|
852
|
+
forward_single=forward_single,
|
|
853
|
+
back_single=back_single,
|
|
854
|
+
back_project_all=back_project_all,
|
|
855
|
+
reference=reference,
|
|
856
|
+
reference_title=reference_title,
|
|
857
|
+
iterative_projection_subset_count=int(config.iterative_projection_subset_count),
|
|
858
|
+
iterative_normalized_sart_relaxation=float(config.iterative_normalized_sart_relaxation),
|
|
859
|
+
iterative_backprojection_scale=(
|
|
860
|
+
None if config.iterative_backprojection_scale is None else float(config.iterative_backprojection_scale)
|
|
861
|
+
),
|
|
862
|
+
pocs_iterative_update_method="normalized_sart",
|
|
863
|
+
iterative_volume_support_mask=iterative_volume_support_mask,
|
|
864
|
+
iterative_volume_support_mask_mode=str(config.iterative_volume_support_mask_mode),
|
|
865
|
+
iterative_voxel_sensitivity_normalization=(str(config.projector_mode).strip().lower() == "footprint"),
|
|
866
|
+
iterative_projection_weights=iterative_projection_weights,
|
|
867
|
+
)
|
|
868
|
+
|
|
869
|
+
|
|
870
|
+
@dataclass
|
|
871
|
+
class NpyProjectionsConfig:
|
|
872
|
+
"""Configuration for building a cone-beam case from pre-computed .npy line integrals.
|
|
873
|
+
|
|
874
|
+
The npy file must contain raw forward-projector output (float32,
|
|
875
|
+
shape [n_views, det_u, det_v]). No log transform is applied — the
|
|
876
|
+
array is used as the sinogram directly.
|
|
877
|
+
|
|
878
|
+
If the source volume has a non-zero background (e.g. Firefly volumes with a
|
|
879
|
+
constant air offset), set subtract_air_baseline=True. This estimates a
|
|
880
|
+
per-view baseline from the detector border pixels and subtracts it,
|
|
881
|
+
matching the behaviour of the TIFF pipeline's subtract_air_baseline option.
|
|
882
|
+
"""
|
|
883
|
+
|
|
884
|
+
projections_npy_path: str | Path
|
|
885
|
+
geometry_json_path: str | Path
|
|
886
|
+
volume_shape: tuple[int, int, int] = (384, 384, 384)
|
|
887
|
+
voxel_spacing_mm: float = 0.3
|
|
888
|
+
projector_mode: str = "footprint"
|
|
889
|
+
flip_det_u: bool = False
|
|
890
|
+
flip_det_v: bool = False
|
|
891
|
+
recenter_to_isocenter: bool = True
|
|
892
|
+
flip_u: bool = False
|
|
893
|
+
flip_v: bool = False
|
|
894
|
+
transpose_uv: bool = True
|
|
895
|
+
subtract_air_baseline: bool = False
|
|
896
|
+
air_border_px: int = 16
|
|
897
|
+
air_baseline_percentile: float = 50.0
|
|
898
|
+
|
|
899
|
+
|
|
900
|
+
def build_npy_cone_3d_case(config: NpyProjectionsConfig) -> ReconstructionCase:
|
|
901
|
+
"""Build a 3D cone-beam ReconstructionCase from pre-computed line integral projections.
|
|
902
|
+
|
|
903
|
+
Reads the geometry from *geometry_json_path* and the sinogram directly from
|
|
904
|
+
*projections_npy_path* — no TIFF loading or log transform involved.
|
|
905
|
+
The npy shape is [n_views, det_u, det_v] and the geometry positions are
|
|
906
|
+
matched 1-to-1 with the npy views (no striding or binning applied).
|
|
907
|
+
Detector pixel offset must be zero; use build_measured_cone_3d_case for
|
|
908
|
+
data with non-zero detector offsets.
|
|
909
|
+
"""
|
|
910
|
+
geometry_json = Path(config.geometry_json_path)
|
|
911
|
+
with geometry_json.open("r", encoding="utf-8") as fh:
|
|
912
|
+
geo = json.load(fh)
|
|
913
|
+
|
|
914
|
+
src_pos, det_center, det_u_vec, det_v_vec = load_arbitrary_cone_geometry_from_json(
|
|
915
|
+
geometry_json,
|
|
916
|
+
flip_det_u=config.flip_det_u,
|
|
917
|
+
flip_det_v=config.flip_det_v,
|
|
918
|
+
recenter_to_isocenter=config.recenter_to_isocenter,
|
|
919
|
+
)
|
|
920
|
+
src_pos = np.asarray(src_pos)
|
|
921
|
+
det_center = np.asarray(det_center)
|
|
922
|
+
det_u_vec = np.asarray(det_u_vec)
|
|
923
|
+
det_v_vec = np.asarray(det_v_vec)
|
|
924
|
+
|
|
925
|
+
sino_np = np.load(Path(config.projections_npy_path), allow_pickle=False).astype(np.float32)
|
|
926
|
+
n_views = sino_np.shape[0]
|
|
927
|
+
|
|
928
|
+
if config.subtract_air_baseline:
|
|
929
|
+
border_px = max(0, int(config.air_border_px))
|
|
930
|
+
if border_px > 0:
|
|
931
|
+
border_samples = [
|
|
932
|
+
sino_np[:, :border_px, :].reshape(n_views, -1),
|
|
933
|
+
sino_np[:, -border_px:, :].reshape(n_views, -1),
|
|
934
|
+
sino_np[:, :, :border_px].reshape(n_views, -1),
|
|
935
|
+
sino_np[:, :, -border_px:].reshape(n_views, -1),
|
|
936
|
+
]
|
|
937
|
+
baseline_source = np.concatenate(border_samples, axis=1)
|
|
938
|
+
else:
|
|
939
|
+
baseline_source = sino_np.reshape(n_views, -1)
|
|
940
|
+
air_baseline = np.percentile(
|
|
941
|
+
baseline_source,
|
|
942
|
+
float(config.air_baseline_percentile),
|
|
943
|
+
axis=1,
|
|
944
|
+
).astype(np.float32).reshape(n_views, 1, 1)
|
|
945
|
+
sino_np = np.maximum(sino_np - air_baseline, 0.0)
|
|
946
|
+
|
|
947
|
+
src_pos = src_pos[:n_views]
|
|
948
|
+
det_center = det_center[:n_views]
|
|
949
|
+
det_u_vec = det_u_vec[:n_views]
|
|
950
|
+
det_v_vec = det_v_vec[:n_views]
|
|
951
|
+
|
|
952
|
+
du = float(geo["detector"]["pixel_size_mm"]["u"])
|
|
953
|
+
dv = float(geo["detector"]["pixel_size_mm"]["v"])
|
|
954
|
+
det_u = sino_np.shape[1]
|
|
955
|
+
det_v = sino_np.shape[2]
|
|
956
|
+
|
|
957
|
+
det_u_vec, det_v_vec, du, dv, det_u, det_v = apply_detector_geometry_convention(
|
|
958
|
+
det_u_vec, det_v_vec,
|
|
959
|
+
du=du, dv=dv, det_u=det_u, det_v=det_v,
|
|
960
|
+
flip_u=config.flip_u, flip_v=config.flip_v, transpose_uv=config.transpose_uv,
|
|
961
|
+
)
|
|
962
|
+
|
|
963
|
+
nz, ny, nx = config.volume_shape
|
|
964
|
+
forward_single, back_single, back_project_all = make_cone_3d_operators(
|
|
965
|
+
src_pos, det_center, det_u_vec, det_v_vec,
|
|
966
|
+
volume_shape=(nz, ny, nx),
|
|
967
|
+
detector_shape=(det_u, det_v),
|
|
968
|
+
du=du,
|
|
969
|
+
dv=dv,
|
|
970
|
+
voxel_spacing=float(config.voxel_spacing_mm),
|
|
971
|
+
projector_mode=str(config.projector_mode),
|
|
972
|
+
)
|
|
973
|
+
|
|
974
|
+
iterative_projection_weights = _trajectory_quadrature_weights(src_pos)
|
|
975
|
+
|
|
976
|
+
return ReconstructionCase(
|
|
977
|
+
name="NPY Cone 3D",
|
|
978
|
+
sinogram=mx.array(sino_np, dtype=mx.float32),
|
|
979
|
+
volume_shape=config.volume_shape,
|
|
980
|
+
forward_single=forward_single,
|
|
981
|
+
back_single=back_single,
|
|
982
|
+
back_project_all=back_project_all,
|
|
983
|
+
pocs_iterative_update_method="normalized_sart",
|
|
984
|
+
iterative_voxel_sensitivity_normalization=(
|
|
985
|
+
str(config.projector_mode).strip().lower() == "footprint"
|
|
986
|
+
),
|
|
987
|
+
iterative_projection_weights=iterative_projection_weights,
|
|
988
|
+
)
|