C-Dash: Add search in tests
[csit.git] / csit.infra.dash / app / cdash / trending / graphs.py
index ab8b627..ede3a06 100644 (file)
@@ -1,4 +1,4 @@
-# Copyright (c) 2023 Cisco and/or its affiliates.
+# Copyright (c) 2024 Cisco and/or its affiliates.
 # Licensed under the Apache License, Version 2.0 (the "License");
 # you may not use this file except in compliance with the License.
 # You may obtain a copy of the License at:
@@ -14,6 +14,7 @@
 """Implementation of graphs for trending data.
 """
 
+import logging
 import plotly.graph_objects as go
 import pandas as pd
 
@@ -70,7 +71,7 @@ def graph_trending(
         data: pd.DataFrame,
         sel: dict,
         layout: dict,
-        normalize: bool
+        normalize: bool=False
     ) -> tuple:
     """Generate the trending graph(s) - MRR, NDR, PDR and for PDR also Latences
     (result_latency_forward_pdr_50_avg).
@@ -97,7 +98,7 @@ def graph_trending(
             name: str,
             df: pd.DataFrame,
             color: str,
-            norm_factor: float
+            nf: float
         ) -> list:
         """Generate the trending traces for the trending graph.
 
@@ -105,13 +106,13 @@ def graph_trending(
         :param name: The test name to be displayed as the graph title.
         :param df: Data frame with test data.
         :param color: The color of the trace (samples and trend line).
-        :param norm_factor: The factor used for normalization of the results to
+        :param nf: The factor used for normalization of the results to
             CPU frequency set to Constants.NORM_FREQUENCY.
         :type ttype: str
         :type name: str
         :type df: pandas.DataFrame
         :type color: str
-        :type norm_factor: float
+        :type nf: float
         :returns: Traces (samples, trending line, anomalies)
         :rtype: list
         """
@@ -120,53 +121,89 @@ def graph_trending(
         if df.empty:
             return list(), list()
 
-        x_axis = df["start_time"].tolist()
-        if ttype == "latency":
-            y_data = [(v / norm_factor) for v in df[C.VALUE[ttype]].tolist()]
-        else:
-            y_data = [(v * norm_factor) for v in df[C.VALUE[ttype]].tolist()]
-        units = df[C.UNIT[ttype]].unique().tolist()
-
-        anomalies, trend_avg, trend_stdev = classify_anomalies(
-            {k: v for k, v in zip(x_axis, y_data)}
-        )
-
         hover = list()
         customdata = list()
         customdata_samples = list()
         name_lst = name.split("-")
-        for idx, (_, row) in enumerate(df.iterrows()):
+        for _, row in df.iterrows():
+            h_tput, h_band, h_lat = str(), str(), str()
+            if ttype in ("mrr", "mrr-bandwidth"):
+                h_tput = (
+                    f"tput avg [{row['result_receive_rate_rate_unit']}]: "
+                    f"{row['result_receive_rate_rate_avg'] * nf:,.0f}<br>"
+                    f"tput stdev [{row['result_receive_rate_rate_unit']}]: "
+                    f"{row['result_receive_rate_rate_stdev'] * nf:,.0f}<br>"
+                )
+                if pd.notna(row["result_receive_rate_bandwidth_avg"]):
+                    h_band = (
+                        f"bandwidth avg "
+                        f"[{row['result_receive_rate_bandwidth_unit']}]: "
+                        f"{row['result_receive_rate_bandwidth_avg'] * nf:,.0f}"
+                        "<br>"
+                        f"bandwidth stdev "
+                        f"[{row['result_receive_rate_bandwidth_unit']}]: "
+                        f"{row['result_receive_rate_bandwidth_stdev']* nf:,.0f}"
+                        "<br>"
+                    )
+            elif ttype in ("ndr", "ndr-bandwidth"):
+                h_tput = (
+                    f"tput [{row['result_ndr_lower_rate_unit']}]: "
+                    f"{row['result_ndr_lower_rate_value'] * nf:,.0f}<br>"
+                )
+                if pd.notna(row["result_ndr_lower_bandwidth_value"]):
+                    h_band = (
+                        f"bandwidth [{row['result_ndr_lower_bandwidth_unit']}]:"
+                        f" {row['result_ndr_lower_bandwidth_value'] * nf:,.0f}"
+                        "<br>"
+                    )
+            elif ttype in ("pdr", "pdr-bandwidth", "latency"):
+                h_tput = (
+                    f"tput [{row['result_pdr_lower_rate_unit']}]: "
+                    f"{row['result_pdr_lower_rate_value'] * nf:,.0f}<br>"
+                )
+                if pd.notna(row["result_pdr_lower_bandwidth_value"]):
+                    h_band = (
+                        f"bandwidth [{row['result_pdr_lower_bandwidth_unit']}]:"
+                        f" {row['result_pdr_lower_bandwidth_value'] * nf:,.0f}"
+                        "<br>"
+                    )
+                if pd.notna(row["result_latency_forward_pdr_50_avg"]):
+                    h_lat = (
+                        f"latency "
+                        f"[{row['result_latency_forward_pdr_50_unit']}]: "
+                        f"{row['result_latency_forward_pdr_50_avg'] / nf:,.0f}"
+                        "<br>"
+                    )
+            elif ttype in ("hoststack-cps", "hoststack-rps",
+                           "hoststack-cps-bandwidth",
+                           "hoststack-rps-bandwidth", "hoststack-latency"):
+                h_tput = (
+                    f"tput [{row['result_rate_unit']}]: "
+                    f"{row['result_rate_value'] * nf:,.0f}<br>"
+                )
+                h_band = (
+                    f"bandwidth [{row['result_bandwidth_unit']}]: "
+                    f"{row['result_bandwidth_value'] * nf:,.0f}<br>"
+                )
+                h_lat = (
+                    f"latency [{row['result_latency_unit']}]: "
+                    f"{row['result_latency_value'] / nf:,.0f}<br>"
+                )
+            elif ttype in ("hoststack-bps", ):
+                h_band = (
+                    f"bandwidth [{row['result_bandwidth_unit']}]: "
+                    f"{row['result_bandwidth_value'] * nf:,.0f}<br>"
+                )
             hover_itm = (
                 f"dut: {name_lst[0]}<br>"
                 f"infra: {'-'.join(name_lst[1:5])}<br>"
                 f"test: {'-'.join(name_lst[5:])}<br>"
                 f"date: {row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
-                f"<prop> [{row[C.UNIT[ttype]]}]: {y_data[idx]:,.0f}<br>"
-                f"<stdev>"
-                f"<additional-info>"
+                f"{h_tput}{h_band}{h_lat}"
                 f"{row['dut_type']}-ref: {row['dut_version']}<br>"
                 f"csit-ref: {row['job']}/{row['build']}<br>"
                 f"hosts: {', '.join(row['hosts'])}"
             )
-            if ttype == "mrr":
-                stdev = (
-                    f"stdev [{row['result_receive_rate_rate_unit']}]: "
-                    f"{row['result_receive_rate_rate_stdev']:,.0f}<br>"
-                )
-            else:
-                stdev = str()
-            if ttype in ("hoststack-cps", "hoststack-rps"):
-                add_info = (
-                    f"bandwidth [{row[C.UNIT['hoststack-bps']]}]: "
-                    f"{row[C.VALUE['hoststack-bps']]:,.0f}<br>"
-                    f"latency [{row[C.UNIT['hoststack-lat']]}]: "
-                    f"{row[C.VALUE['hoststack-lat']]:,.0f}<br>"
-                )
-            else:
-                add_info = str()
-            hover_itm = hover_itm.replace(
-                "<prop>", "latency" if ttype == "latency" else "average"
-            ).replace("<stdev>", stdev).replace("<additional-info>", add_info)
             hover.append(hover_itm)
             if ttype == "latency":
                 customdata_samples.append(get_hdrh_latencies(row, name))
@@ -177,6 +214,21 @@ def graph_trending(
                 )
                 customdata.append({"name": name})
 
+        x_axis = df["start_time"].tolist()
+        if "latency" in ttype:
+            y_data = [(v / nf) for v in df[C.VALUE[ttype]].tolist()]
+        else:
+            y_data = [(v * nf) for v in df[C.VALUE[ttype]].tolist()]
+        units = df[C.UNIT[ttype]].unique().tolist()
+
+        try:
+            anomalies, trend_avg, trend_stdev = classify_anomalies(
+                {k: v for k, v in zip(x_axis, y_data)}
+            )
+        except ValueError as err:
+            logging.error(err)
+            return list(), list()
+
         hover_trend = list()
         for avg, stdev, (_, row) in zip(trend_avg, trend_stdev, df.iterrows()):
             hover_itm = (
@@ -295,6 +347,7 @@ def graph_trending(
 
     fig_tput = None
     fig_lat = None
+    fig_band = None
     y_units = set()
     for idx, itm in enumerate(sel):
         df = select_trending_data(data, itm)
@@ -304,7 +357,7 @@ def graph_trending(
         if normalize:
             phy = itm["phy"].split("-")
             topo_arch = f"{phy[0]}-{phy[1]}" if len(phy) == 4 else str()
-            norm_factor = (C.NORM_FREQUENCY / C.FREQUENCY[topo_arch]) \
+            norm_factor = (C.NORM_FREQUENCY / C.FREQUENCY.get(topo_arch, 1.0)) \
                 if topo_arch else 1.0
         else:
             norm_factor = 1.0
@@ -326,9 +379,22 @@ def graph_trending(
                 fig_tput = go.Figure()
             fig_tput.add_traces(traces)
 
-        if itm["testtype"] == "pdr":
+        if ttype in ("ndr", "pdr", "mrr", "hoststack-cps", "hoststack-rps"):
+            traces, _ = _generate_trending_traces(
+                f"{ttype}-bandwidth",
+                itm["id"],
+                df,
+                get_color(idx),
+                norm_factor
+            )
+            if traces:
+                if not fig_band:
+                    fig_band = go.Figure()
+                fig_band.add_traces(traces)
+
+        if ttype in ("pdr", "hoststack-cps", "hoststack-rps"):
             traces, _ = _generate_trending_traces(
-                "latency",
+                "latency" if ttype == "pdr" else "hoststack-latency",
                 itm["id"],
                 df,
                 get_color(idx),
@@ -346,10 +412,12 @@ def graph_trending(
         fig_layout["yaxis"]["title"] = \
             f"Throughput [{'|'.join(sorted(y_units))}]"
         fig_tput.update_layout(fig_layout)
+    if fig_band:
+        fig_band.update_layout(layout.get("plot-trending-bandwidth", dict()))
     if fig_lat:
         fig_lat.update_layout(layout.get("plot-trending-lat", dict()))
 
-    return fig_tput, fig_lat
+    return fig_tput, fig_band, fig_lat
 
 
 def graph_tm_trending(