Runnable examples¶
These scripts generate their own two-by-two imzML data. No external datasets or notebook runtime is required.
Run commands from a repository checkout, or download both scripts into the same directory and omit examples/
from the commands. Use a fresh output directory for each run to avoid replacing previous data.
Spectra, images, and conversion¶
pip install "imzy[plot]"
python examples/quickstart.py /tmp/imzy-quickstart --plot
On Windows, use an output path such as example-output/quickstart.
Omit --plot to run without Matplotlib. The script writes sample.imzML / sample.ibd,
normalized.imzML / normalized.ibd, and optionally quickstart.png.
The input spectra contain [1, 2, 3] multiplied by pixel numbers 1 through 4.
The TIC vector is [6, 12, 18, 24]; the m/z 200 image is [[2, 4], [6, 8]].
TIC factors scale each spectrum to a total intensity of 15, the median input TIC.
The script reads the normalized output back to check this result.
"""Generate portable IMS data, extract images, normalize, and round-trip an export."""
from __future__ import annotations
import argparse
from pathlib import Path
import numpy as np
from imzy import IMZMLReader, IMZMLWriter, write_imzml
def create_sample(directory: Path) -> Path:
"""Write a two-by-two centroid dataset with three masses and known intensities."""
directory.mkdir(parents=True, exist_ok=True)
path = directory / "sample.imzML"
with IMZMLWriter(path, spectrum_type="centroid", ibd_mode="processed") as writer:
for index in range(4):
intensities = np.array([1.0, 2.0, 3.0]) * (index + 1)
writer.add_spectrum([100.0, 200.0, 300.0], intensities, (index % 2 + 1, index // 2 + 1))
return path
def run(directory: Path, *, plot: bool = False) -> Path:
"""Create sample data and a TIC-normalized copy, optionally saving a plot."""
path = create_sample(directory)
with IMZMLReader(path) as reader:
mzs, intensities = reader.get_spectrum(0)
tic = reader.get_tic(silent=True)
images = reader.get_ion_images([100.0, 200.0], tol=0.1, silent=True)
scales = reader.get_normalizations(silent=True)["TIC"]
normalized = images[1] * reader.reshape(scales)
output = write_imzml(reader, directory / "normalized.imzML", normalization="TIC", silent=True)
if plot:
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 3, figsize=(10, 3))
axes[0].plot(mzs, intensities)
axes[0].set(xlabel="m/z", ylabel="Intensity", title="Pixel 0")
for ax, image, title in zip(
axes[1:], [reader.reshape(tic), normalized], ["TIC", "TIC-normalized m/z 200"], strict=True
):
artist = ax.imshow(image)
ax.set(xlabel="x", ylabel="y", title=title)
fig.colorbar(artist, ax=ax)
fig.tight_layout()
fig.savefig(directory / "quickstart.png", dpi=150)
plt.close(fig)
with IMZMLReader(output) as converted:
# Each normalized pixel has the same total intensity for this proportional input.
np.testing.assert_allclose(converted.get_tic(silent=True), np.full(4, 15.0), rtol=1e-6)
print(f"Wrote {output}")
return output
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("output", type=Path, help="Directory for new datasets; use a fresh directory for each run.")
parser.add_argument("--plot", action="store_true", help="Save quickstart.png (requires imzy[plot]).")
args = parser.parse_args()
run(args.output, plot=args.plot)
Storage¶
Run each backend in a different output directory. HDF5 requires imzy[hdf5];
Zarr requires Python 3.11+ and imzy[zarr].
pip install "imzy[hdf5,zarr]"
python examples/storage.py /tmp/imzy-hdf5 --backend hdf5
python examples/storage.py /tmp/imzy-zarr --backend zarr
Keep quickstart.py alongside storage.py: it supplies the shared sample-data function.
The script checks the exported (4, 2) table against known intensities and reshapes it into (2, 2, 2) images.
"""Export sample ion tables to HDF5 and Zarr and verify their stored intensities."""
from __future__ import annotations
import argparse
from pathlib import Path
import numpy as np
from quickstart import create_sample
from imzy import IMZMLReader
def run(directory: Path, *, backend: str) -> Path:
"""Create sample data and verify one optional storage backend against known sums."""
path = create_sample(directory)
expected = np.arange(1, 5)[:, None] * np.array([1.0, 2.0])
with IMZMLReader(path) as reader:
if backend == "hdf5":
from imzy import H5CentroidsStore
output = reader.to_hdf5(directory / "centroids.h5", [100.0, 200.0], tol=0.1, silent=True)
store = H5CentroidsStore(output, mode="r")
table = np.column_stack([store.get_ion(100.0), store.get_ion(200.0)])
elif backend == "zarr":
from imzy import ZarrCentroidsStore
output = reader.to_zarr(directory / "centroids.zarr", [100.0, 200.0], tol=0.1, silent=True)
store = ZarrCentroidsStore(output)
table = store.get_ions(np.array([100.0, 200.0]))
else:
raise ValueError("Choose hdf5 or zarr.")
np.testing.assert_allclose(table, expected)
np.testing.assert_allclose(reader.reshape_batch(table), expected.T.reshape(2, 2, 2))
print(f"Verified {output}: {table.shape}")
return output
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("output", type=Path, help="Directory for new datasets; use a fresh directory for each run.")
parser.add_argument("--backend", choices=["hdf5", "zarr"], required=True)
args = parser.parse_args()
run(args.output, backend=args.backend)
Notebooks¶
The repository also contains exploratory notebooks for basic reading and plotting and imzML conversion. Those require your own input data and platform-specific readers. The scripts above are the automated smoke-tested examples.