feat(uti): Move directory
[csit.git] / csit.infra.dash / app / pal / stats / graphs.py
1 # Copyright (c) 2022 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:
5 #
6 #     http://www.apache.org/licenses/LICENSE-2.0
7 #
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.
13
14 """
15 """
16
17 import plotly.graph_objects as go
18 import pandas as pd
19
20
21 def select_data(data: pd.DataFrame, itm:str) -> pd.DataFrame:
22     """Select the data for graphs from the provided data frame.
23
24     :param data: Data frame with data for graphs.
25     :param itm: Item (in this case job name) which data will be selected from
26         the input data frame.
27     :type data: pandas.DataFrame
28     :type itm: str
29     :returns: A data frame with selected data.
30     :rtype: pandas.DataFrame
31     """
32
33     df = data.loc[(data["job"] == itm)].sort_values(
34         by="start_time", ignore_index=True)
35     df = df.dropna(subset=["duration", ])
36
37     return df
38
39
40 def graph_statistics(df: pd.DataFrame, job:str, layout: dict) -> tuple:
41     """Generate graphs:
42     1. Passed / failed tests,
43     2. Job durations
44     with additional information shown in hover.
45
46     :param df: Data frame with input data.
47     :param job: The name of job which data will be presented in the graphs.
48     :param layout: Layout of plot.ly graph.
49     :type df: pandas.DataFrame
50     :type job: str
51     :type layout: dict
52     :returns: Tuple with two generated graphs (pased/failed tests and job
53         duration).
54     :rtype: tuple(plotly.graph_objects.Figure, plotly.graph_objects.Figure)
55     """
56
57     data = select_data(df, job)
58     if data.empty:
59         return None, None
60
61     hover = list()
62     for _, row in data.iterrows():
63         d_type = "trex" if row["dut_type"] == "none" else row["dut_type"]
64         hover_itm = (
65             f"date: {row['start_time'].strftime('%Y-%m-%d %H:%M:%S')}<br>"
66             f"duration: "
67             f"{(int(row['duration']) // 3600):02d}:"
68             f"{((int(row['duration']) % 3600) // 60):02d}<br>"
69             f"passed: {row['passed']}<br>"
70             f"failed: {row['failed']}<br>"
71             f"{d_type}-ref: {row['dut_version']}<br>"
72             f"csit-ref: {row['job']}/{row['build']}<br>"
73             f"hosts: {', '.join(row['hosts'])}"
74         )
75         hover.append(hover_itm)
76
77     # Job durations:
78     fig_duration = go.Figure(
79         data=go.Scatter(
80             x=data["start_time"],
81             y=data["duration"],
82             name=u"Duration",
83             text=hover,
84             hoverinfo=u"text"
85         )
86     )
87
88     tickvals = [0, ]
89     step = max(data["duration"]) / 5
90     for i in range(5):
91         tickvals.append(int(step * (i + 1)))
92     layout_duration = layout.get("plot-stats-duration", dict())
93     if layout_duration:
94         layout_duration["yaxis"]["tickvals"] = tickvals
95         layout_duration["yaxis"]["ticktext"] = [
96             f"{(val // 3600):02d}:{((val % 3600) // 60):02d}" \
97                 for val in tickvals
98         ]
99         fig_duration.update_layout(layout_duration)
100
101     # Passed / failed:
102     fig_passed = go.Figure(
103         data=[
104             go.Bar(
105                 x=data["start_time"],
106                 y=data["passed"],
107                 name=u"Passed",
108                 hovertext=hover,
109                 hoverinfo=u"text"
110             ),
111             go.Bar(
112                 x=data["start_time"],
113                 y=data["failed"],
114                 name=u"Failed",
115                 hovertext=hover,
116                 hoverinfo=u"text"
117             )
118         ]
119     )
120     layout_pf = layout.get("plot-stats-passed", dict())
121     if layout_pf:
122         fig_passed.update_layout(layout_pf)
123
124     return fig_passed, fig_duration