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,85 @@
|
|
|
1
|
+
"""Geometry-agnostic TV-POCS 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 ..regularizers import tv_pocs as tv_pocs_step
|
|
11
|
+
from ._core import (
|
|
12
|
+
ArrayLike,
|
|
13
|
+
BackProjector,
|
|
14
|
+
ForwardProjector,
|
|
15
|
+
ReconstructionParameters,
|
|
16
|
+
RegularizationParameters,
|
|
17
|
+
clamp_reconstruction_volume,
|
|
18
|
+
initialize_volume,
|
|
19
|
+
normalize_measured_projections,
|
|
20
|
+
print_progress,
|
|
21
|
+
run_iterative_sweeps,
|
|
22
|
+
validate_reconstruction_inputs,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass
|
|
27
|
+
class TVPOCSParameters(RegularizationParameters):
|
|
28
|
+
"""TV-POCS regularization parameters."""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
TV_POCS_Parameter = TVPOCSParameters
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def reconstruct_tv_pocs(
|
|
35
|
+
measured_projections: Sequence[ArrayLike],
|
|
36
|
+
forward_project: ForwardProjector,
|
|
37
|
+
back_project: BackProjector,
|
|
38
|
+
reco_params: ReconstructionParameters,
|
|
39
|
+
reg_params: TVPOCSParameters,
|
|
40
|
+
*,
|
|
41
|
+
show_progress: bool = False,
|
|
42
|
+
) -> mx.array:
|
|
43
|
+
"""Reconstruct with TV-POCS using user-provided per-view operators."""
|
|
44
|
+
validate_reconstruction_inputs(reco_params, measured_projections)
|
|
45
|
+
measured = normalize_measured_projections(measured_projections, reco_params.dtype)
|
|
46
|
+
volume, ones_volume, zero_volume = initialize_volume(reco_params)
|
|
47
|
+
|
|
48
|
+
for iteration in range(reco_params.iteration_count):
|
|
49
|
+
skip_first_sart = iteration == 0 and reco_params.initial_volume is not None
|
|
50
|
+
iteration_reference = zero_volume if skip_first_sart else volume
|
|
51
|
+
|
|
52
|
+
if not skip_first_sart:
|
|
53
|
+
volume = run_iterative_sweeps(
|
|
54
|
+
volume=volume,
|
|
55
|
+
measured_projections=measured,
|
|
56
|
+
ones_volume=ones_volume,
|
|
57
|
+
forward_project=forward_project,
|
|
58
|
+
back_project=back_project,
|
|
59
|
+
params=reco_params,
|
|
60
|
+
outer_iteration_index=iteration,
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
volume = clamp_reconstruction_volume(volume, reco_params, stage="iteration")
|
|
64
|
+
|
|
65
|
+
if reg_params.reg_iteration_count > 0:
|
|
66
|
+
volume, _ = tv_pocs_step(
|
|
67
|
+
volume,
|
|
68
|
+
iteration_reference,
|
|
69
|
+
reg_params.reg_iteration_count,
|
|
70
|
+
reg_params.alpha,
|
|
71
|
+
eta=reg_params.tv_eps,
|
|
72
|
+
)
|
|
73
|
+
volume = clamp_reconstruction_volume(volume, reco_params, stage="regularization")
|
|
74
|
+
|
|
75
|
+
mx.eval(volume)
|
|
76
|
+
|
|
77
|
+
if show_progress:
|
|
78
|
+
print_progress(iteration, reco_params.iteration_count)
|
|
79
|
+
|
|
80
|
+
volume = clamp_reconstruction_volume(volume, reco_params, stage="final")
|
|
81
|
+
mx.eval(volume)
|
|
82
|
+
return volume
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
run_tv_pocs = reconstruct_tv_pocs
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""Regularizers and POCS regularization steps for iterative CT reconstruction."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import mlx.core as mx
|
|
6
|
+
import numpy as np
|
|
7
|
+
|
|
8
|
+
from .tv_gradients import awtv_gradient
|
|
9
|
+
from .tv_gradients import _awtv_objective as awtv_objective
|
|
10
|
+
from .tv_gradients import _tv_objective as tv_objective
|
|
11
|
+
from .tv_gradients import tv_gradient
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _as_array(volume):
|
|
15
|
+
"""Convert arbitrary array-like inputs to MLX arrays."""
|
|
16
|
+
return mx.array(volume)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _scalar_norm(value) -> float:
|
|
20
|
+
"""Return an MLX norm as a Python float."""
|
|
21
|
+
return float(np.asarray(mx.linalg.norm(value)))
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def l2_regularizer(volume):
|
|
25
|
+
"""Mean squared voxel magnitude."""
|
|
26
|
+
volume = _as_array(volume)
|
|
27
|
+
return mx.mean(mx.square(volume))
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def normalize_reconstruction_volume(volume, eps=1e-6):
|
|
31
|
+
"""Project a nonnegative reconstruction volume to a stable max-one scale."""
|
|
32
|
+
volume = mx.maximum(_as_array(volume), 0.0)
|
|
33
|
+
scale = mx.maximum(mx.max(volume), float(eps))
|
|
34
|
+
return volume / scale
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def tv_regularizer(volume, eps=1e-6):
|
|
38
|
+
"""Isotropic total variation over the shared interior of an N-D volume."""
|
|
39
|
+
return tv_objective(volume, eta=eps)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def tv_regularizer_3d(volume, eps=1e-6):
|
|
43
|
+
"""Backward-compatible alias for isotropic TV regularization."""
|
|
44
|
+
return tv_regularizer(volume, eps=eps)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def awtv_regularizer(volume, delta, eps=1e-6):
|
|
48
|
+
"""Adaptive-weighted TV regularizer over the shared interior of an N-D volume."""
|
|
49
|
+
return awtv_objective(volume, delta=delta, eta=eps)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def tv_pocs(volume, backup_volume, reg_iteration_count, alpha, eta=1e-6):
|
|
53
|
+
"""Regularization step of TV-POCS."""
|
|
54
|
+
volume = _as_array(volume)
|
|
55
|
+
backup_volume = _as_array(backup_volume)
|
|
56
|
+
dp = _scalar_norm(volume - backup_volume)
|
|
57
|
+
|
|
58
|
+
for _ in range(int(reg_iteration_count)):
|
|
59
|
+
gradient_volume = tv_gradient(volume, eta=eta)
|
|
60
|
+
norm = _scalar_norm(gradient_volume)
|
|
61
|
+
if norm > 0.0:
|
|
62
|
+
gradient_volume = gradient_volume / norm
|
|
63
|
+
volume = volume - float(alpha) * dp * gradient_volume
|
|
64
|
+
|
|
65
|
+
backup_volume = volume
|
|
66
|
+
return volume, backup_volume
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def asd_pocs(
|
|
70
|
+
volume,
|
|
71
|
+
backup_volume,
|
|
72
|
+
iteration_index,
|
|
73
|
+
reg_iteration_count,
|
|
74
|
+
dd,
|
|
75
|
+
dtvg,
|
|
76
|
+
alpha,
|
|
77
|
+
alpha_red,
|
|
78
|
+
r_max,
|
|
79
|
+
epsilon,
|
|
80
|
+
eta=1e-6,
|
|
81
|
+
):
|
|
82
|
+
"""Regularization step of ASD-POCS."""
|
|
83
|
+
volume = _as_array(volume)
|
|
84
|
+
backup_volume = _as_array(backup_volume)
|
|
85
|
+
|
|
86
|
+
dp = _scalar_norm(volume - backup_volume)
|
|
87
|
+
if int(iteration_index) == 0:
|
|
88
|
+
dtvg = float(alpha) * dp
|
|
89
|
+
|
|
90
|
+
backup_volume = volume
|
|
91
|
+
|
|
92
|
+
for _ in range(int(reg_iteration_count)):
|
|
93
|
+
gradient_volume = tv_gradient(volume, eta=eta)
|
|
94
|
+
norm = _scalar_norm(gradient_volume)
|
|
95
|
+
if norm > 0.0:
|
|
96
|
+
gradient_volume = gradient_volume / norm
|
|
97
|
+
volume = volume - float(dtvg) * gradient_volume
|
|
98
|
+
|
|
99
|
+
dg = _scalar_norm(volume - backup_volume)
|
|
100
|
+
if dg > float(r_max) * dp and float(dd) > float(epsilon):
|
|
101
|
+
dtvg = float(dtvg) * float(alpha_red)
|
|
102
|
+
|
|
103
|
+
backup_volume = volume
|
|
104
|
+
return volume, backup_volume, float(dtvg)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def awtv_pocs(volume, backup_volume, reg_iteration_count, alpha, delta, eta=1e-6):
|
|
108
|
+
"""Regularization step of AwTV-POCS."""
|
|
109
|
+
volume = _as_array(volume)
|
|
110
|
+
backup_volume = _as_array(backup_volume)
|
|
111
|
+
dp = _scalar_norm(volume - backup_volume)
|
|
112
|
+
|
|
113
|
+
for _ in range(int(reg_iteration_count)):
|
|
114
|
+
gradient_volume = awtv_gradient(volume, delta=delta, eta=eta)
|
|
115
|
+
norm = _scalar_norm(gradient_volume)
|
|
116
|
+
if norm > 0.0:
|
|
117
|
+
gradient_volume = gradient_volume / norm
|
|
118
|
+
volume = volume - dp * float(alpha) * gradient_volume
|
|
119
|
+
|
|
120
|
+
backup_volume = volume
|
|
121
|
+
alpha = float(alpha) * 0.995
|
|
122
|
+
return volume, backup_volume, alpha
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""TV and AwTV gradient helpers for iterative CT reconstruction."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import mlx.core as mx
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _as_array(volume):
|
|
9
|
+
"""Convert arbitrary array-like inputs to MLX arrays."""
|
|
10
|
+
return mx.array(volume)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _tv_objective(volume, eta=1e-6):
|
|
14
|
+
"""Isotropic TV objective over the shared interior of an N-D array."""
|
|
15
|
+
volume = _as_array(volume)
|
|
16
|
+
if any(int(dim) < 2 for dim in volume.shape):
|
|
17
|
+
return mx.array(0.0, dtype=volume.dtype)
|
|
18
|
+
|
|
19
|
+
anchor = [slice(0, -1)] * volume.ndim
|
|
20
|
+
diffs = []
|
|
21
|
+
for axis in range(volume.ndim):
|
|
22
|
+
shifted = list(anchor)
|
|
23
|
+
shifted[axis] = slice(1, None)
|
|
24
|
+
diffs.append(volume[tuple(shifted)] - volume[tuple(anchor)])
|
|
25
|
+
|
|
26
|
+
sq_mag = diffs[0] * diffs[0]
|
|
27
|
+
for diff in diffs[1:]:
|
|
28
|
+
sq_mag = sq_mag + diff * diff
|
|
29
|
+
return mx.mean(mx.sqrt(sq_mag + float(eta)))
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def weight_d_volume(d_volume, delta):
|
|
33
|
+
"""Compute the AwTV diffusion weighting for a finite-difference field."""
|
|
34
|
+
if delta <= 0.0:
|
|
35
|
+
raise ValueError("delta must be positive.")
|
|
36
|
+
d_volume = _as_array(d_volume)
|
|
37
|
+
scaled = d_volume / float(delta)
|
|
38
|
+
return mx.exp(-(scaled * scaled)) * d_volume
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _awtv_objective(volume, delta, eta=1e-6):
|
|
42
|
+
"""Adaptive-weighted TV objective over the shared interior of an N-D array."""
|
|
43
|
+
if delta <= 0.0:
|
|
44
|
+
raise ValueError("delta must be positive.")
|
|
45
|
+
|
|
46
|
+
volume = _as_array(volume)
|
|
47
|
+
if any(int(dim) < 2 for dim in volume.shape):
|
|
48
|
+
return mx.array(0.0, dtype=volume.dtype)
|
|
49
|
+
|
|
50
|
+
anchor = [slice(0, -1)] * volume.ndim
|
|
51
|
+
diffs = []
|
|
52
|
+
for axis in range(volume.ndim):
|
|
53
|
+
shifted = list(anchor)
|
|
54
|
+
shifted[axis] = slice(1, None)
|
|
55
|
+
diffs.append(volume[tuple(shifted)] - volume[tuple(anchor)])
|
|
56
|
+
|
|
57
|
+
weighted_diffs = [weight_d_volume(diff, delta) for diff in diffs]
|
|
58
|
+
sq_mag = diffs[0] * weighted_diffs[0]
|
|
59
|
+
for diff, weighted_diff in zip(diffs[1:], weighted_diffs[1:]):
|
|
60
|
+
sq_mag = sq_mag + diff * weighted_diff
|
|
61
|
+
|
|
62
|
+
return mx.mean(mx.sqrt(sq_mag + float(eta)))
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def tv_gradient(volume, eta=1e-6):
|
|
66
|
+
"""Gradient of the isotropic TV objective."""
|
|
67
|
+
volume = _as_array(volume)
|
|
68
|
+
return mx.grad(lambda x: _tv_objective(x, eta=eta))(volume)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def awtv_gradient(volume, delta, eta=1e-6):
|
|
72
|
+
"""Gradient of the adaptive-weighted TV objective."""
|
|
73
|
+
volume = _as_array(volume)
|
|
74
|
+
return mx.grad(lambda x: _awtv_objective(x, delta=delta, eta=eta))(volume)
|
diffct_mlx/utils.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Utility functions for DiffCT-MLX package.
|
|
2
|
+
|
|
3
|
+
This module provides helper functions for grid computation
|
|
4
|
+
and memory layout validation for the MLX-based CT reconstruction.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import math
|
|
8
|
+
from .constants import _TG_2D, _TG_3D
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _grid_2d(n1, n2):
|
|
12
|
+
"""Compute Metal grid and threadgroup sizes for 2D kernels.
|
|
13
|
+
|
|
14
|
+
Parameters
|
|
15
|
+
----------
|
|
16
|
+
n1 : int
|
|
17
|
+
First dimension size (e.g., number of views/angles).
|
|
18
|
+
n2 : int
|
|
19
|
+
Second dimension size (e.g., number of detectors).
|
|
20
|
+
|
|
21
|
+
Returns
|
|
22
|
+
-------
|
|
23
|
+
grid : tuple of int
|
|
24
|
+
Metal grid dimensions (total threads in each dimension).
|
|
25
|
+
threadgroup : tuple of int
|
|
26
|
+
Metal threadgroup dimensions.
|
|
27
|
+
"""
|
|
28
|
+
tg = _TG_2D
|
|
29
|
+
grid = (
|
|
30
|
+
math.ceil(n1 / tg[0]) * tg[0],
|
|
31
|
+
math.ceil(n2 / tg[1]) * tg[1],
|
|
32
|
+
1,
|
|
33
|
+
)
|
|
34
|
+
threadgroup = (tg[0], tg[1], 1)
|
|
35
|
+
return grid, threadgroup
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _grid_3d(n1, n2, n3):
|
|
39
|
+
"""Compute Metal grid and threadgroup sizes for 3D kernels.
|
|
40
|
+
|
|
41
|
+
Parameters
|
|
42
|
+
----------
|
|
43
|
+
n1 : int
|
|
44
|
+
First dimension size (e.g., number of views).
|
|
45
|
+
n2 : int
|
|
46
|
+
Second dimension size (e.g., number of u-detectors).
|
|
47
|
+
n3 : int
|
|
48
|
+
Third dimension size (e.g., number of v-detectors).
|
|
49
|
+
|
|
50
|
+
Returns
|
|
51
|
+
-------
|
|
52
|
+
grid : tuple of int
|
|
53
|
+
Metal grid dimensions (total threads in each dimension).
|
|
54
|
+
threadgroup : tuple of int
|
|
55
|
+
Metal threadgroup dimensions.
|
|
56
|
+
"""
|
|
57
|
+
tg = _TG_3D
|
|
58
|
+
grid = (
|
|
59
|
+
math.ceil(n1 / tg[0]) * tg[0],
|
|
60
|
+
math.ceil(n2 / tg[1]) * tg[1],
|
|
61
|
+
math.ceil(n3 / tg[2]) * tg[2],
|
|
62
|
+
)
|
|
63
|
+
threadgroup = (tg[0], tg[1], tg[2])
|
|
64
|
+
return grid, threadgroup
|
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: diffct_mlx
|
|
3
|
+
Version: 1.0.1
|
|
4
|
+
Summary: Differentiable CT reconstruction for Apple Silicon using MLX and custom Metal kernels
|
|
5
|
+
Project-URL: Homepage, https://github.com/Linda-SophieSchneider/diffct_arbit
|
|
6
|
+
Project-URL: Repository, https://github.com/Linda-SophieSchneider/diffct_arbit
|
|
7
|
+
Project-URL: Issues, https://github.com/Linda-SophieSchneider/diffct_arbit/issues
|
|
8
|
+
Author: Linda-Sophie Schneider
|
|
9
|
+
Author-email: Yipeng Sun <yipeng.sun@fau.de>
|
|
10
|
+
License-Expression: Apache-2.0
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: apple silicon,computed tomography,ct,metal,mlx,reconstruction
|
|
13
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
14
|
+
Classifier: Operating System :: MacOS
|
|
15
|
+
Classifier: Operating System :: MacOS :: MacOS X
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
|
|
21
|
+
Requires-Python: >=3.10
|
|
22
|
+
Requires-Dist: mlx>=0.20.0
|
|
23
|
+
Requires-Dist: numpy
|
|
24
|
+
Provides-Extra: dev
|
|
25
|
+
Requires-Dist: build; extra == 'dev'
|
|
26
|
+
Requires-Dist: matplotlib; extra == 'dev'
|
|
27
|
+
Requires-Dist: pytest; extra == 'dev'
|
|
28
|
+
Requires-Dist: twine; extra == 'dev'
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
|
|
31
|
+
# diffct_mlx: Differentiable CT for Apple Silicon
|
|
32
|
+
|
|
33
|
+
[](https://opensource.org/licenses/Apache-2.0)
|
|
34
|
+
[](https://doi.org/10.5281/zenodo.14999333)
|
|
35
|
+
|
|
36
|
+
A high-performance, differentiable computed tomography (CT) reconstruction library built with [MLX](https://github.com/ml-explore/mlx) and custom Metal kernels, optimized for Apple Silicon (M-series) chips.
|
|
37
|
+
|
|
38
|
+
This is the Apple Silicon port of [diffct](https://github.com/sypsyp97/diffct), replacing CUDA/PyTorch with MLX/Metal for native M-series GPU acceleration.
|
|
39
|
+
|
|
40
|
+
## Features
|
|
41
|
+
|
|
42
|
+
- **Apple Silicon Native:** Custom Metal kernels via `mx.fast.metal_kernel` — no CUDA required
|
|
43
|
+
- **Differentiable:** End-to-end gradient propagation using `mx.custom_function` with custom VJPs
|
|
44
|
+
- **Siddon Ray-Tracing:** Bilinear (2D) and trilinear (3D) interpolation for accurate projection
|
|
45
|
+
- **Atomic Backprojection:** Thread-safe gradient accumulation using Metal atomic operations
|
|
46
|
+
|
|
47
|
+
## Supported Geometries
|
|
48
|
+
|
|
49
|
+
| Geometry | Forward | Backward | Differentiable |
|
|
50
|
+
|----------|---------|----------|----------------|
|
|
51
|
+
| 2D Parallel Beam | ✅ | ✅ | ✅ |
|
|
52
|
+
| 2D Fan Beam | ✅ | ✅ | ✅ |
|
|
53
|
+
| 3D Cone Beam | ✅ | ✅ | ✅ |
|
|
54
|
+
|
|
55
|
+
## Trajectory Generators
|
|
56
|
+
|
|
57
|
+
- **Circular** — standard single-rotation scan
|
|
58
|
+
- **Spiral / Helical** — helical CT with z-axis translation (3D)
|
|
59
|
+
- **Sinusoidal** — variable source-to-isocenter distance
|
|
60
|
+
- **Saddle** — combined z-oscillation and radial variation (3D)
|
|
61
|
+
- **Random** — perturbed circular with configurable noise (3D)
|
|
62
|
+
- **Custom** — user-defined source path functions
|
|
63
|
+
|
|
64
|
+
## Quick Start
|
|
65
|
+
|
|
66
|
+
### Prerequisites
|
|
67
|
+
|
|
68
|
+
- Apple Silicon Mac (M1/M2/M3/M4 series)
|
|
69
|
+
- Python 3.10+
|
|
70
|
+
- macOS 13.5+
|
|
71
|
+
|
|
72
|
+
### Installation from PyPI
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
pip install diffct_mlx
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
### Installation from Source
|
|
79
|
+
|
|
80
|
+
```bash
|
|
81
|
+
# Clone the repository
|
|
82
|
+
git clone https://github.com/Linda-SophieSchneider/diffct_arbit.git
|
|
83
|
+
cd diffct_arbit
|
|
84
|
+
|
|
85
|
+
# Create and activate conda environment
|
|
86
|
+
conda create -n diffct-mlx python=3.11
|
|
87
|
+
conda activate diffct-mlx
|
|
88
|
+
|
|
89
|
+
# Install MLX and dependencies
|
|
90
|
+
pip install mlx numpy matplotlib
|
|
91
|
+
|
|
92
|
+
# Install diffct_mlx
|
|
93
|
+
pip install -e .
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
### Build a Release Distribution
|
|
97
|
+
|
|
98
|
+
```bash
|
|
99
|
+
python -m pip install --upgrade build twine
|
|
100
|
+
python -m build
|
|
101
|
+
python -m twine check dist/*
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
This creates both a source distribution and a wheel in `dist/`.
|
|
105
|
+
|
|
106
|
+
### Publish to TestPyPI or PyPI
|
|
107
|
+
|
|
108
|
+
```bash
|
|
109
|
+
# TestPyPI
|
|
110
|
+
python -m twine upload --repository testpypi dist/*
|
|
111
|
+
|
|
112
|
+
# PyPI
|
|
113
|
+
python -m twine upload dist/*
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
For publishing from your machine, create an API token on PyPI and use it as the
|
|
117
|
+
password with the username `__token__`.
|
|
118
|
+
|
|
119
|
+
If you publish through GitHub Actions, prefer PyPI Trusted Publishing instead of
|
|
120
|
+
storing a long-lived API token.
|
|
121
|
+
|
|
122
|
+
The repository release workflow is documented in [RELEASING.md](RELEASING.md).
|
|
123
|
+
|
|
124
|
+
### Basic Usage
|
|
125
|
+
|
|
126
|
+
```python
|
|
127
|
+
import mlx.core as mx
|
|
128
|
+
import diffct_mlx
|
|
129
|
+
|
|
130
|
+
# Create a 64x64 test image
|
|
131
|
+
image = mx.ones((64, 64), dtype=mx.float32)
|
|
132
|
+
|
|
133
|
+
# Generate parallel beam geometry (90 views)
|
|
134
|
+
ray_dir, det_origin, det_u_vec = diffct_mlx.circular_trajectory_2d_parallel(90)
|
|
135
|
+
|
|
136
|
+
# Forward projection → sinogram
|
|
137
|
+
sino = diffct_mlx.parallel_forward(
|
|
138
|
+
image, ray_dir, det_origin, det_u_vec,
|
|
139
|
+
num_detectors=92, detector_spacing=1.0, voxel_spacing=1.0
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
# Backprojection → reconstruction
|
|
143
|
+
reco = diffct_mlx.parallel_backward(
|
|
144
|
+
sino, ray_dir, det_origin, det_u_vec,
|
|
145
|
+
H=64, W=64, detector_spacing=1.0, voxel_spacing=1.0
|
|
146
|
+
)
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
### Gradient Computation
|
|
150
|
+
|
|
151
|
+
Since all projectors are differentiable, you can compute gradients directly:
|
|
152
|
+
|
|
153
|
+
```python
|
|
154
|
+
import mlx.core as mx
|
|
155
|
+
import diffct_mlx
|
|
156
|
+
|
|
157
|
+
def loss_fn(image):
|
|
158
|
+
ray_dir, det_origin, det_u_vec = diffct_mlx.circular_trajectory_2d_parallel(90)
|
|
159
|
+
sino = diffct_mlx.parallel_forward(image, ray_dir, det_origin, det_u_vec, 92)
|
|
160
|
+
return mx.sum(sino ** 2)
|
|
161
|
+
|
|
162
|
+
image = mx.ones((64, 64), dtype=mx.float32)
|
|
163
|
+
grad_fn = mx.grad(loss_fn)
|
|
164
|
+
gradient = grad_fn(image)
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
### 3D Cone Beam Example
|
|
168
|
+
|
|
169
|
+
```python
|
|
170
|
+
import mlx.core as mx
|
|
171
|
+
import diffct_mlx
|
|
172
|
+
|
|
173
|
+
# Create a 32x64x64 volume (D, H, W)
|
|
174
|
+
volume = mx.ones((32, 64, 64), dtype=mx.float32)
|
|
175
|
+
|
|
176
|
+
# Generate cone beam geometry
|
|
177
|
+
src, det_c, det_u, det_v = diffct_mlx.circular_trajectory_3d(
|
|
178
|
+
n_views=60, sid=500.0, sdd=1000.0
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
# Forward projection
|
|
182
|
+
sino = diffct_mlx.cone_forward(
|
|
183
|
+
volume, src, det_c, det_u, det_v,
|
|
184
|
+
det_u=64, det_v=32, du=1.0, dv=1.0, voxel_spacing=1.0
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
# Backprojection
|
|
188
|
+
reco = diffct_mlx.cone_backward(
|
|
189
|
+
sino, src, det_c, det_u, det_v,
|
|
190
|
+
D=32, H=64, W=64, du=1.0, dv=1.0, voxel_spacing=1.0
|
|
191
|
+
)
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
## API Reference
|
|
195
|
+
|
|
196
|
+
### Projectors
|
|
197
|
+
|
|
198
|
+
| Function | Description |
|
|
199
|
+
|----------|-------------|
|
|
200
|
+
| `parallel_forward(image, ray_dir, det_origin, det_u_vec, ...)` | 2D parallel beam forward projection |
|
|
201
|
+
| `parallel_backward(sinogram, ray_dir, det_origin, det_u_vec, ...)` | 2D parallel beam backprojection |
|
|
202
|
+
| `fan_forward(image, src_pos, det_center, det_u_vec, ...)` | 2D fan beam forward projection |
|
|
203
|
+
| `fan_backward(sinogram, src_pos, det_center, det_u_vec, ...)` | 2D fan beam backprojection |
|
|
204
|
+
| `cone_forward(volume, src_pos, det_center, det_u_vec, det_v_vec, ...)` | 3D cone beam forward projection |
|
|
205
|
+
| `cone_backward(sinogram, src_pos, det_center, det_u_vec, det_v_vec, ...)` | 3D cone beam backprojection |
|
|
206
|
+
|
|
207
|
+
### Iterative Reconstruction Algorithms
|
|
208
|
+
|
|
209
|
+
The package now also exposes callback-based iterative reconstruction algorithms
|
|
210
|
+
that are independent of geometry and dimensionality:
|
|
211
|
+
|
|
212
|
+
| Function | Description |
|
|
213
|
+
|----------|-------------|
|
|
214
|
+
| `run_sart(...)` | SART with user-provided single-view forward/backprojectors |
|
|
215
|
+
| `run_tv_pocs(...)` | TV-POCS using the same projector callback pattern |
|
|
216
|
+
| `run_asd_pocs(...)` | ASD-POCS with adaptive TV step-size damping |
|
|
217
|
+
| `run_awtv_pocs(...)` | AwTV-POCS with edge-adaptive weighted TV regularization |
|
|
218
|
+
|
|
219
|
+
Each algorithm takes:
|
|
220
|
+
|
|
221
|
+
- `measured_projections`: a list/sequence of per-view projections
|
|
222
|
+
- `forward_project(volume, projection_index)`: user callback for one view
|
|
223
|
+
- `back_project(projection, projection_index)`: user callback for one view
|
|
224
|
+
- `ReconstructionParameters`: shared reconstruction settings
|
|
225
|
+
- an algorithm-specific regularization dataclass where applicable
|
|
226
|
+
|
|
227
|
+
This keeps the algorithms reusable across parallel, fan, cone, 2D, and 3D
|
|
228
|
+
setups as long as the caller provides the appropriate single-view projector
|
|
229
|
+
wrappers.
|
|
230
|
+
|
|
231
|
+
### Trajectory Generators
|
|
232
|
+
|
|
233
|
+
| Function | Geometry |
|
|
234
|
+
|----------|----------|
|
|
235
|
+
| `circular_trajectory_2d_parallel(n_views, ...)` | 2D parallel |
|
|
236
|
+
| `sinusoidal_trajectory_2d_parallel(n_views, ...)` | 2D parallel |
|
|
237
|
+
| `custom_trajectory_2d_parallel(n_views, ...)` | 2D parallel |
|
|
238
|
+
| `circular_trajectory_2d_fan(n_views, sid, sdd, ...)` | 2D fan |
|
|
239
|
+
| `sinusoidal_trajectory_2d_fan(n_views, sid, sdd, ...)` | 2D fan |
|
|
240
|
+
| `custom_trajectory_2d_fan(n_views, sid, sdd, ...)` | 2D fan |
|
|
241
|
+
| `circular_trajectory_3d(n_views, sid, sdd, ...)` | 3D cone |
|
|
242
|
+
| `spiral_trajectory_3d(n_views, sid, sdd, ...)` | 3D cone |
|
|
243
|
+
| `sinusoidal_trajectory_3d(n_views, sid, sdd, ...)` | 3D cone |
|
|
244
|
+
| `saddle_trajectory_3d(n_views, sid, sdd, ...)` | 3D cone |
|
|
245
|
+
| `random_trajectory_3d(n_views, sid_mean, sdd_mean, ...)` | 3D cone |
|
|
246
|
+
| `custom_trajectory_3d(n_views, sid, sdd, ...)` | 3D cone |
|
|
247
|
+
|
|
248
|
+
## Examples
|
|
249
|
+
|
|
250
|
+
Ready-to-run scripts are provided in the `examples/` directory:
|
|
251
|
+
|
|
252
|
+
### Circular Trajectory (Analytical Reconstruction)
|
|
253
|
+
|
|
254
|
+
| Script | Description |
|
|
255
|
+
|--------|-------------|
|
|
256
|
+
| `examples/circular_trajectory/fbp_parallel.py` | FBP with ramp filter — 2D parallel beam |
|
|
257
|
+
| `examples/circular_trajectory/fbp_fan.py` | FBP with cosine weighting + ramp filter — 2D fan beam |
|
|
258
|
+
| `examples/circular_trajectory/fdk_cone.py` | FDK with distance weighting + ramp filter — 3D cone beam |
|
|
259
|
+
|
|
260
|
+
### Non-Circular Trajectory (Iterative Reconstruction)
|
|
261
|
+
|
|
262
|
+
| Script | Description |
|
|
263
|
+
|--------|-------------|
|
|
264
|
+
| `examples/non_circular_trajectory/iterative_reco_parallel.py` | Gradient-based iterative reco — sinusoidal & custom wobble trajectories |
|
|
265
|
+
| `examples/non_circular_trajectory/iterative_reco_fan.py` | Gradient-based iterative reco — sinusoidal & custom elliptical trajectories |
|
|
266
|
+
| `examples/non_circular_trajectory/iterative_reco_cone.py` | Gradient-based iterative reco — spiral, sinusoidal, saddle & figure-8 trajectories |
|
|
267
|
+
|
|
268
|
+
Run any example with:
|
|
269
|
+
|
|
270
|
+
```bash
|
|
271
|
+
conda activate diffct-mlx
|
|
272
|
+
python examples/circular_trajectory/fbp_parallel.py
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
## Package Structure
|
|
276
|
+
|
|
277
|
+
```
|
|
278
|
+
diffct_mlx/
|
|
279
|
+
├── __init__.py # Public API exports
|
|
280
|
+
├── constants.py # MLX-specific constants and dtypes
|
|
281
|
+
├── utils.py # Grid computation utilities
|
|
282
|
+
├── geometry.py # Trajectory generation functions
|
|
283
|
+
├── projectors.py # Differentiable projector functions with VJPs
|
|
284
|
+
└── kernels/
|
|
285
|
+
├── __init__.py
|
|
286
|
+
├── parallel_beam.py # Metal kernels for 2D parallel beam
|
|
287
|
+
├── fan_beam.py # Metal kernels for 2D fan beam
|
|
288
|
+
└── cone_beam.py # Metal kernels for 3D cone beam
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
## Citation
|
|
292
|
+
|
|
293
|
+
If you use this library in your research, please cite:
|
|
294
|
+
|
|
295
|
+
```bibtex
|
|
296
|
+
@software{diffct2026,
|
|
297
|
+
author = {Yipeng Sun, Linda-Sophie Schneider},
|
|
298
|
+
title = {diffct_mlx: Differentiable CT for Apple Silicon},
|
|
299
|
+
year = 2026,
|
|
300
|
+
}
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
## License
|
|
304
|
+
|
|
305
|
+
This project is licensed under the Apache 2.0 License — see the [LICENSE](LICENSE) file for details.
|
|
306
|
+
|
|
307
|
+
## Acknowledgements
|
|
308
|
+
|
|
309
|
+
This project was highly inspired by:
|
|
310
|
+
|
|
311
|
+
- [PYRO-NN](https://github.com/csyben/PYRO-NN)
|
|
312
|
+
- [geometry_gradients_CT](https://github.com/mareikethies/geometry_gradients_CT)
|
|
313
|
+
- [MLX](https://github.com/ml-explore/mlx) by Apple
|
|
314
|
+
|
|
315
|
+
Issues and contributions are welcome!
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
diffct_mlx/__about__.py,sha256=GfWooOmE74QxN6dVtsKDEoJghHwht9eW8W2lSTBTajc,62
|
|
2
|
+
diffct_mlx/__init__.py,sha256=MOhwPfwcAO51zDccM52KWW_KajDTH_5DwXwAiMD-5nc,5685
|
|
3
|
+
diffct_mlx/constants.py,sha256=o8Q-RTyfq9lnX335K-N-ROmYISG1J2JgWNARVE4zHso,1444
|
|
4
|
+
diffct_mlx/geometry.py,sha256=lVXK7PKXvTQVppwX9lpCHo3BOIg15zK9xzkGfiTo1ZA,26945
|
|
5
|
+
diffct_mlx/projectors.py,sha256=X8c6iZoktH4Wq1CuHp4ot6PIMGe2Ba8HQOnH2TsNk3Y,32358
|
|
6
|
+
diffct_mlx/real_measured_data_helper.py,sha256=Jg_MHxDqxfHXHYcjSBxjAcaKGypNxMvsGxq8S8lsOv8,20905
|
|
7
|
+
diffct_mlx/regularizers.py,sha256=uyF19ZjJD_u2lI9PQ_utspE2m4jECVbNfI961WigpC4,3698
|
|
8
|
+
diffct_mlx/tv_gradients.py,sha256=ak4GdxMOerFHpOXeH_A2IcPrhDyYvlaLPaCryAoLJOw,2419
|
|
9
|
+
diffct_mlx/utils.py,sha256=5QHUR1aB0cZEIKMp5Owh5Np8jMdQAlqLH_88R_DoRHk,1620
|
|
10
|
+
diffct_mlx/kernels/__init__.py,sha256=g8W8ne9VpnaRJmu5ZNpr4Wdi6LEcpwmsIHB3hA-PtPM,1131
|
|
11
|
+
diffct_mlx/kernels/cone_beam.py,sha256=4yBEpd_aGuZr91PqZgcVgshwoMh9nfiJZl1Xnl1q4nU,27961
|
|
12
|
+
diffct_mlx/kernels/fan_beam.py,sha256=2-VzIdjmsNvxzW5JlefFvgtN58iVNtMwFQVfQeWKzAg,18346
|
|
13
|
+
diffct_mlx/kernels/parallel_beam.py,sha256=vA8jyabpne0NWIbPWzB9Sm8FdnCziF1NSVPQv0j922k,16068
|
|
14
|
+
diffct_mlx/phantoms/__init__.py,sha256=HU4l0ghQ2l2DKVLk-eOsU0qi228VuXmGg_qrh-6stes,140
|
|
15
|
+
diffct_mlx/phantoms/shepp_logan.py,sha256=OoLgdfVnQnKSyTJk9W8XLIsBmmtMYuJ1u35KK4RQFzg,4365
|
|
16
|
+
diffct_mlx/reconstruction_algorithms/__init__.py,sha256=N_Vtz4TVW9unNNTOog2koW5odmKhaig2MJ2se3HW6GQ,2483
|
|
17
|
+
diffct_mlx/reconstruction_algorithms/_analytic.py,sha256=o9jKpkjSp1czJ0JY-Y19uWjKKddWwnZdX5Ig8OPpaIk,3648
|
|
18
|
+
diffct_mlx/reconstruction_algorithms/_core.py,sha256=AqWz8Axv1P1o3819Wlk6vGvvGMx4vQzzyrLHVkU8Shg,35773
|
|
19
|
+
diffct_mlx/reconstruction_algorithms/asd_pocs.py,sha256=GpjvV6e55GOVWkG3TzEChWJG9agveoan26aAuKRLf2E,3463
|
|
20
|
+
diffct_mlx/reconstruction_algorithms/awtv_pocs.py,sha256=6tLDftcKGcOg7zp638QQGpLl6LjlGTHMNSWwlAnA5cw,3411
|
|
21
|
+
diffct_mlx/reconstruction_algorithms/cases.py,sha256=6QiqF66IP-6Me_PePKhaXPuvFTfFjyORDH_7W5x3IGc,36627
|
|
22
|
+
diffct_mlx/reconstruction_algorithms/dart.py,sha256=-m_Dte0cZYsxd--iFge8v81TKWcBr7-y3TTdzJnAYiE,16912
|
|
23
|
+
diffct_mlx/reconstruction_algorithms/fbp.py,sha256=lng7w8t9kQHAn1fX5iTC-Eh4ZSDkmqNoSQ5wGYLJxw4,2282
|
|
24
|
+
diffct_mlx/reconstruction_algorithms/fdk.py,sha256=FokA8BikZ-r6rr_1qB1-8EW54kY-pURxkTmVrc0cb6I,2282
|
|
25
|
+
diffct_mlx/reconstruction_algorithms/sart.py,sha256=_CGxG5g3C5nnPVQ7pNAXu66UuiDTHHP7OnzJJfnrtOU,2031
|
|
26
|
+
diffct_mlx/reconstruction_algorithms/sirt.py,sha256=_qakyRu1AJ_5t_tMQtkL9oWWEtUXuqjbiqUvCrTwP84,1884
|
|
27
|
+
diffct_mlx/reconstruction_algorithms/tv_pocs.py,sha256=qvi6g8EyyjPa5HflmI46GN-GbXFo3Wbl9S5J8BHm7nI,2596
|
|
28
|
+
diffct_mlx-1.0.1.dist-info/METADATA,sha256=jzehJF5_z2QMf14i8ygJhZjFkAy8b1I31_7Vc1cp83s,10910
|
|
29
|
+
diffct_mlx-1.0.1.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
|
|
30
|
+
diffct_mlx-1.0.1.dist-info/licenses/LICENSE,sha256=a1fjzGs44LpDnV_LmA2Tzp8z-eJKoNVVdLOnh-F6J6E,11344
|
|
31
|
+
diffct_mlx-1.0.1.dist-info/RECORD,,
|