From c3382adc5e2364fd0a3ce587d010363ae8813d1f Mon Sep 17 00:00:00 2001 From: David Meijer Date: Fri, 16 Oct 2026 11:09:05 -0400 Subject: [PATCH 1/7] WIP: adding sequence roles for linear readout --- database/scripts/common.py | 18 +-- gui/src/server/routes/jobs.py | 31 ++--- src/retromol/data/README.md | 41 +++++- src/retromol/data/mxn.yml | 165 +++++++++++++++++++++++ src/retromol/model/assembly_graph.py | 47 ++++--- src/retromol/model/readout.py | 138 ++++++++++++++----- src/retromol/model/rules.py | 11 +- tests/test_readout.py | 192 +++++++++++++++++++++++++++ tests/test_result.py | 13 ++ 9 files changed, 571 insertions(+), 85 deletions(-) create mode 100644 tests/test_readout.py diff --git a/database/scripts/common.py b/database/scripts/common.py index 2668725..0bc9e27 100644 --- a/database/scripts/common.py +++ b/database/scripts/common.py @@ -115,18 +115,12 @@ def npatlas_url(npaid: str | None) -> str | None: def primary_sequence_from_result(result: Result) -> list[str]: """ The single primary sequence for a parsed compound, read directly off - `result.linear_readout` -- no backbone reconstruction involved, that's a - display-only concern this pipeline has no use for. `result.linear_readout` is - already computed by retromol.pipelines.parsing.run_retromol (it's just a field - on Result); every path through the molecule -- including single-node paths for - tailoring events that don't connect to any chain, e.g. glycosylation/methylation - (AssemblyGraph only keeps C-C/C-N bonds as "connections", so a sugar attached via - a glycosidic C-O-C linkage always ends up disconnected from the main chain) -- - is merged into one sequence (longest first, ties broken lexicographically, joined - by TOKEN_LINK -- see `LinearReadout.primary_sequence`), and that single sequence - becomes this compound's one db entry (see load_compounds.py). Nothing found in - the assembly graph is dropped. An unidentified node is named "X", the same - convention used everywhere else in RetroMol. + `result.linear_readout`. The readout is calculated + on demand and includes every identified monomer, including tailoring groups. + Unresolved and unassigned regions are excluded and break paths. The paths are + merged longest first, with lexical ties and TOKEN_LINK between them (see + `LinearReadout.primary_sequence`). This becomes the compound's one database + sequence; `result.calculate_coverage()` measures its heavy-atom completeness. :param result: a parsed RetroMol Result :return: the single primary sequence diff --git a/gui/src/server/routes/jobs.py b/gui/src/server/routes/jobs.py index 6b7805f..65a2261 100644 --- a/gui/src/server/routes/jobs.py +++ b/gui/src/server/routes/jobs.py @@ -307,21 +307,13 @@ def submit_compound() -> tuple[Response, int]: DB_MATCHING_SEQUENCE_NOTE = ( - "This is the exact primary sequence the database-population pipeline stores for " - "this molecule (read directly off result.linear_readout with no backbone " - "reconstruction, no eligibility/orientation filtering, no length filtering: " - "every path found in the assembly graph is included, tailoring events like " - "glycosylation/methylation among them). Every path is merged into this one " - "sequence, longest first, ties broken lexicographically, joined by \"\". " - "The same merge database/scripts/common.py's primary_sequence_from_result " - "applies before storing a compound. Use this to search, not a reconstructed " - "candidate above: reconstruct_linear_readout builds a separate identified-only " - "readout to attempt backbone reconstruction, which diverges from what's actually " - "stored for a real fraction of compounds (anything with unidentified content). " - "Querying with that instead silently caps how similar a match can ever score, " - "even against the molecule's own database entry. To search with just one " - "biosynthetic chain rather than the whole molecule, split this sequence on " - "\"\" and use one of the resulting subsequences instead." + "This sequence includes all identified monomers, including tailoring groups. " + "Unresolved and unassigned regions are omitted; coverage shows the fraction " + "of submitted heavy atoms represented by these identities. Paths are joined " + "by \"\", longest first with lexical tie-breaking. This is the sequence " + "format used when populating the database. Backbone reconstruction can use " + "only a subset of these monomers. To search with one path, split this sequence " + "on \"\" and use the desired part." ) @@ -329,9 +321,8 @@ def _db_matching_primary_sequences(result: Result) -> list[dict]: """ The single primary sequence read directly off result.linear_readout -- the same representation database/scripts/common.py's primary_sequence_from_result uses to - populate the persistent database (itself reproducing the original - db_scripts/create_database.py recipe, recovered from git history at commit - 72a1bbb). Every path is merged into one sequence, nothing filtered out (see + populate the persistent database. Every identified path is merged into one + sequence; unresolved and unassigned regions are excluded (see retromol.model.readout.LinearReadout.primary_sequence / merge_named_paths). Shaped identically to a Reconstruction dict, in a one-element list, so the frontend can render it the same way it does reconstruct_linear_readout's @@ -346,9 +337,7 @@ def _db_matching_primary_sequences(result: Result) -> list[dict]: tagged_input_smiles = mol_to_smiles(result.submission.mol, include_tags=True) named_paths = [ - [[name, list(get_tags_mol(node.mol))] for name, node in zip( - [n.identity.matched_rule.name if n.is_identified else "X" for n in path], path - )] + [[node.identity.name, list(get_tags_mol(node.mol))] for node in path] for path in result.linear_readout.paths ] diff --git a/src/retromol/data/README.md b/src/retromol/data/README.md index 6b3bec8..a42dc32 100644 --- a/src/retromol/data/README.md +++ b/src/retromol/data/README.md @@ -8,7 +8,7 @@ This directory contains three YAML configuration files: | [mxn.yml](mxn.yml) | SMILES that identify whole fragments as monomers, modified units, or tailoring groups. | | [pmp.yml](pmp.yml) | Maps predictions from BGC annotations/models onto matching-rule names or pseudonyms. It does not control compound disconnections. | -Settings that affect parsing belong at the top level of each rule. `props` is for descriptive metadata such as references, notes, and example structures. +Settings that affect parsing or sequence readout belong at the top level of each rule. `props` is for descriptive metadata such as references, notes, and example structures. ## How compound parsing uses the rules @@ -84,6 +84,7 @@ This file is also a YAML list. | `stereochemistry` | Boolean; `false` | Marks a stereo-specific rule. These rules are prioritized when global stereochemical matching is enabled and skipped when it is disabled. | | `preserve_across_routes` | Boolean; `true` | For terminal matches, also protect the original atom region against subdivision through alternative routes. See below. | | `display_smiles` | String or `null`; `null` | Optional alternative structure for depiction. It does not replace `smiles` during matching or change coverage. | +| `sequence_role` | `backbone`, `tailoring`, or `null`; `null` | Role of this monomer in linear assembly readouts. It does not change matching, expansion, terminal protection, or coverage. See below. | | `props` | Mapping; `{}` | Descriptive metadata, such as a reference or an explanation of a modified residue. | For example: @@ -100,6 +101,44 @@ For example: note: Formal capped beta-keto PK unit. ``` +### Backbone and tailoring roles + +Set `sequence_role` on a monomer matching rule when its role in the sequence view +is known: + +```yaml +- name: methylation + smiles: C + sequence_role: tailoring +``` + +`tailoring` means a separately represented modification that should be read +outside the backbone path, even if attached through C–C or C–N. Connected tailoring +units form their own paths, including multi-unit moieties. A modification already +contained in a matched monomer, such as N-methylalanine, stays part of that monomer; +its name alone does not make the whole unit tailoring. This is a representation +policy, not evidence that a reaction happened after backbone synthesis. + +Connections between two explicit `backbone` units are also retained regardless of +bond elements. Where either non-tailoring endpoint has no role, the readout falls +back to C–C/C–N connections. A `tailoring` endpoint always separates from an untagged +or `backbone` endpoint. The defaults mark the existing modification identities as +tailoring and leave other units untagged; no role is inferred from size or degree. +Role choices can depend on the intended compound class, so use custom matching +rules where a motif plays a different role. + +Roles are saved with matching rules in result JSON. Older results without the +field remain readable and use the fallback; reparse with annotated rules to +apply the new defaults to those compounds. + +`assembly_to_primary_sequence(assembly)` returns the resulting paths as +`list[list[str]]`. It retains branches in additional paths and does not label an +unannotated leftover branch as tailoring. Each identified monomer occurs once; +unresolved fragments and the synthetic unassigned node are omitted. Unresolved +regions break paths. Assembly coverage measures how much of the compound these +named units represent: 100% means all submitted heavy atoms have a monomer +identity. See the [Python example](../../../README.md#linear-sequences-from-sampled-assemblies). + ### `terminal` versus `preserve_across_routes` `terminal` controls expansion of the matched fragment itself. `preserve_across_routes` controls whether that terminal match also restricts how **other derivations** divide the same original atoms. diff --git a/src/retromol/data/mxn.yml b/src/retromol/data/mxn.yml index daba9fe..ec51757 100644 --- a/src/retromol/data/mxn.yml +++ b/src/retromol/data/mxn.yml @@ -5,12 +5,14 @@ display_smiles: "O=C(CC([1*])=O)S[2*]" pseudonyms: ["PK_A", "PK"] preserve_across_routes: false + sequence_role: backbone - name: A1 smiles: "O=C(O)C=C(O)SO" display_smiles: "O=C(CC([1*])=O)S[2*]" pseudonyms: ["PK_A", "PK"] preserve_across_routes: false + sequence_role: backbone - name: A1-alpha-oxo smiles: O=C(O)C(=O)C(=O)SO @@ -19,6 +21,7 @@ - PK_A - PK preserve_across_routes: false + sequence_role: backbone props: reference: https://pmc.ncbi.nlm.nih.gov/articles/PMC3624582/ note: Formal alpha-oxidized PK unit; retains the mature carbonyl state, not a distinct biosynthetic extender substrate. @@ -29,6 +32,7 @@ stereochemistry: true pseudonyms: ["A2", "PK_A", "PK"] preserve_across_routes: false + sequence_role: backbone - name: A2^S smiles: "C[C@H](C(SO)=O)C(O)=O" @@ -36,24 +40,28 @@ stereochemistry: true pseudonyms: ["A2", "PK_A", "PK"] preserve_across_routes: false + sequence_role: backbone - name: A2 smiles: "CC(C(=O)O)C(=O)SO" display_smiles: "O=C(C(C)C([1*])=O)S[2*]" pseudonyms: ["PK_A", "PK"] preserve_across_routes: false + sequence_role: backbone - name: A2 smiles: "CC(C(=O)O)=C(O)SO" display_smiles: "O=C(C(C)C([1*])=O)S[2*]" pseudonyms: ["PK_A", "PK"] preserve_across_routes: false + sequence_role: backbone - name: A3 smiles: "CC(C)(C(=O)O)C(=O)SO" display_smiles: "CC(C)(C(=O)[1*])C(=O)S[2*]" pseudonyms: ["PK_A", "PK"] preserve_across_routes: false + sequence_role: backbone - name: A4^R smiles: "CC[C@@H](C(SO)=O)C(O)=O" @@ -61,6 +69,7 @@ stereochemistry: true pseudonyms: ["A4", "PK_A", "PK"] preserve_across_routes: false + sequence_role: backbone - name: A4^S smiles: "CC[C@H](C(SO)=O)C(O)=O" @@ -68,12 +77,14 @@ stereochemistry: true pseudonyms: ["A4", "PK_A", "PK"] preserve_across_routes: false + sequence_role: backbone - name: A4 smiles: "CCC(C(=O)O)C(=O)SO" display_smiles: "CCC(C(=O)[1*])C(=O)S[2*]" pseudonyms: ["PK_A", "PK"] preserve_across_routes: false + sequence_role: backbone - name: A5^R smiles: "O=C([C@H](C(SO)=O)O)O" @@ -81,6 +92,7 @@ stereochemistry: true pseudonyms: ["A5", "PK_A", "PK"] preserve_across_routes: false + sequence_role: backbone - name: A5^S smiles: "O=C([C@@H](C(SO)=O)O)O" @@ -88,18 +100,21 @@ stereochemistry: true pseudonyms: ["A5", "PK_A", "PK"] preserve_across_routes: false + sequence_role: backbone - name: A5 smiles: "O=C(O)C(O)C(=O)SO" display_smiles: "O=C(C(C(S[2*])=O)O)[1*]" pseudonyms: ["PK_A", "PK"] preserve_across_routes: false + sequence_role: backbone - name: A5 smiles: "O=C(C(O)=C(SO)O)O" display_smiles: "O=C(C(C(S[2*])=O)O)[1*]" pseudonyms: ["PK_A", "PK"] preserve_across_routes: false + sequence_role: backbone - name: A6^R smiles: "C[C@@](C(O)=O)(C(SO)=O)O" @@ -107,6 +122,7 @@ stereochemistry: true pseudonyms: ["A6", "PK_A", "PK"] preserve_across_routes: false + sequence_role: backbone - name: A6^S smiles: "C[C@](C(O)=O)(C(SO)=O)O" @@ -114,12 +130,14 @@ stereochemistry: true pseudonyms: ["A6", "PK_A", "PK"] preserve_across_routes: false + sequence_role: backbone - name: A6 smiles: "CC(O)(C(=O)O)C(=O)SO" display_smiles: "CC(C([1*])=O)(C(S[2*])=O)O" pseudonyms: ["PK_A", "PK"] preserve_across_routes: false + sequence_role: backbone - name: A7^R smiles: "O=C([C@H](C(SO)=O)CO)O" @@ -127,6 +145,7 @@ stereochemistry: true pseudonyms: ["A7", "PK_A", "PK"] preserve_across_routes: false + sequence_role: backbone - name: A7^S smiles: "O=C([C@@H](C(SO)=O)CO)O" @@ -134,30 +153,35 @@ stereochemistry: true pseudonyms: ["A7", "PK_A", "PK"] preserve_across_routes: false + sequence_role: backbone - name: A7 smiles: "O=C(O)C(CO)C(=O)SO" display_smiles: "O=C(C(C(S[2*])=O)CO)[1*]" pseudonyms: ["PK_A", "PK"] preserve_across_routes: false + sequence_role: backbone - name: A7 smiles: "O=C(O)C(CO)=C(O)SO" display_smiles: "O=C(C(C(S[2*])=O)CO)[1*]" pseudonyms: ["PK_A", "PK"] preserve_across_routes: false + sequence_role: backbone - name: A8 smiles: "C=C(CC(=O)O)SO" display_smiles: "C=C(CC(=O)S[2*])[1*]" pseudonyms: ["PK_A", "PK"] preserve_across_routes: false + sequence_role: backbone - name: A8 smiles: "CC(=CC(=O)O)SO" display_smiles: "C=C(CC(=O)S[2*])[1*]" pseudonyms: ["PK_A", "PK"] preserve_across_routes: false + sequence_role: backbone - name: A9^R smiles: "C=C([C@@H](C(O)=O)C)SO" @@ -165,6 +189,7 @@ stereochemistry: true pseudonyms: ["A9", "PK_A", "PK"] preserve_across_routes: false + sequence_role: backbone - name: A9^S smiles: "C=C([C@H](C(O)=O)C)SO" @@ -172,12 +197,14 @@ stereochemistry: true pseudonyms: ["A9", "PK_A", "PK"] preserve_across_routes: false + sequence_role: backbone - name: A9 smiles: "C=C(SO)C(C)C(=O)O" display_smiles: "C=C(C(C(S[2*])=O)C)[1*]" pseudonyms: ["PK_A", "PK"] preserve_across_routes: false + sequence_role: backbone - name: A10^R smiles: "C=C([C@@H](C(O)=O)O)SO" @@ -185,6 +212,7 @@ stereochemistry: true pseudonyms: ["A10", "PK_A", "PK"] preserve_across_routes: false + sequence_role: backbone - name: A10^S smiles: "C=C([C@H](C(O)=O)O)SO" @@ -192,18 +220,21 @@ stereochemistry: true pseudonyms: ["A10", "PK_A", "PK"] preserve_across_routes: false + sequence_role: backbone - name: A10 smiles: "C=C(SO)C(O)C(=O)O" display_smiles: "C=C(C(C(S[2*])=O)O)[1*]" pseudonyms: ["PK_A", "PK"] preserve_across_routes: false + sequence_role: backbone - name: A11 smiles: "C=C(SO)C(=O)C(=O)O" display_smiles: "C=C([1*])C(=O)C(=O)S[2*]" pseudonyms: ["PK_A", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^R1 smiles: "O=C(C[C@@H](SO)O)O" @@ -211,6 +242,7 @@ stereochemistry: true pseudonyms: ["B1", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^S1 smiles: "O=C(C[C@H](SO)O)O" @@ -218,12 +250,14 @@ stereochemistry: true pseudonyms: ["B1", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B1 smiles: "O=C(O)CC(O)SO" display_smiles: "O=C(CC([1*])O)S[2*]" pseudonyms: ["PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^R2^R smiles: "C[C@@H]([C@@H](SO)O)C(O)=O" @@ -231,6 +265,7 @@ stereochemistry: true pseudonyms: ["B2", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^R2^S smiles: "C[C@H]([C@@H](SO)O)C(O)=O" @@ -238,6 +273,7 @@ stereochemistry: true pseudonyms: ["B2", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^R2 smiles: "CC([C@@H](SO)O)C(O)=O" @@ -245,6 +281,7 @@ stereochemistry: true pseudonyms: ["B2", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^S2^R smiles: "C[C@@H]([C@H](SO)O)C(O)=O" @@ -252,6 +289,7 @@ stereochemistry: true pseudonyms: ["B2", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^S2^S smiles: "C[C@H]([C@H](SO)O)C(O)=O" @@ -259,6 +297,7 @@ stereochemistry: true pseudonyms: ["B2", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^S2 smiles: "CC([C@H](SO)O)C(O)=O" @@ -266,12 +305,14 @@ stereochemistry: true pseudonyms: ["B2", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B2 smiles: "CC(C(=O)O)C(O)SO" display_smiles: "CC(C(=O)S[2*])C(O)[1*]" pseudonyms: ["PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B2-alpha-carboxy smiles: CC(C(=O)O)(C(=O)O)C(O)SO @@ -285,6 +326,7 @@ pseudonyms: - PK_B - PK + sequence_role: backbone - name: B2-alpha-hydroxymethyl smiles: CC(CO)(C(=O)O)C(O)SO @@ -298,6 +340,7 @@ pseudonyms: - PK_B - PK + sequence_role: backbone - name: B^R3 smiles: "CC(C(O)=O)([C@@H](SO)O)C" @@ -305,6 +348,7 @@ stereochemistry: true pseudonyms: ["B3", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^S3 smiles: "CC(C(O)=O)([C@H](SO)O)C" @@ -312,12 +356,14 @@ stereochemistry: true pseudonyms: ["B3", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B3 smiles: "CC(C)(C(=O)O)C(O)SO" display_smiles: "CC(C)(C(=O)S[2*])C(O)[1*]" pseudonyms: ["PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^R4^R smiles: "CC[C@@H]([C@@H](SO)O)C(O)=O" @@ -325,6 +371,7 @@ stereochemistry: true pseudonyms: ["B4", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^R4^S smiles: "CC[C@H]([C@@H](SO)O)C(O)=O" @@ -332,6 +379,7 @@ stereochemistry: true pseudonyms: ["B4", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^S4^R smiles: "CC[C@@H]([C@H](SO)O)C(O)=O" @@ -339,6 +387,7 @@ stereochemistry: true pseudonyms: ["B4", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^S4^S smiles: "CC[C@H]([C@H](SO)O)C(O)=O" @@ -346,12 +395,14 @@ stereochemistry: true pseudonyms: ["B4", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B4 smiles: "CCC(C(=O)O)C(O)SO" display_smiles: "CCC(C(=O)S[2*])C(O)[1*]" pseudonyms: ["PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^R5^R smiles: "O=C([C@H]([C@@H](SO)O)O)O" @@ -359,6 +410,7 @@ stereochemistry: true pseudonyms: ["B5", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^R5^S smiles: "O=C([C@@H]([C@@H](SO)O)O)O" @@ -366,6 +418,7 @@ stereochemistry: true pseudonyms: ["B5", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^S5^R smiles: "O=C([C@H]([C@H](SO)O)O)O" @@ -373,6 +426,7 @@ stereochemistry: true pseudonyms: ["B5", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^S5^S smiles: "O=C([C@@H]([C@H](SO)O)O)O" @@ -380,12 +434,14 @@ stereochemistry: true pseudonyms: ["B5", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B5 smiles: "O=C(O)C(O)C(O)SO" display_smiles: "O=C(S[2*])C(O)C(O)[1*]" pseudonyms: ["PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^R6^R smiles: "C[C@@](C(O)=O)([C@@H](SO)O)O" @@ -393,6 +449,7 @@ stereochemistry: true pseudonyms: ["B6", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^R6^S smiles: "C[C@](C(O)=O)([C@@H](SO)O)O" @@ -400,6 +457,7 @@ stereochemistry: true pseudonyms: ["B6", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^S6^R smiles: "C[C@@](C(O)=O)([C@H](SO)O)O" @@ -407,6 +465,7 @@ stereochemistry: true pseudonyms: ["B6", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^S6^S smiles: "C[C@](C(O)=O)([C@H](SO)O)O" @@ -414,12 +473,14 @@ stereochemistry: true pseudonyms: ["B6", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B6 smiles: "CC(O)(C(=O)O)C(O)SO" display_smiles: "CC(O)(C(=O)S[2*])C(O)[1*]" pseudonyms: ["PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^R7^R smiles: "O=C([C@H]([C@@H](SO)O)CO)O" @@ -427,6 +488,7 @@ stereochemistry: true pseudonyms: ["B7", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^R7^S smiles: "O=C([C@@H]([C@@H](SO)O)CO)O" @@ -434,6 +496,7 @@ stereochemistry: true pseudonyms: ["B7", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^S7^R smiles: "O=C([C@H]([C@H](SO)O)CO)O" @@ -441,6 +504,7 @@ stereochemistry: true pseudonyms: ["B7", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^S7^S smiles: "O=C([C@@H]([C@H](SO)O)CO)O" @@ -448,12 +512,14 @@ stereochemistry: true pseudonyms: ["B7", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B7 smiles: "O=C(O)C(CO)C(O)SO" display_smiles: "O=C(S[2*])C(CO)C(O)[1*]" pseudonyms: ["PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^R8 smiles: "C[C@](CC(O)=O)(SO)O" @@ -461,6 +527,7 @@ stereochemistry: true pseudonyms: ["B8", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^S8 smiles: "C[C@@](CC(O)=O)(SO)O" @@ -468,12 +535,14 @@ stereochemistry: true pseudonyms: ["B8", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B8 smiles: "CC(O)(CC(=O)O)SO" display_smiles: "CC(O)(CC(=O)S[2*])[1*]" pseudonyms: ["PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^R9^R smiles: "C[C@@H]([C@](O)(SO)C)C(O)=O" @@ -481,6 +550,7 @@ stereochemistry: true pseudonyms: ["B9", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^R9^S smiles: "C[C@H]([C@](O)(SO)C)C(O)=O" @@ -488,6 +558,7 @@ stereochemistry: true pseudonyms: ["B9", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^S9^R smiles: "C[C@@H]([C@@](O)(SO)C)C(O)=O" @@ -495,6 +566,7 @@ stereochemistry: true pseudonyms: ["B9", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^S9^S smiles: "C[C@H]([C@@](O)(SO)C)C(O)=O" @@ -502,12 +574,14 @@ stereochemistry: true pseudonyms: ["B9", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B9 smiles: "CC(C(=O)O)C(C)(O)SO" display_smiles: "CC(C(=O)S[2*])C(C)(O)[1*]" pseudonyms: ["PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^R10^R smiles: "C[C@@](SO)([C@@H](C(O)=O)O)O" @@ -515,6 +589,7 @@ stereochemistry: true pseudonyms: ["B10", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^R10^S smiles: "C[C@@](SO)([C@H](C(O)=O)O)O" @@ -522,6 +597,7 @@ stereochemistry: true pseudonyms: ["B10", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^S10^R smiles: "C[C@](SO)([C@@H](C(O)=O)O)O" @@ -529,6 +605,7 @@ stereochemistry: true pseudonyms: ["B10", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^S10^S smiles: "C[C@](SO)([C@H](C(O)=O)O)O" @@ -536,18 +613,21 @@ stereochemistry: true pseudonyms: ["B10", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B10 smiles: "CC(O)(SO)C(O)C(=O)O" display_smiles: "CC(O)([1*])C(O)C(=O)S[2*]" pseudonyms: ["PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B11 smiles: "O=C(O)C(=O)C(O)SO" display_smiles: "O=C(S[2*])C(=O)C(O)[1*]" pseudonyms: ["PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^R12^R smiles: "N[C@@H]([C@@H](SO)O)C(O)=O" @@ -555,6 +635,7 @@ stereochemistry: true pseudonyms: ["B12", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^R12^S smiles: "N[C@H]([C@@H](SO)O)C(O)=O" @@ -562,6 +643,7 @@ stereochemistry: true pseudonyms: ["B12", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^S12^R smiles: "N[C@@H]([C@H](SO)O)C(O)=O" @@ -569,6 +651,7 @@ stereochemistry: true pseudonyms: ["B12", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^S12^S smiles: "N[C@H]([C@H](SO)O)C(O)=O" @@ -576,12 +659,14 @@ stereochemistry: true pseudonyms: ["B12", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B12 smiles: "NC(C(=O)O)C(O)SO" display_smiles: "NC(C(=O)S[2*])C(O)[1*]" pseudonyms: ["PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^R13 smiles: "OS[C@H](C(C(O)=O)C(O)=O)O" @@ -589,6 +674,7 @@ stereochemistry: true pseudonyms: ["B13", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B^S13 smiles: "OS[C@@H](C(C(O)=O)C(O)=O)O" @@ -596,12 +682,14 @@ stereochemistry: true pseudonyms: ["B13", "PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: B13 smiles: "OSC(O)C(C(=O)O)C(=O)O" display_smiles: "[1*]C(O)C(C(=O)O)C(=O)S[2*]" pseudonyms: ["PK_B", "PK"] preserve_across_routes: false + sequence_role: backbone - name: C^E1 smiles: 'O=C(/C=C/SO)O' @@ -609,6 +697,7 @@ stereochemistry: true pseudonyms: ["PK_C", "PK"] preserve_across_routes: false + sequence_role: backbone - name: C^Z1 smiles: 'O=C(/C=C\SO)O' @@ -616,12 +705,14 @@ stereochemistry: true pseudonyms: ["PK_C", "PK"] preserve_across_routes: false + sequence_role: backbone - name: C1 smiles: "O=C(O)C=CSO" display_smiles: "O=C(S[2*])C=C[1*]" pseudonyms: ["PK_C", "PK"] preserve_across_routes: false + sequence_role: backbone - name: C^E2 smiles: 'C/C(C(O)=O)=C\SO' @@ -629,6 +720,7 @@ stereochemistry: true pseudonyms: ["C2", "PK_C", "PK"] preserve_across_routes: false + sequence_role: backbone - name: C^Z2 smiles: 'C/C(C(O)=O)=C/SO' @@ -636,12 +728,14 @@ stereochemistry: true pseudonyms: ["C2", "PK_C", "PK"] preserve_across_routes: false + sequence_role: backbone - name: C2 smiles: "CC(=CSO)C(=O)O" display_smiles: "CC(=C[1*])C(=O)S[2*]" pseudonyms: ["PK_C", "PK"] preserve_across_routes: false + sequence_role: backbone - name: C^E4 smiles: 'CC/C(C(O)=O)=C\SO' @@ -649,6 +743,7 @@ stereochemistry: true pseudonyms: ["C4", "PK_C", "PK"] preserve_across_routes: false + sequence_role: backbone - name: C^Z4 smiles: 'CC/C(C(O)=O)=C/SO' @@ -656,6 +751,7 @@ stereochemistry: true pseudonyms: ["C4", "PK_C", "PK"] preserve_across_routes: false + sequence_role: backbone - name: C4 smiles: "CCC(=CSO)C(=O)O" @@ -669,6 +765,7 @@ stereochemistry: true pseudonyms: ["C7", "PK_C", "PK"] preserve_across_routes: false + sequence_role: backbone - name: C^Z7 smiles: 'O=C(/C(CO)=C\SO)O' @@ -676,24 +773,28 @@ stereochemistry: true pseudonyms: ["C7", "PK_C", "PK"] preserve_across_routes: false + sequence_role: backbone - name: C7 smiles: "O=C(O)C(=CSO)CO" display_smiles: "O=C(S[2*])C(=C[1*])CO" pseudonyms: ["PK_C", "PK"] preserve_across_routes: false + sequence_role: backbone - name: C13 smiles: "O=C(C(C(O)=O)=CSO)O" display_smiles: "O=C(C(C(O)=O)=C[1*])S[2*]" pseudonyms: ["PK_C", "PK"] preserve_across_routes: false + sequence_role: backbone - name: D1 smiles: "O=C(O)CCSO" display_smiles: "O=C(S[2*])CC[1*]" pseudonyms: ["PK_D", "PK"] preserve_across_routes: false + sequence_role: backbone - name: D2^R smiles: "C[C@H](C(O)=O)CSO" @@ -701,6 +802,7 @@ stereochemistry: true pseudonyms: ["D2", "PK_D", "PK"] preserve_across_routes: false + sequence_role: backbone - name: D2^S smiles: "C[C@@H](C(O)=O)CSO" @@ -708,18 +810,21 @@ stereochemistry: true pseudonyms: ["D2", "PK_D", "PK"] preserve_across_routes: false + sequence_role: backbone - name: D2 smiles: "CC(CSO)C(=O)O" display_smiles: "CC(C[1*])C(=O)S[2*]" pseudonyms: ["PK_D", "PK"] preserve_across_routes: false + sequence_role: backbone - name: D3 smiles: "CC(C)(CSO)C(=O)O" display_smiles: "CC(C)(C[1*])C(=O)S[2*]" pseudonyms: ["PK_D", "PK"] preserve_across_routes: false + sequence_role: backbone - name: D4^R smiles: "CC[C@H](C(O)=O)CSO" @@ -727,6 +832,7 @@ stereochemistry: true pseudonyms: ["D4", "PK_D", "PK"] preserve_across_routes: false + sequence_role: backbone - name: D4^S smiles: "CC[C@@H](C(O)=O)CSO" @@ -734,12 +840,14 @@ stereochemistry: true pseudonyms: ["D4", "PK_D", "PK"] preserve_across_routes: false + sequence_role: backbone - name: D4 smiles: "CCC(CSO)C(=O)O" display_smiles: "CCC(C[1*])C(=O)S[2*]" pseudonyms: ["PK_D", "PK"] preserve_across_routes: false + sequence_role: backbone - name: D5^R smiles: "O=C([C@H](CSO)O)O" @@ -747,6 +855,7 @@ pseudonyms: ["D5", "PK_D", "PK"] stereochemistry: true preserve_across_routes: false + sequence_role: backbone - name: D5^S smiles: "O=C([C@@H](CSO)O)O" @@ -754,12 +863,14 @@ stereochemistry: true pseudonyms: ["D5", "PK_D", "PK"] preserve_across_routes: false + sequence_role: backbone - name: D5 smiles: "O=C(O)C(O)CSO" display_smiles: "O=C(S[2*])C(O)C[1*]" pseudonyms: ["PK_D", "PK"] preserve_across_routes: false + sequence_role: backbone - name: D6^R smiles: "C[C@](CSO)(C(O)=O)O" @@ -767,6 +878,7 @@ stereochemistry: true pseudonyms: ["D6", "PK_D", "PK"] preserve_across_routes: false + sequence_role: backbone - name: D6^S smiles: "C[C@@](CSO)(C(O)=O)O" @@ -774,12 +886,14 @@ stereochemistry: true pseudonyms: ["D6", "PK_D", "PK"] preserve_across_routes: false + sequence_role: backbone - name: D6 smiles: "CC(O)(CSO)C(=O)O" display_smiles: "CC(O)(C[1*])C(=O)S[2*]" pseudonyms: ["PK_D", "PK"] preserve_across_routes: false + sequence_role: backbone - name: D7^R smiles: "O=C([C@H](CSO)CO)O" @@ -787,6 +901,7 @@ stereochemistry: true pseudonyms: ["D7", "PK_D", "PK"] preserve_across_routes: false + sequence_role: backbone - name: D7^S smiles: "O=C([C@@H](CSO)CO)O" @@ -794,12 +909,14 @@ stereochemistry: true pseudonyms: ["D7", "PK_D", "PK"] preserve_across_routes: false + sequence_role: backbone - name: D7 smiles: "O=C(O)C(CO)CSO" display_smiles: "O=C(S[2*])C(CO)C[1*]" pseudonyms: ["PK_D", "PK"] preserve_across_routes: false + sequence_role: backbone - name: D^R8 smiles: "C[C@@H](SO)CC(O)=O" @@ -807,6 +924,7 @@ stereochemistry: true pseudonyms: ["D8", "PK_D", "PK"] preserve_across_routes: false + sequence_role: backbone - name: D^S8 smiles: "C[C@H](SO)CC(O)=O" @@ -814,12 +932,14 @@ stereochemistry: true pseudonyms: ["D8", "PK_D", "PK"] preserve_across_routes: false + sequence_role: backbone - name: D8 smiles: "CC(CC(=O)O)SO" display_smiles: "CC(CC(=O)S[2*])[1*]" pseudonyms: ["PK_D", "PK"] preserve_across_routes: false + sequence_role: backbone - name: D^R10^R smiles: "C[C@H]([C@@H](C(O)=O)O)SO" @@ -827,6 +947,7 @@ stereochemistry: true pseudonyms: ["D10", "PK_D", "PK"] preserve_across_routes: false + sequence_role: backbone - name: D^R10^S smiles: "C[C@H]([C@H](C(O)=O)O)SO" @@ -834,6 +955,7 @@ stereochemistry: true pseudonyms: ["D10", "PK_D", "PK"] preserve_across_routes: false + sequence_role: backbone - name: D^S10^R smiles: "C[C@@H]([C@@H](C(O)=O)O)SO" @@ -841,6 +963,7 @@ stereochemistry: true pseudonyms: ["D10", "PK_D", "PK"] preserve_across_routes: false + sequence_role: backbone - name: D^S10^S smiles: "C[C@@H]([C@H](C(O)=O)O)SO" @@ -848,12 +971,14 @@ stereochemistry: true pseudonyms: ["D10", "PK_D", "PK"] preserve_across_routes: false + sequence_role: backbone - name: D10 smiles: "CC(SO)C(O)C(=O)O" display_smiles: "CC([1*])C(O)C(=O)S[2*]" pseudonyms: ["PK_D", "PK"] preserve_across_routes: false + sequence_role: backbone - name: D11 smiles: "O=C(O)C(=O)CSO" @@ -974,42 +1099,53 @@ preserve_across_routes: false - name: methylation + sequence_role: tailoring smiles: "C" - name: oxidation + sequence_role: tailoring smiles: "O" - name: amination + sequence_role: tailoring smiles: "N" - name: cyanide + sequence_role: tailoring smiles: "C#N" - name: boronation + sequence_role: tailoring smiles: "B" - name: phosphonylation + sequence_role: tailoring smiles: "OP(O)(O)O" - name: phosphate + sequence_role: tailoring smiles: "O=P(O)(O)O" terminal: true props: note: "Ordinary phosphate, distinct from the existing OP(O)(O)O phosphonylation entry." - name: fluorination + sequence_role: tailoring smiles: "F" pseudonyms: ["halogenation"] - name: chlorination + sequence_role: tailoring smiles: "Cl" pseudonyms: ["halogenation"] - name: bromination + sequence_role: tailoring smiles: "Br" pseudonyms: ["halogenation"] - name: iodination + sequence_role: tailoring smiles: "I" pseudonyms: ["halogenation"] @@ -1041,96 +1177,125 @@ smiles: "CCC(O)=O" - name: glycosylation + sequence_role: tailoring smiles: "CC1CC(N)C(O)C(O)O1" - name: glycosylation + sequence_role: tailoring smiles: "CC1OC(O)CC(N)C1O" - name: glycosylation + sequence_role: tailoring smiles: "CC1OC(O)CC(C)(O)C1O" - name: glycosylation + sequence_role: tailoring smiles: "CC1CC(O)C(O)C(O)O1" - name: glycosylation + sequence_role: tailoring smiles: "NC1C(O)OC(O)C(O)C1O" - name: glycosylation + sequence_role: tailoring smiles: "OC1COC(O)C(O)C1O" - name: glycosylation + sequence_role: tailoring smiles: "OCC1OC(O)C(O)C(O)C1O" - name: glycosylation + sequence_role: tailoring smiles: "CC1OC(O)CCC1O" - name: glycosylation + sequence_role: tailoring smiles: "CC1OC(O)CC(O)C1O" - name: glycosylation + sequence_role: tailoring smiles: "CC1OC(O)C(O)C(O)C1O" - name: glycosylation + sequence_role: tailoring smiles: "CC1OC(O)C(O)C(N)C1O" - name: glycosylation + sequence_role: tailoring smiles: "CC(C1(C(C(C(OC1C)O)O)O)O)O" - name: glycosylation + sequence_role: tailoring smiles: "CC(C1(O)C(O)C(O)C(O)OC1C)=O" - name: glycosylation + sequence_role: tailoring smiles: "NC1C(C(C(OC1O)CO)O)O" - name: glycosylation + sequence_role: tailoring smiles: "NC1COC(CC1O)O" - name: glycosylation + sequence_role: tailoring smiles: "OC1C(O)C(N)C(C)OC1O" - name: glycosylation + sequence_role: tailoring smiles: "CC1OC(CC(C1S)O)O" - name: glycosylation + sequence_role: tailoring smiles: "CC1(N)CC(O)OC(C)C1O" - name: glycosylation + sequence_role: tailoring smiles: "NC1C(O)C(O)C(O)C(N)C1" - name: glycosylation + sequence_role: tailoring smiles: "O=CC1(O)C(CO)OC(O)C1O" # Tautomers - name: glycosylation + sequence_role: tailoring smiles: "NC(N)=NC1C(O)C(O)C(O)C(N=C(N)N)C1O" - name: glycosylation + sequence_role: tailoring smiles: "N=C(N)NC1C(O)C(NC(=N)N)C(O)C(O)C1O" - name: glycosylation + sequence_role: tailoring smiles: "OCC1OC(O)C(O)C1O" - name: glycosylation + sequence_role: tailoring smiles: "NCC1OC(C(C(C1O)O)N)O" - name: glycosylation + sequence_role: tailoring smiles: "OC1CC(C)(OC)C(O)C(C)O1" - name: glycosylation + sequence_role: tailoring smiles: "OC1C(O)C(N(C)C)CC(C)O1" - name: glycosylation + sequence_role: tailoring smiles: CC1OC(O)CC(C)([N+](=O)[O-])C1N props: reference: https://pubmed.ncbi.nlm.nih.gov/17985890/ note: Kijanose-derived nitrosugar after removing the N-methoxycarbonyl tailoring group. - name: glycosylation + sequence_role: tailoring smiles: CC1OC(O)CC(C)([N+](=O)[O-])C1O props: reference: https://doi.org/10.1007/s00203-007-0337-3 note: O-demethylated rubranitrose/evernitrose constitution; stereochemistry is not specified. - name: glycosylation + sequence_role: tailoring smiles: CC1OC(O)CCC1=O props: reference: https://pmc.ncbi.nlm.nih.gov/articles/PMC1851095/ diff --git a/src/retromol/model/assembly_graph.py b/src/retromol/model/assembly_graph.py index 88ec291..9f2ace0 100644 --- a/src/retromol/model/assembly_graph.py +++ b/src/retromol/model/assembly_graph.py @@ -297,12 +297,18 @@ def connected_components(self, keep_unassigned: bool = False) -> list["AssemblyG def longest_path(self, keep_unassigned: bool = False, max_starts: int = 25) -> list[MolNode]: """ - Find the longest path of monomer nodes in assembly graph. + Find a long simple path across all components, with stable tie-breaking. + + Exact for trees; cyclic graphs use a bounded multi-start heuristic. + Orientation is deterministic for the same tagged graph, not an inferred + biosynthetic direction. :param keep_unassigned: Whether to keep the unassigned node in the graph (default: False) :param max_starts: Maximum number of starting nodes for greedy search (default: 25) - :return: List of MolNode instances representing the longest path + :return: List of MolNode instances representing the selected path """ + if type(max_starts) is not int or max_starts < 1: + raise ValueError("max_starts must be a positive integer") g = self.g h = g.copy() @@ -340,11 +346,20 @@ def to_molnodes(path_nodes: list[Any]) -> list[MolNode]: """ return [node_to_molnode(n) for n in path_nodes] + def node_key(node_id: Any) -> tuple: + node = node_to_molnode(node_id) + name = node.identity.name if node.is_identified else "X" + return name, tuple(sorted(h.nodes[node_id].get("tags", set()))), str(node_id) + + def path_key(path: list[Any]) -> tuple: + return -len(path), tuple(node_key(n) for n in path) + def oriented(path: list[Any]) -> list[Any]: + return min(path, list(reversed(path)), key=path_key) + + best_path_nodes: list[Any] = [] for comp_nodes in nx.connected_components(h): # Work per connected component; pick the longest result - best_path_nodes: list[Any] = [] - c = h.subgraph(comp_nodes).copy() if c.number_of_nodes() == 0: continue @@ -353,15 +368,15 @@ def to_molnodes(path_nodes: list[Any]) -> list[MolNode]: is_tree = nx.is_connected(c) and (c.number_of_edges() == c.number_of_nodes() - 1) if is_tree: # Diameter of a tree via two BFS - start = next(iter(c.nodes)) + start = min(c.nodes, key=node_key) dist1 = nx.single_source_shortest_path_length(c, start) - u = max(dist1, key=dist1.get) + u = min(dist1, key=lambda n: (-dist1[n], node_key(n))) dist2 = nx.single_source_shortest_path_length(c, u) - v = max(dist2, key=dist2.get) + v = min(dist2, key=lambda n: (-dist2[n], node_key(n))) - path_uv = nx.shortest_path(c, u, v) - if len(path_uv) > len(best_path_nodes): + path_uv = oriented(nx.shortest_path(c, u, v)) + if path_key(path_uv) < path_key(best_path_nodes): best_path_nodes = path_uv continue @@ -378,7 +393,7 @@ def greedy_walk(start: Any) -> list[Any]: cur = start while True: - options = [nb for nb in c.neighbors(cur) if nb not in used] + options = sorted((nb for nb in c.neighbors(cur) if nb not in used), key=node_key) if not options: break @@ -411,24 +426,24 @@ def greedy_walk(start: Any) -> list[Any]: return path # Try low-degree starts first (often good for long simple paths) - nodes_sorted = sorted(c.nodes, key=lambda n: c.degree(n)) + nodes_sorted = sorted(c.nodes, key=lambda n: (c.degree(n), node_key(n))) n_starts = min(max_starts, len(nodes_sorted)) starts = nodes_sorted[:n_starts] best_comp_path: list[Any] = [] for s in starts: - cand = greedy_walk(s) - if len(cand) > len(best_comp_path): + cand = oriented(greedy_walk(s)) + if path_key(cand) < path_key(best_comp_path): best_comp_path = cand # Try starting from the found endpoints (sometimes extends) if best_comp_path: for endpoint in (best_comp_path[0], best_comp_path[-1]): - cand = greedy_walk(endpoint) - if len(cand) > len(best_comp_path): + cand = oriented(greedy_walk(endpoint)) + if path_key(cand) < path_key(best_comp_path): best_comp_path = cand - if len(best_comp_path) > len(best_path_nodes): + if path_key(best_comp_path) < path_key(best_path_nodes): best_path_nodes = best_comp_path return to_molnodes(best_path_nodes) diff --git a/src/retromol/model/readout.py b/src/retromol/model/readout.py index 1c64a31..1613e49 100644 --- a/src/retromol/model/readout.py +++ b/src/retromol/model/readout.py @@ -5,9 +5,6 @@ from retromol.model.reaction_graph import MolNode, ReactionGraph from retromol.model.assembly_graph import AssemblyGraph -from retromol.model.rules import MatchingRule -from retromol.chem.mol import encode_mol -from retromol.chem.tagging import get_tags_mol from retromol_fingerprint.fingerprint import TOKEN_LINK @@ -20,8 +17,8 @@ def merge_named_paths(paths: list[list[T]], key: Callable[[T], str], link_item: """ Merge candidate primary sequence paths into a single sequence, joined by `link_item`, so a compound/BGC with more than one disconnected path (e.g. a - branched/cyclic assembly, or a sugar attached via a glycosidic bond that - AssemblyGraph never treats as a "connection") still gets exactly one primary + branched/cyclic assembly, or a separately represented tailoring moiety) + still gets exactly one primary sequence to store/query/align, instead of one entry per path. Longer paths sort first; paths of equal length are ordered lexicographically @@ -74,12 +71,28 @@ class LinearReadout: A linear readout representation of a RetroMol parsing result. :cvar assembly_graph: AssemblyGraph representing the assembly of monomers. - :cvar paths: list of paths (each path is a list of MolNodes) extracted from the assembly graph, representing linear sequences of monomers. + :cvar paths: Disjoint paths of identified MolNodes. Unresolved regions break + paths and remain only in the source assembly graph. """ assembly_graph: AssemblyGraph paths: list[list[MolNode]] + def __post_init__(self) -> None: + """Keep direct construction and older serialized paths identified-only.""" + paths: list[list[MolNode]] = [] + for path in self.paths: + part: list[MolNode] = [] + for node in path: + if node.is_identified and node.identity is not None: + part.append(node) + elif part: + paths.append(part) + part = [] + if part: + paths.append(part) + object.__setattr__(self, "paths", paths) + def __str__(self) -> str: """ Return a string representation of the LinearReadout. @@ -104,7 +117,8 @@ def from_reaction_graph( :param root_enc: Encoding of the root molecule. :param reaction_graph: ReactionGraph object. - :param identified_only: Whether to only include identified monomers. + :param identified_only: Whether to only include identified monomers in + the source assembly graph. Readout paths are always identified-only. :param include_unassigned: Whether to include an unassigned node in the assembly graph. :return: LinearReadout instance. :raises ValueError: If root_enc not found in reaction graph nodes. @@ -123,44 +137,81 @@ def from_reaction_graph( @classmethod def from_assembly_graph(cls, assembly_graph: AssemblyGraph) -> "LinearReadout": - """Extract sequences from a particular assembly projection on demand.""" - a = assembly_graph - # Break bonds between monomers that are not backbone-related bonds (i.e., keep C-C and C-N bonds only) - f = a.filtered_by_root_bond_elements(allow_pairs={frozenset(("C", "C")), frozenset(("C", "N"))}, drop_isolated=False) - - # Get individual connected components from the assembly graph and extract longest paths (allow to visit each edge only once) - hs = f.connected_components() + """Partition a sampled assembly into deterministic, disjoint paths. + + Matching-rule ``sequence_role`` separates tailoring units from other + units. Connections between units with the same explicit role survive + regardless of bond elements (e.g. a connected sugar chain). Otherwise, + the C-C/C-N heuristic applies to non-tailoring units. + + Repeatedly extract a long simple path and process its remaining branches + so every identified MolNode occurs exactly once. Unidentified and + unassigned nodes are excluded before traversal, breaking paths at gaps. + The input graph is unchanged; use its coverage to measure completeness. + Rings are opened deterministically, without assigning a biological start + or direction; cyclic path selection is heuristic. + """ + g = assembly_graph.g.copy() + if g.has_node(assembly_graph.unassigned): + g.remove_node(assembly_graph.unassigned) + + roles = {} + for node_id, data in list(g.nodes(data=True)): + node = data.get("molnode") + if node is None: + raise ValueError(f"AssemblyGraph node {node_id!r} has no 'molnode' attached!") + if not node.is_identified or node.identity is None: + g.remove_node(node_id) + continue + roles[node_id] = node.identity.matched_rule.sequence_role + + backbone_pairs = {frozenset(("C", "C")), frozenset(("C", "N"))} + for u, v, data in list(g.edges(data=True)): + if roles[u] is not None and roles[u] == roles[v]: + continue + if "tailoring" in (roles[u], roles[v]) or not any( + frozenset((bond.a1_symbol, bond.a2_symbol)) in backbone_pairs + for bond in data["bonds"] + ): + g.remove_edge(u, v) paths: list[list[MolNode]] = [] - for h in hs: + pending = AssemblyGraph(g, unassigned=assembly_graph.unassigned).connected_components() + while pending: + h = pending.pop() path = h.longest_path() paths.append(path) + # Graph node IDs need not be identical to MolNode.enc. + used = {id(node) for node in path} + h.g.remove_nodes_from([n for n, data in h.g.nodes(data=True) if id(data["molnode"]) in used]) + pending.extend(h.connected_components()) - return cls(assembly_graph=a, paths=paths) + paths.sort(key=lambda path: (-len(path), [_node_name(node) for node in path], [node.enc for node in path])) + return cls(assembly_graph=assembly_graph, paths=paths) + + def primary_sequence_parts(self) -> list[list[str]]: + """Named backbone/tailoring paths, longest first with lexical tie-breaks. + + Each identified assembly monomer occurs once, including repeated + identities. Unresolved and unassigned regions are omitted; assembly + coverage measures completeness. Sublists do not encode attachment + points, omitted crosslinks, or ring closures; retain ``assembly_graph`` + when those are needed. Untagged paths are not biological role labels. + """ + return sorted( + [[_node_name(node) for node in path] for path in self.paths], + key=lambda path: (-len(path), path), + ) def primary_sequence(self) -> list[str]: """ - The single primary sequence for this readout: every path in `self.paths` - -- including single-node ones, e.g. a lone tailoring event like - glycosylation or methylation that AssemblyGraph never connects to the - main chain (it only keeps C-C/C-N bonds as "connections", so e.g. a sugar - attached via a glycosidic C-O-C linkage always ends up disconnected) -- - merged into one sequence via `merge_named_paths` (longest first, ties - broken lexicographically, joined by TOKEN_LINK). Nothing found in the - assembly graph is dropped; a caller that wants just one biosynthetic - chain, without tailoring events mixed in, can split the result back - apart on TOKEN_LINK. - - An unidentified node is named "X", the convention used everywhere else in - RetroMol. + Compatibility flat view of ``primary_sequence_parts()``, joined by + TOKEN_LINK. Use the nested view to keep separate backbone, branch and + tailoring paths. Only identified monomers are included. :return: the single merged primary sequence """ - named_paths = [ - [node.identity.matched_rule.name if node.is_identified else "X" for node in path] - for path in self.paths - ] - return merge_named_paths(named_paths, key=lambda n: n, link_item=TOKEN_LINK) + return merge_named_paths(self.primary_sequence_parts(), key=lambda n: n, link_item=TOKEN_LINK) def to_dict(self) -> dict: """ @@ -184,3 +235,22 @@ def from_dict(cls, data: dict) -> "LinearReadout": assembly_graph = AssemblyGraph.from_dict(data["assembly_graph"]) paths = [[MolNode.from_dict(node_data) for node_data in path_data] for path_data in data["paths"]] return cls(assembly_graph=assembly_graph, paths=paths) + + +def _node_name(node: MolNode) -> str: + return node.identity.name + + +def assembly_to_primary_sequence(assembly_graph: AssemblyGraph) -> list[list[str]]: + """Return linear parts of one assembly, including backbone and tailoring. + + Uses matching-rule sequence roles with a C-C/C-N fallback and includes every + identified monomer once. Unresolved and unassigned regions are excluded; + use ``result.calculate_coverage(assembly_graph)`` for completeness. Parts are ordered + longest first, then lexically. Ordering is structural, not biosynthetic; + branch attachments and ring closures remain in the input assembly graph. + + For the corresponding MolNodes (including atom tags and identities), use + ``LinearReadout.from_assembly_graph(assembly_graph).paths``. + """ + return LinearReadout.from_assembly_graph(assembly_graph).primary_sequence_parts() diff --git a/src/retromol/model/rules.py b/src/retromol/model/rules.py index 810d912..fb20fce 100644 --- a/src/retromol/model/rules.py +++ b/src/retromol/model/rules.py @@ -9,7 +9,7 @@ from functools import cached_property from importlib.resources import files from pathlib import Path -from typing import Any +from typing import Any, Literal import yaml from rdkit.Chem.rdchem import Mol @@ -32,6 +32,8 @@ log = logging.getLogger(__name__) +SequenceRole = Literal["backbone", "tailoring"] + @dataclass(frozen=True) class ReactionRule: @@ -412,6 +414,8 @@ class MatchingRule: may not be the clearest depiction of the motif on its own. :cvar preserve_across_routes: Whether a terminal match also protects its atom region from subdivision in alternative derivations. Defaults to True. + :cvar sequence_role: Optional role in a linear assembly readout. None uses + the bond-element heuristic; this setting does not affect parsing. """ name: str @@ -422,6 +426,7 @@ class MatchingRule: stereochemistry: bool = False display_smiles: str | None = None preserve_across_routes: bool = True + sequence_role: SequenceRole | None = None mol: Mol = field(init=False, repr=False) @@ -433,6 +438,8 @@ def __post_init__(self) -> None: object.__setattr__(self, "mol", mol) if type(self.preserve_across_routes) is not bool: raise ValueError(f"{self.name}: preserve_across_routes must be a boolean") + if self.sequence_role not in (None, "backbone", "tailoring"): + raise ValueError(f"{self.name}: sequence_role must be 'backbone', 'tailoring', or null") @property def id(self) -> str: @@ -458,6 +465,7 @@ def to_dict(self) -> dict[str, Any]: "stereochemistry": self.stereochemistry, "display_smiles": self.display_smiles, "preserve_across_routes": self.preserve_across_routes, + "sequence_role": self.sequence_role, } @classmethod @@ -480,6 +488,7 @@ def from_dict(cls, data: dict[str, Any]) -> "MatchingRule": stereochemistry=data.get("stereochemistry", False), display_smiles=data.get("display_smiles"), preserve_across_routes=data.get("preserve_across_routes", legacy_preserve), + sequence_role=data.get("sequence_role"), ) return matching_rule diff --git a/tests/test_readout.py b/tests/test_readout.py new file mode 100644 index 0000000..e86b8a0 --- /dev/null +++ b/tests/test_readout.py @@ -0,0 +1,192 @@ +"""Linear assembly parts, role boundaries, and preservation of branched units.""" + +import json +import random +from dataclasses import replace + +import networkx as nx +import pytest + +from retromol.chem.mol import smiles_to_mol +from retromol.model.assembly_graph import AssemblyGraph, RootBondLink +from retromol.model.identity import MolIdentity +from retromol.model.reaction_graph import MolNode +from retromol.model.readout import LinearReadout, assembly_to_primary_sequence, split_named_paths +from retromol.model.result import Result +from retromol.model.rules import MatchingRule, RuleSet +from retromol.model.submission import Submission +from retromol.pipelines.parsing import run_retromol + + +def assembly(names, edges=(), roles=None): + """Synthetic connectivity fixture; graph IDs deliberately differ from enc.""" + g = nx.Graph() + for i, name in enumerate(names): + role = roles[i] if roles else None + identity = None if name is None else MolIdentity(MatchingRule( + name, 'C', {}, [], sequence_role=role, + )) + node = MolNode(f'mol-{i}', smiles_to_mol(f'[{i + 1}CH4]'), 'C', identity, name is not None) + g.add_node(i, molnode=node, tags={i + 1}, identity=identity) + for u, v, elements in edges: + a, b = elements.split('-') + bond = RootBondLink(u, v, u + 1, v + 1, a, b, 'SINGLE', 1.0) + g.add_edge(u, v, bonds=[bond], n_bonds=1) + return AssemblyGraph(g, validate_upon_initialization=True) + + +def test_unannotated_rules_keep_the_bond_fallback(): + a = assembly(['A', 'B', 'C', 'sugar'], [ + (0, 1, 'C-N'), (1, 2, 'C-C'), (1, 3, 'C-O'), + ]) + assert assembly_to_primary_sequence(a) == [['A', 'B', 'C'], ['sugar']] + + +def test_roles_separate_c_and_n_linked_tailoring_and_group_connected_sugars(): + a = assembly(['A', 'B', 'C', 'methylation', 'sugar1', 'sugar2'], [ + (0, 1, 'C-N'), (1, 2, 'C-C'), (1, 3, 'C-N'), + (2, 4, 'C-C'), (4, 5, 'C-O'), + ], roles=[None, 'backbone', None, 'tailoring', 'tailoring', 'tailoring']) + before = a.to_dict() + expected = [['A', 'B', 'C'], ['sugar1', 'sugar2'], ['methylation']] + readout = LinearReadout.from_assembly_graph(a) + assert readout.primary_sequence_parts() == expected + assert assembly_to_primary_sequence(a) == expected + assert split_named_paths(readout.primary_sequence(), key=lambda x: x) == expected + assert a.to_dict() == before + restored = AssemblyGraph.from_dict(json.loads(json.dumps(before))) + assert assembly_to_primary_sequence(restored) == expected + assert LinearReadout.from_dict(readout.to_dict()).primary_sequence_parts() == expected + + +@pytest.mark.parametrize('roles, expected', [ + (['backbone', 'backbone'], [['A', 'B']]), + (['backbone', None], [['A'], ['B']]), + (['backbone', 'tailoring'], [['A'], ['B']]), + (['tailoring', 'tailoring'], [['A', 'B']]), +]) +def test_explicit_equal_roles_retain_oxygen_links(roles, expected): + a = assembly(['A', 'B'], [(0, 1, 'C-O')], roles) + assert assembly_to_primary_sequence(a) == expected + + +def test_branches_are_retained_once_without_repeating_the_branch_point(): + a = assembly(['A', 'B', 'C', 'D'], [(0, i, 'C-C') for i in (1, 2, 3)]) + assert assembly_to_primary_sequence(a) == [['B', 'A', 'C'], ['D']] + + +def test_longest_path_compares_all_disconnected_components(): + a = assembly(['A', 'B', 'C', 'D', 'E'], [(0, 1, 'C-C'), (1, 2, 'C-C'), (3, 4, 'C-C')]) + assert [node.identity.name for node in a.longest_path()] == ['A', 'B', 'C'] + assert assembly_to_primary_sequence(a) == [['A', 'B', 'C'], ['D', 'E']] + + +def test_ring_has_a_stable_cut_and_no_repeated_start(): + a = assembly(['A', 'B', 'C', 'D'], [(i, (i + 1) % 4, 'C-N') for i in range(4)]) + assert assembly_to_primary_sequence(a) == [['A', 'B', 'C', 'D']] + + +def test_repeated_identities_survive_but_unknowns_and_unassigned_are_excluded(): + a = assembly(['glycine', 'glycine', None, 'sugar'], [(0, 1, 'C-N'), (1, 2, 'C-C')]) + # The aggregate unassigned placeholder is not a sequencable MolNode. + a.g.add_node(a.unassigned, molnode=None, tags={99}, identity=None) + before = a.to_dict() + readout = LinearReadout.from_assembly_graph(a) + assert assembly_to_primary_sequence(a) == [['glycine', 'glycine'], ['sugar']] + assert sum(map(len, readout.paths)) == 3 + assert 'X' not in readout.primary_sequence() + assert a.to_dict() == before + + +def test_unidentified_bridge_splits_named_paths(): + a = assembly(['A', None, 'B'], [(0, 1, 'C-C'), (1, 2, 'C-N')]) + assert assembly_to_primary_sequence(a) == [['A'], ['B']] + + +def test_direct_and_legacy_readouts_split_at_unidentified_nodes(): + a = assembly(['A', None, 'B'], [(0, 1, 'C-C'), (1, 2, 'C-N')]) + nodes = a.monomer_nodes() + direct = LinearReadout(a, [nodes]) + legacy = LinearReadout.from_dict({ + 'assembly_graph': a.to_dict(), 'paths': [[node.to_dict() for node in nodes]], + }) + for readout in (direct, legacy): + assert readout.primary_sequence_parts() == [['A'], ['B']] + assert all(node.is_identified for path in readout.paths for node in path) + + +def test_empty_assembly_and_unassigned_only_are_empty_sequences(): + a = assembly([]) + assert assembly_to_primary_sequence(a) == [] + a.g.add_node(a.unassigned, molnode=None, tags={1}, identity=None) + assert assembly_to_primary_sequence(a) == [] + + +def test_wholly_unidentified_assembly_is_an_empty_readout(): + a = assembly([None, None], [(0, 1, 'C-C')]) + readout = LinearReadout.from_assembly_graph(a) + assert readout.paths == [] + assert readout.primary_sequence_parts() == [] + assert readout.primary_sequence() == [] + + +@pytest.mark.parametrize('seed', range(10)) +def test_path_partition_preserves_all_nodes_and_ignores_insertion_order(seed): + topology = nx.gnp_random_graph(12, .25, seed=seed) + a = assembly([f'unit-{i}' for i in topology], [(u, v, 'C-C') for u, v in topology.edges]) + readout = LinearReadout.from_assembly_graph(a) + nodes = [node.enc for path in readout.paths for node in path] + assert len(nodes) == len(set(nodes)) == 12 + by_enc = {data['molnode'].enc: n for n, data in a.g.nodes(data=True)} + assert all(a.g.has_edge(by_enc[u.enc], by_enc[v.enc]) + for path in readout.paths for u, v in zip(path, path[1:])) + + rng = random.Random(seed) + nodes = list(a.g.nodes(data=True)) + edges = list(a.g.edges(data=True)) + rng.shuffle(nodes) + rng.shuffle(edges) + shuffled = nx.Graph() + shuffled.add_nodes_from(nodes) + shuffled.add_edges_from((v, u, data) for u, v, data in edges) + reordered = LinearReadout.from_assembly_graph(AssemblyGraph(shuffled)) + assert [[n.enc for n in path] for path in reordered.paths] == [[n.enc for n in path] for path in readout.paths] + + +@pytest.mark.parametrize('role', ['unknown', '', True, 1, []]) +def test_invalid_sequence_role_is_rejected(role): + with pytest.raises(ValueError, match='sequence_role'): + MatchingRule('unit', 'C', {}, [], sequence_role=role) + + +def test_rule_role_defaults_roundtrips_and_changes_provenance(tmp_path): + legacy = {'name': 'unit', 'smiles': 'C'} + rule = MatchingRule.from_dict(legacy) + assert rule.sequence_role is None + tagged = replace(rule, sequence_role='tailoring') + assert MatchingRule.from_dict(tagged.to_dict()).sequence_role == 'tailoring' + assert RuleSet(False, [], [rule]).matching_rules_hash != RuleSet(False, [], [tagged]).matching_rules_hash + matching = tmp_path / 'mxn.yml' + matching.write_text('- name: unit\n smiles: C\n sequence_role: tailoring\n') + reaction = tmp_path / 'rxn.yml' + reaction.write_text('[]\n') + loaded = RuleSet.load_from_files(reaction, matching) + assert loaded.matching_rules[0].sequence_role == 'tailoring' + + +def test_default_modification_rules_have_tailoring_roles(ruleset): + for name in ('glycosylation', 'methylation', 'oxidation', 'amination', 'phosphate', 'chlorination'): + matching = [rule for rule in ruleset.matching_rules if rule.name == name] + assert matching and all(rule.sequence_role == 'tailoring' for rule in matching) + # A modified monomer remains a whole unit, not a separate tailoring event. + assert all(rule.sequence_role is None for rule in ruleset.matching_rules if rule.name == 'N-methylalanine') + + +def test_sequences_from_sampled_assemblies_and_saved_result(ruleset): + result = run_retromol(Submission('CCCCCCCCCC(=O)NCC(=O)NC(C)C(=O)O'), ruleset) + assemblies = result.sample_assemblies(10, seed=42) + sequences = [assembly_to_primary_sequence(a) for a in assemblies] + assert sorted(len(parts[0]) for parts in sequences) == [3, 4, 5, 6, 7] + assert all(len(parts) == 1 for parts in sequences) + restored = Result.from_dict(json.loads(json.dumps(result.to_dict()))) + assert [assembly_to_primary_sequence(a) for a in restored.sample_assemblies(10, seed=42)] == sequences diff --git a/tests/test_result.py b/tests/test_result.py index bd2b4db..f7dd124 100644 --- a/tests/test_result.py +++ b/tests/test_result.py @@ -43,6 +43,19 @@ def test_coverage_ignores_identified_intermediates_and_unknown_leaves() -> None: assert Result.from_dict(result.to_dict()).calculate_coverage() == pytest.approx(0.5) +@pytest.mark.parametrize('known, expected_coverage', [(False, 0.5), (True, 1.0)]) +def test_identified_only_readout_leaves_assembly_coverage_unchanged(known, expected_coverage): + result = make_result('CCOC', [('[1CH3][2CH3]', True), ('[3OH][4CH3]', known)]) + assembly = result.assembly_graph + before = assembly.to_dict() + readout = result.linear_readout + assert sum(map(len, readout.paths)) == 1 + int(known) + assert all(node.is_identified for path in readout.paths for node in path) + assert 'X' not in readout.primary_sequence() + assert assembly.to_dict() == before + assert result.calculate_coverage(assembly) == pytest.approx(expected_coverage) + + def test_coverage_counts_assembly_monomers_without_linear_paths(monkeypatch) -> None: result = make_result("CCOC", [("[1CH3][2CH3]", True), ("[3OH][4CH3]", True)]) From 0927d3e80c6ea3e56dd439df78694cca40a7078d Mon Sep 17 00:00:00 2001 From: David Meijer Date: Mon, 19 Oct 2026 12:59:36 -0400 Subject: [PATCH 2/7] ENH: write out primary sequences with single compound parsing --- src/retromol/data/mxn.yml | 88 +++++++++++++++++++++++++++++++++++++++ src/retromol_cli/cli.py | 16 ++++++- tests/test_cli.py | 37 +++++++++++++++- tests/test_json_io.py | 1 + 4 files changed, 139 insertions(+), 3 deletions(-) diff --git a/src/retromol/data/mxn.yml b/src/retromol/data/mxn.yml index ec51757..4f27b93 100644 --- a/src/retromol/data/mxn.yml +++ b/src/retromol/data/mxn.yml @@ -985,24 +985,28 @@ display_smiles: "O=C(S[2*])C(=O)C[1*]" pseudonyms: ["PK_D", "PK"] preserve_across_routes: false + sequence_role: backbone - name: D11 smiles: "O=C(O)C(O)=CSO" display_smiles: "O=C(S[2*])C(O)=C[1*]" pseudonyms: ["PK_D", "PK"] preserve_across_routes: false + sequence_role: backbone - name: D14 smiles: "CC(O)C(CSO)C(=O)O" display_smiles: "CC(O)C(C[1*])C(=O)S[2*]" pseudonyms: ["PK_D", "PK"] preserve_across_routes: false + sequence_role: backbone - name: D15 smiles: "C=C(C(O)=O)CSO" display_smiles: "C=C(C(S[2*])=O)C[1*]" pseudonyms: ["PK_D", "PK"] preserve_across_routes: false + sequence_role: backbone - name: D16^R smiles: "OSC[C@@H](C(O)=O)CC=O" @@ -1010,6 +1014,7 @@ stereochemistry: true pseudonyms: ["D16", "PK_D", "PK"] preserve_across_routes: false + sequence_role: backbone - name: D16^S smiles: "OSC[C@H](C(O)=O)CC=O" @@ -1017,12 +1022,14 @@ stereochemistry: true pseudonyms: ["D16", "PK_D", "PK"] preserve_across_routes: false + sequence_role: backbone - name: D16 smiles: "OSCC(CC=O)C(=O)O" display_smiles: "[1*]CC(CC=O)C(=O)S[2*]" pseudonyms: ["PK_D", "PK"] preserve_across_routes: false + sequence_role: backbone - name: D^R17 smiles: "O=C(O)C([C@H](SO)C)=O" @@ -1030,6 +1037,7 @@ stereochemistry: true pseudonyms: ["D17", "PK_D", "PK"] preserve_across_routes: false + sequence_role: backbone - name: D^S17 smiles: "O=C(O)C([C@@H](SO)C)=O" @@ -1037,66 +1045,77 @@ stereochemistry: true pseudonyms: ["D17", "PK_D", "PK"] preserve_across_routes: false + sequence_role: backbone - name: D17 smiles: "O=C(C(C(C)SO)=O)O" display_smiles: "O=C(C(C(C)[1*])=O)S[2*]" pseudonyms: ["PK_D", "PK"] preserve_across_routes: false + sequence_role: backbone - name: D17 smiles: "O=C(C(O)=C(C)SO)O" display_smiles: "O=C(C(C(C)[1*])=O)S[2*]" pseudonyms: ["PK_D", "PK"] preserve_across_routes: false + sequence_role: backbone - name: A smiles: "OSC(N)CC(=O)O" display_smiles: "[1*]C(N)CC(=O)S[2*]" pseudonyms: ["PK"] preserve_across_routes: false + sequence_role: backbone - name: A smiles: "OSC(N)C(C)C(=O)O" display_smiles: "[1*]C(N)C(C)C(=O)S[2*]" pseudonyms: ["PK"] preserve_across_routes: false + sequence_role: backbone - name: A smiles: "OSC(N)C(C)(C)C(=O)O" display_smiles: "[1*]C(N)C(C)(C)C(=O)S[2*]" pseudonyms: ["PK"] preserve_across_routes: false + sequence_role: backbone - name: A smiles: "OSC(N)C(CC)C(=O)O" display_smiles: "[1*]C(N)C(CC)C(=O)S[2*]" pseudonyms: ["PK"] preserve_across_routes: false + sequence_role: backbone - name: A smiles: "OSC(N)C(C)(O)C(=O)O" display_smiles: "[1*]C(N)C(C)(O)C(=O)S[2*]" pseudonyms: ["PK"] preserve_across_routes: false + sequence_role: backbone - name: A smiles: "NC(C(O)=O)CSO" display_smiles: "NC(C(S[2*])=O)C[1*]" pseudonyms: ["PK"] preserve_across_routes: false + sequence_role: backbone - name: A smiles: "NC(C(C(O)=O)O)SO" display_smiles: "NC(C(C(S[2*])=O)O)[1*]" pseudonyms: ["PK"] preserve_across_routes: false + sequence_role: backbone - name: A smiles: "O=C(C(C(C(O)=O)SO)O)O" display_smiles: "O=C(C(C(C(O)=O)[1*])O)S[2*]" pseudonyms: ["PK"] preserve_across_routes: false + sequence_role: backbone - name: methylation sequence_role: tailoring @@ -1151,30 +1170,39 @@ - name: methanol smiles: "CO" + sequence_role: tailoring - name: ethanol smiles: "CCO" + sequence_role: tailoring - name: propanol smiles: "CCCO" + sequence_role: tailoring - name: formaldehyde smiles: "C=O" + sequence_role: tailoring - name: carbamic acid smiles: "NC(=O)O" + sequence_role: tailoring - name: carbonic acid smiles: "OC(=O)O" + sequence_role: tailoring - name: acetic acid smiles: "CC(=O)O" + sequence_role: tailoring - name: glyceric acid smiles: "OC(CO)C(O)=O" + sequence_role: tailoring - name: propanoic acid smiles: "CCC(O)=O" + sequence_role: tailoring - name: glycosylation sequence_role: tailoring @@ -1304,210 +1332,270 @@ # Tautomers - name: arginine smiles: "NC(N)=NCCCC(N)C(=O)O" + sequence_role: backbone - name: arginine smiles: "N=C(N)NCCCC(N)C(=O)O" + sequence_role: backbone - name: arginine^L smiles: "NC(N)=NCC[C@H](N)C(=O)O" stereochemistry: true pseudonyms: ["arginine"] + sequence_role: backbone - name: arginine^D smiles: "NC(N)=NCC[C@@H](N)C(=O)O" stereochemistry: true pseudonyms: ["arginine"] + sequence_role: backbone - name: N-methylarginine smiles: "NC(N)=NCCCC(NC)C(=O)O" + sequence_role: backbone - name: N-methylarginine^L smiles: "NC(N)=NCC[C@H](NC)C(=O)O" stereochemistry: true pseudonyms: ["N-methylarginine"] + sequence_role: backbone - name: N-methylarginine^D smiles: "NC(N)=NCC[C@@H](NC)C(=O)O" stereochemistry: true pseudonyms: ["N-methylarginine"] + sequence_role: backbone - name: histidine smiles: "NC(Cc1cnc[nH]1)C(=O)O" + sequence_role: backbone - name: histidine^L smiles: "N[C@@H](Cc1cnc[nH]1)C(=O)O" stereochemistry: true pseudonyms: ["histidine"] + sequence_role: backbone - name: histidine^D smiles: "N[C@H](Cc1cnc[nH]1)C(=O)O" stereochemistry: true pseudonyms: ["histidine"] + sequence_role: backbone - name: N-methylhistidine smiles: "CNC(Cc1cnc[nH]1)C(=O)O" + sequence_role: backbone - name: N-methylhistidine^L smiles: "CN[C@@H](Cc1cnc[nH]1)C(=O)O" stereochemistry: true pseudonyms: ["N-methylhistidine"] + sequence_role: backbone - name: N-methylhistidine^D smiles: "CN[C@H](Cc1cnc[nH]1)C(=O)O" stereochemistry: true pseudonyms: ["N-methylhistidine"] + sequence_role: backbone - name: 3-hydroxy histdine smiles: "NC(C(c1[nH]cnc1)O)C(O)=O" + sequence_role: backbone - name: lysine smiles: "NCCCCC(N)C(=O)O" + sequence_role: backbone - name: lysine^L smiles: "NCCCC[C@H](N)C(=O)O" stereochemistry: true pseudonyms: ["lysine"] + sequence_role: backbone - name: lysine^D smiles: "NCCCC[C@@H](N)C(=O)O" stereochemistry: true pseudonyms: ["lysine"] + sequence_role: backbone - name: N-methyllysine smiles: "NCCCCC(NC)C(=O)O" + sequence_role: backbone - name: N-methyllysine^L smiles: "NCCCC[C@H](NC)C(=O)O" stereochemistry: true pseudonyms: ["N-methyllysine"] + sequence_role: backbone - name: N-methyllysine^D smiles: "NCCCC[C@@H](NC)C(=O)O" stereochemistry: true pseudonyms: ["N-methyllysine"] + sequence_role: backbone - name: aspartic acid smiles: "NC(CC(=O)O)C(=O)O" + sequence_role: backbone - name: aspartic acid^L smiles: "N[C@@H](CC(=O)O)C(=O)O" stereochemistry: true pseudonyms: ["aspartic acid"] + sequence_role: backbone - name: aspartic acid^D smiles: "N[C@H](CC(=O)O)C(=O)O" stereochemistry: true pseudonyms: ["aspartic acid"] + sequence_role: backbone - name: N-methylaspartic acid smiles: "CNC(CC(=O)O)C(=O)O" + sequence_role: backbone - name: N-methylaspartic acid^L smiles: "CN[C@@H](CC(=O)O)C(=O)O" stereochemistry: true pseudonyms: ["N-methylaspartic acid"] + sequence_role: backbone - name: N-methylaspartic acid^D smiles: "CN[C@H](CC(=O)O)C(=O)O" stereochemistry: true pseudonyms: ["N-methylaspartic acid"] + sequence_role: backbone - name: glutamic acid smiles: "NC(CCC(=O)O)C(=O)O" + sequence_role: backbone - name: glutamic acid^L smiles: "N[C@@H](CCC(=O)O)C(=O)O" stereochemistry: true pseudonyms: ["glutamic acid"] + sequence_role: backbone - name: glutamic acid^D smiles: "N[C@H](CCC(=O)O)C(=O)O" stereochemistry: true pseudonyms: ["glutamic acid"] + sequence_role: backbone - name: N-methylglutamic acid smiles: "CNC(CCC(=O)O)C(=O)O" + sequence_role: backbone - name: N-methylglutamic acid^L smiles: "CN[C@@H](CCC(=O)O)C(=O)O" stereochemistry: true pseudonyms: ["N-methylglutamic acid"] + sequence_role: backbone - name: N-methylglutamic acid^D smiles: "CN[C@H](CCC(=O)O)C(=O)O" stereochemistry: true pseudonyms: ["N-methylglutamic acid"] + sequence_role: backbone - name: serine smiles: "NC(CO)C(=O)O" + sequence_role: backbone - name: serine^L smiles: "N[C@@H](CO)C(=O)O" stereochemistry: true pseudonyms: ["serine"] + sequence_role: backbone - name: serine^D smiles: "N[C@H](CO)C(=O)O" stereochemistry: true pseudonyms: ["serine"] + sequence_role: backbone - name: N-methylserine smiles: "CNC(CO)C(=O)O" + sequence_role: backbone - name: N-methylserine^L smiles: "CN[C@@H](CO)C(=O)O" stereochemistry: true pseudonyms: ["N-methylserine"] + sequence_role: backbone - name: N-methylserine^D smiles: "CN[C@H](CO)C(=O)O" stereochemistry: true pseudonyms: ["N-methylserine"] + sequence_role: backbone - name: threonine smiles: "CC(O)C(N)C(=O)O" + sequence_role: backbone - name: N-methylthreonine smiles: "CNC(C(O)C)C(=O)O" terminal: true + sequence_role: backbone - name: asparagine smiles: "NC(=O)CC(N)C(=O)O" + sequence_role: backbone - name: asparagine^L smiles: "NC(=O)C[C@H](N)C(=O)O" stereochemistry: true pseudonyms: ["asparagine"] + sequence_role: backbone - name: asparagine^D smiles: "NC(=O)C[C@@H](N)C(=O)O" stereochemistry: true pseudonyms: ["asparagine"] + sequence_role: backbone - name: N-methylasparagine smiles: "NC(=O)CC(NC)C(=O)O" + sequence_role: backbone - name: N-methylasparagine^L smiles: "NC(=O)C[C@H](NC)C(=O)O" stereochemistry: true pseudonyms: ["N-methylasparagine"] + sequence_role: backbone - name: N-methylasparagine^D smiles: "NC(=O)C[C@@H](NC)C(=O)O" stereochemistry: true pseudonyms: ["N-methylasparagine"] + sequence_role: backbone - name: glutamine smiles: "NC(=O)CCC(N)C(=O)O" + sequence_role: backbone - name: glutamine^L smiles: "NC(=O)CC[C@H](N)C(=O)O" stereochemistry: true pseudonyms: ["glutamine"] + sequence_role: backbone - name: glutamine^D smiles: "NC(=O)CC[C@@H](N)C(=O)O" stereochemistry: true pseudonyms: ["glutamine"] + sequence_role: backbone - name: N-methylglutamine smiles: "NC(=O)CCC(NC)C(=O)O" + sequence_role: backbone - name: N-methylglutamine^L smiles: "NC(=O)CC[C@H](NC)C(=O)O" stereochemistry: true pseudonyms: ["N-methylglutamine"] + sequence_role: backbone - name: N-methylglutamine^D smiles: "NC(=O)CC[C@@H](NC)C(=O)O" stereochemistry: true pseudonyms: ["N-methylglutamine"] + sequence_role: backbone - name: glycine smiles: "NCC(=O)O" + sequence_role: backbone - name: sarcosine smiles: "CNCC(=O)O" pseudonyms: ["N-methylglycine"] terminal: true + sequence_role: backbone - name: proline smiles: "O=C(O)C1CCCN1" + sequence_role: backbone - name: proline^L smiles: "O=C(O)[C@@H]1CCCN1" stereochemistry: true pseudonyms: ["proline"] + sequence_role: backbone - name: proline^D smiles: "O=C(O)[C@H]1CCCN1" stereochemistry: true pseudonyms: ["proline"] + sequence_role: backbone - name: N-methylproline smiles: "O=C(O)C1CCCN1C" + sequence_role: backbone - name: N-methylproline^L smiles: "O=C(O)[C@@H]1CCCN1C" stereochemistry: true pseudonyms: ["N-methylproline"] + sequence_role: backbone - name: N-methylproline^D smiles: "O=C(O)[C@H]1CCCN1C" stereochemistry: true pseudonyms: ["N-methylproline"] + sequence_role: backbone - name: cysteine smiles: "NC(CS)C(=O)O" diff --git a/src/retromol_cli/cli.py b/src/retromol_cli/cli.py index 32df9dd..881c0ad 100644 --- a/src/retromol_cli/cli.py +++ b/src/retromol_cli/cli.py @@ -16,6 +16,7 @@ from retromol.utils.logging import setup_logging, add_file_handler from retromol.model.rules import RuleSet from retromol.model.result import Result +from retromol.model.readout import assembly_to_primary_sequence from retromol.model.assembly_sampling import AssemblyConstraintError, AssemblyLimitError from retromol.model.submission import Submission from retromol.pipelines.parsing import run_retromol_with_timeout @@ -256,10 +257,23 @@ def main() -> None: os.remove(entry.path) drawing_layout = MoleculeLayout.from_mol(result2.root.mol) if assemblies else None + assembly_sequences = [] for index, assembly in enumerate(assemblies, start=1): filename = "assembly_graph.png" if args.max_assembly_graphs == 1 else f"assembly_graph_{index:03d}.png" assembly.draw(show_unassigned=True, savepath=os.path.join(args.outdir, filename), layout=drawing_layout) - log.info("%s coverage: %.2f%%", filename, 100 * result2.calculate_coverage(assembly)) + coverage = result2.calculate_coverage(assembly) + assembly_sequences.append({ + "assembly_graph": filename, + "coverage": coverage, + "primary_sequence": assembly_to_primary_sequence(assembly), + }) + log.info("%s coverage: %.2f%%", filename, 100 * coverage) + + sequences_path = os.path.join(args.outdir, "assembly_sequences.json") + with open(sequences_path, "w", encoding="utf-8") as f: + json.dump(assembly_sequences, f, ensure_ascii=False, indent=2) + f.write("\n") + log.info("Saved %d assembly sequences to %s", len(assembly_sequences), sequences_path) # Visualize reaction graph visualize_reaction_graph( diff --git a/tests/test_cli.py b/tests/test_cli.py index 64507a6..d66baa5 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1,4 +1,4 @@ -"""Single-mode drawing limits use distinct, reproducible assembly projections.""" +"""Single-mode drawings and sequence exports use the same assembly projections.""" import json from pathlib import Path @@ -7,6 +7,7 @@ from retromol.model.assembly_graph import AssemblyGraph from retromol.model.assembly_sampling import AssemblyLimitError, AssemblySpace +from retromol.model.readout import assembly_to_primary_sequence from retromol.model.result import Result from retromol.visualization.assembly_layout import MoleculeLayout from retromol_cli import cli as cli_module @@ -48,6 +49,8 @@ def run(*options, smiles=SMILES): assert 'linear_readout' not in payload assert 'assembly_graph' not in payload assert len(visualized) == 1 + sequences = json.loads((output / 'assembly_sequences.json').read_text()) + assert [entry['assembly_graph'] for entry in sequences] == [name for name, _ in drawn] return Result.from_dict(payload), list(drawn) return run @@ -58,6 +61,31 @@ def test_single_default_keeps_default_assembly_filename_and_selection(single_run assert drawn == [('assembly_graph.png', tuple(sorted(result.assembly_graph.monomer_ids())))] +@pytest.mark.parametrize('maximum', [1, 3]) +def test_single_exports_sequence_and_coverage_for_each_drawn_assembly(single_run, tmp_path, maximum): + result, drawn = single_run('--max-assembly-graphs', str(maximum)) + entries = json.loads((tmp_path / 'output' / 'assembly_sequences.json').read_text()) + space = result.assembly_space() + for entry, (filename, nodes) in zip(entries, drawn): + assembly = space.build(frozenset(nodes)) + assert entry == { + 'assembly_graph': filename, + 'coverage': result.calculate_coverage(assembly), + 'primary_sequence': assembly_to_primary_sequence(assembly), + } + # These sampled resolutions have different monomer identities, so exporting + # the default readout repeatedly cannot satisfy the per-drawing contract. + assert len({json.dumps(entry['primary_sequence']) for entry in entries}) == maximum + + +@pytest.mark.parametrize('maximum', [0, 1]) +def test_single_rerun_replaces_sequence_export(single_run, tmp_path, maximum): + single_run('--max-assembly-graphs', '3') + single_run('--max-assembly-graphs', str(maximum)) + entries = json.loads((tmp_path / 'output' / 'assembly_sequences.json').read_text()) + assert len(entries) == maximum + + @pytest.mark.parametrize('maximum,expected_count', [(0, 0), (1, 1), (3, 3), (10, 5)]) def test_single_respects_drawing_limit_and_available_assemblies(single_run, maximum, expected_count): result, drawn = single_run('--max-assembly-graphs', str(maximum)) @@ -139,7 +167,7 @@ def test_daptomycin_samples_only_full_coverage_and_keeps_all_resolutions(single_ assert any(n.identity.name == 'B12' for n in result.reaction_graph.identified_nodes.values()) -def test_single_default_also_uses_maximum_if_default_projection_is_lower(single_run, monkeypatch): +def test_single_default_also_uses_maximum_if_default_projection_is_lower(single_run, monkeypatch, tmp_path): from .test_assembly_sampling import partially_identified_result parsed = partially_identified_result() @@ -150,6 +178,11 @@ def test_single_default_also_uses_maximum_if_default_projection_is_lower(single_ assert result.calculate_coverage(result.assembly_space().build(frozenset(drawn[0][1]))) == 1 _, lower = single_run('--min-coverage', '.75') assert lower == [('assembly_graph.png', tuple(sorted(result.assembly_graph.monomer_ids())))] + entries = json.loads((tmp_path / 'output' / 'assembly_sequences.json').read_text()) + assert entries[0]['coverage'] == .75 + sequence = entries[0]['primary_sequence'] + assert sum(map(len, sequence)) == 3 + assert all(name not in ('X', 'unassigned') for part in sequence for name in part) _, all_views = single_run('--max-assembly-graphs', '10', '--min-coverage', '.75') assert len(all_views) == 4 diff --git a/tests/test_json_io.py b/tests/test_json_io.py index 59a3387..469b9f1 100644 --- a/tests/test_json_io.py +++ b/tests/test_json_io.py @@ -162,3 +162,4 @@ def test_single_can_save_compressed_result(tmp_path, monkeypatch): with gzip.open(tmp_path / 'result.json.gz', 'rt') as handle: result = Result.from_dict(json.load(handle)) assert result.calculate_coverage() == .75 + assert json.loads((tmp_path / 'assembly_sequences.json').read_text()) == [] From 5b3f90d683b24e94713b865a4b7ce72d664cc04a Mon Sep 17 00:00:00 2001 From: David Meijer Date: Mon, 19 Oct 2026 23:47:39 -0400 Subject: [PATCH 3/7] UPD: distinguish between identical moieties being starter or tailoring --- database/scripts/common.py | 2 +- .../components/workspace/WorkspaceRules.tsx | 36 ++- gui/src/client/src/features/rules/types.ts | 9 + gui/src/server/routes/discovery.py | 4 +- gui/src/server/routes/rules.py | 10 + src/retromol/chem/matching.py | 5 +- src/retromol/data/README.md | 34 ++- src/retromol/data/mxn.yml | 10 +- src/retromol/model/rules.py | 131 +++++++++- src/retromol_antismash/modules.py | 8 +- src/retromol_synthesis/reconstruction.py | 2 +- .../data/integration_retromol_assemblies.yml | 180 ++++++------- ...on_retromol_stereochemistry_assemblies.yml | 2 +- tests/test_assembly_sampling.py | 2 +- tests/test_cli.py | 2 +- tests/test_matching.py | 238 ++++++++++++++++++ 16 files changed, 563 insertions(+), 112 deletions(-) create mode 100644 tests/test_matching.py diff --git a/database/scripts/common.py b/database/scripts/common.py index 0bc9e27..b704ebe 100644 --- a/database/scripts/common.py +++ b/database/scripts/common.py @@ -58,7 +58,7 @@ def build_fingerprint_context(ruleset: RuleSet) -> tuple[dict[str, MatchingRule] vocab_tokens: set[str] = set() name_to_rule: dict[str, MatchingRule] = {} - for rule in ruleset.matching_rules: + for rule in ruleset.matching_rule_variants: vocab_tokens.add(rule.name) vocab_tokens.update(rule.pseudonyms) name_to_rule.setdefault(rule.name, rule) diff --git a/gui/src/client/src/components/workspace/WorkspaceRules.tsx b/gui/src/client/src/components/workspace/WorkspaceRules.tsx index 9c32b2f..25bbe0c 100644 --- a/gui/src/client/src/components/workspace/WorkspaceRules.tsx +++ b/gui/src/client/src/components/workspace/WorkspaceRules.tsx @@ -76,6 +76,7 @@ function MatchingRuleRow({ rule }: { rule: MatchingRule }) { + {rule.cases.length > 0 && } {rule.terminal && } {rule.stereochemistry && } {rule.pseudonyms.length > 0 && ( @@ -146,6 +147,35 @@ function MatchingRuleRow({ rule }: { rule: MatchingRule }) { )} + + Default sequence role: {rule.sequenceRole ?? "inferred from bonds"} + + {rule.requiresSmarts && ( + + Required SMARTS + + {rule.requiresSmarts} + + + )} + {rule.cases.length > 0 && ( + + + Cases after structural matching (first match wins; otherwise use defaults) + + {rule.cases.map((ruleCase, i) => ( + + + {i + 1}. + {" · "}{ruleCase.sequenceRole ?? rule.sequenceRole ?? "inferred from bonds"} + + + {ruleCase.requiresSmarts} + + + ))} + + )} {rule.terminal && ( {rule.preserveAcrossRoutes @@ -242,7 +272,11 @@ export const WorkspaceRules: React.FC = () => { const filteredMatchingRules = React.useMemo(() => { const rules = ruleSetQuery.data?.matchingRules ?? []; if (!search.trim()) return rules; - return rules.filter((r) => matchesQuery([r.name, r.smiles, r.displaySmiles ?? "", ...r.pseudonyms], search)); + return rules.filter((r) => matchesQuery([ + r.name, r.smiles, r.displaySmiles ?? "", ...r.pseudonyms, + r.sequenceRole ?? "", r.requiresSmarts ?? "", + ...r.cases.flatMap((c) => [c.name ?? "", c.requiresSmarts, c.sequenceRole ?? ""]), + ], search)); }, [ruleSetQuery.data, search]); const filteredReactionRules = React.useMemo(() => { diff --git a/gui/src/client/src/features/rules/types.ts b/gui/src/client/src/features/rules/types.ts index d4222d1..62c6250 100644 --- a/gui/src/client/src/features/rules/types.ts +++ b/gui/src/client/src/features/rules/types.ts @@ -1,5 +1,7 @@ import { z } from "zod"; +const SequenceRoleSchema = z.enum(["backbone", "tailoring"]).nullable(); + export const MatchingRuleSchema = z.object({ id: z.string(), name: z.string(), @@ -11,6 +13,13 @@ export const MatchingRuleSchema = z.object({ terminal: z.boolean(), stereochemistry: z.boolean(), preserveAcrossRoutes: z.boolean(), + sequenceRole: SequenceRoleSchema.default(null), + requiresSmarts: z.string().nullable().default(null), + cases: z.array(z.object({ + requiresSmarts: z.string(), + name: z.string().nullable(), + sequenceRole: SequenceRoleSchema, + })).default([]), props: z.record(z.string(), z.any()), }); export type MatchingRule = z.output; diff --git a/gui/src/server/routes/discovery.py b/gui/src/server/routes/discovery.py index dab602d..f32ade8 100644 --- a/gui/src/server/routes/discovery.py +++ b/gui/src/server/routes/discovery.py @@ -127,7 +127,7 @@ def _build_context() -> DiscoveryContext: name_to_rule: dict[str, MatchingRule] = {} records: list[tuple[str, str]] = [] - for rule in rules.matching_rules: + for rule in rules.matching_rule_variants: vocab_tokens.add(rule.name) vocab_tokens.update(rule.pseudonyms) name_to_rule.setdefault(rule.name, rule) @@ -540,7 +540,7 @@ def motif_structures() -> tuple[Response, int]: structures = {name: (rule.display_smiles or rule.smiles) for name, rule in ctx.name_to_rule.items()} smiles_by_name: dict[str, set[str]] = {} - for rule in ctx.ruleset.matching_rules: + for rule in ctx.ruleset.matching_rule_variants: smiles_by_name.setdefault(rule.name, set()).add(rule.display_smiles or rule.smiles) ambiguous_names = sorted(name for name, smiles in smiles_by_name.items() if len(smiles) > 1) diff --git a/gui/src/server/routes/rules.py b/gui/src/server/routes/rules.py index 3399c8b..a833703 100644 --- a/gui/src/server/routes/rules.py +++ b/gui/src/server/routes/rules.py @@ -119,6 +119,16 @@ def rule_set() -> tuple[Response, int]: "terminal": r.terminal, "stereochemistry": r.stereochemistry, "preserveAcrossRoutes": r.preserve_across_routes, + "sequenceRole": r.sequence_role, + "requiresSmarts": r.requires_smarts, + "cases": [ + { + "requiresSmarts": case.requires_smarts, + "name": case.name, + "sequenceRole": case.sequence_role, + } + for case in r.cases + ], "props": r.props, } for r in rules.matching_rules diff --git a/src/retromol/chem/matching.py b/src/retromol/chem/matching.py index ed95a6c..360b551 100644 --- a/src/retromol/chem/matching.py +++ b/src/retromol/chem/matching.py @@ -21,7 +21,8 @@ def match_mol( """ for rl in rules: if not rl.stereochemistry or (rl.stereochemistry and match_stereochemistry): - if rl.is_match(mol, match_stereochemistry): - return MolIdentity(matched_rule=rl) + resolved = rl.match(mol, match_stereochemistry) + if resolved is not None: + return MolIdentity(matched_rule=resolved) return None diff --git a/src/retromol/data/README.md b/src/retromol/data/README.md index a42dc32..5c0669e 100644 --- a/src/retromol/data/README.md +++ b/src/retromol/data/README.md @@ -79,6 +79,8 @@ This file is also a YAML list. | --- | --- | --- | | `name` | String; required | Identity assigned to the matched fragment and used in assembly graphs. Multiple structural entries can share a name, for example keto/enol representations of one unit. | | `smiles` | String; required | The whole fragment structure to recognize, including any artificial caps expected after disconnection. This field takes SMILES, not a SMARTS query. | +| `requires_smarts` | SMARTS string or `null`; `null` | Additional substructure condition on the tagged fragment. Both this query and the whole-fragment `smiles` match must succeed. Compiled and validated when loading the rule. | +| `cases` | List; `[]` | Conditional `name` and/or `sequence_role` overrides after the structural match. Each case requires `requires_smarts`; the first matching case wins, otherwise the rule's defaults apply. | | `pseudonyms` | List of strings; `[]` | Alternative names or broader groups, such as `PK_A` and `PK`, used by downstream representations and BGC matching. They do not change the structural match. | | `terminal` | Boolean; `true` | Stop expanding a fragment identified by this rule. With `false`, keep its identity but also allow further reactions and finer assemblies. | | `stereochemistry` | Boolean; `false` | Marks a stereo-specific rule. These rules are prioritized when global stereochemical matching is enabled and skipped when it is disabled. | @@ -101,6 +103,24 @@ For example: note: Formal capped beta-keto PK unit. ``` +### Conditional names and sequence roles + +Define the structure once, then use `cases` to assign a name and role based on +the matched fragment's existing atom tags. The default PK cleavage rules add a complete +carboxyl cap to the remaining chain. An acetate starter therefore has an +artificial carboxyl carbon and oxygens (tag zero), whereas acetate cleaved from +an acetyl substituent retains its original carbonyl atoms (positive tags): + +```yaml +- name: acetic acid + smiles: 'CC(=O)O' + sequence_role: tailoring + cases: + - requires_smarts: '[0C](=[0O])[0OH]' + name: acetic acid starter + sequence_role: backbone +``` + ### Backbone and tailoring roles Set `sequence_role` on a monomer matching rule when its role in the sequence view @@ -122,8 +142,9 @@ policy, not evidence that a reaction happened after backbone synthesis. Connections between two explicit `backbone` units are also retained regardless of bond elements. Where either non-tailoring endpoint has no role, the readout falls back to C–C/C–N connections. A `tailoring` endpoint always separates from an untagged -or `backbone` endpoint. The defaults mark the existing modification identities as -tailoring and leave other units untagged; no role is inferred from size or degree. +or `backbone` endpoint. The defaults explicitly mark PK units and conditional +acid starters as backbone and modification identities as tailoring. Other units +can remain untagged; no role is inferred from size or degree. Role choices can depend on the intended compound class, so use custom matching rules where a motif plays a different role. @@ -181,7 +202,14 @@ Use YAML booleans `true` and `false`, not quoted strings. Quote SMILES/SMARTS; s Older YAML files and saved results with `props.preserve_across_routes` or `props.product_max_matches` are still accepted through `from_dict`. Loading moves these values out of metadata. If both locations occur, the explicit top-level value wins, including `true` or an empty `{}`. Serialization always writes the new top-level fields. When constructing Python rule objects directly, pass these settings as named constructor arguments. -Individual rule IDs are hashes of their SMARTS or SMILES strings. Ruleset hashes include the ordered serialized definitions, including behavior settings, names, and metadata. Moving to the new serialization therefore changes ruleset hashes even when the chemistry and effective settings are unchanged; old saved provenance remains historical. Treat loaded rules and their nested mappings as immutable. +Reaction rule IDs hash their SMARTS. Matching rule IDs hash their SMILES and, +when present, the top-level `requires_smarts`. Cases choose output identities +without changing this structural ID, so variants of one rule share an ID. +Matching rules without a top-level condition retain their SMILES-only IDs. +Ruleset hashes include the ordered serialized definitions, including behavior +settings, names, cases, and metadata. Adding serialized fields therefore changes +ruleset hashes even when effective behavior is unchanged; old saved provenance +remains historical. Treat loaded rules and their nested mappings as immutable. ## Prediction mapping: `pmp.yml` diff --git a/src/retromol/data/mxn.yml b/src/retromol/data/mxn.yml index 4f27b93..a85dbb7 100644 --- a/src/retromol/data/mxn.yml +++ b/src/retromol/data/mxn.yml @@ -1195,6 +1195,10 @@ - name: acetic acid smiles: "CC(=O)O" sequence_role: tailoring + cases: + - requires_smarts: "[0C](=[0O])[0OH]" + name: acetic acid starter + sequence_role: backbone - name: glyceric acid smiles: "OC(CO)C(O)=O" @@ -1203,6 +1207,10 @@ - name: propanoic acid smiles: "CCC(O)=O" sequence_role: tailoring + cases: + - requires_smarts: "[0C](=[0O])[0OH]" + name: propanoic acid starter + sequence_role: backbone - name: glycosylation sequence_role: tailoring @@ -4185,4 +4193,4 @@ note: Enol tautomer of the formal alpha-carboxylated keto PK unit. pseudonyms: - PK_A - - PK \ No newline at end of file + - PK diff --git a/src/retromol/model/rules.py b/src/retromol/model/rules.py index fb20fce..defd259 100644 --- a/src/retromol/model/rules.py +++ b/src/retromol/model/rules.py @@ -5,7 +5,7 @@ import hashlib import json from collections import Counter -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from functools import cached_property from importlib.resources import files from pathlib import Path @@ -397,6 +397,52 @@ def apply_uncontested( return products, applied_reactions, failed_combos +@dataclass(frozen=True) +class MatchingCase: + """Conditional name/role overrides evaluated after a structural match. + + Omitted or null overrides inherit the matching rule's defaults. + """ + + requires_smarts: str + name: str | None = None + sequence_role: SequenceRole | None = None + _pattern: Mol = field(init=False, repr=False, compare=False) + + def __post_init__(self) -> None: + if not isinstance(self.requires_smarts, str) or not self.requires_smarts.strip(): + raise ValueError("Matching case requires_smarts must be a nonempty SMARTS string") + try: + pattern = smarts_to_mol(self.requires_smarts) + except ValueError as exc: + raise ValueError(f"Invalid matching case requires_smarts: {self.requires_smarts!r}") from exc + object.__setattr__(self, "_pattern", pattern) + if self.name is not None and (not isinstance(self.name, str) or not self.name.strip()): + raise ValueError("Matching case name must be a nonempty string or null") + if self.sequence_role not in (None, "backbone", "tailoring"): + raise ValueError("Matching case sequence_role must be 'backbone', 'tailoring', or null") + + def matches(self, mol: Mol, match_stereochemistry: bool = False) -> bool: + return mol.HasSubstructMatch(self._pattern, useChirality=match_stereochemistry) + + def to_dict(self) -> dict[str, Any]: + data = {"requires_smarts": self.requires_smarts} + if self.name is not None: + data["name"] = self.name + if self.sequence_role is not None: + data["sequence_role"] = self.sequence_role + return data + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> "MatchingCase": + if not isinstance(data, dict) or "requires_smarts" not in data: + raise ValueError("Each matching case must be a mapping with requires_smarts") + unknown = data.keys() - {"requires_smarts", "name", "sequence_role"} + if unknown: + raise ValueError(f"Unknown matching case fields: {sorted(unknown)}") + return cls(**data) + + @dataclass(frozen=True) class MatchingRule: """ @@ -416,6 +462,11 @@ class MatchingRule: region from subdivision in alternative derivations. Defaults to True. :cvar sequence_role: Optional role in a linear assembly readout. None uses the bond-element heuristic; this setting does not affect parsing. + :cvar requires_smarts: Optional additional substructure query evaluated on + the tagged fragment after the whole-fragment SMILES match. Isotope zero + can distinguish reaction-added atoms from original input atoms. + :cvar cases: Conditional name/role overrides, evaluated only after this rule + matches. The first matching case wins; otherwise the defaults apply. """ name: str @@ -427,8 +478,11 @@ class MatchingRule: display_smiles: str | None = None preserve_across_routes: bool = True sequence_role: SequenceRole | None = None + requires_smarts: str | None = None + cases: list[MatchingCase] = field(default_factory=list) mol: Mol = field(init=False, repr=False) + _required_pattern: Mol | None = field(init=False, repr=False, compare=False) def __post_init__(self) -> None: """ @@ -440,15 +494,32 @@ def __post_init__(self) -> None: raise ValueError(f"{self.name}: preserve_across_routes must be a boolean") if self.sequence_role not in (None, "backbone", "tailoring"): raise ValueError(f"{self.name}: sequence_role must be 'backbone', 'tailoring', or null") + pattern = None + if self.requires_smarts is not None: + if not isinstance(self.requires_smarts, str) or not self.requires_smarts.strip(): + raise ValueError(f"{self.name}: requires_smarts must be a nonempty SMARTS string or null") + try: + pattern = smarts_to_mol(self.requires_smarts) + except ValueError as exc: + raise ValueError(f"{self.name}: invalid requires_smarts: {self.requires_smarts!r}") from exc + object.__setattr__(self, "_required_pattern", pattern) + if not isinstance(self.cases, list) or any(not isinstance(case, MatchingCase) for case in self.cases): + raise ValueError(f"{self.name}: cases must be a list of MatchingCase objects") @property def id(self) -> str: """ - Unique identifier for the matching rule based on its SMILES pattern. + Identifier for the SMILES and optional SMARTS condition. + + Rules without a condition retain their historical SMILES-only IDs. :return: Unique identifier. """ - return hashlib.sha256(self.smiles.encode("utf-8")).hexdigest() + definition = self.smiles if self.requires_smarts is None else json.dumps( + {"smiles": self.smiles, "requires_smarts": self.requires_smarts}, + sort_keys=True, separators=(",", ":"), + ) + return hashlib.sha256(definition.encode("utf-8")).hexdigest() def to_dict(self) -> dict[str, Any]: """ @@ -466,6 +537,8 @@ def to_dict(self) -> dict[str, Any]: "display_smiles": self.display_smiles, "preserve_across_routes": self.preserve_across_routes, "sequence_role": self.sequence_role, + "requires_smarts": self.requires_smarts, + "cases": [case.to_dict() for case in self.cases], } @classmethod @@ -479,6 +552,9 @@ def from_dict(cls, data: dict[str, Any]) -> "MatchingRule": # Keep old YAML/JSON readable without retaining behavior settings in metadata. props = dict(data.get("props", {})) legacy_preserve = props.pop("preserve_across_routes", True) + cases = data.get("cases", []) + if not isinstance(cases, list): + raise ValueError(f"{data['name']}: cases must be a list") matching_rule = cls( name=data["name"], smiles=data["smiles"], @@ -489,6 +565,8 @@ def from_dict(cls, data: dict[str, Any]) -> "MatchingRule": display_smiles=data.get("display_smiles"), preserve_across_routes=data.get("preserve_across_routes", legacy_preserve), sequence_role=data.get("sequence_role"), + requires_smarts=data.get("requires_smarts"), + cases=[MatchingCase.from_dict(case) for case in cases], ) return matching_rule @@ -505,10 +583,37 @@ def is_match(self, mol: Mol, match_stereochemistry: bool = False) -> bool: has_equal_num_bonds = mol.GetNumBonds() == self.mol.GetNumBonds() if has_substruct_match and has_equal_num_atoms and has_equal_num_bonds: - return True + return self._required_pattern is None or mol.HasSubstructMatch( + self._required_pattern, useChirality=match_stereochemistry, + ) return False + def _resolved(self, case: MatchingCase | None = None) -> "MatchingRule": + """Snapshot the effective identity without modifying the source rule.""" + if not self.cases: + return self + return replace( + self, + name=case.name if case is not None and case.name is not None else self.name, + sequence_role=(case.sequence_role if case is not None and case.sequence_role is not None + else self.sequence_role), + cases=[], + ) + + def match(self, mol: Mol, match_stereochemistry: bool = False) -> "MatchingRule | None": + """Match the structure, then resolve its name and role using cases.""" + if not self.is_match(mol, match_stereochemistry): + return None + for case in self.cases: + if case.matches(mol, match_stereochemistry): + return self._resolved(case) + return self._resolved() + + def variants(self) -> list["MatchingRule"]: + """Possible identities for name lookup/depiction, not parser matching.""" + return [self._resolved(), *(self._resolved(case) for case in self.cases)] + @dataclass(frozen=True) class RuleSet: @@ -537,6 +642,15 @@ def matching_rules_hash(self) -> str: """SHA-256 of ordered matching definitions, including names and flags.""" return self._hash_rules(self.matching_rules) + @cached_property + def matching_rule_variants(self) -> list[MatchingRule]: + """Default and case identities for vocabularies and name-based lookup. + + Parsing always uses matching_rules, so each structure is matched once + before evaluating its cases. Variants may share a structural rule ID. + """ + return [variant for rule in self.matching_rules for variant in rule.variants()] + @staticmethod def _hash_rules(rules: list) -> str: content = json.dumps( @@ -555,13 +669,18 @@ def __str__(self) -> str: def find_structural_matches(self, mol: Mol, match_stereochemistry: bool = False) -> list["MatchingRule"]: """ - Find every matching rule whose motif has the same structure as mol. + Find every matching rule and resolve its cases for this tagged molecule. :param mol: Molecule to match against every rule in this ruleset. :param match_stereochemistry: Whether to consider stereochemistry in matching. :return: Every MatchingRule whose motif has the same structure as `mol`, in ruleset order (possibly empty). """ - return [rule for rule in self.matching_rules if rule.is_match(mol, match_stereochemistry=match_stereochemistry)] + matches = [] + for rule in self.matching_rules: + resolved = rule.match(mol, match_stereochemistry) + if resolved is not None: + matches.append(resolved) + return matches @classmethod def load_from_files( diff --git a/src/retromol_antismash/modules.py b/src/retromol_antismash/modules.py index 90df174..6d0499e 100644 --- a/src/retromol_antismash/modules.py +++ b/src/retromol_antismash/modules.py @@ -11,6 +11,7 @@ from typing import Any, Literal, overload from retromol.chem.mol import smiles_to_mol +from retromol.chem.tagging import tag_mol from retromol.model.rules import RuleSet from retromol_antismash.model import Region, Gene, Strand, Domain from retromol_antismash.predictions import ( @@ -1167,7 +1168,7 @@ def module_primary_sequence_tokens(module: Module, ruleset: RuleSet) -> tuple[st the same "unidentified block" convention used for compound primary sequences. """ def _by_name(name: str) -> tuple[str, list[str]] | None: - matches = [r for r in ruleset.matching_rules if r.name == name] + matches = [r for r in ruleset.matching_rule_variants if r.name == name] if not matches: return None tokens: set[str] = set() @@ -1246,6 +1247,9 @@ def _by_name(name: str) -> tuple[str, list[str]] | None: except ValueError: return "X", [] + # Predicted substrates are input structures, not reaction-added fragments. + # Preserve that distinction for origin-sensitive requires_smarts conditions. + tag_mol(mol) matches = ruleset.find_structural_matches(mol, match_stereochemistry=ruleset.match_stereochemistry) if not matches: return "X", [] @@ -1281,4 +1285,4 @@ def bgc_primary_sequence(readout: LinearReadout, ruleset: RuleSet) -> tuple[list names.append(name) tokens.append(module_tokens) - return names, tokens \ No newline at end of file + return names, tokens diff --git a/src/retromol_synthesis/reconstruction.py b/src/retromol_synthesis/reconstruction.py index b6db9e0..76e489c 100644 --- a/src/retromol_synthesis/reconstruction.py +++ b/src/retromol_synthesis/reconstruction.py @@ -610,7 +610,7 @@ def reconstruct_named_sequence(rule_set: RuleSet, names: list[str]) -> Reconstru if not names: raise BackboneReconstructionError("No building blocks given.") - name_to_rule = {rule.name: rule for rule in rule_set.matching_rules} + name_to_rule = {rule.name: rule for rule in rule_set.matching_rule_variants} building_blocks: list[str] = [] primary_sequence: list[tuple[str, set[int]]] = [] diff --git a/tests/data/integration_retromol_assemblies.yml b/tests/data/integration_retromol_assemblies.yml index 5c7cb18..82937a9 100644 --- a/tests/data/integration_retromol_assemblies.yml +++ b/tests/data/integration_retromol_assemblies.yml @@ -2,7 +2,7 @@ "10-deoxymethynolide": - coverage: 1.0 nodes: - - ["propanoic acid", 2] + - ["propanoic acid starter", 2] - ["B2", 4] - ["C1", 2] - ["A2", 4] @@ -19,7 +19,7 @@ "13-deoxytedanolide": - coverage: 1.0 nodes: - - ["propanoic acid", 2] + - ["propanoic acid starter", 2] - ["C2", 3] - ["C2", 3] - ["oxidation", 1] @@ -56,7 +56,7 @@ "6-deoxyerythronolide B": - coverage: 1.0 nodes: - - ["propanoic acid", 2] + - ["propanoic acid starter", 2] - ["B2", 4] - ["B2", 4] - ["A2", 4] @@ -80,10 +80,10 @@ - ["C1", 2] - ["C1", 2] - ["C1", 5] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["oxidation", 1] - ["B10", 7] - - ["acetic acid", 1] + - ["acetic acid starter", 1] edges: - [0, 1, ["C-O:SINGLE"]] - [0, 7, ["C-O:SINGLE"]] @@ -102,7 +102,7 @@ - ["A2", 4] - ["oxidation", 1] - ["D2", 3] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["C1", 2] - ["C1", 2] - ["A1", 5] @@ -123,7 +123,7 @@ nodes: - ["oxidation", 1] - ["C1", 2] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["C1", 2] - ["C1", 2] - ["A1", 5] @@ -144,7 +144,7 @@ "aculeximycin": - coverage: 1.0 nodes: - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["D1", 2] - ["B2", 4] - ["glycosylation", 10] @@ -200,7 +200,7 @@ "acutiphycin": - coverage: 1.0 nodes: - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["D1", 2] - ["D1", 2] - ["B1", 3] @@ -278,7 +278,7 @@ "amphidinolide J": - coverage: 1.0 nodes: - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["D1", 2] - ["C1", 2] - ["D10", 4] @@ -373,7 +373,7 @@ - ["C1", 2] - ["C1", 2] - ["D2", 3] - - ["acetic acid", 1] + - ["acetic acid starter", 1] edges: - [0, 1, ["C-C:DOUBLE"]] - [0, 6, ["C-C:SINGLE"]] @@ -459,7 +459,7 @@ - ["methylation", 1] - ["chlorination", 1] - ["chlorination", 1] - - ["acetic acid", 1] + - ["acetic acid starter", 1] edges: - [0, 1, ["C-O:SINGLE"]] - [0, 12, ["C-O:SINGLE"]] @@ -502,7 +502,7 @@ - ["methylation", 1] - ["chlorination", 1] - ["chlorination", 1] - - ["acetic acid", 1] + - ["acetic acid starter", 1] edges: - [0, 1, ["C-O:SINGLE"]] - [0, 12, ["C-O:SINGLE"]] @@ -615,7 +615,7 @@ - ["glycosylation", 10] - ["methylation", 1] - ["iodination", 1] - - ["acetic acid", 1] + - ["acetic acid starter", 1] edges: - [0, 1, ["C-N:SINGLE"]] - [1, 2, ["C-O:SINGLE"]] @@ -700,7 +700,7 @@ - ["C1", 2] - ["B11", 4] - ["C2", 3] - - ["acetic acid", 1] + - ["acetic acid starter", 1] edges: - [0, 1, ["C-C:SINGLE"]] - [0, 9, ["C-C:SINGLE"]] @@ -747,7 +747,7 @@ - ["D2", 3] - ["chlorination", 1] - ["chlorination", 1] - - ["acetic acid", 1] + - ["acetic acid starter", 1] edges: - [0, 1, ["C-C:DOUBLE"]] - [0, 6, ["C-C:SINGLE"]] @@ -768,7 +768,7 @@ "chlorothricin": - coverage: 1.0 nodes: - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["C13", 5] - ["C1", 2] - ["glyceric acid", 5] @@ -783,7 +783,7 @@ - ["glycosylation", 9] - ["A1", 5] - ["C1", 2] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["chlorination", 1] - ["C1", 2] - ["methylation", 1] @@ -834,7 +834,7 @@ - ["C1", 2] - ["C1", 2] - ["C1", 2] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["C1", 2] - ["D1", 2] - ["B1", 3] @@ -855,7 +855,7 @@ "cremimycin": - coverage: 1.0 nodes: - - ["propanoic acid", 2] + - ["propanoic acid starter", 2] - ["D1", 2] - ["D1", 2] - ["A", 3] @@ -893,7 +893,7 @@ "deschlorothricin": - coverage: 1.0 nodes: - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["C13", 5] - ["C1", 2] - ["glyceric acid", 5] @@ -908,7 +908,7 @@ - ["glycosylation", 9] - ["A1", 5] - ["C1", 2] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["C1", 2] - ["methylation", 1] - ["D1", 2] @@ -942,7 +942,7 @@ "daptomycin": - coverage: 1.0 nodes: - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["D1", 2] - ["D1", 2] - ["D1", 2] @@ -995,7 +995,7 @@ - ["D2", 3] - ["C2", 3] - ["C1", 2] - - ["acetic acid", 1] + - ["acetic acid starter", 1] edges: - [0, 1, ["C-C:SINGLE"]] - [0, 9, ["C-C:SINGLE"]] @@ -1025,7 +1025,7 @@ - ["B2", 4] - ["C2", 3] - ["C1", 2] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["carbamic acid", 3] edges: - [0, 1, ["C-C:SINGLE", "C-O:SINGLE"]] @@ -1071,7 +1071,7 @@ "erythromycin": - coverage: 1.0 nodes: - - ["propanoic acid", 2] + - ["propanoic acid starter", 2] - ["B6", 5] - ["B2", 4] - ["A2", 4] @@ -1143,7 +1143,7 @@ "harzianic acid": - coverage: 1.0 nodes: - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["D1", 2] - ["C1", 2] - ["C1", 2] @@ -1200,7 +1200,7 @@ "hymenosetin": - coverage: 1.0 nodes: - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["C1", 2] - ["C2", 3] - ["C1", 2] @@ -1336,7 +1336,7 @@ - ["B2", 4] - ["methylation", 1] - ["C2", 3] - - ["propanoic acid", 2] + - ["propanoic acid starter", 2] - ["B1", 3] - ["C1", 2] - ["C2", 3] @@ -1372,7 +1372,7 @@ - ["B3", 5] - ["C1", 2] - ["C1", 2] - - ["acetic acid", 1] + - ["acetic acid starter", 1] edges: - [0, 1, ["C-N:SINGLE"]] - [0, 13, ["C-C:SINGLE"]] @@ -1430,7 +1430,7 @@ - ["acetic acid", 3] - ["methylation", 1] - ["B2", 4] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["acetic acid", 3] - ["methylation", 1] edges: @@ -1485,7 +1485,7 @@ - ["C1", 2] - ["B2", 4] - ["C1", 2] - - ["propanoic acid", 2] + - ["propanoic acid starter", 2] - ["B-beta-carboxymethyl", 6] - ["B2", 4] - ["A8", 3] @@ -1516,7 +1516,7 @@ - ["C1", 2] - ["C1", 2] - ["C1", 2] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["D1", 2] - ["B1", 3] - ["B1", 5] @@ -1536,7 +1536,7 @@ "macrolactin A": - coverage: 1.0 nodes: - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["B1", 3] - ["D1", 2] - ["C1", 2] @@ -1603,7 +1603,7 @@ "megalomycin A": - coverage: 1.0 nodes: - - ["propanoic acid", 2] + - ["propanoic acid starter", 2] - ["B6", 5] - ["B2", 4] - ["A2", 4] @@ -1632,7 +1632,7 @@ "micacocidin A": - coverage: 1.0 nodes: - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["D1", 2] - ["D1", 2] - ["C1", 2] @@ -1686,7 +1686,7 @@ "narbonolide": - coverage: 1.0 nodes: - - ["propanoic acid", 2] + - ["propanoic acid starter", 2] - ["B2", 4] - ["C1", 2] - ["A2", 4] @@ -1717,7 +1717,7 @@ - ["methylation", 1] - ["methylation", 1] - ["methylation", 1] - - ["acetic acid", 1] + - ["acetic acid starter", 1] edges: - [0, 1, ["C-O:SINGLE"]] - [0, 2, ["C-C:SINGLE"]] @@ -1737,7 +1737,7 @@ "peluriside A": - coverage: 1.0 nodes: - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["D7", 4] - ["C2", 3] - ["B1", 3] @@ -1779,7 +1779,7 @@ "periconiasin A": - coverage: 1.0 nodes: - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["C2", 3] - ["leucine", 7] - ["A1", 5] @@ -1808,7 +1808,7 @@ - ["C1", 2] - ["C2", 3] - ["leucine", 7] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["oxidation", 1] edges: - [0, 1, ["C-C:DOUBLE"]] @@ -1825,7 +1825,7 @@ "ratjadon": - coverage: 1.0 nodes: - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["C1", 2] - ["B2", 4] - ["B1", 3] @@ -1963,7 +1963,7 @@ - ["methylation", 1] - ["formaldehyde", 1] - ["methylation", 1] - - ["acetic acid", 1] + - ["acetic acid starter", 1] edges: - [0, 1, ["C-O:SINGLE"]] - [0, 2, ["C-C:SINGLE"]] @@ -1997,7 +1997,7 @@ - ["methylation", 1] - ["formaldehyde", 1] - ["methylation", 1] - - ["acetic acid", 1] + - ["acetic acid starter", 1] edges: - [0, 1, ["C-O:SINGLE"]] - [0, 2, ["C-C:SINGLE"]] @@ -2028,7 +2028,7 @@ - ["B2", 4] - ["B2", 4] - ["B1", 3] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["acetic acid", 3] edges: - [0, 1, ["C-C:SINGLE"]] @@ -2076,7 +2076,7 @@ "zincophorin": - coverage: 1.0 nodes: - - ["propanoic acid", 2] + - ["propanoic acid starter", 2] - ["D2", 3] - ["C2", 3] - ["B2", 4] @@ -2145,7 +2145,7 @@ - ["B6", 5] - ["D2", 3] - ["D5", 3] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["methylation", 1] edges: - [0, 1, ["C-N:SINGLE"]] @@ -2172,7 +2172,7 @@ - ["methylation", 1] - ["B1", 3] - ["D1", 2] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["C1", 4] edges: - [0, 1, ["C-C:SINGLE"]] @@ -2196,7 +2196,7 @@ "dihydroxydione": - coverage: 1.0 nodes: - - ["propanoic acid", 2] + - ["propanoic acid starter", 2] - ["B2", 6] - ["A2", 4] - ["D1", 2] @@ -2218,7 +2218,7 @@ "amamistatin B": - coverage: 1.0 nodes: - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["D1", 2] - ["D1", 2] - ["D1", 2] @@ -2240,7 +2240,7 @@ "nocardichelin B": - coverage: 1.0 nodes: - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["D1", 2] - ["D1", 2] - ["D1", 2] @@ -2283,9 +2283,9 @@ - ["D1", 2] - ["C1", 2] - ["B1", 3] - - ["propanoic acid", 2] + - ["propanoic acid starter", 2] - ["D2", 3] - - ["propanoic acid", 2] + - ["propanoic acid starter", 2] - ["D2", 3] edges: - [0, 1, ["B-O:SINGLE", "B-O:SINGLE"]] @@ -2365,7 +2365,7 @@ - ["A2", 4] - ["A1", 5] - ["B1", 3] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["C1", 2] - ["chlorination", 1] edges: @@ -2380,7 +2380,7 @@ "actinoquinoline B": - coverage: 1.0 nodes: - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["D8", 5] - ["5-hydroxylysine", 10] - ["3-hydroxyquinaldic acid", 13] @@ -2587,7 +2587,7 @@ - ["isoleucine", 8] - ["alanine", 5] - ["alanine", 5] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["B1", 5] - ["D1", 2] - ["D1", 2] @@ -2752,7 +2752,7 @@ - ["B-alpha-hexyl", 11] - ["lactic acid", 3] - ["3-formamido-2-hydroxybenzoic acid", 12] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["D8", 5] - ["threonine", 7] edges: @@ -2785,7 +2785,7 @@ - ["C1", 2] - ["B1", 3] - ["B5", 4] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["B1", 3] - ["C1", 2] - ["C2", 3] @@ -2930,7 +2930,7 @@ nodes: - ["isoleucine", 8] - ["A1", 5] - - ["acetic acid", 1] + - ["acetic acid starter", 1] edges: - [0, 1, ["C-C:DOUBLE", "C-N:SINGLE"]] - [1, 2, ["C-C:SINGLE"]] @@ -2977,7 +2977,7 @@ - ["D2", 6] - ["formaldehyde", 2] - ["D8", 5] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["N-methylpipecolic acid", 9] - ["valine", 5] - ["tyrosine", 10] @@ -3046,7 +3046,7 @@ - ["C1", 2] - ["C1", 2] - ["B2-alpha-carboxy", 7] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["B2-alpha-hydroxymethyl", 6] - ["C1", 2] - ["serine", 5] @@ -3054,7 +3054,7 @@ - ["serine", 5] - ["C1", 4] - ["B1", 3] - - ["acetic acid", 1] + - ["acetic acid starter", 1] edges: - [0, 8, ["C-C:SINGLE"]] - [0, 9, ["C-C:SINGLE"]] @@ -3110,7 +3110,7 @@ - ["glyceric acid", 6] - ["isoleucine", 8] - ["Aeap", 11] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["D1", 2] - ["glycosylation", 11] - ["D1", 4] @@ -3118,7 +3118,7 @@ - ["D1", 4] - ["carbonic acid", 2] - ["D1", 2] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["sulfate", 4] edges: - [0, 6, ["C-O:SINGLE"]] @@ -3139,7 +3139,7 @@ nodes: - ["C1", 2] - ["A1", 3] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["A4", 7] edges: - [0, 2, ["C-C:SINGLE"]] @@ -3291,7 +3291,7 @@ - ["C1", 2] - ["C1", 2] - ["C1", 2] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["A1", 5] edges: - [0, 5, ["C-C:SINGLE"]] @@ -3306,7 +3306,7 @@ nodes: - ["C1", 2] - ["D2", 3] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["C2", 3] - ["B2", 4] - ["C2", 3] @@ -3370,7 +3370,7 @@ - ["D1", 2] - ["D1", 2] - ["A1", 5] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["D1", 2] - ["D1", 2] - ["D1", 2] @@ -3424,7 +3424,7 @@ - ["D1", 2] - ["D1", 2] - ["A1", 5] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["D1", 2] - ["D1", 2] - ["D1", 2] @@ -3451,13 +3451,13 @@ - coverage: 1.0 nodes: - ["C1", 5] - - ["propanoic acid", 2] + - ["propanoic acid starter", 2] edges: - [0, 1, ["C-C:DOUBLE"]] "PK shifted alkene donor H2": - coverage: 1.0 nodes: - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["C1", 5] edges: - [0, 1, ["C-C:DOUBLE"]] @@ -3716,7 +3716,7 @@ - ["B1", 3] - ["C1", 2] - ["B1", 3] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["B1", 3] - ["B1", 3] - ["B1", 3] @@ -3769,7 +3769,7 @@ - ["C1", 2] - ["C1", 2] - ["D1", 2] - - ["acetic acid", 1] + - ["acetic acid starter", 1] edges: - [0, 6, ["C-C:SINGLE"]] - [0, 7, ["C-C:SINGLE"]] @@ -3789,7 +3789,7 @@ - ["A1", 2] - ["A1", 3] - ["A1", 3] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["A1", 3] - ["A1", 3] - ["oxidation", 1] @@ -3818,7 +3818,7 @@ - ["A1", 2] - ["A1", 2] - ["A1", 6] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["A1", 3] - ["A1", 3] edges: @@ -3843,7 +3843,7 @@ - ["A1", 3] - ["glycosylation", 9] - ["methylation", 1] - - ["propanoic acid", 2] + - ["propanoic acid starter", 2] - ["oxidation", 1] - ["glycosylation", 9] - ["glycosylation", 8] @@ -3952,7 +3952,7 @@ - ["methylation", 1] - ["D11", 3] - ["glycosylation", 9] - - ["propanoic acid", 2] + - ["propanoic acid starter", 2] - ["A1", 3] - ["A1", 3] - ["methylation", 1] @@ -4003,7 +4003,7 @@ - ["C1", 2] - ["C1", 2] - ["A1", 3] - - ["acetic acid", 1] + - ["acetic acid starter", 1] edges: - [0, 6, ["C-C:AROMATIC"]] - [0, 7, ["C-C:AROMATIC"]] @@ -4025,7 +4025,7 @@ - coverage: 1.0 nodes: - ["C1", 2] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["B5", 4] - ["C2", 3] - ["B1", 3] @@ -4070,7 +4070,7 @@ "PK aldol ring donor H1": - coverage: 1.0 nodes: - - ["propanoic acid", 2] + - ["propanoic acid starter", 2] - ["A1", 6] - ["D1", 2] - ["A1", 3] @@ -4084,7 +4084,7 @@ - coverage: 1.0 nodes: - ["A1", 3] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["A1", 6] - ["D1", 2] edges: @@ -4096,7 +4096,7 @@ "PK pentyl-branched beta-hydroxy chain": - coverage: 1.0 nodes: - - ["propanoic acid", 2] + - ["propanoic acid starter", 2] - ["B-alpha-pentyl", 11] edges: - [0, 1, ["C-C:SINGLE"]] @@ -4274,7 +4274,7 @@ - coverage: 1.0 nodes: - ["A1", 3] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["A1", 2] - ["A1", 3] edges: @@ -4287,7 +4287,7 @@ - coverage: 1.0 nodes: - ["A1", 2] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["A1", 3] - ["A1", 3] - ["A1", 5] @@ -4303,7 +4303,7 @@ - coverage: 1.0 nodes: - ["A1", 2] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["oxidation", 1] - ["A1", 3] - ["A1", 3] @@ -4323,7 +4323,7 @@ - ["A1", 3] - ["A1", 2] - ["A1", 5] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["A1", 3] - ["A1", 2] - ["A1", 3] @@ -4341,12 +4341,12 @@ "nidulin": - coverage: 1.0 nodes: - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["A1", 3] - ["chlorination", 1] - ["A1", 2] - ["A1", 5] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["chlorination", 1] - ["chlorination", 1] - ["A2", 4] @@ -4376,11 +4376,11 @@ - ["C2", 3] - ["A2", 4] - ["C1", 2] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["A1", 5] - ["A1", 3] - ["C2", 3] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["A1", 2] - ["A2", 4] edges: diff --git a/tests/data/integration_retromol_stereochemistry_assemblies.yml b/tests/data/integration_retromol_stereochemistry_assemblies.yml index d051f78..2292806 100644 --- a/tests/data/integration_retromol_stereochemistry_assemblies.yml +++ b/tests/data/integration_retromol_stereochemistry_assemblies.yml @@ -4,7 +4,7 @@ nodes: - ["B^S1", 3] - ["D1", 2] - - ["acetic acid", 1] + - ["acetic acid starter", 1] - ["B^R1", 3] - ["D^R8", 3] - ["B^R1", 3] diff --git a/tests/test_assembly_sampling.py b/tests/test_assembly_sampling.py index bb65aa2..532bea1 100644 --- a/tests/test_assembly_sampling.py +++ b/tests/test_assembly_sampling.py @@ -538,7 +538,7 @@ def test_decanoic_lipopeptide_has_five_resolutions(ruleset): assert sorted(len(a.monomer_ids()) for a in assemblies) == [3, 4, 5, 6, 7] fatty_names = {n.identity.name for a in assemblies for n in a.monomer_nodes() if 'acid' in n.identity.name} - assert fatty_names == {'decanoic acid', 'octanoic acid', 'hexanoic acid', 'butanoic acid', 'acetic acid'} + assert fatty_names == {'decanoic acid', 'octanoic acid', 'hexanoic acid', 'butanoic acid', 'acetic acid starter'} assert all(result.calculate_coverage(a) == 1 for a in assemblies) sequences = [LinearReadout.from_assembly_graph(a).primary_sequence() for a in assemblies] assert sorted(map(len, sequences)) == [3, 4, 5, 6, 7] diff --git a/tests/test_cli.py b/tests/test_cli.py index d66baa5..0cbc033 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -154,7 +154,7 @@ def test_daptomycin_samples_only_full_coverage_and_keeps_all_resolutions(single_ assert 'Drawing 5 of 5 eligible assemblies (5 total' in caplog.text assemblies = [space.build(frozenset(nodes)) for _, nodes in drawn] assert all(result.calculate_coverage(a) == 1 for a in assemblies) - fatty_acids = {'decanoic acid', 'octanoic acid', 'hexanoic acid', 'butanoic acid', 'acetic acid'} + fatty_acids = {'decanoic acid', 'octanoic acid', 'hexanoic acid', 'butanoic acid', 'acetic acid starter'} assert fatty_acids <= {node.identity.name for a in assemblies for node in a.monomer_nodes()} assert len({nodes for _, nodes in drawn}) == 5 threonine = next(n.enc for n in result.reaction_graph.identified_nodes.values() diff --git a/tests/test_matching.py b/tests/test_matching.py new file mode 100644 index 0000000..290aaf3 --- /dev/null +++ b/tests/test_matching.py @@ -0,0 +1,238 @@ +"""Whole-fragment matching with optional conditions on the tagged structure.""" + +import hashlib +import json +from dataclasses import replace + +import pytest +import yaml + +from retromol.chem.matching import match_mol +from retromol.chem.mol import smiles_to_mol +from retromol.model.result import Result +from retromol.model.rules import MatchingCase, MatchingRule, RuleSet +from retromol.model.submission import Submission +from retromol.pipelines.parsing import run_retromol +from retromol_antismash.modules import NRPSModule, module_primary_sequence_tokens +from retromol_synthesis.reconstruction import reconstruct_named_sequence + + +ADDED_ACID = '[0C](=[0O])[0OH]' + + +def starter_rule(): + return MatchingRule('acetic acid starter', 'CC(=O)O', {}, [], + requires_smarts=ADDED_ACID, sequence_role='backbone') + + +def acid_rule(): + return MatchingRule.from_dict({ + 'name': 'acetic acid', 'smiles': 'CC(=O)O', 'sequence_role': 'tailoring', + 'cases': [{'requires_smarts': ADDED_ACID, 'name': 'acetic acid starter', + 'sequence_role': 'backbone'}], + }) + + +def test_single_structural_rule_resolves_each_fragment_without_mutating_defaults(): + rule = acid_rule() + original_definition = rule.to_dict() + unrelated = MatchingRule('methane', 'C', {}, []) + for rules in ([rule, unrelated], [unrelated, rule]): + for fragment, name, role in [ + (smiles_to_mol('[1CH3]C(=O)O'), 'acetic acid starter', 'backbone'), + (smiles_to_mol('[1CH3][2C](=[3O])O'), 'acetic acid', 'tailoring'), + (Submission('CC(=O)O').mol, 'acetic acid', 'tailoring'), + ]: + assert rule.is_match(fragment) + identity = match_mol(fragment, rules) + assert identity.name == name + assert identity.matched_rule.sequence_role == role + assert identity.matched_rule.cases == [] + assert rule.to_dict() == original_definition + # Cases are evaluated only after the whole structure and any top-level gate match. + assert rule.match(smiles_to_mol('[1CH3][2CH2]C(=O)O')) is None + assert replace(rule, requires_smarts='N').match(smiles_to_mol('[1CH3]C(=O)O')) is None + + +def test_cases_use_first_matching_override_and_inherit_unspecified_defaults(): + rule = replace(acid_rule(), cases=[ + MatchingCase('[0C]', name='first'), + MatchingCase('[0O]', name='second', sequence_role='backbone'), + ]) + generated = smiles_to_mol('[1CH3]C(=O)O') + resolved = rule.match(generated) + assert (resolved.name, resolved.sequence_role) == ('first', 'tailoring') + role_only = replace(rule, cases=[MatchingCase(ADDED_ACID, sequence_role='backbone')]) + resolved = role_only.match(generated) + assert (resolved.name, resolved.sequence_role) == ('acetic acid', 'backbone') + + +def test_case_queries_use_the_requested_chirality(): + rule = MatchingRule('alanine', 'NC(C)C(=O)O', {}, [], cases=[ + MatchingCase('N[C@@H](C)C(=O)O', name='stereo case'), + ]) + same = smiles_to_mol('N[C@@H](C)C(=O)O') + opposite = smiles_to_mol('N[C@H](C)C(=O)O') + assert rule.match(same, match_stereochemistry=True).name == 'stereo case' + assert rule.match(opposite, match_stereochemistry=True).name == 'alanine' + assert rule.match(opposite, match_stereochemistry=False).name == 'stereo case' + + +@pytest.mark.parametrize('cases', [ + None, {}, 'case', [None], [{}], [{'requires_smarts': ''}], + [{'requires_smarts': '[C'}], [{'requires_smarts': True}], + [{'requires_smarts': 'C', 'smiles': 'C'}], + [{'requires_smarts': 'C', 'name': ''}], + [{'requires_smarts': 'C', 'sequence_role': 'unknown'}], +]) +def test_invalid_cases_fail_when_loading(cases): + with pytest.raises(ValueError, match='case'): + MatchingRule.from_dict({'name': 'invalid', 'smiles': 'C', 'cases': cases}) + + +def test_cases_roundtrip_and_catalog_names(tmp_path): + rule = acid_rule() + restored = MatchingRule.from_dict(json.loads(json.dumps(rule.to_dict()))) + assert restored.to_dict() == rule.to_dict() + assert restored.id == replace(rule, cases=[]).id + ruleset = RuleSet(False, [], [restored]) + assert ruleset.matching_rules_hash != RuleSet(False, [], [replace(rule, cases=[])]).matching_rules_hash + assert [(r.name, r.sequence_role) for r in ruleset.matching_rule_variants] == [ + ('acetic acid', 'tailoring'), ('acetic acid starter', 'backbone'), + ] + assert [r.name for r in ruleset.find_structural_matches(smiles_to_mol('[1CH3]C(=O)O'))] == [ + 'acetic acid starter', + ] + assert [r.name for r in ruleset.find_structural_matches(Submission('CC(=O)O').mol)] == [ + 'acetic acid', + ] + reaction_path = tmp_path / 'rxn.yml' + matching_path = tmp_path / 'mxn.yml' + reaction_path.write_text('[]\n') + matching_path.write_text(yaml.safe_dump([rule.to_dict()])) + loaded = RuleSet.load_from_files(reaction_path, matching_path) + assert len(loaded.matching_rules) == 1 + assert loaded.matching_rules_hash == ruleset.matching_rules_hash + assert match_mol(smiles_to_mol('[1CH3]C(=O)O'), loaded.matching_rules).name == 'acetic acid starter' + + +@pytest.mark.parametrize('name', ['acetic acid', 'propanoic acid']) +def test_default_starter_cases_remain_available_for_named_reconstruction(name, ruleset): + assert [r.name for r in ruleset.matching_rules if r.name in (name, name + ' starter')] == [name] + reconstructed = reconstruct_named_sequence(ruleset, [name + ' starter', 'A1']) + assert reconstructed.tagged_backbone_smiles + assert [part[0] for part in reconstructed.primary_sequence] == [name + ' starter', 'A1'] + + +@pytest.mark.parametrize('smiles, expected', [ + ('[1CH3]C(=O)O', True), + ('[1CH3][2C](=[3O])O', False), # Cleaved acetyl group; only OH is added. + ('[1CH3][2C](=[3O])[4OH]', False), # Original free acid. + ('[1CH3]C(=[3O])O', False), # A partially artificial cap is insufficient. + ('[1CH3]C(=O)[4OH]', False), + ('[1CH3][2CH2]C(=O)O', False), # Query matches, whole-fragment SMILES does not. +]) +def test_requires_smarts_checks_tagged_atoms_without_replacing_structure(smiles, expected): + assert starter_rule().is_match(smiles_to_mol(smiles)) is expected + + +def test_conditional_rule_precedes_ordinary_acid_fallback(): + starter = starter_rule() + ordinary = MatchingRule('acetic acid', 'CC(=O)O', {}, [], sequence_role='tailoring') + generated = smiles_to_mol('[1CH3]C(=O)O') + original = Submission('CC(=O)O').mol + assert match_mol(generated, [starter, ordinary]).name == 'acetic acid starter' + assert match_mol(original, [starter, ordinary]).name == 'acetic acid' + # The feature does not change first-match ordering. + assert match_mol(generated, [ordinary, starter]).name == 'acetic acid' + + +def test_requires_smarts_uses_the_requested_chirality(): + rule = MatchingRule('conditional alanine', 'NC(C)C(=O)O', {}, [], + requires_smarts='N[C@@H](C)C(=O)O') + same = smiles_to_mol('N[C@@H](C)C(=O)O') + opposite = smiles_to_mol('N[C@H](C)C(=O)O') + assert rule.is_match(same, match_stereochemistry=True) + assert not rule.is_match(opposite, match_stereochemistry=True) + assert rule.is_match(opposite, match_stereochemistry=False) + + +@pytest.mark.parametrize('condition', ['', ' ', True, 0, [], {}, '[C']) +def test_invalid_requires_smarts_fails_when_loading(condition): + with pytest.raises(ValueError, match='requires_smarts'): + MatchingRule.from_dict({'name': 'invalid', 'smiles': 'C', 'requires_smarts': condition}) + + +def test_condition_serialization_ids_and_legacy_defaults(tmp_path): + starter = starter_rule() + restored = MatchingRule.from_dict(json.loads(json.dumps(starter.to_dict()))) + assert restored.requires_smarts == ADDED_ACID + assert restored.id == starter.id + assert restored.is_match(smiles_to_mol('[1CH3]C(=O)O')) + assert not restored.is_match(Submission('CC(=O)O').mol) + + legacy = MatchingRule.from_dict({'name': 'acetic acid', 'smiles': 'CC(=O)O'}) + assert legacy.requires_smarts is None + assert legacy.is_match(Submission('CC(=O)O').mol) + assert legacy.id == hashlib.sha256(b'CC(=O)O').hexdigest() + assert legacy.id != starter.id + assert replace(starter, requires_smarts='[0C]').id != starter.id + assert RuleSet(False, [], [starter]).matching_rules_hash != RuleSet( + False, [], [replace(starter, requires_smarts=None)], + ).matching_rules_hash + + reaction_path = tmp_path / 'rxn.yml' + matching_path = tmp_path / 'mxn.yml' + reaction_path.write_text('[]\n') + matching_path.write_text(yaml.safe_dump([starter.to_dict(), legacy.to_dict()])) + loaded = RuleSet.load_from_files(reaction_path, matching_path) + assert match_mol(smiles_to_mol('[1CH3]C(=O)O'), loaded.matching_rules).name == starter.name + assert match_mol(Submission('CC(=O)O').mol, loaded.matching_rules).name == legacy.name + + +@pytest.mark.parametrize('smiles, expected', [ + ('CC(=O)CC(=O)O', [['A1', 'acetic acid starter']]), + ('CCC(=O)CC(=O)O', [['A1', 'propanoic acid starter']]), + ('CC(O)CC(=O)O', [['B1', 'acetic acid starter']]), + ('CC=CC(=O)O', [['C1', 'acetic acid starter']]), + ('CCCC(=O)O', [['D1', 'acetic acid starter']]), + ('CC(=O)CC(=O)CC(=O)O', [['A1', 'A1', 'acetic acid starter']]), + ('CC(OC(C)=O)CC(=O)O', [['B1', 'acetic acid starter'], ['acetic acid']]), + ('NC(COC(C)=O)C(=O)NC(C)C(=O)O', [['alanine', 'serine'], ['acetic acid']]), + ('NC(CCCCNC(C)=O)C(=O)NC(C)C(=O)O', [['alanine', 'lysine'], ['acetic acid']]), + ('CC(=O)NCC(=O)NC(C)C(=O)O', [['alanine', 'glycine'], ['acetic acid']]), + ('CC(=O)O', [['acetic acid']]), + ('CCC(=O)O', [['propanoic acid']]), +]) +def test_default_rules_distinguish_pk_starters_and_acyl_tailoring(smiles, expected, ruleset): + result = run_retromol(Submission(smiles), ruleset) + assert result.linear_readout.primary_sequence_parts() == expected + assert result.calculate_coverage() == 1.0 + restored = Result.from_dict(json.loads(json.dumps(result.to_dict()))) + assert restored.linear_readout.primary_sequence_parts() == expected + assert restored.calculate_coverage() == 1.0 + + +def test_old_results_keep_their_saved_identities(ruleset): + # Before conditional starter rules, this same PK fragment was ordinary acid. + old_rules = replace(ruleset, matching_rules=[replace(r, cases=[]) for r in ruleset.matching_rules]) + result = run_retromol(Submission('CC(=O)CC(=O)O'), old_rules) + data = result.to_dict() + for identity in data['reaction_graph']['identities']: + identity.pop('requires_smarts') + identity.pop('cases') + restored = Result.from_dict(data) + assert restored.linear_readout.primary_sequence_parts() == [['A1'], ['acetic acid']] + + +@pytest.mark.parametrize('smiles, name', [ + ('CC(=O)O', 'acetic acid'), + ('CCC(=O)O', 'propanoic acid'), +]) +def test_predicted_substrate_smiles_do_not_imply_generated_atoms(smiles, name, ruleset): + module = NRPSModule.from_dict({ + 'module_index_in_gene': 0, 'start': 0, 'end': 100, + 'gene_id': 'test', 'gene_strand': '+', 'present_domains': [], + 'predicted_substrate': {'smiles': smiles}, + }) + assert module_primary_sequence_tokens(module, ruleset) == (name, [name]) From becff6486a416f709bf2ccd09ecaac9cfcefe895 Mon Sep 17 00:00:00 2001 From: David Meijer Date: Tue, 20 Oct 2026 00:32:57 -0400 Subject: [PATCH 4/7] UPD: orient backbones N-terminus to C-terminus --- src/retromol/data/README.md | 25 +- src/retromol/data/mxn.yml | 4 +- src/retromol/model/readout.py | 225 +++++++++++++++--- .../data/integration_retromol_assemblies.yml | 4 +- tests/test_integration_readout.py | 99 ++++++++ tests/test_matching.py | 37 ++- tests/test_readout.py | 147 ++++++++++++ 7 files changed, 490 insertions(+), 51 deletions(-) create mode 100644 tests/test_integration_readout.py diff --git a/src/retromol/data/README.md b/src/retromol/data/README.md index 5c0669e..bc1c673 100644 --- a/src/retromol/data/README.md +++ b/src/retromol/data/README.md @@ -106,17 +106,19 @@ For example: ### Conditional names and sequence roles Define the structure once, then use `cases` to assign a name and role based on -the matched fragment's existing atom tags. The default PK cleavage rules add a complete -carboxyl cap to the remaining chain. An acetate starter therefore has an -artificial carboxyl carbon and oxygens (tag zero), whereas acetate cleaved from -an acetyl substituent retains its original carbonyl atoms (positive tags): +the matched fragment's existing atom tags. The default PK cleavage rules add a +complete carboxyl cap to the remaining chain. Reversing thiazole formation instead +retains the original acyl carbon and restores its carbonyl oxygen; subsequent +amide cleavage adds the acid hydroxyl. Both starter representations have two +reaction-added acid oxygens (tag zero). Ordinary O- or N-acetyl substituents +retain their original carbonyl oxygen (a positive tag): ```yaml - name: acetic acid smiles: 'CC(=O)O' sequence_role: tailoring cases: - - requires_smarts: '[0C](=[0O])[0OH]' + - requires_smarts: '[C](=[0O])[0OH]' name: acetic acid starter sequence_role: backbone ``` @@ -139,8 +141,17 @@ contained in a matched monomer, such as N-methylalanine, stays part of that mono its name alone does not make the whole unit tailoring. This is a representation policy, not evidence that a reaction happened after backbone synthesis. -Connections between two explicit `backbone` units are also retained regardless of -bond elements. Where either non-tailoring endpoint has no role, the readout falls +Connections between two explicit `backbone` units are initially retained regardless +of bond elements. The readout then excludes acyl side attachments: if a unit's +artificial S–OH cap marks an incoming carbon already connected to a preceding +unit's carboxyl side, an extra ester/thioester connection to its O/S is omitted +from traversal. This covers ring closures and ester attachments between separate +backbones; both chains remain backbone sequences. Extra ether links to the already +connected incoming carbon are also excluded, so they cannot redirect the path. +Esters without that competing entry evidence remain eligible, including ordinary +ester-linked backbone steps. All original bonds remain in the assembly graph. + +Where either non-tailoring endpoint has no role, the readout falls back to C–C/C–N connections. A `tailoring` endpoint always separates from an untagged or `backbone` endpoint. The defaults explicitly mark PK units and conditional acid starters as backbone and modification identities as tailoring. Other units diff --git a/src/retromol/data/mxn.yml b/src/retromol/data/mxn.yml index a85dbb7..6608763 100644 --- a/src/retromol/data/mxn.yml +++ b/src/retromol/data/mxn.yml @@ -1196,7 +1196,7 @@ smiles: "CC(=O)O" sequence_role: tailoring cases: - - requires_smarts: "[0C](=[0O])[0OH]" + - requires_smarts: "[C](=[0O])[0OH]" name: acetic acid starter sequence_role: backbone @@ -1208,7 +1208,7 @@ smiles: "CCC(O)=O" sequence_role: tailoring cases: - - requires_smarts: "[0C](=[0O])[0OH]" + - requires_smarts: "[C](=[0O])[0OH]" name: propanoic acid starter sequence_role: backbone diff --git a/src/retromol/model/readout.py b/src/retromol/model/readout.py index 1613e49..13dd71a 100644 --- a/src/retromol/model/readout.py +++ b/src/retromol/model/readout.py @@ -3,6 +3,9 @@ from dataclasses import dataclass from typing import Callable, Literal, TypeVar +import networkx as nx + +from retromol.chem.mol import smarts_to_mol from retromol.model.reaction_graph import MolNode, ReactionGraph from retromol.model.assembly_graph import AssemblyGraph from retromol_fingerprint.fingerprint import TOKEN_LINK @@ -12,6 +15,184 @@ T = TypeVar("T") +_CARBOXYL = smarts_to_mol("[CX3](=[OX1])-[OX2H1,OX1-]") +_UNIT_ENTRY_CAP = smarts_to_mol("[#6]-[0S]-[0OH]") + + +def _carboxyl_exit_tags(node: MolNode, include_added_caps: bool = True) -> set[int]: + """Original atoms at a fragment's carboxyl-side continuation points. + + A retained carboxyl carbon is the donor in a cleaved peptide/ester link. + When the entire carboxyl is an added cap (tag zero), its original carbon + neighbor is the continuation point instead. This uses the same fragment + representation for peptide, PK, and hybrid paths, without rematching units. + """ + exits: set[int] = set() + for carbon_idx, oxo_idx, hydroxyl_idx in node.mol.GetSubstructMatches(_CARBOXYL): + carbon = node.mol.GetAtomWithIdx(carbon_idx) + if carbon.GetIsotope(): + exits.add(carbon.GetIsotope()) + elif include_added_caps and all(node.mol.GetAtomWithIdx(i).GetIsotope() == 0 + for i in (oxo_idx, hydroxyl_idx)): + exits.update(atom.GetIsotope() for atom in carbon.GetNeighbors() + if atom.GetAtomicNum() == 6 and atom.GetIsotope()) + return exits + + +def _remove_side_links(g: nx.Graph) -> None: + """Omit side attachments that compete with connected backbone entries. + + The artificial S-OH cap marks the original atom receiving the preceding + unit. If that entry is connected, an additional acyl link to the same unit's + O/S is a side attachment, whether it closes a ring or joins separate chains. + Being a graph bridge does not make that attachment a backbone continuation. + An extra ether link to the already connected incoming carbon likewise does + not replace the connection from the preceding unit's carboxyl side. + Esters without this competing entry evidence retain their connectivity. + This mutates only the readout's graph copy, never the source assembly. + """ + nodes = {key: data["molnode"] for key, data in g.nodes(data=True) + if data["molnode"].identity.matched_rule.sequence_role != "tailoring"} + entries = { + key: {node.mol.GetAtomWithIdx(match[0]).GetIsotope() + for match in node.mol.GetSubstructMatches(_UNIT_ENTRY_CAP) + if node.mol.GetAtomWithIdx(match[0]).GetIsotope()} + for key, node in nodes.items() + } + if not any(entries.values()): + return + exits = {key: _carboxyl_exit_tags(node) for key, node in nodes.items()} + retained = {key: _carboxyl_exit_tags(node, include_added_caps=False) for key, node in nodes.items()} + connected_entries = {key: set() for key in nodes} + for u, v, data in g.edges(data=True): + if u not in nodes or v not in nodes: + continue + for bond in data["bonds"]: + for left, right in ((bond.a1_tag, bond.a2_tag), (bond.a2_tag, bond.a1_tag)): + if left in exits[u] and right in entries[v]: + connected_entries[v].add(right) + if left in entries[u] and right in exits[v]: + connected_entries[u].add(left) + if not any(connected_entries.values()): + return + + for u, v, data in list(g.edges(data=True)): + if u not in nodes or v not in nodes: + continue + kept = [] + for bond in data["bonds"]: + side_attachment = False + for carbon, hetero, symbol in ( + (bond.a1_tag, bond.a2_tag, bond.a2_symbol), + (bond.a2_tag, bond.a1_tag, bond.a1_symbol), + ): + if bond.bond_type == "SINGLE" and symbol in ("O", "S") and ( + carbon in retained[u] and hetero in g.nodes[v]["tags"] and connected_entries[v] + or carbon in retained[v] and hetero in g.nodes[u]["tags"] and connected_entries[u] + or carbon in connected_entries[u] and hetero in g.nodes[v]["tags"] + or carbon in connected_entries[v] and hetero in g.nodes[u]["tags"] + ): + side_attachment = True + if not side_attachment: + kept.append(bond) + if len(kept) == len(data["bonds"]): + continue + if kept: + g[u][v].update(bonds=kept, n_bonds=len(kept)) + else: + g.remove_edge(u, v) + + +def _readout_graph(assembly: AssemblyGraph) -> nx.Graph: + """Shared connectivity for both path selection and path orientation.""" + g = assembly.g.copy() + if g.has_node(assembly.unassigned): + g.remove_node(assembly.unassigned) + roles = {} + for node_id, data in list(g.nodes(data=True)): + node = data.get("molnode") + if node is None: + raise ValueError(f"AssemblyGraph node {node_id!r} has no 'molnode' attached!") + if not node.is_identified or node.identity is None: + g.remove_node(node_id) + continue + roles[node_id] = node.identity.matched_rule.sequence_role + + backbone_pairs = {frozenset(("C", "C")), frozenset(("C", "N"))} + for u, v, data in list(g.edges(data=True)): + if roles[u] is not None and roles[u] == roles[v]: + continue + if "tailoring" in (roles[u], roles[v]) or not any( + frozenset((bond.a1_symbol, bond.a2_symbol)) in backbone_pairs + for bond in data["bonds"] + ): + g.remove_edge(u, v) + _remove_side_links(g) + return g + + +def _orient_paths(assembly: AssemblyGraph, paths: list[list[MolNode]]) -> list[list[MolNode]]: + """Orient paths toward the carboxyl end when connection evidence agrees. + + Root bond tags identify the actual connection; merely finding a free acid + (including an Asp/Glu side-chain acid) is not a direction signal. Missing or + contradictory connection evidence can still be resolved by a unique retained + terminal carboxyl. Otherwise the existing deterministic orientation is kept. + Closed rings keep their selected start, a convention rather than a terminus. + """ + g = _readout_graph(assembly) + by_enc = {data["molnode"].enc: node_id for node_id, data in g.nodes(data=True)} + exits = {node.enc: _carboxyl_exit_tags(node) for path in paths for node in path} + oriented = [] + for path in paths: + if len(path) < 2 or any(node.identity.matched_rule.sequence_role == "tailoring" for node in path): + oriented.append(path) + continue + ids = [by_enc.get(node.enc) for node in path] + if any(node_id is None for node_id in ids): + oriented.append(path) + continue + + closed = len(path) > 2 and g.has_edge(ids[-1], ids[0]) + steps = list(zip(range(len(path) - 1), range(1, len(path)))) + if closed: + steps.append((len(path) - 1, 0)) + directions: set[int] = set() + for i, j in steps: + edge = g.get_edge_data(ids[i], ids[j]) + if edge is None: + continue + left_tags = g.nodes[ids[i]]["tags"] + right_tags = g.nodes[ids[j]]["tags"] + for bond in edge["bonds"]: + # Root bond begin/end order is unrelated to sequence direction. + for left, right in ((bond.a1_tag, bond.a2_tag), (bond.a2_tag, bond.a1_tag)): + if left in left_tags and right in right_tags: + if left in exits[path[i].enc]: + directions.add(1) + if right in exits[path[j].enc]: + directions.add(-1) + reverse = directions == {-1} + if len(directions) != 1 and not closed: + terminal_ends = [] + for i, j in ((0, 1), (len(path) - 1, len(path) - 2)): + retained = _carboxyl_exit_tags(path[i], include_added_caps=False) + edge = g.get_edge_data(ids[i], ids[j], {}) + connected = {tag for bond in edge.get("bonds", []) for tag in (bond.a1_tag, bond.a2_tag)} + # A side-chain acid is not a terminal anchor when the same unit + # donates through another retained carboxyl to its neighbor. + if retained and not retained.intersection(connected): + terminal_ends.append(i) + if len(terminal_ends) == 1: + reverse = terminal_ends[0] == 0 + if reverse: + path = list(reversed(path)) + if closed: + # Preserve the chosen ring start while reversing its traversal. + path = path[-1:] + path[:-1] + oriented.append(path) + return oriented + def merge_named_paths(paths: list[list[T]], key: Callable[[T], str], link_item: T) -> list[T]: """ @@ -79,7 +260,7 @@ class LinearReadout: paths: list[list[MolNode]] def __post_init__(self) -> None: - """Keep direct construction and older serialized paths identified-only.""" + """Normalize identified paths and their direction, including saved paths.""" paths: list[list[MolNode]] = [] for path in self.paths: part: list[MolNode] = [] @@ -91,6 +272,8 @@ def __post_init__(self) -> None: part = [] if part: paths.append(part) + paths = _orient_paths(self.assembly_graph, paths) + paths.sort(key=lambda path: (-len(path), [_node_name(node) for node in path], [node.enc for node in path])) object.__setattr__(self, "paths", paths) def __str__(self) -> str: @@ -148,33 +331,13 @@ def from_assembly_graph(cls, assembly_graph: AssemblyGraph) -> "LinearReadout": so every identified MolNode occurs exactly once. Unidentified and unassigned nodes are excluded before traversal, breaking paths at gaps. The input graph is unchanged; use its coverage to measure completeness. - Rings are opened deterministically, without assigning a biological start - or direction; cyclic path selection is heuristic. + Ester closures competing with an already connected cap-defined unit + entry are omitted from traversal before selecting paths. + Carboxyl-side connections orient consistent paths N/starter-to-C end. + Ambiguous paths retain deterministic direction. Rings have a conventional + start, not a biological terminus; cyclic path selection is heuristic. """ - g = assembly_graph.g.copy() - if g.has_node(assembly_graph.unassigned): - g.remove_node(assembly_graph.unassigned) - - roles = {} - for node_id, data in list(g.nodes(data=True)): - node = data.get("molnode") - if node is None: - raise ValueError(f"AssemblyGraph node {node_id!r} has no 'molnode' attached!") - if not node.is_identified or node.identity is None: - g.remove_node(node_id) - continue - roles[node_id] = node.identity.matched_rule.sequence_role - - backbone_pairs = {frozenset(("C", "C")), frozenset(("C", "N"))} - for u, v, data in list(g.edges(data=True)): - if roles[u] is not None and roles[u] == roles[v]: - continue - if "tailoring" in (roles[u], roles[v]) or not any( - frozenset((bond.a1_symbol, bond.a2_symbol)) in backbone_pairs - for bond in data["bonds"] - ): - g.remove_edge(u, v) - + g = _readout_graph(assembly_graph) paths: list[list[MolNode]] = [] pending = AssemblyGraph(g, unassigned=assembly_graph.unassigned).connected_components() while pending: @@ -186,7 +349,6 @@ def from_assembly_graph(cls, assembly_graph: AssemblyGraph) -> "LinearReadout": h.g.remove_nodes_from([n for n, data in h.g.nodes(data=True) if id(data["molnode"]) in used]) pending.extend(h.connected_components()) - paths.sort(key=lambda path: (-len(path), [_node_name(node) for node in path], [node.enc for node in path])) return cls(assembly_graph=assembly_graph, paths=paths) def primary_sequence_parts(self) -> list[list[str]]: @@ -197,6 +359,7 @@ def primary_sequence_parts(self) -> list[list[str]]: coverage measures completeness. Sublists do not encode attachment points, omitted crosslinks, or ring closures; retain ``assembly_graph`` when those are needed. Untagged paths are not biological role labels. + Consistent carboxyl-side connection evidence puts the N/starter end first. """ return sorted( [[_node_name(node) for node in path] for path in self.paths], @@ -247,8 +410,10 @@ def assembly_to_primary_sequence(assembly_graph: AssemblyGraph) -> list[list[str Uses matching-rule sequence roles with a C-C/C-N fallback and includes every identified monomer once. Unresolved and unassigned regions are excluded; use ``result.calculate_coverage(assembly_graph)`` for completeness. Parts are ordered - longest first, then lexically. Ordering is structural, not biosynthetic; - branch attachments and ring closures remain in the input assembly graph. + longest first, then lexically. Within each path, consistent carboxyl-side + connections orient N/starter-to-C end; ambiguous paths retain deterministic + order. This is not proof of biosynthesis. Branch attachments and ring closures + remain in the input assembly graph. For the corresponding MolNodes (including atom tags and identities), use ``LinearReadout.from_assembly_graph(assembly_graph).paths``. diff --git a/tests/data/integration_retromol_assemblies.yml b/tests/data/integration_retromol_assemblies.yml index 82937a9..0a91796 100644 --- a/tests/data/integration_retromol_assemblies.yml +++ b/tests/data/integration_retromol_assemblies.yml @@ -1054,7 +1054,7 @@ - ["B2", 4] - ["C2", 3] - ["cysteine", 4] - - ["acetic acid", 2] + - ["acetic acid starter", 2] edges: - [0, 1, ["C-C:SINGLE"]] - [0, 7, ["C-C:SINGLE"]] @@ -2204,7 +2204,7 @@ - ["B1", 3] - ["C2", 3] - ["cysteine", 4] - - ["acetic acid", 2] + - ["acetic acid starter", 2] edges: - [0, 1, ["C-C:SINGLE"]] - [1, 2, ["C-C:SINGLE"]] diff --git a/tests/test_integration_readout.py b/tests/test_integration_readout.py new file mode 100644 index 0000000..01ab456 --- /dev/null +++ b/tests/test_integration_readout.py @@ -0,0 +1,99 @@ +"""Exact, ordered sequence expectations for cyclic peptide/PK/hybrid inputs.""" + +import json + +import pytest +from rdkit import Chem + +from retromol.model.assembly_graph import AssemblyGraph +from retromol.model.readout import assembly_to_primary_sequence, split_named_paths +from retromol.model.result import Result + +from .data.integration_retromol import CASES as ASSEMBLY_CASES +from .helpers_retromol import parse_compound + +EPOTHILONE = ( + r'C[C@H]1CCC[C@@]2(C)O[C@H]2C[C@H](OC(=O)C[C@H](O)C(C)(C)' + r'C(=O)[C@H](C)[C@H]1O)C(\C)=C\C1=CSC(C)=N1' +) +ERYTHROMYCIN_C = ( + 'CC[C@@H]1[C@@]([C@@H]([C@H](C(=O)[C@@H](C[C@@]([C@@H]([C@H](' + '[C@@H]([C@H](C(=O)O1)C)O[C@H]2C[C@@]([C@H]([C@@H](O2)C)O)(C)O)C)' + 'O[C@H]3[C@@H]([C@H](C[C@H](O3)C)N(C)C)O)(C)O)C)C)O)(C)O' +) +NEOPELTOLIDE = ( + r'O=C(/C=C\CCC1=COC(/C=C\CNC(OC)=O)=N1)O[C@@H]2C[C@@H](' + r'C[C@@H](C)C[C@H](OC)C[C@H](CCC)OC(C3)=O)O[C@@H]3C2' +) + + +READOUT_CASES = [ + pytest.param( + NEOPELTOLIDE, + [['acetic acid starter', 'D1', 'B1', 'B1', 'D8', 'B1', 'B1', 'C1'], + ['glycine', 'C1', 'serine', 'D1', 'C1'], + ['carbonic acid', 'methylation'], ['methylation']], + [['acetic acid starter', 'D1', 'B^S1', 'B^R1', 'D^R8', 'B^R1', 'B^R1', 'C1'], + ['glycine', 'C^Z1', 'serine', 'D1', 'C^Z1'], + ['carbonic acid', 'methylation'], ['methylation']], + id='neopeltolide', + ), + pytest.param( + EPOTHILONE, + [['acetic acid starter', 'cysteine', 'C2', 'B1', 'C2', 'D1', 'D2', 'B2', 'A3', 'B1'], + ['oxidation']], + [['acetic acid starter', 'cysteine', 'C^E2', 'B^R1', 'C2', 'D1', 'D2^R', 'B^S2^S', 'A3', 'B^R1'], + ['oxidation']], + id='epothilone', + ), + pytest.param( + dict(ASSEMBLY_CASES)['daptomycin'], + [['acetic acid starter', 'D1', 'D1', 'D1', 'D1', 'tryptophan', 'asparagine', + 'aspartic acid', 'threonine', 'glycine', 'ornithine', 'aspartic acid', 'alanine', + 'aspartic acid', 'glycine', 'serine', '3-methylglutamic acid', 'kynurenine']], + [['acetic acid starter', 'D1', 'D1', 'D1', 'D1', 'tryptophan^L', 'asparagine^D', + 'aspartic acid^L', 'threonine', 'glycine', 'ornithine^L', 'aspartic acid^L', 'alanine^D', + 'aspartic acid^L', 'glycine', 'serine^D', '3-methylglutamic acid', 'kynurenine']], + id='daptomycin', + ), + pytest.param( + ERYTHROMYCIN_C, + [['propanoic acid starter', 'B6', 'B2', 'A2', 'D6', 'B2', 'B2'], + ['glycosylation'], ['glycosylation']], + [['propanoic acid starter', 'B^R6^S', 'B^S2^S', 'A2^R', 'D6^S', 'B^S2^S', 'B^S2^S'], + ['glycosylation'], ['glycosylation']], + id='erythromycin-C', + ), +] + + +@pytest.mark.parametrize('smiles, expected_plain, expected_stereo', READOUT_CASES) +@pytest.mark.parametrize('stereo', [False, True], ids=['plain', 'stereo']) +@pytest.mark.parametrize('reverse_atoms', [False, True], ids=['input-order', 'reversed-atoms']) +def test_integration_linear_readout(smiles, expected_plain, expected_stereo, stereo, reverse_atoms, + ruleset, stereo_ruleset): + if reverse_atoms: + mol = Chem.MolFromSmiles(smiles) + mol = Chem.RenumberAtoms(mol, list(reversed(range(mol.GetNumAtoms())))) + smiles = Chem.MolToSmiles(mol, canonical=False) + result = parse_compound(smiles, stereo_ruleset if stereo else ruleset) + expected = expected_stereo if stereo else expected_plain + assembly_before = result.assembly_graph.to_dict() + + readout = result.linear_readout + assert readout.primary_sequence_parts() == expected + assert split_named_paths(readout.primary_sequence(), key=lambda name: name) == expected + assert result.calculate_coverage() == 1.0 + assert result.assembly_graph.to_dict() == assembly_before + + # Saved results and the assembly-only API used by sampled CLI exports must + # preserve direction and roles without rematching or access to a live root. + restored = Result.from_dict(json.loads(json.dumps(result.to_dict()))) + assert restored.linear_readout.primary_sequence_parts() == expected + assembly = AssemblyGraph.from_dict(json.loads(json.dumps(assembly_before))) + assert assembly_to_primary_sequence(assembly) == expected + + path_nodes = [node.enc for path in readout.paths for node in path] + identified = {node.enc for node in result.assembly_graph.monomer_nodes() if node.is_identified} + assert len(path_nodes) == len(set(path_nodes)) + assert set(path_nodes) == identified diff --git a/tests/test_matching.py b/tests/test_matching.py index 290aaf3..0f58c57 100644 --- a/tests/test_matching.py +++ b/tests/test_matching.py @@ -124,6 +124,23 @@ def test_default_starter_cases_remain_available_for_named_reconstruction(name, r assert [part[0] for part in reconstructed.primary_sequence] == [name + ' starter', 'A1'] +@pytest.mark.parametrize('name, prefix', [ + ('acetic acid', '[1CH3]'), ('propanoic acid', '[1CH3][2CH2]'), +]) +@pytest.mark.parametrize('acid, starter', [ + ('C(=O)O', True), # Complete cap added by PK cleavage. + ('[3C](=O)O', True), # Original thiazole carbon; both oxygens restored. + ('[3C](=[4O])O', False), # O-/N-acyl cleavage retains carbonyl oxygen. + ('[3C](=O)[5OH]', False), # One new oxygen alone is insufficient. + ('[3C](=[4O])[5OH]', False), # Original free acid. +]) +def test_default_acid_case_accepts_restored_oxygens_with_either_carbon_origin(name, prefix, acid, starter, ruleset): + rule, = [r for r in ruleset.matching_rules if r.name == name] + identity = match_mol(smiles_to_mol(prefix + acid), [rule]) + assert identity.name == name + (' starter' if starter else '') + assert identity.matched_rule.sequence_role == ('backbone' if starter else 'tailoring') + + @pytest.mark.parametrize('smiles, expected', [ ('[1CH3]C(=O)O', True), ('[1CH3][2C](=[3O])O', False), # Cleaved acetyl group; only OH is added. @@ -191,16 +208,16 @@ def test_condition_serialization_ids_and_legacy_defaults(tmp_path): @pytest.mark.parametrize('smiles, expected', [ - ('CC(=O)CC(=O)O', [['A1', 'acetic acid starter']]), - ('CCC(=O)CC(=O)O', [['A1', 'propanoic acid starter']]), - ('CC(O)CC(=O)O', [['B1', 'acetic acid starter']]), - ('CC=CC(=O)O', [['C1', 'acetic acid starter']]), - ('CCCC(=O)O', [['D1', 'acetic acid starter']]), - ('CC(=O)CC(=O)CC(=O)O', [['A1', 'A1', 'acetic acid starter']]), - ('CC(OC(C)=O)CC(=O)O', [['B1', 'acetic acid starter'], ['acetic acid']]), - ('NC(COC(C)=O)C(=O)NC(C)C(=O)O', [['alanine', 'serine'], ['acetic acid']]), - ('NC(CCCCNC(C)=O)C(=O)NC(C)C(=O)O', [['alanine', 'lysine'], ['acetic acid']]), - ('CC(=O)NCC(=O)NC(C)C(=O)O', [['alanine', 'glycine'], ['acetic acid']]), + ('CC(=O)CC(=O)O', [['acetic acid starter', 'A1']]), + ('CCC(=O)CC(=O)O', [['propanoic acid starter', 'A1']]), + ('CC(O)CC(=O)O', [['acetic acid starter', 'B1']]), + ('CC=CC(=O)O', [['acetic acid starter', 'C1']]), + ('CCCC(=O)O', [['acetic acid starter', 'D1']]), + ('CC(=O)CC(=O)CC(=O)O', [['acetic acid starter', 'A1', 'A1']]), + ('CC(OC(C)=O)CC(=O)O', [['acetic acid starter', 'B1'], ['acetic acid']]), + ('NC(COC(C)=O)C(=O)NC(C)C(=O)O', [['serine', 'alanine'], ['acetic acid']]), + ('NC(CCCCNC(C)=O)C(=O)NC(C)C(=O)O', [['lysine', 'alanine'], ['acetic acid']]), + ('CC(=O)NCC(=O)NC(C)C(=O)O', [['glycine', 'alanine'], ['acetic acid']]), ('CC(=O)O', [['acetic acid']]), ('CCC(=O)O', [['propanoic acid']]), ]) diff --git a/tests/test_readout.py b/tests/test_readout.py index e86b8a0..2c7da10 100644 --- a/tests/test_readout.py +++ b/tests/test_readout.py @@ -6,6 +6,7 @@ import networkx as nx import pytest +from rdkit import Chem from retromol.chem.mol import smiles_to_mol from retromol.model.assembly_graph import AssemblyGraph, RootBondLink @@ -16,6 +17,7 @@ from retromol.model.rules import MatchingRule, RuleSet from retromol.model.submission import Submission from retromol.pipelines.parsing import run_retromol +from retromol_synthesis.reconstruction import reconstruct_linear_readout def assembly(names, edges=(), roles=None): @@ -190,3 +192,148 @@ def test_sequences_from_sampled_assemblies_and_saved_result(ruleset): assert all(len(parts) == 1 for parts in sequences) restored = Result.from_dict(json.loads(json.dumps(result.to_dict()))) assert [assembly_to_primary_sequence(a) for a in restored.sample_assemblies(10, seed=42)] == sequences + + +@pytest.mark.parametrize('reverse_atoms', [False, True]) +@pytest.mark.parametrize('smiles, expected', [ + ('NCC(=O)NC(C)C(=O)O', [['glycine', 'alanine']]), + ('CC(N)C(=O)NCC(=O)O', [['alanine', 'glycine']]), + ('NC(CC(=O)O)C(=O)NC(C)C(=O)O', [['aspartic acid', 'alanine']]), + ('NCC(=O)NC(CC(=O)O)C(=O)O', [['glycine', 'aspartic acid']]), + ('NCC(=O)N(C)C(C)C(=O)O', [['glycine', 'N-methylalanine']]), + ('NCC(=O)NC(C)C(N)=O', [['glycine', 'alanine'], ['amination']]), + ('CC(=O)CC(O)CC(=O)O', [['acetic acid starter', 'A1', 'B1']]), + ('CCC(=O)CC(=O)O', [['propanoic acid starter', 'A1']]), + ('NCC(=O)CC(=O)O', [['glycine', 'A1']]), + ('CC(=O)CC(=O)NCC(=O)NC(C)C(=O)O', [['acetic acid starter', 'A1', 'glycine', 'alanine']]), + ('CC(=O)CC(=O)NCC(=O)CC(=O)O', [['acetic acid starter', 'A1', 'glycine', 'A1']]), +]) +def test_readout_runs_from_n_or_starter_end_to_carboxyl_end(smiles, expected, reverse_atoms, ruleset): + mol = smiles_to_mol(smiles) + if reverse_atoms: + mol = Chem.RenumberAtoms(mol, list(reversed(range(mol.GetNumAtoms())))) + result = run_retromol(Submission(Chem.MolToSmiles(mol, canonical=False)), ruleset) + a = result.assembly_graph + before = a.to_dict() + readout = LinearReadout.from_assembly_graph(a) + assert readout.primary_sequence_parts() == expected + assert a.to_dict() == before + assert result.calculate_coverage(a) == 1.0 + # Orientation must also work without the in-memory root molecule. + restored = AssemblyGraph.from_dict(json.loads(json.dumps(before))) + assert 'root_mol' not in restored.g.graph + assert assembly_to_primary_sequence(restored) == expected + # Direct construction and old saved readouts may contain the opposite direction. + reversed_readout = readout.to_dict() + reversed_readout['paths'] = [list(reversed(path)) for path in reversed_readout['paths']] + assert LinearReadout.from_dict(reversed_readout).primary_sequence_parts() == expected + assert LinearReadout(a, [list(reversed(path)) for path in readout.paths]).primary_sequence_parts() == expected + + +def test_oxygen_linked_backbone_uses_the_same_direction_rule(ruleset): + backbone_rules = replace(ruleset, matching_rules=[ + replace(rule, sequence_role='backbone') if rule.name in ('glycine', 'lactic acid', 'alanine') else rule + for rule in ruleset.matching_rules + ]) + result = run_retromol(Submission('NCC(=O)OC(C)C(=O)NC(C)C(=O)O'), backbone_rules) + assert result.linear_readout.primary_sequence_parts() == [['glycine', 'lactic acid', 'alanine']] + + +def test_retained_terminal_carboxyl_anchors_alternative_pk_decompositions(ruleset): + # This structure also admits a reverse-cut route containing malonic acid. + # Its competing artificial caps must not put the retained terminal acid first. + result = run_retromol(Submission('CCC(=O)CC(O)CC(=O)O'), ruleset) + sequences = [assembly_to_primary_sequence(a) for a in result.sample_assemblies(10, seed=42)] + assert sorted(sequences) == sorted([ + [['propanoic acid starter', 'A1', 'B1']], + [['propanoic acid starter', 'B1', 'malonic acid']], + ]) + + +def test_carboxyl_direction_does_not_reorient_tailoring_paths(ruleset): + tailoring_rules = replace(ruleset, matching_rules=[ + replace(rule, sequence_role='tailoring') for rule in ruleset.matching_rules + ]) + result = run_retromol(Submission('NCC(=O)NC(C)C(=O)O'), tailoring_rules) + assert result.linear_readout.primary_sequence_parts() == [['alanine', 'glycine']] + + +def test_converging_carboxyl_links_do_not_invent_a_direction(ruleset): + # Gly and Ala both donate to Lys (backbone N and side-chain N respectively). + # The undirected path has no consistent N-to-C traversal through all three. + result = run_retromol(Submission('NCC(=O)NC(CCCCNC(=O)C(N)C)C(=O)O'), ruleset) + expected = [[node.identity.name for node in result.assembly_graph.longest_path()]] + assert result.linear_readout.primary_sequence_parts() == expected + assert len(expected[0]) == 3 + + +def test_cyclic_peptide_preserves_conventional_start_and_carboxyl_direction(ruleset): + # Around this ring: Gly -> Ala -> Ser -> Gly; there is no natural terminus. + result = run_retromol(Submission('O=C1NCC(=O)NC(C)C(=O)NC(CO)1'), ruleset) + readout = result.linear_readout + assert readout.primary_sequence_parts() == [['alanine', 'serine', 'glycine']] + restored = LinearReadout.from_dict(readout.to_dict()) + assert restored.primary_sequence_parts() == readout.primary_sequence_parts() + + +def test_reconstruction_consumes_the_oriented_peptide_readout(ruleset): + smiles = 'NCC(=O)NC(C)C(=O)O' + result = run_retromol(Submission(smiles), ruleset) + reconstruction, = reconstruct_linear_readout(result) + assert [name for name, _ in reconstruction.primary_sequence] == ['glycine', 'alanine'] + mol = smiles_to_mol(reconstruction.tagged_backbone_smiles) + for atom in mol.GetAtoms(): + atom.SetIsotope(0) + assert Chem.MolToSmiles(mol) == Chem.MolToSmiles(smiles_to_mol(smiles)) + + +ARTIFICIAL_ERYTHROMYCIN = ( + 'CC[C@@H]1[C@@](C)(O)[C@H](O)[C@@H](C)C([C@H](C)C[C@@](C)(OC(C)=O)' + '[C@H](O[C@H]2[C@H](O)[C@@H](N(C)C)C[C@@H](C)O2)[C@@H](C)' + '[C@H](O[C@H]3C[C@@](C)(O)[C@@H](O)[C@H](C)O3)[C@@H](C)C(O1)=O)=O' +) + + +@pytest.mark.parametrize('stereo', [False, True]) +@pytest.mark.parametrize('reverse_atoms', [False, True]) +def test_macrolactone_closure_does_not_shortcut_the_linear_backbone(stereo, reverse_atoms, ruleset, stereo_ruleset): + mol = smiles_to_mol(ARTIFICIAL_ERYTHROMYCIN) + if reverse_atoms: + mol = Chem.RenumberAtoms(mol, list(reversed(range(mol.GetNumAtoms())))) + result = run_retromol(Submission(Chem.MolToSmiles(mol, canonical=False)), stereo_ruleset if stereo else ruleset) + a = result.assembly_graph + before = a.to_dict() + backbone = ['propanoic acid starter', 'B^R6^S', 'B^S2^S', 'A2^R', 'D6^S', 'B^S2^S', 'B^S2^S'] if stereo else [ + 'propanoic acid starter', 'B6', 'B2', 'A2', 'D6', 'B2', 'B2', + ] + expected = [backbone, ['acetic acid'], ['glycosylation'], ['glycosylation']] + readout = LinearReadout.from_assembly_graph(a) + assert readout.primary_sequence_parts() == expected + assert result.calculate_coverage(a) == 1.0 + assert a.to_dict() == before + assert assembly_to_primary_sequence(AssemblyGraph.from_dict(json.loads(json.dumps(before)))) == expected + # Every sequential connection follows C-C; the original lactone closure is + # still present as a C-O connection between the first and last PK units. + path = readout.paths[0] + assert a.g.has_edge(path[1].enc, path[-1].enc) + for left, right in zip(path, path[1:]): + assert all((b.a1_symbol, b.a2_symbol) == ('C', 'C') for b in a.g[left.enc][right.enc]['bonds']) + + # Direction/topology must not depend on a name containing "starter". + renamed = a.g.copy() + for i, node in enumerate(path): + identity = MolIdentity(replace(node.identity.matched_rule, name=f'unit-{len(path) - i}')) + renamed.nodes[node.enc]['molnode'] = replace(node, identity=identity) + renamed.nodes[node.enc]['identity'] = identity + renamed_path = LinearReadout.from_assembly_graph(AssemblyGraph(renamed)).paths[0] + assert [node.enc for node in renamed_path] == [node.enc for node in path] + + # A side attachment must not become a continuation merely because it is + # the only link between two chains. The acceptor still has its own entry. + opened = a.g.copy() + opened.remove_edge(path[3].enc, path[4].enc) + opened_readout = LinearReadout.from_assembly_graph(AssemblyGraph(opened)) + closure_pair = {path[1].enc, path[-1].enc} + assert not any({left.enc, right.enc} == closure_pair + for part in opened_readout.paths for left, right in zip(part, part[1:])) + assert opened_readout.primary_sequence_parts() == [backbone[:4], backbone[4:], *expected[1:]] From 277c8a496c3d9a8ec5c1cb4a97473be127d7fffa Mon Sep 17 00:00:00 2001 From: David Meijer Date: Tue, 20 Oct 2026 00:42:42 -0400 Subject: [PATCH 5/7] FIX: backbone separation when multiple backbones are present --- src/retromol/data/README.md | 11 +++++--- src/retromol/model/readout.py | 44 ++++++++++++++++++++----------- tests/test_integration_readout.py | 25 ++++++++++++++++++ tests/test_readout.py | 26 +++++++++++++++++- 4 files changed, 86 insertions(+), 20 deletions(-) diff --git a/src/retromol/data/README.md b/src/retromol/data/README.md index bc1c673..85881c7 100644 --- a/src/retromol/data/README.md +++ b/src/retromol/data/README.md @@ -142,14 +142,19 @@ its name alone does not make the whole unit tailoring. This is a representation policy, not evidence that a reaction happened after backbone synthesis. Connections between two explicit `backbone` units are initially retained regardless -of bond elements. The readout then excludes acyl side attachments: if a unit's -artificial S–OH cap marks an incoming carbon already connected to a preceding -unit's carboxyl side, an extra ester/thioester connection to its O/S is omitted +of bond elements. The readout then distinguishes backbone continuation from side +attachments using connection sites in the fragments: an incoming carbon marked +by an artificial S–OH cap, or an alpha-amino acid's backbone nitrogen. If that +entry is already connected to a preceding unit's carboxyl side, an extra +ester/thioester connection to the unit's O/S is omitted from traversal. This covers ring closures and ester attachments between separate backbones; both chains remain backbone sequences. Extra ether links to the already connected incoming carbon are also excluded, so they cannot redirect the path. Esters without that competing entry evidence remain eligible, including ordinary ester-linked backbone steps. All original bonds remain in the assembly graph. +For example, enterobactin's three N-acylated serines yield three identical +`['2,3-dihydroxybenzoic acid', 'serine']` paths; their side-chain ester links do +not merge those paths. Repeated parts are retained as separate occurrences. Where either non-tailoring endpoint has no role, the readout falls back to C–C/C–N connections. A `tailoring` endpoint always separates from an untagged diff --git a/src/retromol/model/readout.py b/src/retromol/model/readout.py index 13dd71a..a66a20f 100644 --- a/src/retromol/model/readout.py +++ b/src/retromol/model/readout.py @@ -17,6 +17,7 @@ _CARBOXYL = smarts_to_mol("[CX3](=[OX1])-[OX2H1,OX1-]") _UNIT_ENTRY_CAP = smarts_to_mol("[#6]-[0S]-[0OH]") +_AMINO_ACID_ENTRY = smarts_to_mol("[NX3,NX4+]-[CX4]-[CX3](=[OX1])-[OX2H1,OX1-]") def _carboxyl_exit_tags(node: MolNode, include_added_caps: bool = True) -> set[int]: @@ -39,12 +40,28 @@ def _carboxyl_exit_tags(node: MolNode, include_added_caps: bool = True) -> set[i return exits +def _backbone_entry_tags(node: MolNode) -> set[int]: + """Incoming carbon of a capped unit or backbone N of an amino acid. + + The N must be attached to the carbon next to the fragment's carboxyl; + unrelated amino groups (such as lysine's side-chain N) are not entries. + Original tags let these same sites be located in the assembly's root bonds. + """ + return { + node.mol.GetAtomWithIdx(match[0]).GetIsotope() + for pattern in (_UNIT_ENTRY_CAP, _AMINO_ACID_ENTRY) + for match in node.mol.GetSubstructMatches(pattern) + if node.mol.GetAtomWithIdx(match[0]).GetIsotope() + } + + def _remove_side_links(g: nx.Graph) -> None: """Omit side attachments that compete with connected backbone entries. - The artificial S-OH cap marks the original atom receiving the preceding - unit. If that entry is connected, an additional acyl link to the same unit's - O/S is a side attachment, whether it closes a ring or joins separate chains. + A capped unit's incoming carbon and an amino acid's backbone nitrogen are + equivalent entry sites. If an entry is connected to a preceding carboxyl + side, an additional acyl link to the same unit's O/S is a side attachment, + whether it closes a ring or joins separate chains. Being a graph bridge does not make that attachment a backbone continuation. An extra ether link to the already connected incoming carbon likewise does not replace the connection from the preceding unit's carboxyl side. @@ -53,12 +70,7 @@ def _remove_side_links(g: nx.Graph) -> None: """ nodes = {key: data["molnode"] for key, data in g.nodes(data=True) if data["molnode"].identity.matched_rule.sequence_role != "tailoring"} - entries = { - key: {node.mol.GetAtomWithIdx(match[0]).GetIsotope() - for match in node.mol.GetSubstructMatches(_UNIT_ENTRY_CAP) - if node.mol.GetAtomWithIdx(match[0]).GetIsotope()} - for key, node in nodes.items() - } + entries = {key: _backbone_entry_tags(node) for key, node in nodes.items()} if not any(entries.values()): return exits = {key: _carboxyl_exit_tags(node) for key, node in nodes.items()} @@ -82,11 +94,11 @@ def _remove_side_links(g: nx.Graph) -> None: kept = [] for bond in data["bonds"]: side_attachment = False - for carbon, hetero, symbol in ( - (bond.a1_tag, bond.a2_tag, bond.a2_symbol), - (bond.a2_tag, bond.a1_tag, bond.a1_symbol), + for carbon, hetero, carbon_symbol, hetero_symbol in ( + (bond.a1_tag, bond.a2_tag, bond.a1_symbol, bond.a2_symbol), + (bond.a2_tag, bond.a1_tag, bond.a2_symbol, bond.a1_symbol), ): - if bond.bond_type == "SINGLE" and symbol in ("O", "S") and ( + if bond.bond_type == "SINGLE" and carbon_symbol == "C" and hetero_symbol in ("O", "S") and ( carbon in retained[u] and hetero in g.nodes[v]["tags"] and connected_entries[v] or carbon in retained[v] and hetero in g.nodes[u]["tags"] and connected_entries[u] or carbon in connected_entries[u] and hetero in g.nodes[v]["tags"] @@ -323,7 +335,7 @@ def from_assembly_graph(cls, assembly_graph: AssemblyGraph) -> "LinearReadout": """Partition a sampled assembly into deterministic, disjoint paths. Matching-rule ``sequence_role`` separates tailoring units from other - units. Connections between units with the same explicit role survive + units. Connections between units with the same explicit role are candidates regardless of bond elements (e.g. a connected sugar chain). Otherwise, the C-C/C-N heuristic applies to non-tailoring units. @@ -331,8 +343,8 @@ def from_assembly_graph(cls, assembly_graph: AssemblyGraph) -> "LinearReadout": so every identified MolNode occurs exactly once. Unidentified and unassigned nodes are excluded before traversal, breaking paths at gaps. The input graph is unchanged; use its coverage to measure completeness. - Ester closures competing with an already connected cap-defined unit - entry are omitted from traversal before selecting paths. + Side attachments competing with an already connected backbone entry + (capped carbon or amino-acid N) are omitted before selecting paths. Carboxyl-side connections orient consistent paths N/starter-to-C end. Ambiguous paths retain deterministic direction. Rings have a conventional start, not a biological terminus; cyclic path selection is heuristic. diff --git a/tests/test_integration_readout.py b/tests/test_integration_readout.py index 01ab456..f7d38b0 100644 --- a/tests/test_integration_readout.py +++ b/tests/test_integration_readout.py @@ -25,9 +25,34 @@ r'O=C(/C=C\CCC1=COC(/C=C\CNC(OC)=O)=N1)O[C@@H]2C[C@@H](' r'C[C@@H](C)C[C@H](OC)C[C@H](CCC)OC(C3)=O)O[C@@H]3C2' ) +THIOCORALINE = ( + 'CSCC1N(C)C(=O)C2CSSCC(N(C)C(=O)CNC(=O)C(CSC1=O)NC(=O)' + 'C1=NC3=CC=CC=C3C=C1O)C(=O)N(C)C(CSC)C(=O)SCC(NC(=O)' + 'C1=C(O)C=C3C=CC=CC3=N1)C(=O)NCC(=O)N2C' +) READOUT_CASES = [ + pytest.param( + dict(ASSEMBLY_CASES)['enterobactin'], + [['2,3-dihydroxybenzoic acid', 'serine'], + ['2,3-dihydroxybenzoic acid', 'serine'], + ['2,3-dihydroxybenzoic acid', 'serine']], + [['2,3-dihydroxybenzoic acid', 'serine'], + ['2,3-dihydroxybenzoic acid', 'serine'], + ['2,3-dihydroxybenzoic acid', 'serine']], + id='enterobactin', + ), + pytest.param( + THIOCORALINE, + [['3-hydroxyquinaldic acid', 'cysteine', 'glycine', 'N-methylcysteine', 'N-methylcysteine'], + ['3-hydroxyquinaldic acid', 'cysteine', 'glycine', 'N-methylcysteine', 'N-methylcysteine'], + ['methylation'], ['methylation']], + [['3-hydroxyquinaldic acid', 'cysteine', 'glycine', 'N-methylcysteine', 'N-methylcysteine'], + ['3-hydroxyquinaldic acid', 'cysteine', 'glycine', 'N-methylcysteine', 'N-methylcysteine'], + ['methylation'], ['methylation']], + id='thiocoraline', + ), pytest.param( NEOPELTOLIDE, [['acetic acid starter', 'D1', 'B1', 'B1', 'D8', 'B1', 'B1', 'C1'], diff --git a/tests/test_readout.py b/tests/test_readout.py index 2c7da10..f1caf7b 100644 --- a/tests/test_readout.py +++ b/tests/test_readout.py @@ -12,7 +12,7 @@ from retromol.model.assembly_graph import AssemblyGraph, RootBondLink from retromol.model.identity import MolIdentity from retromol.model.reaction_graph import MolNode -from retromol.model.readout import LinearReadout, assembly_to_primary_sequence, split_named_paths +from retromol.model.readout import LinearReadout, _backbone_entry_tags, assembly_to_primary_sequence, split_named_paths from retromol.model.result import Result from retromol.model.rules import MatchingRule, RuleSet from retromol.model.submission import Submission @@ -239,6 +239,30 @@ def test_oxygen_linked_backbone_uses_the_same_direction_rule(ruleset): assert result.linear_readout.primary_sequence_parts() == [['glycine', 'lactic acid', 'alanine']] +@pytest.mark.parametrize('smiles, expected', [ + ('NCC(=O)NC(COC(=O)C(C)N)C(=O)O', [['glycine', 'serine'], ['alanine']]), + ('NCC(=O)N(C)C(COC(=O)C(C)N)C(=O)O', [['glycine', 'N-methylserine'], ['alanine']]), + ('NC(COC(=O)C(C)N)C(=O)O', [['alanine', 'serine']]), +]) +def test_amino_entry_connection_distinguishes_side_esters_from_continuations(smiles, expected, ruleset): + # All units are explicitly backbone, so separation cannot come from the + # fallback bond filter. An unconnected amine alone does not exclude an ester. + backbone_rules = replace(ruleset, matching_rules=[ + replace(rule, sequence_role='backbone') + if rule.name in ('glycine', 'alanine', 'serine', 'N-methylserine') else rule + for rule in ruleset.matching_rules + ]) + result = run_retromol(Submission(smiles), backbone_rules) + assert result.linear_readout.primary_sequence_parts() == expected + assert result.calculate_coverage() == 1.0 + + +def test_amino_entry_excludes_lysine_side_chain_nitrogen(): + tagged = '[1NH2][2CH]([3CH2][4CH2][5CH2][6CH2][7NH2])[8C](=[9O])[10OH]' + node = MolNode('lysine', smiles_to_mol(tagged), 'NC(CCCCN)C(=O)O') + assert _backbone_entry_tags(node) == {1} + + def test_retained_terminal_carboxyl_anchors_alternative_pk_decompositions(ruleset): # This structure also admits a reverse-cut route containing malonic acid. # Its competing artificial caps must not put the retained terminal acid first. From 873694c6e13485bc7f8586b538deef410c12670f Mon Sep 17 00:00:00 2001 From: David Meijer Date: Tue, 20 Oct 2026 16:38:35 -0400 Subject: [PATCH 6/7] UPD: improve linear readout direction; add integration tests --- src/retromol/model/readout.py | 94 +- tests/data/integration_retromol_readouts.yml | 1301 +++++++++++++++++ ...tion_retromol_stereochemistry_readouts.yml | 13 + tests/helpers_retromol.py | 97 ++ tests/test_integration_readout.py | 34 + tests/test_integration_retromol.py | 38 +- ...st_integration_retromol_stereochemistry.py | 16 +- tests/test_readout.py | 93 +- tests/test_readout_expectations.py | 73 + 9 files changed, 1726 insertions(+), 33 deletions(-) create mode 100644 tests/data/integration_retromol_readouts.yml create mode 100644 tests/data/integration_retromol_stereochemistry_readouts.yml create mode 100644 tests/test_readout_expectations.py diff --git a/src/retromol/model/readout.py b/src/retromol/model/readout.py index a66a20f..9c156e5 100644 --- a/src/retromol/model/readout.py +++ b/src/retromol/model/readout.py @@ -1,7 +1,7 @@ """Data structures for representing readouts from RetroMol parsing results.""" from dataclasses import dataclass -from typing import Callable, Literal, TypeVar +from typing import Any, Callable, Literal, TypeVar import networkx as nx @@ -60,12 +60,12 @@ def _remove_side_links(g: nx.Graph) -> None: A capped unit's incoming carbon and an amino acid's backbone nitrogen are equivalent entry sites. If an entry is connected to a preceding carboxyl - side, an additional acyl link to the same unit's O/S is a side attachment, - whether it closes a ring or joins separate chains. + side, an additional acyl link to a non-entry O/S/N on the same unit is a + side attachment, whether it closes a ring or joins separate chains. Being a graph bridge does not make that attachment a backbone continuation. An extra ether link to the already connected incoming carbon likewise does not replace the connection from the preceding unit's carboxyl side. - Esters without this competing entry evidence retain their connectivity. + Acyl links without this competing entry evidence retain their connectivity. This mutates only the readout's graph copy, never the source assembly. """ nodes = {key: data["molnode"] for key, data in g.nodes(data=True) @@ -98,13 +98,18 @@ def _remove_side_links(g: nx.Graph) -> None: (bond.a1_tag, bond.a2_tag, bond.a1_symbol, bond.a2_symbol), (bond.a2_tag, bond.a1_tag, bond.a2_symbol, bond.a1_symbol), ): - if bond.bond_type == "SINGLE" and carbon_symbol == "C" and hetero_symbol in ("O", "S") and ( - carbon in retained[u] and hetero in g.nodes[v]["tags"] and connected_entries[v] - or carbon in retained[v] and hetero in g.nodes[u]["tags"] and connected_entries[u] - or carbon in connected_entries[u] and hetero in g.nodes[v]["tags"] - or carbon in connected_entries[v] and hetero in g.nodes[u]["tags"] - ): - side_attachment = True + if bond.bond_type != "SINGLE" or carbon_symbol != "C": + continue + for donor, acceptor in ((u, v), (v, u)): + if hetero not in g.nodes[acceptor]["tags"]: + continue + if (hetero_symbol in ("O", "S", "N") + and carbon in retained[donor] + and hetero not in entries[acceptor] + and connected_entries[acceptor]): + side_attachment = True + if hetero_symbol in ("O", "S") and carbon in connected_entries[donor]: + side_attachment = True if not side_attachment: kept.append(bond) if len(kept) == len(data["bonds"]): @@ -143,14 +148,56 @@ def _readout_graph(assembly: AssemblyGraph) -> nx.Graph: return g +def _connected_backbone_order(g: nx.Graph) -> list[Any] | None: + """Find a complete order determined by carboxyl-exit to entry connections. + + Ring crosslinks can give an undirected longest path the right units in the + wrong order. Prefer the fragment ports when they determine a single chain + through every unit. This applies equally to peptide, PK, and hybrid units. + At each step, only one successor may still reach all remaining units; a + shortcut that strands units or a closure into an already visited entry + cannot replace the next backbone step. Ambiguous components, incomplete + port evidence, and rings without a source retain the usual path fallback. + """ + if len(g) < 2 or any(data["molnode"].identity.matched_rule.sequence_role == "tailoring" + for _, data in g.nodes(data=True)): + return None + entries = {key: _backbone_entry_tags(data["molnode"]) for key, data in g.nodes(data=True)} + exits = {key: _carboxyl_exit_tags(data["molnode"]) for key, data in g.nodes(data=True)} + directed = nx.DiGraph() + directed.add_nodes_from(g) + for u, v, data in g.edges(data=True): + for bond in data["bonds"]: + for left, right in ((bond.a1_tag, bond.a2_tag), (bond.a2_tag, bond.a1_tag)): + if left in exits[u] and right in entries[v]: + directed.add_edge(u, v) + if left in entries[u] and right in exits[v]: + directed.add_edge(v, u) + sources = [key for key, degree in directed.in_degree() if degree == 0] + if len(sources) != 1: + return None + path = [sources[0]] + remaining = set(g) - set(path) + while remaining: + subgraph = directed.subgraph(remaining) + candidates = [key for key in directed.successors(path[-1]) if key in remaining + and len(nx.descendants(subgraph, key)) + 1 == len(remaining)] + if len(candidates) != 1: + return None + path.append(candidates[0]) + remaining.remove(candidates[0]) + return path + + def _orient_paths(assembly: AssemblyGraph, paths: list[list[MolNode]]) -> list[list[MolNode]]: """Orient paths toward the carboxyl end when connection evidence agrees. Root bond tags identify the actual connection; merely finding a free acid - (including an Asp/Glu side-chain acid) is not a direction signal. Missing or - contradictory connection evidence can still be resolved by a unique retained - terminal carboxyl. Otherwise the existing deterministic orientation is kept. - Closed rings keep their selected start, a convention rather than a terminus. + (including an Asp/Glu side-chain acid) is not a direction signal. + A complete order supported by entry/exit connections also corrects paths + saved with a crosslink in place of a backbone step. Otherwise, missing or + contradictory evidence can be resolved by a unique retained terminal acid. + Rings without a source keep a conventional start rather than a terminus. """ g = _readout_graph(assembly) by_enc = {data["molnode"].enc: node_id for node_id, data in g.nodes(data=True)} @@ -165,6 +212,12 @@ def _orient_paths(assembly: AssemblyGraph, paths: list[list[MolNode]]) -> list[l oriented.append(path) continue + connected_order = _connected_backbone_order(g.subgraph(ids)) + if connected_order is not None: + by_id = dict(zip(ids, path)) + oriented.append([by_id[node_id] for node_id in connected_order]) + continue + closed = len(path) > 2 and g.has_edge(ids[-1], ids[0]) steps = list(zip(range(len(path) - 1), range(1, len(path)))) if closed: @@ -339,22 +392,25 @@ def from_assembly_graph(cls, assembly_graph: AssemblyGraph) -> "LinearReadout": regardless of bond elements (e.g. a connected sugar chain). Otherwise, the C-C/C-N heuristic applies to non-tailoring units. - Repeatedly extract a long simple path and process its remaining branches + Prefer a complete chain determined by fragment entry/exit connections. + Otherwise extract a long simple path and process its remaining branches so every identified MolNode occurs exactly once. Unidentified and unassigned nodes are excluded before traversal, breaking paths at gaps. The input graph is unchanged; use its coverage to measure completeness. Side attachments competing with an already connected backbone entry (capped carbon or amino-acid N) are omitted before selecting paths. Carboxyl-side connections orient consistent paths N/starter-to-C end. - Ambiguous paths retain deterministic direction. Rings have a conventional - start, not a biological terminus; cyclic path selection is heuristic. + Ambiguous paths retain deterministic direction. Rings without a source + have a conventional start; their path selection remains heuristic. """ g = _readout_graph(assembly_graph) paths: list[list[MolNode]] = [] pending = AssemblyGraph(g, unassigned=assembly_graph.unassigned).connected_components() while pending: h = pending.pop() - path = h.longest_path() + connected_order = _connected_backbone_order(h.g) + path = ([h.g.nodes[node_id]["molnode"] for node_id in connected_order] + if connected_order is not None else h.longest_path()) paths.append(path) # Graph node IDs need not be identical to MolNode.enc. used = {id(node) for node in path} diff --git a/tests/data/integration_retromol_readouts.yml b/tests/data/integration_retromol_readouts.yml new file mode 100644 index 0000000..b2d1c00 --- /dev/null +++ b/tests/data/integration_retromol_readouts.yml @@ -0,0 +1,1301 @@ +# Fixed regression readouts of the current structural parsing policy. +# These are not a claim of biological correctness for every cyclic/branched case. +# "assemblies" follows the entry order in the corresponding *_assemblies.yml. +# "default_assembly" is a zero-based reference; "default_sequence" covers a +# default decomposition not represented by those required assembly fixtures. +# Known starter-order limitations have separate strict expected-failure tests. + +"10-deoxymethynolide": + default_assembly: 0 + assemblies: + - + - ["propanoic acid starter", "B2", "C1", "A2", "D2", "B2"] + +"13-deoxytedanolide": + default_assembly: 0 + assemblies: + - + - ["propanoic acid starter", "C2", "C2", "B7", "A2", "D1", "A2", "C2", "B2", "A2", "B5"] + - ["methylation"] + - ["oxidation"] + +"2-deoxystreptamine": + default_assembly: 0 + assemblies: + - + - ["glycosylation"] + +"6-deoxyerythronolide B": + default_assembly: 0 + assemblies: + - + - ["propanoic acid starter", "B2", "B2", "A2", "D2", "B2", "B2"] + +"AF-toxin": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "D17", "C1", "C1", "C1"] + - ["acetic acid starter", "B10"] + - ["2-hydroxy-3-methylpentanoic acid"] + - ["oxidation"] + +"abyssomicin C": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "C1", "C1", "C1", "A2", "D2", "A1"] + - ["glyceric acid"] + - ["oxidation"] + +"atrop-abyssocymin C": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "C1", "C1", "C1", "A2", "D2", "A1"] + - ["glyceric acid"] + - ["oxidation"] + +"aculeximycin": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "D1", "B2", "B4", "C1", "B2", "B1", "C2", "B2", "B1", "B2", "B1", "B1", "B5", "A1", "B2", "D1", "B1", "B1", "C4"] + - ["glycosylation", "glycosylation", "glycosylation"] + - ["glycosylation"] + - ["glycosylation"] + +"acutiphycin": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "D1", "D1", "B1", "C2", "B3", "A2", "C2", "B1", "B1", "A1"] + +"aflatoxin G1": + default_assembly: 0 + assemblies: + - + - ["methylation"] + +"alternapyrone": + default_assembly: 0 + assemblies: + - + - ["2-methylbutyric acid", "C2", "D1", "D2", "C2", "C2", "D2", "A2", "A2"] + +"amicoumacin": + default_assembly: 0 + assemblies: + - + - ["asparagine", "B5", "leucine", "B1", "C1", "C1", "A1"] + +"amphidinolide J": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "D1", "C1", "D10", "B1", "C2", "B1", "C1", "D15", "D8"] + +"amphidinolide P": + default_assembly: 0 + assemblies: + - + - ["2-methylprop-2-enoic acid", "D10", "C1", "A8", "C1", "B1", "A9", "A1"] + - ["oxidation"] + +"ansamitocin P-3 ": + default_assembly: 0 + assemblies: + - + - ["3-amino-5-hydroxybenzoic acid", "D2", "C1", "D11", "A1", "B2", "C2", "B1"] + - ["carbamic acid"] + - ["chlorination"] + - ["isobutyric acid"] + - ["methylation"] + - ["methylation"] + - ["methylation"] + - ["oxidation"] + +"anthracimycin": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "B1", "C1", "C2", "C1", "C1", "D2", "C1", "C1", "A1", "A2"] + +"apoptolidin": + default_sequence: + - ["malonic acid", "B2", "B2", "A5", "B1", "B5", "D1", "C2", "C1", "B2", "C2", "C2", "C2"] + - ["glycosylation", "glycosylation", "methylation"] + - ["glycosylation", "methylation"] + - ["methanol", "methylation"] + - ["methylation"] + assemblies: + - + - ["glycolic acid", "B1", "B2", "B2", "A5", "B1", "B5", "D1", "C2", "C1", "B2", "C2", "C2", "C2"] + - ["glycosylation", "glycosylation", "methylation"] + - ["glycosylation", "methylation"] + - ["methylation"] + - ["methylation"] + +"avilamycin A": + default_assembly: 0 + assemblies: + - + - ["glycosylation", "glycosylation", "glycosylation", "glycosylation", "glycosylation", "glycosylation", "glycosylation", "methanol"] + - ["acetic acid starter", "C1", "A1", "A1"] + - ["chlorination"] + - ["chlorination"] + - ["isobutyric acid"] + - ["methylation"] + - ["methylation"] + - ["methylation"] + - ["methylation"] + +"avilamycin C": + default_assembly: 0 + assemblies: + - + - ["glycosylation", "glycosylation", "glycosylation", "glycosylation", "glycosylation", "glycosylation", "glycosylation", "methanol"] + - ["acetic acid starter", "C1", "A1", "A1"] + - ["chlorination"] + - ["chlorination"] + - ["isobutyric acid"] + - ["methylation"] + - ["methylation"] + - ["methylation"] + - ["methylation"] + +"bitungolide F": + default_assembly: 0 + assemblies: + - + - ["cinnamic acid", "C1", "B1", "B1", "D2", "B4", "C1"] + +"borrelidin": + default_assembly: 0 + assemblies: + - + - ["cyclopentane-1,2-dicarboxylic acid", "B1", "C1", "C1", "B2", "D2", "D2", "D2", "B1"] + - ["cyanide"] + +"butirosin A": + default_assembly: 0 + assemblies: + - + - ["glycosylation", "glycosylation", "glycosylation"] + - ["glycine", "D5"] + +"butirosin B": + default_assembly: 0 + assemblies: + - + - ["glycosylation", "glycosylation", "glycosylation"] + - ["glycine", "D5"] + +"calicheamicin": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "C1", "A5", "A1"] + - ["ethanol", "glycosylation", "glycosylation", "glycosylation"] + - ["carbonic acid", "methylation"] + - ["glycosylation", "methylation"] + - ["iodination"] + - ["methylation"] + - ["methylation"] + - ["methylation"] + - ["methylation"] + +"callystatin": + default_assembly: 0 + assemblies: + - + - ["2-methylbutyric acid", "B2", "A2", "C2", "C1", "D2", "C4", "C1", "B1", "C1"] + +"carolacton": + default_assembly: 0 + assemblies: + - + - ["malonic acid", "B2", "A2", "C2", "B2", "D1", "D2", "C1", "B5"] + - ["methylation"] + +"chaetoglobosin A": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "C2", "C1", "C1", "D2", "C2", "B11", "C1", "A1", "tryptophan"] + - ["oxidation"] + +"chichorine": + default_assembly: 0 + assemblies: + - + - ["C1", "glycine", "D11", "D17"] + - ["methylation"] + +"chlorotonil A": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "B1", "C1", "C2", "C1", "C1", "D2", "C2", "C1", "A1", "A2"] + - ["chlorination"] + - ["chlorination"] + +"chlorothricin": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "C13", "C1", "C1", "D1", "D1", "C1", "C1", "B1", "D1", "C1"] + - ["acetic acid starter", "C1", "C1", "A1"] + - ["glycosylation", "glycosylation"] + - ["chlorination"] + - ["glyceric acid"] + - ["glycolic acid"] + - ["methylation"] + +"coelimycin P1": + default_assembly: 0 + assemblies: + - + - ["acetic acid"] + - ["cysteine"] + +"compactin": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "C1", "C1", "C1", "D5", "C1", "D1", "B1", "B1"] + - ["2-methylbutyric acid"] + +"cremimycin": + default_assembly: 0 + assemblies: + - + - ["propanoic acid starter", "D1", "D1", "A", "A1", "D1", "B1", "A1", "B1", "C1", "C2", "C1", "C1"] + - ["methylation", "glycosylation", "oxidation"] + +"deschlorothricin": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "C13", "C1", "C1", "D1", "D1", "C1", "C1", "B1", "D1", "C1"] + - ["acetic acid starter", "C1", "C1", "A1"] + - ["glycosylation", "glycosylation"] + - ["glyceric acid"] + - ["glycolic acid"] + - ["methylation"] + +"daptomycin": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "D1", "D1", "D1", "D1", "tryptophan", "asparagine", "aspartic acid", "threonine", "glycine", "ornithine", "aspartic acid", "alanine", "aspartic acid", "glycine", "serine", "3-methylglutamic acid", "kynurenine"] + +"dictyostatin": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "C1", "C2", "B2", "B1", "D2", "D2", "B2", "C1", "B1", "B2", "C1", "C1"] + +"discodermolide": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "C1", "C2", "B2", "B2", "D2", "C2", "B2", "C1", "B1", "B2", "B2"] + - ["carbamic acid"] + +"epothilone": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "cysteine", "C2", "B1", "C1", "D1", "D2", "B2", "A3", "B1"] + - ["oxidation"] + +"erythromycin": + default_assembly: 0 + assemblies: + - + - ["propanoic acid starter", "B6", "B2", "A2", "D6", "B2", "B2"] + - ["glycosylation", "methylation"] + - ["glycosylation"] + +"georatusin": + default_assembly: 0 + assemblies: + - + - ["2-methylbutyric acid", "D2", "B2", "D2", "B2", "D2", "A2", "tryptophan"] + +"gephyronic acid": + default_assembly: 0 + assemblies: + - + - ["isobutyric acid", "C2", "C2", "B2", "D2", "A3", "B2", "B1"] + - ["methylation"] + - ["oxidation"] + +"harzianic acid": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "D1", "C1", "C1", "A1", "artificial amino acid harzianic acid"] + - ["methylation"] + +"herboxidiene": + default_assembly: 0 + assemblies: + - + - ["lactic acid", "B2", "C2", "D2", "C1", "C2", "B2", "D1", "C1"] + - ["methylation"] + - ["oxidation"] + +"hydroxystreptomycin": + default_assembly: 0 + assemblies: + - + - ["glycosylation", "glycosylation", "glycosylation", "methylation"] + +"hymenosetin": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "C1", "C2", "C1", "D2", "D1", "C2", "A1", "threonine"] + +"indanomycin": + default_assembly: 0 + assemblies: + - + - ["pyrrole-2-carboxylic acid", "A1", "C1", "D4", "C1", "C1", "C1", "C4", "B2", "D1", "C2"] + +"ircinianin": + default_sequence: + - ["furan-3-carboxylic acid", "D1", "D2", "C1", "C2", "C1", "D2", "D11"] + - ["propanoic acid"] + assemblies: + - + - ["furan-3-carboxylic acid", "D1", "D2", "C1", "C2", "C1", "D2", "D11", "A2"] + +"iriomoteolide 1a": + default_assembly: 0 + assemblies: + - + - ["lactic acid", "D8", "B2", "C1", "D6", "A1", "A8", "B1", "C1", "B2", "A8"] + +"iriomoteolide 3a": + default_assembly: 0 + assemblies: + - + - ["lactic acid", "D8", "B2", "C1", "D6", "A1", "A8", "B1", "C1", "B2", "A8"] + +"jerangolid A": + default_assembly: 0 + assemblies: + - + - ["propanoic acid starter", "C2", "C1", "B2", "C2", "C1", "B1", "A7"] + - ["methylation"] + +"kirromycin": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "C1", "C1", "B3", "B5", "A4", "glycine", "C1", "C2", "B2", "D11", "B5", "C1", "C1", "C2", "A1", "beta-alanine"] + - ["methylation"] + +"lactimidomycin": + default_assembly: 0 + assemblies: + - + - ["2-(2,6-dioxopiperidin-4-yl)acetic acid", "B1", "A2", "C2", "B2", "C1", "C1", "D1", "C1"] + +"lankamycin": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "B2", "B2", "B2", "A6", "D2", "B2", "B2"] + - ["acetic acid", "glycosylation", "methylation"] + - ["glycosylation", "methylation"] + - ["acetic acid"] + +"latrunculin": + default_assembly: 0 + assemblies: + - + - ["cysteine", "A1", "B1", "B1", "D2", "C1", "C1", "D1", "A8"] + - ["carbonic acid"] + +"leiodermatolide": + default_assembly: 0 + assemblies: + - + - ["propanoic acid starter", "B2", "B-beta-carboxymethyl", "C1", "C2", "B2", "C1", "C1", "B2", "B2", "A8", "D1"] + - ["carbamic acid"] + +"lovastatin": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "C1", "C1", "C2", "D5", "C1", "D1", "B1", "B1"] + - ["2-methylbutyric acid"] + +"macrolactin A": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "B1", "D1", "C1", "C1", "B1", "B1", "C1", "C1", "B1", "C1", "C1"] + +"maytansine": + default_assembly: 0 + assemblies: + - + - ["3-amino-5-hydroxybenzoic acid", "D2", "C1", "D11", "A1", "B2", "C2", "B1"] + - ["N-methylalanine"] + - ["acetic acid"] + - ["carbamic acid"] + - ["chlorination"] + - ["methylation"] + - ["methylation"] + - ["methylation"] + - ["oxidation"] + +"megalomycin A": + default_assembly: 0 + assemblies: + - + - ["propanoic acid starter", "B6", "B2", "A2", "D6", "B2", "B2"] + - ["methylation", "glycosylation", "methylation"] + - ["glycosylation"] + - ["glycosylation"] + +"micacocidin A": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "D1", "D1", "C1", "C1", "A1", "cysteine", "cysteine", "B3", "cysteine"] + - ["methylation"] + - ["methylation"] + +"migrastatin": + default_assembly: 0 + assemblies: + - + - ["2-(2,6-dioxopiperidin-4-yl)acetic acid", "D1", "A2", "B2", "C2", "B5", "C1", "D1", "C1"] + - ["methylation"] + +"narbonolide": + default_assembly: 0 + assemblies: + - + - ["propanoic acid starter", "B2", "C1", "A2", "D2", "B2", "A2"] + +"pederin": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "B2", "A8", "A5", "2-hydroxyglycine", "B1", "B3", "C1"] + - ["methanol", "methylation"] + - ["methylation"] + - ["methylation"] + - ["methylation"] + +"peluriside A": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "D7", "C2", "B1", "B1", "B3", "A5", "B1", "B1", "B5"] + - ["methylation"] + - ["methylation"] + - ["methylation"] + +"penicillin G": + default_assembly: 0 + assemblies: + - + - ["2-phenylacetic acid", "cysteine", "valine"] + +"periconiasin A": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "C2", "C1", "D2", "C1", "B1", "A1", "leucine"] + +"periconiasin I": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "C2", "C1", "D2", "C1", "B1", "A1", "leucine"] + - ["oxidation"] + +"ratjadon": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "C1", "B2", "B1", "D11", "C1", "C2", "D2", "C2", "C1", "B1", "C1"] + +"soraphen A": + default_assembly: 0 + assemblies: + - + - ["benzoic acid", "B1", "D1", "D5", "B1", "C2", "B2", "B5", "A2"] + - ["methylation"] + - ["methylation"] + - ["methylation"] + +"spiculoic acid A": + default_assembly: 0 + assemblies: + - + - ["2-phenylacetic acid", "C4", "C4", "C2", "A4", "C4"] + +"spongidepsin": + default_assembly: 0 + assemblies: + - + - ["3-butynoic acid", "D1", "B1", "D8", "D2", "D2", "N-methylphenylalanine"] + +"thailanstatin A": + default_assembly: 0 + assemblies: + - + - ["lactic acid", "C1", "threonine", "D2", "C1", "C2", "C1", "B5", "A8", "C1"] + - ["acetic acid"] + - ["oxidation"] + +"theopederin A": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "B2", "A8", "A5", "2-hydroxyglycine", "B5", "B3", "C1", "B1", "D1"] + - ["formaldehyde"] + - ["methylation"] + - ["methylation"] + +"theopederin B": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "B2", "A8", "A5", "2-hydroxyglycine", "B5", "B3", "C1", "B1", "D1"] + - ["formaldehyde"] + - ["methylation"] + - ["methylation"] + - ["methylation"] + +"thermolide A": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "B1", "B2", "B2", "D2", "B2", "D2", "B1", "B1", "alanine"] + - ["acetic acid"] + +"thiocoraline": + default_assembly: 0 + assemblies: + - + - ["3-hydroxyquinaldic acid", "cysteine", "glycine", "N-methylcysteine", "N-methylcysteine"] + - ["3-hydroxyquinaldic acid", "cysteine", "glycine", "N-methylcysteine", "N-methylcysteine"] + - ["methylation"] + - ["methylation"] + +"zincophorin": + default_assembly: 0 + assemblies: + - + - ["propanoic acid starter", "D2", "C2", "B2", "C1", "D1", "B2", "B2", "B2", "B2", "D1", "C2"] + +"zwittermicin A": + default_assembly: 0 + assemblies: + - + - ["serine", "B1", "B12", "B5", "2,3-diaminopropionate"] + - ["amination"] + - ["carbamic acid"] + +"enterobactin": + default_assembly: 0 + assemblies: + - + - ["2,3-dihydroxybenzoic acid", "serine"] + - ["2,3-dihydroxybenzoic acid", "serine"] + - ["2,3-dihydroxybenzoic acid", "serine"] + +"curvularide C": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "D5", "D2", "B6", "C1", "isoleucinol"] + - ["methylation"] + +"neopeltolide": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "D1", "B1", "B1", "D8", "B1", "B1", "C1"] + - ["glycine", "C1", "serine", "D1", "C1"] + - ["carbonic acid", "methylation"] + - ["methylation"] + +"dihydroxydione": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "cysteine", "C2", "B1", "C2", "D1", "A2", "B2", "propanoic acid starter"] + +"amamistatin B": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "D1", "D1", "D1", "B3", "N6-hydroxylysine"] + - ["salicylic acid", "threonine", "N6-formyl-N6-hydroxylysine"] + +"nocardichelin B": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "D1", "D1", "D1", "D1", "D1", "C1", "N-(5-aminopentyl)hydroxylamine", "butanedioic acid", "N-(5-aminopentyl)hydroxylamine", "serine", "salicylic acid"] + +"borophycin": + default_assembly: 0 + assemblies: + - + - ["propanoic acid starter", "B1", "C1", "D1", "B1", "A3", "B1", "D2", "A5"] + - ["propanoic acid starter", "B1", "C1", "D1", "B1", "A3", "B1", "D2", "A5"] + - ["boronation"] + +"aplasmomycin C": + default_assembly: 0 + assemblies: + - + - ["lactic acid", "B1", "C1", "C1", "B3", "B1", "D2", "A5"] + - ["lactic acid", "B1", "C1", "C1", "B3", "B1", "D2", "A5"] + - ["acetic acid"] + - ["acetic acid"] + - ["boronation"] + +"chaetosemin G": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "B1", "C1", "A2", "A1"] + - ["chlorination"] + +"actinoquinoline B": + default_assembly: 0 + assemblies: + - + - ["3-hydroxyquinaldic acid", "5-hydroxylysine"] + - ["acetic acid starter", "D8"] + +"NRP with intramolecular threonine-cysteine bridges": + default_assembly: 0 + assemblies: + - + - ["glycine", "threonine", "cysteine", "threonine", "valine", "cysteine", "histidine", "tryptophan", "glycine", "tyrosine", "threonine", "isoleucine", "leucine", "cysteine", "aspartic acid", "aspartic acid", "phenylalanine", "serine", "threonine", "arginine", "serine"] + +"vancomycin": + default_assembly: 0 + assemblies: + - + - ["N-methylleucine", "beta-hydroxytyrosine", "asparagine", "4-hydroxyphenylglycine", "4-hydroxyphenylglycine", "beta-hydroxytyrosine", "3,5-dihydroxyphenylglycine"] + - ["glycosylation", "glycosylation"] + - ["chlorination"] + - ["chlorination"] + +"capreomycin IA": + default_assembly: 0 + assemblies: + - + - ["2,3-diaminoacrylic acid", "capreomycidine", "2,3-diaminopropionate", "serine", "2,3-diaminopropionate"] + - ["beta-lysine"] + - ["carbamic acid"] + +"aeruginosin 98-A": + default_assembly: 0 + assemblies: + - + - ["4-hydroxybenzoic acid", "D5", "isoleucine", "2-carboxy-6-hydroxyoctahydroindole", "agmatine"] + - ["chlorination"] + - ["sulfate"] + +"corpeptin A": + default_assembly: 1 + assemblies: + - + - ["3-hydroxydecanoic acid", "dehydrobutyrine", "proline", "alanine", "alanine", "alanine", "valine", "valine", "dehydrobutyrine", "homoserine", "valine", "isoleucine", "dehydroalanine", "alanine", "alanine", "alanine", "valine", "dehydrobutyrine", "threonine", "alanine", "2,4-diaminobytyric acid", "serine", "isoleucine"] + - + - ["acetic acid starter", "D1", "D1", "D1", "B1", "dehydrobutyrine", "proline", "alanine", "alanine", "alanine", "valine", "valine", "dehydrobutyrine", "homoserine", "valine", "isoleucine", "dehydroalanine", "alanine", "alanine", "alanine", "valine", "dehydrobutyrine", "threonine", "alanine", "2,4-diaminobytyric acid", "serine", "isoleucine"] + +"cyanopeptolin 1138": + default_assembly: 0 + assemblies: + - + - ["homotyrosine", "threonine", "homotyrosine", "glutamate-5-semialdehyde", "isoleucine", "N-methylphenylalanine", "isoleucine"] + - ["glyceric acid", "methylation"] + - ["sulfate"] + +"gramicidin": + default_assembly: 0 + assemblies: + - + - ["formic acid", "valine", "glycine", "alanine", "leucine", "alanine", "valine", "valine", "valine", "tryptophan", "leucine", "tryptophan", "leucine", "tryptophan", "leucine", "tryptophan", "ethanolamine"] + +"hormaomycin": + default_assembly: 0 + assemblies: + - + - ["N-hydroxypyrrole-2-carboxylic acid", "3-(2-nitrocyclopropylalanine)", "threonine", "beta-methylphenylalanine", "3-(2-nitrocyclopropylalanine)", "beta-methylphenylalanine", "isoleucine", "4-propenylproline"] + - ["chlorination"] + +"myxochelin A": + default_assembly: 0 + assemblies: + - + - ["2,3-dihydroxybenzoic acid", "lysinol", "2,3-dihydroxybenzoic acid"] + +"marformycin A": + default_assembly: 0 + assemblies: + - + - ["formic acid", "valine", "threonine", "tyrosine", "isoleucine", "piperazic acid", "leucine", "N-methylvaline"] + - ["methylation"] + +"antimycin": + default_assembly: 0 + assemblies: + - + - ["3-formamido-2-hydroxybenzoic acid", "threonine"] + - ["acetic acid starter", "D8"] + - ["lactic acid", "B-alpha-hexyl"] + - + - ["3-formamido-2-hydroxybenzoic acid", "threonine"] + - ["lactic acid", "B-alpha-hexyl"] + - ["3-methylbutanoic acid"] + +"phorbactazole A": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "B1", "B2", "A1", "serine", "C2", "B2", "B1", "C1", "C2", "serine", "B1", "B5", "C1", "B1", "B5", "C1", "B1", "B2", "C1", "C1"] + - ["carbamic acid"] + - ["methylation"] + +"pacidamycin 1": + default_assembly: 0 + assemblies: + - + - ["alanine", "2,3-diaminobutyric acid", "3'-deoxy-4',5'-enamino-uridine"] + - ["alanine", "meta-tyrosine"] + - ["carbonic acid"] + - ["methylation"] + - ["tryptophan"] + +"napsamycin C": + default_assembly: 0 + assemblies: + - + - ["homocysteine", "2,3-diaminobutyric acid", "3'-deoxy-4',5'-enamino-dihydrouridine"] + - ["6-hydroxy-tetrahydro-isoquinoline-3-carboxylic acid"] + - ["carbonic acid"] + - ["meta-tyrosine"] + - ["methylation"] + - ["methylation"] + +"napsamycin B": + default_assembly: 0 + assemblies: + - + - ["homocysteine", "2,3-diaminobutyric acid", "3'-deoxy-4',5'-enamino-uridine"] + - ["1-methyl-6-hydroxy-tetrahydroisoquinoline-3-carboxylic acid"] + - ["carbonic acid"] + - ["meta-tyrosine"] + - ["methylation"] + - ["methylation"] + +"sansanmycin C": + default_assembly: 0 + assemblies: + - + - ["methionine sulfoxide", "2,3-diaminobutyric acid", "3'-deoxy-4',5'-enamino-uridine"] + - ["carbonic acid"] + - ["meta-tyrosine"] + - ["methylation"] + - ["tryptophan"] + +"sansanmycin K": + default_assembly: 0 + assemblies: + - + - ["homocysteine", "2,3-diaminobutyric acid", "3'-deoxy-4',5'-enamino-uridine"] + - ["8-hydroxy-tetrahydroisoquinoline-3-carboxylic acid"] + - ["carbonic acid"] + - ["methylation"] + - ["methylation"] + - ["tyrosine"] + +"tenuazonic acid": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "A1", "isoleucine"] + +"epifadin": + default_assembly: 0 + assemblies: + - + - ["phenylalanine", "phenylalanine", "aspartic acid", "asparagine", "alanine", "C1", "C1", "C1", "C1", "D1", "D1", "D1", "C1", "A1", "aspartic acid"] + +"tubulysin A": + default_assembly: 0 + assemblies: + - + - ["N-methylpipecolic acid", "isoleucine", "valine", "D5", "cysteine", "tyrosine", "D2"] + - ["acetic acid starter", "D8"] + - ["acetic acid"] + - ["formaldehyde"] + +"actinomycin D": + default_assembly: 0 + assemblies: + - + - ["N-methylvaline", "sarcosine", "proline", "valine", "threonine", "4-methyl-3-hydroxyanthranilic acid", "4-methyl-3-hydroxyanthranilic acid", "threonine", "valine", "proline", "sarcosine", "N-methylvaline"] + +"tenellin": + default_assembly: 0 + assemblies: + - + - ["2-methylbutyric acid", "C2", "C1", "A1", "tyrosine"] + - ["oxidation"] + +"disorazole Z9": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "C1", "B2-alpha-carboxy", "B1", "C1", "C1", "C1", "serine"] + - ["acetic acid starter", "C1", "B2-alpha-hydroxymethyl", "B1", "C1", "C1", "C1", "serine"] + +"Ristocetin B": + default_assembly: 0 + assemblies: + - + - ["4-hydroxyphenylglycine", "beta-hydroxytyrosine", "4-methyl-3,5-dihydroxyphenylglycine", "4-hydroxyphenylglycine", "4-hydroxyphenylglycine", "beta-hydroxytyrosine", "3,5-dihydroxyphenylglycine"] + - ["glycosylation", "glycosylation"] + - ["glycosylation"] + - ["glycosylation"] + - ["methylation"] + +"suomilide": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "D1", "D1"] + - ["acetic acid starter", "D1", "D1"] + - ["isoleucine", "hydrolyzed suomilide Abn", "Aeap"] + - ["glyceric acid", "methylation"] + - ["carbonic acid"] + - ["glycosylation"] + - ["sulfate"] + +"3,6-dialkyl-α-pyrone": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "C1", "A1", "A4"] + +"heterobactin S2": + default_assembly: 0 + assemblies: + - + - ["2,3-dihydroxy-4-(methylsulfonyl)benzoic acid", "A", "glycine", "N5-hydroxyornithine"] + +"bleomycin A2": + default_assembly: 0 + assemblies: + - + - ["3-hydroxy histdine", "alanine", "B2", "threonine", "beta-alanine", "cysteine", "cysteine", "3-aminopropyl-dimethylsulfonium"] + - ["carbamic acid", "glycosylation", "glycosylation"] + - ["amination"] + +"monensin": + default_assembly: 0 + assemblies: + - + - ["glycolic acid", "A2", "D2", "A1", "D2", "A4", "D1", "A2", "D1", "A1", "B2", "B2", "B2"] + - ["methylation"] + +"rapamycin": + default_assembly: 0 + assemblies: + - + - ["3,4-dihydroxycyclohexanecarboxylic acid", "D2", "B1", "A2", "C2", "B5", "A2", "D2", "C1", "C1", "C2", "B1", "B1", "D2", "A1-alpha-oxo", "pipecolic acid"] + - ["methylation"] + - ["methylation"] + - ["methylation"] + +"Basiliskamide A": + default_assembly: 0 + assemblies: + - + - ["2-methylbutyric acid", "B2", "B1", "C1", "C1"] + - ["amination"] + - ["cinnamic acid"] + +"epipyriculol": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "C1", "B5", "C1", "C1", "C1", "A1"] + +"kijanimicin": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "C7", "C1", "C2", "B1", "C2", "C1", "C1", "B2", "D2", "C2", "A1"] + - ["glycosylation", "glycosylation", "glycosylation", "methylation"] + - ["glycosylation", "carbonic acid", "methylation"] + - ["glyceric acid"] + - ["glycosylation"] + +"rubradirin": + default_assembly: 0 + assemblies: + - + - ["glycosylation", "methylation"] + - ["methylation"] + +"4-hexadecanoyl-3-hydroxy-2-(hydroxymethyl)-2H-furan-5-one": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "D1", "D1", "D1", "D1", "D1", "D1", "D1", "A1"] + - ["glyceric acid"] + +"granaticin": + default_assembly: 0 + assemblies: + - + - ["C1"] + +"actinospirol A": + default_assembly: 0 + assemblies: + - + - ["fumaric acid", "C1", "A1", "A1-alpha-oxo", "C1", "A8", "A1"] + - ["chlorination"] + +"acyltetronate diketo tautomer": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "D1", "D1", "D1", "D1", "D1", "D1", "D1", "A1"] + - ["glyceric acid"] + +"PK shifted alkene donor H0": + default_assembly: 0 + assemblies: + - + - ["isobutyric acid", "C1"] + +"PK shifted alkene donor H1": + default_assembly: 0 + assemblies: + - + - ["propanoic acid starter", "C1"] + +"PK shifted alkene donor H2": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "C1"] + +"stambomycin A": + default_assembly: 0 + assemblies: + - + - ["lactic acid", "C1", "B1", "B1", "D1", "B2", "B1", "D2", "B1", "B1", "D8", "D5", "B-alpha-(4-methylhexyl)", "C2", "B1", "B1", "D1", "B2", "B1", "C1", "C2", "B2", "B1", "B2", "A1"] + - ["methylation", "glycosylation", "methylation"] + +"stambomycin B": + default_assembly: 0 + assemblies: + - + - ["lactic acid", "C1", "B1", "B1", "D1", "B2", "B1", "D2", "B1", "B1", "D8", "D5", "B-alpha-(5-methylhexyl)", "C2", "B1", "B1", "D1", "B2", "B1", "C1", "C2", "B2", "B1", "B2", "A1"] + - ["methylation", "glycosylation", "methylation"] + +"stambomycin C": + default_assembly: 0 + assemblies: + - + - ["lactic acid", "C1", "B1", "B1", "D1", "B2", "B1", "D2", "B1", "B1", "D8", "D5", "B-alpha-(4-methylpentyl)", "C2", "B1", "B1", "D1", "B2", "B1", "C1", "C2", "B2", "B1", "B2", "A1"] + - ["methylation", "glycosylation", "methylation"] + +"stambomycin D": + default_assembly: 0 + assemblies: + - + - ["lactic acid", "C1", "B1", "B1", "D1", "B2", "B1", "D2", "B1", "B1", "D8", "D5", "B-alpha-hexyl", "C2", "B1", "B1", "D1", "B2", "B1", "C1", "C2", "B2", "B1", "B2", "A1"] + - ["methylation", "glycosylation", "methylation"] + +"filipin": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "B5", "C1", "C1", "C1", "C1", "C2", "B1", "B1", "B1", "B1", "B1", "B1", "B-alpha-(1-hydroxyhexyl)"] + +"splenocin C": + default_assembly: 0 + assemblies: + - + - ["3-formamido-2-hydroxybenzoic acid", "threonine"] + - ["lactic acid", "B-alpha-benzyl"] + - ["2-methylbutyric acid"] + +"solanapyrone D": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "C1", "C1", "D1", "D1", "C1", "A1", "A-alpha-carboxyl"] + - ["methylation"] + +"emodin": + default_sequence: + - ["acetic acid starter", "A1", "A1", "C1", "A1", "A1", "A1", "A1"] + - ["oxidation"] + assemblies: + - + - ["acetic acid starter", "A1", "A1", "A1", "A1", "A1", "A1", "A1"] + - ["oxidation"] + +"endocrocin": + default_sequence: + - ["acetic acid starter", "C1", "A1-alpha-oxo", "C1", "A1", "A1", "A1", "A1"] + assemblies: + - + - ["acetic acid starter", "A1", "A1", "A1", "A1", "A1", "A1", "A1"] + - ["oxidation"] + +"aclacinomycin": + default_sequence: + - ["A1", "A1", "A1", "C1", "C1", "A1-alpha-oxo", "C1", "malonic acid", "B1", "propanoic acid starter"] + - ["glycosylation", "glycosylation", "glycosylation", "methylation"] + - ["methylation"] + - ["methylation"] + known_starter_order_issue: "A default path places its only starter after another unit; backbone direction or separation remains unresolved." + assemblies: + - + - ["propanoic acid starter", "A1", "A1", "A1", "A1", "A1", "C1", "C1", "C1", "A1"] + - ["glycosylation", "glycosylation", "glycosylation", "methylation"] + - ["methylation"] + - ["methylation"] + - ["oxidation"] + +"daunorubicin": + default_sequence: + - ["pyruvic acid", "A1", "A1", "A1", "A1", "A1", "C1", "C1", "A5", "C1"] + - ["glycosylation"] + - ["methylation"] + - ["oxidation"] + assemblies: + - + - ["pyruvic acid", "A1", "A1", "A1", "A1", "A1", "C1", "C1", "D11", "A1"] + - ["glycosylation"] + - ["methylation"] + - ["oxidation"] + +"doxorubicin": + default_sequence: + - ["hydroxypyruvic acid", "A1", "A1", "A1", "A1", "A1", "C1", "C1", "A5", "C1"] + - ["glycosylation"] + - ["methylation"] + - ["oxidation"] + assemblies: + - + - ["hydroxypyruvic acid", "A1", "A1", "A1", "A1", "A1", "C1", "C1", "D11", "A1"] + - ["glycosylation"] + - ["methylation"] + - ["oxidation"] + +"rhodomycin": + default_sequence: + - ["propanoic acid starter", "A1", "A1", "A1", "A1", "A1", "C1", "C1", "A5", "C1"] + - ["methylation", "glycosylation", "methylation"] + - ["methylation", "glycosylation", "methylation"] + - ["oxidation"] + - ["oxidation"] + assemblies: + - + - ["propanoic acid starter", "A1", "A1", "A1", "A1", "A1", "C1", "C1", "D11", "A1"] + - ["methylation", "glycosylation", "methylation"] + - ["methylation", "glycosylation", "methylation"] + - ["oxidation"] + - ["oxidation"] + +"nogalaviketone": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "A1", "A1", "A1", "A1", "A1", "C1", "C1", "C1", "A1"] + - ["methylation"] + - ["oxidation"] + +"14-hydroxyisochainin": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "B5", "C1", "C1", "C1", "C1", "C2", "B5", "B1", "B1", "B1", "B1", "B1", "B-alpha-butyl"] + +"PK aldol ring donor H0": + default_assembly: 0 + assemblies: + - + - ["isobutyric acid", "A1", "D1", "A1"] + +"PK aldol ring donor H1": + default_sequence: + - ["D1", "propanoic acid starter", "A1", "malonic acid"] + known_starter_order_issue: "A default path places its only starter after another unit; backbone direction or separation remains unresolved." + assemblies: + - + - ["propanoic acid starter", "A1", "D1", "A1"] + +"PK aldol ring donor H2": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "A1", "D1", "A1"] + +"PK pentyl-branched beta-hydroxy chain": + default_assembly: 0 + assemblies: + - + - ["propanoic acid starter", "B-alpha-pentyl"] + +"anthraquinone without peri hydroxyls": + default_assembly: 0 + assemblies: + - [] + +"cylindrocyclophane F": + default_sequence: + - ["A1", "A1", "A1", "D8", "D1", "D1", "D1", "A1", "A1", "A1", "D8", "D1", "D1", "D1", "D1", "acetic acid starter"] + - ["acetic acid starter", "D1"] + known_starter_order_issue: "A default path places its only starter after another unit; backbone direction or separation remains unresolved." + assemblies: + - + - ["A1", "A1", "A1", "decanoic acid", "D8", "A1", "A1", "A1", "decanoic acid", "D8"] + +"carbamidocyclophane A": + default_sequence: + - ["A1", "A1", "A1", "D10", "D1", "D1", "D1", "A1", "A1", "A1", "D10", "D1", "D1", "D1", "D1", "acetic acid starter"] + - ["acetic acid starter", "D1"] + - ["carbamic acid"] + - ["carbamic acid"] + - ["chlorination"] + - ["chlorination"] + - ["chlorination"] + - ["chlorination"] + known_starter_order_issue: "A default path places its only starter after another unit; backbone direction or separation remains unresolved." + assemblies: + - + - ["A1", "A1", "A1", "D10", "decanoic acid", "A1", "A1", "A1", "D10", "decanoic acid"] + - ["carbamic acid"] + - ["carbamic acid"] + - ["chlorination"] + - ["chlorination"] + - ["chlorination"] + - ["chlorination"] + +"geldanamycin": + default_assembly: 0 + assemblies: + - + - ["3-amino-5-hydroxybenzoic acid", "D2", "D5", "B2", "C2", "B5", "C1", "C2"] + - ["methylation", "oxidation"] + - ["carbamic acid"] + - ["methylation"] + - ["methylation"] + - ["oxidation"] + +"herbimycin A": + default_assembly: 0 + assemblies: + - + - ["3-amino-5-hydroxybenzoic acid", "B2", "D5", "B2", "C2", "B5", "C1", "C2"] + - ["carbamic acid"] + - ["methylation"] + - ["methylation"] + - ["methylation"] + - ["methylation"] + - ["oxidation"] + +"macbecin II": + default_assembly: 0 + assemblies: + - + - ["3-amino-5-hydroxybenzoic acid", "B2", "D5", "B2", "C2", "B2", "C1", "C2"] + - ["carbamic acid"] + - ["methylation"] + - ["methylation"] + - ["methylation"] + - ["oxidation"] + +"orcinol": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "A1", "A1", "A1"] + +"1,3,6,8-tetrahydroxynaphthalene": + default_sequence: + - ["acetic acid starter", "C1", "A1", "A1", "A1"] + assemblies: + - + - ["acetic acid starter", "A1", "A1", "A1", "A1"] + +"flaviolin": + default_sequence: + - ["acetic acid starter", "C1", "A1", "A1", "A1"] + - ["oxidation"] + assemblies: + - + - ["acetic acid starter", "A1", "A1", "A1", "A1"] + - ["oxidation"] + +"alternariol": + default_sequence: + - ["acetic acid starter", "C1", "A1", "A1", "A1", "A1", "A1"] + assemblies: + - + - ["acetic acid starter", "A1", "A1", "A1", "A1", "A1", "A1"] + +"nidulin": + default_sequence: + - ["acetic acid starter", "C2", "A1", "A2", "A1", "A1", "A1", "C1", "acetic acid starter"] + - ["chlorination"] + - ["chlorination"] + - ["chlorination"] + - ["methylation"] + assemblies: + - + - ["acetic acid starter", "C2", "A1", "A2", "A1", "A1", "A1", "A1", "acetic acid starter"] + - ["chlorination"] + - ["chlorination"] + - ["chlorination"] + - ["methylation"] + +"agonodepside A": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "C2", "A1", "A2", "A1"] + - ["acetic acid starter", "C2", "C1", "A2", "A1"] + +"resorcinol without a carbon substituent": + default_assembly: 0 + assemblies: + - [] + +"monohydroxynaphthalene": + default_assembly: 0 + assemblies: + - [] + +"naphthoquinone without peri hydroxyls": + default_assembly: 0 + assemblies: + - [] diff --git a/tests/data/integration_retromol_stereochemistry_readouts.yml b/tests/data/integration_retromol_stereochemistry_readouts.yml new file mode 100644 index 0000000..4eb5158 --- /dev/null +++ b/tests/data/integration_retromol_stereochemistry_readouts.yml @@ -0,0 +1,13 @@ +# Fixed regression readouts of the current structural parsing policy. +# These are not a claim of biological correctness for every cyclic/branched case. +# "assemblies" follows the entry order in the corresponding *_assemblies.yml. +# "default_assembly" is a zero-based reference; "default_sequence" covers a +# default decomposition not represented by those required assembly fixtures. +# Known starter-order limitations have separate strict expected-failure tests. + +"ring-opened Z double bond (small-ring C1 unit)": + default_assembly: 0 + assemblies: + - + - ["acetic acid starter", "D1", "B^S1", "B^R1", "D^R8", "B^R1", "B^R1", "C^Z1"] + - ["methylation"] diff --git a/tests/helpers_retromol.py b/tests/helpers_retromol.py index 2ae9b5f..4353322 100644 --- a/tests/helpers_retromol.py +++ b/tests/helpers_retromol.py @@ -1,6 +1,8 @@ """Shared helpers for RetroMol integration tests.""" +from collections import Counter from dataclasses import dataclass +import json from pathlib import Path from typing import Sequence @@ -10,8 +12,10 @@ from retromol.model.assembly_graph import AssemblyGraph from retromol.model.rules import RuleSet from retromol.model.result import Result +from retromol.model.readout import LinearReadout from retromol.model.submission import Submission from retromol.pipelines.parsing import run_retromol_with_timeout +from retromol_fingerprint.fingerprint import TOKEN_LINK def load_rule_set() -> RuleSet: @@ -93,6 +97,85 @@ def load_expected_assemblies(path: Path) -> dict[str, tuple[ExpectedAssembly, .. return expectations +SequenceParts = tuple[tuple[str, ...], ...] + + +@dataclass(frozen=True) +class ExpectedReadouts: + """Fixed default sequence and one sequence per required assembly graph.""" + + default: SequenceParts + assemblies: tuple[SequenceParts, ...] + known_starter_order_issue: str | None = None + + +def load_expected_readouts( + path: Path, assemblies: dict[str, tuple[ExpectedAssembly, ...]], +) -> dict[str, ExpectedReadouts]: + """Validate readout fixtures against the independently specified graphs.""" + raw = yaml.safe_load(path.read_text()) + if not isinstance(raw, dict) or set(raw) != set(assemblies): + raise ValueError("Readout fixtures must cover exactly the assembly compound set") + + def parts(value) -> SequenceParts: + if not isinstance(value, list) or any( + not isinstance(part, list) or not part + or any(not isinstance(name, str) or not name for name in part) + for part in value + ): + raise ValueError("A readout must be a list of nonempty named paths (or [] if unidentified)") + return tuple(tuple(part) for part in value) + + expectations = {} + for name, data in raw.items(): + if not isinstance(data, dict) or set(data) - { + "assemblies", "default_assembly", "default_sequence", "known_starter_order_issue", + }: + raise ValueError(f"{name}: invalid readout fields") + sequences = data.get("assemblies") + if not isinstance(sequences, list) or len(sequences) != len(assemblies[name]): + raise ValueError(f"{name}: provide one readout for every expected assembly") + sequences = tuple(parts(sequence) for sequence in sequences) + for index, (sequence, graph) in enumerate(zip(sequences, assemblies[name])): + if Counter(token for part in sequence for token in part) != Counter( + label for label, _ in graph.nodes if label is not None + ): + raise ValueError(f"{name} assembly {index}: readout must include every identified unit exactly once") + if ("default_assembly" in data) == ("default_sequence" in data): + raise ValueError(f"{name}: choose either default_assembly or default_sequence") + if "default_assembly" in data: + index = data["default_assembly"] + if type(index) is not int or not 0 <= index < len(sequences): + raise ValueError(f"{name}: invalid default assembly index") + default = sequences[index] + else: + default = parts(data["default_sequence"]) + issue = data.get("known_starter_order_issue") + if issue is not None and (not isinstance(issue, str) or not issue.strip()): + raise ValueError(f"{name}: known starter-order issue must have a reason") + expectations[name] = ExpectedReadouts(default, sequences, issue) + return expectations + + +def assert_linear_readout(assembly: AssemblyGraph, expected: SequenceParts) -> None: + """Check exact direction, part boundaries, multiplicity, flat export and reload.""" + before = assembly.to_dict() + readout = LinearReadout.from_assembly_graph(assembly) + assert readout.primary_sequence_parts() == [list(part) for part in expected], "Wrong linear readout" + flat = [] + for part in expected: + if flat: + flat.append(TOKEN_LINK) + flat.extend(part) + assert readout.primary_sequence() == flat, "Wrong flat sequence readout" + actual = [node.enc for part in readout.paths for node in part] + identified = {node.enc for node in assembly.monomer_nodes() if node.is_identified} + assert len(actual) == len(set(actual)) and set(actual) == identified, "Missing or repeated readout units" + assert assembly.to_dict() == before, "Readout changed the assembly" + restored = AssemblyGraph.from_dict(json.loads(json.dumps(before))) + assert LinearReadout.from_assembly_graph(restored).primary_sequence_parts() == [list(part) for part in expected] + + def assembly_comparison_graph(result: Result, assembly: AssemblyGraph) -> nx.Graph: """Keep labels, original atom counts and connectivity, excluding empty nodes. @@ -136,6 +219,7 @@ def assert_assemblies( expected: Sequence[ExpectedAssembly], *, coverage_tolerance: float = 1e-2, + expected_readouts: Sequence[SequenceParts] | None = None, ) -> None: """Require EVERY expected graph to occur among the valid parsed assemblies. @@ -145,6 +229,8 @@ def assert_assemblies( """ if not expected: raise ValueError("At least one expected assembly graph is required") + if expected_readouts is not None and len(expected_readouts) != len(expected): + raise ValueError("Provide one readout for every expected assembly graph") unmatched = {index: (fixture, fixture.graph()) for index, fixture in enumerate(expected, start=1)} space = result.assembly_space() @@ -152,6 +238,7 @@ def assert_assemblies( min_coverage=max(0.0, min(alternative.coverage for alternative in expected) - coverage_tolerance), ) diagnostics = [] + readout_mismatches = [] node_match = nx.algorithms.isomorphism.categorical_node_match( ["name", "heavy_atoms"], [None, None], ) @@ -164,6 +251,14 @@ def assert_assemblies( if abs(coverage - fixture.coverage) > coverage_tolerance: continue if nx.is_isomorphic(actual_graph, expected_graph, node_match=node_match, edge_match=edge_match): + if expected_readouts is not None: + sequence = expected_readouts[index - 1] + actual = LinearReadout.from_assembly_graph(assembly).primary_sequence_parts() + if actual != [list(part) for part in sequence]: + if len(readout_mismatches) < 5: + readout_mismatches.append(f"#{index}: expected {sequence!r}; actual {actual!r}") + continue + assert_linear_readout(assembly, sequence) del unmatched[index] if not unmatched: return @@ -180,4 +275,6 @@ def assert_assemblies( + f"\nParsed {len(space.frontiers)} valid assemblies; {len(frontiers)} meet the coverage lower bound." + f" Maximum coverage: {space.max_coverage:.6f}.\nFirst candidates (at most 5):\n " + "\n ".join(diagnostics) + + ("\nMatching graphs with wrong readouts:\n " + "\n ".join(readout_mismatches) + if readout_mismatches else "") ) diff --git a/tests/test_integration_readout.py b/tests/test_integration_readout.py index f7d38b0..872cbaf 100644 --- a/tests/test_integration_readout.py +++ b/tests/test_integration_readout.py @@ -33,6 +33,40 @@ READOUT_CASES = [ + pytest.param( + dict(ASSEMBLY_CASES)['actinoquinoline B'], + [['3-hydroxyquinaldic acid', '5-hydroxylysine'], ['acetic acid starter', 'D8']], + [['3-hydroxyquinaldic acid', '5-hydroxylysine'], ['acetic acid starter', 'D8']], + id='actinoquinoline-B', + ), + pytest.param( + dict(ASSEMBLY_CASES)['chaetoglobosin A'], + [['acetic acid starter', 'C2', 'C1', 'C1', 'D2', 'C2', 'B11', 'C1', 'A1', 'tryptophan'], + ['oxidation']], + [['acetic acid starter', 'C2', 'C1', 'C^E1', 'D2^R', 'C^E2', 'B11', 'C^E1', 'A1', 'tryptophan^L'], + ['oxidation']], + id='chaetoglobosin-A', + ), + pytest.param( + dict(ASSEMBLY_CASES)['chlorothricin'], + [['acetic acid starter', 'C13', 'C1', 'C1', 'D1', 'D1', 'C1', 'C1', 'B1', 'D1', 'C1'], + ['acetic acid starter', 'C1', 'C1', 'A1'], + ['glycosylation', 'glycosylation'], ['chlorination'], ['glyceric acid'], + ['glycolic acid'], ['methylation']], + [['acetic acid starter', 'C13', 'C1', 'C1', 'D1', 'D1', 'C1', 'C1', 'B^R1', 'D1', 'C1'], + ['acetic acid starter', 'C1', 'C1', 'A1'], + ['glycosylation', 'glycosylation'], ['chlorination'], ['glyceric acid'], + ['glycolic acid'], ['methylation']], + id='chlorothricin', + ), + pytest.param( + dict(ASSEMBLY_CASES)['cremimycin'], + [['propanoic acid starter', 'D1', 'D1', 'A', 'A1', 'D1', 'B1', 'A1', 'B1', 'C1', 'C2', 'C1', 'C1'], + ['methylation', 'glycosylation', 'oxidation']], + [['propanoic acid starter', 'D1', 'D1', 'A', 'A1', 'D1', 'B1', 'A1', 'B1', 'C1', 'C^E2', 'C^Z1', 'C^Z1'], + ['methylation', 'glycosylation', 'oxidation']], + id='cremimycin', + ), pytest.param( dict(ASSEMBLY_CASES)['enterobactin'], [['2,3-dihydroxybenzoic acid', 'serine'], diff --git a/tests/test_integration_retromol.py b/tests/test_integration_retromol.py index 4343d87..2ca9f7e 100644 --- a/tests/test_integration_retromol.py +++ b/tests/test_integration_retromol.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- -"""Compare parsed assemblies with explicit graph expectations for demo compounds.""" +"""Compare demo compounds with fixed graph and ordered readout expectations.""" from pathlib import Path @@ -10,7 +10,10 @@ from retromol.model.rules import RuleSet from .data.integration_retromol import CASES -from .helpers_retromol import assert_assemblies, load_expected_assemblies, parse_compound +from .helpers_retromol import ( + assert_assemblies, assert_linear_readout, load_expected_assemblies, + load_expected_readouts, parse_compound, +) # Disable RDKit warnings for cleaner test output @@ -19,14 +22,41 @@ EXPECTED_ASSEMBLIES = load_expected_assemblies( Path(__file__).parent / "data" / "integration_retromol_assemblies.yml" ) +EXPECTED_READOUTS = load_expected_readouts( + Path(__file__).parent / "data" / "integration_retromol_readouts.yml", EXPECTED_ASSEMBLIES, +) def test_assembly_fixtures_match_compound_cases() -> None: assert set(EXPECTED_ASSEMBLIES) == {name for name, _ in CASES} + assert set(EXPECTED_READOUTS) == set(EXPECTED_ASSEMBLIES) @pytest.mark.parametrize("name, smiles", CASES, ids=[c[0] for c in CASES]) def test_integration_demo_set(name: str, smiles: str, ruleset: RuleSet) -> None: - """Every expected graph must occur among the valid parsed assemblies.""" + """Every required graph must have its sequence; also check the default view.""" + result = parse_compound(smiles, ruleset) + readouts = EXPECTED_READOUTS[name] + assert_assemblies(result, EXPECTED_ASSEMBLIES[name], expected_readouts=readouts.assemblies) + assert_linear_readout(result.assembly_graph, readouts.default) + assert result.linear_readout.primary_sequence_parts() == [list(part) for part in readouts.default] + + +@pytest.mark.parametrize("name, smiles", [ + pytest.param(name, smiles, id=name, marks=pytest.mark.xfail( + strict=True, raises=AssertionError, reason=EXPECTED_READOUTS[name].known_starter_order_issue, + )) + for name, smiles in CASES if EXPECTED_READOUTS[name].known_starter_order_issue +]) +def test_known_backbone_starter_order(name, smiles, ruleset): + """Keep known ordering errors visible independently of compatibility snapshots. + + These checks express the desired property, not the current faulty order. + A fix must remove its expected-failure mark and update the corresponding + regression fixture; strict XPASS prevents leaving a fixed issue hidden. + """ result = parse_compound(smiles, ruleset) - assert_assemblies(result, EXPECTED_ASSEMBLIES[name]) + paths = result.linear_readout.primary_sequence_parts() + single_starter_paths = [part for part in paths if sum(token.endswith(' starter') for token in part) == 1] + assert single_starter_paths, f"{name}: the starter disappeared from the readout" + assert all(part[0].endswith(' starter') for part in single_starter_paths), paths diff --git a/tests/test_integration_retromol_stereochemistry.py b/tests/test_integration_retromol_stereochemistry.py index 0fc2e53..84d4871 100644 --- a/tests/test_integration_retromol_stereochemistry.py +++ b/tests/test_integration_retromol_stereochemistry.py @@ -10,7 +10,10 @@ from retromol.model.rules import RuleSet from .data.integration_retromol_stereochemistry import CASES -from .helpers_retromol import assert_assemblies, load_expected_assemblies, parse_compound +from .helpers_retromol import ( + assert_assemblies, assert_linear_readout, load_expected_assemblies, + load_expected_readouts, parse_compound, +) # Disable RDKit warnings for cleaner test output @@ -19,10 +22,14 @@ EXPECTED_ASSEMBLIES = load_expected_assemblies( Path(__file__).parent / "data" / "integration_retromol_stereochemistry_assemblies.yml" ) +EXPECTED_READOUTS = load_expected_readouts( + Path(__file__).parent / "data" / "integration_retromol_stereochemistry_readouts.yml", EXPECTED_ASSEMBLIES, +) def test_stereo_assembly_fixtures_match_compound_cases() -> None: assert set(EXPECTED_ASSEMBLIES) == {name for name, _ in CASES} + assert set(EXPECTED_READOUTS) == set(EXPECTED_ASSEMBLIES) @pytest.mark.parametrize("name, smiles", CASES, ids=[c[0] for c in CASES]) @@ -31,6 +38,9 @@ def test_integration_stereochemistry_set( smiles: str, stereo_ruleset: RuleSet, ) -> None: - """Graph matching preserves stereo-qualified identities such as C^Z1.""" + """Graphs and ordered sequences preserve stereo-qualified identities such as C^Z1.""" result = parse_compound(smiles, stereo_ruleset) - assert_assemblies(result, EXPECTED_ASSEMBLIES[name]) + readouts = EXPECTED_READOUTS[name] + assert_assemblies(result, EXPECTED_ASSEMBLIES[name], expected_readouts=readouts.assemblies) + assert_linear_readout(result.assembly_graph, readouts.default) + assert result.linear_readout.primary_sequence_parts() == [list(part) for part in readouts.default] diff --git a/tests/test_readout.py b/tests/test_readout.py index f1caf7b..9867983 100644 --- a/tests/test_readout.py +++ b/tests/test_readout.py @@ -12,7 +12,10 @@ from retromol.model.assembly_graph import AssemblyGraph, RootBondLink from retromol.model.identity import MolIdentity from retromol.model.reaction_graph import MolNode -from retromol.model.readout import LinearReadout, _backbone_entry_tags, assembly_to_primary_sequence, split_named_paths +from retromol.model.readout import ( + LinearReadout, _backbone_entry_tags, _connected_backbone_order, + assembly_to_primary_sequence, split_named_paths, +) from retromol.model.result import Result from retromol.model.rules import MatchingRule, RuleSet from retromol.model.submission import Submission @@ -282,13 +285,27 @@ def test_carboxyl_direction_does_not_reorient_tailoring_paths(ruleset): assert result.linear_readout.primary_sequence_parts() == [['alanine', 'glycine']] -def test_converging_carboxyl_links_do_not_invent_a_direction(ruleset): - # Gly and Ala both donate to Lys (backbone N and side-chain N respectively). - # The undirected path has no consistent N-to-C traversal through all three. - result = run_retromol(Submission('NCC(=O)NC(CCCCNC(=O)C(N)C)C(=O)O'), ruleset) - expected = [[node.identity.name for node in result.assembly_graph.longest_path()]] +@pytest.mark.parametrize('explicit_roles', [False, True]) +@pytest.mark.parametrize('smiles, expected', [ + # Gly enters the backbone N; Ala acylates the side-chain N. + ('NCC(=O)NC(CCCCNC(=O)C(N)C)C(=O)O', [['glycine', 'lysine'], ['alanine']]), + # Exchanging the acyl donors must exchange their roles in the readout. + ('CC(N)C(=O)NC(CCCCNC(=O)CN)C(=O)O', [['alanine', 'lysine'], ['glycine']]), + # A side-chain amide alone is insufficient evidence to split a path. + ('NC(CCCCNC(=O)C(N)C)C(=O)O', [['alanine', 'lysine']]), +]) +def test_side_chain_amides_compete_with_connected_backbone_entries(smiles, expected, explicit_roles, ruleset): + if explicit_roles: + ruleset = replace(ruleset, matching_rules=[ + replace(rule, sequence_role='backbone') if rule.name in ('glycine', 'alanine', 'lysine') else rule + for rule in ruleset.matching_rules + ]) + result = run_retromol(Submission(smiles), ruleset) + before = result.assembly_graph.to_dict() assert result.linear_readout.primary_sequence_parts() == expected - assert len(expected[0]) == 3 + assert result.assembly_graph.to_dict() == before + restored = AssemblyGraph.from_dict(json.loads(json.dumps(before))) + assert assembly_to_primary_sequence(restored) == expected def test_cyclic_peptide_preserves_conventional_start_and_carboxyl_direction(ruleset): @@ -300,6 +317,68 @@ def test_cyclic_peptide_preserves_conventional_start_and_carboxyl_direction(rule assert restored.primary_sequence_parts() == readout.primary_sequence_parts() +def crosslinked_capped_chain(): + """A source, two capped units and an amino acid, with competing ring bonds.""" + g = nx.Graph() + for index, (name, smiles) in enumerate([ + ('z-source', '[1CH3]C(=O)O'), + ('b-unit', '[2CH2](SO)[3CH2]C(=O)O'), + ('a-unit', '[4CH2](SO)[5CH2]C(=O)O'), + ('c-end', '[6NH2][7CH]([8CH3])[9C](=[10O])[11OH]'), + ]): + mol = smiles_to_mol(smiles) + identity = MolIdentity(MatchingRule(name, smiles, {}, [], sequence_role='backbone')) + node = MolNode(f'unit-{index}', mol, smiles, identity, True) + g.add_node(index, molnode=node, identity=identity, + tags={atom.GetIsotope() for atom in mol.GetAtoms() if atom.GetIsotope()}) + for u, v, a, b, symbol in [ + (0, 1, 1, 2, 'C'), (1, 2, 3, 4, 'C'), (2, 3, 5, 6, 'N'), + (3, 1, 9, 2, 'C'), # Ring closure into an already connected entry. + (1, 3, 3, 6, 'N'), # Exit-to-entry shortcut that skips a unit. + ]: + bond = RootBondLink(a - 1, b - 1, a, b, 'C', symbol, 'SINGLE', 1.0) + if g.has_edge(u, v): + g[u][v]['bonds'].append(bond) + g[u][v]['n_bonds'] += 1 + else: + g.add_edge(u, v, bonds=[bond], n_bonds=1) + return AssemblyGraph(g) + + +def test_entry_exit_connections_select_order_before_undirected_crosslinks(): + a = crosslinked_capped_chain() + before = a.to_dict() + expected = [['z-source', 'b-unit', 'a-unit', 'c-end']] + assert assembly_to_primary_sequence(a) == expected + # This connected path takes a ring shortcut; neither orientation is correct. + saved = LinearReadout(a, [[a.g.nodes[i]['molnode'] for i in (0, 1, 3, 2)]]) + assert saved.primary_sequence_parts() == expected + assert LinearReadout.from_dict(saved.to_dict()).primary_sequence_parts() == expected + assert a.to_dict() == before + + # Labels and graph insertion order cannot choose a different backbone. + for i, data in a.g.nodes(data=True): + rule = replace(data['molnode'].identity.matched_rule, name=f'renamed-{3 - i}') + data['identity'] = MolIdentity(rule) + data['molnode'] = replace(data['molnode'], identity=data['identity']) + reordered = nx.Graph() + reordered.add_nodes_from(reversed(list(a.g.nodes(data=True)))) + reordered.add_edges_from((v, u, data) for u, v, data in reversed(list(a.g.edges(data=True)))) + readout = LinearReadout.from_assembly_graph(AssemblyGraph(reordered)) + assert [[node.enc for node in path] for path in readout.paths] == [ + ['unit-0', 'unit-1', 'unit-2', 'unit-3'], + ] + + +def test_competing_complete_port_orders_are_left_ambiguous(): + a = crosslinked_capped_chain() + # The terminal acid can also enter the middle unit: both 0-1-2-3 and + # 0-1-3-2 now follow exit-to-entry links, so neither is uniquely supported. + a.g[3][2]['bonds'].append(RootBondLink(8, 3, 9, 4, 'C', 'C', 'SINGLE', 1.0)) + a.g[3][2]['n_bonds'] += 1 + assert _connected_backbone_order(a.g) is None + + def test_reconstruction_consumes_the_oriented_peptide_readout(ruleset): smiles = 'NCC(=O)NC(C)C(=O)O' result = run_retromol(Submission(smiles), ruleset) diff --git a/tests/test_readout_expectations.py b/tests/test_readout_expectations.py new file mode 100644 index 0000000..f5a3154 --- /dev/null +++ b/tests/test_readout_expectations.py @@ -0,0 +1,73 @@ +"""The broad integration fixtures must catch order, grouping and coverage errors.""" + +import pytest +import yaml + +from .helpers_retromol import ( + ExpectedAssembly, assert_assemblies, assert_linear_readout, + load_expected_readouts, parse_compound, +) +from .test_assembly_sampling import layered_result +from .test_readout import assembly + + +FINE = ExpectedAssembly( + 1.0, (("C", 1),) * 4, + ((0, 1, ("C-C:SINGLE",)), (1, 2, ("C-C:SINGLE",)), (2, 3, ("C-C:SINGLE",))), +) +COARSE = ExpectedAssembly(1.0, (("CC", 2),) * 2, ((0, 1, ("C-C:SINGLE",)),)) + + +def test_each_assembly_alternative_requires_its_own_readout(): + result, *_ = layered_result() + expected = ((('C', 'C', 'C', 'C'),), (('CC', 'CC'),)) + assert_assemblies(result, [FINE, COARSE], expected_readouts=expected) + with pytest.raises(AssertionError, match="Matching graphs with wrong readouts"): + assert_assemblies(result, [FINE, COARSE], expected_readouts=(expected[0], (('CC',), ('CC',)))) + with pytest.raises(ValueError, match="one readout for every"): + assert_assemblies(result, [FINE, COARSE], expected_readouts=expected[:1]) + + +@pytest.mark.parametrize('wrong', [ + (('norleucine', 'alanine'),), + (('alanine',), ('norleucine',)), + (('alanine',),), + (('alanine', 'norleucine', 'norleucine'),), +], ids=['reversed', 'split', 'missing', 'duplicated']) +def test_exact_readout_comparison_rejects_wrong_order_or_parts(wrong, ruleset): + result = parse_compound('CC(N)C(=O)NC(CCCC)C(=O)O', ruleset) + assert_linear_readout(result.assembly_graph, (('alanine', 'norleucine'),)) + with pytest.raises(AssertionError, match="Wrong linear readout"): + assert_linear_readout(result.assembly_graph, wrong) + + +def test_identical_parts_are_not_deduplicated_and_unknown_units_are_omitted(): + graph = assembly(['repeat', 'repeat', None]) + assert_linear_readout(graph, (('repeat',), ('repeat',))) + with pytest.raises(AssertionError, match="Wrong linear readout"): + assert_linear_readout(graph, (('repeat',),)) + assert_linear_readout(assembly([None]), ()) + + +@pytest.mark.parametrize('data, message', [ + ({}, 'exactly the assembly compound set'), + ({'case': {'default_assembly': 0, 'assemblies': []}}, 'every expected assembly'), + ({'case': {'default_assembly': 0, 'assemblies': [[['C', 'C', 'C']]]}}, 'every identified unit'), + ({'case': {'default_assembly': 1, 'assemblies': [[['C', 'C', 'C', 'C']]]}}, 'invalid default assembly index'), +]) +def test_readout_fixture_validation_rejects_incomplete_expectations(tmp_path, data, message): + path = tmp_path / 'readouts.yml' + path.write_text(yaml.safe_dump(data)) + with pytest.raises(ValueError, match=message): + load_expected_readouts(path, {'case': (FINE,)}) + + +def test_default_readout_can_describe_a_different_decomposition(tmp_path): + path = tmp_path / 'readouts.yml' + path.write_text(yaml.safe_dump({'case': { + 'default_sequence': [['C', 'C', 'C', 'C']], + 'assemblies': [[['CC', 'CC']]], + }})) + expected = load_expected_readouts(path, {'case': (COARSE,)})['case'] + assert expected.default == (('C', 'C', 'C', 'C'),) + assert expected.assemblies == ((('CC', 'CC'),),) From 35fa3cf81fe15ea84c9a0d14043e5acfad679e5c Mon Sep 17 00:00:00 2001 From: David Meijer Date: Tue, 20 Oct 2026 17:03:22 -0400 Subject: [PATCH 7/7] FIX: simpler readout strategy with one deterministic readout for a single assembly graph --- src/retromol/model/readout.py | 331 ++++++++++--------- tests/data/integration_retromol_readouts.yml | 44 +-- tests/helpers_retromol.py | 16 +- tests/test_integration_readout.py | 28 ++ tests/test_integration_retromol.py | 20 -- tests/test_readout.py | 81 ++++- 6 files changed, 318 insertions(+), 202 deletions(-) diff --git a/src/retromol/model/readout.py b/src/retromol/model/readout.py index 9c156e5..61aeaf5 100644 --- a/src/retromol/model/readout.py +++ b/src/retromol/model/readout.py @@ -148,115 +148,175 @@ def _readout_graph(assembly: AssemblyGraph) -> nx.Graph: return g -def _connected_backbone_order(g: nx.Graph) -> list[Any] | None: - """Find a complete order determined by carboxyl-exit to entry connections. - - Ring crosslinks can give an undirected longest path the right units in the - wrong order. Prefer the fragment ports when they determine a single chain - through every unit. This applies equally to peptide, PK, and hybrid units. - At each step, only one successor may still reach all remaining units; a - shortcut that strands units or a closure into an already visited entry - cannot replace the next backbone step. Ambiguous components, incomplete - port evidence, and rings without a source retain the usual path fallback. +def _backbone_connections(g: nx.Graph) -> nx.DiGraph: + """Directed continuations inferred solely from this assembly's fragments. + + Exit-to-entry bonds continue a chain. Bonds between two exits, two entries, + or side sites of already connected units are crosslinks, not continuations. + Missing port annotations retain the element/role fallback from _readout_graph; + missing evidence must not be confused with contradictory evidence. + + Anhydride-style cuts can cap a segment in the opposite direction. A free + retained acid anchors one end; a separate acyl starter must anchor the other. + Reverse only the artificial-cap connections between these anchors; + retained amide/ester directions never reverse. This resolves the direction + of the supplied fragments without replacing, rematching or reparsing them. """ - if len(g) < 2 or any(data["molnode"].identity.matched_rule.sequence_role == "tailoring" - for _, data in g.nodes(data=True)): - return None entries = {key: _backbone_entry_tags(data["molnode"]) for key, data in g.nodes(data=True)} exits = {key: _carboxyl_exit_tags(data["molnode"]) for key, data in g.nodes(data=True)} - directed = nx.DiGraph() - directed.add_nodes_from(g) + retained = {key: _carboxyl_exit_tags(data["molnode"], include_added_caps=False) + for key, data in g.nodes(data=True)} + capped_entries = { + key: {data["molnode"].mol.GetAtomWithIdx(match[0]).GetIsotope() + for match in data["molnode"].mol.GetSubstructMatches(_UNIT_ENTRY_CAP)} + for key, data in g.nodes(data=True) + } + connected = {key: {tag for _, _, data in g.edges(key, data=True) + for bond in data["bonds"] for tag in (bond.a1_tag, bond.a2_tag)} for key in g} + terminals = {key for key in g if retained[key] and not retained[key] & connected[key]} + sources = {key for key in g if exits[key] and not entries[key] and key not in terminals} + strict = nx.DiGraph() + strict.add_nodes_from(g.nodes(data=True)) + reversible = nx.DiGraph() + reversible.add_nodes_from(g) + links = [] for u, v, data in g.edges(data=True): for bond in data["bonds"]: - for left, right in ((bond.a1_tag, bond.a2_tag), (bond.a2_tag, bond.a1_tag)): - if left in exits[u] and right in entries[v]: - directed.add_edge(u, v) - if left in entries[u] and right in exits[v]: - directed.add_edge(v, u) - sources = [key for key, degree in directed.in_degree() if degree == 0] - if len(sources) != 1: - return None - path = [sources[0]] - remaining = set(g) - set(path) - while remaining: - subgraph = directed.subgraph(remaining) - candidates = [key for key in directed.successors(path[-1]) if key in remaining - and len(nx.descendants(subgraph, key)) + 1 == len(remaining)] - if len(candidates) != 1: - return None - path.append(candidates[0]) - remaining.remove(candidates[0]) - return path - - -def _orient_paths(assembly: AssemblyGraph, paths: list[list[MolNode]]) -> list[list[MolNode]]: - """Orient paths toward the carboxyl end when connection evidence agrees. - - Root bond tags identify the actual connection; merely finding a free acid - (including an Asp/Glu side-chain acid) is not a direction signal. - A complete order supported by entry/exit connections also corrects paths - saved with a crosslink in place of a backbone step. Otherwise, missing or - contradictory evidence can be resolved by a unique retained terminal acid. - Rings without a source keep a conventional start rather than a terminus. - """ - g = _readout_graph(assembly) - by_enc = {data["molnode"].enc: node_id for node_id, data in g.nodes(data=True)} - exits = {node.enc: _carboxyl_exit_tags(node) for path in paths for node in path} - oriented = [] - for path in paths: - if len(path) < 2 or any(node.identity.matched_rule.sequence_role == "tailoring" for node in path): - oriented.append(path) + a, b = bond.a1_tag, bond.a2_tag + if a not in g.nodes[u]["tags"]: + a, b = b, a + links.append((u, v, a, b)) + for donor, acceptor, out_tag, in_tag in ((u, v, a, b), (v, u, b, a)): + if out_tag in exits[donor] and in_tag in entries[acceptor]: + strict.add_edge(donor, acceptor) + if out_tag not in retained[donor] and in_tag in capped_entries[acceptor]: + reversible.add_edge(donor, acceptor) + + reverse_edges = set() + reversed_units = set() + for terminal in terminals: + if entries[terminal] or not exits[terminal] - retained[terminal]: continue - ids = [by_enc.get(node.enc) for node in path] - if any(node_id is None for node_id in ids): - oriented.append(path) + segment = {terminal} | nx.descendants(reversible, terminal) + # A free side-chain acid on a starter is insufficient. The opposite + # end must actually meet a separate acyl starter at two outgoing ports. + # Only this combination anchors both ends of a reverse-cut segment. + if not any( + donor in sources and acceptor in segment + and out_tag in exits[donor] and in_tag in retained[acceptor] + for u, v, a, b in links + for donor, acceptor, out_tag, in_tag in ((u, v, a, b), (v, u, b, a)) + ): continue - - connected_order = _connected_backbone_order(g.subgraph(ids)) - if connected_order is not None: - by_id = dict(zip(ids, path)) - oriented.append([by_id[node_id] for node_id in connected_order]) + reversed_units.update(segment) + reverse_edges.update(reversible.subgraph(segment).edges()) + directed = strict.copy() + directed.remove_edges_from(reverse_edges) + directed.add_edges_from((v, u) for u, v in reverse_edges) + + for u, v, a, b in links: + if strict.has_edge(u, v) or strict.has_edge(v, u): continue - - closed = len(path) > 2 and g.has_edge(ids[-1], ids[0]) - steps = list(zip(range(len(path) - 1), range(1, len(path)))) - if closed: - steps.append((len(path) - 1, 0)) - directions: set[int] = set() - for i, j in steps: - edge = g.get_edge_data(ids[i], ids[j]) - if edge is None: - continue - left_tags = g.nodes[ids[i]]["tags"] - right_tags = g.nodes[ids[j]]["tags"] - for bond in edge["bonds"]: - # Root bond begin/end order is unrelated to sequence direction. - for left, right in ((bond.a1_tag, bond.a2_tag), (bond.a2_tag, bond.a1_tag)): - if left in left_tags and right in right_tags: - if left in exits[path[i].enc]: - directions.add(1) - if right in exits[path[j].enc]: - directions.add(-1) - reverse = directions == {-1} - if len(directions) != 1 and not closed: - terminal_ends = [] - for i, j in ((0, 1), (len(path) - 1, len(path) - 2)): - retained = _carboxyl_exit_tags(path[i], include_added_caps=False) - edge = g.get_edge_data(ids[i], ids[j], {}) - connected = {tag for bond in edge.get("bonds", []) for tag in (bond.a1_tag, bond.a2_tag)} - # A side-chain acid is not a terminal anchor when the same unit - # donates through another retained carboxyl to its neighbor. - if retained and not retained.intersection(connected): - terminal_ends.append(i) - if len(terminal_ends) == 1: - reverse = terminal_ends[0] == 0 - if reverse: - path = list(reversed(path)) - if closed: - # Preserve the chosen ring start while reversing its traversal. - path = path[-1:] + path[:-1] - oriented.append(path) - return oriented + a_exit, b_exit = a in exits[u], b in exits[v] + if a_exit and b_exit: + # Join a reverse-capped segment to its entryless acyl starter. + # Two ordinary outgoing ports (e.g. dimerisation) stay separate. + if u in sources and v in reversed_units: + directed.add_edge(u, v) + if v in sources and u in reversed_units: + directed.add_edge(v, u) + continue + if a_exit or b_exit: + donor, acceptor, tag = (u, v, b) if a_exit else (v, u, a) + acceptor_mol = g.nodes[acceptor]["molnode"].mol + hetero_entry = any(atom.GetIsotope() == tag and atom.GetAtomicNum() in (7, 8, 16) + for atom in acceptor_mol.GetAtoms()) + if (not (entries[acceptor] or exits[acceptor]) or hetero_entry) and strict.in_degree(acceptor) == 0: + directed.add_edge(donor, acceptor) + continue + if a in entries[u] and not (entries[v] or exits[v]): + directed.add_edge(v, u) + elif b in entries[v] and not (entries[u] or exits[u]): + directed.add_edge(u, v) + elif not (entries[u] or exits[u] or entries[v] or exits[v]): + # No chemical direction is available for these legacy/custom units. + directed.add_edge(u, v) + directed.add_edge(v, u) + return directed + + +def _directed_paths(g: nx.DiGraph) -> list[list[MolNode]]: + """Cover every unit once, following continuations rather than crosslinks. + + Start at unconnected entries; a source-free ring gets a conventional cut. + Reachability lookahead avoids shortcuts that strand intermediate units. + Branches become additional paths, never an undirected walk through a junction. + Ties have a stable order; this does not assert a unique biosynthetic route. + """ + g = g.copy() + + def node_key(key): + node = g.nodes[key]["molnode"] + return _node_name(node), tuple(sorted(g.nodes[key]["tags"])), node.enc + + def walk(start): + path = [start] + remaining = set(g) - {start} + while remaining: + options = [key for key in g.successors(path[-1]) if key in remaining] + if not options: + break + rest = g.subgraph(remaining) + next_node = min(options, key=lambda key: ( + -len(nx.descendants(rest, key)), rest.in_degree(key), node_key(key), + )) + path.append(next_node) + remaining.remove(next_node) + return path + + paths = [] + while g: + starts = [key for key, degree in g.in_degree() if degree == 0] + if not starts: + # A ring can have an outgoing chain. Start in a source strongly + # connected component, not at an alphabetically earlier tail unit. + condensed = nx.condensation(g) + starts = [key for component, degree in condensed.in_degree() if degree == 0 + for key in condensed.nodes[component]["members"]] + candidates = [walk(key) for key in sorted(starts, key=node_key)] + path = min(candidates, key=lambda path: (-len(path), tuple(node_key(key) for key in path))) + paths.append([g.nodes[key]["molnode"] for key in path]) + g.remove_nodes_from(path) + return paths + + +def _assembly_paths(assembly: AssemblyGraph) -> list[list[MolNode]]: + """One canonical partition for one supplied assembly, including saved results.""" + g = _readout_graph(assembly) + paths = [] + for component in nx.connected_components(g): + h = g.subgraph(component).copy() + if any(data["molnode"].identity.matched_rule.sequence_role == "tailoring" + for _, data in h.nodes(data=True)) or not any( + _backbone_entry_tags(data["molnode"]) or _carboxyl_exit_tags(data["molnode"]) + for _, data in h.nodes(data=True)): + # Tailoring groups and units with no chemical ports keep the existing + # deterministic topology-only convention. + pending = [AssemblyGraph(h)] + while pending: + part = pending.pop() + path = part.longest_path() + paths.append(path) + used = {node.enc for node in path} + part.g.remove_nodes_from([key for key, data in part.g.nodes(data=True) + if data["molnode"].enc in used]) + pending.extend(part.connected_components()) + else: + directed = _backbone_connections(h) + for component in nx.weakly_connected_components(directed): + paths.extend(_directed_paths(directed.subgraph(component))) + return sorted(paths, key=lambda path: (-len(path), [_node_name(node) for node in path], + [node.enc for node in path])) def merge_named_paths(paths: list[list[T]], key: Callable[[T], str], link_item: T) -> list[T]: @@ -317,29 +377,17 @@ class LinearReadout: A linear readout representation of a RetroMol parsing result. :cvar assembly_graph: AssemblyGraph representing the assembly of monomers. - :cvar paths: Disjoint paths of identified MolNodes. Unresolved regions break - paths and remain only in the source assembly graph. + :cvar paths: Derived disjoint paths of identified MolNodes. Recomputed from + assembly_graph on construction, including when loading old saved paths. + Unresolved regions break paths and remain only in the source graph. """ assembly_graph: AssemblyGraph paths: list[list[MolNode]] def __post_init__(self) -> None: - """Normalize identified paths and their direction, including saved paths.""" - paths: list[list[MolNode]] = [] - for path in self.paths: - part: list[MolNode] = [] - for node in path: - if node.is_identified and node.identity is not None: - part.append(node) - elif part: - paths.append(part) - part = [] - if part: - paths.append(part) - paths = _orient_paths(self.assembly_graph, paths) - paths.sort(key=lambda path: (-len(path), [_node_name(node) for node in path], [node.enc for node in path])) - object.__setattr__(self, "paths", paths) + """The assembly is authoritative; legacy saved paths are only a cache.""" + object.__setattr__(self, "paths", _assembly_paths(self.assembly_graph)) def __str__(self) -> str: """ @@ -385,39 +433,15 @@ def from_reaction_graph( @classmethod def from_assembly_graph(cls, assembly_graph: AssemblyGraph) -> "LinearReadout": - """Partition a sampled assembly into deterministic, disjoint paths. - - Matching-rule ``sequence_role`` separates tailoring units from other - units. Connections between units with the same explicit role are candidates - regardless of bond elements (e.g. a connected sugar chain). Otherwise, - the C-C/C-N heuristic applies to non-tailoring units. - - Prefer a complete chain determined by fragment entry/exit connections. - Otherwise extract a long simple path and process its remaining branches - so every identified MolNode occurs exactly once. Unidentified and - unassigned nodes are excluded before traversal, breaking paths at gaps. - The input graph is unchanged; use its coverage to measure completeness. - Side attachments competing with an already connected backbone entry - (capped carbon or amino-acid N) are omitted before selecting paths. - Carboxyl-side connections orient consistent paths N/starter-to-C end. - Ambiguous paths retain deterministic direction. Rings without a source - have a conventional start; their path selection remains heuristic. + """Read one supplied graph as disjoint N/starter-to-carboxyl paths. + + Fragment connection sites separate continuations from side attachments + and crosslinks. Every identified unit occurs exactly once. Tailoring + groups remain separate; gaps break paths. The graph and its matched units + are unchanged. Cyclic chains have a conventional start, and units lacking + chemical direction use deterministic topology-only ordering. """ - g = _readout_graph(assembly_graph) - paths: list[list[MolNode]] = [] - pending = AssemblyGraph(g, unassigned=assembly_graph.unassigned).connected_components() - while pending: - h = pending.pop() - connected_order = _connected_backbone_order(h.g) - path = ([h.g.nodes[node_id]["molnode"] for node_id in connected_order] - if connected_order is not None else h.longest_path()) - paths.append(path) - # Graph node IDs need not be identical to MolNode.enc. - used = {id(node) for node in path} - h.g.remove_nodes_from([n for n, data in h.g.nodes(data=True) if id(data["molnode"]) in used]) - pending.extend(h.connected_components()) - - return cls(assembly_graph=assembly_graph, paths=paths) + return cls(assembly_graph=assembly_graph, paths=[]) def primary_sequence_parts(self) -> list[list[str]]: """Named backbone/tailoring paths, longest first with lexical tie-breaks. @@ -427,7 +451,8 @@ def primary_sequence_parts(self) -> list[list[str]]: coverage measures completeness. Sublists do not encode attachment points, omitted crosslinks, or ring closures; retain ``assembly_graph`` when those are needed. Untagged paths are not biological role labels. - Consistent carboxyl-side connection evidence puts the N/starter end first. + Backbone continuations run N/starter-to-carboxyl. Rings have a + conventional cut; unannotated units retain deterministic ordering. """ return sorted( [[_node_name(node) for node in path] for path in self.paths], @@ -463,9 +488,7 @@ def from_dict(cls, data: dict) -> "LinearReadout": :param data: Dictionary representation of LinearReadout. :return: LinearReadout instance. """ - assembly_graph = AssemblyGraph.from_dict(data["assembly_graph"]) - paths = [[MolNode.from_dict(node_data) for node_data in path_data] for path_data in data["paths"]] - return cls(assembly_graph=assembly_graph, paths=paths) + return cls.from_assembly_graph(AssemblyGraph.from_dict(data["assembly_graph"])) def _node_name(node: MolNode) -> str: diff --git a/tests/data/integration_retromol_readouts.yml b/tests/data/integration_retromol_readouts.yml index b2d1c00..43e13f6 100644 --- a/tests/data/integration_retromol_readouts.yml +++ b/tests/data/integration_retromol_readouts.yml @@ -3,7 +3,8 @@ # "assemblies" follows the entry order in the corresponding *_assemblies.yml. # "default_assembly" is a zero-based reference; "default_sequence" covers a # default decomposition not represented by those required assembly fixtures. -# Known starter-order limitations have separate strict expected-failure tests. +# Each input assembly has exactly one readout; these fields describe different +# input graphs, not alternative readout modes. "10-deoxymethynolide": default_assembly: 0 @@ -635,7 +636,8 @@ default_assembly: 0 assemblies: - - - ["acetic acid starter", "cysteine", "C2", "B1", "C2", "D1", "A2", "B2", "propanoic acid starter"] + - ["acetic acid starter", "cysteine", "C2", "B1", "C2", "D1", "A2", "B2"] + - ["propanoic acid starter"] "amamistatin B": default_assembly: 0 @@ -648,7 +650,9 @@ default_assembly: 0 assemblies: - - - ["acetic acid starter", "D1", "D1", "D1", "D1", "D1", "C1", "N-(5-aminopentyl)hydroxylamine", "butanedioic acid", "N-(5-aminopentyl)hydroxylamine", "serine", "salicylic acid"] + - ["acetic acid starter", "D1", "D1", "D1", "D1", "D1", "C1", "N-(5-aminopentyl)hydroxylamine"] + - ["salicylic acid", "serine", "N-(5-aminopentyl)hydroxylamine"] + - ["butanedioic acid"] "borophycin": default_assembly: 0 @@ -746,7 +750,8 @@ default_assembly: 0 assemblies: - - - ["2,3-dihydroxybenzoic acid", "lysinol", "2,3-dihydroxybenzoic acid"] + - ["2,3-dihydroxybenzoic acid", "lysinol"] + - ["2,3-dihydroxybenzoic acid"] "marformycin A": default_assembly: 0 @@ -853,7 +858,8 @@ default_assembly: 0 assemblies: - - - ["N-methylvaline", "sarcosine", "proline", "valine", "threonine", "4-methyl-3-hydroxyanthranilic acid", "4-methyl-3-hydroxyanthranilic acid", "threonine", "valine", "proline", "sarcosine", "N-methylvaline"] + - ["4-methyl-3-hydroxyanthranilic acid", "threonine", "valine", "proline", "sarcosine", "N-methylvaline"] + - ["4-methyl-3-hydroxyanthranilic acid", "threonine", "valine", "proline", "sarcosine", "N-methylvaline"] "tenellin": default_assembly: 0 @@ -1071,11 +1077,10 @@ "aclacinomycin": default_sequence: - - ["A1", "A1", "A1", "C1", "C1", "A1-alpha-oxo", "C1", "malonic acid", "B1", "propanoic acid starter"] + - ["propanoic acid starter", "B1", "A1", "A1", "A1", "C1", "C1", "A1-alpha-oxo", "C1", "malonic acid"] - ["glycosylation", "glycosylation", "glycosylation", "methylation"] - ["methylation"] - ["methylation"] - known_starter_order_issue: "A default path places its only starter after another unit; backbone direction or separation remains unresolved." assemblies: - - ["propanoic acid starter", "A1", "A1", "A1", "A1", "A1", "C1", "C1", "C1", "A1"] @@ -1147,8 +1152,7 @@ "PK aldol ring donor H1": default_sequence: - - ["D1", "propanoic acid starter", "A1", "malonic acid"] - known_starter_order_issue: "A default path places its only starter after another unit; backbone direction or separation remains unresolved." + - ["propanoic acid starter", "D1", "A1", "malonic acid"] assemblies: - - ["propanoic acid starter", "A1", "D1", "A1"] @@ -1172,27 +1176,27 @@ "cylindrocyclophane F": default_sequence: - - ["A1", "A1", "A1", "D8", "D1", "D1", "D1", "A1", "A1", "A1", "D8", "D1", "D1", "D1", "D1", "acetic acid starter"] - - ["acetic acid starter", "D1"] - known_starter_order_issue: "A default path places its only starter after another unit; backbone direction or separation remains unresolved." + - ["acetic acid starter", "D1", "D1", "D1", "D1", "D8", "A1", "A1", "A1"] + - ["acetic acid starter", "D1", "D1", "D1", "D1", "D8", "A1", "A1", "A1"] assemblies: - - - ["A1", "A1", "A1", "decanoic acid", "D8", "A1", "A1", "A1", "decanoic acid", "D8"] + - ["decanoic acid", "D8", "A1", "A1", "A1"] + - ["decanoic acid", "D8", "A1", "A1", "A1"] "carbamidocyclophane A": default_sequence: - - ["A1", "A1", "A1", "D10", "D1", "D1", "D1", "A1", "A1", "A1", "D10", "D1", "D1", "D1", "D1", "acetic acid starter"] - - ["acetic acid starter", "D1"] + - ["acetic acid starter", "D1", "D1", "D1", "D1", "D10", "A1", "A1", "A1"] + - ["acetic acid starter", "D1", "D1", "D1", "D1", "D10", "A1", "A1", "A1"] - ["carbamic acid"] - ["carbamic acid"] - ["chlorination"] - ["chlorination"] - ["chlorination"] - ["chlorination"] - known_starter_order_issue: "A default path places its only starter after another unit; backbone direction or separation remains unresolved." assemblies: - - - ["A1", "A1", "A1", "D10", "decanoic acid", "A1", "A1", "A1", "D10", "decanoic acid"] + - ["decanoic acid", "D10", "A1", "A1", "A1"] + - ["decanoic acid", "D10", "A1", "A1", "A1"] - ["carbamic acid"] - ["carbamic acid"] - ["chlorination"] @@ -1265,14 +1269,16 @@ "nidulin": default_sequence: - - ["acetic acid starter", "C2", "A1", "A2", "A1", "A1", "A1", "C1", "acetic acid starter"] + - ["acetic acid starter", "C2", "A1", "A2", "A1"] + - ["acetic acid starter", "C1", "A1", "A1"] - ["chlorination"] - ["chlorination"] - ["chlorination"] - ["methylation"] assemblies: - - - ["acetic acid starter", "C2", "A1", "A2", "A1", "A1", "A1", "A1", "acetic acid starter"] + - ["acetic acid starter", "C2", "A1", "A2", "A1"] + - ["acetic acid starter", "A1", "A1", "A1"] - ["chlorination"] - ["chlorination"] - ["chlorination"] diff --git a/tests/helpers_retromol.py b/tests/helpers_retromol.py index 4353322..af080c0 100644 --- a/tests/helpers_retromol.py +++ b/tests/helpers_retromol.py @@ -106,7 +106,6 @@ class ExpectedReadouts: default: SequenceParts assemblies: tuple[SequenceParts, ...] - known_starter_order_issue: str | None = None def load_expected_readouts( @@ -129,7 +128,7 @@ def parts(value) -> SequenceParts: expectations = {} for name, data in raw.items(): if not isinstance(data, dict) or set(data) - { - "assemblies", "default_assembly", "default_sequence", "known_starter_order_issue", + "assemblies", "default_assembly", "default_sequence", }: raise ValueError(f"{name}: invalid readout fields") sequences = data.get("assemblies") @@ -150,10 +149,7 @@ def parts(value) -> SequenceParts: default = sequences[index] else: default = parts(data["default_sequence"]) - issue = data.get("known_starter_order_issue") - if issue is not None and (not isinstance(issue, str) or not issue.strip()): - raise ValueError(f"{name}: known starter-order issue must have a reason") - expectations[name] = ExpectedReadouts(default, sequences, issue) + expectations[name] = ExpectedReadouts(default, sequences) return expectations @@ -162,6 +158,8 @@ def assert_linear_readout(assembly: AssemblyGraph, expected: SequenceParts) -> N before = assembly.to_dict() readout = LinearReadout.from_assembly_graph(assembly) assert readout.primary_sequence_parts() == [list(part) for part in expected], "Wrong linear readout" + assert all(index == 0 for part in readout.primary_sequence_parts() + for index, name in enumerate(part) if name.endswith(' starter')), "Starter inside a backbone" flat = [] for part in expected: if flat: @@ -174,6 +172,12 @@ def assert_linear_readout(assembly: AssemblyGraph, expected: SequenceParts) -> N assert assembly.to_dict() == before, "Readout changed the assembly" restored = AssemblyGraph.from_dict(json.loads(json.dumps(before))) assert LinearReadout.from_assembly_graph(restored).primary_sequence_parts() == [list(part) for part in expected] + reordered = nx.Graph() + reordered.add_nodes_from(reversed(list(restored.g.nodes(data=True)))) + reordered.add_edges_from((v, u, data) for u, v, data in reversed(list(restored.g.edges(data=True)))) + assert LinearReadout.from_assembly_graph(AssemblyGraph(reordered)).primary_sequence_parts() == [ + list(part) for part in expected + ], "Readout depends on graph insertion order" def assembly_comparison_graph(result: Result, assembly: AssemblyGraph) -> nx.Graph: diff --git a/tests/test_integration_readout.py b/tests/test_integration_readout.py index 872cbaf..a98050f 100644 --- a/tests/test_integration_readout.py +++ b/tests/test_integration_readout.py @@ -33,6 +33,34 @@ READOUT_CASES = [ + pytest.param( + dict(ASSEMBLY_CASES)['PK aldol ring donor H1'], + [['propanoic acid starter', 'D1', 'A1', 'malonic acid']], + [['propanoic acid starter', 'D1', 'A1', 'malonic acid']], + id='PK-aldol-ring-donor-H1', + ), + pytest.param( + dict(ASSEMBLY_CASES)['aclacinomycin'], + [['propanoic acid starter', 'B1', 'A1', 'A1', 'A1', 'C1', 'C1', 'A1-alpha-oxo', 'C1', 'malonic acid'], + ['glycosylation', 'glycosylation', 'glycosylation', 'methylation'], ['methylation'], ['methylation']], + [['propanoic acid starter', 'B^R1', 'A1', 'A1', 'A1', 'C1', 'C1', 'A1-alpha-oxo', 'C1', 'malonic acid'], + ['glycosylation', 'glycosylation', 'glycosylation', 'methylation'], ['methylation'], ['methylation']], + id='aclacinomycin', + ), + pytest.param( + dict(ASSEMBLY_CASES)['cylindrocyclophane F'], + [['acetic acid starter', 'D1', 'D1', 'D1', 'D1', 'D8', 'A1', 'A1', 'A1']] * 2, + [['acetic acid starter', 'D1', 'D1', 'D1', 'D1', 'D^R8', 'A1', 'A1', 'A1']] * 2, + id='cylindrocyclophane-F', + ), + pytest.param( + dict(ASSEMBLY_CASES)['carbamidocyclophane A'], + [['acetic acid starter', 'D1', 'D1', 'D1', 'D1', 'D10', 'A1', 'A1', 'A1']] * 2 + + [['carbamic acid']] * 2 + [['chlorination']] * 4, + [['acetic acid starter', 'D1', 'D1', 'D1', 'D1', 'D^R10^S', 'A1', 'A1', 'A1']] * 2 + + [['carbamic acid']] * 2 + [['chlorination']] * 4, + id='carbamidocyclophane-A', + ), pytest.param( dict(ASSEMBLY_CASES)['actinoquinoline B'], [['3-hydroxyquinaldic acid', '5-hydroxylysine'], ['acetic acid starter', 'D8']], diff --git a/tests/test_integration_retromol.py b/tests/test_integration_retromol.py index 2ca9f7e..6059152 100644 --- a/tests/test_integration_retromol.py +++ b/tests/test_integration_retromol.py @@ -40,23 +40,3 @@ def test_integration_demo_set(name: str, smiles: str, ruleset: RuleSet) -> None: assert_assemblies(result, EXPECTED_ASSEMBLIES[name], expected_readouts=readouts.assemblies) assert_linear_readout(result.assembly_graph, readouts.default) assert result.linear_readout.primary_sequence_parts() == [list(part) for part in readouts.default] - - -@pytest.mark.parametrize("name, smiles", [ - pytest.param(name, smiles, id=name, marks=pytest.mark.xfail( - strict=True, raises=AssertionError, reason=EXPECTED_READOUTS[name].known_starter_order_issue, - )) - for name, smiles in CASES if EXPECTED_READOUTS[name].known_starter_order_issue -]) -def test_known_backbone_starter_order(name, smiles, ruleset): - """Keep known ordering errors visible independently of compatibility snapshots. - - These checks express the desired property, not the current faulty order. - A fix must remove its expected-failure mark and update the corresponding - regression fixture; strict XPASS prevents leaving a fixed issue hidden. - """ - result = parse_compound(smiles, ruleset) - paths = result.linear_readout.primary_sequence_parts() - single_starter_paths = [part for part in paths if sum(token.endswith(' starter') for token in part) == 1] - assert single_starter_paths, f"{name}: the starter disappeared from the readout" - assert all(part[0].endswith(' starter') for part in single_starter_paths), paths diff --git a/tests/test_readout.py b/tests/test_readout.py index 9867983..881622a 100644 --- a/tests/test_readout.py +++ b/tests/test_readout.py @@ -13,7 +13,7 @@ from retromol.model.identity import MolIdentity from retromol.model.reaction_graph import MolNode from retromol.model.readout import ( - LinearReadout, _backbone_entry_tags, _connected_backbone_order, + LinearReadout, _backbone_entry_tags, _backbone_connections, assembly_to_primary_sequence, split_named_paths, ) from retromol.model.result import Result @@ -370,13 +370,88 @@ def test_entry_exit_connections_select_order_before_undirected_crosslinks(): ] -def test_competing_complete_port_orders_are_left_ambiguous(): +def test_competing_complete_port_orders_have_one_deterministic_readout(): a = crosslinked_capped_chain() # The terminal acid can also enter the middle unit: both 0-1-2-3 and # 0-1-3-2 now follow exit-to-entry links, so neither is uniquely supported. a.g[3][2]['bonds'].append(RootBondLink(8, 3, 9, 4, 'C', 'C', 'SINGLE', 1.0)) a.g[3][2]['n_bonds'] += 1 - assert _connected_backbone_order(a.g) is None + readout = LinearReadout.from_assembly_graph(a) + directed = _backbone_connections(a.g) + by_enc = {data['molnode'].enc: key for key, data in a.g.nodes(data=True)} + assert len(readout.paths) == 1 and len(readout.paths[0]) == 4 + assert readout.paths[0][0].enc == 'unit-0' + assert all(directed.has_edge(by_enc[u.enc], by_enc[v.enc]) + for u, v in zip(readout.paths[0], readout.paths[0][1:])) + reordered = nx.Graph() + reordered.add_nodes_from(reversed(list(a.g.nodes(data=True)))) + reordered.add_edges_from(reversed(list(a.g.edges(data=True)))) + assert assembly_to_primary_sequence(AssemblyGraph(reordered)) == readout.primary_sequence_parts() + + +@pytest.mark.parametrize('crosslinks', [1, 2]) +def test_exit_crosslinks_separate_chains_even_when_they_are_graph_bridges(crosslinks): + first = crosslinked_capped_chain() + second = crosslinked_capped_chain().to_dict() + # Shift the complete second graph, including the original atom tags. + for data in second['nodes']: + data['id'] += 4 + data['tags'] = [tag + 30 for tag in data['tags']] + mol = smiles_to_mol(data['molnode']['tagged_smiles']) + for atom in mol.GetAtoms(): + if atom.GetIsotope(): + atom.SetIsotope(atom.GetIsotope() + 30) + data['molnode']['tagged_smiles'] = Chem.MolToSmiles(mol) + data['molnode']['enc'] += '-second' + for edge in second['edges']: + edge['u'] += 4 + edge['v'] += 4 + for bond in edge['bonds']: + bond['a1_tag'] += 30 + bond['a2_tag'] += 30 + g = nx.compose(first.g, AssemblyGraph.from_dict(second).g) + for u, v, a, b in [(1, 6, 3, 35), (2, 5, 5, 33)][:crosslinks]: + bond = RootBondLink(a - 1, b - 1, a, b, 'C', 'C', 'SINGLE', 1.) + g.add_edge(u, v, bonds=[bond], n_bonds=1) + a = AssemblyGraph(g) + before = a.to_dict() + assert nx.is_connected(g) + expected = [['z-source', 'b-unit', 'a-unit', 'c-end']] * 2 + readout = LinearReadout.from_assembly_graph(a) + assert readout.primary_sequence_parts() == expected + assert a.to_dict() == before + # Cached paths, including missing units, cannot select a different readout. + saved = readout.to_dict() + saved['paths'] = [[a.g.nodes[3]['molnode'].to_dict()]] + assert LinearReadout.from_dict(saved).primary_sequence_parts() == expected + assert LinearReadout(a, [a.monomer_nodes()]).primary_sequence_parts() == expected + + +def test_reverse_caps_need_both_a_terminal_acid_and_a_connected_acyl_source(): + g = nx.Graph() + for key, smiles in enumerate([ + '[1CH3]C(=O)O', + 'OS[2CH2][3CH2][4C](=[5O])O', + 'O=C(O)[6CH2][7CH2]SO', + 'O=C(O)[8CH2][9C](=[10O])[11OH]', + ]): + mol = smiles_to_mol(smiles) + # Adversarial names: ordering must come from the ports, not labels. + identity = MolIdentity(MatchingRule(f'unit-{3 - key}', smiles, {}, [])) + node = MolNode(str(key), mol, smiles, identity, True) + g.add_node(key, molnode=node, identity=identity, + tags={a.GetIsotope() for a in mol.GetAtoms() if a.GetIsotope()}) + for u, v, a, b in [(0, 1, 1, 4), (1, 2, 2, 6), (2, 3, 7, 8), (0, 2, 1, 7)]: + bond = RootBondLink(a - 1, b - 1, a, b, 'C', 'C', 'SINGLE', 1.) + g.add_edge(u, v, bonds=[bond], n_bonds=1) + a = AssemblyGraph(g) + assert assembly_to_primary_sequence(a) == [['unit-3', 'unit-2', 'unit-1', 'unit-0']] + assert assembly_to_primary_sequence(AssemblyGraph.from_dict(a.to_dict())) == [ + ['unit-3', 'unit-2', 'unit-1', 'unit-0'], + ] + # Without the second anchor this could be a starter with a free side acid. + g.remove_node(0) + assert assembly_to_primary_sequence(AssemblyGraph(g)) == [['unit-0', 'unit-1', 'unit-2']] def test_reconstruction_consumes_the_oriented_peptide_readout(ruleset):