
The master production schedule is the primary communication tool between the commercial team and production.
Production planning is a critical process for any Manufacturing operation, but balancing the competing priorities of minimizing inventory costs and maximizing production efficiency can be challenging.
As a data scientist, how can you support your planning team to plan production batches?
This is a powerful tool for supply chain professionals because it can find the optimal balance between inventory and production costs.
In this article, we will discover how to use the Wagner-Whitin algorithm with Python to minimize the total cost of production.
Summary
I. How to plan your production with Python?
1. Scenario
2. Setup vs. Inventory Costs
II. Implementation
The algorithm has been deployed a web application ready to be used
III. Solution
1. Assumptions
2. Wagner-Whitin Algorithm
3. Backward Calculation
IV. Results & Conclusion
1. Forward Calculation
2. Backward Calculation
3. Final Solution
4. Implementation with Python
V. Next Steps
1. Generative AI: GPT for Supply Chain Optimization
2. Include your Algorithm in a Digital Twin
3. Production Lines Scheduling
How do you plan your production with Python?
Scenario
As a data scientist, you support a production planning manager in a small factory that produces radio equipment for local and international markets.
Customers send purchase orders (PO) with quantities and expected delivery dates to your commercial team.

Your role is to schedule production to deliver on time with a minimum total cost of production that includes
- Setup Costs: fixed costs you have each time you set up a production line
- Production Costs: variable costs per unit produced
- Holding Costs: cost of storage per unit per time
In our example, the customer ordered products for the next 12 months

What do we have to consider in the balance?
Setup vs. Inventory Costs
The main challenges for you are
- Reducing the average inventory on hand to minimize storage costs
- Minimize the number of production setups

However, these two constraints are antagonistic.
Therefore, you need help finding an intuitive way to build an optimal plan.
Example 1: Minimize Inventory

In this example, you produce the exact demand quantity each month
- Pros: No excess inventory
- Cons: You get production set up for each month with a positive demand
Example 2: Minimize the number of production setups

In this example, you build stock to minimize the number of setups
- Pros: only two production setups for the whole period
- Cons: a large stock on hand that increases the inventory costs
Conclusion
It would be best to have an optimization algorithm to balance the two constraints.
Solution
Assumptions
Suppose you receive a purchase order for the next 12 months with the quantities presented in the chart above.
- Set up cost: 500 $
- Holding cost: 1 $/unit/month
- Production cost per unit: 50 $/unit
- Units produced month m can be shipped the same month
- Inventory costs are charged from the month m+1
Have you heard about the economic order quantity?
Wagner-Whitin Algorithm
This problem can be seen as a generalization of the economic order quantity model that considers that demand for the product varies over time.
Wagner and Whitin developed an algorithm for finding the optimal solution by dynamic programming.
What’s the principle?
The idea is to understand each month whether adding the current month’s demand quantity to past months’ orders is more economical than setting up a new production cycle.
It starts with forward calculation …
Forward Calculation
Start at period 1:
- Calculate the total cost to satisfy the demand of month 1, D(1)
Period N:
- Calculate the total cost to satisfy the demand of month t, D(t)
- Look at all past orders (t=1 .. N) and find the cost for ordering for D(t) by adding the quantity to past orders D(t-1)
- Take the most economical option and go to t = N+1

And to finish …
Backward Calculation
Start from period t = N and work backwards to find the lowest options to satisfy the demand of each D(t).
Let’s see how it looks like with an actual example.
Results & Conclusion
Forward Calculation
You should export the results of the forward calculation using a table like the one below:

Let me take a few examples:
Period 1, if you produce for the
- First month demand only (D(1) = 200 units): 500$
- Two first months (D(1) + D(2) = 350 units): 650$
Now, let’s finish with the backward calculation.
Backward Calculation
We can use the table above to resolve the algorithm visually using the rules explained before.

-
Start with t = 12 The cheapest solution is to produce the month 11 for D(11) + D(12)
-
Continue with t = 10 The cheapest solution is to produce the month 9 for D(9) + D(10)
-
Continue with t = 8 The cheapest solution is to produce the month 6 for D(6) + D(7) + D(8)
-
Continue with t = 6 The cheapest solution is to produce the month 1 for D(1) + D(2) + D(3) + D(4) + D(5) + D(6)
What’s the result?
Final Solution
- Month 1: Produce 550 units to meet the demand of the first five months
- Month 6: Produce 450 units for months 6, 7 and 8
- Month 9: Produce 450 units for months 9 and 10
- Month 11: Produce 550 for months 11 and 12
Inventory Optimization
The chart below shows the inventory on hand (IOH) can be way higher than the demand forecast.

This shows no balance between setup and inventory impacts on the overall costs.
That means keeping a high inventory is way cheaper than multiplying the number of setups.
If the holding costs were higher, you would likely see an IOH closer to the forecasts and more production months.
A great balance between inventory and set-up costs.
In the chart below, you can follow the cumulative holding and set-up costs over the 12 months:

