исправлена эксперементальная часть

This commit is contained in:
komissarovgo 2026-05-17 16:52:03 +03:00
parent eab701c381
commit e2c95c6096
7 changed files with 104 additions and 15 deletions

View File

@ -18,7 +18,14 @@ class ExperimentRunner:
] ]
def run_experiment(self, maze_file: str, runs: int = 5) -> List[Dict[str, Any]]: def run_experiment(self, maze_file: str, runs: int = 5) -> List[Dict[str, Any]]:
maze = self.builder.build_from_file(maze_file)
try:
maze = self.builder.build_from_file(maze_file)
except ValueError as e:
# Если лабиринт некорректный (нет старта или выхода)
print(f" Пропуск: {e}")
return []
results = [] results = []
for strategy in self.strategies: for strategy in self.strategies:
@ -28,33 +35,49 @@ class ExperimentRunner:
path_lengths = [] path_lengths = []
for _ in range(runs): for _ in range(runs):
path, stats = solver.solve() try:
times.append(stats.time_ms) path, stats = solver.solve()
path_lengths.append(stats.path_length) times.append(stats.time_ms)
path_lengths.append(stats.path_length)
except Exception as e:
print(f" Ошибка при {strategy.name}: {e}")
continue
results.append({ if times:
'maze': Path(maze_file).stem, results.append({
'strategy': strategy.name, 'maze': Path(maze_file).stem,
'avg_time_ms': sum(times) / runs, 'strategy': strategy.name,
'min_time_ms': min(times), 'avg_time_ms': sum(times) / runs,
'max_time_ms': max(times), 'min_time_ms': min(times),
'path_length': path_lengths[0] if path_lengths else 0 'max_time_ms': max(times),
}) 'path_length': path_lengths[0] if path_lengths else 0,
'path_found': path_lengths[0] > 0 if path_lengths else False
})
return results return results
def run_all_experiments(self, maze_files: List[str], runs: int = 5, def run_all_experiments(self, maze_files: List[str], runs: int = 5,
output_file: str = "results/experiment_results.csv"): output_file: str = "results/experiment_results.csv"):
all_results = [] all_results = []
for maze_file in maze_files: for maze_file in maze_files:
print(f"Запуск на лабиринте: {maze_file}") print(f"Запуск на лабиринте: {maze_file}")
results = self.run_experiment(maze_file, runs) results = self.run_experiment(maze_file, runs)
all_results.extend(results)
for r in results: if results:
print(f" {r['strategy']}: {r['avg_time_ms']:.3f} мс, путь: {r['path_length']}") all_results.extend(results)
for r in results:
status = "" if r['path_found'] else "✗ (нет пути)"
print(f" {r['strategy']}: {r['avg_time_ms']:.3f} мс, путь: {r['path_length']} {status}")
else:
print(f" Лабиринт пропущен (нет старта или выхода)")
if not all_results:
print("Нет результатов для сохранения!")
return
# Сохранение в CSV
Path("results").mkdir(exist_ok=True) Path("results").mkdir(exist_ok=True)
with open(output_file, 'w', newline='', encoding='utf-8') as f: with open(output_file, 'w', newline='', encoding='utf-8') as f:
writer = csv.DictWriter(f, fieldnames=all_results[0].keys()) writer = csv.DictWriter(f, fieldnames=all_results[0].keys())

View File

@ -16,6 +16,7 @@ def create_test_maze_file(filename: str, maze_data: list):
def setup_test_mazes(): def setup_test_mazes():
small_maze = [ small_maze = [
"##########", "##########",
"#S #", "#S #",
@ -30,6 +31,7 @@ def setup_test_mazes():
] ]
create_test_maze_file("small_maze.txt", small_maze) create_test_maze_file("small_maze.txt", small_maze)
simple_maze = [ simple_maze = [
"##########", "##########",
"#S #", "#S #",
@ -44,6 +46,7 @@ def setup_test_mazes():
] ]
create_test_maze_file("simple_maze.txt", simple_maze) create_test_maze_file("simple_maze.txt", simple_maze)
no_exit_maze = [ no_exit_maze = [
"##########", "##########",
"#S #", "#S #",
@ -56,7 +59,23 @@ def setup_test_mazes():
"# #######", "# #######",
"##########" "##########"
] ]
create_test_maze_file("no_exit_maze.txt", no_exit_maze) create_test_maze_file("no_exit_maze.txt", no_exit_maze)
blocked_maze = [
"##########",
"#S# #",
"# # #",
"# # #",
"# # #",
"# # #",
"# # #",
"# # #",
"# #######E",
"##########"
]
create_test_maze_file("blocked_maze.txt", blocked_maze)
def interactive_mode(): def interactive_mode():

View File

@ -0,0 +1,10 @@
##########
#S# #
# # #
# # #
# # #
# # #
# # #
# # #
# #######E
##########

View File

@ -0,0 +1,10 @@
##########
#S #
# ####### #
# # #
##### # # #
# # #
# ### ### #
# # #
# #######
##########

View File

@ -0,0 +1,10 @@
##########
#S #
# #
# #
# #
# #
# #
# #
# E#
##########

View File

@ -0,0 +1,10 @@
##########
#S #
# ####### #
# # #
##### # # #
# # #
# ### ### #
# # #
# #### E#
##########

View File

@ -0,0 +1,7 @@
maze,strategy,avg_time_ms,min_time_ms,max_time_ms,path_length,path_found
small_maze,BFS,0.09410000002390007,0.06260000009206124,0.17690000004222384,16,True
small_maze,DFS,0.0747799999317067,0.061499999901570845,0.12589999960255227,16,True
small_maze,A*,0.10337000007893948,0.07970000024215551,0.1430000002073939,16,True
simple_maze,BFS,0.14079999996283732,0.1119000003200199,0.18079999972542282,15,True
simple_maze,DFS,0.07789999999658903,0.07430000005115289,0.0957000002017594,29,True
simple_maze,A*,0.21409000005405687,0.18180000006395858,0.2953999996861967,15,True
1 maze strategy avg_time_ms min_time_ms max_time_ms path_length path_found
2 small_maze BFS 0.09410000002390007 0.06260000009206124 0.17690000004222384 16 True
3 small_maze DFS 0.0747799999317067 0.061499999901570845 0.12589999960255227 16 True
4 small_maze A* 0.10337000007893948 0.07970000024215551 0.1430000002073939 16 True
5 simple_maze BFS 0.14079999996283732 0.1119000003200199 0.18079999972542282 15 True
6 simple_maze DFS 0.07789999999658903 0.07430000005115289 0.0957000002017594 29 True
7 simple_maze A* 0.21409000005405687 0.18180000006395858 0.2953999996861967 15 True