TDS Archive

An archive of data science, data analytics, data engineering, machine learning, and artificial intelligence writing from the former Towards Data Science Medium publication.

Containers Loading Optimization with Python

How can we use heuristic algorithms to find the right strategy to load a maximum number of pallets in a sea container?

Samir Saci
TDS Archive
Published in
8 min readApr 23, 2021

--

A 3D rendering of two large shipping containers, one red and one green, with pallets stacked nearby. A red forklift is seen carrying a pallet toward one of the containers. This image visualizes the container loading process, with different pallet arrangements intended to maximize space utilization inside the sea containers. The scene demonstrates the need for optimization strategies to load a maximum number of pallets efficiently.Containers Loading Optimization with Python
Application of the 2D knapsack problem for pallet loading — (Image by Author)

Due to the container shortage during COVID, the price of a container from Shanghai to North Europe exploded from $4,000 to $12,000.

Therefore, optimizing container loading became a priority for any company importing goods from overseas via sea freight.

As a data scientist, how can you use Python support the reduction of sea freight costs?

Multiple heuristic algorithms could be adapted to this problem to develop a tool that operations would use.

In this article, we will use a Two-Dimensional adaptation of the knapsack problem to build optimal strategies for container loading with Python.

Summary
I. How to optimize container loading?
II. Two-dimensional knapsack problem applied to pallet loading
1. Two-Dimensional knapsack problem
2. Tentative 1: The Intuitive solution
3. Tentative 2: The Optimization Algorithm Result

III. Build the Model
1. Initialize the model and set parameters
2. Build your Optimization Model
3. Plot your result

IV. Conclusion
1. Generative AI: GPT for Supply Chain Optimization
2. Reduce the Environmental Impact of your Transportation
3. Do you want to generate animated graph of the solutions?

How to optimize container loading?

Scenario

You are a data scientist in the logistics department of an International Fashion Apparel Retailer.

The logistics manager wants to ship 200 containers from Yangshan Port (Shanghai, PRC) to Le Havre Port (Le Havre, France).

  • Retail value (USD): your goods’ retail value is 225,000$ per container
  • Profit Margin (%): based on pre-crisis shipping cost, your profit margin is 8.5%
  • Shipping Costs — Previous (%): 100 x 2,000 / 225,000 = 0.88 (%)
  • Shipping Costs — Current (%): 100 x 12,000 / 225,000 = 5.33 (%)

The finance team is putting huge pressure on Logistics Operations because 4.45 % of profit is lost because of shipping costs.

How can you support this effort of cost optimization?

As the manager has limited influence on the market price, her only solution is to improve your loading capacity to save space.

Let’s see how you can support her!

Parameters

She has received pallets from your plants and suppliers in China that are ready to be shipped to France.

You have two types of pallets:

  • European Pallets: Dimensions 80 (cm) x 120 (cm)
A standard EUR wooden pallet, used in logistics and shipping. It features a flat surface with spaced wooden slats for easy handling by forklifts. This pallet is typically used for transporting goods in warehouses and for optimizing container loading. Its dimensions are critical when calculating the maximum number of pallets that can fit into a container.
Example of European pallet-(Source: Rotom)
  • North American pallets: Dimensions 100 (cm) x 120 (cm)
A blue CHEP pallet, designed for use in logistics operations. It has a reinforced structure compared to a standard wooden pallet and features wide entry points for forklifts. CHEP pallets are widely used in global supply chains for loading and transporting goods, and their size and weight play a significant role in container loading optimization.
Example of North American pallet— (Source: Chep)

You can use two types of containers

  • Dry container 20': Inner Length (5,9 m), Inner Width (2,35 m), Inner Height (2,39 m)
  • Dry container 40': Inner Length (12,03 m), Inner Width (2,35 m), Inner Height (2,39 m)

What’s the difference? Their size 👇

