跳转至

快速开始

基本流程

OptAgent 的求解流程分为三步:建模配置编排器求解并查看结果

线性规划:0/1 背包问题

from optagent import ExactBackendName, ModelBuilder, Orchestrator, OrchestratorConfig, OrchestratorSolver, PhaseConfig

builder = ModelBuilder(
    metadata={"case": "knapsack_mathopt"},
    solve_config={"preferred_backend": "mathopt_mp", "mathopt_solver_type": "GSCIP"},
)

weights = [2, 3, 4, 5, 9]
values = [3, 4, 8, 8, 10]
picks = [builder.int_var(default=0, lb=0, ub=1, name=f"pick_{idx}") for idx in range(len(weights))]

total_weight = builder.sum(*((pick * weight) for pick, weight in zip(picks, weights, strict=True)))
total_value = builder.sum(*((pick * value) for pick, value in zip(picks, values, strict=True)))

builder.constraint(total_weight <= 10, name="capacity")
builder.maximize(total_value, name="profit")
program = builder.freeze()

result = Orchestrator().run(
    program,
    config=OrchestratorConfig(
        required_backend=ExactBackendName.MATHOPT_MP,
        strict_backend=True,
        phases=[PhaseConfig(name="mathopt_knapsack", solver=OrchestratorSolver.MILP, budget_iterations=20)],
    ),
)

solution = result.final_solution
print(f"solver: {solution.solver_name}")
print(f"status: {solution.status.value}")
print(f"objective: {solution.objective_values}")
print(f"variables: {solution.variable_values}")

使用预设求解

预设(Preset)封装了最优的求解策略配置,一行代码即可求解:

from optagent import BuiltInStrategyPreset, ModelBuilder, Orchestrator

builder = ModelBuilder(metadata={"case": "scheduling_preset_demo"})
# ... 建模过程 ...
program = builder.freeze()

# 使用预设,无需手动配置编排器
result = Orchestrator().run(program, preset=BuiltInStrategyPreset.SCHEDULING_EVOLUTIONARY_REPAIR)

# 或者不指定预设,让系统自动选择
result = Orchestrator().run(program)

查看求解结果

solution = result.final_solution

# 基本信息
print(f"solver: {solution.solver_name}")        # 使用的求解器
print(f"status: {solution.status.value}")        # 求解状态
print(f"feasible: {solution.feasible}")          # 是否可行
print(f"objective: {solution.objective_values}") # 目标函数值
print(f"variables: {solution.variable_values}")  # 变量赋值

# 预设相关信息
print(f"preset: {result.selected_preset_name}")       # 选用的预设名
print(f"preset source: {result.selected_preset_source}") # 预设来源(枚举/字符串/自动)