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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 7 additions & 13 deletions database/scripts/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
36 changes: 35 additions & 1 deletion gui/src/client/src/components/workspace/WorkspaceRules.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ function MatchingRuleRow({ rule }: { rule: MatchingRule }) {
</Typography>
</Box>

{rule.cases.length > 0 && <Chip label="Conditional roles" size="small" sx={{ fontSize: "0.7rem" }} />}
{rule.terminal && <Chip label="Terminal" size="small" sx={{ fontSize: "0.7rem" }} />}
{rule.stereochemistry && <Chip label="Stereochemistry" size="small" color="info" sx={{ fontSize: "0.7rem", color: "white" }} />}
{rule.pseudonyms.length > 0 && (
Expand Down Expand Up @@ -146,6 +147,35 @@ function MatchingRuleRow({ rule }: { rule: MatchingRule }) {
</Box>
)}

<Typography variant="body2" color="text.secondary">
Default sequence role: {rule.sequenceRole ?? "inferred from bonds"}
</Typography>
{rule.requiresSmarts && (
<Box>
<Typography variant="caption" color="text.secondary">Required SMARTS</Typography>
<Typography variant="body2" sx={{ fontFamily: "monospace", wordBreak: "break-all" }}>
{rule.requiresSmarts}
</Typography>
</Box>
)}
{rule.cases.length > 0 && (
<Stack spacing={0.5}>
<Typography variant="caption" color="text.secondary">
Cases after structural matching (first match wins; otherwise use defaults)
</Typography>
{rule.cases.map((ruleCase, i) => (
<Box key={i}>
<Typography variant="body2">
{i + 1}. <MotifName name={ruleCase.name ?? rule.name} />
{" · "}{ruleCase.sequenceRole ?? rule.sequenceRole ?? "inferred from bonds"}
</Typography>
<Typography variant="body2" sx={{ fontFamily: "monospace", wordBreak: "break-all" }}>
{ruleCase.requiresSmarts}
</Typography>
</Box>
))}
</Stack>
)}
{rule.terminal && (
<Typography variant="body2" color="text.secondary">
{rule.preserveAcrossRoutes
Expand Down Expand Up @@ -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(() => {
Expand Down
9 changes: 9 additions & 0 deletions gui/src/client/src/features/rules/types.ts
Original file line number Diff line number Diff line change
@@ -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(),
Expand All @@ -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<typeof MatchingRuleSchema>;
Expand Down
4 changes: 2 additions & 2 deletions gui/src/server/routes/discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)

Expand Down
31 changes: 10 additions & 21 deletions gui/src/server/routes/jobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,31 +307,22 @@ 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 \"<LINK>\". "
"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 "
"\"<LINK>\" 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 \"<LINK>\", 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 \"<LINK>\" and use the desired part."
)


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
Expand All @@ -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
]

Expand Down
10 changes: 10 additions & 0 deletions gui/src/server/routes/rules.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 3 additions & 2 deletions src/retromol/chem/matching.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
87 changes: 85 additions & 2 deletions src/retromol/data/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -79,11 +79,14 @@ 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. |
| `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:
Expand All @@ -100,6 +103,79 @@ 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. 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: '[C](=[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
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 initially retained regardless
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
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.

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.
Expand Down Expand Up @@ -142,7 +218,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`

Expand Down
Loading
Loading