MSFormulator
MSFormulator 是基于扩散模型(diffusion)的质谱二级碎片(MS2)分子式预测方法。
本仓库是对原始 dxzx2/ms2_formula_model 的整理版本:将原本堆在单个 main.py(约 1480 行)中的
化学计算、推理流水线、模型定义拆分成了清晰的 Python 包结构,并把数据/权重与代码分离,
现已可经 pip install 安装与发布(PyPI 包名 msformulator)。
目录结构
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>}。
运行方式
- 安装依赖:
pip install -r requirements.txt - 命令行(源码方式):
python run.py 439.326 "[]" "[M+H]+" "[M+H]+"
或作为模块:python -m msformulator 439.326 "[]" "[M+H]+" "[M+H]+"
- 在 Python 中调用(推荐):
from msformulator import predict_formula print(predict_formula(439.326, [], "[M+H]+", "[M+H]+"))
运行推理时需要两个
.pt权重文件(约 1.5GB)与msformulator/data/下的小型数据文件。 小型数据文件随包分发;权重文件不随包分发,首次运行会自动下载(见下文“安装 / 权重”)。
扩散步数、实时进度与组合筛选(v0.1.11)
本节的三个开关(
n_steps/verbose/enable_screening)在单谱predict_formula与批量predict_formulas(n>1)上都可用,两个接口的语义完全一致。
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 / enable_screening)
模型的完整解码(get_formula,即组合筛选步骤:在母离子质量约束下枚举候选并校验)耗时最长。
若只想看模型直接输出的 top1 分子式,可关闭该步骤以提速:
msformulator 439.326 "[]" "[M+H]+" "[M+H]+" --no-screen
predict_formula(439.326, [], enable_screening=False) # 仅返回模型直接输出的 top1 分子式
enable_screening=True(默认):返回按 ppm 升序的候选分子式列表(与旧版本一致)。enable_screening=False:跳过 top10 模型与枚举解码,直接返回单条{"pred": ..., "ppm": ...}, 速度更快,但候选单一。
批量接口同理(每条谱都遵循同一开关):
from msformulator import predict_formulas
predict_formulas(spectra, n_steps=50, enable_screening=False) # n>1 时同样生效
安装(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 依赖)。包括adjust_formula_by_mass/adjust_counts_by_mass(质量微调)、calculate_ppm、calculate_molecular_mass、check_molecular_formula、extract_*_numbers(分子式各元素数量解析)、parse_ion_pattern/get_mass等。 - inference.py:推理流水线。
get_adduct_encoding(按质量查找加合离子编码)、get_peak_mass(碎片峰编码)、model_test(加载权重并做扩散模型预测)、build_argmax_formula/get_formula(解码分子式)。 - model.py:原
model.py完整保留,仅将embedding_parameters.pth的加载路径改为相对于包目录解析。 核心网络类即MSFormulator(配合GaussianDiffusion做扩散采样)。 注意:MSFormulator内部的权重属性名(如embeddings_biaozhun、embeddings_zero、xt_l) 与训练好的权重文件一一对应,不可重命名,否则 checkpoint 无法加载。 - 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.11
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| msformulator-0.1.11.tar.gz | 12.2 MB | Without provenance | Details for msformulator-0.1.11.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| msformulator-0.1.11-py3-none-any.whl | Python 3 | none | any | Details for msformulator-0.1.11-py3-none-any.whl |
Total release size: 24.7 MB
Release files / msformulator-0.1.11.tar.gz
| Download URL | msformulator-0.1.11.tar.gz |
|---|---|
| Size | 12.2 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
d66091dd950457b37e8d9c169950479c0748af3598aa8a4971aa4e7a54b58809
|
|
BLAKE2b-256 checksum How to use checksums |
146ac1718a4dacaa986b2fda015d0a635422b7e7537f1396b9d54410ccecff25
|
| 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.11-py3-none-any.whl
| Download URL | msformulator-0.1.11-py3-none-any.whl |
|---|---|
| Size | 12.5 MB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
74edaba5b8604293db20a0fbf7860fbfc50ad2ce472d52f9d05b27cc1bdbeaaf
|
|
BLAKE2b-256 checksum How to use checksums |
d896d989ee903549254afc6f4f399c8eefaf0b83b64019c389b7ab464eacc703
|
| 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.11
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.