Google OR-Tools
Here is a basic example of using $OR-Tools$ in $Python$ to solve a simple linear programming problem.
$OR-Tools$ is a powerful optimization library provided by Google, and it can be used to solve a wide range of problems, including linear programming, mixed-integer programming, constraint programming, and more.
Example: Linear Programming with OR-Tools
This example demonstrates solving a linear programming problem where we want to maximize the objective function $3x + 4y$ subject to some constraints.
1 | from ortools.linear_solver import pywraplp |
Explanation
- Solver: We create a solver instance using
pywraplp.Solver.CreateSolver('SCIP')
. $SCIP$ is a powerful mixed-integer programming solver, and $OR-Tools$ uses it as one of its backends. - Variables: We define two variables,
x
andy
, both with a lower bound of0
and an upper bound of infinity. - Constraints: We add three constraints:
- $(2x + 3y \leq 12)$
- $(4x + y \leq 14)$
- $(3x - y \geq 0)$
- Objective: We want to maximize the function $3x + 4y$.
- Solve: The solver solves the problem, and we check if an optimal solution was found.
- Result: If a solution is found, it prints the optimal objective value and the values of
x
andy
.
Output
1 | Solution: |
Let’s break down the result of the optimization problem using $OR-Tools$:
Objective Value:
- Objective value = 17.0: This is the maximum value of the objective function
3x + 4y
given the constraints.
The solver found that this is the highest value that can be achieved without violating any of the constraints.
Variable Values:
- x = 2.9999999999999996: This is the optimal value of the variable
x
that maximizes the objective function.
Due to floating-point precision in computational mathematics, this value is extremely close to 3 (but not exactly 3). - y = 2.0000000000000018: Similarly, this is the optimal value of the variable
y
. This value is extremely close to 2.
Interpretation:
Floating-Point Precision: The values
2.9999999999999996
forx
and2.0000000000000018
fory
are due to the way computers handle floating-point arithmetic. In practice, these values can be considered asx = 3
andy = 2
.Objective Function Calculation: Given the optimal values of
x
andy
, we can calculate the objective function:
$$
3x + 4y = 3(3) + 4(2) = 9 + 8 = 17
$$
This confirms that the objective value of17.0
is indeed the maximum value that can be achieved under the given constraints.
Summary:
The solver has determined that to achieve the maximum value of 17
for the objective function 3x + 4y
, the values of x
and y
should be approximately 3
and 2
, respectively.
The slight deviations from exact integers are due to the limitations of floating-point representation in computers.
Running the Code
To run this code, ensure you have installed the $OR-Tools$ package.
You can install it using pip:
1 | pip install ortools |
This example should give you a good starting point for working with $OR-Tools$ in $Python$.