From 97c68439e8aabe5786037b716800a1a668e8dbab Mon Sep 17 00:00:00 2001 From: David Meijer Date: Thu, 8 Oct 2026 21:30:39 -0400 Subject: [PATCH] UPD: coverage as unique input heavy atoms represented by identified assembly monomers divided by all submitted heavy atoms --- database/scripts/load_compounds.py | 4 +- .../components/workspace/DialogViewItem.tsx | 2 +- .../workspace/WorkspaceItemCard.tsx | 2 +- src/retromol/model/result.py | 30 ++--- src/retromol_cli/cli.py | 2 +- src/retromol_database/duckdb.py | 4 +- tests/test_result.py | 112 ++++++++++++++++++ 7 files changed, 135 insertions(+), 21 deletions(-) create mode 100644 tests/test_result.py diff --git a/database/scripts/load_compounds.py b/database/scripts/load_compounds.py index 5d3464f..fa16632 100644 --- a/database/scripts/load_compounds.py +++ b/database/scripts/load_compounds.py @@ -12,8 +12,8 @@ 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 +Each entry also stores `result.calculate_coverage()`, the proportion of all submitted +heavy atoms represented by identified monomers in the assembly graph. 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. diff --git a/gui/src/client/src/components/workspace/DialogViewItem.tsx b/gui/src/client/src/components/workspace/DialogViewItem.tsx index 1377daf..a433896 100644 --- a/gui/src/client/src/components/workspace/DialogViewItem.tsx +++ b/gui/src/client/src/components/workspace/DialogViewItem.tsx @@ -273,7 +273,7 @@ export const DialogViewItem: React.FC = ({ {hasReconstructions && itemScore < 0.5 && ( diff --git a/gui/src/client/src/components/workspace/WorkspaceItemCard.tsx b/gui/src/client/src/components/workspace/WorkspaceItemCard.tsx index 1e75d87..1c7d591 100644 --- a/gui/src/client/src/components/workspace/WorkspaceItemCard.tsx +++ b/gui/src/client/src/components/workspace/WorkspaceItemCard.tsx @@ -228,7 +228,7 @@ export const WorkspaceItemCard: React.FC = ({ str: def calculate_coverage(self) -> float: """ - Calculate coverage score for result. - + Calculate the fraction of input heavy atoms in identified assembly monomers. + :return: Coverage score as a float. """ - # Collect all unique tags from identified nodes - identified_tags = set() - for node in self.reaction_graph.identified_nodes.values(): - identified_tags.update(get_tags_mol(node.mol)) + input_heavy_atoms = smiles_to_mol(self.submission.smiles).GetNumHeavyAtoms() + if not input_heavy_atoms: + return 0.0 - # Get all unique tags from the root - root_tags = set(get_tags_mol(self.submission.mol)) - - # Calculate coverage: proportion of root tags identified - if root_tags: - coverage = len(identified_tags.intersection(root_tags)) / len(root_tags) - return coverage + root_heavy_tags = { + atom.GetIsotope() + for atom in self.submission.mol.GetAtoms() + if atom.GetAtomicNum() > 1 and atom.GetIsotope() != 0 + } + identified_tags: set[int] = set() + for node in self.linear_readout.assembly_graph.monomer_nodes(): + if node.is_identified: + identified_tags.update(get_tags_mol(node.mol)) - return 0.0 + return len(identified_tags.intersection(root_heavy_tags)) / input_heavy_atoms def to_dict(self) -> dict[str, Any]: """ diff --git a/src/retromol_cli/cli.py b/src/retromol_cli/cli.py index 455dd0f..c494ac5 100644 --- a/src/retromol_cli/cli.py +++ b/src/retromol_cli/cli.py @@ -160,7 +160,7 @@ def main() -> None: result_data = json.load(f) result2 = Result.from_dict(result_data) - # Report on coverage as percentage of tags identified + # Report the percentage of input heavy atoms in identified assembly monomers coverage = result2.calculate_coverage() log.info(f"coverage: {coverage:.2%}") diff --git a/src/retromol_database/duckdb.py b/src/retromol_database/duckdb.py index e238d18..35b012d 100644 --- a/src/retromol_database/duckdb.py +++ b/src/retromol_database/duckdb.py @@ -36,8 +36,8 @@ class Entry: # 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 + # database/scripts/load_compounds.py): the proportion of all submitted heavy atoms + # represented by identified assembly monomers. Compounds only; always None for # bgc entries (a BGC has no Result/coverage of its own) and for synthetic entries. coverage: float | None = None diff --git a/tests/test_result.py b/tests/test_result.py new file mode 100644 index 0000000..a376d2b --- /dev/null +++ b/tests/test_result.py @@ -0,0 +1,112 @@ +"""Regression tests for coverage of identified assembly monomers.""" + +from dataclasses import replace + +import pytest + +from retromol.chem.mol import mol_to_smiles, smiles_to_mol +from retromol.model.assembly_graph import AssemblyGraph +from retromol.model.reaction_graph import ReactionGraph, ReactionStep +from retromol.model.readout import LinearReadout +from retromol.model.result import Result +from retromol.model.rules import MatchingRule +from retromol.model.submission import Submission + + +def make_result(smiles: str, fragments: list[tuple[str, bool]]) -> Result: + """Build an identified parent with explicitly identified/unknown assembly leaves.""" + submission = Submission(smiles) + graph = ReactionGraph() + root = graph.add_node(submission.mol) + parent_rule = MatchingRule( + name="identified parent", smiles=mol_to_smiles(submission.mol, include_tags=True), + props={}, pseudonyms=[], terminal=False, + ) + graph.nodes[root].identify([parent_rule]) + children = graph.add_edge( + root, + [smiles_to_mol(smi) for smi, _ in fragments], + ReactionStep(kind="contested", names=("split",), rule_ids=("split",)), + ) + for enc, (tagged_smiles, identified) in zip(children, fragments): + node = graph.nodes[enc] + rules = [MatchingRule(name=node.smiles, smiles=tagged_smiles, props={}, pseudonyms=[])] if identified else [] + node.identify(rules) + assembly = AssemblyGraph.build( + root_mol=submission.mol, + monomers=[graph.nodes[enc] for enc in children], + include_unassigned=True, + ) + # No extracted paths: identified assembly nodes must count independently of sequences. + return Result(submission, graph, LinearReadout(assembly_graph=assembly, paths=[])) + + +def test_coverage_ignores_identified_intermediates_and_unknown_leaves() -> None: + result = make_result("CCOC", [("[1CH3][2CH3]", True), ("[3OH][4CH3]", False)]) + + assert len(result.reaction_graph.identified_nodes) == 2 + assert result.calculate_coverage() == pytest.approx(0.5) + assert Result.from_dict(result.to_dict()).calculate_coverage() == pytest.approx(0.5) + + +def test_coverage_counts_assembly_monomers_without_linear_paths() -> None: + result = make_result("CCOC", [("[1CH3][2CH3]", True), ("[3OH][4CH3]", True)]) + + assert result.linear_readout.paths == [] + assert result.calculate_coverage() == 1.0 + + +def test_coverage_keeps_atoms_missing_from_assembly_in_denominator() -> None: + result = make_result("CCOC", [("[1CH3][2CH3]", True)]) + + assert result.calculate_coverage() == pytest.approx(0.5) + + +def test_coverage_includes_all_submitted_fragments_in_denominator() -> None: + result = make_result("CCO.[Na+]", [("[1CH3][2CH2][3OH]", True)]) + + assert result.submission.mol.GetNumHeavyAtoms() == 3 + assert result.calculate_coverage() == pytest.approx(3 / 4) + assert Result.from_dict(result.to_dict()).calculate_coverage() == pytest.approx(3 / 4) + + +def test_coverage_ignores_hydrogens_and_reaction_introduced_atoms() -> None: + # The isotope-labelled H survives SMILES parsing and gets root tag 1. + # Carbon tags 2/3 are covered; oxygen tag 4 is absent. Tag 99 and the + # untagged oxygen were introduced by a reaction and cannot count as input. + result = make_result("[2H]CCO", [("[1H][2CH2][3CH2][99CH2]O", True)]) + + assert result.submission.mol.GetNumAtoms() == 4 + assert result.calculate_coverage() == pytest.approx(2 / 3) + + +def test_coverage_does_not_drop_untagged_input_atoms_from_denominator() -> None: + result = make_result("CCO", [("[1CH3][2CH2]O", True)]) + result.submission.mol.GetAtomWithIdx(2).SetIsotope(0) + + assert result.calculate_coverage() == pytest.approx(2 / 3) + + +@pytest.mark.parametrize("smiles", ["[2H][2H]", ""]) +def test_coverage_with_no_heavy_atoms_is_zero(smiles: str) -> None: + result = make_result(smiles, []) + + assert result.calculate_coverage() == 0.0 + + +def test_coverage_of_empty_assembly_is_zero() -> None: + result = make_result("CCO", []) + + assert result.calculate_coverage() == 0.0 + + +def test_coverage_counts_repeated_atom_tags_only_once() -> None: + result = make_result("CCO", [("[1CH3][2CH3]", True)]) + graph = result.linear_readout.assembly_graph.g + node = result.linear_readout.assembly_graph.monomer_nodes()[0] + graph.add_node( + "overlapping monomer", tags=graph.nodes[node.enc]["tags"], + identity=node.identity, molnode=replace(node, enc="overlapping monomer"), + ) + + assert result.calculate_coverage() == pytest.approx(2 / 3)