Optimization with Constraints Using SciPy
Introduction to Optimization with Constraints
Welcome to the final lesson of the course: Optimization with Constraints. Building on your knowledge of function optimization using SciPy, we're now going to tackle optimization challenges that involve constraints, which are crucial for many real-world applications. Consider scenarios where resource limitations must be honored — this is where constrained optimization shines. By the end of this lesson, you'll be equipped to solve such problems using SciPy, enhancing your ability to model and solve complex problems.
Basics of Defining Constraints in Optimization
Before we dive into the code, let's revisit the concept of constraints. Constraints in optimization are conditions that the solution must satisfy. These can be of two types: inequality constraints, which specify that a certain expression should be greater than or equal to zero, and equality constraints, which specify that a certain expression should be exactly zero.
Let's use the following constraint for an example:
This constraint means that we are limited to the region under the line:

We will search for a solution only in the grey region, including the black line itself.
Defining Constraints
In SciPy, we define constraints using a dictionary format. Here's how you define an inequality constraint where the sum of variables x[0] and x[1] is less than or equal to 1:
In this constraint dictionary, 'type' signifies the kind of constraint ('ineq' for inequality), while 'fun' provides the function definition for the constraint. The lambda function returns a positive value when x[0] + x[1] is less than or equal to 1, which ensures the constraint is met.
Formulating and Solving a Constrained Optimization Problem
Now that we understand constraints, let's formulate and solve a constrained optimization problem using SciPy. Below is a complete code snippet that includes defining the objective function, setting an initial guess, defining constraints, and solving the problem using SciPy's minimize function.
Explanation:
-
Objective Function: The function
f(x)is defined to be minimized. It is a quadratic function of two variables. -
Initial Guess: We start the optimization process with an initial guess of
[1, 1]. -
Define Constraints: The constraint
x[0] + x[1] <= 1is defined using a dictionary format, specifying it as an inequality constraint. -
Solving with SciPy's
minimize: Theminimizefunction is used to find the values ofxthat minimize the objective function while satisfying the constraints. The result is stored inresult_constraints, and the optimal solution and its corresponding function value are printed.


