import random
# Define parameters
k = 1
evaporation_rate = 0.1
ant_count = 10
iterations = 10
# Define edges with pheromone values and lengths
edges = [
{"pheromone": 2, "length": 5},
{"pheromone": 1, "length": 10}
]
# Define the source and destination nodes
source_node = 0
destination_node = 1
# Define pheromone update function
def update_pheromones(edge_index, length):
edges[edge_index]["pheromone"] += k / length
# Main ACO loop
for _ in range(iterations):
for _ in range(ant_count):
current = source_node # Starting at the source node
while current != destination_node:
# Select the next edge based on pheromone values and lengths
probabilities = [edge["pheromone"] for edge in edges]
selected_edge_index = random.choices(range(len(edges)), weights=probabilities)[0]
next_node = destination_node # Assuming there are only two nodes
if current == source_node: # If the current node is the source node
next_node = selected_edge_index # Move to the next node based on selected edge
else:
next_node = destination_node # Move to the destination node
# Update pheromone levels on the selected edge
update_pheromones(selected_edge_index, edges[selected_edge_index]["length"])
# Move to the next node
current = next_node
pheromone_levels = [] # List to store the pheromone levels on each path
# Print final pheromone levels on each edge
for index, edge in enumerate(edges):
print("Edge ", index+1, ": Pheromone = ", edge['pheromone'])
pheromone_levels.append(edge['pheromone'])
# Print optimal path
print("The optimal path is: E{}".format(pheromone_levels.index(max(pheromone_levels))+1))