Python library for large-scale comparisons and processing of tandem mass spectral data


Keywords
similarity, measures, mass, spectrometry, fuzzy, matching, search, analysis, fuzzy-matching, fuzzy-search, mass-spectrometry, metabolomics, python3, similarity-measures
License
Apache-2.0
Install
pip install matchms==0.24.4

Documentation

fair-software.nl recommendations:

GitHub Badge License Badge Conda Badge Pypi Badge Research Software Directory Badge Zenodo Badge CII Best Practices Badge

Code quality checks:

Continuous integration workflow Continuous integration workflow Documentation Status Sonarcloud Quality Gate Sonarcloud Coverage

matchms

Matchms is a versatile open-source Python package developed for importing, processing, cleaning, and comparing mass spectrometry data (MS/MS). It facilitates the implementation of straightforward, reproducible workflows, transforming raw data from common mass spectra file formats into pre- and post-processed spectral data, and enabling large-scale spectral similarity comparisons.

The software supports a range of popular spectral data formats, including mzML, mzXML, msp, metabolomics-USI, MGF, and JSON. Matchms offers an array of tools for metadata cleaning and validation, alongside basic peak filtering, to ensure data accuracy and integrity. A key feature of matchms is its ability to apply various pairwise similarity measures for comparing extensive amounts of spectra. This encompasses not only common Cosine-related scores but also molecular fingerprint-based comparisons and other metadata-related assessments.

One of the strengths of matchms is its extensibility, allowing users to integrate custom similarity measures. Notable examples of spectrum similarity measures tailored for Matchms include Spec2Vec and MS2DeepScore. Additionally, Matchms enhances efficiency by using faster similarity measures for initial pre-selection and supports storing results in sparse data formats, enabling the comparison of several hundred thousands of spectra. This combination of features positions Matchms as a comprehensive tool for mass spectrometry data analysis.

If you use matchms in your research, please cite the following software papers:

F Huber, S. Verhoeven, C. Meijer, H. Spreeuw, E. M. Villanueva Castilla, C. Geng, J.J.J. van der Hooft, S. Rogers, A. Belloum, F. Diblen, J.H. Spaaks, (2020). matchms - processing and similarity evaluation of mass spectrometry data. Journal of Open Source Software, 5(52), 2411, https://doi.org/10.21105/joss.02411

de Jonge NF, Hecht H, van der Hooft JJJ, Huber F. (2023). Reproducible MS/MS library cleaning pipeline in matchms. ChemRxiv. Cambridge: Cambridge Open Engage; 2023, https://doi.org/10.26434/chemrxiv-2023-l44cm

Latest changes (matchms >= 0.18.0)

Pipeline class

To make typical matchms workflows (data import, processing, score computations) more accessible to users, matchms now offers a Pipeline class to handle complex workflows. This also allows to create, import, export, or modify workflows using yaml files. See code examples below (and soon: updated tutorial).

Sparse scores array

We realized that many matchms-based workflows aim to compare many-to-many spectra whereby not all pairs and scores are equally important. Often, for instance, it will be about searching similar or related spectra/compounds. This also means that often not all scores need to be stored (or computed). For this reason, we now shifted to a sparse handling of scores in matchms (that means: only storing actually computed, non-null values).

matchms code design

Documentation for users

For more extensive documentation see our readthedocs and our matchms introduction tutorial.

Installation

Prerequisites:

  • Python 3.8 - 3.11, (higher versions should work as well, but are not yet tested systematically)
  • Anaconda (recommended)

We recommend installing matchms in a new virtual environment to avoid dependency clashes

conda create --name matchms python=3.9
conda activate matchms
conda install --channel bioconda --channel conda-forge matchms

Alternatively, matchms can also be installed using pip. In the most basic version matchms will then come without rdkit so that several filter functions related to processing and cleaning chemical metadata will not run. To include rdkit install matchms as matchms[chemistry]:

pip install matchms  # simple install w/o rdkit
pip install matchms[chemistry]  # full install including rdkit

matchms ecosystem -> additional functionalities

