-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathperformance_test.py
More file actions
348 lines (289 loc) · 11.4 KB
/
performance_test.py
File metadata and controls
348 lines (289 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
from __future__ import annotations
import csv
import json
import multiprocessing as mp
import os
import sys
import time
import tracemalloc
import warnings
from collections import defaultdict
from typing import ClassVar
import jsonschema
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import psutil
from alive_progress import alive_bar
from tqdm import tqdm
from hypex import AATest
from hypex.dataset import Dataset, TargetRole
warnings.filterwarnings("ignore")
sys.path.append("../../..")
class DataProfiler:
default_data_params: ClassVar[dict] = {
"n_columns": 10,
"n_rows": 10000,
"n2c_ratio": 0.7,
"rs": 42,
"num_range": (-100, 100),
"n_categories": 10,
}
def __init__(self, fixed_data_params: dict | None = None):
fixed_data_params = fixed_data_params or {}
self.fixed_data_params = self.default_data_params.copy()
self.fixed_data_params.update(fixed_data_params)
# Remove any keys that aren't in default params
for key in list(self.fixed_data_params.keys()):
if key not in list(self.default_data_params.keys()):
del self.fixed_data_params[key]
@staticmethod
def _generate_synthetic_data(
n_columns: int,
n_rows: int,
n2c_ratio: float,
rs: int | None,
num_range: tuple,
n_categories: int,
) -> pd.DataFrame:
if rs is not None:
np.random.seed(rs)
n_numerical = int(n_columns * n2c_ratio)
n_categorical = n_columns - n_numerical
numerical_data = np.random.randint(
num_range[0], num_range[1], size=(n_rows, n_numerical)
)
categories = [f"Category_{i + 1}" for i in range(n_categories)]
categorical_data = np.random.choice(categories, size=(n_rows, n_categorical))
return pd.DataFrame(
np.hstack((numerical_data, categorical_data)),
columns=[f"num_col_{i}" for i in range(n_numerical)]
+ [f"cat_col_{i}" for i in range(n_categorical)],
)
def create_dataset(
self, params: dict
) -> tuple[Dataset, dict[str, int | tuple[int, int] | float]]:
all_params = self.fixed_data_params.copy()
all_params.update(params)
data = self._generate_synthetic_data(**all_params)
return (
Dataset(roles={column: TargetRole() for column in data.columns}, data=data),
all_params,
)
class ExperimentProfiler:
default_experiment_params: ClassVar[dict] = {"n_iterations": 10}
def __init__(
self,
fixed_experiment_params: dict | None = None,
experiment: type = AATest,
):
fixed_experiment_params = fixed_experiment_params or {}
self.fixed_experiment_params = self.default_experiment_params.copy()
self.fixed_experiment_params.update(fixed_experiment_params)
self.experiment = experiment
# Remove any keys that aren't in default params
for key in list(self.fixed_experiment_params.keys()):
if key not in list(self.default_experiment_params.keys()):
del self.fixed_experiment_params[key]
def get_experiment(self, experiment_params):
all_params = self.fixed_experiment_params.copy()
all_params.update(experiment_params)
return self.experiment(**all_params), all_params
class PerformanceTester:
resume: ClassVar[defaultdict] = defaultdict(dict)
def __init__(
self,
dataProfiler: DataProfiler,
experimentProfiler: ExperimentProfiler,
iterable_params: list | None = None,
use_memory: bool = True,
rewrite: bool = True,
):
self.dataProfiler = dataProfiler
self.experimentProfiler = experimentProfiler
self.iterable_params = iterable_params or []
self.use_memory = use_memory
self.rewrite = rewrite
def get_params(self):
for params in self.iterable_params:
all_params = params.copy()
if "n_iterations" in list(params.keys()):
experiment_params = {"n_iterations": params["n_iterations"]}
params.pop("n_iterations", None)
else:
experiment_params = {}
data_params = params
yield all_params, self.dataProfiler.create_dataset(
data_params
), self.experimentProfiler.get_experiment(experiment_params)
def get_number_params(self):
return len(self.iterable_params)
def execute(self, file_name, analysis="onefactor"):
if self.rewrite:
with open(file_name, "w", newline="") as file:
writer = csv.writer(file)
row_items = [
"analysis",
*list(self.experimentProfiler.fixed_experiment_params.keys()),
*list(self.dataProfiler.fixed_data_params.keys()),
"time",
"M1",
"M2",
]
writer.writerow(row_items)
with alive_bar(
self.get_number_params(),
bar="squares",
spinner="dots_waves2",
title=f"Analysis : {analysis}",
) as bar:
for params, data, experiment in tqdm(self.get_params()):
combined_params = {**data[1], **experiment[1]}
print(f"{combined_params}")
manager = mp.Manager()
return_dict1 = manager.dict()
return_dict2 = manager.dict()
process = mp.Process(
target=self.function_performance,
args=(experiment[0].execute, {"data": data[0]}, return_dict1),
)
process.start()
monitor = mp.Process(
target=self._memory_monitor, args=(process.pid, return_dict2)
)
monitor.start()
process.join()
monitor.join()
max_memory_mb = return_dict2["max_memory"] / 1024**2
with open(file_name, "a", newline="") as file:
writer = csv.writer(file)
combined_params = {**experiment[1], **data[1]}
row_items = [
analysis,
*list(combined_params.values()),
*return_dict1["results"],
max_memory_mb,
]
writer.writerow(row_items)
bar()
@staticmethod
def _memory_monitor(pid, return_dict, interval=0.1):
process = psutil.Process(pid)
max_memory = 0
while process.is_running():
try:
mem_info = process.memory_info().rss # Current memory usage (RSS)
max_memory = max(max_memory, mem_info) # Update maximum
time.sleep(interval)
except psutil.NoSuchProcess:
break # If the process has finished
return_dict["max_memory"] = max_memory # Save the result
def function_performance(self, func, param_dict, return_dict):
param_dict = param_dict or {}
exec_time = None
memory_usage = None
start_time = time.time()
if self.use_memory:
tracemalloc.start()
func(**param_dict)
if self.use_memory:
_, memory_usage = tracemalloc.get_traced_memory()
tracemalloc.stop()
end_time = time.time()
exec_time = end_time - start_time
return_dict["results"] = [
exec_time,
memory_usage / 10**6 if self.use_memory else None,
]
def performance_test_plot(
params: dict,
output_path: str,
title="The results of the one-factor performance test of the AA Test",
):
df = pd.read_csv(output_path)
df = df[df.analysis == "onefactor"]
df = df[["time", "M1", "M2"]]
result = {"Var": [], "P": []}
for key, values in params.items():
for value in values:
result["Var"].append(key)
result["P"].append(value)
df["Var"] = result["Var"]
df["P"] = result["P"]
plot_size = df["Var"].nunique()
if plot_size == 1:
fig, axs = plt.subplots(1, 3, figsize=(33, 5))
axs = axs.reshape(1, -1) # Делаем 2D массив
else:
fig, axs = plt.subplots(plot_size, 3, figsize=(plot_size * 11, 15))
for counter, (var, table) in enumerate(df.groupby("Var")):
table = table.sort_values(by="P")
axs[counter, 0].plot(table["P"], table["time"])
axs[counter, 0].set_title(f"{var} time")
axs[counter, 0].grid(True)
axs[counter, 0].set_ylabel("sec")
axs[counter, 1].plot(table["P"], table["M1"])
axs[counter, 1].set_title(f"{var} memory of execution")
axs[counter, 1].grid(True)
axs[counter, 1].set_ylabel("MB")
axs[counter, 2].plot(table["P"], table["M2"])
axs[counter, 2].set_title(f"{var} memory of process")
axs[counter, 2].grid(True)
axs[counter, 2].set_ylabel("MB")
fig.suptitle(title)
plt.subplots_adjust(hspace=0.5)
plt.savefig(f"{output_path[:output_path.rfind('.')]}.png")
def executor(config: dict, output_path: str):
output_path = f"{output_path}.csv"
if "fixed_params" not in config:
config["fixed_params"] = {}
experimentProfiler = ExperimentProfiler(
fixed_experiment_params=config["fixed_params"], experiment=AATest
)
dataProfiler = DataProfiler(fixed_data_params=config["fixed_params"])
test = PerformanceTester(
experimentProfiler=experimentProfiler, dataProfiler=dataProfiler
)
if "onefactor_params" in config:
iterable_params = []
def _format(param):
return param if isinstance(param, list) else [param]
for param_name, params in config["onefactor_params"].items():
params = _format(params)
for param in params:
iterable_params.append({param_name: param})
test.iterable_params = iterable_params
test.execute(output_path, analysis="onefactor")
test.rewrite = False
performance_test_plot(config["onefactor_params"], output_path)
if "montecarlo_params" in config:
mcparams = config["montecarlo_params"]
df = {}
for key in list(mcparams["bounds"].keys()):
df[key] = np.round(
np.random.uniform(
mcparams["bounds"][key]["min"],
mcparams["bounds"][key]["max"],
mcparams["num_points"],
)
).astype(int)
keys = list(df.keys())
df = [
{key: value.item() for key, value in zip(keys, values)}
for values in zip(*df.values())
]
test.iterable_params = df
test.execute(output_path, analysis="montecarlo")
if __name__ == "__main__":
script_dir = os.path.dirname(os.path.abspath(__file__))
file_path_schema = os.path.join(script_dir, "config.schema.json")
file_path_config = os.path.join(script_dir, "config.json")
with open(file_path_schema) as file1, open(file_path_config) as file2:
schema = json.load(file1)
config = json.load(file2)
try:
jsonschema.validate(instance=config, schema=schema)
except jsonschema.exceptions.ValidationError as err:
raise ValueError(f"JSON validation error: {err}") from err
output_path = "aa_performance_test_result"
executor(config=config, output_path=output_path)