Practical Python AI Projects: Mathematical Models of Optimization Problems with Google OR-Tools
Introduction 🚀
Artificial intelligence is often associated with neural networks, computer vision, and natural language processing. However, many engineering and business problems do not require a predictive model at all. Instead, they require a system that can choose the best possible decision from thousands or millions of alternatives.
This is where mathematical optimization becomes extremely powerful.
Imagine a logistics company with dozens of vehicles and hundreds of delivery locations. The company wants to determine which vehicle should visit each customer, in what order, and under which restrictions. Or consider a manufacturing plant that must assign workers to shifts while respecting working hours, machine availability, deadlines, and production priorities.
These are optimization problems. Python provides an accessible environment for building such decision systems, while Google OR-Tools provides specialized optimization technologies for routing, scheduling, assignment, packing, network flows, linear optimization, mixed-integer programming, and constraint programming.
The central idea is simple:
Data → Mathematical Model → Constraints → Optimization → Decision
This article explains how students, engineers, developers, and data professionals can use Python and OR-Tools to transform real-world engineering problems into practical optimization projects. 🐍⚙️
Background Theory 📚
Optimization belongs to the broader field of Operations Research (OR). Its purpose is to make better decisions when resources are limited and multiple possible solutions exist.
A typical optimization problem contains three fundamental components:
- Decision variables — what the algorithm is allowed to decide.
- Constraints — rules that every acceptable solution must obey.
- Objective function — what should be minimized or maximized.
Google’s OR-Tools documentation describes optimization in essentially these terms: an objective identifies what should be optimized, while constraints restrict the set of acceptable solutions.
Why Optimization Matters in Engineering
Engineering systems frequently contain competing requirements.
For example:
- Reduce transportation distance 🚚
- Minimize fuel consumption ⛽
- Increase production
- Respect machine capacity
- Meet customer deadlines
- Reduce employee overtime
- Maximize equipment utilization
- Maintain safety restrictions
A human may find a reasonable solution, but optimization software can systematically explore a much larger decision space.
Optimization Is Not the Same as Prediction
A machine-learning model might predict:
“Customer A will probably order 20 units tomorrow.”
An optimization model can then decide:
“Which warehouse should supply those units, which vehicle should deliver them, and in what sequence?”
This distinction is important.
Machine learning predicts. Optimization decides.
In modern AI systems, the two approaches can also work together. 🤖➕⚙️
Definition 🎯
Mathematical optimization is the process of finding the best feasible solution to a decision problem according to a defined objective and a collection of constraints.
Google OR-Tools is an open-source software suite designed for solving optimization problems. Its Python interface supports several important optimization technologies, including linear and mixed-integer optimization, CP-SAT constraint programming, routing, graph algorithms, and related methods.
What Is Google OR-Tools?
OR-Tools can be thought of as an optimization toolbox for Python.
Instead of manually developing a solver for every problem, a developer describes the problem and lets an appropriate OR-Tools solver search for a strong solution.
Typical applications include:
| Problem | Engineering Decision |
|---|---|
| Vehicle Routing | Which vehicle visits which customer? |
| Scheduling | When should each task be performed? |
| Assignment | Which worker receives which task? |
| Packing | Which items fit into available containers? |
| Network Flow | How should resources move through a network? |
| Production Planning | What should a factory produce? |
| Workforce Planning | How should shifts be assigned? |
OR-Tools officially provides examples covering assignment, packing, scheduling, routing, and network-flow problems.
Step-by-Step: Building an Optimization Project with Python 🐍⚙️
A practical OR-Tools project usually follows a structured workflow.
Step 1: Describe the Real Engineering Problem
Start with the business or engineering question.
For example:
“How can a delivery company serve all customers using the available vehicles while reducing total travel distance?”
Avoid starting with Python code.
First understand the decision.
Step 2: Identify the Decision Variables
Ask:
What exactly must the computer decide?
For routing, the decisions might include:
- Which vehicle serves each location
- Which location comes next
- Whether a vehicle returns to the depot
- How routes are distributed among vehicles
For scheduling, decisions might include:
- Which worker performs a task
- When a task starts
- Which machine processes it
Step 3: Identify the Constraints
Constraints represent reality.
Examples include:
- Vehicle capacity
- Maximum working hours
- Customer time windows
- Machine availability
- Employee availability
- Required task order
- Maximum travel distance
A solution that violates a critical constraint may be mathematically attractive but operationally useless.
Step 4: Define the Objective
Next, decide what “best” means.
Possible objectives include:
Minimize:
- Distance
- Cost
- Travel time
- Overtime
- Energy consumption
- Production waste
Maximize:
- Profit
- Production
- Customer coverage
- Resource utilization
- Service quality
Step 5: Select the OR-Tools Model
Different problems require different approaches.
For example:
- CP-SAT → scheduling, assignment, discrete decisions
- Routing solver → vehicle routing and related route problems
- Linear/MIP models → linear relationships and integer decisions
- Graph algorithms → flows and network problems
Step 6: Load the Data
Data may come from:
- CSV files
- Databases
- APIs
- Excel
- Sensors
- ERP systems
- GPS systems
For a routing project, the data could contain locations, vehicle capacities, customer demand, and travel information.
Step 7: Build the Model
The Python program creates variables, constraints, and objectives.
A simplified conceptual structure is:
from ortools.sat.python import cp_model
model = cp_model.CpModel()
🤖 # Create decision variables
# Add constraints
# Define objective
solver = cp_model.CpSolver()
status = solver.Solve(model)The important point is that the code is only the implementation. The mathematical model comes first.
Step 8: Solve and Evaluate
After solving, inspect:
- Solver status
- Objective value
- Constraint satisfaction
- Resource utilization
- Runtime
- Quality of the solution
For large routing problems, OR-Tools supports search limits so that the solver can stop after a specified amount of time or after reaching a solution limit.
Comparison: Traditional Programming vs Optimization vs Machine Learning 🔍
| Feature | Traditional Programming | Machine Learning | Mathematical Optimization |
|---|---|---|---|
| Main purpose | Execute known rules | Learn patterns | Select decisions |
| Input | Data + rules | Training data | Data + constraints |
| Output | Predetermined process | Prediction | Best feasible decision |
| Constraints | Manually coded | Usually indirect | Explicitly modeled |
| Example | Calculate invoice | Predict demand | Assign delivery routes |
| Explainability | Usually high | Varies | Often high |
| Best use | Deterministic processes | Prediction | Decision-making |
Optimization vs AI
Optimization is sometimes treated as separate from AI, but modern intelligent systems frequently combine both.
For example:
Forecasting model → predicted demand → OR-Tools optimizer → production schedule
The predictive model estimates what may happen.
The optimization model decides what to do.
That combination is particularly useful for engineering systems with changing demand.
Mathematical Models, Diagrams, and Practical Structure 🧩
A useful way to visualize an optimization system is:
REAL-WORLD PROBLEM
│
▼
INPUT DATA
│
┌──────────┴──────────┐
▼ ▼
DECISION VARIABLES CONSTRAINTS
│ │
└──────────┬──────────┘
▼
OBJECTIVE FUNCTION
│
▼
OR-TOOLS
SOLVER
│
▼
OPTIMIZED DECISION
│
▼
REAL-WORLD ACTIONExample Model Architecture
| Layer | Example |
|---|---|
| Input | Customer locations |
| Data processing | Distance information |
| Variables | Vehicle-route decisions |
| Constraints | Capacity and service limits |
| Objective | Minimize travel cost |
| Solver | OR-Tools |
| Output | Optimized routes |
The key engineering principle is separation of concerns.
Keep data preparation, mathematical modeling, solving, and result reporting as separate parts of the Python application.
Practical Examples 💡
Example 1: Delivery Route Optimization 🚚
A company has one warehouse, several delivery locations, and multiple trucks.
A basic routing model can determine:
- Which truck visits each customer
- The sequence of stops
- Whether capacity restrictions are respected
- The total travel cost
OR-Tools provides dedicated functionality for vehicle-routing problems and supports constraints such as travel limits.
Example 2: University Timetabling 🎓
A university needs to schedule:
- Lectures
- Professors
- Rooms
- Student groups
The model must avoid conflicts.
For example, one professor cannot teach two classes simultaneously, while a room cannot host multiple classes at the same time.
This becomes a constraint-programming problem.
Example 3: Factory Scheduling 🏭
A factory has several machines and production jobs.
Each job may require multiple processing stages.
The optimization model can determine an efficient schedule while respecting machine availability and task order.
OR-Tools includes scheduling examples using CP-SAT and interval-based modeling.
Example 4: Employee Assignment 👷
Suppose an engineering company needs to assign technicians to maintenance jobs.
The optimizer can consider:
- Technician availability
- Skills
- Job requirements
- Working hours
- Geographic location
- Priority
The output becomes a practical workforce plan.
Real-World Applications 🌍
OR-Tools-style optimization models can support many industries.
Logistics and Transportation
Optimization can improve:
- Delivery routes
- Fleet utilization
- Warehouse distribution
- Vehicle scheduling
- Last-mile delivery
Vehicle routing is particularly important because route combinations can become extremely large as the number of locations increases.
Manufacturing
Factories can use optimization for:
- Production scheduling
- Machine assignment
- Inventory decisions
- Job sequencing
- Resource allocation
Energy Engineering ⚡
Optimization can assist with:
- Energy dispatch
- Battery scheduling
- Load management
- Resource allocation
- Renewable-energy planning
Construction 🏗️
Potential applications include:
- Equipment allocation
- Workforce scheduling
- Project sequencing
- Material delivery planning
Healthcare 🏥
Optimization can support:
- Staff scheduling
- Operating-room planning
- Resource allocation
- Patient appointment scheduling
The model should always be validated against domain requirements, especially when decisions affect safety or critical services.
Common Mistakes ⚠️
Mistake 1: Starting With Code
Writing Python before understanding the optimization problem often produces complicated models.
Solution: Write the problem in plain English first.
Mistake 2: Missing Constraints
A model may produce an impressive-looking solution that cannot actually be used.
Solution: Build a complete constraint checklist before coding.
Mistake 3: Choosing the Wrong Solver
Not every optimization problem should be treated as a routing problem.
Solution: Identify the mathematical structure first.
Mistake 4: Using Poor Data
Incorrect distances, capacities, working hours, or demand values can produce incorrect decisions.
Solution: Validate input data before solving.
Mistake 5: Assuming “Optimal” Always Means “Practical”
A mathematically optimal solution may create operational difficulties.
For example, minimizing distance alone might produce undesirable workloads among drivers.
Solution: Model the actual business priorities.
Challenges & Solutions 🛠️
| Challenge | Practical Solution |
|---|---|
| Huge search space | Use heuristics and search limits |
| Slow solving | Simplify unnecessary constraints |
| No feasible solution | Check conflicting constraints |
| Poor data quality | Validate and clean inputs |
| Unbalanced workload | Add workload-related objectives |
| Changing demand | Re-run models periodically |
| Complex implementation | Separate data/model/solver layers |
Routing problems can become computationally demanding as the number of locations increases, which is why OR-Tools provides search-time and solution-count controls.
Case Study: Optimizing a Small Delivery Operation 🚚📦
Consider a fictional engineering-services company that delivers replacement components to customers.
The company has:
- One central depot
- Several delivery vehicles
- Multiple customer locations
- Different customer requirements
- Vehicle capacity restrictions
- A daily operating period
The existing process uses manually prepared routes.
Phase 1: Data Preparation
The engineering team collects:
- Customer locations
- Delivery requirements
- Vehicle capacities
- Travel information
- Service requirements
Phase 2: Model Design
The team defines:
Decision: Which vehicle serves each customer and in what order?
Constraints: Vehicle capacity, service requirements, and operating limits.
Objective: Reduce total travel cost while maintaining service requirements.
Phase 3: OR-Tools Implementation
The routing model uses OR-Tools to represent locations and vehicles and to search for an improved route configuration.
The OR-Tools routing examples follow this general architecture: create a routing index manager, create a routing model, register a cost callback, configure search parameters, solve, and inspect the resulting routes.
Phase 4: Operational Testing
The team does not immediately deploy the model.
Instead, it compares:
Existing routes
versus
Optimized routes
The engineers examine:
- Total distance
- Vehicle utilization
- Number of stops
- Service compliance
- Driver workload
- Solver runtime
Phase 5: Deployment
After validation, the optimization model can become part of a larger application:
Database
↓
Python Data Pipeline
↓
OR-Tools Optimization Model
↓
Optimized Routes
↓
Dashboard / Dispatch System
↓
DriversThis illustrates an important principle: optimization is not simply an algorithm; it is a decision-support component inside a larger engineering system.
Essential Tips for Python OR-Tools Projects ⭐
Start Small
Do not begin with 10,000 customers.
Start with:
- 5 locations
- 2 vehicles
- A few constraints
Then increase complexity.
Visualize the Result
For routing problems, plotting routes can reveal problems that numerical output does not make obvious.
A route that looks excellent numerically may cross itself unnecessarily or create an operationally awkward sequence.
Keep Units Consistent
Use consistent units for:
- Time
- Distance
- Capacity
- Cost
- Demand
Unit inconsistencies are a common source of modeling errors.
Separate Hard and Soft Constraints
A hard constraint must never be violated.
A soft constraint is desirable but may be relaxed at a cost.
This distinction allows models to represent real operational priorities more accurately.
Add Logging
For production systems, record:
- Input size
- Solver status
- Runtime
- Objective value
- Number of constraints
- Key solution statistics
This makes debugging and performance monitoring much easier.
Set Reasonable Time Limits
Large optimization problems may continue searching for improvements for a long time.
A practical application often needs a high-quality answer within a predictable period rather than waiting indefinitely for a mathematically proven optimum.
OR-Tools explicitly supports time limits and solution limits for routing searches.
FAQs ❓
What is Google OR-Tools used for?
Google OR-Tools is used to solve optimization problems such as routing, scheduling, assignment, packing, network flows, linear optimization, and constraint-based decision problems.
Is OR-Tools suitable for Python beginners?
Yes. Python provides a relatively accessible interface, although understanding optimization concepts such as variables, constraints, objectives, and feasibility is important.
Is OR-Tools machine learning?
Not in the conventional sense. OR-Tools is primarily an optimization toolkit. However, it can work alongside machine-learning models in AI systems.
What is CP-SAT?
CP-SAT is an OR-Tools solver designed for constraint programming and integer-based optimization problems. It is especially useful for problems involving discrete decisions, scheduling, assignments, and complex constraints.
Can OR-Tools optimize delivery routes?
Yes. OR-Tools provides a routing framework for problems involving vehicles, locations, costs, and routing constraints.
Can OR-Tools solve scheduling problems?
Yes. Scheduling is one of the major OR-Tools application areas, including problems involving jobs, machines, intervals, and timing restrictions.
Does OR-Tools always find the mathematically perfect solution?
Not necessarily in practical large-scale applications. Some problems have enormous search spaces, so engineers may impose time or solution limits and use high-quality feasible solutions rather than waiting indefinitely.
Should I learn mathematics before learning OR-Tools?
A strong understanding of basic concepts such as variables, constraints, objectives, graphs, and discrete decisions is extremely helpful. You do not need to become an advanced mathematician before starting practical projects.
Conclusion 🚀
Python + Google OR-Tools provides a powerful framework for turning engineering decisions into computational optimization problems.
The most important lesson is not a particular Python function or solver parameter. It is the ability to translate a real-world situation into a structured model:
Problem → Variables → Constraints → Objective → Solver → Decision
That approach can be applied to logistics 🚚, manufacturing 🏭, construction 🏗️, energy ⚡, workforce planning 👷, transportation, scheduling, and many other engineering domains.
For beginners, the best learning strategy is to start with small projects such as assignment and simple routing. As your understanding improves, introduce capacities, time windows, scheduling restrictions, multiple objectives, and real-world data.
For professionals, the next step is to treat optimization as an engineering system rather than a standalone script: validate data, test constraints, monitor solver performance, compare solutions with existing processes, and integrate the model into operational workflows.
Ultimately, optimization gives Python developers something extremely valuable: the ability not only to analyze what is happening, but to determine what should happen next. 🐍🤖⚙️
Technical reference: Google’s current OR-Tools Python documentation covers optimization modeling, routing, scheduling, network flows, and related solver technologies.




