Skip to content

API Reference

rdchiral

rdchiralReactants

Bases: object

Class to store everything that should be pre-computed for a reactant mol so that library application is faster

Attributes:

Name Type Description
reactant_smiles str

Reactant SMILES string

reactants Mol

RDKit Molecule created from _initialize_reactants_from_smiles

atoms_r dict

Dictionary mapping from atom map number to atom in reactants Molecule

reactants_achiral Mol

achiral version of reactants

bonds_by_mapnum list

List of reactant bonds as (int, int, rdkit.Chem.rdchem.Bond) tuples keyed by atom-map numbers

bond_dirs_by_mapnum dict

Dictionary mapping from atom map number tuples to BondDir

atoms_across_double_bonds list

List of cis/trans specifications from get_atoms_across_double_bonds

Methods:

Name Description
idx_to_mapnum

Return atom map number for given atom idx

Parameters:

Name Type Description Default
reactant_smiles str

Reactant SMILES string

required
custom_reactant_mapping bool

Whether to use custom reactant mapping

False
lazy_init bool

If True, delay initialization of reactants until accessed

True
enumerate_tautomers bool

Whether to enumerate tautomers (currently unused)

False
Source code in rdchiral/initialization.py
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
class rdchiralReactants(object):
    """
    Class to store everything that should be pre-computed for a reactant mol
    so that library application is faster

    Attributes:
        reactant_smiles (str): Reactant SMILES string
        reactants (rdkit.Chem.rdchem.Mol): RDKit Molecule created from `_initialize_reactants_from_smiles`
        atoms_r (dict): Dictionary mapping from atom map number to atom in `reactants` Molecule
        reactants_achiral (rdkit.Chem.rdchem.Mol): achiral version of `reactants`
        bonds_by_mapnum (list): List of reactant bonds as
            (int, int, rdkit.Chem.rdchem.Bond) tuples keyed by atom-map numbers
        bond_dirs_by_mapnum (dict): Dictionary mapping from atom map number tuples to BondDir
        atoms_across_double_bonds (list): List of cis/trans specifications from `get_atoms_across_double_bonds`

    Methods:
        idx_to_mapnum(idx): Return atom map number for given atom idx

    Args:
        reactant_smiles (str): Reactant SMILES string
        custom_reactant_mapping (bool): Whether to use custom reactant mapping
        lazy_init (bool): If True, delay initialization of reactants until accessed
        enumerate_tautomers (bool): Whether to enumerate tautomers (currently unused)
    """

    def __init__(
        self,
        reactant_smiles: str,
        custom_reactant_mapping: bool = False,
        lazy_init: bool = True,
        enumerate_tautomers: bool = False,
    ):
        # Keep original smiles, useful for reporting
        self.reactant_smiles: str = reactant_smiles
        self.custom_mapping: bool = custom_reactant_mapping

        self.fast_reactants = Chem.MolFromSmiles(reactant_smiles)

        self._reactants: Optional[Chem.Mol] = None
        self._n_atoms: Optional[int] = None
        self._n_bonds: Optional[int] = None
        self._atoms_r: Optional[Dict[int, Chem.Atom]] = None
        self._idx_to_map_num: Optional[Dict[int, int]] = None
        self._reactants_achiral: Optional[Chem.Mol] = None
        self._bonds_by_mapnum: Optional[List[Tuple[int, int, Chem.Bond]]] = None
        self._bond_dirs_by_mapnum: Optional[Dict[Tuple[int, int], BondDir]] = None
        self._atoms_across_double_bonds: Optional[
            List[Tuple[Tuple[int, int, int, int], Tuple[BondDir, BondDir], bool]]
        ] = None
        self._reactants_has_tetra_stereo: Optional[bool] = None
        self._reactants_has_doublebond_stereo: Optional[bool] = None
        self._reactants_is_chiral: Optional[bool] = None

        if not lazy_init:
            _ = self.reactants
            self._ensure_atom_maps()
            _ = self.atoms_r
            _ = self.reactants_achiral
            _ = self.bonds_by_mapnum
            _ = self.bond_dirs_by_mapnum
            _ = self.atoms_across_double_bonds
            _ = self.reactants_has_tetra_stereo
            _ = self.reactants_has_doublebond_stereo
            _ = self.reactants_is_chiral

    @property
    def reactants(self) -> Chem.Mol:
        if self._reactants is None:
            reactants: Chem.Mol = _fully_initialize_reactants_from_mol(
                self.fast_reactants
            )
            self._n_atoms = reactants.GetNumAtoms()
            if not self.custom_mapping:
                for idx in range(self._n_atoms):
                    reactants.GetAtomWithIdx(idx).SetAtomMapNum(idx + 1)
            self._reactants = reactants
        assert self._reactants is not None
        return self._reactants

    def _ensure_atom_maps(self) -> None:
        if self._atoms_r is not None and self._idx_to_map_num is not None:
            return

        atoms_r: Dict[int, Chem.Atom] = {}
        idx_to_map_num: Dict[int, int] = {}
        has_tetra_stereo = False

        if self._n_atoms is None:
            self._n_atoms = self.reactants.GetNumAtoms()
        n_atoms = self._n_atoms
        for idx in range(n_atoms):
            atom = self.reactants.GetAtomWithIdx(idx)
            map_num = atom.GetAtomMapNum()
            atoms_r[map_num] = atom
            idx_to_map_num[idx] = map_num
            if (
                not has_tetra_stereo
                and atom.GetChiralTag() != ChiralType.CHI_UNSPECIFIED
            ):
                has_tetra_stereo = True

        self._atoms_r = atoms_r
        self._idx_to_map_num = idx_to_map_num
        self._reactants_has_tetra_stereo = has_tetra_stereo

    def _ensure_bond_maps(self) -> None:
        if self._bonds_by_mapnum is not None and self._bond_dirs_by_mapnum is not None:
            return

        bonds_by_mapnum: List[Tuple[int, int, Chem.Bond]] = []
        bond_dirs: Dict[Tuple[int, int], BondDir] = {}
        has_doublebond_stereo = False

        if self._n_bonds is None:
            self._n_bonds = self.reactants.GetNumBonds()
        n_bonds = self._n_bonds
        for bond_idx in range(n_bonds):
            b = self.reactants.GetBondWithIdx(bond_idx)
            i = b.GetBeginAtom().GetAtomMapNum()
            j = b.GetEndAtom().GetAtomMapNum()
            bonds_by_mapnum.append((i, j, b))

            bond_dir = b.GetBondDir()
            if bond_dir != BondDir.NONE:
                has_doublebond_stereo = True
                bond_dirs[(i, j)] = bond_dir
                bond_dirs[(j, i)] = BondDirOpposite[bond_dir]

        self._bonds_by_mapnum = bonds_by_mapnum
        self._bond_dirs_by_mapnum = bond_dirs
        self._reactants_has_doublebond_stereo = has_doublebond_stereo

    @property
    def atoms_r(self) -> Dict[int, Chem.Atom]:
        self._ensure_atom_maps()
        assert self._atoms_r is not None
        return self._atoms_r

    @property
    def reactants_achiral(self) -> Chem.Mol:
        if self._reactants_achiral is None:
            reactants_achiral = Chem.Mol(self.reactants)
            Chem.RemoveStereochemistry(reactants_achiral)
            self._reactants_achiral = reactants_achiral
        return self._reactants_achiral

    @property
    def bonds_by_mapnum(self) -> List[Tuple[int, int, Chem.Bond]]:
        self._ensure_bond_maps()
        assert self._bonds_by_mapnum is not None
        return self._bonds_by_mapnum

    @property
    def bond_dirs_by_mapnum(self) -> Dict[Tuple[int, int], BondDir]:
        self._ensure_bond_maps()
        assert self._bond_dirs_by_mapnum is not None
        return self._bond_dirs_by_mapnum

    @property
    def atoms_across_double_bonds(
        self,
    ) -> List[Tuple[Tuple[int, int, int, int], Tuple[BondDir, BondDir], bool]]:
        if self._atoms_across_double_bonds is None:
            self._atoms_across_double_bonds = get_atoms_across_double_bonds(
                self.reactants
            )
        return self._atoms_across_double_bonds

    @property
    def reactants_has_tetra_stereo(self) -> bool:
        if self._reactants_has_tetra_stereo is None:
            self._ensure_atom_maps()
        assert self._reactants_has_tetra_stereo is not None
        return self._reactants_has_tetra_stereo

    @property
    def reactants_has_doublebond_stereo(self) -> bool:
        if self._reactants_has_doublebond_stereo is None:
            self._ensure_bond_maps()
        assert self._reactants_has_doublebond_stereo is not None
        return self._reactants_has_doublebond_stereo

    @property
    def reactants_is_chiral(self) -> bool:
        if self._reactants_is_chiral is None:
            self._reactants_is_chiral = (
                self.reactants_has_tetra_stereo or self.reactants_has_doublebond_stereo
            )
        return self._reactants_is_chiral

    def idx_to_mapnum(self, idx: int) -> int:
        self._ensure_atom_maps()
        assert self._idx_to_map_num is not None
        return self._idx_to_map_num[idx]

