Coverage for SynRBL/SynMCSImputer/SubStructure/mcs_graph_detector.py: 78%
90 statements
« prev ^ index » next coverage.py v7.4.3, created at 2024-04-11 11:17 +0200
« prev ^ index » next coverage.py v7.4.3, created at 2024-04-11 11:17 +0200
1from rdkit import Chem
2from rdkit.Chem import rdFMCS
3from rdkit.Chem import rdRascalMCES
4from SynRBL.SynMCSImputer.SubStructure.substructure_analyzer import SubstructureAnalyzer
7class MCSMissingGraphAnalyzer:
8 """A class for detecting missing graph in reactants and products using MCS
9 and RDKit."""
11 def __init__(self):
12 """Initialize the MolecularOperations class."""
13 pass
15 @staticmethod
16 def get_smiles(reaction_dict):
17 """
18 Extract reactant and product SMILES strings from a reaction dictionary.
20 Parameters:
21 - reaction_dict: dict
22 A dictionary containing 'reactants' and 'products' as keys.
24 Returns:
25 - tuple
26 A tuple containing reactant SMILES and product SMILES strings.
27 """
28 return reaction_dict["reactants"], reaction_dict["products"]
30 @staticmethod
31 def convert_smiles_to_molecule(smiles):
32 """
33 Convert a SMILES string to an RDKit molecule object.
35 Parameters:
36 - smiles: str
37 The SMILES string representing a molecule.
39 Returns:
40 - rdkit.Chem.Mol
41 The RDKit molecule object.
42 """
43 return Chem.MolFromSmiles(smiles)
45 @staticmethod
46 def IterativeMCSReactionPairs(
47 reactant_mol_list,
48 product_mol,
49 params=None,
50 method="MCIS",
51 sort="MCIS",
52 remove_substructure=True,
53 ):
54 """
55 Find the MCS for each reactant fragment with the product, updating the
56 product after each step. Reactants are processed based on the size of
57 their MCS with the product at each iteration.
59 Parameters:
60 - reactant_mol_list: list of rdkit.Chem.Mol
61 List of RDKit molecule objects for reactants.
62 - product_mol: rdkit.Chem.Mol
63 RDKit molecule object for the product.
64 - sort (str):
65 Method of sorting reactants, either 'MCS' or 'Fragments'.
66 - remove_substructure (bool):
67 If True, update the product by removing the MCS substructure.
68 - params (rdkit.Chem.rdFMCS.MCSParameters):
69 Parameters for RDKit's rdFMCS.
71 Returns:
72 - list of rdkit.Chem.Mol
73 List of RDKit molecule objects representing the MCS for each
74 reactant-product pair.
75 - list of rdkit.Chem.Mol
76 Sorted list of reactant molecule objects.
77 """
79 # Sort reactants based on the specified method
80 if sort == "MCIS":
81 if params is None:
82 params = rdFMCS.MCSParameters()
83 mcs_results = [
84 (reactant, rdFMCS.FindMCS([reactant, product_mol], params))
85 for reactant in reactant_mol_list
86 ]
87 mcs_results = [
88 (reactant, mcs_result)
89 for reactant, mcs_result in mcs_results
90 if not mcs_result.canceled
91 ]
92 sorted_reactants = sorted(
93 mcs_results, key=lambda x: x[1].numAtoms, reverse=True
94 )
95 elif sort == "MCES":
96 if params is None:
97 params = rdRascalMCES.RascalOptions()
98 mcs_results = [
99 (reactant, rdRascalMCES.FindMCES(reactant, product_mol, params)[0])
100 for reactant in reactant_mol_list
101 ]
102 mcs_results = [
103 (reactant, mcs_result)
104 for reactant, mcs_result in mcs_results
105 if hasattr(mcs_result, "atomMatches")
106 ]
107 sorted_reactants = sorted(
108 mcs_results, key=lambda x: len(x[1].atomMatches()), reverse=True
109 )
110 elif sort == "Fragments":
111 sorted_reactants = sorted(
112 reactant_mol_list, key=lambda x: x.GetNumAtoms(), reverse=True
113 )
114 else:
115 raise ValueError("Invalid sort method. Choose 'MCS' or 'Fragments'.")
117 mcs_list = []
118 current_product = product_mol
119 for reactant, _ in sorted_reactants:
120 # Calculate the MCS with the current product
121 try:
122 if method == "MCIS":
123 mcs_result = rdFMCS.FindMCS([reactant, current_product], params)
124 elif method == "MCES":
125 mcs_result = rdRascalMCES.FindMCES(
126 reactant, current_product, params
127 )[0]
128 else:
129 raise ValueError("Invalid method. Choose 'MCIS' or 'MCES'.")
131 if (
132 not mcs_result.canceled
133 if method == "MCIS"
134 else hasattr(mcs_result, "atomMatches")
135 ):
136 mcs_smarts = (
137 mcs_result.smartsString
138 if method == "MCIS"
139 else mcs_result.smartsString.split(".")[0]
140 )
141 mcs_mol = Chem.MolFromSmarts(mcs_smarts)
142 mcs_list.append(mcs_mol)
143 # Conditional substructure removal
144 if remove_substructure:
145 # Identify the optimal substructure
146 analyzer = SubstructureAnalyzer()
147 optimal_substructure = analyzer.identify_optimal_substructure(
148 parent_mol=current_product, child_mol=mcs_mol
149 )
150 if optimal_substructure:
151 rw_mol = Chem.RWMol(current_product)
152 # Remove atoms in descending order of their indices
153 for atom_idx in sorted(optimal_substructure, reverse=True):
154 if (
155 atom_idx < rw_mol.GetNumAtoms()
156 ): # Check if the index is valid
157 rw_mol.RemoveAtom(atom_idx)
158 else:
159 pass
160 current_product = rw_mol.GetMol()
162 try:
163 Chem.SanitizeMol(current_product)
164 except Exception:
165 pass
166 except Exception:
167 mcs_list.append(None)
168 pass
170 return mcs_list, [reactant for reactant, _ in sorted_reactants]
172 @staticmethod
173 def fit(
174 reaction_dict,
175 RingMatchesRingOnly=True,
176 CompleteRingsOnly=True,
177 Timeout=60,
178 similarityThreshold=0.5,
179 sort="MCIS",
180 method="MCIS",
181 remove_substructure=True,
182 ignore_atom_map=False,
183 ignore_bond_order=False,
184 ):
185 """
186 Process a reaction dictionary to find MCS, missing parts in reactants
187 and products.
189 Parameters:
190 - reaction_dict: dict
191 A dictionary containing 'reactants' and 'products' as keys.
193 Returns:
194 - tuple
195 A tuple containing lists of MCS, missing parts in reactants,
196 missing parts in products, reactant molecules, and product
197 molecules.
198 """
200 # define parameters
202 if method == "MCIS":
203 params = rdFMCS.MCSParameters()
204 params.Timeout = Timeout
205 params.BondCompareParameters.RingMatchesRingOnly = RingMatchesRingOnly
206 params.BondCompareParameters.CompleteRingsOnly = CompleteRingsOnly
207 if ignore_bond_order:
208 params.BondTyper = rdFMCS.BondCompare.CompareAny
209 if ignore_atom_map:
210 params.AtomTyper = rdFMCS.AtomCompare.CompareAny
212 elif method == "MCES":
213 params = rdRascalMCES.RascalOptions()
214 params.singleLargestFrag = False
215 params.returnEmptyMCES = True
216 params.timeout = Timeout
217 params.similarityThreshold = similarityThreshold
219 if reaction_dict["carbon_balance_check"] in ["products", "balanced"]:
220 # Calculate the MCS for each reactant with the product
221 reactant_smiles, product_smiles = MCSMissingGraphAnalyzer.get_smiles(
222 reaction_dict
223 )
224 reactant_mol_list = [
225 MCSMissingGraphAnalyzer.convert_smiles_to_molecule(smiles)
226 for smiles in reactant_smiles.split(".")
227 ]
228 product_mol = MCSMissingGraphAnalyzer.convert_smiles_to_molecule(
229 product_smiles
230 )
232 (
233 mcs_list,
234 sorted_parents,
235 ) = MCSMissingGraphAnalyzer.IterativeMCSReactionPairs(
236 reactant_mol_list,
237 product_mol,
238 params,
239 method=method,
240 sort=sort,
241 remove_substructure=remove_substructure,
242 )
244 return mcs_list, sorted_parents, reactant_mol_list, product_mol
246 elif reaction_dict["carbon_balance_check"] == "reactants":
247 # Calculate the MCS for each product with the reactant
248 reactant_smiles, product_smiles = MCSMissingGraphAnalyzer.get_smiles(
249 reaction_dict
250 )
251 product_mol_list = [
252 MCSMissingGraphAnalyzer.convert_smiles_to_molecule(smiles)
253 for smiles in product_smiles.split(".")
254 ]
255 reactant_mol = MCSMissingGraphAnalyzer.convert_smiles_to_molecule(
256 reactant_smiles
257 )
259 (
260 mcs_list,
261 sorted_parents,
262 ) = MCSMissingGraphAnalyzer.IterativeMCSReactionPairs(
263 product_mol_list,
264 reactant_mol,
265 params,
266 method=method,
267 sort=sort,
268 remove_substructure=remove_substructure,
269 )
271 return mcs_list, sorted_parents, product_mol_list, reactant_mol