### Clone OptaPlanner Quickstarts Repository Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/use-cases-and-examples/vaccination-scheduling/vaccination-scheduling.adoc Clone the official OptaPlanner quickstarts repository to access the vaccination scheduling example. ```shell git clone https://github.com/kiegroup/optaplanner-quickstarts.git ``` -------------------------------- ### Clone Git Repository Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/quickstart/hello-world/hello-world-quickstart.adoc Clone the OptaPlanner quickstarts repository to access the complete example code. ```shell $ git clone {quickstarts-clone-url} ``` -------------------------------- ### Run OptaPlanner Examples on Windows Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/planner-introduction/planner-introduction.adoc Execute the OptaPlanner examples script on Windows systems after downloading and unzipping the release. ```sh $ cd examples $ runExamples.bat ``` -------------------------------- ### Run OptaPlanner Examples Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/planner-introduction/planner-introduction.adoc After building, navigate to the optaplanner-examples directory and run the examples using Maven's exec plugin. ```sh $ cd optaplanner-examples $ mvn exec:java ... ``` -------------------------------- ### Run OptaPlanner Examples on Linux/Mac Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/planner-introduction/planner-introduction.adoc Execute the OptaPlanner examples script on Linux or macOS systems after downloading and unzipping the release. ```sh $ cd examples $ ./runExamples.sh ``` -------------------------------- ### Start OptaPlanner Quarkus Application Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/quickstart/quarkus/quarkus-quickstart.adoc Run this command to compile and start the Quarkus development server. ```shell $ mvn compile quarkus:dev ``` -------------------------------- ### CloudBalancePartitioner Example Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/partitioned-search/partitioned-search.adoc An example implementation of the SolutionPartitioner interface for the CloudBalance problem. ```java public class CloudBalancePartitioner implements SolutionPartitioner { private int partCount = 4; private int minimumProcessListSize = 75; @Override public List splitWorkingSolution(ScoreDirector scoreDirector, Integer runnablePartThreadLimit) { CloudBalance originalSolution = scoreDirector.getWorkingSolution(); ``` -------------------------------- ### Custom Move Implementation Example Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/move-and-neighborhood-selection/move-and-neighborhood-selection.adoc Example of a custom move implementation extending `AbstractMove`. This specific example demonstrates changing a process to a different computer in a cloud balancing scenario. ```java public class CloudComputerChangeMove extends AbstractMove { private CloudProcess cloudProcess; private CloudComputer toCloudComputer; ``` -------------------------------- ### Run Cloud Balancing Hello World Example Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/use-cases-and-examples/cloud-balancing/cloud-balancing.adoc Executes the Cloud Balancing Hello World example. Configure the main class as 'org.optaplanner.examples.cloudbalancing.app.CloudBalancingHelloWorld'. The default run time is 120 seconds. ```java public class CloudBalancingHelloWorld { public static void main(String[] args) { // Build the Solver SolverFactory solverFactory = SolverFactory.createFromXmlResource( "org/optaplanner/examples/cloudbalancing/solver/cloudBalancingSolverConfig.xml"); Solver solver = solverFactory.buildSolver(); // Load a problem with 400 computers and 1200 processes CloudBalance unsolvedCloudBalance = new CloudBalancingGenerator().createCloudBalance(400, 1200); // Solve the problem CloudBalance solvedCloudBalance = solver.solve(unsolvedCloudBalance); // Display the result System.out.println("\nSolved cloudBalance with 400 computers and 1200 processes:\n" + toDisplayString(solvedCloudBalance)); } ... } ``` -------------------------------- ### Build and Run OptaPlanner from Source Source: https://github.com/kiegroup/optaplanner/blob/main/README.adoc Use these Maven commands to build OptaPlanner from source and run the examples. ```bash mvn clean install -Dquickly cd optaplanner-examples mvn exec:java ``` -------------------------------- ### Custom Phase Command Implementation Example Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/optimization-algorithms/optimization-algorithms.adoc Example implementation of `CustomPhaseCommand` to initialize a solution by setting processes to their original machines. Ensure all changes to planning entities are notified to the `ScoreDirector`. ```java public class ToOriginalMachineSolutionInitializer extends AbstractCustomPhaseCommand { public void changeWorkingSolution(ScoreDirector scoreDirector) { MachineReassignment machineReassignment = scoreDirector.getWorkingSolution(); for (MrProcessAssignment processAssignment : machineReassignment.getProcessAssignmentList()) { scoreDirector.beforeVariableChanged(processAssignment, "machine"); processAssignment.setMachine(processAssignment.getOriginalMachine()); scoreDirector.afterVariableChanged(processAssignment, "machine"); scoreDirector.triggerVariableListeners(); } } } ``` -------------------------------- ### Apply School Timetabling Solver Resource (OpenShift) Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-operator/README.adoc Apply the example Solver custom resource to your OpenShift cluster. ```bash oc apply -f src/k8s/school-timetabling-solver.yml ``` -------------------------------- ### Expose Prometheus Metrics via HTTP Server Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/planner-configuration/planner-configuration.adoc This example demonstrates how to set up an HTTP server to expose Prometheus metrics scraped from a PrometheusMeterRegistry. It includes creating a context for scraping and starting the server in a new thread. ```java PrometheusMeterRegistry prometheusRegistry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT); try { HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0); server.createContext("/prometheus", httpExchange -> { String response = prometheusRegistry.scrape(); (1) httpExchange.sendResponseHeaders(200, response.getBytes().length); try (OutputStream os = httpExchange.getResponseBody()) { os.write(response.getBytes()); } }); new Thread(server::start).start(); } catch (IOException e) { throw new RuntimeException(e); } Metrics.addRegistry(prometheusRegistry); ``` -------------------------------- ### Example Solver Logging Output Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/planner-configuration/planner-configuration.adoc This example shows typical debug logging output during solver execution, indicating phase completion and step progression. It is useful for understanding solver behavior and performance. ```log INFO Solving started: time spent (3), best score (-4init/0), random (JDK with seed 0). DEBUG CH step (0), time spent (5), score (-3init/0), selected move count (1), picked move (Queen-2 {null -> Row-0}). DEBUG CH step (1), time spent (7), score (-2init/0), selected move count (3), picked move (Queen-1 {null -> Row-2}). DEBUG CH step (2), time spent (10), score (-1init/0), selected move count (4), picked move (Queen-3 {null -> Row-3}). DEBUG CH step (3), time spent (12), score (-1), selected move count (4), picked move (Queen-0 {null -> Row-1}). INFO Construction Heuristic phase (0) ended: time spent (12), best score (-1), score calculation speed (9000/sec), step total (4). DEBUG LS step (0), time spent (19), score (-1), best score (-1), accepted/selected move count (12/12), picked move (Queen-1 {Row-2 -> Row-3}). DEBUG LS step (1), time spent (24), score (0), new best score (0), accepted/selected move count (9/12), picked move (Queen-3 {Row-3 -> Row-2}). INFO Local Search phase (1) ended: time spent (24), best score (0), score calculation speed (4000/sec), step total (2). INFO Solving ended: time spent (24), best score (0), score calculation speed (7000/sec), phase total (2), environment mode (REPRODUCIBLE). ``` -------------------------------- ### Apply School Timetabling Solver Resource (Minikube) Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-operator/README.adoc Apply the example Solver custom resource to your Minikube cluster. Replace with your target namespace. ```bash kubectl apply -f src/k8s/school-timetabling-solver.yml -n ``` -------------------------------- ### NQueens Solution Class Example Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/planner-configuration/planner-configuration.adoc An example of an NQueens solution class annotated with @PlanningSolution. It holds all problem facts, planning entities, and the score. ```java @PlanningSolution public class NQueens { ``` -------------------------------- ### MoveListFactory Implementation Example Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/move-and-neighborhood-selection/move-and-neighborhood-selection.adoc An example implementation of MoveListFactory that generates CloudComputerChangeMove instances for all processes and computers. ```java public class CloudComputerChangeMoveFactory implements MoveListFactory { @Override public List createMoveList(CloudBalance cloudBalance) { List moveList = new ArrayList<>(); List cloudComputerList = cloudBalance.getComputerList(); for (CloudProcess cloudProcess : cloudBalance.getProcessList()) { for (CloudComputer cloudComputer : cloudComputerList) { moveList.add(new CloudComputerChangeMove(cloudProcess, cloudComputer)); } } return moveList; } } ``` -------------------------------- ### MachineReassignment Incremental Score Calculation Example Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/score-calculation/score-calculation.adoc Example implementation of ConstraintMatchAwareIncrementalScoreCalculator for machine reassignment, demonstrating how to create and add constraint matches. ```java public class MachineReassignmentIncrementalScoreCalculator implements ConstraintMatchAwareIncrementalScoreCalculator { ... @Override public void resetWorkingSolution(MachineReassignment workingSolution, boolean constraintMatchEnabled) { resetWorkingSolution(workingSolution); // ignore constraintMatchEnabled, it is always presumed enabled } @Override public Collection> getConstraintMatchTotals() { ConstraintMatchTotal maximumCapacityMatchTotal = new DefaultConstraintMatchTotal<>(CONSTRAINT_PACKAGE, "maximumCapacity", HardSoftLongScore.ZERO); ... for (MrMachineScorePart machineScorePart : machineScorePartMap.values()) { for (MrMachineCapacityScorePart machineCapacityScorePart : machineScorePart.machineCapacityScorePartList) { if (machineCapacityScorePart.maximumAvailable < 0L) { maximumCapacityMatchTotal.addConstraintMatch( Arrays.asList(machineCapacityScorePart.machineCapacity), HardSoftLongScore.valueOf(machineCapacityScorePart.maximumAvailable, 0)); } } } ... List> constraintMatchTotalList = new ArrayList<>(4); constraintMatchTotalList.add(maximumCapacityMatchTotal); ... return constraintMatchTotalList; } @Override ``` -------------------------------- ### Start OptaPlanner Solver Operator Locally Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-operator/README.adoc Run this command to start the solver operator locally. It will automatically connect to your Kubernetes cluster. ```bash mvn quarkus:dev ``` -------------------------------- ### Local Search Logging Example Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/local-search/local-search.adoc Turn on trace logging to observe the decision-making process of the solver during local search. This helps in understanding how moves are evaluated and accepted. ```log INFO Solver started: time spent (0), score (-6), new best score (-6), random (JDK with seed 0). TRACE Move index (0) not doable, ignoring move (Queen-0 {Row-0 -> Row-0}). TRACE Move index (1), score (-4), accepted (true), move (Queen-0 {Row-0 -> Row-1}). TRACE Move index (2), score (-4), accepted (true), move (Queen-0 {Row-0 -> Row-2}). TRACE Move index (3), score (-4), accepted (true), move (Queen-0 {Row-0 -> Row-3}). ... TRACE Move index (6), score (-3), accepted (true), move (Queen-1 {Row-0 -> Row-3}). ... TRACE Move index (9), score (-3), accepted (true), move (Queen-2 {Row-0 -> Row-3}). ... TRACE Move index (12), score (-4), accepted (true), move (Queen-3 {Row-0 -> Row-3}). DEBUG LS step (0), time spent (6), score (-3), new best score (-3), accepted/selected move count (12/12), picked move (Queen-1 {Row-0 -> Row-3}). ... ``` -------------------------------- ### View Solver Step Details with Debug Logging Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/quickstart/quarkus/quarkus-quickstart.adoc Example of debug log output showing solver steps. Includes time spent, best score, and selected moves. ```log ... Solving started: time spent (67), best score (-20init/0hard/0soft), environment mode (REPRODUCIBLE), random (JDK with seed 0). ... CH step (0), time spent (128), score (-18init/0hard/0soft), selected move count (15), picked move ([Math(101) {null -> Room A}, Math(101) {null -> MONDAY 08:30}]). ... CH step (1), time spent (145), score (-16init/0hard/0soft), selected move count (15), picked move ([Physics(102) {null -> Room A}, Physics(102) {null -> MONDAY 09:30}]). ... ``` -------------------------------- ### Benchmark Blueprint Configuration Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/benchmarking-and-tweaking/benchmarking-and-tweaking.adoc Example of a benchmark blueprint configuration using solverBenchmarkBluePrint for predefined solver configurations. It includes inherited solver settings and problem benchmarks. ```xml local/data/nqueens org.optaplanner.examples.nqueens.domain.NQueens org.optaplanner.examples.nqueens.domain.Queen org.optaplanner.examples.nqueens.score.NQueensConstraintProvider ONLY_DOWN 1 org.optaplanner.examples.nqueens.persistence.NQueensSolutionFileIO data/nqueens/unsolved/32queens.json data/nqueens/unsolved/64queens.json ``` -------------------------------- ### Get Solver Resource (Minikube) Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-operator/README.adoc Check the status of the created Solver custom resource in Minikube. Replace with your target namespace. ```bash kubectl get solver -n ``` -------------------------------- ### Simplest Constraint Stream Example Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/constraint-streams/constraint-streams.adoc The most basic constraint stream, starting with `forEach` and ending with `penalize`. It penalizes every initialized instance of `Shift`. ```java private Constraint penalizeInitializedShifts(ConstraintFactory factory) { return factory.forEach(Shift.class) .penalize(HardSoftScore.ONE_SOFT) .asConstraint("Initialized shift"); } ``` -------------------------------- ### TimeTableController REST Endpoints Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/quickstart/spring-boot/spring-boot-quickstart.adoc These methods handle starting the solver and retrieving the current timetable status. The `solve()` method initiates the optimization process, and `stopSolving()` allows for early termination. ```java @PostMapping("/solve") public void solve() { solverManager.solve(TimeTableRepository.SINGLETON_TIME_TABLE_ID, this::getTimeTable, this::updateTimeTable); } @GetMapping("/getTimeTable") public TimeTable getTimeTable() { return solverManager.getSolverStatus(TimeTableRepository.SINGLETON_TIME_TABLE_ID) == SolverStatus.NOT_SOLVING ? TimeTableRepository.getTimeTable() : solverManager.getBestSolution(TimeTableRepository.SINGLETON_TIME_TABLE_ID); } @PostMapping("/stopSolving") public void stopSolving() { solverManager.terminateEarly(TimeTableRepository.SINGLETON_TIME_TABLE_ID); } } ``` -------------------------------- ### Standstill Interface Example Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/planner-configuration/planner-configuration.adoc Interface used by both anchors and planning entities in a chained planning variable setup. It defines a common method to retrieve the City. ```java public interface Standstill { City getCity(); } ``` -------------------------------- ### Run a Simple Benchmark with Datasets Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/benchmarking-and-tweaking/benchmarking-and-tweaking.adoc Quickly set up a benchmark by creating a PlannerBenchmarkFactory from a solver configuration XML, loading datasets, and building a PlannerBenchmark. The benchmark report is generated and displayed in the browser. ```java PlannerBenchmarkFactory benchmarkFactory = PlannerBenchmarkFactory.createFromSolverConfigXmlResource( "org/optaplanner/examples/cloudbalancing/solver/cloudBalancingSolverConfig.xml"); CloudBalance dataset1 = ...; CloudBalance dataset2 = ...; CloudBalance dataset3 = ...; PlannerBenchmark benchmark = benchmarkFactory.buildPlannerBenchmark( dataset1, dataset2, dataset3); benchmark.benchmarkAndShowReportInBrowser(); ``` -------------------------------- ### Build OptaPlanner with Maven Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/planner-introduction/planner-introduction.adoc Navigate to the cloned optaplanner directory and build the project using Maven. This command skips tests and may take time on the first run due to dependency downloads. ```sh $ cd optaplanner $ mvn clean install -DskipTests ... ``` -------------------------------- ### CustomerNearbyDistanceMeter Example Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/move-and-neighborhood-selection/move-and-neighborhood-selection.adoc An example implementation of `NearbyDistanceMeter` for a vehicle routing problem, calculating distance between a customer and a location-aware destination. ```java public class CustomerNearbyDistanceMeter implements NearbyDistanceMeter { public double getNearbyDistance(Customer origin, LocationAware destination) { return origin.getDistanceTo(destination); } } ``` -------------------------------- ### Build OptaPlanner Project with Maven Source: https://github.com/kiegroup/optaplanner/blob/main/README.adoc Run this Maven command to format your code and enforce style conventions before creating a pull request. ```bash mvn clean install ``` -------------------------------- ### UniConstraintStream Example Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/constraint-streams/constraint-streams.adoc This is a basic example of a UniConstraintStream, which has a cardinality of 1, meaning each constraint match consists of a single object. ```java factory.forEach(Shift.class) ``` -------------------------------- ### Configure Logback for OptaPlanner Output Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/quickstart/hello-world/hello-world-quickstart.adoc Set up logback.xml to display OptaPlanner's INFO level logs, which are crucial for observing the solving process and results. ```xml %d{HH:mm:ss.SSS} [%-12.12t] %-5p %m%n ``` -------------------------------- ### Domicile Class Example Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/planner-configuration/planner-configuration.adoc Example of a Domicile class, which can serve as an anchor in chained planning variables. It implements the Standstill interface. ```java public class Domicile ... implements Standstill { ... public City getCity() {...} } ``` -------------------------------- ### Create NQueens Planning Solution Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/planner-configuration/planner-configuration.adoc Example method to create an uninitialized NQueens planning solution. It sets up the basic structure, including lists of columns, rows, and queens, with planning variables initially null. ```java private NQueens createNQueens(int n) { NQueens nQueens = new NQueens(); nQueens.setId(0L); nQueens.setN(n); nQueens.setColumnList(createColumnList(nQueens)); nQueens.setRowList(createRowList(nQueens)); nQueens.setQueenList(createQueenList(nQueens)); return nQueens; } private List createQueenList(NQueens nQueens) { int n = nQueens.getN(); List queenList = new ArrayList(n); long id = 0L; for (Column column : nQueens.getColumnList()) { Queen queen = new Queen(); queen.setId(id); id++; queen.setColumn(column); // Notice that we leave the PlanningVariable properties on null queenList.add(queen); } return queenList; } ``` -------------------------------- ### JAXB: Pretty XML Output Example Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/integration/integration.adoc Example of pretty XML output for a CloudBalance score marshalled using HardSoftScoreJaxbAdapter. ```xml ... 0hard/-200soft ``` -------------------------------- ### NQueens Advanced Incremental Score Calculator Example Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/score-calculation/score-calculation.adoc An example implementation of IncrementalScoreCalculator for the N-Queens problem, demonstrating incremental score updates. ```java public class NQueensAdvancedIncrementalScoreCalculator implements IncrementalScoreCalculator { private Map> rowIndexMap; private Map> ascendingDiagonalIndexMap; private Map> descendingDiagonalIndexMap; private int score; public void resetWorkingSolution(NQueens nQueens) { int n = nQueens.getN(); rowIndexMap = new HashMap>(n); ascendingDiagonalIndexMap = new HashMap>(n * 2); descendingDiagonalIndexMap = new HashMap>(n * 2); for (int i = 0; i < n; i++) { rowIndexMap.put(i, new ArrayList(n)); ascendingDiagonalIndexMap.put(i, new ArrayList(n)); descendingDiagonalIndexMap.put(i, new ArrayList(n)); if (i != 0) { ascendingDiagonalIndexMap.put(n - 1 + i, new ArrayList(n)); descendingDiagonalIndexMap.put((-i), new ArrayList(n)); } } score = 0; for (Queen queen : nQueens.getQueenList()) { insert(queen); } } public void beforeEntityAdded(Object entity) { // Do nothing } public void afterEntityAdded(Object entity) { insert((Queen) entity); } public void beforeVariableChanged(Object entity, String variableName) { retract((Queen) entity); } public void afterVariableChanged(Object entity, String variableName) { insert((Queen) entity); } public void beforeEntityRemoved(Object entity) { retract((Queen) entity); } public void afterEntityRemoved(Object entity) { // Do nothing } private void insert(Queen queen) { Row row = queen.getRow(); if (row != null) { int rowIndex = queen.getRowIndex(); List rowIndexList = rowIndexMap.get(rowIndex); score -= rowIndexList.size(); rowIndexList.add(queen); List ascendingDiagonalIndexList = ascendingDiagonalIndexMap.get(queen.getAscendingDiagonalIndex()); score -= ascendingDiagonalIndexList.size(); ascendingDiagonalIndexList.add(queen); List descendingDiagonalIndexList = descendingDiagonalIndexMap.get(queen.getDescendingDiagonalIndex()); ``` -------------------------------- ### Configure and Run an Advanced Benchmark Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/benchmarking-and-tweaking/benchmarking-and-tweaking.adoc Build a PlannerBenchmark using a benchmark configuration XML file. This allows for more detailed comparison of different solver configurations against multiple datasets. ```java PlannerBenchmarkFactory benchmarkFactory = PlannerBenchmarkFactory.createFromXmlResource( "org/optaplanner/examples/cloudbalancing/benchmark/cloudBalancingBenchmarkConfig.xml"); PlannerBenchmark benchmark = benchmarkFactory.buildPlannerBenchmark(); benchmark.benchmarkAndShowReportInBrowser(); ``` -------------------------------- ### JSON-B: HardSoftScore Example Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/integration/integration.adoc Example of a HardSoftScore marshalled to JSON using JSON-B and OptaPlannerJsonbConfig. This demonstrates the expected JSON format for scores. ```json {"hardSoftScore":"0hard/-200soft"} ``` -------------------------------- ### Jackson: HardSoftScore JSON Example Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/integration/integration.adoc Example of a HardSoftScore marshalled to JSON using the OptaPlannerJacksonModule. This demonstrates the expected JSON format for scores. ```json { "score":"0hard/-200soft" ... ``` -------------------------------- ### Build PlannerBenchmark with Preloaded Datasets Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/benchmarking-and-tweaking/benchmarking-and-tweaking.adoc Load datasets in advance and pass them to the buildPlannerBenchmark() method for scenarios where datasets are already available in memory or a readily accessible format. ```java PlannerBenchmark plannerBenchmark = benchmarkFactory.buildPlannerBenchmark(dataset1, dataset2, dataset3); ``` -------------------------------- ### Configure Simulated Annealing with Dynamic Parameters Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/benchmarking-and-tweaking/benchmarking-and-tweaking.adoc Sets up solver benchmarks for Simulated Annealing, using Freemarker to dynamically set the startingTemperature and replace '/' with '_' in the benchmark name. ```xml ... ... <#list ["1hard/10soft", "1hard/20soft", "1hard/50soft", "1hard/70soft"] as startingTemperature> Simulated Annealing startingTemperature ${startingTemperature?replace("/", "_")} ${startingTemperature} ``` -------------------------------- ### JSON-B: BendableScore Example Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/integration/integration.adoc Example of a BendableScore marshalled to JSON using JSON-B and OptaPlannerJsonbConfig. This demonstrates the expected JSON format for bendable scores. ```json {"bendableScore":"[0/0]hard/[-200/-20/0]soft"} ``` -------------------------------- ### Configure Separate Construction Heuristics for Multiple Entity Classes Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/construction-heuristics/construction-heuristics.adoc Run a separate Construction Heuristic for each entity class to handle multiple entity types. This example configures one for DogEntity and another for CatEntity. ```xml ...DogEntity PHASE ... ...CatEntity PHASE ... ``` -------------------------------- ### Drools Score Rules Example Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/drools-score-calculation/drools-score-calculation.adoc Example Drools rules demonstrating how to add hard and soft constraint matches using `scoreHolder.addHardConstraintMatch()` and `scoreHolder.addSoftConstraintMatch()`. ```drl global HardSoftScoreHolder scoreHolder; rule "requiredCpuPowerTotal" when ... then scoreHolder.addHardConstraintMatch(...); end ... rule "computerCost" when ... then scoreHolder.addSoftConstraintMatch(...); end ``` -------------------------------- ### Build Solver from XML Resource Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/planner-configuration/planner-configuration.adoc Instantiate a SolverFactory from an XML resource file on the classpath and then build a Solver instance. This is the recommended approach for portability. ```java SolverFactory solverFactory = SolverFactory.createFromXmlResource( "org/optaplanner/examples/nqueens/solver/nqueensSolverConfig.xml"); Solver solver = solverFactory.buildSolver(); ``` -------------------------------- ### Another Problem Fact Class Example Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/planner-configuration/planner-configuration.adoc Another example of a problem fact class, 'Row', demonstrating that problem facts are standard Java objects. ```java public class Row { private int index; // ... getters } ``` -------------------------------- ### Load, Solve, and Print Solution Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/quickstart/hello-world/hello-world-quickstart.adoc Load the problem data, build the solver, solve the problem, and then visualize the resulting timetable. ```java // Load the problem TimeTable problem = generateDemoData(); // Solve the problem Solver solver = solverFactory.buildSolver(); TimeTable solution = solver.solve(problem); // Visualize the solution printTimetable(solution); ``` -------------------------------- ### Jackson: Polymorphic Score JSON Example Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/integration/integration.adoc Example of a Score supertype marshalled to JSON using PolymorphicScoreJacksonSerializer. This includes the score type for correct deserialization. ```json { "score":{"HardSoftScore":"0hard/-200soft"} ... ``` -------------------------------- ### Problem Fact Class Example Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/planner-configuration/planner-configuration.adoc A problem fact is a plain old JavaBean (POJO) that does not change during planning. This example shows a simple 'Column' class. ```java public class Column { private int index; // ... getters } ``` -------------------------------- ### Simplest Partitioned Search Configuration Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/partitioned-search/partitioned-search.adoc Configure the basic partitioned search with a custom solution partitioner class. ```xml org.optaplanner.examples.cloudbalancing.optional.partitioner.CloudBalancePartitioner ``` -------------------------------- ### Jackson: BendableScore JSON Example Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/integration/integration.adoc Example of a BendableScore marshalled to JSON. Note that the hardLevelsSize and softLevelsSize implied in the JSON must match the solution class definition. ```json { "score":"[0/0]hard/[-100/-20/-3]soft" ... ``` -------------------------------- ### Configure Additional OptaPlanner Metrics Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/planner-configuration/planner-configuration.adoc Configure additional metrics for detailed monitoring by adding the `` element to your solver configuration XML. This incurs a performance cost. ```xml BEST_SCORE SCORE_CALCULATION_COUNT ... ... ``` -------------------------------- ### Cloud Balancing ProblemChange Example Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/repeated-planning/repeated-planning.adoc Demonstrates deleting a computer in the cloud balancing use case. It shows how to update planning entities, modify problem fact lists, and remove the problem fact itself using the ProblemChangeDirector. ```java public void deleteComputer(final CloudComputer computer) { solver.addProblemChange((cloudBalance, problemChangeDirector) -> { CloudComputer workingComputer = problemChangeDirector.lookUpWorkingObject(computer); if (workingComputer == null) { throw new IllegalStateException("A computer " + computer + " does not exist. Maybe it has been already deleted."); } // First remove the problem fact from all planning entities that use it for (CloudProcess process : cloudBalance.getProcessList()) { if (process.getComputer() == workingComputer) { problemChangeDirector.changeVariable(process, "computer", workingProcess -> workingProcess.setComputer(null)); } } // A SolutionCloner does not clone problem fact lists (such as computerList) // Shallow clone the computerList so only workingSolution is affected, not bestSolution or guiSolution ArrayList computerList = new ArrayList<>(cloudBalance.getComputerList()); cloudBalance.setComputerList(computerList); // Remove the problem fact itself problemChangeDirector.removeProblemFact(workingComputer, computerList::remove); }); } ``` -------------------------------- ### NQueens Easy Score Calculation Example Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/score-calculation/score-calculation.adoc An example implementation of EasyScoreCalculator for the N-Queens problem, calculating conflicts between queens. It iterates through pairs of queens to check for row and diagonal attacks. ```java public class NQueensEasyScoreCalculator implements EasyScoreCalculator { @Override public SimpleScore calculateScore(NQueens nQueens) { int n = nQueens.getN(); List queenList = nQueens.getQueenList(); int score = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { Queen leftQueen = queenList.get(i); Queen rightQueen = queenList.get(j); if (leftQueen.getRow() != null && rightQueen.getRow() != null) { if (leftQueen.getRowIndex() == rightQueen.getRowIndex()) { score--; } if (leftQueen.getAscendingDiagonalIndex() == rightQueen.getAscendingDiagonalIndex()) { score--; } ``` -------------------------------- ### Gradle Dependencies for OptaPlanner Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/quickstart/hello-world/hello-world-quickstart.adoc Configure your build.gradle file with OptaPlanner core and logging dependencies. ```groovy plugins { id "java" id "application" } def optaplannerVersion = "{optaplanner-version}" def logbackVersion = "1.2.9" group = "org.acme" version = "1.0-SNAPSHOT" repositories { mavenCentral() } dependencies { implementation platform("org.optaplanner:optaplanner-bom:${optaplannerVersion}") implementation "org.optaplanner:optaplanner-core" testImplementation "org.optaplanner:optaplanner-test" runtimeOnly "ch.qos.logback:logback-classic:${logbackVersion}" } java { sourceCompatibility = JavaVersion.VERSION_11 targetCompatibility = JavaVersion.VERSION_11 } compileJava { options.encoding = "UTF-8" options.compilerArgs << "-parameters" } compileTestJava { options.encoding = "UTF-8" } application { mainClass = "org.acme.schooltimetabling.TimeTableApp" } test { // Log the test execution results. testLogging { events "passed", "skipped", "failed" } } ``` -------------------------------- ### Simple First Fit Configuration Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/construction-heuristics/construction-heuristics.adoc Configure the First Fit construction heuristic. This is the simplest way to enable the algorithm. ```xml FIRST_FIT ``` -------------------------------- ### JAXB: Bendable Score XML Output Example Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/integration/integration.adoc Example of XML output for a bendable score with 2 hard levels and 3 soft levels, marshalled using BendableScoreJaxbAdapter. ```xml ... [0/0]hard/[-100/-20/-3]soft ``` -------------------------------- ### Create VS Code Settings File Source: https://github.com/kiegroup/optaplanner/blob/main/build/optaplanner-ide-config/ide-configuration.adoc This command sequence creates the necessary .vscode directory and settings.json file for VS Code. ```shell cd optaplanner mkdir .vscode touch .vscode/settings.json ``` -------------------------------- ### CHEAPEST_INSERTION Simple Configuration Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/construction-heuristics/construction-heuristics.adoc Simple configuration for the CHEAPEST_INSERTION construction heuristic. ```xml CHEAPEST_INSERTION ``` -------------------------------- ### Get Solver Resource (OpenShift) Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-operator/README.adoc Check the status of the created Solver custom resource in OpenShift. ```bash oc get solver ``` -------------------------------- ### Apply OptaPlanner Operator Deployment Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-operator/README.adoc Apply the deployment template for the OptaPlanner Operator. ```bash oc apply -f optaplanner-operator.yml ``` -------------------------------- ### Get All Constraint Justifications Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/score-calculation/score-calculation.adoc Retrieve a list of all constraint justifications from the ScoreExplanation. This is useful for understanding the details of why a score was achieved. ```java List constraintJustificationlist = scoreExplanation.getJustificationList(); ``` -------------------------------- ### Configure Benchmark Warm-up Time (60 seconds) Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/benchmarking-and-tweaking/benchmarking-and-tweaking.adoc Adjust the warm-up phase duration for benchmarks to ensure more reliable results by allowing the HotSpot JIT compiler to stabilize. Set to 60 seconds. ```xml ... 60 ... ``` -------------------------------- ### Build Planner Benchmark from Freemarker XML Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/benchmarking-and-tweaking/benchmarking-and-tweaking.adoc Instantiates PlannerBenchmarkFactory from a Freemarker XML resource and builds the PlannerBenchmark object. ```java PlannerBenchmarkFactory benchmarkFactory = PlannerBenchmarkFactory.createFromFreemarkerXmlResource( "org/optaplanner/examples/cloudbalancing/optional/benchmark/cloudBalancingBenchmarkConfigTemplate.xml.ftl"); PlannerBenchmark benchmark = benchmarkFactory.buildPlannerBenchmark(); ``` -------------------------------- ### Custom Move: getPlanningValues() Example Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/move-and-neighborhood-selection/move-and-neighborhood-selection.adoc Implement getPlanningValues() to return a collection of the values to which planning entities are changing. Used for value tabu. ```java @Override public Collection getPlanningValues() { return Collections.singletonList(toCloudComputer); } ``` -------------------------------- ### Custom Move: getPlanningEntities() Example Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/move-and-neighborhood-selection/move-and-neighborhood-selection.adoc Implement getPlanningEntities() to return a collection of planning entities affected by this move. Used for entity tabu. ```java @Override public Collection getPlanningEntities() { return Collections.singletonList(cloudProcess); } ``` -------------------------------- ### Implementing toString() for Readable Logs Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/move-and-neighborhood-selection/move-and-neighborhood-selection.adoc Implement the toString() method for moves to ensure OptaPlanner's logs are readable and consistent. Keep the output non-verbose. ```java public String toString() { return cloudProcess + " {" + cloudProcess.getComputer() + " -> " + toCloudComputer + "}"; } ``` -------------------------------- ### Implementing a Fine-Grained Move Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/move-and-neighborhood-selection/move-and-neighborhood-selection.adoc This is an example of a fine-grained move that changes only one planning variable. It demonstrates how to notify the ScoreDirector before and after modifying the variable. ```java public CloudComputerChangeMove(CloudProcess cloudProcess, CloudComputer toCloudComputer) { this.cloudProcess = cloudProcess; this.toCloudComputer = toCloudComputer; } @Override protected void doMoveOnGenuineVariables(ScoreDirector scoreDirector) { scoreDirector.beforeVariableChanged(cloudProcess, "computer"); cloudProcess.setComputer(toCloudComputer); scoreDirector.afterVariableChanged(cloudProcess, "computer"); } ``` -------------------------------- ### Checking if a Move is Doable Source: https://github.com/kiegroup/optaplanner/blob/main/optaplanner-docs/src/modules/ROOT/pages/move-and-neighborhood-selection/move-and-neighborhood-selection.adoc Implement the isMoveDoable method to filter out non-doable moves. This example checks if the process is already assigned to the target computer. ```java @Override public boolean isMoveDoable(ScoreDirector scoreDirector) { return !Objects.equals(cloudProcess.getComputer(), toCloudComputer); } ```