repo_name stringlengths 1 62 | dataset stringclasses 1 value | lang stringclasses 11 values | pr_id int64 1 20.1k | owner stringlengths 2 34 | reviewer stringlengths 2 39 | diff_hunk stringlengths 15 262k | code_review_comment stringlengths 1 99.6k |
|---|---|---|---|---|---|---|---|
timefold-solver | github_2023 | others | 734 | TimefoldAI | zepfred | @@ -366,89 +368,109 @@ A xref:using-timefold-solver/running-the-solver.adoc#logging[logging level] of `
and slow down the xref:constraints-and-score/performance.adoc#scoreCalculationSpeed[score calculation speed].
====
-[#planningId]
-==== `@PlanningId`
-
-For some functionality (such as multi-threaded solving and real-time planning),
-Timefold Solver needs to map problem facts and planning entities to an ID.
-Timefold Solver uses that ID to _rebase_ a move from one thread's solution state to another's.
-To enable such functionality, specify the `@PlanningId` annotation on the identification field or getter method,
-for example on the database ID:
-
-[source,java,options="nowrap"]
-----
-public class Visit {
+[#multithreadedIncrementalSolving]
+==== Multi-threaded incremental solving
- @PlanningId
- private String username;
+With this feature, the solver can run significantly faster, getting you the right solution earlier.
+It is especially useful for large datasets, where score calculation speed is the bottleneck. | ```suggestion
It is especially useful for large datasets,
where score calculation speed is the bottleneck.
``` |
timefold-solver | github_2023 | others | 734 | TimefoldAI | zepfred | @@ -366,89 +368,109 @@ A xref:using-timefold-solver/running-the-solver.adoc#logging[logging level] of `
and slow down the xref:constraints-and-score/performance.adoc#scoreCalculationSpeed[score calculation speed].
====
-[#planningId]
-==== `@PlanningId`
-
-For some functionality (such as multi-threaded solving and real-time planning),
-Timefold Solver needs to map problem facts and planning entities to an ID.
-Timefold Solver uses that ID to _rebase_ a move from one thread's solution state to another's.
-To enable such functionality, specify the `@PlanningId` annotation on the identification field or getter method,
-for example on the database ID:
-
-[source,java,options="nowrap"]
-----
-public class Visit {
+[#multithreadedIncrementalSolving]
+==== Multi-threaded incremental solving
- @PlanningId
- private String username;
+With this feature, the solver can run significantly faster, getting you the right solution earlier.
+It is especially useful for large datasets, where score calculation speed is the bottleneck.
- ...
-}
-----
+The following table shows the observed score calculation speeds
+of the Vehicle Routing Problem and the Maintenance Scheduling Problem,
+as the number of threads increases:
-A `@PlanningId` property must be:
+|===
+|Number of Threads |Vehicle Routing |Maintenance Scheduling
-* Unique for that specific class
-** It does not need to be unique across different problem fact classes
-(unless in that rare case that those classes are mixed in the same value range or planning entity collection).
-* An instance of a type that implements `Object.hashCode()` and `Object.equals()`.
-** It's recommended to use the type `Integer`, `int`, `Long`, `long`, `String` or `UUID`.
-* Never `null` by the time `Solver.solve()` is called.
+|1
+|~ 22,000
+|~ 6,000
+|2
+|~ 40,000
+|~ 11,000
-[#customThreadFactory]
-==== Custom thread factory (WildFly, GAE, ...)
+|4
+|~ 70,000
+|~ 19,000
+|===
-The `threadFactoryClass` allows to plug in a custom `ThreadFactory` for environments
-where arbitrary thread creation should be avoided,
-such as most application servers (including WildFly) or Google App Engine.
+As we can see, the speed increases with the number of threads,
+but the scaling is not exactly linear due to the overhead of managing communication between multiple thread. | ```suggestion
but the scaling is not exactly linear due to the overhead of managing communication between multiple threads.
``` |
timefold-solver | github_2023 | others | 734 | TimefoldAI | zepfred | @@ -366,89 +368,109 @@ A xref:using-timefold-solver/running-the-solver.adoc#logging[logging level] of `
and slow down the xref:constraints-and-score/performance.adoc#scoreCalculationSpeed[score calculation speed].
====
-[#planningId] | The page responding-to-change.adoc still references this section |
timefold-solver | github_2023 | others | 730 | TimefoldAI | zepfred | @@ -301,50 +301,12 @@ To pin the entire list, preventing any modifications to the list whatsoever,
Replanning an existing plan can be very disruptive.
If the plan affects humans (such as employees, drivers, ...), very disruptive changes are often undesirable.
-In such cases, nonvolatile replanning helps by restricting planning freedom: the gain of changing a plan must be higher than the disruption it causes.
+In such cases, nonvolatile replanning helps by restricting planning freedom:
+the gain of changing a plan must be higher than the disruption it causes.
This is usually implemented by taxing all planning entities that change.
image::responding-to-change/nonDisruptiveReplanning.png[align="center"]
-In the machine reassignment example, the entity has both the planning variable `machine` and its original value ``originalMachine``: | Can we retain this example? It appears intersting to me. |
timefold-solver | github_2023 | others | 730 | TimefoldAI | zepfred | @@ -1648,48 +1525,8 @@ public interface ConstraintMatchAwareIncrementalScoreCalculator<Solution_, Score
}
----
-For example in machine reassignment, create one `ConstraintMatchTotal` per constraint type and call `addConstraintMatch()` for each constraint match: | Can we keep or replace the code by another example? |
timefold-solver | github_2023 | others | 730 | TimefoldAI | zepfred | @@ -1810,114 +1728,38 @@ To use a custom cloner, configure it on the planning solution:
[source,java,options="nowrap"]
----
-@PlanningSolution(solutionCloner = NQueensSolutionCloner.class)
-public class NQueens {
+@PlanningSolution(solutionCloner = TimetableSolutionCloner.class)
+public class Timetable {
...
}
----
-For example, a `NQueens` planning clone only deep clones all `Queen` instances.
-So when the original solution changes (later on during planning) and one or more ``Queen`` instances change,
+For example, a `Timetable` planning clone only deep clones all `Timetable` instances.
+So when the original solution changes (later on during planning) and one or more ``Timetable`` instances change,
the planning clone isn't affected.
-[source,java,options="nowrap"]
-----
-public class NQueensSolutionCloner implements SolutionCloner<NQueens> {
-
- @Override
- public NQueens cloneSolution(CloneLedger ledger, NQueens original) {
- NQueens clone = new NQueens();
- ledger.registerClone(original, clone);
- clone.setId(original.getId());
- clone.setN(original.getN());
- clone.setColumnList(original.getColumnList());
- clone.setRowList(original.getRowList());
- List<Queen> queenList = original.getQueenList();
- List<Queen> clonedQueenList = new ArrayList<Queen>(queenList.size());
- for (Queen originalQueen : queenList) {
- Queen cloneQueen = new Queen();
- ledger.registerClone(originalQueen, cloneQueen);
- cloneQueen.setId(originalQueen.getId());
- cloneQueen.setColumn(originalQueen.getColumn());
- cloneQueen.setRow(originalQueen.getRow());
- clonedQueenList.add(cloneQueen);
- }
- clone.setQueenList(clonedQueenList);
- clone.setScore(original.getScore());
- return clone;
- }
-
-}
-----
-
_The `cloneSolution()` method should only deep clone the planning entities._
-Notice that the problem facts, such as `Column` and `Row` are normally _not_ cloned: even their `List` instances are _not_ cloned.
-If the problem facts were cloned too, then you would have to make sure that the new planning entity clones also refer to the new problem facts clones used by the cloned solution.
-For example, if you were to clone all `Row` instances, then each `Queen` clone and the `NQueens` clone itself should refer to those new `Row` clones.
+The problem facts, such as `Timeslot` and `Room` are normally _not_ cloned: even their `List` instances are _not_ cloned.
+If the problem facts were cloned too,
+then you would have to make sure that the new planning entity clones also refer to the new problem facts clones used by the cloned solution.
+For example, if you were to clone all `Timeslot` instances,
+then each `Lesson` clone and the `Timetable` clone itself should refer to those new `Timeslot` clones.
[WARNING]
====
-Cloning an entity with a <<chainedPlanningVariable,chained>> variable is devious: a variable of an entity A might point to another entity B.
+Cloning an entity with a <<chainedPlanningVariable,chained>> variable is devious:
+a variable of an entity A might point to another entity B.
If A is cloned, then its variable must point to the clone of B, not the original B.
====
[#createAnUninitializedSolution]
=== Create an uninitialized solution
-Create a `@PlanningSolution` instance to represent your planning problem's dataset, so it can be set on the `Solver` as the planning problem to solve. | Let's add an initialization snippet from school timetabling quickstart. |
timefold-solver | github_2023 | others | 730 | TimefoldAI | zepfred | @@ -23,7 +23,7 @@ Annotate it with `@ConstraintConfiguration`:
[source,java,options="nowrap"]
----
@ConstraintConfiguration
-public class ConferenceConstraintConfiguration { | Why are we replacing conference scheduling with vehicle routing? |
timefold-solver | github_2023 | others | 730 | TimefoldAI | zepfred | @@ -142,11 +143,15 @@ image::constraints-and-score/overview/scoreFoldingIsBroken.png[align="center"]
[NOTE]
====
-Your business might tell you that your hard constraints all have the same weight, because they cannot be broken (so the weight does not matter). This is not true because if no feasible solution exists for a specific dataset, the least infeasible solution allows the business to estimate how many business resources they are lacking.
-For example in cloud balancing, how many new computers to buy.
+Your business might tell you that your hard constraints all have the same weight,
+because they cannot be broken (so the weight does not matter).
+This is not true because if no feasible solution exists for a specific dataset,
+the least infeasible solution allows the business to estimate how many business resources they are lacking.
Furthermore, it will likely create a xref:constraints-and-score/performance.adoc#scoreTrap[score trap].
-For example in cloud balance if a `Computer` has seven CPU too little for its ``Process``es, then it must be weighted seven times as much as if it had only one CPU too little.
+For example in vehicle routing if a vehicle exceeds its capacity by 15 tons, | ```suggestion
For example, in vehicle routing, if a vehicle exceeds its capacity by 15 tons,
``` |
timefold-solver | github_2023 | others | 730 | TimefoldAI | zepfred | @@ -195,20 +190,20 @@ get the `Indictment` map from the ``ScoreExplanation``:
[source,java,options="nowrap"]
----
-SolutionManager<CloudBalance, HardSoftScore> scoreManager = SolutionManager.create(solverFactory);
-ScoreExplanation<CloudBalance, HardSoftScore> scoreExplanation = solutionManager.explain(cloudBalance);
-Map<Object, Indictment<HardSoftScore>> indictmentMap = scoreExplanation.getIndictmentMap();
-for (CloudProcess process : cloudBalance.getProcessList()) {
- Indictment<HardSoftScore> indictment = indictmentMap.get(process);
+SolutionManager<VehicleRoutePlan, HardSoftLongScore> solutionManager = SolutionManager.create(solverFactory);
+ScoreExplanation<VehicleRoutePlan, HardSoftLongScore> scoreExplanation = solutionManager.explain(vehicleRoutePlan);
+Map<Object, Indictment<HardSoftLongScore>> indictmentMap = scoreExplanation.getIndictmentMap();
+for (Visit visit : vehicleRoutePlan.getVisitList()) { | ```suggestion
for (Visit visit : vehicleRoutePlan.getVisitList()) {
```
```suggestion
for (Visit visit : vehicleRoutePlan.getVisitList()) {
```
```suggestion
for (Visit visit : vehicleRoutePlan.getVisitList()) {
```
```suggestion
for (Visit visit : vehicleRoutePlan.getVisitList()) {
```
```suggestion
for (Visit visit : vehicleRoutePlan.getVisitList()) {
```
```suggestion
for (Visit visit : vehicleRoutePlan.getVisitList()) {
```
```suggestion
for (Visit visit : vehicleRoutePlan.getVisitList()) {
```
```suggestion
for (Visit visit : vehicleRoutePlan.getVisitList()) {
```
```suggestion
for (Visit visit : vehicleRoutePlan.getVisits()) {
``` |
timefold-solver | github_2023 | others | 730 | TimefoldAI | zepfred | @@ -686,21 +684,9 @@ public interface Solver<Solution_> {
----
The ``BestSolutionChangedEvent``'s `newBestSolution` may not be initialized or feasible.
-Use the `isFeasible()` method on ``BestSolutionChangedEvent``'s new best `Score` to detect such cases:
- | Can we keep/replace this snippet? |
timefold-solver | github_2023 | others | 730 | TimefoldAI | zepfred | @@ -2235,7 +2203,8 @@ public interface SelectionProbabilityWeightFactory<Solution_, T> {
</entitySelector>
----
-For example, if there are three entities: process A (probabilityWeight 2.0), process B (probabilityWeight 0.5) and process C (probabilityWeight 0.5), then process A will be selected four times more than B and C.
+Assume the following entities: process A (probabilityWeight 2.0), process B (probabilityWeight 0.5) and process C (probabilityWeight 0.5).
+Then process A will be selected four times more than B and C. | Should we replace the word process by visit or any other model name? |
timefold-solver | github_2023 | others | 730 | TimefoldAI | zepfred | @@ -2399,59 +2344,27 @@ it must not change any of the problem facts as that will cause score corruption.
Use xref:responding-to-change/responding-to-change.adoc#realTimePlanning[real-time planning] to change problem facts while solving.
====
-Timefold Solver automatically filters out _non doable moves_ by calling the `isMoveDoable(ScoreDirector)` method on each selected move.
+Timefold Solver automatically filters out _non doable moves_
+by calling the `isMoveDoable(ScoreDirector)` method on each selected move.
A _non doable move_ is:
* A move that changes nothing on the current solution.
-For example, moving process `P1` on computer `X` to computer `X` is not doable, because it is already there.
+For example, moving visit `V1` from vehicle `X` to vehicle `X` is not doable, because it is already there.
* A move that is impossible to do on the current solution.
-For example, moving process `P1` to computer `Q` (when `Q` isn't in the list of computers) is not doable
+For example, moving visit `V1` to vehicle `Y` (when `Y` isn't in the list of vehicles) is not doable,
because it would assign a planning value that's not inside the planning variable's value range.
-In the cloud balancing example, a move which assigns a process to the computer it's already assigned to is not doable:
-
-[source,java,options="nowrap"]
-----
- @Override
- public boolean isMoveDoable(ScoreDirector<CloudBalance> scoreDirector) {
- return !Objects.equals(cloudProcess.getComputer(), toCloudComputer);
- }
-----
-
-We don't need to check if `toCloudComputer` is in the value range,
-because we only generate moves for which that is the case.
A move that is currently not doable can become doable when the working solution changes in a later step,
otherwise we probably shouldn't have created it in the first place.
Each move has an __undo move__: a move (normally of the same type) which does the exact opposite.
-In the cloud balancing example the undo move of `P1 {X -> Y}` is the move `P1 {Y -> X}`.
-The undo move of a move is created when the `Move` is being done on the current solution,
-before the genuine variables change: | Let's add another example. |
timefold-solver | github_2023 | others | 730 | TimefoldAI | zepfred | @@ -2519,12 +2432,12 @@ and return all their values (to which they are changing) in ``getPlanningValues(
----
@Override | Let's add another code? |
timefold-solver | github_2023 | others | 730 | TimefoldAI | zepfred | @@ -2991,11 +2857,9 @@ For example, on N queens it hits wall at a few dozen queens:
image::optimization-algorithms/exhaustiveSearchScalabilityNQueens.png[align="center"]
-In most use cases, such as Cloud Balancing, the wall appears out of thin air:
-
-image::optimization-algorithms/exhaustiveSearchScalabilityCloudBalance.png[align="center"]
-
-*Exhaustive Search hits this wall on small datasets already, so in production these optimizations algorithms are mostly useless.* Use Construction Heuristics with Local Search instead: those can handle thousands of queens/computers easily.
+In most use cases, the wall appears out of thin air. | Let's delete the image exhaustiveSearchScalabilityCloudBalance.png. |
timefold-solver | github_2023 | others | 730 | TimefoldAI | zepfred | @@ -200,41 +200,11 @@ To attain a schedule in which certain entities are scheduled earlier in the sche
Only consider adding planning entity difficulty too if it can make the solver more efficient.
====
-To allow the heuristics to take advantage of that domain specific information, set a `difficultyComparatorClass` to the `@PlanningEntity` annotation: | Let's reuse the VRP code you showed before. |
timefold-solver | github_2023 | others | 730 | TimefoldAI | zepfred | @@ -1044,45 +1014,18 @@ To affect the score function, xref:constraints-and-score/overview.adoc#formalize
Only consider adding planning value strength too if it can make the solver more efficient.
====
-To allow the heuristics to take advantage of that domain specific information, set a `strengthComparatorClass` to the `@PlanningVariable` annotation: | Let's add a code snippet. |
timefold-solver | github_2023 | others | 730 | TimefoldAI | zepfred | @@ -1044,45 +1014,18 @@ To affect the score function, xref:constraints-and-score/overview.adoc#formalize
Only consider adding planning value strength too if it can make the solver more efficient.
====
-To allow the heuristics to take advantage of that domain specific information, set a `strengthComparatorClass` to the `@PlanningVariable` annotation:
-
-[source,java,options="nowrap"]
-----
- @PlanningVariable(..., strengthComparatorClass = CloudComputerStrengthComparator.class)
- public CloudComputer getComputer() {
- return computer;
- }
-----
-
-[source,java,options="nowrap"]
-----
-public class CloudComputerStrengthComparator implements Comparator<CloudComputer> {
-
- public int compare(CloudComputer a, CloudComputer b) {
- return new CompareToBuilder()
- .append(a.getMultiplicand(), b.getMultiplicand())
- .append(b.getCost(), a.getCost()) // Descending (but this is debatable)
- .append(a.getId(), b.getId())
- .toComparison();
- }
-
-}
-----
+To allow the heuristics to take advantage of that domain specific information,
+set a `strengthComparatorClass` to the `@PlanningVariable` annotation.
[NOTE]
====
-If you have multiple planning value classes in the _same_ value range, the `strengthComparatorClass` needs to implement a `Comparator` of a common superclass (for example ``Comparator<Object>``) and be able to handle comparing instances of those different classes.
+If you have multiple planning value classes in the _same_ value range,
+the `strengthComparatorClass` needs to implement a `Comparator` of a common superclass (for example ``Comparator<Object>``)
+and be able to handle comparing instances of those different classes.
====
-Alternatively, you can also set a `strengthWeightFactoryClass` to the `@PlanningVariable` annotation, so you have access to the rest of the problem facts from the solution too:
- | Let's add a code snippet |
timefold-solver | github_2023 | others | 730 | TimefoldAI | zepfred | @@ -1401,48 +1409,12 @@ public interface EasyScoreCalculator<Solution_, Score_ extends Score<Score_>> {
}
----
-For example in N-queens:
-
-[source,java,options="nowrap"]
-----
-public class NQueensEasyScoreCalculator | Let's add an EasyScoreCalculator code snippet. |
timefold-solver | github_2023 | others | 730 | TimefoldAI | zepfred | @@ -1504,113 +1476,18 @@ public interface IncrementalScoreCalculator<Solution_, Score_ extends Score<Scor
image::constraints-and-score/score-calculation/incrementalScoreCalculatorSequenceDiagram.png[align="center"]
-For example in n queens:
-
-[source,java,options="nowrap"]
-----
-public class NQueensAdvancedIncrementalScoreCalculator | Does it make sense to add the incremental score calculator? |
timefold-solver | github_2023 | others | 730 | TimefoldAI | zepfred | @@ -2121,49 +2091,14 @@ public interface SelectionSorterWeightFactory<Solution_, T> {
}
----
-[source,java,options="nowrap"]
-----
-public class QueenDifficultyWeightFactory implements SelectionSorterWeightFactory<NQueens, Queen> {
-
- public QueenDifficultyWeight createSorterWeight(NQueens nQueens, Queen queen) {
- int distanceFromMiddle = calculateDistanceFromMiddle(nQueens.getN(), queen.getColumnIndex());
- return new QueenDifficultyWeight(queen, distanceFromMiddle);
- }
-
- ...
-
- public static class QueenDifficultyWeight implements Comparable<QueenDifficultyWeight> {
-
- private final Queen queen;
- private final int distanceFromMiddle;
-
- public QueenDifficultyWeight(Queen queen, int distanceFromMiddle) {
- this.queen = queen;
- this.distanceFromMiddle = distanceFromMiddle;
- }
-
- public int compareTo(QueenDifficultyWeight other) {
- return new CompareToBuilder()
- // The more difficult queens have a lower distance to the middle
- .append(other.distanceFromMiddle, distanceFromMiddle) // Decreasing
- // Tie breaker
- .append(queen.getColumnIndex(), other.queen.getColumnIndex())
- .toComparison();
- }
-
- }
-
-}
-----
-
You'll also need to configure it (unless it's annotated on the domain model and automatically applied by the optimization algorithm): | Can we use a VRP example here? |
timefold-solver | github_2023 | others | 730 | TimefoldAI | zepfred | @@ -245,8 +203,9 @@ For example, in bin packing: small item < medium item < big item.
Although most algorithms start with the more difficult entities first, they just reverse the ordering.
====
-_None of the current planning variable states should be used to compare planning entity difficulty._ During Construction Heuristics, those variables are likely to be `null` anyway.
-For example, a ``Queen``'s `row` variable should not be used.
+_None of the current planning variable states should be used to compare planning entity difficulty._
+During Construction Heuristics, those variables are likely to be `null` anyway.
+For example, a ``Lessons``'s `timeslot` variable should not be used. | ```suggestion
For example, a ``Lesson``'s `timeslot` variable should not be used.
``` |
timefold-solver | github_2023 | others | 730 | TimefoldAI | zepfred | @@ -258,29 +217,33 @@ For example, a ``Queen``'s `row` variable should not be used.
A planning variable is a JavaBean property (so a getter and setter) on a planning entity.
It points to a planning value, which changes during planning.
-For example, a ``Queen``'s `row` property is a genuine planning variable.
-Note that even though a ``Queen``'s `row` property changes to another `Row` during planning, no `Row` instance itself is changed.
+For example, a ``Lessons``'s `timeslot` property is a genuine planning variable. | The domain name `Lessons` is being used in other places. |
timefold-solver | github_2023 | others | 730 | TimefoldAI | zepfred | @@ -1810,114 +1728,38 @@ To use a custom cloner, configure it on the planning solution:
[source,java,options="nowrap"]
----
-@PlanningSolution(solutionCloner = NQueensSolutionCloner.class)
-public class NQueens {
+@PlanningSolution(solutionCloner = TimetableSolutionCloner.class)
+public class Timetable {
...
}
----
-For example, a `NQueens` planning clone only deep clones all `Queen` instances.
-So when the original solution changes (later on during planning) and one or more ``Queen`` instances change,
+For example, a `Timetable` planning clone only deep clones all `Timetable` instances.
+So when the original solution changes (later on during planning) and one or more ``Timetable`` instances change,
the planning clone isn't affected.
-[source,java,options="nowrap"]
-----
-public class NQueensSolutionCloner implements SolutionCloner<NQueens> {
-
- @Override
- public NQueens cloneSolution(CloneLedger ledger, NQueens original) {
- NQueens clone = new NQueens();
- ledger.registerClone(original, clone);
- clone.setId(original.getId());
- clone.setN(original.getN());
- clone.setColumnList(original.getColumnList());
- clone.setRowList(original.getRowList());
- List<Queen> queenList = original.getQueenList();
- List<Queen> clonedQueenList = new ArrayList<Queen>(queenList.size());
- for (Queen originalQueen : queenList) {
- Queen cloneQueen = new Queen();
- ledger.registerClone(originalQueen, cloneQueen);
- cloneQueen.setId(originalQueen.getId());
- cloneQueen.setColumn(originalQueen.getColumn());
- cloneQueen.setRow(originalQueen.getRow());
- clonedQueenList.add(cloneQueen);
- }
- clone.setQueenList(clonedQueenList);
- clone.setScore(original.getScore());
- return clone;
- }
-
-}
-----
-
_The `cloneSolution()` method should only deep clone the planning entities._ | Let's add a partial code snippet for Timetable solution cloner. |
timefold-solver | github_2023 | others | 730 | TimefoldAI | zepfred | @@ -41,17 +41,18 @@ Just provide the planning problem as argument to the `solve()` method and it wil
[source,java,options="nowrap"]
----
- NQueens problem = ...;
- NQueens bestSolution = solver.solve(problem);
+ Timetable problem = ...;
+ Timetable bestSolution = solver.solve(problem);
----
-For example in n queens, the `solve()` method will return an `NQueens` instance with every `Queen` assigned to a ``Row``.
+For example in school timetabling, | ```suggestion
For example, in school timetabling,
``` |
timefold-solver | github_2023 | others | 730 | TimefoldAI | zepfred | @@ -41,17 +41,18 @@ Just provide the planning problem as argument to the `solve()` method and it wil
[source,java,options="nowrap"]
----
- NQueens problem = ...;
- NQueens bestSolution = solver.solve(problem);
+ Timetable problem = ...;
+ Timetable bestSolution = solver.solve(problem);
----
-For example in n queens, the `solve()` method will return an `NQueens` instance with every `Queen` assigned to a ``Row``.
+For example in school timetabling,
+the `solve()` method will return a `Timetable` instance with every `Lesson` assigned to a `Teacher` and a `Timeslot`.
-.Best Solution for the Four Queens Puzzle in 8ms (Also an Optimal Solution)
-image::using-timefold-solver/running-the-solver/solvedNQueens04.png[align="left"] | Let's delete the image solvedNQueens04.png |
timefold-solver | github_2023 | java | 727 | TimefoldAI | triceo | @@ -0,0 +1,5 @@
+package ai.timefold.solver.core.impl.domain.solution.cloner;
+
+public interface PlanningCloneable<T> {
+ T createEmptyInstance(); | I'd like this interface to have wider use. It should not only serve for collections, it should serve for any type.
To that end, the method should be called `createNewInstance()`, and the cloner should be adapted to handle it. As a test case, if it can clone a cloneable planning entity inside of a non-cloneable planning solution, that will be enough proof. |
timefold-solver | github_2023 | java | 727 | TimefoldAI | triceo | @@ -228,12 +232,16 @@ private <K, V> Map<K, V> cloneMap(Class<?> expectedType, Map<K, V> originalMap,
return cloneMap;
}
+ @SuppressWarnings("unchecked")
private static <K, V> Map<K, V> constructCloneMap(Map<K, V> originalMap) {
// Normally, a Map will never be selected for cloning, but extending implementations might anyway.
if (originalMap instanceof SortedMap<K, V> map) {
var setComparator = map.comparator();
return new TreeMap<>(setComparator);
}
+ if (originalMap instanceof PlanningCloneable<?> planningClonable) {
+ return (Map<K, V>) planningClonable.createEmptyInstance();
+ } | Why shouldn't this go first? Why does `TreeMap` get precedence? |
timefold-solver | github_2023 | java | 727 | TimefoldAI | triceo | @@ -0,0 +1,5 @@
+package ai.timefold.solver.core.impl.domain.solution.cloner;
+
+public interface PlanningCloneable<T> { | The interface needs a good description of what it's for, what will happen when used, and how the method should be implemented. |
timefold-solver | github_2023 | others | 723 | TimefoldAI | zepfred | @@ -3,26 +3,12 @@ updates:
- package-ecosystem: maven
directory: "/"
schedule:
- interval: daily
- time: '05:00'
+ interval: weekly | Should we keep the scheduling time? |
timefold-solver | github_2023 | others | 685 | TimefoldAI | triceo | @@ -759,5 +760,191 @@ the host is likely to hang or freeze,
unless there is an OS specific policy in place to avoid Timefold Solver from hogging all the CPU processors.
====
+[#automaticNodeSharing]
+=== Automatic node sharing
+[NOTE]
+====
+This feature is a commercial feature of Timefold Solver Enterprise Edition.
+It is not available in the Community Edition.
+====
+
+When a `ConstraintProvider` does an operation for multiple constraints (such as finding all shifts corresponding to an employee), that work can be shared.
+This can massively improve score calculation speed if the repeated operation is computationally expensive. | ```suggestion
This can significantly improve score calculation speed if the repeated operation is computationally expensive.
``` |
timefold-solver | github_2023 | others | 685 | TimefoldAI | triceo | @@ -759,5 +760,191 @@ the host is likely to hang or freeze,
unless there is an OS specific policy in place to avoid Timefold Solver from hogging all the CPU processors.
====
+[#automaticNodeSharing]
+=== Automatic node sharing
+[NOTE]
+====
+This feature is a commercial feature of Timefold Solver Enterprise Edition.
+It is not available in the Community Edition.
+====
+
+When a `ConstraintProvider` does an operation for multiple constraints (such as finding all shifts corresponding to an employee), that work can be shared.
+This can massively improve score calculation speed if the repeated operation is computationally expensive.
+
+==== Configuration
+
+[tabs]
+======
+Plain Java::
+
+* Add `<constraintStreamAutomaticNodeSharing>true</constraintStreamAutomaticNodeSharing>` in your `solverConfig.xml`:
++
+[source,xml,options="nowrap"]
+----
+<!-- ... -->
+<scoreDirectorFactory>
+ <constraintProviderClass>org.acme.MyConstraintProvider</constraintProviderClass>
+ <constraintStreamAutomaticNodeSharing>true</constraintStreamAutomaticNodeSharing>
+</scoreDirectorFactory>
+<!-- ... -->
+----
+
+Spring Boot::
+
+Set the property `timefold.solver.constraint-stream-automatic-node-sharing` to `true` in `application.properties`:
++
+[source,properties,options="nowrap"]
+----
+timefold.solver.constraint-stream-automatic-node=true
+----
+
+Quarkus::
+
+Set the property `quarkus.timefold.solver.constraint-stream-automatic-node-sharing` to `true` in `application.properties`:
++
+[source,properties,options="nowrap"]
+----
+quarkus.timefold.solver.constraint-stream-automatic-node-sharing=true
+----
+======
+
+IMPORTANT: Debugging breakpoints put inside your constraints will not be respected, because the ConstraintProvider class will be transformed when this feature is enabled. | ```suggestion
[IMPORTANT]
====
Debugging breakpoints put inside your constraints will not be respected, because the `ConstraintProvider` class will be transformed when this feature is enabled.
====
``` |
timefold-solver | github_2023 | others | 685 | TimefoldAI | triceo | @@ -759,5 +760,191 @@ the host is likely to hang or freeze,
unless there is an OS specific policy in place to avoid Timefold Solver from hogging all the CPU processors.
====
+[#automaticNodeSharing]
+=== Automatic node sharing
+[NOTE]
+====
+This feature is a commercial feature of Timefold Solver Enterprise Edition.
+It is not available in the Community Edition.
+====
+
+When a `ConstraintProvider` does an operation for multiple constraints (such as finding all shifts corresponding to an employee), that work can be shared.
+This can massively improve score calculation speed if the repeated operation is computationally expensive.
+
+==== Configuration
+
+[tabs]
+======
+Plain Java::
+
+* Add `<constraintStreamAutomaticNodeSharing>true</constraintStreamAutomaticNodeSharing>` in your `solverConfig.xml`:
++
+[source,xml,options="nowrap"]
+----
+<!-- ... -->
+<scoreDirectorFactory>
+ <constraintProviderClass>org.acme.MyConstraintProvider</constraintProviderClass>
+ <constraintStreamAutomaticNodeSharing>true</constraintStreamAutomaticNodeSharing>
+</scoreDirectorFactory>
+<!-- ... -->
+----
+
+Spring Boot::
+
+Set the property `timefold.solver.constraint-stream-automatic-node-sharing` to `true` in `application.properties`:
++
+[source,properties,options="nowrap"]
+----
+timefold.solver.constraint-stream-automatic-node=true
+----
+
+Quarkus::
+
+Set the property `quarkus.timefold.solver.constraint-stream-automatic-node-sharing` to `true` in `application.properties`:
++
+[source,properties,options="nowrap"]
+----
+quarkus.timefold.solver.constraint-stream-automatic-node-sharing=true
+----
+======
+
+IMPORTANT: Debugging breakpoints put inside your constraints will not be respected, because the ConstraintProvider class will be transformed when this feature is enabled.
+
+==== What is node sharing?
+
+When using xref:constraints-and-score/score-calculation.adoc#constraintStreams[constraint streams], each xref:constraints-and-score/score-calculation.adoc#constraintStreamsBuildingBlocks[building block] forms a node in the score calculation network.
+When two building blocks are functionality equivalent, they can share the same node in the network. | ```suggestion
When two building blocks are functionally equivalent, they can share the same node in the network.
``` |
timefold-solver | github_2023 | others | 685 | TimefoldAI | triceo | @@ -759,5 +760,191 @@ the host is likely to hang or freeze,
unless there is an OS specific policy in place to avoid Timefold Solver from hogging all the CPU processors.
====
+[#automaticNodeSharing]
+=== Automatic node sharing
+[NOTE]
+====
+This feature is a commercial feature of Timefold Solver Enterprise Edition.
+It is not available in the Community Edition.
+====
+
+When a `ConstraintProvider` does an operation for multiple constraints (such as finding all shifts corresponding to an employee), that work can be shared.
+This can massively improve score calculation speed if the repeated operation is computationally expensive.
+
+==== Configuration
+
+[tabs]
+======
+Plain Java::
+
+* Add `<constraintStreamAutomaticNodeSharing>true</constraintStreamAutomaticNodeSharing>` in your `solverConfig.xml`:
++
+[source,xml,options="nowrap"]
+----
+<!-- ... -->
+<scoreDirectorFactory>
+ <constraintProviderClass>org.acme.MyConstraintProvider</constraintProviderClass>
+ <constraintStreamAutomaticNodeSharing>true</constraintStreamAutomaticNodeSharing>
+</scoreDirectorFactory>
+<!-- ... -->
+----
+
+Spring Boot::
+
+Set the property `timefold.solver.constraint-stream-automatic-node-sharing` to `true` in `application.properties`:
++
+[source,properties,options="nowrap"]
+----
+timefold.solver.constraint-stream-automatic-node=true
+----
+
+Quarkus::
+
+Set the property `quarkus.timefold.solver.constraint-stream-automatic-node-sharing` to `true` in `application.properties`:
++
+[source,properties,options="nowrap"]
+----
+quarkus.timefold.solver.constraint-stream-automatic-node-sharing=true
+----
+======
+
+IMPORTANT: Debugging breakpoints put inside your constraints will not be respected, because the ConstraintProvider class will be transformed when this feature is enabled.
+
+==== What is node sharing?
+
+When using xref:constraints-and-score/score-calculation.adoc#constraintStreams[constraint streams], each xref:constraints-and-score/score-calculation.adoc#constraintStreamsBuildingBlocks[building block] forms a node in the score calculation network.
+When two building blocks are functionality equivalent, they can share the same node in the network.
+Sharing nodes allows the operation to be performed only once instead of multiple times, improving the performance of the solver.
+To be functionality equivalent, the following must be true: | ```suggestion
To be functionally equivalent, the following must be true:
``` |
timefold-solver | github_2023 | others | 685 | TimefoldAI | triceo | @@ -759,5 +760,191 @@ the host is likely to hang or freeze,
unless there is an OS specific policy in place to avoid Timefold Solver from hogging all the CPU processors.
====
+[#automaticNodeSharing]
+=== Automatic node sharing
+[NOTE]
+====
+This feature is a commercial feature of Timefold Solver Enterprise Edition.
+It is not available in the Community Edition.
+====
+
+When a `ConstraintProvider` does an operation for multiple constraints (such as finding all shifts corresponding to an employee), that work can be shared.
+This can massively improve score calculation speed if the repeated operation is computationally expensive.
+
+==== Configuration
+
+[tabs]
+======
+Plain Java::
+
+* Add `<constraintStreamAutomaticNodeSharing>true</constraintStreamAutomaticNodeSharing>` in your `solverConfig.xml`:
++
+[source,xml,options="nowrap"]
+----
+<!-- ... -->
+<scoreDirectorFactory>
+ <constraintProviderClass>org.acme.MyConstraintProvider</constraintProviderClass>
+ <constraintStreamAutomaticNodeSharing>true</constraintStreamAutomaticNodeSharing>
+</scoreDirectorFactory>
+<!-- ... -->
+----
+
+Spring Boot::
+
+Set the property `timefold.solver.constraint-stream-automatic-node-sharing` to `true` in `application.properties`:
++
+[source,properties,options="nowrap"]
+----
+timefold.solver.constraint-stream-automatic-node=true
+----
+
+Quarkus::
+
+Set the property `quarkus.timefold.solver.constraint-stream-automatic-node-sharing` to `true` in `application.properties`:
++
+[source,properties,options="nowrap"]
+----
+quarkus.timefold.solver.constraint-stream-automatic-node-sharing=true
+----
+======
+
+IMPORTANT: Debugging breakpoints put inside your constraints will not be respected, because the ConstraintProvider class will be transformed when this feature is enabled.
+
+==== What is node sharing?
+
+When using xref:constraints-and-score/score-calculation.adoc#constraintStreams[constraint streams], each xref:constraints-and-score/score-calculation.adoc#constraintStreamsBuildingBlocks[building block] forms a node in the score calculation network.
+When two building blocks are functionality equivalent, they can share the same node in the network.
+Sharing nodes allows the operation to be performed only once instead of multiple times, improving the performance of the solver.
+To be functionality equivalent, the following must be true:
+
+* The building blocks must represent the same operation.
+
+* The building blocks must have functionality equivalent parent building blocks. | ```suggestion
* The building blocks must have functionally equivalent parent building blocks.
``` |
timefold-solver | github_2023 | others | 685 | TimefoldAI | triceo | @@ -759,5 +760,191 @@ the host is likely to hang or freeze,
unless there is an OS specific policy in place to avoid Timefold Solver from hogging all the CPU processors.
====
+[#automaticNodeSharing]
+=== Automatic node sharing
+[NOTE]
+====
+This feature is a commercial feature of Timefold Solver Enterprise Edition.
+It is not available in the Community Edition.
+====
+
+When a `ConstraintProvider` does an operation for multiple constraints (such as finding all shifts corresponding to an employee), that work can be shared.
+This can massively improve score calculation speed if the repeated operation is computationally expensive.
+
+==== Configuration
+
+[tabs]
+======
+Plain Java::
+
+* Add `<constraintStreamAutomaticNodeSharing>true</constraintStreamAutomaticNodeSharing>` in your `solverConfig.xml`:
++
+[source,xml,options="nowrap"]
+----
+<!-- ... -->
+<scoreDirectorFactory>
+ <constraintProviderClass>org.acme.MyConstraintProvider</constraintProviderClass>
+ <constraintStreamAutomaticNodeSharing>true</constraintStreamAutomaticNodeSharing>
+</scoreDirectorFactory>
+<!-- ... -->
+----
+
+Spring Boot::
+
+Set the property `timefold.solver.constraint-stream-automatic-node-sharing` to `true` in `application.properties`:
++
+[source,properties,options="nowrap"]
+----
+timefold.solver.constraint-stream-automatic-node=true
+----
+
+Quarkus::
+
+Set the property `quarkus.timefold.solver.constraint-stream-automatic-node-sharing` to `true` in `application.properties`:
++
+[source,properties,options="nowrap"]
+----
+quarkus.timefold.solver.constraint-stream-automatic-node-sharing=true
+----
+======
+
+IMPORTANT: Debugging breakpoints put inside your constraints will not be respected, because the ConstraintProvider class will be transformed when this feature is enabled.
+
+==== What is node sharing?
+
+When using xref:constraints-and-score/score-calculation.adoc#constraintStreams[constraint streams], each xref:constraints-and-score/score-calculation.adoc#constraintStreamsBuildingBlocks[building block] forms a node in the score calculation network.
+When two building blocks are functionality equivalent, they can share the same node in the network.
+Sharing nodes allows the operation to be performed only once instead of multiple times, improving the performance of the solver.
+To be functionality equivalent, the following must be true:
+
+* The building blocks must represent the same operation.
+
+* The building blocks must have functionality equivalent parent building blocks.
+
+* The building blocks must have functionality equivalent inputs. | ```suggestion
* The building blocks must have functionally equivalent inputs.
``` |
timefold-solver | github_2023 | others | 685 | TimefoldAI | triceo | @@ -759,5 +760,191 @@ the host is likely to hang or freeze,
unless there is an OS specific policy in place to avoid Timefold Solver from hogging all the CPU processors.
====
+[#automaticNodeSharing]
+=== Automatic node sharing
+[NOTE]
+====
+This feature is a commercial feature of Timefold Solver Enterprise Edition.
+It is not available in the Community Edition.
+====
+
+When a `ConstraintProvider` does an operation for multiple constraints (such as finding all shifts corresponding to an employee), that work can be shared.
+This can massively improve score calculation speed if the repeated operation is computationally expensive.
+
+==== Configuration
+
+[tabs]
+======
+Plain Java::
+
+* Add `<constraintStreamAutomaticNodeSharing>true</constraintStreamAutomaticNodeSharing>` in your `solverConfig.xml`:
++
+[source,xml,options="nowrap"]
+----
+<!-- ... -->
+<scoreDirectorFactory>
+ <constraintProviderClass>org.acme.MyConstraintProvider</constraintProviderClass>
+ <constraintStreamAutomaticNodeSharing>true</constraintStreamAutomaticNodeSharing>
+</scoreDirectorFactory>
+<!-- ... -->
+----
+
+Spring Boot::
+
+Set the property `timefold.solver.constraint-stream-automatic-node-sharing` to `true` in `application.properties`:
++
+[source,properties,options="nowrap"]
+----
+timefold.solver.constraint-stream-automatic-node=true
+----
+
+Quarkus::
+
+Set the property `quarkus.timefold.solver.constraint-stream-automatic-node-sharing` to `true` in `application.properties`:
++
+[source,properties,options="nowrap"]
+----
+quarkus.timefold.solver.constraint-stream-automatic-node-sharing=true
+----
+======
+
+IMPORTANT: Debugging breakpoints put inside your constraints will not be respected, because the ConstraintProvider class will be transformed when this feature is enabled.
+
+==== What is node sharing?
+
+When using xref:constraints-and-score/score-calculation.adoc#constraintStreams[constraint streams], each xref:constraints-and-score/score-calculation.adoc#constraintStreamsBuildingBlocks[building block] forms a node in the score calculation network.
+When two building blocks are functionality equivalent, they can share the same node in the network.
+Sharing nodes allows the operation to be performed only once instead of multiple times, improving the performance of the solver.
+To be functionality equivalent, the following must be true:
+
+* The building blocks must represent the same operation.
+
+* The building blocks must have functionality equivalent parent building blocks.
+
+* The building blocks must have functionality equivalent inputs.
+
+For example, the building blocks below are functionality equivalent: | ```suggestion
For example, the building blocks below are functionally equivalent:
``` |
timefold-solver | github_2023 | others | 685 | TimefoldAI | triceo | @@ -759,5 +760,191 @@ the host is likely to hang or freeze,
unless there is an OS specific policy in place to avoid Timefold Solver from hogging all the CPU processors.
====
+[#automaticNodeSharing]
+=== Automatic node sharing
+[NOTE]
+====
+This feature is a commercial feature of Timefold Solver Enterprise Edition.
+It is not available in the Community Edition.
+====
+
+When a `ConstraintProvider` does an operation for multiple constraints (such as finding all shifts corresponding to an employee), that work can be shared.
+This can massively improve score calculation speed if the repeated operation is computationally expensive.
+
+==== Configuration
+
+[tabs]
+======
+Plain Java::
+
+* Add `<constraintStreamAutomaticNodeSharing>true</constraintStreamAutomaticNodeSharing>` in your `solverConfig.xml`:
++
+[source,xml,options="nowrap"]
+----
+<!-- ... -->
+<scoreDirectorFactory>
+ <constraintProviderClass>org.acme.MyConstraintProvider</constraintProviderClass>
+ <constraintStreamAutomaticNodeSharing>true</constraintStreamAutomaticNodeSharing>
+</scoreDirectorFactory>
+<!-- ... -->
+----
+
+Spring Boot::
+
+Set the property `timefold.solver.constraint-stream-automatic-node-sharing` to `true` in `application.properties`:
++
+[source,properties,options="nowrap"]
+----
+timefold.solver.constraint-stream-automatic-node=true
+----
+
+Quarkus::
+
+Set the property `quarkus.timefold.solver.constraint-stream-automatic-node-sharing` to `true` in `application.properties`:
++
+[source,properties,options="nowrap"]
+----
+quarkus.timefold.solver.constraint-stream-automatic-node-sharing=true
+----
+======
+
+IMPORTANT: Debugging breakpoints put inside your constraints will not be respected, because the ConstraintProvider class will be transformed when this feature is enabled.
+
+==== What is node sharing?
+
+When using xref:constraints-and-score/score-calculation.adoc#constraintStreams[constraint streams], each xref:constraints-and-score/score-calculation.adoc#constraintStreamsBuildingBlocks[building block] forms a node in the score calculation network.
+When two building blocks are functionality equivalent, they can share the same node in the network.
+Sharing nodes allows the operation to be performed only once instead of multiple times, improving the performance of the solver.
+To be functionality equivalent, the following must be true:
+
+* The building blocks must represent the same operation.
+
+* The building blocks must have functionality equivalent parent building blocks.
+
+* The building blocks must have functionality equivalent inputs.
+
+For example, the building blocks below are functionality equivalent:
+
+[source,java,options="nowrap"]
+----
+Predicate<Shift> predicate = shift -> shift.getEmployee().getName().equals("Ann");
+
+var a = factory.forEach(Shift.class)
+ .filter(predicate);
+
+var b = factory.forEach(Shift.class)
+ .filter(predicate);
+----
+
+Whereas these building blocks are not functionality equivalent: | ```suggestion
Whereas these building blocks are not functionally equivalent:
``` |
timefold-solver | github_2023 | others | 685 | TimefoldAI | triceo | @@ -759,5 +760,191 @@ the host is likely to hang or freeze,
unless there is an OS specific policy in place to avoid Timefold Solver from hogging all the CPU processors.
====
+[#automaticNodeSharing]
+=== Automatic node sharing
+[NOTE]
+====
+This feature is a commercial feature of Timefold Solver Enterprise Edition.
+It is not available in the Community Edition.
+====
+
+When a `ConstraintProvider` does an operation for multiple constraints (such as finding all shifts corresponding to an employee), that work can be shared.
+This can massively improve score calculation speed if the repeated operation is computationally expensive.
+
+==== Configuration
+
+[tabs]
+======
+Plain Java::
+
+* Add `<constraintStreamAutomaticNodeSharing>true</constraintStreamAutomaticNodeSharing>` in your `solverConfig.xml`:
++
+[source,xml,options="nowrap"]
+----
+<!-- ... -->
+<scoreDirectorFactory>
+ <constraintProviderClass>org.acme.MyConstraintProvider</constraintProviderClass>
+ <constraintStreamAutomaticNodeSharing>true</constraintStreamAutomaticNodeSharing>
+</scoreDirectorFactory>
+<!-- ... -->
+----
+
+Spring Boot::
+
+Set the property `timefold.solver.constraint-stream-automatic-node-sharing` to `true` in `application.properties`:
++
+[source,properties,options="nowrap"]
+----
+timefold.solver.constraint-stream-automatic-node=true
+----
+
+Quarkus::
+
+Set the property `quarkus.timefold.solver.constraint-stream-automatic-node-sharing` to `true` in `application.properties`:
++
+[source,properties,options="nowrap"]
+----
+quarkus.timefold.solver.constraint-stream-automatic-node-sharing=true
+----
+======
+
+IMPORTANT: Debugging breakpoints put inside your constraints will not be respected, because the ConstraintProvider class will be transformed when this feature is enabled.
+
+==== What is node sharing?
+
+When using xref:constraints-and-score/score-calculation.adoc#constraintStreams[constraint streams], each xref:constraints-and-score/score-calculation.adoc#constraintStreamsBuildingBlocks[building block] forms a node in the score calculation network.
+When two building blocks are functionality equivalent, they can share the same node in the network.
+Sharing nodes allows the operation to be performed only once instead of multiple times, improving the performance of the solver.
+To be functionality equivalent, the following must be true:
+
+* The building blocks must represent the same operation.
+
+* The building blocks must have functionality equivalent parent building blocks.
+
+* The building blocks must have functionality equivalent inputs.
+
+For example, the building blocks below are functionality equivalent:
+
+[source,java,options="nowrap"]
+----
+Predicate<Shift> predicate = shift -> shift.getEmployee().getName().equals("Ann");
+
+var a = factory.forEach(Shift.class)
+ .filter(predicate);
+
+var b = factory.forEach(Shift.class)
+ .filter(predicate);
+----
+
+Whereas these building blocks are not functionality equivalent:
+
+[source,java,options="nowrap"]
+----
+Predicate<Shift> predicate1 = shift -> shift.getEmployee().getName().equals("Ann");
+Predicate<Shift> predicate2 = shift -> shift.getEmployee().getName().equals("Bob");
+
+// Different parents
+var a = factory.forEach(Shift.class)
+ .filter(predicate2);
+
+var b = factory.forEach(Shift.class)
+ .filter(predicate1)
+ .filter(predicate2);
+
+// Different operations
+var a = factory.forEach(Shift.class)
+ .ifExists(Employee.class);
+
+var b = factory.forEach(Shift.class)
+ .ifNotExists(Employee.class);
+
+// Different inputs
+var a = factory.forEach(Shift.class)
+ .filter(predicate1);
+
+var b = factory.forEach(Shift.class)
+ .filter(predicate2);
+----
+
+Counterintuitively, the building blocks produced by these (seemly) identical methods are not necessarily functionality equivalent: | ```suggestion
Counterintuitively, the building blocks produced by these (seemly) identical methods are not necessarily functionally equivalent:
``` |
timefold-solver | github_2023 | others | 685 | TimefoldAI | triceo | @@ -759,5 +760,191 @@ the host is likely to hang or freeze,
unless there is an OS specific policy in place to avoid Timefold Solver from hogging all the CPU processors.
====
+[#automaticNodeSharing]
+=== Automatic node sharing
+[NOTE]
+====
+This feature is a commercial feature of Timefold Solver Enterprise Edition.
+It is not available in the Community Edition.
+====
+
+When a `ConstraintProvider` does an operation for multiple constraints (such as finding all shifts corresponding to an employee), that work can be shared.
+This can massively improve score calculation speed if the repeated operation is computationally expensive.
+
+==== Configuration
+
+[tabs]
+======
+Plain Java::
+
+* Add `<constraintStreamAutomaticNodeSharing>true</constraintStreamAutomaticNodeSharing>` in your `solverConfig.xml`:
++
+[source,xml,options="nowrap"]
+----
+<!-- ... -->
+<scoreDirectorFactory>
+ <constraintProviderClass>org.acme.MyConstraintProvider</constraintProviderClass>
+ <constraintStreamAutomaticNodeSharing>true</constraintStreamAutomaticNodeSharing>
+</scoreDirectorFactory>
+<!-- ... -->
+----
+
+Spring Boot::
+
+Set the property `timefold.solver.constraint-stream-automatic-node-sharing` to `true` in `application.properties`:
++
+[source,properties,options="nowrap"]
+----
+timefold.solver.constraint-stream-automatic-node=true
+----
+
+Quarkus::
+
+Set the property `quarkus.timefold.solver.constraint-stream-automatic-node-sharing` to `true` in `application.properties`:
++
+[source,properties,options="nowrap"]
+----
+quarkus.timefold.solver.constraint-stream-automatic-node-sharing=true
+----
+======
+
+IMPORTANT: Debugging breakpoints put inside your constraints will not be respected, because the ConstraintProvider class will be transformed when this feature is enabled.
+
+==== What is node sharing?
+
+When using xref:constraints-and-score/score-calculation.adoc#constraintStreams[constraint streams], each xref:constraints-and-score/score-calculation.adoc#constraintStreamsBuildingBlocks[building block] forms a node in the score calculation network.
+When two building blocks are functionality equivalent, they can share the same node in the network.
+Sharing nodes allows the operation to be performed only once instead of multiple times, improving the performance of the solver.
+To be functionality equivalent, the following must be true:
+
+* The building blocks must represent the same operation.
+
+* The building blocks must have functionality equivalent parent building blocks.
+
+* The building blocks must have functionality equivalent inputs.
+
+For example, the building blocks below are functionality equivalent:
+
+[source,java,options="nowrap"]
+----
+Predicate<Shift> predicate = shift -> shift.getEmployee().getName().equals("Ann");
+
+var a = factory.forEach(Shift.class)
+ .filter(predicate);
+
+var b = factory.forEach(Shift.class)
+ .filter(predicate);
+----
+
+Whereas these building blocks are not functionality equivalent:
+
+[source,java,options="nowrap"]
+----
+Predicate<Shift> predicate1 = shift -> shift.getEmployee().getName().equals("Ann");
+Predicate<Shift> predicate2 = shift -> shift.getEmployee().getName().equals("Bob");
+
+// Different parents
+var a = factory.forEach(Shift.class)
+ .filter(predicate2);
+
+var b = factory.forEach(Shift.class)
+ .filter(predicate1)
+ .filter(predicate2);
+
+// Different operations
+var a = factory.forEach(Shift.class)
+ .ifExists(Employee.class);
+
+var b = factory.forEach(Shift.class)
+ .ifNotExists(Employee.class);
+
+// Different inputs
+var a = factory.forEach(Shift.class)
+ .filter(predicate1);
+
+var b = factory.forEach(Shift.class)
+ .filter(predicate2);
+----
+
+Counterintuitively, the building blocks produced by these (seemly) identical methods are not necessarily functionality equivalent:
+
+[source,java,options="nowrap"]
+----
+UniConstraintStream<Shift> a(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter(shift -> shift.getEmployee().getName().equals("Ann"));
+}
+
+UniConstraintStream<Shift> b(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter(shift -> shift.getEmployee().getName().equals("Ann"));
+}
+----
+
+The Java Virtual Machine is free to (and often does) create different instances of functionality equivalent lambdas. | ```suggestion
The Java Virtual Machine is free to (and often does) create different instances of functionally equivalent lambdas.
``` |
timefold-solver | github_2023 | others | 685 | TimefoldAI | triceo | @@ -759,5 +760,191 @@ the host is likely to hang or freeze,
unless there is an OS specific policy in place to avoid Timefold Solver from hogging all the CPU processors.
====
+[#automaticNodeSharing]
+=== Automatic node sharing
+[NOTE]
+====
+This feature is a commercial feature of Timefold Solver Enterprise Edition.
+It is not available in the Community Edition.
+====
+
+When a `ConstraintProvider` does an operation for multiple constraints (such as finding all shifts corresponding to an employee), that work can be shared.
+This can massively improve score calculation speed if the repeated operation is computationally expensive.
+
+==== Configuration
+
+[tabs]
+======
+Plain Java::
+
+* Add `<constraintStreamAutomaticNodeSharing>true</constraintStreamAutomaticNodeSharing>` in your `solverConfig.xml`:
++
+[source,xml,options="nowrap"]
+----
+<!-- ... -->
+<scoreDirectorFactory>
+ <constraintProviderClass>org.acme.MyConstraintProvider</constraintProviderClass>
+ <constraintStreamAutomaticNodeSharing>true</constraintStreamAutomaticNodeSharing>
+</scoreDirectorFactory>
+<!-- ... -->
+----
+
+Spring Boot::
+
+Set the property `timefold.solver.constraint-stream-automatic-node-sharing` to `true` in `application.properties`:
++
+[source,properties,options="nowrap"]
+----
+timefold.solver.constraint-stream-automatic-node=true
+----
+
+Quarkus::
+
+Set the property `quarkus.timefold.solver.constraint-stream-automatic-node-sharing` to `true` in `application.properties`:
++
+[source,properties,options="nowrap"]
+----
+quarkus.timefold.solver.constraint-stream-automatic-node-sharing=true
+----
+======
+
+IMPORTANT: Debugging breakpoints put inside your constraints will not be respected, because the ConstraintProvider class will be transformed when this feature is enabled.
+
+==== What is node sharing?
+
+When using xref:constraints-and-score/score-calculation.adoc#constraintStreams[constraint streams], each xref:constraints-and-score/score-calculation.adoc#constraintStreamsBuildingBlocks[building block] forms a node in the score calculation network.
+When two building blocks are functionality equivalent, they can share the same node in the network.
+Sharing nodes allows the operation to be performed only once instead of multiple times, improving the performance of the solver.
+To be functionality equivalent, the following must be true:
+
+* The building blocks must represent the same operation.
+
+* The building blocks must have functionality equivalent parent building blocks.
+
+* The building blocks must have functionality equivalent inputs.
+
+For example, the building blocks below are functionality equivalent:
+
+[source,java,options="nowrap"]
+----
+Predicate<Shift> predicate = shift -> shift.getEmployee().getName().equals("Ann");
+
+var a = factory.forEach(Shift.class)
+ .filter(predicate);
+
+var b = factory.forEach(Shift.class)
+ .filter(predicate);
+----
+
+Whereas these building blocks are not functionality equivalent:
+
+[source,java,options="nowrap"]
+----
+Predicate<Shift> predicate1 = shift -> shift.getEmployee().getName().equals("Ann");
+Predicate<Shift> predicate2 = shift -> shift.getEmployee().getName().equals("Bob");
+
+// Different parents
+var a = factory.forEach(Shift.class)
+ .filter(predicate2);
+
+var b = factory.forEach(Shift.class)
+ .filter(predicate1)
+ .filter(predicate2);
+
+// Different operations
+var a = factory.forEach(Shift.class)
+ .ifExists(Employee.class);
+
+var b = factory.forEach(Shift.class)
+ .ifNotExists(Employee.class);
+
+// Different inputs
+var a = factory.forEach(Shift.class)
+ .filter(predicate1);
+
+var b = factory.forEach(Shift.class)
+ .filter(predicate2);
+----
+
+Counterintuitively, the building blocks produced by these (seemly) identical methods are not necessarily functionality equivalent:
+
+[source,java,options="nowrap"]
+----
+UniConstraintStream<Shift> a(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter(shift -> shift.getEmployee().getName().equals("Ann"));
+}
+
+UniConstraintStream<Shift> b(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter(shift -> shift.getEmployee().getName().equals("Ann"));
+}
+----
+
+The Java Virtual Machine is free to (and often does) create different instances of functionality equivalent lambdas.
+This severely limits the effectiveness of node sharing, since the only way to know two lambdas are equal is to compare their references.
+
+When automatic node sharing is used, the `ConstraintProvider` class is transformed so all lambdas are accessed via a static final field.
+So a class that looks like this: | ```suggestion
Consider the following input class:
``` |
timefold-solver | github_2023 | others | 685 | TimefoldAI | triceo | @@ -759,5 +760,191 @@ the host is likely to hang or freeze,
unless there is an OS specific policy in place to avoid Timefold Solver from hogging all the CPU processors.
====
+[#automaticNodeSharing]
+=== Automatic node sharing
+[NOTE]
+====
+This feature is a commercial feature of Timefold Solver Enterprise Edition.
+It is not available in the Community Edition.
+====
+
+When a `ConstraintProvider` does an operation for multiple constraints (such as finding all shifts corresponding to an employee), that work can be shared.
+This can massively improve score calculation speed if the repeated operation is computationally expensive.
+
+==== Configuration
+
+[tabs]
+======
+Plain Java::
+
+* Add `<constraintStreamAutomaticNodeSharing>true</constraintStreamAutomaticNodeSharing>` in your `solverConfig.xml`:
++
+[source,xml,options="nowrap"]
+----
+<!-- ... -->
+<scoreDirectorFactory>
+ <constraintProviderClass>org.acme.MyConstraintProvider</constraintProviderClass>
+ <constraintStreamAutomaticNodeSharing>true</constraintStreamAutomaticNodeSharing>
+</scoreDirectorFactory>
+<!-- ... -->
+----
+
+Spring Boot::
+
+Set the property `timefold.solver.constraint-stream-automatic-node-sharing` to `true` in `application.properties`:
++
+[source,properties,options="nowrap"]
+----
+timefold.solver.constraint-stream-automatic-node=true
+----
+
+Quarkus::
+
+Set the property `quarkus.timefold.solver.constraint-stream-automatic-node-sharing` to `true` in `application.properties`:
++
+[source,properties,options="nowrap"]
+----
+quarkus.timefold.solver.constraint-stream-automatic-node-sharing=true
+----
+======
+
+IMPORTANT: Debugging breakpoints put inside your constraints will not be respected, because the ConstraintProvider class will be transformed when this feature is enabled.
+
+==== What is node sharing?
+
+When using xref:constraints-and-score/score-calculation.adoc#constraintStreams[constraint streams], each xref:constraints-and-score/score-calculation.adoc#constraintStreamsBuildingBlocks[building block] forms a node in the score calculation network.
+When two building blocks are functionality equivalent, they can share the same node in the network.
+Sharing nodes allows the operation to be performed only once instead of multiple times, improving the performance of the solver.
+To be functionality equivalent, the following must be true:
+
+* The building blocks must represent the same operation.
+
+* The building blocks must have functionality equivalent parent building blocks.
+
+* The building blocks must have functionality equivalent inputs.
+
+For example, the building blocks below are functionality equivalent:
+
+[source,java,options="nowrap"]
+----
+Predicate<Shift> predicate = shift -> shift.getEmployee().getName().equals("Ann");
+
+var a = factory.forEach(Shift.class)
+ .filter(predicate);
+
+var b = factory.forEach(Shift.class)
+ .filter(predicate);
+----
+
+Whereas these building blocks are not functionality equivalent:
+
+[source,java,options="nowrap"]
+----
+Predicate<Shift> predicate1 = shift -> shift.getEmployee().getName().equals("Ann");
+Predicate<Shift> predicate2 = shift -> shift.getEmployee().getName().equals("Bob");
+
+// Different parents
+var a = factory.forEach(Shift.class)
+ .filter(predicate2);
+
+var b = factory.forEach(Shift.class)
+ .filter(predicate1)
+ .filter(predicate2);
+
+// Different operations
+var a = factory.forEach(Shift.class)
+ .ifExists(Employee.class);
+
+var b = factory.forEach(Shift.class)
+ .ifNotExists(Employee.class);
+
+// Different inputs
+var a = factory.forEach(Shift.class)
+ .filter(predicate1);
+
+var b = factory.forEach(Shift.class)
+ .filter(predicate2);
+----
+
+Counterintuitively, the building blocks produced by these (seemly) identical methods are not necessarily functionality equivalent:
+
+[source,java,options="nowrap"]
+----
+UniConstraintStream<Shift> a(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter(shift -> shift.getEmployee().getName().equals("Ann"));
+}
+
+UniConstraintStream<Shift> b(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter(shift -> shift.getEmployee().getName().equals("Ann"));
+}
+----
+
+The Java Virtual Machine is free to (and often does) create different instances of functionality equivalent lambdas.
+This severely limits the effectiveness of node sharing, since the only way to know two lambdas are equal is to compare their references.
+
+When automatic node sharing is used, the `ConstraintProvider` class is transformed so all lambdas are accessed via a static final field.
+So a class that looks like this:
+
+[source,java,options="nowrap"]
+----
+public class MyConstraintProvider implements ConstraintProvider {
+
+ public Constraint[] defineConstraints(ConstraintFactory constraintFactory) {
+ return new Constraint[] {
+ a(constraintFactory),
+ b(constraintFactory)
+ };
+ }
+
+ Constraint a(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter(shift -> shift.getEmployee().getName().equals("Ann"))
+ .penalize(SimpleScore.ONE)
+ .asConstraint("a");
+ }
+
+ Constraint b(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter(shift -> shift.getEmployee().getName().equals("Ann"))
+ .penalize(SimpleScore.ONE)
+ .asConstraint("b");
+ }
+}
+----
+
+is transformed to a class that looks like this: | ```suggestion
When automatic node sharing is enabled, the class will be transformed to look like this:
``` |
timefold-solver | github_2023 | others | 685 | TimefoldAI | triceo | @@ -759,5 +760,191 @@ the host is likely to hang or freeze,
unless there is an OS specific policy in place to avoid Timefold Solver from hogging all the CPU processors.
====
+[#automaticNodeSharing]
+=== Automatic node sharing
+[NOTE]
+====
+This feature is a commercial feature of Timefold Solver Enterprise Edition.
+It is not available in the Community Edition.
+====
+
+When a `ConstraintProvider` does an operation for multiple constraints (such as finding all shifts corresponding to an employee), that work can be shared.
+This can massively improve score calculation speed if the repeated operation is computationally expensive.
+
+==== Configuration
+
+[tabs]
+======
+Plain Java::
+
+* Add `<constraintStreamAutomaticNodeSharing>true</constraintStreamAutomaticNodeSharing>` in your `solverConfig.xml`:
++
+[source,xml,options="nowrap"]
+----
+<!-- ... -->
+<scoreDirectorFactory>
+ <constraintProviderClass>org.acme.MyConstraintProvider</constraintProviderClass>
+ <constraintStreamAutomaticNodeSharing>true</constraintStreamAutomaticNodeSharing>
+</scoreDirectorFactory>
+<!-- ... -->
+----
+
+Spring Boot::
+
+Set the property `timefold.solver.constraint-stream-automatic-node-sharing` to `true` in `application.properties`:
++
+[source,properties,options="nowrap"]
+----
+timefold.solver.constraint-stream-automatic-node=true
+----
+
+Quarkus::
+
+Set the property `quarkus.timefold.solver.constraint-stream-automatic-node-sharing` to `true` in `application.properties`:
++
+[source,properties,options="nowrap"]
+----
+quarkus.timefold.solver.constraint-stream-automatic-node-sharing=true
+----
+======
+
+IMPORTANT: Debugging breakpoints put inside your constraints will not be respected, because the ConstraintProvider class will be transformed when this feature is enabled.
+
+==== What is node sharing?
+
+When using xref:constraints-and-score/score-calculation.adoc#constraintStreams[constraint streams], each xref:constraints-and-score/score-calculation.adoc#constraintStreamsBuildingBlocks[building block] forms a node in the score calculation network.
+When two building blocks are functionality equivalent, they can share the same node in the network.
+Sharing nodes allows the operation to be performed only once instead of multiple times, improving the performance of the solver.
+To be functionality equivalent, the following must be true:
+
+* The building blocks must represent the same operation.
+
+* The building blocks must have functionality equivalent parent building blocks.
+
+* The building blocks must have functionality equivalent inputs.
+
+For example, the building blocks below are functionality equivalent:
+
+[source,java,options="nowrap"]
+----
+Predicate<Shift> predicate = shift -> shift.getEmployee().getName().equals("Ann");
+
+var a = factory.forEach(Shift.class)
+ .filter(predicate);
+
+var b = factory.forEach(Shift.class)
+ .filter(predicate);
+----
+
+Whereas these building blocks are not functionality equivalent:
+
+[source,java,options="nowrap"]
+----
+Predicate<Shift> predicate1 = shift -> shift.getEmployee().getName().equals("Ann");
+Predicate<Shift> predicate2 = shift -> shift.getEmployee().getName().equals("Bob");
+
+// Different parents
+var a = factory.forEach(Shift.class)
+ .filter(predicate2);
+
+var b = factory.forEach(Shift.class)
+ .filter(predicate1)
+ .filter(predicate2);
+
+// Different operations
+var a = factory.forEach(Shift.class)
+ .ifExists(Employee.class);
+
+var b = factory.forEach(Shift.class)
+ .ifNotExists(Employee.class);
+
+// Different inputs
+var a = factory.forEach(Shift.class)
+ .filter(predicate1);
+
+var b = factory.forEach(Shift.class)
+ .filter(predicate2);
+----
+
+Counterintuitively, the building blocks produced by these (seemly) identical methods are not necessarily functionality equivalent:
+
+[source,java,options="nowrap"]
+----
+UniConstraintStream<Shift> a(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter(shift -> shift.getEmployee().getName().equals("Ann"));
+}
+
+UniConstraintStream<Shift> b(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter(shift -> shift.getEmployee().getName().equals("Ann"));
+}
+----
+
+The Java Virtual Machine is free to (and often does) create different instances of functionality equivalent lambdas.
+This severely limits the effectiveness of node sharing, since the only way to know two lambdas are equal is to compare their references.
+
+When automatic node sharing is used, the `ConstraintProvider` class is transformed so all lambdas are accessed via a static final field.
+So a class that looks like this:
+
+[source,java,options="nowrap"]
+----
+public class MyConstraintProvider implements ConstraintProvider {
+
+ public Constraint[] defineConstraints(ConstraintFactory constraintFactory) {
+ return new Constraint[] {
+ a(constraintFactory),
+ b(constraintFactory)
+ };
+ }
+
+ Constraint a(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter(shift -> shift.getEmployee().getName().equals("Ann"))
+ .penalize(SimpleScore.ONE)
+ .asConstraint("a");
+ }
+
+ Constraint b(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter(shift -> shift.getEmployee().getName().equals("Ann"))
+ .penalize(SimpleScore.ONE)
+ .asConstraint("b");
+ }
+}
+----
+
+is transformed to a class that looks like this:
+
+[source,java,options="nowrap"]
+----
+public class MyConstraintProvider implements ConstraintProvider {
+ private static final Predicate<Shift> $predicate1 = shift -> shift.getEmployee().getName().equals("Ann");
+
+ public Constraint[] defineConstraints(ConstraintFactory constraintFactory) {
+ return new Constraint[] {
+ a(constraintFactory),
+ b(constraintFactory)
+ };
+ }
+
+ Constraint a(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter($predicate1)
+ .penalize(SimpleScore.ONE)
+ .asConstraint("a");
+ }
+
+ Constraint b(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter($predicate1)
+ .penalize(SimpleScore.ONE)
+ .asConstraint("b");
+ }
+}
+----
+
+IMPORTANT: This transformation prevents breakpoints from being placed inside the ConstraintProvider. | ```suggestion
This transformation means that debugging breakpoints placed inside the original `ConstraintProvider` will not be honored in the transformed `ConstraintProvider`.
``` |
timefold-solver | github_2023 | others | 685 | TimefoldAI | triceo | @@ -759,5 +760,191 @@ the host is likely to hang or freeze,
unless there is an OS specific policy in place to avoid Timefold Solver from hogging all the CPU processors.
====
+[#automaticNodeSharing]
+=== Automatic node sharing
+[NOTE]
+====
+This feature is a commercial feature of Timefold Solver Enterprise Edition.
+It is not available in the Community Edition.
+====
+
+When a `ConstraintProvider` does an operation for multiple constraints (such as finding all shifts corresponding to an employee), that work can be shared.
+This can massively improve score calculation speed if the repeated operation is computationally expensive.
+
+==== Configuration
+
+[tabs]
+======
+Plain Java::
+
+* Add `<constraintStreamAutomaticNodeSharing>true</constraintStreamAutomaticNodeSharing>` in your `solverConfig.xml`:
++
+[source,xml,options="nowrap"]
+----
+<!-- ... -->
+<scoreDirectorFactory>
+ <constraintProviderClass>org.acme.MyConstraintProvider</constraintProviderClass>
+ <constraintStreamAutomaticNodeSharing>true</constraintStreamAutomaticNodeSharing>
+</scoreDirectorFactory>
+<!-- ... -->
+----
+
+Spring Boot::
+
+Set the property `timefold.solver.constraint-stream-automatic-node-sharing` to `true` in `application.properties`:
++
+[source,properties,options="nowrap"]
+----
+timefold.solver.constraint-stream-automatic-node=true
+----
+
+Quarkus::
+
+Set the property `quarkus.timefold.solver.constraint-stream-automatic-node-sharing` to `true` in `application.properties`:
++
+[source,properties,options="nowrap"]
+----
+quarkus.timefold.solver.constraint-stream-automatic-node-sharing=true
+----
+======
+
+IMPORTANT: Debugging breakpoints put inside your constraints will not be respected, because the ConstraintProvider class will be transformed when this feature is enabled.
+
+==== What is node sharing?
+
+When using xref:constraints-and-score/score-calculation.adoc#constraintStreams[constraint streams], each xref:constraints-and-score/score-calculation.adoc#constraintStreamsBuildingBlocks[building block] forms a node in the score calculation network.
+When two building blocks are functionality equivalent, they can share the same node in the network.
+Sharing nodes allows the operation to be performed only once instead of multiple times, improving the performance of the solver.
+To be functionality equivalent, the following must be true:
+
+* The building blocks must represent the same operation.
+
+* The building blocks must have functionality equivalent parent building blocks.
+
+* The building blocks must have functionality equivalent inputs.
+
+For example, the building blocks below are functionality equivalent:
+
+[source,java,options="nowrap"]
+----
+Predicate<Shift> predicate = shift -> shift.getEmployee().getName().equals("Ann");
+
+var a = factory.forEach(Shift.class)
+ .filter(predicate);
+
+var b = factory.forEach(Shift.class)
+ .filter(predicate);
+----
+
+Whereas these building blocks are not functionality equivalent:
+
+[source,java,options="nowrap"]
+----
+Predicate<Shift> predicate1 = shift -> shift.getEmployee().getName().equals("Ann");
+Predicate<Shift> predicate2 = shift -> shift.getEmployee().getName().equals("Bob");
+
+// Different parents
+var a = factory.forEach(Shift.class)
+ .filter(predicate2);
+
+var b = factory.forEach(Shift.class)
+ .filter(predicate1)
+ .filter(predicate2);
+
+// Different operations
+var a = factory.forEach(Shift.class)
+ .ifExists(Employee.class);
+
+var b = factory.forEach(Shift.class)
+ .ifNotExists(Employee.class);
+
+// Different inputs
+var a = factory.forEach(Shift.class)
+ .filter(predicate1);
+
+var b = factory.forEach(Shift.class)
+ .filter(predicate2);
+----
+
+Counterintuitively, the building blocks produced by these (seemly) identical methods are not necessarily functionality equivalent:
+
+[source,java,options="nowrap"]
+----
+UniConstraintStream<Shift> a(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter(shift -> shift.getEmployee().getName().equals("Ann"));
+}
+
+UniConstraintStream<Shift> b(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter(shift -> shift.getEmployee().getName().equals("Ann"));
+}
+----
+
+The Java Virtual Machine is free to (and often does) create different instances of functionality equivalent lambdas.
+This severely limits the effectiveness of node sharing, since the only way to know two lambdas are equal is to compare their references.
+
+When automatic node sharing is used, the `ConstraintProvider` class is transformed so all lambdas are accessed via a static final field.
+So a class that looks like this:
+
+[source,java,options="nowrap"]
+----
+public class MyConstraintProvider implements ConstraintProvider {
+
+ public Constraint[] defineConstraints(ConstraintFactory constraintFactory) {
+ return new Constraint[] {
+ a(constraintFactory),
+ b(constraintFactory)
+ };
+ }
+
+ Constraint a(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter(shift -> shift.getEmployee().getName().equals("Ann"))
+ .penalize(SimpleScore.ONE)
+ .asConstraint("a");
+ }
+
+ Constraint b(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter(shift -> shift.getEmployee().getName().equals("Ann"))
+ .penalize(SimpleScore.ONE)
+ .asConstraint("b");
+ }
+}
+----
+
+is transformed to a class that looks like this:
+
+[source,java,options="nowrap"]
+----
+public class MyConstraintProvider implements ConstraintProvider {
+ private static final Predicate<Shift> $predicate1 = shift -> shift.getEmployee().getName().equals("Ann");
+
+ public Constraint[] defineConstraints(ConstraintFactory constraintFactory) {
+ return new Constraint[] {
+ a(constraintFactory),
+ b(constraintFactory)
+ };
+ }
+
+ Constraint a(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter($predicate1)
+ .penalize(SimpleScore.ONE)
+ .asConstraint("a");
+ }
+
+ Constraint b(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter($predicate1)
+ .penalize(SimpleScore.ONE)
+ .asConstraint("b");
+ }
+}
+----
+
+IMPORTANT: This transformation prevents breakpoints from being placed inside the ConstraintProvider.
+This allows building blocks to share functionality equivalent parents without needing the `ConstraintProvider` to be written in an awkward way. | ```suggestion
From the above, you can see how this feature allows building blocks to share functionally equivalent parents, without needing the `ConstraintProvider` to be written in an awkward way.
``` |
timefold-solver | github_2023 | others | 686 | TimefoldAI | zepfred | @@ -4,6 +4,7 @@
** xref:quickstart/hello-world/hello-world-quickstart.adoc[leveloffset=+1]
** xref:quickstart/quarkus/quarkus-quickstart.adoc[leveloffset=+1]
** xref:quickstart/spring-boot/spring-boot-quickstart.adoc[leveloffset=+1]
+** xref:quickstart/quarkus-vehicle-routing/quarkus-vehicle-routing-quickstart.adoc[leveloffset=+1] | Is this expected? |
timefold-solver | github_2023 | others | 686 | TimefoldAI | zepfred | @@ -0,0 +1,213 @@
+[#upgradeToLatestVersion]
+= Upgrade to the latest version
+:doctype: book
+:sectnums:
+:icons: font
+
+Timefold Solver public APIs are backwards compatible,
+but users often also use impl classes,
+many of which are documented in the reference manual too. | Do we have a link for that? |
timefold-solver | github_2023 | others | 686 | TimefoldAI | zepfred | @@ -0,0 +1,18 @@
+[#upgradeAndMigrationOverview]
+= Upgrade and Migration: Overview
+:doctype: book
+:sectnums:
+:icons: font
+
+In this section, you will:
+
+- Learn how to upgrade from OptaPlanner to Timefold Solver.
+- Learn how to upgrade to the latest version of Timefold Solver automatically.
+- Find a detailed upgrade recipe for every major change we make to the Timefold Solver APIs.
+
+To find out what's new in the latest version of Timefold Solver,
+see the [Timefold Solver release notes](https://github.com/TimefoldAI/timefold-solver/releases) | The
```suggestion
see the https://github.com/TimefoldAI/timefold-solver/releases[Timefold Solver release notes]
``` |
timefold-solver | github_2023 | others | 686 | TimefoldAI | zepfred | @@ -0,0 +1,213 @@
+[#upgradeToLatestVersion]
+= Upgrade to the latest version
+:doctype: book
+:sectnums:
+:icons: font
+
+Timefold Solver public APIs are backwards compatible,
+but users often also use impl classes, | implementation classes? |
timefold-solver | github_2023 | others | 686 | TimefoldAI | zepfred | @@ -0,0 +1,213 @@
+[#upgradeToLatestVersion]
+= Upgrade to the latest version
+:doctype: book
+:sectnums:
+:icons: font
+
+Timefold Solver public APIs are backwards compatible,
+but users often also use impl classes,
+many of which are documented in the reference manual too.
+This upgrade recipe minimizes the pain to upgrade your code
+and to take advantage of the newest features in Timefold Solver.
+
+[#automaticUpgradeToLatestVersion]
+== Automatic upgrade to the latest version
+
+For many of the upgrade steps mentioned later,
+we actually provide a migration tool that can automatically apply those changes to Java files.
+This tool is based on OpenRewrite and can be run as a Maven or Gradle plugin.
+To run the tool, execute the following command in your project directory:
+
+[tabs]
+====
+Maven::
++
+--
+[source,shell,subs=attributes+]
+----
+mvn org.openrewrite.maven:rewrite-maven-plugin:{rewrite-maven-plugin-version}:run -Drewrite.recipeArtifactCoordinates=ai.timefold.solver:timefold-solver-migration:{timefold-solver-version} -Drewrite.activeRecipes=ai.timefold.solver.migration.ToLatest
+----
+--
+
+Gradle::
++
+--
+[source,shell,subs=attributes+]
+----
+curl https://timefold.ai/product/upgrade/upgrade-timefold.gradle > upgrade-timefold.gradle ; gradle -Dorg.gradle.jvmargs=-Xmx2G --init-script upgrade-timefold.gradle rewriteRun -DtimefoldSolverVersion={timefold-solver-version} ; rm upgrade-timefold.gradle
+----
+--
+====
+
+Having done that, you can check the local changes and commit them.
+Note that none of the upgrade steps could be automatically applied,
+and it may still be worth your while to read the rest the upgrade recipe below.
+
+For the time being,
+Kotlin users need to follow the upgrade recipe and apply the steps manually.
+
+[#manualUpgrade]
+== Manual upgrade recipe
+
+Every upgrade note indicates how likely your code will be affected by that change:
+
+- icon:magic[] *Automated*: Can be applied automatically using our <<automaticUpgradeToLatestVersion,migration tooling>>.
+- icon:exclamation-triangle[role=red] *Major*: Likely to affect your code.
+- icon:info-circle[role=yellow] *Minor*: Unlikely to affect your code, unless you use internal classes.
+- icon:info[] *Impl detail*: Will not affect your code, unless you are using some very dark corner of Solver's internals. | There's something off about this Impl detail icon. What do you think?

|
timefold-solver | github_2023 | java | 671 | TimefoldAI | triceo | @@ -0,0 +1,12 @@
+package ai.timefold.solver.core.api.solver;
+
+/**
+ * The statistics of a given problem submitted to a {@link Solver}.
+ *
+ * @param entityCount The number of genuine entities defined by the problem.
+ * @param variableCount The number of genuine variables defined by the problem.
+ * @param maximumValueRangeSize The number of possible assignments for the genuine variable with the largest range.
+ * @param problemScale An approximate log of the solution space. | I think this last line deserves a bit more description. What do you mean by `log`, a logarithm? A natural logarithm? What is a solution space? Maybe it'd be best if we just say what the formula is. |
timefold-solver | github_2023 | java | 671 | TimefoldAI | triceo | @@ -95,6 +95,14 @@ public interface SolverJob<Solution_, ProblemId_> {
*/
long getScoreCalculationCount();
+ /**
+ * Return the {@link ProblemStatistics} for the {@link PlanningSolution problem} submitted to the
+ * {@link SolverManager}. | I'm wondering if we should describe the volatility of this value.
It may be something else at solver start, during solver run, and at the end. (`ProblemChange` again.) |
timefold-solver | github_2023 | java | 671 | TimefoldAI | triceo | @@ -36,7 +36,10 @@ public enum SolverMetric {
PICKED_MOVE_TYPE_BEST_SCORE_DIFF("timefold.solver.move.type.best.score.diff", new PickedMoveBestScoreDiffStatistic<>(),
true),
PICKED_MOVE_TYPE_STEP_SCORE_DIFF("timefold.solver.move.type.step.score.diff", new PickedMoveStepScoreDiffStatistic<>(),
- false);
+ false),
+ PROBLEM_ENTITY_COUNT("timefold.solver.problem.entities", false),
+ PROBLEM_VARIABLE_COUNT("timefold.solver.problem.variables", false),
+ PROBLEM_VALUE_COUNT("timefold.solver.problem.values", false); | Since these metrics are enabled by default, I'd put them amongst the others which are enabled by default, at the top. The enum is not inside public API, so I don't worry about ordinals staying constant. |
timefold-solver | github_2023 | java | 671 | TimefoldAI | triceo | @@ -1039,6 +1039,7 @@ public long getMaximumValueCount(Solution_ solution) {
/**
* Calculates an indication on how big this problem instance is.
* This is intentionally very loosely defined for now.
+ * This is explicitly NOT the solution space size. | I see that this PR makes no changes to any of the scale computations. So we are happy with what is currently there for list and chained? I recall there were some PLANNER JIRA references there; at the very least they should be removed, since we've been over that code and the new version is something we want to move forward with. |
timefold-solver | github_2023 | java | 671 | TimefoldAI | triceo | @@ -234,18 +228,52 @@ public void solvingStarted(SolverScope<Solution_> solverScope) {
solverScope.startingNow();
solverScope.getScoreDirector().resetCalculationCount();
super.solvingStarted(solverScope);
- int startingSolverCount = solverScope.getStartingSolverCount() + 1;
+ var startingSolverCount = solverScope.getStartingSolverCount() + 1;
solverScope.setStartingSolverCount(startingSolverCount);
- logger.info("Solving {}: time spent ({}), best score ({}), environment mode ({}), "
- + "move thread count ({}), random ({}).",
+ registerSolverSpecificMetrics();
+ logger.info("Solving {}: time spent ({}), best score ({}), "
+ + "entity count ({}), variable count ({}), "
+ + "maximum value range size ({}), "
+ + "environment mode ({}), move thread count ({}), random ({}).",
(startingSolverCount == 1 ? "started" : "restarted"),
solverScope.calculateTimeMillisSpentUpToNow(),
solverScope.getBestScore(),
+ solverScope.getProblemStatistics().entityCount(),
+ solverScope.getProblemStatistics().variableCount(),
+ solverScope.getProblemStatistics().maximumValueRangeSize(),
environmentMode.name(),
moveThreadCountDescription,
(randomFactory != null ? randomFactory : "not fixed"));
}
+ private void registerSolverSpecificMetrics() {
+ solverScope.setProblemStatistics(
+ solverScope.calculateProblemStatistics(getSolverScope().getWorkingSolution()));
+ Metrics.gauge(SolverMetric.SCORE_CALCULATION_COUNT.getMeterId(), solverScope.getMonitoringTags(),
+ solverScope, SolverScope::getScoreCalculationCount);
+ Metrics.gauge(SolverMetric.PROBLEM_ENTITY_COUNT.getMeterId(), solverScope.getMonitoringTags(),
+ solverScope.getProblemStatistics(), ProblemStatistics::entityCount);
+ Metrics.gauge(SolverMetric.PROBLEM_VARIABLE_COUNT.getMeterId(), solverScope.getMonitoringTags(),
+ solverScope.getProblemStatistics(), ProblemStatistics::variableCount);
+ Metrics.gauge(SolverMetric.PROBLEM_VALUE_COUNT.getMeterId(), solverScope.getMonitoringTags(),
+ solverScope.getProblemStatistics(), ProblemStatistics::maximumValueRangeSize);
+ solverScope.getSolverMetricSet().forEach(solverMetric -> solverMetric.register(this));
+ }
+
+ private void unregisterSolverSpecificMetrics() {
+ for (var metric : List.of(SolverMetric.SCORE_CALCULATION_COUNT,
+ SolverMetric.PROBLEM_ENTITY_COUNT,
+ SolverMetric.PROBLEM_VARIABLE_COUNT,
+ SolverMetric.PROBLEM_VALUE_COUNT)) { | Shouldn't we unregister the metrics that are registered, instead of relying on a list that needs to be updated every time we add a new default metric?
This is a bug in the making. |
timefold-solver | github_2023 | java | 671 | TimefoldAI | triceo | @@ -224,6 +226,22 @@ public long getTimeMillisSpent() {
return endingSystemTimeMillis - startingSystemTimeMillis;
}
+ public ProblemStatistics getProblemStatistics() {
+ return problemStatistics;
+ }
+
+ public void setProblemStatistics(ProblemStatistics problemStatistics) {
+ this.problemStatistics = problemStatistics;
+ }
+
+ public ProblemStatistics calculateProblemStatistics(Solution_ problem) {
+ var solutionDescriptor = getSolutionDescriptor();
+ return new ProblemStatistics(solutionDescriptor.getGenuineEntityCount(problem),
+ solutionDescriptor.getGenuineVariableCount(problem),
+ solutionDescriptor.getMaximumValueRangeSize(problem),
+ solutionDescriptor.getProblemScale(problem));
+ } | This might as well be on the `SolutionDescriptor` directly. It only uses stuff from there. |
timefold-solver | github_2023 | java | 671 | TimefoldAI | triceo | @@ -302,16 +330,20 @@ public void solvingEnded(SolverScope<Solution_> solverScope) {
}
public void outerSolvingEnded(SolverScope<Solution_> solverScope) {
- // Must be kept open for doProblemFactChange
- solverScope.getScoreDirector().close();
logger.info("Solving ended: time spent ({}), best score ({}), score calculation speed ({}/sec), "
+ + "entity count ({}), variable count ({}), maximum value range size ({}), "
+ "phase total ({}), environment mode ({}), move thread count ({}).",
solverScope.getTimeMillisSpent(),
solverScope.getBestScore(),
solverScope.getScoreCalculationSpeed(),
+ solverScope.getProblemStatistics().entityCount(),
+ solverScope.getProblemStatistics().variableCount(),
+ solverScope.getProblemStatistics().maximumValueRangeSize(),
phaseList.size(),
environmentMode.name(),
moveThreadCountDescription); | I'm thinking that maybe we introduce a new logging line for problem statistics?
It seems to me that the counts and sizes are a different kind of information than the env mode, move thread count etc. - one is problem-specific, one is solver configuration.
Not entirely sure about it, but the current approach seems to me like information overload. Too much information at the same place. |
timefold-solver | github_2023 | java | 671 | TimefoldAI | triceo | @@ -0,0 +1,12 @@
+package ai.timefold.solver.core.api.solver;
+
+/**
+ * The statistics of a given problem submitted to a {@link Solver}.
+ *
+ * @param entityCount The number of genuine entities defined by the problem.
+ * @param variableCount The number of genuine variables defined by the problem.
+ * @param maximumValueRangeSize The number of possible assignments for the genuine variable with the largest range.
+ * @param problemScale An approximate log of the solution space.
+ */
+public record ProblemStatistics(long entityCount, long variableCount, long maximumValueRangeSize, long problemScale) { | Since this is public API, maybe we need to think about this a bit more.
Shouldn't it be `planningEntityCount`? `planningVariableCount`?
Maybe it's `SolutionStatistics`?
Perhaps we should start a quick poll on Slack. |
timefold-solver | github_2023 | java | 671 | TimefoldAI | triceo | @@ -0,0 +1,12 @@
+package ai.timefold.solver.core.api.solver;
+
+/**
+ * The statistics of a given problem submitted to a {@link Solver}.
+ *
+ * @param entityCount The number of genuine entities defined by the problem.
+ * @param variableCount The number of genuine variables defined by the problem.
+ * @param maximumValueRangeSize The number of possible assignments for the genuine variable with the largest range. | We already have to iterate over every entity to get this number. So I'm wondering... why not replace this number with a total number of distinct values?
Could be a perf problem for int value ranges, which could easily include millions of distinct values. But for multi-variate problems, it does seem fairer to get a sum instead of the max. |
timefold-solver | github_2023 | java | 671 | TimefoldAI | triceo | @@ -121,12 +119,10 @@ public SubSingleBenchmarkRunner<Solution_> call() {
subSingleStatistic.hibernatePointList();
}
if (!warmUp) {
- SolverScope<Solution_> solverScope = solver.getSolverScope();
- SolutionDescriptor<Solution_> solutionDescriptor = solverScope.getSolutionDescriptor();
- problemBenchmarkResult.registerScale(solutionDescriptor.getGenuineEntityCount(solution),
- solutionDescriptor.getGenuineVariableCount(solution),
- solutionDescriptor.getMaximumValueCount(solution),
- solutionDescriptor.getProblemScale(solution));
+ var solverScope = solver.getSolverScope();
+ var solutionDescriptor = solverScope.getSolutionDescriptor();
+ problemBenchmarkResult
+ .registerScale(solutionDescriptor.getProblemSizeStatistics(solverScope.getScoreDirector(), solution)); | Aren't we mixing terms here? One speaks of scale, the other speaks of size. |
timefold-solver | github_2023 | java | 671 | TimefoldAI | triceo | @@ -419,45 +420,42 @@ private void determineWinningScoreDifference() {
* HACK to avoid loading the problem just to extract its problemScale.
* Called multiple times, for every {@link SingleBenchmarkResult} of this {@link ProblemBenchmarkResult}.
*
- * @param registeringEntityCount {@code >= 0}
- * @param registeringVariableCount {@code >= 0}
- * @param registeringProblemScale {@code >= 0}
+ * @param problemStatistics never null
*/
- public void registerScale(long registeringEntityCount, long registeringVariableCount,
- long registeringMaximumValueCount, long registeringProblemScale) {
+ public void registerScale(ProblemSizeStatistics problemStatistics) { | Arguably `problemSizeStatistics` now.
Please look for all uses of `problemStatistics` (incl. in getter/setter names) and make it consistent - looking at the PR, there are several places where you kept the old name, and I won't list all of them. |
timefold-solver | github_2023 | java | 671 | TimefoldAI | triceo | @@ -0,0 +1,50 @@
+package ai.timefold.solver.core.api.solver;
+
+import java.text.DecimalFormat;
+
+import ai.timefold.solver.core.impl.util.MathUtils;
+
+/**
+ * The statistics of a given problem submitted to a {@link Solver}.
+ *
+ * @param entityCount The number of genuine entities defined by the problem.
+ * @param variableCount The number of genuine variables defined by the problem.
+ * @param approximateValueCount The estimated number of values defined by the problem.
+ * Can be larger than the actual value count.
+ * @param approximateProblemSizeLog The estimated log_10 of the problem's search space.
+ */
+public record ProblemSizeStatistics(long entityCount,
+ long variableCount,
+ long approximateValueCount,
+ double approximateProblemSizeLog) {
+
+ private static final DecimalFormat BASIC_FORMATTER = new DecimalFormat("#,###");
+
+ // Exponent should not use grouping, unlike basic
+ private static final DecimalFormat EXPONENT_FORMATTER = new DecimalFormat("#");
+ private static final DecimalFormat SIGNIFICANT_FIGURE_FORMATTER = new DecimalFormat("0.######");
+
+ /**
+ * Return the {@link #approximateProblemSizeLog} as a fixed point integer.
+ */
+ public long getApproximateProblemScaleLogAsFixedPointLong() {
+ return Math.round(approximateProblemSizeLog * MathUtils.LOG_PRECISION);
+ }
+
+ public String formatApproximateProblemScale() {
+ if (approximateProblemSizeLog < 10) {
+ // log_10(10_000_000_000) = 10
+ return "~%s".formatted(BASIC_FORMATTER.format(Math.pow(10d, approximateProblemSizeLog)));
+ }
+ // The actual number will often be too large to fit in a double, so cannot use normal
+ // formatting.
+ // Separate the exponent into its integral and fractional parts
+ // Use the integral part as the power of 10, and the fractional part as the significant digits.
+ double exponentPart = Math.floor(approximateProblemSizeLog);
+ double remainderPartAsExponent = approximateProblemSizeLog - exponentPart;
+ double remainderPart = Math.pow(10, remainderPartAsExponent);
+ return "~%se%s".formatted( | I'd prefer going with a more human-readable `A × 10^B`, unless there is a specific reason why we can't do that. |
timefold-solver | github_2023 | java | 671 | TimefoldAI | triceo | @@ -684,22 +687,57 @@ public long getMaximumValueCount(Solution_ solution, Object entity) {
}
- public long getProblemScale(Solution_ solution, Object entity) {
- int genuineEntityCount = getSolutionDescriptor().getGenuineEntityCount(solution);
- long problemScale = 1L;
+ public void processProblemScale(ScoreDirector<Solution_> scoreDirector, Solution_ solution, Object entity,
+ SolutionDescriptor.ProblemScaleTracker tracker) {
for (GenuineVariableDescriptor<Solution_> variableDescriptor : effectiveGenuineVariableDescriptorList) {
long valueCount = variableDescriptor.getValueRangeSize(solution, entity);
- problemScale *= valueCount;
- if (variableDescriptor.isListVariable()) {
- // This formula probably makes no sense other than that it results in the same problem scale for both
- // chained and list variable models.
- // TODO fix https://issues.redhat.com/browse/PLANNER-2623 to get rid of this.
- problemScale *= valueCount;
- problemScale /= genuineEntityCount;
- problemScale += valueCount;
+ // TODO: When minimum Java supported is 21, this can be replaced with a sealed interface switch
+ if (variableDescriptor instanceof BasicVariableDescriptor<Solution_> basicVariableDescriptor) {
+ if (basicVariableDescriptor.isChained()) {
+ // An entity is a value
+ tracker.listTotalValueCount().increment();
+ if (!isMovable(scoreDirector, entity)) {
+ tracker.listPinnedValueCount().increment();
+ }
+ // Anchors are entities
+ ValueRange<?> valueRange = variableDescriptor.getValueRangeDescriptor().extractValueRange(solution, entity);
+ if (valueRange instanceof CountableValueRange<?> countableValueRange) {
+ Iterator<?> valueIterator = countableValueRange.createOriginalIterator();
+ while (valueIterator.hasNext()) {
+ Object value = valueIterator.next();
+ if (variableDescriptor.isValuePotentialAnchor(value)) {
+ if (tracker.visitedAnchorSet().contains(value)) {
+ continue;
+ }
+ tracker.visitedAnchorSet().add(value);
+ tracker.listTotalEntityCount().increment();
+ tracker.listMovableEntityCount().increment();
+ // Assumes anchors are not pinned
+ }
+ }
+ } else {
+ // Assume 0 entities (this might be impossible) | Uncountable value ranges already fail fast elsewhere. Please confirm and if that's the case, please also fail fast here. People shouldn't be using them. |
timefold-solver | github_2023 | java | 671 | TimefoldAI | triceo | @@ -1026,7 +1030,39 @@ public long getGenuineVariableCount(Solution_ solution) {
return result.longValue();
}
- public long getMaximumValueCount(Solution_ solution) {
+ /**
+ * @param solution never null
+ * @return {@code >= 0}
+ */
+ public long getApproximateValueCount(Solution_ solution) {
+ Set<GenuineVariableDescriptor<Solution_>> genuineVariableDescriptorSet = | IMO this is precisely the kind of code that benefits from `var` the most. We have `Set` in the var name, we have `Set` in the method call on the right, no need to repeat the entire type on the left. (Even if it means putting the generic type directly to the diamond of `IdentityHashMap`.) |
timefold-solver | github_2023 | java | 671 | TimefoldAI | triceo | @@ -1036,22 +1072,64 @@ public long getMaximumValueCount(Solution_ solution) {
.orElse(0L);
}
+ public record ProblemScaleTracker(long logBase, | This is abusing the record a bit, isn't it? Records are supposed to be immutable, and to get that, we introduce deeply mutable types. :-) Personally, I think this should just be a class, which in turn would allow us to get rid of the `MutableLong`. |
timefold-solver | github_2023 | java | 671 | TimefoldAI | triceo | @@ -1036,22 +1072,64 @@ public long getMaximumValueCount(Solution_ solution) {
.orElse(0L);
}
+ public record ProblemScaleTracker(long logBase,
+ MutableLong basicProblemScaleLog,
+ Set<Object> visitedAnchorSet,
+ MutableLong listPinnedValueCount,
+ MutableLong listTotalEntityCount,
+ MutableLong listMovableEntityCount,
+ MutableLong listTotalValueCount) {
+ public void addBasicProblemScale(long count) {
+ basicProblemScaleLog.add(MathUtils.getScaledApproximateLog(MathUtils.LOG_PRECISION, logBase, count));
+ }
+ }
+
/**
* Calculates an indication on how big this problem instance is.
- * This is intentionally very loosely defined for now.
+ * This is approximately the base 10 log of the solution space size. | Solution space size... Maybe we use "search space size" instead? It's closer to the industry lingo. (Assuming that search space size is what you mean here.) |
timefold-solver | github_2023 | java | 671 | TimefoldAI | triceo | @@ -234,16 +226,34 @@ public void solvingStarted(SolverScope<Solution_> solverScope) {
solverScope.startingNow();
solverScope.getScoreDirector().resetCalculationCount();
super.solvingStarted(solverScope);
- int startingSolverCount = solverScope.getStartingSolverCount() + 1;
+ var startingSolverCount = solverScope.getStartingSolverCount() + 1;
solverScope.setStartingSolverCount(startingSolverCount);
- logger.info("Solving {}: time spent ({}), best score ({}), environment mode ({}), "
- + "move thread count ({}), random ({}).",
+ registerSolverSpecificMetrics();
+ logger.info("Solving {}: time spent ({}), best score ({}), "
+ + "environment mode ({}), move thread count ({}), random ({}).",
(startingSolverCount == 1 ? "started" : "restarted"),
solverScope.calculateTimeMillisSpentUpToNow(),
solverScope.getBestScore(),
environmentMode.name(),
moveThreadCountDescription,
(randomFactory != null ? randomFactory : "not fixed"));
+ logger.info( | I keep thinking... isn't it enough to print this just once, either at start or finish?
It will end up in the log, which means it's just duplication if the same information is there twice. |
timefold-solver | github_2023 | others | 624 | TimefoldAI | triceo | @@ -443,6 +443,9 @@
<xs:element minOccurs="0" name="constraintStreamImplType" type="tns:constraintStreamImplType"/>
+ <xs:element minOccurs="0" name="constraintStreamShareLambdas" type="xs:boolean"/> | Not sure about the name. Maybe we should avoid implementation details?
- `constraintStreamAutomaticNodeSharing` (true/false)
- `constraintStreamNodeSharing` (auto/none) |
timefold-solver | github_2023 | java | 624 | TimefoldAI | triceo | @@ -90,7 +94,8 @@ <Solution_> DestinationSelector<Solution_> applyNearbySelection(DestinationSelec
public enum Feature {
MULTITHREADED_SOLVING("Multi-threaded solving", "remove moveThreadCount from solver configuration"),
PARTITIONED_SEARCH("Partitioned search", "remove partitioned search phase from solver configuration"),
- NEARBY_SELECTION("Nearby selection", "remove nearby selection from solver configuration");
+ NEARBY_SELECTION("Nearby selection", "remove nearby selection from solver configuration"),
+ LAMBDA_SHARING("Lambda sharing", "remove lambda sharing from solver configuration"); | ```suggestion
LAMBDA_SHARING("Automatic node sharing", "remove automatic node sharing from solver configuration");
``` |
timefold-solver | github_2023 | others | 624 | TimefoldAI | triceo | @@ -716,5 +717,215 @@ the host is likely to hang or freeze,
unless there is an OS specific policy in place to avoid Timefold Solver from hogging all the CPU processors.
====
+[#automaticNodeSharing]
+=== Automatic node sharing
+[NOTE]
+====
+This feature is a commercial feature of Timefold Solver Enterprise Edition.
+It is not available in the Community Edition.
+====
+
+When using xref:constraints-and-score/score-calculation.adoc#constraintStreams[constraint streams], each xref:constraints-and-score/score-calculation.adoc#constraintStreamsBuildingBlocks[building block] forms a node in the score calculation network. | Think like a user who wants to use this feature. What do they want to know first?
- What do I get out of it?
- How do I enable it?
Everything else is secondary. Start with a simple paragraph explaining what it's for (improves score speeds when many constraints). If you can give a ballpark estimate for the improvements (10%, 50%, ...), do that. Then show the configuration tab. Then mention the downside (debugging).
Only after that, separate sub-sections can explain all the gory details like what it does, what's the downside. Most people won't read that, they just want to get stuff done. They will be happy with the first paragraph. The other paragraphs are for people who like to understand, like us. |
timefold-solver | github_2023 | others | 624 | TimefoldAI | triceo | @@ -716,5 +717,215 @@ the host is likely to hang or freeze,
unless there is an OS specific policy in place to avoid Timefold Solver from hogging all the CPU processors.
====
+[#automaticNodeSharing]
+=== Automatic node sharing
+[NOTE]
+====
+This feature is a commercial feature of Timefold Solver Enterprise Edition.
+It is not available in the Community Edition.
+====
+
+When using xref:constraints-and-score/score-calculation.adoc#constraintStreams[constraint streams], each xref:constraints-and-score/score-calculation.adoc#constraintStreamsBuildingBlocks[building block] forms a node in the score calculation network.
+When two building blocks are functionality equivalent, they can share the same node in the network.
+Sharing nodes allows the operation to be performed only once instead of multiple times, improving the performance of the solver.
+To be functionality equivalent, the following must be true:
+
+* The building blocks must represent the same operation.
+
+* The building blocks must have functionality equivalent parent building blocks.
+
+* The building blocks must have functionality equivalent inputs.
+
+For example, the building blocks below are functionality equivalent:
+
+[source,java,options="nowrap"]
+----
+Predicate<Shift> predicate = shift -> shift.getEmployee().getName().equals("Ann");
+
+var a = factory.forEach(Shift.class)
+ .filter(predicate);
+
+var b = factory.forEach(Shift.class)
+ .filter(predicate);
+----
+
+Whereas these building blocks are not functionality equivalent:
+
+[source,java,options="nowrap"]
+----
+Predicate<Shift> predicate1 = shift -> shift.getEmployee().getName().equals("Ann");
+Predicate<Shift> predicate2 = shift -> shift.getEmployee().getName().equals("Bob");
+
+// Different parents
+var a = factory.forEach(Shift.class)
+ .filter(predicate2);
+
+var b = factory.forEach(Shift.class)
+ .filter(predicate1)
+ .filter(predicate2);
+
+// Different operations
+var a = factory.forEach(Shift.class)
+ .ifExists(Employee.class);
+
+var b = factory.forEach(Shift.class)
+ .ifNotExists(Employee.class);
+
+// Different inputs
+var a = factory.forEach(Shift.class)
+ .filter(predicate1);
+
+var b = factory.forEach(Shift.class)
+ .filter(predicate2);
+----
+
+Counterintuitively, the building blocks produced by these (seemly) identical methods are not necessarily functionality equivalent:
+
+[source,java,options="nowrap"]
+----
+UniConstraintStream<Shift> a(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter(shift -> shift.getEmployee().getName().equals("Ann"));
+}
+
+UniConstraintStream<Shift> b(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter(shift -> shift.getEmployee().getName().equals("Ann"));
+}
+----
+
+The Java Virtual Machine is free to (and often does) create different instances of functionality equivalent lambdas.
+This severely limits the effectiveness of node sharing, since the only way to know two lambdas are equal is to compare their references.
+
+When automatic node sharing is used, the `ConstraintProvider` class is transformed so all lambdas are accessed via a static final field.
+So a class that looks like this:
+
+[source,java,options="nowrap"]
+----
+public class MyConstraintProvider implements ConstraintProvider {
+
+ public Constraint[] defineConstraints(ConstraintFactory constraintFactory) {
+ return new Constraint[] {
+ a(constraintFactory),
+ b(constraintFactory)
+ };
+ }
+
+ Constraint a(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter(shift -> shift.getEmployee().getName().equals("Ann"))
+ .penalize(SimpleScore.ONE)
+ .asConstraint("a");
+ }
+ Constraint b(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter(shift -> shift.getEmployee().getName().equals("Ann"))
+ .penalize(SimpleScore.ONE)
+ .asConstraint("b");
+ }
+}
+----
+
+is transformed to a class that looks like this:
+
+[source,java,options="nowrap"]
+----
+public class MyConstraintProvider implements ConstraintProvider {
+ private static final Predicate<Shift> $predicate1 = shift -> shift.getEmployee().getName().equals("Ann");
+
+ public Constraint[] defineConstraints(ConstraintFactory constraintFactory) {
+ return new Constraint[] {
+ a(constraintFactory),
+ b(constraintFactory)
+ };
+ }
+
+ Constraint a(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter($predicate1)
+ .penalize(SimpleScore.ONE)
+ .asConstraint("a");
+ }
+
+ Constraint b(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter($predicate1)
+ .penalize(SimpleScore.ONE)
+ .asConstraint("b");
+ }
+}
+----
+
+IMPORTANT: This transformation prevents breakpoints from being placed inside the ConstraintProvider. | As explained above, this needs to be up there. But because it can not mention this transformation, it needs to be restated. Something like "Debugging breakpoints put inside your constraints will not be respected, because the `ConstraintProvider` class will be transformed when this feature is enabled".
Then when you're back down here, you can mention it again - and now they will understand _why_. Those that will care. Which, again, most won't. |
timefold-solver | github_2023 | others | 624 | TimefoldAI | triceo | @@ -716,5 +717,215 @@ the host is likely to hang or freeze,
unless there is an OS specific policy in place to avoid Timefold Solver from hogging all the CPU processors.
====
+[#automaticNodeSharing]
+=== Automatic node sharing
+[NOTE]
+====
+This feature is a commercial feature of Timefold Solver Enterprise Edition.
+It is not available in the Community Edition.
+====
+
+When using xref:constraints-and-score/score-calculation.adoc#constraintStreams[constraint streams], each xref:constraints-and-score/score-calculation.adoc#constraintStreamsBuildingBlocks[building block] forms a node in the score calculation network.
+When two building blocks are functionality equivalent, they can share the same node in the network.
+Sharing nodes allows the operation to be performed only once instead of multiple times, improving the performance of the solver.
+To be functionality equivalent, the following must be true:
+
+* The building blocks must represent the same operation.
+
+* The building blocks must have functionality equivalent parent building blocks.
+
+* The building blocks must have functionality equivalent inputs.
+
+For example, the building blocks below are functionality equivalent:
+
+[source,java,options="nowrap"]
+----
+Predicate<Shift> predicate = shift -> shift.getEmployee().getName().equals("Ann");
+
+var a = factory.forEach(Shift.class)
+ .filter(predicate);
+
+var b = factory.forEach(Shift.class)
+ .filter(predicate);
+----
+
+Whereas these building blocks are not functionality equivalent:
+
+[source,java,options="nowrap"]
+----
+Predicate<Shift> predicate1 = shift -> shift.getEmployee().getName().equals("Ann");
+Predicate<Shift> predicate2 = shift -> shift.getEmployee().getName().equals("Bob");
+
+// Different parents
+var a = factory.forEach(Shift.class)
+ .filter(predicate2);
+
+var b = factory.forEach(Shift.class)
+ .filter(predicate1)
+ .filter(predicate2);
+
+// Different operations
+var a = factory.forEach(Shift.class)
+ .ifExists(Employee.class);
+
+var b = factory.forEach(Shift.class)
+ .ifNotExists(Employee.class);
+
+// Different inputs
+var a = factory.forEach(Shift.class)
+ .filter(predicate1);
+
+var b = factory.forEach(Shift.class)
+ .filter(predicate2);
+----
+
+Counterintuitively, the building blocks produced by these (seemly) identical methods are not necessarily functionality equivalent:
+
+[source,java,options="nowrap"]
+----
+UniConstraintStream<Shift> a(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter(shift -> shift.getEmployee().getName().equals("Ann"));
+}
+
+UniConstraintStream<Shift> b(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter(shift -> shift.getEmployee().getName().equals("Ann"));
+}
+----
+
+The Java Virtual Machine is free to (and often does) create different instances of functionality equivalent lambdas.
+This severely limits the effectiveness of node sharing, since the only way to know two lambdas are equal is to compare their references.
+
+When automatic node sharing is used, the `ConstraintProvider` class is transformed so all lambdas are accessed via a static final field.
+So a class that looks like this:
+
+[source,java,options="nowrap"]
+----
+public class MyConstraintProvider implements ConstraintProvider {
+
+ public Constraint[] defineConstraints(ConstraintFactory constraintFactory) {
+ return new Constraint[] {
+ a(constraintFactory),
+ b(constraintFactory)
+ };
+ }
+
+ Constraint a(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter(shift -> shift.getEmployee().getName().equals("Ann"))
+ .penalize(SimpleScore.ONE)
+ .asConstraint("a");
+ }
+ Constraint b(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter(shift -> shift.getEmployee().getName().equals("Ann"))
+ .penalize(SimpleScore.ONE)
+ .asConstraint("b");
+ }
+}
+----
+
+is transformed to a class that looks like this:
+
+[source,java,options="nowrap"]
+----
+public class MyConstraintProvider implements ConstraintProvider {
+ private static final Predicate<Shift> $predicate1 = shift -> shift.getEmployee().getName().equals("Ann");
+
+ public Constraint[] defineConstraints(ConstraintFactory constraintFactory) {
+ return new Constraint[] {
+ a(constraintFactory),
+ b(constraintFactory)
+ };
+ }
+
+ Constraint a(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter($predicate1)
+ .penalize(SimpleScore.ONE)
+ .asConstraint("a");
+ }
+
+ Constraint b(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter($predicate1)
+ .penalize(SimpleScore.ONE)
+ .asConstraint("b");
+ }
+}
+----
+
+IMPORTANT: This transformation prevents breakpoints from being placed inside the ConstraintProvider.
+
+This allows building blocks to share the same nodes without needing the `ConstraintProvider` to be written in an awkward way.
+
+==== Configuration
+
+[tabs]
+======
+Plain Java::
+* Add `ai.timefold.solver.enterprise:timefold-solver-enterprise-asm` to your `pom.xml`:
++
+[source,xml,options="nowrap"]
+----
+<!-- ... -->
+<dependencies>
+ <dependency>
+ <groupId>ai.timefold.solver.enterprise</groupId>
+ <artifactId>timefold-solver-enterprise-asm</artifactId>
+ </dependency>
+</dependencies> | This should not be necessary. This is boilerplate, we need Enterprise to be easy. Make `enterprise-core` depend on ASM by default. |
timefold-solver | github_2023 | others | 624 | TimefoldAI | triceo | @@ -716,5 +717,215 @@ the host is likely to hang or freeze,
unless there is an OS specific policy in place to avoid Timefold Solver from hogging all the CPU processors.
====
+[#automaticNodeSharing]
+=== Automatic node sharing
+[NOTE]
+====
+This feature is a commercial feature of Timefold Solver Enterprise Edition.
+It is not available in the Community Edition.
+====
+
+When using xref:constraints-and-score/score-calculation.adoc#constraintStreams[constraint streams], each xref:constraints-and-score/score-calculation.adoc#constraintStreamsBuildingBlocks[building block] forms a node in the score calculation network.
+When two building blocks are functionality equivalent, they can share the same node in the network.
+Sharing nodes allows the operation to be performed only once instead of multiple times, improving the performance of the solver.
+To be functionality equivalent, the following must be true:
+
+* The building blocks must represent the same operation.
+
+* The building blocks must have functionality equivalent parent building blocks.
+
+* The building blocks must have functionality equivalent inputs.
+
+For example, the building blocks below are functionality equivalent:
+
+[source,java,options="nowrap"]
+----
+Predicate<Shift> predicate = shift -> shift.getEmployee().getName().equals("Ann");
+
+var a = factory.forEach(Shift.class)
+ .filter(predicate);
+
+var b = factory.forEach(Shift.class)
+ .filter(predicate);
+----
+
+Whereas these building blocks are not functionality equivalent:
+
+[source,java,options="nowrap"]
+----
+Predicate<Shift> predicate1 = shift -> shift.getEmployee().getName().equals("Ann");
+Predicate<Shift> predicate2 = shift -> shift.getEmployee().getName().equals("Bob");
+
+// Different parents
+var a = factory.forEach(Shift.class)
+ .filter(predicate2);
+
+var b = factory.forEach(Shift.class)
+ .filter(predicate1)
+ .filter(predicate2);
+
+// Different operations
+var a = factory.forEach(Shift.class)
+ .ifExists(Employee.class);
+
+var b = factory.forEach(Shift.class)
+ .ifNotExists(Employee.class);
+
+// Different inputs
+var a = factory.forEach(Shift.class)
+ .filter(predicate1);
+
+var b = factory.forEach(Shift.class)
+ .filter(predicate2);
+----
+
+Counterintuitively, the building blocks produced by these (seemly) identical methods are not necessarily functionality equivalent:
+
+[source,java,options="nowrap"]
+----
+UniConstraintStream<Shift> a(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter(shift -> shift.getEmployee().getName().equals("Ann"));
+}
+
+UniConstraintStream<Shift> b(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter(shift -> shift.getEmployee().getName().equals("Ann"));
+}
+----
+
+The Java Virtual Machine is free to (and often does) create different instances of functionality equivalent lambdas.
+This severely limits the effectiveness of node sharing, since the only way to know two lambdas are equal is to compare their references.
+
+When automatic node sharing is used, the `ConstraintProvider` class is transformed so all lambdas are accessed via a static final field.
+So a class that looks like this:
+
+[source,java,options="nowrap"]
+----
+public class MyConstraintProvider implements ConstraintProvider {
+
+ public Constraint[] defineConstraints(ConstraintFactory constraintFactory) {
+ return new Constraint[] {
+ a(constraintFactory),
+ b(constraintFactory)
+ };
+ }
+
+ Constraint a(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter(shift -> shift.getEmployee().getName().equals("Ann"))
+ .penalize(SimpleScore.ONE)
+ .asConstraint("a");
+ }
+ Constraint b(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter(shift -> shift.getEmployee().getName().equals("Ann"))
+ .penalize(SimpleScore.ONE)
+ .asConstraint("b");
+ }
+}
+----
+
+is transformed to a class that looks like this:
+
+[source,java,options="nowrap"]
+----
+public class MyConstraintProvider implements ConstraintProvider {
+ private static final Predicate<Shift> $predicate1 = shift -> shift.getEmployee().getName().equals("Ann");
+
+ public Constraint[] defineConstraints(ConstraintFactory constraintFactory) {
+ return new Constraint[] {
+ a(constraintFactory),
+ b(constraintFactory)
+ };
+ }
+
+ Constraint a(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter($predicate1)
+ .penalize(SimpleScore.ONE)
+ .asConstraint("a");
+ }
+
+ Constraint b(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter($predicate1)
+ .penalize(SimpleScore.ONE)
+ .asConstraint("b");
+ }
+}
+----
+
+IMPORTANT: This transformation prevents breakpoints from being placed inside the ConstraintProvider.
+
+This allows building blocks to share the same nodes without needing the `ConstraintProvider` to be written in an awkward way.
+
+==== Configuration | I'm thinking if we should enable this by default everywhere. Enterprise ought to be simple. Maybe not right now, but eventually, yes. |
timefold-solver | github_2023 | others | 624 | TimefoldAI | triceo | @@ -716,5 +717,215 @@ the host is likely to hang or freeze,
unless there is an OS specific policy in place to avoid Timefold Solver from hogging all the CPU processors.
====
+[#automaticNodeSharing]
+=== Automatic node sharing
+[NOTE]
+====
+This feature is a commercial feature of Timefold Solver Enterprise Edition.
+It is not available in the Community Edition.
+====
+
+When using xref:constraints-and-score/score-calculation.adoc#constraintStreams[constraint streams], each xref:constraints-and-score/score-calculation.adoc#constraintStreamsBuildingBlocks[building block] forms a node in the score calculation network.
+When two building blocks are functionality equivalent, they can share the same node in the network.
+Sharing nodes allows the operation to be performed only once instead of multiple times, improving the performance of the solver.
+To be functionality equivalent, the following must be true:
+
+* The building blocks must represent the same operation.
+
+* The building blocks must have functionality equivalent parent building blocks.
+
+* The building blocks must have functionality equivalent inputs.
+
+For example, the building blocks below are functionality equivalent:
+
+[source,java,options="nowrap"]
+----
+Predicate<Shift> predicate = shift -> shift.getEmployee().getName().equals("Ann");
+
+var a = factory.forEach(Shift.class)
+ .filter(predicate);
+
+var b = factory.forEach(Shift.class)
+ .filter(predicate);
+----
+
+Whereas these building blocks are not functionality equivalent:
+
+[source,java,options="nowrap"]
+----
+Predicate<Shift> predicate1 = shift -> shift.getEmployee().getName().equals("Ann");
+Predicate<Shift> predicate2 = shift -> shift.getEmployee().getName().equals("Bob");
+
+// Different parents
+var a = factory.forEach(Shift.class)
+ .filter(predicate2);
+
+var b = factory.forEach(Shift.class)
+ .filter(predicate1)
+ .filter(predicate2);
+
+// Different operations
+var a = factory.forEach(Shift.class)
+ .ifExists(Employee.class);
+
+var b = factory.forEach(Shift.class)
+ .ifNotExists(Employee.class);
+
+// Different inputs
+var a = factory.forEach(Shift.class)
+ .filter(predicate1);
+
+var b = factory.forEach(Shift.class)
+ .filter(predicate2);
+----
+
+Counterintuitively, the building blocks produced by these (seemly) identical methods are not necessarily functionality equivalent:
+
+[source,java,options="nowrap"]
+----
+UniConstraintStream<Shift> a(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter(shift -> shift.getEmployee().getName().equals("Ann"));
+}
+
+UniConstraintStream<Shift> b(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter(shift -> shift.getEmployee().getName().equals("Ann"));
+}
+----
+
+The Java Virtual Machine is free to (and often does) create different instances of functionality equivalent lambdas.
+This severely limits the effectiveness of node sharing, since the only way to know two lambdas are equal is to compare their references.
+
+When automatic node sharing is used, the `ConstraintProvider` class is transformed so all lambdas are accessed via a static final field.
+So a class that looks like this:
+
+[source,java,options="nowrap"]
+----
+public class MyConstraintProvider implements ConstraintProvider {
+
+ public Constraint[] defineConstraints(ConstraintFactory constraintFactory) {
+ return new Constraint[] {
+ a(constraintFactory),
+ b(constraintFactory)
+ };
+ }
+
+ Constraint a(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter(shift -> shift.getEmployee().getName().equals("Ann"))
+ .penalize(SimpleScore.ONE)
+ .asConstraint("a");
+ }
+ Constraint b(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter(shift -> shift.getEmployee().getName().equals("Ann"))
+ .penalize(SimpleScore.ONE)
+ .asConstraint("b");
+ }
+}
+----
+
+is transformed to a class that looks like this:
+
+[source,java,options="nowrap"]
+----
+public class MyConstraintProvider implements ConstraintProvider {
+ private static final Predicate<Shift> $predicate1 = shift -> shift.getEmployee().getName().equals("Ann");
+
+ public Constraint[] defineConstraints(ConstraintFactory constraintFactory) {
+ return new Constraint[] {
+ a(constraintFactory),
+ b(constraintFactory)
+ };
+ }
+
+ Constraint a(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter($predicate1)
+ .penalize(SimpleScore.ONE)
+ .asConstraint("a");
+ }
+
+ Constraint b(ConstraintFactory constraintFactory) {
+ return factory.forEach(Shift.class)
+ .filter($predicate1)
+ .penalize(SimpleScore.ONE)
+ .asConstraint("b");
+ }
+}
+----
+
+IMPORTANT: This transformation prevents breakpoints from being placed inside the ConstraintProvider.
+
+This allows building blocks to share the same nodes without needing the `ConstraintProvider` to be written in an awkward way.
+
+==== Configuration
+
+[tabs]
+======
+Plain Java::
+* Add `ai.timefold.solver.enterprise:timefold-solver-enterprise-asm` to your `pom.xml`:
++
+[source,xml,options="nowrap"]
+----
+<!-- ... -->
+<dependencies>
+ <dependency>
+ <groupId>ai.timefold.solver.enterprise</groupId>
+ <artifactId>timefold-solver-enterprise-asm</artifactId>
+ </dependency>
+</dependencies>
+<!-- ... -->
+----
++
+* Add `<constraintStreamAutomaticNodeSharing>true</constraintStreamAutomaticNodeSharing>` in your `solverConfig.xml`:
++
+[source,xml,options="nowrap"]
+----
+<!-- ... -->
+<scoreDirectorFactory>
+ <constraintProviderClass>org.acme.MyConstraintProvider</constraintProviderClass>
+ <constraintStreamAutomaticNodeSharing>true</constraintStreamAutomaticNodeSharing>
+</scoreDirectorFactory>
+<!-- ... -->
+----
+
+Spring Boot::
+* Add `ai.timefold.solver.enterprise:timefold-solver-enterprise-asm` to your `pom.xml`:
++
+[source,xml,options="nowrap"]
+----
+<!-- ... -->
+<dependencies>
+ <dependency>
+ <groupId>ai.timefold.solver.enterprise</groupId>
+ <artifactId>timefold-solver-enterprise-asm</artifactId>
+ </dependency>
+</dependencies>
+<!-- ... -->
+----
++
+* Add `<constraintStreamAutomaticNodeSharing>true</constraintStreamAutomaticNodeSharing>` in your `solverConfig.xml`:
++
+[source,xml,options="nowrap"]
+----
+<!-- ... -->
+<scoreDirectorFactory>
+ <constraintProviderClass>org.acme.MyConstraintProvider</constraintProviderClass>
+ <constraintStreamAutomaticNodeSharing>true</constraintStreamAutomaticNodeSharing>
+</scoreDirectorFactory>
+<!-- ... -->
+----
+
+Quarkus::
+Automatic node sharing is enabled by default. | If we're not enabling it by default everywhere, then I'd argue it shouldn't be the default anywhere. |
timefold-solver | github_2023 | others | 670 | TimefoldAI | zepfred | @@ -1,11 +1,14 @@
-# This workflow currently doesn't work as a PR can not check out a private repo due to no secrets being available.
name: Downstream - Timefold Solver Enterprise Edition
on:
- push:
- branches: [main]
- pull_request:
+ # Enables the workflow to run on PRs from forks;
+ # token sharing is safe here, because enterprise is a private repo and therefore fully under our control.
+ pull_request_target: | Have you checked if the action ran after submitting a PR in your fork?
I suspect that the CI may not run if we open a PR due to the `branches` property: `branches: [main, '*.x']`. You can replicate it by making this modification to the main branch of your fork and submitting a pull request to your fork. |
timefold-solver | github_2023 | others | 660 | TimefoldAI | triceo | @@ -472,13 +480,28 @@ Increase the termination time to potentially find a better solution.
== Run the application
-First start the application:
+First start the application in dev mode:
+IMPORTANT: The solver runs considerably slower in dev mode since the https://www.baeldung.com/jvm-tiered-compilation#2c2---server-complier[JVM C2 compiler] is disabled to decrease live reload times. | I question if we need this, and if this is important.
- I'd convert it to `NOTE` and use [Admonition](https://docs.asciidoctor.org/asciidoc/latest/blocks/admonitions/) to mark it properly.
- I'd move it to the end after the code examples; don't break user flow. They want to see it work, performance is a secondary consideration. |
timefold-solver | github_2023 | others | 660 | TimefoldAI | triceo | @@ -873,6 +896,50 @@ Use `debug` logging to show every _step_:
Use `trace` logging to show every _step_ and every _move_ per step.
+=== Create a native image
+
+[[native]]
+IMPORTANT: The solver runs considerably slower in a native image due to a lack of https://www.baeldung.com/jvm-tiered-compilation#1-best-of-both-worlds[profiling based JIT optimizations that a JVM performs]. | I suggest we remove this note altogether.
Native has its trade-offs and benefits; it is not for us docs to explain what those are, right? Our docs should explain how to get it to work. |
timefold-solver | github_2023 | others | 660 | TimefoldAI | triceo | @@ -873,6 +896,50 @@ Use `debug` logging to show every _step_:
Use `trace` logging to show every _step_ and every _move_ per step.
+=== Create a native image
+
+[[native]]
+IMPORTANT: The solver runs considerably slower in a native image due to a lack of https://www.baeldung.com/jvm-tiered-compilation#1-best-of-both-worlds[profiling based JIT optimizations that a JVM performs].
+
+To decrease startup times for serverless deployments, or to deploy to environments without a JVM, you can build the application as a native executable:
+
+Prerequisites:
+https://quarkus.io/guides/building-native-image#configuring-graalvm[Install GraalVM and gu install the native-image tool] | ```suggestion
To decrease startup times for serverless deployments, or to deploy to environments without a JVM, you can build the application as a native executable. As a prerequisite, https://quarkus.io/guides/building-native-image#configuring-graalvm[install GraalVM and gu install the native-image tool]. Then continue with your build tool of choice:
``` |
timefold-solver | github_2023 | others | 660 | TimefoldAI | triceo | @@ -166,10 +169,16 @@ dependencies {
test {
useJUnitPlatform()
}
+
+tasks.named("bootRun") {
+ optimizedLaunch = false
+}
----
--
====
+IMPORTANT: Optimized launch is disabled, since optimized launch disables the https://www.baeldung.com/jvm-tiered-compilation#2c2---server-complier[JVM C2 compiler], considerably decreasing the solver's performance. | Use Admonition as described above.
Arguably, the concerns on optimized launch only apply to dev usage, and therefore should be in this note, and not above as the general example of doing things. |
timefold-solver | github_2023 | others | 660 | TimefoldAI | triceo | @@ -779,6 +788,75 @@ Use `debug` logging to show every _step_:
Use `trace` logging to show every _step_ and every _move_ per step.
+=== Create a native image
+
+IMPORTANT: The solver runs considerably slower in a native image due to a lack of https://www.baeldung.com/jvm-tiered-compilation#1-best-of-both-worlds[profiling based JIT optimizations that a JVM performs].
+
+If you want faster startup times or need to deploy to an environment without a JVM, you can build a native image. | ```suggestion
To achieve faster startup times or to deploy to an environment without a JVM, you can build a native image:
``` |
timefold-solver | github_2023 | others | 660 | TimefoldAI | triceo | @@ -779,6 +788,75 @@ Use `debug` logging to show every _step_:
Use `trace` logging to show every _step_ and every _move_ per step.
+=== Create a native image
+
+IMPORTANT: The solver runs considerably slower in a native image due to a lack of https://www.baeldung.com/jvm-tiered-compilation#1-best-of-both-worlds[profiling based JIT optimizations that a JVM performs]. | Remove please, rationale given above. |
timefold-solver | github_2023 | java | 573 | TimefoldAI | Christopher-Chianelli | @@ -90,9 +91,10 @@ public class EntityDescriptor<Solution_> {
private final SolutionDescriptor<Solution_> solutionDescriptor;
private final Class<?> entityClass;
private final Predicate<Object> isInitializedPredicate;
- private final Predicate<Object> hasNoNullVariables;
private final List<MemberAccessor> declaredPlanningPinIndexMemberAccessorList = new ArrayList<>();
+ private Predicate<Object> hasNoNullVariablesBasicVar;
+ private Predicate<Object> hasNoNullVariablesListVar; | `hasNoUnassignedVariablesListVar`, since `nullable` deprecated? |
timefold-solver | github_2023 | java | 573 | TimefoldAI | Christopher-Chianelli | @@ -146,16 +147,49 @@ public int getOrdinal() {
* Using entityDescriptor::isInitialized directly breaks node sharing
* because it creates multiple instances of this {@link Predicate}.
*
- * @deprecated Prefer {@link #getHasNoNullVariables()}.
+ * @deprecated Prefer {@link #getHasNoNullVariablesPredicateListVar()}.
* @return never null, always the same {@link Predicate} instance to {@link #isInitialized(Object)}
*/
@Deprecated(forRemoval = true)
public Predicate<Object> getIsInitializedPredicate() {
return isInitializedPredicate;
}
- public Predicate<Object> getHasNoNullVariables() {
- return hasNoNullVariables;
+ public <A> Predicate<A> getHasNoNullVariablesPredicateBasicVar() {
+ if (hasNoNullVariablesBasicVar == null) {
+ hasNoNullVariablesBasicVar = this::hasNoNullVariables;
+ }
+ return (Predicate<A>) hasNoNullVariablesBasicVar;
+ }
+
+ public <A> Predicate<A> getHasNoNullVariablesPredicateListVar() {
+ /*
+ * This code depends on all entity descriptors and solution descriptor to be fully initialized.
+ * For absolute safety, we only construct the predicate the first time it is requested.
+ * That will be during the building of the score director, when the descriptors are already set in stone.
+ */
+ if (hasNoNullVariablesListVar == null) {
+ var listVariableDescriptor = solutionDescriptor.getListVariableDescriptor();
+ if (listVariableDescriptor == null || !listVariableDescriptor.acceptsValueType(entityClass)) {
+ throw new IllegalStateException(
+ "Impossible state: method called without an applicable list variable descriptor.");
+ } else { | Style: pointless else, since the if throws |
timefold-solver | github_2023 | java | 573 | TimefoldAI | Christopher-Chianelli | @@ -410,13 +444,13 @@ private void createEffectiveVariableDescriptorMaps() {
}
effectiveGenuineVariableDescriptorMap.putAll(declaredGenuineVariableDescriptorMap);
effectiveShadowVariableDescriptorMap.putAll(declaredShadowVariableDescriptorMap);
- effectiveVariableDescriptorMap = new LinkedHashMap<>(
- effectiveGenuineVariableDescriptorMap.size() + effectiveShadowVariableDescriptorMap.size());
+ effectiveVariableDescriptorMap = CollectionUtils | Why is this a utility method? |
timefold-solver | github_2023 | java | 573 | TimefoldAI | Christopher-Chianelli | @@ -0,0 +1,234 @@
+package ai.timefold.solver.core.impl.domain.variable;
+
+import java.util.Collections;
+import java.util.IdentityHashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+
+import ai.timefold.solver.core.api.score.director.ScoreDirector;
+import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
+import ai.timefold.solver.core.impl.heuristic.selector.list.ElementLocation;
+import ai.timefold.solver.core.impl.heuristic.selector.list.LocationInList;
+import ai.timefold.solver.core.impl.heuristic.selector.list.UnassignedLocation;
+import ai.timefold.solver.core.impl.util.CollectionUtils;
+
+final class ExternalizedListVariableDataSupply<Solution_>
+ implements ListVariableDataSupply<Solution_> {
+
+ private final ListVariableDescriptor<Solution_> sourceVariableDescriptor;
+ private Map<Object, ElementLocation> elementLocationMap;
+ private Set<Object> applicableElementSet;
+ private int notAssignedElementCount;
+
+ public ExternalizedListVariableDataSupply(ListVariableDescriptor<Solution_> sourceVariableDescriptor) {
+ this.sourceVariableDescriptor = sourceVariableDescriptor;
+ }
+
+ @Override
+ public void resetWorkingSolution(ScoreDirector<Solution_> scoreDirector) {
+ this.elementLocationMap = new IdentityHashMap<>();
+ var workingSolution = scoreDirector.getWorkingSolution();
+ int expectedValueCount = (int) sourceVariableDescriptor.getValueRangeSize(workingSolution, null);
+ if (expectedValueCount > 0) {
+ applicableElementSet = Collections.newSetFromMap(CollectionUtils.newIdentityHashMap(expectedValueCount));
+ var elementIterator = sourceVariableDescriptor.getValuesFromValueRange(workingSolution, null);
+ while (elementIterator.hasNext()) {
+ applicableElementSet.add(elementIterator.next());
+ }
+ } else {
+ applicableElementSet = Collections.emptySet();
+ }
+ notAssignedElementCount = applicableElementSet.size();
+ sourceVariableDescriptor.getEntityDescriptor().visitAllEntities(workingSolution, this::insert);
+ }
+
+ private void insert(Object entity) {
+ var assignedElements = sourceVariableDescriptor.getValue(entity);
+ var index = 0;
+ for (var element : assignedElements) {
+ var oldLocation = elementLocationMap.put(element, new LocationInList(entity, index));
+ if (oldLocation != null) {
+ throw new IllegalStateException(
+ "The supply (%s) is corrupted, because the element (%s) at index (%d) already exists (%s)."
+ .formatted(this, element, index, oldLocation));
+ }
+ index++;
+ notAssignedElementCount--;
+ }
+ }
+
+ @Override
+ public void close() {
+ applicableElementSet = null;
+ elementLocationMap = null;
+ }
+
+ @Override
+ public void beforeEntityAdded(ScoreDirector<Solution_> scoreDirector, Object o) {
+ }
+
+ @Override
+ public void afterEntityAdded(ScoreDirector<Solution_> scoreDirector, Object o) {
+ insert(o);
+ }
+
+ @Override
+ public void beforeEntityRemoved(ScoreDirector<Solution_> scoreDirector, Object o) {
+ }
+
+ @Override
+ public void afterEntityRemoved(ScoreDirector<Solution_> scoreDirector, Object o) {
+ // When the entity is removed, its values become unassigned.
+ // An unassigned value has no inverse entity and no index.
+ retract(o);
+ }
+
+ private void retract(Object entity) {
+ var assignedElements = sourceVariableDescriptor.getValue(entity);
+ var index = 0;
+ for (var element : assignedElements) {
+ var oldElementLocation = elementLocationMap.put(element, ElementLocation.unassigned());
+ if (oldElementLocation == null) {
+ throw new IllegalStateException(
+ "The supply (%s) is corrupted, because the element (%s) at index (%d) did not exist."
+ .formatted(this, element, index));
+ } else if (oldElementLocation instanceof LocationInList oldLocationInlist) {
+ var oldIndex = oldLocationInlist.index();
+ if (oldIndex != index) {
+ throw new IllegalStateException(
+ "The supply (%s) is corrupted, because the element (%s) at index (%d) had an old index (%d) which is not the current index (%d)."
+ .formatted(this, element, index, oldIndex, index));
+ }
+ } else {
+ throw new IllegalStateException(
+ "The supply (%s) is corrupted, because the element (%s) at index (%d) was already unassigned (%s)."
+ .formatted(this, element, index, oldElementLocation));
+ }
+ index++;
+ notAssignedElementCount++;
+ }
+ }
+
+ @Override
+ public void afterListVariableElementInitialized(ListVariableDescriptor<Solution_> variableDescriptor, Object element) {
+ var oldRef = elementLocationMap.put(element, ElementLocation.unassigned());
+ if (oldRef != null) {
+ throw new IllegalStateException(
+ "The supply (%s) is corrupted, because the element (%s) already existed before initialization."
+ .formatted(this, element));
+ }
+ }
+
+ @Override
+ public void afterListVariableElementUninitialized(ListVariableDescriptor<Solution_> variableDescriptor, Object element) {
+ var oldLocation = elementLocationMap.remove(element);
+ if (oldLocation == null) {
+ throw new IllegalStateException(
+ "The supply (%s) is corrupted, because the element (%s) did not existed before uninitialization."
+ .formatted(this, element));
+ } else if (oldLocation instanceof LocationInList oldLocationInList) {
+ throw new IllegalStateException(
+ "The supply (%s) is corrupted, because the element (%s) at index (%s) was still assigned before uninitialization."
+ .formatted(this, oldLocationInList.entity(), oldLocationInList.index()));
+ }
+ }
+
+ @Override
+ public void afterListVariableElementUnassigned(ScoreDirector<Solution_> scoreDirector, Object o) {
+ var oldRef = elementLocationMap.put(o, ElementLocation.unassigned());
+ if (oldRef == null) {
+ throw new IllegalStateException(
+ "The supply (%s) is corrupted, because the element (%s) did not exist before."
+ .formatted(this, o));
+ } else if (oldRef instanceof UnassignedLocation) {
+ throw new IllegalStateException(
+ "The supply (%s) is corrupted, because the element (%s) was not assigned before."
+ .formatted(this, o));
+ }
+ notAssignedElementCount++;
+ }
+
+ @Override
+ public void beforeListVariableChanged(ScoreDirector<Solution_> scoreDirector, Object o, int fromIndex, int toIndex) {
+ }
+
+ @Override
+ public void afterListVariableChanged(ScoreDirector<Solution_> scoreDirector, Object o, int fromIndex, int toIndex) {
+ updateIndexes(o, fromIndex);
+ }
+
+ private void updateIndexes(Object entity, int startIndex) {
+ var assignedElements = sourceVariableDescriptor.getValue(entity);
+ for (var index = startIndex; index < assignedElements.size(); index++) {
+ var element = assignedElements.get(index);
+ var oldLocation = elementLocationMap.put(element, new LocationInList(entity, index));
+ if (oldLocation == null || oldLocation instanceof UnassignedLocation) {
+ // Fixes the lack of before/afterListVariableElementAssigned().
+ notAssignedElementCount--;
+ }
+ // The first element is allowed to have a null oldIndex because it might have been just assigned. | Couldn't a custom move assign multiple variables at once? |
timefold-solver | github_2023 | java | 573 | TimefoldAI | Christopher-Chianelli | @@ -1072,8 +1069,11 @@ public SolutionInitializationStatistics computeInitializationStatistics(Solution
var unassignedValueCount = new MutableInt();
var genuineEntityCount = new MutableInt();
var shadowEntityCount = new MutableInt();
- for (var listVariableDescriptor : listVariableDescriptors) {
- unassignedValueCount.add((int) listVariableDescriptor.getValueCount(solution, null));
+ for (var listVariableDescriptor : listVariableDescriptorList) {
+ if (listVariableDescriptor.allowsUnassigned()) { // Unassigned elements count as assigned.
+ continue;
+ }
+ unassignedValueCount.add((int) listVariableDescriptor.getValueRangeSize(solution, null)); | Might want to add a comment that we count the number of possibly unassigned, and then subtract the number of actually assigned (i.e. instead of counting of number of unassigned directly, we compute `valueListSize - (count(assignedValues) = sum(size of entityList))` |
timefold-solver | github_2023 | java | 573 | TimefoldAI | Christopher-Chianelli | @@ -91,35 +76,36 @@ public Class<?> getElementType() {
// ************************************************************************
@Override
- public boolean isInitialized(Object entity) {
- return true;
- }
-
- public List<Object> getListVariable(Object entity) {
- Object value = getValue(entity);
+ public List<Object> getValue(Object entity) {
+ Object value = super.getValue(entity);
if (value == null) {
throw new IllegalStateException("The planning list variable (" + this + ") of entity (" + entity + ") is null.");
}
return (List<Object>) value;
}
public Object removeElement(Object entity, int index) {
- return getListVariable(entity).remove(index);
+ return getValue(entity).remove(index);
}
public void addElement(Object entity, int index, Object element) {
- getListVariable(entity).add(index, element);
+ getValue(entity).add(index, element);
}
public Object getElement(Object entity, int index) {
- return getListVariable(entity).get(index);
+ return getValue(entity).get(index);
}
public Object setElement(Object entity, int index, Object element) {
- return getListVariable(entity).set(index, element);
+ return getValue(entity).set(index, element);
}
public int getListSize(Object entity) {
- return getListVariable(entity).size();
+ return getValue(entity).size();
+ }
+
+ public ListVariableDataDemand<Solution_> getProvidedDemand() { | Unsure about that method name; what is provided? Arbitrary data? |
timefold-solver | github_2023 | java | 573 | TimefoldAI | Christopher-Chianelli | @@ -94,7 +102,9 @@ public <Supply_ extends Supply> boolean cancel(Demand<Supply_> demand) {
var supplyWithDemandCount = supplyMap.get(demand);
if (supplyWithDemandCount == null) {
return false;
- } else if (supplyWithDemandCount.demandCount == 1L) {
+ }
+ demand.cancel(this); | If an object is demanded twice, should the demand be cancelled twice? |
timefold-solver | github_2023 | java | 573 | TimefoldAI | Christopher-Chianelli | @@ -0,0 +1,26 @@
+package ai.timefold.solver.core.impl.heuristic.move;
+
+import ai.timefold.solver.core.api.score.director.ScoreDirector;
+
+public abstract class AbstractEasyMove<Solution_> implements Move<Solution_> { | Consider adding Javadoc for this class, given it is referenced by `AbstractMove` |
timefold-solver | github_2023 | java | 573 | TimefoldAI | Christopher-Chianelli | @@ -81,7 +71,7 @@ public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) {
}
@Override
- public CompositeMove<Solution_> doMove(ScoreDirector<Solution_> scoreDirector) {
+ public Move<Solution_> doMove(ScoreDirector<Solution_> scoreDirector) { | Changes to this class look good, but I do not like the class itself, because it is very easy to create invalid composite moves. In particular, For each move in the `moveList` MUST be independent. Consider the following two moves, for instance:
```
ListSwapMove(e1, v2, e2, v3)
SublistSwap(e1, v1, v2)
```
This would be an invalid composite move, since the `SublistSwap` would become invalid (as `v1` and `v2` are now assigned to different entities when the move is executed). |
timefold-solver | github_2023 | java | 573 | TimefoldAI | Christopher-Chianelli | @@ -0,0 +1,138 @@
+package ai.timefold.solver.core.impl.heuristic.move;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import ai.timefold.solver.core.api.score.director.ScoreDirector;
+import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
+import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
+import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
+import ai.timefold.solver.core.impl.score.director.AbstractScoreDirector;
+import ai.timefold.solver.core.impl.score.director.VariableDescriptorAwareScoreDirector;
+
+final class VariableChangeRecordingScoreDirector<Solution_> implements VariableDescriptorAwareScoreDirector<Solution_> {
+
+ private final AbstractScoreDirector<Solution_, ?, ?> delegate;
+ private final List<ChangeAction<Solution_>> variableChanges;
+
+ VariableChangeRecordingScoreDirector(ScoreDirector<Solution_> delegate) {
+ this.delegate = (AbstractScoreDirector<Solution_, ?, ?>) delegate;
+ this.variableChanges = new ArrayList<>();
+ }
+
+ public List<ChangeAction<Solution_>> getVariableChanges() {
+ return variableChanges;
+ }
+
+ // For variable change operations, record the change then call the delegate
+
+ @Override
+ public void beforeVariableChanged(VariableDescriptor<Solution_> variableDescriptor, Object entity) {
+ variableChanges.add(new VariableChangeAction<>(entity, variableDescriptor.getValue(entity), variableDescriptor));
+ delegate.beforeVariableChanged(variableDescriptor, entity);
+ }
+
+ @Override
+ public void afterVariableChanged(VariableDescriptor<Solution_> variableDescriptor, Object entity) {
+ delegate.afterVariableChanged(variableDescriptor, entity);
+ }
+
+ @Override
+ public void beforeListVariableChanged(ListVariableDescriptor<Solution_> variableDescriptor, Object entity, int fromIndex,
+ int toIndex) {
+ // List is fromIndex, fromIndex, since the undo action for afterListVariableChange will clear the affected list | We can add a check here to check for user errors. In particular, if `beforeListVariableChanged` is called for the same entity twice without an `triggerVariableListeners()` call in-between, that is almost certainly an error. (Additional checks could be added to make sure there a before call for each after call, but that will be less useful). |
timefold-solver | github_2023 | java | 573 | TimefoldAI | Christopher-Chianelli | @@ -0,0 +1,138 @@
+package ai.timefold.solver.core.impl.heuristic.move;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import ai.timefold.solver.core.api.score.director.ScoreDirector;
+import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
+import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
+import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
+import ai.timefold.solver.core.impl.score.director.AbstractScoreDirector;
+import ai.timefold.solver.core.impl.score.director.VariableDescriptorAwareScoreDirector;
+
+final class VariableChangeRecordingScoreDirector<Solution_> implements VariableDescriptorAwareScoreDirector<Solution_> {
+
+ private final AbstractScoreDirector<Solution_, ?, ?> delegate;
+ private final List<ChangeAction<Solution_>> variableChanges;
+
+ VariableChangeRecordingScoreDirector(ScoreDirector<Solution_> delegate) {
+ this.delegate = (AbstractScoreDirector<Solution_, ?, ?>) delegate;
+ this.variableChanges = new ArrayList<>();
+ }
+
+ public List<ChangeAction<Solution_>> getVariableChanges() {
+ return variableChanges;
+ }
+
+ // For variable change operations, record the change then call the delegate
+
+ @Override
+ public void beforeVariableChanged(VariableDescriptor<Solution_> variableDescriptor, Object entity) {
+ variableChanges.add(new VariableChangeAction<>(entity, variableDescriptor.getValue(entity), variableDescriptor));
+ delegate.beforeVariableChanged(variableDescriptor, entity);
+ }
+
+ @Override
+ public void afterVariableChanged(VariableDescriptor<Solution_> variableDescriptor, Object entity) {
+ delegate.afterVariableChanged(variableDescriptor, entity);
+ }
+
+ @Override
+ public void beforeListVariableChanged(ListVariableDescriptor<Solution_> variableDescriptor, Object entity, int fromIndex,
+ int toIndex) {
+ // List is fromIndex, fromIndex, since the undo action for afterListVariableChange will clear the affected list
+ variableChanges.add(new ListVariableBeforeChangeAction<>(entity,
+ new ArrayList<>(variableDescriptor.getValue(entity).subList(fromIndex, toIndex)), fromIndex, toIndex,
+ variableDescriptor));
+ delegate.beforeListVariableChanged(variableDescriptor, entity, fromIndex, toIndex);
+ }
+
+ @Override
+ public void afterListVariableChanged(ListVariableDescriptor<Solution_> variableDescriptor, Object entity, int fromIndex,
+ int toIndex) {
+ // Use an empty list as old value to clear the list so beforeListVariableChanged can undo the value correctly | Outdated comment (from when `ListVariableBeforeChangeAction` and `ListVariableAfterChangeAction` shared the same code). |
timefold-solver | github_2023 | java | 573 | TimefoldAI | Christopher-Chianelli | @@ -59,7 +65,14 @@ public SelectionCacheType getCacheType() {
public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) {
super.phaseStarted(phaseScope);
InnerScoreDirector<Solution_, ?> scoreDirector = phaseScope.getScoreDirector();
+ reloadCachedEntityList(scoreDirector);
+ }
+
+ private void reloadCachedEntityList(InnerScoreDirector<Solution_, ?> scoreDirector) {
cachedEntityList = entityDescriptor.extractEntities(scoreDirector.getWorkingSolution());
+ if (includeNull) {
+ cachedEntityList.add(null); | Should `cachedEntityList` include null for an `EntitySelector`? I am not sure if `MoveSelectors` would like or expect getting a null entity from their selectors. |
timefold-solver | github_2023 | java | 573 | TimefoldAI | Christopher-Chianelli | @@ -0,0 +1,77 @@
+package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list;
+
+import java.util.Objects;
+
+import ai.timefold.solver.core.api.score.director.ScoreDirector;
+import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
+import ai.timefold.solver.core.impl.heuristic.move.AbstractEasyMove;
+import ai.timefold.solver.core.impl.score.director.VariableDescriptorAwareScoreDirector;
+
+public final class ListInitializeMove<Solution_> extends AbstractEasyMove<Solution_> {
+
+ private final ListVariableDescriptor<Solution_> variableDescriptor;
+ private final Object planningValue;
+
+ public ListInitializeMove(ListVariableDescriptor<Solution_> variableDescriptor, Object planningValue) {
+ this.variableDescriptor = variableDescriptor;
+ this.planningValue = planningValue;
+ }
+
+ public Object getInitializedValue() {
+ return planningValue;
+ }
+
+ // ************************************************************************
+ // Worker methods
+ // ************************************************************************
+
+ @Override
+ public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) {
+ return true;
+ }
+
+ @Override
+ protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
+ var variableDescriptorAwareScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector;
+ variableDescriptorAwareScoreDirector.beforeListVariableElementInitialized(variableDescriptor, planningValue); | Does this move do nothing but call a variable listener? |
timefold-solver | github_2023 | java | 573 | TimefoldAI | Christopher-Chianelli | @@ -0,0 +1,126 @@
+package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.LinkedHashSet;
+import java.util.Objects;
+
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
+import ai.timefold.solver.core.api.score.director.ScoreDirector;
+import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
+import ai.timefold.solver.core.impl.heuristic.move.AbstractEasyMove;
+import ai.timefold.solver.core.impl.heuristic.selector.list.SubList;
+import ai.timefold.solver.core.impl.score.director.VariableDescriptorAwareScoreDirector;
+
+/**
+ *
+ * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
+ */
+public class SubListUnassignMove<Solution_> extends AbstractEasyMove<Solution_> {
+
+ private final ListVariableDescriptor<Solution_> variableDescriptor;
+ private final Object sourceEntity;
+ private final int sourceIndex;
+ private final int length;
+
+ private Collection<Object> planningValues;
+
+ public SubListUnassignMove(ListVariableDescriptor<Solution_> variableDescriptor, SubList subList) {
+ this(variableDescriptor, subList.entity(), subList.fromIndex(), subList.length());
+ }
+
+ public SubListUnassignMove(ListVariableDescriptor<Solution_> variableDescriptor, Object sourceEntity, int sourceIndex,
+ int length) {
+ this.variableDescriptor = variableDescriptor;
+ this.sourceEntity = sourceEntity;
+ this.sourceIndex = sourceIndex;
+ this.length = length;
+ }
+
+ public Object getSourceEntity() {
+ return sourceEntity;
+ }
+
+ public int getFromIndex() {
+ return sourceIndex;
+ }
+
+ public int getSubListSize() {
+ return length;
+ }
+
+ public int getToIndex() {
+ return sourceIndex + length;
+ }
+
+ @Override
+ public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) {
+ return true;
+ }
+
+ @Override
+ protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
+ var innerScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector;
+
+ var sourceList = variableDescriptor.getValue(sourceEntity);
+ var subList = sourceList.subList(sourceIndex, sourceIndex + length);
+ planningValues = new ArrayList<>(subList);
+
+ innerScoreDirector.beforeListVariableChanged(variableDescriptor, sourceEntity, sourceIndex, sourceIndex + length); | Is there any ordering requirements for list variable changed and list variable element assigned/unassigned? |
timefold-solver | github_2023 | java | 573 | TimefoldAI | Christopher-Chianelli | @@ -0,0 +1,96 @@
+package ai.timefold.solver.core.impl.domain.valuerange.buildin.composite;
+
+import static ai.timefold.solver.core.impl.testdata.util.PlannerAssert.assertAllElementsOfIterator;
+import static ai.timefold.solver.core.impl.testdata.util.PlannerAssert.assertElementsOfIterator;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+import ai.timefold.solver.core.impl.domain.valuerange.buildin.collection.ListValueRange;
+import ai.timefold.solver.core.impl.testutil.TestRandom;
+
+import org.junit.jupiter.api.Test;
+
+class NullAllowingCountableValueRangeTest {
+
+ @Test
+ void getSize() {
+ assertThat(new NullAllowingCountableValueRange<>(new ListValueRange<>(Arrays.asList(0, 2, 5, 10))).getSize())
+ .isEqualTo(5L);
+ assertThat(new NullAllowingCountableValueRange<>(new ListValueRange<>(Arrays.asList(100, 120, 5, 7, 8))).getSize())
+ .isEqualTo(6L);
+ assertThat(new NullAllowingCountableValueRange<>(new ListValueRange<>(Arrays.asList(-15, 25, 0))).getSize())
+ .isEqualTo(4L);
+ assertThat(new NullAllowingCountableValueRange<>(new ListValueRange<>(Arrays.asList("b", "z", "a"))).getSize())
+ .isEqualTo(4L);
+ assertThat(new NullAllowingCountableValueRange<>(new ListValueRange<>(Collections.emptyList())).getSize())
+ .isEqualTo(1L);
+ }
+
+ @Test
+ void get() {
+ assertThat(new NullAllowingCountableValueRange<>(new ListValueRange<>(Arrays.asList(0, 2, 5, 10))).get(2L).intValue())
+ .isEqualTo(5);
+ assertThat(new NullAllowingCountableValueRange<>(new ListValueRange<>(Arrays.asList(0, 2, 5, 10))).get(4L))
+ .isEqualTo(null);
+ assertThat(new NullAllowingCountableValueRange<>(new ListValueRange<>(Arrays.asList("b", "z", "a", "c", "g", "d")))
+ .get(3L))
+ .isEqualTo("c");
+ assertThat(new NullAllowingCountableValueRange<>(new ListValueRange<>(Arrays.asList("b", "z", "a", "c", "g", "d")))
+ .get(6L))
+ .isEqualTo(null);
+ }
+
+ @Test
+ void contains() {
+ assertThat(new NullAllowingCountableValueRange<>(new ListValueRange<>(Arrays.asList(0, 2, 5, 10))).contains(5))
+ .isTrue();
+ assertThat(new NullAllowingCountableValueRange<>(new ListValueRange<>(Arrays.asList(0, 2, 5, 10))).contains(4))
+ .isFalse();
+ assertThat(new NullAllowingCountableValueRange<>(new ListValueRange<>(Arrays.asList(0, 2, 5, 10))).contains(null))
+ .isTrue();
+ assertThat(new NullAllowingCountableValueRange<>(new ListValueRange<>(Arrays.asList("b", "z", "a"))).contains("a"))
+ .isTrue();
+ assertThat(new NullAllowingCountableValueRange<>(new ListValueRange<>(Arrays.asList("b", "z", "a"))).contains("n"))
+ .isFalse();
+ assertThat(new NullAllowingCountableValueRange<>(new ListValueRange<>(Arrays.asList("b", "z", "a"))).contains(null))
+ .isTrue();
+ }
+
+ @Test
+ void createOriginalIterator() {
+ assertAllElementsOfIterator(
+ new NullAllowingCountableValueRange<>(new ListValueRange<>(Arrays.asList(0, 2, 5, 10)))
+ .createOriginalIterator(),
+ null, 0, 2, 5, 10);
+ assertAllElementsOfIterator(
+ new NullAllowingCountableValueRange<>(new ListValueRange<>(Arrays.asList(100, 120, 5, 7, 8)))
+ .createOriginalIterator(),
+ null, 100, 120, 5, 7, 8); | So null is returned first in the original iterator, but last when accessed via `get(int index)`? |
timefold-solver | github_2023 | java | 573 | TimefoldAI | Christopher-Chianelli | @@ -12,31 +13,16 @@ class NoChangeMoveTest {
@Test
void isMoveDoable() {
- assertThat(new NoChangeMove<>().isMoveDoable(null)).isTrue();
- }
-
- @Test
- void createUndoMove() {
- assertThat(new NoChangeMove<>().createUndoMove(null))
- .isInstanceOf(NoChangeMove.class);
- }
-
- @Test
- void getPlanningEntities() {
- assertThat(new NoChangeMove<>().getPlanningEntities()).isEmpty();
- }
-
- @Test
- void getPlanningValues() {
- assertThat(new NoChangeMove<>().getPlanningValues()).isEmpty();
+ assertThat(NoChangeMove.getInstance().isMoveDoable(null)).isFalse();
}
@Test
void rebase() {
ScoreDirector<TestdataSolution> destinationScoreDirector = mockRebasingScoreDirector(
TestdataSolution.buildSolutionDescriptor(), new Object[][] {});
- NoChangeMove<TestdataSolution> move = new NoChangeMove<>();
- move.rebase(destinationScoreDirector);
+ NoChangeMove<TestdataSolution> move = NoChangeMove.getInstance();
+ assertThatThrownBy(() -> move.rebase(destinationScoreDirector)) | I am guessing we can support not implementing rebase for NoChangeMove by never making a NoChangeMove doable (whereas before a NoChangeMove was always doable). |
timefold-solver | github_2023 | java | 573 | TimefoldAI | Christopher-Chianelli | @@ -34,8 +36,12 @@ void original() {
var a = TestdataListEntity.createWithValues("A", v2, v1);
var b = TestdataListEntity.createWithValues("B");
var c = TestdataListEntity.createWithValues("C", v3);
+ var solution = new TestdataListSolution();
+ solution.setEntityList(List.of(a, b, c));
+ solution.setValueList(List.of(v1, v2, v3));
var scoreDirector = mockScoreDirector(TestdataListSolution.buildSolutionDescriptor());
+ scoreDirector.setWorkingSolution(solution); | Does the score director mock have side effects (that is, does `setWorkingSolution` do something)? |
timefold-solver | github_2023 | java | 573 | TimefoldAI | Christopher-Chianelli | @@ -121,18 +131,80 @@ void originalWithPinning() {
// Not testing size; filtering selector doesn't and can't report correct size unless iterating over all values.
assertAllCodesOfMoveSelectorWithoutSize(moveSelector,
// Moving 3 from C[0]
- "3 {C[0]->C[0]}", // noop
+ "3 {C[0]->C[0]}", // undoable
"3 {C[0]->C[1]}", // undoable
"3 {C[0]->A[2]}",
"3 {C[0]->A[1]}",
// Moving 1 from A[1]
"1 {A[1]->C[0]}",
"1 {A[1]->C[1]}",
"1 {A[1]->A[2]}", // undoable
- "1 {A[1]->A[1]}" // noop
+ "1 {A[1]->A[1]}" // undoable
);
}
+ @Test
+ void originalAllowsUnassignedValues() {
+ var v1 = new TestdataAllowsUnassignedValuesListValue("1");
+ var v2 = new TestdataAllowsUnassignedValuesListValue("2");
+ var v3 = new TestdataAllowsUnassignedValuesListValue("3");
+ var v4 = new TestdataAllowsUnassignedValuesListValue("4");
+ var a = TestdataAllowsUnassignedValuesListEntity.createWithValues("A", v2, v1);
+ var b = TestdataAllowsUnassignedValuesListEntity.createWithValues("B");
+ var c = TestdataAllowsUnassignedValuesListEntity.createWithValues("C", v3);
+ var solution = new TestdataAllowsUnassignedValuesListSolution();
+ solution.setEntityList(List.of(a, b, c));
+ solution.setValueList(List.of(v1, v2, v3, v4));
+
+ var scoreDirector = mockScoreDirector(TestdataAllowsUnassignedValuesListSolution.buildSolutionDescriptor());
+ scoreDirector.setWorkingSolution(solution);
+
+ var moveSelector = new ListChangeMoveSelector<>(
+ mockEntityIndependentValueSelector(getAllowsUnassignedvaluesListVariableDescriptor(scoreDirector), v3, v1, v4,
+ v2),
+ mockDestinationSelector(
+ new LocationInList(a, 0),
+ new LocationInList(b, 0),
+ new LocationInList(c, 0),
+ new LocationInList(c, 1),
+ new LocationInList(a, 2),
+ new LocationInList(a, 1),
+ ElementLocation.unassigned()),
+ false);
+
+ solvingStarted(moveSelector, scoreDirector);
+
+ assertAllCodesOfMoveSelector(moveSelector,
+ "3 {C[0]->A[0]}", | Add a comment saying "First try all destinations for v3 (which is originally at C[0]), then v1 (originally at A[1]), then v4 (uninitialized), then v2 (originally at A[0]). |
timefold-solver | github_2023 | java | 573 | TimefoldAI | Christopher-Chianelli | @@ -92,23 +105,76 @@ void originalWithPinning() {
// - C [3]
assertAllCodesOfMoveSelectorWithoutSize(moveSelector,
- "3 {C[0]} <-> 3 {C[0]}", // undoable
- "3 {C[0]} <-> 1 {A[1]}",
- "1 {A[1]} <-> 3 {C[0]}", // redundant
- "1 {A[1]} <-> 1 {A[1]}" // undoable
+ "No change", // undoable
+ "v3 {C[0]} <-> v1 {A[1]}",
+ "v1 {A[1]} <-> v3 {C[0]}", // redundant
+ "No change" // undoable
);
}
+ @Test
+ void originalAllowsUnassignedValues() {
+ var v1 = new TestdataAllowsUnassignedValuesListValue("v1");
+ var v2 = new TestdataAllowsUnassignedValuesListValue("v2");
+ var v3 = new TestdataAllowsUnassignedValuesListValue("v3");
+ var v4 = new TestdataAllowsUnassignedValuesListValue("v4");
+ var a = TestdataAllowsUnassignedValuesListEntity.createWithValues("A", v2, v1);
+ var b = TestdataAllowsUnassignedValuesListEntity.createWithValues("B", v3);
+ var solution = new TestdataAllowsUnassignedValuesListSolution();
+ solution.setEntityList(List.of(a, b));
+ solution.setValueList(List.of(v1, v2, v3, v4));
+
+ var scoreDirector = mockScoreDirector(TestdataAllowsUnassignedValuesListSolution.buildSolutionDescriptor());
+ scoreDirector.setWorkingSolution(solution);
+
+ // swap moves do not support uninitialized entities
+ var listVariableDescriptor = getAllowsUnassignedvaluesListVariableDescriptor(scoreDirector);
+ var initializedElements = scoreDirector.getInitializedUnassignedListVariableElements();
+ assertThat(initializedElements)
+ .containsOnly(Map.entry(listVariableDescriptor, Collections.emptySet()));
+ scoreDirector.initializeElements(Map.of(listVariableDescriptor, Set.of(v4)));
+
+ var moveSelector = new ListSwapMoveSelector<>(
+ mockEntityIndependentValueSelector(listVariableDescriptor, v1, v2, v3, v4),
+ mockEntityIndependentValueSelector(listVariableDescriptor, v4, v3, v2, v1),
+ false);
+
+ solvingStarted(moveSelector, scoreDirector);
+
+ assertAllCodesOfMoveSelectorWithoutSize(moveSelector,
+ "v1 {A[1]->null}+v4 {null->A[1]}", | Ditto (explain that the test is checking each swap move from the product of the two value selectors is tested). |
timefold-solver | github_2023 | java | 573 | TimefoldAI | Christopher-Chianelli | @@ -0,0 +1,100 @@
+package ai.timefold.solver.core.impl.solver;
+
+import java.util.stream.IntStream;
+
+import ai.timefold.solver.core.api.solver.SolverFactory;
+import ai.timefold.solver.core.config.constructionheuristic.ConstructionHeuristicPhaseConfig;
+import ai.timefold.solver.core.config.heuristic.selector.move.MoveSelectorConfig;
+import ai.timefold.solver.core.config.heuristic.selector.move.composite.UnionMoveSelectorConfig;
+import ai.timefold.solver.core.config.heuristic.selector.move.generic.ChangeMoveSelectorConfig;
+import ai.timefold.solver.core.config.heuristic.selector.move.generic.SwapMoveSelectorConfig;
+import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.SubListChangeMoveSelectorConfig;
+import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.SubListSwapMoveSelectorConfig;
+import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.kopt.KOptListMoveSelectorConfig;
+import ai.timefold.solver.core.config.localsearch.LocalSearchPhaseConfig;
+import ai.timefold.solver.core.config.localsearch.decider.acceptor.LocalSearchAcceptorConfig;
+import ai.timefold.solver.core.config.localsearch.decider.forager.LocalSearchForagerConfig;
+import ai.timefold.solver.core.config.solver.EnvironmentMode;
+import ai.timefold.solver.core.config.solver.SolverConfig;
+import ai.timefold.solver.core.config.solver.termination.TerminationConfig;
+import ai.timefold.solver.core.impl.testdata.domain.list.allows_unassigned_values.TestdataAllowsUnassignedValuesListEasyScoreCalculator;
+import ai.timefold.solver.core.impl.testdata.domain.list.allows_unassigned_values.TestdataAllowsUnassignedValuesListEntity;
+import ai.timefold.solver.core.impl.testdata.domain.list.allows_unassigned_values.TestdataAllowsUnassignedValuesListSolution;
+import ai.timefold.solver.core.impl.testdata.domain.list.allows_unassigned_values.TestdataAllowsUnassignedValuesListValue;
+
+import org.assertj.core.api.Assertions;
+import org.junit.jupiter.api.parallel.Execution;
+import org.junit.jupiter.api.parallel.ExecutionMode;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+
+@Execution(ExecutionMode.CONCURRENT)
+class AllowsUnassignedValuesListVariableSolverTest {
+
+ @ParameterizedTest
+ @EnumSource
+ void runSolver(ListVariableMoveType moveType) {
+ // Generate solution.
+ var solution = new TestdataAllowsUnassignedValuesListSolution();
+ solution.setEntityList(IntStream.range(0, 5)
+ .mapToObj(i -> new TestdataAllowsUnassignedValuesListEntity("e" + i))
+ .toList());
+ solution.setValueList(IntStream.range(0, 25)
+ .mapToObj(i -> new TestdataAllowsUnassignedValuesListValue("v" + i))
+ .toList());
+
+ // Generate deterministic, fully asserted solver.
+ var solverConfig = new SolverConfig()
+ .withEnvironmentMode(EnvironmentMode.TRACKED_FULL_ASSERT)
+ .withSolutionClass(TestdataAllowsUnassignedValuesListSolution.class)
+ .withEntityClasses(TestdataAllowsUnassignedValuesListEntity.class,
+ TestdataAllowsUnassignedValuesListValue.class)
+ .withEasyScoreCalculatorClass(TestdataAllowsUnassignedValuesListEasyScoreCalculator.class)
+ .withPhases(new ConstructionHeuristicPhaseConfig(),
+ new LocalSearchPhaseConfig()
+ .withAcceptorConfig(new LocalSearchAcceptorConfig()
+ .withMoveTabuSize(7))
+ .withForagerConfig(new LocalSearchForagerConfig()
+ .withAcceptedCountLimit(100))
+ .withTerminationConfig(new TerminationConfig().withStepCountLimit(1000))
+ .withMoveSelectorConfig(new UnionMoveSelectorConfig()
+ .withMoveSelectors(moveType.moveSelectorConfigs)));
+ var solverFactory = SolverFactory.create(solverConfig);
+ var solver = solverFactory.buildSolver();
+
+ // Run solver.
+ var bestSolution = solver.solve(solution);
+ Assertions.assertThat(bestSolution).isNotNull(); | We are only asserting `solve` does not throw an exception? |
timefold-solver | github_2023 | java | 573 | TimefoldAI | Christopher-Chianelli | @@ -109,6 +114,39 @@ void resetGlobalRegistry() {
meterRegistryList.forEach(Metrics.globalRegistry::remove);
}
+ @Test
+ void constructionHeuristicWithAllowsUnassignedValuesListVariable() {
+ var solverConfig = PlannerTestUtils.buildSolverConfig(TestdataAllowsUnassignedValuesListSolution.class,
+ TestdataAllowsUnassignedValuesListEntity.class, TestdataAllowsUnassignedValuesListValue.class)
+ .withEasyScoreCalculatorClass(TestdataAllowsUnassignedValuesListEasyScoreCalculator.class);
+ var phaseConfig = new ConstructionHeuristicPhaseConfig();
+ solverConfig.setPhaseConfigList(Collections.singletonList(phaseConfig));
+ var solverFactory = SolverFactory.<TestdataAllowsUnassignedValuesListSolution> create(solverConfig);
+ var solver = solverFactory.buildSolver();
+
+ var value1 = new TestdataAllowsUnassignedValuesListValue("v1");
+ var value2 = new TestdataAllowsUnassignedValuesListValue("v2");
+ var value3 = new TestdataAllowsUnassignedValuesListValue("v3");
+ var value4 = new TestdataAllowsUnassignedValuesListValue("v4");
+ var entity = new TestdataAllowsUnassignedValuesListEntity("e1");
+ entity.setValueList(Arrays.asList(value1, value2));
+
+ var solution = new TestdataAllowsUnassignedValuesListSolution();
+ solution.setEntityList(List.of(entity));
+ solution.setValueList(Arrays.asList(value1, value2, value3, value4));
+
+ var bestSolution = solver.solve(solution);
+ assertSoftly(softly -> {
+ softly.assertThat(bestSolution.getScore()).isEqualTo(SimpleScore.of(-2)); // Length of the value list. | Nitpick: length of the entity's value list |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.