Statistical bootstrapping for spectral similarity and molecular networking
Status: in active development 🚧
Feedback, ideas, issues, and PRs are very welcome!
specreboot.bioinformatics.nl runs SpecReBoot without installing anything.
- Library matching — search a spectrum against GNPS-MSn, MSn-COCONUT, GNPS-NP, MassBank or a drugs-of-abuse library, and see the match support for every candidate alongside its score.
- Molecular networking — upload an MGF and get the base, threshold and rescued networks as GraphML, ready for Cytoscape.
There is a one-click example on each tab if you just want to see what it does. The web version caps job size so the server stays responsive; for larger datasets or the full set of options, use the command line below.
SpecReBoot brings the spirit of phylogenetic bootstrapping to MS/MS molecular networking.
In phylogenetics, bootstrapping asks: “If I slightly perturb my data, do I recover the same relationships?”
SpecReBoot asks the same question for MS/MS spectra:
“If I resample spectral features, do I recover the same edges in the network?”
SpecReBoot generates pseudo-replicate spectra (via feature resampling), recomputes similarities across replicates, and reports edge support as a confidence measure for spectral relationships.
For a dataset + similarity method, SpecReBoot produces:
- Mean similarity matrix (consensus similarity across replicates)
- Edge support matrix (how often an edge is recovered across replicates)
- Networks (GraphML):
- Base network (similarity threshold) - Only when using the matchms mode
- Threshold network (similarity + support + component-size constraints)
- Core-rescue network (strict “core” edges + rescued edges)
This helps you:
- Filter unstable / fragile edges
- Improve reproducibility across instruments and studies
- Compare robustness across similarity methods
- Spectral features ≈ alignment positions (but for fragments / losses / learned features)
- Bootstrapping = repeatedly resample features → pseudo-replicate spectra
- Edge support = fraction of replicates where two spectra are recovered as mutual top-K neighbours
- Threshold network = build using similarity and edge support thresholds
- Rescued edges = connections with high edge support but spectral similarity below threshold
SpecReBoot can run multiple similarity methods so you can compare results across “classic” and learned scores:
-
Flash Cosine / Flash Modified Cosine
Fast cosine-based scoring (fragment and hybrid matching). Great baseline and scalable. -
Spec2Vec
A machine-learning similarity that treats peaks like “words” and spectra like “documents”.
Uses a trained Word2Vec model to compare spectra by learned peak co-occurrence patterns. -
MS2DeepScore
Deep learning embeddings for spectra. Similar spectra have nearby embeddings, allowing robust similarity even when peak overlap is imperfect.
Note: Spec2Vec and MS2DeepScore require pre-trained models (paths passed via CLI).
Bootstrapping is a computationally expensive step, so SpecReBoot uses a batched thread-pool strategy via Python's concurrent.futures.ThreadPoolExecutor:
- The
Bbootstrap replicates, for >50,000 spectra, these are divided in batches--batch-size(default: 10). - If there are mutiple batches, each is submitted as an independent task to a pool of
--n-jobsworker threads (default: 8). - Within a batch, replicates run sequentially — similarity scoring via
matchms.calculate_scoresreleases the GIL, so threads provide parallelism for heavy steps. - In fast mode (default), each batch returns only aggregated pair-similarity sums and edge-support counts, minimising memory overhead during parallel execution.
- In history mode (
--return-historyor--track-bins), each batch returns per-replicate results which are merged and sorted after all threads complete.
--batch-size: Controls the granularity of work units sent to the thread pool. Smaller batches increase parallelism but add scheduling overhead. Larger batches reduce overhead but may leave some threads idle near the end.--n-jobs: Number of concurrent worker threads.
If you don’t have conda yet, Miniconda is enough:
https://docs.conda.io/projects/conda/en/latest/user-guide/install/index.html
First clone our repository where you want it:
git clone https://github.com/ECharria/SpecReBoot.git Go to the SpecReBoot repo root:
cd SpecReBootNow create the environment using the .yml file:
conda env create -f environment.yml
conda activate specrebootThen from the repo root type in the bash terminal:
pip install -e . quick test:
specreboot --helpSpecReBoot is developed on Linux and macOS.
SpecReBoot provides a single command with two modes:
- matchms → full workflow: preprocessing → bootstrapping → network generation
- gnps → bootstrapping → network rebooting conserving GNPS metadata
Help is always available:
specreboot --help
specreboot matchms --help
specreboot gnps --helpRuns:
- preprocessing (general_cleaning)
- binning
- bootstrapping across a single or multiple similarity scores
- exports CSV + GraphML networks
By default, cosine and modified cosine are chosen.
Example:
specreboot matchms \
--mgf "path_to_your_expectra.mgf" \
--ms2dp-model "path_to_your_ms2deepscore_model.pt" \
--spec2vec-model "path_to_your_Spec2Vec_model.model" \
--outdir "output_matchms" \
--prefix "Reboot" \
--B 30 --k 5 --n-jobs 4 \
--sim-threshold 0.7 \
--sim-threshold-ms2dp 0.8You can restrict the run to one or more metrics using --similarities.
Example — only Modified Cosine:
specreboot matchms \
--mgf "/.../input_spectra.mgf" \
--similarities modcosine \
--tolerance 0.02 \
--outdir "/.../output_matchms" \
--prefix "Reboot_modcos" \
--B 30 --k 5 --n-jobs 4 \
--sim-threshold 0.7Example — multiple selected metrics:
--similarities cosine spec2vec| Argument | Default | Description |
|---|---|---|
--mgf |
(required) | Input MGF file |
--similarities |
cosine modcosine |
Similarity metric(s) to run (all, cosine, modcosine, spec2vec, ms2deepscore) |
--B |
100 |
Number of bootstrap replicates |
--k |
5 |
Top-k neighbours for mutual-kNN edge support |
--n-jobs |
8 |
Number of parallel worker threads |
--sim-threshold |
0.7 |
Mean similarity threshold for cosine/modcosine/spec2vec graphs |
--sim-threshold-ms2dp |
0.8 |
Mean similarity threshold for MS2DeepScore graphs |
--spec2vec-allowed-missing-percentage |
5.0 |
Maximum percentage of missing peaks allowed in spec2vec similarity calculation |
--support-threshold |
0.5 |
Minimum edge support for threshold graph |
--max-component-size |
100 |
Maximum connected-component size |
--max-links |
None |
Maximum edges per node; each node keeps only its top-N neighbours by mean similarity. None disables the filter |
--link-method |
mutual |
How to resolve the per-node degree cap: mutual keeps an edge only if both endpoints accept it; single keeps an edge if either endpoint accepts it |
--tolerance |
0.01 |
Fragment m/z tolerance (Da) |
--decimals |
2 |
Decimal places for m/z binning |
--label-mode |
feature |
Node label source: feature, scan, or internal |
--return-history |
flag | Store cumulative bootstrap history (slower, more memory) |
--track-bins |
flag | Store sampled/missing bins per replicate (slower) |
--sim-rescue-min |
1e-5 |
Minimum similarity floor for rescued edges |
--save-matrices |
True |
Save mean similarity and edge support as CSV files. Use --no-save-matrices to skip (recommended for large datasets >20k spectra) |
Use this mode when you already have a GNPS2 network (GraphML) and want to:
- compute edge support for your spectral connections
- “rescue” supported edges with low spectral similarity
- refine GNPS network and explore recovered connections as new GraphML networks
Notes:
- only Modified Cosine allows direct comparison of the new graphs with your GNPS2 network
- bootstrap bin histories inspection is not available in this mode, use
specreboot matchmswith--return-historyif you need cumulative bootstrap diagnostics.
Example:
specreboot gnps \
--mgf "path_to_mgf.mgf" \
--gnps-graphml "path_to_graphml.graphml" \
--outdir "output_gnps" \
--prefix "Reboot" \
--B 100 --k 5 --n-jobs 4 \
--similarity modcosine \
--tolerance 0.02 \
--candidate-node-attrs "shared name" \
--sim-threshold 0.7 \
--support-threshold 0.5 \
--sim-rescue-min 1e-5| Argument | Default | Description |
|---|---|---|
--mgf |
(required) | Input MGF file |
--gnps-graphml |
(required) | Input GNPS GraphML network |
--similarity |
modcosine |
Metric to use: cosine, modcosine |
--B |
100 |
Number of bootstrap replicates |
--k |
5 |
Top-k neighbours for mutual-kNN |
--n-jobs |
8 |
Number of parallel worker threads |
--sim-threshold |
0.7 |
Similarity threshold for core edges and threshold graph |
--support-threshold |
0.5 |
Minimum edge support |
--sim-rescue-min |
1e-5 |
Minimum similarity floor for rescued edges |
--candidate-node-attrs |
shared name |
GNPS node attribute(s) used to map bootstrap IDs to GNPS nodes |
--label-mode |
feature |
Node label source: feature, scan, or internal |
--max-component-size |
100 |
Maximum connected-component size |
--max-links |
None |
Maximum edges per node; each node keeps only its top-N neighbours by mean similarity. None disables the filter |
--link-method |
mutual |
How to resolve the per-node degree cap: mutual keeps an edge only if both endpoints accept it; single keeps an edge if either endpoint accepts it |
--save-matrices |
True |
Save mean similarity and edge support as CSV files. Use --no-save-matrices to skip (recommended for large datasets >20k spectra) |
This repository includes a small demo MS/MS dataset of RiPPs so you can quickly test whether SpecReBoot runs correctly on your machine.
From the repo root, run:
specreboot matchms \
--mgf "demo/matchms/input/Manually_collected_RiPPs_NPATLAS_GNPS.mgf" \
--ms2dp-model "/path/to/ms2deepscore_model.pt" \
--spec2vec-model "/path/to/spec2vec_model.model" \
--outdir "/path/to/results_folder" \
--prefix "Reboot" \
--B 30 --k 5 --n-jobs 4 \
--sim-threshold 0.7 --sim-threshold-ms2dp 0.8 \
--return-history \
--track-binsIf the run completes successfully, results will include:
- .csv files with mean similarity and edge support matrices
- .pkl files storing bootstrap bin histories
- .graphml files corresponding to the inferred molecular networks
These outputs reproduce the RiPP case study discussed in the preprint and can be used as a reference for adapting SpecReBoot to your own datasets!
In addition to the molecular networking, SpecReBoot now includes a library matching module for confidence-aware spectral matching. The approach is described in Charria Girón et al. (2026), bioRxiv. This module applies the same core idea of bootstrap resampling to spectral library matching, allowing candidate hits to be evaluated not only by their original score but also by quantifying their reproducibility under perturbation of the underlying fragment evidence.
For a given query spectrum, the workflow first performs a standard library search and retains the top-N candidate library spectra. It then constructs a global bin space from the query spectrum fragment bins only. In each bootstrap replicate, bins are resampled with replacement from this query-derived bin space, and the sampled bins define a shared mask that is applied to both the query and each candidate spectrum before rescoring. This yields a distribution of bootstrap similarity scores for every candidate in the top-N subset.
The final output summarizes each candidate by both score-based and confidence-aware metrics.
- Score the query spectrum against the full library.
- Retain the top-N candidate library spectra.
- Build the bootstrap bin space from the query spectrum only.
- Bin the query and candidate spectra.
- Run B bootstrap replicates by resampling query-derived bins.
- Recalculate query–candidate similarity in each replicate.
- Summarize bootstrap-derived support and rank stability metrics.
For each candidate, the module reports:
original_score: similarity score from the original query spectrumoriginal_rank: rank in the original top-N candidate listmatch_support: fraction of bootstrap replicates with score above the support thresholdscore_mean: mean bootstrap similarity scorescore_std: standard deviation of bootstrap similarity scorestop1_stability: fraction of replicates in which the candidate ranks firsttop3_stability: fraction of replicates in which the candidate ranks in the top 3top5_stability: fraction of replicates in which the candidate ranks in the top 5mean_rank: mean rank across bootstrap replicates
These metrics allow candidates to be interpreted as reliable, ambiguous or fragile matches rather than relying on score alone!
The library matching workflow is implemented in:
specreboot/library/library_matching.py
The most important user-facing functions are:
confidence_aware_match()for one query spectrumsave_results()for exporting one query resultcollect_results()for aggregating results across many queries
from matchms.similarity import ModifiedCosine
from specreboot.library.library_matching import confidence_aware_match
result = confidence_aware_match(
query_spectrum=query_spectrum,
library_spectra=library_spectra,
similarity_metric=ModifiedCosine(),
B=50,
top_n=50,
score_threshold=0.7,
decimals=2,
seed=42,
)
print(result.candidate_stats.head())The module can also be run from the command line, which processes every spectrum in a query MGF against a library MGF and writes the per-candidate metrics to CSV:
python specreboot/run_library_matching.py \
--library library.mgf \
--query queries.mgf \
--similarity-type modcos \
--B 100 \
--top-n 100 \
--outdir results/Defaults are read from specreboot/configs/library_matching.yaml; any argument
given on the command line overrides the config file. Point --config-file at
your own YAML to keep per-project settings.
| Argument | Default | Description |
|---|---|---|
--config-file |
configs/library_matching.yaml |
YAML file supplying defaults for every argument below |
--library |
(required) | MGF file with the library spectra |
--query |
(required) | MGF file with the query spectra to be matched |
--library-cleaned / --query-cleaned |
None |
Pre-cleaned MGF files, to skip re-cleaning on a rerun |
--similarity-type |
cos |
Metric: cos, modcos, ms2ds, or spec2vec (aliases accepted) |
--B |
100 |
Number of bootstrap replicates |
--top-n |
100 |
Number of candidates carried into the bootstrap phase |
--score-threshold |
0.7 |
Minimum bootstrap score counted towards match_support (see note below) |
--precursor-tolerance |
0.02 |
Da window for precursor m/z filtering |
--analog-search |
True |
Fill up to top-N with analogs when exact precursor matches are too few; disable with --no-analog-search |
--cosine-tolerance |
0.01 |
Flash tolerance for cosine and modified cosine |
--binning-decimals |
2 |
Binning precision used when masking peaks |
--ms2deepscore-model-path |
None |
Model path, required only for ms2ds |
--spec2vec-model-path |
None |
Model path, required only for spec2vec |
--metadata-csv |
None |
Optional MZmine metadata CSV supplying adduct information |
--outdir |
. |
Output directory for the result CSVs |
Note on
--score-threshold.match_supportcounts the fraction of replicates scoring above this threshold, so the default of0.7is only meaningful on the cosine-like scales it was chosen for. Scores fromspec2vecin particular occupy a lower range, where a fixed0.7can drivematch_supportto zero even for tightly reproducible hits. Set it per metric, and readscore_mean ± score_stdalongsidematch_supportrather than relying on the support value alone.
The code in this package is licensed under the MIT License.
If you use SpecReBoot in your work, please cite:
Charria Girón, E., Torres Ortega, L. R., Mergola Greef, J., Marin Felix, Y., Caicedo Ortega, N. H., Surup, F., Medema, M. H., & van der Hooft, J. J. J. (2026). Bootstrap resampling of mass spectral pairs with SpecReBoot reveals hidden molecular relationships. bioRxiv. doi: https://doi.org/10.64898/2026.02.03.703446
If you use the library matching module, please also cite:
Charria Girón, E., van IJcken, J., Della Vedova, L., Torres Ortega, L. R., & van der Hooft, J. J. J. (2026). Quantifying per-match reliability in library matching for untargeted metabolomics workflows. bioRxiv. doi: https://doi.org/10.64898/2026.07.30.741704
Please open a GitHub Issue for bugs/feature requests. Maintainers: Rosina Torres-Ortega (rosina.torresortea@wur.nl) and Esteban Charria-Girón (esteban.charriagiron@wur.nl)