rdchiralReaction

Bases: object

Class to store everything that should be pre-computed for a reaction. This makes library application much faster, since we can pre-do a lot of work instead of doing it for every mol-template pair

Attributes:

Name Type Description
reaction_smarts str

Reaction SMARTS string

rxn ChemicalReaction

RDKit reaction object. Generated lazily from reaction_smarts using initialize_rxn_from_smarts

template_r Mol

Reaction reactant template fragments

template_p Mol

Reaction product template fragments

atoms_rt_map dict

Dictionary mapping from atom map number to RDKit Atom for reactants

atoms_pt_map dict

Dictionary mapping from atom map number to RDKit Atom for products

atoms_rt_idx_to_map dict

Dictionary mapping from atom idx to atom map number for reactants

atoms_pt_idx_to_map dict

Dictionary mapping from atom idx to atom map number for products

Parameters:

Name Type Description Default
reaction_smarts str

Reaction SMARTS string

required
lazy_init bool

If True, delay initialization of the reaction object and template fragments until first accessed. Defaults to True.

True
Source code in rdchiral/initialization.py
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
class rdchiralReaction(object):
    """
    Class to store everything that should be pre-computed for a reaction. This
    makes library application much faster, since we can pre-do a lot of work
    instead of doing it for every mol-template pair

    Attributes:
        reaction_smarts (str): Reaction SMARTS string
        rxn (rdkit.Chem.rdChemReactions.ChemicalReaction): RDKit reaction object.
            Generated lazily from `reaction_smarts` using `initialize_rxn_from_smarts`
        template_r: Reaction reactant template fragments
        template_p: Reaction product template fragments
        atoms_rt_map (dict): Dictionary mapping from atom map number to RDKit Atom for reactants
        atoms_pt_map (dict): Dictionary mapping from atom map number to RDKit Atom for products
        atoms_rt_idx_to_map (dict): Dictionary mapping from atom idx to atom map number for reactants
        atoms_pt_idx_to_map (dict): Dictionary mapping from atom idx to atom map number for products

    Args:
        reaction_smarts (str): Reaction SMARTS string
        lazy_init (bool): If True, delay initialization of the reaction object and
            template fragments until first accessed. Defaults to True.
    """

    def __init__(self, reaction_smarts: str, lazy_init: bool = True):
        split_reaction_smarts = reaction_smarts.split(">>")
        # Treat as pseudo-intramolecular, so that reactions with multiple reacting centers can work
        if "." in split_reaction_smarts[0]:
            reaction_smarts = (
                "(" + split_reaction_smarts[0] + ")>>(" + split_reaction_smarts[1] + ")"
            )

        self.reaction_smarts: str = reaction_smarts

        self.fast_reactant_smarts: Chem.Mol = Chem.MolFromSmarts(
            split_reaction_smarts[0]
        )

        # Initialize lazily - assigns stereochemistry and fills in missing rct map numbers
        self._rxn: Optional[rdChemReactions.ChemicalReaction] = None

        self._template_r_orig: Optional[Chem.Mol] = None
        self._template_p_orig: Optional[Chem.Mol] = None
        self._template_r: Optional[Chem.Mol] = None
        self._template_p: Optional[Chem.Mol] = None

        # Define molAtomMapNumber->atom dictionary for template rct and prd
        self._atoms_rt_map: Optional[Dict[int, Chem.Atom]] = None
        self._atoms_pt_map: Optional[Dict[int, Chem.Atom]] = None

        # Back-up the mapping for the reaction
        self._atoms_rt_idx_to_map: Optional[Dict[int, int]] = None
        self._atoms_pt_idx_to_map: Optional[Dict[int, int]] = None

        # Pre-list chiral double bonds (for copying back into outcomes/matching)
        self._rt_bond_dirs_by_mapnum: Optional[Dict[Tuple[int, int], BondDir]] = None
        self._pt_bond_dirs_by_mapnum: Optional[Dict[Tuple[int, int], BondDir]] = None

        # Enumerate possible cis/trans...
        self._required_rt_bond_defs: Optional[
            Dict[Tuple[int, int, int, int], Tuple[BondDir, BondDir]]
        ] = None
        self._required_bond_defs_coreatoms: Optional[Set[Tuple[int, int]]] = None

        self._template_has_tetra_stereo: Optional[bool] = None
        self._template_has_doublebond_stereo: Optional[bool] = None
        self._template_is_chiral: Optional[bool] = None

        if not lazy_init:
            _ = self.rxn
            self._ensure_templates()
            _ = self.template_r_orig
            _ = self.template_p_orig
            _ = self.template_r
            _ = self.template_p
            _ = self.atoms_rt_map
            _ = self.atoms_pt_map
            _ = self.atoms_rt_idx_to_map
            _ = self.atoms_pt_idx_to_map
            _ = self.rt_bond_dirs_by_mapnum
            _ = self.pt_bond_dirs_by_mapnum
            _ = self.required_rt_bond_defs
            _ = self.required_bond_defs_coreatoms
            _ = self.template_has_tetra_stereo
            _ = self.template_has_doublebond_stereo
            _ = self.template_is_chiral

    @property
    def rxn(self) -> rdChemReactions.ChemicalReaction:
        if self._rxn is None:
            self._rxn = initialize_rxn_from_smarts(self.reaction_smarts)
        return self._rxn

    def _ensure_templates(self) -> None:
        """
        Ensure template fragments and derived data are initialized.

        If templates have not yet been created, extracts them from the reaction
        object, precomputes stereochemistry and atom-map lookups, and caches
        all derived properties on the instance.
        """
        if (
            self._template_r_orig is not None
            and self._template_p_orig is not None
            and self._template_r is not None
            and self._template_p is not None
        ):
            return

        if self._template_r_orig is None or self._template_p_orig is None:
            template_r, template_p = _get_template_frags_from_rxn(self.rxn)
            self._template_r_orig = Chem.Mol(template_r)
            self._template_p_orig = Chem.Mol(template_p)

        assert self._template_r_orig is not None
        assert self._template_p_orig is not None

        self._template_r = Chem.Mol(self._template_r_orig)
        self._template_p = Chem.Mol(self._template_p_orig)

        # Call template_atom_could_have_been_tetra to pre-assign value to atom
        for a in self._template_r.GetAtoms():
            template_atom_could_have_been_tetra(a)
        for a in self._template_p.GetAtoms():
            template_atom_could_have_been_tetra(a)

        # Precompute template invariants that depend on original atom-map numbers
        self._rt_bond_dirs_by_mapnum = bond_dirs_by_mapnum(self._template_r_orig)
        self._pt_bond_dirs_by_mapnum = bond_dirs_by_mapnum(self._template_p_orig)
        self._required_rt_bond_defs, self._required_bond_defs_coreatoms = (
            enumerate_possible_cistrans_defs(self._template_r_orig)
        )

        # Build atom-map dicts from the COPY, not the original.
        # assign_outcome_atom_mapnums mutates these atoms' map numbers in-place,
        # so they must NOT be the same objects as _template_r_orig's atoms.
        self._atoms_rt_map = {
            a.GetAtomMapNum(): a
            for a in self._template_r.GetAtoms()
            if a.GetAtomMapNum()
        }
        self._atoms_pt_map = {
            a.GetAtomMapNum(): a
            for a in self._template_p.GetAtoms()
            if a.GetAtomMapNum()
        }

        # Capture idx→mapnum from the originals while they are guaranteed clean
        self._atoms_rt_idx_to_map = {
            a.GetIdx(): a.GetAtomMapNum() for a in self._template_r_orig.GetAtoms()
        }
        self._atoms_pt_idx_to_map = {
            a.GetIdx(): a.GetAtomMapNum() for a in self._template_p_orig.GetAtoms()
        }

    @property
    def template_r_orig(self) -> Chem.Mol:
        if self._template_r_orig is None:
            self._ensure_templates()
        assert self._template_r_orig is not None
        return self._template_r_orig

    @property
    def template_p_orig(self) -> Chem.Mol:
        if self._template_p_orig is None:
            self._ensure_templates()
        assert self._template_p_orig is not None
        return self._template_p_orig

    @property
    def template_r(self) -> Chem.Mol:
        if self._template_r is None:
            self._ensure_templates()
        assert self._template_r is not None
        return self._template_r

    @property
    def template_p(self) -> Chem.Mol:
        if self._template_p is None:
            self._ensure_templates()
        assert self._template_p is not None
        return self._template_p

    @property
    def atoms_rt_map(self) -> Dict[int, Chem.Atom]:
        if self._rt_bond_dirs_by_mapnum is None:
            self._ensure_templates()
            self._rt_bond_dirs_by_mapnum = bond_dirs_by_mapnum(self.template_r)
        if (
            self._required_rt_bond_defs is None
            or self._required_bond_defs_coreatoms is None
        ):
            self._ensure_templates()
            self._required_rt_bond_defs, self._required_bond_defs_coreatoms = (
                enumerate_possible_cistrans_defs(self.template_r)
            )
        if self._atoms_rt_map is None:
            self._ensure_templates()
            self._atoms_rt_map = {
                a.GetAtomMapNum(): a
                for a in self.template_r.GetAtoms()
                if a.GetAtomMapNum()
            }
        assert self._atoms_rt_map is not None
        return self._atoms_rt_map

    @property
    def atoms_pt_map(self) -> Dict[int, Chem.Atom]:
        if self._pt_bond_dirs_by_mapnum is None:
            self._ensure_templates()
            self._pt_bond_dirs_by_mapnum = bond_dirs_by_mapnum(self.template_p)
        if self._atoms_pt_map is None:
            self._atoms_pt_map = {
                a.GetAtomMapNum(): a
                for a in self.template_p.GetAtoms()
                if a.GetAtomMapNum()
            }
        assert self._atoms_pt_map is not None
        return self._atoms_pt_map

    @property
    def atoms_rt_idx_to_map(self) -> Dict[int, int]:
        if self._atoms_rt_idx_to_map is None:
            self._ensure_templates()
            self._atoms_rt_idx_to_map = {
                a.GetIdx(): a.GetAtomMapNum() for a in self.template_r_orig.GetAtoms()
            }
        assert self._atoms_rt_idx_to_map is not None
        return self._atoms_rt_idx_to_map

    @property
    def atoms_pt_idx_to_map(self) -> Dict[int, int]:
        if self._atoms_pt_idx_to_map is None:
            self._ensure_templates()
            self._atoms_pt_idx_to_map = {
                a.GetIdx(): a.GetAtomMapNum() for a in self.template_p_orig.GetAtoms()
            }
        assert self._atoms_pt_idx_to_map is not None
        return self._atoms_pt_idx_to_map

    @property
    def rt_bond_dirs_by_mapnum(self) -> Dict[Tuple[int, int], BondDir]:
        if self._rt_bond_dirs_by_mapnum is None:
            self._ensure_templates()
            self._rt_bond_dirs_by_mapnum = bond_dirs_by_mapnum(self.template_r)
        assert self._rt_bond_dirs_by_mapnum is not None
        return self._rt_bond_dirs_by_mapnum

    @property
    def pt_bond_dirs_by_mapnum(self) -> Dict[Tuple[int, int], BondDir]:
        if self._pt_bond_dirs_by_mapnum is None:
            self._ensure_templates()
            self._pt_bond_dirs_by_mapnum = bond_dirs_by_mapnum(self.template_p)
        assert self._pt_bond_dirs_by_mapnum is not None
        return self._pt_bond_dirs_by_mapnum

    @property
    def required_rt_bond_defs(
        self,
    ) -> Dict[Tuple[int, int, int, int], Tuple[BondDir, BondDir]]:
        if self._required_rt_bond_defs is None:
            self._ensure_templates()
            self._required_rt_bond_defs, self._required_bond_defs_coreatoms = (
                enumerate_possible_cistrans_defs(self.template_r)
            )
        assert self._required_rt_bond_defs is not None
        return self._required_rt_bond_defs

    @property
    def required_bond_defs_coreatoms(self) -> Set[Tuple[int, int]]:
        if self._required_bond_defs_coreatoms is None:
            self._ensure_templates()
            self._required_rt_bond_defs, self._required_bond_defs_coreatoms = (
                enumerate_possible_cistrans_defs(self.template_r)
            )
        assert self._required_bond_defs_coreatoms is not None
        return self._required_bond_defs_coreatoms

    @property
    def template_has_tetra_stereo(self) -> bool:
        if self._template_has_tetra_stereo is None:
            self._ensure_templates()
            self._template_has_tetra_stereo = _has_tetra_stereo(
                self.template_r
            ) or _has_tetra_stereo(self.template_p)
        return self._template_has_tetra_stereo

    @property
    def template_has_doublebond_stereo(self) -> bool:
        if self._template_has_doublebond_stereo is None:
            self._ensure_templates()
            self._template_has_doublebond_stereo = _has_doublebond_stereo(
                self.template_r
            ) or _has_doublebond_stereo(self.template_p)
        return self._template_has_doublebond_stereo

    @property
    def template_is_chiral(self) -> bool:
        if self._template_is_chiral is None:
            self._ensure_templates()
            if self._template_has_tetra_stereo is None:
                self._template_has_tetra_stereo = _has_tetra_stereo(
                    self.template_r
                ) or _has_tetra_stereo(self.template_p)
            if self._template_has_doublebond_stereo is None:
                self._template_has_doublebond_stereo = _has_doublebond_stereo(
                    self.template_r
                ) or _has_doublebond_stereo(self.template_p)
            self._template_is_chiral = (
                self._template_has_tetra_stereo or self._template_has_doublebond_stereo
            )
        return self._template_is_chiral

    def reset(self) -> None:
        """
        Restore template fragment atom-map numbers to their original values.

        Iterates over `template_r` and `template_p` atoms and resets each
        atom's map number to the value recorded in `atoms_rt_idx_to_map` /
        `atoms_pt_idx_to_map` during initialization. This is an in-place
        operation — no molecular graph copy is made.

        Note:
            This method must be called between reaction applications when
            reusing the same `rdchiralReaction` object, because
            `assign_outcome_atom_mapnums` and `assign_pt_mapnums` mutate
            template atom map numbers in-place.
        """
        if not self._template_r or not self._template_p:
            self._ensure_templates()
        assert self._template_r is not None
        assert self._template_p is not None
        assert self._atoms_rt_idx_to_map is not None
        assert self._atoms_pt_idx_to_map is not None
        for a in self._template_r.GetAtoms():
            a.SetAtomMapNum(self._atoms_rt_idx_to_map[a.GetIdx()])
        for a in self._template_p.GetAtoms():
            a.SetAtomMapNum(self._atoms_pt_idx_to_map[a.GetIdx()])

