Spaces:
Sleeping
Sleeping
File size: 13,211 Bytes
b6f1234 |
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 372 373 374 375 376 377 378 379 |
import pandas as pd
import shutil, os
import os.path as osp
import numpy as np
from tqdm import tqdm
import torch
from torch_geometric.data import Data
from torch.autograd import Variable
from rdkit import Chem
from data.features import (
allowable_features,
atom_to_feature_vector,
bond_to_feature_vector,
atom_feature_vector_to_dict,
bond_feature_vector_to_dict,
)
from utils.data_util import one_hot_vector_sm, one_hot_vector_am, get_atom_feature_dims
def load_dataset(
cross_val, binary_task, target, args, use_prot=False, advs=False, test=False
):
"""
Load data and return data in dataframes format for each split and the loader of each split.
Args:
cross_val (int): Data partition being used [1-4].
binary_tast (boolean): Whether to perform binary classification or multiclass classification.
target (string): Name of the protein target for binary classification.
args (parser): Complete arguments (configuration) of the model.
use_prot (boolean): Whether to use the PM module.
advs (boolean): Whether to train the LM module with adversarial augmentations.
test (boolean): Whether the model is being tested or trained.
Return:
train (loader): Training loader
valid (loader): Validation loader
test (loader): Test loader
data_train (dataframe): Training data dataframe
data_valid (dataframe): Validation data dataframe
data_test (dataframe): Test data dataframe
"""
# TODO: NO QUEREMOS QUE ESTÉ LA PARTICIÓN DEL MULTICLASE?
# Read all data files
if not test:
# Verify cross validation partition is defined
assert cross_val in [1, 2, 3, 4], "{} data partition is not defined".format(
cross_val
)
print("Loading data...")
if binary_task:
path = "data/datasets/AD/"
A = pd.read_csv(
path + "Smiles_AD_1.csv", names=["Smiles", "Target", "Label"]
)
B = pd.read_csv(
path + "Smiles_AD_2.csv", names=["Smiles", "Target", "Label"]
)
C = pd.read_csv(
path + "Smiles_AD_3.csv", names=["Smiles", "Target", "Label"]
)
D = pd.read_csv(
path + "Smiles_AD_4.csv", names=["Smiles", "Target", "Label"]
)
data_test = pd.read_csv(
path + "AD_Test.csv", names=["Smiles", "Target", "Label"]
)
if use_prot:
data_target = pd.read_csv(
path + "Targets_Fasta.csv", names=["Fasta", "Target", "Label"]
)
else:
data_target = []
# Generate train and validation splits according to cross validation number
if cross_val == 1:
data_train = pd.concat([A, B, C], ignore_index=True)
data_val = D
elif cross_val == 2:
data_train = pd.concat([A, C, D], ignore_index=True)
data_val = B
elif cross_val == 3:
data_train = pd.concat([A, B, D], ignore_index=True)
data_val = C
elif cross_val == 4:
data_train = pd.concat([B, C, D], ignore_index=True)
data_val = A
# If in binary classification select data for the specific target being train
if binary_task:
data_train = data_train[data_train.Target == target]
data_val = data_val[data_val.Target == target]
data_test = data_test[data_test.Target == target]
if use_prot:
data_target = data_target[data_target.Target == target]
# Get dataset for each split
train = get_dataset(data_train, use_prot, data_target, args, advs)
valid = get_dataset(data_val, use_prot, data_target, args)
test = get_dataset(data_test, use_prot, data_target, args)
else:
# Read test data file
if binary_task:
path = "data/datasets/AD/"
data_test = pd.read_csv(
path + "Smiles_AD_Test.csv", names=["Smiles", "Target", "Label"]
)
data_test = data_test[data_test.Target == target]
if use_prot:
data_target = pd.read_csv(
path + "Targets_Fasta.csv", names=["Fasta", "Target", "Label"]
)
data_target = data_target[data_target.Target == target]
else:
data_target = []
test = get_dataset(data_test,target=data_target, use_prot=use_prot, args=args, advs=advs, saliency=args.saliency)
train = []
valid = []
data_train = []
data_val = []
print("Done.")
return train, valid, test, data_train, data_val, data_test
def reload_dataset(cross_val, binary_task, target, args, advs=False):
print("Reloading data")
args.edge_dict = {}
if binary_task:
path = "data/datasets/AD/"
A = pd.read_csv(path + "Smiles_AD_1.csv", names=["Smiles", "Target", "Label"])
B = pd.read_csv(path + "Smiles_AD_2.csv", names=["Smiles", "Target", "Label"])
C = pd.read_csv(path + "Smiles_AD_3.csv", names=["Smiles", "Target", "Label"])
D = pd.read_csv(path + "Smiles_AD_4.csv", names=["Smiles", "Target", "Label"])
data_test = pd.read_csv(
path + "AD_Test.csv", names=["Smiles", "Target", "Label"]
)
if cross_val == 1:
data_train = pd.concat([A, B, C], ignore_index=True)
elif cross_val == 2:
data_train = pd.concat([A, C, D], ignore_index=True)
elif cross_val == 3:
data_train = pd.concat([A, B, D], ignore_index=True)
else:
data_train = pd.concat([B, C, D], ignore_index=True)
if binary_task:
data_train = data_train[data_train.Target == target]
train = get_dataset(data_train, args=args, advs=advs)
print("Done.")
return train, data_train
def smiles_to_graph(smiles_string, is_prot=False, received_mol=False, saliency=False):
"""
Converts SMILES string to graph Data object
:input: SMILES string (str)
:return: graph object
"""
if not is_prot:
mol = Chem.MolFromSmiles(smiles_string)
else:
mol = Chem.MolFromFASTA(smiles_string)
# atoms
atom_features_list = []
atom_feat_dims = get_atom_feature_dims()
for atom in mol.GetAtoms():
ftrs = atom_to_feature_vector(atom)
if saliency:
ftrs_oh = one_hot_vector_am(ftrs, atom_feat_dims)
atom_features_list.append(torch.unsqueeze(ftrs_oh, 0))
else:
atom_features_list.append(ftrs)
if saliency:
x = torch.cat(atom_features_list)
else:
x = np.array(atom_features_list, dtype=np.int64)
# bonds
num_bond_features = 3 # bond type, bond stereo, is_conjugated
if len(mol.GetBonds()) > 0: # mol has bonds
edges_list = []
edge_features_list = []
for bond in mol.GetBonds():
i = bond.GetBeginAtomIdx()
j = bond.GetEndAtomIdx()
edge_feature = bond_to_feature_vector(bond)
# add edges in both directions
edges_list.append((i, j))
edge_features_list.append(edge_feature)
edges_list.append((j, i))
edge_features_list.append(edge_feature)
# data.edge_index: Graph connectivity in COO format with shape [2, num_edges]
edge_index = np.array(edges_list, dtype=np.int64).T
# data.edge_attr: Edge feature matrix with shape [num_edges, num_edge_features]
edge_attr = np.array(edge_features_list, dtype=np.int64)
else: # mol has no bonds
edge_index = np.empty((2, 0), dtype=np.int64)
edge_attr = np.empty((0, num_bond_features), dtype=np.int64)
return edge_attr, edge_index, x
def smiles_to_graph_advs(
smiles_string, args, advs=False, received_mol=False, saliency=False
):
"""
Converts SMILES string to graph Data object
:input: SMILES string (str)
:return: graph object
"""
if not received_mol:
mol = Chem.MolFromSmiles(smiles_string)
else:
mol = smiles_string
# atoms
atom_features_list = []
atom_feat_dims = get_atom_feature_dims()
for atom in mol.GetAtoms():
ftrs = atom_to_feature_vector(atom)
if saliency:
ftrs_oh = one_hot_vector_am(ftrs, atom_feat_dims)
atom_features_list.append(torch.unsqueeze(ftrs_oh, 0))
else:
atom_features_list.append(ftrs)
if saliency:
x = torch.cat(atom_features_list)
else:
x = np.array(atom_features_list, dtype=np.int64)
if advs:
# bonds
mol_edge_dict = {}
num_bond_features = 3 # bond type, bond stereo, is_conjugated
features_dim1 = torch.eye(5)
features_dim2 = torch.eye(6)
features_dim3 = torch.eye(2)
if len(mol.GetBonds()) > 0: # mol has bonds
edges_list = []
edge_features_list = []
for bond in mol.GetBonds():
i = bond.GetBeginAtomIdx()
j = bond.GetEndAtomIdx()
edge_feature = bond_to_feature_vector(bond)
# add edges in both directions
edges_list.append((i, j))
edges_list.append((j, i))
edge_feature_oh = one_hot_vector_sm(
edge_feature, features_dim1, features_dim2, features_dim3
)
if advs:
mol_edge_dict[(i, j)] = Variable(
torch.tensor([1.0]), requires_grad=True
)
# add edges in both directions
edge_features_list.append(
torch.unsqueeze(mol_edge_dict[(i, j)] * edge_feature_oh, 0)
)
edge_features_list.append(
torch.unsqueeze(mol_edge_dict[(i, j)] * edge_feature_oh, 0)
)
else:
# add edges in both directions
edge_features_list.append(torch.unsqueeze(edge_feature_oh, 0))
edge_features_list.append(torch.unsqueeze(edge_feature_oh, 0))
if advs:
# Update edge dict
args.edge_dict[smiles_string] = mol_edge_dict
# data.edge_index: Graph connectivity in COO format with shape [2, num_edges]
edge_index = np.array(edges_list, dtype=np.int64).T
# data.edge_attr: Edge feature matrix with shape [num_edges, num_edge_features]
edge_attr = torch.cat(edge_features_list)
else: # mol has no bonds
edge_index = np.empty((2, 0), dtype=np.int64)
edge_attr = np.empty((0, num_bond_features), dtype=np.int64)
args.edge_dict[smiles_string] = {}
return edge_attr, edge_index, x
def get_dataset(
dataset, use_prot=False, target=None, args=None, advs=False, saliency=False
):
total_dataset = []
if use_prot:
prot_graph = transform_molecule_pg(
target["Fasta"].item(), label=None, is_prot=use_prot
)
for mol, label in tqdm(
zip(dataset["Smiles"], dataset["Label"]), total=len(dataset["Smiles"])
):
if use_prot:
total_dataset.append([transform_molecule_pg(mol,label,args, advs, saliency=saliency),prot_graph])
else:
total_dataset.append(
transform_molecule_pg(mol, label, args, advs, saliency=saliency)
)
return total_dataset
def get_perturbed_dataset(mols, labels, args):
total_dataset = []
for mol, label in zip(mols, labels):
total_dataset.append(transform_molecule_pg(mol, label, args, received_mol=True))
return total_dataset
def transform_molecule_pg(
smiles,
label,
args=None,
advs=False,
received_mol=False,
saliency=False,
is_prot=False,
):
if is_prot:
edge_attr_p, edge_index_p, x_p = smiles_to_graph(smiles, is_prot)
x_p = torch.tensor(x_p)
edge_index_p = torch.tensor(edge_index_p)
edge_attr_p = torch.tensor(edge_attr_p)
return Data(edge_attr=edge_attr_p, edge_index=edge_index_p, x=x_p)
else:
if args.advs or received_mol:
if advs or received_mol:
edge_attr, edge_index, x = smiles_to_graph_advs(
smiles,
args,
advs=True,
received_mol=received_mol,
saliency=saliency,
)
else:
edge_attr, edge_index, x = smiles_to_graph_advs(
smiles, args, received_mol=received_mol, saliency=saliency
)
else:
edge_attr, edge_index, x = smiles_to_graph(smiles, saliency=saliency)
if not saliency:
x = torch.tensor(x)
y = torch.tensor([label])
edge_index = torch.tensor(edge_index)
if not args.advs and not received_mol:
edge_attr = torch.tensor(edge_attr)
if received_mol:
mol = smiles
else:
mol = Chem.MolFromSmiles(smiles)
return Data(
edge_attr=edge_attr, edge_index=edge_index, x=x, y=y, mol=mol, smiles=smiles
)
|