What is mathematical optimization? Objectives and constraints
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
Mathematical optimization uses constraints to define the available choices and finds variables that minimize or maximize an objective function within those choices. A two-product production problem introduces decision variables, the objective, the feasible set, and the optimal solution. We compare a hand calculation with SciPy and plot how the optimal value changes with available resources.
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("101_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"101_{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. Decide what to choose and what to measure
Let $x_1,x_2$ be the production quantities of products A and B. These quantities can be divided, as with production measured in tonnes. Requiring integer quantities would give a different problem.
| Item | Per unit of A | Per unit of B | Available amount |
|---|---|---|---|
| Profit | 3 | 2 | — |
| Working time | 1 | 1 | 4 |
| Material | 2 | 1 | 6 |
Use consistent units within each row. We assume that doubling production doubles both profit and resource use. Fixed costs, volume discounts, and changes in defect rates are excluded.
With the column vector $\mathbf{x}=(x_1,x_2)^{\mathsf T}$ as the decision variable, the problem is:
$$ \begin{aligned} \max_{\mathbf{x}}\quad &p(\mathbf{x})=3x_1+2x_2,\\ \text{subject to}\quad &x_1+x_2\le4,\\ &2x_1+x_2\le6,\\ &x_1\ge0,\quad x_2\ge0. \end{aligned} $$
Here $p$ is the objective function, and the remaining conditions are constraints. The set of points satisfying every condition is the feasible set $\mathcal F$. Satisfying just one constraint does not make a point feasible.
$$ \mathcal F=\{\mathbf{x}\in\mathbb R^2\mid x_1+x_2\le4,\ 2x_1+x_2\le6,\ \mathbf{x}\ge\mathbf{0}\}. $$
The optimal solution $\mathbf{x}^{\star}$ is a pair of production quantities; the optimal value $p^{\star}=p(\mathbf{x}^{\star})$ is the resulting profit. These are different objects. To convert maximization to minimization, reverse the sign of the objective.
$$ \underset{\mathbf{x}\in\mathcal F}{\operatorname{argmax}}\ p(\mathbf{x}) =\underset{\mathbf{x}\in\mathcal F}{\operatorname{argmin}}\ [-p(\mathbf{x})]. $$
2. Find the solution at the intersection of constraints
Using both resources fully gives $x_1+x_2=4$ and $2x_1+x_2=6$. Subtracting the first equation from the second yields $x_1=2$; substitution gives $x_2=2$. The profit is $3\times2+2\times2=10$.
Finding the intersection alone does not prove optimality. Here, adding the constraints gives an upper bound on the objective itself.
$$ \begin{aligned} 3x_1+2x_2 &=(x_1+x_2)+(2x_1+x_2)\\ &\le4+6=10. \end{aligned} $$
The feasible point $(2,2)$ reaches the upper bound of 10, so it is a global optimum. Equality requires both resource constraints to hold with equality, which also makes the solution unique in this example.
profit = np.array([3, 2])
A = np.array([[1, 1], [2, 1]])
b = np.array([4, 6])
result = optimize.linprog(-profit, A_ub=A, b_ub=b,
bounds=[(0, None), (0, None)], method="highs")
assert result.success, result.message
pprint({"最適解": result.x, "最大利益": sig3(-result.fun),
"資源の余り": b - A @ result.x})
assert np.allclose(result.x, [2, 2])
assert np.all(A @ result.x <= b + 1.00e-9)
vertices = np.array([[0, 0], [3, 0], [2, 2], [0, 4]])
fig, ax = plt.subplots(figsize=(6, 4.20), layout="constrained")
ax.fill(vertices[:, 0], vertices[:, 1], alpha=0.250, label="実行可能集合")
grid = np.linspace(0, 4, 200)
ax.plot(grid, 4 - grid, label="作業時間の上限")
ax.plot(grid, 6 - 2 * grid, label="材料の上限")
ax.plot(grid, (10 - 3 * grid) / 2, "--", label="利益10の等高線")
ax.scatter(*result.x, color="crimson", zorder=5, label="最適解 (2, 2)")
ax.set(xlim=(0, 4), ylim=(0, 5), xlabel="$x_1$", ylabel="$x_2$",
title="図1:制約を同時に満たす領域")
ax.legend(fontsize=9)
save_svg(fig, "01_feasible_set")
{'最大利益': '10.0', '最適解': array([2.00, 2.00]), '資源の余り': array([0.00, 0.00])}
$$ \displaystyle \mathbf{x}^{\star}=\begin{bmatrix}2\\2\end{bmatrix},\quad p^{\star}=10 $$
In Figure 1, moving the profit contour upward and to the right makes $(2,2)$ its last point of contact with the feasible set. Since linprog solves a minimization problem, its objective coefficients are $(-3,-2)^{\mathsf T}$, and the maximum profit is -result.fun. SciPy linprog documentation
This feasible set is nonempty, closed, and bounded, so a continuous objective attains a maximum on it. For a linear program with a finite optimum and a feasible polygon of this kind, at least one vertex attains the optimum. This does not mean that every optimal solution must be a vertex.
values = vertices @ profit
pprint({str(tuple(v.tolist())): int(value) for v, value in zip(vertices, values)})
fig, ax = plt.subplots(figsize=(6, 3.40), layout="constrained")
bars = ax.bar(["(0, 0)", "(3, 0)", "(2, 2)", "(0, 4)"], values,
color=["steelblue", "steelblue", "crimson", "steelblue"])
ax.bar_label(bars, labels=[str(int(v)) for v in values], padding=3)
ax.set(ylim=(0, 12), xlabel="実行可能集合の頂点", ylabel="利益",
title="図2:4頂点の目的関数値")
save_svg(fig, "02_vertex_values")
{'(0, 0)': 0, '(0, 4)': 8, '(2, 2)': 10, '(3, 0)': 9}
3. How much can more resources increase profit?
Change the working-time limit to $T$, keeping the material limit at 6. For $0\le T\le3$, we can produce $T$ units of A alone, which has the higher profit per unit of working time. For $3\le T\le6$, solve the two resource constraints as equalities.
$$ \begin{aligned} x_1+x_2&=T,\qquad 2x_1+x_2=6,\\ x_1&=6-T,\qquad x_2=2T-6,\\ p^{\star}(T)&=3(6-T)+2(2T-6)=T+6. \end{aligned} $$
For $T\ge6$, producing 6 units of B uses all the material, and profit cannot increase further. The bounds on the three intervals follow from $p\le3T$, $p\le T+6$, and $p\le2\times6$, respectively.
$$ p^{\star}(T)= \begin{cases} 3T & 0\le T\le3,\\ T+6 & 3\le T\le6,\\ 12 & T\ge6. \end{cases} $$
When considering additional resources, examine this piecewise linear curve as well as the current optimum. It shows where extra working time goes unused because material is limited.
times = np.linspace(0, 8, 81)
best = []
for time in times:
solution = optimize.linprog(-profit, A_ub=A, b_ub=[time, 6], method="highs")
assert solution.success
best.append(-solution.fun)
theory = np.minimum.reduce([3 * times, times + 6, np.full_like(times, 12)])
assert np.allclose(best, theory)
fig, ax = plt.subplots(figsize=(6, 3.60), layout="constrained")
ax.plot(times, best, label="SciPy")
ax.plot(times[::5], theory[::5], "o", fillstyle="none", label="手計算")
ax.set(xlabel="作業時間の上限 T", ylabel="最大利益", title="図3:資源量と最適値")
ax.legend()
save_svg(fig, "03_resource_sensitivity")
4. Some problems have no optimal solution
Imposing $x\ge1$ and $x\le0$ together makes the feasible set empty. Such a problem is infeasible. In contrast, maximizing $x$ under $x\ge0$ is unbounded above: any candidate value can be exceeded, so there is no finite optimal value.
For another example, minimizing $x$ under $x>0$ gives an infimum of 0, but 0 is not feasible. An infimum need not be a minimum. Using only the solution array without checking the solver’s termination status can hide these cases.
Conclusion
We formulated a production plan with an objective and constraints, proved an upper bound, checked the numerical solution, and varied the resource limits.
First define the units and allowed values of the variables, then write the objective and each constraint. Check separately that the returned point is feasible and that its objective value is optimal.
References: Boyd and Vandenberghe, Convex Optimization, Chapter 4 , SciPy linprog .