Skip to main content

msbuddy

Maintainer PyPI PyPI Downloads Generic badge

Sample Image

msbuddy is developed for molecular formula analysis in MS-based small molecule (<1500 Da) studies.

msbuddy is able to provide formula annotations for queries:

  • with or without MS1 isotopic pattern
  • with or without MS/MS spectra
  • in either positive or negative ionization mode

The minimum requirement for a msbuddy query is a single m/z value and its ionization polarity.

Official documentation is available at https://msbuddy.readthedocs.io/en/latest/.

Installation

msbuddy is available on PyPI, you can install the latest version via pip:

pip install msbuddy

LightGBM and the CPU ONNX Runtime are inference dependencies. PyTorch and CUDA are not required. Python 3.8 or newer is supported; Python 3.8 uses NumPy 1.x and a compatible ONNX Runtime version.

Compact models and downloads in 1.4

MS2 and joint MS1+MS2 ranking share one 749,644-parameter spectral encoder and one candidate scorer. The 1.4 hybrid refines the encoder's output head while retaining formula, mass, isotope and fragment evidence. The default model download is 8.75 MB. Compatibility weights are downloaded when an older evidence mode or setting requires them; use download_data(include_compatibility=True) for offline use.

The lossless formula database is 18.41 MB, with every formula, duplicate, index and stored mass bit preserved. Default model and database downloads total 27.16 MB, compared with 32.37 MB in 1.3. Existing custom legacy databases and models remain supported.

On a 1,696-formula fresh accuracy review, native MS2 top-1 improved from 1,225 to 1,241 correct, and joint top-1 with simulated isotope evidence from 1,447 to 1,461. Transfer varies by acquisition source: an independent 1,507-formula diagnostic reached 900 correct with MS2 alone. A nominal pooled 5% error threshold had 3 errors among 34 accepted halogen MS2 annotations in that diagnostic (8.82%). The 1.4 confidence estimates are model-based and are not validated as general 5% FDR control across sources or halogen-rich MS2 data. See the 1.4 model review.

Acquisition metadata are optional. Set MsbuddyConfig(ms_instr="orbitrap") or the appropriate instrument family to configure mass tolerances and provide the instrument hint. MetaFeature also accepts instrument, collision_energy and collision_energy_unit ("ev" or "nce"). MGF fields INSTRUMENT_TYPE and COLLISION_ENERGY=30 nce are recognized. Unknown or stepped energies are masked; bare numbers need explicit units.

Use MsbuddyConfig(use_spectral=False) or --no-spectral to select the established numerical rankers. They are also used for custom candidate budgets and inputs outside the compact models' validated settings. See the model guide for confidence interpretation and supported settings.

Model update in 1.1

The revised evidence-mode models use explicit elemental and adduct features, a learned candidate selector, and mode-specific candidate limits. Starting with 1.1.1, halogen atoms (F, Cl, Br and I) are included in the search by default. This allows both halogen-free and halogen-containing formulas without requiring prior knowledge of the unknown compound. Only when prior knowledge rules out halogens should you set MsbuddyConfig(halogen=False) or pass --no-halogen. The default fluorine limit is 80 atoms. Set element_ranges={'F': (0, n)} or --f-max n when a different limit is justified by prior knowledge. Use MsbuddyConfig(max_candidates=350) or --max-candidates 350 to override the recommended candidate budget.

Probability calibration now reserves mass for an absent correct formula. A singleton candidate no longer becomes certain through normalization. See the model guide and validation report for budgets, confidence interpretation, comparisons and limitations.

Upgrading to 1.0

The 1.0 Python API contains breaking changes and is not fully compatible with 0.x. Formula compositions now use dictionaries, such as {'C': 6, 'H': 12, 'O': 6}, instead of fixed-order element arrays. read_formula() returns a dictionary, and Formula() accepts one. Use formula_to_string() and the lazy enumerate_subformulas() iterator in place of the former top-level array helpers. Invalid formulas and unsupported element symbols raise errors.

Configure element limits with MsbuddyConfig(element_ranges={'C': (0, 40)}) instead of separate arguments such as c_range. Msbuddy.add_data() now appends data; call clear_data() first when replacing the loaded dataset. See the migration guide for examples and other changes.

Python usage

Quick start (docs)

As a quick start, we here load a mgf file and annotate the molecular formula for each query. All the configurations are specified in the MsbuddyConfig class. Parallel computing is supported.

from msbuddy import Msbuddy, MsbuddyConfig

# instantiate a MsbuddyConfig object
msb_config = MsbuddyConfig(ms_instr='orbitrap', # supported: "qtof", "orbitrap", "fticr" or None
                                                # custom MS1 and MS2 tolerance will be used if None
                           ppm=True,  # use ppm for mass tolerance
                           ms1_tol=5,  # MS1 tolerance in ppm or Da
                           ms2_tol=10,  # MS2 tolerance in ppm or Da
                           halogen=True)  # default: allow F, Cl, Br and I

# instantiate a Msbuddy object
msb_engine = Msbuddy(msb_config)

# load data, here we use a mgf file as an example
msb_engine.load_mgf('input_file.mgf')

