Coverage for SynRBL/SynRuleImputer/synthetic_rule_constraint.py: 87%

76 statements  

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

1import copy 

2import re 

3from rdkit import Chem 

4from typing import List, Dict, Pattern, Any, Optional, Tuple 

5 

6 

7class RuleConstraint: 

8 """ 

9 A class for applying specific chemical reaction constraints and modifications. 

10 

11 Attributes 

12 ---------- 

13 list_dict : list of dict 

14 A list containing chemical reaction data. 

15 ban_atoms : list of str 

16 A list of SMILES strings representing banned atoms or molecules in reactions. 

17 

18 Methods 

19 ------- 

20 fit(): 

21 Applies oxidation rules to modify reactions and filters out reactions 

22 with banned atoms. 

23 """ 

24 

25 def __init__( 

26 self, 

27 list_dict: List[Dict[str, Any]], 

28 ban_atoms: Optional[List[str]] = None, 

29 ban_atoms_reactants: Optional[List[str]] = None, 

30 ) -> None: 

31 """ 

32 Initializes the RuleConstraint class with a list of chemical reactions 

33 and optional banned atoms. 

34 

35 Parameters 

36 ---------- 

37 list_dict : List[Dict[str, Any]] 

38 A list of dictionaries, each representing a chemical reaction. 

39 ban_atoms : Optional[List[str]], optional 

40 A list of SMILES strings for atoms or molecules to be banned from 

41 the reactions. Defaults to a predefined list. 

42 """ 

43 self.list_dict = copy.deepcopy(list_dict) 

44 self.ban_atoms = ban_atoms or [ 

45 "[H]", 

46 "[O].[O]", 

47 "F-F", 

48 "Cl-Cl", 

49 "Br-Br", 

50 "I-I", 

51 "Cl-Br", 

52 "Cl-I", 

53 "Br-I", 

54 ] 

55 self.ban_atoms = [Chem.CanonSmiles(atom) for atom in self.ban_atoms] 

56 self.ban_pattern = re.compile("|".join(map(re.escape, self.ban_atoms))) 

57 self.ban_atoms_reactants = ban_atoms_reactants or [".[H]"] 

58 # self.ban_atoms_reactants = [Chem.CanonSmiles(atom) for atom in self.ban_atoms_reactants] 

59 self.ban_pattern_reactants = re.compile( 

60 "|".join(map(re.escape, self.ban_atoms_reactants)) 

61 ) 

62 

63 @staticmethod 

64 def reduction_oxidation_rules_modify( 

65 data: List[Dict[str, str]] 

66 ) -> List[Dict[str, str]]: 

67 """ 

68 Modify the oxidation rules in the given data. 

69 

70 Args: 

71 data (List[Dict[str, str]]): The input data containing oxidation rules. 

72 

73 Returns: 

74 List[Dict[str, str]]: The modified data with updated oxidation rules. 

75 """ 

76 modified_data = [] 

77 for entry in data: 

78 if ".[H]" in entry["products"]: 

79 reactants = entry["reactants"].split(".") 

80 reactants = [ 

81 RuleConstraint.remove_atom_mapping(smiles) for smiles in reactants 

82 ] 

83 no_constraint = ["[Na]", "[K]", "[Li]", "[H-]"] 

84 contains_no_constraint = RuleConstraint.check_no_constraint( 

85 reactants, no_constraint 

86 ) 

87 if contains_no_constraint: 

88 pass 

89 else: 

90 if RuleConstraint.check_even(entry, "products", "[H]", "."): 

91 hydrogen_count = entry["products"].count(".[H]") 

92 hydrogen_count = int(hydrogen_count / 2) 

93 entry["products"] = entry["products"].replace(".[H]", "") 

94 entry["reactants"] += ".[O]" * hydrogen_count 

95 

96 if entry["products"]: 

97 entry["products"] += ".O" * hydrogen_count 

98 else: 

99 entry["products"] = "O" * hydrogen_count 

100 else: 

101 pass 

102 

103 if ".[O]" in entry["products"]: 

104 if RuleConstraint.check_even(entry, "products", "[O]", "."): 

105 pass 

106 else: 

107 oxygen_count = int(entry["products"].count(".[O]")) 

108 entry["products"] = entry["products"].replace(".[O]", "") 

109 entry["reactants"] += ".[H].[H]" * oxygen_count 

110 

111 if entry["products"]: 

112 entry["products"] += ".O" * oxygen_count 

113 else: 

114 entry["products"] = "O" * oxygen_count 

115 

116 elif ".OO" in entry["products"]: 

117 entry["products"] = entry["products"].replace(".OO", "") 

118 entry["reactants"] += ".[H].[H]" 

119 

120 if entry["products"]: 

121 entry["products"] += ".O.O" 

122 else: 

123 entry["products"] = "O.O" 

