yanxia / NIST /Human /msp_to_mgf.py
robert05's picture
Upload folder using huggingface_hub
8fb2f0e verified
# -*- coding: utf-8 -*-
import re
from pathlib import Path
from openpyxl import Workbook
# =========================================================
# 1) 路径配置:改这里即可
# INPUT_DIR : 你截图里的 extracted 目录(存放 .msp)
# OUTPUT_DIR: 输出 .mgf 的目录(会自动创建)
# EXCEL_PATH: 输出统计表
# =========================================================
INPUT_DIR = Path("/Users/guanmumu/Desktop/Data/Human/extracted")
OUTPUT_DIR = Path("/Users/guanmumu/Desktop/Data/Human/mgf")
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
EXCEL_PATH = OUTPUT_DIR / "msp_to_mgf_summary.xlsx"
# 进度打印(大文件可调)
PROGRESS_EVERY_SPECTRA = 50000
# =========================================================
# 2) MSP 字段解析函数(保持和你单文件脚本一致)
# =========================================================
def parse_sequence_from_name(name_val: str) -> str:
# Name: SEQUENCE/charge_...
return name_val.split("/", 1)[0].strip()
def parse_charge_from_name(name_val: str):
m = re.search(r"/(\d+)", name_val)
return int(m.group(1)) if m else None
def parse_mz_exact_from_comment(line: str):
# Comment: ... Mz_exact=536.5844 ...
m = re.search(r"\bMz_exact=([0-9]*\.?[0-9]+)", line)
return float(m.group(1)) if m else None
# =========================================================
# 3) 转换单个 MSP -> MGF,并返回统计信息
# - Spectra count: Num peaks 次数
# - Unique peptides: 对 Name: 的 seq 去重(与你单文件脚本一致)
# =========================================================
def convert_one_msp(msp_path: Path, mgf_path: Path):
spectra_count = 0
unique_peptides = set()
with msp_path.open("r", encoding="utf-8", errors="replace") as fin, \
mgf_path.open("w", encoding="utf-8") as fout:
name_val = None
seq = None
charge = None
mw = None # 你要求用作 PEPMASS
precursor_mz = None # 仅用于辅助记录(Mz_exact)
for line in fin:
line = line.rstrip("\n")
if line.startswith("Name:"):
name_val = line.split("Name:", 1)[1].strip()
seq = parse_sequence_from_name(name_val)
charge = parse_charge_from_name(name_val)
unique_peptides.add(seq)
elif line.startswith("MW:"):
try:
mw = float(line.split("MW:", 1)[1].strip())
except Exception:
mw = None
elif line.startswith("Comment:"):
precursor_mz = parse_mz_exact_from_comment(line)
elif line.startswith("Num peaks:"):
num_peaks = int(line.split("Num peaks:", 1)[1].strip())
spectra_count += 1
# ===== 写一个 MGF block =====
fout.write("BEGIN IONS\n")
if seq is not None and charge is not None:
fout.write(f"TITLE={seq}/z{charge}\n")
elif seq is not None:
fout.write(f"TITLE={seq}\n")
else:
fout.write(f"TITLE=Spectrum_{spectra_count}\n")
# 你要求:PEPMASS = MW(不做换算)
if mw is not None:
fout.write(f"PEPMASS={mw:.6f}\n")
if charge is not None:
fout.write(f"CHARGE={charge}+\n")
# 自定义字段
if seq is not None:
fout.write(f"SEQ={seq}\n")
# 可选:记录 Mz_exact(不影响你要求)
if precursor_mz is not None:
fout.write(f"PRECURSOR_MZ={precursor_mz:.6f}\n")
# 峰:每行 "m/z intensity"
for _ in range(num_peaks):
peak_line = next(fin).strip()
if not peak_line:
continue
parts = peak_line.split()
if len(parts) >= 2:
fout.write(f"{parts[0]} {parts[1]}\n")
fout.write("END IONS\n\n")
# reset 当前谱状态(与你单文件脚本一致)
name_val = None
seq = None
charge = None
mw = None
precursor_mz = None
if spectra_count % PROGRESS_EVERY_SPECTRA == 0:
print(f" ... {msp_path.name}: spectra={spectra_count}")
return spectra_count, len(unique_peptides)
# =========================================================
# 4) 写 Excel(3列:文件名 / Spectra count / Unique peptides)
# =========================================================
def write_excel(excel_path: Path, rows):
wb = Workbook()
ws = wb.active
ws.title = "summary"
for r in rows:
ws.append(list(r))
ws.column_dimensions["A"].width = 55
ws.column_dimensions["B"].width = 18
ws.column_dimensions["C"].width = 20
wb.save(excel_path)
# =========================================================
# 5) 批量处理
# =========================================================
def main():
if not INPUT_DIR.exists():
raise FileNotFoundError(f"INPUT_DIR not found: {INPUT_DIR}")
msp_files = sorted(INPUT_DIR.glob("*.msp"))
if not msp_files:
print(f"No .msp files found in: {INPUT_DIR}")
return
print(f"Input dir : {INPUT_DIR}")
print(f"Output dir: {OUTPUT_DIR}")
print(f"Found {len(msp_files)} MSP files.")
rows = [("file_name", "spectra_count", "unique_peptides")]
for idx, msp_path in enumerate(msp_files, 1):
mgf_path = OUTPUT_DIR / (msp_path.stem + ".mgf")
print(f"\n[{idx}/{len(msp_files)}] Converting: {msp_path.name}")
spectra_count, unique_pep = convert_one_msp(msp_path, mgf_path)
print(f" -> MGF: {mgf_path.name}")
print(f" Spectra count : {spectra_count}")
print(f" Unique peptides : {unique_pep}")
rows.append((msp_path.name, spectra_count, unique_pep))
write_excel(EXCEL_PATH, rows)
print("\n================= DONE =================")
print(f"Excel summary: {EXCEL_PATH}")
if __name__ == "__main__":
main()