A top-down 3D rendering of a sea container showing an optimized pallet loading arrangement. Inside the container, pallets are stacked in a grid-like fashion, with some areas densely packed and others left open. Several blue and white pallets are positioned outside the container, along with an open container door on the right. This visual highlights the complexity of container loading and the need for optimization to maximize space, minimize costs, and increase efficiency in shipping logistics.
20' and 40' containers at scale — (CAD by Author)

What are the constraints for loading?

Constraints

  • European pallets and American can be mixed
  • No Pallet Stacking (put a pallet above another pallet)
  • The loading strategy must be performed in real life (using a counter-balance truck)

Objective: Load a maximum number of pallets per container

Now that we have the constraints and the objective, we can tackle the optimization part.

If you prefer watching, have a look at the video version of this article

Two-dimensional knapsack problem applied to pallet loading

Two-Dimensional knapsack problem

Given a set of rectangular pieces and a rectangular container, the two-dimensional knapsack problem (2D-KP) consists of orthogonally packing a subset of the pieces within the container such that the sum of the values of the packed pieces is maximized.

Two diagrams (labeled a and b) visualizing the Two-Dimensional Knapsack Problem applied to pallet loading. Diagram (a) shows an intuitive packing arrangement with rectangular pieces arranged in a suboptimal way. Diagram (b) shows an optimized packing solution with better space utilization. Each piece is labeled with a number, representing different items to be packed. This illustrates how applying an optimization algorithm can yield a more efficient packing arrangement compared to the intuitive
Exact algorithms for the two-dimensional guillotine knapsack (Mohammad Dolatabadia, Andrea Lodi, Michele Monaci) — (Link)

Adapt it to our problem

If we consider that

  • Pallets cannot be stacked
  • Pallets have to be orthogonally packed to respect the loading constraints
  • Pallets Height is always lower than the internal height of your containers

We can transform our 3D problem into a 2D knapsack problem and apply this algorithm to find an optimal solution.

We need to load in a 40' Container

  • 20 European Pallets 80 x 120 (cm)
  • 4 North American Pallets 100 x 120 (cm)

How would we do without advanced tools?

Tentative 1: The Intuitive solution

A forklift driver tried to fit a maximum number of European pallets and find some space for the 4 North American Pallets.

A top-down 3D rendering of a sea container showing an optimized pallet loading arrangement. Inside the container, pallets are stacked in a grid-like fashion, with some areas densely packed and others left open. Several blue and white pallets are positioned outside the container, along with an open container door on the right. This visual highlights the complexity of container loading and the need for optimization to maximize space, minimize costs, and increase efficiency in shipping logistics.
Initial Solution — (Image by Author)

Results

  • 20/20 Euro Pallets loaded, 2/4 American pallets loaded.
  • You need another container for the two remaining pallets.

Can we do better with Python's support?

Tentative 2: The Optimization Algorithm Result

On the left, you can see the solution of the optimization algorithm.

Side-by-side 3D renderings of two sea containers showing the difference between an initial pallet packing solution (right) and an optimized solution (left). The left container is packed more efficiently with both European and North American pallets, while the right container leaves space unused. The blue pallets inside the containers represent a more optimized arrangement in the left solution, which results in higher space utilization.
Optimized Solution (Left) | Initial Solution (Right) — (Image by Author)

Results

  • 20/20 Euro Pallets loaded, 4/4 American pallets loaded.
  • You don’t need another container.

Conclusion

  • The optimized solution can fit 100% of pallets.
  • Our filling rate is increased, and pallets are more “packed”.

The solution is based on a non-intuitive placement that can only be found by trying many combinations.

In the next part, we’ll see how to implement a model to get this solution.

🏫 Discover 70+ case studies using data analytics for supply chain sustainability🌳and business optimization 🏪 in this: Cheat Sheet

Build your model

To keep this article concise, we will not build the algorithm from scratch.

There is a Python library called rectpack.

A grid visualization representing the output from the rectpack Python library. The image displays a set of blue rectangles packed within a square container, each rectangle representing a pallet in the loading optimization process. The goal of this image is to show how the algorithm efficiently arranges rectangular pallets to maximize space utilization in the container, simulating a 2D knapsack problem solution.
Example of results of rectpact library — (Source: Documentation)

