I’ll solve an integer programming example using $Python$, showing the implementation, solution, and visualization.
Let’s solve a classic integer programming problem - the Knapsack Problem.
Integer Programming Example: Knapsack Problem
The knapsack problem is a classic optimization problem: Given a set of items, each with a weight and a value, determine which items to include in a collection so that the total weight is less than or equal to a given limit and the total value is maximized.
Mathematically, we can formulate this as:
$$\begin{align}
\text{Maximize} & \sum_{i=1}^{n} v_i x_i \
\text{Subject to} & \sum_{i=1}^{n} w_i x_i \leq W \
& x_i \in {0,1} \quad \forall i \in {1,2,\ldots,n}
\end{align}$$
Where:
- $v_i$ is the value of item $i$
- $w_i$ is the weight of item $i$
- $x_i$ is a binary variable indicating whether item $i$ is selected
- $W$ is the maximum weight capacity
Let’s implement this using $PuLP$, a popular linear programming library in $Python$:
1 | import numpy as np |
Code Explanation
Setting up the problem:
- We defined $10$ items with corresponding values and weights
- The knapsack capacity is set to $40$ units
Formulating the integer program with PuLP:
- Created binary decision variables for each item (
x
) - Set the objective function to maximize total value
- Added a constraint to ensure the total weight doesn’t exceed capacity
- Created binary decision variables for each item (
Solving the problem:
- $PuLP$ uses branch and bound algorithms to solve the integer program
- Results are extracted and organized into a pandas DataFrame
Visualization:
- Four plots are created to analyze different aspects of the solution:
- All items plotted by weight vs. value
- Selected vs. not selected items
- Value/weight efficiency ratio for each item
- Each selected item’s contribution to the total value
- Four plots are created to analyze different aspects of the solution:
Solution Analysis
When executed, this code will select the optimal combination of items that maximizes value while staying within the weight limit.
The optimization model makes trade-offs based on both the absolute value of items and their weight efficiency (value per unit weight).
Items with high values and relatively low weights are preferred.
The visualizations help us understand:
- The distribution of all items in the value-weight space
- Which items were selected by the optimizer
- The efficiency (value/weight) of each item
- How much each selected item contributes to the total solution value
This example demonstrates how integer programming can be applied to combinatorial optimization problems, finding the optimal solution among a finite but potentially very large set of possibilities.
Result
Status: Optimal Selected Items: Item Value Weight 0 Item_1 10 5 1 Item_4 31 16 2 Item_5 7 3 3 Item_8 22 11 4 Item_9 11 5 Total Value: 81 Total Weight: 40 Capacity: 40