Coverage for SynRBL/SynVis/reaction_visualizer.py: 55%

69 statements  

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

1import io 

2import matplotlib.pyplot as plt 

3 

4from rdkit import Chem 

5from rdkit.Chem import AllChem 

6from rdkit.Chem.Draw import rdMolDraw2D 

7from PIL import Image 

8from typing import Dict, Tuple, Optional 

9 

10 

11class ReactionVisualizer: 

12 """ 

13 Plot and optionally compare two chemical reactions for visualization using 

14 data from a given source. 

15 

16 This method allows the visualization of chemical reactions represented as 

17 strings. It can plot a single reaction or compare two reactions 

18 side-by-side, depending on the 'compare' parameter. The reactions are 

19 visualized using RDKit and plotted using Matplotlib. 

20 

21 Parameters 

22 ---------- 

23 data : dict 

24 A dictionary containing the reaction data. 

25 old_reaction_col : str 

26 The key in 'data' for the old reaction string. 

27 new_reaction_col : str 

28 The key in 'data' for the new reaction string. 

29 compare : bool, optional 

30 If True, both the old and new reactions are plotted side by side for 

31 comparison. Default is False. 

32 orientation : str, optional 

33 The layout orientation of the plots, either 'vertical' or 'horizontal'. 

34 Default is 'vertical'. 

35 savefig : bool, optional 

36 If True, the figure is saved to the specified pathname. Default is False. 

37 pathname : str, optional 

38 The pathname where the figure will be saved, if 'savefig' is True. 

39 dpi : int, optional 

40 The resolution of the figure in dots per inch. Default is 300. 

41 

42 Examples 

43 -------- 

44 # Example usage of the plot_reactions method 

45 visualizer = ReactionVisualizer() 

46 reaction_data = { 

47 "old_reaction": "C1=CC=CC=C1.CCO>>C1=CC=CC=C1OCCO", 

48 "new_reaction": "C1=CC=CC=C1>>CCO", 

49 } 

50 visualizer.plot_reactions( 

51 reaction_data, 

52 "old_reaction", 

53 "new_reaction", 

54 compare=True, 

55 orientation="horizontal", 

56 ) 

57 

58 # To save the plot as an image 

59 visualizer.plot_reactions( 

60 reaction_data, 

61 "old_reaction", 

62 "new_reaction", 

63 compare=True, 

64 savefig=True, 

65 pathname="reaction_comparison.png", 

66 ) 

67 """ 

68 

69 def __init__( 

70 self, 

71 compare: bool = True, 

72 orientation: str = "vertical", 

73 figsize: Tuple[int, int] = (10, 5), 

74 label_position: str = "below", 

75 dpi: int = 300, 

76 bond_line_width: float = 6, 

77 atom_label_font_size: int = 50, 

78 padding: float = 0.001, 

79 ) -> None: 

80 """ 

81 Initialize the ReactionVisualizer. 

82 

83 Parameters: 

84 - compare (bool): Whether to compare old and new reactions side by 

85 side. Default is True. 

86 - orientation (str): Orientation of comparison ('vertical' or 

87 'horizontal'). Default is 'vertical'. 

88 - figsize (Tuple[int, int]): Figure size (width, height) in inches. 

89 Default is (10, 5). 

90 - label_position (str): Position of labels ('above' or 'below') the 

91 reaction images. Default is 'below'. 

92 - dpi (int): Dots per inch for image resolution. Default is 300. 

93 - bond_line_width (float): Width of bond lines in the reaction image. 

94 Default is 6. 

95 - atom_label_font_size (int): Font size for atom labels in the reaction 

96 image. Default is 50. 

97 - padding (float): Padding around the drawing in the reaction image. 

98 Default is 0.001. 

99 """ 

100 self.compare = compare 

101 self.orientation = orientation 

102 self.figsize = figsize 

103 self.label_position = label_position 

104 self.dpi = dpi 

105 self.bond_line_width = bond_line_width 

106 self.atom_label_font_size = atom_label_font_size 

107 self.padding = padding 

108 

109 @staticmethod 

110 def draw_molecule_with_atom_numbers(mol): 

111 """ 

112 Draw a molecule with atom numbers annotated. 

113 

114 Parameters 

115 ---------- 

116 mol : RDKit Molecule object 

117 The molecule to be drawn with atom numbers. 

118 

119 Returns 

120 ------- 

121 mol : RDKit Molecule object 

122 The molecule with atom numbers. 

123 """ 

124 mol_with_atom_numbers = Chem.Mol(mol) 

125 for atom in mol_with_atom_numbers.GetAtoms(): 

126 atom.SetProp("atomLabel", str(atom.GetIdx())) 

127 return mol_with_atom_numbers 

128 

129 def visualize_reaction( 

130 self, reaction_str: str, show_atom_numbers: bool = False 

131 ) -> Image: 

