fix hang when BLKTRACESETUP fails and "-o -" is used
[blktrace.git] / btt / btt_plot.py
CommitLineData
726d2aee
AB
1#! /usr/bin/env python
2#
3# btt_plot.py: Generate matplotlib plots for BTT generate data files
4#
5# (C) Copyright 2009 Hewlett-Packard Development Company, L.P.
6#
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.
11#
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.
16#
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
20#
21
22"""
23btt_plot.py: Generate matplotlib plots for BTT generated data files
24
25Files handled:
26 AQD - Average Queue Depth Running average of queue depths
27
28 BNOS - Block numbers accessed Markers for each block
29
30 Q2D - Queue to Issue latencies Running averages
31 D2C - Issue to Complete latencies Running averages
32 Q2C - Queue to Complete latencies Running averages
33
34Usage:
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
40
41Arguments:
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
47 <data-files...>
48
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.
56"""
57
70d5ca2d
ES
58from __future__ import absolute_import
59from __future__ import print_function
fd3766eb 60import getopt, glob, os, sys
70d5ca2d
ES
61import six
62from six.moves import range
726d2aee
AB
63__author__ = 'Alan D. Brunelle <alan.brunelle@hp.com>'
64
65#------------------------------------------------------------------------------
66
67import matplotlib
68matplotlib.use('Agg')
726d2aee
AB
69import matplotlib.pyplot as plt
70
71plot_size = [10.9, 8.4] # inches...
72
73add_legend = True
74generate_all = False
75output_file = None
76title_str = None
77type = None
78verbose = False
79
2e37a10e 80types = [ 'aqd', 'q2d', 'd2c', 'q2c', 'live', 'bnos' ]
726d2aee
AB
81progs = [ 'btt_plot_%s.py' % t for t in types ]
82
83get_base = lambda file: file[file.find('_')+1:file.rfind('_')]
84
85#------------------------------------------------------------------------------
86def fatal(msg):
87 """Generate fatal error message and exit"""
88
70d5ca2d 89 print('FATAL: %s' % msg, file=sys.stderr)
726d2aee
AB
90 sys.exit(1)
91
2e37a10e
AB
92#------------------------------------------------------------------------------
93def 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')
99
726d2aee
AB
100#----------------------------------------------------------------------
101def get_data(files):
102 """Retrieve data from files provided.
103
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...
110 """
111 #--------------------------------------------------------------
112 def check(mn, mx, v):
113 """Returns new min, max, and float value for those passed in"""
114
115 v = float(v)
e984bd6d
VL
116 if mn is None or v < mn: mn = v
117 if mx is None or v > mx: mx = v
726d2aee
AB
118 return mn, mx, v
119
120 #--------------------------------------------------------------
121 def avg(xs, ys):
122 """Computes running average for Xs and Ys"""
123
124 #------------------------------------------------------
125 def _avg(vals):
126 """Computes average for array of values passed"""
127
86c6ec28 128 return sum(vals) / len(vals)
726d2aee
AB
129
130 #------------------------------------------------------
131 if len(xs) < 1000:
132 return xs, ys
133
134 axs = [xs[0]]
135 ays = [ys[0]]
136 _xs = [xs[0]]
137 _ys = [ys[0]]
138
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))
144 del _xs, _ys
145
146 _xs = [xs[idx]]
147 _ys = [ys[idx]]
148 else:
149 _xs.append(xs[idx])
150 _ys.append(ys[idx])
151
152 if len(_xs) > 1:
153 axs.append(_avg(_xs))
154 ays.append(_avg(_ys))
155
156 return axs, ays
157
158 #--------------------------------------------------------------
159 global verbose
160
161 db = {}
162 min_x = max_x = min_y = max_y = None
163 for file in files:
164 if not os.path.exists(file):
165 fatal('%s not found' % file)
166 elif verbose:
70d5ca2d 167 print('Processing %s' % file)
726d2aee
AB
168
169 xs = []
170 ys = []
db4f6340
VL
171 with open(file, 'r') as fi:
172 for line in fi:
173 f = line.rstrip().split(None)
174 if line.find('#') == 0 or len(f) < 2:
175 continue
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])
178 xs.append(x)
179 ys.append(y)
726d2aee
AB
180
181 db[file] = {'x':xs, 'y':ys}
182 if len(xs) > 10:
183 db[file]['ax'], db[file]['ay'] = avg(xs, ys)
184 else:
185 db[file]['ax'] = db[file]['ay'] = None
186
187 db['min_x'] = min_x
188 db['max_x'] = max_x
189 db['min_y'] = min_y
190 db['max_y'] = max_y
191 return db
192
193#----------------------------------------------------------------------
194def parse_args(args):
195 """Parse command line arguments.
196
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...
200 """
201
202 global add_legend, output_file, title_str, type, verbose
203 global generate_all
204
205 prog = args[0][args[0].rfind('/')+1:]
206 if prog == 'btt_plot.py':
207 pass
208 elif not prog in progs:
209 fatal('%s not a valid command name' % prog)
210 else:
211 type = prog[prog.rfind('_')+1:prog.rfind('.py')]
212
213 s_opts = 'ALo:t:T:v'
214 l_opts = [ 'generate-all', 'type', 'no-legend', 'output', 'title',
215 'verbose' ]
216
217 try:
218 (opts, args) = getopt.getopt(args[1:], s_opts, l_opts)
70d5ca2d
ES
219 except getopt.error as msg:
220 print(msg, file=sys.stderr)
726d2aee
AB
221 fatal(__doc__)
222
223 for (o, a) in opts:
224 if o in ('-A', '--generate-all'):
225 generate_all = True
226 elif o in ('-L', '--no-legend'):
227 add_legend = False
228 elif o in ('-o', '--output'):
229 output_file = a
230 elif o in ('-t', '--type'):
231 if not a in types:
232 fatal('Type %s not supported' % a)
233 type = a
234 elif o in ('-T', '--title'):
235 title_str = a
236 elif o in ('-v', '--verbose'):
237 verbose = True
238
e984bd6d 239 if type is None and not generate_all:
726d2aee
AB
240 fatal('Need type of data files to process - (-t <type>)')
241
242 return args
243
244#------------------------------------------------------------------------------
245def gen_title(fig, type, title_str):
246 """Sets the title for the figure based upon the type /or/ user title"""
247
e984bd6d 248 if title_str is not None:
726d2aee
AB
249 pass
250 elif type == 'aqd':
251 title_str = 'Average Queue Depth'
252 elif type == 'bnos':
253 title_str = 'Block Numbers Accessed'
254 elif type == 'q2d':
255 title_str = 'Queue (Q) To Issue (D) Average Latencies'
256 elif type == 'd2c':
257 title_str = 'Issue (D) To Complete (C) Average Latencies'
258 elif type == 'q2c':
259 title_str = 'Queue (Q) To Complete (C) Average Latencies'
260
261 title = fig.text(.5, .95, title_str, horizontalalignment='center')
262 title.set_fontsize('large')
263
264#------------------------------------------------------------------------------
265def gen_labels(db, ax, type):
266 """Generate X & Y 'axis'"""
267
268 #----------------------------------------------------------------------
269 def gen_ylabel(ax, type):
270 """Set the Y axis label based upon the type"""
271
272 if type == 'aqd':
273 str = 'Number of Requests Queued'
274 elif type == 'bnos':
275 str = 'Block Number'
276 else:
277 str = 'Seconds'
278 ax.set_ylabel(str)
279
280 #----------------------------------------------------------------------
281 xdelta = 0.1 * (db['max_x'] - db['min_x'])
282 ydelta = 0.1 * (db['max_y'] - db['min_y'])
283
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)')
287 ax.grid(True)
288 gen_ylabel(ax, type)
289
290#------------------------------------------------------------------------------
291def generate_output(type, db):
292 """Generate the output plot based upon the type and database"""
293
294 #----------------------------------------------------------------------
295 def color(idx, style):
296 """Returns a color/symbol type based upon the index passed."""
297
70d5ca2d 298 colors = [ 'b', 'g', 'r', 'c', 'm', 'y', 'k' ]
726d2aee
AB
299 l_styles = [ '-', ':', '--', '-.' ]
300 m_styles = [ 'o', '+', '.', ',', 's', 'v', 'x', '<', '>' ]
301
302 color = colors[idx % len(colors)]
303 if style == 'line':
70d5ca2d 304 style = l_styles[int((idx / len(l_styles)) % len(l_styles))]
726d2aee 305 elif style == 'marker':
70d5ca2d 306 style = m_styles[int((idx / len(m_styles)) % len(m_styles))]
726d2aee
AB
307
308 return '%s%s' % (color, style)
309
726d2aee
AB
310 #----------------------------------------------------------------------
311 global add_legend, output_file, title_str, verbose
312
e984bd6d 313 if output_file is not None:
726d2aee
AB
314 ofile = output_file
315 else:
316 ofile = '%s.png' % type
317
318 if verbose:
70d5ca2d 319 print('Generating plot into %s' % ofile)
726d2aee
AB
320
321 fig = plt.figure(figsize=plot_size)
322 ax = fig.add_subplot(111)
323
324 gen_title(fig, type, title_str)
325 gen_labels(db, ax, type)
326
327 idx = 0
328 if add_legend:
329 legends = []
330 else:
331 legends = None
332
333 keys = []
70d5ca2d 334 for file in six.iterkeys(db):
726d2aee
AB
335 if not file in ['min_x', 'max_x', 'min_y', 'max_y']:
336 keys.append(file)
337
338 keys.sort()
339 for file in keys:
340 dat = db[file]
341 if type == 'bnos':
342 ax.plot(dat['x'], dat['y'], color(idx, 'marker'),
343 markersize=1)
e984bd6d 344 elif dat['ax'] is None:
726d2aee
AB
345 continue # Don't add legend
346 else:
347 ax.plot(dat['ax'], dat['ay'], color(idx, 'line'),
348 linewidth=1.0)
349 if add_legend:
350 legends.append(get_base(file))
351 idx += 1
352
592c70d0 353 if add_legend and legends:
726d2aee
AB
354 gen_legends(ax, legends)
355 plt.savefig(ofile)
356
357#------------------------------------------------------------------------------
358def get_files(type):
359 """Returns the list of files for the -A option based upon type"""
360
361 if type == 'bnos':
362 files = []
363 for fn in glob.glob('*c.dat'):
364 for t in [ 'q2q', 'd2d', 'q2c', 'd2c' ]:
365 if fn.find(t) >= 0:
366 break
367 else:
368 files.append(fn)
369 else:
370 files = glob.glob('*%s.dat' % type)
371 return files
372
2e37a10e
AB
373#------------------------------------------------------------------------------
374def do_bnos(files):
375 for file in files:
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]))
380
381#------------------------------------------------------------------------------
382def do_live(files):
383 global plot_size
384
385 #----------------------------------------------------------------------
386 def get_live_data(fn):
387 xs = []
388 ys = []
db4f6340
VL
389 with open(fn, 'r') as fi:
390 for line in 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]))
2e37a10e
AB
395 return xs, ys
396
397 #----------------------------------------------------------------------
398 def live_sort(a, b):
399 if a[0] == 'sys' and b[0] == 'sys':
400 return 0
af756d57 401 if a[0] == 'sys' or a[2][0] < b[2][0]:
2e37a10e 402 return -1
af756d57 403 if b[0] == 'sys' or a[2][0] > b[2][0]:
2e37a10e 404 return 1
af756d57 405 return 0
2e37a10e
AB
406
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
417
418 #----------------------------------------------------------------------
419 fig = plt.figure(figsize=plot_size)
420 ax = fig.add_subplot(111)
421
422 db = []
423 for fn in files:
424 if not os.path.exists(fn):
425 continue
426 (xs, ys) = get_live_data(fn)
427 db.append([fn[:fn.find('_live.dat')], xs, ys])
428 db.sort(live_sort)
429
430 for rec in db:
431 ax.plot(rec[1], rec[2])
432
433 gen_title(fig, 'live', 'Active I/O Per Device')
434 ax.set_xlabel('Runtime (seconds)')
435 ax.set_ylabel('Device')
436 ax.grid(False)
437
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])
441 turn_off_ticks(ax)
442
443 plt.savefig('live.png')
444 plt.savefig('live.eps')
445
726d2aee
AB
446#------------------------------------------------------------------------------
447if __name__ == '__main__':
448 files = parse_args(sys.argv)
449
450 if generate_all:
451 output_file = title_str = type = None
452 for t in types:
453 files = get_files(t)
592c70d0 454 if files == 0:
726d2aee 455 continue
2e37a10e
AB
456 elif t == 'bnos':
457 do_bnos(files)
458 elif t == 'live':
459 do_live(files)
460 else:
726d2aee
AB
461 generate_output(t, get_data(files))
462 continue
463
592c70d0 464 elif not files:
726d2aee
AB
465 fatal('Need data files to process')
466 else:
467 generate_output(type, get_data(files))
468 sys.exit(0)