Metadata-Version: 2.5
Name: imzy
Version: 0.4.0
Summary: imzy: A new reader interface to imzML and other imaging mass spectrometry formats.
Project-URL: homepage, https://github.com/vandeplaslab/imzy
Project-URL: repository, https://github.com/vandeplaslab/imzy
Project-URL: documentation, https://vandeplaslab.github.io/imzy/
Author-email: "Lukasz G. Migas" <lukas.migas@yahoo.com>
License: BSD 3-Clause License
License-File: LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Education
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Natural Language :: English
Classifier: Operating System :: MacOS
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: POSIX
Classifier: Operating System :: Unix
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
Classifier: Topic :: Scientific/Engineering :: Visualization
Classifier: Topic :: Utilities
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: click
Requires-Dist: ims-utils>=0.2.0
Requires-Dist: koyo>=0.3.7
Requires-Dist: natsort
Requires-Dist: numba
Requires-Dist: numpy
Requires-Dist: pluggy
Requires-Dist: scipy
Requires-Dist: tqdm
Requires-Dist: yoki5>=0.1.3
Provides-Extra: all
Requires-Dist: dask; (python_version >= '3.11') and extra == 'all'
Requires-Dist: h5py; extra == 'all'
Requires-Dist: hdf5plugin; extra == 'all'
Requires-Dist: matplotlib; extra == 'all'
Requires-Dist: zarr<4,>3; (python_version >= '3.11') and extra == 'all'
Provides-Extra: hdf5
Requires-Dist: h5py; extra == 'hdf5'
Requires-Dist: hdf5plugin; extra == 'hdf5'
Provides-Extra: plot
Requires-Dist: matplotlib; extra == 'plot'
Provides-Extra: test
Requires-Dist: dask; (python_version >= '3.11') and extra == 'test'
Requires-Dist: h5py; extra == 'test'
Requires-Dist: hdf5plugin; extra == 'test'
Requires-Dist: matplotlib; extra == 'test'
Requires-Dist: pytest-cov>=6.1.1; extra == 'test'
Requires-Dist: pytest>=8.3.5; extra == 'test'
Requires-Dist: zarr<4,>3; (python_version >= '3.11') and extra == 'test'
Provides-Extra: zarr
Requires-Dist: dask; (python_version >= '3.11') and extra == 'zarr'
Requires-Dist: zarr<4,>3; (python_version >= '3.11') and extra == 'zarr'
Description-Content-Type: text/markdown

# imzy

<div align="center">

[![Python Version](https://img.shields.io/pypi/pyversions/imzy.svg)](https://pypi.org/project/imzy/)
[![PyPI](https://img.shields.io/pypi/v/imzy.svg)](https://pypi.org/project/imzy)
[![Downloads](https://img.shields.io/pypi/dm/imzy.svg)](https://pypistats.org/packages/imzy)
[![Code coverage](https://codecov.io/gh/vandeplaslab/imzy/branch/main/graph/badge.svg)](https://codecov.io/gh/vandeplaslab/imzy)
[![Pre-commit](https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white)](https://github.com/vandeplaslab/imzy/blob/main/.pre-commit-config.yaml)
[![License](https://img.shields.io/github/license/vandeplaslab/imzy)](https://github.com/vandeplaslab/imzy/blob/main/LICENSE)

Read, inspect, process, and export imaging mass spectrometry datasets from Python.

</div>

imzy provides a common reader interface for imzML, Bruker, and Waters imaging mass spectrometry data. It includes tools
for reading spectra, extracting ion images, computing common normalization factors, exporting centroid tables to HDF5 or
Zarr, and converting supported inputs to imzML.

See the [documentation](https://vandeplaslab.github.io/imzy/) for the quickstart, usage guides, runnable examples,
API reference, and benchmarks.

## Installation

Install the core package with pip:

```bash
pip install imzy
```

Optional storage and plotting extras are available when you need them:

```bash
pip install "imzy[hdf5]"
pip install "imzy[zarr]"
pip install "imzy[plot]"
pip install "imzy[all]"
```

imzy requires Python 3.10 or newer.
The Zarr backend requires Python 3.11 or newer and Zarr 3 (`zarr>3,<4`). On Python 3.10, the `all` and `test`
extras include the core, HDF5, and plotting dependencies; Zarr support is omitted.

### Rust imzML backend

Release wheels include a Rust backend for memory-mapped spectrum access, pixel iteration, TIC calculation, and ion
images. Installing a wheel needs no Rust compiler. The XML parser and metadata cache remain in Python.

```python
from imzy import IMZMLReader

with IMZMLReader("sample.imzML", backend="auto") as reader:
    print(reader.backend)  # "rust" when available, otherwise "python"
    mzs, intensities = reader.get_spectrum(0)
    images = reader.get_ion_images([734.569, 760.585], ppm=10, silent=True)
```

Use `backend="rust"` to require the extension or `backend="python"` to select the fallback. Arrays are read-only;
call `.copy()` for writable data. Aligned arrays use views into the file and unaligned arrays are copied safely.
Keep the dataset unchanged while a reader, returned array, or iterator exists. `close()` releases the reader's mapping;
existing arrays and iterators keep their mappings alive, including any file locks held on Windows.

Source installations build the extension automatically when Cargo is available. To require it, install the stable
[Rust toolchain](https://rustup.rs/) and run:

```bash
IMZY_BUILD_RUST=1 pip install .
```

`IMZY_BUILD_RUST=0 pip install .` explicitly selects a compiler-free installation. PowerShell users can set
`$env:IMZY_BUILD_RUST = "1"` before running `pip install .`. Compilation failures are reported rather than silently
producing a fallback wheel. Supported input arrays are uncompressed little-endian float32, float64, int32, and int64.
Rayon parallelizes bulk extraction; set `RAYON_NUM_THREADS` before starting Python to limit its worker count.
Ion extraction expects m/z arrays in ascending order.

## Supported Formats

| Format | Support |
| --- | --- |
| imzML (`.imzML`/`.ibd`) | Windows, macOS, Linux |
| Bruker TSF/TDF/NeoFlex (`.d`) | Windows, Linux, macOS (with `pytsf`) |
| Bruker BAF (`.d` with `analysis.baf` + `*peaks.sqlite`) | Windows, Linux |
| Bruker rapifleX (folder with `.dat`, `_info.txt`, `_poslog.txt`) | Windows, macOS, Linux |
| Waters MassLynx (`.raw`) | Windows |

Bruker TDF ion mobility data can be read, but imzML export currently writes spectra collapsed to the m/z axis.

### Bruker on macOS

Bruker ships no timsdata library for macOS, so imzy reads `.d` data there with
[pytsf](https://github.com/VU-MSRC/timsMac), when it is installed:

```bash
pip install "pytsf @ git+https://github.com/VU-MSRC/timsMac.git@main"
```

Differences from Windows/Linux:

- TSF spectra are identical; m/z agrees to about 1 ppm.
- TDF intensities are the values stored in the file (the vendor library scales them by an undocumented per-file factor).
- TDF 1/K0 is approximate (about 0.3% with reference ions in the file, a few % otherwise); voltage conversion is not available.
- Recalibrated states (`use_recalibrated_state=True`) are not applied.

## Python Usage

```python
import numpy as np
from imzy import get_reader, write_imzml

path = "path/to/dataset"
reader = get_reader(path)

# Read one spectrum by pixel index.
mzs, intensities = reader.get_spectrum(0)

# Sum spectra across selected pixels.
summed_mzs, summed_intensities = reader.get_summed_spectrum(np.arange(100))

# Iterate through spectra. Each item is an (m/z, intensity) pair.
for mzs, intensities in reader.spectra_iter():
    ...

# Create a 2-D total ion current image.
tic_image = reader.reshape(reader.get_tic())

# Extract one ion image, using either a tolerance in Da or ppm.
ion_image = reader.get_ion_image(885.549, ppm=10)

# Extract many ion images in one pass.
target_mzs = [885.549, 886.552, 887.555]
images = reader.get_ion_images(target_mzs, tol=0.05)

# Export any imzy reader to imzML.
output_path = write_imzml(reader, "converted_dataset", silent=True)
```

Useful reader properties include `n_pixels`, `image_shape`, `x_coordinates`, `y_coordinates`, `xyz_coordinates`,
`mz_min`, `mz_max`, `is_centroid`, `rois`, `x_pixel_size`, and `y_pixel_size`.

## Command Line Usage

The `imzy` command can convert any supported input to imzML:

```bash
imzy convert path/to/input path/to/output --silent
```

Common options:

```bash
imzy convert path/to/input path/to/output \
  --spectrum-type auto \
  --ibd-mode auto \
  --normalization TIC \
  --overwrite
```

Use `--roi` to export a specific Bruker TSF/TDF/NeoFlex/BAF/rapifleX region of interest:

```bash
imzy convert path/to/bruker.d path/to/output --roi 0
```

Run `imzy convert --help` for the full list of options.

## Normalization and Batch Exports

Readers can compute normalization multipliers for common strategies such as TIC, RMS, median, percentile-filtered TIC,
and vector norms:

```python
normalizations = reader.get_normalizations(silent=True)
tic_scales = normalizations["TIC"]
```

For larger extraction jobs, write flat centroid tables to optional HDF5 or Zarr stores:

```python
target_mzs = [734.569, 760.585, 782.567]

hdf5_path = reader.to_hdf5("centroids.h5", target_mzs, ppm=10, silent=True)
zarr_path = reader.to_zarr("centroids.zarr", target_mzs, ppm=10, silent=True)
```

Install `imzy[hdf5]` or `imzy[zarr]` before using those storage backends.

## imzML Writing

Use `write_imzml` for reader-to-reader conversion, or `IMZMLWriter` when you need to add spectra manually:

```python
from imzy import IMZMLWriter

with IMZMLWriter(
    "manual_export", pixel_size=(50.0, 50.0), spectrum_type="centroid", ibd_mode="processed"
) as writer:
    writer.add_spectrum([100.0, 101.0], [10.0, 50.0], (1, 1))
    writer.add_spectrum([100.0, 101.0], [20.0, 30.0], (2, 1))
```

Writer options include `spectrum_type`, `ibd_mode`, `coordinate_origin`, `normalization`, `indices`, `overwrite`, and
`on_error`.

## Plugins

Custom readers can be registered through the `imzy.plugins` entry point. Implement the `imzy_reader` hook and return a
reader when the input path is supported:

```python
from __future__ import annotations

import typing as ty
from pathlib import Path

from koyo.typing import PathLike

from imzy import BaseReader
from imzy.hookspec import hook_impl


class YourReader(BaseReader):
    """Reader for your custom imaging format."""


@hook_impl
def imzy_reader(path: PathLike, reader_kwargs: dict[str, ty.Any]) -> BaseReader | None:
    """Return a reader when path points to a supported dataset."""
    if Path(path).suffix != ".yourformat":
        return None
    return YourReader(path, **reader_kwargs)
```

Then expose the module from your package metadata:

```toml
[project.entry-points."imzy.plugins"]
your_project_name = "your_project_name.imzy"
```

When `get_reader()` is called, imzy registers built-in readers and then loads installed plugins from this entry point.

## Development

Install an editable build, including the optional native extension:

```bash
uv pip install -e ".[test]"
```

Run the main checks before opening a change:

```bash
uv run pytest
cargo test --manifest-path rust/Cargo.toml
cargo fmt --manifest-path rust/Cargo.toml -- --check
```

See [CONTRIBUTING.md](CONTRIBUTING.md) for contribution guidelines and [SECURITY.md](SECURITY.md) for reporting security
issues.

### Performance benchmarks

The [benchmark website](https://vandeplaslab.github.io/imzy/benchmarks/) tracks Python and Rust performance across main revisions
using Airspeed Velocity (ASV). It covers reader initialization, spectra, ion images, TICs, normalizations, and imzML,
HDF5, and Zarr exports. Results publish after main changes and weekly; pull requests run correctness and smoke checks.

See the [benchmark guide](benchmarks/README.md) for setup, local runs, methodology, and GitHub Pages initialization.

After editing Rust sources, rerun the editable installation to rebuild the extension. The standalone backend comparison
also remains available:

```bash
uv run python scripts/benchmark_imzml.py --output benchmark.json
```

The benchmark generates varied continuous and processed spectra, warms Numba and the OS page cache, consumes complete
spectra, resets TIC caching, validates results, and alternates backend order. It reports median latency, pixel throughput,
and speedups. Use `--pixels`, `--points`, `--targets`, and `--repeats` to change the workload.

See the [benchmark report](benchmarks/imzml.md) for local measurements and their methodology.

### Documentation

Build the documentation in a separate environment:

```bash
uv venv .asv/docs-env --python 3.12
uv pip install --python .asv/docs-env/bin/python --group docs
.asv/docs-env/bin/python -m mkdocs build --strict
.asv/docs-env/bin/python -m mkdocs serve
```

On Windows, use `.asv/docs-env/Scripts/python.exe`. See the
[documentation development guide](https://vandeplaslab.github.io/imzy/development/) for examples, checks, and Pages setup.

## License

This project is licensed under the BSD 3-Clause License. See [LICENSE](LICENSE) for details.

## Citation

```bibtex
@misc{imzy,
  author = {Migas, Lukasz G. and contributors},
  title = {imzy: A reader and writer interface for imzML and other imaging mass spectrometry formats},
  year = {2022},
  publisher = {GitHub},
  journal = {GitHub repository},
  howpublished = {\url{https://github.com/vandeplaslab/imzy}}
}
```
