1 # Copyright (c) 2024 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 """Plotly Dash HTML layout override.
18 import dash_bootstrap_components as dbc
20 from flask import Flask
21 from dash import dcc, html, dash_table, callback_context, no_update, ALL
22 from dash import Input, Output, State
23 from dash.exceptions import PreventUpdate
24 from dash.dash_table.Format import Format, Scheme
25 from ast import literal_eval
27 from ..utils.constants import Constants as C
28 from ..utils.control_panel import ControlPanel
29 from ..utils.trigger import Trigger
30 from ..utils.url_processing import url_decode
31 from ..utils.utils import generate_options, gen_new_url, navbar_report, \
33 from .tables import comparison_table
36 # Control panel partameters and their default values.
47 "frmsize-opt": list(),
48 "frmsize-val": list(),
51 "cmp-par-opt": list(),
54 "cmp-val-opt": list(),
57 "normalize-val": list(),
58 "outliers-val": list()
61 # List of comparable parameters.
63 "dutver": "Release and Version",
64 "infra": "Infrastructure",
65 "frmsize": "Frame Size",
66 "core": "Number of Cores",
67 "ttype": "Measurement"
72 """The layout of the dash app and the callbacks.
78 data_iterative: pd.DataFrame,
82 - save the input parameters,
83 - prepare data for the control panel,
84 - read HTML layout file,
86 :param app: Flask application running the dash application.
87 :param data_iterative: Iterative data to be used in comparison tables.
88 :param html_layout_file: Path and name of the file specifying the HTML
89 layout of the dash application.
91 :type data_iterative: pandas.DataFrame
92 :type html_layout_file: str
97 self._html_layout_file = html_layout_file
98 self._data = data_iterative
100 # Get structure of tests:
103 "job", "test_id", "test_type", "dut_type", "dut_version", "tg_type",
106 for _, row in self._data[cols].drop_duplicates().iterrows():
107 lst_job = row["job"].split("-")
109 dver = f"{row['release']}-{row['dut_version']}"
110 tbed = "-".join(lst_job[-2:])
111 lst_test_id = row["test_id"].split(".")
113 suite = lst_test_id[-2].replace("2n1l-", "").replace("1n1l-", "").\
115 test = lst_test_id[-1]
116 nic = suite.split("-")[0]
117 for driver in C.DRIVERS:
119 drv = driver.replace("-", "_")
120 test = test.replace(f"{driver}-", "")
124 infra = "-".join((tbed, nic, drv))
125 lst_test = test.split("-")
127 core = lst_test[1] if lst_test[1] else "8C"
129 if tbs.get(dut, None) is None:
131 if tbs[dut].get(dver, None) is None:
132 tbs[dut][dver] = dict()
133 if tbs[dut][dver].get(infra, None) is None:
134 tbs[dut][dver][infra] = dict()
135 tbs[dut][dver][infra]["core"] = list()
136 tbs[dut][dver][infra]["fsize"] = list()
137 tbs[dut][dver][infra]["ttype"] = list()
138 if core.upper() not in tbs[dut][dver][infra]["core"]:
139 tbs[dut][dver][infra]["core"].append(core.upper())
140 if fsize.upper() not in tbs[dut][dver][infra]["fsize"]:
141 tbs[dut][dver][infra]["fsize"].append(fsize.upper())
142 if row["test_type"] == "mrr":
143 if "MRR" not in tbs[dut][dver][infra]["ttype"]:
144 tbs[dut][dver][infra]["ttype"].append("MRR")
145 elif row["test_type"] == "ndrpdr":
146 if "NDR" not in tbs[dut][dver][infra]["ttype"]:
147 tbs[dut][dver][infra]["ttype"].extend(
148 ("NDR", "PDR", "Latency")
150 elif row["test_type"] == "hoststack" and \
151 row["tg_type"] in ("iperf", "vpp"):
152 if "BPS" not in tbs[dut][dver][infra]["ttype"]:
153 tbs[dut][dver][infra]["ttype"].append("BPS")
154 elif row["test_type"] == "hoststack" and row["tg_type"] == "ab":
155 if "CPS" not in tbs[dut][dver][infra]["ttype"]:
156 tbs[dut][dver][infra]["ttype"].extend(("CPS", "RPS", ))
160 self._html_layout = str()
162 with open(self._html_layout_file, "r") as file_read:
163 self._html_layout = file_read.read()
164 except IOError as err:
166 f"Not possible to open the file {self._html_layout_file}\n{err}"
170 if self._app is not None and hasattr(self, "callbacks"):
171 self.callbacks(self._app)
174 def html_layout(self):
175 return self._html_layout
177 def add_content(self):
178 """Top level method which generated the web page.
181 - Store for user input data,
183 - Main area with control panel and ploting area.
185 If no HTML layout is provided, an error message is displayed instead.
187 :returns: The HTML div with the whole page.
191 if self.html_layout and self._tbs:
199 children=[navbar_report((False, True, False, False)), ]
205 dcc.Store(id="store-control-panel"),
206 dcc.Store(id="store-selected"),
207 dcc.Store(id="store-table-data"),
208 dcc.Store(id="store-filtered-table-data"),
209 dcc.Location(id="url", refresh=False),
210 self._add_ctrl_col(),
211 self._add_plotting_col()
216 id="offcanvas-documentation",
217 title="Documentation",
220 children=html.Iframe(
221 src=C.URL_DOC_REL_NOTES,
241 def _add_ctrl_col(self) -> dbc.Col:
242 """Add column with controls. It is placed on the left side.
244 :returns: Column with the control panel.
249 children=self._add_ctrl_panel(),
250 className="sticky-top"
254 def _add_plotting_col(self) -> dbc.Col:
255 """Add column with plots. It is placed on the right side.
257 :returns: Column with plots.
261 id="col-plotting-area",
267 class_name="g-0 p-0",
278 def _add_ctrl_panel(self) -> list:
279 """Add control panel.
281 :returns: Control panel.
287 class_name="g-0 p-1",
291 dbc.InputGroupText("DUT"),
293 id={"type": "ctrl-dd", "index": "dut"},
294 placeholder="Select a Device under Test...",
297 {"label": k, "value": k} \
298 for k in self._tbs.keys()
300 key=lambda d: d["label"]
309 class_name="g-0 p-1",
313 dbc.InputGroupText("CSIT and DUT Version"),
315 id={"type": "ctrl-dd", "index": "dutver"},
316 placeholder="Select a CSIT and DUT Version...")
323 class_name="g-0 p-1",
327 dbc.InputGroupText("Infra"),
329 id={"type": "ctrl-dd", "index": "infra"},
331 "Select a Physical Test Bed Topology..."
339 class_name="g-0 p-1",
343 dbc.InputGroupText("Frame Size"),
345 id={"type": "ctrl-cl", "index": "frmsize"},
350 style={"align-items": "center"},
356 class_name="g-0 p-1",
360 dbc.InputGroupText("Number of Cores"),
362 id={"type": "ctrl-cl", "index": "core"},
367 style={"align-items": "center"},
373 class_name="g-0 p-1",
377 dbc.InputGroupText("Measurement"),
379 id={"type": "ctrl-cl", "index": "ttype"},
384 style={"align-items": "center"},
393 class_name="g-0 p-1",
397 dbc.InputGroupText("Parameter"),
399 id={"type": "ctrl-dd", "index": "cmpprm"},
400 placeholder="Select a Parameter..."
408 class_name="g-0 p-1",
412 dbc.InputGroupText("Value"),
414 id={"type": "ctrl-dd", "index": "cmpval"},
415 placeholder="Select a Value..."
426 class_name="g-0 p-1",
433 "value": "normalize",
434 "label": "Normalize to 2GHz CPU frequency"
444 "label": "Remove Extreme Outliers"
451 style={"align-items": "center"},
463 html.H5("Reference Value")
479 html.H5("Compared Value")
495 html.H5("Data Manipulations")
510 def _get_plotting_area(
515 """Generate the plotting area with all its content.
517 :param title: The title of the comparison table.
518 :param table: Comparison table to be displayed.
519 :param url: URL to be displayed in the modal window.
521 :type table: pandas.DataFrame
523 :returns: List of rows with elements to be displayed in the plotting
532 "No data for comparison.",
535 class_name="g-0 p-1",
541 for idx, col in enumerate(table.columns):
551 l_col = col.rsplit(" ", 2)
553 "name": [l_col[0], " ".join(l_col[-2:])],
558 "format": Format(precision=2, scheme=Scheme.fixed)
563 children=html.H5(title),
569 children=dash_table.DataTable(
570 id={"type": "table", "index": "comparison"},
572 data=table.to_dict("records"),
573 merge_duplicate_headers=True,
575 filter_action="custom",
577 sort_action="native",
582 style_cell={"textAlign": "right"},
583 style_cell_conditional=[{
584 "if": {"column_id": "Test Name"},
603 "text-transform": "none",
604 "padding": "0rem 1rem"
609 dbc.ModalHeader(dbc.ModalTitle("URL")),
618 id="plot-btn-download",
619 children="Download Data",
623 "text-transform": "none",
624 "padding": "0rem 1rem"
627 dcc.Download(id="download-iterative-data")
630 "d-grid gap-0 d-md-flex justify-content-md-end"
636 children=C.PLACEHOLDER,
641 def callbacks(self, app):
642 """Callbacks for the whole application.
644 :param app: The application.
650 Output("store-control-panel", "data"),
651 Output("store-selected", "data"),
652 Output("store-table-data", "data"),
653 Output("store-filtered-table-data", "data"),
654 Output("plotting-area", "children"),
655 Output({"type": "table", "index": ALL}, "data"),
656 Output({"type": "ctrl-dd", "index": "dut"}, "value"),
657 Output({"type": "ctrl-dd", "index": "dutver"}, "options"),
658 Output({"type": "ctrl-dd", "index": "dutver"}, "disabled"),
659 Output({"type": "ctrl-dd", "index": "dutver"}, "value"),
660 Output({"type": "ctrl-dd", "index": "infra"}, "options"),
661 Output({"type": "ctrl-dd", "index": "infra"}, "disabled"),
662 Output({"type": "ctrl-dd", "index": "infra"}, "value"),
663 Output({"type": "ctrl-cl", "index": "core"}, "options"),
664 Output({"type": "ctrl-cl", "index": "core"}, "value"),
665 Output({"type": "ctrl-cl", "index": "frmsize"}, "options"),
666 Output({"type": "ctrl-cl", "index": "frmsize"}, "value"),
667 Output({"type": "ctrl-cl", "index": "ttype"}, "options"),
668 Output({"type": "ctrl-cl", "index": "ttype"}, "value"),
669 Output({"type": "ctrl-dd", "index": "cmpprm"}, "options"),
670 Output({"type": "ctrl-dd", "index": "cmpprm"}, "disabled"),
671 Output({"type": "ctrl-dd", "index": "cmpprm"}, "value"),
672 Output({"type": "ctrl-dd", "index": "cmpval"}, "options"),
673 Output({"type": "ctrl-dd", "index": "cmpval"}, "disabled"),
674 Output({"type": "ctrl-dd", "index": "cmpval"}, "value"),
675 Output("normalize", "value"),
676 Output("outliers", "value")
679 State("store-control-panel", "data"),
680 State("store-selected", "data"),
681 State("store-table-data", "data"),
682 State("store-filtered-table-data", "data"),
683 State({"type": "table", "index": ALL}, "data")
686 Input("url", "href"),
687 Input("normalize", "value"),
688 Input("outliers", "value"),
689 Input({"type": "table", "index": ALL}, "filter_query"),
690 Input({"type": "ctrl-dd", "index": ALL}, "value"),
691 Input({"type": "ctrl-cl", "index": ALL}, "value"),
692 Input({"type": "ctrl-btn", "index": ALL}, "n_clicks")
695 def _update_application(
698 store_table_data: list,
707 """Update the application when the event is detected.
710 ctrl_panel = ControlPanel(CP_PARAMS, control_panel)
723 parsed_url = url_decode(href)
725 url_params = parsed_url["params"]
730 plotting_area = no_update
732 trigger = Trigger(callback_context.triggered)
733 if trigger.type == "url" and url_params:
736 selected = literal_eval(url_params["selected"][0])
737 r_sel = selected["reference"]["selection"]
738 c_sel = selected["compare"]
739 normalize = literal_eval(url_params["norm"][0])
740 try: # Necessary for backward compatibility
741 outliers = literal_eval(url_params["outliers"][0])
742 except (KeyError, IndexError, AttributeError):
745 (selected["reference"]["set"] == True) and
746 (c_sel["set"] == True)
748 except (KeyError, IndexError, AttributeError):
752 "dut-val": r_sel["dut"],
753 "dutver-opt": generate_options(
754 self._tbs[r_sel["dut"]].keys()
757 "dutver-val": r_sel["dutver"],
758 "infra-opt": generate_options(
759 self._tbs[r_sel["dut"]][r_sel["dutver"]].keys()
762 "infra-val": r_sel["infra"],
763 "core-opt": generate_options(
764 self._tbs[r_sel["dut"]][r_sel["dutver"]]\
765 [r_sel["infra"]]["core"]
767 "core-val": r_sel["core"],
768 "frmsize-opt": generate_options(
769 self._tbs[r_sel["dut"]][r_sel["dutver"]]\
770 [r_sel["infra"]]["fsize"]
772 "frmsize-val": r_sel["frmsize"],
773 "ttype-opt": generate_options(
774 self._tbs[r_sel["dut"]][r_sel["dutver"]]\
775 [r_sel["infra"]]["ttype"]
777 "ttype-val": r_sel["ttype"],
778 "normalize-val": normalize,
779 "outliers-val": outliers
782 for itm, label in CMP_PARAMS.items():
783 if len(ctrl_panel.get(f"{itm}-opt")) > 1:
784 opts.append({"label": label, "value": itm})
787 "cmp-par-dis": False,
788 "cmp-par-val": c_sel["parameter"]
791 for itm in ctrl_panel.get(f"{c_sel['parameter']}-opt"):
792 set_val = ctrl_panel.get(f"{c_sel['parameter']}-val")
793 if isinstance(set_val, list):
794 if itm["value"] not in set_val:
797 if itm["value"] != set_val:
801 "cmp-val-dis": False,
802 "cmp-val-val": c_sel["value"]
805 elif trigger.type == "normalize":
806 ctrl_panel.set({"normalize-val": normalize})
808 elif trigger.type == "outliers":
809 ctrl_panel.set({"outliers-val": outliers})
811 elif trigger.type == "ctrl-dd":
812 if trigger.idx == "dut":
814 opts = generate_options(self._tbs[trigger.value].keys())
820 "dut-val": trigger.value,
822 "dutver-dis": disabled,
829 "frmsize-opt": list(),
830 "frmsize-val": list(),
833 "cmp-par-opt": list(),
835 "cmp-par-val": str(),
836 "cmp-val-opt": list(),
840 elif trigger.idx == "dutver":
842 dut = ctrl_panel.get("dut-val")
843 dver = self._tbs[dut][trigger.value]
844 opts = generate_options(dver.keys())
850 "dutver-val": trigger.value,
852 "infra-dis": disabled,
856 "frmsize-opt": list(),
857 "frmsize-val": list(),
860 "cmp-par-opt": list(),
862 "cmp-par-val": str(),
863 "cmp-val-opt": list(),
867 elif trigger.idx == "infra":
868 dut = ctrl_panel.get("dut-val")
869 dver = ctrl_panel.get("dutver-val")
870 if all((dut, dver, trigger.value, )):
871 driver = self._tbs[dut][dver][trigger.value]
873 "infra-val": trigger.value,
874 "core-opt": generate_options(driver["core"]),
876 "frmsize-opt": generate_options(driver["fsize"]),
877 "frmsize-val": list(),
878 "ttype-opt": generate_options(driver["ttype"]),
880 "cmp-par-opt": list(),
882 "cmp-par-val": str(),
883 "cmp-val-opt": list(),
887 elif trigger.idx == "cmpprm":
888 value = trigger.value
890 for itm in ctrl_panel.get(f"{value}-opt"):
891 set_val = ctrl_panel.get(f"{value}-val")
892 if isinstance(set_val, list):
893 if itm["value"] == "Latency":
895 if itm["value"] not in set_val:
898 if itm["value"] != set_val:
901 "cmp-par-val": value,
903 "cmp-val-dis": False,
906 elif trigger.idx == "cmpval":
907 ctrl_panel.set({"cmp-val-val": trigger.value})
908 selected["reference"] = {
911 "dut": ctrl_panel.get("dut-val"),
912 "dutver": ctrl_panel.get("dutver-val"),
913 "infra": ctrl_panel.get("infra-val"),
914 "core": ctrl_panel.get("core-val"),
915 "frmsize": ctrl_panel.get("frmsize-val"),
916 "ttype": ctrl_panel.get("ttype-val")
919 selected["compare"] = {
921 "parameter": ctrl_panel.get("cmp-par-val"),
922 "value": trigger.value
925 elif trigger.type == "ctrl-cl":
926 ctrl_panel.set({f"{trigger.idx}-val": trigger.value})
927 if all((ctrl_panel.get("core-val"),
928 ctrl_panel.get("frmsize-val"),
929 ctrl_panel.get("ttype-val"), )):
930 if "Latency" in ctrl_panel.get("ttype-val"):
931 ctrl_panel.set({"ttype-val": ["Latency", ]})
933 for itm, label in CMP_PARAMS.items():
934 if "Latency" in ctrl_panel.get("ttype-val") and \
937 if len(ctrl_panel.get(f"{itm}-opt")) > 1:
938 if isinstance(ctrl_panel.get(f"{itm}-val"), list):
939 if len(ctrl_panel.get(f"{itm}-opt")) == \
940 len(ctrl_panel.get(f"{itm}-val")):
942 opts.append({"label": label, "value": itm})
945 "cmp-par-dis": False,
946 "cmp-par-val": str(),
947 "cmp-val-opt": list(),
953 "cmp-par-opt": list(),
955 "cmp-par-val": str(),
956 "cmp-val-opt": list(),
960 elif trigger.type == "table" and trigger.idx == "comparison":
961 filtered_data = filter_table_data(
965 table_data = [filtered_data, ]
967 if all((on_draw, selected["reference"]["set"],
968 selected["compare"]["set"], )):
969 title, table = comparison_table(
974 remove_outliers=outliers
976 plotting_area = self._get_plotting_area(
982 "selected": selected,
988 store_table_data = table.to_dict("records")
989 filtered_data = store_table_data
991 table_data = [store_table_data, ]
1001 ret_val.extend(ctrl_panel.values)
1005 Output("plot-mod-url", "is_open"),
1006 Input("plot-btn-url", "n_clicks"),
1007 State("plot-mod-url", "is_open")
1009 def toggle_plot_mod_url(n, is_open):
1010 """Toggle the modal window with url.
1017 Output("download-iterative-data", "data"),
1018 State("store-table-data", "data"),
1019 State("store-filtered-table-data", "data"),
1020 Input("plot-btn-download", "n_clicks"),
1021 prevent_initial_call=True
1023 def _download_comparison_data(
1025 filtered_table_data: list,
1028 """Download the data.
1030 :param table_data: Original unfiltered table data.
1031 :param filtered_table_data: Filtered table data.
1032 :type table_data: list
1033 :type filtered_table_data: list
1034 :returns: dict of data frame content (base64 encoded) and meta data
1035 used by the Download component.
1042 if filtered_table_data:
1043 table = pd.DataFrame.from_records(filtered_table_data)
1045 table = pd.DataFrame.from_records(table_data)
1047 return dcc.send_data_frame(table.to_csv, C.COMP_DOWNLOAD_FILE_NAME)
1050 Output("offcanvas-documentation", "is_open"),
1051 Input("btn-documentation", "n_clicks"),
1052 State("offcanvas-documentation", "is_open")
1054 def toggle_offcanvas_documentation(n_clicks, is_open):