forked from UNN/2026-rff_mp
experiment2
реализован запуск эксперимента с сохранением результатов в csv файле и png графиков в папке lab2_result
This commit is contained in:
parent
b091b98a93
commit
dbd088daff
|
|
@ -421,3 +421,73 @@ def generate_test_maze_file(filename: str, maze_type: str):
|
||||||
|
|
||||||
with open(full_path, 'w', encoding='utf-8') as f:
|
with open(full_path, 'w', encoding='utf-8') as f:
|
||||||
f.write('\n'.join(lines))
|
f.write('\n'.join(lines))
|
||||||
|
|
||||||
|
def run_experiment():
|
||||||
|
ensure_results_dir()
|
||||||
|
maze_types = ["small", "medium", "large", "empty", "no_exit"]
|
||||||
|
strategies = {
|
||||||
|
"BFS": BFSStrategy(),
|
||||||
|
"DFS": DFSStrategy(),
|
||||||
|
"AStar": AStarStrategy()
|
||||||
|
}
|
||||||
|
results = []
|
||||||
|
|
||||||
|
for maze_type in maze_types:
|
||||||
|
filename = f"maze_{maze_type}.txt"
|
||||||
|
generate_test_maze_file(filename, maze_type)
|
||||||
|
full_path = os.path.join(RESULTS_DIR, filename)
|
||||||
|
builder = TextFileMazeBuilder()
|
||||||
|
try:
|
||||||
|
maze = builder.build_from_file(full_path)
|
||||||
|
except ValueError as e:
|
||||||
|
print(f"Лабиринт {maze_type} пропущен: {e}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
for strat_name, strat_obj in strategies.items():
|
||||||
|
times = []
|
||||||
|
path_lengths = []
|
||||||
|
visited_counts = []
|
||||||
|
for run in range(5):
|
||||||
|
solver = MazeSolver(maze, strat_obj)
|
||||||
|
path, stats = solver.solve()
|
||||||
|
times.append(stats.time_ms)
|
||||||
|
path_lengths.append(stats.path_length)
|
||||||
|
visited_counts.append(stats.visited_cells)
|
||||||
|
avg_time = sum(times) / len(times)
|
||||||
|
avg_path_len = sum(path_lengths) / len(path_lengths)
|
||||||
|
avg_visited = sum(visited_counts) / len(visited_counts)
|
||||||
|
results.append({
|
||||||
|
"maze": maze_type,
|
||||||
|
"strategy": strat_name,
|
||||||
|
"avg_time_ms": avg_time,
|
||||||
|
"avg_visited": avg_visited,
|
||||||
|
"avg_path_length": avg_path_len
|
||||||
|
})
|
||||||
|
print(f"{maze_type} / {strat_name}: время={avg_time:.2f}ms, посещено={avg_visited:.1f}, путь={avg_path_len:.1f}")
|
||||||
|
|
||||||
|
csv_path = os.path.join(RESULTS_DIR, "experiment_results.csv")
|
||||||
|
with open(csv_path, "w", newline='', encoding='utf-8') as f:
|
||||||
|
writer = csv.DictWriter(f, fieldnames=["maze", "strategy", "avg_time_ms", "avg_visited", "avg_path_length"])
|
||||||
|
writer.writeheader()
|
||||||
|
writer.writerows(results)
|
||||||
|
try:
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
for maze_type in ["small", "medium", "large", "empty"]:
|
||||||
|
data = [r for r in results if r["maze"] == maze_type]
|
||||||
|
if not data:
|
||||||
|
continue
|
||||||
|
names = [d["strategy"] for d in data]
|
||||||
|
times = [d["avg_time_ms"] for d in data]
|
||||||
|
visited = [d["avg_visited"] for d in data]
|
||||||
|
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
|
||||||
|
ax1.bar(names, times)
|
||||||
|
ax1.set_title(f"Время (мс) - {maze_type}")
|
||||||
|
ax2.bar(names, visited)
|
||||||
|
ax2.set_title(f"Посещено клеток - {maze_type}")
|
||||||
|
plt.tight_layout()
|
||||||
|
plot_path = os.path.join(RESULTS_DIR, f"plot_{maze_type}.png")
|
||||||
|
plt.savefig(plot_path)
|
||||||
|
plt.close()
|
||||||
|
print(f"Графики сохранены в папку {RESULTS_DIR}")
|
||||||
|
except ImportError:
|
||||||
|
print("matplotlib не установлен. Графики не построены.")
|
||||||
Loading…
Reference in New Issue
Block a user