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