-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils_data.py
297 lines (234 loc) · 10.2 KB
/
utils_data.py
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
"""## utils.py"""
import os
import sys
import numpy as np
from math import sqrt
from scipy import stats
from sklearn.metrics import r2_score
from torch_geometric.data import InMemoryDataset
# from torch_geometric.loader import DataLoader # for pyg >= 2.0
# pyg < 2, seems also works on pyg >= 2.0
from torch_geometric.data import DataLoader
from torch_geometric import data as DATA
import torch
import matplotlib.pyplot as plt
class TestbedDataset(InMemoryDataset):
def __init__(self, root='root_folder', dataset='davis',
xd=None, xt=None, y=None, transform=None,
pre_transform=None, smile_graph=None, saliency_map=False, testing=False, dgl=None, cosl=None):
super(TestbedDataset, self).__init__(root, transform, pre_transform)
self.dataset = dataset
self.saliency_map = saliency_map
self.testing = testing
if (self.testing):
self.process(xd, xt, y, smile_graph, dgl, cosl)
elif os.path.isfile(self.processed_paths[0]):
print(
'Pre-processed data found: {}, loading ...'.format(self.processed_paths[0]))
self.data, self.slices = torch.load(self.processed_paths[0])
else:
print(
'Pre-processed data {} not found, doing pre-processing...'.format(self.processed_paths[0]))
self.process(xd, xt, y, smile_graph, dgl, cosl)
self.data, self.slices = torch.load(self.processed_paths[0])
@property
def raw_file_names(self):
pass
@property
def processed_file_names(self):
return [self.dataset + '.pt']
def download(self):
# Download to `self.raw_dir`.
pass
def _download(self):
pass
def _process(self):
if not os.path.exists(self.processed_dir):
os.makedirs(self.processed_dir)
'''
def process(self, xd, xt, y, smile_graph):
## xd : smile,
## cx : np array of 735 mutation values,
## y : IC50 value
## smile_graph : dictionary keys : smile, and values : 4_drug_outputs (num of mols, 72 features, edges, graph)
assert (len(xd) == len(xt) and len(xt) == len(y)), "The three lists must be the same length!"
data_list = []
data_len = len(xd)
for i in range(data_len):
if ((i%2000 == 0 or i+1 == data_len) and (not self.testing)):
print('Converting SMILES to graph: {}/{}'.format(i+1, data_len))
smiles = xd[i]
target = xt[i]
labels = y[i]
c_size, features, edge_index, edge_features, this_graph = smile_graph[smiles]
if len(edge_index) == 0:
print('smiles with no graph: ', smiles)
# print(edge_index)
# print(edge_features)
# make the graph ready for PyTorch Geometrics GCN algorithms:
if (self.testing):
ptr_F =torch.tensor([0, int(c_size)])
batch_F = torch.zeros((int(c_size)), dtype = int)
GCNData = DATA.Data(x=torch.Tensor(features),
edge_index=torch.LongTensor(edge_index).transpose(1, 0),
y=torch.FloatTensor([labels]), batch = batch_F, ptr = ptr_F)
else:
GCNData = DATA.Data(x=torch.Tensor(features), ## rid_00
edge_index=torch.LongTensor(edge_index).transpose(1, 0), ## rid_01
edge_features=torch.Tensor(edge_features),
y=torch.FloatTensor([labels])) ## rid_02 tensor([0.6563])
# require_grad of cell-line for saliency map
if self.saliency_map == True:
GCNData.target = torch.tensor([target], dtype=torch.float, requires_grad=True)
else:
GCNData.target = torch.FloatTensor([target]) ## rid_03
GCNData.__setitem__('c_size', torch.LongTensor([c_size]))
# append graph, label and target sequence to data list
data_list.append(GCNData)
if (self.testing):
ptr_F =torch.tensor([0, int(c_size)])
batch_F = torch.zeros((int(c_size)), dtype = int)
if self.pre_filter is not None:
data_list = [data for data in data_list if self.pre_filter(data)]
if self.pre_transform is not None:
data_list = [self.pre_transform(data) for data in data_list]
if (self.testing):
return data_list ## nico utils
print('Graph construction done. Saving to file.')
bts = sys.getsizeof(data_list)
print(f"data_list: {bts} bytes")
print(f"data_list: {bts/1000000} mb")
print(f"data_list: {bts/1000000000} gb")
print(f"len(data_list): {len(data_list)}")
print(f"type(data_list[0]): {type(data_list[0])}")
data, slices = self.collate(data_list)
if (self.testing):
return (data, slices) ## nico utils
print(" Saved to file.")
# save preprocessed data:
torch.save((data, slices), self.processed_paths[0])
print(" Complete.")
'''
def process(self, xd, xt, y, smile_graph, dgl, cosl):
# xd : smile,
# cx : np array of 735 mutation values,
# y : IC50 value
# smile_graph : dictionary keys : smile, and values : 4_drug_outputs (num of mols, 72 features, edges, graph)
assert (len(xd) == len(xt) and len(xt) == len(
y)), "The three lists must be the same length!"
data_list = []
data_len = len(xd)
for i in range(data_len):
if ((i % 2000 == 0 or i+1 == data_len) and (not self.testing)):
print('Converting SMILES to graph: {}/{}'.format(i+1, data_len))
smiles = xd[i]
target = xt[i]
labels = y[i]
dg_name = dgl[i]
cos_name = cosl[i]
c_size, features, edge_index, edge_features, this_graph = smile_graph[smiles]
# make the graph ready for PyTorch Geometrics GCN algorithms:
if (self.testing):
ptr_F = torch.tensor([0, int(c_size)])
batch_F = torch.zeros((int(c_size)), dtype=int)
GCNData = DATA.Data(x=torch.Tensor(features),
edge_index=torch.LongTensor(
edge_index).transpose(1, 0),
y=torch.FloatTensor([labels]), batch=batch_F, ptr=ptr_F, smiles=smiles, drug_name=dg_name, cell_line_name=cos_name)
else:
GCNData = DATA.Data(x=torch.Tensor(features), # rid_00
edge_index=torch.LongTensor(
edge_index).transpose(1, 0), # rid_01
edge_features=torch.Tensor(
edge_features),
y=torch.FloatTensor([labels]), smiles=smiles, drug_name=dg_name, cell_line_name=cos_name) # rid_02 tensor([0.6563])
# require_grad of cell-line for saliency map
if self.saliency_map == True:
GCNData.target = torch.tensor(
[target], dtype=torch.float, requires_grad=True)
else:
GCNData.target = torch.FloatTensor([target]) # rid_03
GCNData.__setitem__('c_size', torch.LongTensor([c_size]))
# append graph, label and target sequence to data list
data_list.append(GCNData)
if (self.testing):
ptr_F = torch.tensor([0, int(c_size)])
batch_F = torch.zeros((int(c_size)), dtype=int)
if self.pre_filter is not None:
data_list = [data for data in data_list if self.pre_filter(data)]
if self.pre_transform is not None:
data_list = [self.pre_transform(data) for data in data_list]
if (self.testing):
return data_list # nico utils
print('Graph construction done. Saving to file.')
bts = sys.getsizeof(data_list)
print(f"data_list: {bts} bytes")
print(f"data_list: {bts/1000000} mb")
print(f"data_list: {bts/1000000000} gb")
print(f"len(data_list): {len(data_list)}")
print(f"type(data_list[0]): {type(data_list[0])}")
data, slices = self.collate(data_list)
if (self.testing):
return (data, slices) # nico utils
print(" Saved to file.")
# save preprocessed data:
torch.save((data, slices), self.processed_paths[0])
print(" Complete.")
def getXD(self):
return self.xd
def rmse(y, f):
rmse = sqrt(((y - f)**2).mean(axis=0))
return rmse
def mse(y, f):
mse = ((y - f)**2).mean(axis=0)
return mse
def pearson(y, f):
rp = np.corrcoef(y, f)[0, 1]
return rp
def spearman(y, f):
rs = stats.spearmanr(y, f)[0]
return rs
def coeffi_determ(y, f):
r2 = r2_score(y, f)
return r2
def ci(y, f):
ind = np.argsort(y)
y = y[ind]
f = f[ind]
i = len(y)-1
j = i-1
z = 0.0
S = 0.0
while i > 0:
while j >= 0:
if y[i] > y[j]:
z = z+1
u = f[i] - f[j]
if u > 0:
S = S + 1
elif u == 0:
S = S + 0.5
j = j - 1
i = i - 1
j = i-1
ci = S/z
return ci
def draw_loss(train_losses, test_losses, title):
plt.figure()
plt.plot(train_losses, label='train loss')
plt.plot(test_losses, label='test loss')
plt.title(title)
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
# save image
plt.savefig(title+".png")
def draw_pearson(pearsons, title):
plt.figure()
plt.plot(pearsons, label='test pearson')
plt.title(title)
plt.xlabel('Epoch')
plt.ylabel('Pearson')
plt.legend()
# save image
plt.savefig(title+".png")