Initialize the model and set parameters

  • bx, by: we add a 5 cm buffer on the x-axis and y-axis to ensure that we do not damage the pallets
  • bins20, bins40: container dimensions by type

Build your Optimization Model

  • bins: the list of available containers (e.g. bins = [bin20, bin40] means that you have one container 20' et one container 40')
  • all_rects: list of all rectangles that could be included in the bins with their coordinates ready to be plot
  • all_pals: the list of pallets that could be loaded in the containers listed in bins

Plot your result

  • color: black for 80x120, red for 100 x120
A 2D schematic showing the layout of pallets inside a container. The image uses dashed lines to outline the pallets, with black lines representing European pallets (80x120 cm) and red lines for North American pallets (100x120 cm). The layout illustrates how different pallet sizes are packed into the container, ensuring an optimal configuration for efficient space usage in the container loading process.
Example of output for 20 Euro pallets and 4 North American Pallets— (Image by Author)

Now, you have everything to share your loading plan with your forklift driver.

Conclusion

We increased the pallet loading rate in both examples vs. the intuitive approach.

This solution was based on a simple scenario of pallets that cannot be stacked.

  • What would the results be if we applied it to stackable pallets?
  • What would the results be if we applied it to bulk cartons?

These improvements would increase the filling rate of your containers and reduce your cost per carton shipped.

What about the environmental impact?

Reduce the Environmental Impact of Logistics

The demand for transparency in carbon emissions of transportation from investors and customers has grown over the years.

What impact this tool could have on the CO2 emissions?

Business intelligence and advanced analytics can help you track your transportation's CO2 emissions by mode, shipment, and period.

Formula using Emission Factor — (Image by Author)

You can then estimate the emissions reductions achieved with your optimization solution with simple formulas based on the

  • Weight of goods
  • Transportation distance and mode

For more details on how to measure it, 👇

A reader decided to take this prototype to another level and deploy it with a 3D interface.

Deploy in a Web Application

Nienke Pieters used the code shared in this article as a basis to build an application that provides this impressive 3D interface.

(Image by Nienke Pieters)

It has been deployed on the VIKTOR platforms, which enable any data scientist to deploy their model on the cloud with an easy-to-use UI.

For more information, you can check the GitHub repository: Nienke Pieters.

Add-on
I also deployed my applications for supply chain sustainability and ABC analysis on this platform:

We have an issue.

The charts presented as outputs do not provide any information on the order in which you load pallets.

Do you want to help the forklift drivers load the pallets in the right order?

Static Outputs of the loading plans — (Image by Author)

Generate Animated Graphs using Pillow.

My solution is to animate these graphs to show the order in which the pallets must be loaded.

With Python’s library Pillow, you can animate your graph like the one below.

Example of Graphs Animated with Pillow — (Image by Author)

This example shows dynamically the difference between two pathfinding algorithms.

If you want to apply this method to the graph generated for the loading plan, check the article linked below,

About Me

Let’s connect on Linkedin and Twitter. I am a Supply Chain Engineer who uses data analytics to improve logistics operations and reduce costs.

For consulting or advice on analytics and sustainable supply chain transformation, feel free to contact me via Logigreen Consulting.

If you are interested in Data Analytics and Supply Chain, look at my website.

💌 New articles straight in your inbox for free: Newsletter
📘 Your complete guide for Supply Chain Analytics: Analytics Cheat Sheet

References

  • Python 2D rectangle packing library (repack), GitHub Documentation, Link
TDS Archive
TDS Archive

Published in TDS Archive

An archive of data science, data analytics, data engineering, machine learning, and artificial intelligence writing from the former Towards Data Science Medium publication.

Samir Saci
Samir Saci

Written by Samir Saci

Top Supply Chain Analytics Writer — Case studies using Data Science for Supply Chain Sustainability 🌳 and Productivity: https://bit.ly/supply-chain-cheat

Responses (2)