Zero Labs
Industry News / AI

Swarm Intelligence: How Ant Colonies Can Solve the Bin Packing Problem (Part 1)

Source · Towards AI By Martin Rmz Rabelo

From the publisher’s feed, collected in the ZeroLabs newsroom.

Moving from routing to grouping problems using decentralized nature-inspired algorithms.Image generated by GeminiThe Power of the Crowd: Understanding Collective IntelligenceImagine a vast, unpredictable forest. A single ant leaves its nest in search of food. On its own, its brain is tiny, its vision is limited, and its chances of finding the most efficient route to a distant sugar source are remarkably low.Yet, if you look at the entire colony, something miraculous happens. Within hours, a perfectly optimized highway of ants forms between the nest and the food. No single ant is in charge. There is no manager, no central blueprint, and no direct verbal communication.How do they do it?The answer lies in a fascinating phenomenon called collective intelligence — an emergent property in multi-agent systems where synchronization allows a group to optimize complex tasks that no single individual could achieve alone.In nature, this self-organization often doesn’t require a master coordinator. Instead, it relies on stigmergy: a decentralized organizational principle where agents interact and coordinate by modifying their shared environment. When an ant finds food, it deposits a chemical trace — a pheromone — on its way back. Other ants perceive this modification, follow it probabilistically, and reinforce it if they are successful.Because ants taking the shorter path return faster, their trail accumulates pheromones much quicker than the longer, inefficient routes. Over time, the entire colony converges on the optimal path through pure, decentralized feedbackImage generated by GeminiShifting the Paradigm: From Routing to GroupingThis elegant mechanism inspired computer scientist Marco Dorigo in 1992 [1] to develop the Ant Colony Optimization (ACO) algorithm. Originally, ACO was designed to solve routing benchmarks like the Traveling Salesman Problem (TSP), where artificial ants explore paths between nodes to find the shortest possible circuit.However, the power of the swarm doesn’t stop at drawing lines on a map. What happens when we apply this collective intelligence to a completely different class of computational headaches?While the TSP is a sequencing problem, many of our real-world bottlenecks are grouping problems. This brings us to the Bin Packing Problem (BPP): the challenge of packing a set of items with different weights into the minimum number of fixed-capacity containers. It is an NP-hard problem that underpins everything from industrial logistics and container shipping to cloud computing server allocation.Can a swarm of virtual ants learn how to pack boxes efficiently? Absolutely. But to do it, we have to completely change how our ants “talk” to each other through their environment.The Math Behind the Swarm: Adapting Pheromones to GroupingTo appreciate how an ant colony can pack containers, we first need to look at how they solve maps. In the classical TSP, an artificial ant k stands on a city i and decides which city j to visit next. This decision is guided by a precise probabilistic rule based on two factors: the intensity of the pheromone trail τ(i, j) between those cities, and a local heuristic η(i, j) (usually the inverse of the distance).The probability expression looks like this:Here, β controls how much the ants trust their immediate greediness versus the collective memory of the colony , while J_k(i) represents the cities left to visit. Once all ants finish their tours, the pheromones evaporate slightly (by a factor of ρ), and new trails are deposited based on the quality of the routes found.The Costa & Hertz Breakthrough: Pheromones as Grouping AffinityIf we map this directly to the Bin Packing Problem, it breaks. In BPP, we don’t care about the order in which items are packed; we care about which items share the same bin.This is where a clever adaptation originally proposed by Costa and Hertz (1997) [2] for graph coloring comes into play. They realized that instead of measuring the distance between two points, the pheromone trail τ(i, j) could encode the affinity between item sizes.In our BPP framework:τ(i,j) represents how favorable it is to place an item of size i and an item of size j inside the same container.The pheromone matrix becomes fully symmetric (τ(i, j) = τ(j, i)).This shift offers a massive computational advantage. In graph coloring or routing, every node is unique. But in the Bin Packing Problem, we frequently encounter multiple items with the exact same size or weight. By mapping the pheromone matrix to item sizes rather than individual item IDs, our matrix remains compact and encodes generalized packing patterns. Once the swarm discovers a highly efficient combination of weights, that pattern can be quickly replicated across completely different bins throughout the optimization process.Designing the Swarm: The Python ImplementationNow that we have established how to map the pheromone matrix to item sizes rather than routing nodes, it is time to translate this decentralized logic into clean, object-oriented Python code.Our architecture begins by modeling an individual agent within the colony: the Ant. In our simulation, each ant is responsible for constructing its own complete solution for the Bin Packing Problem by interacting with the shared pheromone matrix and applying a modified greedy heuristic.The Ant Class StructureThe initialization of our Ant class requires three key parameters: the total capacity of the containers, the current state of the pheromone matrix, and the parameter β, which weights the relative importance of our local heuristic.class Ant:def __init__(self, capacity, pheromone_matrix, beta): self.pheromone_matrix = pheromone_matrix self.capacity = capacity self.beta = betaThe Modified First Fit Decreasing (FFD) HeuristicIn standard deterministic approaches, the First Fit Decreasing (FFD) algorithm sorts all available items in descending order and places each item into the first bin where it can fit. However, to allow our virtual ants to build probabilistic solutions guided by pheromones, we must invert this procedure.According to [3], the ant selects a single container and keeps filling it by choosing among the remaining items that fit. If no more items can fit into that specific container, the ant seals it and opens a new one.To embed this behavior, we define the item size itself as our local heuristic function:This ensures that when an ant is choosing the next element to pack inside a partially filled bin, larger items will naturally be favored over smaller ones to optimize space utilization early on.Core Solution Construction LoopBelow is the foundational logic of the Build_Sol method inside our Ant class. This function takes the complete list of item weights, initializes an empty tracking list for the bins, and dynamically manages the remaining items until the entire workload is packed.def build_solution(self, item_weights): solution = [[]] # List of empty bins available_items = item_weights.copy() while available_items: current_bin = solution[-1] # Selects the active bin remaining_capacity = self.capacity - sum(current_bin) if remaining_capacity != 0: Jk = [] # List of viable candidates that fit in the current bin for item in available_items: weight_ratio = item / remaining_capacity if weight_ratio Jk.append(item) if not Jk: # If no single remaining item fits, open a new bin solution.append([]) else: # Probabilistic selection logic based on pheromones will take place here pass else: # Open a new bin immediately if the current one is exactly full solution.append([]) return solutionCalculating the Pheromone TrailTo make the probabilistic selection, the ant needs to know the pheromone valueτ_b(j)of an item j relative to a specific bin b. As defined in our mathematical framework, this is not just a single matrix lookup. It is the average of the pheromone values between the candidate item j and all the items i that are already packed inside the current bin b.If the bin is completely empty, the pheromone value defaults to 1. This logic is neatly captured in our auxiliary function:def calculate_pheromone(self, bin_items, candidate_item): # Tau_b(j): Average pheromone between candidate object and items in the bin pheromone = sum([self.pheromone_matrix[self.weight_index(i), self.weight_index(candidate_item)] for i in bin_items]) / len(bin_items) return pheromoneThe Probabilistic Selection EngineFinally, we arrive at the heart of the Ant Colony Optimization algorithm: the transition probability. When an ant has a list of viable candidate items (J) that can physically fit into the remaining space of the current bin, it doesn’t just pick the largest one. It calculates the probability of selecting each item based on our core equation:In Python, this translates to evaluating the numerator (the item’s specific pheromone-heuristic combination) against the denominator (the sum of those combinations for all viable items).def get_probability(self, candidate_item, current_bin, Jk_list): # If the bin is not empty, calculate using both Pheromone and Heuristic if candidate_item in Jk_list and len(current_bin) != 0: tau_bj = self.calculate_pheromone(current_bin, candidate_item) numerator = tau_bj * (candidate_item)**self.beta denominator = sum([self.calculate_pheromone(current_bin, item) * (item)**self.beta for item in Jk_list]) # If the bin is empty, rely solely on the Heuristic (Size) else: numerator = (candidate_item)**self.beta denominator = sum([(item)**self.beta for item in Jk_list]) return numerator / denominatorBy integrating this probability calculation into our Build_Sol loop, we allow the swarm to make weighted, pseudo-random decisions. The ants will generally favor larger items and combinations that have worked well in the past, but they will occasionally explore bizarre, low-probability combinations—which is exactly how better optimums are discovered.Wrapping Up Part 1 & What’s NextWe have successfully bridged the gap between biological swarm intelligence and discrete combinatorial optimization. By redefining the pheromone matrix to represent size affinity rather than physical distance, we empowered our virtual ants to tackle the Bin Packing Problem. We then translated the complex probabilistic math into an object-oriented Python structure.However, there is a hidden danger in the code we just built. Calculating these probabilities for every available item, in every bin, for every ant across dozens of generations is extremely computationally expensive.In Part 2 of this series, we will address this bottleneck. We will introduce a clever optimization technique — borrowing the concept of a Restricted Candidate List (RCL) from the GRASP metaheuristic — to slash execution times without crippling the swarm’s intelligence. We will also explore the critical Max-Min Ant System (MMAS) update strategy, balancing the fine line between exploration and exploitation to squeeze the best possible performance out of our colony.Stay tuned!References[1] Dorigo, M., Bonabeau, E., and Theraulaz, G. (2000). Ant algorithms and stigmergy. Future generation computer systems, 16(8), 851–871.[2] Costa, D., and Hertz, A. (1997). Ants can colour graphs. Journal of the operational research society, 48(3), 295–305.[3] Levine, J., and Ducatelle, F. (2004). Ant colony optimization and local search for bin packing and cutting stock problems. Journal of the Operational Research society, 55(7), 705–716.Swarm Intelligence: How Ant Colonies Can Solve the Bin Packing Problem (Part 1) was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.