MaldiAMRKit
A comprehensive toolkit for MALDI-TOF mass spectrometry data preprocessing for antimicrobial resistance (AMR) prediction purposes
Installation • Features • Quick Start • Documentation • Tutorials • MaldiSuite • Contributing • Citing • License
Installation
pip install maldiamrkit
Install the full MaldiSuite
To install MaldiAMRKit together with MaldiBatchKit and MaldiDeepKit at compatible versions, install the maldisuite meta-package:
pip install maldisuite
Visit the MaldiSuite landing page at https://ettorerocchi.github.io/MaldiSuite/.
Optional: UMAP & combatlearn
pip install maldiamrkit[batch]
MaldiAMRKit has no batch corrector of its own. This extra adds umap-learn for UMAP exploratory plots, and combatlearn to use ComBat directly on a feature matrix. For batch correction built for MALDI-TOF spectra, see MaldiBatchKit.
Optional: extended mzML/mzXML support
pip install maldiamrkit[formats]
.mzML and .mzXML files are read out of the box (zlib-compressed or uncompressed arrays). This extra installs pyteomics with lxml, psims, and pynumpress, which additionally handle numpress-compressed arrays. pynumpress ships no wheels for Python 3.10, so numpress arrays need Python 3.11 or newer.
Development installation
git clone https://github.com/EttoreRocchi/MaldiAMRKit.git
cd MaldiAMRKit
pip install -e .[dev]
Features
Preprocessing
- Composable Pipeline: Build custom
PreprocessingPipelinefrom individual transformers (smoothing, baseline correction, normalisation, trimming), serialisable to JSON/YAML - Smoothing: Savitzky-Golay and moving-average filters
- Baseline Correction: SNIP, morphological top-hat, lower-convex-hull, and iterative rolling-median baselines
- Multiple Binning Strategies: Uniform, proportional, adaptive, and custom bin edges
- Quality Metrics: SNR estimation, MAD-based noise estimation, comprehensive quality reports, and alignment assessment
- Replicate Merging: Mean/median/weighted merging with correlation-based outlier detection
Alignment & detection
- Spectral Alignment: Shift, linear, piecewise, DTW, quadratic, cubic, and LOWESS warping for both binned and raw full-resolution spectra. Spectra are first shifted and then aligned to the reference of the shifted spectra, a non-rigid warp is kept only when the matched peaks support it, and resampling preserves the total intensity (neither applies to DTW); spectra of several species are best aligned one species at a time
- Peak Detection: Local maxima and persistent homology methods
- Peak Sets:
PeakSet/PeakListrepresent each spectrum as a variable-length(m/z, intensity)set for peak-set models, viaMaldiPeakDetector.transform_peaklist()on binned spectra orcreate_peakset_input()at full m/z resolution; extraction is stateless per spectrum, so results are cacheable without leakage - Fit-Free Peak Alignment:
align_peaks()warps a peak set onto caller-supplied reference peaks, which the caller estimates on the training split (for exampleRawWarping(...).fit(X_train).ref_peaks_mz_; a reference built with test spectra leaks)
Extensibility
- Component Registries: Plug your own components into the name-dispatched machinery -
register_spectral_metric()for distance metrics (usable inspectral_distance,pairwise_distances, andDriftMonitor),register_transformer()to makePreprocessingPipelineconfigs holding custom transformers round-trip through JSON/YAML, andregister_binning_method()for custom bin edges - Discovery & Safety:
list_spectral_metrics(),list_transformers(),list_binning_methods()report what is registered; built-ins are replaced only with an explicitoverride=True, and unregistering an overridden built-in restores the default
Evaluation
- AMR Metrics: VME, ME, sensitivity, specificity, categorical agreement, and
amr_classification_reportfollowing EUCAST conventions mic_regression_report: RMSE in log2 dilutions, essential agreement (±1 dilution), and categorical agreement after re-binning to S/I/R - the regression counterpart toamr_classification_report- Stratified Splitting: Species-drug stratified and case-based (patient-grouped) splitting to prevent data leakage
- Group-Aware CV:
MaldiSet.groups/isolate_ids()derive per-isolate labels (DRIAMS_MALDI<N>replicates stripped by default, or read from a metadata column) to pass asgroups=to splitters likeStratifiedGroupKFold, keeping replicates of one isolate on the same side of a split
Susceptibility (MIC encoding & breakpoints)
MICEncoder: Convert raw MIC strings intolog2(MIC)regression targets plus S/I/R categories and ATU flags in a single passBreakpointTable: Clinical breakpoint tables (19 EUCAST versions between v1.0 and v16.0 bundled) loaded by version, year, latest, or custom YAMLLabelEncoder: Map R/I/S to binary with configurable intermediate handling (moved frommaldiamrkit.evaluationin v0.15)
Differential analysis
DifferentialAnalysis: Per-bin statistical testing (Mann-Whitney U, Welch's t-test) between resistant and susceptible groups, with multiple-testing correction, log2 fold change, and Cohen's d effect size- Peak Ranking:
top_peaks()by adjusted p-value,significant_peaks()with fold-change and p-value thresholds,compare_drugs()for multi-drug boolean significance matrices (to select features for a classifier, rank peaks inside each training fold) - AMR-Aware Plots:
plot_volcano(),plot_manhattan()along the m/z axis, andplot_drug_comparison()with binary heatmap or UpSet-style intersection view
Drift monitoring
DriftMonitor: Anchor a baseline on early timestamps (default: first 20%) and track temporal drift via three complementary views - reference similarity of per-window median spectra, PCA centroid trajectory in a baseline-fitted PCA space, and Jaccard stability of top-k differential peaks over time- Trajectory Plots:
plot_reference_drift,plot_pca_drift,plot_peak_stability,plot_effect_size_drift
Spectral similarity
- Distances & Clustering:
spectral_distanceandpairwise_distanceswith built-in or registered metrics,cluster_spectrawith hierarchical, HDBSCAN, and k-medoids methods, silhouette scores, and metadata concordance - Plots:
plot_distance_heatmapandplot_dendrogram
Data management
- Dataset Building & Loading:
DatasetBuilderandDatasetLoaderwith pluggable layout adapters (FlatLayout,BrukerTreeLayout,DRIAMSLayout,MARISMaLayout) - Replicate Collapsing:
DRIAMSLayout(collapse_replicates=True)merges technical replicates (_MALDI<N>) to one row per isolate at load time via the activeduplicate_strategy - Bruker Format Support: Read Bruker flexAnalysis binary data (fid/1r + acqus) natively via
read_spectrum()on directories - Open Formats: Read
.mzMLand.mzXMLfiles (optionally gzipped) viaread_spectrum(),MaldiSpectrum, andFlatLayout(spectrum_ext=".mzML");pip install maldiamrkit[formats]addspyteomicsfor numpress-compressed arrays - MIC Parsing:
parse_mic_column()for parsing MIC strings with qualifiers and European decimals - Composable Filters:
SpeciesFilter,DrugFilter,QualityFilter,MetadataFiltercombinable with&/|/~operators - Spectrum Export: Save spectra to CSV, TXT, or mzML via
MaldiSpectrum.save()andMaldiSet.save_spectra()
Visualisation & tools
- Exploratory Plots: PCA, t-SNE, and UMAP scatter plots coloured by species, resistance phenotype, or any metadata column
- Batch Effect Correction: Not part of this package. Use
combatlearndirectly (pip install maldiamrkit[batch]) or MaldiBatchKit - CLI:
maldiamrkit preprocess,maldiamrkit quality, andmaldiamrkit buildfor batch processing - Parallel Processing: Multi-core support via
n_jobsparameter - ML-Ready: Direct integration with scikit-learn pipelines
Documentation
Full documentation is available at maldiamrkit.readthedocs.io.
Quick start
Load and preprocess a single spectrum
from maldiamrkit import MaldiSpectrum
# Load spectrum from file
spec = MaldiSpectrum("data/spectrum.txt")
# Preprocess: smoothing, baseline removal, normalization
spec.preprocess()
# Optional: bin to reduce dimensions
spec.bin(bin_width=3) # 3 Da bins
# Visualize
from maldiamrkit.visualization import plot_spectrum
plot_spectrum(spec, stage="binned")
Build a dataset from multiple spectra
from maldiamrkit import MaldiSet
# Load multiple spectra with metadata
data = MaldiSet.from_directory(
spectra_dir="data/spectra/",
meta_file="data/metadata.csv",
aggregate_by=dict(antibiotics="Drug", species="Escherichia coli"),
bin_width=3
)
# Access features and labels
X = data.X # Feature matrix
y = data.get_y_single("Drug") # Target labels
Machine learning pipeline
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
from maldiamrkit.alignment import Warping
from maldiamrkit.detection import MaldiPeakDetector
# Create ML pipeline
pipe = Pipeline([
("peaks", MaldiPeakDetector(binary=False, prominence=1e-4)),
("warp", Warping(method="shift")),
("scaler", StandardScaler()),
("clf", RandomForestClassifier(n_estimators=100, random_state=42))
])
# Cross-validation (with replicates, use StratifiedGroupKFold and groups=data.groups)
scores = cross_val_score(pipe, X, y, cv=5, scoring="accuracy")
print(f"CV Accuracy: {scores.mean():.3f} +/- {scores.std():.3f}")
For more examples covering alignment, filtering, evaluation, CLI usage, and more, see the Quickstart Guide and API Reference.
Tutorials
For more detailed examples, see the notebooks:
- Quick Start - Loading, preprocessing, binning, and quality assessment
- Peak Detection - Local maxima and persistent homology methods
- Alignment - Warping methods and alignment quality
- Evaluation - AMR metrics, label encoding, and stratified splitting
- Exploration - PCA, t-SNE, and UMAP visualisations, spectral similarity, and clustering
- Differential Analysis - R vs. S peak testing, volcano/Manhattan plots, and multi-drug comparison
- Drift Monitoring - Baseline-anchored drift detection: reference similarity, PCA trajectory, peak stability, and effect-size drift
- Susceptibility -
MICEncoder+BreakpointTablefor log2(MIC) regression targets, S/I/R categorisation with ATU, andmic_regression_reportevaluation - Peak Sets -
PeakSet/PeakListextraction, ranking and padding, caching, and fit-free peak alignment - Custom Components - registering a custom distance metric and a custom transformer end-to-end
Notebooks 01-03 and 08-10 run on the small example dataset bundled under data/ or are fully self-contained. Notebooks 04-07 need more samples and pull the real MALDI-Kleb-AI archive (Rocchi et al., 2026; Zenodo DOI 10.5281/zenodo.17405072) via the demo helper. By default the helper restricts the dataset to the Rome sub-cohort (~470 spectra, single acquisition centre, no batch correction required); the 370 MB tarball is cached under ~/.cache/maldiamrkit/ on first use.
MaldiSuite ecosystem
MaldiAMRKit is one of the three packages of the MaldiSuite ecosystem:
- MaldiAMRKit (this package) - data model (
MaldiSpectrum,MaldiSet), preprocessing, alignment, peak detection, differential analysis, and AMR-aware evaluation. - MaldiBatchKit - batch-effect correction and harmonisation for multi-centre / multi-instrument MALDI-TOF spectra.
- MaldiDeepKit - sklearn-compatible deep learning classifiers (MLP, CNN, ResNet, Transformer).
The three packages share the MaldiSet data model. Each can be used on its own, or combined with the others. Install the full suite with pip install maldisuite. Landing page: MaldiSuite.
Contributing
Pull requests, bug reports, and feature ideas are welcome. See the Contributing Guide for how to get started.
Citing
If you use MaldiAMRKit in your research, please cite:
Rocchi, E., Nicitra, E., Calvo, M. et al. Combining mass spectrometry and machine learning models for predicting Klebsiella pneumoniae antimicrobial resistance: a multicenter experience from clinical isolates in Italy. BMC Microbiol (2026). doi:10.1186/s12866-025-04657-2
See the full publications list for more papers using MaldiAMRKit.
License
This project is licensed under the MIT License. See the LICENSE file for details.
Acknowledgements
This toolkit is inspired by:
Weis, C., Cuénod, A., Rieck, B., et al. (2022). Direct antimicrobial resistance prediction from clinical MALDI-TOF mass spectra using machine learning. Nature Medicine, 28, 164-174. https://doi.org/10.1038/s41591-021-01619-9
Metadata
Release files for MaldiAMRKit 0.22.3
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| maldiamrkit-0.22.3.tar.gz | 266.2 kB | Without provenance | Details for maldiamrkit-0.22.3.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| maldiamrkit-0.22.3-py3-none-any.whl | Python 3 | none | any | Details for maldiamrkit-0.22.3-py3-none-any.whl |
Total release size: 559.6 kB
Release files / maldiamrkit-0.22.3.tar.gz
| Download URL | maldiamrkit-0.22.3.tar.gz |
|---|---|
| Size | 266.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
1a515126fe80198fe4abfd2d88029b6bf4b760f75ce4d3b0d6c97f2c573683f8
|
|
BLAKE2b-256 checksum How to use checksums |
1ca304083ebac86a0d08408ba822a76f2aa4b5c3ea20fa66df672e853676851b
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.13.18
|
Release files / maldiamrkit-0.22.3-py3-none-any.whl
| Download URL | maldiamrkit-0.22.3-py3-none-any.whl |
|---|---|
| Size | 293.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
9db30baf638b9c440ff7ad3ff8dbd85dbfd03b2be4eff6c909745f5cd2184836
|
|
BLAKE2b-256 checksum How to use checksums |
5404a295813434c412087121011ace283f482ff237ca4bd3d1f8d8da920a4e42
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.13.18
|
Security for MaldiAMRKit 0.22.3
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.