-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathanalyze_output.py
264 lines (222 loc) · 7 KB
/
analyze_output.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
"""
Filename: visualize.py
Authors:
Jason Youn -jyoun@ucdavis.edu
Description:
Visualize data in multiples ways as requested by the user.
To-do:
"""
# import from generic packages
import os
import warnings
import argparse
import logging as log
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
from sklearn.cluster import SpectralBiclustering
# default arguments
DEFAULT_DATA_DIR_STR = '../output'
DEFAULT_ENTITY_FULL_NAMES_FILENAME = 'entity_full_names.txt'
DEFAULT_KNOWLEDGE_GRAPH_FILENAME = 'kg_final.txt'
# drop these columns because it's not necessary for network training
COLUMN_NAMES_TO_DROP = ['Belief', 'Source size', 'Sources']
SORT_ANTIBIOTIC = [
'5-Nitro-2-furaldehyde semicarbazone',
'Furaltadone',
'Amoxicillin',
'Ampicillin',
'Aztreonam',
'Cefamandole',
'Cefazolin',
'Cefoxitin',
'Cefuroxime',
'Cefsulodin',
'Ceftazidime',
'Cephalothin',
'Cerulenin',
'Ciprofloxacin',
'Levofloxacin',
'Lomefloxacin',
'Norfloxacin',
'Ofloxacin',
'Enoxacin',
'Nalidixic acid',
'Metronidazole',
'Ornidazole',
'Tinidazole',
'Mitomycin C',
'Nitrofurantoin',
'Spectinomycin',
'Streptonigrin',
'Thiolactomycin',
'Amikacin',
'Kanamycin',
'Tobramycin',
'Neomycin',
'Paromomycin',
'Apramycin',
'Dihydrostreptomycin',
'Geneticin',
'Gentamicins',
'Sisomicin',
'Streptomycin',
'Azithromycin',
'Clarythromycin',
'Erythromycin',
'Hygromycin B',
'Josamycin',
'Oleandomycin',
'Spiramycin',
'Troleandomycin',
'Tylosin',
'Novobiocin',
'Nigericin',
'Bicyclomycin',
'Cefmetazole',
'Cephradine',
'Moxalactam',
'Lincomycin',
'Mecillinam',
'Blasticidin S',
'Capreomycin',
'Carbenicillin',
'Cloxacillin',
'Nafcillin',
'Oxacillin',
'Penicillin G',
'Phenethicillin',
'Vancomycin',
'Cefoperazone',
'Piperacillin',
'Bleomycin',
'Dactinomycin',
'Fosfomycin',
'Chloramphenicol',
'Oxycarboxin',
'Radicicol',
'Sulfachloropyridazine',
'Sulfadiazine',
'Sulfamethazine',
'Sulfamethizole',
'Sulfamethoxazole',
'Sulfamonomethoxine',
'Sulfanilamide',
'Sulfathiazole',
'Sulfisoxazole',
'Triclosan',
'Trimethoprim',
'Chlortetracycline',
'Doxycycline',
'Doxycycline hyclate',
'Minocycline',
'Oxytetracycline',
'Penimepicycline',
'Rolitetracycline',
'Tetracycline',
'Rifampin',
'Rifamycin SV',
'Fusidic acid',
'Puromycin',
'CHIR090',
'Phleomycin',
'Polymyxin B',
'Tunicamycin',
'Hygromycin ',
'Bacitracin',
'Colistin',
'Doxorubicin']
def set_logging():
"""
Configure logging.
"""
log.basicConfig(format='(%(levelname)s) %(filename)s: %(message)s', level=log.DEBUG)
# set logging level to WARNING for matplotlib
logger = log.getLogger('matplotlib')
logger.setLevel(log.WARNING)
def parse_argument():
"""
Parse input arguments.
Returns:
- parsed arguments
"""
parser = argparse.ArgumentParser(description='Visualize data.')
parser.add_argument(
'--data_dir',
default=DEFAULT_DATA_DIR_STR,
help='Path to the file data_path_file.txt')
return parser.parse_args()
def save_cra_matrix(pd_known_cra, pd_genes, pd_antibiotics):
pd_pivot_table = pd.pivot_table(
pd_known_cra[['Subject', 'Predicate', 'Object']],
index='Subject',
columns='Object',
values='Predicate',
aggfunc='first')
genes_not_in_cra_triples = list(set(pd_genes.values) - set(pd_pivot_table.index.values))
antibiotics_not_in_cra_triples = list(set(pd_antibiotics.values) - set(pd_pivot_table.columns.values))
if genes_not_in_cra_triples:
pd_pivot_table = pd_pivot_table.reindex(index=pd_pivot_table.index.union(genes_not_in_cra_triples))
if antibiotics_not_in_cra_triples:
pd_pivot_table = pd_pivot_table.reindex(columns=pd_pivot_table.columns.union(antibiotics_not_in_cra_triples))
# pd_pivot_table.to_excel('/home/jyoun/Jason/UbuntuShare/heatmap.xlsx')
return pd_pivot_table
def plot_heatmap(pd_pivot_table):
pd_pivot_table = pd_pivot_table.replace('confers resistance to antibiotic', 1)
pd_pivot_table = pd_pivot_table.replace('confers no resistance to antibiotic', -1)
pd_pivot_table = pd_pivot_table[pd_pivot_table.columns].astype(float)
pd_pivot_table = pd_pivot_table.fillna(0)
pd_pivot_table = pd_pivot_table.transpose()
pd_pivot_table = pd_pivot_table.reset_index()
pd_pivot_table['Object'] = pd.Categorical(pd_pivot_table['Object'], SORT_ANTIBIOTIC)
pd_pivot_table = pd_pivot_table.sort_values('Object')
antibiotics = pd_pivot_table['Object'].to_numpy().tolist()
pd_pivot_table = pd_pivot_table.set_index('Object')
# build the figure instance with the desired height
fig, ax = plt.subplots(figsize=(40, 15))
# generate heatmap
myColors = [(1, 0.6, 0.6), (1, 1, 1), (0, 0, 0.7)]
cmap = LinearSegmentedColormap.from_list('custom', myColors, len(myColors))
ax = sns.heatmap(pd_pivot_table, cmap=cmap, ax=ax)
# x, y axis labels
# ax.yaxis.set_label_coords(0.5, -0.04)
# ax.xaxis.set_label_coords(-0.02, 0.5)
ax.set_xticks([])
ax.set_yticks([])
plt.savefig('/home/jyoun/Jason/UbuntuShare/heatmap.png', dpi=600, transparent=True)
def main():
"""
Main function.
"""
# set log and parse args
set_logging()
args = parse_argument()
# read full names dataframe
pd_entities = pd.read_csv(
os.path.join(args.data_dir, DEFAULT_ENTITY_FULL_NAMES_FILENAME),
sep='\n',
names=['Full name'])
# split full names
pd_entities = pd_entities['Full name'].str.split(':', n=2, expand=True)
pd_entities.columns = ['Global', 'Type', 'Name']
# get all genes and antibiotics in KG
pd_genes = pd_entities[pd_entities['Type'].str.match('gene')]['Name'].reset_index(drop=True)
pd_antibiotics = pd_entities[pd_entities['Type'].str.match('antibiotic')]['Name'].reset_index(drop=True)
pd_genes.sort_values(inplace=True)
pd_antibiotics.sort_values(inplace=True)
log.debug('Number of genes: %d', pd_genes.shape[0])
log.debug('Number of antibiotics: %d', pd_antibiotics.shape[0])
# read knowledge graph and drop unnecessary columns
pd_kg = pd.read_csv(os.path.join(args.data_dir, DEFAULT_KNOWLEDGE_GRAPH_FILENAME), sep='\t')
pd_kg = pd_kg.drop(COLUMN_NAMES_TO_DROP, axis=1)
pd_known_cra = pd_kg[pd_kg['Predicate'].str.contains('resistance to antibiotic')].reset_index(drop=True)
if pd_known_cra.duplicated(keep='first').sum() != 0:
log.warning('There are duplicates in the knowledge graph!')
log.debug('Number of CRA triples: %d', pd_known_cra.shape[0])
# save heatmap as matrix
pd_pivot_table = save_cra_matrix(pd_known_cra, pd_genes, pd_antibiotics)
plot_heatmap(pd_pivot_table)
if __name__ == '__main__':
main()