reset()

Restore template fragment atom-map numbers to their original values.

Iterates over template_r and template_p atoms and resets each atom's map number to the value recorded in atoms_rt_idx_to_map / atoms_pt_idx_to_map during initialization. This is an in-place operation — no molecular graph copy is made.

Note

This method must be called between reaction applications when reusing the same rdchiralReaction object, because assign_outcome_atom_mapnums and assign_pt_mapnums mutate template atom map numbers in-place.

Source code in rdchiral/initialization.py
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
def reset(self) -> None:
    """
    Restore template fragment atom-map numbers to their original values.

    Iterates over `template_r` and `template_p` atoms and resets each
    atom's map number to the value recorded in `atoms_rt_idx_to_map` /
    `atoms_pt_idx_to_map` during initialization. This is an in-place
    operation — no molecular graph copy is made.

    Note:
        This method must be called between reaction applications when
        reusing the same `rdchiralReaction` object, because
        `assign_outcome_atom_mapnums` and `assign_pt_mapnums` mutate
        template atom map numbers in-place.
    """
    if not self._template_r or not self._template_p:
        self._ensure_templates()
    assert self._template_r is not None
    assert self._template_p is not None
    assert self._atoms_rt_idx_to_map is not None
    assert self._atoms_pt_idx_to_map is not None
    for a in self._template_r.GetAtoms():
        a.SetAtomMapNum(self._atoms_rt_idx_to_map[a.GetIdx()])
    for a in self._template_p.GetAtoms():
        a.SetAtomMapNum(self._atoms_pt_idx_to_map[a.GetIdx()])

