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 __author__ = 'Alan D. Brunelle <alan.brunelle@hp.com>'
60 #------------------------------------------------------------------------------
64 import getopt, glob, os, sys
65 import matplotlib.pyplot as plt
67 plot_size = [10.9, 8.4] # inches...
76 types = [ 'aqd', 'q2d', 'd2c', 'q2c', 'bnos' ]
77 progs = [ 'btt_plot_%s.py' % t for t in types ]
79 get_base = lambda file: file[file.find('_')+1:file.rfind('_')]
81 #------------------------------------------------------------------------------
83 """Generate fatal error message and exit"""
85 print >>sys.stderr, 'FATAL: %s' % msg
88 #----------------------------------------------------------------------
90 """Retrieve data from files provided.
92 Returns a database containing:
93 'min_x', 'max_x' - Minimum and maximum X values found
94 'min_y', 'max_y' - Minimum and maximum Y values found
95 'x', 'y' - X & Y value arrays
96 'ax', 'ay' - Running average over X & Y --
97 if > 10 values provided...
99 #--------------------------------------------------------------
100 def check(mn, mx, v):
101 """Returns new min, max, and float value for those passed in"""
104 if mn == None or v < mn: mn = v
105 if mx == None or v > mx: mx = v
108 #--------------------------------------------------------------
110 """Computes running average for Xs and Ys"""
112 #------------------------------------------------------
114 """Computes average for array of values passed"""
119 return total / len(vals)
121 #------------------------------------------------------
130 x_range = (xs[-1] - xs[0]) / 100
131 for idx in range(1, len(ys)):
132 if (xs[idx] - _xs[0]) > x_range:
133 axs.append(_avg(_xs))
134 ays.append(_avg(_ys))
144 axs.append(_avg(_xs))
145 ays.append(_avg(_ys))
149 #--------------------------------------------------------------
153 min_x = max_x = min_y = max_y = None
155 if not os.path.exists(file):
156 fatal('%s not found' % file)
158 print 'Processing %s' % file
162 for line in open(file, 'r'):
163 f = line.rstrip().split(None)
164 if line.find('#') == 0 or len(f) < 2:
166 (min_x, max_x, x) = check(min_x, max_x, f[0])
167 (min_y, max_y, y) = check(min_y, max_y, f[1])
171 db[file] = {'x':xs, 'y':ys}
173 db[file]['ax'], db[file]['ay'] = avg(xs, ys)
175 db[file]['ax'] = db[file]['ay'] = None
183 #----------------------------------------------------------------------
184 def parse_args(args):
185 """Parse command line arguments.
187 Returns list of (data) files that need to be processed -- /unless/
188 the -A (--generate-all) option is passed, in which case superfluous
189 data files are ignored...
192 global add_legend, output_file, title_str, type, verbose
195 prog = args[0][args[0].rfind('/')+1:]
196 if prog == 'btt_plot.py':
198 elif not prog in progs:
199 fatal('%s not a valid command name' % prog)
201 type = prog[prog.rfind('_')+1:prog.rfind('.py')]
204 l_opts = [ 'generate-all', 'type', 'no-legend', 'output', 'title',
208 (opts, args) = getopt.getopt(args[1:], s_opts, l_opts)
209 except getopt.error, msg:
210 print >>sys.stderr, msg
214 if o in ('-A', '--generate-all'):
216 elif o in ('-L', '--no-legend'):
218 elif o in ('-o', '--output'):
220 elif o in ('-t', '--type'):
222 fatal('Type %s not supported' % a)
224 elif o in ('-T', '--title'):
226 elif o in ('-v', '--verbose'):
229 if type == None and not generate_all:
230 fatal('Need type of data files to process - (-t <type>)')
234 #------------------------------------------------------------------------------
235 def gen_title(fig, type, title_str):
236 """Sets the title for the figure based upon the type /or/ user title"""
238 if title_str != None:
241 title_str = 'Average Queue Depth'
243 title_str = 'Block Numbers Accessed'
245 title_str = 'Queue (Q) To Issue (D) Average Latencies'
247 title_str = 'Issue (D) To Complete (C) Average Latencies'
249 title_str = 'Queue (Q) To Complete (C) Average Latencies'
251 title = fig.text(.5, .95, title_str, horizontalalignment='center')
252 title.set_fontsize('large')
254 #------------------------------------------------------------------------------
255 def gen_labels(db, ax, type):
256 """Generate X & Y 'axis'"""
258 #----------------------------------------------------------------------
259 def gen_ylabel(ax, type):
260 """Set the Y axis label based upon the type"""
263 str = 'Number of Requests Queued'
270 #----------------------------------------------------------------------
271 xdelta = 0.1 * (db['max_x'] - db['min_x'])
272 ydelta = 0.1 * (db['max_y'] - db['min_y'])
274 ax.set_xlim(db['min_x'] - xdelta, db['max_x'] + xdelta)
275 ax.set_ylim(db['min_y'] - ydelta, db['max_y'] + ydelta)
276 ax.set_xlabel('Runtime (seconds)')
280 #------------------------------------------------------------------------------
281 def generate_output(type, db):
282 """Generate the output plot based upon the type and database"""
284 #----------------------------------------------------------------------
285 def color(idx, style):
286 """Returns a color/symbol type based upon the index passed."""
288 colors = [ 'b', 'g', 'r', 'c', 'm', 'y', 'k' ]
289 l_styles = [ '-', ':', '--', '-.' ]
290 m_styles = [ 'o', '+', '.', ',', 's', 'v', 'x', '<', '>' ]
292 color = colors[idx % len(colors)]
294 style = l_styles[(idx / len(l_styles)) % len(l_styles)]
295 elif style == 'marker':
296 style = m_styles[(idx / len(m_styles)) % len(m_styles)]
298 return '%s%s' % (color, style)
300 #----------------------------------------------------------------------
301 def gen_legends(a, legends):
302 leg = ax.legend(legends, 'best', shadow=True)
303 frame = leg.get_frame()
304 frame.set_facecolor('0.80')
305 for t in leg.get_texts():
306 t.set_fontsize('xx-small')
308 #----------------------------------------------------------------------
309 global add_legend, output_file, title_str, verbose
311 if output_file != None:
314 ofile = '%s.png' % type
317 print 'Generating plot into %s' % ofile
319 fig = plt.figure(figsize=plot_size)
320 ax = fig.add_subplot(111)
322 gen_title(fig, type, title_str)
323 gen_labels(db, ax, type)
332 for file in db.iterkeys():
333 if not file in ['min_x', 'max_x', 'min_y', 'max_y']:
340 ax.plot(dat['x'], dat['y'], color(idx, 'marker'),
342 elif dat['ax'] == None:
343 continue # Don't add legend
345 ax.plot(dat['ax'], dat['ay'], color(idx, 'line'),
348 legends.append(get_base(file))
351 if add_legend and len(legends) > 0:
352 gen_legends(ax, legends)
355 #------------------------------------------------------------------------------
357 """Returns the list of files for the -A option based upon type"""
361 for fn in glob.glob('*c.dat'):
362 for t in [ 'q2q', 'd2d', 'q2c', 'd2c' ]:
368 files = glob.glob('*%s.dat' % type)
371 #------------------------------------------------------------------------------
372 if __name__ == '__main__':
373 files = parse_args(sys.argv)
376 output_file = title_str = type = None
382 generate_output(t, get_data(files))
386 base = get_base(file)
387 title_str = 'Block Numbers Accessed: %s' % base
388 output_file = 'bnos_%s.png' % base
389 generate_output(t, get_data([file]))
391 fatal('Need data files to process')
393 generate_output(type, get_data(files))