Matchms functionalities can be complemented by additional packages. To date, we are aware of:

  • Spec2Vec an alternative machine-learning spectral similarity score that can simply be installed by pip install spec2vec and be imported as from spec2vec import Spec2Vec following the same API as the scores in matchms.similarity.
  • MS2DeepScore a supervised, deep-learning based spectral similarity score that can simply be installed by pip install ms2deepscore and be imported as from ms2deepscore import MS2DeepScore following the same API as the scores in matchms.similarity.
  • matchmsextras which contains additional functions to create networks based on spectral similarities, to run spectrum searchers against PubChem, or additional plotting methods.
  • MS2Query Reliable and fast MS/MS spectral-based analogue search, running on top of matchms.
  • memo a method allowing a Retention Time (RT) agnostic alignment of metabolomics samples using the fragmentation spectra (MS2) of their constituents.
  • RIAssigner a tool for retention index calculation for gas chromatography - mass spectrometry (GC-MS) data.
  • MSMetaEnhancer is a python package to collect mass spectral library metadata using various web services and computational chemistry packages.

(if you know of any other packages that are fully compatible with matchms, let us know!)

Introduction

To get started with matchms, we recommend following our matchms introduction tutorial.

Below is an example of using default filter steps for cleaning spectra, followed by calculating the Cosine score between mass Spectrums in the tests/testdata/pesticides.mgf file.

Below is a more advanced code example showing how you can make a specific pipeline for your needs.

Alternatively, in particular, if you need more room to add custom functions and steps, the individual steps can run without using the matchms Pipeline:

from matchms.importing import load_from_mgf
from matchms.filtering import default_filters, normalize_intensities
from matchms import calculate_scores
from matchms.similarity import CosineGreedy

# Read spectrums from a MGF formatted file, for other formats see https://matchms.readthedocs.io/en/latest/api/matchms.importing.html 
file = load_from_mgf("tests/testdata/pesticides.mgf")

# Apply filters to clean and enhance each spectrum
spectrums = []
for spectrum in file:
    # Apply default filter to standardize ion mode, correct charge and more.
    # Default filter is fully explained at https://matchms.readthedocs.io/en/latest/api/matchms.filtering.html .
    spectrum = default_filters(spectrum)
    # Scale peak intensities to maximum of 1
    spectrum = normalize_intensities(spectrum)
    spectrums.append(spectrum)

# Calculate Cosine similarity scores between all spectrums
# For other similarity score methods see https://matchms.readthedocs.io/en/latest/api/matchms.similarity.html .
scores = calculate_scores(references=spectrums,
                          queries=spectrums,
                          similarity_function=CosineGreedy())

# Matchms allows to get the best matches for any query using scores_by_query
query = spectrums[15]  # just an example
best_matches = scores.scores_by_query(query, 'CosineGreedy_score', sort=True)

# Print the calculated scores for each spectrum pair
for (reference, score) in best_matches[:10]:
    # Ignore scores between same spectra
    if reference is not query:
        print(f"Reference scan id: {reference.metadata['scans']}")
        print(f"Query scan id: {query.metadata['scans']}")
        print(f"Score: {score[0]:.4f}")
        print(f"Number of matching peaks: {score[1]}")
        print("----------------------------")

Different spectrum similarity scores

Matchms comes with numerous different scoring methods in matchms.similarity and can further seamlessly work with Spec2Vec or MS2DeepScore.

Code example:

Documentation for developers

Installation

To install matchms, do:

git clone https://github.com/matchms/matchms.git
cd matchms
conda create --name matchms-dev python=3.8
conda activate matchms-dev
# Install rdkit using conda, rest of dependencies can be installed with pip
conda install -c conda-forge rdkit
python -m pip install --upgrade pip
pip install --editable .[dev]  # if this won't work try "poetry install"

Run the linter with:

prospector

Automatically fix incorrectly sorted imports:

isort .

Files will be changed in place and need to be committed manually. If you only want to inspect the isort suggestions then simply run:

isort --check-only --diff .

Run tests (including coverage) with:

pytest

Conda package

The conda packaging is handled by a recipe at Bioconda.

Publishing to PyPI will trigger the creation of a pull request on the bioconda recipes repository Once the PR is merged the new version of matchms will appear on https://anaconda.org/bioconda/matchms

Flowchart

Flowchart of matchms workflow. Reference and query spectrums are filtered using the same set of set filters (here: filter A and filter B). Once filtered, every reference spectrum is compared to every query spectrum using the matchms.Scores object.

Flowchart of matchms workflow. Reference and query spectrums are filtered using the same set of set filters (here: filter A and filter B). Once filtered, every reference spectrum is compared to every query spectrum using the matchms.Scores object.

Contributing

If you want to contribute to the development of matchms, have a look at the contribution guidelines.

License

Copyright (c) 2023, Düsseldorf University of Applied Sciences & Netherlands eScience Center

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Credits

This package was created with Cookiecutter and the NLeSC/python-template.