1 # Copyright (c) 2018 Cisco and/or its affiliates.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
6 # http://www.apache.org/licenses/LICENSE-2.0
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
14 """Algorithms to generate plots.
20 import plotly.offline as ploff
21 import plotly.graph_objs as plgo
23 from plotly.exceptions import PlotlyError
24 from collections import OrderedDict
25 from copy import deepcopy
27 from utils import mean
30 COLORS = ["SkyBlue", "Olive", "Purple", "Coral", "Indigo", "Pink",
31 "Chocolate", "Brown", "Magenta", "Cyan", "Orange", "Black",
32 "Violet", "Blue", "Yellow", "BurlyWood", "CadetBlue", "Crimson",
33 "DarkBlue", "DarkCyan", "DarkGreen", "Green", "GoldenRod",
34 "LightGreen", "LightSeaGreen", "LightSkyBlue", "Maroon",
35 "MediumSeaGreen", "SeaGreen", "LightSlateGrey"]
38 def generate_plots(spec, data):
39 """Generate all plots specified in the specification file.
41 :param spec: Specification read from the specification file.
42 :param data: Data to process.
43 :type spec: Specification
47 logging.info("Generating the plots ...")
48 for index, plot in enumerate(spec.plots):
50 logging.info(" Plot nr {0}: {1}".format(index + 1,
51 plot.get("title", "")))
52 plot["limits"] = spec.configuration["limits"]
53 eval(plot["algorithm"])(plot, data)
54 logging.info(" Done.")
55 except NameError as err:
56 logging.error("Probably algorithm '{alg}' is not defined: {err}".
57 format(alg=plot["algorithm"], err=repr(err)))
61 def plot_performance_box(plot, input_data):
62 """Generate the plot(s) with algorithm: plot_performance_box
63 specified in the specification file.
65 :param plot: Plot to generate.
66 :param input_data: Data to process.
67 :type plot: pandas.Series
68 :type input_data: InputData
72 plot_title = plot.get("title", "")
73 logging.info(" Creating the data set for the {0} '{1}'.".
74 format(plot.get("type", ""), plot_title))
75 data = input_data.filter_data(plot)
77 logging.error("No data.")
80 # Prepare the data for the plot
86 if y_vals.get(test["parent"], None) is None:
87 y_vals[test["parent"]] = list()
88 y_tags[test["parent"]] = test.get("tags", None)
90 if test["type"] in ("NDRPDR", ):
91 if "-pdr" in plot_title.lower():
92 y_vals[test["parent"]].\
93 append(test["throughput"]["PDR"]["LOWER"])
94 elif "-ndr" in plot_title.lower():
95 y_vals[test["parent"]]. \
96 append(test["throughput"]["NDR"]["LOWER"])
101 except (KeyError, TypeError):
102 y_vals[test["parent"]].append(None)
105 order = plot.get("sort", None)
107 y_sorted = OrderedDict()
108 y_tags_l = {s: [t.lower() for t in ts] for s, ts in y_tags.items()}
111 for suite, tags in y_tags_l.items():
113 tag = tag.split(" ")[-1]
114 if tag.lower() in tags:
117 if tag.lower() not in tags:
120 y_sorted[suite] = y_vals.pop(suite)
123 except KeyError as err:
124 logging.error("Not found: {0}".format(err))
130 # Add None to the lists with missing data
132 for val in y_sorted.values():
133 if len(val) > max_len:
135 for key, val in y_sorted.items():
136 if len(val) < max_len:
137 val.extend([None for _ in range(max_len - len(val))])
141 df = pd.DataFrame(y_sorted)
144 for i, col in enumerate(df.columns):
145 name = "{0}. {1}".format(i + 1, col.lower().replace('-ndrpdrdisc', '').
146 replace('-ndrpdr', ''))
148 traces.append(plgo.Box(x=[str(i + 1) + '.'] * len(df[col]),
149 y=[y / 1000000 if y else None for y in df[col]],
152 val_max = max(df[col])
154 y_max.append(int(val_max / 1000000) + 1)
158 layout = deepcopy(plot["layout"])
159 if layout.get("title", None):
160 layout["title"] = "<b>Packet Throughput:</b> {0}". \
161 format(layout["title"])
163 layout["yaxis"]["range"] = [0, max(y_max)]
164 plpl = plgo.Figure(data=traces, layout=layout)
167 logging.info(" Writing file '{0}{1}'.".
168 format(plot["output-file"], plot["output-file-type"]))
169 ploff.plot(plpl, show_link=False, auto_open=False,
170 filename='{0}{1}'.format(plot["output-file"],
171 plot["output-file-type"]))
172 except PlotlyError as err:
173 logging.error(" Finished with error: {}".
174 format(str(err).replace("\n", " ")))
178 def plot_latency_error_bars(plot, input_data):
179 """Generate the plot(s) with algorithm: plot_latency_error_bars
180 specified in the specification file.
182 :param plot: Plot to generate.
183 :param input_data: Data to process.
184 :type plot: pandas.Series
185 :type input_data: InputData
189 plot_title = plot.get("title", "")
190 logging.info(" Creating the data set for the {0} '{1}'.".
191 format(plot.get("type", ""), plot_title))
192 data = input_data.filter_data(plot)
194 logging.error("No data.")
197 # Prepare the data for the plot
203 if y_tmp_vals.get(test["parent"], None) is None:
204 y_tmp_vals[test["parent"]] = [
205 list(), # direction1, min
206 list(), # direction1, avg
207 list(), # direction1, max
208 list(), # direction2, min
209 list(), # direction2, avg
210 list() # direction2, max
212 y_tags[test["parent"]] = test.get("tags", None)
214 if test["type"] in ("NDRPDR", ):
215 if "-pdr" in plot_title.lower():
217 elif "-ndr" in plot_title.lower():
221 y_tmp_vals[test["parent"]][0].append(
222 test["latency"][ttype]["direction1"]["min"])
223 y_tmp_vals[test["parent"]][1].append(
224 test["latency"][ttype]["direction1"]["avg"])
225 y_tmp_vals[test["parent"]][2].append(
226 test["latency"][ttype]["direction1"]["max"])
227 y_tmp_vals[test["parent"]][3].append(
228 test["latency"][ttype]["direction2"]["min"])
229 y_tmp_vals[test["parent"]][4].append(
230 test["latency"][ttype]["direction2"]["avg"])
231 y_tmp_vals[test["parent"]][5].append(
232 test["latency"][ttype]["direction2"]["max"])
235 except (KeyError, TypeError):
239 order = plot.get("sort", None)
241 y_sorted = OrderedDict()
242 y_tags_l = {s: [t.lower() for t in ts] for s, ts in y_tags.items()}
244 for suite, tags in y_tags_l.items():
245 if tag.lower() in tags:
247 y_sorted[suite] = y_tmp_vals.pop(suite)
249 except KeyError as err:
250 logging.error("Not found: {0}".format(err))
254 y_sorted = y_tmp_vals
260 for key, val in y_sorted.items():
261 key = "-".join(key.split("-")[1:-1])
262 x_vals.append(key) # dir 1
263 y_vals.append(mean(val[1]) if val[1] else None)
264 y_mins.append(mean(val[0]) if val[0] else None)
265 y_maxs.append(mean(val[2]) if val[2] else None)
266 x_vals.append(key) # dir 2
267 y_vals.append(mean(val[4]) if val[4] else None)
268 y_mins.append(mean(val[3]) if val[3] else None)
269 y_maxs.append(mean(val[5]) if val[5] else None)
274 for idx in range(len(x_vals)):
275 if not bool(int(idx % 2)):
276 direction = "West - East"
278 direction = "East - West"
279 hovertext = ("Test: {test}<br>"
280 "Direction: {dir}<br>".format(test=x_vals[idx],
282 if isinstance(y_maxs[idx], float):
283 hovertext += "Max: {max:.2f}uSec<br>".format(max=y_maxs[idx])
284 if isinstance(y_vals[idx], float):
285 hovertext += "Avg: {avg:.2f}uSec<br>".format(avg=y_vals[idx])
286 if isinstance(y_mins[idx], float):
287 hovertext += "Min: {min:.2f}uSec".format(min=y_mins[idx])
289 if isinstance(y_maxs[idx], float) and isinstance(y_vals[idx], float):
290 array = [y_maxs[idx] - y_vals[idx], ]
293 if isinstance(y_mins[idx], float) and isinstance(y_vals[idx], float):
294 arrayminus = [y_vals[idx] - y_mins[idx], ]
296 arrayminus = [None, ]
297 traces.append(plgo.Scatter(
301 legendgroup=x_vals[idx],
302 showlegend=bool(int(idx % 2)),
308 arrayminus=arrayminus,
309 color=COLORS[int(idx / 2)]
313 color=COLORS[int(idx / 2)],
318 annotations.append(dict(
325 text="E-W" if bool(int(idx % 2)) else "W-E",
335 logging.info(" Writing file '{0}{1}'.".
336 format(plot["output-file"], plot["output-file-type"]))
337 layout = deepcopy(plot["layout"])
338 if layout.get("title", None):
339 layout["title"] = "<b>Packet Latency:</b> {0}".\
340 format(layout["title"])
341 layout["annotations"] = annotations
342 plpl = plgo.Figure(data=traces, layout=layout)
346 show_link=False, auto_open=False,
347 filename='{0}{1}'.format(plot["output-file"],
348 plot["output-file-type"]))
349 except PlotlyError as err:
350 logging.error(" Finished with error: {}".
351 format(str(err).replace("\n", " ")))
355 def plot_throughput_speedup_analysis(plot, input_data):
356 """Generate the plot(s) with algorithm:
357 plot_throughput_speedup_analysis
358 specified in the specification file.
360 :param plot: Plot to generate.
361 :param input_data: Data to process.
362 :type plot: pandas.Series
363 :type input_data: InputData
367 plot_title = plot.get("title", "")
368 logging.info(" Creating the data set for the {0} '{1}'.".
369 format(plot.get("type", ""), plot_title))
370 data = input_data.filter_data(plot)
372 logging.error("No data.")
380 if y_vals.get(test["parent"], None) is None:
381 y_vals[test["parent"]] = {"1": list(),
384 y_tags[test["parent"]] = test.get("tags", None)
386 if test["type"] in ("NDRPDR",):
387 if "-pdr" in plot_title.lower():
389 elif "-ndr" in plot_title.lower():
393 if "1C" in test["tags"]:
394 y_vals[test["parent"]]["1"]. \
395 append(test["throughput"][ttype]["LOWER"])
396 elif "2C" in test["tags"]:
397 y_vals[test["parent"]]["2"]. \
398 append(test["throughput"][ttype]["LOWER"])
399 elif "4C" in test["tags"]:
400 y_vals[test["parent"]]["4"]. \
401 append(test["throughput"][ttype]["LOWER"])
402 except (KeyError, TypeError):
406 logging.warning("No data for the plot '{}'".
407 format(plot.get("title", "")))
411 for test_name, test_vals in y_vals.items():
412 for key, test_val in test_vals.items():
414 y_vals[test_name][key] = sum(test_val) / len(test_val)
416 y_1c_max[test_name] = max(test_val) / 1000000.0
422 pci_limit = plot["limits"]["pci"]["pci-g3-x8"]
423 for test_name, test_vals in y_vals.items():
425 name = "-".join(test_name.split('-')[1:-1])
428 y_val_1 = test_vals["1"] / 1000000.0
429 y_val_2 = test_vals["2"] / 1000000.0 if test_vals["2"] else None
430 y_val_4 = test_vals["4"] / 1000000.0 if test_vals["4"] else None
432 vals[name]["val"] = [y_val_1, y_val_2, y_val_4]
433 vals[name]["rel"] = [1.0, None, None]
434 vals[name]["ideal"] = [y_1c_max[test_name],
435 y_1c_max[test_name] * 2,
436 y_1c_max[test_name] * 4]
437 vals[name]["diff"] = \
438 [(y_val_1 - y_1c_max[test_name]) * 100 / y_val_1, None, None]
440 val_max = max(max(vals[name]["val"], vals[name]["ideal"]))
442 y_max.append(int((val_max / 10) + 1) * 10)
445 vals[name]["rel"][1] = round(y_val_2 / y_val_1, 2)
446 vals[name]["diff"][1] = \
447 (y_val_2 - vals[name]["ideal"][1]) * 100 / y_val_2
449 vals[name]["rel"][2] = round(y_val_4 / y_val_1, 2)
450 vals[name]["diff"][2] = \
451 (y_val_4 - vals[name]["ideal"][2]) * 100 / y_val_4
454 if "x520" in test_name:
455 limit = plot["limits"]["nic"]["x520"]
456 elif "x710" in test_name:
457 limit = plot["limits"]["nic"]["x710"]
458 elif "xxv710" in test_name:
459 limit = plot["limits"]["nic"]["xxv710"]
460 elif "xl710" in test_name:
461 limit = plot["limits"]["nic"]["xl710"]
464 if limit > nic_limit:
467 mul = 2 if "ge2p" in test_name else 1
468 if "10ge" in test_name:
469 limit = plot["limits"]["link"]["10ge"] * mul
470 elif "25ge" in test_name:
471 limit = plot["limits"]["link"]["25ge"] * mul
472 elif "40ge" in test_name:
473 limit = plot["limits"]["link"]["40ge"] * mul
474 elif "100ge" in test_name:
475 limit = plot["limits"]["link"]["100ge"] * mul
478 if limit > lnk_limit:
482 order = plot.get("sort", None)
484 y_sorted = OrderedDict()
485 y_tags_l = {s: [t.lower() for t in ts] for s, ts in y_tags.items()}
487 for test, tags in y_tags_l.items():
488 if tag.lower() in tags:
489 name = "-".join(test.split('-')[1:-1])
491 y_sorted[name] = vals.pop(name)
493 except KeyError as err:
494 logging.error("Not found: {0}".format(err))
505 threshold = 1.1 * max(y_max) # 10%
507 nic_limit /= 1000000.0
508 if nic_limit < threshold:
509 traces.append(plgo.Scatter(
511 y=[nic_limit, ] * len(x_vals),
512 name="NIC: {0:.2f}Mpps".format(nic_limit),
521 annotations.append(dict(
528 text="NIC: {0:.2f}Mpps".format(nic_limit),
536 y_max.append(int((nic_limit / 10) + 1) * 10)
538 lnk_limit /= 1000000.0
539 if lnk_limit < threshold:
540 traces.append(plgo.Scatter(
542 y=[lnk_limit, ] * len(x_vals),
543 name="Link: {0:.2f}Mpps".format(lnk_limit),
552 annotations.append(dict(
559 text="Link: {0:.2f}Mpps".format(lnk_limit),
567 y_max.append(int((lnk_limit / 10) + 1) * 10)
569 pci_limit /= 1000000.0
570 if pci_limit < threshold:
571 traces.append(plgo.Scatter(
573 y=[pci_limit, ] * len(x_vals),
574 name="PCIe: {0:.2f}Mpps".format(pci_limit),
583 annotations.append(dict(
590 text="PCIe: {0:.2f}Mpps".format(pci_limit),
598 y_max.append(int((pci_limit / 10) + 1) * 10)
600 # Perfect and measured:
602 for name, val in y_sorted.iteritems():
604 for idx in range(len(val["val"])):
606 if isinstance(val["val"][idx], float):
607 htext += "value: {0:.2f}Mpps<br>".format(val["val"][idx])
608 if isinstance(val["diff"][idx], float):
609 htext += "diff: {0:.0f}%<br>".format(round(val["diff"][idx]))
610 if isinstance(val["rel"][idx], float):
611 htext += "speedup: {0:.2f}".format(val["rel"][idx])
612 hovertext.append(htext)
613 traces.append(plgo.Scatter(x=x_vals,
617 mode="lines+markers",
626 hoverinfo="text+name"
628 traces.append(plgo.Scatter(x=x_vals,
630 name="{0} perfect".format(name),
633 mode="lines+markers",
642 text=["perfect: {0:.2f}Mpps".format(y)
643 for y in val["ideal"]],
650 logging.info(" Writing file '{0}{1}'.".
651 format(plot["output-file"], plot["output-file-type"]))
652 layout = deepcopy(plot["layout"])
653 if layout.get("title", None):
654 layout["title"] = "<b>Speedup Multi-core:</b> {0}". \
655 format(layout["title"])
656 layout["annotations"].extend(annotations)
657 plpl = plgo.Figure(data=traces, layout=layout)
661 show_link=False, auto_open=False,
662 filename='{0}{1}'.format(plot["output-file"],
663 plot["output-file-type"]))
664 except PlotlyError as err:
665 logging.error(" Finished with error: {}".
666 format(str(err).replace("\n", " ")))
670 def plot_http_server_performance_box(plot, input_data):
671 """Generate the plot(s) with algorithm: plot_http_server_performance_box
672 specified in the specification file.
674 :param plot: Plot to generate.
675 :param input_data: Data to process.
676 :type plot: pandas.Series
677 :type input_data: InputData
681 logging.info(" Creating the data set for the {0} '{1}'.".
682 format(plot.get("type", ""), plot.get("title", "")))
683 data = input_data.filter_data(plot)
685 logging.error("No data.")
688 # Prepare the data for the plot
693 if y_vals.get(test["name"], None) is None:
694 y_vals[test["name"]] = list()
696 y_vals[test["name"]].append(test["result"])
697 except (KeyError, TypeError):
698 y_vals[test["name"]].append(None)
700 # Add None to the lists with missing data
702 for val in y_vals.values():
703 if len(val) > max_len:
705 for key, val in y_vals.items():
706 if len(val) < max_len:
707 val.extend([None for _ in range(max_len - len(val))])
711 df = pd.DataFrame(y_vals)
713 for i, col in enumerate(df.columns):
714 name = "{0}. {1}".format(i + 1, col.lower().replace('-cps', '').
716 traces.append(plgo.Box(x=[str(i + 1) + '.'] * len(df[col]),
722 plpl = plgo.Figure(data=traces, layout=plot["layout"])
725 logging.info(" Writing file '{0}{1}'.".
726 format(plot["output-file"], plot["output-file-type"]))
727 ploff.plot(plpl, show_link=False, auto_open=False,
728 filename='{0}{1}'.format(plot["output-file"],
729 plot["output-file-type"]))
730 except PlotlyError as err:
731 logging.error(" Finished with error: {}".
732 format(str(err).replace("\n", " ")))