Coverage for SynRBL/SynUtils/functional_group_utils.py: 99%

134 statements  

« prev     ^ index     » next       coverage.py v7.4.3, created at 2024-04-11 11:17 +0200

1import copy 

2import itertools 

3import numpy as np 

4import rdkit.Chem as Chem 

5import rdkit.Chem.rdchem as rdchem 

6import rdkit.Chem.rdmolfiles as rdmolfiles 

7 

8 

9class FGConfig: 

10 def __init__(self, pattern, group_atoms=None, anti_pattern=[], depth=None): 

11 pattern = pattern if isinstance(pattern, list) else [pattern] 

12 for p in pattern: 

13 if p != Chem.CanonSmiles(p): 

14 # We don't fix the pattern smiles because group_atoms might rely on the pattern 

15 raise ValueError( 

16 ( 

17 "Pattern must be canonical smiles. (value: {}, expected: {})" 

18 ).format(p, Chem.CanonSmiles(p)) 

19 ) 

20 

21 self.pattern = [rdmolfiles.MolFromSmiles(p) for p in pattern] 

22 

23 if group_atoms is None: 

24 self.groups = [rdmolfiles.MolFromSmiles(p) for p in pattern] 

25 else: 

26 self.groups = [rdchem.RWMol(p) for p in self.pattern] 

27 for g in self.groups: 

28 rm_indices = [] 

29 for a in g.GetAtoms(): 

30 if a.GetIdx() not in group_atoms: 

31 rm_indices.append(a.GetIdx()) 

32 for i in sorted(rm_indices, reverse=True): 

33 g.RemoveAtom(i) 

34 

35 anti_pattern = ( 

36 anti_pattern if isinstance(anti_pattern, list) else [anti_pattern] 

37 ) 

38 self.anti_pattern = sorted( 

39 [rdmolfiles.MolFromSmiles(s) for s in anti_pattern], 

40 key=lambda x: len(x.GetAtoms()), 

41 reverse=True, 

42 ) 

43 

44 self.max_pattern_size = ( 

45 depth 

46 if depth is not None 

47 else np.max([len(c.GetAtoms()) for c in self.pattern + self.anti_pattern]) 

48 ) 

49 

50 

51functional_group_config = { 

52 "phenol": FGConfig( 

53 ["Oc1ccccc1", "Oc1ccc[nH]1"], anti_pattern=["COc1ccccc1", "COc1ccc[nH]1"] 

54 ), 

55 "alcohol": FGConfig( 

56 "CO", anti_pattern=["C(=O)O", "C=CO", "COC", "OCO", "Oc1ccccc1", "Oc1ccc[nH]1"] 

57 ), 

58 "ether": FGConfig( 

59 "COC", 

60 anti_pattern=["OC=S", "C=O", "C=CO", "OCOC", "OC=O", "OCN"], 

61 ), 

62 "enol": FGConfig("C=CO"), 

63 "amid": FGConfig("NC=O", anti_pattern=["O=C(N)O"]), 

64 "acyl": FGConfig( 

65 "C=O", 

66 anti_pattern=[ 

67 "CC(C)=O", 

68 "SC=O", 

69 "CC=O", 

70 "C(N)=O", 

71 "O=C(O)O", 

72 "O=C(C)OC", 

73 "O=C(C)O", 

74 "CC(=O)OC=O", 

75 ], 

76 ), 

77 "diol": FGConfig("OCO", anti_pattern=["OCOC", "O=C(O)O"]), 

78 "hemiacetal": FGConfig("COCO", anti_pattern=["COCOC", "O=C(O)O"]), 

79 "acetal": FGConfig("COCOC"), 

80 "urea": FGConfig("NC(=O)O"), 

81 "carbonat": FGConfig("O=C(O)O"), 

82 "anhydrid": FGConfig("CC(=O)OC=O"), 

83 "ester": FGConfig("COC(C)=O", group_atoms=[1, 2, 4], anti_pattern=["O=C(C)OC=O"]), 

84 "acid": FGConfig( 

85 "CC(=O)O", 

86 group_atoms=[1, 2, 3], 

87 anti_pattern=["O=CS", "O=C(C)OC=O", "O=C(C)OC"], 

88 ), 

89 "anilin": FGConfig("Nc1ccccc1"), 

90 "amin": FGConfig("CN", anti_pattern=["C=O", "Nc1ccccc1", "NC=O"]), 

91 "nitril": FGConfig("C#N"), 

92 "hydroxylamin": FGConfig("NO", anti_pattern=["O=NO"]), 

93 "nitrose": FGConfig("N=O", anti_pattern=["O=NO"]), 

94 "nitro": FGConfig("O=NO"), 

95 "thioether": FGConfig("CSC", anti_pattern=["O=CS"]), 

96 "thioester": FGConfig(["O=CS", "OC=S"]), 

97 "aldehyde": FGConfig( 

98 "CC=O", 

99 group_atoms=[1, 2], 

100 anti_pattern=["CC(C)=O", "SC(=O)C", "COC(C)=O", "NC=O", "CC(=O)O"], 

101 ), 

102 "keton": FGConfig("CC(C)=O", group_atoms=[1, 3]), 

103} 

