mlxradiomics 0.1.0.dev4__tar.gz → 0.1.0.dev6__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.dev6/PKG-INFO +66 -0
- mlxradiomics-0.1.0.dev6/README.md +45 -0
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev6}/pyproject.toml +8 -9
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev6}/src/mlxradiomics/__init__.py +1 -1
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev6}/src/mlxradiomics/_typing.py +0 -63
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev6}/src/mlxradiomics/config.py +5 -1
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev6}/src/mlxradiomics/distributions.py +6 -4
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev6}/src/mlxradiomics/eigen.py +1 -1
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev6}/src/mlxradiomics/engine.py +8 -4
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev6}/src/mlxradiomics/histogram.py +1 -1
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev6}/src/mlxradiomics/io.py +55 -8
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev6}/src/mlxradiomics/lbp.py +2 -0
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev6}/src/mlxradiomics/medmlx.py +115 -20
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev6}/src/mlxradiomics/preprocessing.py +5 -4
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev6}/src/mlxradiomics/recursive_gaussian.py +3 -0
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev6}/src/mlxradiomics/reduction.py +2 -1
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev6}/src/mlxradiomics/shape.py +5 -3
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev6}/src/mlxradiomics/spatial.py +6 -2
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev6}/src/mlxradiomics/texture.py +8 -6
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev6}/src/mlxradiomics/transforms.py +7 -3
- mlxradiomics-0.1.0.dev4/PKG-INFO +0 -66
- mlxradiomics-0.1.0.dev4/README.md +0 -46
- 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.dev6}/.gitignore +0 -0
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev6}/LICENSE +0 -0
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev6}/THIRD_PARTY_NOTICES.md +0 -0
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev6}/src/mlxradiomics/_runtime.py +0 -0
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev6}/src/mlxradiomics/lbp3d.py +0 -0
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev6}/src/mlxradiomics/mesh_tables.json +0 -0
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev6}/src/mlxradiomics/pipeline.py +0 -0
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev6}/src/mlxradiomics/precision.py +0 -0
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev6}/src/mlxradiomics/spline.py +0 -0
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev6}/src/mlxradiomics/statistics.py +0 -0
- {mlxradiomics-0.1.0.dev4 → mlxradiomics-0.1.0.dev6}/src/mlxradiomics/wavelet_tables.json +0 -0
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: mlxradiomics
|
|
3
|
+
Version: 0.1.0.dev6
|
|
4
|
+
Summary: Apple Silicon Metal radiomics with bounded voxel batches.
|
|
5
|
+
License-Expression: Apache-2.0 AND MIT AND BSD-3-Clause
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
License-File: THIRD_PARTY_NOTICES.md
|
|
8
|
+
Classifier: Operating System :: MacOS :: MacOS X
|
|
9
|
+
Requires-Python: <3.15,>=3.13
|
|
10
|
+
Requires-Dist: medmlx-core==0.2.5
|
|
11
|
+
Requires-Dist: mlx==0.32.4; sys_platform == 'darwin' and platform_machine == 'arm64'
|
|
12
|
+
Requires-Dist: nibabel<6,>=5.3
|
|
13
|
+
Requires-Dist: numpy<3,>=2.0
|
|
14
|
+
Requires-Dist: pyyaml<7,>=6
|
|
15
|
+
Requires-Dist: simpleitk==2.5.6
|
|
16
|
+
Provides-Extra: io
|
|
17
|
+
Provides-Extra: lbp
|
|
18
|
+
Requires-Dist: scipy==1.18.1; extra == 'lbp'
|
|
19
|
+
Requires-Dist: trimesh==4.9.0; extra == 'lbp'
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# mlxradiomics
|
|
23
|
+
|
|
24
|
+
Extract radiomics features and voxel maps on the Apple Silicon GPU with native MLX.
|
|
25
|
+
|
|
26
|
+
| Input | Output |
|
|
27
|
+
| :--- | :--- |
|
|
28
|
+
| Aligned image + label mask | ROI features or voxel maps |
|
|
29
|
+
|
|
30
|
+
**Apple Silicon · Metal · Python 3.13 / 3.14** · [uv](https://docs.astral.sh/uv/)
|
|
31
|
+
|
|
32
|
+
## Quick start
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
uv venv --python 3.13
|
|
36
|
+
source .venv/bin/activate
|
|
37
|
+
uv pip install "mlxradiomics==0.1.0.dev5"
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## MedMLX runner
|
|
41
|
+
|
|
42
|
+
With an aligned image and label-mask file:
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
from mlxradiomics.medmlx import run
|
|
46
|
+
|
|
47
|
+
result = run(
|
|
48
|
+
image_path="image.nii.gz",
|
|
49
|
+
mask_path="mask.nii.gz",
|
|
50
|
+
output_dir="features",
|
|
51
|
+
)
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
File I/O and YAML support are included in the standard installation. No model
|
|
55
|
+
weights are required. The [API guide](docs/technical.md) covers label selection, parameter
|
|
56
|
+
files, voxel maps and the lower-level array interface.
|
|
57
|
+
|
|
58
|
+
## Documentation
|
|
59
|
+
|
|
60
|
+
[API, settings and validation](docs/technical.md)
|
|
61
|
+
|
|
62
|
+
## License
|
|
63
|
+
|
|
64
|
+
Apache-2.0; license and third-party notices are included in the distribution.
|
|
65
|
+
|
|
66
|
+
For research and education. Outputs require human review.
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# mlxradiomics
|
|
2
|
+
|
|
3
|
+
Extract radiomics features and voxel maps on the Apple Silicon GPU with native MLX.
|
|
4
|
+
|
|
5
|
+
| Input | Output |
|
|
6
|
+
| :--- | :--- |
|
|
7
|
+
| Aligned image + label mask | ROI features or voxel maps |
|
|
8
|
+
|
|
9
|
+
**Apple Silicon · Metal · Python 3.13 / 3.14** · [uv](https://docs.astral.sh/uv/)
|
|
10
|
+
|
|
11
|
+
## Quick start
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
uv venv --python 3.13
|
|
15
|
+
source .venv/bin/activate
|
|
16
|
+
uv pip install "mlxradiomics==0.1.0.dev5"
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## MedMLX runner
|
|
20
|
+
|
|
21
|
+
With an aligned image and label-mask file:
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
from mlxradiomics.medmlx import run
|
|
25
|
+
|
|
26
|
+
result = run(
|
|
27
|
+
image_path="image.nii.gz",
|
|
28
|
+
mask_path="mask.nii.gz",
|
|
29
|
+
output_dir="features",
|
|
30
|
+
)
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
File I/O and YAML support are included in the standard installation. No model
|
|
34
|
+
weights are required. The [API guide](docs/technical.md) covers label selection, parameter
|
|
35
|
+
files, voxel maps and the lower-level array interface.
|
|
36
|
+
|
|
37
|
+
## Documentation
|
|
38
|
+
|
|
39
|
+
[API, settings and validation](docs/technical.md)
|
|
40
|
+
|
|
41
|
+
## License
|
|
42
|
+
|
|
43
|
+
Apache-2.0; license and third-party notices are included in the distribution.
|
|
44
|
+
|
|
45
|
+
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.dev6"
|
|
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,29 @@ 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
|
+
"nibabel>=5.3,<6",
|
|
19
|
+
"SimpleITK==2.5.6",
|
|
20
|
+
"PyYAML>=6,<7",
|
|
18
21
|
]
|
|
19
22
|
|
|
20
23
|
[project.optional-dependencies]
|
|
21
|
-
io = [
|
|
24
|
+
io = [] # Compatibility extra; registered-runner I/O is included by default.
|
|
22
25
|
lbp = ["scipy==1.18.1", "trimesh==4.9.0"]
|
|
23
26
|
|
|
24
27
|
[project.entry-points."medmlx.models"]
|
|
25
28
|
mlxradiomics = "mlxradiomics.medmlx:MODEL"
|
|
26
29
|
|
|
27
|
-
[project.scripts]
|
|
28
|
-
mlxradiomics-qualify = "mlxradiomics.qualification:main"
|
|
29
30
|
|
|
30
31
|
[dependency-groups]
|
|
31
32
|
dev = [
|
|
32
33
|
"pytest==9.1.1",
|
|
33
34
|
"hypothesis>=6,<7",
|
|
34
|
-
"PyYAML>=6,<7",
|
|
35
35
|
"scikit-image==0.26.0",
|
|
36
36
|
"scipy==1.16.3",
|
|
37
37
|
"trimesh==4.9.0",
|
|
38
38
|
"ruff==0.15.21",
|
|
39
39
|
"pyright==1.1.414",
|
|
40
|
-
"SimpleITK==2.5.6",
|
|
41
40
|
"pyradiomics==3.0.1a1+medmlx.1",
|
|
42
41
|
]
|
|
43
42
|
|
|
@@ -48,7 +47,6 @@ packages = ["src/mlxradiomics"]
|
|
|
48
47
|
allow-direct-references = true
|
|
49
48
|
|
|
50
49
|
[tool.uv.sources]
|
|
51
|
-
medmlx-core = { git = "https://github.com/MedMLX/medmlx.git", rev = "f98e0924f50228e2b9509474947b9672054b3217", subdirectory = "packages/core" }
|
|
52
50
|
pyradiomics = { path = "reference/pyradiomics" }
|
|
53
51
|
|
|
54
52
|
[tool.uv]
|
|
@@ -67,7 +65,7 @@ select = ["E", "F", "I", "UP", "B", "SIM"]
|
|
|
67
65
|
[tool.pyright]
|
|
68
66
|
include = ["scripts","src","tests","typings"]
|
|
69
67
|
stubPath = "typings"
|
|
70
|
-
extraPaths = ["src"]
|
|
68
|
+
extraPaths = ["src", "scripts", "tests"]
|
|
71
69
|
pythonVersion = "3.13"
|
|
72
70
|
typeCheckingMode = "strict"
|
|
73
71
|
enableTypeIgnoreComments = false
|
|
@@ -76,6 +74,7 @@ reportUnnecessaryTypeIgnoreComment = "error"
|
|
|
76
74
|
|
|
77
75
|
[tool.pytest.ini_options]
|
|
78
76
|
testpaths = ["tests"]
|
|
77
|
+
pythonpath = ["src", "tests"]
|
|
79
78
|
addopts = "-q"
|
|
80
79
|
|
|
81
80
|
[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.dev6"
|
|
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).
|
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
"""NIfTI/NRRD volume I/O and PyRadiomics-style parameter loading for the runner.
|
|
2
2
|
|
|
3
|
-
Reading and writing use SimpleITK
|
|
4
|
-
|
|
3
|
+
Reading and writing use SimpleITK. NiBabel also checks NIfTI image values before
|
|
4
|
+
extraction because SimpleITK 2.5.6 replaces stored non-finite voxels with zero.
|
|
5
5
|
"""
|
|
6
6
|
|
|
7
7
|
from __future__ import annotations
|
|
8
8
|
|
|
9
9
|
import dataclasses
|
|
10
|
+
import gzip
|
|
10
11
|
from collections.abc import Mapping
|
|
11
12
|
from pathlib import Path
|
|
12
|
-
from typing import Literal, cast
|
|
13
|
+
from typing import Literal, Protocol, cast
|
|
13
14
|
|
|
14
15
|
import numpy as np
|
|
15
16
|
from medmlx_core import MissingDependencyError
|
|
@@ -21,6 +22,18 @@ from mlxradiomics.config import Settings
|
|
|
21
22
|
_VOLUME_SUFFIXES = (".nii", ".nii.gz", ".nrrd", ".nhdr")
|
|
22
23
|
|
|
23
24
|
|
|
25
|
+
class _NiftiImage(Protocol):
|
|
26
|
+
def get_fdata(self) -> NDArray[np.float64]:
|
|
27
|
+
"""Return scaled image values in NiBabel's default float64 precision."""
|
|
28
|
+
...
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class _NiftiReader(Protocol):
|
|
32
|
+
def load(self, filename: str) -> _NiftiImage:
|
|
33
|
+
"""Load an image with its on-disk voxel values intact."""
|
|
34
|
+
...
|
|
35
|
+
|
|
36
|
+
|
|
24
37
|
@dataclasses.dataclass(frozen=True)
|
|
25
38
|
class Volume:
|
|
26
39
|
"""A 2D/3D volume in this package's array-axis convention (NumPy order).
|
|
@@ -42,6 +55,7 @@ class Volume:
|
|
|
42
55
|
direction: tuple[float, ...]
|
|
43
56
|
|
|
44
57
|
def __post_init__(self) -> None:
|
|
58
|
+
"""Reject arrays, spacing, origin or direction outside the documented contract."""
|
|
45
59
|
ndim = self.array.ndim
|
|
46
60
|
if ndim not in (2, 3) or any(size == 0 for size in self.array.shape):
|
|
47
61
|
raise ValueError("volume must have a nonempty 2D or 3D shape")
|
|
@@ -67,10 +81,29 @@ def _require_volume_path(path: str | Path) -> Path:
|
|
|
67
81
|
return source
|
|
68
82
|
|
|
69
83
|
|
|
84
|
+
def _require_single_file_nifti(source: Path) -> None:
|
|
85
|
+
"""Reject paired NIfTI/Analyze headers disguised as single-file ``.nii`` inputs.
|
|
86
|
+
|
|
87
|
+
SimpleITK 2.5.6 reads header bytes as voxels for these names, so they must
|
|
88
|
+
be converted to a single-file image or a supported NRRD before extraction.
|
|
89
|
+
"""
|
|
90
|
+
with gzip.open(source, "rb") if source.name.endswith(".gz") else source.open("rb") as stream:
|
|
91
|
+
header = stream.read(348)
|
|
92
|
+
magic1, magic2 = header[344:348], header[4:8]
|
|
93
|
+
header1 = header[:4] in (b"\x5c\x01\0\0", b"\0\0\x01\x5c")
|
|
94
|
+
header2 = header[:4] in (b"\x1c\x02\0\0", b"\0\0\x02\x1c")
|
|
95
|
+
analyze = header1 and magic1 not in (b"n+1\0", b"ni1\0")
|
|
96
|
+
if (header1 and magic1 == b"ni1\0") or (header2 and magic2 == b"ni2\0") or analyze:
|
|
97
|
+
raise ValueError(f"detached NIfTI/Analyze input is unsupported: {source}")
|
|
98
|
+
|
|
99
|
+
|
|
70
100
|
def _read(path: str | Path, *, integer: bool) -> Volume:
|
|
101
|
+
# Shared reader: ``integer`` selects mask rules (integer labels) over image rules (finite).
|
|
71
102
|
import SimpleITK as sitk
|
|
72
103
|
|
|
73
104
|
source = _require_volume_path(path)
|
|
105
|
+
if source.name.endswith((".nii", ".nii.gz")):
|
|
106
|
+
_require_single_file_nifti(source)
|
|
74
107
|
image = sitk.ReadImage(source.as_posix())
|
|
75
108
|
if image.GetDimension() not in (2, 3):
|
|
76
109
|
raise ValueError(f"expected a 2D or 3D volume: {source}")
|
|
@@ -82,6 +115,14 @@ def _read(path: str | Path, *, integer: bool) -> Volume:
|
|
|
82
115
|
array = np.asarray(raw)
|
|
83
116
|
if not integer and not np.all(np.isfinite(array)):
|
|
84
117
|
raise ValueError(f"image contains non-finite voxels: {source}")
|
|
118
|
+
if not integer and source.name.endswith((".nii", ".nii.gz")):
|
|
119
|
+
import nibabel as nib
|
|
120
|
+
|
|
121
|
+
# ITK's NIfTI reader zeroes NaN and infinities before SimpleITK exposes
|
|
122
|
+
# the array; inspect the scaled source values with NiBabel as well.
|
|
123
|
+
values = cast(_NiftiReader, nib).load(source.as_posix()).get_fdata()
|
|
124
|
+
if not np.all(np.isfinite(values)):
|
|
125
|
+
raise ValueError(f"image contains non-finite voxels: {source}")
|
|
85
126
|
return Volume(
|
|
86
127
|
array=array,
|
|
87
128
|
# SimpleITK orders spacing/origin/direction x-first; this package's arrays
|
|
@@ -95,9 +136,11 @@ def _read(path: str | Path, *, integer: bool) -> Volume:
|
|
|
95
136
|
def read_image(path: str | Path) -> Volume:
|
|
96
137
|
"""Read a 2D/3D NIfTI or NRRD image preserving pixel type and physical geometry.
|
|
97
138
|
|
|
139
|
+
SimpleITK and NiBabel read errors propagate for unreadable files.
|
|
140
|
+
|
|
98
141
|
Raises:
|
|
99
|
-
ValueError: If the file is missing, has an unsupported suffix
|
|
100
|
-
2-D or 3-D volume, or contains non-finite values.
|
|
142
|
+
ValueError: If the file is missing, has an unsupported suffix or detached NIfTI
|
|
143
|
+
header, is not a single-channel 2-D or 3-D volume, or contains non-finite values.
|
|
101
144
|
"""
|
|
102
145
|
|
|
103
146
|
return _read(path, integer=False)
|
|
@@ -106,9 +149,11 @@ def read_image(path: str | Path) -> Volume:
|
|
|
106
149
|
def read_mask(path: str | Path) -> Volume:
|
|
107
150
|
"""Read a 2D/3D integer label mask preserving pixel type and physical geometry.
|
|
108
151
|
|
|
152
|
+
SimpleITK read errors propagate, including ``RuntimeError`` for unreadable files.
|
|
153
|
+
|
|
109
154
|
Raises:
|
|
110
|
-
ValueError: If the file is missing, has an unsupported suffix
|
|
111
|
-
2-D or 3-D volume, or has a non-integer pixel type.
|
|
155
|
+
ValueError: If the file is missing, has an unsupported suffix or detached NIfTI
|
|
156
|
+
header, is not a single-channel 2-D or 3-D volume, or has a non-integer pixel type.
|
|
112
157
|
"""
|
|
113
158
|
|
|
114
159
|
return _read(path, integer=True)
|
|
@@ -118,7 +163,9 @@ def write_feature_map(path: str | Path, array: NDArray[np.float64], *, reference
|
|
|
118
163
|
"""Write one voxel-mode feature map as float32, reusing the reference volume's geometry.
|
|
119
164
|
|
|
120
165
|
The format follows the file suffix (for example ``.nii.gz``); missing parent
|
|
121
|
-
directories are created.
|
|
166
|
+
directories are created. The observed SimpleITK 2.5.6 NIfTI reader maps stored
|
|
167
|
+
NaN and infinities to zero on read-back, even though those values are present in
|
|
168
|
+
the written file; use a reader that preserves them when they matter.
|
|
122
169
|
|
|
123
170
|
Raises:
|
|
124
171
|
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:
|