CSIT-1041: Trending dashboard
[csit.git] / resources / tools / presentation / utils.py
1 # Copyright (c) 2017 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 """General purpose utilities.
15 """
16
17 import subprocess
18 import numpy as np
19 import pandas as pd
20 import logging
21
22 from os import walk, makedirs, environ
23 from os.path import join, isdir
24 from shutil import copy, Error
25 from math import sqrt
26
27 from errors import PresentationError
28
29
30 def mean(items):
31     """Calculate mean value from the items.
32
33     :param items: Mean value is calculated from these items.
34     :type items: list
35     :returns: MEan value.
36     :rtype: float
37     """
38
39     return float(sum(items)) / len(items)
40
41
42 def stdev(items):
43     """Calculate stdev from the items.
44
45     :param items: Stdev is calculated from these items.
46     :type items: list
47     :returns: Stdev.
48     :rtype: float
49     """
50
51     avg = mean(items)
52     variance = [(x - avg) ** 2 for x in items]
53     stddev = sqrt(mean(variance))
54     return stddev
55
56
57 def relative_change(nr1, nr2):
58     """Compute relative change of two values.
59
60     :param nr1: The first number.
61     :param nr2: The second number.
62     :type nr1: float
63     :type nr2: float
64     :returns: Relative change of nr1.
65     :rtype: float
66     """
67
68     return float(((nr2 - nr1) / nr1) * 100)
69
70
71 def remove_outliers(input_data, outlier_const):
72     """
73
74     :param input_data: Data from which the outliers will be removed.
75     :param outlier_const: Outlier constant.
76     :type input_data: list
77     :type outlier_const: float
78     :returns: The input list without outliers.
79     :rtype: list
80     """
81
82     data = np.array(input_data)
83     upper_quartile = np.percentile(data, 75)
84     lower_quartile = np.percentile(data, 25)
85     iqr = (upper_quartile - lower_quartile) * outlier_const
86     quartile_set = (lower_quartile - iqr, upper_quartile + iqr)
87     result_lst = list()
88     for y in data.tolist():
89         if quartile_set[0] <= y <= quartile_set[1]:
90             result_lst.append(y)
91     return result_lst
92
93
94 def find_outliers(input_data, outlier_const=1.5):
95     """Go through the input data and generate two pandas series:
96     - input data without outliers
97     - outliers.
98     The function uses IQR to detect outliers.
99
100     :param input_data: Data to be examined for outliers.
101     :param outlier_const: Outlier constant.
102     :type input_data: pandas.Series
103     :type outlier_const: float
104     :returns: Tuple: input data with outliers removed; Outliers.
105     :rtype: tuple (trimmed_data, outliers)
106     """
107
108     upper_quartile = input_data.quantile(q=0.75)
109     lower_quartile = input_data.quantile(q=0.25)
110     iqr = (upper_quartile - lower_quartile) * outlier_const
111     low = lower_quartile - iqr
112     high = upper_quartile + iqr
113     trimmed_data = pd.Series()
114     outliers = pd.Series()
115     for item in input_data.items():
116         item_pd = pd.Series([item[1], ], index=[item[0], ])
117         if low <= item[1] <= high:
118             trimmed_data = trimmed_data.append(item_pd)
119         else:
120             trimmed_data = trimmed_data.append(pd.Series([np.nan, ],
121                                                          index=[item[0], ]))
122             outliers = outliers.append(item_pd)
123
124     return trimmed_data, outliers
125
126
127 def get_files(path, extension=None, full_path=True):
128     """Generates the list of files to process.
129
130     :param path: Path to files.
131     :param extension: Extension of files to process. If it is the empty string,
132     all files will be processed.
133     :param full_path: If True, the files with full path are generated.
134     :type path: str
135     :type extension: str
136     :type full_path: bool
137     :returns: List of files to process.
138     :rtype: list
139     """
140
141     file_list = list()
142     for root, _, files in walk(path):
143         for filename in files:
144             if extension:
145                 if filename.endswith(extension):
146                     if full_path:
147                         file_list.append(join(root, filename))
148                     else:
149                         file_list.append(filename)
150             else:
151                 file_list.append(join(root, filename))
152
153     return file_list
154
155
156 def get_rst_title_char(level):
157     """Return character used for the given title level in rst files.
158
159     :param level: Level of the title.
160     :type: int
161     :returns: Character used for the given title level in rst files.
162     :rtype: str
163     """
164     chars = ('=', '-', '`', "'", '.', '~', '*', '+', '^')
165     if level < len(chars):
166         return chars[level]
167     else:
168         return chars[-1]
169
170
171 def execute_command(cmd):
172     """Execute the command in a subprocess and log the stdout and stderr.
173
174     :param cmd: Command to execute.
175     :type cmd: str
176     :returns: Return code of the executed command.
177     :rtype: int
178     """
179
180     env = environ.copy()
181     proc = subprocess.Popen(
182         [cmd],
183         stdout=subprocess.PIPE,
184         stderr=subprocess.PIPE,
185         shell=True,
186         env=env)
187
188     stdout, stderr = proc.communicate()
189
190     logging.debug(stdout)
191     logging.debug(stderr)
192
193     if proc.returncode != 0:
194         logging.error("    Command execution failed.")
195     return proc.returncode, stdout, stderr
196
197
198 def get_last_successful_build_number(jenkins_url, job_name):
199     """Get the number of the last successful build of the given job.
200
201     :param jenkins_url: Jenkins URL.
202     :param job_name: Job name.
203     :type jenkins_url: str
204     :type job_name: str
205     :returns: The build number as a string.
206     :rtype: str
207     """
208
209     url = "{}/{}/lastSuccessfulBuild/buildNumber".format(jenkins_url, job_name)
210     cmd = "wget -qO- {url}".format(url=url)
211
212     return execute_command(cmd)
213
214
215 def get_last_completed_build_number(jenkins_url, job_name):
216     """Get the number of the last completed build of the given job.
217
218     :param jenkins_url: Jenkins URL.
219     :param job_name: Job name.
220     :type jenkins_url: str
221     :type job_name: str
222     :returns: The build number as a string.
223     :rtype: str
224     """
225
226     url = "{}/{}/lastCompletedBuild/buildNumber".format(jenkins_url, job_name)
227     cmd = "wget -qO- {url}".format(url=url)
228
229     return execute_command(cmd)
230
231
232 def archive_input_data(spec):
233     """Archive the report.
234
235     :param spec: Specification read from the specification file.
236     :type spec: Specification
237     :raises PresentationError: If it is not possible to archive the input data.
238     """
239
240     logging.info("    Archiving the input data files ...")
241
242     if spec.is_debug:
243         extension = spec.debug["input-format"]
244     else:
245         extension = spec.input["file-format"]
246     data_files = get_files(spec.environment["paths"]["DIR[WORKING,DATA]"],
247                            extension=extension)
248     dst = spec.environment["paths"]["DIR[STATIC,ARCH]"]
249     logging.info("      Destination: {0}".format(dst))
250
251     try:
252         if not isdir(dst):
253             makedirs(dst)
254
255         for data_file in data_files:
256             logging.info("      Copying the file: {0} ...".format(data_file))
257             copy(data_file, dst)
258
259     except (Error, OSError) as err:
260         raise PresentationError("Not possible to archive the input data.",
261                                 str(err))
262
263     logging.info("    Done.")