Coverage for SynRBL/SynUtils/chem_utils.py: 38%

91 statements  

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

1import io 

2import re 

3import tempfile 

4import matplotlib.pyplot as plt 

5 

6from typing import List, Dict 

7from typing import Union 

8from rdkit import Chem 

9from PIL import Image 

10from reportlab.pdfgen import canvas 

11from reportlab.lib.pagesizes import landscape, letter 

12from SynRBL.SynVis.reaction_visualizer import ReactionVisualizer 

13 

14 

15class CheckCarbonBalance: 

16 def __init__( 

17 self, reactions_data: List[Dict[str, str]], rsmi_col="reactions", symbol=">>" 

18 ): 

19 """ 

20 Initialize the CheckCarbonBalance class with reaction data. 

21 

22 Parameters: 

23 reactions_data (List[Dict[str, str]]): A list of dictionaries, each 

24 containing reaction information. 

25 """ 

26 self.reactions_data = reactions_data 

27 self.rsmi_col = rsmi_col 

28 self.symbol = symbol 

29 

30 @staticmethod 

31 def count_carbon_atoms(smiles: str) -> int: 

32 """ 

33 Count the number of carbon atoms in a molecule represented by a SMILES 

34 string. 

35 

36 Parameters: 

37 smiles (str): A SMILES string. 

38 

39 Returns: 

40 int: The number of carbon atoms in the molecule. Returns 0 if the 

41 SMILES string is invalid. 

42 """ 

43 mol = Chem.MolFromSmiles(smiles) 

44 return ( 

45 sum(1 for atom in mol.GetAtoms() if atom.GetSymbol() == "C") if mol else 0 

46 ) 

47 

48 def check_carbon_balance(self) -> None: 

49 """ 

50 Check and update the carbon balance status for each reaction in the 

51 reactions data. 

52 

53 The method updates each reaction dictionary in the reactions data with 

54 a new key 'carbon_balance_check'. This key will have the value 

55 'products' if the number of carbon atoms in the products is greater 

56 than or equal to the reactants, and 'reactants' otherwise. 

57 """ 

58 for reaction in self.reactions_data: 

59 try: 

60 reactants_smiles, products_smiles = reaction[self.rsmi_col].split( 

61 self.symbol 

62 ) 

63 reactants_carbon = sum( 

64 self.count_carbon_atoms(smiles) 

65 for smiles in reactants_smiles.split(".") 

66 ) 

67 products_carbon = sum( 

68 self.count_carbon_atoms(smiles) 

69 for smiles in products_smiles.split(".") 

70 ) 

71 

72 if reactants_carbon >= products_carbon: 

73 reaction["carbon_balance_check"] = "products" 

74 else: 

75 reaction["carbon_balance_check"] = "reactants" 

76 except KeyError as e: 

77 print(f"Key error: {e}") 

78 except ValueError as e: 

79 print(f"Value error: {e}") 

80 

81 def is_carbon_balance(self) -> None: 

82 """ 

83 Check and update the carbon balance status for each reaction in the 

84 reactions data. 

85 

86 The method updates each reaction dictionary in the reactions data with 

87 a new key 'carbon_balance_check'. This key will have the value 

88 'products' if the number of carbon atoms in the products is greater 

89 than or equal to the reactants, and 'reactants' otherwise. 

90 """ 

91 for reaction in self.reactions_data: 

92 try: 

93 reactants_smiles, products_smiles = reaction[self.rsmi_col].split( 

94 self.symbol 

95 ) 

96 reactants_carbon = sum( 

97 self.count_carbon_atoms(smiles) 

98 for smiles in reactants_smiles.split(".") 

99 ) 

100 products_carbon = sum( 

101 self.count_carbon_atoms(smiles) 

102 for smiles in products_smiles.split(".") 

103 ) 

104 reaction["is_carbon_balance"] = reactants_carbon == products_carbon 

105 

106 except KeyError as e: 

107 print(f"Key error: {e}") 

108 except ValueError as e: 

109 print(f"Value error: {e}") 

110 

111 

112def calculate_net_charge(sublist: list[dict[str, Union[str, int]]]) -> int: 

113 """ 

114 Calculate the net charge from a list of molecules represented as SMILES 

115 strings. 

116 

117 Args: 

118 sublist: A list of dictionaries, each with a 'smiles' string and a 

119 'Ratio' integer. 

120 

121 Returns: 

122 The net charge of the sublist as an integer. 

123 """ 

124 total_charge = 0 

125 for item in sublist: 

126 if "smiles" in item and "Ratio" in item: 

127 mol = Chem.MolFromSmiles(item["smiles"]) 

128 if mol: 

129 charge = ( 

130 sum(abs(atom.GetFormalCharge()) for atom in mol.GetAtoms()) 

131 * item["Ratio"] 

132 ) 

133 total_charge += charge 

134 return total_charge 

135 

136 

137def save_reactions_to_pdf( 

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

139 old_reaction_col: str, 

140 new_reaction_col: str, 

141 pdf_filename: str, 

142 compare: bool = False, 

143 orientation: str = "vertical", 

144 show_atom_numbers: bool = False, 

145): 

146 """ 

147 Save a list of reaction visualizations to a PDF file. 

148 

149 Parameters 

150 ---------- 

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

152 A list of dictionaries containing reaction data. 

153 old_reaction_col : str 

154 The column name containing the string representation of the old reaction. 

155 new_reaction_col : str 

156 The column name containing the string representation of the new reaction. 

157 pdf_filename : str 

158 The filename of the PDF to be saved. 

159 compare : bool, optional 

160 If True, both the old and new reactions are plotted. Default is False. 

161 orientation : str, optional 

162 The layout orientation of the plots ('vertical' or 'horizontal'). 

163 Default is 'vertical'. 

164 show_atom_numbers : bool, optional 

165 Whether to show atom numbers in the reaction visualizations. 

166 Default is False. 

167 scale_factor : float, optional 

168 Factor to scale the reaction image size in the PDF. Default is 1.0. 

169 title_font_size : int, optional 

170 Font size for the title. Default is 14. 

171 

172 Notes 

173 ----- 

174 The method plots each reaction using the plot_reactions method and saves 

175 it to a PDF file. Each reaction is plotted on a separate page. The method 

176 also handles scaling of the reaction image and includes a customizable 

177 title for each reaction page in the PDF. 

178 """ 

179 c = canvas.Canvas(pdf_filename, pagesize=landscape(letter)) 

180 page_width, page_height = landscape(letter) 

181 

182 for reaction_data in data: 

183 # Create a figure using plot_reactions method 

184 fig = ReactionVisualizer(figsize=(10, 5)).plot_reactions( 

185 reaction_data, 

186 old_reaction_col, 

187 new_reaction_col, 

188 compare, 

189 orientation, 

190 show_atom_numbers, 

191 ) 

192 

193 # Save figure to a temporary buffer 

194 buf = io.BytesIO() 

195 plt.savefig(buf, format="png") 

196 plt.close(fig) 

197 buf.seek(0) 

198 img = Image.open(buf) 

199 

200 # Save the image to a temporary file 

201 with tempfile.NamedTemporaryFile(suffix=".png") as img_temp: 

202 img.save(img_temp, format="PNG") 

203 img_temp.flush() 

204 

205 # Image dimensions 

206 img_width, img_height = img.size 

207 scale_factor = min( 

208 (page_width - 100) / img_width, (page_height - 100) / img_height 

209 ) 

210 scaled_width, scaled_height = ( 

211 img_width * scale_factor, 

212 img_height * scale_factor, 

213 ) 

214 

215 # Calculate coordinates to center the image 

216 x = (page_width - scaled_width) / 2 

217 y = (page_height - scaled_height) / 2 

218 

219 # Draw the centered image 

220 c.drawImage( 

221 img_temp.name, 

222 x, 

223 y, 

224 width=scaled_width, 

225 height=scaled_height, 

226 mask="auto", 

227 ) 

228 c.showPage() 

229 

230 c.save() 

231 print(f"Saved reactions to {pdf_filename}") 

232 

233 

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

235 pattern = re.compile(r":\d+") 

236 smiles = pattern.sub("", smiles) 

237 pattern = re.compile(r"\[(?P<atom>(B|C|N|O|P|S|F|Cl|Br|I){1,2})(?:H\d?)?\]") 

238 smiles = pattern.sub(r"\g<atom>", smiles) 

239 return smiles 

240 

241 

242def normalize_smiles(smiles: str) -> str: 

243 smiles = smiles.replace("@", "") 

244 if ">>" in smiles: 

245 return ">>".join([normalize_smiles(t) for t in smiles.split(">>")]) 

246 elif "." in smiles: 

247 token = sorted( 

248 smiles.split("."), 

249 key=lambda x: (sum(1 for c in x if c.isupper()), sum(ord(c) for c in x)), 

250 reverse=True, 

251 ) 

252 token = [normalize_smiles(t) for t in token] 

253 token.sort( 

254 key=lambda x: (sum(1 for c in x if c.isupper()), sum(ord(c) for c in x)), 

255 reverse=True, 

256 ) 

257 return ".".join(token) 

258 else: 

259 return Chem.CanonSmiles(remove_atom_mapping(smiles))