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,424 @@
|
|
|
1
|
+
"""Discrete algebraic reconstruction technique (DART) for 2D and 3D problems."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections import deque
|
|
6
|
+
from dataclasses import dataclass, replace
|
|
7
|
+
from itertools import product
|
|
8
|
+
from typing import Sequence
|
|
9
|
+
|
|
10
|
+
import mlx.core as mx
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
from ._core import (
|
|
14
|
+
ArrayLike,
|
|
15
|
+
BackProjector,
|
|
16
|
+
ForwardProjector,
|
|
17
|
+
ReconstructionParameters,
|
|
18
|
+
clamp_reconstruction_volume,
|
|
19
|
+
forward_project_views,
|
|
20
|
+
initialize_volume,
|
|
21
|
+
normalize_measured_projections,
|
|
22
|
+
print_progress,
|
|
23
|
+
run_iterative_sweeps,
|
|
24
|
+
validate_reconstruction_inputs,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class DARTParameters(ReconstructionParameters):
|
|
30
|
+
"""Configuration for discrete-valued DART reconstruction."""
|
|
31
|
+
|
|
32
|
+
gray_levels: Sequence[float] = (0.0, 1.0)
|
|
33
|
+
free_pixel_probability: float = 0.15
|
|
34
|
+
initial_reconstruction_sweeps: int | None = None
|
|
35
|
+
apply_smoothing: bool = True
|
|
36
|
+
smoothing_beta: float = 0.2
|
|
37
|
+
convergence_epsilon: float | None = None
|
|
38
|
+
boundary_connectivity: str = "axial"
|
|
39
|
+
segmentation_threshold_method: str = "midpoint"
|
|
40
|
+
segmentation_threshold_value: float | None = None
|
|
41
|
+
otsu_foreground_only: bool = False
|
|
42
|
+
otsu_percentile_window: tuple[float, float] | None = None
|
|
43
|
+
binary_fill_holes: bool = False
|
|
44
|
+
return_segmented_volume: bool = False
|
|
45
|
+
random_seed: int = 0
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _validate_dart_inputs(
|
|
49
|
+
params: DARTParameters,
|
|
50
|
+
measured_projections: Sequence[ArrayLike],
|
|
51
|
+
) -> np.ndarray:
|
|
52
|
+
"""Validate DART-specific inputs and return the gray levels as NumPy."""
|
|
53
|
+
validate_reconstruction_inputs(params, measured_projections)
|
|
54
|
+
if len(params.volume_shape) not in {2, 3}:
|
|
55
|
+
raise ValueError(
|
|
56
|
+
"DART currently supports only 2D and 3D reconstruction volumes, "
|
|
57
|
+
f"got volume_shape={params.volume_shape!r}."
|
|
58
|
+
)
|
|
59
|
+
gray_levels = np.asarray(params.gray_levels, dtype=np.float32)
|
|
60
|
+
if gray_levels.ndim != 1 or gray_levels.size < 2:
|
|
61
|
+
raise ValueError("gray_levels must contain at least two discrete values.")
|
|
62
|
+
if not np.all(np.isfinite(gray_levels)):
|
|
63
|
+
raise ValueError("gray_levels must be finite.")
|
|
64
|
+
if np.any(np.diff(gray_levels) < 0.0):
|
|
65
|
+
raise ValueError("gray_levels must be sorted in ascending order.")
|
|
66
|
+
if not 0.0 <= float(params.free_pixel_probability) <= 1.0:
|
|
67
|
+
raise ValueError("free_pixel_probability must lie in [0, 1].")
|
|
68
|
+
if params.initial_reconstruction_sweeps is not None and params.initial_reconstruction_sweeps <= 0:
|
|
69
|
+
raise ValueError("initial_reconstruction_sweeps must be positive when specified.")
|
|
70
|
+
if params.iterative_update_method != "sart":
|
|
71
|
+
raise ValueError("DART currently requires iterative_update_method='sart'.")
|
|
72
|
+
if not 0.0 <= float(params.smoothing_beta) <= 1.0:
|
|
73
|
+
raise ValueError("smoothing_beta must lie in [0, 1].")
|
|
74
|
+
if params.convergence_epsilon is not None and not 0.0 <= float(params.convergence_epsilon) <= 1.0:
|
|
75
|
+
raise ValueError("convergence_epsilon must lie in [0, 1] when specified.")
|
|
76
|
+
if params.boundary_connectivity not in {"axial", "full"}:
|
|
77
|
+
raise ValueError("boundary_connectivity must be either 'axial' or 'full'.")
|
|
78
|
+
if params.segmentation_threshold_method not in {"midpoint", "otsu"}:
|
|
79
|
+
raise ValueError("segmentation_threshold_method must be 'midpoint' or 'otsu'.")
|
|
80
|
+
if params.segmentation_threshold_value is not None and gray_levels.size != 2:
|
|
81
|
+
raise ValueError("A manual segmentation threshold currently supports binary DART only.")
|
|
82
|
+
if params.segmentation_threshold_method == "otsu" and gray_levels.size != 2:
|
|
83
|
+
raise ValueError("Otsu thresholding currently supports binary DART only.")
|
|
84
|
+
if params.binary_fill_holes and gray_levels.size != 2:
|
|
85
|
+
raise ValueError("binary_fill_holes currently supports binary DART only.")
|
|
86
|
+
if params.otsu_percentile_window is not None:
|
|
87
|
+
lower_percentile, upper_percentile = params.otsu_percentile_window
|
|
88
|
+
if lower_percentile < 0.0 or upper_percentile > 100.0 or lower_percentile >= upper_percentile:
|
|
89
|
+
raise ValueError("otsu_percentile_window must satisfy 0 <= low < high <= 100.")
|
|
90
|
+
return gray_levels
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _otsu_threshold(
|
|
94
|
+
volume: np.ndarray,
|
|
95
|
+
*,
|
|
96
|
+
foreground_only: bool = False,
|
|
97
|
+
percentile_window: tuple[float, float] | None = None,
|
|
98
|
+
) -> float:
|
|
99
|
+
"""Compute an Otsu threshold from a NumPy array."""
|
|
100
|
+
values = np.asarray(volume, dtype=np.float32)
|
|
101
|
+
values = values[np.isfinite(values)]
|
|
102
|
+
if foreground_only:
|
|
103
|
+
positive_values = values[values > 0.0]
|
|
104
|
+
if positive_values.size > 0:
|
|
105
|
+
values = positive_values
|
|
106
|
+
if percentile_window is not None and values.size > 0:
|
|
107
|
+
lower_percentile, upper_percentile = percentile_window
|
|
108
|
+
lower_value, upper_value = np.percentile(values, [lower_percentile, upper_percentile])
|
|
109
|
+
values = values[(values >= lower_value) & (values <= upper_value)]
|
|
110
|
+
if values.size == 0:
|
|
111
|
+
return 0.0
|
|
112
|
+
value_min = float(np.min(values))
|
|
113
|
+
value_max = float(np.max(values))
|
|
114
|
+
if value_max <= value_min:
|
|
115
|
+
return value_min
|
|
116
|
+
histogram, bin_edges = np.histogram(values, bins=256, range=(value_min, value_max))
|
|
117
|
+
histogram = histogram.astype(np.float64)
|
|
118
|
+
total = float(histogram.sum())
|
|
119
|
+
if total <= 0.0:
|
|
120
|
+
return 0.5 * (value_min + value_max)
|
|
121
|
+
probabilities = histogram / total
|
|
122
|
+
bin_centers = 0.5 * (bin_edges[:-1] + bin_edges[1:])
|
|
123
|
+
cumulative_probability = np.cumsum(probabilities)
|
|
124
|
+
cumulative_mean = np.cumsum(probabilities * bin_centers)
|
|
125
|
+
global_mean = float(cumulative_mean[-1])
|
|
126
|
+
denominator = cumulative_probability * (1.0 - cumulative_probability)
|
|
127
|
+
numerator = (global_mean * cumulative_probability - cumulative_mean) ** 2
|
|
128
|
+
between_class_variance = np.divide(
|
|
129
|
+
numerator,
|
|
130
|
+
denominator,
|
|
131
|
+
out=np.zeros_like(numerator),
|
|
132
|
+
where=denominator > 0.0,
|
|
133
|
+
)
|
|
134
|
+
return float(bin_centers[int(np.argmax(between_class_variance))])
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _segment_volume(
|
|
138
|
+
volume: np.ndarray,
|
|
139
|
+
gray_levels: np.ndarray,
|
|
140
|
+
*,
|
|
141
|
+
threshold_method: str = "midpoint",
|
|
142
|
+
threshold_value: float | None = None,
|
|
143
|
+
otsu_foreground_only: bool = False,
|
|
144
|
+
otsu_percentile_window: tuple[float, float] | None = None,
|
|
145
|
+
) -> np.ndarray:
|
|
146
|
+
"""Project a continuous-valued image onto the configured gray levels."""
|
|
147
|
+
if threshold_value is not None:
|
|
148
|
+
thresholds = np.array([float(threshold_value)], dtype=np.float32)
|
|
149
|
+
elif threshold_method == "otsu":
|
|
150
|
+
threshold = _otsu_threshold(
|
|
151
|
+
volume,
|
|
152
|
+
foreground_only=otsu_foreground_only,
|
|
153
|
+
percentile_window=otsu_percentile_window,
|
|
154
|
+
)
|
|
155
|
+
thresholds = np.array([threshold], dtype=np.float32)
|
|
156
|
+
else:
|
|
157
|
+
thresholds = 0.5 * (gray_levels[:-1] + gray_levels[1:])
|
|
158
|
+
segment_indices = np.digitize(volume, thresholds, right=False)
|
|
159
|
+
return gray_levels[segment_indices]
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _neighbor_offsets(
|
|
163
|
+
ndim: int,
|
|
164
|
+
*,
|
|
165
|
+
connectivity: str,
|
|
166
|
+
) -> tuple[tuple[int, ...], ...]:
|
|
167
|
+
"""Enumerate neighbor offsets for the requested DART connectivity."""
|
|
168
|
+
if connectivity == "axial":
|
|
169
|
+
offsets: list[tuple[int, ...]] = []
|
|
170
|
+
for axis in range(ndim):
|
|
171
|
+
negative = [0] * ndim
|
|
172
|
+
positive = [0] * ndim
|
|
173
|
+
negative[axis] = -1
|
|
174
|
+
positive[axis] = 1
|
|
175
|
+
offsets.append(tuple(negative))
|
|
176
|
+
offsets.append(tuple(positive))
|
|
177
|
+
return tuple(offsets)
|
|
178
|
+
if connectivity == "full":
|
|
179
|
+
return tuple(
|
|
180
|
+
offset
|
|
181
|
+
for offset in product((-1, 0, 1), repeat=ndim)
|
|
182
|
+
if any(component != 0 for component in offset)
|
|
183
|
+
)
|
|
184
|
+
raise ValueError(f"Unsupported connectivity {connectivity!r}.")
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _boundary_pixels(
|
|
188
|
+
segmented: np.ndarray,
|
|
189
|
+
*,
|
|
190
|
+
connectivity: str = "axial",
|
|
191
|
+
) -> np.ndarray:
|
|
192
|
+
"""Return a boolean mask marking cells that touch another gray level."""
|
|
193
|
+
padded = np.pad(segmented, 1, mode="edge")
|
|
194
|
+
boundary = np.zeros(segmented.shape, dtype=bool)
|
|
195
|
+
spatial_shape = segmented.shape
|
|
196
|
+
for offset in _neighbor_offsets(segmented.ndim, connectivity=connectivity):
|
|
197
|
+
slices = tuple(
|
|
198
|
+
slice(1 + offset[axis], 1 + offset[axis] + spatial_shape[axis])
|
|
199
|
+
for axis in range(segmented.ndim)
|
|
200
|
+
)
|
|
201
|
+
neighbor_view = padded[slices]
|
|
202
|
+
boundary |= neighbor_view != segmented
|
|
203
|
+
return boundary
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _sample_free_pixels(
|
|
207
|
+
shape: tuple[int, ...],
|
|
208
|
+
free_pixel_probability: float,
|
|
209
|
+
rng: np.random.Generator,
|
|
210
|
+
) -> np.ndarray:
|
|
211
|
+
"""Randomly sample additional free pixels."""
|
|
212
|
+
return rng.random(shape) < float(free_pixel_probability)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _smooth_boundary_voxels(
|
|
216
|
+
image: np.ndarray,
|
|
217
|
+
boundary_mask: np.ndarray,
|
|
218
|
+
*,
|
|
219
|
+
beta: float,
|
|
220
|
+
connectivity: str = "axial",
|
|
221
|
+
) -> np.ndarray:
|
|
222
|
+
"""Blend boundary voxels toward the mean of their local neighborhood."""
|
|
223
|
+
image = np.asarray(image, dtype=np.float32)
|
|
224
|
+
boundary_mask = np.asarray(boundary_mask, dtype=bool)
|
|
225
|
+
if beta <= 0.0 or not np.any(boundary_mask):
|
|
226
|
+
return np.array(image, copy=True)
|
|
227
|
+
|
|
228
|
+
offsets = _neighbor_offsets(image.ndim, connectivity=connectivity)
|
|
229
|
+
padded = np.pad(image, 1, mode="edge")
|
|
230
|
+
neighbor_sum = np.zeros_like(image, dtype=np.float32)
|
|
231
|
+
spatial_shape = image.shape
|
|
232
|
+
for offset in offsets:
|
|
233
|
+
slices = tuple(
|
|
234
|
+
slice(1 + offset[axis], 1 + offset[axis] + spatial_shape[axis])
|
|
235
|
+
for axis in range(image.ndim)
|
|
236
|
+
)
|
|
237
|
+
neighbor_sum += padded[slices]
|
|
238
|
+
neighbor_mean = neighbor_sum / float(len(offsets))
|
|
239
|
+
|
|
240
|
+
smoothed = np.array(image, copy=True)
|
|
241
|
+
smoothed[boundary_mask] = (
|
|
242
|
+
(1.0 - float(beta)) * image[boundary_mask]
|
|
243
|
+
+ float(beta) * neighbor_mean[boundary_mask]
|
|
244
|
+
)
|
|
245
|
+
return smoothed
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _fill_binary_holes(segmented: np.ndarray, gray_levels: np.ndarray) -> np.ndarray:
|
|
249
|
+
"""Fill enclosed air pockets inside a binary object mask."""
|
|
250
|
+
background_mask = segmented == float(gray_levels[0])
|
|
251
|
+
if not np.any(background_mask):
|
|
252
|
+
return segmented
|
|
253
|
+
|
|
254
|
+
visited = np.zeros_like(background_mask, dtype=bool)
|
|
255
|
+
queue: deque[tuple[int, ...]] = deque()
|
|
256
|
+
|
|
257
|
+
for axis in range(background_mask.ndim):
|
|
258
|
+
for boundary_index in (0, background_mask.shape[axis] - 1):
|
|
259
|
+
boundary_slice = [slice(None)] * background_mask.ndim
|
|
260
|
+
boundary_slice[axis] = boundary_index
|
|
261
|
+
boundary_coords = np.argwhere(background_mask[tuple(boundary_slice)])
|
|
262
|
+
for coord in boundary_coords:
|
|
263
|
+
full_coord = list(coord)
|
|
264
|
+
full_coord.insert(axis, boundary_index)
|
|
265
|
+
full_coord_tuple = tuple(full_coord)
|
|
266
|
+
if not visited[full_coord_tuple]:
|
|
267
|
+
visited[full_coord_tuple] = True
|
|
268
|
+
queue.append(full_coord_tuple)
|
|
269
|
+
|
|
270
|
+
neighbor_offsets = []
|
|
271
|
+
for axis in range(background_mask.ndim):
|
|
272
|
+
negative = [0] * background_mask.ndim
|
|
273
|
+
positive = [0] * background_mask.ndim
|
|
274
|
+
negative[axis] = -1
|
|
275
|
+
positive[axis] = 1
|
|
276
|
+
neighbor_offsets.append(tuple(negative))
|
|
277
|
+
neighbor_offsets.append(tuple(positive))
|
|
278
|
+
|
|
279
|
+
while queue:
|
|
280
|
+
current = queue.popleft()
|
|
281
|
+
for offset in neighbor_offsets:
|
|
282
|
+
neighbor = tuple(current[axis] + offset[axis] for axis in range(background_mask.ndim))
|
|
283
|
+
if any(index < 0 or index >= background_mask.shape[axis] for axis, index in enumerate(neighbor)):
|
|
284
|
+
continue
|
|
285
|
+
if visited[neighbor] or not background_mask[neighbor]:
|
|
286
|
+
continue
|
|
287
|
+
visited[neighbor] = True
|
|
288
|
+
queue.append(neighbor)
|
|
289
|
+
|
|
290
|
+
hole_mask = background_mask & ~visited
|
|
291
|
+
if not np.any(hole_mask):
|
|
292
|
+
return segmented
|
|
293
|
+
filled = np.array(segmented, copy=True)
|
|
294
|
+
filled[hole_mask] = float(gray_levels[-1])
|
|
295
|
+
return filled
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _segment_dart_volume(
|
|
299
|
+
volume: np.ndarray,
|
|
300
|
+
gray_levels: np.ndarray,
|
|
301
|
+
params: DARTParameters,
|
|
302
|
+
) -> np.ndarray:
|
|
303
|
+
"""Segment a DART iterate and apply optional binary hole filling immediately."""
|
|
304
|
+
segmented = _segment_volume(
|
|
305
|
+
volume,
|
|
306
|
+
gray_levels,
|
|
307
|
+
threshold_method=params.segmentation_threshold_method,
|
|
308
|
+
threshold_value=params.segmentation_threshold_value,
|
|
309
|
+
otsu_foreground_only=params.otsu_foreground_only,
|
|
310
|
+
otsu_percentile_window=params.otsu_percentile_window,
|
|
311
|
+
)
|
|
312
|
+
if params.binary_fill_holes:
|
|
313
|
+
segmented = _fill_binary_holes(segmented, gray_levels)
|
|
314
|
+
return segmented
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def reconstruct_dart(
|
|
318
|
+
measured_projections: Sequence[ArrayLike],
|
|
319
|
+
forward_project: ForwardProjector,
|
|
320
|
+
back_project: BackProjector,
|
|
321
|
+
params: DARTParameters,
|
|
322
|
+
*,
|
|
323
|
+
show_progress: bool = True,
|
|
324
|
+
) -> mx.array:
|
|
325
|
+
"""Reconstruct a 2D or 3D discrete-valued image/volume with DART."""
|
|
326
|
+
gray_levels = _validate_dart_inputs(params, measured_projections)
|
|
327
|
+
measured = normalize_measured_projections(measured_projections, params.dtype)
|
|
328
|
+
volume, ones_volume, _ = initialize_volume(params)
|
|
329
|
+
|
|
330
|
+
initial_sweeps = params.initial_reconstruction_sweeps
|
|
331
|
+
if initial_sweeps is None:
|
|
332
|
+
initial_sweeps = params.sart_iteration_count
|
|
333
|
+
initial_params = replace(params, sart_iteration_count=initial_sweeps)
|
|
334
|
+
volume = run_iterative_sweeps(
|
|
335
|
+
volume=volume,
|
|
336
|
+
measured_projections=measured,
|
|
337
|
+
ones_volume=ones_volume,
|
|
338
|
+
forward_project=forward_project,
|
|
339
|
+
back_project=back_project,
|
|
340
|
+
params=initial_params,
|
|
341
|
+
outer_iteration_index=-1,
|
|
342
|
+
)
|
|
343
|
+
volume = clamp_reconstruction_volume(volume, params, stage="iteration")
|
|
344
|
+
|
|
345
|
+
rng = np.random.default_rng(int(params.random_seed))
|
|
346
|
+
for iteration in range(params.iteration_count):
|
|
347
|
+
volume_np = np.asarray(volume)
|
|
348
|
+
segmented = _segment_dart_volume(volume_np, gray_levels, params)
|
|
349
|
+
boundary_mask = _boundary_pixels(
|
|
350
|
+
segmented,
|
|
351
|
+
connectivity=params.boundary_connectivity,
|
|
352
|
+
)
|
|
353
|
+
free_pixel_mask = boundary_mask | _sample_free_pixels(
|
|
354
|
+
params.volume_shape,
|
|
355
|
+
params.free_pixel_probability,
|
|
356
|
+
rng,
|
|
357
|
+
)
|
|
358
|
+
|
|
359
|
+
# DART restarts each masked subproblem from the discrete segmentation.
|
|
360
|
+
updated_volume_np = np.array(segmented, copy=True)
|
|
361
|
+
updated_volume = mx.array(updated_volume_np, dtype=params.dtype)
|
|
362
|
+
|
|
363
|
+
fixed_volume_np = np.array(updated_volume_np, copy=True)
|
|
364
|
+
fixed_volume_np[free_pixel_mask] = 0.0
|
|
365
|
+
fixed_volume = mx.array(fixed_volume_np, dtype=params.dtype)
|
|
366
|
+
free_mask_volume = mx.array(free_pixel_mask.astype(np.float32), dtype=params.dtype)
|
|
367
|
+
|
|
368
|
+
fixed_projections = forward_project_views(
|
|
369
|
+
fixed_volume,
|
|
370
|
+
forward_project,
|
|
371
|
+
len(measured),
|
|
372
|
+
params,
|
|
373
|
+
)
|
|
374
|
+
free_measurements = [
|
|
375
|
+
measured_projection - fixed_projections[projection_index]
|
|
376
|
+
for projection_index, measured_projection in enumerate(measured)
|
|
377
|
+
]
|
|
378
|
+
|
|
379
|
+
def masked_forward_project(volume: mx.array, projection_index: int) -> mx.array:
|
|
380
|
+
masked_volume = volume * free_mask_volume
|
|
381
|
+
return forward_project(masked_volume, projection_index)
|
|
382
|
+
|
|
383
|
+
def masked_back_project(projection: mx.array, projection_index: int) -> mx.array:
|
|
384
|
+
backprojection = back_project(projection, projection_index)
|
|
385
|
+
return backprojection * free_mask_volume
|
|
386
|
+
|
|
387
|
+
volume = run_iterative_sweeps(
|
|
388
|
+
volume=updated_volume,
|
|
389
|
+
measured_projections=free_measurements,
|
|
390
|
+
ones_volume=ones_volume,
|
|
391
|
+
forward_project=masked_forward_project,
|
|
392
|
+
back_project=masked_back_project,
|
|
393
|
+
params=params,
|
|
394
|
+
outer_iteration_index=iteration,
|
|
395
|
+
)
|
|
396
|
+
if params.apply_smoothing and iteration < params.iteration_count - 1:
|
|
397
|
+
smoothed_volume = _smooth_boundary_voxels(
|
|
398
|
+
np.asarray(volume),
|
|
399
|
+
boundary_mask,
|
|
400
|
+
beta=float(params.smoothing_beta),
|
|
401
|
+
connectivity=params.boundary_connectivity,
|
|
402
|
+
)
|
|
403
|
+
volume = mx.array(smoothed_volume, dtype=params.dtype)
|
|
404
|
+
volume = clamp_reconstruction_volume(volume, params, stage="iteration")
|
|
405
|
+
converged = False
|
|
406
|
+
if params.convergence_epsilon is not None:
|
|
407
|
+
updated_segmented = _segment_dart_volume(np.asarray(volume), gray_levels, params)
|
|
408
|
+
changed_ratio = float(np.count_nonzero(segmented != updated_segmented)) / float(segmented.size)
|
|
409
|
+
converged = changed_ratio <= float(params.convergence_epsilon)
|
|
410
|
+
if show_progress:
|
|
411
|
+
print_progress(iteration, params.iteration_count)
|
|
412
|
+
if converged and iteration < params.iteration_count - 1:
|
|
413
|
+
print()
|
|
414
|
+
if converged:
|
|
415
|
+
break
|
|
416
|
+
|
|
417
|
+
volume = clamp_reconstruction_volume(volume, params, stage="final")
|
|
418
|
+
if params.return_segmented_volume:
|
|
419
|
+
segmented = _segment_dart_volume(np.asarray(volume), gray_levels, params)
|
|
420
|
+
return mx.array(segmented, dtype=params.dtype)
|
|
421
|
+
return volume
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
run_dart = reconstruct_dart
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Projector-agnostic filtered backprojection."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
import mlx.core as mx
|
|
8
|
+
|
|
9
|
+
from ._analytic import (
|
|
10
|
+
AnalyticalBackProjector,
|
|
11
|
+
AnalyticalFilter,
|
|
12
|
+
AnalyticalReconstructionParameters,
|
|
13
|
+
AnalyticalWeighting,
|
|
14
|
+
_as_array,
|
|
15
|
+
_positive_and_scale,
|
|
16
|
+
default_angular_normalization,
|
|
17
|
+
ramp_filter,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass
|
|
22
|
+
class FBPParameters(AnalyticalReconstructionParameters):
|
|
23
|
+
"""Parameters for projector-agnostic filtered backprojection."""
|
|
24
|
+
|
|
25
|
+
filter_axis: int = 1
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def reconstruct_fbp(
|
|
29
|
+
sinogram,
|
|
30
|
+
back_project: AnalyticalBackProjector,
|
|
31
|
+
params: FBPParameters,
|
|
32
|
+
*,
|
|
33
|
+
weight_projections: AnalyticalWeighting | None = None,
|
|
34
|
+
filter_projections: AnalyticalFilter | None = None,
|
|
35
|
+
):
|
|
36
|
+
"""Reconstruct with FBP using user-provided weighting/filtering/backprojection."""
|
|
37
|
+
sinogram = _as_array(sinogram, dtype=params.dtype)
|
|
38
|
+
if sinogram.ndim < 2:
|
|
39
|
+
raise ValueError(f"Expected sinogram with at least 2 dimensions, got shape {sinogram.shape!r}.")
|
|
40
|
+
|
|
41
|
+
weighted_sinogram = sinogram if weight_projections is None else _as_array(weight_projections(sinogram), dtype=params.dtype)
|
|
42
|
+
if weighted_sinogram.shape != sinogram.shape:
|
|
43
|
+
raise ValueError(
|
|
44
|
+
"weight_projections must preserve sinogram shape: "
|
|
45
|
+
f"expected {sinogram.shape!r}, got {weighted_sinogram.shape!r}."
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
if filter_projections is None:
|
|
49
|
+
filtered_sinogram = ramp_filter(weighted_sinogram, axis=params.filter_axis)
|
|
50
|
+
else:
|
|
51
|
+
filtered_sinogram = _as_array(filter_projections(weighted_sinogram), dtype=params.dtype)
|
|
52
|
+
if filtered_sinogram.shape != sinogram.shape:
|
|
53
|
+
raise ValueError(
|
|
54
|
+
"filter_projections must preserve sinogram shape: "
|
|
55
|
+
f"expected {sinogram.shape!r}, got {filtered_sinogram.shape!r}."
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
reconstruction = _as_array(back_project(filtered_sinogram), dtype=params.dtype)
|
|
59
|
+
normalization = params.normalization_scale
|
|
60
|
+
if normalization is None:
|
|
61
|
+
normalization = default_angular_normalization(sinogram.shape[0])
|
|
62
|
+
return _positive_and_scale(
|
|
63
|
+
reconstruction,
|
|
64
|
+
enforce_positivity=params.enforce_positivity,
|
|
65
|
+
normalization_scale=normalization,
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
run_fbp = reconstruct_fbp
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Projector-agnostic Feldkamp-Davis-Kress-style reconstruction."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
from ._analytic import (
|
|
8
|
+
AnalyticalBackProjector,
|
|
9
|
+
AnalyticalFilter,
|
|
10
|
+
AnalyticalReconstructionParameters,
|
|
11
|
+
AnalyticalWeighting,
|
|
12
|
+
_as_array,
|
|
13
|
+
_positive_and_scale,
|
|
14
|
+
default_angular_normalization,
|
|
15
|
+
ramp_filter,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class FDKParameters(AnalyticalReconstructionParameters):
|
|
21
|
+
"""Parameters for projector-agnostic FDK reconstruction."""
|
|
22
|
+
|
|
23
|
+
filter_axis: int = 1
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def reconstruct_fdk(
|
|
27
|
+
sinogram,
|
|
28
|
+
back_project: AnalyticalBackProjector,
|
|
29
|
+
params: FDKParameters,
|
|
30
|
+
*,
|
|
31
|
+
weight_projections: AnalyticalWeighting | None = None,
|
|
32
|
+
filter_projections: AnalyticalFilter | None = None,
|
|
33
|
+
):
|
|
34
|
+
"""Reconstruct with FDK using user-provided weighting/filtering/backprojection."""
|
|
35
|
+
sinogram = _as_array(sinogram, dtype=params.dtype)
|
|
36
|
+
if sinogram.ndim < 3:
|
|
37
|
+
raise ValueError(f"Expected cone-beam sinogram with at least 3 dimensions, got shape {sinogram.shape!r}.")
|
|
38
|
+
|
|
39
|
+
weighted_sinogram = sinogram if weight_projections is None else _as_array(weight_projections(sinogram), dtype=params.dtype)
|
|
40
|
+
if weighted_sinogram.shape != sinogram.shape:
|
|
41
|
+
raise ValueError(
|
|
42
|
+
"weight_projections must preserve sinogram shape: "
|
|
43
|
+
f"expected {sinogram.shape!r}, got {weighted_sinogram.shape!r}."
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
if filter_projections is None:
|
|
47
|
+
filtered_sinogram = ramp_filter(weighted_sinogram, axis=params.filter_axis)
|
|
48
|
+
else:
|
|
49
|
+
filtered_sinogram = _as_array(filter_projections(weighted_sinogram), dtype=params.dtype)
|
|
50
|
+
if filtered_sinogram.shape != sinogram.shape:
|
|
51
|
+
raise ValueError(
|
|
52
|
+
"filter_projections must preserve sinogram shape: "
|
|
53
|
+
f"expected {sinogram.shape!r}, got {filtered_sinogram.shape!r}."
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
reconstruction = _as_array(back_project(filtered_sinogram), dtype=params.dtype)
|
|
57
|
+
normalization = params.normalization_scale
|
|
58
|
+
if normalization is None:
|
|
59
|
+
normalization = default_angular_normalization(sinogram.shape[0])
|
|
60
|
+
return _positive_and_scale(
|
|
61
|
+
reconstruction,
|
|
62
|
+
enforce_positivity=params.enforce_positivity,
|
|
63
|
+
normalization_scale=normalization,
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
run_fdk = reconstruct_fdk
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Geometry-agnostic SART reconstruction."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Sequence
|
|
7
|
+
|
|
8
|
+
import mlx.core as mx
|
|
9
|
+
|
|
10
|
+
from ._core import (
|
|
11
|
+
ArrayLike,
|
|
12
|
+
BackProjector,
|
|
13
|
+
ForwardProjector,
|
|
14
|
+
ReconstructionParameters,
|
|
15
|
+
clamp_reconstruction_volume,
|
|
16
|
+
initialize_volume,
|
|
17
|
+
normalize_measured_projections,
|
|
18
|
+
print_progress,
|
|
19
|
+
run_iterative_sweeps,
|
|
20
|
+
validate_reconstruction_inputs,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class SARTParameters(ReconstructionParameters):
|
|
26
|
+
"""SART-specific configuration."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def reconstruct_sart(
|
|
30
|
+
measured_projections: Sequence[ArrayLike],
|
|
31
|
+
forward_project: ForwardProjector,
|
|
32
|
+
back_project: BackProjector,
|
|
33
|
+
params: SARTParameters,
|
|
34
|
+
*,
|
|
35
|
+
show_progress: bool = True,
|
|
36
|
+
) -> mx.array:
|
|
37
|
+
"""Reconstruct with SART using user-provided per-view operators."""
|
|
38
|
+
validate_reconstruction_inputs(params, measured_projections)
|
|
39
|
+
measured = normalize_measured_projections(measured_projections, params.dtype)
|
|
40
|
+
volume, ones_volume, _ = initialize_volume(params)
|
|
41
|
+
|
|
42
|
+
for iteration in range(params.iteration_count):
|
|
43
|
+
skip_first_sart = iteration == 0 and params.initial_volume is not None
|
|
44
|
+
if not skip_first_sart:
|
|
45
|
+
volume = run_iterative_sweeps(
|
|
46
|
+
volume=volume,
|
|
47
|
+
measured_projections=measured,
|
|
48
|
+
ones_volume=ones_volume,
|
|
49
|
+
forward_project=forward_project,
|
|
50
|
+
back_project=back_project,
|
|
51
|
+
params=params,
|
|
52
|
+
outer_iteration_index=iteration,
|
|
53
|
+
)
|
|
54
|
+
volume = clamp_reconstruction_volume(volume, params, stage="iteration")
|
|
55
|
+
# Force evaluation per outer iteration so long measured-data runs do not
|
|
56
|
+
# accumulate an unbounded lazy graph on Metal.
|
|
57
|
+
mx.eval(volume)
|
|
58
|
+
if show_progress:
|
|
59
|
+
print_progress(iteration, params.iteration_count)
|
|
60
|
+
|
|
61
|
+
volume = clamp_reconstruction_volume(volume, params, stage="final")
|
|
62
|
+
mx.eval(volume)
|
|
63
|
+
return volume
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
run_sart = reconstruct_sart
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Geometry-agnostic SIRT reconstruction."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Sequence
|
|
7
|
+
|
|
8
|
+
import mlx.core as mx
|
|
9
|
+
|
|
10
|
+
from ._core import (
|
|
11
|
+
ArrayLike,
|
|
12
|
+
BackProjector,
|
|
13
|
+
ForwardProjector,
|
|
14
|
+
ReconstructionParameters,
|
|
15
|
+
clamp_reconstruction_volume,
|
|
16
|
+
initialize_volume,
|
|
17
|
+
normalize_measured_projections,
|
|
18
|
+
print_progress,
|
|
19
|
+
run_sirt_sweeps,
|
|
20
|
+
validate_reconstruction_inputs,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class SIRTParameters(ReconstructionParameters):
|
|
26
|
+
"""SIRT-specific configuration."""
|
|
27
|
+
|
|
28
|
+
iterative_update_method: str = "sirt"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def reconstruct_sirt(
|
|
32
|
+
measured_projections: Sequence[ArrayLike],
|
|
33
|
+
forward_project: ForwardProjector,
|
|
34
|
+
back_project: BackProjector,
|
|
35
|
+
params: SIRTParameters,
|
|
36
|
+
*,
|
|
37
|
+
show_progress: bool = True,
|
|
38
|
+
) -> mx.array:
|
|
39
|
+
"""Reconstruct with SIRT using user-provided per-view operators."""
|
|
40
|
+
validate_reconstruction_inputs(params, measured_projections)
|
|
41
|
+
measured = normalize_measured_projections(measured_projections, params.dtype)
|
|
42
|
+
volume, ones_volume, _ = initialize_volume(params)
|
|
43
|
+
|
|
44
|
+
for iteration in range(params.iteration_count):
|
|
45
|
+
skip_first_sirt = iteration == 0 and params.initial_volume is not None
|
|
46
|
+
if not skip_first_sirt:
|
|
47
|
+
volume = run_sirt_sweeps(
|
|
48
|
+
volume=volume,
|
|
49
|
+
measured_projections=measured,
|
|
50
|
+
ones_volume=ones_volume,
|
|
51
|
+
forward_project=forward_project,
|
|
52
|
+
back_project=back_project,
|
|
53
|
+
params=params,
|
|
54
|
+
outer_iteration_index=iteration,
|
|
55
|
+
)
|
|
56
|
+
volume = clamp_reconstruction_volume(volume, params, stage="iteration")
|
|
57
|
+
if show_progress:
|
|
58
|
+
print_progress(iteration, params.iteration_count)
|
|
59
|
+
|
|
60
|
+
volume = clamp_reconstruction_volume(volume, params, stage="final")
|
|
61
|
+
return volume
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
run_sirt = reconstruct_sirt
|