blob: 0e8990157f059b38150ce222063426389a3f4e74 [file] [log] [blame]
ivica05cfcd32015-09-07 06:04:16 -07001#!/usr/bin/env python
2# Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
3#
4# Use of this source code is governed by a BSD-style license
5# that can be found in the LICENSE file in the root of the source
6# tree. An additional intellectual property rights grant can be found
7# in the file PATENTS. All contributing project authors may
8# be found in the AUTHORS file in the root of the source tree.
9
ivica5d6a06c2015-09-17 05:30:24 -070010"""Generate graphs for data generated by loopback tests.
ivica05cfcd32015-09-07 06:04:16 -070011
12Usage examples:
13 Show end to end time for a single full stack test.
14 ./full_stack_plot.py -df end_to_end -o 600 --frames 1000 vp9_data.txt
15
16 Show simultaneously PSNR and encoded frame size for two different runs of
17 full stack test. Averaged over a cycle of 200 frames. Used e.g. for
18 screenshare slide test.
19 ./full_stack_plot.py -c 200 -df psnr -drf encoded_frame_size \\
20 before.txt after.txt
21
22 Similar to the previous test, but multiple graphs.
23 ./full_stack_plot.py -c 200 -df psnr vp8.txt vp9.txt --next \\
24 -c 200 -df sender_time vp8.txt vp9.txt --next \\
25 -c 200 -df end_to_end vp8.txt vp9.txt
26"""
27
28import argparse
29from collections import defaultdict
30import itertools
31import sys
32import matplotlib.pyplot as plt
33import numpy
34
35# Fields
36DROPPED = 0
kjellander81044792015-10-06 11:34:08 -070037INPUT_TIME = 1 # ms
38SEND_TIME = 2 # ms
39RECV_TIME = 3 # ms
40ENCODED_FRAME_SIZE = 4 # bytes
41PSNR = 5
42SSIM = 6
43RENDER_TIME = 7 # ms
ivica05cfcd32015-09-07 06:04:16 -070044
kjellander81044792015-10-06 11:34:08 -070045TOTAL_RAW_FIELDS = 8
ivica05cfcd32015-09-07 06:04:16 -070046
47SENDER_TIME = TOTAL_RAW_FIELDS + 0
48RECEIVER_TIME = TOTAL_RAW_FIELDS + 1
49END_TO_END = TOTAL_RAW_FIELDS + 2
50RENDERED_DELTA = TOTAL_RAW_FIELDS + 3
51
52FIELD_MASK = 255
53
54# Options
55HIDE_DROPPED = 256
56RIGHT_Y_AXIS = 512
57
58# internal field id, field name, title
59_fields = [
60 # Raw
61 (DROPPED, "dropped", "dropped"),
62 (INPUT_TIME, "input_time_ms", "input time"),
63 (SEND_TIME, "send_time_ms", "send time"),
64 (RECV_TIME, "recv_time_ms", "recv time"),
65 (ENCODED_FRAME_SIZE, "encoded_frame_size", "encoded frame size"),
66 (PSNR, "psnr", "PSNR"),
67 (SSIM, "ssim", "SSIM"),
68 (RENDER_TIME, "render_time_ms", "render time"),
69 # Auto-generated
70 (SENDER_TIME, "sender_time", "sender time"),
71 (RECEIVER_TIME, "receiver_time", "receiver time"),
72 (END_TO_END, "end_to_end", "end to end"),
73 (RENDERED_DELTA, "rendered_delta", "rendered delta"),
74]
75
76name_to_id = {field[1]: field[0] for field in _fields}
77id_to_title = {field[0]: field[2] for field in _fields}
78
ivica05cfcd32015-09-07 06:04:16 -070079def field_arg_to_id(arg):
80 if arg == "none":
81 return None
82 if arg in name_to_id:
83 return name_to_id[arg]
84 if arg + "_ms" in name_to_id:
85 return name_to_id[arg + "_ms"]
86 raise Exception("Unrecognized field name \"{}\"".format(arg))
87
88
89class PlotLine(object):
90 """Data for a single graph line."""
91
92 def __init__(self, label, values, flags):
93 self.label = label
94 self.values = values
95 self.flags = flags
96
97
98class Data(object):
99 """Object representing one full stack test."""
100
101 def __init__(self, filename):
102 self.title = ""
103 self.length = 0
104 self.samples = defaultdict(list)
105
106 self._read_samples(filename)
107
108 def _read_samples(self, filename):
109 """Reads graph data from the given file."""
110 f = open(filename)
111 it = iter(f)
112
113 self.title = it.next().strip()
114 self.length = int(it.next())
115 field_names = [name.strip() for name in it.next().split()]
116 field_ids = [name_to_id[name] for name in field_names]
117
118 for field_id in field_ids:
119 self.samples[field_id] = [0.0] * self.length
120
121 for sample_id in xrange(self.length):
122 for col, value in enumerate(it.next().split()):
123 self.samples[field_ids[col]][sample_id] = float(value)
124
125 self._subtract_first_input_time()
126 self._generate_additional_data()
127
128 f.close()
129
130 def _subtract_first_input_time(self):
131 offset = self.samples[INPUT_TIME][0]
132 for field in [INPUT_TIME, SEND_TIME, RECV_TIME, RENDER_TIME]:
133 if field in self.samples:
134 self.samples[field] = [x - offset for x in self.samples[field]]
135
136 def _generate_additional_data(self):
137 """Calculates sender time, receiver time etc. from the raw data."""
138 s = self.samples
139 last_render_time = 0
140 for field_id in [SENDER_TIME, RECEIVER_TIME, END_TO_END, RENDERED_DELTA]:
141 s[field_id] = [0] * self.length
142
143 for k in range(self.length):
144 s[SENDER_TIME][k] = s[SEND_TIME][k] - s[INPUT_TIME][k]
145
146 decoded_time = s[RENDER_TIME][k]
147 s[RECEIVER_TIME][k] = decoded_time - s[RECV_TIME][k]
148 s[END_TO_END][k] = decoded_time - s[INPUT_TIME][k]
149 if not s[DROPPED][k]:
150 if k > 0:
151 s[RENDERED_DELTA][k] = decoded_time - last_render_time
152 last_render_time = decoded_time
153
154 def _hide(self, values):
155 """
156 Replaces values for dropped frames with None.
157 These values are then skipped by the plot() method.
158 """
159
160 return [None if self.samples[DROPPED][k] else values[k]
161 for k in range(len(values))]
162
163 def add_samples(self, config, target_lines_list):
164 """Creates graph lines from the current data set with given config."""
165 for field in config.fields:
166 # field is None means the user wants just to skip the color.
167 if field is None:
168 target_lines_list.append(None)
169 continue
170
171 field_id = field & FIELD_MASK
172 values = self.samples[field_id]
173
174 if field & HIDE_DROPPED:
175 values = self._hide(values)
176
177 target_lines_list.append(PlotLine(
178 self.title + " " + id_to_title[field_id],
179 values, field & ~FIELD_MASK))
180
181
182def average_over_cycle(values, length):
183 """
184 Returns the list:
185 [
186 avg(values[0], values[length], ...),
187 avg(values[1], values[length + 1], ...),
188 ...
189 avg(values[length - 1], values[2 * length - 1], ...),
190 ]
191
192 Skips None values when calculating the average value.
193 """
194
195 total = [0.0] * length
196 count = [0] * length
197 for k in range(len(values)):
198 if values[k] is not None:
199 total[k % length] += values[k]
200 count[k % length] += 1
201
202 result = [0.0] * length
203 for k in range(length):
204 result[k] = total[k] / count[k] if count[k] else None
205 return result
206
207
208class PlotConfig(object):
209 """Object representing a single graph."""
210
211 def __init__(self, fields, data_list, cycle_length=None, frames=None,
212 offset=0, output_filename=None, title="Graph"):
213 self.fields = fields
214 self.data_list = data_list
215 self.cycle_length = cycle_length
216 self.frames = frames
217 self.offset = offset
218 self.output_filename = output_filename
219 self.title = title
220
221 def plot(self, ax1):
222 lines = []
223 for data in self.data_list:
224 if not data:
225 # Add None lines to skip the colors.
226 lines.extend([None] * len(self.fields))
227 else:
228 data.add_samples(self, lines)
229
230 def _slice_values(values):
231 if self.offset:
232 values = values[self.offset:]
233 if self.frames:
234 values = values[:self.frames]
235 return values
236
237 length = None
238 for line in lines:
239 if line is None:
240 continue
241
242 line.values = _slice_values(line.values)
243 if self.cycle_length:
244 line.values = average_over_cycle(line.values, self.cycle_length)
245
246 if length is None:
247 length = len(line.values)
248 elif length != len(line.values):
249 raise Exception("All arrays should have the same length!")
250
251 ax1.set_xlabel("Frame", fontsize="large")
252 if any(line.flags & RIGHT_Y_AXIS for line in lines if line):
253 ax2 = ax1.twinx()
254 ax2.set_xlabel("Frame", fontsize="large")
255 else:
256 ax2 = None
257
258 # Have to implement color_cycle manually, due to two scales in a graph.
259 color_cycle = ["b", "r", "g", "c", "m", "y", "k"]
260 color_iter = itertools.cycle(color_cycle)
261
262 for line in lines:
263 if not line:
264 color_iter.next()
265 continue
266
267 if self.cycle_length:
268 x = numpy.array(range(self.cycle_length))
269 else:
270 x = numpy.array(range(self.offset, self.offset + len(line.values)))
271 y = numpy.array(line.values)
272 ax = ax2 if line.flags & RIGHT_Y_AXIS else ax1
273 ax.plot(x, y, "o-", label=line.label, markersize=3.0, linewidth=1.0,
274 color=color_iter.next())
275
276 ax1.grid(True)
277 if ax2:
278 ax1.legend(loc="upper left", shadow=True, fontsize="large")
279 ax2.legend(loc="upper right", shadow=True, fontsize="large")
280 else:
281 ax1.legend(loc="best", shadow=True, fontsize="large")
282
283
284def load_files(filenames):
285 result = []
286 for filename in filenames:
287 if filename in load_files.cache:
288 result.append(load_files.cache[filename])
289 else:
290 data = Data(filename)
291 load_files.cache[filename] = data
292 result.append(data)
293 return result
294load_files.cache = {}
295
296
297def get_parser():
298 class CustomAction(argparse.Action):
ivica05cfcd32015-09-07 06:04:16 -0700299 def __call__(self, parser, namespace, values, option_string=None):
300 if "ordered_args" not in namespace:
301 namespace.ordered_args = []
302 namespace.ordered_args.append((self.dest, values))
303
304 parser = argparse.ArgumentParser(
305 description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
306
307 parser.add_argument(
308 "-c", "--cycle_length", nargs=1, action=CustomAction,
309 type=int, help="Cycle length over which to average the values.")
310 parser.add_argument(
311 "-f", "--field", nargs=1, action=CustomAction,
312 help="Name of the field to show. Use 'none' to skip a color.")
313 parser.add_argument("-r", "--right", nargs=0, action=CustomAction,
314 help="Use right Y axis for given field.")
315 parser.add_argument("-d", "--drop", nargs=0, action=CustomAction,
316 help="Hide values for dropped frames.")
317 parser.add_argument("-o", "--offset", nargs=1, action=CustomAction, type=int,
318 help="Frame offset.")
319 parser.add_argument("-n", "--next", nargs=0, action=CustomAction,
320 help="Separator for multiple graphs.")
321 parser.add_argument(
322 "--frames", nargs=1, action=CustomAction, type=int,
323 help="Frame count to show or take into account while averaging.")
324 parser.add_argument("-t", "--title", nargs=1, action=CustomAction,
325 help="Title of the graph.")
326 parser.add_argument(
327 "-O", "--output_filename", nargs=1, action=CustomAction,
328 help="Use to save the graph into a file. "
329 "Otherwise, a window will be shown.")
330 parser.add_argument(
331 "files", nargs="+", action=CustomAction,
ivica5d6a06c2015-09-17 05:30:24 -0700332 help="List of text-based files generated by loopback tests.")
ivica05cfcd32015-09-07 06:04:16 -0700333 return parser
334
335
336def _plot_config_from_args(args, graph_num):
337 # Pylint complains about using kwargs, so have to do it this way.
338 cycle_length = None
339 frames = None
340 offset = 0
341 output_filename = None
342 title = "Graph"
343
344 fields = []
345 files = []
346 mask = 0
347 for key, values in args:
348 if key == "cycle_length":
349 cycle_length = values[0]
350 elif key == "frames":
351 frames = values[0]
352 elif key == "offset":
353 offset = values[0]
354 elif key == "output_filename":
355 output_filename = values[0]
356 elif key == "title":
357 title = values[0]
358 elif key == "drop":
359 mask |= HIDE_DROPPED
360 elif key == "right":
361 mask |= RIGHT_Y_AXIS
362 elif key == "field":
363 field_id = field_arg_to_id(values[0])
364 fields.append(field_id | mask if field_id is not None else None)
365 mask = 0 # Reset mask after the field argument.
366 elif key == "files":
367 files.extend(values)
368
369 if not files:
370 raise Exception("Missing file argument(s) for graph #{}".format(graph_num))
371 if not fields:
372 raise Exception("Missing field argument(s) for graph #{}".format(graph_num))
373
374 return PlotConfig(fields, load_files(files), cycle_length=cycle_length,
375 frames=frames, offset=offset, output_filename=output_filename,
376 title=title)
377
378
379def plot_configs_from_args(args):
380 """Generates plot configs for given command line arguments."""
381 # The way it works:
382 # First we detect separators -n/--next and split arguments into groups, one
383 # for each plot. For each group, we partially parse it with
384 # argparse.ArgumentParser, modified to remember the order of arguments.
385 # Then we traverse the argument list and fill the PlotConfig.
386 args = itertools.groupby(args, lambda x: x in ["-n", "--next"])
387 args = list(list(group) for match, group in args if not match)
388
389 parser = get_parser()
390 plot_configs = []
391 for index, raw_args in enumerate(args):
392 graph_args = parser.parse_args(raw_args).ordered_args
393 plot_configs.append(_plot_config_from_args(graph_args, index))
394 return plot_configs
395
396
397def show_or_save_plots(plot_configs):
398 for config in plot_configs:
399 fig = plt.figure(figsize=(14.0, 10.0))
400 ax = fig.add_subplot(1, 1, 1)
401
402 plt.title(config.title)
403 config.plot(ax)
404 if config.output_filename:
405 print "Saving to", config.output_filename
406 fig.savefig(config.output_filename)
407 plt.close(fig)
408
409 plt.show()
410
411if __name__ == "__main__":
412 show_or_save_plots(plot_configs_from_args(sys.argv[1:]))