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:
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 """Algorithms to generate tables.
19 from string import replace
21 from errors import PresentationError
22 from utils import mean, stdev, relative_change
25 def generate_tables(spec, data):
26 """Generate all tables specified in the specification file.
28 :param spec: Specification read from the specification file.
29 :param data: Data to process.
30 :type spec: Specification
34 logging.info("Generating the tables ...")
35 for table in spec.tables:
37 eval(table["algorithm"])(table, data)
39 logging.error("The algorithm '{0}' is not defined.".
40 format(table["algorithm"]))
44 def table_details(table, input_data):
45 """Generate the table(s) with algorithm: table_detailed_test_results
46 specified in the specification file.
48 :param table: Table to generate.
49 :param input_data: Data to process.
50 :type table: pandas.Series
51 :type input_data: InputData
54 logging.info(" Generating the table {0} ...".
55 format(table.get("title", "")))
58 data = input_data.filter_data(table)
60 # Prepare the header of the tables
62 for column in table["columns"]:
63 header.append('"{0}"'.format(str(column["title"]).replace('"', '""')))
65 # Generate the data for the table according to the model in the table
68 job = table["data"].keys()[0]
69 build = str(table["data"][job][0])
70 for suite_longname, suite in input_data.suites(job, build).iteritems():
72 suite_name = suite["name"]
74 for test in data[job][build].keys():
75 if data[job][build][test]["parent"] in suite_name:
77 for column in table["columns"]:
79 col_data = str(data[job][build][test][column["data"].
80 split(" ")[1]]).replace('"', '""')
81 if column["data"].split(" ")[1] in ("vat-history",
83 col_data = replace(col_data, " |br| ", "",
85 col_data = " |prein| {0} |preout| ".\
87 row_lst.append('"{0}"'.format(col_data))
89 row_lst.append("No data")
90 table_lst.append(row_lst)
92 # Write the data to file
94 file_name = "{0}_{1}{2}".format(table["output-file"], suite_name,
95 table["output-file-ext"])
96 logging.info(" Writing file: '{}'".format(file_name))
97 with open(file_name, "w") as file_handler:
98 file_handler.write(",".join(header) + "\n")
99 for item in table_lst:
100 file_handler.write(",".join(item) + "\n")
102 logging.info(" Done.")
105 def table_performance_improvements(table, input_data):
106 """Generate the table(s) with algorithm: table_performance_improvements
107 specified in the specification file.
109 :param table: Table to generate.
110 :param input_data: Data to process.
111 :type table: pandas.Series
112 :type input_data: InputData
115 def _write_line_to_file(file_handler, data):
116 """Write a line to the .csv file.
118 :param file_handler: File handler for the csv file. It must be open for
120 :param data: Item to be written to the file.
121 :type file_handler: BinaryIO
127 if isinstance(item["data"], str):
128 line_lst.append(item["data"])
129 elif isinstance(item["data"], float):
130 line_lst.append("{:.1f}".format(item["data"]))
131 file_handler.write(",".join(line_lst) + "\n")
133 logging.info(" Generating the table {0} ...".
134 format(table.get("title", "")))
137 file_name = table.get("template", None)
140 tmpl = _read_csv_template(file_name)
141 except PresentationError:
142 logging.error(" The template '{0}' does not exist. Skipping the "
143 "table.".format(file_name))
146 logging.error("The template is not defined. Skipping the table.")
150 data = input_data.filter_data(table)
152 # Prepare the header of the tables
154 for column in table["columns"]:
155 header.append(column["title"])
157 # Generate the data for the table according to the model in the table
160 for tmpl_item in tmpl:
162 for column in table["columns"]:
163 cmd = column["data"].split(" ")[0]
164 args = column["data"].split(" ")[1:]
165 if cmd == "template":
167 val = float(tmpl_item[int(args[0])])
169 val = tmpl_item[int(args[0])]
170 tbl_item.append({"data": val})
175 for build in data[job]:
177 data_lst.append(float(build[tmpl_item[0]]["throughput"]
178 ["value"]) / 1000000)
179 except (KeyError, TypeError):
183 tbl_item.append({"data": eval(operation)(data_lst)})
184 elif cmd == "operation":
186 nr1 = tbl_item[int(args[1])]["data"]
187 nr2 = tbl_item[int(args[2])]["data"]
189 tbl_item.append({"data": eval(operation)(nr1, nr2)})
191 tbl_item.append({"data": None})
193 logging.error("Not supported command {0}. Skipping the table.".
196 tbl_lst.append(tbl_item)
198 # Sort the table according to the relative change
199 tbl_lst.sort(key=lambda rel: rel[-1]["data"], reverse=True)
201 # Create the tables and write them to the files
203 "{0}_ndr_top{1}".format(table["output-file"], table["output-file-ext"]),
204 "{0}_pdr_top{1}".format(table["output-file"], table["output-file-ext"]),
205 "{0}_ndr_low{1}".format(table["output-file"], table["output-file-ext"]),
206 "{0}_pdr_low{1}".format(table["output-file"], table["output-file-ext"])
209 for file_name in file_names:
210 logging.info(" Writing the file '{0}'".format(file_name))
211 with open(file_name, "w") as file_handler:
212 file_handler.write(",".join(header) + "\n")
214 if "ndr_top" in file_name \
215 and "ndr" in item[1]["data"] \
216 and item[-1]["data"] >= 10:
217 _write_line_to_file(file_handler, item)
218 elif "pdr_top" in file_name \
219 and "pdr" in item[1]["data"] \
220 and item[-1]["data"] >= 10:
221 _write_line_to_file(file_handler, item)
222 elif "ndr_low" in file_name \
223 and "ndr" in item[1]["data"] \
224 and item[-1]["data"] < 10:
225 _write_line_to_file(file_handler, item)
226 elif "pdr_low" in file_name \
227 and "pdr" in item[1]["data"] \
228 and item[-1]["data"] < 10:
229 _write_line_to_file(file_handler, item)
231 logging.info(" Done.")
234 def _read_csv_template(file_name):
235 """Read the template from a .csv file.
237 :param file_name: Name / full path / relative path of the file to read.
239 :returns: Data from the template as list (lines) of lists (items on line).
241 :raises: PresentationError if it is not possible to read the file.
245 with open(file_name, 'r') as csv_file:
247 for line in csv_file:
248 tmpl_data.append(line[:-1].split(","))
250 except IOError as err:
251 raise PresentationError(str(err), level="ERROR")