Search code examples
droolsdrools-planner

Drools Creating a Custom Score


So I've created a custom score in drools:

public interface MyScore extends Score<MyScore>

and have implemented it. However I can't see how to use the score. The config has a

<scoreDefinition>

tag but putting anything inside this other than SIMPLE or HARD_AND_SOFT produces an error.

How can I configure the solver to use the score I've created, the docs seem to imply this is possible but doesn't go into any detail.


Solution

  • This was meant to be possible (and a normal practice), but there's a roadblock.

    I just added this documentation:

    Implementing a custom Score

    To implement a custom Score, you 'll also need to implement a custom ScoreDefinition. Extend AbstractScoreDefinition (preferable by copy pasting HardAndSoftScoreDefinition or SimpleScoreDefinition) and start from there.

    Next, hook you custom ScoreDefinition in your SolverConfig.xml:

    <scoreDefinition>
        <scoreDefinitionClass>org.drools.planner.examples.my.score.definition.MyScoreDefinition</scoreDefinitionClass>
    </scoreDefinition>
    

    The Roadblock

    There's a roadblock that I 'll fix for 5.3 or 5.4:

    ScoreDefinitionConfig has this code:

    /**
     * @TODO score-in-solution refactor
     */
    public ScoreCalculator buildScoreCalculator() {
        if (scoreDefinitionType != null) {
            switch (scoreDefinitionType) {
                case SIMPLE:
                    return new SimpleScoreCalculator();
                case SIMPLE_DOUBLE:
                    return new SimpleDoubleScoreCalculator();
                case HARD_AND_SOFT:
                    return new DefaultHardAndSoftConstraintScoreCalculator();
                default:
                    throw new IllegalStateException("The scoreDefinitionType (" + scoreDefinitionType
                            + ") is not implemented");
            }
        } else {
            return new SimpleScoreCalculator();
        }
    }
    

    One way to deal with that is to extend ScoreDefinitionConfig and overwrite that method, as described in the manual in the section using a custom Selector, Acceptor or Forager.