SciPy Constrained Optimization
Real problems come with rules. A diet must meet nutrient minimums, an investment portfolio must add up to 100%, a part must fit inside a box. The Optimizers lesson minimized functions freely; this lesson shows how to tell scipy.optimize.minimize() about bounds and constraints.
| Kind of restriction | Example | How to pass it |
|---|---|---|
| Bounds | 0 ≤ x ≤ 10 | bounds=[(0, 10), ...] |
| Inequality constraint | x + y ≤ 4 | {"type": "ineq", "fun": lambda p: 4 - p[0] - p[1]} |
| Equality constraint | x + y = 1 | {"type": "eq", "fun": lambda p: p[0] + p[1] - 1} |
| Linear constraints | lb ≤ A x ≤ ub | LinearConstraint(A, lb, ub) |
| Non-linear constraints | lb ≤ g(x) ≤ ub | NonlinearConstraint(g, lb, ub) |
In the dictionary style, an "ineq" function must be ≥ 0 when the constraint is satisfied, and an "eq" function must be = 0.
Bounds only
Simple box limits are handled by L-BFGS-B, Powell, TNC and others. Here the free minimum would be at (3, −1), but the bounds forbid negative y:
import numpy as np
from scipy.optimize import minimize
def f(p):
x, y = p
return (x - 3) ** 2 + (y + 1) ** 2
free = minimize(f, x0=[0, 0])
boxed = minimize(f, x0=[1, 1], bounds=[(0, 2), (0, 5)], method="L-BFGS-B")
print("free :", np.round(free.x, 4) + 0.0)
print("bounded:", np.round(boxed.x, 4) + 0.0, " f =", round(boxed.fun, 4))free : [ 3. -1.]
bounded: [2. 0.] f = 2.0
With the box 0 ≤ x ≤ 2, 0 ≤ y ≤ 5, the best point lies on the corner (2, 0) of the allowed region.
Equality and inequality constraints with SLSQP
A farmer has 100 m of fencing for a rectangular pen along a river (no fence needed on the river side). Maximize the area x·y subject to 2x + y = 100:
from scipy.optimize import minimize
def neg_area(p):
x, y = p
return -x * y
fence = {"type": "eq", "fun": lambda p: 2 * p[0] + p[1] - 100}
res = minimize(neg_area, x0=[10, 10], method="SLSQP", constraints=[fence],
bounds=[(0, None), (0, None)])
x, y = res.x
print(f"sides: x = {x:.3f} m, y = {y:.3f} m")
print(f"area : {-res.fun:.1f} m^2")
print(f"fence used: {2 * x + y:.3f} m")sides: x = 25.000 m, y = 50.000 m
area : 1250.0 m^2
fence used: 100.000 m
Now an inequality: we want the point on the line y = 2x that is closest to (4, 1), but it must also satisfy x ≤ 1:
import numpy as np
from scipy.optimize import minimize
def dist2(p):
return (p[0] - 4) ** 2 + (p[1] - 1) ** 2
constraints = [
{"type": "eq", "fun": lambda p: p[1] - 2 * p[0]}, # on the line y = 2x
{"type": "ineq", "fun": lambda p: 1 - p[0]}, # x <= 1 -> 1 - x >= 0
]
only_line = minimize(dist2, [0, 0], method="SLSQP", constraints=constraints[:1])
both = minimize(dist2, [0, 0], method="SLSQP", constraints=constraints)
print("line only :", np.round(only_line.x, 4))
print("line and x<=1 :", np.round(both.x, 4))line only : [1.2 2.4]
line and x<=1 : [1. 2.]
Portfolio allocation
A classic finance problem: split money between three assets to minimize risk (variance) while reaching a target expected return. The weights must add to 1 and can't be negative. LinearConstraint expresses linear rules compactly as lb ≤ A @ w ≤ ub:
import numpy as np
from scipy.optimize import minimize, LinearConstraint
expected = np.array([0.04, 0.07, 0.11]) # yearly returns
cov = np.array([[0.0025, 0.0010, 0.0005],
[0.0010, 0.0100, 0.0040],
[0.0005, 0.0040, 0.0400]])
def risk(w):
return w @ cov @ w
rules = LinearConstraint(np.vstack([np.ones(3), expected]),
lb=[1.0, 0.07], # weights sum to 1, return >= 7%
ub=[1.0, np.inf])
res = minimize(risk, x0=np.full(3, 1 / 3), method="trust-constr",
constraints=[rules], bounds=[(0, 1)] * 3)
w = res.x
print("weights :", np.round(w, 3))
print(f"expected return : {w @ expected:.2%}")
print(f"risk (std. dev.) : {np.sqrt(risk(w)):.2%}")weights : [0.318 0.442 0.239]
expected return : 7.00%
risk (std. dev.) : 7.55%
Non-linear constraints
NonlinearConstraint(fun, lb, ub) restricts any function of the variables. Find the largest-volume box (with a lid) whose surface area is at most 600 cm²:
import numpy as np
from scipy.optimize import minimize, NonlinearConstraint
def neg_volume(d):
return -np.prod(d)
def surface(d):
l, w, h = d
return 2 * (l * w + l * h + w * h)
limit = NonlinearConstraint(surface, -np.inf, 600)
res = minimize(neg_volume, x0=[5, 5, 5], method="SLSQP", constraints=[limit],
bounds=[(0.1, None)] * 3)
print("dimensions:", np.round(res.x, 3))
print(f"volume : {-res.fun:.1f} cm^3")
print(f"surface : {surface(res.x):.1f} cm^2")dimensions: [10. 10. 10.]
volume : 1000.0 cm^3
surface : 600.0 cm^2
The answer is a cube with side 10 cm, as symmetry suggests.
Tip: Check constraint values at the solution (as we did with the fence and the surface) — they should be exactly at the limit when the constraint is active. If they're violated, look at
res.message; a bad starting point or inconsistent constraints are the usual causes.
Test yourself
In the dictionary style, what must an 'ineq' constraint function return for a valid point?
- A negative number
- Zero exactly
- A value ≥ 0
- True
How do you express the constraint x ≤ 5 as an 'ineq' dictionary?
- lambda p: p[0] - 5
- lambda p: 5 - p[0]
- lambda p: p[0] <= 5
- lambda p: p[0] == 5
Which methods support general equality and inequality constraints?
- Nelder-Mead and Powell
- BFGS only
- SLSQP and trust-constr (and COBYLA for inequalities)
- Every method