1 # Copyright (c) 2018 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 """Generation of Continuous Performance Trending and Analysis.
19 import plotly.offline as ploff
20 import plotly.graph_objs as plgo
24 from collections import OrderedDict
25 from utils import find_outliers, archive_input_data, execute_command
28 # Command to build the html format of the report
29 HTML_BUILDER = 'sphinx-build -v -c conf_cpta -a ' \
35 # .css file for the html format of the report
36 THEME_OVERRIDES = """/* override table width restrictions */
38 max-width: 1200px !important;
42 COLORS = ["SkyBlue", "Olive", "Purple", "Coral", "Indigo", "Pink",
43 "Chocolate", "Brown", "Magenta", "Cyan", "Orange", "Black",
44 "Violet", "Blue", "Yellow"]
47 def generate_cpta(spec, data):
48 """Generate all formats and versions of the Continuous Performance Trending
51 :param spec: Specification read from the specification file.
52 :param data: Full data set.
53 :type spec: Specification
57 logging.info("Generating the Continuous Performance Trending and Analysis "
60 ret_code = _generate_all_charts(spec, data)
62 cmd = HTML_BUILDER.format(
63 date=datetime.date.today().strftime('%d-%b-%Y'),
64 working_dir=spec.environment["paths"]["DIR[WORKING,SRC]"],
65 build_dir=spec.environment["paths"]["DIR[BUILD,HTML]"])
68 with open(spec.environment["paths"]["DIR[CSS_PATCH_FILE]"], "w") as \
70 css_file.write(THEME_OVERRIDES)
72 with open(spec.environment["paths"]["DIR[CSS_PATCH_FILE2]"], "w") as \
74 css_file.write(THEME_OVERRIDES)
76 archive_input_data(spec)
83 def _select_data(in_data, period, fill_missing=False, use_first=False):
84 """Select the data from the full data set. The selection is done by picking
85 the samples depending on the period: period = 1: All, period = 2: every
86 second sample, period = 3: every third sample ...
88 :param in_data: Full set of data.
89 :param period: Sampling period.
90 :param fill_missing: If the chosen sample is missing in the full set, its
91 nearest neighbour is used.
92 :param use_first: Use the first sample even though it is not chosen.
93 :type in_data: OrderedDict
95 :type fill_missing: bool
97 :returns: Reduced data.
101 first_idx = min(in_data.keys())
102 last_idx = max(in_data.keys())
107 data_dict[first_idx] = in_data[first_idx]
108 while idx >= first_idx:
109 data = in_data.get(idx, None)
112 threshold = int(round(idx - period / 2)) + 1 - period % 2
113 idx_low = first_idx if threshold < first_idx else threshold
114 threshold = int(round(idx + period / 2))
115 idx_high = last_idx if threshold > last_idx else threshold
121 while flag_l or flag_h:
122 if idx + inc > idx_high:
125 idx_lst.append(idx + inc)
126 if idx - inc < idx_low:
129 idx_lst.append(idx - inc)
133 if i in in_data.keys():
134 data_dict[i] = in_data[i]
137 data_dict[idx] = data
140 return OrderedDict(sorted(data_dict.items(), key=lambda t: t[0]))
143 def _evaluate_results(in_data, trimmed_data, window=10):
144 """Evaluates if the sample value is regress, normal or progress compared to
145 previous data within the window.
146 We use the intervals defined as:
147 - regress: less than median - 3 * stdev
148 - normal: between median - 3 * stdev and median + 3 * stdev
149 - progress: more than median + 3 * stdev
151 :param in_data: Full data set.
152 :param trimmed_data: Full data set without the outliers.
153 :param window: Window size used to calculate moving median and moving stdev.
154 :type in_data: pandas.Series
155 :type trimmed_data: pandas.Series
157 :returns: Evaluated results.
162 win_size = in_data.size if in_data.size < window else window
163 results = [0.0, ] * win_size
164 median = in_data.rolling(window=win_size).median()
165 stdev_t = trimmed_data.rolling(window=win_size, min_periods=2).std()
166 m_vals = median.values
167 s_vals = stdev_t.values
168 d_vals = in_data.values
169 for day in range(win_size, in_data.size):
170 if np.isnan(m_vals[day - 1]) or np.isnan(s_vals[day - 1]):
172 elif d_vals[day] < (m_vals[day - 1] - 3 * s_vals[day - 1]):
174 elif (m_vals[day - 1] - 3 * s_vals[day - 1]) <= d_vals[day] <= \
175 (m_vals[day - 1] + 3 * s_vals[day - 1]):
182 median = np.median(in_data)
183 stdev = np.std(in_data)
184 if in_data.values[-1] < (median - 3 * stdev):
186 elif (median - 3 * stdev) <= in_data.values[-1] <= (
196 def _generate_trending_traces(in_data, period, moving_win_size=10,
197 fill_missing=True, use_first=False,
198 show_moving_median=True, name="", color=""):
199 """Generate the trending traces:
201 - moving median (trending plot)
202 - outliers, regress, progress
204 :param in_data: Full data set.
205 :param period: Sampling period.
206 :param moving_win_size: Window size.
207 :param fill_missing: If the chosen sample is missing in the full set, its
208 nearest neighbour is used.
209 :param use_first: Use the first sample even though it is not chosen.
210 :param show_moving_median: Show moving median (trending plot).
211 :param name: Name of the plot
212 :param color: Name of the color for the plot.
213 :type in_data: OrderedDict
215 :type moving_win_size: int
216 :type fill_missing: bool
217 :type use_first: bool
218 :type show_moving_median: bool
221 :returns: Generated traces (list) and the evaluated result (float).
222 :rtype: tuple(traces, result)
226 in_data = _select_data(in_data, period,
227 fill_missing=fill_missing,
230 data_x = [key for key in in_data.keys()]
231 data_y = [val for val in in_data.values()]
232 data_pd = pd.Series(data_y, index=data_x)
234 t_data, outliers = find_outliers(data_pd)
236 results = _evaluate_results(data_pd, t_data, window=moving_win_size)
238 anomalies = pd.Series()
239 anomalies_res = list()
240 for idx, item in enumerate(in_data.items()):
241 item_pd = pd.Series([item[1], ], index=[item[0], ])
242 if item[0] in outliers.keys():
243 anomalies = anomalies.append(item_pd)
244 anomalies_res.append(0.0)
245 elif results[idx] in (0.33, 1.0):
246 anomalies = anomalies.append(item_pd)
247 anomalies_res.append(results[idx])
248 anomalies_res.extend([0.0, 0.33, 0.66, 1.0])
251 color_scale = [[0.00, "grey"],
260 trace_samples = plgo.Scatter(
267 name="{name}-thput".format(name=name),
274 traces = [trace_samples, ]
276 trace_anomalies = plgo.Scatter(
283 name="{name}: outliers".format(name=name),
286 "symbol": "circle-open",
287 "color": anomalies_res,
288 "colorscale": color_scale,
294 "title": "Results Clasification",
295 "titleside": 'right',
300 "tickvals": [0.125, 0.375, 0.625, 0.875],
301 "ticktext": ["Outlier", "Regress", "Normal", "Progress"],
309 traces.append(trace_anomalies)
311 if show_moving_median:
312 data_mean_y = pd.Series(data_y).rolling(
313 window=moving_win_size).median()
314 trace_median = plgo.Scatter(
323 name='{name}-trend'.format(name=name, size=moving_win_size)
325 traces.append(trace_median)
327 return traces, results[-1]
330 def _generate_chart(traces, layout, file_name):
331 """Generates the whole chart using pre-generated traces.
333 :param traces: Traces for the chart.
334 :param layout: Layout of the chart.
335 :param file_name: File name for the generated chart.
342 logging.info(" Writing the file '{0}' ...".format(file_name))
343 plpl = plgo.Figure(data=traces, layout=layout)
344 ploff.plot(plpl, show_link=False, auto_open=False, filename=file_name)
347 def _generate_all_charts(spec, input_data):
348 """Generate all charts specified in the specification file.
350 :param spec: Specification.
351 :param input_data: Full data set.
352 :type spec: Specification
353 :type input_data: InputData
357 for chart in spec.cpta["plots"]:
358 logging.info(" Generating the chart '{0}' ...".
359 format(chart.get("title", "")))
362 data = input_data.filter_data(chart, continue_on_error=True)
364 logging.error("No data.")
369 for idx, build in job.items():
371 if chart_data.get(test["name"], None) is None:
372 chart_data[test["name"]] = OrderedDict()
374 chart_data[test["name"]][int(idx)] = \
375 test["result"]["throughput"]
376 except (KeyError, TypeError):
377 chart_data[test["name"]][int(idx)] = None
379 for period in chart["periods"]:
382 win_size = 10 if period == 1 else 5 if period < 20 else 3
384 for test_name, test_data in chart_data.items():
386 logging.warning("No data for the test '{0}'".
389 trace, result = _generate_trending_traces(
392 moving_win_size=win_size,
395 name='-'.join(test_name.split('-')[3:-1]),
398 results.append(result)
401 # Generate the chart:
402 period_name = "Daily" if period == 1 else \
403 "Weekly" if period < 20 else "Monthly"
404 chart["layout"]["title"] = chart["title"].format(period=period_name)
405 _generate_chart(traces,
407 file_name="{0}-{1}-{2}{3}".format(
408 spec.cpta["output-file"],
409 chart["output-file-name"],
411 spec.cpta["output-file-type"]))
413 logging.info(" Done.")
420 if item == 0.66 and result == "PASS":
422 elif item == 0.33 or item == 0.0: