Ant Colony Optimization in Action | by Hennie de Harder | Sep, 2023

A working ant. Image created with Dall-E 2 by the author.

Solving optimization problems and enhancing results with ACO in Python

Hennie de Harder

Welcome back! In my previous post, I introduced the fundamentals of Ant Colony Optimization (ACO). In this installment, we’ll delve into implementing the ACO algorithm from scratch to tackle two distinct problem types.

The problems we’ll be addressing are the Traveling Salesman Problem (TSP) and the Quadratic Assignment Problem (QAP). Why these two? Well, the TSP is a classic challenge, and ACO happens to be an effective algorithm for finding the most cost-efficient path through a graph. On the other hand, the Quadratic Assignment Problem represents a different class of problems related to optimizing the arrangement of items, and in this post, I aim to demonstrate that ACO can be a valuable tool for solving such assignment-related problems as well. This versatility makes the ACO algorithm applicable to a wide range of problems. Finally, I’ll share some tips for achieving improved solutions more rapidly.

TSP is straightforward to describe but can pose a significant challenge in finding a solution. Here’s the basic definition: you’re tasked with discovering the shortest route that visits all nodes in a graph. This problem falls into the category of NP-hard problems, which implies that if you attempt to explore all possible routes, it can take an impractical amount of time to find the solution. Instead, a more effective approach is to seek a high-quality solution within a reasonable timeframe, and that’s precisely what we’ll accomplish using ACO.

Problem Definition

With the following code, we can create a TSP instance with a given number of nodes:

import itertools
import math
import random
from typing import Tuple

import networkx as nx
import networkx.algorithms.shortest_paths.dense as nxalg

class TSP:
Creates a TSP problem with a certain number of nodes
def __init__(self, nodes: int = 30, dimensions: Tuple[int, int] = (1000, 1000), seed: int = 5):
if seed:

graph = nx.Graph()
nodes_dict = dict()

for i in range(nodes):
nodes_dict[i] =…

Source link

This post originally appeared on TechToday.