第一个模型¶
用两个整数变量表示产量,在满足需求的前提下最小化成本。运行前先完成安装与许可证配置。
建模、求解与读值¶
from optagent import OptModel
model = OptModel()
x = model.int(0, 10)
y = model.int(0, 10)
cost = 2 * x + y
model.constraint(x + y >= 7)
model.minimize(cost)
solution = model.solve(time_limit_s=1.0, log_level="off")
print(solution.status, solution.objectives)
if solution.feasible:
print("x =", x.value, "y =", y.value, "cost =", cost.value)
示例不需要模型或变量名称:x、y、cost 是 Python 表达式引用,求解后通过 .value 读值。
这里的整数上下界都包含端点。constraint() 与 add_constraint() 等价;minimize() 声明最小化目标。这个小模型的数学最优解是 x=0, y=7,成本为 7;限时搜索的返回结果应以实际可行性与目标值为准。
选择精确求解后端¶
该模型是混合整数线性模型,可以复用模型并通过 OptX 选择 HiGHS:
from optagent import HighsConfig
solution = model.solve_optx(config=HighsConfig(time_limit_s=5.0))
if solution.feasible:
print(x.value, y.value)
这个整数模型也可以通过同一个入口选择内置 CP-SAT:
from optagent import CpSatConfig
solution = model.solve_optx(config=CpSatConfig(time_limit_s=5.0))
if solution.feasible:
print(x.value, y.value)
HighsConfig 和 CpSatConfig 分别选择对应后端;省略 config 时默认使用 HiGHS。所选后端不支持模型时会报告原因,不会自动更换后端。更多选择见求解指南。