File size: 16,542 Bytes
e3e39ce ef2df99 0ae62f9 e3e39ce 7605b4f e3e39ce 0ae62f9 e3e39ce 0ae62f9 e3e39ce 96fb9cd e3e39ce 96fb9cd e3e39ce |
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 |
## Script to sanitize and split HematoxLong2023 dataset
# 1. Load modules
pip install rdkit
pip install molvs
import pandas as pd
import numpy as np
import urllib.request
import tqdm
import rdkit
from rdkit import Chem
import molvs
standardizer = molvs.Standardizer()
fragment_remover = molvs.fragment.FragmentRemover()
#2. Download the original dataset
# Download SI Table 2 from
#. Structural Analysis and Prediction of Hematotoxicity Using Deep Learning Approaches
#. Teng-Zhi Long, Shao-Hua Shi, Shao Liu, Ai-Ping Lu, Zhao-Qian Liu, Min Li, Ting-Jun Hou*, and Dong-Sheng Cao*
#. J. Chem. Inf. Model. 2023, 63, 1, 111–125
#. https://doi.org/10.1021/acs.jcim.2c01088
urllib.request.urlretrieve(
url = "https://ndownloader.figstatic.com/files/38442996",
filename = "Long2023_SI2.xls")
Long2023 = pd.read_excel(
io = "Long2023_SI2.xls",
sheet_name = "all_data",
engine = "xlrd",
names = ['SMILES', 'Y'])
Long2023['ID'] = [f"Long2023_{i}" for i in range(len(Long2023.index))]
#3. Resolve SMILES parse error
# failed to parse smiles, looked it up in ChemSpider and found Octahydro-1H-purine-6-thiol
# (Found by conversion of search term to chemical structure (connectivity match))
# https://www.chemspider.com/Chemical-Structure.114454999.html?rid=8f8bdf21-6482-44e5-adc9-71c5aef41627
Long2023.loc[Long2023['SMILES'] == 'Sc1[nH]cnc-2[n+H]cnc1-2', 'SMILES'] = "SC1NCNC2NCNC21"
# failed to parse smiles, looked it up in Pubchem and found 2-Amino-3,7-dihydropurin-1-ium-6-thione
# https://pubchem.ncbi.nlm.nih.gov/compound/117071895
Long2023.loc[Long2023['SMILES'] == 'Sc1nc(N)nc2[n+H]c[nH]c12', 'SMILES'] = "C1=NC2=C(N1)C(=S)[NH+]=C(N2)N"
# failed to parse smiles, looked it up in ChemSpider and found gentamicin
# (Found by conversion of search term to chemical structure (connectivity match))
# The approved drug gentamicin is a complex of three closely-related aminoglycoside sulfates: C1, C1a and C2
# It's unclear from the smiles, if they used just one of the forms or the mixture of all three
# Clinically, there appears to be a wide range of compositions of C1, C1a, C2 forms (!)
# Here, we'll just use the C1 form (https://www.ebi.ac.uk/chebi/searchId.do;D579C431E9548A30AFBD88A2D05CA777?chebiId=CHEBI:27412)
Long2023.loc[Long2023['SMILES'] == 'O(C1C(O)C(OC2C(O)C([N+H2]C)[C@](O)(C)CO2)C(N)CC1N)C1C([N+H3])CCC(C([N+H2]C)C)O1', 'SMILES'] = \
"CNC(C)[C@@H]1CC[C@@H](N)[C@H](O1)O[C@@H]1[C@@H](N)C[C@@H](N)[C@H](O[C@H]2OC[C@](C)(O)[C@H](NC)[C@H]2O)[C@H]1O"
# failed to parse smiles, looked it up in ChemSpider and found (2S)-2-Hydroxy-N-isopropyl-3-(1-naphthyloxy)-1-propanaminium
# (Found by conversion of search term to chemical structure (connectivity match))
# https://www.chemspider.com/Chemical-Structure.5296478.html?rid=129380a1-888e-48d0-b240-43646b288842
Long2023.loc[Long2023['SMILES'] == 'O(C[C@@H](O)C[N+H2]C(C)C)c1c2c(ccc1)cccc2', 'SMILES'] = \
"O[C@@H](C[NH2+]C(C)C)COc2cccc1ccccc12"
# failed to parse smiles, looked it up in ChemSpider, removing charge and H from nitrogens
# matches Periciazine, which I think is what this compound is
# https://www.chemspider.com/Chemical-Structure.4585.html?rid=0694332f-3886-4df1-85d4-8cdb11554c3d
Long2023.loc[Long2023['SMILES'] == 'OC1CC[N+H](CCC[N+@H]2c3c(Sc4c2cccc4)ccc(C#N)c3)CC1', 'SMILES'] = \
"c1ccc2c(c1)N(c3cc(ccc3S2)C#N)CCCN4CCC(CC4)O"
# failed to parse smiles, looked it up in ChemSpider and found idarubicin
# (Found by conversion of search term to chemical structure (connectivity match))
# Idarubicin, or 4-demethoxydaunorubicin is an anthracycline antileukemic drug.
# https://www.chemspider.com/Chemical-Structure.39117.html?rid=a418032b-d8ab-4200-9226-bcb194221cf0&page_num=0
Long2023.loc[Long2023['SMILES'] == 'O=C(C)[C@@]1(O)CC(OC2OC(C)C(O)C([N+H3])C2)c2c(O)c3C(=O)c4c(C(=O)c3c(O)c2C1)cccc4', 'SMILES'] = \
"C[C@H]1[C@H]([C@H](C[C@@H](O1)O[C@H]2C[C@@](Cc3c2c(c4c(c3O)C(=O)c5ccccc5C4=O)O)(C(=O)C)O)N)O"
# failed to parse smiles, looked it up in ChemSpider and found (2S)-5-[(6-Methoxy-8-quinolinyl)amino]-2-pentanaminium
# (Found by conversion of search term to chemical structure (full match))
# https://www.chemspider.com/Chemical-Structure.1291555.html?rid=b22e2c45-078e-48d9-8907-22deb37bed0c
Long2023.loc[Long2023['SMILES'] == 'O(C)c1cc(NCCC[C@@H]([N+H3])C)c2ncccc2c1', 'SMILES'] = "C[C@@H](CCCNc1cc(cc2c1nccc2)OC)[NH3+]"
# failed to parse smiles, looked it up in PUbchem
# found diethyl-[2-[[5-[(Z)-(5-fluoro-2-oxo-1H-indol-3-ylidene)methyl]-2,4-dimethyl-1H-pyrrole-3-carbonyl]amino]ethyl]azanium
# https://pubchem.ncbi.nlm.nih.gov/compound/40469377
Long2023.loc[Long2023['SMILES'] == 'Fc1cc2/C(=C/c3c(C)c(C(=O)NCC[N+H](CC)CC)c(C)[nH]3)/C(=O)Nc2cc1', 'SMILES'] = \
"CC[NH+](CC)CCNC(=O)C1=C(NC(=C1C)C=C2C3=C(C=CC(=C3)F)NC2=O)C"
# failed to parse smiles, looked it up in ChemSpider
# found 1-Methyl-4-{4-[(4-methyl-3-{[4-(3-pyridinyl)-2-pyrimidinyl]amino}phenyl)carbamoyl]benzyl}piperazin-1-ium
# (Found by conversion of search term to chemical structure (full match))
# https://www.chemspider.com/Chemical-Structure.13082883.html?rid=8baa4568-3947-473e-9fdc-8872f411694c#synonymsTab
Long2023.loc[Long2023['SMILES'] == 'O=C([N+H2]c1cc(Nc2nc(-c3cnccc3)ccn2)c(C)cc1)c1ccc(CN2CCN(C)CC2)cc1', 'SMILES'] = \
"Cc1ccc(cc1Nc2nccc(n2)c3cccnc3)NC(=O)c4ccc(cc4)CN5CC[NH+](CC5)C"
# failed to parse smiles, looked it up in ChemSpider and found 6-Chloro-9-{[(2S)-5-(diethylammonio)-2-pentanyl]amino}-2-methoxyacridinium
# (Found by conversion of search term to chemical structure (full match))
# https://www.chemspider.com/Chemical-Structure.5408834.html?rid=c1cdd9c2-d48b-4cd4-945d-606bf2bff1ee
Long2023.loc[Long2023['SMILES'] == 'Clc1cc2[n+H]c3c(c(N[C@H](CCC[N+H](CC)CC)C)c2cc1)cc(OC)cc3', 'SMILES'] = \
"Clc3ccc2c(c1cc(OC)ccc1[nH+]c2c3)N[C@@H](C)CCC[NH+](CC)CC"
# failed to parse smiles, looked it up in ChemSpider, removing charge
# found Carvedilol
# (Found by conversion of search term to chemical structure (connectivity match))
# Carvedilol is a beta-blocker medication, that may be prescribed for treating high blood pressure and chronic heart failure with reduced ejection fraction.
# https://www.chemspider.com/Chemical-Structure.2487.html?rid=f8358443-8c32-4e5f-b1d8-47ad13ea8a16&page_num=0
Long2023.loc[Long2023['SMILES'] == 'O(CC[N+H2]C[C@H](O)COc1c-2c([N+H2]c3c-2cccc3)ccc1)c1c(OC)cccc1', 'SMILES'] = \
"COc1ccccc1OCCNCC(COc2cccc3c2c4ccccc4[nH]3)O"
# failed to parse smiles, looked it up in ChemSpider, found (2S)-1-(2,6-Dimethylphenoxy)-2-propanaminium
# (Found by conversion of search term to chemical structure (full match))
# https://www.chemspider.com/Chemical-Structure.5296573.html?rid=c8c0121e-fad3-4458-8c64-a0baa3e18358
Long2023.loc[Long2023['SMILES'] == 'O(C[C@@H]([N+H3])C)c1c(C)cccc1C', 'SMILES'] = \
"O(c1c(cccc1C)C)C[C@@H]([NH3+])C"
# failed to parse smiles, looked it up in ChemSpider and found 4-{2-[(5-Cyano-5,5-diphenylpentyl)(methyl)amino]ethyl}-4-methylmorpholin-4-ium
# (Found by conversion of search term to chemical structure (connectivity match))
# https://www.chemspider.com/Chemical-Structure.2310136.html?rid=ce2b48f6-04d6-4df3-ad71-b6507906c7cb
Long2023.loc[Long2023['SMILES'] == '[N+@H](CCCCC(C#N)(c1ccccc1)c1ccccc1)(CC[N+]1(C)CCOCC1)C', 'SMILES'] = \
"CN(CCCCC(C#N)(c1ccccc1)c2ccccc2)CC[N+]3(CCOCC3)C"
# failed to parse smiles, looked it up in ChemSpider
# found (5E)-3-[(2R,6S)-2,6-Dimethyl-1-piperidinyl]-5-[(4-methoxybenzoyl)imino]-4,5-dihydro-1,2,3-oxadiazol-3-ium-4-ide
# (Found by conversion of search term to chemical structure (full match))
# https://www.chemspider.com/Chemical-Structure.28530638.html?rid=b44dbe3c-24f1-4303-8deb-82b879b7f0e0
Long2023.loc[Long2023['SMILES'] == 'O=C(/N=C1/ON=[N+](N2[C@@H](C)CCC[C@H]2C)[C-H]/1)c1ccc(OC)cc1', 'SMILES'] = \
"C[C@@H]1CCC[C@@H](N1[n+]2[cH-]/c(=N\C(=O)c3ccc(cc3)OC)/on2)C"
# failed to parse smiles, looked it up in Pubchem
# found ((R)-[(2S)-7-ethenyl-1-azabicyclo[2.2.1]heptan-2-yl]-(6-methoxyquinolin-4-yl)methanol
# https://pubchem.ncbi.nlm.nih.gov/compound/139247817
Long2023.loc[Long2023['SMILES'] == 'O(C)c1cc2c([C@@H](O)[C@@H]3[N+@H]4[C@@H](C=C)[C@H](C3)CC4)ccnc2cc1', 'SMILES'] = \
"COC1=CC2=C(C=CN=C2C=C1)C(C3CC4CCN3C4C=C)O"
#4. Sanitize with MolVS and print problems
Long2023['X'] = [ \
rdkit.Chem.MolToSmiles(
fragment_remover.remove(
standardizer.standardize(
rdkit.Chem.MolFromSmiles(
smiles))))
for smiles in Long2023['SMILES']]
problems = []
for index, row in tqdm.tqdm(Long2023.iterrows()):
result = molvs.validate_smiles(row['X'])
if len(result) == 0:
continue
problems.append( (row['ID'], result) )
# Most are because it includes the salt form and/or it is not neutralized
for id, alert in problems:
print(f"ID: {id}, problem: {alert[0]}")
# Result interpretation
# - Can't kekulize mol: The error message means that kekulization would break the molecules down, so it couldn't proceed
# It doesn't mean that the molecules are bad, it just means that normalization failed
# - () is present: The error message is not about a salt, not about a fragment,
# It is showing there is a molecule () (ex) Benzene is present
#5. Select columns and rename the dataset
Long2023.rename(columns={'X': 'new SMILES', 'Y': 'Label'}, inplace=True)
HematoxLong2023 = Long2023[['new SMILES', 'Label']]
#6. Import modules to split the dataset
import sys
from rdkit import DataStructs
from rdkit.Chem import AllChem as Chem
from rdkit.Chem import PandasTools
#7. Split the dataset into test and train
class MolecularFingerprint:
def __init__(self, fingerprint):
self.fingerprint = fingerprint
def __str__(self):
return self.fingerprint.__str__()
def compute_fingerprint(molecule):
try:
fingerprint = Chem.GetMorganFingerprintAsBitVect(molecule, 2, nBits=1024)
result = np.zeros(len(fingerprint), np.int32)
DataStructs.ConvertToNumpyArray(fingerprint, result)
return MolecularFingerprint(result)
except:
print("Fingerprints for a structure cannot be calculated")
return None
def tanimoto_distances_yield(fingerprints, num_fingerprints):
for i in range(1, num_fingerprints):
yield [1 - x for x in DataStructs.BulkTanimotoSimilarity(fingerprints[i], fingerprints[:i])]
def cluster_data(fingerprints, num_points, distance_threshold, reordering=False):
nbr_lists = [None] * num_points
for i in range(num_points):
nbr_lists[i] = []
dist_fun = tanimoto_distances_yield(fingerprints, num_points)
for i in range(1, num_points):
dists = next(dist_fun)
for j in range(i):
dij = dists[j]
if dij <= distance_threshold:
nbr_lists[i].append(j)
nbr_lists[j].append(i)
t_lists = [(len(y), x) for x, y in enumerate(nbr_lists)]
t_lists.sort(reverse=True)
res = []
seen = [0] * num_points
while t_lists:
_, idx = t_lists.pop(0)
if seen[idx]:
continue
t_res = [idx]
for nbr in nbr_lists[idx]:
if not seen[nbr]:
t_res.append(nbr)
seen[nbr] = 1
if reordering:
nbr_nbr = [nbr_lists[t] for t in t_res]
nbr_nbr = frozenset().union(*nbr_nbr)
for x, y in enumerate(t_lists):
y1 = y[1]
if seen[y1] or (y1 not in nbr_nbr):
continue
nbr_lists[y1] = set(nbr_lists[y1]).difference(t_res)
t_lists[x] = (len(nbr_lists[y1]), y1)
t_lists.sort(reverse=True)
res.append(tuple(t_res))
return tuple(res)
def cluster_fingerprints(fingerprints, method="Auto"):
num_fingerprints = len(fingerprints)
if method == "Auto":
method = "TB" if num_fingerprints >= 10000 else "Hierarchy"
if method == "TB":
cutoff = 0.56
print("Butina clustering is selected. Dataset size is:", num_fingerprints)
clusters = cluster_data(fingerprints, num_fingerprints, cutoff)
elif method == "Hierarchy":
import scipy.spatial.distance as ssd
from scipy.cluster import hierarchy
print("Hierarchical clustering is selected. Dataset size is:", num_fingerprints)
av_cluster_size = 8
dists = []
for i in range(0, num_fingerprints):
sims = DataStructs.BulkTanimotoSimilarity(fingerprints[i], fingerprints)
dists.append([1 - x for x in sims])
dis_array = ssd.squareform(dists)
Z = hierarchy.linkage(dis_array)
average_cluster_size = av_cluster_size
cluster_amount = int(num_fingerprints / average_cluster_size)
clusters = hierarchy.cut_tree(Z, n_clusters=cluster_amount)
clusters = list(clusters.transpose()[0])
cs = []
for i in range(max(clusters) + 1):
cs.append([])
for i in range(len(clusters)):
cs[clusters[i]].append(i)
return cs
def split_dataframe(dataframe, smiles_col_index, fraction_to_train, split_for_exact_fraction=True, cluster_method="Auto"):
try:
import math
smiles_column_name = dataframe.columns[smiles_col_index]
molecule = 'molecule'
fingerprint = 'fingerprint'
group = 'group'
testing = 'testing'
try:
PandasTools.AddMoleculeColumnToFrame(dataframe, smiles_column_name, molecule)
except:
print("Exception occurred during molecule generation...")
dataframe = dataframe.loc[dataframe[molecule].notnull()]
dataframe[fingerprint] = [compute_fingerprint(m) for m in dataframe[molecule]]
dataframe = dataframe.loc[dataframe[fingerprint].notnull()]
fingerprints = [Chem.GetMorganFingerprintAsBitVect(m, 2, nBits=2048) for m in dataframe[molecule]]
clusters = cluster_fingerprints(fingerprints, method=cluster_method)
dataframe.drop([molecule, fingerprint], axis=1, inplace=True)
last_training_index = int(math.ceil(len(dataframe) * fraction_to_train))
clustered = None
cluster_no = 0
mol_count = 0
for cluster in clusters:
cluster_no = cluster_no + 1
try:
one_cluster = dataframe.iloc[list(cluster)].copy()
except:
print("Wrong indexes in Cluster: %i, Molecules: %i" % (cluster_no, len(cluster)))
continue
one_cluster.loc[:, 'ClusterNo'] = cluster_no
one_cluster.loc[:, 'MolCount'] = len(cluster)
if (mol_count < last_training_index) or (cluster_no < 2):
one_cluster.loc[:, group] = 'training'
else:
one_cluster.loc[:, group] = testing
mol_count += len(cluster)
clustered = pd.concat([clustered, one_cluster], ignore_index=True)
if split_for_exact_fraction:
print("Adjusting test to train ratio. It may split one cluster")
clustered.loc[last_training_index + 1:, group] = testing
print("Clustering finished. Training set size is %i, Test set size is %i, Fraction %.2f" %
(len(clustered.loc[clustered[group] != testing]),
len(clustered.loc[clustered[group] == testing]),
len(clustered.loc[clustered[group] == testing]) / len(clustered)))
except KeyboardInterrupt:
print("Clustering interrupted.")
return clustered
def realistic_split(df, smile_col_index, frac_train, split_for_exact_frac=True, cluster_method = "Auto"):
return split_dataframe(df.copy(), smile_col_index, frac_train, split_for_exact_frac, cluster_method=cluster_method)
def split_df_into_train_and_test_sets(df):
df['group'] = df['group'].str.replace(' ', '_')
df['group'] = df['group'].str.lower()
train = df[df['group'] == 'training']
test = df[df['group'] == 'testing']
return train, test
# 8. Test and train datasets have been made
smiles_index = 0 # Because smiles is in the first column
realistic = realistic_split(HematoxLong2023.copy(), smiles_index, 0.75, split_for_exact_frac=True, cluster_method="Auto")
realistic_train, realistic_test = split_df_into_train_and_test_sets(realistic)
#9. Select columns and name the datasets
selected_columns = realistic_train[['new SMILES', 'Label']]
selected_columns.to_csv("HematoxLong2023_train.csv", index=False)
selected_columns = realistic_test[['new SMILES', 'Label']]
selected_columns.to_csv("HematoxLong2023_test.csv", index=False)
|