154b6e9b2306e3336fca6976e06ed28bc6bcc13b
[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 find_outliers(input_data, outlier_const=1.5):
72     """Go through the input data and generate two pandas series:
73     - input data without outliers
74     - outliers.
75     The function uses IQR to detect outliers.
76
77     :param input_data: Data to be examined for outliers.
78     :param outlier_const: Outlier constant.
79     :type input_data: pandas.Series
80     :type outlier_const: float
81     :returns: Tuple: input data with outliers removed; Outliers.
82     :rtype: tuple (trimmed_data, outliers)
83     """
84
85     upper_quartile = input_data.quantile(q=0.75)
86     lower_quartile = input_data.quantile(q=0.25)
87     iqr = (upper_quartile - lower_quartile) * outlier_const
88     low = lower_quartile - iqr
89     high = upper_quartile + iqr
90     trimmed_data = pd.Series()
91     outliers = pd.Series()
92     for item in input_data.items():
93         item_pd = pd.Series([item[1], ], index=[item[0], ])
94         if low <= item[1] <= high:
95             trimmed_data = trimmed_data.append(item_pd)
96         else:
97             trimmed_data = trimmed_data.append(pd.Series([np.nan, ],
98                                                          index=[item[0], ]))
99             outliers = outliers.append(item_pd)
100
101     return trimmed_data, outliers
102
103
104 def get_files(path, extension=None, full_path=True):
105     """Generates the list of files to process.
106
107     :param path: Path to files.
108     :param extension: Extension of files to process. If it is the empty string,
109     all files will be processed.
110     :param full_path: If True, the files with full path are generated.
111     :type path: str
112     :type extension: str
113     :type full_path: bool
114     :returns: List of files to process.
115     :rtype: list
116     """
117
118     file_list = list()
119     for root, _, files in walk(path):
120         for filename in files:
121             if extension:
122                 if filename.endswith(extension):
123                     if full_path:
124                         file_list.append(join(root, filename))
125                     else:
126                         file_list.append(filename)
127             else:
128                 file_list.append(join(root, filename))
129
130     return file_list
131
132
133 def get_rst_title_char(level):
134     """Return character used for the given title level in rst files.
135
136     :param level: Level of the title.
137     :type: int
138     :returns: Character used for the given title level in rst files.
139     :rtype: str
140     """
141     chars = ('=', '-', '`', "'", '.', '~', '*', '+', '^')
142     if level < len(chars):
143         return chars[level]
144     else:
145         return chars[-1]
146
147
148 def execute_command(cmd):
149     """Execute the command in a subprocess and log the stdout and stderr.
150
151     :param cmd: Command to execute.
152     :type cmd: str
153     :returns: Return code of the executed command.
154     :rtype: int
155     """
156
157     env = environ.copy()
158     proc = subprocess.Popen(
159         [cmd],
160         stdout=subprocess.PIPE,
161         stderr=subprocess.PIPE,
162         shell=True,
163         env=env)
164
165     stdout, stderr = proc.communicate()
166
167     logging.info(stdout)
168     logging.info(stderr)
169
170     if proc.returncode != 0:
171         logging.error("    Command execution failed.")
172     return proc.returncode, stdout, stderr
173
174
175 def get_last_successful_build_number(jenkins_url, job_name):
176     """Get the number of the last successful build of the given job.
177
178     :param jenkins_url: Jenkins URL.
179     :param job_name: Job name.
180     :type jenkins_url: str
181     :type job_name: str
182     :returns: The build number as a string.
183     :rtype: str
184     """
185
186     url = "{}/{}/lastSuccessfulBuild/buildNumber".format(jenkins_url, job_name)
187     cmd = "wget -qO- {url}".format(url=url)
188
189     return execute_command(cmd)
190
191
192 def get_last_completed_build_number(jenkins_url, job_name):
193     """Get the number of the last completed build of the given job.
194
195     :param jenkins_url: Jenkins URL.
196     :param job_name: Job name.
197     :type jenkins_url: str
198     :type job_name: str
199     :returns: The build number as a string.
200     :rtype: str
201     """
202
203     url = "{}/{}/lastCompletedBuild/buildNumber".format(jenkins_url, job_name)
204     cmd = "wget -qO- {url}".format(url=url)
205
206     return execute_command(cmd)
207
208
209 def archive_input_data(spec):
210     """Archive the report.
211
212     :param spec: Specification read from the specification file.
213     :type spec: Specification
214     :raises PresentationError: If it is not possible to archive the input data.
215     """
216
217     logging.info("    Archiving the input data files ...")
218
219     if spec.is_debug:
220         extension = spec.debug["input-format"]
221     else:
222         extension = spec.input["file-format"]
223     data_files = get_files(spec.environment["paths"]["DIR[WORKING,DATA]"],
224                            extension=extension)
225     dst = spec.environment["paths"]["DIR[STATIC,ARCH]"]
226     logging.info("      Destination: {0}".format(dst))
227
228     try:
229         if not isdir(dst):
230             makedirs(dst)
231
232         for data_file in data_files:
233             logging.info("      Copying the file: {0} ...".format(data_file))
234             copy(data_file, dst)
235
236     except (Error, OSError) as err:
237         raise PresentationError("Not possible to archive the input data.",
238                                 str(err))
239
240     logging.info("    Done.")