diff --git a/benchmark/Snakemake b/benchmark/Snakemake new file mode 100644 index 0000000..c29b9d9 --- /dev/null +++ b/benchmark/Snakemake @@ -0,0 +1,128 @@ +"""RetroMol benchmarking pipeline: figures over a compiled NPAtlas+MIBiG database. + +Run from the repo root with: + + snakemake -s benchmark/Snakemake --configfile benchmark/config.yaml --cores 4 + +Requires a database already built by database/Snakemake (see benchmark/config.yaml's +`paths.database`); this pipeline only reads it, never writes to it. In particular, +figure1's coverage numbers are read straight off `entries.coverage`, populated at +database-build time by database/scripts/load_compounds.py. A database built before +that column existed needs to be reopened for writing once (e.g. rerun +`load_npatlas_compounds`/`load_mibig_compounds` from database/Snakemake) so +RetroMolDuckDB's schema migration backfills it; see that module's docstring. Produces: + + 1. link_bgc_compounds - MIBiG accession -> {bgc_entry_ids, compound_entry_ids} + 2. figure1 - coverage distributions (NPAtlas chemical classes / MIBiG + biosynthetic classes vs. their respective "all") + 3. figure2 - top-1 retrieved compound Tc per MIBiG BGC + 4. figure3 - cross-modal retrieval hit@k + per-method timing + 5. figure4 - BGC-compound pair score distributions vs. random pairs + +Steps 2-5 are independent of each other once 1 is done, so they run in parallel +under `--cores`. +""" + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(workflow.basedir) / "scripts")) + +DB_PATH = Path(config["paths"]["database"]) +WORKDIR = Path(config["paths"]["workdir"]) +FIGURES_DIR = Path(config["paths"]["figures_dir"]) + +RXN_RULES = config["paths"].get("reaction_rules") +MXN_RULES = config["paths"].get("matching_rules") + + +rule all: + input: + FIGURES_DIR / "figure1_coverage.png", + FIGURES_DIR / "figure2_retrieval.png", + FIGURES_DIR / "figure3_cross_modal.png", + FIGURES_DIR / "figure3_timing.png", + FIGURES_DIR / "figure4_score_distributions.png" + + +rule link_bgc_compounds: + output: + links=WORKDIR / "links.json" + run: + import link_bgc_compounds + link_bgc_compounds.run( + db_path=DB_PATH, + output_path=output.links, + min_modules=config.get("min_bgc_modules", 1), + ) + + +rule figure1: + input: + links=WORKDIR / "links.json" + output: + figure=FIGURES_DIR / "figure1_coverage.png" + run: + import figure1_coverage + figure1_coverage.run( + db_path=str(DB_PATH), + links_path=str(input.links), + npatlas_highlight_classes=config["npatlas_highlight_classes"], + mibig_highlight_classes=config["mibig_highlight_classes"], + output_path=str(output.figure), + ) + + +rule figure2: + input: + links=WORKDIR / "links.json" + output: + figure=FIGURES_DIR / "figure2_retrieval.png" + run: + import figure2_retrieval + figure2_retrieval.run( + db_path=str(DB_PATH), + links_path=str(input.links), + method=config["figure2"]["method"], + mibig_highlight_classes=config["mibig_highlight_classes"], + retrieval_cfg=config["retrieval"], + tanimoto_cfg=config["tanimoto"], + output_path=str(output.figure), + ) + + +rule figure3: + input: + links=WORKDIR / "links.json" + output: + figure=FIGURES_DIR / "figure3_cross_modal.png", + timing=FIGURES_DIR / "figure3_timing.png" + run: + import figure3_cross_modal + figure3_cross_modal.run( + db_path=str(DB_PATH), + links_path=str(input.links), + figure3_cfg=config["figure3"], + mibig_highlight_classes=config["mibig_highlight_classes"], + retrieval_cfg=config["retrieval"], + tanimoto_cfg=config["tanimoto"], + output_path=str(output.figure), + timing_output_path=str(output.timing), + ) + + +rule figure4: + input: + links=WORKDIR / "links.json" + output: + figure=FIGURES_DIR / "figure4_score_distributions.png" + run: + import figure4_score_distributions + figure4_score_distributions.run( + db_path=str(DB_PATH), + links_path=str(input.links), + retrieval_cfg=config["retrieval"], + n_random_pairs=config["figure4"]["n_random_pairs"], + random_seed=config["figure4"]["random_pairs_seed"], + output_path=str(output.figure), + ) diff --git a/benchmark/config.yaml b/benchmark/config.yaml new file mode 100644 index 0000000..b953078 --- /dev/null +++ b/benchmark/config.yaml @@ -0,0 +1,116 @@ +paths: + # Compiled DuckDB database produced by database/Snakemake (NPAtlas + MIBiG compounds, + # MIBiG BGCs, npclassifier chemical-class + biosynthetic-class annotations). Opened + # read-only; this pipeline never writes to it. + database: "/Users/davidmeijer/Desktop/retromol.duckdb" + + # Scratch space for intermediate JSON (BGC<->compound links). + workdir: "/Users/davidmeijer/Desktop/retromol_benchmark_tmp" + + # Where the final figures (and their underlying data tables, as JSON) are written. + figures_dir: "/Users/davidmeijer/Desktop/retromol_benchmark_figures" + + # null -> RuleSet.load_default()'s bundled reaction/matching rules. Must match + # whatever rules the database itself was built with (see database/config.yaml), + # otherwise fingerprints/alignment scores recomputed here won't line up with what's + # stored in the database. + reaction_rules: null + matching_rules: null + +# Minimum number of primary-sequence blocks (biosynthetic modules) a MIBiG BGC entry +# must have to be included anywhere in this pipeline (figures 1, 2, 3, and 4 all read +# the same links.json, see scripts/link_bgc_compounds.py). A single-module BGC +# carries little sequence signal for alignment-based retrieval and can make hit rate +# look artificially easy or hard depending on how trivial that one token is. 1 = no +# filtering (every BGC with a non-empty primary sequence is eligible). +min_bgc_modules: 3 + +# NPClassifier chemical-class groups highlighted in Figure 1's NPAtlas panel, on top +# of the "all NPAtlas compounds" density curve. `npclassifier_level` is which of +# NPClassifier's three ranks `npclassifier_labels` are drawn from (see +# database/scripts/annotate_npclassifier.py). "Oligopeptides"/"Macrolides"/"Cyclic +# polyketides" are all superclass-level labels in NPClassifier's own taxonomy, not +# class-level. +npatlas_highlight_classes: + oligopeptides: + label: "Oligopeptides" + npclassifier_level: "superclass" + npclassifier_labels: ["Oligopeptides"] + macrolides: + label: "Macrolides" + npclassifier_level: "superclass" + npclassifier_labels: ["Macrolides"] + cyclic_polyketides: + label: "Cyclic polyketides" + npclassifier_level: "superclass" + npclassifier_labels: ["Cyclic polyketides"] + +# MIBiG biosynthetic-class groups highlighted in figures 1/2/3, on top of "all MIBiG +# BGCs". `biosynthetic_class_labels` is the EXACT set of biosynthetic_class_annotations +# labels a BGC's representative entry must carry to join that group -- not "has at +# least these labels". A BGC labeled e.g. Polyketide + Terpene matches neither +# "polyketide" nor "hybrid_pks_nrp" below; it only counts toward "all MIBiG BGCs". +# See common.exact_label_group_accessions. +# +# No iterative-vs-non-iterative PKS split: antiSMASH's region `product` qualifier +# (re-parsed from the raw GBK stored per bgc entry) is "unknown" for every BGC in the +# compiled database. MIBiG's GBK archive stores curator-defined region boundaries, +# not output from an actual antiSMASH rule-based run (its own antiSMASH-Data header +# says `Version :: False`), so that qualifier carries no usable signal here. +mibig_highlight_classes: + polyketide: + label: "Polyketide" + biosynthetic_class_labels: ["Polyketide"] + nrp: + label: "Nonribosomal peptide" + biosynthetic_class_labels: ["Nonribosomal peptide"] + hybrid_pks_nrp: + label: "Hybrid polyketide/NRP" + biosynthetic_class_labels: ["Polyketide", "Nonribosomal peptide"] + +# Whole-molecule Tanimoto (Tc) fingerprint, used everywhere a figure needs "how +# structurally similar are these two compounds" (figures 2 & 3). Distinct from the +# database's own per-token cosine fingerprint (used for nearest-neighbor retrieval, +# see retrieval.fingerprint_only) and from retromol_alignment's per-token Tanimoto +# scoring matrix (used for alignment-based retrieval, see retrieval.alignment_only). +tanimoto: + radius: 2 + num_bits: 2048 + use_chirality: true + +retrieval: + # Fingerprint-prefilter size for the "combined" method (figure 3) and for building + # each query's candidate shortlist before alignment-based re-ranking. Mirrors + # gui/src/server/routes/discovery.py's run_discovery_query exactly (fingerprint + # cosine nearest-neighbors first, then re-rank the shortlist by alignment). + fingerprint_prefilter_n: 1000 + + # "longest_sequence" or "subsequence". See ALIGNMENT_SCORE_MODES in + # gui/src/server/routes/discovery.py for what each normalizes against. + score_mode: "longest_sequence" + + # Candidate pool size for the "alignment_only" method (figure 3), which has no + # fingerprint prefilter and so would otherwise pairwise-align every query BGC + # against every compound in the database. A random sample (seeded, and always + # including every compound that's an actual ground-truth match for some BGC in the + # evaluated set, so recall@k stays measurable) keeps this tractable. null = no + # cap (every compound in the database); slow at full NPAtlas+MIBiG scale. + alignment_only_candidate_pool_size: 3000 + alignment_only_candidate_pool_seed: 0 + +figure2: + # Retrieval method used to pick each BGC's top-1 candidate for the Tc distribution: + # "fingerprint_only", "alignment_only", or "combined" (fingerprint prefilter + realign). + method: "combined" + +figure3: + top_ks: [1, 5, 10, 50, 100] + tc_thresholds: [0.4, 0.675] + methods: ["fingerprint_only", "combined"] +# methods: ["fingerprint_only", "alignment_only", "combined"] + +figure4: + # Number of random (non-matching) BGC-compound pairs to sample as the null baseline, + # matched to the number of real BGC-compound pairs evaluated (null = same count). + n_random_pairs: null + random_pairs_seed: 0 diff --git a/benchmark/scripts/common.py b/benchmark/scripts/common.py new file mode 100644 index 0000000..ef5fe1f --- /dev/null +++ b/benchmark/scripts/common.py @@ -0,0 +1,191 @@ +"""Shared helpers for the benchmark pipeline: discovery context, BGC<->compound +linking, and plotting style. + +The fingerprint/alignment recipe in `build_discovery_context` must match +gui/src/server/routes/discovery.py's `_build_context` exactly (vocabulary, n_hashes=2, +Tanimoto scoring matrix radius/num_bits); see that module's docstring. Reproduced +here rather than imported, since discovery.py pulls in the Flask app (blueprints, +routes.database, routes.queue) this standalone pipeline has no use for. +""" + +import re +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +from retromol.model.rules import MatchingRule, RuleSet +from retromol_alignment.aligner import setup_aligner +from retromol_alignment.pairwise import Converter +from retromol_alignment.scoring import HARDCODED_PK_SCORING, create_tanimoto_scoring_matrix +from retromol_database.duckdb import RetroMolDuckDB, FINGERPRINT_SIZE +from retromol_fingerprint.fingerprint import TOKEN_LINK, TOKEN_UNK, Fingerprinter, Vocabulary + +PK_GROUP_TOKENS = ("PK_A", "PK_B", "PK_C", "PK_D") + +# Both compound and bgc entries sourced from MIBiG carry a `mibig_url(accession, +# version)` URL (see database/scripts/common.py). The accession is the only +# queryable signal linking a BGC entry to its compound(s), since the database schema +# doesn't persist mibig_accession as its own column (see MIBIG_URL_TEMPLATE). +_MIBIG_ACCESSION_RE = re.compile(r"/repository/([A-Za-z0-9]+)\.") + + +def mibig_accession_from_url(url: str | None) -> str | None: + if not url: + return None + m = _MIBIG_ACCESSION_RE.search(url) + return m.group(1) if m else None + + +@dataclass(frozen=True) +class DiscoveryContext: + ruleset: RuleSet + name_to_rule: dict[str, MatchingRule] + fingerprinter: Fingerprinter + aligner: Any + converter: Converter + alphabet: frozenset[str] + + +def build_discovery_context( + reaction_rules_path: str | Path | None = None, + matching_rules_path: str | Path | None = None, +) -> DiscoveryContext: + rules = RuleSet.load_from_files( + reaction_rules_path=reaction_rules_path or None, + matching_rules_path=matching_rules_path or None, + match_stereochemistry=False, + ) + + vocab_tokens: set[str] = set() + name_to_rule: dict[str, MatchingRule] = {} + records: list[tuple[str, str]] = [] + + for rule in rules.matching_rules: + vocab_tokens.add(rule.name) + vocab_tokens.update(rule.pseudonyms) + name_to_rule.setdefault(rule.name, rule) + records.append((rule.name, rule.smiles)) + + vocab = Vocabulary(vocab_tokens) + fingerprinter = Fingerprinter(vocab, n_bits=FINGERPRINT_SIZE, n_hashes=2) + + scoring_matrix = create_tanimoto_scoring_matrix( + records, + radius=2, + num_bits=2048, + stereochemistry=False, + self_score_tokens=[TOKEN_UNK, TOKEN_LINK, *PK_GROUP_TOKENS], + self_score=1.0, + hardcoded_scores=HARDCODED_PK_SCORING, + ) + aligner = setup_aligner(scoring_matrix, mode="global") + alphabet = scoring_matrix.alphabet + converter = Converter( + to_identifier=lambda s: alphabet.index(s), + from_identifier=lambda i: alphabet[i], + ) + + return DiscoveryContext( + ruleset=rules, + name_to_rule=name_to_rule, + fingerprinter=fingerprinter, + aligner=aligner, + converter=converter, + alphabet=frozenset(alphabet), + ) + + +def per_monomer_tokens(name: str, ctx: DiscoveryContext) -> list[str]: + if name == TOKEN_LINK: + return [TOKEN_LINK] + if name in PK_GROUP_TOKENS: + return [name, "PK"] + rule = ctx.name_to_rule.get(name) + if rule is None: + return [] + tokens = {rule.name} + tokens.update(rule.pseudonyms) + return list(tokens) + + +def normalize_for_alignment(name: str, ctx: DiscoveryContext) -> str: + if name == "X" or name not in ctx.alphabet: + return TOKEN_UNK + return name + + +def fingerprint_for_sequence(names: list[str], ctx: DiscoveryContext): + tokens = [per_monomer_tokens(n, ctx) for n in names if n != TOKEN_LINK] + return ctx.fingerprinter.encode(tokens) + + +def open_db(db_path: str | Path, read_only: bool = True) -> RetroMolDuckDB: + return RetroMolDuckDB.open(db_path, read_only=read_only) + + +def bgc_biosynthetic_label_sets(con) -> dict[str, frozenset[str]]: + """entry_id -> the full, exact set of biosynthetic_class_annotations labels for + that bgc entry (e.g. {"Polyketide"}, or {"Polyketide", "Nonribosomal peptide"} + for a PKS/NRPS hybrid). `con` is a duckdb connection (RetroMolDuckDB.con or a raw + duckdb.connect(...) both work).""" + labels_by_entry: dict[str, set[str]] = {} + for entry_id, label in con.execute("SELECT entry_id, label FROM biosynthetic_class_annotations").fetchall(): + labels_by_entry.setdefault(entry_id, set()).add(label) + return {entry_id: frozenset(labels) for entry_id, labels in labels_by_entry.items()} + + +def exact_label_group_accessions( + con, links: dict[str, dict], group_label_sets: dict[str, frozenset[str]] +) -> dict[str, set[str]]: + """{group_key: {accession, ...}} for benchmark/config.yaml's mibig_highlight_classes, + where an accession belongs to a group only if its representative bgc entry's + biosynthetic_class label set is EXACTLY that group's `biosynthetic_class_labels` + (not a superset) -- so a BGC labeled e.g. Polyketide + Terpene lands in neither + the "polyketide" nor any hybrid group, only in "all". The representative bgc + entry is `links[accession]["bgc_entry_ids"][0]` (already sorted; same one + retrieval_engine.build_eval_bgcs uses as that accession's query), so group + membership always refers to the same bgc entry actually evaluated elsewhere. + """ + label_sets = bgc_biosynthetic_label_sets(con) + groups: dict[str, set[str]] = {key: set() for key in group_label_sets} + + for accession, ids in links.items(): + if not ids["bgc_entry_ids"]: + continue + bgc_labels = label_sets.get(ids["bgc_entry_ids"][0], frozenset()) + for key, required in group_label_sets.items(): + if bgc_labels == required: + groups[key].add(accession) + + return groups + + +def figure_style() -> None: + """Shared matplotlib backend/rcParams for every figureN_*.py script. + + Snakemake's `run:` rules execute in worker threads of the main process (not + subprocesses) when multiple independent rules run under `--cores N`, so with + figures 1-4 all runnable in parallel, matplotlib's default interactive backend + (MacOSX on a Mac) crashes with "Cannot create a GUI FigureManager outside of the + main thread" for every figure but whichever happened to run first. Forcing the + non-interactive Agg backend (all these scripts only ever call savefig, never + show()) fixes this regardless of which thread it runs on. + """ + import matplotlib + + matplotlib.use("Agg", force=True) + + matplotlib.rcParams.update( + { + "figure.dpi": 150, + "savefig.dpi": 150, + "font.size": 10, + "axes.titlesize": 11, + "axes.labelsize": 10, + "axes.spines.top": False, + "axes.spines.right": False, + "legend.frameon": False, + "figure.facecolor": "white", + "savefig.facecolor": "white", + } + ) diff --git a/benchmark/scripts/figure1_coverage.py b/benchmark/scripts/figure1_coverage.py new file mode 100644 index 0000000..d98e4a8 --- /dev/null +++ b/benchmark/scripts/figure1_coverage.py @@ -0,0 +1,174 @@ +"""Figure 1: RetroMol coverage distributions. + +Left panel: all NPAtlas compounds vs. NPAtlas compounds restricted to a handful of +NPClassifier chemical classes (default: oligopeptides, macrolides, cyclic +polyketides), meant to show coverage is especially good for those classes. + +Right panel: all MIBiG BGCs (one point per BGC accession, the best-coverage +compound among that accession's associated product compounds, since a BGC can have +more than one) vs. the same, restricted to MIBiG's own Polyketide and Nonribosomal +peptide biosynthetic_class labels. + +Both panels overlay density curves (gaussian KDE) on the same [0, 1] coverage axis +so they're directly comparable, plus the raw sample counts in the legend. + +Coverage is read straight off `entries.coverage` (see +src/retromol_database/duckdb.py / database/scripts/load_compounds.py); no RetroMol +re-parsing needed here. +""" + +import argparse +import json +import logging +from pathlib import Path + +import duckdb +import matplotlib.pyplot as plt +import numpy as np +from scipy.stats import gaussian_kde + +from common import exact_label_group_accessions, figure_style + +log = logging.getLogger(__name__) + +_COLORS = ["#4C72B0", "#DD8452", "#55A868", "#C44E52"] + + +def _kde_line(values: list[float], ax, label: str, color: str, linestyle: str = "-") -> None: + x = np.linspace(0.0, 1.0, 400) + if len(values) < 2 or np.std(values) == 0: + ax.axvline(values[0] if values else 0.0, color=color, linestyle=linestyle, label=f"{label} (n={len(values)})") + return + density = gaussian_kde(values)(x) + ax.plot(x, density, color=color, linestyle=linestyle, label=f"{label} (n={len(values)})") + ax.fill_between(x, density, color=color, alpha=0.12) + + +def _npatlas_panel(ax, con, coverage_by_entry: dict[str, float], highlight_classes: dict) -> None: + npatlas_ids = { + r[0] + for r in con.execute( + "SELECT DISTINCT entry_id FROM entry_sources WHERE database_name = 'NPAtlas'" + ).fetchall() + } + npatlas_entries = {eid: cov for eid, cov in coverage_by_entry.items() if eid in npatlas_ids} + all_values = list(npatlas_entries.values()) + _kde_line(all_values, ax, "All NPAtlas compounds", "#808080", linestyle="--") + + for i, (_, group) in enumerate(highlight_classes.items()): + labels = group["npclassifier_labels"] + level = group.get("npclassifier_level", "class") + placeholders = ",".join(["?"] * len(labels)) + rows = con.execute( + f""" + SELECT DISTINCT entry_id FROM chemical_class_annotations + WHERE level = ? AND label IN ({placeholders}) + """, + [level, *labels], + ).fetchall() + group_ids = {r[0] for r in rows} & npatlas_entries.keys() + values = [npatlas_entries[eid] for eid in group_ids] + _kde_line(values, ax, group["label"], _COLORS[i % len(_COLORS)]) + + ax.set_title("NPAtlas compounds") + ax.set_xlabel("RetroMol coverage") + ax.set_ylabel("Density") + ax.set_xlim(0, 1) + ax.legend(loc="upper left", fontsize=8) + + +def _mibig_panel( + ax, + con, + coverage_by_entry: dict[str, float], + links: dict[str, dict], + highlight_classes: dict, +) -> None: + # One value per accession: the best-coverage compound among its associated + # products (a BGC entry can have more than one associated product compound). + best_by_accession: dict[str, float] = {} + for accession, ids in links.items(): + if not ids["bgc_entry_ids"] or not ids["compound_entry_ids"]: + continue + covs = [coverage_by_entry[eid] for eid in ids["compound_entry_ids"] if eid in coverage_by_entry] + if covs: + best_by_accession[accession] = max(covs) + + all_values = list(best_by_accession.values()) + _kde_line(all_values, ax, "All MIBiG BGCs", "#808080", linestyle="--") + + group_label_sets = {key: frozenset(g["biosynthetic_class_labels"]) for key, g in highlight_classes.items()} + group_accessions_by_key = exact_label_group_accessions(con, links, group_label_sets) + + for i, (key, group) in enumerate(highlight_classes.items()): + values = [best_by_accession[a] for a in group_accessions_by_key[key] if a in best_by_accession] + _kde_line(values, ax, group["label"], _COLORS[i % len(_COLORS)]) + + ax.set_title("MIBiG BGCs (best-scoring product per BGC)") + ax.set_xlabel("RetroMol coverage") + ax.set_xlim(0, 1) + ax.legend(loc="upper left", fontsize=8) + + +def run( + db_path: str, + links_path: str, + npatlas_highlight_classes: dict, + mibig_highlight_classes: dict, + output_path: str, +) -> None: + figure_style() + + with open(links_path) as fh: + links = json.load(fh) + + con = duckdb.connect(db_path, read_only=True) + try: + coverage_by_entry = { + r[0]: r[1] + for r in con.execute( + "SELECT id, coverage FROM entries WHERE type = 'compound' AND coverage IS NOT NULL" + ).fetchall() + } + + fig, axes = plt.subplots(1, 2, figsize=(11, 4.2)) + _npatlas_panel(axes[0], con, coverage_by_entry, npatlas_highlight_classes) + _mibig_panel(axes[1], con, coverage_by_entry, links, mibig_highlight_classes) + finally: + con.close() + + fig.suptitle("Figure 1 - RetroMol coverage distributions") + fig.tight_layout() + + output_path = Path(output_path) + output_path.parent.mkdir(parents=True, exist_ok=True) + fig.savefig(output_path) + plt.close(fig) + log.info("figure1_coverage: wrote %s", output_path) + + +def main() -> None: + logging.basicConfig(level=logging.INFO) + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--db-path", required=True) + ap.add_argument("--links", required=True) + ap.add_argument("--config", required=True, help="path to benchmark/config.yaml") + ap.add_argument("--output", required=True) + args = ap.parse_args() + + import yaml + + with open(args.config) as fh: + cfg = yaml.safe_load(fh) + + run( + db_path=args.db_path, + links_path=args.links, + npatlas_highlight_classes=cfg["npatlas_highlight_classes"], + mibig_highlight_classes=cfg["mibig_highlight_classes"], + output_path=args.output, + ) + + +if __name__ == "__main__": + main() diff --git a/benchmark/scripts/figure2_retrieval.py b/benchmark/scripts/figure2_retrieval.py new file mode 100644 index 0000000..b5d9af7 --- /dev/null +++ b/benchmark/scripts/figure2_retrieval.py @@ -0,0 +1,172 @@ +"""Figure 2: top-1 retrieved compound's Tc for every MIBiG BGC. + +For every MIBiG BGC (one query per accession; a BGC with multiple product compounds +is scored against whichever one the retrieval method itself ranks best, see +config's figure2.method), retrieve the single top-ranked compound candidate and +compute its whole-molecule Tanimoto (Tc) against the best-matching associated +ground-truth compound. Plotted as one density +per group: all MIBiG BGCs, plus each biosynthetic-class group configured in +benchmark/config.yaml's mibig_highlight_classes (default: Polyketide, Nonribosomal +peptide). +""" + +import argparse +import json +import logging +from pathlib import Path + +import duckdb +import matplotlib.pyplot as plt +import numpy as np +from scipy.stats import gaussian_kde +from tqdm import tqdm + +from common import build_discovery_context, figure_style, normalize_for_alignment, open_db +from retrieval_engine import ( + TanimotoCache, + build_eval_bgcs, + combined_rank, + fingerprint_only_rank, + group_accessions_from_config, + load_compound_universe, + sample_candidate_pool, + self_alignment_score, + alignment_only_rank, +) + +log = logging.getLogger(__name__) +_COLORS = ["#808080", "#4C72B0", "#DD8452", "#55A868"] + + +def _top1_tc(method: str, bq, ctx, db, universe, tanimoto: TanimotoCache, retrieval_cfg: dict, entries_by_id: dict) -> float | None: + query_seq_norm = [normalize_for_alignment(n, ctx) for n in bq.primary_sequence] + + if method == "fingerprint_only": + ranked = fingerprint_only_rank(db, bq.fingerprint, limit=1) + elif method == "alignment_only": + self_score = self_alignment_score(query_seq_norm, ctx) + pool = sample_candidate_pool( + universe, + retrieval_cfg["alignment_only_candidate_pool_size"], + retrieval_cfg["alignment_only_candidate_pool_seed"], + must_include_ids=set(bq.ground_truth_ids), + ) + ranked = alignment_only_rank(ctx, query_seq_norm, self_score, pool, retrieval_cfg["score_mode"], top_k=1) + else: # combined + self_score = self_alignment_score(query_seq_norm, ctx) + ranked = combined_rank( + db, ctx, bq.fingerprint, query_seq_norm, self_score, retrieval_cfg["score_mode"], + retrieval_cfg["fingerprint_prefilter_n"], top_k=1, + ) + + if not ranked: + return None + + top1_smiles = entries_by_id.get(ranked[0].entry_id) + if top1_smiles is None: + return None + + best_tc = None + for gt_id in bq.ground_truth_ids: + gt_smiles = entries_by_id.get(gt_id) + tc = tanimoto.tc(top1_smiles, gt_smiles) + if tc is not None and (best_tc is None or tc > best_tc): + best_tc = tc + return best_tc + + +def run( + db_path: str, + links_path: str, + method: str, + mibig_highlight_classes: dict, + retrieval_cfg: dict, + tanimoto_cfg: dict, + output_path: str, +) -> None: + figure_style() + + with open(links_path) as fh: + links = json.load(fh) + + ctx = build_discovery_context() + universe = load_compound_universe(db_path) + entries_by_id = {c.entry_id: c.smiles for c in universe} + + db = open_db(db_path) + try: + groups = build_eval_bgcs(db, links, group_accessions_from_config(db, links, mibig_highlight_classes)) + + tanimoto = TanimotoCache(tanimoto_cfg["radius"], tanimoto_cfg["num_bits"], tanimoto_cfg["use_chirality"]) + + tc_by_group: dict[str, list[float]] = {} + for group_name, queries in groups.items(): + values = [] + for bq in tqdm(queries, desc=f"figure2[{group_name}]", unit="bgc"): + tc = _top1_tc(method, bq, ctx, db, universe, tanimoto, retrieval_cfg, entries_by_id) + if tc is not None: + values.append(tc) + tc_by_group[group_name] = values + finally: + db.close() + + fig, ax = plt.subplots(figsize=(6.5, 4.5)) + x = np.linspace(0.0, 1.0, 400) + labels = {"all": "All MIBiG BGCs", **{k: v["label"] for k, v in mibig_highlight_classes.items()}} + for i, group_name in enumerate(["all", *mibig_highlight_classes.keys()]): + values = tc_by_group.get(group_name, []) + label = f"{labels[group_name]} (n={len(values)})" + color = _COLORS[i % len(_COLORS)] + if len(values) < 2 or np.std(values) == 0: + if values: + ax.axvline(values[0], color=color, label=label, linestyle="--" if group_name == "all" else "-") + continue + density = gaussian_kde(values)(x) + ax.plot(x, density, color=color, linestyle="--" if group_name == "all" else "-", label=label) + ax.fill_between(x, density, color=color, alpha=0.12) + + ax.set_xlim(0, 1) + ax.set_xlabel("Top-1 retrieved compound Tc (vs. best-matching ground truth)") + ax.set_ylabel("Density") + ax.set_title(f"Figure 2 - Top-1 retrieval Tc per MIBiG BGC ({method})") + ax.legend(loc="upper left", fontsize=8) + fig.tight_layout() + + output_path = Path(output_path) + output_path.parent.mkdir(parents=True, exist_ok=True) + fig.savefig(output_path) + plt.close(fig) + + with open(output_path.with_suffix(".json"), "w") as fh: + json.dump(tc_by_group, fh) + + log.info("figure2_retrieval: wrote %s", output_path) + + +def main() -> None: + logging.basicConfig(level=logging.INFO) + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--db-path", required=True) + ap.add_argument("--links", required=True) + ap.add_argument("--config", required=True) + ap.add_argument("--output", required=True) + args = ap.parse_args() + + import yaml + + with open(args.config) as fh: + cfg = yaml.safe_load(fh) + + run( + db_path=args.db_path, + links_path=args.links, + method=cfg["figure2"]["method"], + mibig_highlight_classes=cfg["mibig_highlight_classes"], + retrieval_cfg=cfg["retrieval"], + tanimoto_cfg=cfg["tanimoto"], + output_path=args.output, + ) + + +if __name__ == "__main__": + main() diff --git a/benchmark/scripts/figure3_cross_modal.py b/benchmark/scripts/figure3_cross_modal.py new file mode 100644 index 0000000..f3b3f6e --- /dev/null +++ b/benchmark/scripts/figure3_cross_modal.py @@ -0,0 +1,279 @@ +"""Figure 3: cross-modal retrieval hit@k, and per-method retrieval timing. + +For every MIBiG BGC query (grouped as in figure2: all, plus each biosynthetic-class +group in benchmark/config.yaml's mibig_highlight_classes), retrieve up to max(top_ks) +compound candidates with each of three methods (fingerprint-only, alignment-only, +combined fingerprint-prefilter-then-realign; see retrieval_engine.py), and check +whether the best candidate among the top-k has a whole-molecule Tc >= each configured +threshold against any of that BGC's ground-truth compounds. Hit rate is plotted vs. +k (one line per method) for every (group, threshold) pair. Wall-clock time per query +is also recorded per method and plotted separately (figure3_timing.png), measured +once, over the "all" group (retrieval cost per query doesn't depend on which +biosynthetic-class group it's reported under). +""" + +import argparse +import json +import logging +from pathlib import Path + +import matplotlib.pyplot as plt +import numpy as np +from tqdm import tqdm + +from common import build_discovery_context, figure_style, normalize_for_alignment, open_db +from retrieval_engine import ( + TanimotoCache, + build_eval_bgcs, + combined_rank, + fingerprint_only_rank, + group_accessions_from_config, + load_compound_universe, + sample_candidate_pool, + self_alignment_score, + timed_rank, + alignment_only_rank, +) + +log = logging.getLogger(__name__) +_METHOD_LABELS = {"fingerprint_only": "Fingerprint only", "alignment_only": "Pairwise alignment only", "combined": "Fingerprint + alignment"} +_METHOD_COLORS = {"fingerprint_only": "#4C72B0", "alignment_only": "#DD8452", "combined": "#55A868"} + + +def _rank_for_method(method: str, bq, ctx, db, universe, retrieval_cfg: dict, max_k: int): + query_seq_norm = [normalize_for_alignment(n, ctx) for n in bq.primary_sequence] + + if method == "fingerprint_only": + return timed_rank(fingerprint_only_rank, db, bq.fingerprint, max_k) + if method == "alignment_only": + self_score = self_alignment_score(query_seq_norm, ctx) + pool = sample_candidate_pool( + universe, + retrieval_cfg["alignment_only_candidate_pool_size"], + retrieval_cfg["alignment_only_candidate_pool_seed"], + must_include_ids=set(bq.ground_truth_ids), + ) + return timed_rank(alignment_only_rank, ctx, query_seq_norm, self_score, pool, retrieval_cfg["score_mode"], max_k) + # combined + self_score = self_alignment_score(query_seq_norm, ctx) + return timed_rank( + combined_rank, db, ctx, bq.fingerprint, query_seq_norm, self_score, + retrieval_cfg["score_mode"], retrieval_cfg["fingerprint_prefilter_n"], max_k, + ) + + +def _plot_hit_rates( + hit_rates: dict, group_labels: dict, methods: list, top_ks: list, thresholds: list, output_path: str +) -> None: + groups = list(hit_rates.keys()) + fig, axes = plt.subplots(len(groups), len(thresholds), figsize=(5.5 * len(thresholds), 3.8 * len(groups)), squeeze=False) + for row, group_name in enumerate(groups): + for col, threshold in enumerate(thresholds): + ax = axes[row][col] + for method in methods: + ys = [hit_rates[group_name][method][str(threshold)][str(k)] for k in top_ks] + ax.plot(top_ks, ys, marker="o", color=_METHOD_COLORS[method], label=_METHOD_LABELS[method]) + ax.set_xticks(top_ks) + ax.set_ylim(0, 1.05) + ax.set_title(f"{group_labels[group_name]} - Tc >= {threshold}") + ax.set_xlabel("k") + if col == 0: + ax.set_ylabel("Hit rate") + if row == 0 and col == len(thresholds) - 1: + ax.legend(loc="lower right", fontsize=8) + fig.suptitle("Figure 3 - Cross-modal retrieval hit@k") + fig.tight_layout() + + output_path = Path(output_path) + output_path.parent.mkdir(parents=True, exist_ok=True) + fig.savefig(output_path) + plt.close(fig) + + +def _plot_timing(timings: dict, methods: list, output_path: str) -> None: + fig2, ax2 = plt.subplots(figsize=(5, 4)) + means = [float(np.mean(timings[m])) if timings[m] else 0.0 for m in methods] + stds = [float(np.std(timings[m])) if timings[m] else 0.0 for m in methods] + ax2.bar([_METHOD_LABELS[m] for m in methods], means, yerr=stds, color=[_METHOD_COLORS[m] for m in methods]) + ax2.set_ylabel("Mean retrieval time per BGC query (s)") + ax2.set_title(f"Figure 3 - Retrieval timing (n={len(timings[methods[0]])} queries)") + plt.setp(ax2.get_xticklabels(), rotation=20, ha="right") + fig2.tight_layout() + + output_path = Path(output_path) + output_path.parent.mkdir(parents=True, exist_ok=True) + fig2.savefig(output_path) + plt.close(fig2) + + +def run( + db_path: str, + links_path: str, + figure3_cfg: dict, + mibig_highlight_classes: dict, + retrieval_cfg: dict, + tanimoto_cfg: dict, + output_path: str, + timing_output_path: str, +) -> None: + figure_style() + + with open(links_path) as fh: + links = json.load(fh) + + group_labels = {"all": "All MIBiG BGCs", **{k: v["label"] for k, v in mibig_highlight_classes.items()}} + + ctx = build_discovery_context() + universe = load_compound_universe(db_path) + entries_by_id = {c.entry_id: c.smiles for c in universe} + tanimoto = TanimotoCache(tanimoto_cfg["radius"], tanimoto_cfg["num_bits"], tanimoto_cfg["use_chirality"]) + + top_ks = figure3_cfg["top_ks"] + thresholds = figure3_cfg["tc_thresholds"] + methods = figure3_cfg["methods"] + max_k = max(top_ks) + + db = open_db(db_path) + try: + groups = build_eval_bgcs(db, links, group_accessions_from_config(db, links, mibig_highlight_classes)) + + # hit_rates[group][method][threshold][k] = fraction of queries with a hit + hit_rates: dict[str, dict[str, dict[float, dict[int, float]]]] = {} + timings: dict[str, list[float]] = {m: [] for m in methods} + + for group_name, queries in groups.items(): + hit_rates[group_name] = {m: {t: {} for t in thresholds} for m in methods} + for method in methods: + per_query_hits: dict[int, dict[float, list[bool]]] = {k: {t: [] for t in thresholds} for k in top_ks} + + for bq in tqdm(queries, desc=f"figure3[{group_name}][{method}]", unit="bgc"): + ranked, elapsed = _rank_for_method(method, bq, ctx, db, universe, retrieval_cfg, max_k) + if group_name == "all": + timings[method].append(elapsed) + + candidate_best_tc = [] + for cand in ranked: + cand_smiles = entries_by_id.get(cand.entry_id) + best_tc = 0.0 + for gt_id in bq.ground_truth_ids: + tc = tanimoto.tc(cand_smiles, entries_by_id.get(gt_id)) + if tc is not None: + best_tc = max(best_tc, tc) + candidate_best_tc.append(best_tc) + + for k in top_ks: + topk_best = max(candidate_best_tc[:k], default=0.0) + for threshold in thresholds: + per_query_hits[k][threshold].append(topk_best >= threshold) + + for k in top_ks: + for threshold in thresholds: + vals = per_query_hits[k][threshold] + hit_rates[group_name][method][threshold][k] = ( + float(np.mean(vals)) if vals else float("nan") + ) + finally: + db.close() + + # _plot_hit_rates always indexes by str(threshold)/str(k), matching how JSON + # round-trips keys (see replot()) -- normalize here so both callers agree. + hit_rates_json = { + group_name: { + method: {str(t): {str(k): v for k, v in kmap.items()} for t, kmap in tmap.items()} + for method, tmap in mmap.items() + } + for group_name, mmap in hit_rates.items() + } + + output_path = Path(output_path) + timing_output_path = Path(timing_output_path) + + _plot_hit_rates(hit_rates_json, group_labels, methods, top_ks, thresholds, output_path) + with open(output_path.with_suffix(".json"), "w") as fh: + json.dump(hit_rates_json, fh, indent=2) + + _plot_timing(timings, methods, timing_output_path) + with open(timing_output_path.with_suffix(".json"), "w") as fh: + json.dump({m: timings[m] for m in methods}, fh) + + log.info("figure3_cross_modal: wrote %s and %s", output_path, timing_output_path) + + +def replot( + hit_rates_json_path: str, + timing_json_path: str, + figure3_cfg: dict, + mibig_highlight_classes: dict, + output_path: str, + timing_output_path: str, +) -> None: + """Redraw both figures straight from a previous run's saved JSON (see run()'s + output_path.with_suffix(".json") / timing_output_path.with_suffix(".json")) -- + for a plotting-only change (styling, axis scale, labels), so the expensive + retrieval computation doesn't need to be redone just to redraw the same numbers. + """ + figure_style() + + with open(hit_rates_json_path) as fh: + hit_rates = json.load(fh) + with open(timing_json_path) as fh: + timings = json.load(fh) + + group_labels = {"all": "All MIBiG BGCs", **{k: v["label"] for k, v in mibig_highlight_classes.items()}} + top_ks = figure3_cfg["top_ks"] + thresholds = figure3_cfg["tc_thresholds"] + methods = figure3_cfg["methods"] + + _plot_hit_rates(hit_rates, group_labels, methods, top_ks, thresholds, output_path) + _plot_timing(timings, methods, timing_output_path) + + log.info("figure3_cross_modal.replot: wrote %s and %s", output_path, timing_output_path) + + +def main() -> None: + logging.basicConfig(level=logging.INFO) + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--db-path", required=False, help="not needed with --replot") + ap.add_argument("--links", required=False, help="not needed with --replot") + ap.add_argument("--config", required=True) + ap.add_argument("--output", required=True) + ap.add_argument("--timing-output", required=True) + ap.add_argument( + "--replot", action="store_true", + help="redraw from --output/--timing-output's existing .json files instead of recomputing", + ) + args = ap.parse_args() + + import yaml + + with open(args.config) as fh: + cfg = yaml.safe_load(fh) + + if args.replot: + replot( + hit_rates_json_path=str(Path(args.output).with_suffix(".json")), + timing_json_path=str(Path(args.timing_output).with_suffix(".json")), + figure3_cfg=cfg["figure3"], + mibig_highlight_classes=cfg["mibig_highlight_classes"], + output_path=args.output, + timing_output_path=args.timing_output, + ) + return + + if not args.db_path or not args.links: + ap.error("--db-path and --links are required unless --replot is given") + + run( + db_path=args.db_path, + links_path=args.links, + figure3_cfg=cfg["figure3"], + mibig_highlight_classes=cfg["mibig_highlight_classes"], + retrieval_cfg=cfg["retrieval"], + tanimoto_cfg=cfg["tanimoto"], + output_path=args.output, + timing_output_path=args.timing_output, + ) + + +if __name__ == "__main__": + main() diff --git a/benchmark/scripts/figure4_score_distributions.py b/benchmark/scripts/figure4_score_distributions.py new file mode 100644 index 0000000..615b029 --- /dev/null +++ b/benchmark/scripts/figure4_score_distributions.py @@ -0,0 +1,183 @@ +"""Figure 4: BGC-compound pair score distributions vs. random pairs. + +For every MIBiG BGC with a known product compound (best-scoring compound per BGC, +same "pick one compound per BGC" rule as figures 1/2), computes two scores against +its ground truth: the database's own fingerprint cosine similarity, and the +normalized pairwise-alignment score. Both are also computed for an equal-sized set of +random (non-matching) BGC-compound pairs, as a null baseline. Real pairs should be +clearly shifted higher than random ones if RetroMol's representation is doing its job. +""" + +import argparse +import json +import logging +import random +from pathlib import Path + +import matplotlib.pyplot as plt +import numpy as np +from scipy.stats import gaussian_kde +from tqdm import tqdm + +from common import build_discovery_context, figure_style, normalize_for_alignment, open_db +from retrieval_engine import build_eval_bgcs, self_alignment_score, score_candidate_alignment, CompoundRecord + + +def _cosine(a: np.ndarray, b: np.ndarray) -> float: + denom = float(np.linalg.norm(a) * np.linalg.norm(b)) + return float(np.dot(a, b) / denom) if denom > 0 else 0.0 + + +def run( + db_path: str, + links_path: str, + retrieval_cfg: dict, + n_random_pairs: int | None, + random_seed: int, + output_path: str, +) -> None: + figure_style() + + with open(links_path) as fh: + links = json.load(fh) + + ctx = build_discovery_context() + db = open_db(db_path) + try: + groups = build_eval_bgcs(db, links, {}) + queries = groups["all"] + + # Ground-truth compound fingerprints/primary_sequences, batch-fetched once. + all_gt_ids = sorted({gt for q in queries for gt in q.ground_truth_ids}) + gt_entries = {e.id: e for e in db.get_entries(all_gt_ids)} + + real_cosine: list[float] = [] + real_alignment: list[float] = [] + for bq in tqdm(queries, desc="figure4[real pairs]", unit="bgc"): + query_seq_norm = [normalize_for_alignment(n, ctx) for n in bq.primary_sequence] + self_score = self_alignment_score(query_seq_norm, ctx) + + best_cos, best_align = None, None + for gt_id in bq.ground_truth_ids: + entry = gt_entries.get(gt_id) + if entry is None: + continue + cos = _cosine(bq.fingerprint, np.array(entry.fingerprint, dtype=np.float32)) + best_cos = cos if best_cos is None else max(best_cos, cos) + + cand = CompoundRecord(entry.id, entry.raw, entry.primary_sequence) + pct = score_candidate_alignment(ctx, query_seq_norm, self_score, retrieval_cfg["score_mode"], cand) + if pct is not None: + best_align = pct if best_align is None else max(best_align, pct) + + if best_cos is not None: + real_cosine.append(best_cos) + if best_align is not None: + real_alignment.append(best_align) + + # Random (non-matching) pairs, sampled from the full compound universe. + n_random = n_random_pairs if n_random_pairs is not None else len(queries) + rng = random.Random(random_seed) + all_compound_ids = [ + r[0] for r in db.con.execute("SELECT id FROM entries WHERE type = 'compound'").fetchall() + ] + + ground_truth_by_bgc = {q.entry_id: set(q.ground_truth_ids) for q in queries} + random_cosine: list[float] = [] + random_alignment: list[float] = [] + + picks = 0 + attempts = 0 + pbar = tqdm(total=n_random, desc="figure4[random pairs]", unit="pair") + while picks < n_random and attempts < n_random * 20: + attempts += 1 + bq = rng.choice(queries) + compound_id = rng.choice(all_compound_ids) + if compound_id in ground_truth_by_bgc.get(bq.entry_id, set()): + continue + + entry = db.get_entry(compound_id) + if entry is None: + continue + + query_seq_norm = [normalize_for_alignment(n, ctx) for n in bq.primary_sequence] + self_score = self_alignment_score(query_seq_norm, ctx) + + cos = _cosine(bq.fingerprint, np.array(entry.fingerprint, dtype=np.float32)) + random_cosine.append(cos) + + cand = CompoundRecord(entry.id, entry.raw, entry.primary_sequence) + pct = score_candidate_alignment(ctx, query_seq_norm, self_score, retrieval_cfg["score_mode"], cand) + if pct is not None: + random_alignment.append(pct) + + picks += 1 + pbar.update(1) + pbar.close() + finally: + db.close() + + fig, axes = plt.subplots(1, 2, figsize=(11, 4.2)) + for ax, real_vals, random_vals, title, xlabel in [ + (axes[0], real_cosine, random_cosine, "Fingerprint cosine similarity", "Cosine similarity"), + (axes[1], real_alignment, random_alignment, "Normalized alignment score", "Normalized alignment score"), + ]: + x = np.linspace(0.0, 1.0, 400) + for vals, label, color in [(real_vals, "Real BGC-compound pairs", "#4C72B0"), (random_vals, "Random pairs", "#808080")]: + if len(vals) < 2 or np.std(vals) == 0: + continue + density = gaussian_kde(vals)(x) + ax.plot(x, density, color=color, label=f"{label} (n={len(vals)})") + ax.fill_between(x, density, color=color, alpha=0.12) + ax.set_xlim(0, 1) + ax.set_title(title) + ax.set_xlabel(xlabel) + ax.set_ylabel("Density") + ax.legend(loc="upper left", fontsize=8) + + fig.suptitle("Figure 4 - BGC-compound pair score distributions vs. random pairs") + fig.tight_layout() + + output_path = Path(output_path) + output_path.parent.mkdir(parents=True, exist_ok=True) + fig.savefig(output_path) + plt.close(fig) + + with open(output_path.with_suffix(".json"), "w") as fh: + json.dump( + { + "real_cosine": real_cosine, "random_cosine": random_cosine, + "real_alignment": real_alignment, "random_alignment": random_alignment, + }, + fh, + ) + + logging.getLogger(__name__).info("figure4_score_distributions: wrote %s", output_path) + + +def main() -> None: + logging.basicConfig(level=logging.INFO) + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--db-path", required=True) + ap.add_argument("--links", required=True) + ap.add_argument("--config", required=True) + ap.add_argument("--output", required=True) + args = ap.parse_args() + + import yaml + + with open(args.config) as fh: + cfg = yaml.safe_load(fh) + + run( + db_path=args.db_path, + links_path=args.links, + retrieval_cfg=cfg["retrieval"], + n_random_pairs=cfg["figure4"]["n_random_pairs"], + random_seed=cfg["figure4"]["random_pairs_seed"], + output_path=args.output, + ) + + +if __name__ == "__main__": + main() diff --git a/benchmark/scripts/link_bgc_compounds.py b/benchmark/scripts/link_bgc_compounds.py new file mode 100644 index 0000000..485c3bd --- /dev/null +++ b/benchmark/scripts/link_bgc_compounds.py @@ -0,0 +1,103 @@ +"""Build the MIBiG accession -> {bgc_entry_ids, compound_entry_ids} mapping. + +The compiled database has no direct BGC<->compound foreign key (see benchmark/ +config.yaml's mibig_highlight_classes comment and common.mibig_accession_from_url): +both entry types carry the same `mibig_url(accession, version)` URL as one of their +`entry_sources` rows, which is the only queryable link between a BGC and its +product compound(s). Re-derived here once and cached, rather than re-parsed by every +downstream script. + +Also drops any bgc entry with fewer than `min_modules` primary-sequence blocks (see +benchmark/config.yaml's min_bgc_modules) -- filtering here, rather than per-figure, +keeps every figure's MIBiG-side sample consistent, since they all read this one +links.json. +""" + +import argparse +import json +import logging +from collections import defaultdict +from pathlib import Path + +import duckdb + +from common import mibig_accession_from_url +from retromol_fingerprint.fingerprint import TOKEN_LINK + +log = logging.getLogger(__name__) + + +def run(db_path: str | Path, output_path: str | Path, min_modules: int = 1) -> None: + output_path = Path(output_path) + output_path.parent.mkdir(parents=True, exist_ok=True) + + con = duckdb.connect(str(db_path), read_only=True) + try: + rows = con.execute( + """ + SELECT e.type, s.entry_id, s.url + FROM entry_sources s + JOIN entries e ON e.id = s.entry_id + WHERE s.database_name = 'MIBiG' AND s.url IS NOT NULL + """ + ).fetchall() + + # Module count per bgc entry: primary_sequence length excluding TOKEN_LINK + # (a join marker between merged paths, not a biosynthetic module). + bgc_module_counts: dict[str, int] = {} + if min_modules > 1: + for entry_id, primary_sequence in con.execute( + "SELECT id, primary_sequence FROM entries WHERE type = 'bgc'" + ).fetchall(): + bgc_module_counts[entry_id] = sum(1 for tok in primary_sequence if tok != TOKEN_LINK) + finally: + con.close() + + links: dict[str, dict[str, set]] = defaultdict(lambda: {"bgc_entry_ids": set(), "compound_entry_ids": set()}) + n_bgc_dropped = 0 + + for entry_type, entry_id, url in rows: + accession = mibig_accession_from_url(url) + if not accession: + continue + if entry_type == "bgc": + if min_modules > 1 and bgc_module_counts.get(entry_id, 0) < min_modules: + n_bgc_dropped += 1 + continue + links[accession]["bgc_entry_ids"].add(entry_id) + else: + links[accession]["compound_entry_ids"].add(entry_id) + + serializable = { + accession: { + "bgc_entry_ids": sorted(ids["bgc_entry_ids"]), + "compound_entry_ids": sorted(ids["compound_entry_ids"]), + } + for accession, ids in links.items() + } + + with open(output_path, "w") as fh: + json.dump(serializable, fh, indent=2, sort_keys=True) + + n_with_both = sum( + 1 for v in serializable.values() if v["bgc_entry_ids"] and v["compound_entry_ids"] + ) + log.info( + "link_bgc_compounds: %d MIBiG accessions, %d with both a bgc and >=1 compound entry " + "(min_modules=%d dropped %d bgc entries) -> %s", + len(serializable), n_with_both, min_modules, n_bgc_dropped, output_path, + ) + + +def main() -> None: + logging.basicConfig(level=logging.INFO) + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--db-path", required=True) + ap.add_argument("--output", required=True) + ap.add_argument("--min-modules", type=int, default=1) + args = ap.parse_args() + run(db_path=args.db_path, output_path=args.output, min_modules=args.min_modules) + + +if __name__ == "__main__": + main() diff --git a/benchmark/scripts/retrieval_engine.py b/benchmark/scripts/retrieval_engine.py new file mode 100644 index 0000000..9423983 --- /dev/null +++ b/benchmark/scripts/retrieval_engine.py @@ -0,0 +1,255 @@ +"""Shared retrieval machinery for figures 2, 3, and 4: fingerprint-only, alignment-only, +and combined (fingerprint prefilter + alignment re-rank) compound retrieval for a BGC +query, plus whole-molecule Tanimoto (Tc) scoring of a retrieved candidate against a +ground-truth compound. + +"combined" mirrors gui/src/server/routes/discovery.py's run_discovery_query exactly: +fingerprint-cosine nearest neighbors first (cheap, DuckDB-vectorized, see +RetroMolDuckDB.closest), then re-rank that shortlist by normalized alignment score. +"alignment_only" has no such prefilter, so it's only tractable over a bounded +candidate pool (see benchmark/config.yaml's retrieval.alignment_only_candidate_pool_size). +""" + +import random +import time +from dataclasses import dataclass, field +from typing import Any + +import duckdb +import numpy as np +from rdkit import Chem + +from common import DiscoveryContext, exact_label_group_accessions, normalize_for_alignment +from retromol.chem.fingerprint import calculate_tanimoto_similarity, mol_to_morgan_fingerprint +from retromol_alignment.pairwise import align +from retromol_alignment.ranking import reorder_target_chains +from retromol_database.duckdb import RetroMolDuckDB + + +@dataclass(frozen=True) +class CompoundRecord: + entry_id: str + smiles: str | None + primary_sequence: list[str] + + +@dataclass +class RankedCandidate: + entry_id: str + score: float # cosine similarity (fingerprint_only) or normalized alignment pct/100 (alignment_only, combined) + + +@dataclass(frozen=True) +class BgcQuery: + entry_id: str + accession: str + fingerprint: np.ndarray + primary_sequence: list[str] + ground_truth_ids: list[str] + + +def group_accessions_from_config( + db: RetroMolDuckDB, links: dict[str, dict], mibig_highlight_classes: dict +) -> dict[str, set[str]]: + """{group_key: {accession, ...}} for every group in benchmark/config.yaml's + mibig_highlight_classes, resolved via exact_label_group_accessions -- an + accession only joins a group if its representative bgc entry's biosynthetic_class + label set is EXACTLY that group's `biosynthetic_class_labels` (see that config + key's comment): a hybrid BGC with an extra, unlisted label doesn't spuriously + join any group it's only partially a match for.""" + group_label_sets = { + key: frozenset(group["biosynthetic_class_labels"]) for key, group in mibig_highlight_classes.items() + } + return exact_label_group_accessions(db.con, links, group_label_sets) + + +def build_eval_bgcs( + db: RetroMolDuckDB, + links: dict[str, dict], + group_accessions: dict[str, set[str]], +) -> dict[str, list[BgcQuery]]: + """One BgcQuery per MIBiG accession that has both a bgc entry and >=1 associated + compound entry (its "ground truth" set for retrieval evaluation), grouped into + "all" plus each group in `group_accessions` (e.g. polyketide, nonribosomal-peptide + accessions; see figure2_retrieval.py/figure3_cross_modal.py for how those sets + are built).""" + eligible = { + accession: ids + for accession, ids in links.items() + if ids["bgc_entry_ids"] and ids["compound_entry_ids"] + } + + all_bgc_ids = sorted({eid for ids in eligible.values() for eid in ids["bgc_entry_ids"]}) + entries_by_id = {e.id: e for e in db.get_entries(all_bgc_ids)} + + queries: dict[str, BgcQuery] = {} + for accession, ids in eligible.items(): + # A BGC accession normally maps to exactly one region/entry; if antiSMASH + # produced more than one region for the same accession, use the first + # (stable, sorted) one as this accession's query. One query per accession + # keeps every group's "n" comparable to a BGC/product count, not a raw region + # count. + bgc_id = ids["bgc_entry_ids"][0] + entry = entries_by_id.get(bgc_id) + if entry is None or not entry.primary_sequence: + continue + queries[accession] = BgcQuery( + entry_id=bgc_id, + accession=accession, + fingerprint=np.array(entry.fingerprint, dtype=np.float32), + primary_sequence=list(entry.primary_sequence), + ground_truth_ids=list(ids["compound_entry_ids"]), + ) + + groups: dict[str, list[BgcQuery]] = {"all": list(queries.values())} + for key, accessions in group_accessions.items(): + groups[key] = [q for acc, q in queries.items() if acc in accessions] + + return groups + + +def load_compound_universe(db_path: str) -> list[CompoundRecord]: + con = duckdb.connect(db_path, read_only=True) + try: + rows = con.execute( + "SELECT id, raw, primary_sequence FROM entries WHERE type = 'compound'" + ).fetchall() + finally: + con.close() + return [CompoundRecord(entry_id=r[0], smiles=r[1], primary_sequence=list(r[2])) for r in rows] + + +def sample_candidate_pool( + universe: list[CompoundRecord], + pool_size: int | None, + seed: int, + must_include_ids: set[str], +) -> list[CompoundRecord]: + """Random (seeded) subsample of the compound universe, always keeping every entry + in `must_include_ids` (e.g. this evaluated set's own ground-truth compounds), so + recall@k stays measurable even when the pool is much smaller than the full DB.""" + if pool_size is None or pool_size >= len(universe): + return universe + + must_have = [c for c in universe if c.entry_id in must_include_ids] + rest = [c for c in universe if c.entry_id not in must_include_ids] + n_random = max(0, pool_size - len(must_have)) + rng = random.Random(seed) + sampled = rng.sample(rest, min(n_random, len(rest))) + return must_have + sampled + + +def self_alignment_score(sequence: list[str], ctx: DiscoveryContext) -> float: + score, _, _ = align(ctx.aligner, sequence, sequence, ctx.converter) + return score + + +def normalized_pct(align_score: float, denom: float) -> float: + if denom <= 0: + return 0.0 + return max(0.0, min(1.0, align_score / denom)) + + +def score_candidate_alignment( + ctx: DiscoveryContext, + query_seq_norm: list[str], + self_score: float, + score_mode: str, + candidate: CompoundRecord, +) -> float | None: + target = [normalize_for_alignment(n, ctx) for n in candidate.primary_sequence] + if not target or not all(t in ctx.alphabet for t in target): + return None + + _assignment_score, reordered_target, _inverted = reorder_target_chains( + query_seq_norm, target, ctx.aligner, ctx.converter + ) + flat_score, _, _ = align(ctx.aligner, query_seq_norm, reordered_target, ctx.converter) + + if score_mode == "longest_sequence": + target_self = self_alignment_score(target, ctx) + denom = max(self_score, target_self) + else: + denom = self_score + + return normalized_pct(flat_score, denom) + + +def alignment_only_rank( + ctx: DiscoveryContext, + query_seq_norm: list[str], + self_score: float, + candidates: list[CompoundRecord], + score_mode: str, + top_k: int, +) -> list[RankedCandidate]: + scored: list[RankedCandidate] = [] + for cand in candidates: + pct = score_candidate_alignment(ctx, query_seq_norm, self_score, score_mode, cand) + if pct is not None: + scored.append(RankedCandidate(cand.entry_id, pct)) + scored.sort(key=lambda r: r.score, reverse=True) + return scored[:top_k] + + +def fingerprint_only_rank(db: RetroMolDuckDB, query_fp: np.ndarray, limit: int) -> list[RankedCandidate]: + hits = db.closest(query_fp, limit=limit, entry_type="compound") + return [RankedCandidate(h.entry.id, h.similarity) for h in hits] + + +def combined_rank( + db: RetroMolDuckDB, + ctx: DiscoveryContext, + query_fp: np.ndarray, + query_seq_norm: list[str], + self_score: float, + score_mode: str, + prefilter_n: int, + top_k: int, +) -> list[RankedCandidate]: + shortlist = db.closest(query_fp, limit=prefilter_n, entry_type="compound") + scored: list[RankedCandidate] = [] + for hit in shortlist: + cand = CompoundRecord(hit.entry.id, hit.entry.raw, hit.entry.primary_sequence) + pct = score_candidate_alignment(ctx, query_seq_norm, self_score, score_mode, cand) + if pct is not None: + scored.append(RankedCandidate(cand.entry_id, pct)) + scored.sort(key=lambda r: r.score, reverse=True) + return scored[:top_k] + + +def timed_rank(fn, *args, **kwargs) -> tuple[list[RankedCandidate], float]: + start = time.perf_counter() + result = fn(*args, **kwargs) + elapsed = time.perf_counter() - start + return result, elapsed + + +class TanimotoCache: + """Whole-molecule Morgan-fingerprint Tanimoto (Tc) between two compounds' SMILES, + memoized per compound (each compound's own fingerprint is reused across every + pair it appears in).""" + + def __init__(self, radius: int, num_bits: int, use_chirality: bool) -> None: + self.radius = radius + self.num_bits = num_bits + self.use_chirality = use_chirality + self._fp_cache: dict[str, Any] = {} + + def _fp(self, smiles: str | None): + if smiles is None: + return None + if smiles not in self._fp_cache: + mol = Chem.MolFromSmiles(smiles) + self._fp_cache[smiles] = ( + mol_to_morgan_fingerprint(mol, self.radius, self.num_bits, self.use_chirality) + if mol is not None + else None + ) + return self._fp_cache[smiles] + + def tc(self, smiles_a: str | None, smiles_b: str | None) -> float | None: + fp_a, fp_b = self._fp(smiles_a), self._fp(smiles_b) + if fp_a is None or fp_b is None: + return None + return calculate_tanimoto_similarity(fp_a, fp_b) diff --git a/database/scripts/load_compounds.py b/database/scripts/load_compounds.py index 1898591..5d3464f 100644 --- a/database/scripts/load_compounds.py +++ b/database/scripts/load_compounds.py @@ -11,6 +11,12 @@ retromol.model.submission.Submission with keep_stereo=True). The same molecule appearing in both NPAtlas and MIBiG lands as one database entry with two source records (see RetroMolDuckDB.add_entry) rather than two separate rows. + +Each entry also stores `result.calculate_coverage()`, the proportion of the +compound's atoms threaded into an identified retrosynthesis node. Downstream +consumers (e.g. benchmark/scripts/figure1_coverage.py) can therefore read it +straight off the database instead of re-running RetroMol over every compound's +SMILES. """ import argparse @@ -183,6 +189,7 @@ def run( entry_type="compound", primary_sequence=names, fingerprint=fp, + coverage=result.calculate_coverage(), ) if source == "mibig": _apply_mibig_annotations(db, result.submission.inchikey, props, annotations, taxdb) diff --git a/src/retromol_database/duckdb.py b/src/retromol_database/duckdb.py index 716511f..e238d18 100644 --- a/src/retromol_database/duckdb.py +++ b/src/retromol_database/duckdb.py @@ -35,6 +35,11 @@ class Entry: # Every (name, database_name, url) a source has contributed for this entry, ordered # by insertion. Empty for synthetic (non-database) entries, e.g. session uploads. sources: list[EntrySource] = field(default_factory=list) + # RetroMol's own coverage metric (Result.calculate_coverage(), see + # database/scripts/load_compounds.py): the proportion of the compound's atoms + # threaded into an identified retrosynthesis node. Compounds only; always None for + # bgc entries (a BGC has no Result/coverage of its own) and for synthetic entries. + coverage: float | None = None @dataclass(frozen=True) @@ -178,10 +183,19 @@ def create_schema(self) -> None: raw VARCHAR, content_hash VARCHAR, primary_sequence VARCHAR[] NOT NULL, - fingerprint FLOAT[{FINGERPRINT_SIZE}] NOT NULL + fingerprint FLOAT[{FINGERPRINT_SIZE}] NOT NULL, + -- RetroMol coverage (Result.calculate_coverage()), compounds only. + -- Always NULL for bgc entries. See add_entry's `coverage` parameter. + coverage FLOAT ) """ ) + # Migrates a database created before the coverage column existed. CREATE + # TABLE IF NOT EXISTS above is a no-op against an already-existing entries + # table, so an older database needs this to actually pick up the column. + # Runs on every non-read-only open() (see open()/create() above), so a + # database only needs to be reopened for writing, not rebuilt from scratch. + self.con.execute("ALTER TABLE entries ADD COLUMN IF NOT EXISTS coverage FLOAT") self.con.execute( """ CREATE TABLE IF NOT EXISTS entry_sources ( @@ -345,6 +359,7 @@ def add_entry( primary_sequence: Sequence[str], fingerprint: Sequence[float] | np.ndarray, content_hash: str | None = None, + coverage: float | None = None, ) -> str: """ Add (or extend) an entry. @@ -353,10 +368,19 @@ def add_entry( compound, or a hash of the source .gbk file's content plus region id for a bgc (see database/scripts/load_compounds.py / load_bgcs.py). If an entry with this id already exists, its stored `raw`/`primary_sequence`/ - `fingerprint` are left untouched (they describe the same molecule/BGC - either way) and only a new `(name, database_name, url)` source row is - added -- or, if that exact (entry_id, database_name, name) combination was - already recorded, its url is refreshed. + `fingerprint` are left untouched (they describe the same molecule/BGC either + way) and only a new `(name, database_name, url)` source row is added -- or, + if that exact (entry_id, database_name, name) combination was already + recorded, its url is refreshed. `coverage` IS refreshed on conflict (unlike + the fields above): it's deterministic from `raw` plus the ruleset, so + recomputing it is always safe, and this is also what lets a database built + before the coverage column existed get backfilled in place, by simply + reopening it and rerunning this same load step against already-parsed + results (see RetroMolDuckDB.create_schema's migration comment). + + `coverage` is RetroMol's own coverage metric (Result.calculate_coverage()), + compounds only; leave it None for bgc entries, which have no Result of their + own. """ entry_type = _normalize_entry_type(entry_type) sequence = _normalize_primary_sequence(primary_sequence) @@ -364,11 +388,11 @@ def add_entry( self.con.execute( """ - INSERT INTO entries (id, type, raw, content_hash, primary_sequence, fingerprint) - VALUES (?, ?, ?, ?, ?, ?) - ON CONFLICT (id) DO NOTHING + INSERT INTO entries (id, type, raw, content_hash, primary_sequence, fingerprint, coverage) + VALUES (?, ?, ?, ?, ?, ?, ?) + ON CONFLICT (id) DO UPDATE SET coverage = excluded.coverage """, - [entry_id, entry_type, raw, content_hash, sequence, fp], + [entry_id, entry_type, raw, content_hash, sequence, fp, coverage], ) self.con.execute( @@ -613,7 +637,7 @@ def search_entries( rows = self.con.execute( f""" - SELECT DISTINCT e.id, e.raw, e.type, e.primary_sequence, e.fingerprint + SELECT DISTINCT e.id, e.raw, e.type, e.primary_sequence, e.fingerprint, e.coverage FROM entries e LEFT JOIN entry_sources es ON es.entry_id = e.id {where_sql} @@ -813,7 +837,7 @@ def _sources_for_entry_ids(self, entry_ids: Sequence[str]) -> dict[str, list[Ent def get_entry(self, entry_id: str) -> Entry | None: row = self.con.execute( """ - SELECT id, raw, type, primary_sequence, fingerprint + SELECT id, raw, type, primary_sequence, fingerprint, coverage FROM entries WHERE id = ? """, @@ -834,7 +858,7 @@ def get_entries(self, entry_ids: Sequence[str]) -> list[Entry]: rows = self.con.execute( """ - SELECT id, raw, type, primary_sequence, fingerprint + SELECT id, raw, type, primary_sequence, fingerprint, coverage FROM entries WHERE id IN (SELECT UNNEST(?)) """, @@ -847,7 +871,7 @@ def get_entries(self, entry_ids: Sequence[str]) -> list[Entry]: def iter_entries(self) -> Iterator[Entry]: rows = self.con.execute( """ - SELECT id, raw, type, primary_sequence, fingerprint + SELECT id, raw, type, primary_sequence, fingerprint, coverage FROM entries ORDER BY id """ @@ -886,6 +910,7 @@ def closest( type, primary_sequence, fingerprint, + coverage, array_cosine_similarity(fingerprint, ?::FLOAT[{FINGERPRINT_SIZE}]) AS similarity FROM entries {where_sql} @@ -899,8 +924,8 @@ def closest( return [ SearchResult( - entry=_entry_from_row(row[:5], sources_by_id.get(str(row[0]), [])), - similarity=float(row[5]), + entry=_entry_from_row(row[:6], sources_by_id.get(str(row[0]), [])), + similarity=float(row[6]), ) for row in rows ] @@ -922,6 +947,7 @@ def _entry_from_row(row, sources: list[EntrySource]) -> Entry: primary_sequence=list(row[3]), fingerprint=list(row[4]), sources=sources, + coverage=row[5] if len(row) > 5 else None, )