Bounded Minimization Examples¶
Example Code¶
Representative script:
"""IMSL BCONF example: minimize quadratic subject to box constraints.
Reproduces the IMSL BCONF style example:
- Function: f(x,y) = (x-1)^2 + (y-2)^2
- Bounds: 0 <= x <= 3, 0 <= y <= 3
- Expected minimum at x = (1.0, 2.0), f = 0.0
Outputs:
- Table printed to stdout
- SVG plot saved to test_output/demo_imsl_bconf.svg
"""
from __future__ import annotations
from pathlib import Path
from typing import Dict
import matplotlib.pyplot as plt
import numpy as np
from optimization import minimize_bounds_bfgs_fd
def run_demo_imsl_bconf() -> Dict[str, object]:
"""Run IMSL BCONF example: bounded quadratic minimization.
Args:
None
Returns:
Dict[str, object]: Result dict with keys ``x``, ``fval``,
``n_iter``, ``n_fev``, and ``plot_path``.
"""
def f(x: np.ndarray) -> float:
return (x[0] - 1.0) ** 2 + (x[1] - 2.0) ** 2
xlb = np.array([0.0, 0.0])
xub = np.array([3.0, 3.0])
x0 = np.array([2.5, 0.5])
result = minimize_bounds_bfgs_fd(
f, ibtype=0, xlb=xlb, xub=xub, x_guess=x0, max_iter=200, max_fev=1000
)
print("\nIMSL BCONF Example: Bounded Minimization of (x-1)^2 + (y-2)^2")
print("-" * 55)
print(f"{'Parameter':<20} {'Value':>25}")
print("-" * 55)
print(f"{'x1 (solution)':<20} {result.x[0]:>25.6f}")
print(f"{'x2 (solution)':<20} {result.x[1]:>25.6f}")
print(f"{'f(x)':<20} {result.fval:>25.8f}")
print(f"{'Iterations':<20} {result.n_iter:>25}")
print(f"{'Function evals':<20} {result.n_fev:>25}")
print(f"{'Converged':<20} {str(result.success):>25}")
print("-" * 55)
output_dir = Path("test_output")
output_dir.mkdir(parents=True, exist_ok=True)
plot_path = output_dir / "demo_imsl_bconf.svg"
x1v = np.linspace(0.0, 3.0, 200)
x2v = np.linspace(0.0, 3.0, 200)
X1, X2 = np.meshgrid(x1v, x2v)
Z = (X1 - 1.0) ** 2 + (X2 - 2.0) ** 2
fig, ax = plt.subplots(figsize=(7, 6))
cs = ax.contourf(X1, X2, Z, levels=20, cmap="coolwarm")
fig.colorbar(cs, ax=ax, label="f(x,y)")
ax.scatter(*x0, color="white", marker="^", s=80, zorder=5, label="Start")
ax.scatter(*result.x, color="red", marker="*", s=100, zorder=5,
label=f"Min ({result.x[0]:.4f},{result.x[1]:.4f})")
ax.set_xlabel("x1")
ax.set_ylabel("x2")
ax.set_title("IMSL BCONF: Bounded Minimization (L-BFGS-B / FD)")
ax.legend()
fig.tight_layout()
fig.savefig(plot_path, format="svg")
plt.close(fig)
return {
"x": result.x,
"fval": result.fval,
"n_iter": result.n_iter,
"n_fev": result.n_fev,
"plot_path": str(plot_path),
}
if __name__ == "__main__":
run_demo_imsl_bconf()
Input (Console)¶
Run the bounded minimization script from the package root:
python examples/example_imsl_bconf.py
Plot Output¶
Generated SVG plot:
Output Console¶
Summary console output:
IMSL BCONF Example: Bounded Minimization of (x-1)^2 + (y-2)^2
-------------------------------------------------------
Parameter Value
-------------------------------------------------------
x1 (solution) 1.000000
x2 (solution) 2.000000
f(x) 0.00000000
Iterations 3
Function evals 12
Converged True
-------------------------------------------------------