testitpy 0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- testit/__init__.py +0 -0
- testit/main.py +56 -0
- testit/run.py +244 -0
- testit/run_util.py +99 -0
- testit/templates/config.test +148 -0
- testit/templates/testit_golden.py +18 -0
- testit/testit.py +411 -0
- testit/testit_util.py +203 -0
- testitpy-0.1.dist-info/LICENSE +674 -0
- testitpy-0.1.dist-info/METADATA +698 -0
- testitpy-0.1.dist-info/RECORD +14 -0
- testitpy-0.1.dist-info/WHEEL +5 -0
- testitpy-0.1.dist-info/entry_points.txt +2 -0
- testitpy-0.1.dist-info/top_level.txt +1 -0
testit/testit.py
ADDED
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
import subprocess
|
|
2
|
+
import re
|
|
3
|
+
import serial
|
|
4
|
+
import pexpect
|
|
5
|
+
import threading
|
|
6
|
+
import queue
|
|
7
|
+
import random
|
|
8
|
+
import os
|
|
9
|
+
import numpy as np
|
|
10
|
+
from . import testit_util
|
|
11
|
+
from rich.console import Console
|
|
12
|
+
from rich.table import Table
|
|
13
|
+
import json
|
|
14
|
+
import copy
|
|
15
|
+
|
|
16
|
+
# Set this to True to enable debugging prints
|
|
17
|
+
# TODO: REMOVE BEFORE RELEASE
|
|
18
|
+
DEBUG_MODE = False
|
|
19
|
+
|
|
20
|
+
# TODO: REMOVE BEFORE RELEASE
|
|
21
|
+
def PRINT_DEB(*args, **kwargs):
|
|
22
|
+
if DEBUG_MODE:
|
|
23
|
+
print(*args, **kwargs)
|
|
24
|
+
|
|
25
|
+
# This class defines the environment for the verification campaign
|
|
26
|
+
class TestItEnv:
|
|
27
|
+
def __init__(self, config):
|
|
28
|
+
self.cfg = config
|
|
29
|
+
|
|
30
|
+
def reset_all(self):
|
|
31
|
+
if self.serial_comm_instance.is_open:
|
|
32
|
+
self.serial_comm_instance.close()
|
|
33
|
+
self.serial_comm_instance = None
|
|
34
|
+
self.serial_comm_queue = None
|
|
35
|
+
self.serial_comm_thread = None
|
|
36
|
+
self.gdb = None
|
|
37
|
+
self.project_root = None
|
|
38
|
+
|
|
39
|
+
def clear_results(self):
|
|
40
|
+
testit_util._clear_database(self.cfg['report']['dir'])
|
|
41
|
+
|
|
42
|
+
# Build the model for the simulation tool or the FPGA board
|
|
43
|
+
def build_model(self):
|
|
44
|
+
if self.cfg['target']['type'] == "fpga":
|
|
45
|
+
cmd = f"make fpga-build board={self.cfg['target']['name']}"
|
|
46
|
+
build_result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
|
|
47
|
+
if ("ERROR" in build_result.stdout) or ("Error" in build_result.stdout):
|
|
48
|
+
print(build_result.stdout)
|
|
49
|
+
return False
|
|
50
|
+
else:
|
|
51
|
+
return True
|
|
52
|
+
else:
|
|
53
|
+
cmd = f"make sim-build tool={self.cfg['target']['name']}"
|
|
54
|
+
build_result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
|
|
55
|
+
if ("ERROR" in build_result.stdout) or ("Error" in build_result.stdout):
|
|
56
|
+
print(build_result.stdout)
|
|
57
|
+
return False
|
|
58
|
+
else:
|
|
59
|
+
return True
|
|
60
|
+
|
|
61
|
+
# Load the bitstream into the FPGA board
|
|
62
|
+
def load_fpga_model(self):
|
|
63
|
+
cmd = f"make fpga-load board={self.cfg['target']['name']}"
|
|
64
|
+
load_result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
|
|
65
|
+
if ("ERROR" in load_result.stdout) or ("Error" in load_result.stdout):
|
|
66
|
+
print(load_result.stdout)
|
|
67
|
+
return False
|
|
68
|
+
else:
|
|
69
|
+
return True
|
|
70
|
+
|
|
71
|
+
# Set-up serial communication with the FPGA board
|
|
72
|
+
def serial_begin(self):
|
|
73
|
+
try:
|
|
74
|
+
self.serial_comm_instance = serial.Serial(f"/dev/ttyUSB{self.cfg['target']['usbPort']}", self.cfg['target']['baudrate'], timeout=1)
|
|
75
|
+
|
|
76
|
+
if not self.serial_comm_instance.is_open:
|
|
77
|
+
return False
|
|
78
|
+
except Exception as e:
|
|
79
|
+
return False
|
|
80
|
+
|
|
81
|
+
self.serial_comm_queue = queue.Queue()
|
|
82
|
+
|
|
83
|
+
return True
|
|
84
|
+
|
|
85
|
+
def setup_deb(self):
|
|
86
|
+
testit_util._run_command_threading(f"make deb-setup")
|
|
87
|
+
|
|
88
|
+
# Set-up GDB
|
|
89
|
+
def setup_gdb(self):
|
|
90
|
+
gdb_cmd = f"""
|
|
91
|
+
cd {os.getcwd()}
|
|
92
|
+
make gdb-setup
|
|
93
|
+
"""
|
|
94
|
+
self.gdb = pexpect.spawn(f"/bin/bash -c '{gdb_cmd}'")
|
|
95
|
+
self.gdb.sendline("set pagination off")
|
|
96
|
+
self.gdb.sendline("set confirm off")
|
|
97
|
+
self.gdb.expect('(gdb)')
|
|
98
|
+
self.gdb.sendline('set remotetimeout 2000')
|
|
99
|
+
self.gdb.expect('(gdb)')
|
|
100
|
+
self.gdb.sendline('target extended-remote localhost:3333')
|
|
101
|
+
self.gdb.expect('(gdb)')
|
|
102
|
+
|
|
103
|
+
if self.gdb.isalive():
|
|
104
|
+
PRINT_DEB("GDB process is still running.")
|
|
105
|
+
return True
|
|
106
|
+
else:
|
|
107
|
+
PRINT_DEB("GDB process has terminated.")
|
|
108
|
+
if self.gdb.exitstatus is not None:
|
|
109
|
+
print(f"GDB exit status: {self.gdb.exitstatus}")
|
|
110
|
+
if self.gdb.signalstatus is not None:
|
|
111
|
+
print(f"GDB terminated by signal: {self.gdb.signalstatus}")
|
|
112
|
+
exit(1)
|
|
113
|
+
|
|
114
|
+
# Stop GDB
|
|
115
|
+
def stop_deb(self):
|
|
116
|
+
self.gdb.sendcontrol('c')
|
|
117
|
+
self.gdb.terminate()
|
|
118
|
+
|
|
119
|
+
# Launch a test by compiling the target application and loading it into the FPGA flash via GDB
|
|
120
|
+
def launch_test(self, app_name, iteration, pattern=r'(\d+):(\d+):(\d+)', output_tags=None, timeout_t=0):
|
|
121
|
+
|
|
122
|
+
if output_tags is None:
|
|
123
|
+
output_tags = ["ID", "Cycles", "Outcome"]
|
|
124
|
+
|
|
125
|
+
# Test using the FPGA board
|
|
126
|
+
if self.cfg['target']['type'] == "fpga":
|
|
127
|
+
# Check that the serial connection is still open
|
|
128
|
+
if not self.serial_comm_instance.is_open:
|
|
129
|
+
print("ERROR: Serial port is not open!")
|
|
130
|
+
exit(1)
|
|
131
|
+
self.serial_comm_thread = threading.Thread(target=testit_util._serial_rx_setup, args=(self.serial_comm_instance, self.serial_comm_queue))
|
|
132
|
+
|
|
133
|
+
self.serial_comm_thread.start()
|
|
134
|
+
|
|
135
|
+
# Compile the application
|
|
136
|
+
app_compile_cmd = f"make sw-fpga app={app_name} target={self.cfg['target']['name']}"
|
|
137
|
+
result_compilation = subprocess.run(app_compile_cmd, shell=True, capture_output=True, text=True)
|
|
138
|
+
|
|
139
|
+
if ("ERROR" in result_compilation.stdout) or ("Error" in result_compilation.stdout) or ("error" in result_compilation.stdout) or \
|
|
140
|
+
("ERROR" in result_compilation.stderr) or ("Error" in result_compilation.stderr) or ("error" in result_compilation.stderr):
|
|
141
|
+
with open("testit_crash.log", "w") as file:
|
|
142
|
+
file.write(result_compilation.stdout)
|
|
143
|
+
file.write(result_compilation.stderr)
|
|
144
|
+
return False
|
|
145
|
+
else:
|
|
146
|
+
PRINT_DEB("Compilation successful!")
|
|
147
|
+
|
|
148
|
+
# Run the testbench with gdb
|
|
149
|
+
self.gdb.sendline('load')
|
|
150
|
+
self.gdb.expect('(gdb)')
|
|
151
|
+
|
|
152
|
+
try:
|
|
153
|
+
output = self.gdb.read_nonblocking(size=100, timeout=1)
|
|
154
|
+
PRINT_DEB("Current gdb output:", output)
|
|
155
|
+
except pexpect.TIMEOUT:
|
|
156
|
+
PRINT_DEB("No new output from GDB.")
|
|
157
|
+
self.gdb.terminate()
|
|
158
|
+
return False
|
|
159
|
+
|
|
160
|
+
# Set a breakpoint at the exit and wait for it
|
|
161
|
+
self.gdb.sendline('b _exit')
|
|
162
|
+
self.gdb.expect('(gdb)')
|
|
163
|
+
self.gdb.sendline('continue')
|
|
164
|
+
|
|
165
|
+
exit_detected = False
|
|
166
|
+
while not exit_detected:
|
|
167
|
+
try:
|
|
168
|
+
index = self.gdb.expect([r"Breakpoint", pexpect.TIMEOUT], timeout=10)
|
|
169
|
+
if index == 0:
|
|
170
|
+
exit_detected = True
|
|
171
|
+
PRINT_DEB("Program finished execution.")
|
|
172
|
+
except pexpect.exceptions.EOF:
|
|
173
|
+
break
|
|
174
|
+
|
|
175
|
+
# Wait for serial to finish
|
|
176
|
+
self.serial_comm_thread.join()
|
|
177
|
+
|
|
178
|
+
outputLines = []
|
|
179
|
+
while not self.serial_comm_queue.empty():
|
|
180
|
+
outputLines.append(self.serial_comm_queue.get())
|
|
181
|
+
|
|
182
|
+
# Test using the simulation tool
|
|
183
|
+
else:
|
|
184
|
+
# Compile the application
|
|
185
|
+
app_compile_cmd = f"make sw-sim app={app_name}"
|
|
186
|
+
result_compilation = subprocess.run(app_compile_cmd, shell=True, capture_output=True, text=True)
|
|
187
|
+
|
|
188
|
+
if ("ERROR" in result_compilation.stdout) or ("Error" in result_compilation.stdout) or ("error" in result_compilation.stdout) or \
|
|
189
|
+
("ERROR" in result_compilation.stderr) or ("Error" in result_compilation.stderr) or ("error" in result_compilation.stderr):
|
|
190
|
+
with open("testit_crash.log", "w") as file:
|
|
191
|
+
file.write(result_compilation.stdout)
|
|
192
|
+
file.write(result_compilation.stderr)
|
|
193
|
+
return False
|
|
194
|
+
|
|
195
|
+
PRINT_DEB("Compilation successful!")
|
|
196
|
+
|
|
197
|
+
# Launch the simulation test
|
|
198
|
+
sim_cmd = f"make sim-run app={app_name}"
|
|
199
|
+
result_sim = subprocess.run(sim_cmd, shell=True, capture_output=True, text=True)
|
|
200
|
+
|
|
201
|
+
if ("ERROR" in result_sim.stdout) or ("Error" in result_sim.stdout) or ("error" in result_sim.stdout) or \
|
|
202
|
+
("ERROR" in result_sim.stderr) or ("Error" in result_sim.stderr) or ("error" in result_sim.stderr):
|
|
203
|
+
with open("testit_crash.log", "w") as file:
|
|
204
|
+
file.write(result_sim.stdout)
|
|
205
|
+
file.write(result_sim.stderr)
|
|
206
|
+
return False
|
|
207
|
+
|
|
208
|
+
PRINT_DEB("Simulation successful!")
|
|
209
|
+
|
|
210
|
+
# Read the output file
|
|
211
|
+
try:
|
|
212
|
+
with open(self.cfg['target']['outputFile'], 'r') as f:
|
|
213
|
+
outputLines = f.readlines()
|
|
214
|
+
except FileNotFoundError:
|
|
215
|
+
return False
|
|
216
|
+
|
|
217
|
+
PRINT_DEB("Output lines:", outputLines)
|
|
218
|
+
|
|
219
|
+
# Analyse the results of the test
|
|
220
|
+
output_matches = []
|
|
221
|
+
pattern = re.compile(pattern)
|
|
222
|
+
for line in outputLines:
|
|
223
|
+
match = pattern.search(line)
|
|
224
|
+
if match:
|
|
225
|
+
|
|
226
|
+
matched_data = match.groups()
|
|
227
|
+
result_dict = {output_tags[i]: matched_data[i] for i in range(len(matched_data))}
|
|
228
|
+
output_matches.append(result_dict)
|
|
229
|
+
|
|
230
|
+
testit_util._append_results_to_report(self.cfg['report']['dir'], app_name, iteration, output_matches)
|
|
231
|
+
return True
|
|
232
|
+
|
|
233
|
+
# Generate a report of the last verification campaign.
|
|
234
|
+
def gen_report(self, sort_key=None, ascending=True):
|
|
235
|
+
console = Console(record=True)
|
|
236
|
+
|
|
237
|
+
with open(f"{self.cfg['report']['dir']}/test_results.json", "r") as f:
|
|
238
|
+
results = json.load(f)
|
|
239
|
+
|
|
240
|
+
for test_name, iterations in results.items():
|
|
241
|
+
|
|
242
|
+
table = Table(title=f"Test Report: {test_name}")
|
|
243
|
+
|
|
244
|
+
if iterations:
|
|
245
|
+
for key in iterations[0].keys():
|
|
246
|
+
table.add_column(key, style="cyan")
|
|
247
|
+
|
|
248
|
+
if sort_key and sort_key in iterations[0]:
|
|
249
|
+
try:
|
|
250
|
+
# Try numeric sorting first
|
|
251
|
+
iterations.sort(key=lambda x: int(x[sort_key]), reverse=not ascending)
|
|
252
|
+
except ValueError:
|
|
253
|
+
# Fallback to string sorting
|
|
254
|
+
iterations.sort(key=lambda x: x[sort_key], reverse=not ascending)
|
|
255
|
+
|
|
256
|
+
for entry in iterations:
|
|
257
|
+
table.add_row(*[str(entry[key]) for key in entry])
|
|
258
|
+
|
|
259
|
+
console.print(table)
|
|
260
|
+
|
|
261
|
+
with open(f"{self.cfg['report']['dir']}/report.rpt", "w") as f:
|
|
262
|
+
f.write(console.export_text())
|
|
263
|
+
|
|
264
|
+
# This function generates datasets for every test insered in config.test.
|
|
265
|
+
# Both input and output datasets are written in a single file, "data.c" and "data.h".
|
|
266
|
+
def gen_datasets(self, swipe_mode=False, test_iteration=None):
|
|
267
|
+
testCopy = copy.deepcopy(self.cfg.get("tests", []))
|
|
268
|
+
for test in testCopy:
|
|
269
|
+
|
|
270
|
+
test_dir = test["dir"]
|
|
271
|
+
if not os.path.exists(test_dir):
|
|
272
|
+
print(f"ERROR: Test directory '{test_dir}' not found.")
|
|
273
|
+
return False
|
|
274
|
+
|
|
275
|
+
# Open files for writing
|
|
276
|
+
try:
|
|
277
|
+
with open(f"{test_dir}/{test['genFilesName']}.h", 'w') as h_file, open(f"{test_dir}/{test['genFilesName']}.c", 'w') as c_file:
|
|
278
|
+
|
|
279
|
+
h_file.write("#ifndef TEST_DATA_H\n")
|
|
280
|
+
h_file.write("#define TEST_DATA_H\n\n")
|
|
281
|
+
h_file.write("#include <stdint.h>\n\n")
|
|
282
|
+
|
|
283
|
+
# Iterate through parameters list
|
|
284
|
+
if "parameters" in test:
|
|
285
|
+
if swipe_mode:
|
|
286
|
+
swipe_parameters = testit_util._get_swipe_parameters(test_iteration, test['parameters'])
|
|
287
|
+
|
|
288
|
+
parameter_index = 0
|
|
289
|
+
for param in test['parameters']:
|
|
290
|
+
|
|
291
|
+
param_name = param["name"]
|
|
292
|
+
|
|
293
|
+
if not swipe_mode:
|
|
294
|
+
|
|
295
|
+
# If the parameter's value is a list, take a random value from the range
|
|
296
|
+
if isinstance(param["value"], list):
|
|
297
|
+
param_value = random.randint(param["value"][0], param["value"][1])
|
|
298
|
+
param["value"] = param_value
|
|
299
|
+
else:
|
|
300
|
+
param["value"] = swipe_parameters[parameter_index]
|
|
301
|
+
parameter_index += 1
|
|
302
|
+
|
|
303
|
+
param_value = param["value"]
|
|
304
|
+
h_file.write(f"#define {param_name} {param_value}\n")
|
|
305
|
+
|
|
306
|
+
h_file.write("\n")
|
|
307
|
+
|
|
308
|
+
file_name = test['genFilesName']
|
|
309
|
+
c_file.write(f'#include "{file_name}.h"\n\n')
|
|
310
|
+
|
|
311
|
+
input_datasets = test.get("inputDataset", [])
|
|
312
|
+
|
|
313
|
+
# Ensure input_datasets is a list (it might be a dict if only one exists)
|
|
314
|
+
if isinstance(input_datasets, dict):
|
|
315
|
+
input_datasets = [input_datasets]
|
|
316
|
+
|
|
317
|
+
if input_datasets:
|
|
318
|
+
|
|
319
|
+
input_arrays = []
|
|
320
|
+
|
|
321
|
+
for dataset in input_datasets:
|
|
322
|
+
dataset_name = dataset["name"]
|
|
323
|
+
datatype = dataset["dataType"]
|
|
324
|
+
value_range = dataset["valueRange"]
|
|
325
|
+
dimensions = dataset["dimensions"]
|
|
326
|
+
|
|
327
|
+
# Handle parameter-dependent dimensions
|
|
328
|
+
converted_dimensions = []
|
|
329
|
+
for dim in dimensions:
|
|
330
|
+
if isinstance(dim, str):
|
|
331
|
+
dim = next((p["value"] for p in test['parameters'] if p["name"] == dim), 1)
|
|
332
|
+
converted_dimensions.append(dim)
|
|
333
|
+
|
|
334
|
+
dataset_shape = tuple(converted_dimensions)
|
|
335
|
+
|
|
336
|
+
# Generate a NumPy array with the correct shape and datatype
|
|
337
|
+
if datatype == "uint8_t":
|
|
338
|
+
input_array = np.random.randint(value_range[0], value_range[1], size=dataset_shape, dtype=np.uint8)
|
|
339
|
+
elif datatype == "uint16_t":
|
|
340
|
+
input_array = np.random.randint(value_range[0], value_range[1], size=dataset_shape, dtype=np.uint16)
|
|
341
|
+
elif datatype == "uint32_t":
|
|
342
|
+
input_array = np.random.randint(value_range[0], value_range[1], size=dataset_shape, dtype=np.uint32)
|
|
343
|
+
elif datatype == "uint64_t":
|
|
344
|
+
input_array = np.random.randint(value_range[0], value_range[1], size=dataset_shape, dtype=np.uint64)
|
|
345
|
+
elif datatype == "int8_t":
|
|
346
|
+
input_array = np.random.randint(value_range[0], value_range[1], size=dataset_shape, dtype=np.int8)
|
|
347
|
+
elif datatype == "int16_t":
|
|
348
|
+
input_array = np.random.randint(value_range[0], value_range[1], size=dataset_shape, dtype=np.int16)
|
|
349
|
+
elif datatype == "int32_t":
|
|
350
|
+
input_array = np.random.randint(value_range[0], value_range[1], size=dataset_shape, dtype=np.int32)
|
|
351
|
+
elif datatype == "int64_t":
|
|
352
|
+
input_array = np.random.randint(value_range[0], value_range[1], size=dataset_shape, dtype=np.int64)
|
|
353
|
+
elif datatype == "float":
|
|
354
|
+
input_array = np.random.uniform(value_range[0], value_range[1], size=dataset_shape).astype(np.float32)
|
|
355
|
+
elif datatype == "double":
|
|
356
|
+
input_array = np.random.uniform(value_range[0], value_range[1], size=dataset_shape).astype(np.float64)
|
|
357
|
+
else:
|
|
358
|
+
raise ValueError(f"unsupported datatype '{datatype}'")
|
|
359
|
+
|
|
360
|
+
input_arrays.append(input_array)
|
|
361
|
+
|
|
362
|
+
total_size = np.prod(dataset_shape)
|
|
363
|
+
h_file.write(f"extern const {datatype} {dataset_name}[{total_size}];\n")
|
|
364
|
+
|
|
365
|
+
# Define dataset in Source File (data.c)
|
|
366
|
+
c_file.write(f"const {datatype} {dataset_name}[{total_size}]" + " = {\n")
|
|
367
|
+
|
|
368
|
+
# Write the golden result array with formatting
|
|
369
|
+
testit_util._write_array(c_file, input_array, dataset_shape)
|
|
370
|
+
|
|
371
|
+
c_file.write("};\n\n")
|
|
372
|
+
|
|
373
|
+
output_datasets = test.get("outputDataset", [])
|
|
374
|
+
|
|
375
|
+
# Ensure output_datasets is a list (it might be a dict if only one exists)
|
|
376
|
+
if isinstance(output_datasets, dict):
|
|
377
|
+
output_datasets = [output_datasets]
|
|
378
|
+
|
|
379
|
+
# Output datasets are not mandatory
|
|
380
|
+
if output_datasets:
|
|
381
|
+
# Generate the golden results using the golden function
|
|
382
|
+
golden_function = testit_util._dyn_load_func(test["goldenResultFunction"]["name"])
|
|
383
|
+
golden_results = golden_function(input_arrays, test["parameters"])
|
|
384
|
+
|
|
385
|
+
# Ensure golden_results is a list (it might be a single array)
|
|
386
|
+
if testit_util._is_numpy_array(golden_results):
|
|
387
|
+
golden_results = [golden_results]
|
|
388
|
+
|
|
389
|
+
# Write the golden result
|
|
390
|
+
for iteration, golden_result in enumerate(golden_results):
|
|
391
|
+
output_name = output_datasets[iteration]["name"]
|
|
392
|
+
output_shape = golden_result.shape
|
|
393
|
+
output_datatype = output_datasets[iteration]["dataType"]
|
|
394
|
+
|
|
395
|
+
total_size = np.prod(output_shape)
|
|
396
|
+
h_file.write(f"extern const {output_datatype} {output_name}[{total_size}];\n")
|
|
397
|
+
|
|
398
|
+
c_file.write(f"const {output_datatype} {output_name}[{total_size}]" + " = {\n")
|
|
399
|
+
|
|
400
|
+
# Write the golden result array with formatting
|
|
401
|
+
testit_util._write_array(c_file, golden_result, output_shape)
|
|
402
|
+
|
|
403
|
+
c_file.write("};\n\n")
|
|
404
|
+
|
|
405
|
+
# Close Header File
|
|
406
|
+
h_file.write("\n#endif // TEST_DATA_H\n")
|
|
407
|
+
except Exception as e:
|
|
408
|
+
print(f"ERROR: {e}")
|
|
409
|
+
return False
|
|
410
|
+
|
|
411
|
+
return True
|
testit/testit_util.py
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import importlib.util
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import serial
|
|
5
|
+
import numpy as np
|
|
6
|
+
import sys
|
|
7
|
+
import threading
|
|
8
|
+
import subprocess
|
|
9
|
+
import rich
|
|
10
|
+
|
|
11
|
+
# Set this to True to enable debugging prints
|
|
12
|
+
# TODO: REMOVE BEFORE RELEASE
|
|
13
|
+
DEBUG_MODE = False
|
|
14
|
+
|
|
15
|
+
def _write_array(f, array, shape, indent=2):
|
|
16
|
+
flat_array = array.flatten()
|
|
17
|
+
num_dims = len(shape)
|
|
18
|
+
f.write(" " * indent)
|
|
19
|
+
|
|
20
|
+
for i, value in enumerate(flat_array):
|
|
21
|
+
|
|
22
|
+
f.write(f" {value}")
|
|
23
|
+
|
|
24
|
+
if i < len(flat_array) - 1:
|
|
25
|
+
f.write(",")
|
|
26
|
+
# Insert a newline after every "row" (last dimension)
|
|
27
|
+
if (i + 1) % shape[-1] == 0:
|
|
28
|
+
f.write("\n" + " " * indent)
|
|
29
|
+
|
|
30
|
+
# Insert a **blank line** when finishing a 2D block (2nd-to-last dimension)
|
|
31
|
+
if num_dims > 2 and (i + 1) % (shape[-2] * shape[-1]) == 0:
|
|
32
|
+
f.write("\n")
|
|
33
|
+
|
|
34
|
+
# Insert **two blank outputLines** when finishing a 3D block
|
|
35
|
+
if num_dims > 3 and (i + 1) % (shape[-3] * shape[-2] * shape[-1]) == 0:
|
|
36
|
+
f.write("\n\n")
|
|
37
|
+
|
|
38
|
+
# Insert **three blank outputLines** when finishing a 4D block, and so on...
|
|
39
|
+
if num_dims > 4:
|
|
40
|
+
for d in range(4, num_dims + 1):
|
|
41
|
+
if (i + 1) % np.prod(shape[-d:]) == 0:
|
|
42
|
+
f.write("\n" * (d - 2))
|
|
43
|
+
|
|
44
|
+
f.write("\n" + " " * indent)
|
|
45
|
+
|
|
46
|
+
# Loads the existing database or initializes a new one
|
|
47
|
+
def _load_database(dir):
|
|
48
|
+
if os.path.exists(f"{dir}/test_results.json"):
|
|
49
|
+
with open(f"{dir}/test_results.json", "r") as file:
|
|
50
|
+
return json.load(file)
|
|
51
|
+
return {}
|
|
52
|
+
|
|
53
|
+
# Eliminates the existing database file
|
|
54
|
+
def _clear_database(dir):
|
|
55
|
+
if os.path.exists(f"{dir}/test_results.json"):
|
|
56
|
+
os.remove(f"{dir}/test_results.json")
|
|
57
|
+
|
|
58
|
+
# Appends results to the report database
|
|
59
|
+
def _append_results_to_report(dir, test_name, iteration, results):
|
|
60
|
+
|
|
61
|
+
db = _load_database(dir)
|
|
62
|
+
|
|
63
|
+
PRINT_DEB(f"Appending results to report: {test_name}, iteration {iteration}, results: {results}")
|
|
64
|
+
|
|
65
|
+
# Ensure the test has a list initialized
|
|
66
|
+
if test_name not in db:
|
|
67
|
+
db[test_name] = []
|
|
68
|
+
|
|
69
|
+
# Append new result
|
|
70
|
+
for result in results:
|
|
71
|
+
result_entry = {"iteration": iteration, **result}
|
|
72
|
+
db[test_name].append(result_entry)
|
|
73
|
+
|
|
74
|
+
PRINT_DEB(f"Database after appending: {db}")
|
|
75
|
+
|
|
76
|
+
# Save back to JSON
|
|
77
|
+
with open(f"{dir}/test_results.json", "w") as file:
|
|
78
|
+
json.dump(db, file, indent=4)
|
|
79
|
+
|
|
80
|
+
# Dynamically load a function from 'testit_golden.py'
|
|
81
|
+
def _dyn_load_func(function_name):
|
|
82
|
+
module_name = "testit_golden"
|
|
83
|
+
module_path = os.path.join(os.getcwd(), f"{module_name}.py")
|
|
84
|
+
|
|
85
|
+
if not os.path.exists(module_path):
|
|
86
|
+
raise ImportError(f"Module {module_name} not found in current directory: {module_path}")
|
|
87
|
+
|
|
88
|
+
spec = importlib.util.spec_from_file_location(module_name, module_path)
|
|
89
|
+
module = importlib.util.module_from_spec(spec)
|
|
90
|
+
spec.loader.exec_module(module)
|
|
91
|
+
|
|
92
|
+
if not hasattr(module, function_name):
|
|
93
|
+
raise AttributeError(f"Function {function_name} not found in {module_name}")
|
|
94
|
+
|
|
95
|
+
return getattr(module, function_name)
|
|
96
|
+
|
|
97
|
+
# SUPER-IMPORTANT: Every communication by the SW application MUST end with an endword character, which is by default "&".
|
|
98
|
+
def _serial_rx_setup(ser: serial.Serial, serial_comm_queue, endword="&"):
|
|
99
|
+
try:
|
|
100
|
+
if not ser.is_open:
|
|
101
|
+
raise serial.SerialException("Serial port not open")
|
|
102
|
+
|
|
103
|
+
received = False
|
|
104
|
+
while not received:
|
|
105
|
+
# Read the data from the serial port
|
|
106
|
+
line = ser.readline().decode('utf-8').rstrip()
|
|
107
|
+
serial_comm_queue.put(line)
|
|
108
|
+
PRINT_DEB(f">: {line}")
|
|
109
|
+
if line:
|
|
110
|
+
if endword in line:
|
|
111
|
+
received = True
|
|
112
|
+
PRINT_DEB(f"Received {endword}: end of serial transmission thread")
|
|
113
|
+
return
|
|
114
|
+
elif "ERROR" in line:
|
|
115
|
+
print("FAILED VERIFICATION!")
|
|
116
|
+
exit(1)
|
|
117
|
+
except serial.SerialException as e:
|
|
118
|
+
print(f"Serial exception: {e}")
|
|
119
|
+
except Exception as e:
|
|
120
|
+
print(f"An ERROR occurred: {e}")
|
|
121
|
+
except KeyboardInterrupt:
|
|
122
|
+
print("Keyboard interruption")
|
|
123
|
+
finally:
|
|
124
|
+
pass
|
|
125
|
+
|
|
126
|
+
def PRINT_DEB(*args, **kwargs):
|
|
127
|
+
if DEBUG_MODE:
|
|
128
|
+
print(*args, **kwargs)
|
|
129
|
+
|
|
130
|
+
def _is_numpy_array(obj):
|
|
131
|
+
return isinstance(obj, np.ndarray)
|
|
132
|
+
|
|
133
|
+
def _run_command_threading(command):
|
|
134
|
+
thread = threading.Thread(target=__run_command, args=(command,), daemon=True)
|
|
135
|
+
thread.start()
|
|
136
|
+
return thread
|
|
137
|
+
|
|
138
|
+
# If the command fails, the process will terminate and the script will exit
|
|
139
|
+
def __run_command(command):
|
|
140
|
+
process = subprocess.Popen(
|
|
141
|
+
command,
|
|
142
|
+
stdout=subprocess.PIPE,
|
|
143
|
+
stderr=subprocess.PIPE,
|
|
144
|
+
text=True,
|
|
145
|
+
shell=True
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
while True:
|
|
149
|
+
output = process.stdout.readline()
|
|
150
|
+
if output:
|
|
151
|
+
if "ERROR" in output or "Error" in output or "error" in output:
|
|
152
|
+
process.terminate()
|
|
153
|
+
process.wait()
|
|
154
|
+
rich.print(f"[bold red]CRITICAL ERROR: {output} failed![/bold red]")
|
|
155
|
+
os._exit(1)
|
|
156
|
+
|
|
157
|
+
error_output = process.stderr.readline()
|
|
158
|
+
if error_output:
|
|
159
|
+
if "ERROR" in output or "Error" in output or "error" in output:
|
|
160
|
+
process.terminate()
|
|
161
|
+
process.wait()
|
|
162
|
+
rich.print(f"[bold red]CRITICAL ERROR: {output} failed![/bold red]")
|
|
163
|
+
os._exit(1)
|
|
164
|
+
|
|
165
|
+
# Check if process is still running
|
|
166
|
+
if process.poll() is not None:
|
|
167
|
+
break # Exit loop when process completes
|
|
168
|
+
|
|
169
|
+
process.wait() # Ensure process is fully done before exiting
|
|
170
|
+
|
|
171
|
+
def _get_swipe_parameters(iteration, parameters):
|
|
172
|
+
swipe_parameters = []
|
|
173
|
+
range_sizes = []
|
|
174
|
+
param_ranges = []
|
|
175
|
+
complete_parameters = []
|
|
176
|
+
steps = []
|
|
177
|
+
|
|
178
|
+
for parameter in parameters:
|
|
179
|
+
if isinstance(parameter['value'], list):
|
|
180
|
+
param_ranges.append(tuple(parameter['value']))
|
|
181
|
+
steps.append(parameter['step'])
|
|
182
|
+
|
|
183
|
+
# Compute range sizes
|
|
184
|
+
for (min_val, max_val), step in zip(param_ranges, steps):
|
|
185
|
+
size = (max_val - min_val) // step + 1
|
|
186
|
+
range_sizes.append(size)
|
|
187
|
+
|
|
188
|
+
step_product = 1
|
|
189
|
+
for idx, ((min_val, _), step) in enumerate(zip(param_ranges, steps)):
|
|
190
|
+
if idx > 0:
|
|
191
|
+
step_product *= range_sizes[idx - 1]
|
|
192
|
+
param_value = min_val + ((iteration // step_product) % range_sizes[idx]) * step
|
|
193
|
+
swipe_parameters.append(param_value)
|
|
194
|
+
|
|
195
|
+
swipe_index = 0
|
|
196
|
+
for param in parameters:
|
|
197
|
+
if isinstance(param['value'], list):
|
|
198
|
+
complete_parameters.append(swipe_parameters[swipe_index])
|
|
199
|
+
swipe_index += 1
|
|
200
|
+
else:
|
|
201
|
+
complete_parameters.append(param['value'])
|
|
202
|
+
|
|
203
|
+
return complete_parameters
|