问题描述¶
Branin 函数 是一个二维函数,由如下方程定义:
$$f(x) = a\left(x_2 - b x_1^2 + c x_1 - r\right)^2 + s(1-t)\cos(x_1) + s$$
推荐的参数取值为 $a = 1$,$b = \frac{5.1}{4\pi^2}$,$c = \frac{5}{\pi}$,$r = 6$,$s = 10$,以及 $t = \frac{1}{8\pi}$。该函数通常在 $x_1 \in [-5, 10]$,$x_2 \in [0, 15]$ 的定义域上求值。
该函数具有三个全局最小值,问题的目标是找到其中之一。更多细节,请参阅 Virtual Library of Simulation Experiments。
学习要点¶
- 添加 浮点决策变量
- 使用
cos与pow算子 构建非线性表达式 - 了解 OptAgent 的建模风格:区分决策变量与中间表达式
建模思路¶
常数取为推荐值:$a = 1$,$b = \frac{5.1}{4\pi^2}$,$c = \frac{5}{\pi}$,$r = 6$,$s = 10$,以及 $t = \frac{1}{8\pi}$。$x_1$ 与 $x_2$ 的定义域分别为 $[-5, 10]$ 与 $[0, 15]$。
Branin 函数问题的 OptAgent 模型非常直接。它使用两个浮点决策变量,分别表示 $x_1$ 与 $x_2$。借助 OptAgent 丰富的非线性数学算子集合,我们可以直接计算该函数的值。使用 cos 与 pow 等算子,我们能够以非常自然的方式表达 Branin 函数。
Python 实现¶
from pathlib import Path
from optagent import OptModel, solve
def main(output_file=None, time_limit=6):
pi = 3.14159265359
a = 1
b = 5.1 / (4 * pi**2)
c = 5 / pi
r = 6
s = 10
t = 1 / (8 * pi)
model = OptModel()
x1 = model.float(-5.0, 10.0)
x2 = model.float(0.0, 15.0)
branin = a * (x2 - b * x1**2 + c * x1 - r) ** 2 + s * (1 - t) * model.cos(x1) + s
model.minimize(branin)
solution = solve(model, time_limit_s=float(time_limit))
result_values = {'objective': branin.value, 'x1': x1.value, 'x2': x2.value}
result_text = (
f"Status = {solution.feasible}; Objective = {result_values['objective']}\n"
f"x1 = {result_values['x1']}\n"
f"x2 = {result_values['x2']}"
)
print(result_text)
if output_file is not None:
Path(output_file).write_text(result_text + "\n", encoding="utf-8")
return solution
本地运行¶
Branin 函数不需要外部实例文件,直接调用 main 即可;调整 time_limit 可以控制求解时间。
solution_branin = main(time_limit=1)