This is the fourth day of my participation in Gwen Challenge

Contents summary

In the previous two chapters, we studied two examples, the high school curriculum and cloud resource optimization. I’m sure you’ll have an intuitive sense of what OptaPlanner is and what it solves. So with that in mind, we’ll look at the steps in OptaPlanner and what it does.

An overview of the

Solving a Planning Problem using OptaPlanner involves the following steps:

  1. Problems in modeling: Model your planning problem as one with@PlanningSolutionAnnotated classes, for exampleCloudBalanceClass.
  2. Configuration solver: Configures a solver, such as anyCloudBalanceExamples of First Fit and Tabu Search solvers (different solvers have very different performance and results for different planning problems, more on how to choose suitable solvers later).
  3. Assemble problem data: Loads a problem dataset, such as one, from the data layerCloudBalanceInstance. That’s the planning problem.
  4. Call solver:Solver.solve(problem)To solve the problem and return to the best solution found.

Solver configuration

Configuration of the solver OptaPlanner supports both XML and API configuration.

The XML configuration

Build a Solver instance with SolverFactory. Configure SolverFactory with a Solver configuration XML file provided as a classpath resource (defined by classLoader.getResource ()).

   SolverFactory<NQueens> solverFactory = SolverFactory.createFromXmlResource(
               "org/optaplanner/examples/nqueens/solver/nqueensSolverConfig.xml");
       Solver<NQueens> solver = solverFactory.buildSolver();
Copy the code

In one project (following the Maven directory structure), SolverConfig XML file is located in the $PROJECT_DIR/SRC/main/resources/org/optaplanner/examples/nqueens/solver/nqueensSolverConfig. The XML. In addition, you can also use SolverFactory. CreateFromXmlFile () to create a SolverFactory from a file. However, for portability, it is recommended to use the CLASspath resource. Solver and SolverFactory both have a common type called Solution_, which is a class that represents planning problems and solutions, such as the CloudBalance class. A solver configuration XML file looks like this:


      
<solver xmlns="https://www.optaplanner.org/xsd/solver" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://www.optaplanner.org/xsd/solver https://www.optaplanner.org/xsd/solver/solver.xsd">
  <! -- Define model -->
  <solutionClass>org.optaplanner.examples.nqueens.domain.NQueens</solutionClass>
  <entityClass>org.optaplanner.examples.nqueens.domain.Queen</entityClass>

  <! Define constraint rules file -->
  <scoreDirectorFactory>
    <scoreDrl>org/optaplanner/examples/nqueens/solver/nQueensConstraints.drl</scoreDrl>
  </scoreDirectorFactory>

  <! -- Configure different parameters and optimization algorithm -->
  <termination>.</termination>
  <constructionHeuristic>.</constructionHeuristic>
  <localSearch>.</localSearch>
</solver>
Copy the code

Notice the three parts:

  • Define the model
  • Define a constraint rule or score calculation class
  • Optional configuration optimization algorithm

These different parts of the configuration will be explained further later.

Configuring through the API

Solver configuration can also be configured through the SolverConfig API. This is especially useful for dynamically changing some values at run time. For example, before building the solver, change the running time based on system properties.

        SolverConfig solverConfig = SolverConfig.createFromXmlResource(
                "org/optaplanner/examples/nqueens/solver/nqueensSolverConfig.xml");
        solverConfig.withTerminationConfig(new TerminationConfig()
                        .withMinutesSpentLimit(userInput));

        SolverFactory<NQueens> solverFactory = SolverFactory.create(solverConfig);
        Solver<NQueens> solver = solverFactory.buildSolver();
Copy the code

Solver each element in the configuration XML can be used as a Config class or package namespace org. Optaplanner. Core. The Config in the Config attribute of the class. These *Config classes are Java representations in XML format. They built a runtime component (belong to package namespace org. Optaplanner. Core. Impl), and assemble them into an efficient Solver.

For example, the CloudBalance example is configured through the API.

