【问题标题】:Remove/Add constraints - optaplanner删除/添加约束 - optaplanner
【发布时间】:2017-09-07 10:47:00
【问题描述】:

是否可以完全忽略某些规则?我有一组规则,但我希望用户能够添加某些输入,比如他们想要规则 1、规则 2、规则 3、规则 5,但可能不是规则 4。所以我希望程序能够识别这一点,并且在检查约束违规时根本不输入规则 4

我该怎么办?

【问题讨论】:

  • 另见考试示例中使用的参数化模式。

标签: constraints add drools rules optaplanner


【解决方案1】:

一个简单的解决方案是创建

class Guard {
    String rulename; ... }

以及在规则中添加模式

rule rule_1
when
    Guard( rulename == "rule_1" )
    ...

然后您需要为应该被阻止的规则插入 Guard 事实。

【讨论】:

  • 谢谢!我不完全确定你所说的最后一点是什么意思。我确实知道如何检查输入,看看规则是否存在,我只是不知道我会调用什么方法来阻止规则并且不再检查。目前,我的程序查看规则是否在执行列表中;如果不是,则“then”部分为空。然而,这似乎不是一种有效的方法,理想情况下,一旦发现规则不存在,程序就根本不会考虑规则。但我不知道我应该调用什么方法来实现这一点。
  • 你必须调用 kieSession.insert(f) 其中 f 是一个合适的 Gard 对象。
【解决方案2】:

我有一个类似的问题,除了我希望用户控制每个规则权重 [0 到 10] 而不是二进制控件 [active - inactive]。我不确定这是一个性能优化的答案(在合理的时间内为我工作,但这当然取决于你的 corpus 大小)。

我们使用的方法是创建一个 Singleton,它将用户设置的每个规则权重保存在易失性内存中,使用 HashMap<Integer, Integer> 以更快地随机访问(键 = 规则编号,值 = 规则权重),因为推理引擎可能会多次调用它。

然后,在我们的规则文件中,我们检查给定规则是否在when 子句中处于活动状态,并根据实际规则权重更新then 子句中的分数:

import my.rules.singleton.package.MyRulesWeightSingleton;

rule "1"
    when
        eval(MyRulesWeightSingleton.isRuleActive(1))
        //other conditions here.
    then
        scoreHolder.addHardConstraintMatch(kcontext, MyRulesWeightSingleton.getRuleWeight(1));
end

Singleton 看起来像这样:

import java.util.HashMap;

public class MyRulesWeightSingleton {

    private static MyRulesWeightSingleton instance;
    private HashMap<Integer, Integer> weights;

    private MyRulesWeightSingleton() {
        this.weights = new HashMap<Integer, Integer>();
    }

    public static MyRulesWeightSingleton getInstance() {
        if (instance == null) {
            instance = new MyRulesWeightSingleton();
        }
        return instance;
    }

    public boolean isRuleActive(int ruleId) {
        Integer weight = weights.get(ruleId);
        return (weight != null && weight > 0);
    }

    public int getRuleWeight(int ruleId) {
        Integer weight = weights.get(ruleId);
        if (weight != null) {
            return weight;
        }
        return 0;
    }

    //Allows you to put and remove weights information
    //before running planner.
    public HashMap<Integer, Integer> getWeights() {
        return this.weights;
    }
}

PS:我们这里的实际问题比这要复杂一些,所以出于教学原因,我简化了我们的方法。 ;)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-08
    • 2017-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多