File size: 5,368 Bytes
1c9758e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# count_mgf_peptides.py
# -*- coding: utf-8 -*-

import re
import sys
from pathlib import Path

import pandas as pd


SEQ_PATTERNS = [
    re.compile(r"^SEQ\s*=\s*(.+)$", re.IGNORECASE),
    re.compile(r"^PEPTIDE\s*=\s*(.+)$", re.IGNORECASE),
    re.compile(r"\bSEQ\s*=\s*([^;\s]+)", re.IGNORECASE),           # inside TITLE/COMMENT
    re.compile(r"\bSEQUENCE\s*=\s*([^;\s]+)", re.IGNORECASE),      # inside TITLE/COMMENT
    re.compile(r"\bPep(?:tide)?\s*=\s*([^;\s]+)", re.IGNORECASE),  # Pep= / Peptide=
]

def normalize_raw(seq: str) -> str:
    s = seq.strip().strip('"').strip("'")
    # 截断在第一个空白处(有些 TITLE 里会把很多字段拼一起)
    s = s.split()[0]
    return s

def strip_modifications(seq: str) -> str:
    """
    将修饰等非字母字符去掉,仅保留 A-Z 作为“纯肽段序列”口径。
    例如: "M(ox)PEP[+16]TIDE" -> "MPEPTIDE"
    """
    s = normalize_raw(seq).upper()
    s = re.sub(r"[^A-Z]", "", s)
    return s

def extract_peptide_from_line(line: str):
    line = line.strip()
    for pat in SEQ_PATTERNS[:2]:
        m = pat.match(line)
        if m:
            return m.group(1).strip()
    # 其他模式一般在 TITLE/COMMENT 这种行里
    for pat in SEQ_PATTERNS[2:]:
        m = pat.search(line)
        if m:
            return m.group(1).strip()
    return None

def parse_mgf_file(mgf_path: Path):
    """
    返回:
      peptides_raw: set[str]      (原始提取到的序列/字段值)
      peptides_stripped: set[str] (去修饰后仅A-Z)
      spectra_cnt: int            (BEGIN IONS ... END IONS 块数)
    """
    peptides_raw = set()
    peptides_stripped = set()
    spectra_cnt = 0

    in_block = False
    current_seq = None

    with mgf_path.open("r", encoding="utf-8", errors="ignore") as f:
        for line in f:
            s = line.strip()
            if not s:
                continue

            up = s.upper()
            if up.startswith("BEGIN IONS"):
                in_block = True
                current_seq = None
                continue

            if up.startswith("END IONS"):
                if in_block:
                    spectra_cnt += 1
                    if current_seq:
                        raw = normalize_raw(current_seq)
                        stripped = strip_modifications(current_seq)
                        if raw:
                            peptides_raw.add(raw)
                        if stripped:
                            peptides_stripped.add(stripped)
                in_block = False
                current_seq = None
                continue

            if in_block:
                seq_candidate = extract_peptide_from_line(s)
                if seq_candidate and (current_seq is None):
                    current_seq = seq_candidate

    return peptides_raw, peptides_stripped, spectra_cnt

def main():
    # 默认:脚本同级目录下的 Data/
    base_dir = Path(sys.argv[1]).expanduser().resolve() if len(sys.argv) > 1 else (Path(__file__).resolve().parent)
    if not base_dir.exists():
        print(f"[ERROR] Data directory not found: {base_dir}")
        print("用法: python count_mgf_peptides.py /path/to/Data")
        sys.exit(1)

    mgf_files = sorted(base_dir.rglob("*.mgf"))
    if not mgf_files:
        print(f"[WARN] No .mgf files found under: {base_dir}")
        sys.exit(0)

    rows = []
    global_raw = set()
    global_stripped = set()

    for p in mgf_files:
        peptides_raw, peptides_stripped, spectra_cnt = parse_mgf_file(p)
        global_raw |= peptides_raw
        global_stripped |= peptides_stripped

        rel = p.relative_to(base_dir)
        organism = rel.parts[0] if len(rel.parts) >= 2 else ""
        rows.append({
            "organism_folder": organism,
            "file_name": p.name,
            "relative_path": str(rel),
            "spectra_blocks": spectra_cnt,
            "unique_peptides_stripped(A-Z)": len(peptides_stripped),
            "unique_peptides_raw": len(peptides_raw),
        })

    df = pd.DataFrame(rows).sort_values(["organism_folder", "file_name"]).reset_index(drop=True)

    # 汇总行
    summary = pd.DataFrame([{
        "organism_folder": "TOTAL",
        "file_name": "",
        "relative_path": "",
        "spectra_blocks": int(df["spectra_blocks"].sum()),
        "unique_peptides_stripped(A-Z)": len(global_stripped),
        "unique_peptides_raw": len(global_raw),
    }])

    out_xlsx = "/Users/guanmumu/Desktop/Data/mgf_unique_peptides_summary.xlsx"
    with pd.ExcelWriter(out_xlsx, engine="openpyxl") as writer:
        df.to_excel(writer, index=False, sheet_name="per_file")
        summary.to_excel(writer, index=False, sheet_name="summary")

    # 可选:把全局unique peptide列表也落盘,方便你核对
    (Path.cwd() / "global_unique_peptides_stripped.txt").write_text(
        "\n".join(sorted(global_stripped)) + "\n", encoding="utf-8"
    )
    (Path.cwd() / "global_unique_peptides_raw.txt").write_text(
        "\n".join(sorted(global_raw)) + "\n", encoding="utf-8"
    )

    print(f"[OK] Found {len(mgf_files)} MGF files under: {base_dir}")
    print(f"[OK] Excel written to: {out_xlsx}")
    print(f"[OK] Global unique peptides (stripped) = {len(global_stripped)}")
    print(f"[OK] Global unique peptides (raw)      = {len(global_raw)}")

if __name__ == "__main__":
    main()