extract_from_reaction(reaction, no_special_groups=False, radius=1, use_stereochemistry=True, canonicalize_template=True, maximum_number_unmapped_product_atoms=5, include_all_unmapped_reactant_atoms=True)

Extract a retrosynthetic reaction template from a mapped chemical reaction.

This function analyzes a chemical reaction with atom-mapped reactants and products to identify the reaction center and extract a template representing the transformation. The template captures the local environment around atoms that change during the reaction, including bonds formed, broken, or modified.

Parameters:

Name Type Description Default
reaction rdChiralTemplateExtractInput

Dictionary containing the reaction data with keys 'reactants' (SMILES string), 'products' (SMILES string), and '_id' (optional reaction identifier).

required
no_special_groups bool

If True, disable special functional group handling during fragment extraction. Defaults to False.

False
radius int

Number of bonds to expand around changed atoms when extracting fragments. A larger radius captures more context. Defaults to 1.

1
use_stereochemistry bool

If True, include stereochemical information in the extracted template. Defaults to True.

True
canonicalize_template bool

If True, canonicalize the reaction SMARTS string for consistent representation. Defaults to True.

True
maximum_number_unmapped_product_atoms int

Maximum allowed number of unmapped atoms in the products. Reactions exceeding this limit are skipped. Defaults to 5.

5
include_all_unmapped_reactant_atoms bool

If True, include all unmapped reactant atoms in the template, not just those near the reaction center. Defaults to True.

True

Returns:

Name Type Description
ExtractedTemplate ExtractedTemplate

A dictionary containing the extracted template with the following keys: - 'products': Product fragment SMARTS string - 'reactants': Reactant fragment SMARTS string - 'spectators': SMILES string of spectator molecules (reactants not participating in the reaction) - 'reaction_smarts': Complete retrosynthetic reaction SMARTS (products>>reactants) - 'separated_reaction_smarts': List of individual reaction SMARTS components - 'intra_only': Boolean indicating if the reaction is intramolecular - 'dimer_only': Boolean indicating if the reaction involves dimerization - 'reaction_id': The reaction identifier from the input - 'necessary_reagent': SMILES fragment for unmapped product atoms that must be supplied as reagents

Raises:

Type Description
ValueError

Propagated from get_fragments_for_changed_atoms if fragment extraction fails (caught internally and returns default template).

