Skip to main content

MSFormulator

MSFormulator 是基于扩散模型(diffusion)的质谱二级碎片(MS2)分子式预测方法。 本仓库是对原始 dxzx2/ms2_formula_model 的整理版本:将原本堆在单个 main.py(约 1480 行)中的 化学计算、推理流水线、模型定义拆分成了清晰的 Python 包结构,并把数据/权重与代码分离, 现已可经 pip install 安装与发布(PyPI 包名 msformulator)。

更新日志

  • v0.1.12:修复「组合筛选」中 top10 模型输出未被使用的问题——此前候选枚举只读取 top1 分支输出, top10 模型(约 825MB 权重)的推理被白白浪费;现 top10 分支输出真正驱动候选枚举,预测结果相较 v0.1.10 可能略有变化(属预期行为)。另改进扩散进度条:新增 step X/Y 显示,便于直观确认实际 去噪步数(如设 n_steps=50 即显示 step 50/50,此前 t=199→0 仅为扩散时间步、并非迭代次数)。
  • v0.1.10:新增扩散步数 n_steps、实时进度显示(含当前时间步 t 与 top1 候选分子式)、 组合筛选开关 screen(关闭后仅返回模型直接输出的 top1 分子式)。

目录结构

ms2_formula_model_organized/        # 工作目录(即本仓库根)
├── run.py                      # 命令行入口:python run.py <pr_mz> <mz2> <type> <peak_type>
├── pyproject.toml             # 打包元数据(包名 msformulator)
├── MANIFEST.in                # 排除大体积权重,避免打进分发包
├── requirements.txt           # 依赖
├── README.md
├── msformulator/              # 核心包(import 名,即方法名)
│   ├── __init__.py            # 暴露 predict_formula / MSFormulator / GaussianDiffusion / ensure_weights
│   ├── config.py              # 数据/权重的路径配置(不再硬编码相对路径)
│   ├── model.py               # 神经网络:MSFormulator / GaussianDiffusion / UNet1D
│   ├── chemistry.py           # 纯计算:质量微调、不饱和度校验、ppm、分子式解析等
│   ├── inference.py           # 推理流水线:注释查找→峰编码→模型预测→分子式解码
│   ├── cli.py                 # 命令行入口(注册为 `msformulator` 命令)
│   ├── download.py            # 权重解析与按需下载
│   ├── main.py                # 入口函数 predict_formula()(main() 为兼容别名)
│   └── data/                  # 小型数据:embedding_parameters.pth、mass_zhushi.npy
├── weights/                    # 模型权重(两个 .pt,体积较大,不随包分发)
└── scripts/                    # 辅助/遗留脚本
    ├── find_cl.py
    ├── find_pubchem_formula.py
    ├── read_pubchem.py
    ├── add_zhushi.py
    └── legacy/                 # 旧版本 main_quick.py / TEST_BIAOZHUN.py(见下“已知问题”)

入口函数

推荐入口为 predict_formula(precursor_mz, peaks, precursor_type, peak_type), 旧接口 main(pr_mz, mz2, type_str, peak_type_str) 仍保留作兼容别名。

参数 含义 示例
precursor_mz 母离子精确质量 (float) 439.326
peaks 二级碎片峰列表 [[mz, intensity], ...](也可传 None / "[]") []
precursor_type 母离子加合类型 "[M+H]+"
peak_type 碎片峰加合类型 "[M+H]+"

返回按 ppm 误差升序排列的候选分子式列表,每个元素形如 {"pred": "C12H...", "ppm": <float>}。

运行方式

  1. 安装依赖:pip install -r requirements.txt
  2. 命令行(源码方式):
    python run.py 439.326 "[]" "[M+H]+" "[M+H]+"
    
    或作为模块:
    python -m msformulator 439.326 "[]" "[M+H]+" "[M+H]+"
    
  3. 在 Python 中调用(推荐):
    from msformulator import predict_formula
    print(predict_formula(439.326, [], "[M+H]+", "[M+H]+"))
    

运行推理时需要两个 .pt 权重文件(约 1.5GB)与 msformulator/data/ 下的小型数据文件。 小型数据文件随包分发;权重文件不随包分发,首次运行会自动下载(见下文“安装 / 权重”)。

扩散步数、实时进度与组合筛选(v0.1.10 新增)

1. 控制扩散次数(--t / n_steps)

扩散模型默认去噪 200 步。可用 --t(命令行)或 n_steps(API)指定更少的步数, 在默认时间轴上均匀子采样(strided 采样)以减少迭代、加快推理;超过 200 会被自动截断。

msformulator 439.326 "[]" "[M+H]+" "[M+H]+" --t 50      # 仅跑 50 步去噪
from msformulator import predict_formula
predict_formula(439.326, [], n_steps=50)   # 减少扩散次数

2. 实时进度与「当前 t 下的分子式」

默认(命令行)在去噪过程中实时刷新一行:当前时间步 t、进度百分比、进度条,以及批次中 第一条谱在当前 t 下由模型直接输出的 top1 分子式(不做后续组合筛选)。可加 --quiet 关闭。

msformulator 439.326 "[]" "[M+H]+" "[M+H]+"        # 显示进度
msformulator 439.326 "[]" "[M+H]+" "[M+H]+" --quiet # 不显示
predict_formula(439.326, [], verbose=True)   # 库调用也可开启实时显示

