File size: 3,910 Bytes
be59fdd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
from typing import ClassVar, Dict, List, Iterable
import re

try:
    from rdkit import Chem
    from rdkit.Chem import AllChem
    from rdkit.Chem.rdchem import Mol
    from rdkit.Chem.rdChemReactions import ChemicalReaction
    from rdkit.Chem import AllChem
except ModuleNotFoundError:
    print("This module requires rdkit to run.")
    exit(-1)

from . import Exceptions


Reactant = Mol
Reactants = Dict[str, Reactant]


class BaseReaction:
    """
    Abstract reaction class to provide common implementations for all reactions.
    """

    """ Dictionary of reactants """
    _reactants: Reactants
    """ Smarts used by the implementing class"""
    _smarts: ClassVar[str]
    """ rdkit ChemicalReaction instance created from the smarts. """
    _rdReaction: ClassVar[ChemicalReaction]

    reactant_names = ClassVar[List[str]]

    def __runReaction__(self, reactants: Reactants) -> List[List[Mol]]:
        """
        Returns all products of all product sets.

        :return: A list of all product sets.
        """
        raise NotImplementedError("You must implement __runReaction__")

    @classmethod
    def set_reaction_smarts(cls, smarts: str) -> None:
        """
        Sets the reaction smarts and creates the rdkit reaction from it.

        :param smarts: A smarts string. All whitespace will be removed.
        """
        cls._smarts = re.sub(r'\s+', '', smarts)
        cls._rdReaction = AllChem.ReactionFromSmarts(cls._smarts)

    def set_reactants(self, reactants: Reactants):
        """
        Sets the reactants.

        :param reactants: A dictionary where each key-value pair associates a reactant name with the corresponding mol.
        :return:

        Example:
            AmideCoupling.set_reactants({"amine": amine_molecule, "acid": acid_molecule})
        """
        self._reactants = reactants

    def get_reactants(self) -> Reactants:
        """
        Returns the reactants as a dictionary, where each key-value pair associates a reactant name with the
        corresponding mol. See set_reactants.

        :return:
        """
        return self._reactants

    def get_products(self, symmetrical_as_one: bool = False) -> List[Mol]:
        """
        Returns a list of all possible products.

        :param symmetrical_as_one: Set to true if symmetrical products should get reduced to one.
        :return:
        """
        productSets = self.__runReaction__(self.get_reactants())

        if productSets is None:
            raise Exception("No product set was returned.")
        elif len(productSets) == 0:
            raise Exceptions.NoProductError("Reaction {} gave no product.".format(type(self)))

        # Retrieve first product of all product sets
        products = []
        productSmiles = []
        for p in productSets:
            # Sanitize product from reaction fragments.
            AllChem.SanitizeMol(p[0])

            if symmetrical_as_one:
                smiles = AllChem.MolToSmiles(p[0])

                if smiles in productSmiles:
                    continue
                else:
                    productSmiles.append(smiles)

            products.append(p[0])

        return products

    def get_product(self, symmetrical_as_one: bool = False) -> Mol:
        """
        Returns one product and raises an exception if multiple products are possible.

        :param symmetrical_as_one: Set to true to remove all but one instance of identical products.
        :return:
        """

        # Get all possible products
        products = self.get_products(symmetrical_as_one=symmetrical_as_one)

        # More than one product is unexpected, raise an error to make the user aware.
        if len(products) > 1:
            raise Exceptions.AmbiguousProductError("Reaction {} gave more than one product sets: {}".format(type(self), [Chem.MolToSmiles(x) for x in products]))

        return products[0]