线性问题示例¶
线性问题示例展示可以降低到 CanonicalMpModel 的模型:0/1 背包、二分指派、设施选址、路由线性化,以及 MPS 数据重建后的 MILP 路径。
https://github.com/Dongbox/optagent-examples
问题说明¶
knapsack_mathopt.py:在容量约束下选择物品,最大化价值,展示二进制变量和线性目标。assignment_highs_native.py:把任务分配给工人,每个任务和工人受唯一性约束,展示 HiGHS native 后端。facility_location_small.py:决定开哪些仓库,并把客户分配给已开启设施,展示固定成本和服务成本组合。routing_linearized_small.py:把小型路由问题改写为线性 MILP,而不是通过黑盒路径评分求解。
目录结构¶
examples/linear/
README.md
knapsack_mathopt.py
assignment_highs_native.py
facility_location_small.py
routing_linearized_small.py
代码示例¶
线性示例的共同结构是创建标量变量、线性约束和线性目标,然后通过 OrchestratorConfig 指定 MILP 家族或具体后端。
from optagent import ExactBackendName, ModelBuilder, Orchestrator, OrchestratorConfig
builder = ModelBuilder(solve_config={"preferred_backend": "highs_native"})
x = builder.int_var(default=0, lb=0, ub=1, name="open_facility")
y = builder.int_var(default=0, lb=0, ub=10, name="served_demand")
builder.constraint(y <= x * 10, name="serve_only_if_open")
builder.minimize((x * 5) + y, name="total_cost")
result = Orchestrator().run(
builder.freeze(),
config=OrchestratorConfig(required_backend=ExactBackendName.HIGHS_NATIVE),
)
运行¶
PYTHONPATH=. python examples/linear/knapsack_mathopt.py
PYTHONPATH=. python examples/linear/assignment_highs_native.py
PYTHONPATH=. python examples/linear/facility_location_small.py
PYTHONPATH=. python examples/linear/routing_linearized_small.py
注意事项¶
- MathOpt 路径通常需要
ortools。 - HiGHS native 路径需要
highspy。 - 严格后端示例会在后端不可用时报错;普通示例可能由 registry 选择可用后端。
- MPS 相关的大窗口示例在 MPS 示例 中单独说明。