| """ |
| System 2 CoT: Deductive Spectral Reasoning. |
| Generates structured, step-by-step reasoning traces deriving structure from spectrum. |
| Key components: |
| 1. Precursor Analysis: ExactMass, Nitrogen Rule, DoU. |
| 2. Neutral Loss Analysis: Delta mass attribution (Causal). |
| 3. Fragment Analysis: Substructure validation (Anti-Hallucination). |
| 4. Scaffold Inference: Aglycone/Core deduction. |
| 5. Assembly: Coherent narrative. |
| """ |
| from __future__ import annotations |
|
|
| import json |
| import math |
| import re |
| from typing import Any, Optional, List, Dict, Tuple |
|
|
| |
|
|
| |
| DIAGNOSTIC_FRAGMENTS = [ |
| ("Indole", "[nH]1cccc2ccccc12", 130, "C9H8N+"), |
| ("3-alkyl-indole", "c1ccc2c(c1)[nH]cc2C", 130, "C9H8N+"), |
| ("Tropylium", "[CH2]c1ccccc1", 91, "C7H7+"), |
| ("Phenyl cation", "c1ccccc1", 77, "C6H5+"), |
| ("Phenol", "c1ccc(O)cc1", 94, "C6H6O"), |
| ("Aniline", "c1ccc(N)cc1", 93, "C6H7N"), |
| ("Pyridine", "n1ccccc1", 79, "C5H5N+"), |
| ("Imidazole", "c1cncn1", 68, "C3H4N2"), |
| ("Quinoline/Isoquinoline", "c1ccc2ncccc2c1", 129, "C9H7N+"), |
| ("Naphthalene", "c1ccc2ccccc2c1", 128, "C10H8+"), |
| ("Acetyl", "CC(=O)", 43, "C2H3O+"), |
| ("Methoxy", "CO", 31, "CH3O+"), |
| ("Carboxyl", "C(=O)O", 45, "CHO2+"), |
| ("Glucuronic Acid", "OC1C(O)C(O)C(O)C(O)O1", 176, "C6H9O6+"), |
| ("Rhamnose", "CC1OC(O)C(O)C(O)C1O", 147, "C6H11O4+"), |
| ("Hexose (Glucose/Galactose)", "OCC1OC(O)C(O)C(O)C1O", 163, "C6H11O5+"), |
| ("Quercetin aglycone", "c1c(O)cc(O)c2c1(=O)c(O)c(c1ccc(O)c(O)c1)o2", 303, "C15H11O7+"), |
| ("Kaempferol aglycone", "c1c(O)cc(O)c2c1(=O)c(O)c(c1ccc(O)cc1)o2", 287, "C15H11O6+"), |
| ("Apigenin aglycone", "c1c(O)cc(O)c2c1(=O)cc(c1ccc(O)cc1)o2", 271, "C15H11O5+"), |
| ("Luteolin aglycone", "c1c(O)cc(O)c2c1(=O)cc(c1ccc(O)c(O)c1)o2", 287, "C15H11O6+"), |
| ("Coumarin", "O=C1C=Cc2ccccc2O1", 147, "C9H7O2+"), |
| ("Ferulic acid moiety", "COc1cc(C=CC(=O)O)ccc1O", 195, "C10H11O4+"), |
| ] |
|
|
| NEUTRAL_LOSSES_MAP = { |
| 162.05: "hexose moiety (e.g., glucose/galactose, -162 Da)", |
| 146.06: "deoxyhexose moiety (e.g., rhamnose, -146 Da)", |
| 132.04: "pentose moiety (e.g., xylose/arabinose, -132 Da)", |
| 176.03: "glucuronic acid moiety (-176 Da)", |
| 308.11: "rutinose (rhamnose-glucose, -308 Da)", |
| 18.01: "water (H2O, -18 Da)", |
| 28.00: "CO (-28 Da)", |
| 44.00: "CO2 (-44 Da)", |
| 15.02: "methyl group (-15 Da)", |
| 17.03: "ammonia (NH3, -17 Da)", |
| 31.02: "methoxy group (-31 Da)", |
| 32.03: "methanol (-32 Da)", |
| 42.01: "acetyl group (ketene loss, -42 Da)", |
| 46.01: "H2O + CO / formic acid (-46 Da)", |
| 56.03: "C4H8 / retro-Diels-Alder fragment", |
| 79.96: "sulfate / phosphate loss (approx 80 Da)", |
| |
| 36.00: "HCl (hydrogen chloride, -36 Da)", |
| 38.00: "HCl (isotope, -38 Da)", |
| 80.91: "HBr (hydrogen bromide, -81 Da)", |
| 78.92: "HBr (isotope, -79 Da)", |
| 127.90: "HI (hydrogen iodide, -128 Da)", |
| 19.99: "HF (hydrogen fluoride, -20 Da)" |
| } |
|
|
| TOLERANCE = 0.5 |
|
|
| |
|
|
| def match_substructures(smiles: str) -> List[str]: |
| """Return list of fragment names present in the molecule.""" |
| try: |
| from rdkit import Chem |
| mol = Chem.MolFromSmiles(smiles) |
| if mol is None: return [] |
| found = [] |
| for name, smarts, _, _ in DIAGNOSTIC_FRAGMENTS: |
| try: |
| pat = Chem.MolFromSmarts(smarts) |
| if pat and mol.HasSubstructMatch(pat): |
| found.append(name) |
| except: |
| continue |
| return found |
| except ImportError: |
| return [] |
|
|
| def calc_dou(formula_str: str) -> float: |
| """ |
| Calculate Degree of Unsaturation. |
| DoU = C - H/2 - X/2 + N/2 + 1 |
| (Where X = F, Cl, Br, I) |
| """ |
| if not formula_str: return 0.0 |
| |
| atoms = {} |
| |
| for match in re.finditer(r"([A-Z][a-z]?)(\d*)", formula_str): |
| elem = match.group(1) |
| count = int(match.group(2)) if match.group(2) else 1 |
| atoms[elem] = atoms.get(elem, 0) + count |
| |
| c = atoms.get('C', 0) |
| h = atoms.get('H', 0) |
| n = atoms.get('N', 0) |
| p = atoms.get('P', 0) |
| |
| |
| x = atoms.get('F', 0) + atoms.get('Cl', 0) + atoms.get('Br', 0) + atoms.get('I', 0) |
| |
| |
| return c + 1 - (h + x)/2 + (n + p)/2 |
|
|
| def precursor_interpretation_deductive( |
| found_in_spectrum: bool, |
| mz: float, |
| exact_mw: float, |
| formula: str, |
| adduct: str = "[M+H]+" |
| ) -> List[str]: |
| """Generate deductive text about precursor, carefully distinguishing Neutral vs Ion.""" |
| steps = [] |
| |
| nominal_mass = round(exact_mw) |
| |
| |
| if found_in_spectrum: |
| delta = mz - exact_mw |
| steps.append(f"The precursor ion is observed at m/z {mz:.4f}, consistent with an {adduct} adduct of a neutral molecule with mass {exact_mw:.4f} Da.") |
| else: |
| steps.append(f"The precursor ion is not observed in the spectrum. The theoretical mass is {exact_mw:.4f} Da.") |
|
|
| |
| try: |
| dou = calc_dou(formula) |
| is_odd_mass = (nominal_mass % 2 != 0) |
| |
| |
| steps.append(f"The neutral nominal mass is {nominal_mass} Da.") |
| |
| if "N" in formula: |
| steps.append(f"Based on the Nitrogen Rule, this {'odd' if is_odd_mass else 'even'} neutral mass indicates an {'odd' if is_odd_mass else 'even'} number of nitrogen atoms.") |
| else: |
| steps.append(f"The {'even' if not is_odd_mass else 'odd'} neutral mass is consistent with the absence of nitrogen.") |
| |
| steps.append(f"The calculated Degree of Unsaturation (DoU) is {dou:.1f}, suggesting significant structural complexity (rings/double bonds).") |
| except Exception as e: |
| pass |
| |
| return steps |
|
|
| def neutral_loss_analysis( |
| precursor_mz: float, |
| peaks: List[Tuple[float, float]], |
| formula: Optional[str] |
| ) -> List[str]: |
| """Identify direct neutral losses from precursor with Formula Validation.""" |
| steps = [] |
| |
| |
| |
| atom_counts = {} |
| if formula: |
| import re |
| for match in re.finditer(r"([A-Z][a-z]?)(\d*)", formula): |
| elem = match.group(1) |
| count = int(match.group(2)) if match.group(2) else 1 |
| atom_counts[elem] = atom_counts.get(elem, 0) + count |
|
|
| |
| def is_loss_allowed(loss_name): |
| if not formula: return True |
| |
| loss_lower = loss_name.lower() |
| |
| |
| if "chloride" in loss_lower or "hcl" in loss_lower: |
| if atom_counts.get("Cl", 0) < 1: return False |
| if "bromide" in loss_lower or "hbr" in loss_lower: |
| if atom_counts.get("Br", 0) < 1: return False |
| if "iodide" in loss_lower or "hi" in loss_lower: |
| if atom_counts.get("I", 0) < 1: return False |
| if "fluoride" in loss_lower or "hf" in loss_lower: |
| if atom_counts.get("F", 0) < 1: return False |
| |
| |
| |
| if any(x in loss_lower for x in ["hexose", "pentose", "rhamnose", "glucuronic", "rutinose"]): |
| if atom_counts.get("O", 0) < 3: return False |
| |
| |
| if "ammonia" in loss_lower or "nh3" in loss_lower: |
| if atom_counts.get("N", 0) < 1: return False |
| |
| return True |
|
|
| |
| sorted_peaks = sorted(peaks, key=lambda x: x[1], reverse=True)[:10] |
| found_losses = [] |
| |
| for mz, _int in sorted_peaks: |
| if mz >= precursor_mz - 1.0: continue |
| loss = precursor_mz - mz |
| |
| best_match = None |
| min_diff = 999.0 |
| |
| for ref_loss, name in NEUTRAL_LOSSES_MAP.items(): |
| diff = abs(loss - ref_loss) |
| |
| if diff < TOLERANCE and diff < min_diff: |
| if is_loss_allowed(name): |
| min_diff = diff |
| best_match = name |
| |
| if best_match: |
| steps.append(f"A neutral loss of {loss:.2f} Da (m/z {precursor_mz:.2f} -> {mz:.2f}) corresponds to the loss of a {best_match}.") |
| found_losses.append(mz) |
| |
| return steps, found_losses |
| |
|
|
| def build_system2_structured( |
| smiles: str, |
| peaks: List[List[float]], |
| precursor_mz: Optional[float] = None, |
| formula: Optional[str] = None, |
| max_peaks: int = 20, |
| ) -> Dict[str, Any]: |
| """ |
| Build a structured dictionary containing the reasoning steps. |
| """ |
| from rdkit import Chem |
| from rdkit.Chem import Descriptors |
| from rdkit.Chem.rdMolDescriptors import CalcMolFormula |
| |
| mol = Chem.MolFromSmiles(smiles) |
| if not mol: |
| return {"error": "Invalid SMILES"} |
| |
| exact_mw = Descriptors.ExactMolWt(mol) |
| calc_formula = formula or CalcMolFormula(mol) |
| |
| |
| max_int = max([p[1] for p in peaks]) if peaks else 1.0 |
| valid_peaks = [(p[0], p[1]) for p in peaks if p[1]/max_int > 0.01] |
| valid_peaks.sort(key=lambda x: x[1], reverse=True) |
| |
| top_peaks = valid_peaks[:max_peaks] |
| base_peak = top_peaks[0] if top_peaks else (0,0) |
| |
| |
| precursor_info = { |
| "found": False, |
| "mz": 0.0, |
| "adduct": "", |
| "deduction": [] |
| } |
| |
| |
| found_in_spectrum = False |
| observed_mz = 0.0 |
| |
| if any(abs(mz - (exact_mw + 1.0078)) < TOLERANCE for mz, _ in top_peaks): |
| observed_mz = next(mz for mz, _ in top_peaks if abs(mz - (exact_mw + 1.0078)) < TOLERANCE) |
| precursor_info["mz"] = observed_mz |
| precursor_info["adduct"] = "[M+H]+" |
| found_in_spectrum = True |
| elif any(abs(mz - (exact_mw + 22.989)) < TOLERANCE for mz, _ in top_peaks): |
| observed_mz = next(mz for mz, _ in top_peaks if abs(mz - (exact_mw + 22.989)) < TOLERANCE) |
| precursor_info["mz"] = observed_mz |
| precursor_info["adduct"] = "[M+Na]+" |
| found_in_spectrum = True |
| |
| |
| if not found_in_spectrum: |
| if precursor_mz and precursor_mz > 0: |
| precursor_info["mz"] = precursor_mz |
| precursor_info["adduct"] = "[M+H]+" |
| else: |
| precursor_info["mz"] = exact_mw + 1.0078 |
| precursor_info["adduct"] = "[M+H]+" |
| |
| precursor_info["found"] = found_in_spectrum |
|
|
| |
| precursor_info["deduction"] = precursor_interpretation_deductive( |
| found_in_spectrum, |
| precursor_info["mz"], |
| exact_mw, |
| calc_formula, |
| precursor_info["adduct"] |
| ) |
| |
| |
| loss_steps, loss_mzs = neutral_loss_analysis(precursor_info["mz"], top_peaks, calc_formula) |
| |
| |
| present_substructures = match_substructures(smiles) |
| fragment_steps = [] |
| |
| for mz, _int in top_peaks: |
| |
| for name, _smarts, hint_mz, hint_formula in DIAGNOSTIC_FRAGMENTS: |
| if abs(mz - hint_mz) < 1.0: |
| |
| if name in present_substructures: |
| fragment_steps.append(f"The peak at m/z {mz:.2f} is diagnostic for {name}" + (f" ({hint_formula})." if hint_formula else ".")) |
| break |
| |
| fragment_steps = list(dict.fromkeys(fragment_steps)) |
| |
| |
| scaffold_text = "" |
| if base_peak[0] > 0: |
| if found_in_spectrum and abs(base_peak[0] - precursor_info["mz"]) < 1.0: |
| scaffold_text = "The base peak corresponds to the intact precursor, suggesting a stable molecular ion." |
| elif loss_mzs and abs(base_peak[0] - loss_mzs[-1]) < 1.0: |
| scaffold_text = "The base peak represents the core scaffold after the loss of labile groups." |
| else: |
| scaffold_text = f"The base peak at m/z {base_peak[0]:.2f} represents the most stable fragment ion." |
|
|
| return { |
| "precursor": precursor_info, |
| "losses": loss_steps, |
| "fragments": fragment_steps, |
| "scaffold": scaffold_text |
| } |
|
|
| def format_structured_cot_as_text(structure: Dict[str, Any]) -> str: |
| """Convert structured dict to narrative string.""" |
| parts = [] |
| |
| |
| if structure.get("error"): |
| return structure["error"] |
| |
| prec = structure["precursor"] |
| parts.extend(prec["deduction"]) |
| |
| |
| if structure["losses"]: |
| parts.append("Fragmentation analysis reveals characteristic neutral losses:") |
| parts.extend(structure["losses"]) |
| else: |
| parts.append("No common neutral losses were clearly identified.") |
| |
| |
| if structure["fragments"]: |
| parts.append("Diagnostic fragment ions confirm the presence of specific substructures:") |
| parts.extend(structure["fragments"]) |
| |
| |
| if structure["scaffold"]: |
| parts.append(structure["scaffold"]) |
| |
| return " ".join(parts) |
|
|
| def build_system2_thought( |
| smiles: str, |
| peaks: list[list[float]], |
| precursor_mz: Optional[float] = None, |
| formula: Optional[str] = None, |
| max_peaks: int = 20, |
| output_format: str = "text", |
| ) -> str: |
| """ |
| Entry point for generating CoT. |
| """ |
| struct = build_system2_structured(smiles, peaks, precursor_mz, formula, max_peaks) |
| |
| if output_format == "json": |
| return json.dumps(struct, indent=2) |
| |
| return format_structured_cot_as_text(struct) |