robert05 commited on
Commit
dfeb49e
·
verified ·
1 Parent(s): 2f9cab1

Delete msp_to_mgf.py

Browse files
Files changed (1) hide show
  1. msp_to_mgf.py +0 -178
msp_to_mgf.py DELETED
@@ -1,178 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- import re
3
- from pathlib import Path
4
- from openpyxl import Workbook
5
-
6
- # =========================================================
7
- # 1) 路径配置:改这里即可
8
- # INPUT_DIR : 你截图里的 extracted 目录(存放 .msp)
9
- # OUTPUT_DIR: 输出 .mgf 的目录(会自动创建)
10
- # EXCEL_PATH: 输出统计表
11
- # =========================================================
12
- INPUT_DIR = Path("/Users/guanmumu/Desktop/Data/Rat/extracted")
13
- OUTPUT_DIR = Path("/Users/guanmumu/Desktop/Data/Rat/mgf")
14
- OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
15
-
16
- EXCEL_PATH = OUTPUT_DIR / "msp_to_mgf_summary.xlsx"
17
-
18
- # 进度打印(大文件可调)
19
- PROGRESS_EVERY_SPECTRA = 50000
20
-
21
- # =========================================================
22
- # 2) MSP 字段解析函数(保持和你单文件脚本一致)
23
- # =========================================================
24
- def parse_sequence_from_name(name_val: str) -> str:
25
- # Name: SEQUENCE/charge_...
26
- return name_val.split("/", 1)[0].strip()
27
-
28
- def parse_charge_from_name(name_val: str):
29
- m = re.search(r"/(\d+)", name_val)
30
- return int(m.group(1)) if m else None
31
-
32
- def parse_mz_exact_from_comment(line: str):
33
- # Comment: ... Mz_exact=536.5844 ...
34
- m = re.search(r"\bMz_exact=([0-9]*\.?[0-9]+)", line)
35
- return float(m.group(1)) if m else None
36
-
37
- # =========================================================
38
- # 3) 转换单个 MSP -> MGF,并返回统计信息
39
- # - Spectra count: Num peaks 次数
40
- # - Unique peptides: 对 Name: 的 seq 去重(与你单文件脚本一致)
41
- # =========================================================
42
- def convert_one_msp(msp_path: Path, mgf_path: Path):
43
- spectra_count = 0
44
- unique_peptides = set()
45
-
46
- with msp_path.open("r", encoding="utf-8", errors="replace") as fin, \
47
- mgf_path.open("w", encoding="utf-8") as fout:
48
-
49
- name_val = None
50
- seq = None
51
- charge = None
52
- mw = None # 你要求用作 PEPMASS
53
- precursor_mz = None # 仅用于辅助记录(Mz_exact)
54
-
55
- for line in fin:
56
- line = line.rstrip("\n")
57
-
58
- if line.startswith("Name:"):
59
- name_val = line.split("Name:", 1)[1].strip()
60
- seq = parse_sequence_from_name(name_val)
61
- charge = parse_charge_from_name(name_val)
62
- unique_peptides.add(seq)
63
-
64
- elif line.startswith("MW:"):
65
- try:
66
- mw = float(line.split("MW:", 1)[1].strip())
67
- except Exception:
68
- mw = None
69
-
70
- elif line.startswith("Comment:"):
71
- precursor_mz = parse_mz_exact_from_comment(line)
72
-
73
- elif line.startswith("Num peaks:"):
74
- num_peaks = int(line.split("Num peaks:", 1)[1].strip())
75
- spectra_count += 1
76
-
77
- # ===== 写一个 MGF block =====
78
- fout.write("BEGIN IONS\n")
79
-
80
- if seq is not None and charge is not None:
81
- fout.write(f"TITLE={seq}/z{charge}\n")
82
- elif seq is not None:
83
- fout.write(f"TITLE={seq}\n")
84
- else:
85
- fout.write(f"TITLE=Spectrum_{spectra_count}\n")
86
-
87
- # 你要求:PEPMASS = MW(不做换算)
88
- if mw is not None:
89
- fout.write(f"PEPMASS={mw:.6f}\n")
90
-
91
- if charge is not None:
92
- fout.write(f"CHARGE={charge}+\n")
93
-
94
- # 自定义字段
95
- if seq is not None:
96
- fout.write(f"SEQ={seq}\n")
97
-
98
- # 可选:记录 Mz_exact(不影响你要求)
99
- if precursor_mz is not None:
100
- fout.write(f"PRECURSOR_MZ={precursor_mz:.6f}\n")
101
-
102
- # 峰:每行 "m/z intensity"
103
- for _ in range(num_peaks):
104
- peak_line = next(fin).strip()
105
- if not peak_line:
106
- continue
107
- parts = peak_line.split()
108
- if len(parts) >= 2:
109
- fout.write(f"{parts[0]} {parts[1]}\n")
110
-
111
- fout.write("END IONS\n\n")
112
-
113
- # reset 当前谱状态(与你单文件脚本一致)
114
- name_val = None
115
- seq = None
116
- charge = None
117
- mw = None
118
- precursor_mz = None
119
-
120
- if spectra_count % PROGRESS_EVERY_SPECTRA == 0:
121
- print(f" ... {msp_path.name}: spectra={spectra_count}")
122
-
123
- return spectra_count, len(unique_peptides)
124
-
125
- # =========================================================
126
- # 4) 写 Excel(3列:文件名 / Spectra count / Unique peptides)
127
- # =========================================================
128
- def write_excel(excel_path: Path, rows):
129
- wb = Workbook()
130
- ws = wb.active
131
- ws.title = "summary"
132
-
133
- for r in rows:
134
- ws.append(list(r))
135
-
136
- ws.column_dimensions["A"].width = 55
137
- ws.column_dimensions["B"].width = 18
138
- ws.column_dimensions["C"].width = 20
139
-
140
- wb.save(excel_path)
141
-
142
- # =========================================================
143
- # 5) 批量处理
144
- # =========================================================
145
- def main():
146
- if not INPUT_DIR.exists():
147
- raise FileNotFoundError(f"INPUT_DIR not found: {INPUT_DIR}")
148
-
149
- msp_files = sorted(INPUT_DIR.glob("*.msp"))
150
- if not msp_files:
151
- print(f"No .msp files found in: {INPUT_DIR}")
152
- return
153
-
154
- print(f"Input dir : {INPUT_DIR}")
155
- print(f"Output dir: {OUTPUT_DIR}")
156
- print(f"Found {len(msp_files)} MSP files.")
157
-
158
- rows = [("file_name", "spectra_count", "unique_peptides")]
159
-
160
- for idx, msp_path in enumerate(msp_files, 1):
161
- mgf_path = OUTPUT_DIR / (msp_path.stem + ".mgf")
162
-
163
- print(f"\n[{idx}/{len(msp_files)}] Converting: {msp_path.name}")
164
- spectra_count, unique_pep = convert_one_msp(msp_path, mgf_path)
165
-
166
- print(f" -> MGF: {mgf_path.name}")
167
- print(f" Spectra count : {spectra_count}")
168
- print(f" Unique peptides : {unique_pep}")
169
-
170
- rows.append((msp_path.name, spectra_count, unique_pep))
171
-
172
- write_excel(EXCEL_PATH, rows)
173
-
174
- print("\n================= DONE =================")
175
- print(f"Excel summary: {EXCEL_PATH}")
176
-
177
- if __name__ == "__main__":
178
- main()