The algorithm balances inventory optimization and reduces the number of setups, as the cumulative value of holding and set-up costs is nearly equal.
What does that mean?
That means,
- If holding costs per unit are very high, the algorithm will increase the number of setups to minimize inventory.
- If you have very high costs per setup, the algorithm will tend more to build inventory in a minimum number of setup costs.
Great! Now how can we implement it with Python?
Implementation with Python
In the GitHub repository, you can find an implementation of this method from scratch using Python.
This method, which uses pandas functions to manipulate data frames, is easy to implement and works well for small datasets.
Forward calculation
# Create columns
data_calc = data.copy()
for i in data_calc['period'].unique():
data_calc['Order {}'.format(i)] = 0
# costs
set_up = 500
holding = 1
# Order 1
order = 1
for index, row in data_calc.iterrows():
current_month = data_calc.loc[index,'period']
cost = 0
# 1 set up
cost += set_up
if current_month > 1:
for t in range(1, current_month+1):
cost += (t-1) * data_calc.loc[t-1,'forecast'] * holding
data_calc.loc[index,'Order {}'.format(order)] = cost
# Order 2
for order in range(2, 13):
for index, row in data_calc.iterrows():
current_month = data_calc.loc[index,'period']
if current_month >= order:
cost = 0
# Best option best Period 1
values = list(data_calc.loc[order-2,
['Order {}'.format(i) for i in range(1, order+1)]].values)
best = min([i for i in values if i >0])
# Add
cost += best + set_up
for t in range(order, current_month+1):
cost += (t-order) * data_calc.loc[t-1,'forecast'] * holding
data_calc.loc[index,'Order {}'.format(order)] = cost
data_calc = data_calc.set_index('period').drop(['forecast'], axis = 1).T
data_calc
As the first month does not have previous orders, I have separated it from the others.
Backward Calculation
costs, initials, nexts, quantities = [], [], [], []
i = 12
while i>1:
# Order with the minimum cost
initial_step = i
next_step = data_calc[data_calc[i]>0][i].idxmin()
cost = data_calc[data_calc[i]>0][i].min()
# Next Step
next_id = int(next_step.replace('Order ',''))
i = next_id - 1
# Quantity
quantity = data[data['period'].isin(range(next_id, initial_step+1))]['forecast'].sum()
costs.append(cost)
initials.append(initial_step)
nexts.append(next_id)
quantities.append(quantity)
df_results = pd.DataFrame({'backward':range(1, len(initials)+1),
'initial':initials,
'nexts':nexts,
'cost':costs,
'quantity':quantities}).set_index('backward')
print("Total Cost: {:,}$".format(df_results.cost.sum()))
df_results
- Start from the last month and move backwards
- Do not forget to capture the costs for output analysis
You can find the source code with dummy data here, 👇
GitHub – samirsaci/production-planning: Production Fixed Horizon Planning with Python
Do you want to test it without running the code?
Implementation
I have implemented this solution on a web application deployed using the VIKTOR platform.
You can use it with your dataset,
![Production Planning Optimization App [Link]](https://towardsdatascience.com/wp-content/uploads/2022/09/1x1OB-QpvUiOWGgDTVHrxqg.gif)
- Upload your dataset (or use the sample data already loaded)
- Select the parameters
- Run the optimization
- Visualize the results
Try it!
Have a look here,

If you prefer to watch, have a look at the video version of this tutorial
Next Steps
The example used today is from a macro angle.
We see the factory as a black box with a production capacity, an inventory level and fixed or variable costs.
What if we look at a higher granularity?
Production scheduling can help you increase this production capacity using linear programming with Python.

The Job Shop Scheduling Problem (JSSP) is an NP-hard problem defined by a set of jobs that machines must execute in a specific order for each job.

As your solution may require high production peaks, use linear programming to schedule the jobs to produce more units per hour with the same equipment and resources.
For more details,
Supply Chain Process Scheduling with Python
Have you heard about Generative AI?
Generative AI: GPT for Process Optimization
Following the adoption of large language models (LLMs), I started experimenting with designing a LangChain Agent connected to a TMS.
![Supply Chain Control Tower Agent with LangChain SQL Agent [Article Link] - (Image by Author)](https://towardsdatascience.com/wp-content/uploads/2022/09/0r_ZlgoN4zmfBuRF-.png)
The outputs are pretty impressive, as the GPT-powered agent can answer operational questions by autonomously querying a database of delivery shipments.

What if we create a Process Optimization super agent?
My strategy is to deploy GPTs equipped with
- Python Scripts of Lean Six Sigma Tools, Workforce Planning and Process Scheduling and Planning
- Context, articles and knowledge about warehousing and transportation processes
The target is to help continuous improvement engineers with an agent equipped with different analytics tools, data upload capacity and LLM intelligence.
For more information,
Create GPTs to Automate Supply Chain Analytics
Leveraging LLMs with LangChain for Supply Chain Analytics – A Control Tower Powered by GPT
Do you want to simulate the impact of your solution on the whole supply chain?
Include your Algorithm in a Digital Twin
A digital twin is a digital replica of a physical object or system.
A Supply Chain digital twin is a computer model representing various components and processes involved in the supply chain, such as warehouses, transportation networks, and production facilities.

Your core model will include a sub-model to simulate the behaviour of your factory.
- Input Data: Production planning with expected production quantity and delivery date
- Output data: Actual production quantity and delivery date
The algorithm developed in this article can be integrated into the digital twin to link your stores and the factory
- Stores’ output will provide historical sales data to forecast future demand: algorithm input
- The factory’s input will take the planning generated by the Wagner-Within algorithm as the quantity to produce per period
You can then easily simulate the impact of several planning algorithms on the inventory level in your warehouse, total production and delivery costs, or utilization rates of production lines.
For more details,
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