robert05 commited on
Commit
1c9758e
·
verified ·
1 Parent(s): ec0e68c

Upload folder using huggingface_hub

Browse files
Files changed (3) hide show
  1. .DS_Store +0 -0
  2. 12/count.py +158 -0
  3. count.py +158 -0
.DS_Store CHANGED
Binary files a/.DS_Store and b/.DS_Store differ
 
12/count.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # count_mgf_peptides.py
2
+ # -*- coding: utf-8 -*-
3
+
4
+ import re
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ import pandas as pd
9
+
10
+
11
+ SEQ_PATTERNS = [
12
+ re.compile(r"^SEQ\s*=\s*(.+)$", re.IGNORECASE),
13
+ re.compile(r"^PEPTIDE\s*=\s*(.+)$", re.IGNORECASE),
14
+ re.compile(r"\bSEQ\s*=\s*([^;\s]+)", re.IGNORECASE), # inside TITLE/COMMENT
15
+ re.compile(r"\bSEQUENCE\s*=\s*([^;\s]+)", re.IGNORECASE), # inside TITLE/COMMENT
16
+ re.compile(r"\bPep(?:tide)?\s*=\s*([^;\s]+)", re.IGNORECASE), # Pep= / Peptide=
17
+ ]
18
+
19
+ def normalize_raw(seq: str) -> str:
20
+ s = seq.strip().strip('"').strip("'")
21
+ # 截断在第一个空白处(有些 TITLE 里会把很多字段拼一起)
22
+ s = s.split()[0]
23
+ return s
24
+
25
+ def strip_modifications(seq: str) -> str:
26
+ """
27
+ 将修饰等非字母字符去掉,仅保留 A-Z 作为“纯肽段序列”口径。
28
+ 例如: "M(ox)PEP[+16]TIDE" -> "MPEPTIDE"
29
+ """
30
+ s = normalize_raw(seq).upper()
31
+ s = re.sub(r"[^A-Z]", "", s)
32
+ return s
33
+
34
+ def extract_peptide_from_line(line: str):
35
+ line = line.strip()
36
+ for pat in SEQ_PATTERNS[:2]:
37
+ m = pat.match(line)
38
+ if m:
39
+ return m.group(1).strip()
40
+ # 其他模式一般在 TITLE/COMMENT 这种行里
41
+ for pat in SEQ_PATTERNS[2:]:
42
+ m = pat.search(line)
43
+ if m:
44
+ return m.group(1).strip()
45
+ return None
46
+
47
+ def parse_mgf_file(mgf_path: Path):
48
+ """
49
+ 返回:
50
+ peptides_raw: set[str] (原始提取到的序列/字段值)
51
+ peptides_stripped: set[str] (去修饰后仅A-Z)
52
+ spectra_cnt: int (BEGIN IONS ... END IONS 块数)
53
+ """
54
+ peptides_raw = set()
55
+ peptides_stripped = set()
56
+ spectra_cnt = 0
57
+
58
+ in_block = False
59
+ current_seq = None
60
+
61
+ with mgf_path.open("r", encoding="utf-8", errors="ignore") as f:
62
+ for line in f:
63
+ s = line.strip()
64
+ if not s:
65
+ continue
66
+
67
+ up = s.upper()
68
+ if up.startswith("BEGIN IONS"):
69
+ in_block = True
70
+ current_seq = None
71
+ continue
72
+
73
+ if up.startswith("END IONS"):
74
+ if in_block:
75
+ spectra_cnt += 1
76
+ if current_seq:
77
+ raw = normalize_raw(current_seq)
78
+ stripped = strip_modifications(current_seq)
79
+ if raw:
80
+ peptides_raw.add(raw)
81
+ if stripped:
82
+ peptides_stripped.add(stripped)
83
+ in_block = False
84
+ current_seq = None
85
+ continue
86
+
87
+ if in_block:
88
+ seq_candidate = extract_peptide_from_line(s)
89
+ if seq_candidate and (current_seq is None):
90
+ current_seq = seq_candidate
91
+
92
+ return peptides_raw, peptides_stripped, spectra_cnt
93
+
94
+ def main():
95
+ # 默认:脚本同级目录下的 Data/
96
+ base_dir = Path(sys.argv[1]).expanduser().resolve() if len(sys.argv) > 1 else (Path(__file__).resolve().parent)
97
+ if not base_dir.exists():
98
+ print(f"[ERROR] Data directory not found: {base_dir}")
99
+ print("用法: python count_mgf_peptides.py /path/to/Data")
100
+ sys.exit(1)
101
+
102
+ mgf_files = sorted(base_dir.rglob("*.mgf"))
103
+ if not mgf_files:
104
+ print(f"[WARN] No .mgf files found under: {base_dir}")
105
+ sys.exit(0)
106
+
107
+ rows = []
108
+ global_raw = set()
109
+ global_stripped = set()
110
+
111
+ for p in mgf_files:
112
+ peptides_raw, peptides_stripped, spectra_cnt = parse_mgf_file(p)
113
+ global_raw |= peptides_raw
114
+ global_stripped |= peptides_stripped
115
+
116
+ rel = p.relative_to(base_dir)
117
+ organism = rel.parts[0] if len(rel.parts) >= 2 else ""
118
+ rows.append({
119
+ "organism_folder": organism,
120
+ "file_name": p.name,
121
+ "relative_path": str(rel),
122
+ "spectra_blocks": spectra_cnt,
123
+ "unique_peptides_stripped(A-Z)": len(peptides_stripped),
124
+ "unique_peptides_raw": len(peptides_raw),
125
+ })
126
+
127
+ df = pd.DataFrame(rows).sort_values(["organism_folder", "file_name"]).reset_index(drop=True)
128
+
129
+ # 汇总行
130
+ summary = pd.DataFrame([{
131
+ "organism_folder": "TOTAL",
132
+ "file_name": "",
133
+ "relative_path": "",
134
+ "spectra_blocks": int(df["spectra_blocks"].sum()),
135
+ "unique_peptides_stripped(A-Z)": len(global_stripped),
136
+ "unique_peptides_raw": len(global_raw),
137
+ }])
138
+
139
+ out_xlsx = "/Users/guanmumu/Desktop/Data/mgf_unique_peptides_summary.xlsx"
140
+ with pd.ExcelWriter(out_xlsx, engine="openpyxl") as writer:
141
+ df.to_excel(writer, index=False, sheet_name="per_file")
142
+ summary.to_excel(writer, index=False, sheet_name="summary")
143
+
144
+ # 可选:把全局unique peptide列表也落盘,方便你核对
145
+ (Path.cwd() / "global_unique_peptides_stripped.txt").write_text(
146
+ "\n".join(sorted(global_stripped)) + "\n", encoding="utf-8"
147
+ )
148
+ (Path.cwd() / "global_unique_peptides_raw.txt").write_text(
149
+ "\n".join(sorted(global_raw)) + "\n", encoding="utf-8"
150
+ )
151
+
152
+ print(f"[OK] Found {len(mgf_files)} MGF files under: {base_dir}")
153
+ print(f"[OK] Excel written to: {out_xlsx}")
154
+ print(f"[OK] Global unique peptides (stripped) = {len(global_stripped)}")
155
+ print(f"[OK] Global unique peptides (raw) = {len(global_raw)}")
156
+
157
+ if __name__ == "__main__":
158
+ main()
count.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # count_mgf_peptides.py
2
+ # -*- coding: utf-8 -*-
3
+
4
+ import re
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ import pandas as pd
9
+
10
+
11
+ SEQ_PATTERNS = [
12
+ re.compile(r"^SEQ\s*=\s*(.+)$", re.IGNORECASE),
13
+ re.compile(r"^PEPTIDE\s*=\s*(.+)$", re.IGNORECASE),
14
+ re.compile(r"\bSEQ\s*=\s*([^;\s]+)", re.IGNORECASE), # inside TITLE/COMMENT
15
+ re.compile(r"\bSEQUENCE\s*=\s*([^;\s]+)", re.IGNORECASE), # inside TITLE/COMMENT
16
+ re.compile(r"\bPep(?:tide)?\s*=\s*([^;\s]+)", re.IGNORECASE), # Pep= / Peptide=
17
+ ]
18
+
19
+ def normalize_raw(seq: str) -> str:
20
+ s = seq.strip().strip('"').strip("'")
21
+ # 截断在第一个空白处(有些 TITLE 里会把很多字段拼一起)
22
+ s = s.split()[0]
23
+ return s
24
+
25
+ def strip_modifications(seq: str) -> str:
26
+ """
27
+ 将修饰等非字母字符去掉,仅保留 A-Z 作为“纯肽段序列”口径。
28
+ 例如: "M(ox)PEP[+16]TIDE" -> "MPEPTIDE"
29
+ """
30
+ s = normalize_raw(seq).upper()
31
+ s = re.sub(r"[^A-Z]", "", s)
32
+ return s
33
+
34
+ def extract_peptide_from_line(line: str):
35
+ line = line.strip()
36
+ for pat in SEQ_PATTERNS[:2]:
37
+ m = pat.match(line)
38
+ if m:
39
+ return m.group(1).strip()
40
+ # 其他模式一般在 TITLE/COMMENT 这种行里
41
+ for pat in SEQ_PATTERNS[2:]:
42
+ m = pat.search(line)
43
+ if m:
44
+ return m.group(1).strip()
45
+ return None
46
+
47
+ def parse_mgf_file(mgf_path: Path):
48
+ """
49
+ 返回:
50
+ peptides_raw: set[str] (原始提取到的序列/字段值)
51
+ peptides_stripped: set[str] (去修饰后仅A-Z)
52
+ spectra_cnt: int (BEGIN IONS ... END IONS 块数)
53
+ """
54
+ peptides_raw = set()
55
+ peptides_stripped = set()
56
+ spectra_cnt = 0
57
+
58
+ in_block = False
59
+ current_seq = None
60
+
61
+ with mgf_path.open("r", encoding="utf-8", errors="ignore") as f:
62
+ for line in f:
63
+ s = line.strip()
64
+ if not s:
65
+ continue
66
+
67
+ up = s.upper()
68
+ if up.startswith("BEGIN IONS"):
69
+ in_block = True
70
+ current_seq = None
71
+ continue
72
+
73
+ if up.startswith("END IONS"):
74
+ if in_block:
75
+ spectra_cnt += 1
76
+ if current_seq:
77
+ raw = normalize_raw(current_seq)
78
+ stripped = strip_modifications(current_seq)
79
+ if raw:
80
+ peptides_raw.add(raw)
81
+ if stripped:
82
+ peptides_stripped.add(stripped)
83
+ in_block = False
84
+ current_seq = None
85
+ continue
86
+
87
+ if in_block:
88
+ seq_candidate = extract_peptide_from_line(s)
89
+ if seq_candidate and (current_seq is None):
90
+ current_seq = seq_candidate
91
+
92
+ return peptides_raw, peptides_stripped, spectra_cnt
93
+
94
+ def main():
95
+ # 默认:脚本同级目录下的 Data/
96
+ base_dir = Path(sys.argv[1]).expanduser().resolve() if len(sys.argv) > 1 else (Path(__file__).resolve().parent)
97
+ if not base_dir.exists():
98
+ print(f"[ERROR] Data directory not found: {base_dir}")
99
+ print("用法: python count_mgf_peptides.py /path/to/Data")
100
+ sys.exit(1)
101
+
102
+ mgf_files = sorted(base_dir.rglob("*.mgf"))
103
+ if not mgf_files:
104
+ print(f"[WARN] No .mgf files found under: {base_dir}")
105
+ sys.exit(0)
106
+
107
+ rows = []
108
+ global_raw = set()
109
+ global_stripped = set()
110
+
111
+ for p in mgf_files:
112
+ peptides_raw, peptides_stripped, spectra_cnt = parse_mgf_file(p)
113
+ global_raw |= peptides_raw
114
+ global_stripped |= peptides_stripped
115
+
116
+ rel = p.relative_to(base_dir)
117
+ organism = rel.parts[0] if len(rel.parts) >= 2 else ""
118
+ rows.append({
119
+ "organism_folder": organism,
120
+ "file_name": p.name,
121
+ "relative_path": str(rel),
122
+ "spectra_blocks": spectra_cnt,
123
+ "unique_peptides_stripped(A-Z)": len(peptides_stripped),
124
+ "unique_peptides_raw": len(peptides_raw),
125
+ })
126
+
127
+ df = pd.DataFrame(rows).sort_values(["organism_folder", "file_name"]).reset_index(drop=True)
128
+
129
+ # 汇总行
130
+ summary = pd.DataFrame([{
131
+ "organism_folder": "TOTAL",
132
+ "file_name": "",
133
+ "relative_path": "",
134
+ "spectra_blocks": int(df["spectra_blocks"].sum()),
135
+ "unique_peptides_stripped(A-Z)": len(global_stripped),
136
+ "unique_peptides_raw": len(global_raw),
137
+ }])
138
+
139
+ out_xlsx = "/Users/guanmumu/Desktop/Data/mgf_unique_peptides_summary.xlsx"
140
+ with pd.ExcelWriter(out_xlsx, engine="openpyxl") as writer:
141
+ df.to_excel(writer, index=False, sheet_name="per_file")
142
+ summary.to_excel(writer, index=False, sheet_name="summary")
143
+
144
+ # 可选:把全局unique peptide列表也落盘,方便你核对
145
+ (Path.cwd() / "global_unique_peptides_stripped.txt").write_text(
146
+ "\n".join(sorted(global_stripped)) + "\n", encoding="utf-8"
147
+ )
148
+ (Path.cwd() / "global_unique_peptides_raw.txt").write_text(
149
+ "\n".join(sorted(global_raw)) + "\n", encoding="utf-8"
150
+ )
151
+
152
+ print(f"[OK] Found {len(mgf_files)} MGF files under: {base_dir}")
153
+ print(f"[OK] Excel written to: {out_xlsx}")
154
+ print(f"[OK] Global unique peptides (stripped) = {len(global_stripped)}")
155
+ print(f"[OK] Global unique peptides (raw) = {len(global_raw)}")
156
+
157
+ if __name__ == "__main__":
158
+ main()