# annotate molecular formula
msb_engine.annotate_formula()

# retrieve the annotation result summary
result = msb_engine.get_summary()

See demo mgf file. One of the following fields is recommended to be included, which will be used as the query identifier: TITLE, FEATURE_ID, SPECTRUMID, or SPECTRUM_ID.

If prior knowledge establishes that the compounds cannot contain halogens, exclude them explicitly:

msb_config = MsbuddyConfig(ms_instr='orbitrap', halogen=False)

For direct mass searches, pass halogen=False to mass_to_formula() or mz_to_formula() under the same condition; these methods also include halogens by default.

MS/MS spectra can be loaded via their USIs if they are publicly available:

# you can load multiple USIs at once
msb_engine.load_usi(['mzspec:GNPS:GNPS-LIBRARY:accession:CCMSLIB00003740036',
                     'mzspec:GNPS:GNPS-LIBRARY:accession:CCMSLIB00003740037'])

Here is a test case on Google Colab.

Other API functions

from itertools import islice
from msbuddy import Formula, MsbuddyConfig, enumerate_subformulas, formula_to_string, read_formula

composition = read_formula('C6H12O6')  # {'C': 6, 'H': 12, 'O': 6}
formula = Formula(composition)          # neutral by default
print(formula.mass, formula.composition, formula_to_string(composition))
print(list(islice(enumerate_subformulas(composition), 5)))

config = MsbuddyConfig(halogen=True, element_ranges={'C': (0, 40), 'Cl': (0, 2)})

Supported elements are C, H, Br, Cl, F, I, K, N, Na, O, P, and S. Unknown symbols raise UnsupportedElementError, a subclass of ValueError. You can also assign subformulas from MS/MS data with assign_subformula(), or use Msbuddy.mass_to_formula() and Msbuddy.mz_to_formula() to search by mass.

See more in the documentation.

Command-line tool (docs)

msbuddy can also be used as a command-line tool. Result summary will be generated in a tsv file. More detailed annotation results can be written with the -details option (or -d for short).

Here is an example command for a mgf file from Orbitrap:

msbuddy -mgf <mgf_file> -output <output_folder> -ms orbitrap -details

for a single USI string (from FT-ICR, for example):

msbuddy -usi <usi_string> -output <output_folder> -ms fticr

or a csv file (template files) containing multiple USI strings (QTOF in this example):

msbuddy -csv <csv_file> -output <output_folder> -ms qtof -details

For mgf file or csv file, you can omit the -output option, and results will be written in the same folder as the input file.

Here is an example of processing a mgf file from Orbitrap (-ms orbitrap) in parallel (-p) using 12 cores (-n_cpu 12). Detailed results are written (-d). Halogen atoms (F, Cl, Br and I) are considered by default.

msbuddy -mgf <mgf_file> -ms orbitrap -p -n_cpu 12 -d

Only if prior knowledge rules out halogens, add --no-halogen:

msbuddy --mgf <mgf_file> --ms-instr orbitrap --no-halogen

The existing --halogen, -halogen and -hal flags remain supported.

Run the following command to see the full list of options:

msbuddy --help

Development

The annotation pipeline lives in msbuddy/, with regression tests in tests/ and repeatable scaling checks in benchmarks/. After installing the project dependencies, run the tests from the repository root:

python -m unittest discover -s tests -v

Run python -m benchmarks.benchmark_workflows to measure synthetic input loading, candidate matching, feature assembly, and subformula mass calculation. See the development guide for the project layout and benchmark options.

msbuddy documentation

PyPI release

Change log

GitHub repository

Citation

S. Xing et al. BUDDY: molecular formula discovery via bottom-up MS/MS interrogation. Nature Methods 2023. DOI: 10.1038/s41592-023-01850-x

License

This work is licensed under the Apache License 2.0.

Contact

Please contact me via sxing@fudan.edu.cn.

Metadata

Release files for msbuddy 1.4.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 msbuddy 1.4.0
File Size Uploaded Provenance Actions
msbuddy-1.4.0.tar.gz 147.8 kB Without provenance Details for msbuddy-1.4.0.tar.gz

Built distribution (wheel)

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

Total release size: 236.7 kB

Release files / msbuddy-1.4.0.tar.gz

Download URL msbuddy-1.4.0.tar.gz
Size 147.8 kB
Tags Source
SHA-256 checksum
How to use checksums
c3b3692354cc42fc5abe822bfd34599c52b365e04cf3ed4b8460def59548bd33
BLAKE2b-256 checksum
How to use checksums
9508acf6c536a350650f0a766b7bf3b2f9aae3cb104af13ef014ac5775a525b6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.10.12

Release files / msbuddy-1.4.0-py3-none-any.whl

Download URL msbuddy-1.4.0-py3-none-any.whl
Size 88.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b381206e25788b2379a401152d5239d81d8e34c556aacaae96fe63c53716cd14
BLAKE2b-256 checksum
How to use checksums
32fb348d152e2aa785614155b78ba3b0982f6618cd5c628f5a0b9c19730a98ce
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.10.12

Security for msbuddy 1.4.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.

Release history Release notifications | RSS feed

This release

1.4.0 This release

2 release files No provenance

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