104 

105 

106def trim_mol(mol: rdchem.Mol, index: int, depth: int) -> rdchem.Mol: 

107 def _dfs( 

108 mol: rdchem.RWMol, 

109 atom: rdchem.Atom, 

110 dist: int, 

111 dist_array: list[int], 

112 ): 

113 dist_array[atom.GetIdx()] = dist 

114 for neighbor in atom.GetNeighbors(): 

115 idx = neighbor.GetIdx() 

116 if dist + 1 < dist_array[idx]: 

117 _dfs(mol, neighbor, dist + 1, dist_array) 

118 

119 atom_cnt = len(mol.GetAtoms()) 

120 dist_array = [atom_cnt + 1 for _ in range(atom_cnt)] 

121 rwmol = rdchem.RWMol(mol) 

122 atom = rwmol.GetAtomWithIdx(index) 

123 _dfs(mol, atom, 0, dist_array) 

124 for i, d in reversed(list(enumerate(dist_array))): 

125 if d > depth: 

126 rwmol.RemoveAtom(i) 

127 return rwmol, atom.GetIdx() 

128 

129 

130def get_mapping_permutations(match_symbols, sym_dict): 

131 mappings = [] 

132 if len(sym_dict) >= len(match_symbols): 

133 sym_map = [(i, s) for i, s in enumerate(sym_dict)] 

134 for sym_permut in itertools.permutations(sym_map): 

135 mapping = [] 

136 is_match = True 

137 for i, s1 in enumerate(match_symbols): 

138 if s1 == sym_permut[i][1]: 

139 mapping.append((i, sym_permut[i][0])) 

140 else: 

141 is_match = False 

142 break 

143 if is_match: 

144 mappings.append(mapping) 

145 return mappings 

146 

147 

148def pattern_match(mol, anchor, pattern_mol, pattern_anchor=None): 

149 def _fits(atom, pattern_atom, visited_atoms=[], visited_pattern_atoms=[]): 

150 atom_idx = atom.GetIdx() 

151 pattern_atom_idx = pattern_atom.GetIdx() 

152 assert atom_idx not in visited_atoms 

153 assert pattern_atom_idx not in visited_pattern_atoms 

154 

155 visited_atoms = copy.deepcopy(visited_atoms) 

156 visited_atoms.append(atom_idx) 

157 visited_pattern_atoms = copy.deepcopy(visited_pattern_atoms) 

158 visited_pattern_atoms.append(pattern_atom_idx) 

159 

160 atom_neighbors = [ 

161 (a.GetIdx(), a.GetSymbol(), a) 

162 for a in atom.GetNeighbors() 

163 if a.GetIdx() not in visited_atoms 

164 ] 

