3 # btt_plot.py: Generate matplotlib plots for BTT generate data files
5 # (C) Copyright 2009 Hewlett-Packard Development Company, L.P.
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 2 of the License, or
10 # (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this program; if not, write to the Free Software
19 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 btt_plot.py: Generate matplotlib plots for BTT generated data files
26 AQD - Average Queue Depth Running average of queue depths
28 BNOS - Block numbers accessed Markers for each block
30 Q2D - Queue to Issue latencies Running averages
31 D2C - Issue to Complete latencies Running averages
32 Q2C - Queue to Complete latencies Running averages
35 btt_plot_aqd.py equivalent to: btt_plot.py -t aqd <type>=aqd
36 btt_plot_bnos.py equivalent to: btt_plot.py -t bnos <type>=bnos
37 btt_plot_q2d.py equivalent to: btt_plot.py -t q2d <type>=q2d
38 btt_plot_d2c.py equivalent to: btt_plot.py -t d2c <type>=d2c
39 btt_plot_q2c.py equivalent to: btt_plot.py -t q2c <type>=q2c
42 [ -A | --generate-all ] Default: False
43 [ -L | --no-legend ] Default: Legend table produced
44 [ -o <file> | --output=<file> ] Default: <type>.png
45 [ -T <string> | --title=<string> ] Default: Based upon <type>
46 [ -v | --verbose ] Default: False
49 The -A (--generate-all) argument is different: when this is specified,
50 an attempt is made to generate default plots for all 5 types (aqd, bnos,
51 q2d, d2c and q2c). It will find files with the appropriate suffix for
52 each type ('aqd.dat' for example). If such files are found, a plot for
53 that type will be made. The output file name will be the default for
54 each type. The -L (--no-legend) option will be obeyed for all plots,
55 but the -o (--output) and -T (--title) options will be ignored.
58 from __future__ import absolute_import
59 from __future__ import print_function
60 import getopt, glob, os, sys
62 from six.moves import range
63 __author__ = 'Alan D. Brunelle <alan.brunelle@hp.com>'
65 #------------------------------------------------------------------------------
69 import matplotlib.pyplot as plt
71 plot_size = [10.9, 8.4] # inches...
80 types = [ 'aqd', 'q2d', 'd2c', 'q2c', 'live', 'bnos' ]
81 progs = [ 'btt_plot_%s.py' % t for t in types ]
83 get_base = lambda file: file[file.find('_')+1:file.rfind('_')]
85 #------------------------------------------------------------------------------
87 """Generate fatal error message and exit"""
89 print('FATAL: %s' % msg, file=sys.stderr)
92 #------------------------------------------------------------------------------
93 def gen_legends(ax, legends):
94 leg = ax.legend(legends, 'best', shadow=True)
95 frame = leg.get_frame()
96 frame.set_facecolor('0.80')
97 for t in leg.get_texts():
98 t.set_fontsize('xx-small')
100 #----------------------------------------------------------------------
102 """Retrieve data from files provided.
104 Returns a database containing:
105 'min_x', 'max_x' - Minimum and maximum X values found
106 'min_y', 'max_y' - Minimum and maximum Y values found
107 'x', 'y' - X & Y value arrays
108 'ax', 'ay' - Running average over X & Y --
109 if > 10 values provided...
111 #--------------------------------------------------------------
112 def check(mn, mx, v):
113 """Returns new min, max, and float value for those passed in"""
116 if mn is None or v < mn: mn = v
117 if mx is None or v > mx: mx = v
120 #--------------------------------------------------------------
122 """Computes running average for Xs and Ys"""
124 #------------------------------------------------------
126 """Computes average for array of values passed"""
128 return sum(vals) / len(vals)
130 #------------------------------------------------------
139 x_range = (xs[-1] - xs[0]) / 100
140 for idx in range(1, len(ys)):
141 if (xs[idx] - _xs[0]) > x_range:
142 axs.append(_avg(_xs))
143 ays.append(_avg(_ys))
153 axs.append(_avg(_xs))
154 ays.append(_avg(_ys))
158 #--------------------------------------------------------------
162 min_x = max_x = min_y = max_y = None
164 if not os.path.exists(file):
165 fatal('%s not found' % file)
167 print('Processing %s' % file)
171 with open(file, 'r') as fi:
173 f = line.rstrip().split(None)
174 if line.find('#') == 0 or len(f) < 2:
176 (min_x, max_x, x) = check(min_x, max_x, f[0])
177 (min_y, max_y, y) = check(min_y, max_y, f[1])
181 db[file] = {'x':xs, 'y':ys}
183 db[file]['ax'], db[file]['ay'] = avg(xs, ys)
185 db[file]['ax'] = db[file]['ay'] = None
193 #----------------------------------------------------------------------
194 def parse_args(args):
195 """Parse command line arguments.
197 Returns list of (data) files that need to be processed -- /unless/
198 the -A (--generate-all) option is passed, in which case superfluous
199 data files are ignored...
202 global add_legend, output_file, title_str, type, verbose
205 prog = args[0][args[0].rfind('/')+1:]
206 if prog == 'btt_plot.py':
208 elif not prog in progs:
209 fatal('%s not a valid command name' % prog)
211 type = prog[prog.rfind('_')+1:prog.rfind('.py')]
214 l_opts = [ 'generate-all', 'type', 'no-legend', 'output', 'title',
218 (opts, args) = getopt.getopt(args[1:], s_opts, l_opts)
219 except getopt.error as msg:
220 print(msg, file=sys.stderr)
224 if o in ('-A', '--generate-all'):
226 elif o in ('-L', '--no-legend'):
228 elif o in ('-o', '--output'):
230 elif o in ('-t', '--type'):
232 fatal('Type %s not supported' % a)
234 elif o in ('-T', '--title'):
236 elif o in ('-v', '--verbose'):
239 if type is None and not generate_all:
240 fatal('Need type of data files to process - (-t <type>)')
244 #------------------------------------------------------------------------------
245 def gen_title(fig, type, title_str):
246 """Sets the title for the figure based upon the type /or/ user title"""
248 if title_str is not None:
251 title_str = 'Average Queue Depth'
253 title_str = 'Block Numbers Accessed'
255 title_str = 'Queue (Q) To Issue (D) Average Latencies'
257 title_str = 'Issue (D) To Complete (C) Average Latencies'
259 title_str = 'Queue (Q) To Complete (C) Average Latencies'
261 title = fig.text(.5, .95, title_str, horizontalalignment='center')
262 title.set_fontsize('large')
264 #------------------------------------------------------------------------------
265 def gen_labels(db, ax, type):
266 """Generate X & Y 'axis'"""
268 #----------------------------------------------------------------------
269 def gen_ylabel(ax, type):
270 """Set the Y axis label based upon the type"""
273 str = 'Number of Requests Queued'
280 #----------------------------------------------------------------------
281 xdelta = 0.1 * (db['max_x'] - db['min_x'])
282 ydelta = 0.1 * (db['max_y'] - db['min_y'])
284 ax.set_xlim(db['min_x'] - xdelta, db['max_x'] + xdelta)
285 ax.set_ylim(db['min_y'] - ydelta, db['max_y'] + ydelta)
286 ax.set_xlabel('Runtime (seconds)')
290 #------------------------------------------------------------------------------
291 def generate_output(type, db):
292 """Generate the output plot based upon the type and database"""
294 #----------------------------------------------------------------------
295 def color(idx, style):
296 """Returns a color/symbol type based upon the index passed."""
298 colors = [ 'b', 'g', 'r', 'c', 'm', 'y', 'k' ]
299 l_styles = [ '-', ':', '--', '-.' ]
300 m_styles = [ 'o', '+', '.', ',', 's', 'v', 'x', '<', '>' ]
302 color = colors[idx % len(colors)]
304 style = l_styles[int((idx / len(l_styles)) % len(l_styles))]
305 elif style == 'marker':
306 style = m_styles[int((idx / len(m_styles)) % len(m_styles))]
308 return '%s%s' % (color, style)
310 #----------------------------------------------------------------------
311 global add_legend, output_file, title_str, verbose
313 if output_file is not None:
316 ofile = '%s.png' % type
319 print('Generating plot into %s' % ofile)
321 fig = plt.figure(figsize=plot_size)
322 ax = fig.add_subplot(111)
324 gen_title(fig, type, title_str)
325 gen_labels(db, ax, type)
334 for file in six.iterkeys(db):
335 if not file in ['min_x', 'max_x', 'min_y', 'max_y']:
342 ax.plot(dat['x'], dat['y'], color(idx, 'marker'),
344 elif dat['ax'] is None:
345 continue # Don't add legend
347 ax.plot(dat['ax'], dat['ay'], color(idx, 'line'),
350 legends.append(get_base(file))
353 if add_legend and legends:
354 gen_legends(ax, legends)
357 #------------------------------------------------------------------------------
359 """Returns the list of files for the -A option based upon type"""
363 for fn in glob.glob('*c.dat'):
364 for t in [ 'q2q', 'd2d', 'q2c', 'd2c' ]:
370 files = glob.glob('*%s.dat' % type)
373 #------------------------------------------------------------------------------
376 base = get_base(file)
377 title_str = 'Block Numbers Accessed: %s' % base
378 output_file = 'bnos_%s.png' % base
379 generate_output(t, get_data([file]))
381 #------------------------------------------------------------------------------
385 #----------------------------------------------------------------------
386 def get_live_data(fn):
389 with open(fn, 'r') as fi:
391 f = line.rstrip().split()
392 if f[0] != '#' and len(f) == 2:
393 xs.append(float(f[0]))
394 ys.append(float(f[1]))
397 #----------------------------------------------------------------------
399 if a[0] == 'sys' and b[0] == 'sys':
401 if a[0] == 'sys' or a[2][0] < b[2][0]:
403 if b[0] == 'sys' or a[2][0] > b[2][0]:
407 #----------------------------------------------------------------------
408 def turn_off_ticks(ax):
409 for tick in ax.xaxis.get_major_ticks():
410 tick.tick1On = tick.tick2On = False
411 for tick in ax.yaxis.get_major_ticks():
412 tick.tick1On = tick.tick2On = False
413 for tick in ax.xaxis.get_minor_ticks():
414 tick.tick1On = tick.tick2On = False
415 for tick in ax.yaxis.get_minor_ticks():
416 tick.tick1On = tick.tick2On = False
418 #----------------------------------------------------------------------
419 fig = plt.figure(figsize=plot_size)
420 ax = fig.add_subplot(111)
424 if not os.path.exists(fn):
426 (xs, ys) = get_live_data(fn)
427 db.append([fn[:fn.find('_live.dat')], xs, ys])
431 ax.plot(rec[1], rec[2])
433 gen_title(fig, 'live', 'Active I/O Per Device')
434 ax.set_xlabel('Runtime (seconds)')
435 ax.set_ylabel('Device')
438 ax.set_xlim(-0.1, db[0][1][-1]+1)
439 ax.set_yticks([idx for idx in range(0, len(db))])
440 ax.yaxis.set_ticklabels([rec[0] for rec in db])
443 plt.savefig('live.png')
444 plt.savefig('live.eps')
446 #------------------------------------------------------------------------------
447 if __name__ == '__main__':
448 files = parse_args(sys.argv)
451 output_file = title_str = type = None
461 generate_output(t, get_data(files))
465 fatal('Need data files to process')
467 generate_output(type, get_data(files))