Trương Gia Bảo commited on
Commit
8f4cbce
·
1 Parent(s): 53e9a2b

Update Optimize a batch page, fix UI

Browse files
Files changed (2) hide show
  1. app.py +363 -63
  2. app_backup.py +0 -437
app.py CHANGED
@@ -101,6 +101,8 @@ def mol_passes_filters_custom(mol,
101
  return 'Isomeric'
102
  if Chem.MolFromSmiles(smiles) is None:
103
  return 'Isomeric'
 
 
104
  return 'YES'
105
 
106
  def penalized_logp_standard(mol):
@@ -169,12 +171,26 @@ def set_step(id):
169
  def get_step():
170
  return st.session_state['current_step']
171
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
  @st.cache_resource
173
  def load_model():
174
- vocab = [x.strip("\r\n ") for x in open('./vocab.txt')]
175
- vocab = Vocab(vocab)
176
  model = JTPropVAE(vocab, 450, 56, 20, 3)
177
- model.load_state_dict(torch.load(model_path,map_location=torch.device('cpu')))
 
 
 
178
  return model
179
 
180
  from streamlit_lottie import st_lottie
@@ -211,6 +227,33 @@ def oam_sidebar(step):
211
  st.markdown('|')
212
  st.markdown("<h4 style='color: "+color_ls[3]+"'>Finished</h4>",unsafe_allow_html=True)
213
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
214
  # @st.cache_data(experimental_allow_widgets=True)
215
 
216
  # if 'sidebar_con' not in st.session_state:
@@ -299,24 +342,37 @@ def Optimize_a_molecule():
299
  with sidebar_con.container():
300
  set_step(0)
301
  oam_sidebar(0)
302
- oab_sel_container = st.empty()
303
  if 'checked_single' not in st.session_state:
304
  st.session_state.checked_single = 'NO'
305
- with oab_sel_container.container():
306
- oam_sel_col = st.columns([3,7])
307
- oam_sel_col[0].selectbox("Select an example",options=['-','Sorafenib','Pazopanib','Sunitinib'],key='mode',on_change=reset_oam_state)
308
- if st.session_state.mode == '-':
309
- st.session_state.smiles = oam_sel_col[1].text_input('Enter a SMILES string (max 200 chars):',max_chars=200)
310
- elif st.session_state.mode == 'Sorafenib':
311
- st.session_state.smiles = 'CNC(=O)C1=NC=CC(=C1)OC2=CC=C(C=C2)NC(=O)NC3=CC(=C(C=C3)Cl)C(F)(F)F'
312
- oam_sel_col[1].text_input('Enter a SMILES string (max 200 chars):','CNC(=O)C1=NC=CC(=C1)OC2=CC=C(C=C2)NC(=O)NC3=CC(=C(C=C3)Cl)C(F)(F)F',max_chars=200,disabled=True)
313
- elif st.session_state.mode == 'Pazopanib':
314
- st.session_state.smiles = 'CC1=C(C=C(C=C1)NC2=NC=CC(=N2)N(C)C3=CC4=NN(C(=C4C=C3)C)C)S(=O)(=O)N'
315
- oam_sel_col[1].text_input('Enter a SMILES string (max 200 chars):','CC1=C(C=C(C=C1)NC2=NC=CC(=N2)N(C)C3=CC4=NN(C(=C4C=C3)C)C)S(=O)(=O)N',max_chars=200,disabled=True)
316
- elif st.session_state.mode == 'Sunitinib':
317
- st.session_state.smiles = 'CCN(CC)CCNC(=O)C1=C(NC(=C1C)C=C2C3=C(C=CC(=C3)F)NC2=O)C'
318
- oam_sel_col[1].text_input('Enter a SMILES string (max 200 chars):','CCN(CC)CCNC(=O)C1=C(NC(=C1C)C=C2C3=C(C=CC(=C3)F)NC2=O)C',max_chars=200,disabled=True)
319
- st.columns([4,1,4])[1].button('Check SMILES',on_click=check_single,args=[st.session_state.smiles])
 
 
 
 
 
 
 
 
 
 
 
 
 
320
 
321
  check_single_con = st.empty()
322
  if 'smiles_selected' in st.session_state:
@@ -325,19 +381,19 @@ def Optimize_a_molecule():
325
  if 'checked_single' in st.session_state:
326
  if st.session_state.checked_single == 'EnterError':
327
  st.markdown("<p style='text-align: center; color: red;'><b>Please enter a SMILES string.</b></p>",unsafe_allow_html=True)
328
- sidebar_con.empty()
329
  with sidebar_con.container():
330
  set_step(0)
331
  oam_sidebar(0)
332
  elif st.session_state.checked_single == 'MolError':
333
  st.markdown("<p style='text-align: center; color: red;'><b>SMILES is invalid. Please enter a valid SMILES.</b></p>",unsafe_allow_html=True)
334
- sidebar_con.empty()
335
  with sidebar_con.container():
336
  set_step(0)
337
  oam_sidebar(0)
338
  elif st.session_state.checked_single == 'YES':
339
  st.markdown("<b>Canonicalized SMILES</b>",unsafe_allow_html=True)
340
- st.code(st.session_state.smiles)
341
  st.markdown("<p style='text-align: center; color: mediumseagreen'>MOSES filters passed successfully.</p>",unsafe_allow_html=True)
342
  mol = Chem.MolFromSmiles(st.session_state.smiles)
343
  imgByteArr = io.BytesIO()
@@ -355,7 +411,7 @@ def Optimize_a_molecule():
355
  st.session_state.smiles_checked = True
356
  # render_sidebar()
357
  # col1, col2, col3 = st.columns(3)
358
- sidebar_con.empty()
359
  with sidebar_con.container():
360
  set_step(1)
361
  oam_sidebar(1)
@@ -363,41 +419,45 @@ def Optimize_a_molecule():
363
  st.slider('Choose learning rate: ',0.0,5.0,0.4,key='lr_s')
364
  st.slider('Choose similarity cutoff: ',0.0,1.0,0.4,key='sim_cutoff_s')
365
  st.slider('Choose number of iterations: ',1,100,80,key='n_iter_s')
366
- st.session_state.optim_single_butt = st.form_submit_button("Optimize")
367
  else:
368
  st.markdown("<b>Canonicalized SMILES</b>",unsafe_allow_html=True)
369
  st.code(st.session_state.smiles)
370
- st.markdown("<p style='text-align: center; color: red;'><b>MOSES filters passed failed. Please use another molecule.</b></p>",unsafe_allow_html=True)
371
- sidebar_con.empty()
 
 
 
372
  with sidebar_con.container():
373
  set_step(0)
374
  oam_sidebar(0)
375
  else: check_single_con.empty()
376
 
377
  optim_single_con = st.empty()
378
- if 'optim_single_butt' in st.session_state:
379
- if st.session_state.optim_single_butt and st.session_state.smiles_checked:
380
- sidebar_con.empty()
381
  with sidebar_con.container():
382
  set_step(2)
383
  oam_sidebar(2)
 
 
 
 
 
 
 
 
 
 
 
384
  with optim_single_con.container():
385
- ani_con = st.empty()
386
- with ani_con.container():
387
- st.markdown('Operation in progress. Please wait...')
388
- render_animation()
389
- new_smiles,sim = optim_single(st.session_state.smiles,st.session_state.lr_s,st.session_state.sim_cutoff_s,st.session_state.n_iter_s)
390
- ani_con.empty()
391
- sidebar_con.empty()
392
- with sidebar_con.container():
393
- set_step(3)
394
- oam_sidebar(3)
395
- if new_smiles is None:
396
  st.markdown("<h4 style='text-align: center; color: red;'>Cannot optimize! Please choose another setting.</h4>",unsafe_allow_html=True)
397
  else:
398
  st.markdown("<b style='text-align: center;'>New SMILES</b>",unsafe_allow_html=True)
399
- st.code(new_smiles)
400
- new_mol = Chem.MolFromSmiles(new_smiles)
401
  if new_mol is None:
402
  st.markdown("<p style='text-align: center; color: red;'>New SMILES is invalid! Please choose another setting.</p>",unsafe_allow_html=True)
403
  # st.write('New SMILES is invalid.')
@@ -422,59 +482,299 @@ def Optimize_a_molecule():
422
  col32.metric('Cycle score', '%d' % (-st.session_state.new_cycle),'%d'%(-st.session_state.new_cycle+st.session_state.cycle),delta_color='inverse')
423
  col42.metric('Penalized LogP', '%.5f' % (st.session_state.new_pen_p),'%.5f'%(st.session_state.new_pen_p-st.session_state.pen_p))
424
  # st.metric('New penalized logP score','%.5f' % (new_score), '%.5f'%(new_score-score))
425
- st.metric('Similarity','%.5f' % (sim))
426
  # st.write('Caching ZINC20 if necessary...')
427
  with st.spinner("Caching ZINC20 if necessary..."):
428
- if buy(new_smiles, catalog='zinc20',canonicalize=True):
429
  st.write('This molecule exists.')
430
  st.markdown("<h3 style='text-align: center; color: darkturquoise;'><b>This molecule exists.</h3>",unsafe_allow_html=True)
431
  else:
432
  # st.write('THIS MOLECULE DOES NOT EXIST!')
433
  st.markdown("<h3 style='text-align: center; color: mediumseagreen;'>THIS MOLECULE DOES NOT EXIST!</h3>",unsafe_allow_html=True)
434
  st.markdown("<p style='text-align: center; color: grey;'>Checked using molbloom</p>",unsafe_allow_html=True)
 
 
 
435
  else: optim_single_con.empty()
 
436
 
437
  def check_single(smiles):
438
  # render_view()
439
  st.session_state.smiles_selected = True
440
- check_single_con = st.empty()
 
441
 
442
  # optim = False
443
- with check_single_con.container():
444
- if len(smiles) == 0:
445
- st.session_state.checked_single = 'EnterError'
 
 
 
 
446
  else:
447
- mol = Chem.MolFromSmiles(smiles)
448
- if mol is None:
449
- st.session_state.checked_single = 'MolError'
450
- else:
451
- st.session_state.smiles = Chem.MolToSmiles(mol)
452
- st.session_state.logp,st.session_state.sa,st.session_state.cycle,st.session_state.pen_p = penalized_logp_standard(mol)
453
- moses_passed = mol_passes_filters_custom(mol)
454
- st.session_state.checked_single = moses_passed
455
 
456
 
457
- def optim_single(smiles,lr,sim_cutoff,n_iter):
458
- # render_view()
459
-
460
-
461
- model = load_model()
462
 
463
  new_smiles,sim = model.optimize(smiles, sim_cutoff=sim_cutoff, lr=lr, num_iter=n_iter)
464
-
465
  return new_smiles,sim
466
 
467
 
468
 
469
  def Optimize_a_batch():
470
- st.empty()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
471
 
472
  def reset_oam_state():
473
  st.session_state.smiles_selected = False
474
  st.session_state.checked_single = 'NO'
475
  st.session_state.smiles_checked = False
 
476
  set_step(0)
477
 
 
 
 
 
 
 
 
 
 
478
  def rerun():
479
  st.experimental_rerun()
480
  def render_view():
 
101
  return 'Isomeric'
102
  if Chem.MolFromSmiles(smiles) is None:
103
  return 'Isomeric'
104
+ if not check_vocab(Chem.MolToSmiles(mol)):
105
+ return 'NoVocab'
106
  return 'YES'
107
 
108
  def penalized_logp_standard(mol):
 
171
  def get_step():
172
  return st.session_state['current_step']
173
 
174
+
175
+ vocab = [x.strip("\r\n ") for x in open('./vocab.txt')]
176
+ vocab_set = set(vocab)
177
+ vocab = Vocab(vocab)
178
+
179
+ def check_vocab(smiles):
180
+ cset = set()
181
+ mol = MolTree(smiles)
182
+ for c in mol.nodes:
183
+ cset.add(c.smiles)
184
+ return cset.issubset(vocab_set)
185
+
186
+
187
  @st.cache_resource
188
  def load_model():
 
 
189
  model = JTPropVAE(vocab, 450, 56, 20, 3)
190
+ if torch.cuda.is_available():
191
+ model.load_state_dict(torch.load(model_path))
192
+ else:
193
+ model.load_state_dict(torch.load(model_path,map_location=torch.device('cpu')))
194
  return model
195
 
196
  from streamlit_lottie import st_lottie
 
227
  st.markdown('|')
228
  st.markdown("<h4 style='color: "+color_ls[3]+"'>Finished</h4>",unsafe_allow_html=True)
229
 
230
+ def oab_sidebar(step):
231
+ st.title('**Optimize a batch**')
232
+ prog_bar = st.progress(0)
233
+ # cur_step = get_step()
234
+ if step == 0: prog_bar.progress(0)
235
+ if step == 1: prog_bar.progress(20)
236
+ if step == 2: prog_bar.progress(40)
237
+ if step == 3: prog_bar.progress(60)
238
+ if step == 4: prog_bar.progress(80)
239
+ if step == 5: prog_bar.progress(100)
240
+ st.markdown('\n')
241
+
242
+ # st.markdown(get_step())
243
+ color_ls = colorize_step(6,step)
244
+
245
+ st.markdown("<h4 style='color: "+color_ls[0]+"'>Upload SMILES file</h4>",unsafe_allow_html=True)
246
+ st.markdown('|')
247
+ st.markdown("<h4 style='color: "+color_ls[1]+"'>Checking SMILES</h4>",unsafe_allow_html=True)
248
+ st.markdown('|')
249
+ st.markdown("<h4 style='color: "+color_ls[2]+"'>Select scores</h4>",unsafe_allow_html=True)
250
+ st.markdown('|')
251
+ st.markdown("<h4 style='color: "+color_ls[3]+"'>Choose settings</h4>",unsafe_allow_html=True)
252
+ st.markdown('|')
253
+ st.markdown("<h4 style='color: "+color_ls[4]+"'>Optimizing a batch</h4>",unsafe_allow_html=True)
254
+ st.markdown('|')
255
+ st.markdown("<h4 style='color: "+color_ls[5]+"'>Finished</h4>",unsafe_allow_html=True)
256
+
257
  # @st.cache_data(experimental_allow_widgets=True)
258
 
259
  # if 'sidebar_con' not in st.session_state:
 
342
  with sidebar_con.container():
343
  set_step(0)
344
  oam_sidebar(0)
345
+ # oab_sel_container = st.empty()
346
  if 'checked_single' not in st.session_state:
347
  st.session_state.checked_single = 'NO'
348
+ if 'mode' not in st.session_state:
349
+ st.session_state.mode = 0
350
+ if 'single_optimized' not in st.session_state:
351
+ st.session_state.single_optimized = False
352
+ if 'smiles_checked' not in st.session_state:
353
+ st.session_state.smiles_checked = False
354
+ # with oab_sel_container.container():
355
+ oam_sel_col = st.columns([3,7])
356
+ mode = oam_sel_col[0].selectbox("Select an example",options=['-','Sorafenib','Pazopanib','Sunitinib'],on_change=reset_oam_state,index=st.session_state.mode)
357
+ if mode == '-':
358
+ smiles = oam_sel_col[1].text_input('Enter a SMILES string (max 200 chars):',max_chars=200)
359
+ st.session_state.mode = 0
360
+ elif mode == 'Sorafenib':
361
+ smiles = 'CNC(=O)C1=NC=CC(=C1)OC2=CC=C(C=C2)NC(=O)NC3=CC(=C(C=C3)Cl)C(F)(F)F'
362
+ oam_sel_col[1].text_input('Enter a SMILES string (max 200 chars):','CNC(=O)C1=NC=CC(=C1)OC2=CC=C(C=C2)NC(=O)NC3=CC(=C(C=C3)Cl)C(F)(F)F',max_chars=200,disabled=True)
363
+ st.session_state.mode = 1
364
+ elif mode == 'Pazopanib':
365
+ smiles = 'CC1=C(C=C(C=C1)NC2=NC=CC(=N2)N(C)C3=CC4=NN(C(=C4C=C3)C)C)S(=O)(=O)N'
366
+ oam_sel_col[1].text_input('Enter a SMILES string (max 200 chars):','CC1=C(C=C(C=C1)NC2=NC=CC(=N2)N(C)C3=CC4=NN(C(=C4C=C3)C)C)S(=O)(=O)N',max_chars=200,disabled=True)
367
+ st.session_state.mode = 2
368
+ elif mode == 'Sunitinib':
369
+ smiles = 'CCN(CC)CCNC(=O)C1=C(NC(=C1C)C=C2C3=C(C=CC(=C3)F)NC2=O)C'
370
+ oam_sel_col[1].text_input('Enter a SMILES string (max 200 chars):','CCN(CC)CCNC(=O)C1=C(NC(=C1C)C=C2C3=C(C=CC(=C3)F)NC2=O)C',max_chars=200,disabled=True)
371
+ st.session_state.mode = 3
372
+ st.columns([4,1,4])[1].button('Check SMILES',on_click=check_single,args=[smiles])
373
+
374
+ if 'optim_single_butt' not in locals():
375
+ optim_single_butt = False
376
 
377
  check_single_con = st.empty()
378
  if 'smiles_selected' in st.session_state:
 
381
  if 'checked_single' in st.session_state:
382
  if st.session_state.checked_single == 'EnterError':
383
  st.markdown("<p style='text-align: center; color: red;'><b>Please enter a SMILES string.</b></p>",unsafe_allow_html=True)
384
+ # sidebar_con.empty()
385
  with sidebar_con.container():
386
  set_step(0)
387
  oam_sidebar(0)
388
  elif st.session_state.checked_single == 'MolError':
389
  st.markdown("<p style='text-align: center; color: red;'><b>SMILES is invalid. Please enter a valid SMILES.</b></p>",unsafe_allow_html=True)
390
+ # sidebar_con.empty()
391
  with sidebar_con.container():
392
  set_step(0)
393
  oam_sidebar(0)
394
  elif st.session_state.checked_single == 'YES':
395
  st.markdown("<b>Canonicalized SMILES</b>",unsafe_allow_html=True)
396
+ st.code(Chem.CanonSmiles(st.session_state.smiles))
397
  st.markdown("<p style='text-align: center; color: mediumseagreen'>MOSES filters passed successfully.</p>",unsafe_allow_html=True)
398
  mol = Chem.MolFromSmiles(st.session_state.smiles)
399
  imgByteArr = io.BytesIO()
 
411
  st.session_state.smiles_checked = True
412
  # render_sidebar()
413
  # col1, col2, col3 = st.columns(3)
414
+ # sidebar_con.empty()
415
  with sidebar_con.container():
416
  set_step(1)
417
  oam_sidebar(1)
 
419
  st.slider('Choose learning rate: ',0.0,5.0,0.4,key='lr_s')
420
  st.slider('Choose similarity cutoff: ',0.0,1.0,0.4,key='sim_cutoff_s')
421
  st.slider('Choose number of iterations: ',1,100,80,key='n_iter_s')
422
+ optim_single_butt = st.form_submit_button("Optimize")
423
  else:
424
  st.markdown("<b>Canonicalized SMILES</b>",unsafe_allow_html=True)
425
  st.code(st.session_state.smiles)
426
+ if st.session_state.checked_single == 'NoVocab':
427
+ st.markdown("<p style='text-align: center; color: red;'><b>The molecule contains unavailable vocab(s). Please use another molecule.</b></p>",unsafe_allow_html=True)
428
+ else:
429
+ st.markdown("<p style='text-align: center; color: red;'><b>MOSES filters passed failed. Please use another molecule.</b></p>",unsafe_allow_html=True)
430
+ # sidebar_con.empty()
431
  with sidebar_con.container():
432
  set_step(0)
433
  oam_sidebar(0)
434
  else: check_single_con.empty()
435
 
436
  optim_single_con = st.empty()
437
+ if st.session_state.smiles_checked:
438
+ if optim_single_butt:
439
+ # sidebar_con.empty()
440
  with sidebar_con.container():
441
  set_step(2)
442
  oam_sidebar(2)
443
+
444
+ ani_con = st.empty()
445
+ with ani_con.container():
446
+ st.markdown('Operation in progress. Please wait...')
447
+ render_animation()
448
+ model = load_model()
449
+ st.session_state.new_smiles,st.session_state.sim = optim_single(st.session_state.smiles,model,st.session_state.lr_s,st.session_state.sim_cutoff_s,st.session_state.n_iter_s)
450
+ st.session_state.single_optimized = True
451
+ ani_con.empty()
452
+ # sidebar_con.empty()
453
+ if st.session_state.single_optimized:
454
  with optim_single_con.container():
455
+ if st.session_state.new_smiles is None:
 
 
 
 
 
 
 
 
 
 
456
  st.markdown("<h4 style='text-align: center; color: red;'>Cannot optimize! Please choose another setting.</h4>",unsafe_allow_html=True)
457
  else:
458
  st.markdown("<b style='text-align: center;'>New SMILES</b>",unsafe_allow_html=True)
459
+ st.code(st.session_state.new_smiles)
460
+ new_mol = Chem.MolFromSmiles(st.session_state.new_smiles)
461
  if new_mol is None:
462
  st.markdown("<p style='text-align: center; color: red;'>New SMILES is invalid! Please choose another setting.</p>",unsafe_allow_html=True)
463
  # st.write('New SMILES is invalid.')
 
482
  col32.metric('Cycle score', '%d' % (-st.session_state.new_cycle),'%d'%(-st.session_state.new_cycle+st.session_state.cycle),delta_color='inverse')
483
  col42.metric('Penalized LogP', '%.5f' % (st.session_state.new_pen_p),'%.5f'%(st.session_state.new_pen_p-st.session_state.pen_p))
484
  # st.metric('New penalized logP score','%.5f' % (new_score), '%.5f'%(new_score-score))
485
+ st.metric('Similarity','%.5f' % (st.session_state.sim))
486
  # st.write('Caching ZINC20 if necessary...')
487
  with st.spinner("Caching ZINC20 if necessary..."):
488
+ if buy(st.session_state.new_smiles, catalog='zinc20',canonicalize=True):
489
  st.write('This molecule exists.')
490
  st.markdown("<h3 style='text-align: center; color: darkturquoise;'><b>This molecule exists.</h3>",unsafe_allow_html=True)
491
  else:
492
  # st.write('THIS MOLECULE DOES NOT EXIST!')
493
  st.markdown("<h3 style='text-align: center; color: mediumseagreen;'>THIS MOLECULE DOES NOT EXIST!</h3>",unsafe_allow_html=True)
494
  st.markdown("<p style='text-align: center; color: grey;'>Checked using molbloom</p>",unsafe_allow_html=True)
495
+ with sidebar_con.container():
496
+ set_step(3)
497
+ oam_sidebar(3)
498
  else: optim_single_con.empty()
499
+ else: optim_single_con.empty()
500
 
501
  def check_single(smiles):
502
  # render_view()
503
  st.session_state.smiles_selected = True
504
+ st.session_state.smiles = smiles
505
+ # check_single_con = st.empty()
506
 
507
  # optim = False
508
+ # with check_single_con.container():
509
+ if len(smiles) == 0:
510
+ st.session_state.checked_single = 'EnterError'
511
+ else:
512
+ mol = Chem.MolFromSmiles(smiles)
513
+ if mol is None:
514
+ st.session_state.checked_single = 'MolError'
515
  else:
516
+ st.session_state.smiles = Chem.MolToSmiles(mol)
517
+ st.session_state.logp,st.session_state.sa,st.session_state.cycle,st.session_state.pen_p = penalized_logp_standard(mol)
518
+ moses_passed = mol_passes_filters_custom(mol)
519
+ st.session_state.checked_single = moses_passed
 
 
 
 
520
 
521
 
522
+ def optim_single(smiles,model,lr,sim_cutoff,n_iter):
 
 
 
 
523
 
524
  new_smiles,sim = model.optimize(smiles, sim_cutoff=sim_cutoff, lr=lr, num_iter=n_iter)
525
+
526
  return new_smiles,sim
527
 
528
 
529
 
530
  def Optimize_a_batch():
531
+ st.session_state.sc_name = ['logp','sa','cycle','pen_logp']
532
+ st.session_state.new_sc_name = ['new_'+n for n in st.session_state.sc_name]
533
+ st.markdown("<h2 style='text-align: center;'>Optimize a batch</h2>",unsafe_allow_html=True)
534
+ with st.expander(':snowman: :blue[Instruction]'):
535
+ guide = """<h4 style='color:tomato;'>Steps to optimize a molucule</h4>
536
+ 1. Upload a text file with SMILES string on each line.</br>
537
+ 2. Check the SMILES strings to make sure that they are valid and pass MOSES filters.</br>
538
+ 3. Select scores to calculate (penalized LogP included). Keep passed SMILES and calculate selected scores.</br>
539
+ 4. Configure the settings to generate new molecules. The new molecules should have higher penalized LogP values.</br>
540
+ - Learning rate: How 'far' from each molecule that you want to search</br>
541
+ - Similarity cutoff: How 'similar' to each molecule that you want to search</br>
542
+ - Number of iterations: Number of generation trials per molecule</br>
543
+ 5. <i>(Optional)</i> You can download the dataframe at any steps as *.csv file.</br>
544
+ <h4 style='color:darkturquoise;'>Annotation</h4>
545
+ <b>SMILES</b> - Simplified molecular-input line-entry system</br>
546
+ <b>LogP</b> - The log of the partition coefficient of a solute between octanol and water, at near infinite dilution</br>
547
+ <b>SA score</b> - Synthetic Accessibility Score (lower is better)</br>
548
+ <b>Cycle score</b> - A number of carbon rings of size larger than 6 (lower is better)</br>
549
+ <b>Penalized LogP</b> - Standardized score of <i>LogP - SA score - Cycle score</i></br>
550
+ <b>Similarity</b> - Molecular similarity is calculated via Morgan fingerprint of radius 2 with Tanimoto similarity</br>
551
+ """
552
+ st.markdown(guide,unsafe_allow_html=True)
553
+
554
+ with st.sidebar:
555
+ sidebar_con = st.empty()
556
+ # sidebar_con.empty()
557
+ with sidebar_con.container():
558
+ set_step(0)
559
+ oab_sidebar(0)
560
+ oab_upl_container = st.empty()
561
+ if 'smiles_upload_change' not in st.session_state:
562
+ st.session_state.smiles_upload_change = False
563
+ if 'checked_batch' not in st.session_state:
564
+ st.session_state.checked_batch = False
565
+ if 'batch_left_checked' not in st.session_state:
566
+ st.session_state.batch_left_checked = False
567
+ if 'scores_calculated' not in st.session_state:
568
+ st.session_state.scores_calculated = False
569
+ if 'batch_optimized' not in st.session_state:
570
+ st.session_state.batch_optimized = False
571
+
572
+ with oab_upl_container.container():
573
+ st.session_state['smiles_file'] = st.file_uploader("Upload a text file with SMILES on each line :sparkles:",on_change=reset_oab_state)
574
+ if 'check_batch_butt' not in locals():
575
+ check_batch_butt = False
576
+
577
+ if st.session_state['smiles_file'] is not None:
578
+ if st.session_state.smiles_upload_change:
579
+ smiles_list = io.StringIO(st.session_state.smiles_file.getvalue().decode("utf-8"))
580
+ smiles_list = list(smiles_list.getvalue().rstrip().split('\n'))
581
+ st.markdown('Number of SMILES: '+str(len(smiles_list)))
582
+ if len(smiles_list) == 1:
583
+ st.markdown("<p style='text-align: center; color: red;'><b>Please use <i>Optimize a molecule</i> tab.</b></p>",unsafe_allow_html=True)
584
+ with sidebar_con.container():
585
+ set_step(0)
586
+ oab_sidebar(0)
587
+ else:
588
+ st.session_state['df'] = pd.DataFrame({'SMILES':smiles_list})
589
+ st.dataframe(st.session_state['df'],use_container_width=True)
590
+ check_batch_butt = st.button('Check SMILES')
591
+ else:
592
+ # if not st.session_state.checked_batch:
593
+ if st.session_state['smiles_file'] is not None:
594
+ st.dataframe(st.session_state['df'],use_container_width=True)
595
+ # st.button('Check SMILES',on_click=check_batch,args=[smiles_list],key='check_batch_butt')
596
+
597
+ if check_batch_butt:
598
+ if st.session_state.smiles_upload_change:
599
+ with sidebar_con.container():
600
+ set_step(1)
601
+ oab_sidebar(1)
602
+ check_batch(list(st.session_state['df'].SMILES))
603
+ st.session_state.smiles_upload_change = False
604
+
605
+ if 'calc_batch_butt' not in locals():
606
+ calc_batch_butt = False
607
+ check_batch_con = st.empty()
608
+ calc_batch_con = st.empty()
609
+ if st.session_state.checked_batch:
610
+ with check_batch_con.container():
611
+ passed_num = st.session_state['df'][st.session_state['df'].checked != 'invalid'].shape[0]
612
+ st.markdown('Number of passed SMILES: '+str(passed_num))
613
+ st.dataframe(st.session_state['df'],use_container_width=True)
614
+ if passed_num == 0:
615
+ st.markdown("<p style='text-align: center; color: red;'><b>The uploaded file contains no suitable SMILES string.</b></p>",unsafe_allow_html=True)
616
+ st.session_state.batch_left_checked = False
617
+ with sidebar_con.container():
618
+ set_step(0)
619
+ oab_sidebar(0)
620
+ else:
621
+ st.session_state.batch_left_checked = True
622
+ df = st.session_state['df']
623
+ download_df(df,0)
624
+ choose_score_con = st.empty()
625
+ if st.session_state.batch_left_checked:
626
+ with sidebar_con.container():
627
+ set_step(2)
628
+ oab_sidebar(2)
629
+ with choose_score_con.container():
630
+ with st.form("Choose score to calculate"):
631
+ st.markdown("<h4>Choose score(s) to calculate</h4>",unsafe_allow_html=True)
632
+ st.caption('Penalized LogP is always calculated.')
633
+ st.checkbox('LogP',key='logp_cal')
634
+ st.checkbox('SA score',key='sa_cal')
635
+ st.checkbox('Cycle score',key='cycle_cal')
636
+ calc_batch_butt = st.form_submit_button("Keep passed SMILES and calculate scores")
637
+ else:
638
+ choose_score_con.empty()
639
+ else:
640
+ check_batch_con.empty()
641
+
642
+ if 'optim_batch_butt' not in locals():
643
+ optim_batch_butt = False
644
+ # if 'calc_batch_butt' in st.session_state:
645
+ if calc_batch_butt and st.session_state.batch_left_checked:
646
+ # if not st.session_state.scores_calculated:
647
+ smiles_list = list(st.session_state['df'][st.session_state['df'].checked != 'invalid'].checked)
648
+ st.session_state.score_df = calc_scores(smiles_list)
649
+ st.session_state.batch_optimized = False
650
+ if st.session_state.scores_calculated:
651
+ calc_batch_con.empty()
652
+ with calc_batch_con.container():
653
+ st.dataframe(st.session_state.score_df,use_container_width=True)
654
+ score_df = st.session_state.score_df
655
+ download_df(score_df,1)
656
+ with sidebar_con.container():
657
+ set_step(3)
658
+ oab_sidebar(3)
659
+ with st.form(":gear: Settings"):
660
+ st.slider('Choose learning rate: ',0.0,5.0,0.4,key='lr_b')
661
+ st.slider('Choose similarity cutoff: ',0.0,1.0,0.4,key='sim_cutoff_b')
662
+ st.slider('Choose number of iterations: ',1,100,80,key='n_iter_b')
663
+ optim_batch_butt = st.form_submit_button("Optimize")
664
+ else:
665
+ calc_batch_con.empty()
666
+
667
+
668
+ optim_batch_con = st.empty()
669
+ ani_con = st.empty()
670
+ if optim_batch_butt and st.session_state.scores_calculated:
671
+ optim_batch_con.empty()
672
+ with sidebar_con.container():
673
+ set_step(4)
674
+ oab_sidebar(4)
675
+ with ani_con.container():
676
+ st.markdown('Operation in progress. Please wait...')
677
+ gen_results = []
678
+ render_animation()
679
+ st.markdown('Generating new SMILES string(s)...')
680
+ model = load_model()
681
+ for canon_smiles in stqdm(list(st.session_state.score_df.SMILES)):
682
+ gen_results.append(optim_single(canon_smiles,model,st.session_state.lr_b,st.session_state.sim_cutoff_b,st.session_state.n_iter_b))
683
+ st.markdown('Checking generated SMILES string(s) ...')
684
+ st.session_state.new_score_df = calc_scores_new(gen_results)
685
+ ani_con.empty()
686
+ if st.session_state.batch_optimized:
687
+ with sidebar_con.container():
688
+ set_step(5)
689
+ oab_sidebar(5)
690
+ with optim_batch_con.container():
691
+ new_score_df = st.session_state.new_score_df
692
+ # new_score_df.style.applymap(highlight_result, subset=pd.IndexSlice[:, ['new_smiles']])
693
+ st.markdown("<h3 style='text-align: center; color: mediumseagreen;'>RESULTS</h3>",unsafe_allow_html=True)
694
+ st.dataframe(new_score_df.style.applymap(highlight_result, subset=pd.IndexSlice[:, ['new_smiles']]),use_container_width=True)
695
+ download_df(new_score_df,3)
696
+ else:
697
+ optim_batch_con.empty()
698
+
699
+
700
+
701
+ def check_batch(smiles_list):
702
+ check = []
703
+ for smi in stqdm(smiles_list):
704
+ mol = Chem.MolFromSmiles(smi)
705
+ if (mol is not None) and (mol_passes_filters_custom(mol) == 'YES'):
706
+ check.append(Chem.MolToSmiles(mol))
707
+ else:
708
+ check.append('invalid')
709
+ st.session_state['df'] = pd.concat([st.session_state['df'],pd.DataFrame({'checked':check})],axis=1)
710
+ st.session_state.checked_batch = True
711
+ # return check
712
+
713
+ def calc_scores(smiles_list):
714
+ score_df = pd.concat([st.session_state.df[st.session_state.df.checked != 'invalid'].SMILES,pd.DataFrame({'Checked_SMILES':smiles_list})],axis=1)
715
+ scores =[]
716
+ for smi in stqdm(smiles_list):
717
+ logp,sa,cycle,pen_logp = penalized_logp_standard(Chem.MolFromSmiles(smi))
718
+ scores+=[(logp,sa,cycle,pen_logp)]
719
+ s_df = pd.DataFrame(scores,columns=st.session_state.sc_name)
720
+ for n, checked in zip(st.session_state.sc_name,[st.session_state.logp_cal,st.session_state.sa_cal,st.session_state.cycle_cal,True]):
721
+ if checked:
722
+ score_df = pd.concat([score_df,s_df[n]],axis=1)
723
+ st.session_state.scores_calculated = True
724
+ return score_df
725
+
726
+ def calc_scores_new(result):
727
+ new_scores =[]
728
+ for new_smiles,sim in stqdm(result):
729
+ if new_smiles is None:
730
+ new_scores+=[('invalid',-100.0,-100.0,-100.0,-100.0,-100.0)]
731
+ else:
732
+ new_mol = Chem.MolFromSmiles(new_smiles)
733
+ if new_mol is None:
734
+ new_scores+=[('invalid',-100.0,-100.0,-100.0,-100.0,-100.0)]
735
+ else:
736
+ logp,sa,cycle,pen_logp = penalized_logp_standard(new_mol)
737
+ new_scores+=[(new_smiles,sim,logp,sa,cycle,pen_logp)]
738
+ new_col = ['new_smiles','sim']+st.session_state.new_sc_name
739
+ s_df = pd.DataFrame(new_scores,columns=new_col)
740
+ new_score_df = st.session_state.score_df
741
+ for n, checked in zip(new_col,[True, True,st.session_state.logp_cal,st.session_state.sa_cal,st.session_state.cycle_cal,True]):
742
+ if checked:
743
+ new_score_df = pd.concat([new_score_df,s_df[n]],axis=1)
744
+ st.session_state.batch_optimized = True
745
+ return new_score_df
746
+
747
+ def highlight_result(value):
748
+ if value == 'invalid': color = 'tomato'
749
+ else: color = 'mediumseagreen'
750
+ return 'color: %s' % color
751
+
752
+ @st.cache_data(experimental_allow_widgets=True)
753
+ def download_df(df,id):
754
+ with st.expander(':arrow_down: Download this dataframe'):
755
+ st.markdown("<h4 style='color:tomato;'>Select column(s) to save:</h4>",unsafe_allow_html=True)
756
+ for col in df.columns:
757
+ st.checkbox(col,key=str(id)+'_col_'+str(col),value=True)
758
+ st.text_input('File name (.csv):','dataframe',key=str(id)+'_file_name')
759
+
760
+ ste.download_button('Download',df_to_file(df[[col for col in df.columns if st.session_state[str(id)+'_col_'+str(col)]]]),st.session_state[str(id)+'_file_name']+'.csv')
761
 
762
  def reset_oam_state():
763
  st.session_state.smiles_selected = False
764
  st.session_state.checked_single = 'NO'
765
  st.session_state.smiles_checked = False
766
+ st.session_state.single_optimized = False
767
  set_step(0)
768
 
769
+ def reset_oab_state():
770
+ st.session_state.smiles_upload_change = True
771
+ st.session_state.smiles_uploaded = False
772
+ st.session_state.checked_batch = False
773
+ st.session_state.batch_left_checked = False
774
+ st.session_state.scores_calculated = False
775
+ st.session_state.batch_optimized = False
776
+ set_step(0)
777
+
778
  def rerun():
779
  st.experimental_rerun()
780
  def render_view():
app_backup.py DELETED
@@ -1,437 +0,0 @@
1
- from pathlib import Path
2
- import torch
3
- from st_on_hover_tabs import on_hover_tabs
4
- import streamlit as st
5
- st.set_page_config(layout="wide")
6
-
7
- model_path = './model.iter-685000'
8
-
9
- import sys, os
10
- import rdkit
11
- import rdkit.Chem as Chem
12
- from rdkit.Chem.Draw import MolToImage
13
- from rdkit.Chem import Descriptors
14
- import sascorer
15
- import networkx as nx
16
- from stqdm import stqdm
17
- import base64, io
18
- import pandas as pd
19
- import streamlit_ext as ste
20
-
21
- os.environ['KMP_DUPLICATE_LIB_OK']='True'
22
-
23
- sys.path.append('%s/fast_jtnn/' % os.path.dirname(os.path.realpath(__file__)))
24
- from mol_tree import Vocab, MolTree
25
- from jtprop_vae import JTPropVAE
26
- from molbloom import buy
27
-
28
- css='''
29
- [data-testid="metric-container"] {
30
- width: fit-content;
31
- margin: auto;
32
- }
33
-
34
- [data-testid="metric-container"] > div {
35
- width: fit-content;
36
- margin: auto;
37
- }
38
-
39
- [data-testid="metric-container"] label {
40
- width: fit-content;
41
- margin: auto;
42
-
43
- [data-testid="stDataFrameResizable"] {
44
- width: fit-content;
45
- margin: auto;
46
- }
47
- }
48
- '''
49
-
50
- st.markdown(f'<style>{css}</style>',unsafe_allow_html=True)
51
-
52
- s_buff = io.StringIO()
53
- def img_to_bytes(img_path):
54
- img_bytes = Path(img_path).read_bytes()
55
- encoded = base64.b64encode(img_bytes).decode()
56
- return encoded
57
- def img_to_html(img_path):
58
- img_html = "<img src='data:image/png;base64,{}' class='img-fluid' style='max-width: 500px;'>".format(
59
- img_to_bytes(img_path)
60
- )
61
- return img_html
62
-
63
- _mcf = pd.read_csv('./mcf.csv')
64
- _pains = pd.read_csv('./wehi_pains.csv',
65
- names=['smarts', 'names'])
66
- _mcf_filters = [Chem.MolFromSmarts(x) for x in
67
- _mcf['smarts'].values]
68
- _pains_filters = [Chem.MolFromSmarts(x) for x in
69
- _pains['smarts'].values]
70
-
71
- def mol_passes_filters_custom(mol,
72
- allowed=None,
73
- isomericSmiles=False):
74
- """
75
- Checks if mol
76
- * passes MCF and PAINS filters,
77
- * has only allowed atoms
78
- * is not charged
79
- """
80
- allowed = allowed or {'C', 'N', 'S', 'O', 'F', 'Cl', 'Br', 'H'}
81
- if mol is None:
82
- return 'NoMol'
83
- ring_info = mol.GetRingInfo()
84
- if ring_info.NumRings() != 0 and any(
85
- len(x) >= 8 for x in ring_info.AtomRings()
86
- ):
87
- return 'ManyRings'
88
- h_mol = Chem.AddHs(mol)
89
- if any(atom.GetFormalCharge() != 0 for atom in mol.GetAtoms()):
90
- return 'Charged'
91
- if any(atom.GetSymbol() not in allowed for atom in mol.GetAtoms()):
92
- return 'AtomNotAllowed'
93
- if any(h_mol.HasSubstructMatch(smarts) for smarts in _mcf_filters):
94
- return 'MCF'
95
- if any(h_mol.HasSubstructMatch(smarts) for smarts in _pains_filters):
96
- return 'PAINS'
97
- smiles = Chem.MolToSmiles(mol, isomericSmiles=isomericSmiles)
98
- if smiles is None or len(smiles) == 0:
99
- return 'Isomeric'
100
- if Chem.MolFromSmiles(smiles) is None:
101
- return 'Isomeric'
102
- return 'YES'
103
-
104
- def penalized_logp_standard(mol):
105
-
106
- logP_mean = 2.4399606244103639873799239
107
- logP_std = 0.9293197802518905481505840
108
- SA_mean = -2.4485512208785431553792478
109
- SA_std = 0.4603110476923852334429910
110
- cycle_mean = -0.0307270378623088931402396
111
- cycle_std = 0.2163675785228087178335699
112
-
113
- log_p = Descriptors.MolLogP(mol)
114
- SA = -sascorer.calculateScore(mol)
115
-
116
- # cycle score
117
- cycle_list = nx.cycle_basis(nx.Graph(Chem.rdmolops.GetAdjacencyMatrix(mol)))
118
- if len(cycle_list) == 0:
119
- cycle_length = 0
120
- else:
121
- cycle_length = max([len(j) for j in cycle_list])
122
- if cycle_length <= 6:
123
- cycle_length = 0
124
- else:
125
- cycle_length = cycle_length - 6
126
- cycle_score = -cycle_length
127
- # print(logP_mean)
128
-
129
- standardized_log_p = (log_p - logP_mean) / logP_std
130
- standardized_SA = (SA - SA_mean) / SA_std
131
- standardized_cycle = (cycle_score - cycle_mean) / cycle_std
132
- return log_p,SA,cycle_score,standardized_log_p + standardized_SA + standardized_cycle
133
-
134
- lg = rdkit.RDLogger.logger()
135
- lg.setLevel(rdkit.RDLogger.CRITICAL)
136
-
137
- def About():
138
- descrip = '''
139
- We seek to automate the design of molecules based on specific chemical properties. In computational terms, this task involves continuous embedding and generation of molecular graphs. Our primary contribution is the direct realization of molecular graphs, a task previously approached by generating linear SMILES strings instead of graphs. Our junction tree variational autoencoder generates molecular graphs in two phases, by first generating a tree-structured scaffold over chemical substructures, and then combining them into a molecule with a graph message passing network. This approach allows us to incrementally expand molecules while maintaining chemical validity at every step. We evaluate our model on multiple tasks ranging from molecular generation to optimization. Across these tasks, our model outperforms previous state-of-the-art baselines by a significant margin.
140
-
141
- [https://arxiv.org/abs/1802.04364](https://arxiv.org/abs/1802.04364)'''
142
- st.markdown(descrip)
143
- st.markdown("<p style='text-align: center;'>"+
144
- img_to_html('about.png')+
145
- "</p>", unsafe_allow_html=True)
146
-
147
- def Optimize_a_molecule():
148
- st.markdown("<h2 style='text-align: center;'>Optimize a molecule</h2>",unsafe_allow_html=True)
149
- with st.expander(':snowman: :blue[Instruction]'):
150
- guide = """<h4 style='color:tomato;'>Steps to optimize a molucule</h4>
151
- 1. Select from examples, or manually enter a valid SMILES string of a molecule.</br>
152
- 2. Configure the settings to generate a new molecule. The new molecule should have a higher penalized LogP value.</br>
153
- - Learning rate: How 'far' from the molecule that you want to search.</br>
154
- - Similarity cutoff: How 'similar' to the molecule that you want to search.</br>
155
- - Number of iterations: Number of generation trials.</br>
156
- <h4 style='color:darkturquoise;'>Annotation</h4>
157
- <b>SMILES</b> - Simplified molecular-input line-entry system</br>
158
- <b>LogP</b> - The log of the partition coefficient of a solute between octanol and water, at near infinite dilution</br>
159
- <b>SA score</b> - Synthetic Accessibility Score (lower is better)</br>
160
- <b>Cycle score</b> - A number of carbon rings of size larger than 6 (lower is better)</br>
161
- <b>Penalized LogP</b> - Standardized score of <i>LogP - SA score - Cycle score</i></br>
162
- <b>Similarity</b> - Molecular similarity is calculated via Morgan fingerprint of radius 2 with Tanimoto similarity</br>
163
- """
164
- st.markdown(guide,unsafe_allow_html=True)
165
-
166
- st.selectbox("Select an example",options=['-','Sorafenib','Pazopanib','Sunitinib'],key='mode')
167
- if st.session_state.mode == '-':
168
- smiles = st.text_input('Enter a SMILES string (max 200 chars):',max_chars=200)
169
- elif st.session_state.mode == 'Sorafenib':
170
- smiles = 'CNC(=O)C1=NC=CC(=C1)OC2=CC=C(C=C2)NC(=O)NC3=CC(=C(C=C3)Cl)C(F)(F)F'
171
- elif st.session_state.mode == 'Pazopanib':
172
- smiles = 'CC1=C(C=C(C=C1)NC2=NC=CC(=N2)N(C)C3=CC4=NN(C(=C4C=C3)C)C)S(=O)(=O)N'
173
- elif st.session_state.mode == 'Sunitinib':
174
- smiles = 'CCN(CC)CCNC(=O)C1=C(NC(=C1C)C=C2C3=C(C=CC(=C3)F)NC2=O)C'
175
-
176
- if len(smiles) > 0:
177
- mol = Chem.MolFromSmiles(smiles)
178
- if mol is None:
179
- st.markdown("<p style='text-align: center; color: red;'><b>SMILES is invalid. Please enter a valid SMILES.</b></p>",unsafe_allow_html=True)
180
- else:
181
- canon_smiles = Chem.MolToSmiles(mol)
182
- st.markdown("<b>Canonicalized SMILES</b>",unsafe_allow_html=True)
183
- st.code(canon_smiles)
184
- logp,sa,cycle,pen_p = penalized_logp_standard(mol)
185
- moses_passed = mol_passes_filters_custom(mol)
186
- if moses_passed=='YES':
187
- st.markdown("<p style='text-align: center; color: mediumseagreen'>MOSES filters passed successfully.</p>",unsafe_allow_html=True)
188
- else:
189
- st.markdown("<p style='text-align: center; color: red;'><b>MOSES filters passed failed. Please use another molecule.</b></p>",unsafe_allow_html=True)
190
- # with st.columns(3)[1]:
191
- # st.markdown("<style>{text-align: center;}</style>",unsafe_allow_html=True)
192
- imgByteArr = io.BytesIO()
193
- MolToImage(mol,size=(400,400)).save(imgByteArr,format='PNG')
194
- st.markdown("<p style='text-align: center;'>"+
195
- f"<img src='data:image/png;base64,{base64.b64encode(imgByteArr.getvalue()).decode()}' class='img-fluid'>"+
196
- "</p>", unsafe_allow_html=True)
197
- # st.image(MolToImage(mol,size=(300,300)))
198
- col1, col2, col3, col4 = st.columns(4)
199
- col1.metric('LogP', '%.5f' % (logp))
200
- col2.metric('SA score', '%.5f' % (-sa))
201
- col3.metric('Cycle score', '%d' % (-cycle))
202
- col4.metric('Penalized LogP', '%.5f' % (pen_p))
203
-
204
- if (mol is not None) and (moses_passed=='YES'):
205
- # col1, col2, col3 = st.columns(3)
206
- with st.form(":gear:Settings"):
207
- st.slider('Choose learning rate: ',0.0,5.0,0.4,key='lr')
208
- st.slider('Choose similarity cutoff: ',0.0,1.0,0.4,key='sim_cutoff')
209
- st.slider('Choose number of iterations: ',1,100,80,key='n_iter')
210
- optim = st.form_submit_button("Optimize")
211
- vocab = [x.strip("\r\n ") for x in open('./vocab.txt')]
212
- vocab = Vocab(vocab)
213
- if optim:
214
- # st.write('Testing')
215
- # canon_smiles = Chem.MolToSmiles(mol)
216
-
217
- # with st.columns(3)[1]:
218
- with st.spinner("Operation in progress. Please wait."):
219
-
220
- model = JTPropVAE(vocab, 450, 56, 20, 3)
221
-
222
- model.load_state_dict(torch.load(model_path,map_location=torch.device('cpu')))
223
-
224
- new_smiles,sim = model.optimize(canon_smiles, sim_cutoff=st.session_state.sim_cutoff, lr=st.session_state.lr, num_iter=st.session_state.n_iter)
225
-
226
- del model
227
- if new_smiles is None:
228
- st.markdown("<h4 style='text-align: center; color: red;'>Cannot optimize! Please choose another setting.</h4>",unsafe_allow_html=True)
229
- else:
230
- st.markdown("<b style='text-align: center;'>New SMILES</b>",unsafe_allow_html=True)
231
- st.code(new_smiles)
232
- new_mol = Chem.MolFromSmiles(new_smiles)
233
- if new_mol is None:
234
- st.markdown("<p style='text-align: center; color: red;'>New SMILES is invalid! Please choose another setting.</p>",unsafe_allow_html=True)
235
- # st.write('New SMILES is invalid.')
236
- else:
237
- # st.write('New SMILES molecule:')
238
- imgByteArr = io.BytesIO()
239
- MolToImage(new_mol,size=(400,400)).save(imgByteArr,format='PNG')
240
- st.markdown("<p style='text-align: center;'>"+
241
- f"<img src='data:image/png;base64,{base64.b64encode(imgByteArr.getvalue()).decode()}' class='img-fluid'>"+
242
- "</p>", unsafe_allow_html=True)
243
-
244
- new_moses_passed = mol_passes_filters_custom(new_mol)
245
- if new_moses_passed=='YES':
246
- st.markdown("<p style='text-align: center; color: mediumseagreen'>MOSES filters passed successfully.</p>",unsafe_allow_html=True)
247
- else:
248
- st.markdown("<p style='text-align: center; color: red;'><b>MOSES filters passed failed.</b></p>",unsafe_allow_html=True)
249
- new_logp,new_sa,new_cycle,new_pen_p = penalized_logp_standard(new_mol)
250
- # st.write('New penalized logP score: %.5f' % (new_score))
251
- col12, col22, col32, col42 = st.columns(4)
252
- col12.metric('LogP', '%.5f' % (new_logp),'%.5f'%(new_logp-logp))
253
- col22.metric('SA score', '%.5f' % (-new_sa),'%.5f'%(-new_sa+sa),delta_color='inverse')
254
- col32.metric('Cycle score', '%d' % (-new_cycle),'%d'%(-new_cycle+cycle),delta_color='inverse')
255
- col42.metric('Penalized LogP', '%.5f' % (new_pen_p),'%.5f'%(new_pen_p-pen_p))
256
- # st.metric('New penalized logP score','%.5f' % (new_score), '%.5f'%(new_score-score))
257
- st.metric('Similarity','%.5f' % (sim))
258
- # st.write('Caching ZINC20 if necessary...')
259
- with st.spinner("Caching ZINC20 if necessary..."):
260
- if buy(new_smiles, catalog='zinc20',canonicalize=True):
261
- st.write('This molecule exists.')
262
- st.markdown("<h3 style='text-align: center; color: darkturquoise;'><b>This molecule exists.</h3>",unsafe_allow_html=True)
263
- else:
264
- # st.write('THIS MOLECULE DOES NOT EXIST!')
265
- st.markdown("<h3 style='text-align: center; color: mediumseagreen;'>THIS MOLECULE DOES NOT EXIST!</h3>",unsafe_allow_html=True)
266
- st.markdown("<p style='text-align: center; color: grey;'>Checked using molbloom</p>",unsafe_allow_html=True)
267
-
268
- def Optimize_a_batch():
269
- st.markdown("<h2 style='text-align: center;'>Optimize a batch</h2>",unsafe_allow_html=True)
270
- # st.text_input('Enter a SMILES string:','CNC(=O)C1=NC=CC(=C1)OC2=CC=C(C=C2)NC(=O)NC3=CC(=C(C=C3)Cl)C(F)(F)F',key='smiles')
271
- with st.expander(':snowman: :blue[Instruction]'):
272
- guide = """<h4 style='color:tomato;'>Steps to optimize a batch</h4>
273
- 1. Upload a text file with SMILES string on each line.</br>
274
- 2. Check the SMILES strings to make sure that they are valid and pass MOSES filters.</br>
275
- 3. Select scores to calculate (penalized LogP included). Keep passed SMILES and calculate selected scores.</br>
276
- 4. Configure the settings to generate new molecules. The new molecules should have higher penalized LogP values.</br>
277
- - Learning rate: How 'far' from each molecule that you want to search</br>
278
- - Similarity cutoff: How 'similar' to each molecule that you want to search</br>
279
- - Number of iterations: Number of generation trials per molecule</br>
280
- 5. <i>(Optional)</i> You can download the dataframe at any steps as *.csv file.</br>
281
- <h4 style='color:darkturquoise;'>Annotation</h4>
282
- <b>SMILES</b> - Simplified molecular-input line-entry system</br>
283
- <b>LogP</b> - The log of the partition coefficient of a solute between octanol and water, at near infinite dilution</br>
284
- <b>SA score</b> - Synthetic Accessibility Score (lower is better)</br>
285
- <b>Cycle score</b> - A number of carbon rings of size larger than 6 (lower is better)</br>
286
- <b>Penalized LogP</b> - Standardized score of <i>LogP - SA score - Cycle score</i></br>
287
- <b>Similarity</b> - Molecular similarity is calculated via Morgan fingerprint of radius 2 with Tanimoto similarity.</br>
288
- """
289
- st.markdown(guide,unsafe_allow_html=True)
290
- st.session_state['smiles_file'] = st.file_uploader("Upload a text file with SMILES on each line :sparkles:")
291
- if st.session_state.smiles_file is not None:
292
- # smiles_list = [str(line).rstrip('\n') for line in smiles_file]
293
- smiles_list = io.StringIO(st.session_state.smiles_file.getvalue().decode("utf-8"))
294
- smiles_list = list(smiles_list.getvalue().rstrip().split('\n'))
295
- st.markdown('Number of SMILES: '+str(len(smiles_list)))
296
- if len(smiles_list) == 1:
297
- st.markdown("<p style='text-align: center; color: red;'><b>Please use <i>Optimize a molecule</i> tab.</b></p>",unsafe_allow_html=True)
298
- else:
299
- def check_smiles():
300
- check = []
301
- for smi in stqdm(smiles_list):
302
- mol = Chem.MolFromSmiles(smi)
303
- if (mol is not None) and (mol_passes_filters_custom(mol) == 'YES'):
304
- check.append(Chem.MolToSmiles(mol))
305
- else:
306
- check.append('invalid')
307
- st.session_state['df'] = pd.concat([df,pd.DataFrame({'checked':check})],axis=1)
308
- df = pd.DataFrame({'SMILES':smiles_list})
309
- st.dataframe(df,use_container_width=True)
310
- st.button('Check SMILES',key='check',on_click=check_smiles)
311
-
312
- if 'df' in st.session_state:
313
- # st.markdown('Number of SMILES: '+str(len(st.session_state.smiles_list)))
314
- df = st.session_state['df']
315
- st.markdown('Number of passed SMILES: '+str(df[df.checked != 'invalid'].shape[0]))
316
- st.dataframe(df,use_container_width=True)
317
- download_df(df,0)
318
- with st.form("Choose score to calculate"):
319
- st.caption('Penalized LogP is always calculated.')
320
- logp_cal= st.checkbox('LogP',key='logp_cal')
321
- sa_cal= st.checkbox('SA score',key='sa_cal')
322
- cycle_cal= st.checkbox('Cycle score',key='cycle_cal')
323
- calc = st.form_submit_button("Keep passed SMILES and calculate scores")
324
- # st.session_state['pen_logp_cal'] = True
325
- if calc:
326
- smiles_list = list(df[df.checked != 'invalid'].SMILES)
327
- # st.write(smiles_list)
328
- score_df = pd.DataFrame({'SMILES':smiles_list})
329
- scores =[]
330
- # pen_logp_ls = logp_ls = sa_ls = cycle_ls =[]
331
- st.session_state.sc_name = ['logp','sa','cycle','pen_logp']
332
- for smi in stqdm(smiles_list):
333
- logp,sa,cycle,pen_logp = penalized_logp_standard(Chem.MolFromSmiles(smi))
334
- # st.write(f"{logp}\t{sa}\t{cycle}\t{pen_logp}")
335
- scores+=[(logp,sa,cycle,pen_logp)]
336
- s_df = pd.DataFrame(scores,columns=st.session_state.sc_name)
337
- # st.write(st.session_state.log_ls)
338
- # to_concat = [score_df] + [d for d,checked in zip(dfs,[logp_cal,sa_cal,cycle_cal]) if checked] + [pd.DataFrame({'pen_logp':pen_logp_ls})]
339
- for n, checked in zip(st.session_state.sc_name,[logp_cal,sa_cal,cycle_cal,True]):
340
- if checked:
341
- score_df = pd.concat([score_df,s_df[n]],axis=1)
342
- # score_df['pen_logp'] = st.session_state.pen_logp_ls
343
- st.session_state.score_df = score_df
344
- st.dataframe(score_df,use_container_width=True)
345
- download_df(score_df,1)
346
- def batch_generate(smiles_list,df):
347
- vocab = [x.strip("\r\n ") for x in open('./vocab.txt')]
348
- vocab = Vocab(vocab)
349
- container = st.empty()
350
- with container.container():
351
-
352
- st_lottie(get_ani_json(), height=200, width=300)
353
- st.markdown('Please wait...')
354
-
355
- model = JTPropVAE(vocab, 450, 56, 20, 3)
356
-
357
- model.load_state_dict(torch.load(model_path,map_location=torch.device('cpu')))
358
-
359
- new_scores =[]
360
- for canon_smiles in stqdm(smiles_list):
361
- new_smiles,sim = model.optimize(canon_smiles, sim_cutoff=st.session_state.sim_cutoff, lr=st.session_state.lr, num_iter=st.session_state.n_iter)
362
- if new_smiles is None:
363
- new_scores+=[('invalid',-100.0,-100.0,-100.0,-100.0,-100.0)]
364
- else:
365
- new_mol = Chem.MolFromSmiles(new_smiles)
366
- if new_mol is None:
367
- new_scores+=[('invalid',-100.0,-100.0,-100.0,-100.0,-100.0)]
368
- else:
369
- logp,sa,cycle,pen_logp = penalized_logp_standard(new_mol)
370
- new_scores+=[(new_smiles,sim,logp,sa,cycle,pen_logp)]
371
-
372
- del model
373
- with container.container():
374
- sc_name = ['new_'+n for n in st.session_state.sc_name]
375
- s_df = pd.DataFrame(new_scores,columns=['new_smiles','sim']+sc_name)
376
- new_score_df = df
377
- # st.write(st.session_state.log_ls)
378
- # to_concat = [score_df] + [d for d,checked in zip(dfs,[logp_cal,sa_cal,cycle_cal]) if checked] + [pd.DataFrame({'pen_logp':pen_logp_ls})]
379
- for n, checked in zip(['new_smiles','sim']+sc_name,[True, True,st.session_state.logp_cal,st.session_state.sa_cal,st.session_state.cycle_cal,True]):
380
- if checked:
381
- new_score_df = pd.concat([new_score_df,s_df[n]],axis=1)
382
- st.markdown("<h3 style='text-align: center; color: mediumseagreen;'>RESULTS</h3>",unsafe_allow_html=True)
383
- st.dataframe(new_score_df,use_container_width=True)
384
- download_df(new_score_df,2)
385
- with st.form(":gear: Settings",clear_on_submit=False):
386
- st.slider('Choose learning rate: ',0.0,5.0,0.4,key='lr')
387
- st.slider('Choose similarity cutoff: ',0.0,1.0,0.4,key='sim_cutoff')
388
- st.slider('Choose number of iterations: ',1,100,80,key='n_iter')
389
- optim = st.form_submit_button("Optimize",on_click=batch_generate,args=(smiles_list,score_df))
390
-
391
-
392
- from streamlit_lottie import st_lottie
393
- import requests
394
-
395
- def get_ani_json():
396
- animation_response = requests.get('https://assets1.lottiefiles.com/packages/lf20_vykpwt8b.json')
397
- animation_json = dict()
398
-
399
- if animation_response.status_code == 200:
400
- animation_json = animation_response.json()
401
- else:
402
- print("Error in the URL")
403
-
404
- return animation_json
405
-
406
- def download_df(df,id):
407
- with st.expander(':arrow_down: Download this dataframe'):
408
- st.markdown("<h4 style='color:tomato;'>Select column(s) to save:</h4>",unsafe_allow_html=True)
409
- for col in df.columns:
410
- st.checkbox(col,key=str(id)+'_col_'+str(col))
411
- st.text_input('File name (.csv):','dataframe',key=str(id)+'_file_name')
412
-
413
- ste.download_button('Download',df_to_file(df[[col for col in df.columns if st.session_state[str(id)+'_col_'+str(col)]]]),st.session_state[str(id)+'_file_name']+'.csv')
414
-
415
- def df_to_file(df):
416
- s_buff.seek(0)
417
- df.to_csv(s_buff)
418
- return s_buff.getvalue().encode()
419
-
420
- st.markdown("<h1 style='text-align: center;'>Junction Tree Variational Autoencoder for Molecular Graph Generation (JTVAE)</h1>",unsafe_allow_html=True)
421
- st.markdown("<h3 style='text-align: center;'>Wengong Jin, Regina Barzilay, Tommi Jaakkola</h3>",unsafe_allow_html=True)
422
- # st.markdown("<-- Use the sidebar to explore --")
423
- st.markdown("<h4 style='text-align: center;'>-- Use the sidebar to explore --</h4>",unsafe_allow_html=True)
424
- st.markdown('<style>' + open('./style.css').read() + '</style>', unsafe_allow_html=True)
425
-
426
- with st.sidebar:
427
- # st.header('+')
428
- st.markdown("<h5 style='text-align: center; color:grey;'>Explore</h5>",unsafe_allow_html=True)
429
- tabs = on_hover_tabs(tabName=['Optimize a molecule', 'Optimize a batch', 'About'],
430
- iconName=['science', 'batch_prediction', 'info'], default_choice=0)
431
-
432
- page_names_to_funcs = {
433
- "About": About,
434
- "Optimize a molecule":Optimize_a_molecule,
435
- "Optimize a batch":Optimize_a_batch
436
- }
437
- page_names_to_funcs[tabs]()