rev: tip chemfp_examples/chembl_search_streamlit.py -rw-r--r-- 12.3 KiB View raw Log this file
871d0037866bAndrew Dalke added description of how the cli output SDF is generated 2 months ago
                                                                                
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
# This is an example of using chemfp with Streamlit 
#
# Given a ChEMBL id or name, or a SMILES string, do a k-nearest
# neighbor search of the ChEMBL fingerprints.
#
# Put the results in a Pandas table, and use RDKit to depict the
# structures.
#
# This requires:
#   - RDKit, streamlit, and Pandas
#   - the ChEMBL 28 fingerprints as 'chembl_28.fpb'
#   - the ChEMBL 28 SQLite3 database as 'chembl_28.db'
#
# For details about getting chembl_28.fpb and chembl_28.db, see:
#    http:///
#
# If the two data files are in the local directory then
# start streamlit with:
#
#    streamlit run chembl_search_streamlit.py
#
# You may configure the fingerprint and sqlite filenames with:
#
#    streamlit run chembl_search_streamlit.py -- --fingerprints /some/path.fpb --sqlite /some/path.db
#
# By default, streamlit will start a server and point your browser
# to it, for example, to:
# 
#    http://127.0.0.1:8501


import os
import time
import argparse
import sqlite3
import random
import csv
import base64

import streamlit as st # This program requires the 'streamlit' package
import pandas as pd # This program requires the 'pandas' package
import rdkit # This program requires RDKit; see http://rdkit.org/
from rdkit.Chem import PandasTools

import chemfp # This program requires chemfp; see http://chemfp.com/download/


# Return the compound report URL for a given ChEMBL id
def get_chembl_url(chembl_id):
    return f"https://www.ebi.ac.uk/chembl/compound_report_card/{chembl_id}/"

# Helper function to report an error message and exit.
def die(msg):
    error_line, _, info = msg.partition("\n")
    st.error(error_line)
    info = info.strip()
    if info:
        st.info(info.replace("\n", "\n\n"))
    st.stop()

def get_filename(filename, default_filenames, errmsg):
    if filename is not None:
        return filename
    for filename in default_filenames:
        if os.path.exists(filename):
            return filename
    die(errmsg)

    
parser = argparse.ArgumentParser(
    description = "Example program using streamlit for a ChEMBL fingerprint similarity search using chemfp.",
    )
parser.add_argument(
    "-f", "--fingerprints", metavar = "FILENAME",
    help = "Location of the FPB file containing ChEMBL fingerprint.",
    )
parser.add_argument(
    "-s", "--sqlite", metavar = "FILENAME",
    help = "Location of 'chembl_28.db' SQLite3 file from the ChEMBL distribution.",
    )
parser.add_argument("--no-mmap", action="store_true")

args = parser.parse_args()

fp_filename = get_filename(
    args.fingerprints,
    ["chembl_28.fpb"],
    "Could not find the ChEMBL fingerprints.\n"
    "--fingerprints not specified and FPB file not found in the current directory.\n"
    "Download it from https://chemfp.com/datasets/chembl_28.fpb.gz .\n"
    "See https://hg.sr.ht/~dalke/chemfp_examples/ for setup details.")

sqlite_filename = get_filename(
    args.sqlite,
    ["chembl_28.db"],
    "Could not find the ChEMBL SQLite database.\n"
    "--sqlite not specified and 'chembl_28.db' not found in the current directory.\n"
    "See https://hg.sr.ht/~dalke/chemfp_examples/ for setup details.")

# Streamlit re-runs the program after each change.
#
# While chemfp support compressed FPB files, it takes several seconds
# to decompress and load the file each time, which is too slow for
# reasonable interactive use.
#
# It's far better to use uncompressed FPB files.
#
# This load step cannot be cached for several reasons:
#
#  1) chemfp uses relative imports inside of functions, which streamlit
#    does not support. (https://github.com/streamlit/streamlit/issues/2790 )
# 
#  2) chemfp by default uses a memory-mapped file to read uncompressed
#    FPB files. Streamlit's cache uses Python's pickle, and Python's
#    mmap object cannot by pickled.
# 
#  3) If allow_mmap=False then it can be pickled, but the pickle requires
#    over 2GB, which is far larger than what Streamlit's cache allows,
#    and in any case, pickling/unpickling is far slower than re-opening
#    the memory-mapped file.
#
t1 = time.time()
try:
    arena = chemfp.load_fingerprints(fp_filename, allow_mmap = not args.no_mmap) # Looking for chemfp_28.fpb