Note

This function returns a default empty template (with empty strings and False flags) if any of the following conditions occur: - RDKit fails to parse reactants or products - The number of unmapped product atoms exceeds the maximum threshold - No reactant atoms are mapped to product atoms - Molecule sanitization fails - No atoms change between reactants and products - The extracted reaction SMARTS fails RDKit validation The returned template uses retro-synthetic direction (products>>reactants).

Source code in rdchiral/template_extractor.py
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
def extract_from_reaction(
    reaction: rdChiralTemplateExtractInput,
    no_special_groups: bool = False,
    radius: int = 1,
    use_stereochemistry: bool = True,
    canonicalize_template: bool = True,
    maximum_number_unmapped_product_atoms: int = 5,
    include_all_unmapped_reactant_atoms: bool = True,
) -> ExtractedTemplate:
    """
    Extract a retrosynthetic reaction template from a mapped chemical reaction.

    This function analyzes a chemical reaction with atom-mapped reactants and products
    to identify the reaction center and extract a template representing the
    transformation. The template captures the local environment around atoms that
    change during the reaction, including bonds formed, broken, or modified.

    Args:
        reaction (rdChiralTemplateExtractInput): Dictionary containing the reaction
            data with keys 'reactants' (SMILES string), 'products' (SMILES string),
            and '_id' (optional reaction identifier).
        no_special_groups (bool): If True, disable special functional group handling
            during fragment extraction. Defaults to False.
        radius (int): Number of bonds to expand around changed atoms when extracting
            fragments. A larger radius captures more context. Defaults to 1.
        use_stereochemistry (bool): If True, include stereochemical information in
            the extracted template. Defaults to True.
        canonicalize_template (bool): If True, canonicalize the reaction SMARTS
            string for consistent representation. Defaults to True.
        maximum_number_unmapped_product_atoms (int): Maximum allowed number of
            unmapped atoms in the products. Reactions exceeding this limit are
            skipped. Defaults to 5.
        include_all_unmapped_reactant_atoms (bool): If True, include all unmapped
            reactant atoms in the template, not just those near the reaction center.
            Defaults to True.

    Returns:
        ExtractedTemplate: A dictionary containing the extracted template with the
            following keys:
            - 'products': Product fragment SMARTS string
            - 'reactants': Reactant fragment SMARTS string
            - 'spectators': SMILES string of spectator molecules (reactants not
              participating in the reaction)
            - 'reaction_smarts': Complete retrosynthetic reaction SMARTS
              (products>>reactants)
            - 'separated_reaction_smarts': List of individual reaction SMARTS
              components
            - 'intra_only': Boolean indicating if the reaction is intramolecular
            - 'dimer_only': Boolean indicating if the reaction involves dimerization
            - 'reaction_id': The reaction identifier from the input
            - 'necessary_reagent': SMILES fragment for unmapped product atoms that
              must be supplied as reagents

    Raises:
        ValueError: Propagated from get_fragments_for_changed_atoms if fragment
            extraction fails (caught internally and returns default template).

    Note:
        This function returns a default empty template (with empty strings and
        False flags) if any of the following conditions occur:
        - RDKit fails to parse reactants or products
        - The number of unmapped product atoms exceeds the maximum threshold
        - No reactant atoms are mapped to product atoms
        - Molecule sanitization fails
        - No atoms change between reactants and products
        - The extracted reaction SMARTS fails RDKit validation
        The returned template uses retro-synthetic direction (products>>reactants).
    """
    # Build a default template that preserves the reaction_id for early returns
    default_template: ExtractedTemplate = {
        **DEFAULT_EXTRACTED_TEMPLATE,
        "reaction_id": reaction["_id"],
    }

    reactants = mols_from_smiles_list(
        replace_deuterated(reaction["reactants"]).split(".")
    )
    products = mols_from_smiles_list(
        replace_deuterated(reaction["products"]).split(".")
    )

    # if rdkit cant understand molecule, return
    if None in reactants:
        return default_template
    if None in products:
        return default_template

    are_unmapped_product_atoms = False
    num_unmapped_product_atoms = 0
    unmapped_ids = []
    seen_atom_map_nums = set()
    for product in products:
        prod_atoms = list(product.GetAtoms())
        num_mapped_atoms = 0
        for atom in prod_atoms:
            map_num = atom.GetAtomMapNum()
            if map_num:
                seen_atom_map_nums.add(map_num)
                num_mapped_atoms += 1
            else:
                num_unmapped_product_atoms += 1
                unmapped_ids.append(atom.GetIdx())
                if num_unmapped_product_atoms > maximum_number_unmapped_product_atoms:
                    # Skip this example - too many unmapped product atoms!
                    return default_template
        if num_mapped_atoms < len(prod_atoms):
            are_unmapped_product_atoms = True

    reactants_in_reaction = []
    for reactant in reactants:
        for atom in reactant.GetAtoms():
            map_num = atom.GetAtomMapNum()
            if map_num and map_num in seen_atom_map_nums:
                reactants_in_reaction.append(reactant)
                break
    spectators_string = ".".join(
        [
            Chem.MolToSmiles(reactant)
            for reactant in reactants
            if reactant not in reactants_in_reaction
        ]
    )
    reactants = reactants_in_reaction
    if not reactants:
        return default_template

    # try to sanitize molecules
    try:
        for i in range(len(reactants)):
            reactants[i] = Chem.RemoveHs(reactants[i])  # *might* not be safe
        for i in range(len(products)):
            products[i] = Chem.RemoveHs(products[i])  # *might* not be safe
        for mol in reactants + products:
            mol = Chem.SanitizeMol(mol)  # redundant w/ RemoveHs
        for mol in reactants + products:
            mol.UpdatePropertyCache()
    except Exception:
        # can't sanitize -> skip
        return default_template

    if None in reactants + products:
        return default_template

    extra_reactant_fragment = ""
    if are_unmapped_product_atoms:  # add fragment to template
        for product in products:
            # Define new atom symbols for fragment with atom maps, generalizing fully
            atom_symbols = ["[{}]".format(a.GetSymbol()) for a in product.GetAtoms()]
            # And bond symbols...
            bond_symbols = ["~" for _ in product.GetBonds()]
            if unmapped_ids:
                extra_reactant_fragment += (
                    rdmolfiles.MolFragmentToSmiles(
                        product,
                        unmapped_ids,
                        allHsExplicit=False,
                        isomericSmiles=use_stereochemistry,
                        atomSymbols=atom_symbols,
                        bondSymbols=bond_symbols,
                    )
                    + "."
                )
        if extra_reactant_fragment:
            extra_reactant_fragment = extra_reactant_fragment[:-1]

        # Consolidate repeated fragments (stoichometry)
        extra_reactant_fragment = ".".join(
            sorted(set(extra_reactant_fragment.split(".")))
        )

    # Calculate changed atoms
    _changed_atoms, changed_atom_tags, err = get_changed_atoms(reactants, products)
    if err:
        return default_template
    if not changed_atom_tags:
        return default_template

    try:
        # Get fragments for reactants
        reactant_fragments, intra_only, dimer_only = get_fragments_for_changed_atoms(
            reactants,
            changed_atom_tags,
            radius=radius,
            expansion=[],
            category="reactants",
            no_special_groups=no_special_groups,
            include_all_unmapped_reactant_atoms=include_all_unmapped_reactant_atoms,
        )
        # Get fragments for products
        # (WITHOUT matching groups but WITH the addition of reactant fragments)
        product_fragments, _, _ = get_fragments_for_changed_atoms(
            products,
            changed_atom_tags,
            radius=0,
            expansion=expand_changed_atom_tags(changed_atom_tags, reactant_fragments),
            category="products",
        )

    except ValueError:
        return default_template

    # Put together and canonicalize (as best as possible)
    rxn_string = "{}>>{}".format(reactant_fragments, product_fragments)
    if canonicalize_template:
        rxn_canonical = canonicalize_transform(rxn_string)
    else:
        rxn_canonical = rxn_string
    # Change from inter-molecular to intra-molecular
    rxn_canonical_split = rxn_canonical.split(">>")
    rxn_canonical = (
        rxn_canonical_split[0][1:-1].replace(").(", ".")
        + ">>"
        + rxn_canonical_split[1][1:-1].replace(").(", ".")
    )

    reactants_string = rxn_canonical.split(">>")[0]
    products_string = rxn_canonical.split(">>")[1]

    retro_canonical = products_string + ">>" + reactants_string

    # Load into RDKit
    rxn: Optional[rdChemReactions.ChemicalReaction] = (
        rdChemReactions.ReactionFromSmarts(retro_canonical)
    )
    if rxn is None:
        return default_template
    if rxn.Validate()[1] != 0:
        return default_template

    template: ExtractedTemplate = {
        "products": products_string,
        "reactants": reactants_string,
        "spectators": spectators_string,
        "reaction_smarts": retro_canonical,
        "separated_reaction_smarts": split_reaction_smarts(retro_canonical),
        "intra_only": intra_only,
        "dimer_only": dimer_only,
        "reaction_id": reaction["_id"],
        "necessary_reagent": extra_reactant_fragment,
    }

    return template

