You need to enable JavaScript to run this app. OptaPlanner如何实现约束动态增删 适配UI选约束的周月排程需求
优惠活动
大模型
产品
解决方案
定价
更多

OptaPlanner如何实现约束动态增删 适配UI选约束的周月排程需求

基于现有代码实现OptaPlanner动态约束启停的落地方案

核心实现思路

OptaPlanner 本身不支持运行时动态加载/卸载约束类,但可以借助内置的约束权重配置机制实现等效的约束启停效果,完全适配你当前月度/周度排程动态切换规则的场景,不需要改动核心求解架构。

第一步:修正现有代码的基础兼容问题

先把你当前代码里会影响动态配置生效的问题逐一修正:

  • 约束方法里的惩罚分值不要硬编码:你现在yarnTypeMatch方法里写的.penalizeConfigurable('yarn type match', HardSoftScore.ofHard(10000))是错误的,penalizeConfigurable本身是从约束配置类读取权重值的,硬编码分值会导致后续的权重设置完全失效,要改成不带固定分值的形式:
    private Constraint yarnTypeMatch(ConstraintFactory constraintFactory){
        return constraintFactory.from(PlanOrder.class)
                .filter(planOrder -> planOrder.getProductionLine()!=null)
                .filter(planOrder-> !planOrder.getProductionLine().getItemName().equals(planOrder.getItemName()))
                .penalizeConfigurable("yarn type match");
    }
    
  • 修正实体引用错误:clientLevelUsed方法里你引用了不存在的Client类,要替换成你实际定义的ProductionLine实体。
  • 把库存实体接入规划解:你现在PlanAssignment里没有库存集合,要加上对应的问题事实属性,才能让库存相关的约束生效:
    @ProblemFactCollectionProperty
    private List<Inventory> inventoryList;
    // 补充对应的getter/setter、构造方法参数
    
  • 在PlanAssignment里加上约束配置的提供者注解,让求解器能读取动态传入的配置:
    private PlanConstraintConfiguration constraintConfiguration;
    
    @ConstraintConfigurationProvider
    public PlanConstraintConfiguration getConstraintConfiguration() {
        return constraintConfiguration;
    }
    
  • 把代码里所有单引号包裹的字符串替换为Java标准的双引号格式,避免编译报错。

第二步:把所有可能用到的约束全部预加载

不管是月度排程用的、周度排程用的,甚至未来要扩展的规则,全部一次性写到PlanConstraintProvider的defineConstraints方法返回值里,不要因为当前用不上就删掉。比如你周度排程要考虑的库存约束,现在就提前写好:

@Override
public Constraint[] defineConstraints(ConstraintFactory constraintFactory) {
    return new Constraint[]{
            yarnTypeMatch(constraintFactory),
            clientLevelUsed(constraintFactory),
            // 提前把周度排程要用到的库存约束写上
            insufficientInventory(constraintFactory)
    };
}

// 周度排程专用:订单需求大于可用库存时触发惩罚
private Constraint insufficientInventory(ConstraintFactory constraintFactory) {
    return constraintFactory.from(PlanOrder.class)
            .join(Inventory.class, 
                Joiners.equal(PlanOrder::getMaterialCode, Inventory::getWlbh))
            .filter((order, inv) -> inv.getKcsl() < Double.parseDouble(order.getActualQuantity1()))
            .penalizeConfigurable("insufficient inventory");
}

第三步:改造约束配置类,实现无代码动态切权重

你现在的PlanConstraintConfiguration类,给每个预加载的约束都加上对应的权重字段,所有字段初始值统一设为HardSoftScore.ZERO:

@ConstraintConfiguration
public class PlanConstraintConfiguration {
    // 默认所有约束不生效,权重为0
    @ConstraintWeight("yarn type match")
    public HardSoftScore yarnTypeMatch = HardSoftScore.ZERO;

    @ConstraintWeight("client level used")
    public HardSoftScore clientLevelUsed = HardSoftScore.ZERO;

    @ConstraintWeight("insufficient inventory")
    public HardSoftScore insufficientInventory = HardSoftScore.ZERO;
}

实现原理:OptaPlanner 计算约束惩罚值的时候,是用规则的匹配次数乘以配置里的权重值,当权重为0时,不管规则匹配多少次,最终贡献的分数都是0,和“完全移除这个约束”的效果完全一致。

第四步:改造求解调用流程,对接前端勾选逻辑

  • 先把XML里的scoreDirectorFactory补上约束配置类的声明:
    <scoreDirectorFactory>
        <constraintProviderClass>com.zbxx.iem.solving.PlanConstraintProvider</constraintProviderClass>
        <constraintConfigClass>com.zbxx.iem.solving.PlanConstraintConfiguration</constraintConfigClass>
    </scoreDirectorFactory>
    
  • 把SolverFactory改成全局单例(不要每次请求都重新创建,解析XML、初始化求解器环境的耗时极高),每次求解的时候根据前端传入的选中约束列表,动态构造配置对象:
    // 全局单例,仅在应用启动时初始化一次
    private static final SolverFactory<PlanAssignment> solverFactory = 
        SolverFactory.createFromXmlResource("planConfiguration.xml");
    
    // Controller层调用逻辑
    public PlanAssignment doScheduling(List<String> selectedConstraints, 
                                        List<ProductionLine> productionLineList,
                                        List<PlanOrder> planOrderList,
                                        List<Inventory> inventoryList) {
        // 根据用户勾选的约束设置对应权重
        PlanConstraintConfiguration config = new PlanConstraintConfiguration();
        if (selectedConstraints.contains("yarn_type_match")) {
            config.yarnTypeMatch = HardSoftScore.ofHard(1);
        }
        if (selectedConstraints.contains("client_level_used")) {
            config.clientLevelUsed = HardSoftScore.ofHard(2);
        }
        if (selectedConstraints.contains("insufficient_inventory")) {
            config.insufficientInventory = HardSoftScore.ofHard(5);
        }
    
        // 构造初始求解方案
        PlanAssignment problem = new PlanAssignment();
        problem.setProductionLineList(productionLineList);
        problem.setPlanOrderList(planOrderList);
        problem.setInventoryList(inventoryList);
        problem.setConstraintConfiguration(config);
    
        // 启动求解
        Solver<PlanAssignment> solver = solverFactory.buildSolver();
        return solver.solve(problem);
    }
    

实际效果

  • 当用户选择“月度排程”模板,只勾选生产匹配、客户规则两个约束时,库存约束权重为0,求解过程完全不计算库存逻辑,和你当前的月度排程效果完全一致。
  • 当用户切换到“周度排程”模板,勾选库存约束时,直接把库存对应的权重改成业务要求值,不需要改任何代码、重启服务,求解器会自动纳入库存校验逻辑。
  • 后续新增规则只需要往ConstraintProvider里加方法、在配置类里加权重字段,不需要改动核心求解流程。

内容的提问来源于stack exchange,提问作者mos_yang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.27 13:45:07