-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathget_data.py
366 lines (302 loc) · 13.3 KB
/
get_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
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
from sklearn.model_selection import KFold
from rdkit import Chem
from representation import Representation
import pandas as pd
import numpy as np
import sys
class GetData:
def __init__(self, L, cell_line, descriptor='jtvae', n_fold=5, random_state=0, random_genes=False,
csv_file="", useChirality=False):
"""
Parameters
-----------
L: dictionary from L1000CDS_subset.json
cell_line: cell_id
params:
string: 'VCAP', 'A549', 'A375', 'PC3', 'MCF7', 'HT29', etc.
descriptor: descriptor for chemical compounds.
params:
string: 'ecfp', 'ecfp_autoencoder', 'maccs', 'topological', 'shed', 'cats2d', 'jtvae'(default)
n_fold: number of folds
params:
int: 5(default)
random_state: random_state for Kfold
params:
int: 0(default)
random_genes: if it is true, returns random 20 genes from target values
params:
bool: False(default)
list of random genes: [118, 919, 274, 866, 354, 253, 207, 667, 773, 563,
553, 918, 934, 81, 56, 232, 892, 485, 30, 53]
csv_file: if it is not empty, representation data used from this file
params:
string: "<csv_file_path>"
"""
self.L = L
self.cell_line = cell_line
self.descriptor = descriptor
self.n_fold = n_fold
self.random_state = random_state
self.random_genes = random_genes
self.csv_file = csv_file
self.useChirality = useChirality
if self.useChirality and self.descriptor != 'ecfp':
sys.exit('useChirality parameter is only usable with ecfp descriptor.')
self.random_index_list = [118, 919, 274, 866, 354, 253, 207, 667, 773, 563,
553, 918, 934, 81, 56, 232, 892, 485, 30, 53]
self.LmGenes = []
self.meta_smiles = pd.read_csv('meta_SMILES.csv')
file_path = 'LmGenes.txt'
with open(file_path) as fp:
line = fp.readline()
while line:
self.LmGenes.append(line.strip())
line = fp.readline()
self.rep = Representation(self.descriptor)
def get_regression_data(self):
X = []
Y = []
perts = []
unique_smiles = []
counter = 0
length = len(self.L[self.cell_line])
print('Getting data...')
data = None
if len(self.csv_file) != 0:
data = pd.read_csv(self.csv_file)
for pert_id in self.L[self.cell_line]:
counter += 1
if counter % 10 == 0:
print('%.1f %% \r' % (counter / length * 100), end=""),
smiles = self.meta_smiles[self.meta_smiles['pert_id'] == pert_id]['SMILES'].values[0]
if str(smiles) == 'nan' or str(smiles) == '-666':
continue
if not self.useChirality:
mol = Chem.MolFromSmiles(smiles)
canonical_smiles = Chem.MolToSmiles(mol, isomericSmiles=False)
else:
canonical_smiles = smiles
if canonical_smiles in unique_smiles or len(canonical_smiles) > 120:
continue
if data is not None:
if data[data['pert_id'] == pert_id].empty:
continue
else:
feature = data[data['pert_id'] == pert_id].drop(['pert_id'], axis=1).values[0].tolist()
else:
feature = self.rep.get_representation(smiles=canonical_smiles, descriptor=self.descriptor,
useChirality=self.useChirality)
unique_smiles.append(canonical_smiles)
labels = self.L[self.cell_line][pert_id]['chdirLm']
X.append(feature)
Y.append(labels)
perts.append(pert_id)
x = np.asarray(X)
y = np.asarray(Y)
x_columns = ['SMILES']
if self.descriptor == 'ecfp':
for i in range(x.shape[1]-1):
x_columns.append('ecfp_' + str(i + 1))
elif self.descriptor == 'ecfp_autoencoder':
for i in range(x.shape[1]-1):
x_columns.append('ecfp_autoencoder_' + str(i + 1))
elif self.descriptor == 'topological':
for i in range(x.shape[1]-1):
x_columns.append('topological_' + str(i + 1))
elif self.descriptor == 'maccs':
for i in range(x.shape[1]-1):
x_columns.append('maccs_' + str(i + 1))
elif self.descriptor == 'jtvae':
for i in range(x.shape[1]-1):
x_columns.append('jtvae_' + str(i + 1))
elif self.descriptor == 'shed':
for i in range(x.shape[1]-1):
x_columns.append('shed_' + str(i + 1))
elif self.descriptor == 'cats2d':
for i in range(x.shape[1]-1):
x_columns.append('cats2d_' + str(i + 1))
x = pd.DataFrame(x, index=perts, columns=x_columns)
y = pd.DataFrame(y, index=perts)
folds = list(KFold(self.n_fold, shuffle=True, random_state=self.random_state).split(x))
if self.random_genes:
y_random = []
for i in self.random_index_list:
y_random.append(y.iloc[:, i:i + 1])
df = y_random[0]
for i in range(len(y_random) - 1):
df = pd.concat([df, y_random[i + 1]], axis=1)
y = df
print('\nDone.')
return x, y, folds
def get_up_genes(self):
X = []
Y = []
perts = []
unique_smiles = []
counter = 0
length = len(self.L[self.cell_line])
print('Getting data...')
class_dict = {}
data = None
if len(self.csv_file) != 0:
data = pd.read_csv(self.csv_file)
for gene in self.LmGenes:
class_dict.update({gene: 0})
for pert_id in self.L[self.cell_line]:
counter += 1
if counter % 10 == 0:
print('%.1f %% \r' % (counter / length * 100), end=""),
if 'upGenes' not in self.L[self.cell_line][pert_id]:
continue
smiles = self.meta_smiles[self.meta_smiles['pert_id'] == pert_id]['SMILES'].values[0]
if str(smiles) == 'nan' or str(smiles) == '-666':
continue
if not self.useChirality:
mol = Chem.MolFromSmiles(smiles)
canonical_smiles = Chem.MolToSmiles(mol, isomericSmiles=False)
else:
canonical_smiles = smiles
if canonical_smiles in unique_smiles or len(canonical_smiles) > 120:
continue
if data is not None:
if data[data['pert_id'] == pert_id].empty:
continue
else:
feature = data[data['pert_id'] == pert_id].drop(['pert_id'], axis=1).values[0].tolist()
else:
feature = self.rep.get_representation(smiles=canonical_smiles, descriptor=self.descriptor,
useChirality=self.useChirality)
unique_smiles.append(canonical_smiles)
up_genes = list(set(self.L[self.cell_line][pert_id]['upGenes']))
class_dict = dict.fromkeys(class_dict, 0)
for gene in up_genes:
if gene in class_dict:
class_dict.update({gene: 1})
labels = np.fromiter(class_dict.values(), dtype=int)
X.append(feature)
Y.append(labels)
perts.append(pert_id)
x = np.asarray(X)
y = np.asarray(Y)
x_columns = ['SMILES']
y_columns = list(class_dict.keys())
if self.descriptor == 'ecfp':
for i in range(x.shape[1]-1):
x_columns.append('ecfp_' + str(i + 1))
elif self.descriptor == 'ecfp_autoencoder':
for i in range(x.shape[1]-1):
x_columns.append('ecfp_autoencoder_' + str(i + 1))
elif self.descriptor == 'topological':
for i in range(x.shape[1]-1):
x_columns.append('topological_' + str(i + 1))
elif self.descriptor == 'maccs':
for i in range(x.shape[1]-1):
x_columns.append('maccs_' + str(i + 1))
elif self.descriptor == 'jtvae':
for i in range(x.shape[1]-1):
x_columns.append('jtvae_' + str(i + 1))
elif self.descriptor == 'shed':
for i in range(x.shape[1]-1):
x_columns.append('shed_' + str(i + 1))
elif self.descriptor == 'cats2d':
for i in range(x.shape[1]-1):
x_columns.append('cats2d_' + str(i + 1))
x = pd.DataFrame(x, index=perts, columns=x_columns)
y = pd.DataFrame(y, index=perts, columns=y_columns)
folds = list(KFold(self.n_fold, shuffle=True, random_state=self.random_state).split(x))
if self.random_genes:
y_random = []
for i in self.random_index_list:
y_random.append(y.iloc[:, i:i + 1])
df = y_random[0]
for i in range(len(y_random) - 1):
df = pd.concat([df, y_random[i + 1]], axis=1)
y = df
print('\nDone.')
return x, y, folds
def get_down_genes(self):
X = []
Y = []
perts = []
unique_smiles = []
counter = 0
length = len(self.L[self.cell_line])
print('Getting data...')
class_dict = {}
data = None
if len(self.csv_file) != 0:
data = pd.read_csv(self.csv_file)
for gene in self.LmGenes:
class_dict.update({gene: 0})
for pert_id in self.L[self.cell_line]:
counter += 1
if counter % 10 == 0:
print('%.1f %% \r' % (counter / length * 100), end=""),
if 'dnGenes' not in self.L[self.cell_line][pert_id]:
continue
smiles = self.meta_smiles[self.meta_smiles['pert_id'] == pert_id]['SMILES'].values[0]
if str(smiles) == 'nan' or str(smiles) == '-666':
continue
if not self.useChirality:
mol = Chem.MolFromSmiles(smiles)
canonical_smiles = Chem.MolToSmiles(mol, isomericSmiles=False)
else:
canonical_smiles = smiles
if canonical_smiles in unique_smiles or len(canonical_smiles) > 120:
continue
if data is not None:
if data[data['pert_id'] == pert_id].empty:
continue
else:
feature = data[data['pert_id'] == pert_id].drop(['pert_id'], axis=1).values[0].tolist()
else:
feature = self.rep.get_representation(smiles=canonical_smiles, descriptor=self.descriptor,
useChirality=self.useChirality)
unique_smiles.append(canonical_smiles)
dn_genes = list(set(self.L[self.cell_line][pert_id]['dnGenes']))
class_dict = dict.fromkeys(class_dict, 0)
for gene in dn_genes:
if gene in class_dict:
class_dict.update({gene: 1})
labels = np.fromiter(class_dict.values(), dtype=int)
X.append(feature)
Y.append(labels)
perts.append(pert_id)
x = np.asarray(X)
y = np.asarray(Y)
x_columns = ['SMILES']
y_columns = list(class_dict.keys())
if self.descriptor == 'ecfp':
for i in range(x.shape[1]-1):
x_columns.append('ecfp_' + str(i + 1))
elif self.descriptor == 'ecfp_autoencoder':
for i in range(x.shape[1]-1):
x_columns.append('ecfp_autoencoder_' + str(i + 1))
elif self.descriptor == 'topological':
for i in range(x.shape[1]-1):
x_columns.append('topological_' + str(i + 1))
elif self.descriptor == 'maccs':
for i in range(x.shape[1]-1):
x_columns.append('maccs_' + str(i + 1))
elif self.descriptor == 'jtvae':
for i in range(x.shape[1]-1):
x_columns.append('jtvae_' + str(i + 1))
elif self.descriptor == 'shed':
for i in range(x.shape[1]-1):
x_columns.append('shed_' + str(i + 1))
elif self.descriptor == 'cats2d':
for i in range(x.shape[1]-1):
x_columns.append('cats2d_' + str(i + 1))
x = pd.DataFrame(x, index=perts, columns=x_columns)
y = pd.DataFrame(y, index=perts, columns=y_columns)
folds = list(KFold(self.n_fold, shuffle=True, random_state=self.random_state).split(x))
if self.random_genes:
y_random = []
for i in self.random_index_list:
y_random.append(y.iloc[:, i:i + 1])
df = y_random[0]
for i in range(len(y_random) - 1):
df = pd.concat([df, y_random[i + 1]], axis=1)
y = df
print('\nDone.')
return x, y, folds