File size: 5,941 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
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
#!/usr/bin/env python
"""
Generate synthetic "Ground Truth Thought" for CoT training.

Two modes:
- **System 2 (default when formula/precursor_mz available):** Deductive trace:
  precursor analysis (formula, DoU, Nitrogen rule) → fragment logic (peak → substructure)
  → neutral loss analysis → core reconstruction → assembly. Uses RDKit for
  substructure matching and formula.
- **Fallback:** Short peak-based hints (m/z 91 → tropylium, etc.) when data or RDKit missing.
"""
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))

# Fallback fragment hints (no RDKit required)
FRAGMENT_HINTS = [
    (91, "m/z 91 (tropylium) suggests benzyl or aromatic ring"),
    (77, "m/z 77 suggests benzene ring"),
    (65, "m/z 65 suggests cyclopentadienyl or aromatic fragment"),
    (43, "m/z 43 often indicates acetyl or C3H7+"),
    (57, "m/z 57 suggests butyl or C4H9+"),
    (41, "m/z 41 suggests allyl or C3H5+"),
    (130, "m/z 130 is diagnostic for indole / 3-alkyl-indole cation"),
    (18, "loss of 18 Da suggests water (e.g. -OH)"),
    (17, "loss of 17 Da suggests ammonia or -OH"),
    (28, "loss of 28 Da suggests CO or C2H4"),
    (44, "loss of 44 Da suggests CO2"),
    (15, "loss of 15 Da suggests methyl"),
]


def get_top_peaks(peaks: list, top_k: int = 10) -> list[tuple[float, float]]:
    """Return top-k peaks by intensity."""
    sorted_peaks = sorted(peaks, key=lambda x: float(x[1]), reverse=True)
    return [(float(p[0]), float(p[1])) for p in sorted_peaks[:top_k]]


def generate_thought_fallback(peaks: list, precursor_mz: float | None = None) -> str:
    """Simple peak-based hints when System 2 is not used."""
    top = get_top_peaks(peaks, top_k=8)
    parts = []
    seen = set()
    for mz, _ in top:
        mz_round = round(mz)
        for frag_mz, hint in FRAGMENT_HINTS:
            if abs(mz_round - frag_mz) <= 2 and frag_mz not in seen:
                parts.append(hint)
                seen.add(frag_mz)
    if precursor_mz is not None and precursor_mz > 0:
        parts.insert(0, f"Precursor m/z {precursor_mz:.1f}.")
    if not parts:
        parts = [f"Key peaks at m/z {', '.join(f'{m:.0f}' for m, _ in top[:5])}."]
    return " ".join(parts)


def _load_cot_system2():
    """Load cot_system2 module without importing full spec_rag (avoids numpy etc)."""
    import importlib.util
    p = ROOT / "spec_rag" / "cot_system2.py"
    spec = importlib.util.spec_from_file_location("cot_system2", p)
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    return mod


def generate_thought_for_record(
    obj: dict, use_system2: bool = True, _system2_mod=None, output_format: str = "text"
) -> str:
    """
    Generate thought for one JSONL record. Prefer System 2 when formula or
    precursor_mz present and use_system2 is True.
    """
    peaks = obj.get("peaks", [])
    smiles = obj.get("smiles", "")
    formula = obj.get("formula") or None
    precursor_mz = obj.get("precursor_mz")
    if precursor_mz is not None:
        try:
            precursor_mz = float(precursor_mz)
        except (TypeError, ValueError):
            precursor_mz = None

    if use_system2 and (formula or precursor_mz or smiles):
        try:
            if _system2_mod is None:
                _system2_mod = _load_cot_system2()
            thought = _system2_mod.build_system2_thought(
                smiles=smiles,
                peaks=peaks if peaks else [[0, 0]],
                precursor_mz=precursor_mz,
                formula=formula,
                max_peaks=10,
                output_format=output_format,
            )
            if thought and len(thought.strip()) > 50:
                return thought.strip()
            print(f"Short thought ({len(thought)}): {thought}")
        except Exception as e:
            print(f"System 2 failed: {e}")
            pass
    if peaks:
        return generate_thought_fallback(peaks, precursor_mz)
    return "Analyzing spectrum for structural features."


def parse_args() -> argparse.Namespace:
    p = argparse.ArgumentParser(
        description="Generate synthetic thoughts for CoT (System 2 or fallback)."
    )
    p.add_argument("--input-jsonl", required=True, help="JSONL with peaks, smiles, optional formula, precursor_mz")
    p.add_argument("--output-jsonl", required=True, help="Same + 'thought' field")
    p.add_argument("--no-system2", action="store_true", help="Use only simple peak hints, no RDKit/System 2")
    p.add_argument("--format", choices=("text", "json"), default="text", help="System 2 thought format: sectioned text or JSON")
    p.add_argument("--precursor-col", default="precursor_mz", help="Column name for precursor m/z if any")
    return p.parse_args()


def main() -> None:
    args = parse_args()
    use_system2 = not args.no_system2
    try:
        system2_mod = _load_cot_system2() if use_system2 else None
    except Exception as e:
        print(f"Failed to load System 2 module: {e}")
        system2_mod = None
        use_system2 = False
    out_lines = []
    with open(args.input_jsonl) as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            obj = json.loads(line)
            thought = generate_thought_for_record(
                obj,
                use_system2=use_system2,
                _system2_mod=system2_mod,
                output_format=getattr(args, "format", "text"),
            )
            obj["thought"] = thought
            out_lines.append(json.dumps(obj) + "\n")
    Path(args.output_jsonl).parent.mkdir(parents=True, exist_ok=True)
    with open(args.output_jsonl, "w") as f:
        f.writelines(out_lines)
    print(f"Wrote {len(out_lines)} records to {args.output_jsonl}")


if __name__ == "__main__":
    main()