Skip to content
Snippets Groups Projects
Commit e3a955ac authored by René Schöne's avatar René Schöne
Browse files

Incoporated mixed scenario in diagrams, combined diagrams.

parent 100d06e2
No related branches found
No related tags found
No related merge requests found
%% Cell type:code id: tags:
``` python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.axes, matplotlib.ticker
%matplotlib inline
plt.ioff()
```
%% Cell type:code id: tags:
``` python
from glob import glob
from datetime import datetime
from itertools import *
from operator import itemgetter
import json, sys, traceback, os, functools
```
%% Cell type:code id: tags:
``` python
if not os.path.exists('doc'):
os.mkdir('doc')
if not os.path.exists('pngs'):
os.mkdir('pngs')
```
%% Cell type:code id: tags:
``` python
spec_files = glob('profiling/*/specs')
spec_files.sort()
specs = {os.path.basename(os.path.dirname(f)):np.genfromtxt(f, delimiter=' ', dtype=int)
for f in spec_files}
```
%% Cell type:code id: tags:
``` python
linestyles = ["-","--","-.",":"]
colors = ('blue','black','red','orange','green','magenta','yellow', 'cyan', 'purple', 'firebrick')
colorcycle = cycle(colors)
lastpe = False
line_def = []
color_def = []
## Currently disabled due to fragile and unused output
if False:
for spec in specs:
pe, comp, impl, mode = (spec[2], spec[4], spec[5], spec[6])
if not lastpe or lastpe != pe:
color = next(colorcycle)
linecycle = cycle(linestyles)
line = next(linecycle)
lastpe = pe
line_def.append(line)
color_def.append(color)
```
%% Cell type:code id: tags:
``` python
def set_keys(*indices):
"""Returns a function that returns a tuple of key values"""
def get_keys(seq, indices=indices):
keys = []
for i in indices:
keys.append(seq[i])
return tuple(keys)
return get_keys
```
%% Cell type:code id: tags:
``` python
def get_average_times(dat, dirCol, stepCol, timeCol):
if dat.size == 1:
return np.array([np.array([dat.item()[timeCol]])])
dat.sort(order=['dir', 'step'])
result = {}
for (c_dir, c_step), rows in groupby(dat, key=set_keys('dir','step')):
#print c_dir, c_step, rows
c_dir, c_step, total_time, counter = None, None, 0, 0
for row in rows:
if not c_dir:
c_dir = row[dirCol]
if not c_step:
c_step = row[stepCol]
total_time+=row[timeCol]
counter += 1
result.setdefault(c_dir, []).append([c_step, total_time*1.0/counter])
result2 = []
for c_dir, rows in result.iteritems():
inner = []
result2.append([row[1] for row in rows])
# for row in rows:
# inner.append(row[1])
# result2.append(inner)
return np.array([np.array(rows) for rows in result2])
```
%% Cell type:code id: tags:
``` python
def is_axis(a):
return not type(a) is np.ndarray
```
%% Cell type:code id: tags:
``` python
with open('profiling/kinds.json') as fd:
kinds = json.load(fd)
print 'Kinds: {}'.format(kinds)
```
%% Output
Kinds: {u'strategies': [u'normal', u'flush', u'noncached'], u'changes': [u'update', u'sw', u'res', u'complex', u'mixed']}
%% Cell type:code id: tags:
``` python
no_split, split_change_only, split_both = 0, 1, 2
dat, dat2, dat3 = None, None, None
def read_single_result(f, name, dtype, data_column, since):
global dat, dat2, dat3
def convdate(text):
return datetime.strptime(text, '%Y-%m-%dT%H:%M:%S.%f')
def convdir(text):
return int(text[-3:])
def convstep(text):
return int(text[0:2])
def safe_div(a, b):
return a/b if b>0 else "{}!".format(a)
dat = np.genfromtxt(f, delimiter=',', names=True, dtype=dtype,
converters={'timestamp':convdate, 'step':convstep, 'dir': convdir})
if since:
dat = dat[dat['timestamp'] > since ]
dat2 = get_average_times(dat, 1, 2, data_column).transpose()
len_dat = 1 if len(dat.shape) == 0 else len(dat)
if dat2.size == 0:
print 'Did not load any record for {}'.format(name)
else:
if len_dat > 1:
print 'Loaded {0} record(s) for {1} ({2[0]}x{2[1]} unique) ~= {3} run(s)'.format(
len_dat, name, dat2.shape, safe_div(len_dat,dat2.size))
else:
print 'Loaded no data for {}'.format(name)
dat3 = dat2
return dat2
def read_results(prefix, name, dtype, data_column, since, splitted = no_split):
if splitted in (split_change_only, split_both):
result = {}
for change in kinds['changes']:
result.setdefault(change, {})
if splitted == split_both:
for strategy in kinds['strategies']:
result[change].setdefault(strategy, {})
new_name = '{0}_{1}_{2}'.format(change, strategy, name)
f = 'profiling/splitted/{0}_{1}.csv'.format(prefix, new_name)
result[change][strategy] = read_single_result(f, new_name, dtype, data_column, since)
else: # splitted == split_change_only
new_name = '{0}_{1}'.format(change, name)
f = 'profiling/splitted/{0}_{1}.csv'.format(prefix, new_name)
result[change] = read_single_result(f, new_name, dtype, data_column, since)
return result
else: # splitted = no_split
f = 'profiling/{0}-{1}-results.csv'.format(prefix, name)
return read_single_result(f, name, dtype, data_column, since)
```
%% Cell type:code id: tags:
``` python
def read_gen_results(impl, since = None):
return read_results('gen', impl, ('datetime64[us]', int, int, float), 3, since, splitted = split_both)
def read_sol_results(solver, since = None):
return read_results('sol', solver, ('datetime64[us]', int, int, int, int, int, float, float), 7, since,
splitted = split_change_only)
```
%% Cell type:code id: tags:
``` python
def safe(a, i, start = 0):
try:
return a[start:,i]
except IndexError:
return np.zeros(a[:,0].size)
def es(y, x):
""" Ensure size of y compared to x """
if y.shape[0] != x.shape[0]:
y = np.ones(x.shape[0]) * y[0]
return y
```
%% Cell type:markdown id: tags:
## ILP-Re-Generation and Solving Time
- ILP-Re-Generation describes the time it takes for the Scheme implementations to evaluate the attribute computing the ILP
- it does not include the time to read from and write to disk
- "Java" denotes the Java- and EMF-based generation
- ILP Solving describes the time it takes the solvers (GLPK and Gurobi in this case) to solve the generated ILP
- "GLPK (Java)" denotes the time to solve the ILP generated by the Java-based generation with GLPK. Its format was modifiert slightly to be accepted by GLPK, as it was originally generated for lp_solve
- "GLPK (Scheme)" denotes the time to solve the ILP generated by any scheme implementation with GLPK
- the plots show different system configurations
- a system configuration is given by "r x ( c \* i \* m )", which describes a system with *r* resources and *c* software components with *i* implementations having *m* modes each.
- for one such configuration the same experiment is run, i.e. the system is modified 7 times leading to the 7 steps, whereas only changes on hardware resources are made
- for the cases involving Java (both, generation and solving), the same time is used for every step, as the generation always starts from skretch. Further, the changes (e.g. change the value of a single hardware resource while generation) can not be reflected by the Java System Generator
- on the x-axis, the steps of this manipulation are shown
- the initial generation of the ILP (step zero) is only shown below in numbers, as it would skew the diagrams
%% Cell type:markdown id: tags:
Header = ['timestamp', 'dir', 'step', 'rows', 'cols', 'non-zero', 'ilp-sol', 'ti-ilp-sol']
%% Cell type:code id: tags:
``` python
racket_dats = read_gen_results('plt-r6rs', since = datetime(2015,8,17,0,0,0))
larceny_dats = read_gen_results('larceny', since = datetime(2015,6,12,0,0,0))
java_dats = read_gen_results('java')
```
%% Output
Loaded 1320 record(s) for update_normal_plt-r6rs (8x31 unique) ~= 5 run(s)
Loaded 504 record(s) for update_flush_plt-r6rs (8x31 unique) ~= 2 run(s)
Loaded 600 record(s) for update_noncached_plt-r6rs (8x31 unique) ~= 2 run(s)
Loaded 364 record(s) for sw_normal_plt-r6rs (7x31 unique) ~= 1 run(s)
Loaded 245 record(s) for sw_flush_plt-r6rs (7x31 unique) ~= 1 run(s)
Loaded 602 record(s) for sw_noncached_plt-r6rs (7x31 unique) ~= 2 run(s)
Loaded 360 record(s) for res_normal_plt-r6rs (7x31 unique) ~= 1 run(s)
Loaded 245 record(s) for res_flush_plt-r6rs (7x31 unique) ~= 1 run(s)
Loaded 609 record(s) for res_noncached_plt-r6rs (7x31 unique) ~= 2 run(s)
Loaded 242 record(s) for complex_normal_plt-r6rs (11x11 unique) ~= 2 run(s)
Loaded 121 record(s) for complex_flush_plt-r6rs (11x11 unique) ~= 1 run(s)
Loaded 121 record(s) for complex_noncached_plt-r6rs (11x11 unique) ~= 1 run(s)
Loaded 200 record(s) for mixed_normal_plt-r6rs (100x2 unique) ~= 1 run(s)
Loaded no data for mixed_flush_plt-r6rs
Loaded no data for mixed_noncached_plt-r6rs
Loaded 359 record(s) for mixed_flush_plt-r6rs (100x2 unique) ~= 1 run(s)
Loaded 200 record(s) for mixed_noncached_plt-r6rs (100x2 unique) ~= 1 run(s)
Loaded 512 record(s) for update_normal_larceny (8x31 unique) ~= 2 run(s)
Loaded no data for update_flush_larceny
Loaded no data for update_noncached_larceny
Loaded 217 record(s) for sw_normal_larceny (7x31 unique) ~= 1 run(s)
Loaded no data for sw_flush_larceny
Loaded no data for sw_noncached_larceny
Loaded 217 record(s) for res_normal_larceny (7x31 unique) ~= 1 run(s)
Loaded no data for res_flush_larceny
Loaded no data for res_noncached_larceny
Loaded 121 record(s) for complex_normal_larceny (11x11 unique) ~= 1 run(s)
Loaded no data for complex_flush_larceny
Loaded no data for complex_noncached_larceny
Loaded no data for mixed_normal_larceny
Loaded no data for mixed_flush_larceny
Loaded no data for mixed_noncached_larceny
Loaded 88 record(s) for update_normal_java (1x31 unique) ~= 2 run(s)
Loaded no data for update_flush_java
Loaded no data for update_noncached_java
Loaded no data for sw_normal_java
Loaded no data for sw_flush_java
Loaded no data for sw_noncached_java
Loaded no data for res_normal_java
Loaded no data for res_flush_java
Loaded no data for res_noncached_java
Loaded no data for complex_normal_java
Loaded no data for complex_flush_java
Loaded no data for complex_noncached_java
Loaded no data for mixed_normal_java
Loaded no data for mixed_flush_java
Loaded no data for mixed_noncached_java
%% Cell type:code id: tags:
``` python
java_glpk_dats = read_sol_results('java', since = datetime(2015,6,22,0,0,0))
glpk_dats = read_sol_results('glpk')
gurobi_dats = read_sol_results('gurobi')
```
%% Output
Loaded 23 record(s) for update_java (1x23 unique) ~= 1 run(s)
Loaded no data for sw_java
Loaded no data for res_java
Loaded no data for complex_java
Loaded no data for mixed_java
Loaded 1656 record(s) for update_glpk (8x23 unique) ~= 9 run(s)
Loaded no data for sw_glpk
Loaded no data for res_glpk
Loaded no data for complex_glpk
Loaded no data for mixed_glpk
Loaded 216 record(s) for update_gurobi (8x27 unique) ~= 1 run(s)
Loaded no data for sw_gurobi
Loaded no data for res_gurobi
Loaded no data for complex_gurobi
Loaded no data for mixed_gurobi
%% Cell type:code id: tags:
``` python
p_ax_nr, p_line_def, p_col_def, p_label = 0, 1, 2, 3
p_gen_racket, p_gen_larceny, p_gen_java = 4, 5, 6
p_sol_glpk, p_sol_gurobi, p_sol_java_glpk = 4, 5, 6
```
%% Cell type:code id: tags:
``` python
def draw_gen(changeName, strategy, params):
try:
name = 'gen_{0}_{1}'.format(changeName, strategy)
# needed number of axes equals ax_nr+1 now
f, ax_arr = plt.subplots(nrows = ax_nr+1, ncols = 3, sharex=True, sharey=True)
f.set_size_inches(25.5,3.5*(ax_nr+1))
one_plot = ax_arr.shape[1] == 1
f.patch.set_facecolor('none')
f.patch.set_alpha(0.0)
lines, labels = [], []
for p in params:
ax_tup = ax_arr if one_plot else ax_arr[p[p_ax_nr]]
ax_j = ax_tup[0]
ax_r = ax_tup[1]
ax_l = ax_tup[2]
# ax_j.set_ylim([0,50])
# ax_r.set_ylim([0,10])
# ax_l.set_ylim([0,10])
# x_g = np.array(xrange(1,len(p[1])+1)) # start at one, since first gen-time is cut
x_g = np.array(xrange(START_STEP,len(p[p_gen_racket])+START_STEP)) # start at zero
line_java = ax_j.plot(x_g, p[p_gen_java][0]*np.ones(len(p[p_gen_racket])), ls = p[p_line_def],
c = p[p_col_def], label = p[p_label])
line_racket = ax_r.plot(x_g, es(p[p_gen_racket], x_g), ls = p[p_line_def],
c = p[p_col_def], label = p[p_label])
line_larceny = ax_l.plot(x_g, es(p[p_gen_larceny], x_g), ls = p[p_line_def],
c = p[p_col_def], label = p[p_label])
ax_l.legend(loc='upper left', bbox_to_anchor=(1, 1.02))
lines.append(line_racket[0])
labels.append(p[p_label])
for ax in ax_arr if one_plot else ax_arr.flatten():
ax.set_ylabel('seconds')
ax.patch.set_alpha(1)
ax.patch.set_facecolor('white')
first_ax = ax_arr if one_plot else ax_arr[0]
plt.suptitle('ILP Generation Time', fontsize = 16)
first_ax[0].set_title('Java')
first_ax[1].set_title('Racket')
first_ax[2].set_title('Larceny')
# Fine-tune figure; make subplots close to each other and hide x ticks for
# all but bottom plots.
f.subplots_adjust(hspace=0.2)
plt.setp([a.get_xticklabels() for a in f.axes[:-3]], visible=False)
plt.setp([a.get_yticklabels() for a in f.axes], visible=True)
plt.savefig('doc/{}.pdf'.format(name), facecolor=f.get_facecolor(), edgecolor='none')
plt.savefig('pngs/{}.png'.format(name), facecolor=f.get_facecolor(), edgecolor='none')
except Exception as e:
print 'Error while drawing gen in {0}-{1}: {2}'.format(change, strategy, e)
traceback.print_exc(file=sys.stdout)
finally:
plt.close()
```
%% Cell type:code id: tags:
``` python
def draw_sol(changeName, params):
try:
name = 'sol_{}'.format(changeName)
f, ax_arr = plt.subplots(nrows = ax_nr+1, ncols = 3, sharex=True, sharey=True)
f.set_size_inches(25.5,3.5*(ax_nr+1))
one_plot = ax_arr.shape[1] == 1
f.patch.set_facecolor('none')
f.patch.set_alpha(0.0)
lines, labels = [], []
for p in params:
ax_tup = ax_arr if one_plot else ax_arr[p[p_ax_nr]]
ax_javaglpk = ax_tup[0]
ax_glpk = ax_tup[1]
ax_gurobi = ax_tup[2]
x = np.array(xrange(0,len(p[p_sol_glpk]))) # start at zero
line_javaglpk = ax_javaglpk.plot(x, p[p_sol_java_glpk][0]*np.ones(len(p[p_sol_glpk])), ls = p[p_line_def],
c = p[p_col_def], label = p[p_label])
line_glpk = ax_glpk.plot(x, es(p[p_sol_glpk],x), ls = p[p_line_def],
c = p[p_col_def], label = p[p_label])
line_gurobi = ax_gurobi.plot(x, es(p[p_sol_gurobi],x), ls = p[p_line_def],
c = p[p_col_def], label = p[p_label])
ax_gurobi.legend(loc='upper left', bbox_to_anchor=(1, 1.02))
lines.append(line_glpk[0])
labels.append(p[p_label])
for ax in ax_arr if one_plot else ax_arr.flatten():
ax.set_ylabel('seconds')
ax.patch.set_alpha(1)
ax.patch.set_facecolor('white')
first_ax = ax_arr if one_plot else ax_arr[0]
plt.suptitle('ILP Solving Time', fontsize = 16)
first_ax[0].set_title('GLPK (Java)')
first_ax[1].set_title('GLPK (Scheme)')
first_ax[2].set_title('Gurobi (Scheme)')
# Fine-tune figure; make subplots close to each other and hide x ticks for
# all but bottom plots.
f.subplots_adjust(hspace=0.2)
plt.setp([a.get_xticklabels() for a in f.axes[:-3]], visible=False)
plt.setp([a.get_yticklabels() for a in f.axes], visible=True)
plt.savefig('doc/{}.pdf'.format(name))
plt.savefig('pngs/{}.png'.format(name))
except Exception as e:
print 'Error while drawing sol in {0}: {1}'.format(changeName, e)
traceback.print_exc(file=sys.stdout)
finally:
plt.close()
```
%% Cell type:code id: tags:
``` python
def draw_comp_sol(changeName, params):
try:
name = 'comp_sol_{}'.format(changeName)
indices = [3, 12, 14, 19]
for i in indices:
p = params[i]
x = np.array(xrange(0,len(p[p_sol_glpk]))) # start at zero
line_javaglpk = plt.plot(x, p[p_sol_java_glpk][0]*np.ones(len(p[p_sol_glpk])), ls = linestyles[0],
c = p[p_col_def], label = p[p_label])
line_glpk = plt.plot(x, es(p[p_sol_glpk],x), ls = p[p_line_def], c = p[p_col_def])
line_gurobi = plt.plot(x, es(p[p_sol_gurobi],x), ls = p[p_line_def], c = p[p_col_def])
plt.legend(loc = 'right')
plt.ylabel('seconds')
plt.suptitle('ILP Solving Time - Comparison', fontsize = 16)
plt.savefig('doc/{}.pdf'.format(name))
plt.savefig('pngs/{}.png'.format(name))
except Exception as e:
print 'Error while drawing comp-sol in {0}: {1}'.format(changeName, e)
traceback.print_exc(file=sys.stdout)
finally:
plt.close()
```
%% Cell type:code id: tags:
``` python
## Currently disabled due to fragile and unused output
if False:
START_STEP, MAX_PLOTS_IN_ONE = 0, 7
for change in kinds['changes']:
print 'Change = {}'.format(change)
for strategy in kinds['strategies']:
ax_nr = 0
print 'Stategy = {}'.format(strategy)
current_plot, ax_nr, last_res = 0, 0, -1
gen_params = []
for i in xrange(len(specs)):
current_res = specs[i][2]
current_plot += 1
if current_plot > MAX_PLOTS_IN_ONE and last_res != current_res:
ax_nr += 1
current_plot = 0
gen_params.append([ax_nr, line_def[i], color_def[i], '{2:d} x ({4}*{5}*{6})'.format(*specs[i]),
safe(racket_dats[change][strategy],i,START_STEP),
safe(larceny_dats[change][strategy],i,START_STEP),
safe(java_dats[change][strategy],i)])
last_res = current_res
draw_gen(change, strategy, gen_params)
# end of for strategies
sol_params = []
ax_nr = 0
for i in xrange(len(specs)):
current_res = specs[i][2]
current_plot += 1
if current_plot > MAX_PLOTS_IN_ONE and last_res != current_res:
ax_nr += 1
current_plot = 0
sol_params.append([ax_nr, line_def[i], color_def[i], '{2:d} x ({4}*{5}*{6})'.format(*specs[i]),
safe(glpk_dats[change],i),
safe(gurobi_dats[change],i),
safe(java_glpk_dats[change],i)])
draw_sol(change, sol_params)
draw_comp_sol(change, sol_params)
```
%% Cell type:code id: tags:
``` python
llong, lshort, lveryshort = 0, 1, 2
l = ['Flushed', '$fs$', 'f']
stt = {'normal' : ['Incremental', '$inc$', 'i'],
'flush' : l, 'flushed': l,
'noncached': ['Noncached', '$nc$', 'n']}
def strategy_to_titel(strategy, length = llong):
try:
return stt[strategy.lower()][length]
except KeyError:
raise Exception('Unknown strategy/length: {0} {1}'.format(strategy, length))
def strategy2_to_titel(ratio):
s1, s2 = ratio.split('To')
return r'${0} \rightarrow {1}$'.format(strategy_to_titel(s1, lshort)[1:-1], strategy_to_titel(s2, lshort)[1:-1])
def change_to_title(change):
if change == 'complex':
change = 'mixed'
return change.title()
```
%% Cell type:markdown id: tags:
## Boxplots for generation times
%% Cell type:code id: tags:
``` python
def setBoxColors(bp, c):
plt.setp(bp['boxes'], color=c)
plt.setp(bp['caps'], color=c)
# plt.setp(bp['caps'][1], color=c)
plt.setp(bp['whiskers'], color=c)
# plt.setp(bp['whiskers'][1], color=c)
plt.setp(bp['fliers'], color=c)
# plt.setp(bp['fliers'][1], color=c)
plt.setp(bp['medians'], color=c)
strategy_colors = {'noncached':'red', 'flush': 'green', 'normal': 'blue'}
```
%% Cell type:code id: tags:
``` python
for (data, name) in ((java_dats, 'java'), (racket_dats, 'racket'), (larceny_dats, 'larceny')):
print name+':'
#change, strategy = 'update', 'normal'
sys.stdout.write('\n{}:'.format(name))
# change, strategy = 'mixed', 'normal'
for change in kinds['changes']:
#if True:
sys.stdout.write(change+' ')
# if True:
# if True:
sys.stdout.write('\n {}'.format(change))
# if True:
for strategy in kinds['strategies']:
sys.stdout.write(strategy+',')
sys.stdout.write(','+strategy)
cdat = data[change][strategy]
plt.boxplot(cdat.transpose())
bp = plt.boxplot(cdat.transpose())
setBoxColors(bp, strategy_colors[strategy])
axes = plt.gca()
axes.set_ylim([0,50])
plt.title('{0} {1} {2}'.format(name.title(), change_to_title(change), strategy_to_titel(strategy)))
plt.ylabel('seconds')
plt.xlabel('step')
if change == 'mixed':
for i, label in enumerate(axes.get_xticklabels()):
label.set_visible(i==0 or (i+1) % 10 == 0)
plt.savefig('pngs/gen_bp_{0}_{1}_{2}.png'.format(name,change,strategy))
plt.savefig('doc/gen_bp_{0}_{1}_{2}.pdf'.format(name,change,strategy))
plt.close()
print ''
```
%% Output
java:
update normal,flush,noncached,sw normal,flush,noncached,res normal,flush,noncached,complex normal,flush,noncached,mixed normal,flush,noncached,
update,normal,flush,noncached
sw,normal,flush,noncached
res,normal,flush,noncached
complex,normal,flush,noncached
mixed,normal,flush,noncached
racket:
update normal,flush,noncached,sw normal,flush,noncached,res normal,flush,noncached,complex normal,flush,noncached,mixed normal,flush,noncached,
update,normal,flush,noncached
sw,normal,flush,noncached
res,normal,flush,noncached
complex,normal,flush,noncached
mixed,normal,flush,noncached
larceny:
update normal,flush,noncached,sw normal,flush,noncached,res normal,flush,noncached,complex normal,flush,noncached,mixed normal,flush,noncached,
update,normal,flush,noncached
sw,normal,flush,noncached
res,normal,flush,noncached
complex,normal,flush,noncached
mixed,normal,flush,noncached
%% Cell type:markdown id: tags:
### Single diagram for update, res, sw. and only for racket.
%% Cell type:code id: tags:
``` python
width = 0.6
name = 'racket'
for change in ['update', 'res', 'sw']:
#change = 'sw'
#if True:
#x*4*width + n*width
invisibles = []
for i, strategy in enumerate(['noncached', 'flush', 'normal']):
# i, strategy, c = 1, 'flush', 'green'
# if True:
y = racket_dats[change][strategy]
c = strategy_colors[strategy]
bp = plt.boxplot(y.transpose(), positions = np.arange(y.shape[0])*4+i)
setBoxColors(bp, c)
line, = plt.plot([1,1],c[0]+'-')
invisibles.append((line,strategy))
axes = plt.gca()
axes.set_xlim([-1,27])
axes.set_ylim([0,50])
plt.ylabel('seconds')
plt.xlabel('step')
axes.set_xticklabels(range(1,8))
axes.set_xticks(range(1,29,4))
# draw temporary red and blue lines and use them to create a legend
plt.legend([l for (l,n) in invisibles],[n for (l,n) in invisibles])
[l.set_visible(False) for (l,n) in invisibles]
plt.savefig('pngs/gen_bp_{0}_{1}.png'.format(name,change))
plt.savefig('doc/gen_bp_{0}_{1}.pdf'.format(name,change))
plt.close()
# plt.show()
```
%% Cell type:markdown id: tags:
## Boxplot for solving times
%% Cell type:code id: tags:
``` python
for (data, name) in ((java_glpk_dats, 'java'), (glpk_dats, 'glpk'), (gurobi_dats, 'gurobi')):
print name+':'
#change = 'update'
for change in kinds['changes']:
#if True:
sys.stdout.write(change+' ')
# if True:
cdat = data[change]
plt.boxplot(cdat.transpose())
plt.title('{0} {1}'.format(name.title(), change_to_title(change)))
plt.ylabel('seconds')
plt.xlabel('step')
plt.savefig('pngs/sol_bp_{0}_{1}.png'.format(name,change))
plt.savefig('doc/sol_bp_{0}_{1}.pdf'.format(name,change))
plt.close()
print ''
```
%% Output
java:
update sw res complex mixed
glpk:
update sw res complex mixed
gurobi:
update sw res complex mixed
%% Cell type:markdown id: tags:
## Attribute metrics
- X = {normal, flushed, noncached}
- (X1,X2) = {(normal, flushed), (normal, noncached), (flushed, noncached)}
%% Cell type:code id: tags:
``` python
def read_att_result(name = 'profiling/att-percentages.csv', adjust_number = True):
def cdir(text):
prefix = text[:-4]
number = int(text[-3:])
if not adjust_number or prefix == 'update':
return number
elif prefix == 'sw':
return 31+number
elif prefix == 'res':
return 62+number
elif prefix == 'complex':
return 93+number
elif prefix == 'mixed':
return 104+number
elif prefix == '':
pass
else:
print 'Unknown prefix "{0}"'.format(prefix)
dat = np.genfromtxt(name, delimiter=',', names=True,
#dtype=(int, float, float, float, float, float, float, float),
converters={'dir': cdir})
dat.sort(axis=0)
print 'Loaded {0} ({1} zero-values) attribute metric run(s) from {2}'.format(dat.size,
reduce(lambda total,row: total + 1*(row == 0.0) if isinstance(row,int) or isinstance(row,float) else
reduce(lambda x,y: x+1 if y == 0 else x, row, 0),dat.tolist(),0), name)
return dat
```
%% Cell type:code id: tags:
``` python
att_dat = read_att_result()
att_dat.dtype
```
%% Output
Loaded 105 (8 zero-values) attribute metric run(s) from profiling/att-percentages.csv
Loaded 106 (0 zero-values) attribute metric run(s) from profiling/att-percentages.csv
dtype([('dir', '<f8'), ('normalBaseline', '<f8'), ('flushedBaseline', '<f8'), ('noncachedBaseline', '<f8'), ('ratioNormalToFlushed', '<f8'), ('ratioNormalToNoncached', '<f8'), ('ratioFlushedToNoncached', '<f8'), ('speedupNormalToFlushed', '<f8'), ('speedupNormalToNoncached', '<f8'), ('speedupFlushedToNoncached', '<f8')])
%% Cell type:markdown id: tags:
1) {X}basline: `total.X.computed / total.X.called`
- the baseline of the method X
%% Cell type:code id: tags:
``` python
width = 0.5
x = att_dat['dir']
for n, (l, c) in enumerate((('noncached', 'grey'), ('flushed', 'g'), ('normal', 'b'))):
y = att_dat[l + 'Baseline']
#plt.plot(x, y, label = l, color = c)
plt.bar(x*4*width + n*width, y, width, label = strategy_to_titel(l), color = c)
plt.legend(loc = 'best')
plt.ylabel('% computed')
plt.suptitle('Attribute Baselines', fontsize = 16)
plt.savefig('doc/att_bl.pdf')
!pdfcrop doc/att_bl.pdf doc/att_bl_cropped.pdf > /dev/null
plt.savefig('pngs/att_bl.png')
plt.close()
```
%% Cell type:markdown id: tags:
2) ratio{X1}To{X2}: `total.{X1}.computed / total.{X2}.called`
- the efficiency of the incremental approach in comparison to the method X2,
i.e. the ratio between actual work done in X1 compared to possible work done with method X2
%% Cell type:code id: tags:
``` python
x = att_dat['dir']
for n, (name, c, ls) in enumerate((('FlushedToNoncached', 'orange', '--'),
('NormalToFlushed', 'purple', '-'),
('NormalToNoncached', 'r', '-.'))):
y = att_dat['ratio' + name]
plt.plot(x, y, label = strategy2_to_titel(name), c = c, ls = ls)
#plt.bar(x*3*width + n*width, y, width, label = l, color = c)
plt.legend(loc = 'best')
plt.ylabel('%')
plt.suptitle('Attribute Ratios', fontsize = 16)
plt.savefig('doc/att_r.pdf')
!pdfcrop doc/att_r.pdf doc/att_r_cropped.pdf > /dev/null
plt.savefig('pngs/att_r.png')
plt.close()
```
%% Cell type:markdown id: tags:
3) speedup{X1}To{X2}: `(total.{X2}.computed / total.{X2}.called) - (total.{X1}.computed / total.{X2}.called)`
- = `baseline({X2}) - ratio({X1}, {X2})`
- the "speed-up" of the incremental approach (normal or flushed) in comparison to the method X2
%% Cell type:code id: tags:
``` python
x = att_dat['dir']
for n, (l, c) in enumerate((('NormalToNoncached', 'r'),
('FlushedToNoncached', 'orange'),
('NormalToFlushed', 'yellow'))):
y = att_dat['speedup' + l]
plt.plot(x, y, label = strategy2_to_titel(l), color = c)
#plt.bar(x*3*width + n*width, y, width, label = l, color = c)
plt.legend(loc = 'best')
plt.ylabel('%')
plt.suptitle('Attribute Speed-Ups', fontsize = 16)
plt.savefig('doc/att_sp.pdf')
!pdfcrop doc/att_sp.pdf doc/att_sp_cropped.pdf > /dev/null
plt.savefig('pngs/att_sp.png')
plt.close()
```
%% Cell type:markdown id: tags:
## Boxplots for attribute measures
%% Cell type:code id: tags:
``` python
att_totals = {change: read_att_result(name = 'profiling/splitted/att-percentages_{}.csv'.format(change),
adjust_number = False) for change in kinds['changes']}
```
%% Output
Loaded 31 (0 zero-values) attribute metric run(s) from profiling/splitted/att-percentages_update.csv
Loaded 31 (0 zero-values) attribute metric run(s) from profiling/splitted/att-percentages_sw.csv
Loaded 31 (0 zero-values) attribute metric run(s) from profiling/splitted/att-percentages_res.csv
Loaded 11 (0 zero-values) attribute metric run(s) from profiling/splitted/att-percentages_complex.csv
Loaded 1 (8 zero-values) attribute metric run(s) from profiling/splitted/att-percentages_mixed.csv
Loaded 2 (0 zero-values) attribute metric run(s) from profiling/splitted/att-percentages_mixed.csv
%% Cell type:code id: tags:
``` python
PRINT_NONCACHED = True
```
%% Cell type:code id: tags:
``` python
def draw_att(x, fcolumn, flabel, title, fname_part, rotation_xaxis = None):
""" Draw boxplots for attribute
@param:fcolum: function with one parameter (name) returning column name
@param:flabel: function with one parameter (name) returning label
@param:title: title of plot
@param:fname_part: unique filename part for storing plot
@param:rotation_xaxis: rotation of xaxis ticks (default: no rotation)"""
try:
fig, axes = plt.subplots(ncols=len(kinds['changes']))
# if not rotation_xaxis:
# print dir(fig)
fig.suptitle(title, fontsize = 16)
l = ['normal', 'flushed']
if PRINT_NONCACHED:
l.append('noncached')
for i, change in enumerate(kinds['changes']):
att_dat = att_totals[change]
axes[i].boxplot([att_dat[fcolumn(name)] for name in x],
labels = [flabel(name) for name in x])
axes[i].set_title(change_to_title(change), fontsize=10)
if i > 0:
axes[i].set_yticklabels([])
for ax in axes.flatten():
if PRINT_NONCACHED:
ax.set_ylim([0,1.05])
if rotation_xaxis:
plt.setp(ax.xaxis.get_majorticklabels(), rotation=rotation_xaxis)
# plt.axes().xaxis.set_major_locator(matplotlib.ticker.FixedLocator(range(0, 3, 2)))
# plt.axes().xaxis.set_minor_locator(matplotlib.ticker.FixedLocator([1]))
# plt.axes().xaxis.set_minor_formatter(matplotlib.ticker.FormatStrFormatter("%s"))
# plt.axes().tick_params(which='major', pad=20, axis='x')
plt.subplots_adjust(top=0.85)
plt.savefig('doc/{}.pdf'.format(fname_part))
!pdfcrop {'doc/{}.pdf'.format(fname_part)} {'doc/{}_cropped.pdf'.format(fname_part)} > /dev/null
plt.savefig('pngs/{}.png'.format(fname_part))
except Exception as e:
print 'Error while drawing att in {0}: {1}'.format(change, e)
traceback.print_exc(file=sys.stdout)
finally:
plt.close()
```
%% Cell type:code id: tags:
``` python
def baseline(x):
return '{}Baseline'.format('flushed' if x == 'flush' else x)
draw_att(kinds['strategies'], baseline, functools.partial(strategy_to_titel, length = lshort),
'Attribute Baselines', 'att_box_bl')
x = ['NormalToFlushed', 'NormalToNoncached', 'FlushedToNoncached']
draw_att(x, lambda x: 'ratio{}'.format(x), strategy2_to_titel, 'Attribute Ratios', 'att_box_r', rotation_xaxis = 30)
draw_att(x, lambda x: 'speedup{}'.format(x), strategy2_to_titel, 'Attribute Speedups', 'att_box_sp', rotation_xaxis = 30)
```
......
......@@ -477,13 +477,14 @@ def incoporate_remote_measurements(archive, dryrun = False):
sys.stdout.write('\n')
@task
def factor(column, *files):
def get_average_time(f):
def avg(column, *files):
""" Caclulate the average of the given column for all given files. """
def get_average_value(f):
with open(f) as fd:
r = csv.reader(fd)
values = [float(row[int(column)]) for row in r if not row[0].isalpha()]
return sum(values) / float(len(values))
print map(get_average_time, files)
print { f : get_average_value(f) for f in files }
if __name__ == '__main__':
check()
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment