| |
| """ |
| Evaluate retrieval on MassSpecGym. Plan §5. |
| Metrics: Recall@1/10/50, optional Tanimoto@1. Unfiltered and formula-filtered. |
| """ |
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import sys |
| from functools import lru_cache |
| 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_args(): |
| p = argparse.ArgumentParser(description="Evaluate retrieval JSONL (from retrieve_generate.py)") |
| p.add_argument("--pred-jsonl", required=True, help="JSONL: each line has smiles_gt, candidates list") |
| p.add_argument("--report", default=None, help="Write metrics JSON here") |
| p.add_argument("--tanimoto", action="store_true", help="Compute Tanimoto@1 (requires RDKit)") |
| return p.parse_args() |
|
|
|
|
| @lru_cache(maxsize=200000) |
| def canonicalize_smiles(smiles: str) -> str: |
| text = str(smiles or "").strip() |
| if not text: |
| return "" |
| try: |
| from rdkit import Chem |
| except ImportError: |
| return text |
| mol = Chem.MolFromSmiles(text) |
| if mol is None: |
| return text |
| return Chem.MolToSmiles(mol, canonical=True) |
|
|
|
|
| def recall_at_k(candidates: list, gt_smiles: str, k: int) -> bool: |
| """True if gt_smiles is in the first k candidates (by order).""" |
| if not gt_smiles or not candidates: |
| return False |
| gt_canon = canonicalize_smiles(gt_smiles) |
| smiles_list = [ |
| canonicalize_smiles(c.get("smiles", c) if isinstance(c, dict) else c) |
| for c in candidates[:k] |
| ] |
| return gt_canon in smiles_list |
|
|
|
|
| def recall_at_k_rank(candidates: list, gt_smiles: str, k: int) -> int | None: |
| """Rank (1-based) of gt_smiles in candidates, or None if not in top k.""" |
| if not gt_smiles or not candidates: |
| return None |
| gt_canon = canonicalize_smiles(gt_smiles) |
| for i, c in enumerate(candidates[:k]): |
| smi = canonicalize_smiles(c.get("smiles", c) if isinstance(c, dict) else c) |
| if smi == gt_canon: |
| return i + 1 |
| return None |
|
|
|
|
| def tanimoto_at_1(candidates: list, gt_smiles: str) -> float | None: |
| """Tanimoto similarity of top-1 candidate to gt_smiles. None if no RDKit or no candidates.""" |
| try: |
| from rdkit import Chem |
| from rdkit.Chem import DataStructs |
| from rdkit.Chem.AllChem import GetMorganFingerprintAsBitVect |
| except ImportError: |
| return None |
| if not candidates or not gt_smiles: |
| return None |
| top = candidates[0] |
| smi_pred = top.get("smiles", top) if isinstance(top, dict) else top |
| mol_gt = Chem.MolFromSmiles(gt_smiles) |
| mol_pred = Chem.MolFromSmiles(smi_pred) |
| if mol_gt is None or mol_pred is None: |
| return None |
| fp_gt = GetMorganFingerprintAsBitVect(mol_gt, 2, nBits=2048) |
| fp_pred = GetMorganFingerprintAsBitVect(mol_pred, 2, nBits=2048) |
| return DataStructs.TanimotoSimilarity(fp_gt, fp_pred) |
|
|
|
|
| def compute_metrics(rows: list, include_tanimoto: bool = False) -> dict: |
| n = len(rows) |
| if n == 0: |
| return {"n": 0, "Recall@1": 0.0, "Recall@10": 0.0, "Recall@50": 0.0} |
|
|
| metrics = { |
| "n": n, |
| "Recall@1": sum(1 for r in rows if recall_at_k(r.get("candidates", []), r.get("smiles_gt", ""), 1)) / n, |
| "Recall@10": sum(1 for r in rows if recall_at_k(r.get("candidates", []), r.get("smiles_gt", ""), 10)) / n, |
| "Recall@50": sum(1 for r in rows if recall_at_k(r.get("candidates", []), r.get("smiles_gt", ""), 50)) / n, |
| } |
|
|
| if include_tanimoto: |
| tan_list = [] |
| for r in rows: |
| t = tanimoto_at_1(r.get("candidates", []), r.get("smiles_gt", "")) |
| if t is not None: |
| tan_list.append(t) |
| if tan_list: |
| metrics["Tanimoto@1_mean"] = sum(tan_list) / len(tan_list) |
| metrics["Tanimoto@1_count"] = len(tan_list) |
|
|
| return metrics |
|
|
|
|
| def main(): |
| args = parse_args() |
| path = Path(args.pred_jsonl) |
| if not path.exists(): |
| raise SystemExit(f"Not found: {path}") |
|
|
| rows = [] |
| with open(path) as f: |
| for line in f: |
| line = line.strip() |
| if not line: |
| continue |
| rows.append(json.loads(line)) |
|
|
| if not rows: |
| raise SystemExit("Empty JSONL") |
| metrics = compute_metrics(rows, include_tanimoto=args.tanimoto) |
|
|
| mode_groups = {} |
| for row in rows: |
| mode = row.get("retrieval_mode") |
| if not mode: |
| continue |
| mode_groups.setdefault(str(mode), []).append(row) |
| if mode_groups: |
| metrics["by_retrieval_mode"] = { |
| mode: compute_metrics(group_rows, include_tanimoto=args.tanimoto) |
| for mode, group_rows in sorted(mode_groups.items()) |
| } |
|
|
| print("Metrics:", json.dumps(metrics, indent=2)) |
| if args.report: |
| with open(args.report, "w") as f: |
| json.dump(metrics, f, indent=2) |
| print(f"Wrote {args.report}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|