132 """ 

133 Visualize a single chemical reaction and return the image. 

134 

135 Parameters 

136 ---------- 

137 reaction_str : str 

138 A string representation of the reaction (e.g., 'C1=CC=CC=C1>>CCO'). 

139 

140 Returns 

141 ------- 

142 PIL.Image.Image 

143 An image of the chemical reaction. 

144 """ 

145 # Parse reactants and products from the reaction string 

146 reactants_str, products_str = reaction_str.split(">>") 

147 reactants = [Chem.MolFromSmiles(smiles) for smiles in reactants_str.split(".")] 

148 products = [Chem.MolFromSmiles(smiles) for smiles in products_str.split(".")] 

149 

150 if show_atom_numbers: 

151 reactants = [self.draw_molecule_with_atom_numbers(mol) for mol in reactants] 

152 products = [self.draw_molecule_with_atom_numbers(mol) for mol in products] 

153 

154 rxn = AllChem.ChemicalReaction() 

155 for reactant in reactants: 

156 rxn.AddReactantTemplate(reactant) 

157 for product in products: 

158 rxn.AddProductTemplate(product) 

159 

160 # Set up RDKit drawer with customizable parameters 

161 drawer = rdMolDraw2D.MolDraw2DCairo(2000, 600) # Adjust canvas size as needed 

162 opts = drawer.drawOptions() 

163 opts.bondLineWidth = self.bond_line_width # Increase bond line width 

164 opts.atomLabelFontSize = ( 

165 self.atom_label_font_size 

166 ) # Increase font size for atom labels 

167 opts.padding = self.padding # Adjust padding around the drawing 

168 

169 drawer.DrawReaction(rxn) 

170 drawer.FinishDrawing() 

171 return Image.open(io.BytesIO(drawer.GetDrawingText())) 

172 

173 def plot_reactions( 

174 self, 

175 data: Dict[str, str], 

176 old_reaction_col: str, 

177 new_reaction_col: str, 

178 compare: bool = False, 

179 orientation: str = "vertical", 

180 savefig: bool = False, 

181 pathname: Optional[str] = None, 

182 dpi: int = 300, 

183 show_atom_numbers: bool = False, 

184 ) -> None: 

185 """ 

186 Plot one or two chemical reactions for visualization. 

187 

188 Parameters 

189 ---------- 

190 data : Dict[str, str] 

191 A dictionary containing the data with keys as column names and 

192 values as reaction strings. 

193 old_reaction_col : str 

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

195 new_reaction_col : str 

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

197 compare : bool, optional 

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

199 orientation : str, optional 

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

201 Default is 'vertical'. 

202 savefig : bool, optional 

203 If True, saves the figure to the specified pathname. Default is False. 

204 pathname : str, optional 

205 Pathname to save the figure, if savefig is True. 

206 dpi : int, optional 

207 Resolution of the figure in dots per inch. Default is 300. 

208 """ 

209 # Get the old and new reaction strings from the data 

210 old_reaction_str = data[old_reaction_col] 

211 new_reaction_str = data[new_reaction_col] 

212 

213 # Create reaction images 

214 new_reaction_image = self.visualize_reaction( 

215 new_reaction_str, show_atom_numbers 

216 ) 

217 old_reaction_image = ( 

218 self.visualize_reaction(old_reaction_str, show_atom_numbers) 

219 if compare 

220 else None 

221 ) 

222 

223 # Set up plot layout 

224 if compare: 

225 nrows, ncols = (2, 1) if orientation == "vertical" else (1, 2) 

226 fig, axs = plt.subplots(nrows, ncols, figsize=self.figsize, dpi=dpi) 

227 ax_new = axs[1] if orientation == "vertical" else axs[0] 

228 ax_old = axs[0] if orientation == "vertical" else axs[1] 

229 else: 

230 fig, ax = plt.subplots(figsize=self.figsize, dpi=dpi) 

231 

232 # Plotting logic 

233 if compare: 

234 ax_old.imshow(old_reaction_image) 

235 ax_old.axis("off") 

236 ax_new.imshow(new_reaction_image) 

237 ax_new.axis("off") 

238 else: 

239 ax.imshow(new_reaction_image) 

240 ax.axis("off") 

241 

242 # Setting titles 

243 label_y_position = -0.1 if self.label_position == "below" else 1.1 

244 if compare: 

245 ax_old.set_title( 

246 "Old Reaction", position=(0.5, label_y_position), weight="bold" 

247 ) 

248 ax_new.set_title( 

249 "New Reaction", position=(0.5, label_y_position), weight="bold" 

250 ) 

251 else: 

252 ax.set_title( 

253 "New Reaction", position=(0.5, label_y_position), weight="bold" 

254 ) 

255 

256 # Saving the figure 

257 if savefig and pathname: 

258 fig.savefig(pathname, dpi=dpi) 

259 

260 # plt.tight_layout() 

261 return fig