fdg-pet-ct-mlx 0.2.1__tar.gz
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.
- fdg_pet_ct_mlx-0.2.1/.gitignore +7 -0
- fdg_pet_ct_mlx-0.2.1/LICENSE +202 -0
- fdg_pet_ct_mlx-0.2.1/PKG-INFO +145 -0
- fdg_pet_ct_mlx-0.2.1/README.md +122 -0
- fdg_pet_ct_mlx-0.2.1/THIRD_PARTY_NOTICES.md +14 -0
- fdg_pet_ct_mlx-0.2.1/pyproject.toml +78 -0
- fdg_pet_ct_mlx-0.2.1/src/fdg_pet_ct_mlx/__init__.py +3 -0
- fdg_pet_ct_mlx-0.2.1/src/fdg_pet_ct_mlx/_typing.py +68 -0
- fdg_pet_ct_mlx-0.2.1/src/fdg_pet_ct_mlx/acquisition.py +140 -0
- fdg_pet_ct_mlx-0.2.1/src/fdg_pet_ct_mlx/activity.py +88 -0
- fdg_pet_ct_mlx-0.2.1/src/fdg_pet_ct_mlx/lesion.py +170 -0
- fdg_pet_ct_mlx-0.2.1/src/fdg_pet_ct_mlx/profiles.py +98 -0
- fdg_pet_ct_mlx-0.2.1/src/fdg_pet_ct_mlx/py.typed +0 -0
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: fdg-pet-ct-mlx
|
|
3
|
+
Version: 0.2.1
|
|
4
|
+
Summary: Native MLX FDG PET image synthesis
|
|
5
|
+
Author: Joseph Sandoval, Alfredo Sandoval Jr.
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
License-File: THIRD_PARTY_NOTICES.md
|
|
9
|
+
Classifier: Operating System :: MacOS :: MacOS X
|
|
10
|
+
Requires-Python: <3.15,>=3.13
|
|
11
|
+
Requires-Dist: medmlx-core==0.2.3
|
|
12
|
+
Requires-Dist: mlx<1,>=0.32.4
|
|
13
|
+
Requires-Dist: numpy<3,>=2.0
|
|
14
|
+
Provides-Extra: conversion
|
|
15
|
+
Requires-Dist: torch<2.14,>=2.13; extra == 'conversion'
|
|
16
|
+
Provides-Extra: dev
|
|
17
|
+
Requires-Dist: pyright==1.1.414; extra == 'dev'
|
|
18
|
+
Requires-Dist: pytest<10,>=8.4; extra == 'dev'
|
|
19
|
+
Requires-Dist: ruff<1,>=0.13; extra == 'dev'
|
|
20
|
+
Requires-Dist: scipy-stubs<1.19,>=1.18; extra == 'dev'
|
|
21
|
+
Requires-Dist: scipy<2,>=1.13; extra == 'dev'
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
|
|
24
|
+
# fdg-pet-ct-mlx
|
|
25
|
+
|
|
26
|
+
Native MLX FDG PET synthesis for Apple Silicon. Turn a CT and its organ labels into
|
|
27
|
+
a synthetic FDG PET (SUV) volume, locally on Mac.
|
|
28
|
+
|
|
29
|
+
- Organ-level FDG activity from a label map
|
|
30
|
+
- Scanner blur, scatter, randoms and count noise
|
|
31
|
+
- Optional lesion uptake
|
|
32
|
+
- FP32 using MLX; every random draw is controlled by an explicit integer seed
|
|
33
|
+
|
|
34
|
+
Part of [MedMLX](https://github.com/MedMLX).
|
|
35
|
+
[Technical notes](https://github.com/MedMLX/fdg-pet-ct-mlx/blob/main/docs/technical.md)
|
|
36
|
+
|
|
37
|
+
[Quick start](#quick-start) · [Input and output](#input-and-output) · [Technical details](#technical-details) · [License](#license)
|
|
38
|
+
|
|
39
|
+
## Requirements
|
|
40
|
+
|
|
41
|
+
Apple Silicon Mac with Metal, Python 3.13 or 3.14 and [uv](https://docs.astral.sh/uv/).
|
|
42
|
+
No model weights are needed.
|
|
43
|
+
|
|
44
|
+
## Quick start
|
|
45
|
+
|
|
46
|
+
Install the current source branch:
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
uv pip install "fdg-pet-ct-mlx @ git+https://github.com/MedMLX/fdg-pet-ct-mlx.git"
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Organ and scanner settings are passed as profile objects; any object with the
|
|
53
|
+
fields below works. This example uses simple dataclasses and a synthetic volume:
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
from collections.abc import Mapping
|
|
57
|
+
from dataclasses import dataclass
|
|
58
|
+
|
|
59
|
+
import mlx.core as mx
|
|
60
|
+
|
|
61
|
+
from fdg_pet_ct_mlx.acquisition import apply_acquisition_model
|
|
62
|
+
from fdg_pet_ct_mlx.activity import synthesize_activity_map
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass(frozen=True)
|
|
66
|
+
class Tissue:
|
|
67
|
+
suv_mean: float
|
|
68
|
+
suv_std: float
|
|
69
|
+
maisi_labels: tuple[int, ...]
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass(frozen=True)
|
|
73
|
+
class Organs:
|
|
74
|
+
tissues: Mapping[str, Tissue]
|
|
75
|
+
|
|
76
|
+
def lookup_table(self, size: int) -> tuple[float, ...]:
|
|
77
|
+
table = [self.tissues["unclassified_soft_tissue"].suv_mean] * size
|
|
78
|
+
for tissue in self.tissues.values():
|
|
79
|
+
for label in tissue.maisi_labels:
|
|
80
|
+
if label < size:
|
|
81
|
+
table[label] = tissue.suv_mean
|
|
82
|
+
return tuple(table)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@dataclass(frozen=True)
|
|
86
|
+
class Scanner:
|
|
87
|
+
scatter_fraction: float = 0.05
|
|
88
|
+
randoms_fraction: float = 0.02
|
|
89
|
+
fwhm_mm: tuple[float, float, float] = (5.0, 5.0, 5.0)
|
|
90
|
+
counts_per_suv: float = 100.0
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
organ = Organs({
|
|
94
|
+
"background": Tissue(0.0, 0.0, (0,)),
|
|
95
|
+
"unclassified_soft_tissue": Tissue(1.0, 0.1, (1,)),
|
|
96
|
+
})
|
|
97
|
+
labels = mx.ones((16, 16, 16), dtype=mx.int32)
|
|
98
|
+
ct_hu = mx.zeros(labels.shape, dtype=mx.float32)
|
|
99
|
+
activity = synthesize_activity_map(labels, organ, seed=7, mx=mx)
|
|
100
|
+
pet = apply_acquisition_model(
|
|
101
|
+
activity,
|
|
102
|
+
ct_hu,
|
|
103
|
+
scanner=Scanner(),
|
|
104
|
+
count_level=1.0,
|
|
105
|
+
spacing_mm=(2.0, 2.0, 2.0),
|
|
106
|
+
seed=8,
|
|
107
|
+
mx=mx,
|
|
108
|
+
)
|
|
109
|
+
mx.eval(pet)
|
|
110
|
+
print(pet.shape, pet.dtype) # (16, 16, 16), float32
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
## Input and output
|
|
114
|
+
|
|
115
|
+
Inputs are a nonnegative integer label volume and a CT volume in HU on the same 3D
|
|
116
|
+
grid. Organ profiles give each tissue's SUV mean, standard deviation and label
|
|
117
|
+
values; scanner profiles give resolution (FWHM), scatter, randoms and counts.
|
|
118
|
+
|
|
119
|
+
The output is a float32 SUVbw MLX array with the input shape. To add lesions, use
|
|
120
|
+
`fdg_pet_ct_mlx.lesion.apply_lesion_uptake` with a lesion profile.
|
|
121
|
+
|
|
122
|
+
Profile validation, resampling and file I/O are up to you. This is image-space
|
|
123
|
+
synthesis; it does not simulate projection physics or reconstruction.
|
|
124
|
+
|
|
125
|
+
## Technical details
|
|
126
|
+
|
|
127
|
+
Activity synthesis and scanner effects operate on MLX arrays in float32.
|
|
128
|
+
The acquisition model approximates blur, scatter, randoms and count noise in
|
|
129
|
+
image space. Profiles, numerical contracts and development commands are described
|
|
130
|
+
in [docs/technical.md](https://github.com/MedMLX/fdg-pet-ct-mlx/blob/main/docs/technical.md).
|
|
131
|
+
|
|
132
|
+
## Intended use
|
|
133
|
+
|
|
134
|
+
Research software, for research and education only; not for clinical diagnosis or
|
|
135
|
+
treatment decisions. The output is a synthetic image from a simple image-space model, not
|
|
136
|
+
a simulation of a real scanner. Outputs require human review.
|
|
137
|
+
|
|
138
|
+
## License
|
|
139
|
+
|
|
140
|
+
Apache-2.0; see [LICENSE](https://github.com/MedMLX/fdg-pet-ct-mlx/blob/main/LICENSE).
|
|
141
|
+
See [THIRD_PARTY_NOTICES.md](https://github.com/MedMLX/fdg-pet-ct-mlx/blob/main/THIRD_PARTY_NOTICES.md) for dependency attribution.
|
|
142
|
+
|
|
143
|
+
## Implementation mapping
|
|
144
|
+
|
|
145
|
+
[Central implementation map](https://github.com/MedMLX/Med-MLX/blob/main/implementation-maps/fdg-pet-ct-mlx.json) records upstream-to-native changes, source references and qualification scope.
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
# fdg-pet-ct-mlx
|
|
2
|
+
|
|
3
|
+
Native MLX FDG PET synthesis for Apple Silicon. Turn a CT and its organ labels into
|
|
4
|
+
a synthetic FDG PET (SUV) volume, locally on Mac.
|
|
5
|
+
|
|
6
|
+
- Organ-level FDG activity from a label map
|
|
7
|
+
- Scanner blur, scatter, randoms and count noise
|
|
8
|
+
- Optional lesion uptake
|
|
9
|
+
- FP32 using MLX; every random draw is controlled by an explicit integer seed
|
|
10
|
+
|
|
11
|
+
Part of [MedMLX](https://github.com/MedMLX).
|
|
12
|
+
[Technical notes](https://github.com/MedMLX/fdg-pet-ct-mlx/blob/main/docs/technical.md)
|
|
13
|
+
|
|
14
|
+
[Quick start](#quick-start) · [Input and output](#input-and-output) · [Technical details](#technical-details) · [License](#license)
|
|
15
|
+
|
|
16
|
+
## Requirements
|
|
17
|
+
|
|
18
|
+
Apple Silicon Mac with Metal, Python 3.13 or 3.14 and [uv](https://docs.astral.sh/uv/).
|
|
19
|
+
No model weights are needed.
|
|
20
|
+
|
|
21
|
+
## Quick start
|
|
22
|
+
|
|
23
|
+
Install the current source branch:
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
uv pip install "fdg-pet-ct-mlx @ git+https://github.com/MedMLX/fdg-pet-ct-mlx.git"
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Organ and scanner settings are passed as profile objects; any object with the
|
|
30
|
+
fields below works. This example uses simple dataclasses and a synthetic volume:
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
from collections.abc import Mapping
|
|
34
|
+
from dataclasses import dataclass
|
|
35
|
+
|
|
36
|
+
import mlx.core as mx
|
|
37
|
+
|
|
38
|
+
from fdg_pet_ct_mlx.acquisition import apply_acquisition_model
|
|
39
|
+
from fdg_pet_ct_mlx.activity import synthesize_activity_map
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class Tissue:
|
|
44
|
+
suv_mean: float
|
|
45
|
+
suv_std: float
|
|
46
|
+
maisi_labels: tuple[int, ...]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True)
|
|
50
|
+
class Organs:
|
|
51
|
+
tissues: Mapping[str, Tissue]
|
|
52
|
+
|
|
53
|
+
def lookup_table(self, size: int) -> tuple[float, ...]:
|
|
54
|
+
table = [self.tissues["unclassified_soft_tissue"].suv_mean] * size
|
|
55
|
+
for tissue in self.tissues.values():
|
|
56
|
+
for label in tissue.maisi_labels:
|
|
57
|
+
if label < size:
|
|
58
|
+
table[label] = tissue.suv_mean
|
|
59
|
+
return tuple(table)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass(frozen=True)
|
|
63
|
+
class Scanner:
|
|
64
|
+
scatter_fraction: float = 0.05
|
|
65
|
+
randoms_fraction: float = 0.02
|
|
66
|
+
fwhm_mm: tuple[float, float, float] = (5.0, 5.0, 5.0)
|
|
67
|
+
counts_per_suv: float = 100.0
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
organ = Organs({
|
|
71
|
+
"background": Tissue(0.0, 0.0, (0,)),
|
|
72
|
+
"unclassified_soft_tissue": Tissue(1.0, 0.1, (1,)),
|
|
73
|
+
})
|
|
74
|
+
labels = mx.ones((16, 16, 16), dtype=mx.int32)
|
|
75
|
+
ct_hu = mx.zeros(labels.shape, dtype=mx.float32)
|
|
76
|
+
activity = synthesize_activity_map(labels, organ, seed=7, mx=mx)
|
|
77
|
+
pet = apply_acquisition_model(
|
|
78
|
+
activity,
|
|
79
|
+
ct_hu,
|
|
80
|
+
scanner=Scanner(),
|
|
81
|
+
count_level=1.0,
|
|
82
|
+
spacing_mm=(2.0, 2.0, 2.0),
|
|
83
|
+
seed=8,
|
|
84
|
+
mx=mx,
|
|
85
|
+
)
|
|
86
|
+
mx.eval(pet)
|
|
87
|
+
print(pet.shape, pet.dtype) # (16, 16, 16), float32
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
## Input and output
|
|
91
|
+
|
|
92
|
+
Inputs are a nonnegative integer label volume and a CT volume in HU on the same 3D
|
|
93
|
+
grid. Organ profiles give each tissue's SUV mean, standard deviation and label
|
|
94
|
+
values; scanner profiles give resolution (FWHM), scatter, randoms and counts.
|
|
95
|
+
|
|
96
|
+
The output is a float32 SUVbw MLX array with the input shape. To add lesions, use
|
|
97
|
+
`fdg_pet_ct_mlx.lesion.apply_lesion_uptake` with a lesion profile.
|
|
98
|
+
|
|
99
|
+
Profile validation, resampling and file I/O are up to you. This is image-space
|
|
100
|
+
synthesis; it does not simulate projection physics or reconstruction.
|
|
101
|
+
|
|
102
|
+
## Technical details
|
|
103
|
+
|
|
104
|
+
Activity synthesis and scanner effects operate on MLX arrays in float32.
|
|
105
|
+
The acquisition model approximates blur, scatter, randoms and count noise in
|
|
106
|
+
image space. Profiles, numerical contracts and development commands are described
|
|
107
|
+
in [docs/technical.md](https://github.com/MedMLX/fdg-pet-ct-mlx/blob/main/docs/technical.md).
|
|
108
|
+
|
|
109
|
+
## Intended use
|
|
110
|
+
|
|
111
|
+
Research software, for research and education only; not for clinical diagnosis or
|
|
112
|
+
treatment decisions. The output is a synthetic image from a simple image-space model, not
|
|
113
|
+
a simulation of a real scanner. Outputs require human review.
|
|
114
|
+
|
|
115
|
+
## License
|
|
116
|
+
|
|
117
|
+
Apache-2.0; see [LICENSE](https://github.com/MedMLX/fdg-pet-ct-mlx/blob/main/LICENSE).
|
|
118
|
+
See [THIRD_PARTY_NOTICES.md](https://github.com/MedMLX/fdg-pet-ct-mlx/blob/main/THIRD_PARTY_NOTICES.md) for dependency attribution.
|
|
119
|
+
|
|
120
|
+
## Implementation mapping
|
|
121
|
+
|
|
122
|
+
[Central implementation map](https://github.com/MedMLX/Med-MLX/blob/main/implementation-maps/fdg-pet-ct-mlx.json) records upstream-to-native changes, source references and qualification scope.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# Third-party notices
|
|
2
|
+
|
|
3
|
+
The image-space FDG synthesis implementation is MedMLX-authored code licensed
|
|
4
|
+
under [Apache-2.0](LICENSE). It does not distribute a pretrained model.
|
|
5
|
+
|
|
6
|
+
## Dependencies
|
|
7
|
+
|
|
8
|
+
MLX and NumPy provide array operations; the runtime, image-I/O and development
|
|
9
|
+
dependencies are declared in [pyproject.toml](pyproject.toml). These packages are
|
|
10
|
+
installed separately and retain their respective licenses. SciPy is used as an
|
|
11
|
+
independent numerical reference in the tests.
|
|
12
|
+
|
|
13
|
+
Input medical images and label maps are supplied by the caller. Their original
|
|
14
|
+
dataset or provider terms apply independently of this package's source license.
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.27"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "fdg-pet-ct-mlx"
|
|
7
|
+
version = "0.2.1"
|
|
8
|
+
description = "Native MLX FDG PET image synthesis"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
classifiers = ["Operating System :: MacOS :: MacOS X"]
|
|
11
|
+
requires-python = ">=3.13,<3.15"
|
|
12
|
+
license = "Apache-2.0"
|
|
13
|
+
license-files = ["LICENSE", "THIRD_PARTY_NOTICES.md"]
|
|
14
|
+
authors = [{ name = "Joseph Sandoval" }, { name = "Alfredo Sandoval Jr." }]
|
|
15
|
+
dependencies = [
|
|
16
|
+
"medmlx-core==0.2.3",
|
|
17
|
+
"mlx>=0.32.4,<1",
|
|
18
|
+
"numpy>=2.0,<3",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[project.optional-dependencies]
|
|
22
|
+
conversion = ["torch>=2.13,<2.14"]
|
|
23
|
+
dev = [
|
|
24
|
+
"pyright==1.1.414",
|
|
25
|
+
"pytest>=8.4,<10",
|
|
26
|
+
"ruff>=0.13,<1",
|
|
27
|
+
"scipy>=1.13,<2",
|
|
28
|
+
"scipy-stubs>=1.18,<1.19",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
[tool.hatch.metadata]
|
|
32
|
+
allow-direct-references = true
|
|
33
|
+
|
|
34
|
+
[tool.hatch.build.targets.wheel]
|
|
35
|
+
packages = ["src/fdg_pet_ct_mlx"]
|
|
36
|
+
|
|
37
|
+
[tool.pytest.ini_options]
|
|
38
|
+
testpaths = ["tests"]
|
|
39
|
+
addopts = "--strict-config --strict-markers"
|
|
40
|
+
|
|
41
|
+
[tool.ruff]
|
|
42
|
+
line-length = 100
|
|
43
|
+
target-version = "py313"
|
|
44
|
+
|
|
45
|
+
[tool.ruff.lint]
|
|
46
|
+
extend-select = ["TID251", "TID252", "ANN401"]
|
|
47
|
+
select = ["E", "F", "I", "UP", "B", "SIM", "RUF"]
|
|
48
|
+
|
|
49
|
+
[tool.pyright]
|
|
50
|
+
include = ["src","tests"]
|
|
51
|
+
extraPaths = ["src"]
|
|
52
|
+
pythonVersion = "3.13"
|
|
53
|
+
typeCheckingMode = "strict"
|
|
54
|
+
enableTypeIgnoreComments = false
|
|
55
|
+
reportUnnecessaryTypeIgnoreComment = "error"
|
|
56
|
+
|
|
57
|
+
[tool.ruff.lint.flake8-tidy-imports]
|
|
58
|
+
ban-relative-imports = "all"
|
|
59
|
+
|
|
60
|
+
[tool.ruff.lint.flake8-tidy-imports.banned-api]
|
|
61
|
+
"typing.Any" = {msg = "Use a precise type and parse untyped values at the boundary."}
|
|
62
|
+
"typing_extensions.Any" = {msg = "Use a precise type and parse untyped values at the boundary."}
|
|
63
|
+
|
|
64
|
+
[tool.uv]
|
|
65
|
+
constraint-dependencies = ["setuptools>=84.1.0", "filelock>=4.2.1", ]
|
|
66
|
+
|
|
67
|
+
[tool.uv.sources]
|
|
68
|
+
medmlx-core = { git = "https://github.com/MedMLX/medmlx.git", rev = "e765f0a94aa31e8dfcdc599e4a4206eaca84f8b0", subdirectory = "packages/core" }
|
|
69
|
+
|
|
70
|
+
[tool.hatch.build.targets.sdist]
|
|
71
|
+
exclude = ["AGENTS.md", "CLAUDE.md", ".claude", ".codex", ".cursor"]
|
|
72
|
+
only-include = [
|
|
73
|
+
"src/fdg_pet_ct_mlx",
|
|
74
|
+
"pyproject.toml",
|
|
75
|
+
"README.md",
|
|
76
|
+
"LICENSE",
|
|
77
|
+
"THIRD_PARTY_NOTICES.md",
|
|
78
|
+
]
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Structural types for the subset of ``mlx.core`` used by this package.
|
|
2
|
+
|
|
3
|
+
Every public function takes the MLX module as an explicit ``mx`` argument. Pass
|
|
4
|
+
``mlx.core`` itself (or the module returned by ``medmlx_core.runtime.import_mlx``).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from collections.abc import Sequence
|
|
10
|
+
from typing import TYPE_CHECKING, Protocol
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from mlx.core import Dtype, array
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class RandomRuntime(Protocol):
|
|
17
|
+
"""The ``mx.random`` functions used for seeded noise."""
|
|
18
|
+
|
|
19
|
+
def key(self, seed: int) -> array: ...
|
|
20
|
+
def normal(
|
|
21
|
+
self, shape: Sequence[int], dtype: Dtype, *, key: array | None = None
|
|
22
|
+
) -> array: ...
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class FdgRuntime(Protocol):
|
|
26
|
+
"""The ``mlx.core`` dtypes and operations used by the FDG kernels."""
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def array(self) -> type[array]: ...
|
|
30
|
+
@property
|
|
31
|
+
def float32(self) -> Dtype: ...
|
|
32
|
+
@property
|
|
33
|
+
def int32(self) -> Dtype: ...
|
|
34
|
+
@property
|
|
35
|
+
def int64(self) -> Dtype: ...
|
|
36
|
+
@property
|
|
37
|
+
def uint32(self) -> Dtype: ...
|
|
38
|
+
@property
|
|
39
|
+
def complex64(self) -> Dtype: ...
|
|
40
|
+
@property
|
|
41
|
+
def bool_(self) -> Dtype: ...
|
|
42
|
+
@property
|
|
43
|
+
def random(self) -> RandomRuntime: ...
|
|
44
|
+
def eval(self, *args: array) -> None: ...
|
|
45
|
+
def zeros(self, shape: Sequence[int], *, dtype: Dtype) -> array: ...
|
|
46
|
+
def ones(self, shape: Sequence[int], *, dtype: Dtype) -> array: ...
|
|
47
|
+
def full(self, shape: Sequence[int], vals: float, *, dtype: Dtype) -> array: ...
|
|
48
|
+
def reshape(self, a: array, /, shape: Sequence[int]) -> array: ...
|
|
49
|
+
def zeros_like(self, a: array, /) -> array: ...
|
|
50
|
+
def arange(self, start: int, stop: int, *, dtype: Dtype) -> array: ...
|
|
51
|
+
def all(self, a: array, /) -> array: ...
|
|
52
|
+
def isfinite(self, a: array, /) -> array: ...
|
|
53
|
+
def min(self, a: array, /) -> array: ...
|
|
54
|
+
def max(self, a: array, /) -> array: ...
|
|
55
|
+
def sum(self, a: array, /) -> array: ...
|
|
56
|
+
def mean(self, a: array, /) -> array: ...
|
|
57
|
+
def floor(self, a: array, /) -> array: ...
|
|
58
|
+
def exp(self, a: array, /) -> array: ...
|
|
59
|
+
def sqrt(self, a: array, /) -> array: ...
|
|
60
|
+
def clip(self, a: array, /, a_min: float, a_max: float) -> array: ...
|
|
61
|
+
def maximum(self, a: array, b: array | float, /) -> array: ...
|
|
62
|
+
def where(self, condition: array, x: array, y: array | int, /) -> array: ...
|
|
63
|
+
def logical_or(self, a: array, b: array, /) -> array: ...
|
|
64
|
+
def logical_and(self, a: array, b: array, /) -> array: ...
|
|
65
|
+
def moveaxis(self, a: array, /, source: int, destination: int) -> array: ...
|
|
66
|
+
def pad(self, a: array, pad_width: list[tuple[int, int]]) -> array: ...
|
|
67
|
+
def conv1d(self, input: array, weight: array, /) -> array: ...
|
|
68
|
+
def conv3d(self, input: array, weight: array, /) -> array: ...
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""Image-space approximation of a reconstructed PET volume.
|
|
2
|
+
|
|
3
|
+
This applies simple multiplicative, additive, blur and noise steps directly to the
|
|
4
|
+
SUV image. It does not simulate projection physics, attenuation correction or
|
|
5
|
+
reconstruction.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import math
|
|
11
|
+
from typing import TYPE_CHECKING
|
|
12
|
+
|
|
13
|
+
from fdg_pet_ct_mlx._typing import FdgRuntime
|
|
14
|
+
from fdg_pet_ct_mlx.profiles import FdgScannerProfile
|
|
15
|
+
|
|
16
|
+
if TYPE_CHECKING:
|
|
17
|
+
from mlx.core import array
|
|
18
|
+
|
|
19
|
+
# FWHM = 2*sqrt(2*ln 2) * sigma for a Gaussian (about 2.3548).
|
|
20
|
+
_FWHM_SIGMA = 2.0 * math.sqrt(2.0 * math.log(2.0))
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def apply_acquisition_model(
|
|
24
|
+
activity: array,
|
|
25
|
+
ct_hu: array,
|
|
26
|
+
*,
|
|
27
|
+
scanner: FdgScannerProfile,
|
|
28
|
+
count_level: float,
|
|
29
|
+
spacing_mm: tuple[float, float, float],
|
|
30
|
+
seed: int,
|
|
31
|
+
mx: FdgRuntime,
|
|
32
|
+
) -> array:
|
|
33
|
+
"""Turn a synthetic activity volume into a PET-like SUV volume.
|
|
34
|
+
|
|
35
|
+
Steps, in order, all in float32:
|
|
36
|
+
|
|
37
|
+
1. Multiply by a CT-dependent factor ``exp(-0.02 * clip((HU + 1000) / 1000, 0, 3))``.
|
|
38
|
+
This is a fixed heuristic, not a physical attenuation model: air gives 1.0 and
|
|
39
|
+
HU of 2000 or more gives about 0.94.
|
|
40
|
+
2. If ``scatter_fraction + randoms_fraction > 0``, add a uniform offset equal to
|
|
41
|
+
that sum times the mean of the whole volume (background voxels included, so the
|
|
42
|
+
offset depends on the grid extent).
|
|
43
|
+
3. Blur with ``gaussian_blur`` using ``scanner.fwhm_mm`` and ``spacing_mm``.
|
|
44
|
+
4. Convert to expected counts ``lam = SUV * counts_per_suv * count_level``, draw
|
|
45
|
+
``max(lam + sqrt(max(lam, 0)) * N(0, 1), 0)`` (a Gaussian approximation to
|
|
46
|
+
Poisson noise, independent per voxel), and divide back by the same factor.
|
|
47
|
+
|
|
48
|
+
Args:
|
|
49
|
+
activity: SUV volume, shape ``(X, Y, Z)``.
|
|
50
|
+
ct_hu: CT in Hounsfield units on the same grid and in the same axis order as
|
|
51
|
+
``activity``. Registration and resampling are the caller's job.
|
|
52
|
+
scanner: Scatter/randoms fractions, blur FWHM and counts per SUV.
|
|
53
|
+
count_level: Multiplier on ``scanner.counts_per_suv``. The product must be
|
|
54
|
+
positive; it is not checked.
|
|
55
|
+
spacing_mm: Voxel spacing in mm for each array axis.
|
|
56
|
+
seed: Seed for the noise draw.
|
|
57
|
+
mx: The ``mlx.core`` module.
|
|
58
|
+
|
|
59
|
+
Returns:
|
|
60
|
+
Nonnegative float32 SUV array with the shape of ``activity``, already evaluated.
|
|
61
|
+
|
|
62
|
+
Raises:
|
|
63
|
+
ValueError: If ``activity`` and ``ct_hu`` have different shapes.
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
if activity.shape != ct_hu.shape:
|
|
67
|
+
raise ValueError("activity and CT must share one grid")
|
|
68
|
+
hu = ct_hu.astype(mx.float32)
|
|
69
|
+
shifted = (hu + mx.array(1000.0, dtype=mx.float32)) / mx.array(1000.0, dtype=mx.float32)
|
|
70
|
+
mu = mx.clip(shifted, 0.0, 3.0)
|
|
71
|
+
residual = mx.exp(mx.array(-0.02, dtype=mx.float32) * mu)
|
|
72
|
+
volume = activity.astype(mx.float32) * residual
|
|
73
|
+
floor_fraction = scanner.scatter_fraction + scanner.randoms_fraction
|
|
74
|
+
if floor_fraction > 0.0:
|
|
75
|
+
volume = volume + mx.mean(volume) * mx.array(floor_fraction, dtype=mx.float32)
|
|
76
|
+
volume = gaussian_blur(volume, scanner.fwhm_mm, spacing_mm, mx)
|
|
77
|
+
counts_per = scanner.counts_per_suv * count_level
|
|
78
|
+
lam = volume * mx.array(counts_per, dtype=mx.float32)
|
|
79
|
+
noise = mx.random.normal(volume.shape, dtype=mx.float32, key=mx.random.key(seed))
|
|
80
|
+
zero = mx.array(0.0, dtype=mx.float32)
|
|
81
|
+
counts = mx.maximum(lam + mx.sqrt(mx.maximum(lam, 0.0)) * noise, zero)
|
|
82
|
+
suv = counts / mx.array(counts_per, dtype=mx.float32)
|
|
83
|
+
mx.eval(suv)
|
|
84
|
+
return suv
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def gaussian_blur(
|
|
88
|
+
volume: array,
|
|
89
|
+
fwhm_mm: tuple[float, float, float],
|
|
90
|
+
spacing_mm: tuple[float, float, float],
|
|
91
|
+
mx: FdgRuntime,
|
|
92
|
+
) -> array:
|
|
93
|
+
"""Blur a volume with a separable Gaussian, one 1-D pass per array axis.
|
|
94
|
+
|
|
95
|
+
For each axis, ``sigma = fwhm / (2 * sqrt(2 * ln 2)) / spacing`` in voxels. The
|
|
96
|
+
kernel is truncated at ``ceil(3 * sigma)`` voxels (at least 1) and normalized to
|
|
97
|
+
sum to 1. The volume is zero-padded, so values near the borders are pulled toward
|
|
98
|
+
zero. An axis with ``fwhm <= 0`` is skipped.
|
|
99
|
+
|
|
100
|
+
Args:
|
|
101
|
+
volume: Array with one axis per entry of ``fwhm_mm`` (3-D in this package).
|
|
102
|
+
fwhm_mm: Blur FWHM in mm for each array axis.
|
|
103
|
+
spacing_mm: Voxel spacing in mm for each array axis; must be positive.
|
|
104
|
+
mx: The ``mlx.core`` module.
|
|
105
|
+
|
|
106
|
+
Returns:
|
|
107
|
+
Float32 array with the shape of ``volume``, already evaluated.
|
|
108
|
+
"""
|
|
109
|
+
|
|
110
|
+
blurred = volume.astype(mx.float32)
|
|
111
|
+
for axis, (fwhm, spacing) in enumerate(zip(fwhm_mm, spacing_mm, strict=True)):
|
|
112
|
+
sigma = (fwhm / _FWHM_SIGMA) / spacing
|
|
113
|
+
if sigma <= 0.0:
|
|
114
|
+
continue
|
|
115
|
+
blurred = _smooth_axis(blurred, _gaussian_kernel(sigma, mx), axis, mx)
|
|
116
|
+
mx.eval(blurred)
|
|
117
|
+
return blurred
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _gaussian_kernel(sigma: float, mx: FdgRuntime) -> array:
|
|
121
|
+
# Truncate at 3 sigma; the kernel is symmetric, so conv1d's correlation equals
|
|
122
|
+
# convolution.
|
|
123
|
+
radius = max(1, math.ceil(3.0 * sigma))
|
|
124
|
+
axis = mx.arange(-radius, radius + 1, dtype=mx.float32)
|
|
125
|
+
scaled = axis / mx.array(sigma, dtype=mx.float32)
|
|
126
|
+
kernel = mx.exp(mx.array(-0.5, dtype=mx.float32) * scaled**2)
|
|
127
|
+
return kernel / mx.sum(kernel)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _smooth_axis(volume: array, kernel: array, axis: int, mx: FdgRuntime) -> array:
|
|
131
|
+
# MLX convolutions are channels-last: (batch, length, channels). Fold every
|
|
132
|
+
# other axis into the batch and use a single channel.
|
|
133
|
+
moved = mx.moveaxis(volume, axis, -1)
|
|
134
|
+
length = moved.shape[-1]
|
|
135
|
+
flat = mx.reshape(moved, (-1, length, 1))
|
|
136
|
+
weight = mx.reshape(kernel, (1, -1, 1))
|
|
137
|
+
pad = kernel.shape[0] // 2
|
|
138
|
+
padded = mx.pad(flat, [(0, 0), (pad, pad), (0, 0)])
|
|
139
|
+
out = mx.conv1d(padded, weight)
|
|
140
|
+
return mx.moveaxis(mx.reshape(out, moved.shape), -1, axis)
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""Per-voxel FDG activity (SUV) drawn from tissue statistics selected by label ID."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TYPE_CHECKING, cast
|
|
6
|
+
|
|
7
|
+
from fdg_pet_ct_mlx._typing import FdgRuntime
|
|
8
|
+
from fdg_pet_ct_mlx.profiles import FdgOrganProfile
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
from mlx.core import array
|
|
12
|
+
|
|
13
|
+
# MAISI label IDs run 0..200 (200 is the body envelope label in nv-generate-mlx), so the
|
|
14
|
+
# lookup tables always cover at least that range.
|
|
15
|
+
_LOOKUP_MIN = 201
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def synthesize_activity_map(
|
|
19
|
+
labels: array,
|
|
20
|
+
profile: FdgOrganProfile,
|
|
21
|
+
*,
|
|
22
|
+
seed: int,
|
|
23
|
+
mx: FdgRuntime,
|
|
24
|
+
) -> array:
|
|
25
|
+
"""Draw a nonnegative float32 SUV volume on the label grid.
|
|
26
|
+
|
|
27
|
+
Each voxel is ``max(mean[label] + std[label] * N(0, 1), 0)``, with independent
|
|
28
|
+
unit-normal draws per voxel and the profile's SUV mean and standard deviation for
|
|
29
|
+
that label. Means come from ``profile.lookup_table`` and standard deviations from
|
|
30
|
+
``profile.tissues``. IDs that no tissue lists get the ``unclassified_soft_tissue``
|
|
31
|
+
standard deviation and, by the lookup-table convention, its mean. IDs at or above
|
|
32
|
+
the lookup size use the unclassified mean and standard deviation directly.
|
|
33
|
+
|
|
34
|
+
Args:
|
|
35
|
+
labels: MAISI label volume, shape ``(X, Y, Z)``. Any real integer or float
|
|
36
|
+
dtype is accepted if every value is finite, integral and in
|
|
37
|
+
``[0, 2**31 - 1]``.
|
|
38
|
+
profile: Organ activity profile.
|
|
39
|
+
seed: Seed for the noise draw.
|
|
40
|
+
mx: The ``mlx.core`` module.
|
|
41
|
+
|
|
42
|
+
Returns:
|
|
43
|
+
Float32 SUV array with the shape of ``labels``, already evaluated.
|
|
44
|
+
|
|
45
|
+
Raises:
|
|
46
|
+
ValueError: If ``labels`` is not 3-D, is empty, is boolean or complex, or has
|
|
47
|
+
non-finite, negative, out-of-range or non-integral values.
|
|
48
|
+
KeyError: If ``profile.tissues`` has no ``"unclassified_soft_tissue"`` entry.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
if labels.ndim != 3:
|
|
52
|
+
raise ValueError("activity labels must be a 3D volume")
|
|
53
|
+
if labels.size == 0:
|
|
54
|
+
raise ValueError("activity labels must be nonempty")
|
|
55
|
+
if labels.dtype == mx.complex64 or labels.dtype == mx.bool_:
|
|
56
|
+
raise ValueError("activity labels must contain real integral identifiers")
|
|
57
|
+
if not bool(mx.all(mx.isfinite(labels)).item()):
|
|
58
|
+
raise ValueError("activity labels must be finite")
|
|
59
|
+
lowest = cast(int | float, mx.min(labels).item())
|
|
60
|
+
highest_value = cast(int | float, mx.max(labels).item())
|
|
61
|
+
if lowest < 0 or highest_value > 2**31 - 1:
|
|
62
|
+
raise ValueError("activity labels must be in the nonnegative int32 range")
|
|
63
|
+
if not bool(mx.all(labels == mx.floor(labels)).item()):
|
|
64
|
+
raise ValueError("activity labels must be integral")
|
|
65
|
+
ids = labels.astype(mx.int32)
|
|
66
|
+
profile_labels = [label for spec in profile.tissues.values() for label in spec.maisi_labels]
|
|
67
|
+
size = max(max(profile_labels, default=0) + 1, _LOOKUP_MIN)
|
|
68
|
+
# Send every ID >= size to one extra table slot holding the unclassified values, so
|
|
69
|
+
# table size does not depend on the largest input ID.
|
|
70
|
+
ids = mx.where(ids < size, ids, size)
|
|
71
|
+
default = profile.tissues["unclassified_soft_tissue"]
|
|
72
|
+
means = mx.array((*profile.lookup_table(size), default.suv_mean), dtype=mx.float32)
|
|
73
|
+
stds = mx.array((*_std_table(profile, size), default.suv_std), dtype=mx.float32)
|
|
74
|
+
base = means[ids]
|
|
75
|
+
noise = mx.random.normal(ids.shape, dtype=mx.float32, key=mx.random.key(seed))
|
|
76
|
+
activity = mx.maximum(base + stds[ids] * noise, mx.array(0.0, dtype=mx.float32))
|
|
77
|
+
mx.eval(activity)
|
|
78
|
+
return activity
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _std_table(profile: FdgOrganProfile, size: int) -> tuple[float, ...]:
|
|
82
|
+
unclassified = profile.tissues["unclassified_soft_tissue"].suv_std
|
|
83
|
+
table = [unclassified] * size
|
|
84
|
+
for spec in profile.tissues.values():
|
|
85
|
+
for label in spec.maisi_labels:
|
|
86
|
+
if label < size:
|
|
87
|
+
table[label] = spec.suv_std
|
|
88
|
+
return tuple(table)
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"""FDG-avid lesion uptake applied to an activity volume, selected by label ID.
|
|
2
|
+
|
|
3
|
+
Lesion geometry comes only from the label volume. A requested necrotic core that
|
|
4
|
+
the labeled lesion cannot support raises ``InvalidInputError``.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import TYPE_CHECKING, cast
|
|
10
|
+
|
|
11
|
+
from medmlx_core.errors import InvalidInputError
|
|
12
|
+
|
|
13
|
+
from fdg_pet_ct_mlx._typing import FdgRuntime
|
|
14
|
+
from fdg_pet_ct_mlx.acquisition import gaussian_blur
|
|
15
|
+
from fdg_pet_ct_mlx.profiles import FdgLesionProfile, FdgOrganProfile
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING:
|
|
18
|
+
from mlx.core import array
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def apply_lesion_uptake(
|
|
22
|
+
activity: array,
|
|
23
|
+
labels: array,
|
|
24
|
+
*,
|
|
25
|
+
organ: FdgOrganProfile,
|
|
26
|
+
lesion: FdgLesionProfile,
|
|
27
|
+
spacing_mm: tuple[float, float, float],
|
|
28
|
+
seed: int,
|
|
29
|
+
mx: FdgRuntime,
|
|
30
|
+
) -> array:
|
|
31
|
+
"""Replace activity in FDG-avid lesion voxels with lesion uptake.
|
|
32
|
+
|
|
33
|
+
Let ``host`` be the ``suv_mean`` of the tissue that ``lesion.host_tissue`` assigns
|
|
34
|
+
to each avid voxel's label. In avid voxels the input activity is discarded and
|
|
35
|
+
replaced by:
|
|
36
|
+
|
|
37
|
+
1. ``host * tumor_to_background``;
|
|
38
|
+
2. if ``heterogeneity > 0``, times ``max(1 + heterogeneity * N(0, 1), 0)``, with
|
|
39
|
+
independent draws per voxel;
|
|
40
|
+
3. if ``necrosis_fraction > 0``, ``0.2 * host`` in the necrotic core (the 0.2 is a
|
|
41
|
+
fixed constant, not a profile field). The core is what remains after
|
|
42
|
+
repeatedly eroding the union of all avid voxels with a full 3x3x3 neighborhood
|
|
43
|
+
until its voxel count is at most ``necrosis_fraction`` times the avid count.
|
|
44
|
+
Erosion removes whole shells, so the core can be smaller than requested.
|
|
45
|
+
Voxels at the volume border erode because the mask is zero-padded;
|
|
46
|
+
4. if ``spillover_fwhm_mm > 0``, avid voxels are reset to ``host`` and the excess
|
|
47
|
+
``(step 3 result - host)`` (negative in a necrotic core), blurred with an
|
|
48
|
+
isotropic Gaussian (``gaussian_blur``), is added to the whole volume, so lesion
|
|
49
|
+
SUV leaks into neighbors.
|
|
50
|
+
|
|
51
|
+
The result is clipped at zero. Voxels whose label is not in
|
|
52
|
+
``avid_maisi_labels`` (for example non-avid cysts) keep their input activity, apart
|
|
53
|
+
from spill-over.
|
|
54
|
+
|
|
55
|
+
Args:
|
|
56
|
+
activity: SUV volume, shape ``(X, Y, Z)``, as from ``synthesize_activity_map``.
|
|
57
|
+
labels: MAISI label volume on the same grid and axis order as ``activity``; the
|
|
58
|
+
shapes are not checked. Values are cast to int32 without validation.
|
|
59
|
+
organ: Organ profile; supplies the host SUV means.
|
|
60
|
+
lesion: Lesion profile.
|
|
61
|
+
spacing_mm: Voxel spacing in mm for each array axis (used for spill-over).
|
|
62
|
+
seed: Seed for the heterogeneity noise; unused when ``heterogeneity == 0``.
|
|
63
|
+
mx: The ``mlx.core`` module.
|
|
64
|
+
|
|
65
|
+
Returns:
|
|
66
|
+
Float32 SUV array with the shape of ``activity``, evaluated with ``mx.eval``. If
|
|
67
|
+
no voxel carries an avid label and ``necrosis_fraction == 0``, ``activity`` itself
|
|
68
|
+
is returned as is (not a copy, and not re-evaluated).
|
|
69
|
+
|
|
70
|
+
Raises:
|
|
71
|
+
InvalidInputError: If ``necrosis_fraction > 0`` and there are no avid voxels,
|
|
72
|
+
or the lesion is too small to erode down to the requested core. This is a
|
|
73
|
+
``ValueError`` subclass.
|
|
74
|
+
KeyError: If ``lesion.host_tissue`` names a tissue missing from ``organ.tissues``.
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
ids = labels.astype(mx.int32)
|
|
78
|
+
avid = _label_mask(ids, lesion.avid_maisi_labels, mx)
|
|
79
|
+
mx.eval(avid)
|
|
80
|
+
avid_voxels = int(cast(int, mx.sum(avid).item()))
|
|
81
|
+
if avid_voxels == 0:
|
|
82
|
+
if lesion.necrosis_fraction > 0.0:
|
|
83
|
+
raise InvalidInputError(
|
|
84
|
+
"necrosis_fraction requires FDG-avid lesion voxels in the label volume"
|
|
85
|
+
)
|
|
86
|
+
return activity
|
|
87
|
+
|
|
88
|
+
host = _host_map(ids, organ, lesion, mx)
|
|
89
|
+
target = host * mx.array(lesion.tumor_to_background, dtype=mx.float32)
|
|
90
|
+
if lesion.heterogeneity > 0.0:
|
|
91
|
+
noise = mx.random.normal(ids.shape, dtype=mx.float32, key=mx.random.key(seed))
|
|
92
|
+
scale = (
|
|
93
|
+
mx.array(1.0, dtype=mx.float32)
|
|
94
|
+
+ mx.array(lesion.heterogeneity, dtype=mx.float32) * noise
|
|
95
|
+
)
|
|
96
|
+
target = target * mx.maximum(scale, mx.array(0.0, dtype=mx.float32))
|
|
97
|
+
if lesion.necrosis_fraction > 0.0:
|
|
98
|
+
necrotic = _necrosis_mask(avid, lesion.necrosis_fraction, mx)
|
|
99
|
+
target = mx.where(
|
|
100
|
+
necrotic,
|
|
101
|
+
host * mx.array(0.2, dtype=mx.float32),
|
|
102
|
+
target,
|
|
103
|
+
)
|
|
104
|
+
updated = mx.where(avid, target, activity)
|
|
105
|
+
if lesion.spillover_fwhm_mm > 0.0:
|
|
106
|
+
excess = mx.where(avid, updated - host, mx.zeros_like(updated))
|
|
107
|
+
spilled = gaussian_blur(
|
|
108
|
+
excess,
|
|
109
|
+
(
|
|
110
|
+
lesion.spillover_fwhm_mm,
|
|
111
|
+
lesion.spillover_fwhm_mm,
|
|
112
|
+
lesion.spillover_fwhm_mm,
|
|
113
|
+
),
|
|
114
|
+
spacing_mm,
|
|
115
|
+
mx,
|
|
116
|
+
)
|
|
117
|
+
updated = mx.where(avid, host, activity) + spilled
|
|
118
|
+
result = mx.maximum(updated, mx.array(0.0, dtype=mx.float32))
|
|
119
|
+
mx.eval(result)
|
|
120
|
+
return result
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _label_mask(ids: array, labels: tuple[int, ...], mx: FdgRuntime) -> array:
|
|
124
|
+
mask = mx.zeros(ids.shape, dtype=mx.bool_)
|
|
125
|
+
for label in labels:
|
|
126
|
+
mask = mx.logical_or(mask, ids == label)
|
|
127
|
+
return mask
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _host_map(
|
|
131
|
+
ids: array,
|
|
132
|
+
organ: FdgOrganProfile,
|
|
133
|
+
lesion: FdgLesionProfile,
|
|
134
|
+
mx: FdgRuntime,
|
|
135
|
+
) -> array:
|
|
136
|
+
host = mx.zeros(ids.shape, dtype=mx.float32)
|
|
137
|
+
for label, tissue in lesion.host_tissue.items():
|
|
138
|
+
value = mx.array(organ.tissues[tissue].suv_mean, dtype=mx.float32)
|
|
139
|
+
host = mx.where(ids == label, value, host)
|
|
140
|
+
return host
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _necrosis_mask(avid: array, fraction: float, mx: FdgRuntime) -> array:
|
|
144
|
+
remaining = avid.astype(mx.float32)
|
|
145
|
+
# The mask is float32, so .item() returns a Python float; the cast only narrows the
|
|
146
|
+
# type for the checker.
|
|
147
|
+
core_target = float(cast(float, mx.sum(remaining).item())) * fraction
|
|
148
|
+
if core_target <= 0.0:
|
|
149
|
+
raise InvalidInputError("necrosis_fraction leaves no remaining lesion voxels")
|
|
150
|
+
while float(cast(float, mx.sum(remaining).item())) > core_target:
|
|
151
|
+
eroded = _erode(remaining, mx)
|
|
152
|
+
eroded_count = float(cast(float, mx.sum(eroded).item()))
|
|
153
|
+
current = float(cast(float, mx.sum(remaining).item()))
|
|
154
|
+
if eroded_count <= 0.0 or eroded_count >= current:
|
|
155
|
+
raise InvalidInputError(
|
|
156
|
+
"necrosis_fraction requires a lesion large enough to erode to the "
|
|
157
|
+
"requested necrotic core fraction"
|
|
158
|
+
)
|
|
159
|
+
remaining = eroded
|
|
160
|
+
return mx.logical_and(avid, remaining >= mx.array(0.5, dtype=mx.float32))
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _erode(mask: array, mx: FdgRuntime) -> array:
|
|
164
|
+
volume = mask.astype(mx.float32)[None, ..., None]
|
|
165
|
+
weight = mx.ones((1, 3, 3, 3, 1), dtype=mx.float32)
|
|
166
|
+
padded = mx.pad(volume, [(0, 0), (1, 1), (1, 1), (1, 1), (0, 0)])
|
|
167
|
+
neighbor_sum = mx.conv3d(padded, weight)
|
|
168
|
+
# A voxel survives only if all 27 voxels of its 3x3x3 box are set; 26.5 avoids
|
|
169
|
+
# an exact float comparison against 27.
|
|
170
|
+
return (neighbor_sum[0, ..., 0] >= mx.array(26.5, dtype=mx.float32)).astype(mx.float32)
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Structural (duck-typed) profile inputs for activity, scanner and lesion settings.
|
|
2
|
+
|
|
3
|
+
The package does not ship profile data, validate profile values or read profile
|
|
4
|
+
files. Callers pass any object with these attributes. Label IDs are MAISI label
|
|
5
|
+
IDs (the NV-Generate/MAISI label vocabulary); SUV values follow the body-weight
|
|
6
|
+
convention but no weight or dose normalization is applied here.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from collections.abc import Mapping
|
|
12
|
+
from typing import Protocol
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class TissueActivity(Protocol):
|
|
16
|
+
"""Activity distribution for one tissue class.
|
|
17
|
+
|
|
18
|
+
Attributes:
|
|
19
|
+
suv_mean: Mean SUV of the tissue.
|
|
20
|
+
suv_std: Standard deviation of the per-voxel Gaussian SUV noise, in SUV.
|
|
21
|
+
maisi_labels: MAISI label IDs belonging to this tissue.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
@property
|
|
25
|
+
def suv_mean(self) -> float: ...
|
|
26
|
+
@property
|
|
27
|
+
def suv_std(self) -> float: ...
|
|
28
|
+
@property
|
|
29
|
+
def maisi_labels(self) -> tuple[int, ...]: ...
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class FdgOrganProfile(Protocol):
|
|
33
|
+
"""Organ-level activity: tissue classes keyed by name.
|
|
34
|
+
|
|
35
|
+
``tissues`` must contain ``"unclassified_soft_tissue"``, which supplies the mean
|
|
36
|
+
and standard deviation for label IDs that no tissue lists. If a label ID is
|
|
37
|
+
listed by several tissues, the one later in ``tissues`` supplies the standard
|
|
38
|
+
deviation; the mean comes from ``lookup_table``.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def tissues(self) -> Mapping[str, TissueActivity]: ...
|
|
43
|
+
def lookup_table(self, size: int) -> tuple[float, ...]:
|
|
44
|
+
"""Return the mean SUV for label IDs ``0..size-1`` as a tuple of length ``size``."""
|
|
45
|
+
...
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class FdgScannerProfile(Protocol):
|
|
49
|
+
"""Image-space scanner approximation settings.
|
|
50
|
+
|
|
51
|
+
Attributes:
|
|
52
|
+
scatter_fraction: Unitless; with ``randoms_fraction``, sets a uniform offset
|
|
53
|
+
equal to the volume mean times their sum.
|
|
54
|
+
randoms_fraction: Unitless; see ``scatter_fraction``.
|
|
55
|
+
fwhm_mm: Gaussian blur FWHM in mm, one entry per array axis. A value of 0 skips
|
|
56
|
+
that axis.
|
|
57
|
+
counts_per_suv: Expected counts per voxel per unit SUV at ``count_level=1``.
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
@property
|
|
61
|
+
def scatter_fraction(self) -> float: ...
|
|
62
|
+
@property
|
|
63
|
+
def randoms_fraction(self) -> float: ...
|
|
64
|
+
@property
|
|
65
|
+
def fwhm_mm(self) -> tuple[float, float, float]: ...
|
|
66
|
+
@property
|
|
67
|
+
def counts_per_suv(self) -> float: ...
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class FdgLesionProfile(Protocol):
|
|
71
|
+
"""FDG-avid lesion settings.
|
|
72
|
+
|
|
73
|
+
Attributes:
|
|
74
|
+
avid_maisi_labels: MAISI label IDs whose voxels are treated as FDG-avid lesion.
|
|
75
|
+
host_tissue: Maps each avid label ID to a key of ``FdgOrganProfile.tissues``;
|
|
76
|
+
that tissue's ``suv_mean`` is the voxel's host (background) SUV. An avid
|
|
77
|
+
label with no entry has host SUV 0.
|
|
78
|
+
tumor_to_background: Lesion mean SUV as a multiple of the host SUV.
|
|
79
|
+
heterogeneity: Relative standard deviation of multiplicative Gaussian noise
|
|
80
|
+
on lesion voxels; 0 disables it.
|
|
81
|
+
necrosis_fraction: Target fraction (by voxel count, over all avid voxels) of
|
|
82
|
+
the lesion set to the necrotic core; 0 disables it.
|
|
83
|
+
spillover_fwhm_mm: FWHM in mm of an isotropic Gaussian that spreads the
|
|
84
|
+
lesion's excess SUV into neighboring voxels; 0 disables it.
|
|
85
|
+
"""
|
|
86
|
+
|
|
87
|
+
@property
|
|
88
|
+
def avid_maisi_labels(self) -> tuple[int, ...]: ...
|
|
89
|
+
@property
|
|
90
|
+
def host_tissue(self) -> Mapping[int, str]: ...
|
|
91
|
+
@property
|
|
92
|
+
def tumor_to_background(self) -> float: ...
|
|
93
|
+
@property
|
|
94
|
+
def heterogeneity(self) -> float: ...
|
|
95
|
+
@property
|
|
96
|
+
def necrosis_fraction(self) -> float: ...
|
|
97
|
+
@property
|
|
98
|
+
def spillover_fwhm_mm(self) -> float: ...
|
|
File without changes
|