except OSError as err:
    die(f"Cannot open ChEMBL fingerprint file: {err}.\nUse --fingerprints to specify an alternate location.")
except ValueError as err:
    die(f"Unable to open fingerprint file: {err}")
    
load_time = time.time() - t1

fptype = arena.get_fingerprint_type()

# Connect to the SQLite database.
if not os.path.exists(sqlite_filename):
    die(f"No ChEMBL SQLite file found at {sqlite_filename!r}.\nUse --sqlite to specify an alternate location.")
db = sqlite3.connect(sqlite_filename)
cursor = db.cursor()
version_name, version_comments = cursor.execute("SELECT name, comments FROM version").fetchone()

# Helper function to figure out what the query was and turn it into a SMILES.
def get_query_smiles(cursor, query):
    if query is None:
        return ("default query", "Cn1cnc2c1c(=O)[nH]c(=O)n2C", None)
    
    if query.startswith("CHEMBL"):
        cursor.execute("SELECT entity_type, entity_id FROM chembl_id_lookup WHERE chembl_id = ?",
                        (query,))
        row = cursor.fetchone()
        if row is None:
            return (None, None, "ChEMBL id not found")
        
        entity_type, entity_id = row
        if entity_type != "COMPOUND":
            return (None, None, f"ChEMBL id entity type is '{entity_type}', expecting 'COMPOUND'")

        molregno = entity_id
        cursor.execute("SELECT canonical_smiles FROM compound_structures WHERE molregno = ?",
                        (molregno,))
        row = cursor.fetchone()
        if row is None:
            return (None, None, "No canonical SMILES available for molregno {molregno}")
        return ("ChEMBL id", row[0], None)

    # See if it's a compound name
    cursor.execute("""
SELECT canonical_smiles FROM compound_structures, compound_records
                       WHERE compound_structures.molregno = compound_records.molregno
                         AND compound_name = ?
                     LIMIT 1""", (query,))
    row = cursor.fetchone()
    if row is not None:
        return ("ChEMBL title", row[0], None)

    # Treat it as a SMILES
    return ("query SMILES", query, None)

# Helper function to get a name and the SMILES for an id.
def get_name_and_smiles_for_id(cursor, chembl_id):
    cursor.execute("""
SELECT molecule_dictionary.pref_name, compound_records.compound_name, compound_structures.canonical_smiles
         FROM molecule_dictionary, chembl_id_lookup, compound_structures, compound_records
        WHERE chembl_id_lookup.chembl_id = ?
          AND chembl_id_lookup.entity_id = compound_structures.molregno
          AND chembl_id_lookup.entity_id = compound_structures.molregno
          AND chembl_id_lookup.entity_id = molecule_dictionary.molregno
      LIMIT 1""", (chembl_id,))
    row = cursor.fetchone()
    if row is None:
        return None, None
    pref_name, compound_name, smiles = row
    
    # If there is a preferred name, use it, otherwise use
    # one of the names in the compound records.
    if pref_name is None:
        return compound_name, smiles
    return pref_name, smiles


#### End of setup. Start working with streamlit.

st.title("ChEMBL similarity search with Streamlit, chemfp, RDKit, and Pandas.")

# Set the query entry widget
query = st.sidebar.text_input(
    "ChEMBL id, name or SMILES",
    value = "CHEMBL1114",
    )

# Let the user choose a random id instead.
if st.sidebar.button("Choose a random id"):
    query = random.choice(arena.ids)


# Choose the number of neighbors to find and minimum threshold.
    
k = st.sidebar.selectbox(
    "k", [1, 5, 10, 25, 50, 100, 250, 500, 1000],
    index = 2)

threshold = st.sidebar.slider(
    "minimum similarity",
    value = 0.4,
    min_value = 0.0, max_value = 1.0,
    step = 0.01)

#### The main section

## Do the k-nearest search

query_placeholder = st.empty()

with query_placeholder:
    st.write(f"Query: {query!r}.")

# Do we already know about the fingerprint?
query_fp = arena.get_fingerprint_by_id(query)
if query_fp is None:
    # What is it?
    query_type, query_smiles, query_errmsg = get_query_smiles(cursor, query)

    if query_errmsg is not None:
        st.warning(f"Unable to use {query!r}: {query_errmsg}")
        st.stop()

    # Can we turn it into a fingerprint?
    query_fp = fptype.parse_molecule_fingerprint(query_smiles, "smistring", errors="ignore")
    if query_fp is None:
        if query_type == "query SMILES":
            st.warning(f"Unable to use {query!r}: cannot process it as a SMILES")
        else:
            st.warning(f"Unable to use {query!r}: cannot process the SMILES {query_smiles!r}")
        st.stop()