extract_from_reaction_smiles(rxn_smiles, no_special_groups=False, radius=1, use_stereochemistry=True, canonicalize_template=True, maximum_number_unmapped_product_atoms=5, include_all_unmapped_reactant_atoms=True, reaction_id=None)

Extract a retrosynthetic reaction template from a reaction SMILES string.

This function parses a reaction SMILES string and extracts a template representing the chemical transformation. It is a convenience wrapper around extract_from_reaction that handles the SMILES parsing and delegates to the core extraction logic.

Parameters:

Name Type Description Default
rxn_smiles str

Reaction SMILES string in the format "reactants>>products". The reactants and products should have atom mapping numbers for template extraction to work correctly.

required
no_special_groups bool

If True, disable special functional group handling during fragment extraction. Defaults to False.

False
radius int

Number of bonds to expand around changed atoms when extracting fragments. A larger radius captures more context. Defaults to 1.

1
use_stereochemistry bool

If True, include stereochemical information in the extracted template. Defaults to True.

True
canonicalize_template bool

If True, canonicalize the reaction SMARTS string for consistent representation. Defaults to True.

True
maximum_number_unmapped_product_atoms int

Maximum allowed number of unmapped atoms in the products. Reactions exceeding this limit are skipped. Defaults to 5.

5
include_all_unmapped_reactant_atoms bool

If True, include all unmapped reactant atoms in the template, not just those near the reaction center. Defaults to True.

True
reaction_id Optional[str | int]

Optional identifier for the reaction. This will be included in the returned template.

None

Returns:

Name Type Description
ExtractedTemplate ExtractedTemplate

A dictionary containing the extracted template with the following keys: - 'products': Product fragment SMARTS string - 'reactants': Reactant fragment SMARTS string - 'spectators': SMILES string of spectator molecules (reactants not participating in the reaction) - 'reaction_smarts': Complete retrosynthetic reaction SMARTS (products>>reactants) - 'separated_reaction_smarts': List of individual reaction SMARTS components - 'intra_only': Boolean indicating if the reaction is intramolecular - 'dimer_only': Boolean indicating if the reaction involves dimerization - 'reaction_id': The reaction identifier from the input - 'necessary_reagent': SMILES fragment for unmapped product atoms that must be supplied as reagents

Raises:

Type Description
ValueError

If the reaction SMILES does not contain exactly one '>>' separator.

Source code in rdchiral/template_extractor.py
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
def extract_from_reaction_smiles(
    rxn_smiles: str,
    no_special_groups: bool = False,
    radius: int = 1,
    use_stereochemistry: bool = True,
    canonicalize_template: bool = True,
    maximum_number_unmapped_product_atoms: int = 5,
    include_all_unmapped_reactant_atoms: bool = True,
    reaction_id: Optional[str | int] = None,
) -> ExtractedTemplate:
    """
    Extract a retrosynthetic reaction template from a reaction SMILES string.

    This function parses a reaction SMILES string and extracts a template representing
    the chemical transformation. It is a convenience wrapper around extract_from_reaction
    that handles the SMILES parsing and delegates to the core extraction logic.

    Args:
        rxn_smiles (str): Reaction SMILES string in the format "reactants>>products".
            The reactants and products should have atom mapping numbers for template
            extraction to work correctly.
        no_special_groups (bool): If True, disable special functional group handling
            during fragment extraction. Defaults to False.
        radius (int): Number of bonds to expand around changed atoms when extracting
            fragments. A larger radius captures more context. Defaults to 1.
        use_stereochemistry (bool): If True, include stereochemical information in
            the extracted template. Defaults to True.
        canonicalize_template (bool): If True, canonicalize the reaction SMARTS
            string for consistent representation. Defaults to True.
        maximum_number_unmapped_product_atoms (int): Maximum allowed number of
            unmapped atoms in the products. Reactions exceeding this limit are
            skipped. Defaults to 5.
        include_all_unmapped_reactant_atoms (bool): If True, include all unmapped
            reactant atoms in the template, not just those near the reaction center.
            Defaults to True.
        reaction_id (Optional[str | int]): Optional identifier for the reaction.
            This will be included in the returned template.

    Returns:
        ExtractedTemplate: A dictionary containing the extracted template with the
            following keys:
            - 'products': Product fragment SMARTS string
            - 'reactants': Reactant fragment SMARTS string
            - 'spectators': SMILES string of spectator molecules (reactants not
              participating in the reaction)
            - 'reaction_smarts': Complete retrosynthetic reaction SMARTS
              (products>>reactants)
            - 'separated_reaction_smarts': List of individual reaction SMARTS
              components
            - 'intra_only': Boolean indicating if the reaction is intramolecular
            - 'dimer_only': Boolean indicating if the reaction involves dimerization
            - 'reaction_id': The reaction identifier from the input
            - 'necessary_reagent': SMILES fragment for unmapped product atoms that
              must be supplied as reagents

    Raises:
        ValueError: If the reaction SMILES does not contain exactly one '>>' separator.
    """
    if len(rxn_smiles.split(">>")) != 2:
        raise ValueError("Reaction SMILES must contain exactly one >>")

    reactants = rxn_smiles.split(">>")[0]
    products = rxn_smiles.split(">>")[1]
    reaction_dict: rdChiralTemplateExtractInput = {
        "reactants": reactants,
        "products": products,
        "spectators": "",
        "_id": reaction_id,
    }

    return extract_from_reaction(
        reaction=reaction_dict,
        no_special_groups=no_special_groups,
        radius=radius,
        use_stereochemistry=use_stereochemistry,
        canonicalize_template=canonicalize_template,
        maximum_number_unmapped_product_atoms=maximum_number_unmapped_product_atoms,
        include_all_unmapped_reactant_atoms=include_all_unmapped_reactant_atoms,
    )

