Metadata-Version: 2.5
Name: mlxradiomics
Version: 0.1.0.dev10
Summary: Extract radiomics features and voxel maps on the Apple Silicon GPU with native MLX
Project-URL: Homepage, https://medmlx.org
Project-URL: Documentation, https://github.com/MedMLX/mlx-radiomics/blob/v0.1.0.dev10/README.md
Project-URL: Repository, https://github.com/MedMLX/mlx-radiomics
Project-URL: Issues, https://github.com/MedMLX/mlx-radiomics/issues
Project-URL: MedMLX, https://github.com/MedMLX/medmlx
Author: Joseph Sandoval, Alfredo Sandoval Jr.
License-Expression: Apache-2.0 AND MIT AND BSD-3-Clause AND CC-BY-4.0
License-File: LICENSE
License-File: THIRD_PARTY_NOTICES.md
Keywords: apple-silicon,feature-extraction,medical-imaging,metal,mlx,pyradiomics,radiomics
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: MacOS :: MacOS X
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Scientific/Engineering :: Image Processing
Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
Requires-Python: <3.14,>=3.13
Requires-Dist: medmlx-core==0.2.6
Requires-Dist: mlx==0.32.4; platform_system == 'Darwin' and platform_machine == 'arm64'
Requires-Dist: nibabel<6,>=5.3
Requires-Dist: numpy<3,>=2.0
Requires-Dist: pyyaml<7,>=6
Requires-Dist: scipy<2,>=1.16.3
Requires-Dist: simpleitk==2.5.6
Provides-Extra: io
Provides-Extra: lbp
Requires-Dist: scipy==1.18.1; extra == 'lbp'
Requires-Dist: trimesh==4.9.0; extra == 'lbp'
Description-Content-Type: text/markdown

<div align="center">

# mlx-radiomics

Extract radiomics features and voxel maps on the Apple Silicon GPU with native MLX.

