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 create 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 (int, int, rdkit.Chem.rdchem.Bond)

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

Returns 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 template_r and template_p until accessed

True
Source code in rdchiral/initialization.py
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
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 create 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
            (int, int, rdkit.Chem.rdchem.Bond)
        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 (int): Returns 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 template_r and template_p until accessed
    """

    def __init__(
        self,
        reactant_smiles: str,
        custom_reactant_mapping: bool = False,
        lazy_init: bool = True,
    ):
        # 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 RDKit Atom for reactants

atoms_pt_idx_to_map dict

Dictionary mapping from atom idx to RDKit Atom for products

Parameters:

Name Type Description Default
reaction_smarts str

Reaction SMARTS string

required
lazy_init bool

If True, delay initialization of template_r and template_p until accessed

True
Source code in rdchiral/initialization.py
 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
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 RDKit Atom for reactants
        atoms_pt_idx_to_map (dict): Dictionary mapping from atom idx to RDKit Atom for products

    Args:
        reaction_smarts (str): Reaction SMARTS string
        lazy_init (bool): If True, delay initialization of template_r and template_p until accessed
    """

    def __init__(self, reaction_smarts: str, lazy_init: bool = True):
        # Keep smarts, useful for reporting

        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 are initialized"""
        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:
        """Reset atom map numbers for template fragment atoms"""
        if not self._template_r or not self._template_p:
            self._ensure_templates()
        self._template_r = self._template_r_orig
        self._template_p = self._template_p_orig

reset()

Reset atom map numbers for template fragment atoms

Source code in rdchiral/initialization.py
328
329
330
331
332
333
def reset(self) -> None:
    """Reset atom map numbers for template fragment atoms"""
    if not self._template_r or not self._template_p:
        self._ensure_templates()
    self._template_r = self._template_r_orig
    self._template_p = self._template_p_orig

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 products into racemic mixtures.

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
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
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
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 products into racemic mixtures.
        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,
            reactant_obj,
            parent_changes,
        ) in current_level.items():
            if reactant_obj is None:
                reactant_obj = rdchiralReactants(
                    parent_mapped, custom_reactant_mapping=custom_reactant_mapping
                )
            products_list, products_dict = rdchiral_step_return_mapped(
                rxn,
                reactant_obj,
                keep_mapnums=True,
                combine_enantiomers=False,
                skip_reset=skip_reset,
            )
            custom_reactant_mapping = True
            if not products_list:
                continue

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

                product_smiles_unmapped = strip_map_numbers_from_smiles(
                    product_smiles_mapped
                )

                _, changed_atoms = products_dict[product_smiles_mapped]
                accumulated_changes = parent_changes + [changed_atoms]

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

            if num_products >= max_products:
                break

        if not next_level:
            break

        current_level = next_level

    if not keep_mapnums:
        final_smiles_list = list(
            set([unmapped for unmapped, _ in all_products.values()])
        )
    else:
        final_smiles_list = list(set([mapped for mapped in all_products.keys()]))

    if combine_enantiomers:
        final_smiles_set, modified_smiles_dict = combine_enantiomers_into_racemic(
            set(final_smiles_list)
        )
        final_smiles_list = list(final_smiles_set)

    all_products = fix_return_mapped_dict_enantiomers(
        all_products=all_products,
        modified_smiles_dict=modified_smiles_dict,
        keep_mapnums=keep_mapnums,
    )

    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, attempt to combine enantiomeric outcomes into racemic outcomes.

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
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, attempt to combine enantiomeric outcomes into
            racemic outcomes.
        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,
    )