Computes mass-spectral similarity and identifies compounds for metabolomics with matchms — comparing mass spectra, scoring similarity (cosine, modified cosine), and searching spectral libraries to annotate unknowns.
Ships in alterlab-cheminformatics. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Matchms is an open-source Python library for mass spectrometry data processing and analysis. Import spectra from various formats, standardize metadata, filter peaks, calculate spectral similarities, and build reproducible analytical workflows.
Use this skill when the user wants to:
SpectrumProcessor) for metabolomics spectra| Scenario | Use Instead |
|---|---|
| Full LC-MS/MS proteomics or feature-detection pipelines (peptide ID, quantification, raw-file processing) | alterlab-pyopenms |
| Looking up a metabolite's reference record, pathways, or published spectra in HMDB | alterlab-hmdb |
| Querying Metabolomics Workbench studies, RefMet names, or m/z mass searches | alterlab-metabolomics-wb |
| Structure-level cheminformatics on the annotated compounds (substructure, descriptors) | alterlab-rdkit |
Hand-off rule. When the request matches a row above, open your answer by naming that skill by its exact id (for example alterlab-pyopenms) and saying in one line why it fits better, then stop applying this skill's procedure. Name it even when you also need to ask for missing input. If only part of the request is out of scope, name the skill for that part and do only the in-scope part. A brief general pointer is fine; the named skill does the work.
Load spectra from multiple file formats and export processed data:
from matchms.importing import load_from_mgf, load_from_mzml, load_from_msp, load_from_json
from matchms.exporting import save_as_mgf, save_as_msp, save_as_json
# Import spectra
spectra = list(load_from_mgf("spectra.mgf"))
spectra = list(load_from_mzml("data.mzML"))
spectra = list(load_from_msp("library.msp"))
# Export processed spectra
save_as_mgf(spectra, "output.mgf")
save_as_json(spectra, "output.json")
Supported formats:
For detailed importing/exporting documentation, consult references/importing_exporting.md.
Apply comprehensive filters to standardize metadata and refine peak data:
from matchms.filtering import default_filters, normalize_intensities
from matchms.filtering import select_by_relative_intensity, require_minimum_number_of_peaks
# Apply default metadata harmonization filters
spectrum = default_filters(spectrum)
# Normalize peak intensities
spectrum = normalize_intensities(spectrum)
# Filter peaks by relative intensity
spectrum = select_by_relative_intensity(spectrum, intensity_from=0.01, intensity_to=1.0)
# Require minimum peaks
spectrum = require_minimum_number_of_peaks(spectrum, n_required=5)
Filter categories:
Matchms provides 40+ filters. For the complete filter reference, consult references/filtering.md.
Compare spectra using various similarity metrics:
from matchms import calculate_scores
from matchms.similarity import CosineGreedy, ModifiedCosineGreedy, CosineHungarian
# Calculate cosine similarity (fast, greedy algorithm)
scores = calculate_scores(references=library_spectra,
queries=query_spectra,
similarity_function=CosineGreedy())
# Calculate modified cosine (accounts for precursor m/z differences)
scores = calculate_scores(references=library_spectra,
queries=query_spectra,
similarity_function=ModifiedCosineGreedy(tolerance=0.1))
# Get best matches. The cosine functions return a structured score
# (score + matched-peak count), so to SORT you must name the field to
# sort by — `sort=True` alone raises IndexError. The field is
# "<FunctionName>_score", e.g. "ModifiedCosineGreedy_score" / "CosineGreedy_score".
best_matches = scores.scores_by_query(query_spectra[0],
name="ModifiedCosineGreedy_score",
sort=True)[:10]
One pair of spectra: call the similarity function's .pair() — no score matrix needed:
result = CosineGreedy(tolerance=0.1).pair(spectrum_1, spectrum_2)
float(result["score"]), int(result["matches"]) # structured value: cosine + matched-peak count
Greedy vs Hungarian: each peak may match at most one peak in the other spectrum. CosineGreedy takes the candidate pairs within tolerance in order of their (weighted) intensity product and keeps each one whose peaks are still free — fast, but when several peaks compete for the same partner it can miss the best overall assignment and under-score. CosineHungarian solves the assignment exactly (never lower, slower). With well-separated peaks the two agree; with peaks closer together than the tolerance they can differ (verified on matchms 0.33.1: two competing peak pairs at 0.1 Da gave 0.767 with 1 match greedy vs 0.844 with 2 matches Hungarian).
Report a score with how it was computed: the function, tolerance, mz_power/intensity_power (defaults 0 and 1), any filters applied first, the matched-peak count, and why greedy or Hungarian was used.
Available similarity functions:
ModifiedCosineHungarian): cosine similarity accounting for precursor mass differences. Note the rename — the class is no longer called ModifiedCosine.For detailed similarity function documentation, consult references/similarity.md.
Create reproducible, multi-step analysis workflows:
from matchms import SpectrumProcessor
from matchms.filtering import default_filters, normalize_intensities
from matchms.filtering import select_by_relative_intensity, remove_peaks_around_precursor_mz
# Define a processing pipeline. Each step is a callable, a registered filter
# name (str), or a ("filter_name", {kwargs}) tuple (introspectable via
# processor.processing_steps). NOTE: default_filters is a composite, so pass it
# as the callable — the string "default_filters" is not a registered name.
processor = SpectrumProcessor([
default_filters,
"normalize_intensities",
("select_by_relative_intensity", {"intensity_from": 0.01}),
("remove_peaks_around_precursor_mz", {"mz_tolerance": 17}),
])
# A SpectrumProcessor is NOT callable. Use .process_spectrum() for one
# spectrum, or .process_spectra() for a list (returns a (spectra, report)
# tuple — unpack it, don't treat the result as the spectra list).
processed_spectra, report = processor.process_spectra(spectra)
# single spectrum: processed = processor.process_spectrum(spectrum)
The core Spectrum class contains mass spectral data:
from matchms import Spectrum
import numpy as np
# Create a spectrum
mz = np.array([100.0, 150.0, 200.0, 250.0])
intensities = np.array([0.1, 0.5, 0.9, 0.3])
metadata = {"precursor_mz": 250.5, "ionmode": "positive"}
spectrum = Spectrum(mz=mz, intensities=intensities, metadata=metadata)
# Access spectrum properties
print(spectrum.peaks.mz) # m/z values
print(spectrum.peaks.intensities) # Intensity values
print(spectrum.get("precursor_mz")) # Metadata field
# Visualize spectra
spectrum.plot()
spectrum.plot_against(reference_spectrum)
Standardize and harmonize spectrum metadata:
# Metadata keys are automatically harmonized
spectrum.set("Compound_Name", "caffeine") # stored under 'compound_name'
print(spectrum.get("compound_name")) # 'caffeine'
# Setting a variant spelling of a key that already exists (e.g. "Precursor_mz" when
# "precursor_mz" is set) raises ValueError — update it with the canonical key instead.
# Derive chemical information
from matchms.filtering import derive_inchi_from_smiles, derive_inchikey_from_inchi
from matchms.filtering import add_fingerprint
spectrum = derive_inchi_from_smiles(spectrum)
spectrum = derive_inchikey_from_inchi(spectrum)
# fingerprint_type must be one of: "daylight", "morgan1", "morgan2", "morgan3"
# (the digit is the Morgan radius). Plain "morgan" is NOT valid.
spectrum = add_fingerprint(spectrum, fingerprint_type="morgan2", nbits=2048)
For typical mass spectrometry analysis workflows, including:
Consult references/workflows.md for detailed examples.
No install step — run install-free with uv, pinning the interpreter (uv's default
Python here is 3.9, but matchms needs ≥ 3.10; on 3.9 uv resolves an old matchms
without ModifiedCosineGreedy):
uv run --python ">=3.11" --with "matchms>=0.33" python your_script.py
Molecular-structure processing (SMILES/InChI/fingerprints) needs rdkit, which
ships in the base matchms install on current versions — there is no separate
[chemistry] extra. If import rdkit fails, add --with rdkit. (A persistent
uv pip install matchms works too.)
API notes below were verified against matchms 0.33.x.
These trip people up and the code examples here account for them:
SpectrumProcessor instances are not callable. Use
processor.process_spectrum(spectrum) for one spectrum or
processor.process_spectra(spectra) for a list — the latter returns a
(processed_spectra, report) tuple, not a bare list.scores_by_query(query, sort=True) raises IndexError for cosine-family
scores. You must pass name="<FunctionName>_score" (e.g.
"CosineGreedy_score") so the structured score knows which field to sort on.scores.scores[i, j] is a structured element, not a float — it carries
both ..._score and ..._matches fields. For plain float matrices use
scores.to_array("CosineGreedy_score"); there is no to_dataframe/to_list.add_fingerprint(fingerprint_type=...) accepts only "daylight",
"morgan1", "morgan2", "morgan3" (no "morgan", no radius= argument).Detailed reference documentation is available in the references/ directory:
filtering.md - Complete filter function reference with descriptionssimilarity.md - All similarity metrics and when to use themimporting_exporting.md - File format details and I/O operationsworkflows.md - Common analysis patterns and examplesLoad these references as needed for detailed information about specific matchms capabilities.
Part of the AlterLab Academic Skills suite.
evals/evals.json (opens in a new tab)evals/fixtures/annotated_spectra.mgf (opens in a new tab)evals/fixtures/mgf_queries/unknown_1.mgf (opens in a new tab)evals/fixtures/mgf_queries/unknown_2.mgf (opens in a new tab)evals/fixtures/mgf_queries/unknown_3.mgf (opens in a new tab)evals/fixtures/reference_library.msp (opens in a new tab)evals/fixtures/two_spectra.mgf (opens in a new tab)references/filtering.md (opens in a new tab)references/importing_exporting.md (opens in a new tab)references/similarity.md (opens in a new tab)references/workflows.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
/alterlab-cheminformatics:alterlab-matchmsfrom alterlab-cheminformatics
npx claudepluginhub alterlab-ieu/alterlab-academic-skills --plugin alterlab-cheminformatics12 skills in this plugin
/alterlab-datamolWraps RDKit in a high-level, pandas-friendly datamol interface with sensible defaults for everyday drug discovery — SMILES/SDF loading into DataFrames, molecule standardization, descriptors, fingerprints, Butina clustering, 3D conformer generation, scaffold analysis, and parallel batch processing, returning native rdkit.Chem.Mol objects. Use when running standard cheminformatics pipelines on molecule tables with minimal boilerplate; for low-level control, custom sanitization, or specialized algorithms prefer alterlab-rdkit. Part of the AlterLab Academic Skills suite./alterlab-deepchemRuns molecular machine learning with DeepChem — diverse featurizers, pre-built MoleculeNet benchmark datasets, and pre-trained models (ChemBERTa, GROVER) for property prediction (ADMET, toxicity, solubility) via traditional ML or graph neural networks. Use when running end-to-end molecular ML experiments that need MoleculeNet benchmarks, scaffold splitting, or ready-made models with minimal setup; for building custom PyTorch graph architectures prefer alterlab-torch-geometric, and for standalone molecule-to-feature-vector generation prefer alterlab-molfeat. Part of the AlterLab Academic Skills suite./alterlab-diffdockPredicts protein-ligand binding poses with DiffDock diffusion-based molecular docking from PDB structures and SMILES, producing pose confidence scores for virtual screening and structure-based drug design. Use when docking ligands into a protein, generating binding poses, or screening compounds against a target; not for binding affinity prediction. Part of the AlterLab Academic Skills suite./alterlab-medchemApplies medicinal-chemistry filters with the medchem library — drug-likeness rules (Lipinski, Veber), PAINS filters, structural alerts, and molecular complexity metrics for compound prioritization and library cleanup. Use when filtering or triaging a compound library, flagging PAINS or reactive groups, or assessing drug-likeness of candidate molecules. Part of the AlterLab Academic Skills suite./alterlab-molecular-dynamicsRuns and analyzes molecular dynamics simulations with OpenMM and MDAnalysis — setting up protein and small-molecule systems, assigning force fields, running energy minimization and production MD, and analyzing trajectories (RMSD, RMSF, contact maps, free energy surfaces). Use when simulating protein or ligand dynamics, equilibrating a system, or computing trajectory metrics for structural biology, drug binding, or biophysics. Part of the AlterLab Academic Skills suite./alterlab-molfeatFeaturizes molecules for machine learning with molfeat — ECFP/MACCS/MAP4 fingerprints, RDKit and Mordred physicochemical descriptors, pharmacophore and shape descriptors, and pretrained embeddings (ChemBERTa, ChemGPT, CheMeleon) exposed as scikit-learn transformers that convert SMILES into feature vectors. Use when turning molecules into ML-ready feature matrices for QSAR/QSPR or virtual screening, or benchmarking fingerprint against descriptor and embedding representations; for training models and MoleculeNet benchmarks on those features prefer alterlab-deepchem, and for low-level fingerprint or descriptor primitives prefer alterlab-rdkit. Part of the AlterLab Academic Skills suite.2 plugins in one repository ship this exact skill · first indexed Nov 9, 2026
Other plugins' skills for the same job