ligdis commited on
Commit
4faab6a
·
verified ·
1 Parent(s): 9aac639

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +437 -0
app.py ADDED
@@ -0,0 +1,437 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import sys
3
+ from fragment_embedder import FragmentEmbedder
4
+ from morgan_desc import *
5
+ from physchem_desc import *
6
+ from rdkit import Chem
7
+ import pandas as pd
8
+ import os
9
+ import random
10
+ import numpy as np
11
+ import joblib
12
+ from rdkit import Chem
13
+ from rdkit.Chem import Draw
14
+ from rdkit.Chem import Draw
15
+ from rdkit.Chem import AllChem
16
+ from rdkit import DataStructs
17
+ from rdkit.Chem import Descriptors
18
+ from scipy import stats
19
+ import textwrap
20
+ from datasets import load_dataset
21
+ import requests
22
+ from io import BytesIO
23
+ import urllib.request
24
+
25
+ import warnings
26
+ warnings.filterwarnings('ignore')
27
+
28
+ st.set_page_config(
29
+ page_title="Fragment predictor app",
30
+ layout="wide",
31
+ initial_sidebar_state="expanded",
32
+ page_icon=None,
33
+ )
34
+
35
+ dataset = load_dataset('ligdis/data', data_files={"predictions.csv"})
36
+ df_predictions = dataset['train'].to_pandas()
37
+
38
+ predictions_inchikeys = df_predictions["inchikey"].tolist()
39
+ df_predictions = df_predictions.rename(columns={"inchikey": "InChIKey"})
40
+
41
+ dataset = load_dataset('ligdis/data', data_files={"applicability.csv"})
42
+ df_applicability = dataset['train'].to_pandas()
43
+
44
+ df_predictions = pd.concat([df_predictions, df_applicability], axis=1)
45
+
46
+ dataset = load_dataset('ligdis/data', data_files={"cemm_smiles.csv"})
47
+ cemm_smiles = dataset['train'].to_pandas()
48
+
49
+ fid2smi = {}
50
+ for r in cemm_smiles.values:
51
+ fid2smi[r[0]] = r[1]
52
+
53
+ fe = FragmentEmbedder()
54
+
55
+ CRF_PATTERN = "CC1(CCC#C)N=N1"
56
+ CRF_PATTERN_0 = "C#CC"
57
+ CRF_PATTERN_1 = "N=N"
58
+
59
+ dataset = load_dataset('ligdis/data', data_files={"all_fff_enamine.csv"})
60
+ enamine_catalog = dataset['train'].to_pandas()
61
+ enamine_catalog_ids_set = set(enamine_catalog["catalog_id"])
62
+ enamine_catalog_dict = {}
63
+ catalog2inchikey = {}
64
+ smiles2catalog = {}
65
+ for i, r in enumerate(enamine_catalog.values):
66
+ enamine_catalog_dict[r[0]] = r[1]
67
+ catalog2inchikey[r[0]] = predictions_inchikeys[i]
68
+ smiles2catalog[r[1]] = r[0]
69
+
70
+
71
+ def is_enamine_catalog_id(identifier):
72
+ if identifier in enamine_catalog_ids_set:
73
+ return True
74
+ else:
75
+ return False
76
+
77
+
78
+ def is_enamine_smiles(identifier):
79
+ if identifier in smiles2catalog:
80
+ return True
81
+ else:
82
+ return False
83
+
84
+
85
+ def is_ligand_discovery_id(identifier):
86
+ if identifier in fid2smi:
87
+ return True
88
+ else:
89
+ return False
90
+
91
+
92
+ def is_valid_smiles(smiles):
93
+ try:
94
+ mol = Chem.MolFromSmiles(smiles)
95
+ except:
96
+ mol = None
97
+ if mol is None:
98
+ return False
99
+ else:
100
+ return True
101
+
102
+
103
+ def has_crf(mol):
104
+ pattern = CRF_PATTERN
105
+ has_pattern = mol.HasSubstructMatch(Chem.MolFromSmarts(pattern))
106
+ if not has_pattern:
107
+ if mol.HasSubstructMatch(
108
+ Chem.MolFromSmarts(CRF_PATTERN_0)
109
+ ) and mol.HasSubstructMatch(Chem.MolFromSmarts(CRF_PATTERN_1)):
110
+ return True
111
+ else:
112
+ return False
113
+ return True
114
+
115
+
116
+ st.title("Fully-functionalized fragment predictions")
117
+
118
+ dataset = load_dataset('ligdis/data', data_files={"model_catalog.csv"})
119
+ dm = dataset['train'].to_pandas()
120
+ all_models = dm["model_name"].tolist()
121
+
122
+ dataset = load_dataset('ligdis/data', data_files={"models_performance.tsv"})
123
+ dp = dataset['train'].to_pandas()
124
+
125
+ model_display = {}
126
+ model_description = {}
127
+ for r in dm.values:
128
+ model_display[r[0]] = r[1]
129
+ model_description[r[0]] = r[2]
130
+ model_auroc = {}
131
+ for r in dp.values:
132
+ model_auroc[r[0]] = r[1]
133
+
134
+ prom_models = [x for x in dm["model_name"].tolist() if x.startswith("promiscuity")]
135
+ sign_models = [x for x in dm["model_name"].tolist() if x.startswith("signature")]
136
+
137
+ def model_to_markdown(model_names):
138
+ items = []
139
+ for mn in model_names:
140
+ items += [
141
+ "{0} ({1:.3f}): {2}".format(
142
+ model_display[mn].ljust(8), model_auroc[mn], model_description[mn]
143
+ )
144
+ ]
145
+ markdown_list = "\n".join(items)
146
+ return markdown_list
147
+
148
+ st.sidebar.title("Promiscuity models")
149
+
150
+ st.sidebar.markdown("**Global models**")
151
+
152
+ global_promiscuity_models = ["promiscuity_pxf0", "promiscuity_pxf1", "promiscuity_pxf2"]
153
+ st.sidebar.text(model_to_markdown(global_promiscuity_models))
154
+
155
+ st.sidebar.markdown("**Specific models**")
156
+
157
+ specific_promiscuity_models = [
158
+ "promiscuity_fxp0_pxf0",
159
+ "promiscuity_fxp1_pxf0",
160
+ "promiscuity_fxp2_pxf0",
161
+ "promiscuity_fxp0_pxf1",
162
+ "promiscuity_fxp1_pxf1",
163
+ "promiscuity_fxp2_pxf1",
164
+ "promiscuity_fxp0_pxf2",
165
+ "promiscuity_fxp1_pxf2",
166
+ "promiscuity_fxp2_pxf2",
167
+ ]
168
+ st.sidebar.text(model_to_markdown(specific_promiscuity_models))
169
+
170
+ st.sidebar.markdown("**Aggregated score**")
171
+ st.sidebar.text("Sum : Sum of individual promiscuity predictors.")
172
+
173
+ st.sidebar.title("Signature models")
174
+ signature_models = ["signature_{0}".format(i) for i in range(10)]
175
+ st.sidebar.text(model_to_markdown(signature_models))
176
+
177
+ st.sidebar.title("Chemical space")
178
+ s = ["MW : Molecular weight.",
179
+ "LogP : Walden-Crippen LogP.",
180
+ "Sim-1 : Tanimoto similarity to the most ",
181
+ " similar fragment in the training set.",
182
+ "Sim-3 : Tanimoto similarity to the third ",
183
+ " most similar fragment in the training set."]
184
+
185
+ st.sidebar.text("\n".join(s))
186
+
187
+ s = textwrap.wrap("* The score in parenthesis corresponds to the mean AUROC in 10 train-test splits.")
188
+ st.sidebar.text("\n".join(s))
189
+
190
+ st.sidebar.markdown("**In the main page...**")
191
+ s = textwrap.wrap("1. Percentages in parenthesis denote the percentile of the score across the Enamine collection of FFFs (>250k compounds)", width=60)
192
+ st.sidebar.text("\n".join(s))
193
+ s = textwrap.wrap("2. The exclamation sign (!) indicates that the corresponding model has an AUROC accuracy below 0.7.", width=60)
194
+ st.sidebar.text("\n".join(s))
195
+
196
+ placeholder_text = []
197
+ keys = random.sample(sorted(enamine_catalog_ids_set), 5)
198
+ for k in keys:
199
+ placeholder_text += [random.choice([k, enamine_catalog_dict[k]])]
200
+ placeholder_text = "\n".join(placeholder_text)
201
+
202
+ text_input = st.text_area(label="Input your fully functionalized fragments:")
203
+ inputs = [x.strip(" ") for x in text_input.split("\n")]
204
+ inputs = [x for x in inputs if x != ""]
205
+ if len(inputs) > 999:
206
+ st.error("Please limit the number of input fragments to 999.")
207
+
208
+ R = []
209
+ all_inputs_are_valid = True
210
+ for i, inp in enumerate(inputs):
211
+ input_id = "input-{0}".format(str(i).zfill(3))
212
+ if is_enamine_catalog_id(inp):
213
+ smiles = enamine_catalog_dict[inp]
214
+ inchikey = catalog2inchikey[inp]
215
+ r = [inp, smiles, inchikey]
216
+ elif is_ligand_discovery_id(inp):
217
+ smiles = fid2smi[inp]
218
+ inchikey = Chem.MolToInchiKey(Chem.MolFromSmiles(smiles))
219
+ r = [inp, smiles, inchikey]
220
+ elif is_enamine_smiles(inp):
221
+ smiles = inp
222
+ inp = smiles2catalog[smiles]
223
+ inchikey = catalog2inchikey[inp]
224
+ r = [inp, smiles, inchikey]
225
+ elif is_valid_smiles(inp):
226
+ mol = Chem.MolFromSmiles(inp)
227
+ if has_crf(mol):
228
+ inchikey = Chem.rdinchi.InchiToInchiKey(Chem.MolToInchi(mol))
229
+ r = [inchikey, inp, inchikey]
230
+ else:
231
+ st.error(
232
+ "Input SMILES {0} does not have the CRF. The CRF pattern is {1}.".format(
233
+ inp, CRF_PATTERN
234
+ )
235
+ )
236
+ all_inputs_are_valid = False
237
+ else:
238
+ st.error(
239
+ "Input {0} is not valid. Please enter a valid fully-functionalized fragment SMILES string or an Enamine catalog identifier of a fully-functionalized fragment".format(
240
+ inp
241
+ )
242
+ )
243
+ all_inputs_are_valid = False
244
+ R += [r]
245
+
246
+
247
+ def get_fragment_image(smiles):
248
+ m = Chem.MolFromSmiles(smiles)
249
+ AllChem.Compute2DCoords(m)
250
+ im = Draw.MolToImage(m, size=(200, 200))
251
+ return im
252
+
253
+ if all_inputs_are_valid and len(R) > 0:
254
+ sum_of_promiscuities = np.sum(
255
+ df_predictions[global_promiscuity_models + specific_promiscuity_models], axis=1
256
+ )
257
+ df = pd.DataFrame(R, columns=["Identifier", "SMILES", "InChIKey"])
258
+
259
+ my_inchikeys = df["InChIKey"].tolist()
260
+
261
+ df_done = df[df["InChIKey"].isin(predictions_inchikeys)]
262
+ df_todo = df[~df["InChIKey"].isin(predictions_inchikeys)]
263
+
264
+ if df_done.shape[0] > 0:
265
+ df_done = df_done.merge(
266
+ df_predictions, on="InChIKey", how="left"
267
+ ).drop_duplicates()
268
+
269
+ if df_todo.shape[0] > 0:
270
+ X = fe.transform(df_todo["SMILES"].tolist())
271
+
272
+ st.info("Making predictions... this make take a few seconds. Please be patient. We may experience high traffic. If something goes wrong, please try again later.")
273
+
274
+ progress_bar = st.progress(0)
275
+
276
+ for i, model_name in enumerate(all_models):
277
+ url = ''.join(('https://huggingface.co/ligdis/fpred/resolve/main/', model_name, '.joblib')) # The URL of the file you want to load
278
+ with urllib.request.urlopen(url) as response: # Download the file
279
+ model = joblib.load(BytesIO(response.read()))
280
+ vals = model.predict(X)
281
+ del model
282
+ progress_bar.progress((i + 1) / len(all_models))
283
+ df_todo[model_name] = vals
284
+
285
+ url = 'https://huggingface.co/ligdis/fpred/resolve/main/cemm_ecfp_2_1024.joblib' # The URL of the file you want to load
286
+ with urllib.request.urlopen(url) as response: # Download the file
287
+ dataset_fps = joblib.load(BytesIO(response.read()))
288
+
289
+ all_query_smiles = df_todo["SMILES"].tolist()
290
+
291
+ sims_1 = []
292
+ sims_3 = []
293
+ logps = []
294
+ mwts = []
295
+ for query_smiles in all_query_smiles:
296
+ query_mol = Chem.MolFromSmiles(query_smiles)
297
+ query_fp = AllChem.GetMorganFingerprintAsBitVect(query_mol, 2, nBits=1024)
298
+ similarity_scores = [
299
+ DataStructs.TanimotoSimilarity(query_fp, dataset_fp)
300
+ for dataset_fp in dataset_fps
301
+ ]
302
+ sorted_scores_indices = sorted(
303
+ enumerate(similarity_scores), key=lambda x: x[1], reverse=True
304
+ )
305
+ top_n = 3
306
+ sims_1 += [sorted_scores_indices[0][1]]
307
+ sims_3 += [sorted_scores_indices[2][1]]
308
+ logps += [Descriptors.MolLogP(query_mol)]
309
+ mwts += [Descriptors.MolWt(query_mol)]
310
+ results = {"sims-1": sims_1, "sims-3": sims_3, "logp": logps, "mw": mwts}
311
+ for k in ["sims-1", "sims-3", "logp", "mw"]:
312
+ df_todo[k] = results[k]
313
+
314
+ if df_done.shape[0] > 0 and df_todo.shape[0] > 0:
315
+ df_ = pd.concat([df_done, df_todo])
316
+ else:
317
+ if df_done.shape[0] > 0:
318
+ df_ = df_done
319
+ else:
320
+ df_ = df_todo
321
+ df_ = df_.drop(columns=["Identifier", "SMILES"])
322
+ df = df.merge(df_, on="InChIKey", how="left")
323
+ df.drop_duplicates(subset=['InChIKey'], keep='first', inplace=True, ignore_index=True)
324
+ df = df.rename(columns=model_display)
325
+ applicability_display = {
326
+ "mw": "MW",
327
+ "logp": "LogP",
328
+ "sims-1": "Sim-1",
329
+ "sims-3": "Sim-3",
330
+ }
331
+ df = df.rename(columns=applicability_display)
332
+
333
+ df_predictions = df_predictions.rename(columns=model_display)
334
+ df_predictions = df_predictions.rename(columns=applicability_display)
335
+
336
+ prom_columns = []
337
+ for i in range(3):
338
+ prom_columns += ["Prom-{0}".format(i)]
339
+ for j in range(3):
340
+ prom_columns += ["Prom-{0}-{0}".format(i, j)]
341
+
342
+ def identifiers_text(ik, smi, ident):
343
+ s = ["{0}".format(ik), "{0}".format(smi)]
344
+ if ik != ident:
345
+ s += ["{0}".format(ident)]
346
+ return "\n".join(s)
347
+
348
+ def score_text(v, c):
349
+ all_scores = np.array(df_predictions[c])
350
+ perc = stats.percentileofscore(all_scores, v)
351
+ t = "{0}: {1:.2f} ({2:.1f}%)".format(c.ljust(8), v, perc).ljust(22)
352
+ if c == "Sign-4" or c == "Sign-7" or c == "Sign-3":
353
+ t += " (!)"
354
+ return t
355
+
356
+ def score_texts(vs, cs):
357
+ all_texts = []
358
+ for v, c in zip(vs, cs):
359
+ all_texts += [score_text(v, c)]
360
+ return "\n".join(all_texts)
361
+
362
+ dorig = pd.DataFrame({"InChIKey": my_inchikeys})
363
+ df = dorig.merge(df, on="InChIKey", how="left")
364
+ df = df.reset_index(inplace=False, drop=True)
365
+ for i, r in enumerate(df.iterrows()):
366
+ v = r[1]
367
+ st.markdown("#### Input {0}: `{1}`".format(i+1, inputs[r[0]]))
368
+ cols = st.columns(4)
369
+ cols[0].markdown("**Fragment**")
370
+ cols[0].image(get_fragment_image(v["SMILES"]))
371
+ cols[0].text(identifiers_text(v["InChIKey"], v["SMILES"], v["Identifier"]))
372
+
373
+ cols[1].markdown("**Chemical space**")
374
+ my_cols = ["MW", "LogP", "Sim-1", "Sim-3"]
375
+ cols[1].text(score_texts(v[my_cols], my_cols))
376
+
377
+ cols[2].markdown("**Promiscuity**")
378
+ sum_prom = np.sum(v[prom_columns])
379
+ perc_prom = stats.percentileofscore(sum_of_promiscuities, sum_prom)
380
+ cols[2].text("Sum : {0:.2f} ({1:.1f}%)".format(sum_prom, perc_prom))
381
+ my_cols = ["Prom-0", "Prom-1", "Prom-2"]
382
+ cols[2].text(score_texts(v[my_cols], my_cols))
383
+
384
+ my_cols = [
385
+ "Prom-0-0",
386
+ "Prom-0-1",
387
+ "Prom-0-2",
388
+ "Prom-1-0",
389
+ "Prom-1-1",
390
+ "Prom-1-2",
391
+ "Prom-2-0",
392
+ "Prom-2-1",
393
+ "Prom-2-2",
394
+ ]
395
+ cols[2].text(score_texts(v[my_cols], my_cols))
396
+
397
+ cols[3].markdown("**Signatures**")
398
+ my_cols = ["Sign-{0}".format(i) for i in range(10)]
399
+ cols[3].text(score_texts(v[my_cols], my_cols))
400
+
401
+ def convert_df(df):
402
+ return df.to_csv(index=False).encode("utf-8")
403
+
404
+ csv = convert_df(df)
405
+
406
+ st.download_button(
407
+ "Download as CSV", csv, "predictions.csv", "text/csv", key="download-csv"
408
+ )
409
+
410
+ else:
411
+ st.info(
412
+ "This tool expects fully functionalized fragments (FFF) as input, including the diazirine+alkyne probe (CRF). We have tailored the chemical space of the predictions to FFFs; the app will through an error if any of the input molecules does not contain a CRF region. Enamine provides a good [catalog](https://enamine.net/compound-libraries/fragment-libraries/fully-functionalized-probe-library) of FFFs. For a quick test input, use any of the options below."
413
+ )
414
+
415
+ example_0 = ["Z5645472552", "Z5645472643", "Z5645472785"]
416
+ st.markdown("**Input Enamine FFF identifiers...**")
417
+ st.text("\n".join(example_0))
418
+
419
+ example_1 = [
420
+ "C#CCCC1(CCCNC(=O)C(Cc2c[nH]c3ncccc23)NC(=O)OC(C)(C)C)N=N1",
421
+ "C#CCCC1(CCCNC(=O)[C@H]2CCC(=O)NC2)N=N1",
422
+ "C#CCCC1(CCCNC(=O)CSc2ncc(C(=O)OCC)c(N)n2)N=N1",
423
+ ]
424
+ st.markdown("**Input FFF SMILES strings...**")
425
+ st.text("\n".join(example_1))
426
+
427
+ example_2 = ["C310", "C045", "C391"]
428
+ st.markdown("**Input Ligand Discovery identifiers...**")
429
+ st.text("\n".join(example_2))
430
+
431
+ example_3 = [
432
+ "Z5645486561",
433
+ "C#CCCCC1(CCCC(=O)N2CCC(C(C(=O)O)c3ccc(C)cc3)CC2)N=N1",
434
+ "C279",
435
+ ]
436
+ st.markdown("**Input a mix of the above identifiers**")
437
+ st.text("\n".join(example_3))