lab6
This commit is contained in:
37
lab6/aco.py
37
lab6/aco.py
@@ -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:
|
||||
|
||||
Reference in New Issue
Block a user