Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions database/scripts/load_compounds.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion gui/src/client/src/components/workspace/DialogViewItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@ export const DialogViewItem: React.FC<DialogViewItemProps> = ({
{hasReconstructions && itemScore < 0.5 && (
<Stack direction="row" spacing={0.5} alignItems="center">
<Tooltip
title="Coverage is the share of the molecule RetroMol could match to known building blocks. Low or 0% coverage means most (or all) of the structure falls outside its rule set, e.g. an unusual scaffold or a modification the current rules don't recognize. A low coverage leads to primary sequences that may be sparse, incomplete, or empty."
title="Coverage is the share of input heavy atoms assigned to identified building blocks. Low or 0% coverage means most (or all) of the structure falls outside its rule set, e.g. an unusual scaffold or a modification the current rules don't recognize. A low coverage leads to primary sequences that may be sparse, incomplete, or empty."
placement="bottom-start"
arrow
>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ export const WorkspaceItemCard: React.FC<WorkspaceItemCardProps> = ({
<Tooltip
title={
isCompound
? "Coverage is the share of the molecule RetroMol could match to known building blocks. Low or 0% coverage means most (or all) of the structure falls outside its rule set, e.g. an unusual scaffold or a modification the current rules don't recognize. A low coverage leads to primary sequences that may be sparse, incomplete, or empty."
? "Coverage is the share of input heavy atoms assigned to identified building blocks. Low or 0% coverage means most (or all) of the structure falls outside its rule set, e.g. an unusual scaffold or a modification the current rules don't recognize. A low coverage leads to primary sequences that may be sparse, incomplete, or empty."
: "Coverage is the share of predicted modules RetroMol could confidently assign a substrate to. Low or 0% usually means PARAS couldn't confidently predict a substrate for the NRPS domains present, so those modules are marked unknown."
}
placement="right"
Expand Down
30 changes: 16 additions & 14 deletions src/retromol/model/result.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from retromol.model.submission import Submission
from retromol.model.reaction_graph import ReactionGraph
from retromol.model.readout import LinearReadout
from retromol.chem.mol import smiles_to_mol
from retromol.chem.tagging import get_tags_mol


Expand Down Expand Up @@ -33,24 +34,25 @@ def __str__(self) -> 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]:
"""
Expand Down
2 changes: 1 addition & 1 deletion src/retromol_cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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%}")

Expand Down
4 changes: 2 additions & 2 deletions src/retromol_database/duckdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
112 changes: 112 additions & 0 deletions tests/test_result.py
Original file line number Diff line number Diff line change
@@ -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)
Loading