Skip to main content

fair-software.nl recommendations:

GitHub Badge License Badge Conda Badge (Bioconda) spec2vec on PyPI Research Software Directory Badge Zenodo Badge CII Best Practices Badge Howfairis Badge

Code quality checks:

GitHub Workflow Status Documentation Status

spec2vec logo

spec2vec

Spec2vec is a novel spectral similarity score inspired by a natural language processing algorithm – Word2Vec. Where Word2Vec learns relationships between words in sentences, spec2vec does so for mass fragments and neutral losses in MS/MS spectra. The spectral similarity score is based on spectral embeddings learnt from the fragmental relationships within a large set of spectral data.

If you use spec2vec for your research, please cite the following references:

Huber F, Ridder L, Verhoeven S, Spaaks JH, Diblen F, Rogers S, van der Hooft JJJ, (2021) “Spec2Vec: Improved mass spectral similarity scoring through learning of structural relationships”. PLoS Comput Biol 17(2): e1008724. doi:10.1371/journal.pcbi.1008724

(and if you use matchms as well: 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 )

Thanks!

Documentation for users

See the full documentation for installation, examples, and the API reference.

Compatibility

The upcoming Spec2Vec 0.10.0 compatibility release supports matchms 1.0 (including 1.0.0.dev1) while retaining support for matchms 0.x. It keeps Gensim 4.4, the existing Word2Vec model format, and the Spec2Vec embedding algorithm. Replacing Gensim is outside the scope of this release.

Spec2Vec currently supports Python 3.10–3.13. For reproducible workflows, pin your Spec2Vec, matchms, and Gensim versions.

Installation

Install the current published release from PyPI:

python -m pip install spec2vec

Or use a Conda environment and install the Bioconda package:

conda create -n spec2vec -c conda-forge -c bioconda python=3.12 spec2vec
conda activate spec2vec

Bioconda packages can lag behind PyPI releases. To test the matchms 1.0 prerelease, explicitly select it in a compatible environment, once the Spec2Vec compatibility changes are installed:

python -m pip install --pre "matchms==1.0.0.dev1"

Check the resulting environment with python -m pip check. Do not assume that a standard installation will automatically choose prerelease versions.

Quick start

Spec2Vec represents spectra as lists of peak@... and optionally loss@... words. A Gensim Word2Vec model learns relationships between these words; Spec2Vec compares the resulting spectrum embeddings.

The example below assumes you have a reference MGF file. Its intensities must be normalized to a maximum of 1 before creating spectrum documents.

from matchms.importing import load_from_mgf
from spec2vec import SpectrumDocument
from spec2vec.model_building import train_new_word2vec_model

references = list(load_from_mgf("references.mgf"))
documents = [SpectrumDocument(s, n_decimals=2) for s in references]

model = train_new_word2vec_model(
    documents,
    iterations=20,
    filename="references.model",
    workers=2,
)

To compare already-preprocessed spectra using a pretrained model:

import numpy as np
from gensim.models import Word2Vec
from matchms import calculate_scores
from spec2vec import Spec2Vec

model = Word2Vec.load("references.model")
similarity = Spec2Vec(model, intensity_weighting_power=0.5)
scores = calculate_scores(references, queries, similarity)

# matchms 1.0: rows correspond to references; columns to queries.
values = scores.to_array("score")
best_reference_indices = np.argsort(values[:, 0])[::-1][:10]
best_references = [references[i] for i in best_reference_indices]

Here references and queries are lists of preprocessed matchms spectra or matching spectrum documents. Preprocessing, peak selection, and decimal rounding must be consistent with the Word2Vec model. See the documentation’s Quickstart for complete loading and preprocessing examples.

matchms 0.x: its calculate_scores result exposes scores.scores_by_query(query, sort=True) instead of the matrix-oriented Scores.to_array("score") API.

Glossary of terms

Term

Description

adduct / addition product