// Build the Solver
        SolverFactory<CloudBalance> solverFactory = SolverFactory.create(new SolverConfig()
                .withSolutionClass(CloudBalance.class)
                .withEntityClasses(CloudProcess.class)
                .withConstraintProviderClass(CloudBalancingConstraintProvider.class)
// .withTerminationSpentLimit(Duration.ofMinutes(2)));
                .withTerminationSpentLimit(Duration.ofSeconds(30)));
        Solver<CloudBalance> solver = solverFactory.buildSolver();
Copy the code

OptPlanner annotations

OptaPlanner needs to know which classes in the business model are PlanningEntity planning entities, which properties are PlanningVariable planning variables, and so on. There are several ways:

  1. Add class annotations and JavaBean attribute annotations to the business model (recommended). Attribute annotations must be ingetterIn method, not insetteR method, in this casegetterIt doesn’t have to be public.
  2. Add class and field annotations to the business model so that the fields do not need to be common.
  3. Working with XML: Configure in an XML file. However, some attributes are not yet supported.

OptaPlanner focuses on the first approach, for example:

@PlanningSolution
@XStreamAlias("CloudBalance")
public class CloudBalance extends AbstractPersistable {

    private List<CloudComputer> computerList;

    private List<CloudProcess> processList;

    @XStreamConverter(HardSoftScoreXStreamConverter.class)
    private HardSoftScore score;

    public CloudBalance(a) {}public CloudBalance(long id, List<CloudComputer> computerList, List<CloudProcess> processList) {
        super(id);
        this.computerList = computerList;
        this.processList = processList;
    }

    @ValueRangeProvider(id = "computerRange")
    @ProblemFactCollectionProperty
    public List<CloudComputer> getComputerList(a) {
        return computerList;
    }

    public void setComputerList(List<CloudComputer> computerList) {
        this.computerList = computerList;
    }

    @PlanningEntityCollectionProperty
    public List<CloudProcess> getProcessList(a) {
        return processList;
    }

    public void setProcessList(List<CloudProcess> processList) {
        this.processList = processList;
    }

    @PlanningScore
    public HardSoftScore getScore(a) {
        return score;
    }

    public void setScore(HardSoftScore score) {
        this.score = score; }}Copy the code

Custom property configuration

Solver configuration supports custom attributes. Custom attributes are useful for adjusting dynamic values through Benchmarker. For example: Suppose the EasyScoreCalculator has a large number of calculations (which are cached) and you want to increase the size of the cache in a benchmark.

  <scoreDirectorFactory>
    <easyScoreCalculatorClass>. MyEasyScoreCalculator</easyScoreCalculatorClass>
    <easyScoreCalculatorCustomProperties>
      <property name="myCacheSize" value="1000"/><! -- Override value -->
    </easyScoreCalculatorCustomProperties>
  </scoreDirectorFactory>
Copy the code

Add a public setter method for each custom property, which is called when Solver is built.

public class MyEasyScoreCalculator extends EasyScoreCalculator<MySolution.SimpleScore> {

        private int myCacheSize = 500; // Default value

        @SuppressWarnings("unused")
        public void setMyCacheSize(int myCacheSize) {
            this.myCacheSize = myCacheSize; }}Copy the code

Custom attributes support most numeric types, including Boolean, int, Double, BigDecimal, String, and enums).

conclusion

This chapter mainly studies the solving steps of OptaPlanner, as well as the main configuration and methods of the solver, which is very helpful for us to learn the solving process of OptaPlanner.

homework

In the previous two examples, we used API method, you can switch to XML method to learn, actually XML elements have corresponding API method, but XML readability is more appropriate, but when using API form is recommended.

conclusion

In the next chapter, we’ll focus on concepts in business models, ProblemFact, ProblemEntity, ProblemSolution, etc.

Creation is not easy, unauthorized reprint is prohibited. Like/like/follow my post if it helps you ❤❤❤❤❤❤