Repository navigation
Expand file tree
/
Copy pathplot_stats.py
More file actions
214 lines (158 loc) · 7.55 KB
/
Copy pathplot_stats.py
File metadata and controls
214 lines (158 loc) · 7.55 KB
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
""" Plots RL stats """
from __future__ import division
import glob
import os
import matplotlib
matplotlib.use('Qt4Agg')
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from stats import plot_result_difference_bars
try:
import cPickle as pickle
except:
import pickle
def plot_stats(prefix, stats_file, val_file, mean_interval=10, plot_graphs=True, save_graphs=False):
plot_stats_single_figure(prefix, stats_file, val_file, mean_interval, plot_graphs, save_graphs)
def plot_stats_single_figure(prefix, stats_file, val_file, mean_interval=10, plot_graphs=True, save_graphs=False):
if not plot_graphs and not save_graphs:
print('Set at least one of plot_graphs and save_graphs to True')
return
sns.set_style('whitegrid')
stats = pickle.load(open(stats_file, 'rb'))
fig, ax = plt.subplots(4)
(qax, rax, vax1, vax2) = ax
failure_count = np.add(stats['detected'], stats['missed'])
x = range(1, int(len(stats['scenarios']) / mean_interval) + 1)
perc_missed = [m / fc if fc > 0 else 0 for (m, fc) in zip(stats['missed'], failure_count)]
mean_missed, missed_fit = mean_values(x, perc_missed, mean_interval)
mean_reward, reward_fit = mean_values(x, stats['rewards'], mean_interval)
plot_results_line_graph(stats, 'napfd', mean_interval, qax, x)
#plot_napfd_metrics(afpd, mean_interval, mean_missed, missed_fit, qax, x)
if 'comparison' in stats:
plot_result_difference_bars(stats, 'napfd', rax, x)
else:
plot_results_line_graph(stats, 'rewards', mean_interval, rax, x)
val_res = pickle.load(open(val_file, 'rb'))
plot_validation(val_res, lambda res: res['napfd'], 'Validation Results', 'NAPFD', vax1)
plot_validation(val_res, lambda res: res['detected'] / (res['detected'] + res['missed']) if (res['detected'] + res['missed']) > 0 else 1,
'Validation Results', 'Failures Detected (in %)', vax2)
# plt.tight_layout()
if plot_graphs:
plt.show()
if save_graphs:
fig.savefig('%s_learning.pgf' % prefix, bbox_inches='tight')
fig.savefig('%s_learning.png' % prefix, bbox_inches='tight')
plt.close('all')
def plot_stats_separate_figures(prefix, stats_file, val_file, mean_interval=10, plot_graphs=False, save_graphs=False):
if not plot_graphs and not save_graphs:
print('Set at least one of plot_graphs and save_graphs to True')
return
sns.set_style('whitegrid')
sns.set_context('paper')
stats = pickle.load(open(stats_file, 'rb'))
failure_count = np.add(stats['detected'], stats['missed'])
x = range(1, int(len(stats['scenarios']) / mean_interval) + 1)
perc_missed = [m / fc if fc > 0 else 0 for (m, fc) in zip(stats['missed'], failure_count)]
mean_missed, missed_fit = mean_values(x, perc_missed, mean_interval)
mean_reward, reward_fit = mean_values(x, stats['rewards'], mean_interval)
fig = plt.figure()
ax = fig.add_subplot(111)
plot_napfd_metrics([r[3] for r in stats['result']], mean_interval, mean_missed, missed_fit, ax, x)
if plot_graphs:
plt.draw()
if save_graphs:
fig.savefig('%s_quality.pgf' % prefix, bbox_inches='tight', transparent=True)
fig.savefig('%s_quality.png' % prefix, bbox_inches='tight')
fig = plt.figure()
ax = fig.add_subplot(111)
plot_reward(mean_interval, mean_reward, ax, reward_fit, x)
if plot_graphs:
plt.draw()
if save_graphs:
fig.savefig('%s_reward.pgf' % prefix, bbox_inches='tight')
fig.savefig('%s_reward.png' % prefix, bbox_inches='tight')
val_res = pickle.load(open(val_file, 'rb'))
fig = plt.figure()
ax = fig.add_subplot(111)
plot_validation(val_res, lambda res: res['napfd'], 'Validation Results', 'NAPFD', ax)
if plot_graphs:
plt.draw()
if save_graphs:
fig.savefig('%s_validation_napfd.pgf' % prefix, bbox_inches='tight')
fig.savefig('%s_validation_napfd.png' % prefix, bbox_inches='tight')
fig = plt.figure()
ax = fig.add_subplot(111)
plot_validation(val_res, lambda res: res['detected'] / (res['detected'] + res['missed']) if (res['detected'] + res['missed']) > 0 else 1,
'Validation Results', 'Failures Detected (in %)', ax)
if plot_graphs:
plt.draw()
if save_graphs:
fig.savefig('%s_validation_failures.pgf' % prefix, bbox_inches='tight')
fig.savefig('%s_validation_failures.png' % prefix, bbox_inches='tight')
if plot_graphs:
plt.show() # Keep window open
else:
plt.close('all')
def plot_results_line_graph(stats, metric, mean_interval, qax, x, include_comparison=True):
if include_comparison and 'comparison' in stats:
for key in stats['comparison'].keys():
values, fitline = mean_values(x, stats['comparison'][key][metric], mean_interval)
qax.plot(x, values * 100, label=key)
#qax.plot(x, fitline(x) * 100, color='black')
values, fitline = mean_values(x, stats[metric], mean_interval)
qax.plot(x, values * 100, label=metric)
#qax.plot(x, fitline(x) * 100, color='black')
qax.set_ylim([0, 100])
qax.legend(ncol=2)
qax.set_xlim([1, max(x)])
def plot_napfd_metrics(afpd, mean_interval, mean_missed, missed_fit, qax, x):
mean_afpd, afpd_fit = mean_values(x, afpd, mean_interval)
qax.plot(x, mean_afpd * 100, label='NAPFD', color='blue')
qax.plot(x, afpd_fit(x) * 100, color='black')
qax.plot(x, mean_missed * 100, label='Percent Missed', color='green')
qax.plot(x, missed_fit(x) * 100, color='black')
qax.set_ylim([0, 100])
qax.legend(ncol=2)
qax.set_xlim([1, max(x)])
qax.set_title('Failure Detection (averaged over %d schedules)' % mean_interval)
def plot_reward(mean_interval, mean_reward, rax, reward_fit, x):
rax.plot(x, mean_reward, label='Reward', color='red')
rax.plot(x, reward_fit(x), color='black')
rax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
rax.set_xlim([1, max(x)])
rax.set_title('Reward (averaged over %d schedules)' % mean_interval)
def plot_validation(val_res, res_fun, title, ylabel, ax=None):
if not ax:
ax = plt.gca()
df = pd.DataFrame.from_dict(val_res)
res_df = df.apply(res_fun, raw=True, axis=1)
res_df.name = 'res'
ydat = pd.concat([df, res_df], axis=1)
sns.boxplot(data=ydat, x='step', y='res', palette=sns.color_palette(n_colors=1), ax=ax)
ax.set_title(title)
ax.set_ylabel(ylabel)
def mean_values(x, y, mean_interval):
#mean_y = np.mean(np.array(y).reshape(-1, mean_interval), axis=1)
mean_y = np.array(y)
z = np.polyfit(x, mean_y, 6)
f = np.poly1d(z)
return mean_y, f
def pickle_to_dataframe(pickle_file):
return pd.DataFrame.from_dict(pd.read_pickle(pickle_file))
def print_failure_detection(result_dir, file_prefixes):
df = pd.DataFrame()
for fp in file_prefixes:
searchpath = os.path.join(result_dir, fp)
files = glob.glob(searchpath + '_*_stats.p')
dfs = pd.concat([pickle_to_dataframe(f) for f in files])
df = df.append(dfs)
print df
if __name__ == '__main__':
stats_file = 'tableau_iofrol_timerank_lr0.3_as5_n1000_eps0.1_hist3_tableau_stats.p'
val_file = 'tableau_iofrol_timerank_lr0.3_as5_n1000_eps0.1_hist3_tableau_val.p'
mean_interval = 1
plot_stats_single_figure('tableau', stats_file, val_file, mean_interval, plot_graphs=True, save_graphs=False)
#plot_stats_separate_figures('netq', stats_file, val_file, mean_interval, plot_graphs=False, save_graphs=True)
#print_failure_detection('evaluation', ['heur_sort', 'heur_weight', 'random'])