Files
genetic-algorithms/lab6/main.py
2025-12-03 18:16:28 +03:00

39 lines
1.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
from aco import ACOConfig, plot_history, plot_tour, run_aco
# В списке из 89 городов только 38 уникальных
cities = set()
with open(os.path.join(os.path.dirname(__file__), "../lab3/data.txt"), "r") as file:
for line in file:
# x и y поменяны местами в визуализациях в методичке
_, y, x = line.split()
cities.add((float(x), float(y)))
cities = list(cities)
config = ACOConfig(
cities=cities,
n_ants=50,
n_iterations=50,
alpha=1.2,
beta=5.0,
rho=0.5,
q=1.0,
seed=7,
)
result = run_aco(config)
print(f"Лучшая длина: {result.best_length:.2f}")
print(f"Лучший тур: {result.best_tour}")
results_dir = os.path.join(os.path.dirname(__file__), "report", "img")
os.makedirs(results_dir, exist_ok=True)
plot_tour(
config.cities, result.best_tour, os.path.join(results_dir, "aco_best_tour.png")
)
plot_history(result.history, os.path.join(results_dir, "aco_history.png"))
with open(os.path.join(results_dir, "aco_best_tour.txt"), "w", encoding="utf-8") as f:
f.write(" ".join(map(str, result.best_tour)))