Metadata-Version: 2.1
Name: msbuddy
Version: 2.1.0
Summary: Molecular formula annotation for MS-based small molecule analysis.
Author-email: Shipei Xing <sxing@fudan.edu.cn>
License: Apache-2.0
Project-URL: Homepage, https://github.com/Philipbear/msbuddy
Project-URL: Bug Tracker, https://github.com/Philipbear/msbuddy/issues
Project-URL: Documentation, https://msbuddy.readthedocs.io/en/latest/
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: brain-isotopic-distribution
Requires-Dist: numpy
Requires-Dist: numba
Requires-Dist: requests
Requires-Dist: joblib
Requires-Dist: gdown
Requires-Dist: chemparse
Requires-Dist: scipy
Requires-Dist: tqdm
Requires-Dist: pandas
Requires-Dist: lightgbm (>=4.0)
Requires-Dist: onnxruntime (<1.19,>=1.16.3) ; python_version < "3.9"
Requires-Dist: numpy (<2) ; python_version < "3.9"
Requires-Dist: onnxruntime (<2,>=1.19.2) ; python_version >= "3.9"

# msbuddy

[![Maintainer](https://img.shields.io/badge/maintainer-Shipei_Xing-blue)](https://scholar.google.ca/citations?user=en0zumcAAAAJ&hl=en)
[![PyPI](https://img.shields.io/pypi/v/msbuddy?color=green)](https://pypi.org/project/msbuddy/)
[![PyPI Downloads](https://static.pepy.tech/badge/msbuddy)](https://pepy.tech/projects/msbuddy)

<p align="center">
  <img src="https://github.com/Philipbear/msbuddy/blob/main/logo/logo.svg" alt="msbuddy logo" height="100"/>
</p>

`msbuddy` annotates molecular formulas for small molecules from mass spectrometry data. It accepts precursor *m/z* alone, MS1 isotope patterns, MS/MS spectra, or combinations of these inputs in positive or negative ionization mode. A precursor *m/z* and polarity are the minimum input.

[Documentation](https://msbuddy.readthedocs.io/en/latest/) · [PyPI](https://pypi.org/project/msbuddy/) · [Version updates and validation](https://msbuddy.readthedocs.io/en/latest/updates.html)

## Install

```bash
pip install msbuddy
```

The default `v1.0` databases and `v2.1.0` public model bundle (**~50.4 MB** total: `formula_db_v1.0.msbdb`, `common_db_v1.0.msbdb`, and `ml_v2.1.0.joblib`) download automatically on first use; the optional `ml_compatibility_v2.0.1.joblib` bundle (**3.2 MB**, **~53.6 MB** combined) is fetched on demand only for MS1-only, precursor-mass-only, and `--no-spectral` (`use_spectral=False`) modes. Multiply-charged MS/MS spectra (`|z| >= 2`) run natively on the default `v2.1.0` engine. Runs on CPU only; PyTorch and GPU/CUDA are not required. Python 3.8 or newer is supported.

### Dependencies and tested environment

Runtime dependencies (declared in `pyproject.toml`): `brain-isotopic-distribution`, `numpy` (`<2` on Python 3.8), `numba`, `requests`, `joblib`, `gdown`, `chemparse`, `scipy`, `tqdm`, `pandas`, `lightgbm>=4.0`, and `onnxruntime` (`>=1.19.2,<2` on Python >=3.9; `>=1.16.3,<1.19` on Python 3.8).

Tested reference environment: Python `3.11.18`, `brain-isotopic-distribution 1.5.19`, `numpy 2.4.6`, `numba 0.68.1`, `scipy 1.17.1`, `pandas 3.1.1`, `lightgbm 4.7.0`, `onnxruntime 1.32.0`, `joblib 1.6.0`, `requests 2.34.2`, `gdown 6.5.2`, `chemparse 0.3.2`, `tqdm 4.70.1`.

## What's new in 2.1

- **Clean `v1.0` formula and common fragment/loss databases:** Purges DBE/SENIOR-invalid entries (`formula_db_v1.0.msbdb`), expands default element ceilings to `C<=150`, `H<=300`, `N<=30`, `O<=50` (with `F<=80`) and PFAS/glycan coverage, and introduces polarity-independent empirical `common_fragment` and `common_loss` log-frequency weights (`common_db_v1.0.msbdb`).
- **Strictly prior-free default policy:** Uses instrument mass tolerances only (`orbitrap`, `fticr`, `tof` with `qtof`/`timstof` aliases) with no biological/database `prior_mode` intervention; halogens (`F, Cl, Br, I`) are enabled by default (`halogen=True`), and omitted adducts default to `[M+H]+` / `[M-H]-` (or `[M±|z|H]|z|±` for `|z| >= 2`).
- **Upgraded `adduct="auto"` & `|z| >= 2` / multi-spectrum support:** Native `|z| >= 2` MS/MS scoring, multi-spectrum feature-group pooling (`MetaFeature(ms2=[spec1, spec2])` or same-identifier MGF scans), extended `mz < 5000` precursor range, monomer-aware dimer (`adduct.m >= 2`) scoring, and a Stage-0 adduct head with cross-adduct joint Stage-3 reranking when `adduct="auto"`.
- **Physicochemical & isolation-window upgrades:** ~1 Da isolation-aware MS2 fragment isotope log-likelihoods (`37Cl/81Br/34S/13C`) that never penalize missing fragment isotopes, `float64` subformula DAG disambiguation (`dbe < -0.5`), DB-backed `O < 2*P` relaxation, exact 12-element DB row matching, and radical DBE `% 1.0` fixes.
- **Low-FDR Stage-4 calibration & adduct-aware exports:** Public-only distilled Stage 0–3 ONNX + LightGBM models with a 9-dimensional context-conditional `[ABSENT]` Stage-4 calibrator for `posterior_error_probability` and `batch_q_value` (`estimate_batch_fdr()`), plus adduct-aware `mz_error_ppm` in detailed exports.

## Inputs and outputs

- **Supported inputs:** MGF files (`load_mgf` / `--mgf`, grouping repeated scans with the same identifier for multi-spectrum pooling), GNPS USIs (`load_usi` / `--usi`), USI CSV files (`--csv`), and Python `MetaFeature` / `Spectrum` / `MsbuddyConfig` objects (`|z| >= 1`, `mz < 5000`, single or pooled `ms2=[spec1, spec2]`).
- **Python outputs:** `engine.get_summary()` returns a list of dicts containing `identifier`, `mz`, `rt`, `adduct`, `formula_rank_1`..`formula_rank_5`, `estimated_fdr`, `posterior_error_probability`, and `batch_q_value`; `engine.estimate_batch_fdr()` computes dataset-wide top-1 `q_values`.
- **CLI outputs:** Writes `msbuddy_result_summary.tsv` (with `batch_q_value`); adding `-d` / `--details` writes per-feature `formula_results.tsv` (adduct-aware `mz_error_ppm`, explained peaks, probabilities, subformula assignments) plus `ms1_preprocessed.tsv` and `ms2_preprocessed.tsv`.

## Python quick start

### 1. Annotate an MGF file

```python
from msbuddy import Msbuddy, MsbuddyConfig

engine = Msbuddy(MsbuddyConfig(ms_instr="orbitrap"))  # also supports "fticr" and "tof" ("qtof"/"timstof" aliases)
engine.load_mgf("input_file.mgf")
engine.annotate_formula()
results = engine.get_summary()
```

Halogens (`F, Cl, Br, I`) are searched by default; set `MsbuddyConfig(halogen=False)` only when prior knowledge rules out halogens. See the [demo MGF](demo/input_file.mgf), [quick start](https://msbuddy.readthedocs.io/en/latest/quickstart.html), and [configuration guide](https://msbuddy.readthedocs.io/en/latest/config.html) for more options.

### 2. Annotate from USIs

```python
from msbuddy import Msbuddy, MsbuddyConfig

engine = Msbuddy(MsbuddyConfig(ms_instr="orbitrap"))
engine.load_usi([
    "mzspec:GNPS:GNPS-LIBRARY:accession:CCMSLIB00003740036",
    "mzspec:GNPS:GNPS-LIBRARY:accession:CCMSLIB00003740037",
])
engine.annotate_formula()
results = engine.get_summary()
```

### 3. Annotate spectra (including pooled MS2 and `|z| >= 2`) via Python API

```python
from msbuddy import MetaFeature, Msbuddy, MsbuddyConfig, Spectrum

features = [
    MetaFeature(
        identifier="feature_1",
        mz=181.0707,
        charge=1,
        adduct="[M+H]+",  # optional; defaults to [M+H]+ / [M-H]-, or use "auto"
        ms1=Spectrum([181.0707, 182.0741], [100.0, 6.7]),  # optional MS1 isotope pattern
        ms2=[  # single Spectrum or list of Spectra for multi-spectrum pooling
            Spectrum([109.0284, 127.0390, 145.0495, 163.0601], [30.0, 60.0, 100.0, 80.0]),
            Spectrum([109.0284, 127.0390, 145.0495], [45.0, 80.0, 100.0]),
        ],
    ),
    MetaFeature(
        identifier="feature_2",
        mz=179.0561,
        charge=-1,
        ms2=Spectrum([89.0244, 101.0244, 119.0350, 161.0455], [100.0, 40.0, 70.0, 30.0]),
    ),
]

engine = Msbuddy(MsbuddyConfig(ms_instr="orbitrap"))
engine.add_data(features)
engine.annotate_formula()
results = engine.get_summary()
```

See the [API reference](https://msbuddy.readthedocs.io/en/latest/pyapi.html) for direct mass-to-formula search (`mass_to_formula`, `mz_to_formula`) and fragment subformula assignment (`assign_subformula`).

## Command line

```bash
msbuddy -mgf input_file.mgf -output results -ms orbitrap -details
```

Run `msbuddy --help` for options (including `--download-data`, `--download-compatibility`, `--no-halogen`, and element bounds defaulting to `C<=150, H<=300, N<=30, O<=50, F<=80`). The [command-line guide](https://msbuddy.readthedocs.io/en/latest/cmdapi.html) covers USIs, batch input, parallel processing, and exports.

## Upgrading and contributing

See the [migration guide](https://msbuddy.readthedocs.io/en/latest/migration.html) when upgrading older scripts. Release details are in the [version updates](https://msbuddy.readthedocs.io/en/latest/updates.html) and [changelog](changelog.md).

The annotation pipeline is in `msbuddy/` and tests are in `tests/`. Run `python -m unittest discover -s tests -v` after installing development dependencies. See the [development guide](https://msbuddy.readthedocs.io/en/latest/development.html).

## 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](https://doi.org/10.1038/s41592-023-01850-x)

## License and contact

Apache License 2.0. Contact: sxing@fudan.edu.cn.
