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.

Raw Materials Optimization for Food Manufacturing with Python

Use linear programming to create an optimal recipe for a cheap meal bar that meets specific nutritional requirements.

Samir Saci
TDS Archive
Published in
7 min readMay 27, 2021

--

This image visualizes the process of raw materials optimization for creating a meal bar recipe using Python. Different ingredients — wheat, chicken, beef, and corn — flow into two recipe formulations. Recipe 1, in orange, results in a bar costing 125 units, providing 20g protein and 15g fat. Recipe 2, in blue, creates a bar costing 55 units with 12g protein and 24g fat. The optimization uses linear programming to balance costs and nutrition, creating an ideal recipe.
Optimize Recipe for Meal Bars Manufacturing — (Image by Author)

Ensuring that products are cost-effective and meet strict nutritional standards is a constant challenge in food manufacturing.

Creating a meal bar that satisfies budget constraints while providing essential nutrients requires carefully selecting raw materials.

This process involves balancing various factors, from ingredient cost to nutritional content, to achieve the desired outcome.

Can advanced tools like Python and linear programming simplify this complex task?

This article will explore how to leverage Python and linear programming to design an optimal recipe.

Summary
I. Optimize Raw Materials for Food Manufacturing with Python
II. Problem Statement for Raw Materials Optimization
1. Available Ingredients and Nutritional Requirements
2. Optimal Recipes for Meeting Nutritional Requirements
3. Using Data-Driven Models for Better Business Decisions
III. Building Your Raw Materials Optimization Model
1. Available Ingredients and Nutritional Requirements
2. Declare your variables and parameters for your model
3. Define the objective and add constraints
4. Solve your model and analyze the results
IV. Conclusions
1. Next Steps
2. Generative AI: GPT for Process Optimization

Optimize Raw Materials for Food Manufacturing with Python

As a data scientist, you need to support the R&D manager of a large food manufacturer.

She must design a recipe for a new cheap and healthy meal bar.

What do we want to achieve?

Meal bars must function as a meal rather than just a snack to fill in the cracks.

This image shows a “No Cow” protein bar in raspberry truffle flavor, emphasizing its high protein content (21g) and low sugar (1g) with the label “dairy-free.” The bar is designed to be a nutritious meal replacement, aligning with the article’s focus on optimizing meal bar recipes for health and cost efficiency. The clean, natural setting highlights the product’s appeal as a healthy, dairy-free option, while reflecting the goals of optimizing ingredients for dietary requirements.
Photo by Sproutified on Unsplash

We want to minimize the cost of production while respecting nutritional constraints.

Can we use analytics tools to automate the design of this recipe?

This is a Linear Programming problem statement with objectives and constraints.

This article will show how to build a model to design this optimal recipe.

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

Problem Statement: Raw Materials Optimization

Before moving to the model design, we must clearly state the problem.

The factory can source raw materials from multiple suppliers; our R&D manager has shortlisted seven ingredients.

Parameters: Ingredients and Nutritional Requirements

The seven available ingredients are

  • Meat: Chicken, Beef, Mutton
  • Non-Meat: Rice, Corn, Wheat bran, Peanuts

These ingredients have different nutrition facts (in grams) per gram

A table listing the nutritional composition of seven ingredients: Chicken, Beef, Mutton, Rice, Wheat bran, Corn, and Peanuts. Each ingredient’s values for protein, fat, fiber, salt, and sugar are measured in grams per gram of ingredient. Peanuts have the highest fat content (0.492 g), while rice has the lowest fat and protein. Beef has the highest protein (0.2 g). The table is used to evaluate the nutritional value for optimization purposes.
Nutrition fact for each ingredient — (Image by Author)

What about costs?

They have also different costs ($/gram)

A table listing the cost per gram in dollars for seven ingredients: Chicken, Beef, Mutton, Rice, Wheat bran, Corn, and Peanuts. Beef is the most expensive at $0.15/gram, followed by Chicken at $0.095/gram, and Rice is the cheapest at $0.002/gram. This table is used in the optimization model to calculate the cost of producing a meal bar that meets nutritional requirements while minimizing expenses.
Cost per gram for each ingredient — (Image by Author)

Let’s formulate the problem now.

Objective

Minimize the total cost per bar (Weight: 120g).

Constraints

Minimal values for protein and fibre

  • Protein: 20g
  • Fibre: 6g

Maximum values for fat, salt and sugar

  • Fat: 22g
  • Salt: 3g
  • Sugar: 30g

Simulate Scenarios with Linear Programming

Now that we have the objective and the constraints, we can test our optimization model with multiple scenarios.

What if we want to minimize the unit cost of production?

  • Scenario 1
Cost per Bar = 7.91 $Qty_Beef = 48.56 g
Qty_Chicken = 0.0 g
Qty_Corn = 0.0 g
Qty_Mutton = 0.0 g
Qty_Peanuts = 34.09 g
Qty_Rice = 0.0 g
Qty_Wheat_bran = 37.36 g

You only need to add beef, peanuts, and wheat bran for $7.91 per bar (120 g).

What is the main cost driver?

Beef drives the costs up to meet the protein constraint.

What if we reduce this constraint?

  • Scenario 2: reduce the protein level to 12 g
