haneulpark commited on
Commit
d38d757
·
verified ·
1 Parent(s): 6a6d2a3

Upload IUPAC_pKa_preprocessing.py

Browse files
Files changed (1) hide show
  1. IUPAC_pKa_preprocessing.py +263 -0
IUPAC_pKa_preprocessing.py ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This is a script to preprocess the IUPAC_pKa dataset
2
+
3
+ # 1. Load necessary modules
4
+ import pandas as pd
5
+ import numpy as np
6
+ import rdkit
7
+ from rdkit import Chem
8
+ import molvs
9
+ import tqdm
10
+ from pathlib import Path
11
+
12
+ standardizer = molvs.Standardizer()
13
+ fragment_remover = molvs.fragment.FragmentRemover()
14
+
15
+
16
+ # 2. Download dataset
17
+ # https://github.com/IUPAC/Dissociation-Constants/blob/main/iupac_high-confidence_v2_2.csv
18
+ # Suppose that we have downloaded 'iupac_high-confidence_v2_2.csv'
19
+
20
+ raw_df = pd.read_csv('iupac_high-confidence_v2_2.csv')
21
+
22
+
23
+ # 3. SMILES sanitization
24
+ raw_df['X'] = [ \
25
+ rdkit.Chem.MolToSmiles(
26
+ fragment_remover.remove(
27
+ standardizer.standardize(
28
+ rdkit.Chem.MolFromSmiles(
29
+ smiles))))
30
+ for smiles in raw_df['SMILES']]
31
+
32
+ problems = []
33
+ for index, row in tqdm.tqdm(raw_df.iterrows()):
34
+ result = molvs.validate_smiles(row['X'])
35
+ if len(result) == 0:
36
+ continue
37
+ problems.append((row['X'], result))
38
+
39
+ # Most are because it includes the salt form and/or it is not neutralized
40
+ for result, alert in problems:
41
+ print(f"SMILES: {result}, problem: {alert[0]}")
42
+
43
+ raw_df.to_csv('IUPAC_pKa_sanitized.csv', index = False)
44
+
45
+
46
+
47
+ # 4. Formatting and naming
48
+ sanitized_df = pd.read_csv('IUPAC_pKa_sanitized.csv')
49
+
50
+ formatted_df = sanitized_df.drop('SMILES', axis=1) # drop the raw SMILES column
51
+ formatted_df = formatted_df.rename(columns={'X': 'SMILES'}) # use the sanitized SMILES
52
+ formatted_df = formatted_df.rename(columns={'pka_value': 'Y'}) # rename the pKa column
53
+ formatted_df['Y'] = pd.to_numeric(formatted_df['Y'], errors='coerce') # convert string to float64 for the 'Y' column
54
+ column_to_move = formatted_df.columns[-1] # Move the sanitized SMILES
55
+ new_order = formatted_df.columns.tolist()
56
+ new_order.remove(column_to_move)
57
+ new_order.insert(1, column_to_move)
58
+ formatted_df = formatted_df[new_order]
59
+
60
+ formatted_df.to_csv('IUPAC_pKa_formatted.csv', index = False)
61
+
62
+
63
+
64
+ # 5. Import modules to split the dataset
65
+ import sys
66
+ from rdkit import DataStructs
67
+ from rdkit.Chem import AllChem as Chem
68
+ from rdkit.Chem import PandasTools
69
+
70
+
71
+ # 6. Split the dataset into train and test
72
+
73
+ class MolecularFingerprint:
74
+ def __init__(self, fingerprint):
75
+ self.fingerprint = fingerprint
76
+
77
+ def __str__(self):
78
+ return self.fingerprint.__str__()
79
+
80
+ def compute_fingerprint(molecule):
81
+ try:
82
+ fingerprint = Chem.GetMorganFingerprintAsBitVect(molecule, 2, nBits=1024)
83
+ result = np.zeros(len(fingerprint), np.int32)
84
+ DataStructs.ConvertToNumpyArray(fingerprint, result)
85
+ return MolecularFingerprint(result)
86
+ except:
87
+ print("Fingerprints for a structure cannot be calculated")
88
+ return None
89
+
90
+ def tanimoto_distances_yield(fingerprints, num_fingerprints):
91
+ for i in range(1, num_fingerprints):
92
+ yield [1 - x for x in DataStructs.BulkTanimotoSimilarity(fingerprints[i], fingerprints[:i])]
93
+
94
+ def butina_cluster(fingerprints, num_points, distance_threshold, reordering=False):
95
+ nbr_lists = [None] * num_points
96
+ for i in range(num_points):
97
+ nbr_lists[i] = []
98
+
99
+ dist_fun = tanimoto_distances_yield(fingerprints, num_points)
100
+ for i in range(1, num_points):
101
+ dists = next(dist_fun)
102
+
103
+ for j in range(i):
104
+ dij = dists[j]
105
+ if dij <= distance_threshold:
106
+ nbr_lists[i].append(j)
107
+ nbr_lists[j].append(i)
108
+
109
+ t_lists = [(len(y), x) for x, y in enumerate(nbr_lists)]
110
+ t_lists.sort(reverse=True)
111
+
112
+ res = []
113
+ seen = [0] * num_points
114
+ while t_lists:
115
+ _, idx = t_lists.pop(0)
116
+ if seen[idx]:
117
+ continue
118
+ t_res = [idx]
119
+ for nbr in nbr_lists[idx]:
120
+ if not seen[nbr]:
121
+ t_res.append(nbr)
122
+ seen[nbr] = 1
123
+ if reordering:
124
+ nbr_nbr = [nbr_lists[t] for t in t_res]
125
+ nbr_nbr = frozenset().union(*nbr_nbr)
126
+ for x, y in enumerate(t_lists):
127
+ y1 = y[1]
128
+ if seen[y1] or (y1 not in nbr_nbr):
129
+ continue
130
+ nbr_lists[y1] = set(nbr_lists[y1]).difference(t_res)
131
+ t_lists[x] = (len(nbr_lists[y1]), y1)
132
+ t_lists.sort(reverse=True)
133
+ res.append(tuple(t_res))
134
+ return tuple(res)
135
+
136
+ def hierarchal_cluster(fingerprints):
137
+
138
+ num_fingerprints = len(fingerprints)
139
+
140
+ av_cluster_size = 8
141
+ dists = []
142
+
143
+ for i in range(0, num_fingerprints):
144
+ sims = DataStructs.BulkTanimotoSimilarity(fingerprints[i], fingerprints)
145
+ dists.append([1 - x for x in sims])
146
+
147
+ dis_array = ssd.squareform(dists)
148
+ Z = hierarchy.linkage(dis_array)
149
+ average_cluster_size = av_cluster_size
150
+ cluster_amount = int(num_fingerprints / average_cluster_size)
151
+ clusters = hierarchy.cut_tree(Z, n_clusters=cluster_amount)
152
+
153
+ clusters = list(clusters.transpose()[0])
154
+ cs = []
155
+ for i in range(max(clusters) + 1):
156
+ cs.append([])
157
+
158
+ for i in range(len(clusters)):
159
+ cs[clusters[i]].append(i)
160
+ return cs
161
+
162
+ def cluster_fingerprints(fingerprints, method="Auto"):
163
+ num_fingerprints = len(fingerprints)
164
+
165
+ if method == "Auto":
166
+ method = "TB" if num_fingerprints >= 10000 else "Hierarchy"
167
+
168
+ if method == "TB":
169
+ cutoff = 0.56
170
+ print("Butina clustering is selected. Dataset size is:", num_fingerprints)
171
+ clusters = butina_cluster(fingerprints, num_fingerprints, cutoff)
172
+
173
+ elif method == "Hierarchy":
174
+ print("Hierarchical clustering is selected. Dataset size is:", num_fingerprints)
175
+ clusters = hierarchal_cluster(fingerprints)
176
+
177
+ return clusters
178
+
179
+ def split_dataframe(dataframe, smiles_col_index, fraction_to_train, split_for_exact_fraction=True, cluster_method="Auto"):
180
+ try:
181
+ import math
182
+ smiles_column_name = dataframe.columns[smiles_col_index]
183
+ molecule = 'molecule'
184
+ fingerprint = 'fingerprint'
185
+ group = 'group'
186
+ testing = 'testing'
187
+
188
+ try:
189
+ PandasTools.AddMoleculeColumnToFrame(dataframe, smiles_column_name, molecule)
190
+ except:
191
+ print("Exception occurred during molecule generation...")
192
+
193
+ dataframe = dataframe.loc[dataframe[molecule].notnull()]
194
+ dataframe[fingerprint] = [compute_fingerprint(m) for m in dataframe[molecule]]
195
+ dataframe = dataframe.loc[dataframe[fingerprint].notnull()]
196
+
197
+ fingerprints = [Chem.GetMorganFingerprintAsBitVect(m, 2, nBits=2048) for m in dataframe[molecule]]
198
+ clusters = cluster_fingerprints(fingerprints, method=cluster_method)
199
+
200
+ dataframe.drop([molecule, fingerprint], axis=1, inplace=True)
201
+
202
+ last_training_index = int(math.ceil(len(dataframe) * fraction_to_train))
203
+ clustered = None
204
+ cluster_no = 0
205
+ mol_count = 0
206
+
207
+ for cluster in clusters:
208
+ cluster_no = cluster_no + 1
209
+ try:
210
+ one_cluster = dataframe.iloc[list(cluster)].copy()
211
+ except:
212
+ print("Wrong indexes in Cluster: %i, Molecules: %i" % (cluster_no, len(cluster)))
213
+ continue
214
+
215
+ one_cluster.loc[:, 'ClusterNo'] = cluster_no
216
+ one_cluster.loc[:, 'MolCount'] = len(cluster)
217
+
218
+ if (mol_count < last_training_index) or (cluster_no < 2):
219
+ one_cluster.loc[:, group] = 'training'
220
+ else:
221
+ one_cluster.loc[:, group] = testing
222
+
223
+ mol_count += len(cluster)
224
+ clustered = pd.concat([clustered, one_cluster], ignore_index=True)
225
+
226
+ if split_for_exact_fraction:
227
+ print("Adjusting test to train ratio. It may split one cluster")
228
+ clustered.loc[last_training_index + 1:, group] = testing
229
+
230
+ print("Clustering finished. Training set size is %i, Test set size is %i, Fraction %.2f" %
231
+ (len(clustered.loc[clustered[group] != testing]),
232
+ len(clustered.loc[clustered[group] == testing]),
233
+ len(clustered.loc[clustered[group] == testing]) / len(clustered)))
234
+
235
+ except KeyboardInterrupt:
236
+ print("Clustering interrupted.")
237
+
238
+ return clustered
239
+
240
+
241
+ def realistic_split(df, smile_col_index, frac_train, split_for_exact_frac=True, cluster_method = "Auto"):
242
+ return split_dataframe(df.copy(), smile_col_index, frac_train, split_for_exact_frac, cluster_method=cluster_method)
243
+
244
+ def split_df_into_train_and_test_sets(df):
245
+ df['group'] = df['group'].str.replace(' ', '_')
246
+ df['group'] = df['group'].str.lower()
247
+ train = df[df['group'] == 'training']
248
+ test = df[df['group'] == 'testing']
249
+ return train, test
250
+
251
+
252
+ formatted_df = pd.read_csv('IUPAC_pKa_formatted.csv')
253
+ smiles_index = 1 # Because smiles is in the second column
254
+ realistic = realistic_split(formatted_df.copy(), smiles_index, 0.75, split_for_exact_frac=True, cluster_method="Auto")
255
+ realistic_train, realistic_test = split_df_into_train_and_test_sets(realistic)
256
+
257
+
258
+ #8. Test and train datasets have been made
259
+ realistic_train.to_csv("IUPAC_pKa_train.csv", index=False)
260
+ realistic_test.to_csv("IUPAC_pKa_test.csv", index=False)
261
+
262
+ realistic_train.to_parquet('IUPAC_pKa_train.parquet', index=False)
263
+ realistic_test.to_parquet('IUPAC_pKa_test.parquet', index=False)