Datasets:
Download IUPAC_pKa_preprocessing.py from maomlab/IUPAC_pKa: direct link, hf CLI and curl.
- Browser
- Download file 9.16 kB
-
https://huggingface.co/datasets/maomlab/IUPAC_pKa/resolve/main/IUPAC_pKa_preprocessing.py
- Command line
-
hf download hf://datasets/maomlab/IUPAC_pKa/IUPAC_pKa_preprocessing.py
-
curl -L -o IUPAC_pKa_preprocessing.py https://huggingface.co/datasets/maomlab/IUPAC_pKa/resolve/main/IUPAC_pKa_preprocessing.py
9.16 kB
| # This is a script to preprocess the IUPAC_pKa dataset | |
| # 1. Load necessary modules | |
| import pandas as pd | |
| import numpy as np | |
| import rdkit | |
| from rdkit import Chem | |
| import molvs | |
| import tqdm | |
| from pathlib import Path | |
| standardizer = molvs.Standardizer() | |
| fragment_remover = molvs.fragment.FragmentRemover() | |
| # 2. Download dataset | |
| # https://github.com/IUPAC/Dissociation-Constants/blob/main/iupac_high-confidence_v2_2.csv | |
| # Suppose that we have downloaded 'iupac_high-confidence_v2_2.csv' | |
| raw_df = pd.read_csv('iupac_high-confidence_v2_2.csv') | |
| # 3. SMILES sanitization | |
| raw_df['X'] = [ \ | |
| rdkit.Chem.MolToSmiles( | |
| fragment_remover.remove( | |
| standardizer.standardize( | |
| rdkit.Chem.MolFromSmiles( | |
| smiles)))) | |
| for smiles in raw_df['SMILES']] | |
| problems = [] | |
| for index, row in tqdm.tqdm(raw_df.iterrows()): | |
| result = molvs.validate_smiles(row['X']) | |
| if len(result) == 0: | |
| continue | |
| problems.append((row['X'], result)) | |
| # Most are because it includes the salt form and/or it is not neutralized | |
| for result, alert in problems: | |
| print(f"SMILES: {result}, problem: {alert[0]}") | |
| raw_df.to_csv('IUPAC_pKa_sanitized.csv', index = False) | |
| # 4. Formatting and naming | |
| sanitized_df = pd.read_csv('IUPAC_pKa_sanitized.csv') | |
| formatted_df = sanitized_df.drop('SMILES', axis=1) # drop the raw SMILES column | |
| formatted_df = formatted_df.rename(columns={'X': 'SMILES'}) # use the sanitized SMILES | |
| formatted_df = formatted_df.rename(columns={'pka_value': 'Y'}) # rename the pKa column | |
| formatted_df['Y'] = pd.to_numeric(formatted_df['Y'], errors='coerce') # convert string to float64 for the 'Y' column | |
| column_to_move = formatted_df.columns[-1] # Move the sanitized SMILES | |
| new_order = formatted_df.columns.tolist() | |
| new_order.remove(column_to_move) | |
| new_order.insert(1, column_to_move) | |
| formatted_df = formatted_df[new_order] | |
| formatted_df.to_csv('IUPAC_pKa_formatted.csv', index = False) | |
| # 5. Import modules to split the dataset | |
| import sys | |
| from rdkit import DataStructs | |
| from rdkit.Chem import AllChem as Chem | |
| from rdkit.Chem import PandasTools | |
| # 6. Split the dataset into train and test | |
| 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 butina_cluster(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 hierarchal_cluster(fingerprints): | |
| num_fingerprints = len(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 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 = butina_cluster(fingerprints, num_fingerprints, cutoff) | |
| elif method == "Hierarchy": | |
| print("Hierarchical clustering is selected. Dataset size is:", num_fingerprints) | |
| clusters = hierarchal_cluster(fingerprints) | |
| return clusters | |
| 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 | |
| formatted_df = pd.read_csv('IUPAC_pKa_formatted.csv') | |
| smiles_index = 1 # Because smiles is in the second column | |
| realistic = realistic_split(formatted_df.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) | |
| # 7. Test and train datasets have been made | |
| realistic_train.to_csv("IUPAC_pKa_train.csv", index=False) | |
| realistic_test.to_csv("IUPAC_pKa_test.csv", index=False) | |
| realistic_train.to_parquet('IUPAC_pKa_train.parquet', index=False) | |
| realistic_test.to_parquet('IUPAC_pKa_test.parquet', index=False) | |