1 # Copyright (c) 2020 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.
21 from collections import OrderedDict
22 from copy import deepcopy
27 import plotly.offline as ploff
28 import plotly.graph_objs as plgo
30 from plotly.subplots import make_subplots
31 from plotly.exceptions import PlotlyError
33 from pal_utils import mean, stdev
36 COLORS = [u"SkyBlue", u"Olive", u"Purple", u"Coral", u"Indigo", u"Pink",
37 u"Chocolate", u"Brown", u"Magenta", u"Cyan", u"Orange", u"Black",
38 u"Violet", u"Blue", u"Yellow", u"BurlyWood", u"CadetBlue", u"Crimson",
39 u"DarkBlue", u"DarkCyan", u"DarkGreen", u"Green", u"GoldenRod",
40 u"LightGreen", u"LightSeaGreen", u"LightSkyBlue", u"Maroon",
41 u"MediumSeaGreen", u"SeaGreen", u"LightSlateGrey"]
43 REGEX_NIC = re.compile(r'(\d*ge\dp\d\D*\d*)-')
46 def generate_plots(spec, data):
47 """Generate all plots specified in the specification file.
49 :param spec: Specification read from the specification file.
50 :param data: Data to process.
51 :type spec: Specification
56 u"plot_nf_reconf_box_name": plot_nf_reconf_box_name,
57 u"plot_perf_box_name": plot_perf_box_name,
58 u"plot_lat_err_bars_name": plot_lat_err_bars_name,
59 u"plot_tsa_name": plot_tsa_name,
60 u"plot_http_server_perf_box": plot_http_server_perf_box,
61 u"plot_nf_heatmap": plot_nf_heatmap,
62 u"plot_lat_hdrh_bar_name": plot_lat_hdrh_bar_name,
63 u"plot_lat_hdrh_percentile": plot_lat_hdrh_percentile,
64 u"plot_hdrh_lat_by_percentile": plot_hdrh_lat_by_percentile
67 logging.info(u"Generating the plots ...")
68 for index, plot in enumerate(spec.plots):
70 logging.info(f" Plot nr {index + 1}: {plot.get(u'title', u'')}")
71 plot[u"limits"] = spec.configuration[u"limits"]
72 generator[plot[u"algorithm"]](plot, data)
73 logging.info(u" Done.")
74 except NameError as err:
76 f"Probably algorithm {plot[u'algorithm']} is not defined: "
79 logging.info(u"Done.")
82 def plot_lat_hdrh_percentile(plot, input_data):
83 """Generate the plot(s) with algorithm: plot_lat_hdrh_percentile
84 specified in the specification file.
86 :param plot: Plot to generate.
87 :param input_data: Data to process.
88 :type plot: pandas.Series
89 :type input_data: InputData
93 plot_title = plot.get(u"title", u"")
95 f" Creating the data set for the {plot.get(u'type', u'')} "
98 data = input_data.filter_tests_by_name(
99 plot, params=[u"latency", u"parent", u"tags", u"type"])
100 if data is None or len(data[0][0]) == 0:
101 logging.error(u"No data.")
106 # Prepare the data for the plot
107 directions = [u"W-E", u"E-W"]
108 for color, test in enumerate(data[0][0]):
110 if test[u"type"] in (u"NDRPDR",):
111 if u"-pdr" in plot_title.lower():
113 elif u"-ndr" in plot_title.lower():
116 logging.warning(f"Invalid test type: {test[u'type']}")
118 name = re.sub(REGEX_NIC, u"", test[u"parent"].
119 replace(u'-ndrpdr', u'').
120 replace(u'2n1l-', u''))
121 for idx, direction in enumerate(
122 (u"direction1", u"direction2", )):
124 hdr_lat = test[u"latency"][ttype][direction][u"hdrh"]
125 # TODO: Workaround, HDRH data must be aligned to 4
126 # bytes, remove when not needed.
127 hdr_lat += u"=" * (len(hdr_lat) % 4)
131 decoded = hdrh.histogram.HdrHistogram.decode(hdr_lat)
132 for item in decoded.get_recorded_iterator():
133 percentile = item.percentile_level_iterated_to
134 if percentile != 100.0:
135 xaxis.append(100.0 / (100.0 - percentile))
136 yaxis.append(item.value_iterated_to)
139 f"Direction: {directions[idx]}<br>"
140 f"Percentile: {percentile:.5f}%<br>"
141 f"Latency: {item.value_iterated_to}uSec"
150 showlegend=bool(idx),
158 except hdrh.codec.HdrLengthException as err:
160 f"No or invalid data for HDRHistogram for the test "
165 logging.warning(f"Invalid test type: {test[u'type']}")
167 except (ValueError, KeyError) as err:
168 logging.warning(repr(err))
170 layout = deepcopy(plot[u"layout"])
172 layout[u"title"][u"text"] = \
173 f"<b>Latency:</b> {plot.get(u'graph-title', u'')}"
174 fig[u"layout"].update(layout)
177 file_type = plot.get(u"output-file-type", u".html")
178 logging.info(f" Writing file {plot[u'output-file']}{file_type}.")
181 ploff.plot(fig, show_link=False, auto_open=False,
182 filename=f"{plot[u'output-file']}{file_type}")
183 except PlotlyError as err:
184 logging.error(f" Finished with error: {repr(err)}")
187 def plot_hdrh_lat_by_percentile(plot, input_data):
188 """Generate the plot(s) with algorithm: plot_hdrh_lat_by_percentile
189 specified in the specification file.
191 :param plot: Plot to generate.
192 :param input_data: Data to process.
193 :type plot: pandas.Series
194 :type input_data: InputData
199 f" Creating the data set for the {plot.get(u'type', u'')} "
200 f"{plot.get(u'title', u'')}."
202 if plot.get(u"include", None):
203 data = input_data.filter_tests_by_name(
205 params=[u"latency", u"throughput", u"parent", u"tags", u"type"]
208 job = list(plot[u"data"].keys())[0]
209 build = str(plot[u"data"][job][0])
210 data = input_data.tests(job, build)
212 if data is None or len(data) == 0:
213 logging.error(u"No data.")
223 file_links = plot.get(u"output-file-links", None)
224 target_links = plot.get(u"target-links", None)
228 if test[u"type"] not in (u"NDRPDR",):
229 logging.warning(f"Invalid test type: {test[u'type']}")
231 name = re.sub(REGEX_NIC, u"", test[u"parent"].
232 replace(u'-ndrpdr', u'').replace(u'2n1l-', u''))
234 nic = re.search(REGEX_NIC, test[u"parent"]).group(1)
235 except (IndexError, AttributeError, KeyError, ValueError):
237 name_link = f"{nic}-{test[u'name']}".replace(u'-ndrpdr', u'')
239 logging.info(f" Generating the graph: {name_link}")
242 u"LAT0": u"No-load.",
243 u"PDR10": u"Low-load, 10% PDR.",
244 u"PDR50": u"Mid-load, 50% PDR.",
245 u"PDR90": u"High-load, 90% PDR.",
246 u"PDR": u"Full-load, 100% PDR.",
247 u"NDR10": u"Low-load, 10% NDR.",
248 u"NDR50": u"Mid-load, 50% NDR.",
249 u"NDR90": u"High-load, 90% NDR.",
250 u"NDR": u"Full-load, 100% NDR."
254 layout = deepcopy(plot[u"layout"])
256 for color, graph in enumerate(graphs):
257 for idx, direction in enumerate((u"direction1", u"direction2")):
261 f"<b>{desc[graph]}</b><br>"
262 f"Direction: {(u'W-E', u'E-W')[idx % 2]}<br>"
263 f"Percentile: 0.0%<br>"
266 decoded = hdrh.histogram.HdrHistogram.decode(
267 test[u"latency"][graph][direction][u"hdrh"]
269 for item in decoded.get_recorded_iterator():
270 percentile = item.percentile_level_iterated_to
271 if percentile > 99.9:
273 xaxis.append(percentile)
274 yaxis.append(item.value_iterated_to)
276 f"<b>{desc[graph]}</b><br>"
277 f"Direction: {(u'W-E', u'E-W')[idx % 2]}<br>"
278 f"Percentile: {percentile:.5f}%<br>"
279 f"Latency: {item.value_iterated_to}uSec"
287 legendgroup=desc[graph],
288 showlegend=bool(idx),
291 dash=u"solid" if idx % 2 else u"dash"
298 layout[u"title"][u"text"] = f"<b>Latency:</b> {name}"
299 fig.update_layout(layout)
302 file_name = f"{plot[u'output-file']}-{name_link}.html"
303 logging.info(f" Writing file {file_name}")
307 ploff.plot(fig, show_link=False, auto_open=False,
309 # Add link to the file:
310 if file_links and target_links:
311 with open(file_links, u"a") as fw:
314 f"<{target_links}/{file_name.split(u'/')[-1]}>`_\n"
316 except FileNotFoundError as err:
318 f"Not possible to write the link to the file "
319 f"{file_links}\n{err}"
321 except PlotlyError as err:
322 logging.error(f" Finished with error: {repr(err)}")
324 except hdrh.codec.HdrLengthException as err:
325 logging.warning(repr(err))
328 except (ValueError, KeyError) as err:
329 logging.warning(repr(err))
333 def plot_lat_hdrh_bar_name(plot, input_data):
334 """Generate the plot(s) with algorithm: plot_lat_hdrh_bar_name
335 specified in the specification file.
337 :param plot: Plot to generate.
338 :param input_data: Data to process.
339 :type plot: pandas.Series
340 :type input_data: InputData
344 plot_title = plot.get(u"title", u"")
346 f" Creating the data set for the {plot.get(u'type', u'')} "
349 data = input_data.filter_tests_by_name(
350 plot, params=[u"latency", u"parent", u"tags", u"type"])
351 if data is None or len(data[0][0]) == 0:
352 logging.error(u"No data.")
355 # Prepare the data for the plot
356 directions = [u"W-E", u"E-W"]
359 for idx_row, test in enumerate(data[0][0]):
361 if test[u"type"] in (u"NDRPDR",):
362 if u"-pdr" in plot_title.lower():
364 elif u"-ndr" in plot_title.lower():
367 logging.warning(f"Invalid test type: {test[u'type']}")
369 name = re.sub(REGEX_NIC, u"", test[u"parent"].
370 replace(u'-ndrpdr', u'').
371 replace(u'2n1l-', u''))
373 for idx_col, direction in enumerate(
374 (u"direction1", u"direction2", )):
376 hdr_lat = test[u"latency"][ttype][direction][u"hdrh"]
377 # TODO: Workaround, HDRH data must be aligned to 4
378 # bytes, remove when not needed.
379 hdr_lat += u"=" * (len(hdr_lat) % 4)
383 decoded = hdrh.histogram.HdrHistogram.decode(hdr_lat)
384 total_count = decoded.get_total_count()
385 for item in decoded.get_recorded_iterator():
386 xaxis.append(item.value_iterated_to)
387 prob = float(item.count_added_in_this_iter_step) / \
392 f"Direction: {directions[idx_col]}<br>"
393 f"Latency: {item.value_iterated_to}uSec<br>"
394 f"Probability: {prob:.2f}%<br>"
396 f"{item.percentile_level_iterated_to:.2f}"
398 marker_color = [COLORS[idx_row], ] * len(yaxis)
399 marker_color[xaxis.index(
400 decoded.get_value_at_percentile(50.0))] = u"red"
401 marker_color[xaxis.index(
402 decoded.get_value_at_percentile(90.0))] = u"red"
403 marker_color[xaxis.index(
404 decoded.get_value_at_percentile(95.0))] = u"red"
411 marker={u"color": marker_color},
416 except hdrh.codec.HdrLengthException as err:
418 f"No or invalid data for HDRHistogram for the test "
422 if len(histograms) == 2:
423 traces.append(histograms)
426 logging.warning(f"Invalid test type: {test[u'type']}")
428 except (ValueError, KeyError) as err:
429 logging.warning(repr(err))
432 logging.warning(f"No data for {plot_title}.")
439 [{u"type": u"bar"}, {u"type": u"bar"}] for _ in range(len(tests))
444 gridcolor=u"rgb(220, 220, 220)",
445 linecolor=u"rgb(220, 220, 220)",
450 tickcolor=u"rgb(220, 220, 220)",
453 for idx_row, test in enumerate(tests):
454 for idx_col in range(2):
456 traces[idx_row][idx_col],
471 layout = deepcopy(plot[u"layout"])
473 layout[u"title"][u"text"] = \
474 f"<b>Latency:</b> {plot.get(u'graph-title', u'')}"
475 layout[u"height"] = 250 * len(tests) + 130
477 layout[u"annotations"][2][u"y"] = 1.06 - 0.008 * len(tests)
478 layout[u"annotations"][3][u"y"] = 1.06 - 0.008 * len(tests)
480 for idx, test in enumerate(tests):
481 layout[u"annotations"].append({
486 u"text": f"<b>{test}</b>",
489 u"xanchor": u"center",
491 u"y": 1.0 - float(idx) * 1.06 / len(tests),
492 u"yanchor": u"bottom",
496 fig[u"layout"].update(layout)
499 file_type = plot.get(u"output-file-type", u".html")
500 logging.info(f" Writing file {plot[u'output-file']}{file_type}.")
503 ploff.plot(fig, show_link=False, auto_open=False,
504 filename=f"{plot[u'output-file']}{file_type}")
505 except PlotlyError as err:
506 logging.error(f" Finished with error: {repr(err)}")
509 def plot_nf_reconf_box_name(plot, input_data):
510 """Generate the plot(s) with algorithm: plot_nf_reconf_box_name
511 specified in the specification file.
513 :param plot: Plot to generate.
514 :param input_data: Data to process.
515 :type plot: pandas.Series
516 :type input_data: InputData
521 f" Creating the data set for the {plot.get(u'type', u'')} "
522 f"{plot.get(u'title', u'')}."
524 data = input_data.filter_tests_by_name(
525 plot, params=[u"result", u"parent", u"tags", u"type"]
528 logging.error(u"No data.")
531 # Prepare the data for the plot
532 y_vals = OrderedDict()
537 if y_vals.get(test[u"parent"], None) is None:
538 y_vals[test[u"parent"]] = list()
539 loss[test[u"parent"]] = list()
541 y_vals[test[u"parent"]].append(test[u"result"][u"time"])
542 loss[test[u"parent"]].append(test[u"result"][u"loss"])
543 except (KeyError, TypeError):
544 y_vals[test[u"parent"]].append(None)
546 # Add None to the lists with missing data
548 nr_of_samples = list()
549 for val in y_vals.values():
550 if len(val) > max_len:
552 nr_of_samples.append(len(val))
553 for val in y_vals.values():
554 if len(val) < max_len:
555 val.extend([None for _ in range(max_len - len(val))])
559 df_y = pd.DataFrame(y_vals)
561 for i, col in enumerate(df_y.columns):
562 tst_name = re.sub(REGEX_NIC, u"",
563 col.lower().replace(u'-ndrpdr', u'').
564 replace(u'2n1l-', u''))
566 traces.append(plgo.Box(
567 x=[str(i + 1) + u'.'] * len(df_y[col]),
568 y=[y if y else None for y in df_y[col]],
571 f"({nr_of_samples[i]:02d} "
572 f"run{u's' if nr_of_samples[i] > 1 else u''}, "
573 f"packets lost average: {mean(loss[col]):.1f}) "
574 f"{u'-'.join(tst_name.split(u'-')[3:-2])}"
580 layout = deepcopy(plot[u"layout"])
581 layout[u"title"] = f"<b>Time Lost:</b> {layout[u'title']}"
582 layout[u"yaxis"][u"title"] = u"<b>Implied Time Lost [s]</b>"
583 layout[u"legend"][u"font"][u"size"] = 14
584 layout[u"yaxis"].pop(u"range")
585 plpl = plgo.Figure(data=traces, layout=layout)
588 file_type = plot.get(u"output-file-type", u".html")
589 logging.info(f" Writing file {plot[u'output-file']}{file_type}.")
594 filename=f"{plot[u'output-file']}{file_type}"
596 except PlotlyError as err:
598 f" Finished with error: {repr(err)}".replace(u"\n", u" ")
603 def plot_perf_box_name(plot, input_data):
604 """Generate the plot(s) with algorithm: plot_perf_box_name
605 specified in the specification file.
607 :param plot: Plot to generate.
608 :param input_data: Data to process.
609 :type plot: pandas.Series
610 :type input_data: InputData
615 f" Creating data set for the {plot.get(u'type', u'')} "
616 f"{plot.get(u'title', u'')}."
618 data = input_data.filter_tests_by_name(
619 plot, params=[u"throughput", u"parent", u"tags", u"type"])
621 logging.error(u"No data.")
624 # Prepare the data for the plot
625 y_vals = OrderedDict()
629 if y_vals.get(test[u"parent"], None) is None:
630 y_vals[test[u"parent"]] = list()
632 if (test[u"type"] in (u"NDRPDR", ) and
633 u"-pdr" in plot.get(u"title", u"").lower()):
634 y_vals[test[u"parent"]].\
635 append(test[u"throughput"][u"PDR"][u"LOWER"])
636 elif (test[u"type"] in (u"NDRPDR", ) and
637 u"-ndr" in plot.get(u"title", u"").lower()):
638 y_vals[test[u"parent"]]. \
639 append(test[u"throughput"][u"NDR"][u"LOWER"])
640 elif test[u"type"] in (u"SOAK", ):
641 y_vals[test[u"parent"]].\
642 append(test[u"throughput"][u"LOWER"])
645 except (KeyError, TypeError):
646 y_vals[test[u"parent"]].append(None)
648 # Add None to the lists with missing data
650 nr_of_samples = list()
651 for val in y_vals.values():
652 if len(val) > max_len:
654 nr_of_samples.append(len(val))
655 for val in y_vals.values():
656 if len(val) < max_len:
657 val.extend([None for _ in range(max_len - len(val))])
661 df_y = pd.DataFrame(y_vals)
664 for i, col in enumerate(df_y.columns):
665 tst_name = re.sub(REGEX_NIC, u"",
666 col.lower().replace(u'-ndrpdr', u'').
667 replace(u'2n1l-', u''))
670 x=[str(i + 1) + u'.'] * len(df_y[col]),
671 y=[y / 1000000 if y else None for y in df_y[col]],
674 f"({nr_of_samples[i]:02d} "
675 f"run{u's' if nr_of_samples[i] > 1 else u''}) "
682 val_max = max(df_y[col])
684 y_max.append(int(val_max / 1000000) + 2)
685 except (ValueError, TypeError) as err:
686 logging.error(repr(err))
691 layout = deepcopy(plot[u"layout"])
692 if layout.get(u"title", None):
693 layout[u"title"] = f"<b>Throughput:</b> {layout[u'title']}"
695 layout[u"yaxis"][u"range"] = [0, max(y_max)]
696 plpl = plgo.Figure(data=traces, layout=layout)
699 logging.info(f" Writing file {plot[u'output-file']}.html.")
704 filename=f"{plot[u'output-file']}.html"
706 except PlotlyError as err:
708 f" Finished with error: {repr(err)}".replace(u"\n", u" ")
713 def plot_lat_err_bars_name(plot, input_data):
714 """Generate the plot(s) with algorithm: plot_lat_err_bars_name
715 specified in the specification file.
717 :param plot: Plot to generate.
718 :param input_data: Data to process.
719 :type plot: pandas.Series
720 :type input_data: InputData
724 plot_title = plot.get(u"title", u"")
726 f" Creating data set for the {plot.get(u'type', u'')} {plot_title}."
728 data = input_data.filter_tests_by_name(
729 plot, params=[u"latency", u"parent", u"tags", u"type"])
731 logging.error(u"No data.")
734 # Prepare the data for the plot
735 y_tmp_vals = OrderedDict()
740 logging.debug(f"test[u'latency']: {test[u'latency']}\n")
741 except ValueError as err:
742 logging.warning(repr(err))
743 if y_tmp_vals.get(test[u"parent"], None) is None:
744 y_tmp_vals[test[u"parent"]] = [
745 list(), # direction1, min
746 list(), # direction1, avg
747 list(), # direction1, max
748 list(), # direction2, min
749 list(), # direction2, avg
750 list() # direction2, max
753 if test[u"type"] not in (u"NDRPDR", ):
754 logging.warning(f"Invalid test type: {test[u'type']}")
756 if u"-pdr" in plot_title.lower():
758 elif u"-ndr" in plot_title.lower():
762 f"Invalid test type: {test[u'type']}"
765 y_tmp_vals[test[u"parent"]][0].append(
766 test[u"latency"][ttype][u"direction1"][u"min"])
767 y_tmp_vals[test[u"parent"]][1].append(
768 test[u"latency"][ttype][u"direction1"][u"avg"])
769 y_tmp_vals[test[u"parent"]][2].append(
770 test[u"latency"][ttype][u"direction1"][u"max"])
771 y_tmp_vals[test[u"parent"]][3].append(
772 test[u"latency"][ttype][u"direction2"][u"min"])
773 y_tmp_vals[test[u"parent"]][4].append(
774 test[u"latency"][ttype][u"direction2"][u"avg"])
775 y_tmp_vals[test[u"parent"]][5].append(
776 test[u"latency"][ttype][u"direction2"][u"max"])
777 except (KeyError, TypeError) as err:
778 logging.warning(repr(err))
784 nr_of_samples = list()
785 for key, val in y_tmp_vals.items():
786 name = re.sub(REGEX_NIC, u"", key.replace(u'-ndrpdr', u'').
787 replace(u'2n1l-', u''))
788 x_vals.append(name) # dir 1
789 y_vals.append(mean(val[1]) if val[1] else None)
790 y_mins.append(mean(val[0]) if val[0] else None)
791 y_maxs.append(mean(val[2]) if val[2] else None)
792 nr_of_samples.append(len(val[1]) if val[1] else 0)
793 x_vals.append(name) # dir 2
794 y_vals.append(mean(val[4]) if val[4] else None)
795 y_mins.append(mean(val[3]) if val[3] else None)
796 y_maxs.append(mean(val[5]) if val[5] else None)
797 nr_of_samples.append(len(val[3]) if val[3] else 0)
802 for idx, _ in enumerate(x_vals):
803 if not bool(int(idx % 2)):
804 direction = u"West-East"
806 direction = u"East-West"
808 f"No. of Runs: {nr_of_samples[idx]}<br>"
809 f"Test: {x_vals[idx]}<br>"
810 f"Direction: {direction}<br>"
812 if isinstance(y_maxs[idx], float):
813 hovertext += f"Max: {y_maxs[idx]:.2f}uSec<br>"
814 if isinstance(y_vals[idx], float):
815 hovertext += f"Mean: {y_vals[idx]:.2f}uSec<br>"
816 if isinstance(y_mins[idx], float):
817 hovertext += f"Min: {y_mins[idx]:.2f}uSec"
819 if isinstance(y_maxs[idx], float) and isinstance(y_vals[idx], float):
820 array = [y_maxs[idx] - y_vals[idx], ]
823 if isinstance(y_mins[idx], float) and isinstance(y_vals[idx], float):
824 arrayminus = [y_vals[idx] - y_mins[idx], ]
826 arrayminus = [None, ]
827 traces.append(plgo.Scatter(
831 legendgroup=x_vals[idx],
832 showlegend=bool(int(idx % 2)),
838 arrayminus=arrayminus,
839 color=COLORS[int(idx / 2)]
843 color=COLORS[int(idx / 2)],
848 annotations.append(dict(
855 text=u"E-W" if bool(int(idx % 2)) else u"W-E",
865 file_type = plot.get(u"output-file-type", u".html")
866 logging.info(f" Writing file {plot[u'output-file']}{file_type}.")
867 layout = deepcopy(plot[u"layout"])
868 if layout.get(u"title", None):
869 layout[u"title"] = f"<b>Latency:</b> {layout[u'title']}"
870 layout[u"annotations"] = annotations
871 plpl = plgo.Figure(data=traces, layout=layout)
876 show_link=False, auto_open=False,
877 filename=f"{plot[u'output-file']}{file_type}"
879 except PlotlyError as err:
881 f" Finished with error: {repr(err)}".replace(u"\n", u" ")
886 def plot_tsa_name(plot, input_data):
887 """Generate the plot(s) with algorithm:
889 specified in the specification file.
891 :param plot: Plot to generate.
892 :param input_data: Data to process.
893 :type plot: pandas.Series
894 :type input_data: InputData
898 plot_title = plot.get(u"title", u"")
900 f" Creating data set for the {plot.get(u'type', u'')} {plot_title}."
902 data = input_data.filter_tests_by_name(
903 plot, params=[u"throughput", u"parent", u"tags", u"type"])
905 logging.error(u"No data.")
908 y_vals = OrderedDict()
912 if y_vals.get(test[u"parent"], None) is None:
913 y_vals[test[u"parent"]] = {
919 if test[u"type"] not in (u"NDRPDR",):
922 if u"-pdr" in plot_title.lower():
924 elif u"-ndr" in plot_title.lower():
929 if u"1C" in test[u"tags"]:
930 y_vals[test[u"parent"]][u"1"]. \
931 append(test[u"throughput"][ttype][u"LOWER"])
932 elif u"2C" in test[u"tags"]:
933 y_vals[test[u"parent"]][u"2"]. \
934 append(test[u"throughput"][ttype][u"LOWER"])
935 elif u"4C" in test[u"tags"]:
936 y_vals[test[u"parent"]][u"4"]. \
937 append(test[u"throughput"][ttype][u"LOWER"])
938 except (KeyError, TypeError):
942 logging.warning(f"No data for the plot {plot.get(u'title', u'')}")
946 for test_name, test_vals in y_vals.items():
947 for key, test_val in test_vals.items():
949 avg_val = sum(test_val) / len(test_val)
950 y_vals[test_name][key] = [avg_val, len(test_val)]
951 ideal = avg_val / (int(key) * 1000000.0)
952 if test_name not in y_1c_max or ideal > y_1c_max[test_name]:
953 y_1c_max[test_name] = ideal
959 pci_limit = plot[u"limits"][u"pci"][u"pci-g3-x8"]
960 for test_name, test_vals in y_vals.items():
962 if test_vals[u"1"][1]:
966 test_name.replace(u'-ndrpdr', u'').replace(u'2n1l-', u'')
968 vals[name] = OrderedDict()
969 y_val_1 = test_vals[u"1"][0] / 1000000.0
970 y_val_2 = test_vals[u"2"][0] / 1000000.0 if test_vals[u"2"][0] \
972 y_val_4 = test_vals[u"4"][0] / 1000000.0 if test_vals[u"4"][0] \
975 vals[name][u"val"] = [y_val_1, y_val_2, y_val_4]
976 vals[name][u"rel"] = [1.0, None, None]
977 vals[name][u"ideal"] = [
979 y_1c_max[test_name] * 2,
980 y_1c_max[test_name] * 4
982 vals[name][u"diff"] = [
983 (y_val_1 - y_1c_max[test_name]) * 100 / y_val_1, None, None
985 vals[name][u"count"] = [
992 val_max = max(vals[name][u"val"])
993 except ValueError as err:
994 logging.error(repr(err))
997 y_max.append(val_max)
1000 vals[name][u"rel"][1] = round(y_val_2 / y_val_1, 2)
1001 vals[name][u"diff"][1] = \
1002 (y_val_2 - vals[name][u"ideal"][1]) * 100 / y_val_2
1004 vals[name][u"rel"][2] = round(y_val_4 / y_val_1, 2)
1005 vals[name][u"diff"][2] = \
1006 (y_val_4 - vals[name][u"ideal"][2]) * 100 / y_val_4
1007 except IndexError as err:
1008 logging.warning(f"No data for {test_name}")
1009 logging.warning(repr(err))
1012 if u"x520" in test_name:
1013 limit = plot[u"limits"][u"nic"][u"x520"]
1014 elif u"x710" in test_name:
1015 limit = plot[u"limits"][u"nic"][u"x710"]
1016 elif u"xxv710" in test_name:
1017 limit = plot[u"limits"][u"nic"][u"xxv710"]
1018 elif u"xl710" in test_name:
1019 limit = plot[u"limits"][u"nic"][u"xl710"]
1020 elif u"x553" in test_name:
1021 limit = plot[u"limits"][u"nic"][u"x553"]
1024 if limit > nic_limit:
1027 mul = 2 if u"ge2p" in test_name else 1
1028 if u"10ge" in test_name:
1029 limit = plot[u"limits"][u"link"][u"10ge"] * mul
1030 elif u"25ge" in test_name:
1031 limit = plot[u"limits"][u"link"][u"25ge"] * mul
1032 elif u"40ge" in test_name:
1033 limit = plot[u"limits"][u"link"][u"40ge"] * mul
1034 elif u"100ge" in test_name:
1035 limit = plot[u"limits"][u"link"][u"100ge"] * mul
1038 if limit > lnk_limit:
1042 annotations = list()
1047 threshold = 1.1 * max(y_max) # 10%
1048 except ValueError as err:
1051 nic_limit /= 1000000.0
1052 traces.append(plgo.Scatter(
1054 y=[nic_limit, ] * len(x_vals),
1055 name=f"NIC: {nic_limit:.2f}Mpps",
1064 annotations.append(dict(
1071 text=f"NIC: {nic_limit:.2f}Mpps",
1079 y_max.append(nic_limit)
1081 lnk_limit /= 1000000.0
1082 if lnk_limit < threshold:
1083 traces.append(plgo.Scatter(
1085 y=[lnk_limit, ] * len(x_vals),
1086 name=f"Link: {lnk_limit:.2f}Mpps",
1095 annotations.append(dict(
1102 text=f"Link: {lnk_limit:.2f}Mpps",
1110 y_max.append(lnk_limit)
1112 pci_limit /= 1000000.0
1113 if (pci_limit < threshold and
1114 (pci_limit < lnk_limit * 0.95 or lnk_limit > lnk_limit * 1.05)):
1115 traces.append(plgo.Scatter(
1117 y=[pci_limit, ] * len(x_vals),
1118 name=f"PCIe: {pci_limit:.2f}Mpps",
1127 annotations.append(dict(
1134 text=f"PCIe: {pci_limit:.2f}Mpps",
1142 y_max.append(pci_limit)
1144 # Perfect and measured:
1146 for name, val in vals.items():
1149 for idx in range(len(val[u"val"])):
1151 if isinstance(val[u"val"][idx], float):
1153 f"No. of Runs: {val[u'count'][idx]}<br>"
1154 f"Mean: {val[u'val'][idx]:.2f}Mpps<br>"
1156 if isinstance(val[u"diff"][idx], float):
1157 htext += f"Diff: {round(val[u'diff'][idx]):.0f}%<br>"
1158 if isinstance(val[u"rel"][idx], float):
1159 htext += f"Speedup: {val[u'rel'][idx]:.2f}"
1160 hovertext.append(htext)
1167 mode=u"lines+markers",
1176 hoverinfo=u"text+name"
1183 name=f"{name} perfect",
1191 text=[f"Perfect: {y:.2f}Mpps" for y in val[u"ideal"]],
1196 except (IndexError, ValueError, KeyError) as err:
1197 logging.warning(f"No data for {name}\n{repr(err)}")
1201 file_type = plot.get(u"output-file-type", u".html")
1202 logging.info(f" Writing file {plot[u'output-file']}{file_type}.")
1203 layout = deepcopy(plot[u"layout"])
1204 if layout.get(u"title", None):
1205 layout[u"title"] = f"<b>Speedup Multi-core:</b> {layout[u'title']}"
1206 layout[u"yaxis"][u"range"] = [0, int(max(y_max) * 1.1)]
1207 layout[u"annotations"].extend(annotations)
1208 plpl = plgo.Figure(data=traces, layout=layout)
1215 filename=f"{plot[u'output-file']}{file_type}"
1217 except PlotlyError as err:
1219 f" Finished with error: {repr(err)}".replace(u"\n", u" ")
1224 def plot_http_server_perf_box(plot, input_data):
1225 """Generate the plot(s) with algorithm: plot_http_server_perf_box
1226 specified in the specification file.
1228 :param plot: Plot to generate.
1229 :param input_data: Data to process.
1230 :type plot: pandas.Series
1231 :type input_data: InputData
1234 # Transform the data
1236 f" Creating the data set for the {plot.get(u'type', u'')} "
1237 f"{plot.get(u'title', u'')}."
1239 data = input_data.filter_data(plot)
1241 logging.error(u"No data.")
1244 # Prepare the data for the plot
1249 if y_vals.get(test[u"name"], None) is None:
1250 y_vals[test[u"name"]] = list()
1252 y_vals[test[u"name"]].append(test[u"result"])
1253 except (KeyError, TypeError):
1254 y_vals[test[u"name"]].append(None)
1256 # Add None to the lists with missing data
1258 nr_of_samples = list()
1259 for val in y_vals.values():
1260 if len(val) > max_len:
1262 nr_of_samples.append(len(val))
1263 for val in y_vals.values():
1264 if len(val) < max_len:
1265 val.extend([None for _ in range(max_len - len(val))])
1269 df_y = pd.DataFrame(y_vals)
1271 for i, col in enumerate(df_y.columns):
1274 f"({nr_of_samples[i]:02d} " \
1275 f"run{u's' if nr_of_samples[i] > 1 else u''}) " \
1276 f"{col.lower().replace(u'-ndrpdr', u'')}"
1278 name_lst = name.split(u'-')
1281 for segment in name_lst:
1282 if (len(name) + len(segment) + 1) > 50 and split_name:
1285 name += segment + u'-'
1288 traces.append(plgo.Box(x=[str(i + 1) + u'.'] * len(df_y[col]),
1294 plpl = plgo.Figure(data=traces, layout=plot[u"layout"])
1298 f" Writing file {plot[u'output-file']}"
1299 f"{plot[u'output-file-type']}."
1305 filename=f"{plot[u'output-file']}{plot[u'output-file-type']}"
1307 except PlotlyError as err:
1309 f" Finished with error: {repr(err)}".replace(u"\n", u" ")
1314 def plot_nf_heatmap(plot, input_data):
1315 """Generate the plot(s) with algorithm: plot_nf_heatmap
1316 specified in the specification file.
1318 :param plot: Plot to generate.
1319 :param input_data: Data to process.
1320 :type plot: pandas.Series
1321 :type input_data: InputData
1324 regex_cn = re.compile(r'^(\d*)R(\d*)C$')
1325 regex_test_name = re.compile(r'^.*-(\d+ch|\d+pl)-'
1327 r'(\d+vm\d+t|\d+dcr\d+t).*$')
1330 # Transform the data
1332 f" Creating the data set for the {plot.get(u'type', u'')} "
1333 f"{plot.get(u'title', u'')}."
1335 data = input_data.filter_data(plot, continue_on_error=True)
1336 if data is None or data.empty:
1337 logging.error(u"No data.")
1343 for tag in test[u"tags"]:
1344 groups = re.search(regex_cn, tag)
1346 chain = str(groups.group(1))
1347 node = str(groups.group(2))
1351 groups = re.search(regex_test_name, test[u"name"])
1352 if groups and len(groups.groups()) == 3:
1354 f"{str(groups.group(1))}-"
1355 f"{str(groups.group(2))}-"
1356 f"{str(groups.group(3))}"
1360 if vals.get(chain, None) is None:
1361 vals[chain] = dict()
1362 if vals[chain].get(node, None) is None:
1363 vals[chain][node] = dict(
1371 if plot[u"include-tests"] == u"MRR":
1372 result = test[u"result"][u"receive-rate"]
1373 elif plot[u"include-tests"] == u"PDR":
1374 result = test[u"throughput"][u"PDR"][u"LOWER"]
1375 elif plot[u"include-tests"] == u"NDR":
1376 result = test[u"throughput"][u"NDR"][u"LOWER"]
1383 vals[chain][node][u"vals"].append(result)
1386 logging.error(u"No data.")
1392 txt_chains.append(key_c)
1393 for key_n in vals[key_c].keys():
1394 txt_nodes.append(key_n)
1395 if vals[key_c][key_n][u"vals"]:
1396 vals[key_c][key_n][u"nr"] = len(vals[key_c][key_n][u"vals"])
1397 vals[key_c][key_n][u"mean"] = \
1398 round(mean(vals[key_c][key_n][u"vals"]) / 1000000, 1)
1399 vals[key_c][key_n][u"stdev"] = \
1400 round(stdev(vals[key_c][key_n][u"vals"]) / 1000000, 1)
1401 txt_nodes = list(set(txt_nodes))
1403 def sort_by_int(value):
1404 """Makes possible to sort a list of strings which represent integers.
1406 :param value: Integer as a string.
1408 :returns: Integer representation of input parameter 'value'.
1413 txt_chains = sorted(txt_chains, key=sort_by_int)
1414 txt_nodes = sorted(txt_nodes, key=sort_by_int)
1416 chains = [i + 1 for i in range(len(txt_chains))]
1417 nodes = [i + 1 for i in range(len(txt_nodes))]
1419 data = [list() for _ in range(len(chains))]
1420 for chain in chains:
1423 val = vals[txt_chains[chain - 1]][txt_nodes[node - 1]][u"mean"]
1424 except (KeyError, IndexError):
1426 data[chain - 1].append(val)
1429 my_green = [[0.0, u"rgb(235, 249, 242)"],
1430 [1.0, u"rgb(45, 134, 89)"]]
1432 my_blue = [[0.0, u"rgb(236, 242, 248)"],
1433 [1.0, u"rgb(57, 115, 172)"]]
1435 my_grey = [[0.0, u"rgb(230, 230, 230)"],
1436 [1.0, u"rgb(102, 102, 102)"]]
1439 annotations = list()
1441 text = (u"Test: {name}<br>"
1446 for chain, _ in enumerate(txt_chains):
1448 for node, _ in enumerate(txt_nodes):
1449 if data[chain][node] is not None:
1458 text=str(data[chain][node]),
1466 hover_line.append(text.format(
1467 name=vals[txt_chains[chain]][txt_nodes[node]][u"name"],
1468 nr=vals[txt_chains[chain]][txt_nodes[node]][u"nr"],
1469 val=data[chain][node],
1470 stdev=vals[txt_chains[chain]][txt_nodes[node]][u"stdev"]))
1471 hovertext.append(hover_line)
1479 title=plot.get(u"z-axis", u""),
1493 colorscale=my_green,
1499 for idx, item in enumerate(txt_nodes):
1517 for idx, item in enumerate(txt_chains):
1544 text=plot.get(u"x-axis", u""),
1561 text=plot.get(u"y-axis", u""),
1570 updatemenus = list([
1581 u"colorscale": [my_green, ],
1582 u"reversescale": False
1591 u"colorscale": [my_blue, ],
1592 u"reversescale": False
1601 u"colorscale": [my_grey, ],
1602 u"reversescale": False
1613 layout = deepcopy(plot[u"layout"])
1614 except KeyError as err:
1615 logging.error(f"Finished with error: No layout defined\n{repr(err)}")
1618 layout[u"annotations"] = annotations
1619 layout[u'updatemenus'] = updatemenus
1623 plpl = plgo.Figure(data=traces, layout=layout)
1626 logging.info(f" Writing file {plot[u'output-file']}.html")
1631 filename=f"{plot[u'output-file']}.html"
1633 except PlotlyError as err:
1635 f" Finished with error: {repr(err)}".replace(u"\n", u" ")