Back to the blog

Optimization with Python (SciPy)

Solve a constrained optimization problem in Python using scipy.optimize.minimize. The classic example: find the point closest to the center \((5, 5)\) within a polygon defined by linear inequalities.

\[\begin{aligned} \text{Minimize: } \quad & f(x, y) = (x - 5)^2 + (y - 5)^2 \\[4pt] \text{Subject to: } \quad & x + y \le 8 \\ & -x + y \le 1 \\ & x - y \le 1 \\ & 2x + y \le 12 \\ & x \ge 0,\quad y \ge 0 \end{aligned}\]
import numpy as np
from scipy.optimize import minimize

# Objective Function
f = lambda x: (x[0] - 5)**2 + (x[1] - 5)**2

# Constraints
cons = [
    {'type': 'ineq', 'fun': lambda x: -x[0] - x[1] + 8},
    {'type': 'ineq', 'fun': lambda x:  x[0] - x[1] + 1},
    {'type': 'ineq', 'fun': lambda x: -x[0] + x[1] + 1},
    {'type': 'ineq', 'fun': lambda x: -2*x[0] - x[1] + 12},
]

# Bounds
bnds = ((0, None), (0, None))

# Starting point to find the minimum
x0 = np.array([1.0, 1.0])

# Minimize
result = minimize(f, x0, bounds=bnds, constraints=cons)

# Show the point that minimizes the Objective Function
print(f"The minimum point is: {result.x}")

Running this gives us:

The minimum point is: [4. 4.]

The optimum lies at the intersection of two active constraints (\(x + y = 8\) and \(2x + y = 12\)), which is the point in the feasible polygon closest to the center \((5, 5)\) of the quadratic objective.

Feasible region + objective contours

How to read the graph: the light blue region is the feasible space (all points satisfying the 6 constraints). The gray curves are isocontours of the objective function — concentric circles around \((5, 5)\). The solution is the point on the polygon that touches the smallest possible contour, marked with the red star.

Practical remarks:

  • scipy.optimize.minimize automatically converts all ineq inequalities to the format \(g(x) \ge 0\), which is why they appear negated in the code compared to the original statement.
  • For purely linear problems, scipy.optimize.linprog is more efficient; minimize with SLSQP is appropriate when the objective function is nonlinear (as here, where it is quadratic).
  • If the problem grows in dimension or has thousands of constraints, it is worth looking at cvxpy — it allows writing the model almost exactly as the mathematical statement.

Installation:

pip install numpy scipy
Back to the blog