3. 组合筛选开关(--no-screen / screen)

模型的完整解码(get_formula,即组合筛选步骤:在母离子质量约束下枚举候选并校验)耗时最长。 若只想看模型直接输出的 top1 分子式,可关闭该步骤以提速:

msformulator 439.326 "[]" "[M+H]+" "[M+H]+" --no-screen
predict_formula(439.326, [], screen=False)   # 仅返回模型直接输出的 top1 分子式
  • screen=True(默认):返回按 ppm 升序的候选分子式列表(与旧版本一致)。
  • screen=False:跳过 top10 模型与枚举解码,直接返回单条 {"pred": ..., "ppm": ...}, 速度更快,但候选单一。

安装(pip)

本包已配置为标准可安装项目(pyproject.toml,分发名 msformulator)。

1. 本地 / 源码安装

cd ms2_formula_model_organized
pip install .

2. 从 PyPI 安装(发布后)

pip install msformulator

3. 权重获取(开箱即用)

权重较大(约 1.5GB),不打包进 wheel。安装后首次运行会自动从 Hugging Face Hub 下载到 ~/.cache/msformulator/weights,之后复用、无需重复下载。无需任何额外配置即可开箱运行。

如需覆盖默认行为,可设置环境变量:

  • MS2_WEIGHTS_DIR:指向已放好两个 .pt 的目录(不触发下载);
  • MS2_WEIGHTS_URL:自定义权重基地址(GitHub Release / HuggingFace / 对象存储均可);
  • MS2_CACHE_DIR:覆盖默认缓存根目录。
# 方式 A:本地已存在权重目录,跳过下载
export MS2_WEIGHTS_DIR="/path/to/your/weights"
msformulator 439.326 "[]" "[M+H]+" "[M+H]+"

# 方式 B:指定自定义下载地址
export MS2_WEIGHTS_URL="https://github.com/<user>/<repo>/releases/download/v1.0.0"
msformulator 439.326 "[]" "[M+H]+" "[M+H]+"

默认下载地址与权重字节数(用于完整性校验)已在 msformulator/download.py 中配置。

发布到 PyPI

cd ms2_formula_model_organized
pip install build twine
python -m build            # 生成 dist/ 下的 sdist 与 wheel
twine check dist/*         # 检查分发包合法性
twine upload dist/*        # 上传到 PyPI(需提前注册 PyPI 账号)

MANIFEST.in 已配置为排除 weights/ 与 scripts/,确保 1.5GB 权重不会被打进 sdist/wheel。 升版时记得同步修改 pyproject.toml 中的 version。

模块说明

  • chemistry.py:原 main.py 中的纯计算函数(无 torch 依赖)。包括 tiaozheng_f / tiaozheng_f2(质量微调)、calculate_ppm、calculate_molecular_mass、 check_molecular_formula、extract_*_numbers(分子式各元素数量解析)、parse_ion_pattern / get_mass 等。
  • inference.py:推理流水线。get_zhushi(按质量查找注释)、get_peak_mass(碎片峰编码)、 model_test(加载权重并做扩散模型预测)、get_one_formula_tiaozheng / get_formula(解码分子式)。
  • model.py:原 model.py 完整保留,仅将 embedding_parameters.pth 的加载路径改为相对于包目录解析。 核心网络类即 MSFormulator(配合 GaussianDiffusion 做扩散采样)。
  • download.py:权重解析与下载(支持 MS2_WEIGHTS_DIR / MS2_WEIGHTS_URL / MS2_CACHE_DIR 环境变量)。

已知问题

  • scripts/legacy/main_quick.py 与 scripts/legacy/TEST_BIAOZHUN.py 引用了 from msformulator.model import PCTE, 但 model.py 中并不存在 PCTE 类(这是原始代码就存在的问题),因此这两个文件当前无法运行。 它们作为历史版本保留在 legacy/ 中,待补齐 PCTE 定义后可恢复使用。
  • 主入口 main() 使用的是 MSFormulator,可正常运行(依赖 weights/ 中的权重文件)。

Metadata

Release files for msformulator 0.1.12

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

Source distribution (sdist)

Source distribution for msformulator 0.1.12
File Size Uploaded Provenance Actions
msformulator-0.1.12.tar.gz 12.2 MB Without provenance Details for msformulator-0.1.12.tar.gz

Built distribution (wheel)

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

Total release size: 24.7 MB

Release files / msformulator-0.1.12.tar.gz

Download URL msformulator-0.1.12.tar.gz
Size 12.2 MB
Tags Source
SHA-256 checksum
How to use checksums
6c5eecaea4d8a1373b55b3c503283fc1d0bba4840bcd650b9d336ee2df9ac7c1
BLAKE2b-256 checksum
How to use checksums
e46c76a4375db008c2d24045c80da0f31cb4f171ca39d0e1c9fb41251fd988cc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Release files / msformulator-0.1.12-py3-none-any.whl

Download URL msformulator-0.1.12-py3-none-any.whl
Size 12.5 MB
Tags Python 3
SHA-256 checksum
How to use checksums
e1f86346991d291a2d785d5863b99d78700046b3bd5f3a88e0decf210fabc7cd
BLAKE2b-256 checksum
How to use checksums
a0f4e0370b2c73648acc2376aecca3e101deb49f0055503521968f21bac8cc71
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Security for msformulator 0.1.12

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