-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbuild.py
207 lines (167 loc) · 9.94 KB
/
build.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
#!/usr/bin/env python
import pandas as pd
import numpy as np
import argparse
from pathlib import Path
from functools import reduce
from sklearn.preprocessing import StandardScaler
# input files
base_data_dir = './data'
response_path = Path('./data/combined_single_response_agg')
cell_cancer_types_map_path = Path('./data/combined_cancer_types')
drug_list_path = Path('./data/drugs_1800')
def parse_arguments(model_name=''):
parser = argparse.ArgumentParser()
parser.add_argument('--top_n', type=int, default=6,
help='Number of cancer types to be included. Default 6')
parser.add_argument('--drug_descriptor', type=str, default='dragon7',
choices=['dragon7', 'mordred'],
help='Drug descriptors. Default dragon7')
parser.add_argument('--cell_feature', default='rnaseq',
choices=['rnaseq', 'snps'],
help='Cell line features. Default rnaseq')
parser.add_argument('--cell_feature_subset', default='lincs1000',
choices=['lincs1000', 'oncogenes', 'all'],
help='Subset of cell line features. Default lincs1000')
parser.add_argument('--format', default='hdf5',
choices=['csv', 'tsv', 'parquet', 'hdf5', 'feather'],
help='Dataframe file format. Default hdf5')
parser.add_argument('--response_type', default='reg',
choices=['reg', 'bin'],
help='Response type. Regression(reg) or Binary Classification(bin). Default reg')
parser.add_argument('--labels', action='store_true',
help='Contains Cell and Drug label. Default False')
parser.add_argument('--target', type=str, default='AUC',
choices=['AUC', 'IC50', 'EC50', 'EC50se', 'R2fit', 'Einf', 'HS', 'AAC1', 'AUC1', 'DSS1'],
help='Response label value. Default AUC')
parser.add_argument('--scaled', action='store_true',
help='Apply scaling. Default False')
parser.add_argument('--drop_bad_fit_by_percent', type=int, default=0,
help='Drop samples where R2fit below this percentage. Default 0')
parser.add_argument('--drop_bad_fit_by_threshold', type=float, default=None,
help='Drop samples where R2fit below this threshold. Default None')
parser.add_argument('--debug', action='store_true',
help='Keep original target value.')
args, unparsed = parser.parse_known_args()
return args, unparsed
def check_file(filepath):
print("checking {}".format(filepath))
status = filepath.is_file()
if status is False:
print("File {} is not found in data dir.".format(filepath))
return status
def check_data_files(args):
filelist = [response_path, cell_cancer_types_map_path, drug_list_path, get_cell_feature_path(args), get_drug_descriptor_path(args)]
return reduce((lambda x, y: x & y), map(check_file, filelist))
def get_cell_feature_path(args):
if args.cell_feature_subset == 'all':
filename = 'combined_{}_data_combat'.format(args.cell_feature)
else:
filename = 'combined_{}_data_{}_combat'.format(args.cell_feature, args.cell_feature_subset)
return Path(base_data_dir, filename)
def get_drug_descriptor_path(args):
filename = 'combined_{}_descriptors'.format(args.drug_descriptor)
return Path(base_data_dir, filename)
def build_file_basename(args):
filename = f'top_{args.top_n}.res_{args.response_type}.cf_{args.cell_feature}.dd_{args.drug_descriptor}'
if args.labels:
filename += '.labeled'
if args.scaled:
filename += '.scaled'
if args.drop_bad_fit_by_percent > 0:
filename += f'.r{args.drop_bad_fit_by_percent}'
if args.drop_bad_fit_by_threshold:
filename += f'.r{args.drop_bad_fit_by_threshold}'
if args.debug:
filename += '.debug'
return filename
def build_filename(args):
return "{}.{}".format(build_file_basename(args), args.format)
def build_dataframe(args):
# Identify Top N cancer types with targeted drug list (1800 drugs)
df_response = pd.read_csv(response_path, sep='\t', engine='c', low_memory=False)
drug_list = pd.read_csv(drug_list_path)['DRUG'].to_list()
df_response = df_response[df_response.DRUG.isin(drug_list)]
df_uniq_cl_drugs = df_response[['CELL', 'DRUG']].drop_duplicates().reset_index(drop=True)
df_cl_cancer_map = pd.read_csv(cell_cancer_types_map_path, sep='\t', header=None, names=['CELL', 'CANCER_TYPE'])
df_cl_cancer_map.set_index('CELL')
df_cl_cancer_drug = df_cl_cancer_map.merge(df_uniq_cl_drugs, on='CELL', how='inner', sort='true')
top_n_cancer_types = df_cl_cancer_drug.CANCER_TYPE.value_counts().head(args.top_n).index.to_list()
print("Identified {} cancer types: ".format(args.top_n), top_n_cancer_types)
# Indentify cell lines associated with the target cancer types
df_cl = df_cl_cancer_drug[df_cl_cancer_drug['CANCER_TYPE'].isin(top_n_cancer_types)][['CELL']].drop_duplicates().reset_index(drop=True)
# Identify drugs associated with the target cancer type & filtered by drug_list
df_drugs = df_cl_cancer_drug[df_cl_cancer_drug['CANCER_TYPE'].isin(top_n_cancer_types)][['DRUG']].drop_duplicates().reset_index(drop=True)
# Filter response by cell lines (4882) and drugs (1779)
cl_filter = df_cl.CELL.to_list()
dr_filter = df_drugs.DRUG.to_list()
target = args.target
df_response = df_response[df_response.CELL.isin(cl_filter) & df_response.DRUG.isin(dr_filter)][['CELL', 'DRUG', target, 'R2fit']].drop_duplicates().reset_index(drop=True)
df_response[target] = df_response[target].astype(dtype=np.float32)
if args.drop_bad_fit_by_percent > 0:
cutoff = int(len(df_response) * (100 - args.drop_bad_fit_by_percent) / 100)
df_drop = df_response.sort_values('R2fit', ascending=False)[cutoff:]
df_drop.to_parquet('dropped.parquet')
df_response = df_response.sort_values('R2fit', ascending=False)[:cutoff]
print("Filter samples on R2fit (>{}) and dropped {} responses.".format(args.drop_bad_fit_by_percent, len(df_drop)))
elif args.drop_bad_fit_by_threshold is not None:
df_response.drop(df_response[df_response.R2fit < args.drop_bad_fit_by_threshold].index, inplace=True)
if args.response_type == 'bin':
if args.debug:
df_response_debug = df_response[[target, 'R2fit']]
df_response[target] = df_response[target].apply(lambda x: 1 if x < 0.5 else 0)
df_response = df_response.drop_duplicates()
df_disagree = df_response[df_response.duplicated(['CELL', 'DRUG'])]
df_disagree.insert(loc=3, column='Sample', value=df_disagree.CELL.map(str) + '__' + df_disagree.DRUG.map(str))
df_response.insert(loc=3, column='Sample', value=df_response.CELL.map(str) + '__' + df_response.DRUG.map(str))
df_response.drop(df_response[df_response.Sample.isin(df_disagree.Sample)].index, inplace=True)
df_response.drop(columns=['Sample'], inplace=True)
if args.debug:
df_response['R2fit'] = df_response_debug[df_response_debug.index.isin(df_response.index)]['R2fit']
df_response[f'{target}_raw'] = df_response_debug[df_response_debug.index.isin(df_response.index)][target]
df_response.reset_index(drop=True, inplace=True)
# Join response data with Drug descriptor & RNASeq
df_rnaseq = pd.read_csv(get_cell_feature_path(args), sep='\t', low_memory=False)
df_rnaseq = df_rnaseq[df_rnaseq['Sample'].isin(cl_filter)].reset_index(drop=True)
df_rnaseq.rename(columns={'Sample': 'CELL'}, inplace=True)
df_rnaseq.columns = ['GE_' + x if i > 0 else x for i, x in enumerate(df_rnaseq.columns.to_list())]
df_rnaseq = df_rnaseq.set_index(['CELL'])
df_descriptor = pd.read_csv(get_drug_descriptor_path(args), sep='\t', low_memory=False, na_values='na')
df_descriptor = df_descriptor[df_descriptor.DRUG.isin(dr_filter)].set_index(['DRUG']).fillna(0.0)
df_descriptor = df_descriptor.astype(dtype=np.float32)
if args.scaled:
scaler = StandardScaler()
df_rnaseq[df_rnaseq.columns] = scaler.fit_transform(df_rnaseq[df_rnaseq.columns]).astype(dtype=np.float32)
df_descriptor[df_descriptor.columns] = scaler.fit_transform(df_descriptor[df_descriptor.columns]).astype(dtype=np.float32)
df = df_response.merge(df_rnaseq, on='CELL', how='left', sort='true')
df.set_index(['DRUG'])
df_final = df.merge(df_descriptor, on='DRUG', how='left', sort='true')
if args.labels:
if args.debug:
df_final_deduped = df_final.drop(columns=['CELL', 'DRUG', target, f'{target}_raw', 'R2fit']).drop_duplicates()
else:
df_final_deduped = df_final.drop(columns=['CELL', 'DRUG', target]).drop_duplicates()
df_final = df_final[df_final.index.isin(df_final_deduped.index)]
df_final.reset_index(drop=True, inplace=True)
else:
df_final.drop(columns=['CELL', 'DRUG'], inplace=True)
df_final.drop_duplicates(inplace=True)
print("Dataframe is built with total {} rows.".format(len(df_final)))
save_filename = build_filename(args)
print("Saving to {}".format(save_filename))
if args.format == 'feather':
df_final.to_feather(save_filename)
elif args.format == 'csv':
df_final.to_csv(save_filename, float_format='%g', index=False)
elif args.format == 'tsv':
df_final.to_csv(save_filename, sep='\t', float_format='%g', index=False)
elif args.format == 'parquet':
df_final.to_parquet(save_filename, index=False)
elif args.format == 'hdf5':
df_cl.to_csv(build_file_basename(args) + '_cellline.txt', header=False, index=False)
df_drugs.to_csv(build_file_basename(args) + '_drug.txt', header=False, index=False)
df_final.to_hdf(save_filename, key='df', mode='w', complib='blosc:snappy', complevel=9)
if __name__ == '__main__':
FLAGS, unparsed = parse_arguments()
if check_data_files(FLAGS):
build_dataframe(FLAGS)