Cost per Bar = 0.78 $Status: Optimal
Qty_Beef = 0.0 g
Qty_Chicken = 0.0 g
Qty_Corn = 0.0 g
Qty_Mutton = 0.0 g
Qty_Peanuts = 43.15 g
Qty_Rice = 55.19 g
Qty_Wheat_bran = 21.66 g

Your bar is now purely vegan and relatively cheap.

However, the marketing did not validate this recipe.

They suggested keeping the same level of protein and reducing sugar.

Would it be more expensive?

  • Scenario 3: reduce the sugar to 20 g
Cost per Bar = 10.32 $Status: Optimal
Qty_Beef = 65.32 g
Qty_Chicken = 0.0 g
Qty_Corn = 0.0 g
Qty_Mutton = 0.0 g
Qty_Peanuts = 30.96 g
Qty_Rice = 0.0 g
Qty_Wheat_bran = 23.72 g

Yes.

You must use more meat to maintain protein consistency and ensure a low sugar level.

Therefore, you will see an increase in your cost per bar.

Using Data-Driven Models for Better Business Decisions

This simulation model shows how such tools can enhance strategic discussions and support data-driven decision-making.

As we will explore in the next section, complex simulations can be executed with a single click, enabling you to answer critical business questions with data.

Remember, figures never lie, but people do.

This kind of model can support any type of strategy discussion by comparing different scenarios using business KPIs.

This image shows a simplified representation of a the value chain from supplier to customer for a small business. It includes icons for each step: a supplier with a store, a freight plane and ship, a warehouse with storage boxes, a delivery truck, and two customer houses. The illustration visually describes the flow of goods from supplier to customer in a straightforward manner, representing a typical supply chain process.
Strategic Decisions for a Small Business — (Image by Author)

For example, I introduced a model designed to help a friend maximize its revenue in another article.

What is the best pricing approach to maximize profit?

He had harsh discussions with his business partner, who had different opinions on improving their pricing to increase sales.

This table presents different pricing strategies and growth scenarios for a business. The top section lists three pricing strategies based on carton/pallet quantities with variable percentage discounts (2.5% to 10%). The bottom section shows the corresponding yearly sales growth scenarios, from baseline to +200% growth, presented in pallets and boxes. It’s designed to help simulate and optimize pricing and sales projections based on business growth scenarios.
Simulation Scenarios — (Image by Author)

This model, developed with Python, can run multiple scenarios with different pricing strategies.

This led to a smoother decision-making process and facilitated the collaboration between associates.

For more details about it, 👇

Now that the value convinces you of this kind of model, let’s see how to build it.

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

Building Your Raw Materials Optimization Model

Pulp is a Python modelling framework for linear (LP) and Integer Programming (IP) problems.

It is very easy to use and can help you solve many problems.

How can we load the parameters?

Available Ingredients and Nutritional Requirements

You can also find these datasets in my GitHub repository.

Nutrition facts

Ingredients Costs

Let’s start by declaring the variables of the model.

Declare your variables and parameters for your model

  • LpMinimize: your objective is to minimize the cost of your bar
  • lowBound =0: you cannot have a negative value of ingredient quantity

We want to minimize the cost while respecting nutritional constraints.

Define the objective and add constraints

Solve your model and analyze the results

You have the entire workflow with the results printed in this script.

Find the complete code in this GitHub repository,

💡 Follow me on Medium for more articles related to 🏭 Supply Chain Analytics, 🌳 Sustainability and 🕜 Productivity.

Conclusions

This solution could be better; you can quickly improve it.

What if your customers want corn?

You can add corn to this recipe by constraining the minimum quantity of corn.

Do we have infinite possibilities?

Let us try to change the quantity from 120 g to 100 g. What is the result?

Cost per Bar = 11.08 $
Status: Infeasible
Qty_Beef = 71.27 g
Qty_Chicken = 0.0 g
Qty_Corn = 0.0 g
Qty_Mutton = 0.0 g
Qty_Peanuts = 30.26 g
Qty_Rice = 0.0 g
Qty_Wheat_bran = -1.53 g

For this combination of constraints, there is no optimal solution for a bar of 100g.

Have you heard about Generative AI?

Generative AI: Optimization Models x GPT

When I saw the trend of Generative AI with large language models (LLMs), I took the opportunity to experiment with their impact on user experience.

What’s more boring than a static dashboard?

My first exercise was designing a LangChain Agent powered by GPT and connected to a TMS to act as a Supply Chain Control Tower.

The process of data querying and analytics is presented here. It starts with a question, goes through AI-driven insights using multiple data processing nodes, accesses SQL databases for querying, and outputs actionable results through an AI agent. The illustration emphasizes the role of both SQL queries and AI in creating an informed decision-making process for optimizing supply chain operations.
Supply Chain Control Tower Agent with LangChain SQL Agent [Article Link] — (Image by Author)

This solution was quite satisfying as it could answer operational questions autonomously by querying a database and extracting the results.

User: What if we want a minimum of 10g of corn?
GPT: This increases the price by 15%.

This can be implemented with this model to improve the user experience.

Instead of relying on a data scientist, users can ask the agent to modify the model based on the scenario they want to test.

For more details on how to implement this kind of solution, 👇

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.

If you need consulting or advice on analytics and sustainable supply chain transformation, feel free to contact me through Logigreen Consulting.

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

References

  • Computational Infrastructure for Operations Research, Optimization with PuLP (Documentation), Link

--

--

No responses yet