This commit is contained in:
2025-11-21 20:35:50 +03:00
parent 93ab829cff
commit 672b1c33d5
10 changed files with 155 additions and 92 deletions

View File

@@ -24,19 +24,14 @@ def build_distance_matrix(cities: Sequence[City]) -> list[list[float]]:
def plot_tour(cities: Sequence[City], tour: Sequence[int], save_path: str) -> None:
ordered = [cities[i] for i in tour] + [cities[tour[0]]]
xs, ys = zip(*ordered)
x = [cities[i][0] for i in tour]
y = [cities[i][1] for i in tour]
fig, ax = plt.subplots(figsize=(7, 7))
ax.plot(xs, ys, "-o", color="#1f77b4", markersize=4, linewidth=1.5)
city_xs, city_ys = zip(*cities)
ax.scatter(city_xs, city_ys, s=18, color="#d62728", zorder=5)
ax.plot(x + [x[0]], y + [y[0]], "k-", linewidth=1)
ax.plot(x, y, "ro", markersize=4)
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_title("Маршрут тура")
ax.set_aspect("equal", adjustable="box")
ax.grid(True, linestyle="--", alpha=0.3)
ax.axis("equal")
fig.tight_layout()
fig.savefig(save_path, dpi=220)
plt.close(fig)
@@ -46,14 +41,16 @@ def plot_history(best_lengths: Sequence[float], save_path: str) -> None:
if not best_lengths:
return
fig, ax = plt.subplots(figsize=(8, 3.8))
ax.plot(best_lengths, color="#111111", linewidth=1.4)
ax.set_xlabel("Итерация")
ax.set_ylabel("Длина лучшего тура")
ax.set_title("Сходимость ACO")
ax.grid(True, linestyle="--", alpha=0.4)
fig.tight_layout()
fig.savefig(save_path, dpi=220)
iterations = list(range(len(best_lengths)))
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(iterations, best_lengths, linewidth=2, color="blue")
ax.set_xlabel("Итерация", fontsize=12)
ax.set_ylabel("Длина лучшего тура", fontsize=12)
ax.grid(True, alpha=0.3)
fig.savefig(save_path, dpi=150, bbox_inches="tight")
plt.close(fig)
@@ -153,7 +150,9 @@ class AntColonyOptimizer:
best_history.append(best_length)
return ACOResult(best_tour=best_tour, best_length=best_length, history=best_history)
return ACOResult(
best_tour=best_tour, best_length=best_length, history=best_history
)
def run_aco(config: ACOConfig) -> ACOResult: