Formulating and visualizing optimization problems with SciPy
Environment
Python 3.14.6, NumPy 2.5.4, SciPy 1.18.1, Matplotlib 3.11.2 (Jupyter Notebook).
This article is a rewrite of a post from around 2021, with calculations performed in the environment described above.
Overview
We translate a constrained quadratic minimization problem in two variables from equations into SciPy inputs. After implementing the objective and gradient, we plot the feasible region, iterates, and constraint residuals. Comparison with an analytical solution detects implementation errors that a solver’s success message alone may miss.
This article corresponds to Chapter 1, “Fundamentals of mathematical optimization,” in Theory and Practice of Mathematical Optimization.
Setup
Run the cells from top to bottom. Round numbers to three significant digits only for display.
Check versions, import libraries, and configure plots
import platform
from pathlib import Path
from pprint import pprint
import numpy as np
import scipy
from scipy import optimize
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import font_manager, ticker
from IPython.display import display, Math, SVG
# 計算値は丸めず、表示するときだけ有効数字3桁にそろえる。
def sig3(value):
return f"{float(value):#.3g}"
np.set_printoptions(formatter={"float_kind": sig3})
available = {font.name for font in font_manager.fontManager.ttflist}
font = next((name for name in ["Hiragino Sans", "Noto Sans CJK JP",
"IPAexGothic"] if name in available), "DejaVu Sans")
plt.rcParams.update({"font.family": [font, "DejaVu Sans"], "font.size": 11,
"axes.unicode_minus": False, "svg.fonttype": "path"})
OUT = Path("103_nb_files")
OUT.mkdir(exist_ok=True)
def save_svg(fig, name):
"""SVGを保存し、同じ画像をノートブックの出力欄に表示する。"""
for ax in fig.axes:
for axis in (ax.xaxis, ax.yaxis):
if isinstance(axis.get_major_formatter(),
(ticker.ScalarFormatter, ticker.LogFormatter)):
axis.set_major_formatter(ticker.FuncFormatter(lambda x, _: sig3(x)))
path = OUT / f"103_{name}.svg"
fig.savefig(path, format="svg", bbox_inches="tight", metadata={"Date": None})
display(SVG(filename=str(path)))
plt.close(fig)
print("実行環境: wa-src(3.14.6)")
print(f"Python: {platform.python_version()}")
pprint({"NumPy": np.__version__, "SciPy": scipy.__version__,
"Matplotlib": matplotlib.__version__})
実行環境: wa-src(3.14.6)
Python: 3.14.6
{'Matplotlib': '3.11.2', 'NumPy': '2.5.4', 'SciPy': '1.18.1'}
1. Define the equations first
Let the two allocation quantities be $x_1,x_2$, with target $(2,1)$. Weight the squared deviation of the second component twice as heavily as that of the first, and limit the total allocation to 2.
$$ \begin{aligned} \min_{\mathbf{x}}\quad & f(\mathbf{x})=(x_1-2)^2+2(x_2-1)^2,\\ \text{subject to}\quad & x_1+x_2\le2,\quad x_1\ge0,\quad x_2\ge0. \end{aligned} $$
The objective returns one real number, while the gradient returns an array with the same length as the variable vector. Taking the partial derivatives gives:
$$ \begin{aligned} \frac{\partial f}{\partial x_1}&=2(x_1-2),\\ \frac{\partial f}{\partial x_2}&=2\times2(x_2-1)=4(x_2-1),\\ \nabla f(\mathbf{x})&= \begin{bmatrix}2(x_1-2)\\4(x_2-1)\end{bmatrix}. \end{aligned} $$
LinearConstraint represents the lower bound $\mathbf{l}\le\mathbf{A}\mathbf{x}$ and upper bound $\mathbf{A}\mathbf{x}\le\mathbf{u}$ together. Here $\mathbf{A}=[1\ 1]$, the lower bound is $-\infty$, and the upper bound is 2. Specify nonnegativity separately with Bounds.
def objective(x):
return (x[0] - 2) ** 2 + 2 * (x[1] - 1) ** 2
def gradient(x):
return np.array([2 * (x[0] - 2), 4 * (x[1] - 1)])
# 解析勾配を中心差分と照合する。差分は検査のためにだけ使う。
probe = np.array([0.700, 0.400])
step = 1.00e-5
basis = np.eye(2)
finite_difference = np.array([
(objective(probe + step * e) - objective(probe - step * e)) / (2 * step)
for e in basis
])
pprint({"解析勾配": gradient(probe), "中心差分": finite_difference})
assert np.allclose(gradient(probe), finite_difference, atol=1.00e-8)
x0 = np.array([0.200, 0.200])
history = [x0.copy()]
constraint = optimize.LinearConstraint([[1, 1]], -np.inf, 2)
bounds = optimize.Bounds([0, 0], [np.inf, np.inf])
result = optimize.minimize(
objective, x0, jac=gradient, method="SLSQP", bounds=bounds,
constraints=[constraint], callback=lambda x: history.append(x.copy()),
options={"ftol": 1.00e-12, "maxiter": 100},
)
assert result.success, result.message
pprint({"解": result.x, "目的関数値": sig3(result.fun),
"反復回数": result.nit, "終了理由": result.message})
{'中心差分': array([-2.60, -2.40]), '解析勾配': array([-2.60, -2.40])}
{'反復回数': 3,
'目的関数値': '0.667',
'終了理由': 'Optimization terminated successfully',
'解': array([1.33, 0.667])}
2. Use a hand calculation as a reference
Without constraints, $(2,1)$ gives $f=0$, but this point exceeds the total limit. Substitute the boundary relation $x_2=2-x_1$ into the objective.
$$ \begin{aligned} \phi(x_1) &=(x_1-2)^2+2(1-x_1)^2\\ &=(x_1^2-4x_1+4)+(2x_1^2-4x_1+2)\\ &=3x_1^2-8x_1+6,\\ \phi^{\prime}(x_1)&=6x_1-8=0. \end{aligned} $$
Thus $x_1=4/3$, $x_2=2/3$, and $f=4/9+2/9=2/3$. We can also prove optimality over the entire region, not just the boundary. Setting $\mathbf{d}=\mathbf{x}-\mathbf{x}^{\star}$ and expanding the quadratic gives:
$$ \begin{aligned} f(\mathbf{x})-f(\mathbf{x}^{\star}) &=\nabla f(\mathbf{x}^{\star})^{\mathsf T}\mathbf{d} +d_1^2+2d_2^2\\ &=-\frac{4}{3}(x_1+x_2-2)+d_1^2+2d_2^2\ge0. \end{aligned} $$
At feasible points, $x_1+x_2-2\le0$, so all three terms are nonnegative. Equality holds only at $\mathbf{x}^{\star}$.
exact = np.array([4 / 3, 2 / 3])
assert np.allclose(result.x, exact, atol=1.00e-7)
assert np.isclose(result.fun, 2 / 3)
u, v = np.meshgrid(np.linspace(0, 2.50, 180), np.linspace(0, 2.20, 180))
z = (u - 2) ** 2 + 2 * (v - 1) ** 2
path = np.asarray(history)
fig, ax = plt.subplots(figsize=(6, 4.20), layout="constrained")
contours = ax.contour(u, v, z, levels=[2 / 3, 1, 2, 4, 6])
ax.clabel(contours, fmt=lambda value: sig3(value))
ax.fill([0, 2, 0], [0, 0, 2], color="steelblue", alpha=0.120)
ax.plot(path[:, 0], path[:, 1], "o-", label="SLSQPの反復点")
ax.scatter(*exact, marker="*", s=170, color="crimson", label="解析解")
ax.scatter(2, 1, marker="x", color="black", label="制約なしの最小点")
ax.set(xlabel="$x_1$", ylabel="$x_2$", title="図1:等高線・制約・反復点")
ax.legend(fontsize=9)
save_svg(fig, "01_solution_path")
$$ \displaystyle \mathbf{x}^{\star}=\begin{bmatrix}4/3\\2/3\end{bmatrix},\quad f^{\star}=2/3 $$
3. Define what counts as success
Check feasibility using the upper-constraint slack $2-x_1-x_2$ and the lower-bound slacks $x_1,x_2$. A negative slack beyond the numerical tolerance indicates a constraint violation.
A constrained solution need not satisfy $\nabla f=\mathbf{0}$. Here $\nabla f(\mathbf{x}^{\star})=(-4/3,-4/3)^{\mathsf T}$, which is normal to the constraint boundary. A nonzero gradient is therefore not itself a failure. Its inner product with the tangent direction $(1,-1)^{\mathsf T}$ is zero.
slack = np.array([2 - result.x.sum(), *result.x])
tangent = np.array([1, -1])
directional_derivative = gradient(result.x) @ tangent
pprint({"制約の余り": slack, "境界に沿う方向微分": sig3(directional_derivative),
"解析解との差のノルム": sig3(np.linalg.norm(result.x - exact))})
assert np.min(slack) >= -1.00e-8
assert abs(directional_derivative) < 1.00e-6
fig, ax = plt.subplots(figsize=(6, 3.40), layout="constrained")
ax.bar(["合計上限", "$x_1$の下限", "$x_2$の下限"], slack)
ax.axhline(0, color="black", linewidth=1)
ax.set(ylabel="制約の余り", title="図2:上限制約だけが有効になる")
save_svg(fig, "02_slack")
{'制約の余り': array([9.77e-15, 1.33, 0.667]),
'境界に沿う方向微分': '4.40e-14',
'解析解との差のノルム': '1.06e-14'}
4. Put parameter changes into a function
Change the total limit to $b\ge0$. For $0\le b\le3$, substitute the boundary relation $x_2=b-x_1$ and differentiate:
$$ \begin{aligned} 2(x_1-2)-4(b-x_1-1)&=0,\\ 6x_1-4b&=0,\\ \mathbf{x}^{\star}(b)&=(2b/3,b/3)^{\mathsf T},\\ f^{\star}(b)&=\frac{2}{3}(b-3)^2. \end{aligned} $$
For $b\ge3$, the target $(2,1)$ is feasible, and the optimal value remains 0. Rebuild only the constraint when changing this limit, so the original objective is not accidentally changed.
limits = np.linspace(0.500, 4, 36)
solutions = []
for limit in limits:
solved = optimize.minimize(
objective, [0, 0], jac=gradient, method="SLSQP", bounds=bounds,
constraints=[optimize.LinearConstraint([[1, 1]], -np.inf, limit)],
options={"ftol": 1.00e-12},
)
assert solved.success, solved.message
solutions.append(solved.fun)
expected = (2 / 3) * np.maximum(3 - limits, 0) ** 2
assert np.allclose(solutions, expected, atol=1.00e-8)
fig, ax = plt.subplots(figsize=(6, 3.60), layout="constrained")
ax.plot(limits, solutions, label="SLSQP")
ax.plot(limits[::3], expected[::3], "o", fillstyle="none", label="解析式")
ax.set(xlabel="合計上限 b", ylabel="最小の二乗誤差", title="図3:制約を緩めた場合")
ax.legend()
save_svg(fig, "03_parameter_sweep")
Large differences in the scales of variables or objective values can make stopping criteria difficult to interpret. First align units, rescale variables, and check gradients. Before tightening tolerances, verify the implementation on a small problem with a known analytical solution.
Conclusion
We implemented constrained quadratic minimization in SciPy and checked it using the analytical solution, gradients, constraint residuals, and plots.
Keeping the objective, gradient, and constraints separate makes changes easier to track. Besides the success flag, check solution accuracy and feasibility in terms of the actual problem.
References: SciPy minimize , LinearConstraint .