Linear, nonlinear, and discrete optimization problems

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

Optimization problems can be classified by two separate criteria: the form of their functions and the allowed values of their variables. Small examples compare linear, nonlinear, and integer programs, and distinguish continuous relaxation from rounding. We also explain why a classification alone does not determine difficulty or guarantee global optimality.

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("102_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"102_{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. Separate function form from variable type

In a linear program, the objective and constraints are first-degree expressions in continuous variables. Expressions with constant terms are technically affine, but optimization terminology often calls them linear as well.

$$ \min_{\mathbf{x}\in\mathbb R^n}\ \mathbf{c}^{\mathsf T}\mathbf{x} \quad\text{subject to}\quad \mathbf{A}\mathbf{x}\le\mathbf{b},\quad \mathbf{E}\mathbf{x}=\mathbf{d}. $$

Terms such as $x_i^2$, $x_ix_j$, or $\exp(x_i)$ in the objective or constraints generally make a problem nonlinear. Discrete optimization instead restricts some or all variables to integers or a finite set.

Variable domainLinear objective and constraintsNonlinear objective or constraints
All continuousLinear programming (LP)Nonlinear programming (NLP)
Includes integer variablesMixed-integer linear programming (MILP)Mixed-integer nonlinear programming (MINLP)

If all variables are integers, the problem is an integer program. Combinatorial optimization may choose permutations or subsets, so not every discrete problem is initially written with integer variables. Linear and discrete are not opposing classifications.

2. Integer constraints change the solution even with the same linear expressions

First solve the following profit maximization with continuous variables.

$$ \max\ 3x_1+2x_2\quad\text{subject to}\quad x_1+x_2\le4,\quad 2x_1+x_2\le\frac{11}{2},\quad \mathbf{x}\ge\mathbf{0}. $$

At the intersection of the two boundaries, subtraction gives $x_1=11/2-4=3/2$, and substitution gives $x_2=5/2$. Adding the constraints yields:

$$ 3x_1+2x_2\le4+\frac{11}{2}=\frac{19}{2}=9.50. $$

The intersection reaches this upper bound. However, if $x_1,x_2\in\mathbb Z$, the left side is an integer, so $2x_1+x_2\le11/2$ is equivalent to $2x_1+x_2\le5$. Profit is therefore at most $4+5=9$, and $(1,3)$ attains the bound of 9.

c = np.array([-3, -2])  # 最大化を最小化へ変換する。
A = np.array([[1, 1], [2, 1]])
b = np.array([4, 5.50])
lp = optimize.linprog(c, A_ub=A, b_ub=b, method="highs")
ip = optimize.milp(c, integrality=np.ones(2),
                   bounds=optimize.Bounds([0, 0], [np.inf, np.inf]),
                   constraints=optimize.LinearConstraint(A, -np.inf, b))
assert lp.success and ip.success
pprint({"連続解": lp.x, "連続の最大利益": sig3(-lp.fun),
        "整数解": ip.x, "整数の最大利益": sig3(-ip.fun)})
assert np.allclose(lp.x, [1.50, 2.50])
assert np.allclose(ip.x, [1, 3])

points = np.array([(x, y) for x in range(5) for y in range(5)
                   if x + y <= 4 and 2 * x + y <= 5.50])
polygon = np.array([[0, 0], [2.75, 0], [1.50, 2.50], [0, 4]])
fig, ax = plt.subplots(figsize=(6, 4.20), layout="constrained")
ax.fill(*polygon.T, alpha=0.200, label="連続の実行可能集合")
ax.scatter(*points.T, label="実行可能な整数点")
ax.scatter(*lp.x, marker="*", s=170, label="LPの解")
ax.scatter(*ip.x, marker="s", s=90, facecolors="none", edgecolors="crimson",
           label="整数計画の解")
ax.set(xlabel="$x_1$", ylabel="$x_2$", title="図1:領域から整数点だけを選ぶ")
ax.legend(fontsize=9)
save_svg(fig, "01_continuous_integer")
{'整数の最大利益': '9.00',
 '整数解': array([1.00, 3.00]),
 '連続の最大利益': '9.50',
 '連続解': array([1.50, 2.50])}

$$ \displaystyle p_{\mathrm{LP}}^{\star}-p_{\mathrm{IP}}^{\star}=9.50-9.00=0.500 $$

Removing integrality constraints is called continuous relaxation. The integer feasible set $\mathcal F_{\mathrm{IP}}$ is contained in the continuous feasible set $\mathcal F_{\mathrm{LP}}$, giving the following relation for maximization.

$$ \mathcal F_{\mathrm{IP}}\subseteq\mathcal F_{\mathrm{LP}} \ \Longrightarrow\ p_{\mathrm{IP}}^{\star}\le p_{\mathrm{LP}}^{\star}. $$

For minimization, the inequality is reversed. Rounding the continuous solution $(1.50,2.50)$ down to $(1,2)$ gives profit 7, below the integer optimum of 9. Rounding up to $(2,3)$ violates the resource constraints. Including integrality directly in the model makes it easier to check the result than assuming rounding will solve the problem.

candidates = {"LP": lp.x, "切り下げ": np.floor(lp.x),
              "切り上げ": np.ceil(lp.x), "整数最適解": ip.x}
fig, ax = plt.subplots(figsize=(6, 3.60), layout="constrained")
for i, (name, point) in enumerate(candidates.items()):
    feasible = bool(np.all(A @ point <= b + 1.00e-9))
    value = -c @ point
    ax.bar(name, value, color="steelblue" if feasible else "lightgray")
    ax.text(i, value + 0.150, sig3(value), ha="center")
    pprint({"候補": name, "座標": point, "実行可能": feasible})
ax.set(ylim=(0, 14), ylabel="利益", title="図2:灰色の候補は制約を満たさない")
save_svg(fig, "02_rounding")
{'候補': 'LP', '実行可能': True, '座標': array([1.50, 2.50])}
{'候補': '切り下げ', '実行可能': True, '座標': array([1.00, 2.00])}
{'候補': '切り上げ', '実行可能': False, '座標': array([2.00, 3.00])}
{'候補': '整数最適解', '実行可能': True, '座標': array([1.00, 3.00])}

3. Convex nonlinear problems have useful global structure

As a nonlinear example, measure the squared deviations from target production quantities.

$$ f(\mathbf{x})=(x_1-1.20)^2+2(x_2-1.70)^2, \qquad \mathbf{x}\ge\mathbf{0}. $$

The partial derivatives are $\partial f/\partial x_1=2(x_1-1.20)$ and $\partial f/\partial x_2=4(x_2-1.70)$. Setting both to zero gives $\mathbf{x}^{\star}=(1.20,1.70)^{\mathsf T}$. Each squared term is nonnegative, and both vanish at this point, so the global minimum is 0.

$$ \nabla^2 f(\mathbf{x})= \begin{bmatrix}2&0\\0&4\end{bmatrix}\succ\mathbf{0}. $$

This is a convex quadratic program, a well-structured class of nonlinear problems. Nonlinearity alone does not imply multiple local optima.

target = np.array([1.20, 1.70])
weight = np.array([1, 2])


def objective(x):
    return np.sum(weight * (x - target) ** 2)


def gradient(x):
    return 2 * weight * (x - target)


nlp = optimize.minimize(objective, [0, 0], jac=gradient, method="L-BFGS-B",
                        bounds=[(0, None), (0, None)])
assert nlp.success and np.allclose(nlp.x, target, atol=1.00e-6)
pprint({"二次計画の解": nlp.x, "目的関数値": sig3(nlp.fun)})
u, v = np.meshgrid(np.linspace(0, 3, 150), np.linspace(0, 3, 150))
z = (u - target[0]) ** 2 + 2 * (v - target[1]) ** 2
fig, ax = plt.subplots(figsize=(5.50, 4.20), layout="constrained")
curves = ax.contour(u, v, z, levels=[0.250, 1, 2, 4, 8])
ax.clabel(curves, fmt=lambda value: sig3(value))
ax.scatter(*nlp.x, color="crimson", label="大域最小点")
ax.set(xlabel="$x_1$", ylabel="$x_2$", title="図3:非線形な凸目的関数")
ax.legend()
save_svg(fig, "03_quadratic")
{'二次計画の解': array([1.20, 1.70]), '目的関数値': '1.17e-11'}

4. Check the model before choosing a solver

SciPy provides linprog for linear programs, milp for mixed-integer linear programs, and minimize for general continuous minimization. The methods within minimize support different constraints and derivative information. Choose after checking function form, variable domains, convexity, and available gradients.

For example, $f(x)=(x^2-1)^2$ is nonconvex, with minima at $x=\pm1$ and a stationary point at $x=0$. Finding a stationary point does not prove global optimality. Integer programs also range from small problems solved by enumeration to difficult large problems. Classification narrows the choice of methods; it does not uniquely determine runtime.

Conclusion

We separated linearity of the functions from discreteness of the variables and compared continuous, integer, and convex quadratic solutions.

A continuous relaxation bounds the integer optimum but does not guarantee feasibility or optimality after rounding. For a nonlinear problem, also check whether it is convex.

References: SciPy milp , SciPy minimize .