|
|
|
|
|
|
|
|
|
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() |
|
|
|
|
|
|
|
|
|
|
|
|
|
AA = pd.read_csv('raw_data.csv') |
|
|
|
|
|
|
|
|
|
|
|
|
|
AA.loc[AA['smiles'] == '[O-][N+](=[O-])C1=CC=CC(=C1)C2=NC(CO2)C3=CC=CC=C3' , 'smiles'] = 'c1ccc(cc1)C2COC(=N2)c3cccc(c3)[N+](=O)[O-]' |
|
|
|
|
|
|
|
|
|
AA.loc[AA['smiles'] == '[O-][N+](=[O-])C1=CC=CC(=C1)C2=NCCC(O2)C3=CC=CC=C3', 'smiles'] = 'c1ccc(cc1)C2CCN=C(O2)c3cccc(c3)[N+](=O)[O-]' |
|
|
|
|
|
|
|
AA['X'] = [ \ |
|
rdkit.Chem.MolToSmiles( |
|
fragment_remover.remove( |
|
standardizer.standardize( |
|
rdkit.Chem.MolFromSmiles( |
|
smiles)))) |
|
for smiles in AA['smiles']] |
|
|
|
problems = [] |
|
for index, row in tqdm.tqdm(AA.iterrows()): |
|
result = molvs.validate_smiles(row['X']) |
|
if len(result) == 0: |
|
continue |
|
problems.append( (row['substance_id'], result) ) |
|
|
|
|
|
for substance_id, alert in problems: |
|
print(f"substance_id: {substance_id}, problem: {alert[0]}") |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
AA.rename(columns={'X': 'SMILES'}, inplace=True) |
|
newAA = AA[['SMILES', 'substance_id', 'aggref_index', 'logP', 'reference']] |
|
|
|
|
|
|
|
import sys |
|
from rdkit import DataStructs |
|
from rdkit.Chem import AllChem as Chem |
|
from rdkit.Chem import PandasTools |
|
import scipy.spatial.distance as ssd |
|
from scipy.cluster import hierarchy |
|
|
|
|
|
|
|
|
|
|
|
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 |
|
|
|
|
|
|
|
smiles_index = 0 |
|
realistic = realistic_split(newAA.copy(), smiles_index, 0.8, split_for_exact_frac=True, cluster_method="Auto") |
|
realistic_train, realistic_test = split_df_into_train_and_test_sets(realistic) |
|
|
|
|
|
|
|
selected_columns = realistic_train[['SMILES', 'substance_id', 'aggref_index', 'logP', 'reference']] |
|
selected_columns.to_csv("AggregatorAdvisor_train.csv", index=False) |
|
selected_columns = realistic_test[['SMILES', 'substance_id', 'aggref_index', 'logP', 'reference']] |
|
selected_columns.to_csv("AggregatorAdvisor_test.csv", index=False) |
|
|