Coverage for SynRBL/SynMCSImputer/MissingGraph/find_missing_graphs.py: 80%
97 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
1import copy
3from rdkit import Chem
4from SynRBL.SynMCSImputer.SubStructure.substructure_analyzer import SubstructureAnalyzer
5from SynRBL.SynMCSImputer.MissingGraph.molcurator import MoleculeCurator
6from typing import List, Dict, Optional, Tuple
9class FindMissingGraphs:
10 """
11 A class for finding missing parts, boundary atoms, and nearest neighbors in
12 a list of reactant molecules.
14 Usage:
15 1. Create an instance of the class.
16 2. Use the class methods to find missing parts, boundary atoms, and nearest
17 neighbors for a list of molecules.
19 Example:
20 ```
21 fm = FindMissingGraphs()
22 missing_results = fm.find_single_graph(mcs_mol_list, sorted_reactants_mol_list)
23 ```
25 Note: This class requires the RDKit library to be installed.
27 Attributes:
28 None
30 Methods:
31 - find_missing_parts_pairs: Analyze a list of molecules and identify
32 missing parts, boundary atoms, and nearest neighbors.
33 - find_single_graph: Find missing parts, boundary atoms, and nearest
34 neighbors for a list of reactant molecules.
35 - find_single_graph_parallel: Find missing parts, boundary atoms, and
36 nearest neighbors in parallel for a list of reactant molecules.
37 """
39 def __init__(self):
40 pass
42 @staticmethod
43 def find_missing_parts_pairs(
44 mol_list: List[Chem.Mol], mcs_list: Optional[List[Chem.Mol]] = None
45 ) -> Tuple[
46 Optional[List[Chem.Mol]], List[List[Dict[str, int]]], List[List[Dict[str, int]]]
47 ]:
48 """
49 This function analyzes each molecule in a given list and identifies the
50 parts that are not present in the corresponding Maximum Common
51 Substructure (MCS). It also finds the boundary atoms and nearest
52 neighbors for each molecule.
54 Parameters:
55 - mol_list (list of rdkit.Chem.Mol): The list of RDKit molecule objects
56 to analyze.
57 - mcs_list (list of rdkit.Chem.Mol or None): List of RDKit molecule
58 objects representing MCS,
59 corresponding to each molecule in mol_list. If None, MCS will be
60 calculated using RDKit's rdFMCS.
61 - use_findMCS (bool): Whether to use RDKit's rdFMCS to find MCS and
62 remove it from mol_list.
63 - params (rdkit.Chem.rdFMCS.MCSParameters): Parameters for RDKit's rdFMCS.
65 Returns:
66 Tuple containing:
67 - list of rdkit.Chem.Mol or None: RDKit molecule objects representing
68 the missing parts of each molecule, or None if no missing parts
69 are found.
70 - list of lists: Each sublist contains the boundary atoms of the
71 corresponding molecule.
72 - list of lists: Each sublist contains the nearest neighbors of the
73 corresponding molecule.
74 """
75 missing_parts_list = []
76 boundary_atoms_lists = []
77 nearest_neighbor_lists = []
79 for mol, mcs_mol in zip(mol_list, mcs_list):
80 atoms_to_remove = set()
81 boundary_atoms_list = []
82 nearest_neighbor_list = []
84 if mcs_mol.GetNumAtoms() > 0:
85 # Finding substructure matches
86 if Chem.MolToSmiles(mcs_mol) == "O":
87 # hardcode special case OC(O)OH
88 smarts_pattern = "[OH]"
89 smarts_mol = Chem.MolFromSmarts(smarts_pattern)
90 substructure_match = mol.GetSubstructMatch(smarts_mol)
91 # if no substructure match is found, use rdkit's
92 # substructure matching for mcs_mol, this not special case
93 if not substructure_match:
94 substructure_match = mol.GetSubstructMatch(mcs_mol)
95 else:
96 analyzer = SubstructureAnalyzer()
97 substructure_match = analyzer.identify_optimal_substructure(
98 parent_mol=mol, child_mol=mcs_mol
99 )
101 if substructure_match:
102 atoms_to_remove.update(substructure_match)
104 left_number = []
105 for i in range(mol.GetNumAtoms()):
106 if i not in substructure_match:
107 left_number.append(i)
109 # Creating the molecule of missing parts
110 missing_part = Chem.RWMol(mol)
111 for idx in sorted(atoms_to_remove, reverse=True):
112 missing_part.RemoveAtom(idx)
114 missing_part_old = copy.deepcopy(missing_part)
116 if missing_part is not None:
117 missing_part_smiles = Chem.MolToSmiles(missing_part)
118 try:
119 missing_part = Chem.MolFromSmiles(
120 missing_part_smiles, sanitize=False
121 )
122 Chem.SanitizeMol(missing_part)
124 except Exception:
125 missing_part = MoleculeCurator.manual_kekulize(
126 missing_part_smiles
127 )
129 missing_part = MoleculeCurator.add_hydrogens_to_radicals(
130 missing_part
131 )
132 atom_mapping = FindMissingGraphs.map_parent_to_child(
133 missing_part_old, missing_part, left_number
134 )
136 else:
137 index_mapping = {
138 idx: i
139 for i, idx in enumerate(
140 sorted(set(range(mol.GetNumAtoms())) - atoms_to_remove)
141 )
142 }
144 boundary_atoms = []
145 nearest_atoms = []
147 # Identifying boundary atoms and nearest neighbors
148 for atom_idx in substructure_match:
149 # display(mol)
150 if atom_idx < mol.GetNumAtoms():
151 atom_symbol = mol.GetAtomWithIdx(atom_idx).GetSymbol()
152 neighbors = mol.GetAtomWithIdx(atom_idx).GetNeighbors()
153 # Loop through neighbors to find boundary atoms
154 # and nearest neighbors
155 for neighbor in neighbors:
156 if neighbor.GetIdx() not in substructure_match:
157 nearest_atoms.append({atom_symbol: atom_idx})
159 if missing_part:
160 renumerate_idx = atom_mapping.get(
161 neighbor.GetIdx(), -1
162 )
163 else:
164 renumerate_idx = index_mapping.get(
165 neighbor.GetIdx(), -1
166 )
167 if renumerate_idx != -1:
168 boundary_atoms.append(
169 {neighbor.GetSymbol(): renumerate_idx}
170 )
171 else:
172 missing_part = None
173 if boundary_atoms:
174 boundary_atoms_list.append(boundary_atoms)
175 if nearest_atoms:
176 nearest_neighbor_list.append(nearest_atoms)
178 try:
179 Chem.SanitizeMol(missing_part)
180 if missing_part.GetNumAtoms() > 0:
181 missing_part = MoleculeCurator.standardize_diazo_charge(
182 missing_part
183 )
184 missing_parts_list.append(missing_part)
185 boundary_atoms_lists.extend(boundary_atoms_list)
186 nearest_neighbor_lists.extend(nearest_neighbor_list)
187 else:
188 missing_parts_list.append(None)
189 boundary_atoms_lists.append(None)
190 nearest_neighbor_lists.append(None)
191 except Exception:
192 missing_parts_list.append(None)
193 boundary_atoms_lists.append(None)
194 nearest_neighbor_lists.append(None)
196 return missing_parts_list, boundary_atoms_lists, nearest_neighbor_lists
198 @staticmethod
199 def map_parent_to_child(parent_mol, child_mol, key_base):
200 # Get atom indices in the parent molecule that match the entire child molecule
201 parent_mcs_indices = parent_mol.GetSubstructMatch(child_mol)
203 # Create a mapping of parent atom indices to child atom indices
204 atom_mapping = {}
205 for child_idx, parent_idx in enumerate(parent_mcs_indices):
206 map_key = key_base[parent_idx]
207 atom_mapping[map_key] = child_idx
209 return atom_mapping
211 @staticmethod
212 def is_mapping_correct(mol, symbol_to_index):
213 # Convert the molecule to a dictionary of atom indices to symbols
214 molecule_dict = {atom.GetIdx(): atom.GetSymbol() for atom in mol.GetAtoms()}
216 # Check if the mappings are consistent
217 for symbol, index in symbol_to_index.items():
218 if index not in molecule_dict:
219 return False
220 if molecule_dict[index] != symbol:
221 return False
223 return True