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 data = input_data.filter_tests_by_name(
203 plot, params=[u"latency", u"throughput", u"parent", u"tags", u"type"])
204 if data is None or len(data[0][0]) == 0:
205 logging.error(u"No data.")
217 for test in data[0][0]:
219 if test[u"type"] not in (u"NDRPDR",):
220 logging.warning(f"Invalid test type: {test[u'type']}")
222 name = re.sub(REGEX_NIC, u"", test[u"parent"].
223 replace(u'-ndrpdr', u'').replace(u'2n1l-', u''))
225 logging.info(f" Generating the graph: {name}")
227 pdr = test[u"throughput"][u"PDR"][u"LOWER"]
228 ndr = test[u"throughput"][u"NDR"][u"LOWER"]
232 u"PDR10": f"10% PDR background traffic ({(pdr*1e-7):.2f}Mpps)",
233 u"PDR50": f"50% PDR background traffic ({(pdr*5e-7):.2f}Mpps)",
234 u"PDR90": f"90% PDR background traffic ({(pdr*9e-7):.2f}Mpps)",
235 u"PDR": f"100% PDR background traffic ({(pdr*1e-6):.2f}Mpps)",
236 u"NDR10": f"10% NDR background traffic ({(ndr*1e-7):.2f}Mpps)",
237 u"NDR50": f"50% NDR background traffic ({(ndr*5e-7):.2f}Mpps)",
238 u"NDR90": f"90% NDR background traffic ({(ndr*9e-7):.2f}Mpps)",
239 u"NDR": f"100% NDR background traffic ({(ndr*1e-6):.2f}Mpps)"
245 column_widths=[0.5, 0.5],
248 u"<b>Direction: W-E</b>",
249 u"<b>Direction: E-W</b>"
251 specs=[[{"type": "scatter"}, {"type": "scatter"}], ]
253 layout = deepcopy(plot[u"layout"])
255 for color, graph in enumerate(graphs):
256 for idx, direction in enumerate((u"direction1", u"direction2")):
260 decoded = hdrh.histogram.HdrHistogram.decode(
261 test[u"latency"][graph][direction][u"hdrh"]
263 for item in decoded.get_recorded_iterator():
264 percentile = item.percentile_level_iterated_to
265 xaxis.append((100.0 / (100.0 - percentile))
266 if percentile != 100.0 else 1e6)
267 yaxis.append(item.value_iterated_to)
269 f"<b>{desc[graph]}</b><br>"
270 f"Percentile: {percentile:.5f}%<br>"
271 f"Latency: {item.value_iterated_to}uSec"
279 legendgroup=desc[graph],
280 showlegend=bool(idx),
309 layout[u"title"][u"text"] = f"<b>Latency:</b> {name}"
310 fig.update_layout(layout)
313 file_name = (f"{plot[u'output-file']}-"
315 f"{plot.get(u'output-file-type', u'.html')}")
316 logging.info(f" Writing file {file_name}")
320 ploff.plot(fig, show_link=False, auto_open=False,
322 except PlotlyError as err:
323 logging.error(f" Finished with error: {repr(err)}")
325 except hdrh.codec.HdrLengthException as err:
326 logging.warning(repr(err))
329 except (ValueError, KeyError) as err:
330 logging.warning(repr(err))
334 def plot_lat_hdrh_bar_name(plot, input_data):
335 """Generate the plot(s) with algorithm: plot_lat_hdrh_bar_name
336 specified in the specification file.
338 :param plot: Plot to generate.
339 :param input_data: Data to process.
340 :type plot: pandas.Series
341 :type input_data: InputData
345 plot_title = plot.get(u"title", u"")
347 f" Creating the data set for the {plot.get(u'type', u'')} "
350 data = input_data.filter_tests_by_name(
351 plot, params=[u"latency", u"parent", u"tags", u"type"])
352 if data is None or len(data[0][0]) == 0:
353 logging.error(u"No data.")
356 # Prepare the data for the plot
357 directions = [u"W-E", u"E-W"]
360 for idx_row, test in enumerate(data[0][0]):
362 if test[u"type"] in (u"NDRPDR",):
363 if u"-pdr" in plot_title.lower():
365 elif u"-ndr" in plot_title.lower():
368 logging.warning(f"Invalid test type: {test[u'type']}")
370 name = re.sub(REGEX_NIC, u"", test[u"parent"].
371 replace(u'-ndrpdr', u'').
372 replace(u'2n1l-', u''))
374 for idx_col, direction in enumerate(
375 (u"direction1", u"direction2", )):
377 hdr_lat = test[u"latency"][ttype][direction][u"hdrh"]
378 # TODO: Workaround, HDRH data must be aligned to 4
379 # bytes, remove when not needed.
380 hdr_lat += u"=" * (len(hdr_lat) % 4)
384 decoded = hdrh.histogram.HdrHistogram.decode(hdr_lat)
385 total_count = decoded.get_total_count()
386 for item in decoded.get_recorded_iterator():
387 xaxis.append(item.value_iterated_to)
388 prob = float(item.count_added_in_this_iter_step) / \
393 f"Direction: {directions[idx_col]}<br>"
394 f"Latency: {item.value_iterated_to}uSec<br>"
395 f"Probability: {prob:.2f}%<br>"
397 f"{item.percentile_level_iterated_to:.2f}"
399 marker_color = [COLORS[idx_row], ] * len(yaxis)
400 marker_color[xaxis.index(
401 decoded.get_value_at_percentile(50.0))] = u"red"
402 marker_color[xaxis.index(
403 decoded.get_value_at_percentile(90.0))] = u"red"
404 marker_color[xaxis.index(
405 decoded.get_value_at_percentile(95.0))] = u"red"
412 marker={u"color": marker_color},
417 except hdrh.codec.HdrLengthException as err:
419 f"No or invalid data for HDRHistogram for the test "
423 if len(histograms) == 2:
424 traces.append(histograms)
427 logging.warning(f"Invalid test type: {test[u'type']}")
429 except (ValueError, KeyError) as err:
430 logging.warning(repr(err))
433 logging.warning(f"No data for {plot_title}.")
440 [{u"type": u"bar"}, {u"type": u"bar"}] for _ in range(len(tests))
445 gridcolor=u"rgb(220, 220, 220)",
446 linecolor=u"rgb(220, 220, 220)",
451 tickcolor=u"rgb(220, 220, 220)",
454 for idx_row, test in enumerate(tests):
455 for idx_col in range(2):
457 traces[idx_row][idx_col],
472 layout = deepcopy(plot[u"layout"])
474 layout[u"title"][u"text"] = \
475 f"<b>Latency:</b> {plot.get(u'graph-title', u'')}"
476 layout[u"height"] = 250 * len(tests) + 130
478 layout[u"annotations"][2][u"y"] = 1.06 - 0.008 * len(tests)
479 layout[u"annotations"][3][u"y"] = 1.06 - 0.008 * len(tests)
481 for idx, test in enumerate(tests):
482 layout[u"annotations"].append({
487 u"text": f"<b>{test}</b>",
490 u"xanchor": u"center",
492 u"y": 1.0 - float(idx) * 1.06 / len(tests),
493 u"yanchor": u"bottom",
497 fig[u"layout"].update(layout)
500 file_type = plot.get(u"output-file-type", u".html")
501 logging.info(f" Writing file {plot[u'output-file']}{file_type}.")
504 ploff.plot(fig, show_link=False, auto_open=False,
505 filename=f"{plot[u'output-file']}{file_type}")
506 except PlotlyError as err:
507 logging.error(f" Finished with error: {repr(err)}")
510 def plot_nf_reconf_box_name(plot, input_data):
511 """Generate the plot(s) with algorithm: plot_nf_reconf_box_name
512 specified in the specification file.
514 :param plot: Plot to generate.
515 :param input_data: Data to process.
516 :type plot: pandas.Series
517 :type input_data: InputData
522 f" Creating the data set for the {plot.get(u'type', u'')} "
523 f"{plot.get(u'title', u'')}."
525 data = input_data.filter_tests_by_name(
526 plot, params=[u"result", u"parent", u"tags", u"type"]
529 logging.error(u"No data.")
532 # Prepare the data for the plot
533 y_vals = OrderedDict()
538 if y_vals.get(test[u"parent"], None) is None:
539 y_vals[test[u"parent"]] = list()
540 loss[test[u"parent"]] = list()
542 y_vals[test[u"parent"]].append(test[u"result"][u"time"])
543 loss[test[u"parent"]].append(test[u"result"][u"loss"])
544 except (KeyError, TypeError):
545 y_vals[test[u"parent"]].append(None)
547 # Add None to the lists with missing data
549 nr_of_samples = list()
550 for val in y_vals.values():
551 if len(val) > max_len:
553 nr_of_samples.append(len(val))
554 for val in y_vals.values():
555 if len(val) < max_len:
556 val.extend([None for _ in range(max_len - len(val))])
560 df_y = pd.DataFrame(y_vals)
562 for i, col in enumerate(df_y.columns):
563 tst_name = re.sub(REGEX_NIC, u"",
564 col.lower().replace(u'-ndrpdr', u'').
565 replace(u'2n1l-', u''))
567 traces.append(plgo.Box(
568 x=[str(i + 1) + u'.'] * len(df_y[col]),
569 y=[y if y else None for y in df_y[col]],
572 f"({nr_of_samples[i]:02d} "
573 f"run{u's' if nr_of_samples[i] > 1 else u''}, "
574 f"packets lost average: {mean(loss[col]):.1f}) "
575 f"{u'-'.join(tst_name.split(u'-')[3:-2])}"
581 layout = deepcopy(plot[u"layout"])
582 layout[u"title"] = f"<b>Time Lost:</b> {layout[u'title']}"
583 layout[u"yaxis"][u"title"] = u"<b>Implied Time Lost [s]</b>"
584 layout[u"legend"][u"font"][u"size"] = 14
585 layout[u"yaxis"].pop(u"range")
586 plpl = plgo.Figure(data=traces, layout=layout)
589 file_type = plot.get(u"output-file-type", u".html")
590 logging.info(f" Writing file {plot[u'output-file']}{file_type}.")
595 filename=f"{plot[u'output-file']}{file_type}"
597 except PlotlyError as err:
599 f" Finished with error: {repr(err)}".replace(u"\n", u" ")
604 def plot_perf_box_name(plot, input_data):
605 """Generate the plot(s) with algorithm: plot_perf_box_name
606 specified in the specification file.
608 :param plot: Plot to generate.
609 :param input_data: Data to process.
610 :type plot: pandas.Series
611 :type input_data: InputData
616 f" Creating data set for the {plot.get(u'type', u'')} "
617 f"{plot.get(u'title', u'')}."
619 data = input_data.filter_tests_by_name(
620 plot, params=[u"throughput", u"parent", u"tags", u"type"])
622 logging.error(u"No data.")
625 # Prepare the data for the plot
626 y_vals = OrderedDict()
630 if y_vals.get(test[u"parent"], None) is None:
631 y_vals[test[u"parent"]] = list()
633 if (test[u"type"] in (u"NDRPDR", ) and
634 u"-pdr" in plot.get(u"title", u"").lower()):
635 y_vals[test[u"parent"]].\
636 append(test[u"throughput"][u"PDR"][u"LOWER"])
637 elif (test[u"type"] in (u"NDRPDR", ) and
638 u"-ndr" in plot.get(u"title", u"").lower()):
639 y_vals[test[u"parent"]]. \
640 append(test[u"throughput"][u"NDR"][u"LOWER"])
641 elif test[u"type"] in (u"SOAK", ):
642 y_vals[test[u"parent"]].\
643 append(test[u"throughput"][u"LOWER"])
646 except (KeyError, TypeError):
647 y_vals[test[u"parent"]].append(None)
649 # Add None to the lists with missing data
651 nr_of_samples = list()
652 for val in y_vals.values():
653 if len(val) > max_len:
655 nr_of_samples.append(len(val))
656 for val in y_vals.values():
657 if len(val) < max_len:
658 val.extend([None for _ in range(max_len - len(val))])
662 df_y = pd.DataFrame(y_vals)
665 for i, col in enumerate(df_y.columns):
666 tst_name = re.sub(REGEX_NIC, u"",
667 col.lower().replace(u'-ndrpdr', u'').
668 replace(u'2n1l-', u''))
671 x=[str(i + 1) + u'.'] * len(df_y[col]),
672 y=[y / 1000000 if y else None for y in df_y[col]],
675 f"({nr_of_samples[i]:02d} "
676 f"run{u's' if nr_of_samples[i] > 1 else u''}) "
683 val_max = max(df_y[col])
685 y_max.append(int(val_max / 1000000) + 2)
686 except (ValueError, TypeError) as err:
687 logging.error(repr(err))
692 layout = deepcopy(plot[u"layout"])
693 if layout.get(u"title", None):
694 layout[u"title"] = f"<b>Throughput:</b> {layout[u'title']}"
696 layout[u"yaxis"][u"range"] = [0, max(y_max)]
697 plpl = plgo.Figure(data=traces, layout=layout)
700 logging.info(f" Writing file {plot[u'output-file']}.html.")
705 filename=f"{plot[u'output-file']}.html"
707 except PlotlyError as err:
709 f" Finished with error: {repr(err)}".replace(u"\n", u" ")
714 def plot_lat_err_bars_name(plot, input_data):
715 """Generate the plot(s) with algorithm: plot_lat_err_bars_name
716 specified in the specification file.
718 :param plot: Plot to generate.
719 :param input_data: Data to process.
720 :type plot: pandas.Series
721 :type input_data: InputData
725 plot_title = plot.get(u"title", u"")
727 f" Creating data set for the {plot.get(u'type', u'')} {plot_title}."
729 data = input_data.filter_tests_by_name(
730 plot, params=[u"latency", u"parent", u"tags", u"type"])
732 logging.error(u"No data.")
735 # Prepare the data for the plot
736 y_tmp_vals = OrderedDict()
741 logging.debug(f"test[u'latency']: {test[u'latency']}\n")
742 except ValueError as err:
743 logging.warning(repr(err))
744 if y_tmp_vals.get(test[u"parent"], None) is None:
745 y_tmp_vals[test[u"parent"]] = [
746 list(), # direction1, min
747 list(), # direction1, avg
748 list(), # direction1, max
749 list(), # direction2, min
750 list(), # direction2, avg
751 list() # direction2, max
754 if test[u"type"] not in (u"NDRPDR", ):
755 logging.warning(f"Invalid test type: {test[u'type']}")
757 if u"-pdr" in plot_title.lower():
759 elif u"-ndr" in plot_title.lower():
763 f"Invalid test type: {test[u'type']}"
766 y_tmp_vals[test[u"parent"]][0].append(
767 test[u"latency"][ttype][u"direction1"][u"min"])
768 y_tmp_vals[test[u"parent"]][1].append(
769 test[u"latency"][ttype][u"direction1"][u"avg"])
770 y_tmp_vals[test[u"parent"]][2].append(
771 test[u"latency"][ttype][u"direction1"][u"max"])
772 y_tmp_vals[test[u"parent"]][3].append(
773 test[u"latency"][ttype][u"direction2"][u"min"])
774 y_tmp_vals[test[u"parent"]][4].append(
775 test[u"latency"][ttype][u"direction2"][u"avg"])
776 y_tmp_vals[test[u"parent"]][5].append(
777 test[u"latency"][ttype][u"direction2"][u"max"])
778 except (KeyError, TypeError) as err:
779 logging.warning(repr(err))
785 nr_of_samples = list()
786 for key, val in y_tmp_vals.items():
787 name = re.sub(REGEX_NIC, u"", key.replace(u'-ndrpdr', u'').
788 replace(u'2n1l-', u''))
789 x_vals.append(name) # dir 1
790 y_vals.append(mean(val[1]) if val[1] else None)
791 y_mins.append(mean(val[0]) if val[0] else None)
792 y_maxs.append(mean(val[2]) if val[2] else None)
793 nr_of_samples.append(len(val[1]) if val[1] else 0)
794 x_vals.append(name) # dir 2
795 y_vals.append(mean(val[4]) if val[4] else None)
796 y_mins.append(mean(val[3]) if val[3] else None)
797 y_maxs.append(mean(val[5]) if val[5] else None)
798 nr_of_samples.append(len(val[3]) if val[3] else 0)
803 for idx, _ in enumerate(x_vals):
804 if not bool(int(idx % 2)):
805 direction = u"West-East"
807 direction = u"East-West"
809 f"No. of Runs: {nr_of_samples[idx]}<br>"
810 f"Test: {x_vals[idx]}<br>"
811 f"Direction: {direction}<br>"
813 if isinstance(y_maxs[idx], float):
814 hovertext += f"Max: {y_maxs[idx]:.2f}uSec<br>"
815 if isinstance(y_vals[idx], float):
816 hovertext += f"Mean: {y_vals[idx]:.2f}uSec<br>"
817 if isinstance(y_mins[idx], float):
818 hovertext += f"Min: {y_mins[idx]:.2f}uSec"
820 if isinstance(y_maxs[idx], float) and isinstance(y_vals[idx], float):
821 array = [y_maxs[idx] - y_vals[idx], ]
824 if isinstance(y_mins[idx], float) and isinstance(y_vals[idx], float):
825 arrayminus = [y_vals[idx] - y_mins[idx], ]
827 arrayminus = [None, ]
828 traces.append(plgo.Scatter(
832 legendgroup=x_vals[idx],
833 showlegend=bool(int(idx % 2)),
839 arrayminus=arrayminus,
840 color=COLORS[int(idx / 2)]
844 color=COLORS[int(idx / 2)],
849 annotations.append(dict(
856 text=u"E-W" if bool(int(idx % 2)) else u"W-E",
866 file_type = plot.get(u"output-file-type", u".html")
867 logging.info(f" Writing file {plot[u'output-file']}{file_type}.")
868 layout = deepcopy(plot[u"layout"])
869 if layout.get(u"title", None):
870 layout[u"title"] = f"<b>Latency:</b> {layout[u'title']}"
871 layout[u"annotations"] = annotations
872 plpl = plgo.Figure(data=traces, layout=layout)
877 show_link=False, auto_open=False,
878 filename=f"{plot[u'output-file']}{file_type}"
880 except PlotlyError as err:
882 f" Finished with error: {repr(err)}".replace(u"\n", u" ")
887 def plot_tsa_name(plot, input_data):
888 """Generate the plot(s) with algorithm:
890 specified in the specification file.
892 :param plot: Plot to generate.
893 :param input_data: Data to process.
894 :type plot: pandas.Series
895 :type input_data: InputData
899 plot_title = plot.get(u"title", u"")
901 f" Creating data set for the {plot.get(u'type', u'')} {plot_title}."
903 data = input_data.filter_tests_by_name(
904 plot, params=[u"throughput", u"parent", u"tags", u"type"])
906 logging.error(u"No data.")
909 y_vals = OrderedDict()
913 if y_vals.get(test[u"parent"], None) is None:
914 y_vals[test[u"parent"]] = {
920 if test[u"type"] not in (u"NDRPDR",):
923 if u"-pdr" in plot_title.lower():
925 elif u"-ndr" in plot_title.lower():
930 if u"1C" in test[u"tags"]:
931 y_vals[test[u"parent"]][u"1"]. \
932 append(test[u"throughput"][ttype][u"LOWER"])
933 elif u"2C" in test[u"tags"]:
934 y_vals[test[u"parent"]][u"2"]. \
935 append(test[u"throughput"][ttype][u"LOWER"])
936 elif u"4C" in test[u"tags"]:
937 y_vals[test[u"parent"]][u"4"]. \
938 append(test[u"throughput"][ttype][u"LOWER"])
939 except (KeyError, TypeError):
943 logging.warning(f"No data for the plot {plot.get(u'title', u'')}")
947 for test_name, test_vals in y_vals.items():
948 for key, test_val in test_vals.items():
950 avg_val = sum(test_val) / len(test_val)
951 y_vals[test_name][key] = [avg_val, len(test_val)]
952 ideal = avg_val / (int(key) * 1000000.0)
953 if test_name not in y_1c_max or ideal > y_1c_max[test_name]:
954 y_1c_max[test_name] = ideal
960 pci_limit = plot[u"limits"][u"pci"][u"pci-g3-x8"]
961 for test_name, test_vals in y_vals.items():
963 if test_vals[u"1"][1]:
967 test_name.replace(u'-ndrpdr', u'').replace(u'2n1l-', u'')
969 vals[name] = OrderedDict()
970 y_val_1 = test_vals[u"1"][0] / 1000000.0
971 y_val_2 = test_vals[u"2"][0] / 1000000.0 if test_vals[u"2"][0] \
973 y_val_4 = test_vals[u"4"][0] / 1000000.0 if test_vals[u"4"][0] \
976 vals[name][u"val"] = [y_val_1, y_val_2, y_val_4]
977 vals[name][u"rel"] = [1.0, None, None]
978 vals[name][u"ideal"] = [
980 y_1c_max[test_name] * 2,
981 y_1c_max[test_name] * 4
983 vals[name][u"diff"] = [
984 (y_val_1 - y_1c_max[test_name]) * 100 / y_val_1, None, None
986 vals[name][u"count"] = [
993 val_max = max(vals[name][u"val"])
994 except ValueError as err:
995 logging.error(repr(err))
998 y_max.append(val_max)
1001 vals[name][u"rel"][1] = round(y_val_2 / y_val_1, 2)
1002 vals[name][u"diff"][1] = \
1003 (y_val_2 - vals[name][u"ideal"][1]) * 100 / y_val_2
1005 vals[name][u"rel"][2] = round(y_val_4 / y_val_1, 2)
1006 vals[name][u"diff"][2] = \
1007 (y_val_4 - vals[name][u"ideal"][2]) * 100 / y_val_4
1008 except IndexError as err:
1009 logging.warning(f"No data for {test_name}")
1010 logging.warning(repr(err))
1013 if u"x520" in test_name:
1014 limit = plot[u"limits"][u"nic"][u"x520"]
1015 elif u"x710" in test_name:
1016 limit = plot[u"limits"][u"nic"][u"x710"]
1017 elif u"xxv710" in test_name:
1018 limit = plot[u"limits"][u"nic"][u"xxv710"]
1019 elif u"xl710" in test_name:
1020 limit = plot[u"limits"][u"nic"][u"xl710"]
1021 elif u"x553" in test_name:
1022 limit = plot[u"limits"][u"nic"][u"x553"]
1025 if limit > nic_limit:
1028 mul = 2 if u"ge2p" in test_name else 1
1029 if u"10ge" in test_name:
1030 limit = plot[u"limits"][u"link"][u"10ge"] * mul
1031 elif u"25ge" in test_name:
1032 limit = plot[u"limits"][u"link"][u"25ge"] * mul
1033 elif u"40ge" in test_name:
1034 limit = plot[u"limits"][u"link"][u"40ge"] * mul
1035 elif u"100ge" in test_name:
1036 limit = plot[u"limits"][u"link"][u"100ge"] * mul
1039 if limit > lnk_limit:
1043 annotations = list()
1048 threshold = 1.1 * max(y_max) # 10%
1049 except ValueError as err:
1052 nic_limit /= 1000000.0
1053 traces.append(plgo.Scatter(
1055 y=[nic_limit, ] * len(x_vals),
1056 name=f"NIC: {nic_limit:.2f}Mpps",
1065 annotations.append(dict(
1072 text=f"NIC: {nic_limit:.2f}Mpps",
1080 y_max.append(nic_limit)
1082 lnk_limit /= 1000000.0
1083 if lnk_limit < threshold:
1084 traces.append(plgo.Scatter(
1086 y=[lnk_limit, ] * len(x_vals),
1087 name=f"Link: {lnk_limit:.2f}Mpps",
1096 annotations.append(dict(
1103 text=f"Link: {lnk_limit:.2f}Mpps",
1111 y_max.append(lnk_limit)
1113 pci_limit /= 1000000.0
1114 if (pci_limit < threshold and
1115 (pci_limit < lnk_limit * 0.95 or lnk_limit > lnk_limit * 1.05)):
1116 traces.append(plgo.Scatter(
1118 y=[pci_limit, ] * len(x_vals),
1119 name=f"PCIe: {pci_limit:.2f}Mpps",
1128 annotations.append(dict(
1135 text=f"PCIe: {pci_limit:.2f}Mpps",
1143 y_max.append(pci_limit)
1145 # Perfect and measured:
1147 for name, val in vals.items():
1150 for idx in range(len(val[u"val"])):
1152 if isinstance(val[u"val"][idx], float):
1154 f"No. of Runs: {val[u'count'][idx]}<br>"
1155 f"Mean: {val[u'val'][idx]:.2f}Mpps<br>"
1157 if isinstance(val[u"diff"][idx], float):
1158 htext += f"Diff: {round(val[u'diff'][idx]):.0f}%<br>"
1159 if isinstance(val[u"rel"][idx], float):
1160 htext += f"Speedup: {val[u'rel'][idx]:.2f}"
1161 hovertext.append(htext)
1168 mode=u"lines+markers",
1177 hoverinfo=u"text+name"
1184 name=f"{name} perfect",
1192 text=[f"Perfect: {y:.2f}Mpps" for y in val[u"ideal"]],
1197 except (IndexError, ValueError, KeyError) as err:
1198 logging.warning(f"No data for {name}\n{repr(err)}")
1202 file_type = plot.get(u"output-file-type", u".html")
1203 logging.info(f" Writing file {plot[u'output-file']}{file_type}.")
1204 layout = deepcopy(plot[u"layout"])
1205 if layout.get(u"title", None):
1206 layout[u"title"] = f"<b>Speedup Multi-core:</b> {layout[u'title']}"
1207 layout[u"yaxis"][u"range"] = [0, int(max(y_max) * 1.1)]
1208 layout[u"annotations"].extend(annotations)
1209 plpl = plgo.Figure(data=traces, layout=layout)
1216 filename=f"{plot[u'output-file']}{file_type}"
1218 except PlotlyError as err:
1220 f" Finished with error: {repr(err)}".replace(u"\n", u" ")
1225 def plot_http_server_perf_box(plot, input_data):
1226 """Generate the plot(s) with algorithm: plot_http_server_perf_box
1227 specified in the specification file.
1229 :param plot: Plot to generate.
1230 :param input_data: Data to process.
1231 :type plot: pandas.Series
1232 :type input_data: InputData
1235 # Transform the data
1237 f" Creating the data set for the {plot.get(u'type', u'')} "
1238 f"{plot.get(u'title', u'')}."
1240 data = input_data.filter_data(plot)
1242 logging.error(u"No data.")
1245 # Prepare the data for the plot
1250 if y_vals.get(test[u"name"], None) is None:
1251 y_vals[test[u"name"]] = list()
1253 y_vals[test[u"name"]].append(test[u"result"])
1254 except (KeyError, TypeError):
1255 y_vals[test[u"name"]].append(None)
1257 # Add None to the lists with missing data
1259 nr_of_samples = list()
1260 for val in y_vals.values():
1261 if len(val) > max_len:
1263 nr_of_samples.append(len(val))
1264 for val in y_vals.values():
1265 if len(val) < max_len:
1266 val.extend([None for _ in range(max_len - len(val))])
1270 df_y = pd.DataFrame(y_vals)
1272 for i, col in enumerate(df_y.columns):
1275 f"({nr_of_samples[i]:02d} " \
1276 f"run{u's' if nr_of_samples[i] > 1 else u''}) " \
1277 f"{col.lower().replace(u'-ndrpdr', u'')}"
1279 name_lst = name.split(u'-')
1282 for segment in name_lst:
1283 if (len(name) + len(segment) + 1) > 50 and split_name:
1286 name += segment + u'-'
1289 traces.append(plgo.Box(x=[str(i + 1) + u'.'] * len(df_y[col]),
1295 plpl = plgo.Figure(data=traces, layout=plot[u"layout"])
1299 f" Writing file {plot[u'output-file']}"
1300 f"{plot[u'output-file-type']}."
1306 filename=f"{plot[u'output-file']}{plot[u'output-file-type']}"
1308 except PlotlyError as err:
1310 f" Finished with error: {repr(err)}".replace(u"\n", u" ")
1315 def plot_nf_heatmap(plot, input_data):
1316 """Generate the plot(s) with algorithm: plot_nf_heatmap
1317 specified in the specification file.
1319 :param plot: Plot to generate.
1320 :param input_data: Data to process.
1321 :type plot: pandas.Series
1322 :type input_data: InputData
1325 regex_cn = re.compile(r'^(\d*)R(\d*)C$')
1326 regex_test_name = re.compile(r'^.*-(\d+ch|\d+pl)-'
1328 r'(\d+vm\d+t|\d+dcr\d+t).*$')
1331 # Transform the data
1333 f" Creating the data set for the {plot.get(u'type', u'')} "
1334 f"{plot.get(u'title', u'')}."
1336 data = input_data.filter_data(plot, continue_on_error=True)
1337 if data is None or data.empty:
1338 logging.error(u"No data.")
1344 for tag in test[u"tags"]:
1345 groups = re.search(regex_cn, tag)
1347 chain = str(groups.group(1))
1348 node = str(groups.group(2))
1352 groups = re.search(regex_test_name, test[u"name"])
1353 if groups and len(groups.groups()) == 3:
1355 f"{str(groups.group(1))}-"
1356 f"{str(groups.group(2))}-"
1357 f"{str(groups.group(3))}"
1361 if vals.get(chain, None) is None:
1362 vals[chain] = dict()
1363 if vals[chain].get(node, None) is None:
1364 vals[chain][node] = dict(
1372 if plot[u"include-tests"] == u"MRR":
1373 result = test[u"result"][u"receive-rate"]
1374 elif plot[u"include-tests"] == u"PDR":
1375 result = test[u"throughput"][u"PDR"][u"LOWER"]
1376 elif plot[u"include-tests"] == u"NDR":
1377 result = test[u"throughput"][u"NDR"][u"LOWER"]
1384 vals[chain][node][u"vals"].append(result)
1387 logging.error(u"No data.")
1393 txt_chains.append(key_c)
1394 for key_n in vals[key_c].keys():
1395 txt_nodes.append(key_n)
1396 if vals[key_c][key_n][u"vals"]:
1397 vals[key_c][key_n][u"nr"] = len(vals[key_c][key_n][u"vals"])
1398 vals[key_c][key_n][u"mean"] = \
1399 round(mean(vals[key_c][key_n][u"vals"]) / 1000000, 1)
1400 vals[key_c][key_n][u"stdev"] = \
1401 round(stdev(vals[key_c][key_n][u"vals"]) / 1000000, 1)
1402 txt_nodes = list(set(txt_nodes))
1404 def sort_by_int(value):
1405 """Makes possible to sort a list of strings which represent integers.
1407 :param value: Integer as a string.
1409 :returns: Integer representation of input parameter 'value'.
1414 txt_chains = sorted(txt_chains, key=sort_by_int)
1415 txt_nodes = sorted(txt_nodes, key=sort_by_int)
1417 chains = [i + 1 for i in range(len(txt_chains))]
1418 nodes = [i + 1 for i in range(len(txt_nodes))]
1420 data = [list() for _ in range(len(chains))]
1421 for chain in chains:
1424 val = vals[txt_chains[chain - 1]][txt_nodes[node - 1]][u"mean"]
1425 except (KeyError, IndexError):
1427 data[chain - 1].append(val)
1430 my_green = [[0.0, u"rgb(235, 249, 242)"],
1431 [1.0, u"rgb(45, 134, 89)"]]
1433 my_blue = [[0.0, u"rgb(236, 242, 248)"],
1434 [1.0, u"rgb(57, 115, 172)"]]
1436 my_grey = [[0.0, u"rgb(230, 230, 230)"],
1437 [1.0, u"rgb(102, 102, 102)"]]
1440 annotations = list()
1442 text = (u"Test: {name}<br>"
1447 for chain, _ in enumerate(txt_chains):
1449 for node, _ in enumerate(txt_nodes):
1450 if data[chain][node] is not None:
1459 text=str(data[chain][node]),
1467 hover_line.append(text.format(
1468 name=vals[txt_chains[chain]][txt_nodes[node]][u"name"],
1469 nr=vals[txt_chains[chain]][txt_nodes[node]][u"nr"],
1470 val=data[chain][node],
1471 stdev=vals[txt_chains[chain]][txt_nodes[node]][u"stdev"]))
1472 hovertext.append(hover_line)
1480 title=plot.get(u"z-axis", u""),
1494 colorscale=my_green,
1500 for idx, item in enumerate(txt_nodes):
1518 for idx, item in enumerate(txt_chains):
1545 text=plot.get(u"x-axis", u""),
1562 text=plot.get(u"y-axis", u""),
1571 updatemenus = list([
1582 u"colorscale": [my_green, ],
1583 u"reversescale": False
1592 u"colorscale": [my_blue, ],
1593 u"reversescale": False
1602 u"colorscale": [my_grey, ],
1603 u"reversescale": False
1614 layout = deepcopy(plot[u"layout"])
1615 except KeyError as err:
1616 logging.error(f"Finished with error: No layout defined\n{repr(err)}")
1619 layout[u"annotations"] = annotations
1620 layout[u'updatemenus'] = updatemenus
1624 plpl = plgo.Figure(data=traces, layout=layout)
1628 f" Writing file {plot[u'output-file']}"
1629 f"{plot[u'output-file-type']}."
1635 filename=f"{plot[u'output-file']}{plot[u'output-file-type']}"
1637 except PlotlyError as err:
1639 f" Finished with error: {repr(err)}".replace(u"\n", u" ")