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
5 changes: 3 additions & 2 deletions src/retromol/io/streaming.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,9 @@ def _process_compound(args_tuple: tuple[str, dict[str, Any]]) -> tuple[dict[str,
result_obj = run_retromol_with_timeout(submission, _G_RULESET)
return result_obj.to_dict(), None
except Exception as e:
# Traceback not returned here to keep workers light-weight; caller can log
return None, str(e)
# Keep failures reproducible when results arrive out of input order.
# Do not return the full row or traceback for every failed compound.
return None, f"{type(e).__name__}: {e} (SMILES={smiles!r})"


@dataclass
Expand Down
37 changes: 28 additions & 9 deletions src/retromol/pipelines/parsing.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,8 @@ def extract_min_edge_synthesis_subgraph(

The extracted subgraph contains at most one chosen outgoing edge per expanded node
and includes all required precursor branches for that choice.
Self-dependent reactions are ignored. If no finite route exists because of a
cycle, keep an unresolved frontier so partial results still contain the root.

:param g: The full retrosynthesis reaction graph
:param root_enc: Encoding of the root molecule to extract from
Expand All @@ -150,8 +152,12 @@ def extract_min_edge_synthesis_subgraph(
raise ValueError(f"Root encoding {root_enc} not found in reaction graph nodes!")

# Adjacency list of outgoing edges for quick access
out_edges: dict[int, list[int]] = defaultdict(list)
out_edges: dict[str, list[int]] = defaultdict(list)
for ei, e in enumerate(g.edges):
# An AND reaction that requires its own reactant cannot make progress,
# even if it also produces other fragments (e.g. sulfate plus water).
if e.src in e.dsts:
continue
out_edges[e.src].append(ei)

kind_rank = {k: i for i, k in enumerate(prefer_kind)}
Expand All @@ -164,9 +170,10 @@ def edge_cost(e: RxnEdge) -> float:
return edge_base_cost + kind_penalty + branch_penalty

# DP memo: cost to "solve" a node into identified leaves
memo_cost: dict[int, float] = {}
memo_choice: dict[int, Optional[int]] = {} # node -> chosen edge index
visiting: set[int] = set()
memo_cost: dict[str, float] = {}
memo_choice: dict[str, Optional[int]] = {} # node -> chosen edge index
visiting: set[str] = set()
allow_cycle_frontier = False

def is_terminal(enc: str) -> bool:
n = g.nodes.get(enc)
Expand Down Expand Up @@ -230,20 +237,29 @@ def solve_cost(enc: str) -> float:

visiting.remove(enc)

if best == inf and allow_cycle_frontier:
# All continuations return to an ancestor. Preserve this molecule as
# an unresolved leaf rather than discarding its entire parent route.
best = unsolved_leaf_penalty

memo_cost[enc] = best
memo_choice[enc] = best_ei
return best

total = solve_cost(root_enc)
# solved = no unsolved frontier was needed
solved = total < inf and total < unsolved_leaf_penalty
if total == inf:
return SynthesisExtractResult(graph=ReactionGraph(), solved=False, total_cost=inf)
# Prefer any existing finite route before introducing cycle frontiers.
# Choices from the first traversal depended on its active ancestors, so
# recompute them together when allowing unresolved cyclic fragments.
allow_cycle_frontier = True
memo_cost.clear()
memo_choice.clear()
total = solve_cost(root_enc)

# Extract chosen policy edges into a new small graph
new_g = ReactionGraph()

kept_nodes: set[int] = set()
kept_nodes: set[str] = set()
kept_edge_indices: set[int] = set()

def extract(enc: str) -> None:
Expand Down Expand Up @@ -285,6 +301,9 @@ def extract(enc: str) -> None:
new_g.edges.append(new_edge)
new_g.out_edges.setdefault(e.src, []).append(len(new_g.edges) - 1)

# Reaction costs can exceed the unresolved-leaf penalty even for a fully
# identified route. Determine completion from the selected frontier itself.
solved = total < inf and all(n.is_identified for n in new_g.get_leaf_nodes(identified_only=False))
return SynthesisExtractResult(graph=new_g, solved=solved, total_cost=total)


Expand All @@ -311,7 +330,7 @@ def run_retromol(submission: Submission, rules: RuleSet) -> Result:
log.debug(f"Extracted synthesis subgraph has {len(r.graph.nodes)} ({len(r.graph.identified_nodes)} identified) nodes and {len(r.graph.edges)} edges")

if not r.solved:
log.debug("Retrosynthesis extraction failed to find a solution")
log.debug("Retrosynthesis extraction retained unresolved frontier fragments")

# Calculate the linear readouts for the synthesis graph
linear_readout = LinearReadout.from_reaction_graph(root, r.graph)
Expand Down
121 changes: 121 additions & 0 deletions tests/test_parsing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
"""Regression tests for extracting usable results from cyclic reaction graphs."""

import networkx as nx
import pytest

from retromol.chem.mol import encode_mol, smiles_to_mol
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, RuleSet
from retromol.model.submission import Submission
from retromol.pipelines.parsing import extract_min_edge_synthesis_subgraph, run_retromol_with_timeout


def add_reaction(graph: ReactionGraph, reactant: str, *products: str) -> None:
source = graph.add_node(smiles_to_mol(reactant))
graph.add_edge(
source,
[smiles_to_mol(smi) for smi in products],
ReactionStep(kind="contested", names=("test reaction",), rule_ids=("test",)),
)


def identify(graph: ReactionGraph, smiles: str) -> None:
node = graph.nodes[encode_mol(smiles_to_mol(smiles))]
node.identify([MatchingRule(name="known", smiles=smiles, props={}, pseudonyms=[])])


def assert_acyclic(graph: ReactionGraph) -> None:
directed = nx.DiGraph()
directed.add_nodes_from(graph.nodes)
directed.add_edges_from((edge.src, dst) for edge in graph.edges for dst in edge.dsts)
assert nx.is_directed_acyclic_graph(directed)


def test_self_dependent_reaction_retains_unresolved_root() -> None:
graph = ReactionGraph()
add_reaction(graph, "[1CH4]", "[1CH4]", "O")
identify(graph, "O")
root = encode_mol(smiles_to_mol("[1CH4]"))

result = extract_min_edge_synthesis_subgraph(graph, root)

assert set(result.graph.nodes) == {root}
assert result.graph.edges == []
assert not result.solved
assert result.total_cost == 5.0


def test_cyclic_fragment_does_not_discard_identified_siblings() -> None:
submission = Submission("CCO")
graph = ReactionGraph()
add_reaction(graph, "[1CH3][2CH2][3OH]", "[1CH4]", "[2CH3][3OH]")
add_reaction(graph, "[2CH3][3OH]", "[2CH2]=[3O]")
add_reaction(graph, "[2CH2]=[3O]", "[2CH3][3OH]")
identify(graph, "[1CH4]")
root = encode_mol(submission.mol)

extracted = extract_min_edge_synthesis_subgraph(graph, root)
result = Result(submission, extracted.graph, LinearReadout.from_reaction_graph(root, extracted.graph))

assert root in extracted.graph.nodes
assert not extracted.solved
assert_acyclic(extracted.graph)
assert len(extracted.graph.get_leaf_nodes(identified_only=True)) == 1
assert result.calculate_coverage() == pytest.approx(1 / 3)


def test_cycle_with_identified_exit_is_solved() -> None:
graph = ReactionGraph()
add_reaction(graph, "[1CH4]", "[1CH3]O")
add_reaction(graph, "[1CH3]O", "[1CH4]")
add_reaction(graph, "[1CH3]O", "[1CH3]N")
identify(graph, "[1CH3]N")
root = encode_mol(smiles_to_mol("[1CH4]"))

result = extract_min_edge_synthesis_subgraph(graph, root)

assert result.solved
assert len(result.graph.edges) == 2
assert_acyclic(result.graph)


def test_fully_identified_route_can_cost_more_than_unsolved_penalty() -> None:
graph = ReactionGraph()
add_reaction(graph, "[1CH4]", "[1CH3]O")
add_reaction(graph, "[1CH3]O", "[1CH3]N")
add_reaction(graph, "[1CH3]N", "[1CH3]Cl")
identify(graph, "[1CH3]Cl")
root = encode_mol(smiles_to_mol("[1CH4]"))

result = extract_min_edge_synthesis_subgraph(graph, root, edge_base_cost=2.0)

assert result.total_cost > 5.0
assert result.solved


@pytest.mark.parametrize(
"smiles",
[
"CCOS(=O)(=O)O",
# NPA000139 and NPA000469 reproduced the missing-root error with default rules.
"O=C(CC(O)(CC(=O)NCCCNCCCNC(=O)c1ccc(O)c(O)c1)C(=O)O)NCCCCNCCCNC(=O)c1ccc(O)c(O)c1S(=O)(=O)O",
"CCCCCCCCCCCCCCCC(=O)NC1CC(O)C(O)NC(=O)C2C(O)C(C)CN2C(=O)C(C(O)CC(N)=O)NC(=O)C(C(O)Cc2ccc(OS(=O)(=O)O)c(O)c2)NC(=O)C2CC(O)CN2C(=O)C(C(C)O)NC1=O",
],
ids=["ethyl sulfate", "NPA000139", "NPA000469"],
)
def test_default_rules_preserve_partial_results_for_sulfated_compounds(smiles: str, ruleset: RuleSet) -> None:
result = run_retromol_with_timeout(Submission(smiles), ruleset)

assert encode_mol(result.submission.mol) in result.reaction_graph.nodes
assert_acyclic(result.reaction_graph)
assert 0 < result.calculate_coverage() < 1
assert any(not node.is_identified for node in result.linear_readout.assembly_graph.monomer_nodes())
restored = Result.from_dict(result.to_dict())
assert restored.calculate_coverage() == result.calculate_coverage()


def test_missing_root_in_invalid_input_graph_still_raises() -> None:
with pytest.raises(ValueError, match="Root encoding missing"):
extract_min_edge_synthesis_subgraph(ReactionGraph(), "missing")
12 changes: 12 additions & 0 deletions tests/test_streaming.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
"""Regression tests for actionable batch parsing errors."""

from retromol.io.streaming import _process_compound


def test_worker_error_includes_input_smiles_and_exception_type() -> None:
result, error = _process_compound(("not-a-smiles", {"id": "broken row"}))

assert result is None
assert error is not None
assert "ValueError" in error
assert "SMILES='not-a-smiles'" in error
Loading