[![PyPI](https://img.shields.io/pypi/v/mlxradiomics)](https://pypi.org/project/mlxradiomics/)
[![Python](https://img.shields.io/pypi/pyversions/mlxradiomics)](https://pypi.org/project/mlxradiomics/)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue)](https://github.com/MedMLX/mlx-radiomics/blob/v0.1.0.dev10/LICENSE)
[![Apple Silicon](https://img.shields.io/badge/Apple_Silicon-MLX-black?logo=apple)](https://github.com/ml-explore/mlx)
[![MedMLX](https://img.shields.io/badge/MedMLX-runtime-A51C30)](https://github.com/MedMLX/medmlx)

[MedMLX](https://github.com/MedMLX/medmlx)

[Scientific qualification](docs/scientific-qualification.md) · [Technical notes](docs/technical.md)

<img src="https://raw.githubusercontent.com/MedMLX/mlx-radiomics/v0.1.0.dev10/docs/showcase.png" alt="Radiomics voxel maps computed from an image and label mask" width="100%">

</div>

| Input | Output |
| :--- | :--- |
| Aligned image + label mask | ROI features or voxel maps |

## Use with MedMLX

The [MedMLX MCP server](https://github.com/MedMLX/medmlx/blob/main/docs/mcp.md) is the lowest-friction way to use this model. It installs this runtime, and lets an AI agent describe, check and run `mlxradiomics` for you.

```sh
uv tool install --python 3.13 "medmlx[vision,mcp]"
MEDMLX="$(uv tool dir --bin --color never)/medmlx"
mkdir -p "$HOME/medmlx-work"
claude mcp add --scope user medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-work"
```

For Codex, use `codex mcp add medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-work"`. Other MCP clients take the same command and arguments. The same install provides the `medmlx` CLI, for example `medmlx describe mlxradiomics`.

> **For AI agents:** prefer the MedMLX MCP tools (`list_models`, `describe_model`, `model_readiness`, `run_model`, `get_job`) over writing Python against this package.

## Install

```bash
uv venv --python 3.13
source .venv/bin/activate
uv pip install "mlxradiomics>=0.1.0.dev10"
```

## Run

With an aligned image and label-mask file:

```python
from mlxradiomics.medmlx import run

result = run(
    image_path="image.nii.gz",
    mask_path="mask.nii.gz",
    output_dir="features",
)
```

File I/O and YAML support are included in the standard installation. No model
weights are required.

### Inputs and outputs

| Argument | Meaning |
| --- | --- |
| `image_path` | One 2D or 3D image: `.nii`, `.nii.gz`, `.nrrd` or `.nhdr` |
| `mask_path` | Integer label mask. A geometry mismatch is refused unless the params enable `correctMask` or `resampledPixelSpacing` |
| `output_dir` | Directory for the outputs; created if missing |
| `params` or `params_path` | Optional PyRadiomics-style settings, as a mapping or a YAML file; pass one at most. Supports `setting`, `featureClass` and `imageType` |
| `label` | Optional mask label; defaults to the params label, or 1 |
| `voxel` | `False` for one value per feature; `True` for one map per feature |
| `overwrite` | `False` by default, which refuses to replace existing outputs |
| `temporary_dir` | Existing directory for voxel scratch; defaults to the system temporary directory |
| `max_temporary_mib` | Positive integer cap for logical voxel scratch, excluding staged/final outputs; requires voxel mode |

ROI mode writes `features.json` and `features.csv`. Voxel mode writes `features.json`
and one float32 NIfTI per feature under `maps/`, on the processed grid and zero outside
the ROI. The runner spools evaluated ROI batches and writes one disk-backed map at
a time. Scratch includes the compact ROI spool and one full float32 grid; its logical
size is checked before extraction and each batch. Mapped pages can remain in process
RSS, so the scratch cap is not a RAM cap. Output staging stays in the output
directory and has a separate free-space admission estimate.
Temporary disk use grows with ROI size and feature count;
the Python APIs keep maps in memory unless you supply `voxel_sink`.
Feature keys look like `original_glcm_Contrast`. Runner parameter files
accept the supported PyRadiomics `setting`, `featureClass` and `imageType` sections,
including derived images, `resampledPixelSpacing`, `interpolator`, `correctMask` and
`padDistance`. Unsupported settings, image types and per-image overrides are rejected
before extraction. Effective settings and processed/source grids are recorded in
`features.json`.

Undefined features are NaN, and float32 overflow can give infinity. `features.json`
uses report schema 2: finite values are JSON numbers, and non-finite values are
the strings `"NaN"`, `"Infinity"` or `"-Infinity"`, including in metadata. CSV files
and voxel maps retain their numerical values. SimpleITK reads stored non-finite
NIfTI voxels as zero, so read voxel maps with NiBabel. With detached NRRD or NIfTI
data files, existing outputs are never
replaced, even with `overwrite=True`; use a new output directory for each run.
Invalid inputs raise `InvalidInputError`; extraction failures raise
`ModelExecutionError`.

The runner returns a standard MedMLX `outputs` list: reports, ROI measurements
and voxel scalar fields with their coordinate space. Maps identify `image_path`
as their voxel grid only when its shape and geometry are unchanged. Cropped or
resampled maps use physical coordinates and retain their source and processed
geometry in the report. Grouped
paths are under `result["files"]` (`features_json`, `features_csv` and `maps`).
This replaces the earlier dictionary-valued `outputs` return field. The saved
feature report remains schema 2.

The runner refuses symbolic-link output files and overlapping calls using the
same output directory. Each run writes private staging files before publication;
if publication fails, previous outputs are restored and new outputs removed.
Readers can observe individual file replacements during publication, and the files
of one run are not published as one atomic set, so consume outputs only after the
run has returned. The directory
lock releases when a process exits; abrupt termination can leave private staging,
which the next run in that directory reclaims. A rollback failure retains recovery
copies at the path reported by the error.

### Features

`FEATURES` lists 190 selectable outputs, including all 116 non-deprecated
PyRadiomics names. The default remains the original 93 intensity and texture
outputs; request additions and shape features explicitly. A versioned manifest
maps 169 IBSI reference-valued public outputs to 167 scientific IDs. Five further
manual definitions, the oriented minimum bounding-box and minimum-volume enclosing
ellipsoid densities and the IVH area under the curve, are implemented without IBSI
reference values. Official-phantom comparisons retain the explicit AEE-area
reference exception. See the [scientific contract](docs/scientific-qualification.md) for
executed coverage and filter qualification.

| Family | Features | Modes |
| --- | ---: | --- |
| First order | 21 | ROI and voxel |
| Intensity histogram | 23 | ROI and voxel |
| GLCM | 26 | ROI and voxel |
| GLDM / NGLDM | 17 | ROI and voxel |
| NGTDM | 5 | ROI and voxel |
| GLRLM | 16 | ROI and voxel |
| GLSZM | 16 | ROI and voxel |
| GLDZM | 16 | ROI and voxel |
| Local intensity | 2 | 3D ROI |
| Intensity-volume histogram | 7 | ROI and voxel |
| Shape | 32 | 3D ROI |
| Shape2D | 9 | 2D ROI, or one slice of a 3D ROI |

`definition_profile="native"` preserves existing conventions; `"ibsi"` selects
explicit IBSI definitions, including sample-covariance shape axes. GLCM/GLRLM have six selectable aggregation modes;
GLSZM/GLDZM/NGTDM/GLDM have three. Fixed-count and fixed-width boundaries use exact
source-value comparisons. Local peaks use physical 1 cm³ spheres; IVH has its own
intensity calibration. The [technical examples](docs/technical.md#explicit-definitions-and-filters)
show profile, aggregation, IVH and filter settings in Python and parameter files.

### Python API

```python
from mlxradiomics import Settings, extract

# image and mask are aligned NumPy arrays; spacing follows their axis order.
result = extract(
    image, mask, spacing=(3.0, 1.0, 1.0),
    settings=Settings(label=2, bin_width=25, features=("firstorder_Mean", "glcm_Contrast")),
    voxel=True,
)
mean_map = result.features["original_firstorder_Mean"]
```

`FEATURES` lists every supported name. `Settings` also covers fixed-count binning
(`bin_count`), normalization, outlier removal, resegmentation, GLCM distances,
kernel radius and `masked_kernel`. With `masked_kernel=False`, neighbourhoods sample
the whole image but outputs stay inside the ROI. `scratch_mib` sets the batch size
from a scratch estimate; it is not a memory cap.

`extract_images` adds derived images through `TransformSettings`: square, square
root, logarithm, exponential, gradient, wavelets, LoG, LBP2D, LBP3D, mean,
Laws, Gabor and radial Simoncelli filters, IBSI sampled-kernel LoG, undecimated
separable wavelets, and Riesz transforms of a LoG or
Simoncelli base with optional local structure-tensor alignment. LBP3D needs
the `lbp` extra. Output keys carry the image prefix, such as
`wavelet-HHL_glcm_Contrast`. `extract_files` reads NIfTI or NRRD files and adds
`ImageSettings` for PyRadiomics-style resampling and mask correction. Its
`ibsi_interpolation=IbsiInterpolation(spacing=(3.0, 2.0, 2.0))` option selects the
centered IBSI grid and partial-volume mask through the Python file APIs; spacing
uses array axis order. Parameter files retain their PyRadiomics-style spatial
controls. Mismatched image and mask geometry requires explicit resampling or
mask correction.

Ordinary intensity resampling preserves fractional interpolated values regardless
of the source file's integer or floating storage. Masks retain integer labels.
LBP2D variance likewise retains fractional values for integer 3D inputs. Explicit
IBSI interpolation rounding remains controlled by its selected protocol.

`extract`, `extract_images` and `extract_files` accept `voxel_sink` in voxel mode
to consume evaluated batches without retaining full maps. Derived-image feature
names keep their prefixes; file-based batch coordinates follow the processed grid.
`export_images` and `export_files` add a supported disk-backed exporter: each
derived image gets its own bounded batch store, and one float32 NIfTI map at a
time is written through private staging and atomic publication. `run_study` runs
one or more cases and labels into separate `<case>/label-<n>` directories with an
explicit status for every combination.

### Execution metadata

`extract`, `extract_images` and `extract_files` return execution metadata; the
runner saves it in `features.json` under `details.execution`.

| Field | Meaning |
| --- | --- |
| `runtime` | Package versions, Python, platform, Metal device and supplied `MLX_ENABLE_TF32` setting; null means unset |
| `settings` | Effective feature, binning, normalization, resegmentation and neighborhood options |
| `array_shape`, `array_dtype`, `spacing` | Processed shape, supplied dtype and spacing in NumPy axis order |
| `roi_voxels`, `excluded_voxels` | Intensity ROI size and array voxels outside it |
| `feature_validity` | Sample counts for every fully prefixed feature, including streamed and derived-image results |
| `transforms` | Effective derived-image settings |
| `source_geometry`, `image_geometry` | Input and processed grids: shape/spacing in NumPy order, origin/direction in ITK LPS order |
| `image_settings` | Effective file resampling, interpolation, correction and padding options |

Per-feature counts distinguish `finite`, `valid_zero` (a subset of finite),
`nan`, `positive_infinity`, `negative_infinity` and `excluded` (uncomputed map
background stored as zero). Finite, NaN, infinite and excluded counts sum to the
map's voxel count; ROI features have one computed sample and no excluded samples.
Counts accumulate before export, including when `voxel_sink` consumes batches,
and retain every derived-image prefix. Top-level ROI counts describe the intensity
ROI; shape follows the separately recorded `resegment_shape` setting.

### Examples

Runnable scripts in [`examples/`](examples) cover the public workflows:

```bash
python examples/roi_from_files.py image.nii.gz mask.nii.gz outputs/roi --label 1
python examples/derived_voxel_export.py image.nii.gz mask.nii.gz outputs/maps --label 1
python examples/multilabel_study.py outputs/study \
  --case case-a image.nii.gz mask.nii.gz --labels 1 2
```

Resampling and advanced parameter files use the same runner:

```yaml
setting:
  binWidth: 25
  resampledPixelSpacing: [1.0, 1.0, 1.0]
  interpolator: sitkLinear
  padDistance: 1
imageType:
  Original: {}
  Wavelet:
    level: 1
featureClass:
  firstorder: [Mean, Entropy]
  glcm: [Contrast, JointEntropy]
```

Feature arithmetic is float32 on Metal; binning uses float64 on the host. Importing
the package does not import MLX. Computation needs Apple Silicon with Metal and has
no CPU fallback.

### Limits

- Shape and physical local-intensity features are ROI-only. Local intensity and
  intensity-dependent morphology require 3D input. Shape2D on a 3D input needs
  `force2d_axis` and an ROI in exactly one slice on that axis. `force2d_axis` counts NumPy axes.
- Voxel mode needs at least two ROI voxels.
- The default recursive LoG needs a 3D image with at least four samples per axis, large enough for the
  requested sigma. Each sigma/spacing ratio must be at most 200; singular or
  numerically unresolved derivative normalization raises a precision error.
- LBP3D needs 3D data and a masked kernel; integer images must be 8- or 16-bit.
  Samples too close to their binary threshold raise a precision error.
- GLCM direction validity is local to each ROI or voxel neighborhood. Empty
  directions are omitted; MCC averages directions with at least two occupied row
  and column gray levels and is NaN if none qualify. Map backgrounds remain 0.
- NGTDM counts only centers with at least one valid neighbor. No eligible centers
  gives NaN. Native singular ratios distinguish positive infinity from undefined
  `0/0`; the IBSI profile selects its explicit finite degenerate conventions.
- Paired NIfTI/Analyze headers named `.nii` or `.nii.gz` are rejected; convert them
  to single-file NIfTI or NRRD.
- Unsupported settings raise an error; nothing falls back to PyRadiomics.
- IBSI 2 agreement for Simoncelli responses requires
  `simoncelli_grid=FourierGrid.CENTERED` (parameter key `grid: centered`). The
  default DFT grid follows the manual's text; on it the published Simoncelli maps
  `8_a_2`/`8_a_3` and two IBSI 2 CT statistics fall outside the published tolerances.
- Simoncelli and Riesz filters are experimental. They use the MLX Metal FFT, and
  MLX 0.32.4 has an out-of-bounds FFT write that can silently modify a neighbouring
  array ([ml-explore/mlx#4733](https://github.com/ml-explore/mlx/issues/4733)). The
  fix is merged upstream but not yet in an MLX release; this package moves its pin
  once one is published. All other features do not use the FFT.
- Qualified hardware is Apple M5 Max with 128 GiB on macOS 27.2. Other Apple
  Silicon generations, 16–32 GiB machines and other macOS versions are untested.
- Mathematical definitions and independent regressions are described in
  [scientific qualification](docs/scientific-qualification.md).

Development setup is described in the [environment guide](environment/README.md).

## License

[Apache-2.0](https://github.com/MedMLX/mlx-radiomics/blob/v0.1.0.dev10/LICENSE). See [third-party notices](THIRD_PARTY_NOTICES.md), including CC BY 4.0 attribution
for adapted IBSI manifest definitions.