During ionization in a mass spectrometer, the molecules of the injected compound break apart into fragments. When fragments combine into a new compound, this is known as an addition product, or adduct. Wikipedia

GNPS

Knowledge base for sharing of mass spectrometry data (link).

InChI / INCHI

InChI is short for International Chemical Identifier. InChIs are useful in retrieving information associated with a certain molecule from a database.

InChIKey / InChI key / INCHIKEY

An identifier for molecules. For example, the InChI key for carbon dioxide is InChIKey=CURLTUGMZLYLDI-UHFFFAOYSA-N (yes, it includes the substring InChIKey=).

MGF File / Mascot Generic Format

A plain ASCII file format to store peak list data from a mass spectrometry experiment. Links: matrixscience.com, fiehnlab.ucdavis.edu.

parent mass / parent_mass

Actual mass (in Dalton) of the original compound prior to fragmentation. It can be recalculated from the precursor m/z by taking into account the charge state and proton/electron masses.

precursor m/z / precursor_mz

Mass-to-charge ratio of the compound targeted for fragmentation.

SMILES

A line notation for describing the structure of chemical species using short ASCII strings. For example, water is encoded as O[H]O, carbon dioxide is encoded as O=C=O, etc. SMILES-encoded species may be converted to InChIKey using a resolver like this one. The Wikipedia entry for SMILES is here.

Documentation for developers

Development installation

The current repository uses Poetry for development and CI. For example:

git clone https://github.com/iomega/spec2vec.git
cd spec2vec
python -m pip install --upgrade poetry
poetry install
poetry run pytest
poetry run prospector -o grouped -o pylint:pylint-report.txt

The planned migration to uv and Ruff will be documented separately; the commands above describe the current tooling.

Documentation build

Install the documentation dependencies described in readthedocs/requirements.txt and run from the repository root:

python -m sphinx -b html readthedocs readthedocs/_build/html

For a local build using the Poetry environment, run the equivalent poetry run sphinx-build -b html readthedocs readthedocs/_build/html.

Conda package

The Conda recipe is under conda/ in this repository. The published Bioconda recipe is at bioconda-recipes. Bioconda packages may be updated separately from PyPI releases.

Contributing

See CONTRIBUTING.md for contributor guidelines.

License

Copyright (c) Florian Huber @ Düsseldorf University of Applied Sciences & Netherlands eScience Center and contributors.

Licensed under the Apache License, Version 2.0. See LICENSE for details.

Metadata

Release files for spec2vec 0.10.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for spec2vec 0.10.0
File Size Uploaded Provenance Actions
spec2vec-0.10.0.tar.gz 24.7 kB Without provenance Details for spec2vec-0.10.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for spec2vec 0.10.0
File Interpreter ABI Platform Actions
spec2vec-0.10.0-py3-none-any.whl Python 3 none any Details for spec2vec-0.10.0-py3-none-any.whl

Total release size: 51.0 kB

Release files / spec2vec-0.10.0.tar.gz

Download URL spec2vec-0.10.0.tar.gz
Size 24.7 kB
Tags Source
SHA-256 checksum
How to use checksums
b6762cac40477958598d5c02a505a03cce0936d06813ec7572f9834fad71921a
BLAKE2b-256 checksum
How to use checksums
cac3dd3513676dfd2b887a6094d97f2f8155ae76fdbd3d8bb2804b05eaeabdda
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/2.5.1 CPython/3.11.0 Linux/7.0.0-1019-azure

Release files / spec2vec-0.10.0-py3-none-any.whl

Download URL spec2vec-0.10.0-py3-none-any.whl
Size 26.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
25b8c13fbd9e28fa62a8903cad73836733e45da6445fd03561cd6f8d568ca76a
BLAKE2b-256 checksum
How to use checksums
009a6f03a3c37aad84a37e2b179e30d443a45af17eab3a8d58f01e1c12275cff
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/2.5.1 CPython/3.11.0 Linux/7.0.0-1019-azure

Security for spec2vec 0.10.0

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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page