else:
    query_type = "fingerprint id"

query_placeholder.empty()
with query_placeholder:
    st.write(f"Query: {query!r}, interpreted as a {query_type}.")

st.write(f"Similarity search for the k = {k} nearest neighbors with a minimum similarity of {threshold}.")
        
# This timing measurement includes the time needed to load the
# fingerprints from mass storage into memory, which can vary
# based on how much space is available for your file system cache.
#
# You can use --no-mmap so all the data is loaded in
# load_fingerprints(), but that will likely reduce the overall
# performance because the k-nearest search might not need to search
# all of the data.

start_time = time.time()
hits = arena.knearest_tanimoto_search_fp(query_fp, k=k, threshold=threshold)
search_time = time.time() - start_time

if args.no_mmap:
    st.write(f"Fingerprint load time: {1000 * load_time:.1f} milliseconds, "
                 f"search time: {1000 * search_time:.1f} milliseconds.")
else:
    st.write(f"Fingerprint load and search time: {1000 * search_time:.1f} milliseconds.")

#### Report the results

st.write(f"Number of hits: {len(hits)}")

chembl_ids = hits.get_ids()

if chembl_ids:
    info_list = [get_name_and_smiles_for_id(cursor, id) for id in chembl_ids]

    # Converts [(name1, smiles1), (name2, smiles2), ... ]
    # into [(name1, name2, ...), (smiles1, smiles2, ...)]
    name_list, smiles_list = list(zip(*info_list))
else:
    name_list = []
    smiles_list = []

results_df = pd.DataFrame({
    "id": chembl_ids,
    "score": hits.get_scores(),
    "name": name_list,
    "smiles": smiles_list,
})
PandasTools.AddMoleculeColumnToFrame(results_df, "smiles", "molecule")

# Change the ordering of the columns
results_df = results_df[["id", "score", "molecule", "name", "smiles"]]

### Export to SMILES and CSV

smi_content = results_df.to_csv(
    sep = "\t",
    columns = ["smiles", "id"],
    header = False,
    index = False,
    quoting = csv.QUOTE_NONE,
    ).encode("utf8")
encoded_smi_content = base64.urlsafe_b64encode(smi_content).decode("ascii")

csv_content = results_df.to_csv(
    columns = ["smiles", "id", "name"],
    index = False,
    ).encode("utf8")
encoded_csv_content = base64.urlsafe_b64encode(csv_content).decode("ascii")

download_links_html = (
    f'Download as: '
    f'<a href="data:text/plain;base64,{encoded_smi_content}">SMILES</a>'
    f' or '
    f'<a href="data:text/plain;base64,{encoded_csv_content}">CSV</a>'
    )

st.write(download_links_html, unsafe_allow_html=True)

### Write the DataFrame

def format_chembl_id(chembl_id):
    return f"<a href='{get_chembl_url(chembl_id)}'>{chembl_id}</a>"

## Add color to the scores.
# Table mapping range to text color and background rgb().
similarity_colors = [
    ("white", (68, 1, 84)),     # 0.0 <= score < 0.1
    ("white", (72, 36, 117)),   # 0.1 <= score < 0.2
    ("white", (65, 67, 135)),   # 0.2 <= score < 0.3
    ("white", (52, 95, 141)),   # 0.3 <= score < 0.4
    ("yellow", (41, 120, 142)), # 0.4 <= score < 0.5
    ("yellow", (32, 145, 140)), # 0.5 <= score < 0.6
    ("yellow", (34, 168, 132)), # 0.6 <= score < 0.7
    ("black", (68, 191, 112)),  # 0.7 <= score < 0.8
    ("black", (122, 210, 81)),  # 0.8 <= score < 0.9
    ("black", (189, 223, 38)),  # 0.9 <= score < 1.0
    ("black", (254, 231, 36)),  # score == 1.0 exactly
    ]
similarity_spans = [
    f"<span style='color: {fgcolor}; background-color: rgb({r}, {g}, {b})'>%f</span>"
         for (fgcolor, (r, g, b)) in similarity_colors]

def format_score(score):
    return similarity_spans[int(score * 10)] % (score,)


results_html = results_df.to_html(
    escape=False,
    formatters = {
        "id": format_chembl_id,
        "score": format_score,
        }
    )
st.write(results_html, unsafe_allow_html=True)