rdchiralRun(rxn, reactants, keep_mapnums=False, combine_enantiomers=True, return_mapped=False, skip_reset=False, max_depth=1, max_products=100)

Iteratively apply an rdchiral reaction template to reactants across multiple depth levels.

At each depth level, the products from the previous iteration are used as reactants for the next iteration. This enables multi-step reaction prediction where products can undergo further transformations defined by the same reaction template.

Parameters:

Name Type Description Default
rxn rdchiralReaction

The reaction template to apply.

required
reactants rdchiralReactants

The initial reactants to start the iteration.

required
keep_mapnums bool

If True, preserve atom map numbers in the output SMILES.

False
combine_enantiomers bool

If True, combine enantiomeric outcomes into their achiral racemic equivalents, removing the individual enantiomers. If False, enantiomers are retained and their achiral racemic forms are also appended to the results.

True
return_mapped bool

If True, return a mapping between mapped and unmapped SMILES along with atom change information.

False
skip_reset bool

If True, skip resetting the reaction object state. Ignored if max_depth > 1, as reset is forced for multi-depth iterations.

False
max_depth int

Maximum number of iterative depth levels to explore (default: 1).

1
max_products int

Maximum number of products to return (default: 100).

100

Returns:

Type Description
Union[List[str], Tuple[List[str], Dict[str, Tuple[str, Tuple[int, ...]]]]]

Union[List[str], Tuple[List[str], Dict[str, Tuple[str, Tuple[int, ...]]]]]: - If return_mapped is False: A list of product SMILES strings. - If return_mapped is True: A tuple containing: - List of product SMILES strings - Dictionary mapping SMILES to a tuple of (mapped_smiles, flattened_changes) where flattened_changes contains all atom indices that changed across all depth levels.

Note

When max_depth > 1, skip_reset is automatically set to False to ensure correct reaction state between iterations. Products already seen at any depth are skipped to avoid duplicate processing and infinite loops.

Source code in rdchiral/main.py
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
def rdchiralRun(
    rxn: rdchiralReaction,
    reactants: rdchiralReactants,
    keep_mapnums: bool = False,
    combine_enantiomers: bool = True,
    return_mapped: bool = False,
    skip_reset: bool = False,
    max_depth: int = 1,
    max_products: int = 100,
) -> Union[List[str], Tuple[List[str], Dict[str, Tuple[str, Tuple[int, ...]]]]]:
    """
    Iteratively apply an rdchiral reaction template to reactants across multiple depth levels.

    At each depth level, the products from the previous iteration are used as reactants
    for the next iteration. This enables multi-step reaction prediction where products
    can undergo further transformations defined by the same reaction template.

    Args:
        rxn (rdchiralReaction): The reaction template to apply.
        reactants (rdchiralReactants): The initial reactants to start the iteration.
        keep_mapnums (bool): If True, preserve atom map numbers in the output SMILES.
        combine_enantiomers (bool): If True, combine enantiomeric outcomes into their
            achiral racemic equivalents, removing the individual enantiomers. If False,
            enantiomers are retained and their achiral racemic forms are also appended
            to the results.
        return_mapped (bool): If True, return a mapping between mapped and unmapped SMILES
            along with atom change information.
        skip_reset (bool): If True, skip resetting the reaction object state. Ignored if
            max_depth > 1, as reset is forced for multi-depth iterations.
        max_depth (int): Maximum number of iterative depth levels to explore (default: 1).
        max_products (int): Maximum number of products to return (default: 100).

    Returns:
        Union[List[str], Tuple[List[str], Dict[str, Tuple[str, Tuple[int, ...]]]]]:
            - If return_mapped is False: A list of product SMILES strings.
            - If return_mapped is True: A tuple containing:
                - List of product SMILES strings
                - Dictionary mapping SMILES to a tuple of (mapped_smiles, flattened_changes)
                  where flattened_changes contains all atom indices that changed across
                  all depth levels.

    Note:
        When max_depth > 1, skip_reset is automatically set to False to ensure correct
        reaction state between iterations. Products already seen at any depth are skipped
        to avoid duplicate processing and infinite loops.
    """
    if max_depth == 1:
        if return_mapped:
            return rdchiral_step_return_mapped(
                rxn=rxn,
                reactants=reactants,
                keep_mapnums=keep_mapnums,
                combine_enantiomers=combine_enantiomers,
                skip_reset=skip_reset,
            )
        else:
            return rdchiral_step(
                rxn=rxn,
                reactants=reactants,
                keep_mapnums=keep_mapnums,
                combine_enantiomers=combine_enantiomers,
                skip_reset=skip_reset,
            )

    # if max_depth is going to be greater than 1, we should force reset rxn
    skip_reset = False

    custom_reactant_mapping = False
    current_level: Dict[
        str, Tuple[str, Optional[rdchiralReactants], List[Tuple[int, ...]]]
    ] = {reactants.reactant_smiles: (reactants.reactant_smiles, reactants, [])}
    all_products: Dict[str, Tuple[str, List[Tuple[int, ...]]]] = {}

    num_products = 0
    for _ in range(max_depth):
        next_level: Dict[
            str, Tuple[str, Optional[rdchiralReactants], List[Tuple[int, ...]]]
        ] = {}

        for parent_mapped, (
            parent_unmapped,
            parent_reactants,
            accumulated_changes,
        ) in current_level.items():
            if parent_reactants is None:
                parent_reactants = rdchiralReactants(
                    parent_mapped, custom_reactant_mapping=custom_reactant_mapping
                )
            product_smiles, product_mapped = rdchiral_step_return_mapped(
                rxn,
                parent_reactants,
                keep_mapnums=True,
                combine_enantiomers=False,
                skip_reset=skip_reset,
            )
            custom_reactant_mapping = True
            if not product_smiles:
                continue

            # Process each product
            for product_smiles_mapped in product_smiles:
                if product_smiles_mapped in all_products:
                    continue
                num_products += 1

                product_smiles_unmapped = strip_map_numbers_from_smiles(
                    product_smiles_mapped
                )

                _, changed_atoms = product_mapped[product_smiles_mapped]
                child_accumulated_changes = accumulated_changes + [changed_atoms]

                next_level[product_smiles_mapped] = (
                    product_smiles_unmapped,
                    None,
                    child_accumulated_changes,
                )
                all_products[product_smiles_mapped] = (
                    product_smiles_unmapped,
                    child_accumulated_changes,
                )

            if num_products >= max_products:
                break

        if not next_level:
            break

        current_level = next_level

        if num_products >= max_products:
            break

    if not keep_mapnums:
        final_smiles_list = list({unmapped for unmapped, _ in all_products.values()})
    else:
        final_smiles_list = list({mapped for mapped in all_products})

    _, combined_enantiomers_dict = combine_enantiomers_into_racemic(
        set(final_smiles_list)
    )

    if combine_enantiomers:
        final_smiles_list = list(
            set(combined_enantiomers_dict.values())
            | (set(final_smiles_list) - set(combined_enantiomers_dict.keys()))
        )
        chiral_to_achiral = combined_enantiomers_dict
    else:
        final_smiles_list.extend(list(set(combined_enantiomers_dict.values())))
        added_achiral = set()
        for chiral_smiles, achiral_smiles in combined_enantiomers_dict.items():
            if achiral_smiles in added_achiral:
                continue
            if keep_mapnums:
                if chiral_smiles in all_products:
                    _, changes = all_products[chiral_smiles]
                    all_products[achiral_smiles] = (
                        strip_map_numbers_from_smiles(achiral_smiles),
                        changes,
                    )
                    added_achiral.add(achiral_smiles)
            else:
                for mapped_key, (unmapped_val, changes) in all_products.items():
                    if unmapped_val == chiral_smiles:
                        mol = Chem.MolFromSmiles(mapped_key)
                        Chem.RemoveStereochemistry(mol)
                        achiral_mapped = Chem.MolToSmiles(mol, True)
                        all_products[achiral_mapped] = (achiral_smiles, changes)
                        added_achiral.add(achiral_smiles)
                        break
        chiral_to_achiral = {}

    all_products = fix_return_mapped_dict_enantiomers(
        all_products=all_products,
        chiral_to_achiral=chiral_to_achiral,
        keep_mapnums=keep_mapnums,
    )

    final_smiles_list = list(set(final_smiles_list))

    if return_mapped:
        if not keep_mapnums:
            mapped_dict = {
                unmapped: (mapped, tuple(x for t in changes for x in t))
                for mapped, (unmapped, changes) in all_products.items()
            }
            return (final_smiles_list, mapped_dict)
        else:
            mapped_dict = {
                mapped: (mapped, tuple(x for t in changes for x in t))
                for mapped, (_, changes) in all_products.items()
            }
            return (final_smiles_list, mapped_dict)

    else:
        return final_smiles_list