165 pattern_neighbors = [ 

166 (a.GetIdx(), a.GetSymbol(), a) 

167 for a in pattern_atom.GetNeighbors() 

168 if a.GetIdx() not in visited_pattern_atoms 

169 ] 

170 

171 fits = False 

172 match = [] 

173 if atom.GetSymbol() == pattern_atom.GetSymbol(): 

174 match.append((atom.GetIdx(), pattern_atom.GetIdx())) 

175 if len(pattern_neighbors) > 0: 

176 an_syms = [a[1] for a in atom_neighbors] 

177 pn_syms = [a[1] for a in pattern_neighbors] 

178 mappings = get_mapping_permutations(pn_syms, an_syms) 

179 for mapping in mappings: 

180 valid_mapping = True 

181 n_matches = set() 

182 for pn_i, an_i in mapping: 

183 atom_neighbor = atom_neighbors[an_i] 

184 pattern_neighbor = pattern_neighbors[pn_i] 

185 mol = atom_neighbor[2].GetOwningMol() 

186 p_mol = pattern_neighbor[2].GetOwningMol() 

187 bond = mol.GetBondBetweenAtoms( 

188 atom_idx, atom_neighbor[0] 

189 ).GetBondType() 

190 p_bond = p_mol.GetBondBetweenAtoms( 

191 pattern_atom_idx, pattern_neighbor[0] 

192 ).GetBondType() 

193 if bond != p_bond: 

194 valid_mapping = False 

195 break 

196 n_fit, n_match = _fits( 

197 atom_neighbor[2], 

198 pattern_neighbor[2], 

199 visited_atoms, 

200 visited_pattern_atoms, 

201 ) 

202 if not n_fit: 

203 valid_mapping = False 

204 break 

205 else: 

206 n_matches.update(n_match) 

207 if valid_mapping: 

208 fits = True 

209 match.extend(n_matches) 

210 break 

211 else: 

212 fits = True 

213 return fits, match 

214 

215 if pattern_anchor is None: 

216 atom = mol.GetAtomWithIdx(anchor) 

217 for pattern_atom in pattern_mol.GetAtoms(): 

218 result = _fits(atom, pattern_atom) 

219 if result[0]: 

220 return result 

221 return False, [[]] 

222 else: 

223 atom = mol.GetAtomWithIdx(anchor) 

224 pattern_atom = pattern_mol.GetAtomWithIdx(pattern_anchor) 

225 return _fits(atom, pattern_atom) 

226 

227 

228def check_functional_group(mol: rdchem.Mol, config: FGConfig, index: int) -> bool: 

229 is_func_group = False 

230 

231 for p_mol, g_mol in zip(config.pattern, config.groups): 

232 is_match, _ = pattern_match(mol, index, p_mol) 

233 if is_match: 

234 is_match, _ = pattern_match(mol, index, g_mol) 

235 is_func_group = is_func_group or is_match 

236 

237 last_len = config.max_pattern_size 

238 for ap_mol, ap_mol_size in sorted( 

239 [(m, len(m.GetAtoms())) for m in config.anti_pattern], 

240 key=lambda x: x[1], 

241 reverse=True, 

242 ): 

243 if not is_func_group: 

244 break 

245 ap_mol_size = len(ap_mol.GetAtoms()) 

246 if last_len > ap_mol_size: 

247 last_len = ap_mol_size 

248 is_match, _ = pattern_match(mol, index, ap_mol) 

249 is_func_group = is_func_group and not is_match 

250 return is_func_group 

251 

252 

253def is_functional_group(mol: rdchem.Mol, group_name: str, index: int) -> bool: 

254 if group_name not in functional_group_config.keys(): 

255 raise NotImplementedError( 

256 "Functional group '{}' is not implemented.".format(group_name) 

257 ) 

258 config = functional_group_config[group_name] 

259 return check_functional_group(mol, config, index)