| |
| """ |
| 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() |
|
|