124 

125 new_reaction = f"{entry['reactants']}>>{entry['products']}" 

126 entry["new_reaction"] = new_reaction 

127 modified_data.append(entry) 

128 

129 return modified_data 

130 

131 @staticmethod 

132 def remove_banned_reactions( 

133 reaction_list: List[Dict[str, str]], 

134 ban_pattern: Pattern, 

135 ban_pattern_reactants: Pattern, 

136 ) -> Tuple[List[Dict[str, str]], List[Dict[str, str]]]: 

137 """ 

138 Filters out reactions that contain banned atoms in their products. 

139 

140 Parameters: 

141 reaction_list (List[Dict[str, str]]): A list containing reaction data. 

142 ban_pattern (Pattern): A compiled regular expression pattern that 

143 matches any of the banned atoms. 

144 

145 Returns: 

146 Tuple[List[Dict[str, str]], List[Dict[str, str]]]: The filtered list 

147 of reactions without and with banned atoms in their products. 

148 """ 

149 filtered_reactions = [ 

150 reaction 

151 for reaction in reaction_list 

152 if not ban_pattern.search(reaction.get("products", "")) 

153 ] 

154 reactions_with_banned_atoms = [ 

155 reaction 

156 for reaction in reaction_list 

157 if ban_pattern.search(reaction.get("products", "")) 

158 ] 

159 

160 # check validity of reactants, should not contain single [H] or single [O] 

161 filtered_reactions = [ 

162 reaction 

163 for reaction in filtered_reactions 

164 if len(re.findall(ban_pattern_reactants, reaction.get("reactants", ""))) % 2 

165 == 0 

166 ] 

167 reactions_with_banned_atoms_reactants = [ 

168 reaction 

169 for reaction in reaction_list 

170 if len(re.findall(ban_pattern_reactants, reaction.get("reactants", ""))) % 2 

171 != 0 

172 ] 

173 reactions_with_banned_atoms.extend(reactions_with_banned_atoms_reactants) 

174 return filtered_reactions, reactions_with_banned_atoms 

175 

176 @staticmethod 

177 def check_even(data_dict: dict, key: str, frag: str, symbol: str = ">>") -> bool: 

178 """ 

179 Check if the number of occurrences of a fragment in a list of SMILES 

180 strings is even. 

181 

182 Args: 

183 data_dict (dict): A dictionary containing SMILES strings. 

184 key (str): The key to access the relevant value in the dictionary. 

185 frag (str): The fragment to count in the SMILES strings. 

186 symbol (str, optional): The delimiter used in the SMILES strings. 

187 Defaults to '>>'. 

188 

189 Returns: 

190 bool: True if the number of occurrences of the fragment is even, 

191 False otherwise. 

192 """ 

193 smiles_list = data_dict[key].split(symbol) 

194 count = smiles_list.count(frag) 

195 return count % 2 == 0 

196 

197 def fit(self) -> List[Dict[str, Any]]: 

198 """ 

199 Applies oxidation modification rules and filters out reactions with 

200 banned atoms. 

201 

202 Returns 

203 ------- 

204 List[Dict[str, Any]] 

205 The modified and filtered list of chemical reactions. 

206 """ 

207 data_modified = self.reduction_oxidation_rules_modify(self.list_dict) 

208 return self.remove_banned_reactions( 

209 data_modified, self.ban_pattern, self.ban_pattern_reactants 

210 ) 

211 

212 @staticmethod 

213 def remove_atom_mapping(smiles: str) -> str: 

214 """ 

215 Remove atom mapping numbers from a SMILES string. 

216 

217 Atom mappings are typically represented by numbers following a 

218 colon (':') after the atom symbol. This function removes these mappings 

219 to return a SMILES string without them. 

220 

221 Args: 

222 smiles (str): A SMILES string with atom mappings. 

223 

224 Returns: 

225 str: A SMILES string without atom mappings. 

226 """ 

227 # Regular expression to find and remove atom mappings (numbers following a colon) 

228 mapping_pattern = re.compile(r":\d+") 

229 return mapping_pattern.sub("", smiles) 

230 

231 @staticmethod 

232 def check_no_constraint(reactants, no_constraint): 

233 """ 

234 Check if any elements in the no_constraint list match exactly with any 

235 elements in the reactants list. 

236 

237 Args: 

238 reactants (List[str]): A list of reactant elements or compounds. 

239 no_constraint (List[str]): A list of elements to check against in 

240 the reactants list. 

241 

242 Returns: 

243 bool: True if any element from no_constraint is found in reactants, 

244 False otherwise. 

245 """ 

246 # Convert lists to sets for efficient membership testing 

247 reactants_set = set(reactants) 

248 no_constraint_set = set(no_constraint) 

249 

250 # Check for intersection 

251 return not reactants_set.isdisjoint(no_constraint_set)