import math import random import numpy as np
demand = [10, 15, 21, 9, 25, 18, 23, 15, 8, 13] x_coords = [3, 12, 2, 24, 31, 5, 17, 16, 12, 8] y_coords = [13, 7, 26, 12, 22, 14, 11, 13, 8, 2] num_stores = len(demand)
depot_x, depot_y = 12, 12
vehicle_capacity = 40 unit_cost = 10
num_ants = 50 max_iterations = 100
rho = 0.5 alpha = 1.0 beta = 2.0
def calculate_distance(x1, y1, x2, y2): return math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
pheromone_matrix = np.ones((num_stores + 1, num_stores + 1))
def aco_algorithm(): global pheromone_matrix best_solution = None best_cost = float('inf') for iteration in range(max_iterations): ants = build_ants() solutions = [] costs = [] for ant in ants: solution, cost = calculate_solution(ant) solutions.append(solution) costs.append(cost) best_idx = np.argmin(costs) if costs[best_idx] < best_cost: best_solution = solutions[best_idx] best_cost = costs[best_idx] update_pheromone_matrix(solutions, costs) print("\nBest solution:") print_solution(best_solution, best_cost)
def build_ants(): ants = [] for _ in range(num_ants): ant = [0] remaining_stores = list(range(1, num_stores + 1)) random.shuffle(remaining_stores) ant.extend(remaining_stores) ants.append(ant) return ants
def calculate_solution(ant): solution = [] current_load = 0 current_route = [0] total_distance = 0 for store in ant[1:]: if current_load + demand[store - 1] <= vehicle_capacity: current_route.append(store) current_load += demand[store - 1] else: total_distance += calculate_route_distance(current_route, x_coords, y_coords, depot_x, depot_y) solution.append(current_route) current_route = [0, store] current_load = demand[store - 1] if current_route: total_distance += calculate_route_distance(current_route, x_coords, y_coords, depot_x, depot_y) solution.append(current_route) cost = total_distance * unit_cost return solution, cost
def calculate_route_distance(route, x_coords, y_coords, depot_x, depot_y): distance = 0 prev_x, prev_y = depot_x, depot_y for store in route[1:]: x, y = x_coords[store - 1], y_coords[store - 1] distance += calculate_distance(prev_x, prev_y, x, y) prev_x, prev_y = x, y distance += calculate_distance(prev_x, prev_y, depot_x, depot_y) return distance
def update_pheromone_matrix(solutions, costs): global pheromone_matrix pheromone_matrix *= (1 - rho) for solution, cost in zip(solutions, costs): for route in solution: for i in range(len(route) - 1): pheromone_matrix[route[i], route[i + 1]] += 1.0 / cost pheromone_matrix[route[i + 1], route[i]] += 1.0 / cost
print("ACO算法:")
def print_solution(solution, cost): for i, route in enumerate(solution): route_distance = calculate_route_distance(route, x_coords, y_coords, depot_x, depot_y) route_cost = route_distance * unit_cost print(f"Vehicle {i + 1} route: 0 -> {' -> '.join(str(store) for store in route[1:])} -> 0, Distance: {route_distance}, Cost: {route_cost}") print(f"\nTotal cost: {cost}")
aco_algorithm()
|