-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathPlotsOld.py
335 lines (302 loc) · 14.3 KB
/
PlotsOld.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
from Measures import BuildMatrices, measures
from Utils import FancyApp, ColourClass
from collections import defaultdict
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import argparse
import os
import matplotlib
matplotlib.use('Agg')
# from Utils.notification import load_configuration, get_api
def tell(*args, **kwargs):
FancyApp.FancyApp.yell(
ColourClass.bcolors.BOLD_GREEN, 'plotter', *args, **kwargs)
aparser = argparse.ArgumentParser()
required_arguments = aparser.add_argument_group('required arguments')
required_arguments.add_argument('--bacteria-selection',
help='pickle file that contains the informtion'
' on the selected bacteria',
required=True)
required_arguments.add_argument('--s2f-dir',
help='S2F directory', required=True)
required_arguments.add_argument('--fasta-directory',
help='directory where all the fasta files'
' can be found', required=True)
required_arguments.add_argument('--goa-directory',
help='directory where all the goa files'
' can be found, the names need to match '
'the ones defined by the '
'`--bacteria-seleciton` argument',
required=True)
required_arguments.add_argument('--plots-directory',
help='directory where the plots will be saved',
required=True)
required_arguments.add_argument('--matrices-directory',
help='directory where the scores matrices will'
' be stored', required=True)
required_arguments.add_argument('--obo',
help='go.obo file', required=True)
required_arguments.add_argument('--plot-individual', action='store_true')
required_arguments.add_argument('--compute-metrics', action='store_true')
args = aparser.parse_args()
obo = args.obo
S2F_DIR = args.s2f_dir
GOA_DIRECTORY = args.goa_directory
FASTA_DIRECTORY = args.fasta_directory
PLOTS_DIRECTORY = args.plots_directory
MATRICES_DIRECTORY = args.matrices_directory
# load the selected organisms pandas fil
final_selection = pd.read_pickle(args.bacteria_selection)
all_organisms = pd.DataFrame()
# for coloring the plots
flatui = ["#705319", "#e5aa34", "#911f76", "#e534bb", "#1c7c69", "#31d6b5", ]
flatui3 = ["#e5aa34", "#e534bb", "#31d6b5", ]
# for nice labelling
labels = [
('I+H+D', 'S2F'),
('I+H', 'InterPro + HMMER'),
('I', 'InterPro'),
('I+D', 'InterPro w/ diffusion'),
('H', 'HMMER'),
('H+D', 'HMMER w/ diffusion'),
]
# we have these values per threshold, so they are unsafe for plotting
unsafe_metrics = ['roc', 'pr', 'tp', 'fp', 'tn', 'fn', 's', 'ru', 'mi',
'AUC per-gene raw', 'AUPR per-gene raw',
'Precision at 0.2 Recall per-gene raw', 'F_max per-gene raw',
'NDCG per-gene raw', 'Jaccard per-gene raw',
'smin per-gene raw', 'AUC per-term raw', 'AUPR per-term raw',
'Precision at 0.2 Recall per-term raw', 'F_max per-term raw',
'NDCG per-term raw', 'Jaccard per-term raw',
'smin per-term raw']
for i, organism in final_selection.sort_values(by='Tax ID').iterrows():
tell('processing organism: ', organism['Organism'],
'(', organism['Tax ID'], ')...')
interpro_file = os.path.join(
S2F_DIR, f'seeds/interpro/{organism["Tax ID"]}.matrix')
hmmer_file = os.path.join(
S2F_DIR, f'seeds/hmmer/{organism["Tax ID"]}.matrix')
interpro_diff_file = os.path.join(
S2F_DIR, f'output/{organism["Tax ID"]}/interpro.diffusion')
hmmer_diff_file = os.path.join(
S2F_DIR, f'output/{organism["Tax ID"]}/hmmer.diffusion')
s2f_file = os.path.join(
S2F_DIR, f'output/{organism["Tax ID"]}/final.diffusion')
goa = os.path.join(GOA_DIRECTORY, organism['File'])
fasta = os.path.join(FASTA_DIRECTORY, organism['Tax ID'] + '.fasta')
org_dir = os.path.join(MATRICES_DIRECTORY, organism['Tax ID'] + '/')
if os.path.exists(org_dir + 'metrics_df.pkl'):
tell('Found saved metrics file, loading...')
metrics_df = pd.read_pickle(org_dir + 'metrics_df.pkl')
else:
if os.path.exists(org_dir):
tell('Found precomputed matrices, loading...')
goa_values = np.load(org_dir + 'goa_values.npy')
hmmer_diff_values = np.load(org_dir + 'hmmer_diff_values.npy')
hmmer_values = np.load(org_dir + 'hmmer_values.npy')
interpro_diff_values = np.load(org_dir +
'interpro_diff_values.npy')
interpro_values = np.load(org_dir + 'interpro_values.npy')
s2f_values = np.load(org_dir + 's2f_values.npy')
information_content = np.load(org_dir + 'information_content.npy')
else:
os.makedirs(org_dir)
matrix_builder = BuildMatrices.BuildMatrices(
interpro_file, interpro_diff_file, None,
hmmer_file, hmmer_diff_file, None, s2f_file, goa,
fasta, obo)
np.save(org_dir + 'goa_values.npy', matrix_builder.goa_values)
np.save(org_dir + 'hmmer_diff_values.npy',
matrix_builder.hmmer_diff_values)
np.save(org_dir + 'hmmer_values.npy', matrix_builder.hmmer_values)
np.save(org_dir + 'interpro_diff_values.npy',
matrix_builder.interpro_diff_values)
np.save(org_dir + 'interpro_values.npy',
matrix_builder.interpro_values)
np.save(org_dir + 's2f_values.npy', matrix_builder.s2f_values)
np.save(org_dir + 'information_content.npy',
matrix_builder.information_content)
goa_values = matrix_builder.goa_values
hmmer_diff_values = matrix_builder.hmmer_diff_values
hmmer_values = matrix_builder.hmmer_values
interpro_diff_values = matrix_builder.interpro_diff_values
interpro_values = matrix_builder.interpro_values
s2f_values = matrix_builder.s2f_values
information_content = matrix_builder.information_content
if args.compute_metrics:
# ranges as HX's method
group_name = ['3-10', '11-30', '31-100', '101-300', '1-300', 'all']
ranges = [(3, 10), (11, 30), (31, 100),
(101, 300), (1, 300), (1, 1000000)]
group_name = ['all']
ranges = [(1, 1000000)]
s2f_nodiff = 0.9 * interpro_values + 0.1 * hmmer_values
sumcol = np.sum(goa_values, axis=0)
sumrow = np.sum(goa_values, axis=1)
predictions = []
gold_standards = []
information_contents = []
for low, high in ranges:
pred = {
'I': interpro_values[sumrow > 3, :][
:, (sumcol >= low) & (sumcol <= high)],
'I+D': interpro_diff_values[sumrow > 3, :][
:, (sumcol >= low) & (sumcol <= high)],
'H': hmmer_values[sumrow > 3, :][
:, (sumcol >= low) & (sumcol <= high)],
'H+D': hmmer_diff_values[sumrow > 3, :][
:, (sumcol >= low) & (sumcol <= high)],
'I+H': s2f_nodiff[sumrow > 3, :][
:, (sumcol >= low) & (sumcol <= high)],
'I+H+D': s2f_values[sumrow > 3, :][
:, (sumcol >= low) & (sumcol <= high)]}
predictions.append(pred)
gold_standards.append(
goa_values[sumrow > 3, :][
:, (sumcol >= low) & (sumcol <= high)])
information_contents.append(
information_content[(sumcol >= low) & (sumcol <= high)])
data = defaultdict(list)
meas = {}
res = {}
for pred, gs, r, ic in zip(predictions, gold_standards, group_name,
information_contents):
tell('Processing range:', r)
# HX measure calculator
for k in pred.keys():
tell(k)
rounded_pred = pred[k]
if len(np.unique(pred[k])) > 10000:
rounded_pred = np.around(pred[k], decimals=4)
meas[k] = measures.HX_py(rounded_pred, ic,
organism['Tax ID'])
tell('computing OVERALL')
res[k] = meas[k].compute_overall(gs)
for m in res[k].keys():
data[m].append([k, r, res[k][m]])
tell('computing per-gene')
res[k] = meas[k].compute_per_gene(gs)
for m in res[k].keys():
data[m].append([k, r, res[k][m]])
tell('computing per-term')
res[k] = meas[k].compute_per_term(gs)
for m in res[k].keys():
data[m].append([k, r, res[k][m]])
tell('saving metrics')
# save all metrics
metrics = []
for k, l in data.items():
for v in l:
metrics.append((k, v[0], v[1], v[2]))
metrics_df = pd.DataFrame(
metrics, columns=['metric', 'method', 'range', 'value'])
metrics_df.to_pickle(org_dir + 'metrics_df.pkl')
if args.compute_metrics:
sns.palplot(sns.color_palette(flatui))
metrics_df = metrics_df.sort_values(by=['metric', 'range', 'method'])
metrics_df['organism'] = organism['Organism']
for source, dest in labels:
metrics_df['method'].replace(source, dest, inplace=True)
all_organisms = all_organisms.append(metrics_df, ignore_index=True)
if args.plot_individual:
tell('Generating figures...')
for metric in metrics_df['metric'].unique():
if metric in unsafe_metrics:
continue
tell(f'metric: {metric}')
plot_selection = metrics_df[metrics_df['metric'] == metric]
if 'per-' in metric:
metric += '(mean)'
# PLOT WITH RANGES
a4_dims = (11.7, 8.27)
fig, ax = plt.subplots(figsize=a4_dims, dpi=100)
g = sns.barplot(ax=ax,
data=plot_selection,
x='range',
y='value',
hue='method',
palette=flatui)
for p in g.patches:
ax.annotate(
"%.3f" % p.get_height(),
(p.get_x() + p.get_width() / 2., p.get_height()),
ha='center',
va='center',
fontsize=9,
xytext=(1, -20),
rotation=90,
textcoords='offset points',
color='white',
weight='black')
ax.set(ylabel=metric)
ax.set(title=organism['Organism'] + ' ' + organism['Tax ID'])
ax.legend(bbox_to_anchor=(1.0, 0.5))
fig.savefig(
PLOTS_DIRECTORY +
organism['Tax ID'] + ' ' + metric + '-ranges.png')
plt.close(fig)
# PLOT WITHOUT RANGES
fig, ax = plt.subplots(figsize=a4_dims, dpi=100)
g = sns.barplot(
ax=ax,
data=plot_selection[plot_selection['range'] == 'all'],
x='method',
y='value',
palette=flatui)
for p in g.patches:
ax.annotate(
"%.3f" % p.get_height(),
(p.get_x() + p.get_width() / 2., p.get_height()),
ha='center',
va='center',
fontsize=11,
xytext=(0, 10),
textcoords='offset points')
ax.set(ylabel=metric)
ax.set(title=organism['Organism'] + ' ' + organism['Tax ID'])
fig.savefig(
PLOTS_DIRECTORY+organism['Tax ID']+' '+metric+'.png')
plt.close(fig)
if args.compute_metrics:
tell('Generating figures for all organisms...')
# plot all organisms
all_organisms.organism = all_organisms.organism.str.split(
'(', n=0, expand=True)[0]
all_organisms.organism = all_organisms.organism.str.split(
'ATCC', n=0, expand=True)[0]
all_organisms.organism = all_organisms.organism.str.split(
'MG', n=0, expand=True)[0]
all_organisms.to_pickle(
os.path.join(MATRICES_DIRECTORY, 'all_organisms.pkl'))
for metric in all_organisms['metric'].unique():
if metric in unsafe_metrics:
continue
methods = ['InterPro', 'HMMER', 'S2F']
fig, ax = plt.subplots(figsize=(11.7, 6.27), dpi=100)
condition = (all_organisms['range'] == 'all') & \
(all_organisms['metric'] == metric) & \
(all_organisms['method'].isin(methods))
g = sns.barplot(ax=ax, data=all_organisms[condition],
x='organism', y='value', hue='method', palette=flatui3)
for p in g.patches:
ax.annotate(
"%.3f" % p.get_height(),
(p.get_x() + p.get_width() / 2., p.get_height()),
ha='center',
va='center',
fontsize=9,
xytext=(1, -20),
rotation=90,
textcoords='offset points',
color='white',
weight='black')
ax.set_xticklabels(ax.get_xticklabels(), rotation=-25, ha='left')
ax.set(ylabel=metric)
ax.set(title='')
ax.legend(bbox_to_anchor=(1.0, 0.5))
plt.savefig(
os.path.join(PLOTS_DIRECTORY, 'ALL '+metric+'.png'),
bbox_inches='tight')
plt.close(fig)