typestar

Constrained optimization in Python

Bounds and constraints, and the linear-programming shortcut.

import numpy as np
from scipy import optimize

# minimize -(3x + 2y) subject to x + y <= 4 and x <= 3
result = optimize.minimize(
    lambda v: -(3 * v[0] + 2 * v[1]),
    x0=np.array([0.0, 0.0]),
    bounds=[(0, 3), (0, None)],
    constraints=[{"type": "ineq", "fun": lambda v: 4 - v[0] - v[1]}],
)
print(result.x.round(3), round(-result.fun, 3))

linear = optimize.linprog(c=[-3, -2], A_ub=[[1, 1]], b_ub=[4],
                          bounds=[(0, 3), (0, None)])
print(linear.x.round(3), round(-linear.fun, 3), linear.status)

How it works

  1. bounds is a list of (low, high) per variable.
  2. A constraint dict gives the type and the function.
  3. linprog is faster when everything is linear.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
487
Tokens
192
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 105 seconds.

Type this snippet

Step 2 of 4 in Optimization, step 11 of 23 in Scientific computing with SciPy.

← Previous Next →