File size: 3,789 Bytes
db32e07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
"""
Prepare JSONL for Spectra-Reason-GCD: peaks (list of [mz, int]) + smiles.
Input: TSV with columns mzs, intensities, smiles (e.g. MassSpecGym) or MGF + metadata.
"""
from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))


def parse_spec_array(s: str) -> list[float]:
    if isinstance(s, (list, tuple)):
        return [float(x) for x in s]
    return [float(x) for x in str(s).split(",") if x.strip()]


def parse_args() -> argparse.Namespace:
    p = argparse.ArgumentParser(description="Prepare peaks+smiles JSONL for CoT training.")
    p.add_argument("--tsv", default=None, help="TSV with mzs, intensities, smiles columns")
    p.add_argument("--mgf", default=None, help="MGF file (requires smiles in TITLE or separate mapping)")
    p.add_argument("--output-jsonl", required=True)
    p.add_argument("--max-peaks", type=int, default=60)
    p.add_argument("--fold", default=None, help="If TSV has 'fold', filter to this (e.g. train)")
    return p.parse_args()


def main() -> None:
    args = parse_args()
    out_path = Path(args.output_jsonl)
    out_path.parent.mkdir(parents=True, exist_ok=True)
    records = []

    if args.tsv:
        import csv
        with open(args.tsv, "r", encoding="utf-8") as f:
            reader = csv.DictReader(f, delimiter="\t")
            rows = list(reader)
        if not rows or "mzs" not in rows[0] or "intensities" not in rows[0] or "smiles" not in rows[0]:
            raise ValueError("TSV must have mzs, intensities, smiles columns")
        for row in rows:
            if args.fold and "fold" in row and row.get("fold") != args.fold:
                continue
            mzs = parse_spec_array(row["mzs"])
            intens = parse_spec_array(row["intensities"])
            peaks = [[m, i] for m, i in zip(mzs, intens)]
            peaks = sorted(peaks, key=lambda x: x[1], reverse=True)[: args.max_peaks]
            rec = {
                "peaks": peaks,
                "smiles": str(row["smiles"]).strip(),
            }
            if "formula" in row and row["formula"]:
                rec["formula"] = str(row["formula"]).strip()
            if "precursor_mz" in row and row["precursor_mz"]:
                try:
                    rec["precursor_mz"] = float(row["precursor_mz"])
                except (ValueError, TypeError):
                    pass
            if "precursor_formula" in row and row["precursor_formula"] and "formula" not in rec:
                rec["formula"] = str(row["precursor_formula"]).strip()
            records.append(rec)
    elif args.mgf:
        try:
            from pyteomics import mgf
        except ImportError:
            raise ImportError("pyteomics required for MGF: pip install pyteomics")
        with mgf.MGF(args.mgf) as reader:
            for spec in reader:
                mz = spec.get("m/z array", [])
                iarr = spec.get("intensity array", [])
                peaks = [[float(m), float(i)] for m, i in zip(mz, iarr)]
                peaks = sorted(peaks, key=lambda x: x[1], reverse=True)[: args.max_peaks]
                smiles = spec.get("params", {}).get("SMILES", spec.get("params", {}).get("smiles", ""))
                if not smiles and "TITLE" in spec.get("params", {}):
                    smiles = spec["params"]["TITLE"]
                records.append({"peaks": peaks, "smiles": str(smiles).strip()})
    else:
        raise ValueError("Provide --tsv or --mgf")

    with open(out_path, "w") as f:
        for r in records:
            f.write(json.dumps(r) + "\n")
    print(f"Wrote {len(records)} records to {out_path}")


if __name__ == "__main__":
    main()