rdchiralRunText(reaction_smarts, reactant_smiles, custom_reactant_mapping=False, keep_mapnums=False, combine_enantiomers=True, return_mapped=False, max_depth=1, max_products=100)

Run a reaction by constructing rdchiralReaction and rdchiralReactants from text inputs.

Parameters:

Name Type Description Default
reaction_smarts str

Reaction SMARTS string used to initialize rdchiralReaction.

required
reactant_smiles str

Reactant SMILES string used to initialize rdchiralReactants.

required
custom_reactant_mapping bool

If True, assume the input reactants already contain an atom-mapping that should be preserved/used.

False
keep_mapnums bool

If True, preserve atom map numbers in returned product SMILES.

False
combine_enantiomers bool

If True, combine enantiomeric outcomes into their achiral racemic equivalents, removing the individual enantiomers. If False, enantiomers are retained and their achiral racemic forms are also appended to the results.

True
return_mapped bool

If True, also return per-outcome atom-mapped information.

False
max_depth int

Maximum number of iterative depth levels to explore (default: 1).

1
max_products int

Maximum number of products to return (default: 100).

100

Returns:

Type Description
Union[List[str], Tuple[List[str], Dict[str, Tuple[str, Tuple[int, ...]]]]]

Union[List[str], Tuple[List[str], Dict[str, Tuple[str, Tuple[int, ...]]]]]: - If return_mapped is False: A list of product SMILES strings. - If return_mapped is True: A tuple of (outcomes, mapped_outcomes) as returned by rdchiralRun.

Note

This helper is convenient for one-off use but is not recommended for batch/library workflows because template/reactant initialization is relatively expensive. For repeated application, construct rdchiralReaction and rdchiralReactants once and call rdchiralRun directly.

Source code in rdchiral/main.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
def rdchiralRunText(
    reaction_smarts: str,
    reactant_smiles: str,
    custom_reactant_mapping: bool = False,
    keep_mapnums: bool = False,
    combine_enantiomers: bool = True,
    return_mapped: bool = False,
    max_depth: int = 1,
    max_products: int = 100,
) -> Union[List[str], Tuple[List[str], Dict[str, Tuple[str, Tuple[int, ...]]]]]:
    """
    Run a reaction by constructing `rdchiralReaction` and `rdchiralReactants` from text inputs.

    Args:
        reaction_smarts (str): Reaction SMARTS string used to initialize `rdchiralReaction`.
        reactant_smiles (str): Reactant SMILES string used to initialize `rdchiralReactants`.
        custom_reactant_mapping (bool): If True, assume the input reactants already contain
            an atom-mapping that should be preserved/used.
        keep_mapnums (bool): If True, preserve atom map numbers in returned product SMILES.
        combine_enantiomers (bool): If True, combine enantiomeric outcomes into their
            achiral racemic equivalents, removing the individual enantiomers. If False,
            enantiomers are retained and their achiral racemic forms are also appended
            to the results.
        return_mapped (bool): If True, also return per-outcome atom-mapped information.
        max_depth (int): Maximum number of iterative depth levels to explore (default: 1).
        max_products (int): Maximum number of products to return (default: 100).

    Returns:
        Union[List[str], Tuple[List[str], Dict[str, Tuple[str, Tuple[int, ...]]]]]:
            - If `return_mapped` is False: A list of product SMILES strings.
            - If `return_mapped` is True: A tuple of `(outcomes, mapped_outcomes)` as
              returned by `rdchiralRun`.

    Note:
        This helper is convenient for one-off use but is not recommended for batch/library
        workflows because template/reactant initialization is relatively expensive. For
        repeated application, construct `rdchiralReaction` and `rdchiralReactants` once and
        call `rdchiralRun` directly.
    """
    rxn = rdchiralReaction(reaction_smarts)
    reactants = rdchiralReactants(reactant_smiles, custom_reactant_mapping)
    return rdchiralRun(
        rxn=rxn,
        reactants=reactants,
        keep_mapnums=keep_mapnums,
        combine_enantiomers=combine_enantiomers,
        return_mapped=return_mapped,
        skip_reset=True,
        max_depth=max_depth,
        max_products=max_products,
    )