-
Notifications
You must be signed in to change notification settings - Fork 0
/
app_molviz_v4.py
339 lines (291 loc) · 14.7 KB
/
app_molviz_v4.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
# Shiny for Python app for viewing and saving 2D images of small molecules of interests
# 2D images of molecules saved as PNG files via MolToFile()
# Atoms & bonds highlighting via MolToImage()
# Select atom & bond highlighting (on or off) with or without atom indices
# Added texts
# Trialled using "atomNote" (previously "atomLabel")
# TODO:
# To add introduction of app
# - how to use, features to view, save and look up compounds
# - split sections: Panel to add compound, panel to view merged image, df to search below
# Import libraries---
import pandas as pd
from rdkit import Chem
from rdkit.Chem import Draw
import datamol as dm
from itables.shiny import DT
from pathlib import Path
from PIL import Image
from matplotlib.colors import ColorConverter
from shiny import App, Inputs, Outputs, Session, render, ui, reactive
from shiny.types import ImgData
import shinyswatch
# Data source---
# Using pre-processed and standardised data
df = pd.read_csv("df_ai_cleaned.csv")
# Avoid any changes to original dataset object by using .copy()
df = df.copy()
#df = df.reset_index()
df["mol"] = df["standard_smiles"].apply(lambda x: dm.to_mol(x))
mols = df["mol"]
mols = list(mols)
# Input---
# ***Added features***
# Added ui.navset_tab_card & ui.nav() to keep each of the 4 cpds in separate tabs!
# - refer to "Orbit simulation" example
# Changed the merged PNG image from ui.row() to ui.column() to be in the right hand side of the space
# - refer to "Orbit simulation" example
# - to allow quick references of compound index numbers in the same app
# Removed multiple input_numeric fields for atom & bond highlightings
# - using direct number inputs in input text areas then string to integer conversion
# Added interactive dataframe beneath PNG image processing area
# Added option to show atom indices in PNG images
# Changed tabs
# - 2 for non-indexed molecules & 2 for indexed molecules
# - both with option to turn on/off highlighting
# - to allow quick comparison between unindexed & indexed molecules side-by-side
# Added shinyswatch theme solar
app_ui = ui.page_fluid(
shinyswatch.theme.solar(),
{"class": "col-lg-15 py-4 mx-auto text-left"},
ui.h3("Small molecule visualiser - Molviz"),
ui.row(
ui.p(
"""
This is a Shiny for Python web application for viewing and saving 2D images of small molecules of interests.
The main backbone libraries used are RDKit and Datamol.
The data source is based on compound data that included molecular representations such as SMILES in a dataframe.
For demonstration purpose, the example provided here was a set of anti-infectives sourced from ChEMBL version _.
Users can generate similar app by using own compound data (e.g. compound activity data for structure-activity relationship work) with the code available.
"""
),
ui.column(
4,
ui.navset_tab_card(
ui.nav(
"Unindexed - 1",
ui.input_numeric("mol1", "Select compound via index number:", 0, min = 0, max = 143),
ui.input_select("image_style1", "Choose substructure highlights:",
{"no_high": "Without highlights",
"high": "With highlights"}),
ui.input_text_area("atom1", "Enter atom number to highlight:", placeholder = "e.g. 0, 1, 2, 3..."),
ui.input_text_area("bond1", "Enter bond number to highlight:", placeholder = "e.g. 0, 1, 2, 3..."),
ui.input_text("filename1", "File name for PNG image:"),
ui.input_action_button("btn1", "Save and view", class_= "btn-success"),
ui.output_image("image1")
),
ui.nav(
"Indexed - 2",
ui.input_numeric("mol2", "Select compound via index number:", 0, min = 0, max = 143),
ui.input_select("image_style2", "Choose substructure highlights:",
{"no_high": "Without highlights",
"high": "With highlights"}),
ui.input_text_area("atom2", "Enter atom number to highlight:", placeholder = "e.g. 0, 1, 2, 3..."),
ui.input_text_area("bond2", "Enter bond number to highlight:", placeholder = "e.g. 0, 1, 2, 3..."),
ui.input_text("filename2", "File name for PNG image:"),
ui.input_action_button("btn2", "Save and view", class_= "btn-success"),
ui.output_image("image2")
),
ui.nav(
"Unindexed - 3",
ui.input_numeric("mol3", "Select compound via index number:", 0, min = 0, max = 143),
ui.input_select("image_style3", "Choose substructure highlights:",
{"no_high": "Without highlights",
"high": "With highlights"}),
ui.input_text_area("atom3", "Enter atom number to highlight:", placeholder = "e.g. 0, 1, 2, 3..."),
ui.input_text_area("bond3", "Enter bond number to highlight:", placeholder = "e.g. 0, 1, 2, 3..."),
ui.input_text("filename3", "File name for PNG image:"),
ui.input_action_button("btn3", "Save and view", class_= "btn-success"),
ui.output_image("image3")
),
ui.nav(
"Indexed - 4",
ui.input_numeric("mol4", "Select compound via index number:", 0, min = 0, max = 143),
ui.input_select("image_style4", "Choose substructure highlights:",
{"no_high": "Without highlights",
"high": "With highlights"}),
ui.input_text_area("atom4", "Enter atom number to highlight:", placeholder = "e.g. 0, 1, 2, 3..."),
ui.input_text_area("bond4", "Enter bond number to highlight:", placeholder = "e.g. 0, 1, 2, 3..."),
ui.input_text("filename4", "File name for PNG image:"),
ui.input_action_button("btn4", "Save and view", class_= "btn-success"),
ui.output_image("image4")
),
)
),
ui.column(
6,
ui.tags.ul(
ui.tags.li(
"""
Two types of PNG images are available: Indexed (atoms labelled with numbers), or Unindexed (native skeletal forms without atoms labelled)"""
),
ui.tags.li(
"""
Atoms & bonds highlighting available via MolToImage()"""
),
ui.tags.li(
"""
2D images of molecules can be saved as PNG files via MolToFile()"""
),
ui.tags.li(
"""
An option to save each of the four images as a merged version in a grid format
with image saved in this order first - top left, second - top right, third - bottom left and lastly - bottom right)"""
),
ui.tags.li(
"""
Compound name search is available in the interactive dataframe beneath the image area"""
)),
ui.input_text("merge_filename", "File name for merged PNG images:"),
ui.input_action_button("btn_merge", "Confirm", class_="btn"),
ui.output_image("merge_image"),
),
ui.row(
ui.page_fluid(ui.HTML(DT(df)))
)
),
)
# Server output---
def server(input, output, session):
@output
@render.image
@reactive.Calc
# Function to show unindexed compound as PNG image (file 1)
def image1():
input.btn1()
with reactive.isolate():
if input.image_style1() == "high":
# Highlight atoms & bonds
img = Draw.MolToImage(mols[input.mol1()],
highlightAtoms = [int(n) for n in input.atom1().split(",")],
highlightBonds = [int(n) for n in input.bond1().split(",")],
highlightColor = ColorConverter().to_rgb("aqua")
)
# Save image
img.save(f"{input.filename1()}.png")
# Show saved PNG file from selected compound
dir = Path(__file__).resolve().parent
img_1: ImgData = {"src": str(dir / f"{input.filename1()}.png")}
return img_1
elif input.image_style1() == "no_high":
Draw.MolToFile(mols[input.mol1()], f"{input.filename1()}.png")
dir = Path(__file__).resolve().parent
img_1: ImgData = {"src": str(dir / f"{input.filename1()}.png")}
return img_1
else:
return None
@output
@render.image
@reactive.Calc
# Function to show indexed compound as PNG image (file 2)
def image2():
input.btn2()
with reactive.isolate():
if input.image_style2() == "no_high":
for atom in mols[input.mol2()].GetAtoms():
# Previously used 'atomLabel'
atom.SetProp('atomNote', str(atom.GetIdx()))
Draw.MolToFile(mols[input.mol2()], f"{input.filename2()}.png")
dir = Path(__file__).resolve().parent
img_2: ImgData = {"src": str(dir / f"{input.filename2()}.png")}
return img_2
elif input.image_style2() == "high":
for atom in mols[input.mol2()].GetAtoms():
atom.SetProp('atomNote', str(atom.GetIdx()))
# Highlight atoms & bonds
img = Draw.MolToImage(mols[input.mol2()],
highlightAtoms = [int(n) for n in input.atom2().split(",")],
highlightBonds = [int(n) for n in input.bond2().split(",")],
highlightColor = ColorConverter().to_rgb("aqua")
)
# Save image
img.save(f"{input.filename2()}.png")
# Show saved PNG file from selected compound
dir = Path(__file__).resolve().parent
img_2: ImgData = {"src": str(dir / f"{input.filename2()}.png")}
return img_2
else:
return None
@output
@render.image
@reactive.Calc
# Function to show unindexed compound as PNG image (file 3)
def image3():
input.btn3()
with reactive.isolate():
if input.image_style3() == "high":
# Highlight atoms & bonds
img = Draw.MolToImage(mols[input.mol3()],
highlightAtoms = [int(n) for n in input.atom3().split(",")],
highlightBonds = [int(n) for n in input.bond3().split(",")],
highlightColor = ColorConverter().to_rgb("aqua")
)
# Save image
img.save(f"{input.filename3()}.png")
# Show saved PNG file from selected compound
dir = Path(__file__).resolve().parent
img_3: ImgData = {"src": str(dir / f"{input.filename3()}.png")}
return img_3
elif input.image_style3() == "no_high":
Draw.MolToFile(mols[input.mol3()], f"{input.filename3()}.png")
dir = Path(__file__).resolve().parent
img_3: ImgData = {"src": str(dir / f"{input.filename3()}.png")}
return img_3
else:
return None
@output
@render.image
@reactive.Calc
# Function to show indexed compound as PNG image (file 4)
def image4():
input.btn4()
with reactive.isolate():
if input.image_style4() == "no_high":
for atom in mols[input.mol4()].GetAtoms():
atom.SetProp('atomNote', str(atom.GetIdx()))
Draw.MolToFile(mols[input.mol4()], f"{input.filename4()}.png")
dir = Path(__file__).resolve().parent
img_4: ImgData = {"src": str(dir / f"{input.filename4()}.png")}
return img_4
elif input.image_style4() == "high":
for atom in mols[input.mol4()].GetAtoms():
atom.SetProp('atomNote', str(atom.GetIdx()))
# Highlight atoms & bonds
img = Draw.MolToImage(mols[input.mol4()],
highlightAtoms = [int(n) for n in input.atom4().split(",")],
highlightBonds = [int(n) for n in input.bond4().split(",")],
highlightColor = ColorConverter().to_rgb("aqua")
)
# Save image
img.save(f"{input.filename4()}.png")
# Show saved PNG file from selected compound
dir = Path(__file__).resolve().parent
img_4: ImgData = {"src": str(dir / f"{input.filename4()}.png")}
return img_4
else:
return None
@output
@render.image
# Function to paste selected PNG files into a table of 4 images
def merge_image():
input.btn_merge()
with reactive.isolate():
# Using PIL/Pillow to manipulate images
img1 = Image.open(f"{input.filename1()}.png")
img2 = Image.open(f"{input.filename2()}.png")
img3 = Image.open(f"{input.filename3()}.png")
img4 = Image.open(f"{input.filename4()}.png")
# Create a blank image template - (width, height)
blank_image = Image.new("RGB", (600, 600))
# Paste img1 to img4 together in a grid (top left, right, bottom left, right)
blank_image.paste(img1, (0, 0))
blank_image.paste(img2, (300, 0))
blank_image.paste(img3, (0, 300))
blank_image.paste(img4, (300, 300))
# Save combined/merged image as a new PNG file
blank_image.save(f"{input.merge_filename()}.png")
# Show merged image of selected PNG images
dir = Path(__file__).resolve().parent
img_merge: ImgData = {"src": str(dir / f"{input.merge_filename()}.png")}
return img_merge
app = App(app_ui, server)