mlxradiomics 0.1.0.dev4__tar.gz → 0.1.0.dev5__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.
Potentially problematic release.
This version of mlxradiomics might be problematic. Click here for more details.
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev5}/PKG-INFO +9 -13
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev5}/README.md +5 -9
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev5}/pyproject.toml +7 -9
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev5}/src/mlxradiomics/__init__.py +1 -1
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev5}/src/mlxradiomics/_typing.py +0 -63
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev5}/src/mlxradiomics/config.py +5 -1
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev5}/src/mlxradiomics/distributions.py +6 -4
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev5}/src/mlxradiomics/eigen.py +1 -1
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev5}/src/mlxradiomics/engine.py +8 -4
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev5}/src/mlxradiomics/histogram.py +1 -1
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev5}/src/mlxradiomics/io.py +8 -1
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev5}/src/mlxradiomics/lbp.py +2 -0
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev5}/src/mlxradiomics/medmlx.py +113 -20
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev5}/src/mlxradiomics/preprocessing.py +5 -4
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev5}/src/mlxradiomics/recursive_gaussian.py +3 -0
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev5}/src/mlxradiomics/reduction.py +2 -1
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev5}/src/mlxradiomics/shape.py +5 -3
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev5}/src/mlxradiomics/spatial.py +4 -2
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev5}/src/mlxradiomics/texture.py +8 -6
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev5}/src/mlxradiomics/transforms.py +6 -3
- mlxradiomics-0.1.0.dev4/src/mlxradiomics/fixtures.py +0 -165
- mlxradiomics-0.1.0.dev4/src/mlxradiomics/qualification.py +0 -205
- mlxradiomics-0.1.0.dev4/src/mlxradiomics/reference.py +0 -153
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev5}/.gitignore +0 -0
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev5}/LICENSE +0 -0
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev5}/THIRD_PARTY_NOTICES.md +0 -0
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev5}/src/mlxradiomics/_runtime.py +0 -0
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev5}/src/mlxradiomics/lbp3d.py +0 -0
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev5}/src/mlxradiomics/mesh_tables.json +0 -0
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev5}/src/mlxradiomics/pipeline.py +0 -0
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev5}/src/mlxradiomics/precision.py +0 -0
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev5}/src/mlxradiomics/spline.py +0 -0
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev5}/src/mlxradiomics/statistics.py +0 -0
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev5}/src/mlxradiomics/wavelet_tables.json +0 -0
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: mlxradiomics
|
|
3
|
-
Version: 0.1.0.
|
|
3
|
+
Version: 0.1.0.dev5
|
|
4
4
|
Summary: Apple Silicon Metal radiomics with bounded voxel batches.
|
|
5
5
|
License-Expression: Apache-2.0 AND MIT AND BSD-3-Clause
|
|
6
6
|
License-File: LICENSE
|
|
7
7
|
License-File: THIRD_PARTY_NOTICES.md
|
|
8
8
|
Classifier: Operating System :: MacOS :: MacOS X
|
|
9
9
|
Requires-Python: <3.15,>=3.13
|
|
10
|
-
Requires-Dist: medmlx-core==0.2.
|
|
10
|
+
Requires-Dist: medmlx-core==0.2.5
|
|
11
11
|
Requires-Dist: mlx==0.32.4; sys_platform == 'darwin' and platform_machine == 'arm64'
|
|
12
12
|
Requires-Dist: numpy<3,>=2.0
|
|
13
|
+
Requires-Dist: pyyaml<7,>=6
|
|
14
|
+
Requires-Dist: simpleitk==2.5.6
|
|
13
15
|
Provides-Extra: io
|
|
14
|
-
Requires-Dist: pyyaml<7,>=6; extra == 'io'
|
|
15
|
-
Requires-Dist: simpleitk==2.5.6; extra == 'io'
|
|
16
16
|
Provides-Extra: lbp
|
|
17
17
|
Requires-Dist: scipy==1.18.1; extra == 'lbp'
|
|
18
18
|
Requires-Dist: trimesh==4.9.0; extra == 'lbp'
|
|
@@ -22,12 +22,6 @@ Description-Content-Type: text/markdown
|
|
|
22
22
|
|
|
23
23
|
Extract radiomics features and voxel maps on the Apple Silicon GPU with native MLX.
|
|
24
24
|
|
|
25
|
-
[Docs](https://github.com/MedMLX/mlxradiomics/blob/main/docs/technical.md) · [MedMLX](https://github.com/MedMLX)
|
|
26
|
-
|
|
27
|
-

|
|
28
|
-
|
|
29
|
-
*Prewindowed CT liver ROI → local entropy, contrast and homogeneity maps.*
|
|
30
|
-
|
|
31
25
|
| Input | Output |
|
|
32
26
|
| :--- | :--- |
|
|
33
27
|
| Aligned image + label mask | ROI features or voxel maps |
|
|
@@ -39,7 +33,7 @@ Extract radiomics features and voxel maps on the Apple Silicon GPU with native M
|
|
|
39
33
|
```bash
|
|
40
34
|
uv venv --python 3.13
|
|
41
35
|
source .venv/bin/activate
|
|
42
|
-
uv pip install mlxradiomics
|
|
36
|
+
uv pip install "mlxradiomics==0.1.0.dev5"
|
|
43
37
|
```
|
|
44
38
|
|
|
45
39
|
With aligned `image` and `mask` NumPy arrays:
|
|
@@ -57,10 +51,12 @@ result = extract(
|
|
|
57
51
|
mean_map = result.features["original_firstorder_Mean"]
|
|
58
52
|
```
|
|
59
53
|
|
|
60
|
-
Use `voxel=False` for ROI features.
|
|
54
|
+
Use `voxel=False` for ROI features. File input and the MedMLX runner work with
|
|
55
|
+
the standard installation; SimpleITK and YAML support are included. No model
|
|
56
|
+
weights are required.
|
|
61
57
|
|
|
62
58
|
## License
|
|
63
59
|
|
|
64
|
-
|
|
60
|
+
Apache-2.0; license and third-party notices are included in the distribution.
|
|
65
61
|
|
|
66
62
|
For research and education. Outputs require human review.
|
|
@@ -2,12 +2,6 @@
|
|
|
2
2
|
|
|
3
3
|
Extract radiomics features and voxel maps on the Apple Silicon GPU with native MLX.
|
|
4
4
|
|
|
5
|
-
[Docs](https://github.com/MedMLX/mlxradiomics/blob/main/docs/technical.md) · [MedMLX](https://github.com/MedMLX)
|
|
6
|
-
|
|
7
|
-

|
|
8
|
-
|
|
9
|
-
*Prewindowed CT liver ROI → local entropy, contrast and homogeneity maps.*
|
|
10
|
-
|
|
11
5
|
| Input | Output |
|
|
12
6
|
| :--- | :--- |
|
|
13
7
|
| Aligned image + label mask | ROI features or voxel maps |
|
|
@@ -19,7 +13,7 @@ Extract radiomics features and voxel maps on the Apple Silicon GPU with native M
|
|
|
19
13
|
```bash
|
|
20
14
|
uv venv --python 3.13
|
|
21
15
|
source .venv/bin/activate
|
|
22
|
-
uv pip install mlxradiomics
|
|
16
|
+
uv pip install "mlxradiomics==0.1.0.dev5"
|
|
23
17
|
```
|
|
24
18
|
|
|
25
19
|
With aligned `image` and `mask` NumPy arrays:
|
|
@@ -37,10 +31,12 @@ result = extract(
|
|
|
37
31
|
mean_map = result.features["original_firstorder_Mean"]
|
|
38
32
|
```
|
|
39
33
|
|
|
40
|
-
Use `voxel=False` for ROI features.
|
|
34
|
+
Use `voxel=False` for ROI features. File input and the MedMLX runner work with
|
|
35
|
+
the standard installation; SimpleITK and YAML support are included. No model
|
|
36
|
+
weights are required.
|
|
41
37
|
|
|
42
38
|
## License
|
|
43
39
|
|
|
44
|
-
|
|
40
|
+
Apache-2.0; license and third-party notices are included in the distribution.
|
|
45
41
|
|
|
46
42
|
For research and education. Outputs require human review.
|
|
@@ -5,7 +5,7 @@ build-backend = "hatchling.build"
|
|
|
5
5
|
[project]
|
|
6
6
|
classifiers = ["Operating System :: MacOS :: MacOS X"]
|
|
7
7
|
name = "mlxradiomics"
|
|
8
|
-
version = "0.1.0.
|
|
8
|
+
version = "0.1.0.dev5"
|
|
9
9
|
description = "Apple Silicon Metal radiomics with bounded voxel batches."
|
|
10
10
|
readme = "README.md"
|
|
11
11
|
requires-python = ">=3.13,<3.15"
|
|
@@ -14,30 +14,28 @@ license-files = ["LICENSE", "THIRD_PARTY_NOTICES.md"]
|
|
|
14
14
|
dependencies = [
|
|
15
15
|
"numpy>=2.0,<3",
|
|
16
16
|
"mlx==0.32.4; sys_platform == 'darwin' and platform_machine == 'arm64'",
|
|
17
|
-
"medmlx-core==0.2.
|
|
17
|
+
"medmlx-core==0.2.5",
|
|
18
|
+
"SimpleITK==2.5.6",
|
|
19
|
+
"PyYAML>=6,<7",
|
|
18
20
|
]
|
|
19
21
|
|
|
20
22
|
[project.optional-dependencies]
|
|
21
|
-
io = [
|
|
23
|
+
io = [] # Compatibility extra; registered-runner I/O is included by default.
|
|
22
24
|
lbp = ["scipy==1.18.1", "trimesh==4.9.0"]
|
|
23
25
|
|
|
24
26
|
[project.entry-points."medmlx.models"]
|
|
25
27
|
mlxradiomics = "mlxradiomics.medmlx:MODEL"
|
|
26
28
|
|
|
27
|
-
[project.scripts]
|
|
28
|
-
mlxradiomics-qualify = "mlxradiomics.qualification:main"
|
|
29
29
|
|
|
30
30
|
[dependency-groups]
|
|
31
31
|
dev = [
|
|
32
32
|
"pytest==9.1.1",
|
|
33
33
|
"hypothesis>=6,<7",
|
|
34
|
-
"PyYAML>=6,<7",
|
|
35
34
|
"scikit-image==0.26.0",
|
|
36
35
|
"scipy==1.16.3",
|
|
37
36
|
"trimesh==4.9.0",
|
|
38
37
|
"ruff==0.15.21",
|
|
39
38
|
"pyright==1.1.414",
|
|
40
|
-
"SimpleITK==2.5.6",
|
|
41
39
|
"pyradiomics==3.0.1a1+medmlx.1",
|
|
42
40
|
]
|
|
43
41
|
|
|
@@ -48,7 +46,6 @@ packages = ["src/mlxradiomics"]
|
|
|
48
46
|
allow-direct-references = true
|
|
49
47
|
|
|
50
48
|
[tool.uv.sources]
|
|
51
|
-
medmlx-core = { git = "https://github.com/MedMLX/medmlx.git", rev = "f98e0924f50228e2b9509474947b9672054b3217", subdirectory = "packages/core" }
|
|
52
49
|
pyradiomics = { path = "reference/pyradiomics" }
|
|
53
50
|
|
|
54
51
|
[tool.uv]
|
|
@@ -67,7 +64,7 @@ select = ["E", "F", "I", "UP", "B", "SIM"]
|
|
|
67
64
|
[tool.pyright]
|
|
68
65
|
include = ["scripts","src","tests","typings"]
|
|
69
66
|
stubPath = "typings"
|
|
70
|
-
extraPaths = ["src"]
|
|
67
|
+
extraPaths = ["src", "scripts", "tests"]
|
|
71
68
|
pythonVersion = "3.13"
|
|
72
69
|
typeCheckingMode = "strict"
|
|
73
70
|
enableTypeIgnoreComments = false
|
|
@@ -76,6 +73,7 @@ reportUnnecessaryTypeIgnoreComment = "error"
|
|
|
76
73
|
|
|
77
74
|
[tool.pytest.ini_options]
|
|
78
75
|
testpaths = ["tests"]
|
|
76
|
+
pythonpath = ["src", "tests"]
|
|
79
77
|
addopts = "-q"
|
|
80
78
|
|
|
81
79
|
[tool.ruff.lint.flake8-tidy-imports]
|
|
@@ -31,7 +31,7 @@ if TYPE_CHECKING:
|
|
|
31
31
|
from mlxradiomics.transforms import TransformSettings as TransformSettings
|
|
32
32
|
from mlxradiomics.transforms import feature_images as feature_images
|
|
33
33
|
|
|
34
|
-
__version__ = "0.1.0.
|
|
34
|
+
__version__ = "0.1.0.dev5"
|
|
35
35
|
|
|
36
36
|
_EXPORT_MODULES = {
|
|
37
37
|
"Result": "engine",
|
|
@@ -108,66 +108,3 @@ class VoxelMemory(TypedDict):
|
|
|
108
108
|
|
|
109
109
|
batch_size: int
|
|
110
110
|
scratch_estimate_bytes: int
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
class Comparison(TypedDict):
|
|
114
|
-
"""Per-feature comparison with the reference; ``max_absolute_error`` is over finite pairs."""
|
|
115
|
-
|
|
116
|
-
feature: str
|
|
117
|
-
passed: bool
|
|
118
|
-
compared_values: int
|
|
119
|
-
mismatches: int
|
|
120
|
-
max_absolute_error: float | None
|
|
121
|
-
reference_nan_count: int
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
class QualificationRecord(TypedDict):
|
|
125
|
-
"""One synthetic case run in ROI or voxel mode against the pinned PyRadiomics.
|
|
126
|
-
|
|
127
|
-
``median_speedup`` is the median PyRadiomics time divided by the median MLX time.
|
|
128
|
-
"""
|
|
129
|
-
|
|
130
|
-
case: str
|
|
131
|
-
synthetic: bool
|
|
132
|
-
voxel: bool
|
|
133
|
-
settings: SettingsPayload
|
|
134
|
-
spacing: tuple[float, ...]
|
|
135
|
-
shape: tuple[int, ...]
|
|
136
|
-
selected_voxels: int
|
|
137
|
-
comparison: list[Comparison]
|
|
138
|
-
passed: bool
|
|
139
|
-
pyradiomics_seconds: list[float]
|
|
140
|
-
mlx_seconds: list[float]
|
|
141
|
-
median_speedup: float
|
|
142
|
-
execution: ExecutionMetadata
|
|
143
|
-
mlx_gpu_peak_memory_bytes: int
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
class QualificationReport(TypedDict):
|
|
147
|
-
"""JSON report written by ``mlxradiomics-qualify`` (``schema_version`` 1)."""
|
|
148
|
-
|
|
149
|
-
schema_version: int
|
|
150
|
-
mlxradiomics_version: str
|
|
151
|
-
pyradiomics_commit: str
|
|
152
|
-
pyradiomics_version: str
|
|
153
|
-
mlx_version: str
|
|
154
|
-
numpy_version: str
|
|
155
|
-
python: str
|
|
156
|
-
platform: str
|
|
157
|
-
device: str
|
|
158
|
-
precision: str
|
|
159
|
-
histogram_method: str
|
|
160
|
-
workload: str
|
|
161
|
-
device_info: dict[str, str | int]
|
|
162
|
-
absolute_tolerance: float
|
|
163
|
-
relative_tolerance: float
|
|
164
|
-
passed: bool
|
|
165
|
-
records: list[QualificationRecord]
|
|
166
|
-
scope: str
|
|
167
|
-
performance_gate: str
|
|
168
|
-
ibsi_qualification: str
|
|
169
|
-
metal_qualification: str
|
|
170
|
-
reference_voxel_batch: int
|
|
171
|
-
reference_2d_representation: str
|
|
172
|
-
unsupported_cases: dict[str, str]
|
|
173
|
-
proposed_performance_targets: dict[str, float]
|
|
@@ -133,7 +133,10 @@ class Settings:
|
|
|
133
133
|
features: tuple[str, ...] = tuple(n for n in FEATURES if not n.startswith("shape"))
|
|
134
134
|
|
|
135
135
|
def validate(self, ndim: int) -> None:
|
|
136
|
-
"""
|
|
136
|
+
"""Check the supported settings and raise ``ValueError`` for detected violations.
|
|
137
|
+
|
|
138
|
+
When ``bin_count`` is set, ``bin_width`` is unused and is not validated.
|
|
139
|
+
This checks settings, not image contents or whether a resegmented ROI is nonempty.
|
|
137
140
|
|
|
138
141
|
Args:
|
|
139
142
|
ndim: Dimensionality of the image the settings will be applied to; only used
|
|
@@ -166,6 +169,7 @@ class Settings:
|
|
|
166
169
|
raise ValueError(f"unsupported features: {sorted(unsupported)}")
|
|
167
170
|
|
|
168
171
|
def _validate_preprocessing(self) -> None:
|
|
172
|
+
# Binning, normalization and resegmentation options.
|
|
169
173
|
if self.bin_count is not None and (
|
|
170
174
|
type(self.bin_count) is not int or not 1 <= self.bin_count <= self.max_gray_levels
|
|
171
175
|
):
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
"""Features computed from count matrices: GLDM, GLRLM, GLSZM and NGTDM.
|
|
2
2
|
|
|
3
|
-
Inputs
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
Inputs have a leading batch axis (one row per ROI or per voxel center). GLDM, GLRLM and
|
|
4
|
+
GLSZM matrices hold counts; NGTDM also includes sums of neighborhood differences, which
|
|
5
|
+
need not be integers. The formulas follow the PyRadiomics feature classes of the same
|
|
6
|
+
names; the tests compare them with PyRadiomics at rtol=atol=1e-4.
|
|
6
7
|
"""
|
|
7
8
|
|
|
8
9
|
from mlxradiomics._runtime import mx
|
|
@@ -27,7 +28,8 @@ def size_statistics(counts: mx.array, family: str) -> dict[str, mx.array]:
|
|
|
27
28
|
Returns:
|
|
28
29
|
Feature name without the family prefix mapped to a ``(batch,)`` float32 array.
|
|
29
30
|
``RunPercentage`` (GLRLM) and ``ZonePercentage`` (GLSZM) are included only for
|
|
30
|
-
those families.
|
|
31
|
+
those families. Empty count matrices have undefined normalized features; callers
|
|
32
|
+
must exclude inactive directions before aggregating them.
|
|
31
33
|
"""
|
|
32
34
|
counts = counts.astype(mx.float32)
|
|
33
35
|
total = sum_rows(counts)
|
|
@@ -68,7 +68,7 @@ def symmetric_eigenvalues(matrix: mx.array) -> mx.array:
|
|
|
68
68
|
|
|
69
69
|
The kernel runs one thread per matrix in float32 and does not check symmetry.
|
|
70
70
|
Iteration stops when the largest off-diagonal magnitude is at most ``1e-7`` times
|
|
71
|
-
the largest diagonal magnitude
|
|
71
|
+
the larger of the largest diagonal magnitude and ``1e-30``.
|
|
72
72
|
|
|
73
73
|
Args:
|
|
74
74
|
matrix: Float32 array ``(batch, n, n)``.
|
|
@@ -32,8 +32,9 @@ class Result:
|
|
|
32
32
|
"""Features and execution metadata from ``extract``.
|
|
33
33
|
|
|
34
34
|
``features`` maps ``original_<family>_<Name>`` to a Python float in ROI mode, or to a
|
|
35
|
-
float64 array of the image's shape in voxel mode
|
|
36
|
-
|
|
35
|
+
float64 array of the image's shape in voxel mode. Undefined features can be NaN;
|
|
36
|
+
even finite inputs can produce infinity when float32 feature arithmetic overflows.
|
|
37
|
+
Voxel maps contain 0 outside the ROI.
|
|
37
38
|
"""
|
|
38
39
|
|
|
39
40
|
features: Mapping[str, float | FloatArray]
|
|
@@ -445,7 +446,9 @@ def extract(
|
|
|
445
446
|
"""Extract original-image features from aligned arrays (NumPy axis order).
|
|
446
447
|
|
|
447
448
|
Host preprocessing bins in float64; feature arithmetic uses float32 on Metal.
|
|
448
|
-
|
|
449
|
+
Finite sampled inputs do not guarantee finite features: for example, float32
|
|
450
|
+
Energy can overflow on large intensities. This function does not resample or
|
|
451
|
+
filter images.
|
|
449
452
|
|
|
450
453
|
Args:
|
|
451
454
|
image: 2-D or 3-D integer or float array, in the image's own intensity units (HU
|
|
@@ -456,7 +459,8 @@ def extract(
|
|
|
456
459
|
non-shape features, bin width 25, label 1).
|
|
457
460
|
spacing: Voxel spacing per array axis, finite and positive, in mm for physical
|
|
458
461
|
results. Defaults to 1.0 per axis. It scales shape features and TotalEnergy
|
|
459
|
-
(
|
|
462
|
+
(the spacing product is voxel volume in 3-D, pixel area in 2-D); texture
|
|
463
|
+
features do not use it.
|
|
460
464
|
voxel: False for one value per feature over the ROI. True for a map per feature,
|
|
461
465
|
computed in a ``(2 * kernel_radius + 1)``-wide neighborhood around each ROI
|
|
462
466
|
voxel (shape features are unavailable).
|
|
@@ -31,7 +31,7 @@ def histogram(
|
|
|
31
31
|
|
|
32
32
|
Args:
|
|
33
33
|
left: Integer array ``(batch, pairs)`` of 1-based gray levels of the first voxel
|
|
34
|
-
of each pair.
|
|
34
|
+
of each pair. Valid-pair levels must be in ``1..ng``; this is not checked.
|
|
35
35
|
right: Same shape; gray levels of the second voxel.
|
|
36
36
|
valid: Boolean array of the same shape; pairs with False are not counted (their
|
|
37
37
|
gray levels may be 0).
|
|
@@ -68,6 +68,7 @@ def _require_volume_path(path: str | Path) -> Path:
|
|
|
68
68
|
|
|
69
69
|
|
|
70
70
|
def _read(path: str | Path, *, integer: bool) -> Volume:
|
|
71
|
+
# Shared reader: ``integer`` selects mask rules (integer labels) over image rules (finite).
|
|
71
72
|
import SimpleITK as sitk
|
|
72
73
|
|
|
73
74
|
source = _require_volume_path(path)
|
|
@@ -95,6 +96,8 @@ def _read(path: str | Path, *, integer: bool) -> Volume:
|
|
|
95
96
|
def read_image(path: str | Path) -> Volume:
|
|
96
97
|
"""Read a 2D/3D NIfTI or NRRD image preserving pixel type and physical geometry.
|
|
97
98
|
|
|
99
|
+
SimpleITK read errors propagate, including ``RuntimeError`` for unreadable files.
|
|
100
|
+
|
|
98
101
|
Raises:
|
|
99
102
|
ValueError: If the file is missing, has an unsupported suffix, is not a single-channel
|
|
100
103
|
2-D or 3-D volume, or contains non-finite values.
|
|
@@ -106,6 +109,8 @@ def read_image(path: str | Path) -> Volume:
|
|
|
106
109
|
def read_mask(path: str | Path) -> Volume:
|
|
107
110
|
"""Read a 2D/3D integer label mask preserving pixel type and physical geometry.
|
|
108
111
|
|
|
112
|
+
SimpleITK read errors propagate, including ``RuntimeError`` for unreadable files.
|
|
113
|
+
|
|
109
114
|
Raises:
|
|
110
115
|
ValueError: If the file is missing, has an unsupported suffix, is not a single-channel
|
|
111
116
|
2-D or 3-D volume, or has a non-integer pixel type.
|
|
@@ -118,7 +123,9 @@ def write_feature_map(path: str | Path, array: NDArray[np.float64], *, reference
|
|
|
118
123
|
"""Write one voxel-mode feature map as float32, reusing the reference volume's geometry.
|
|
119
124
|
|
|
120
125
|
The format follows the file suffix (for example ``.nii.gz``); missing parent
|
|
121
|
-
directories are created.
|
|
126
|
+
directories are created. The observed SimpleITK 2.5.6 NIfTI reader maps stored
|
|
127
|
+
NaN and infinities to zero on read-back, even though those values are present in
|
|
128
|
+
the written file; use a reader that preserves them when they matter.
|
|
122
129
|
|
|
123
130
|
Raises:
|
|
124
131
|
ValueError: If ``array`` does not have the shape of ``reference.array``.
|
|
@@ -26,6 +26,8 @@ class LBPMethod(StrEnum):
|
|
|
26
26
|
|
|
27
27
|
|
|
28
28
|
def _method_source(samples: int, method: LBPMethod) -> str:
|
|
29
|
+
# Metal statements that turn the raw bit ``code`` into the output ``value`` for ``method``.
|
|
30
|
+
# ``DEFAULT`` needs none (value stays the raw code).
|
|
29
31
|
if method == LBPMethod.UNIFORM:
|
|
30
32
|
return f"value = changes <= 2 ? ones : {samples + 1};"
|
|
31
33
|
if method == LBPMethod.NONROTATION_UNIFORM:
|
|
@@ -9,6 +9,7 @@ from __future__ import annotations
|
|
|
9
9
|
|
|
10
10
|
import csv
|
|
11
11
|
import dataclasses
|
|
12
|
+
import gzip
|
|
12
13
|
import json
|
|
13
14
|
import os
|
|
14
15
|
from collections.abc import Mapping
|
|
@@ -28,10 +29,11 @@ from mlxradiomics.io import (
|
|
|
28
29
|
write_feature_map,
|
|
29
30
|
)
|
|
30
31
|
|
|
31
|
-
# Registered through the ``medmlx.models`` entry point in pyproject.toml;
|
|
32
|
-
#
|
|
32
|
+
# Registered through the ``medmlx.models`` entry point in pyproject.toml; MedMLX
|
|
33
|
+
# calls ``run`` with an image path, mask path and output directory.
|
|
33
34
|
MODEL = {
|
|
34
35
|
"id": "mlxradiomics",
|
|
36
|
+
"requires_weights": False,
|
|
35
37
|
"label": "PyRadiomics-compatible radiomics feature extraction",
|
|
36
38
|
"task": "feature-extraction",
|
|
37
39
|
"run": "mlxradiomics.medmlx:run",
|
|
@@ -50,12 +52,16 @@ type JsonValue = bool | int | float | str | None | list["JsonValue"] | dict[str,
|
|
|
50
52
|
|
|
51
53
|
|
|
52
54
|
class RunOutputs(TypedDict):
|
|
55
|
+
"""Absolute paths written by a run; voxel runs set ``maps`` and leave ``features_csv`` None."""
|
|
56
|
+
|
|
53
57
|
features_json: str
|
|
54
58
|
features_csv: str | None
|
|
55
59
|
maps: dict[str, str]
|
|
56
60
|
|
|
57
61
|
|
|
58
62
|
class RunDetails(TypedDict):
|
|
63
|
+
"""Run metadata; ``shape`` and ``spacing`` follow the image array axis order."""
|
|
64
|
+
|
|
59
65
|
voxel: bool
|
|
60
66
|
label: int
|
|
61
67
|
shape: list[int]
|
|
@@ -113,6 +119,80 @@ def _check_geometry(image: Volume, mask: Volume, *, image_path: Path, mask_path:
|
|
|
113
119
|
)
|
|
114
120
|
|
|
115
121
|
|
|
122
|
+
def _reject_input_aliases(outputs: tuple[Path, ...], inputs: tuple[Path, ...]) -> None:
|
|
123
|
+
"""Refuse output paths resolving to, or hard-linked to, an input file."""
|
|
124
|
+
for output in outputs:
|
|
125
|
+
for source in inputs:
|
|
126
|
+
if output.resolve() == source.resolve() or (
|
|
127
|
+
output.exists() and output.samefile(source)
|
|
128
|
+
):
|
|
129
|
+
raise InvalidInputError(f"output aliases an input: {output}")
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _reject_output_aliases(outputs: tuple[Path, ...]) -> None:
|
|
133
|
+
"""Refuse outputs sharing a resolved path or an existing file identity."""
|
|
134
|
+
resolved: set[Path] = set()
|
|
135
|
+
identities: set[tuple[int, int]] = set()
|
|
136
|
+
for output in outputs:
|
|
137
|
+
path = output.resolve()
|
|
138
|
+
if path in resolved:
|
|
139
|
+
raise InvalidInputError(f"output aliases another output: {output}")
|
|
140
|
+
resolved.add(path)
|
|
141
|
+
if output.exists():
|
|
142
|
+
info = output.stat()
|
|
143
|
+
identity = (info.st_dev, info.st_ino)
|
|
144
|
+
if identity in identities:
|
|
145
|
+
raise InvalidInputError(f"output aliases another output: {output}")
|
|
146
|
+
identities.add(identity)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _has_detached_data(source: Path) -> bool:
|
|
150
|
+
"""Detect detached NRRD and NIfTI data by header, including compressed headers."""
|
|
151
|
+
try:
|
|
152
|
+
with (
|
|
153
|
+
gzip.open(source, "rb") if source.name.endswith(".gz") else source.open("rb")
|
|
154
|
+
) as header:
|
|
155
|
+
prefix = header.read(348)
|
|
156
|
+
if prefix.startswith(b"NRRD"):
|
|
157
|
+
header.seek(0)
|
|
158
|
+
for line in header:
|
|
159
|
+
if not line.strip():
|
|
160
|
+
break
|
|
161
|
+
field, separator, value = line.partition(b":")
|
|
162
|
+
if (separator and not value.startswith(b"=")
|
|
163
|
+
and field.strip().lower() in (b"data file", b"datafile")):
|
|
164
|
+
return True
|
|
165
|
+
return False
|
|
166
|
+
if prefix[344:348] in (b"n+1\0", b"ni1\0"):
|
|
167
|
+
return prefix[344:348] == b"ni1\0"
|
|
168
|
+
if prefix[4:8] in (b"n+2\0", b"ni2\0"):
|
|
169
|
+
return prefix[4:8] == b"ni2\0"
|
|
170
|
+
# SimpleITK also accepts Analyze 7.5 pairs renamed with a .nii suffix.
|
|
171
|
+
if prefix[:4] in (b"\x5c\x01\0\0", b"\0\0\x01\x5c"):
|
|
172
|
+
return True
|
|
173
|
+
except (OSError, EOFError) as error:
|
|
174
|
+
raise InvalidInputError(f"cannot inspect volume header: {source}") from error
|
|
175
|
+
raise InvalidInputError(f"cannot inspect volume header: {source}")
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _check_output_replacement(
|
|
179
|
+
existing: list[str], *, overwrite: bool, image: Path, mask: Path,
|
|
180
|
+
) -> None:
|
|
181
|
+
if not existing:
|
|
182
|
+
return
|
|
183
|
+
if not overwrite:
|
|
184
|
+
raise InvalidInputError(
|
|
185
|
+
f"outputs already exist: {', '.join(existing)}; pass overwrite=True to replace them"
|
|
186
|
+
)
|
|
187
|
+
# A detached image can reference output files or their hard links. Refuse
|
|
188
|
+
# all replacement rather than guessing every possible payload path.
|
|
189
|
+
if _has_detached_data(image) or _has_detached_data(mask):
|
|
190
|
+
raise InvalidInputError(
|
|
191
|
+
"cannot replace existing outputs with detached NRRD, NIfTI or Analyze inputs; "
|
|
192
|
+
"choose a new output directory"
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
|
|
116
196
|
def run(
|
|
117
197
|
*,
|
|
118
198
|
image_path: str | os.PathLike[str],
|
|
@@ -126,32 +206,44 @@ def run(
|
|
|
126
206
|
) -> RunResult:
|
|
127
207
|
"""Extract radiomics features from one NIfTI/NRRD image and label mask.
|
|
128
208
|
|
|
209
|
+
File I/O dependencies are included. No model weights or checkpoint directory are used.
|
|
210
|
+
|
|
129
211
|
Args:
|
|
130
212
|
image_path: 2D/3D ``.nii``, ``.nii.gz``, or ``.nrrd``/``.nhdr`` image.
|
|
131
|
-
mask_path:
|
|
132
|
-
origin and direction within a small tolerance); no resampling is done.
|
|
213
|
+
mask_path: An integer label mask sharing the image's shape and physical geometry
|
|
214
|
+
(spacing, origin and direction within a small tolerance); no resampling is done.
|
|
133
215
|
output_dir: Directory for the outputs; created if missing.
|
|
134
216
|
params: A PyRadiomics-style params mapping (``setting``/``featureClass``
|
|
135
217
|
sections); see :func:`mlxradiomics.io.settings_from_params` for the
|
|
136
218
|
supported subset. Mutually exclusive with ``params_path``.
|
|
137
219
|
params_path: A YAML file holding the same mapping.
|
|
138
|
-
label:
|
|
220
|
+
label: Optional mask-label override. ``None`` keeps the label from ``params`` or
|
|
221
|
+
``params_path``, or uses ``1`` if neither supplies a label.
|
|
139
222
|
voxel: Extract one feature map per voxel instead of one value per feature.
|
|
140
|
-
overwrite: Boolean permission to replace existing outputs instead of refusing
|
|
223
|
+
overwrite: Boolean permission to replace existing outputs instead of refusing;
|
|
224
|
+
outputs that alias the supplied image, mask or params paths are refused.
|
|
225
|
+
Outputs that alias one another are also refused. These are preflight
|
|
226
|
+
checks; they cannot prevent concurrent path changes, and writes are not atomic.
|
|
227
|
+
If either input is a detached NRRD, NIfTI or Analyze image, existing outputs
|
|
228
|
+
are never replaced, because they may alias a data file referenced by the header.
|
|
141
229
|
|
|
142
230
|
Returns:
|
|
143
231
|
``outputs.features_json`` always points to a metadata-plus-values (ROI) or
|
|
144
232
|
metadata-plus-map-paths (voxel) JSON file. ROI mode also writes
|
|
145
233
|
``features_csv``; voxel mode also writes one float32 NIfTI per feature at
|
|
146
234
|
``<output_dir>/maps/<feature>.nii.gz``, reusing the input image's geometry (zero
|
|
147
|
-
outside the ROI,
|
|
148
|
-
and spacing is taken from the image file, in mm.
|
|
235
|
+
outside the ROI, with nonfinite values possible inside). Feature keys are
|
|
236
|
+
``original_<family>_<Name>`` and spacing is taken from the image file, in mm.
|
|
237
|
+
Undefined or overflowed ROI scalars can be NaN or infinite; the JSON writer
|
|
238
|
+
emits Python's non-standard ``NaN`` and ``Infinity`` tokens for those values,
|
|
239
|
+
which strict JSON parsers may reject.
|
|
149
240
|
|
|
150
241
|
Raises:
|
|
151
|
-
InvalidInputError: An input file is missing or
|
|
152
|
-
geometry disagrees, params are invalid,
|
|
153
|
-
``overwrite`` is false or is not a boolean.
|
|
242
|
+
InvalidInputError: An input file is missing or invalid, image/mask
|
|
243
|
+
geometry disagrees, params are invalid, an output aliases a supplied input,
|
|
244
|
+
or outputs exist and ``overwrite`` is false or is not a boolean.
|
|
154
245
|
ModelExecutionError: Extraction itself failed.
|
|
246
|
+
RuntimeError: SimpleITK could not read an input volume.
|
|
155
247
|
"""
|
|
156
248
|
|
|
157
249
|
if type(overwrite) is not bool:
|
|
@@ -175,11 +267,12 @@ def run(
|
|
|
175
267
|
raise InvalidInputError(f"output_dir is not a directory: {directory}")
|
|
176
268
|
features_json = directory / FEATURES_JSON
|
|
177
269
|
features_csv = directory / FEATURES_CSV if not voxel else None
|
|
270
|
+
inputs = (source_image, source_mask, *((Path(params_path),) if params_path else ()))
|
|
271
|
+
fixed_outputs = (features_json,) if features_csv is None else (features_json, features_csv)
|
|
272
|
+
_reject_input_aliases(fixed_outputs, inputs)
|
|
273
|
+
_reject_output_aliases(fixed_outputs)
|
|
178
274
|
existing = [path.as_posix() for path in (features_json, features_csv) if path and path.exists()]
|
|
179
|
-
|
|
180
|
-
raise InvalidInputError(
|
|
181
|
-
f"outputs already exist: {', '.join(existing)}; pass overwrite=True to replace them"
|
|
182
|
-
)
|
|
275
|
+
_check_output_replacement(existing, overwrite=overwrite, image=source_image, mask=source_mask)
|
|
183
276
|
|
|
184
277
|
try:
|
|
185
278
|
result = extract(
|
|
@@ -193,13 +286,13 @@ def run(
|
|
|
193
286
|
map_paths = {
|
|
194
287
|
name: directory / MAPS_DIR / f"{name}.nii.gz" for name in result.features
|
|
195
288
|
} if voxel else {}
|
|
289
|
+
_reject_input_aliases(tuple(map_paths.values()), inputs)
|
|
290
|
+
_reject_output_aliases((*fixed_outputs, *map_paths.values()))
|
|
196
291
|
# Interrupted voxel runs may have maps without final features.json metadata.
|
|
197
292
|
existing_maps = [path.as_posix() for path in map_paths.values() if path.exists()]
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
"pass overwrite=True to replace them"
|
|
202
|
-
)
|
|
293
|
+
_check_output_replacement(
|
|
294
|
+
existing_maps, overwrite=overwrite, image=source_image, mask=source_mask,
|
|
295
|
+
)
|
|
203
296
|
|
|
204
297
|
directory.mkdir(parents=True, exist_ok=True)
|
|
205
298
|
details: RunDetails = {
|
|
@@ -106,20 +106,21 @@ def resegment_roi(
|
|
|
106
106
|
|
|
107
107
|
|
|
108
108
|
def _bin_edges(selected: NDArray[np.float64], settings: Settings) -> NDArray[np.float64]:
|
|
109
|
+
# Gray-level bin edges for the ROI intensities, from ``bin_count`` or else ``bin_width``.
|
|
109
110
|
if settings.bin_count is not None:
|
|
110
111
|
edges = np.histogram(selected, bins=settings.bin_count)[1]
|
|
111
112
|
# np.digitize would put the maximum in bin N + 1; shifting the last edge keeps it in
|
|
112
113
|
# bin N, as PyRadiomics does.
|
|
113
114
|
edges[-1] += 1
|
|
114
115
|
return edges
|
|
115
|
-
# Edges are multiples of bin_width counted from zero
|
|
116
|
-
# (PyRadiomics getBinEdges).
|
|
117
|
-
# minimum for negative values such as CT in HU.
|
|
116
|
+
# Edges are multiples of bin_width counted from zero with an exclusive stop two widths
|
|
117
|
+
# past the maximum (PyRadiomics getBinEdges). Floored modulo keeps the lowest edge at or
|
|
118
|
+
# below the minimum for negative values such as CT in HU.
|
|
118
119
|
low = selected.min() - selected.min() % settings.bin_width
|
|
119
120
|
high = selected.max() + 2 * settings.bin_width
|
|
120
121
|
if not np.isfinite(high) or (high - low) / settings.bin_width > settings.max_gray_levels + 2:
|
|
121
122
|
raise ValueError("gray-level range exceeds max_gray_levels; increase bin_width")
|
|
122
|
-
return np.arange(low, high, settings.bin_width)
|
|
123
|
+
return np.arange(low, high, settings.bin_width, dtype=np.float64)
|
|
123
124
|
|
|
124
125
|
|
|
125
126
|
def prepare_input(
|
|
@@ -49,6 +49,9 @@ def _numerator(sigma: float, order: int) -> tuple[float, ...]:
|
|
|
49
49
|
|
|
50
50
|
@lru_cache(maxsize=128)
|
|
51
51
|
def _coefficients(sigma: float, spacing: float, order: int) -> RecursiveCoefficients:
|
|
52
|
+
# Recursive-filter coefficients for ``sigma`` (physical units) on an axis with ``spacing``;
|
|
53
|
+
# the filter works in voxels, so sigma is divided by spacing. ``order`` is 0 (smoothing)
|
|
54
|
+
# or 2 (second derivative).
|
|
52
55
|
sigmad = sigma / spacing
|
|
53
56
|
e1, e2 = exp(-1.3932 / sigmad), exp(-1.3732 / sigmad)
|
|
54
57
|
c1, c2 = cos(0.6681 / sigmad), cos(2.0787 / sigmad)
|
|
@@ -51,7 +51,8 @@ def sum_rows(values: mx.array) -> mx.array:
|
|
|
51
51
|
Array ``(batch,)`` of the same dtype.
|
|
52
52
|
|
|
53
53
|
Raises:
|
|
54
|
-
ValueError: If the dtype is not float32 or int32.
|
|
54
|
+
ValueError: If a row has more than one element and the dtype is not float32 or int32.
|
|
55
|
+
Singleton rows are returned without invoking the dtype-checked reduction kernel.
|
|
55
56
|
"""
|
|
56
57
|
values = mx.reshape(values, (values.shape[0], -1))
|
|
57
58
|
while values.shape[1] > 1:
|