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 | java | 1,422 | TimefoldAI | zepfred | @@ -0,0 +1,78 @@
+package ai.timefold.solver.core.impl.phase.custom;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.time.Duration;
+import java.util.function.BooleanSupplier;
+
+import ai.timefold.solver.core.api.score.director.ScoreDirector;
+import ai.timefold.solver.core.api.solver.SolverFactory;
+import ai.timefold.solver.core.api.solver.phase.PhaseCommand;
+import ai.timefold.solver.core.config.phase.custom.CustomPhaseConfig;
+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.TestdataConstraintProvider;
+import ai.timefold.solver.core.impl.testdata.domain.TestdataEntity;
+import ai.timefold.solver.core.impl.testdata.domain.TestdataSolution;
+
+import org.jspecify.annotations.NullMarked;
+import org.junit.jupiter.api.Test;
+
+class DefaultCustomPhaseTest {
+
+ private static final Duration RUN_TIME = Duration.ofMillis(10L);
+
+ @Test
+ void solverTermination() {
+ var solverConfig = new SolverConfig()
+ .withTerminationConfig(new TerminationConfig().withSpentLimit(RUN_TIME))
+ .withPhases(
+ new CustomPhaseConfig()
+ .withCustomPhaseCommands(new NeverendingPhaseCommand()))
+ .withSolutionClass(TestdataSolution.class)
+ .withEntityClasses(TestdataEntity.class)
+ .withConstraintProviderClass(TestdataConstraintProvider.class);
+ var solver = SolverFactory.create(solverConfig).buildSolver();
+ var solution = TestdataSolution.generateSolution(2, 2);
+ var duration = measure(() -> solver.solve(solution));
+ assertThat(duration).isGreaterThanOrEqualTo(RUN_TIME);
+ }
+
+ @Test
+ void phaseTermination() {
+ var solverConfig = new SolverConfig()
+ .withPhases(
+ new CustomPhaseConfig()
+ .withTerminationConfig(new TerminationConfig()
+ .withSpentLimit(RUN_TIME))
+ .withCustomPhaseCommands(new NeverendingPhaseCommand()))
+ .withSolutionClass(TestdataSolution.class)
+ .withEntityClasses(TestdataEntity.class)
+ .withConstraintProviderClass(TestdataConstraintProvider.class);
+ var solver = SolverFactory.create(solverConfig).buildSolver();
+ var solution = TestdataSolution.generateSolution(2, 2);
+ var duration = measure(() -> solver.solve(solution));
+ assertThat(duration).isGreaterThanOrEqualTo(RUN_TIME);
+ }
+
+ private static Duration measure(Runnable runnable) {
+ var milliTime = System.currentTimeMillis();
+ runnable.run();
+ return Duration.ofMillis(System.currentTimeMillis() - milliTime);
+ }
+
+ @NullMarked
+ private static final class NeverendingPhaseCommand implements PhaseCommand<TestdataSolution> { | The name implies it never ends. Perhaps we could use a different name, such as `PhaseEndingCheckPhaseCommand` or something similar. |
timefold-solver | github_2023 | others | 1,422 | TimefoldAI | zepfred | @@ -839,37 +839,38 @@ For example, to implement a custom Construction Heuristic without implementing a
[NOTE]
====
-Most of the time, a custom solver phase is not worth the development time investment.
-xref:optimization-algorithms/construction-heuristics.adoc#constructionHeuristics[Construction Heuristics] are configurable,
-`Termination`-aware and support partially initialized solutions too.
+Most of the time, a custom solver phase is not worth the investment of development time.
+xref:optimization-algorithms/construction-heuristics.adoc#constructionHeuristics[Construction Heuristics] are configurable and support partially initialized solutions too.
You can use the xref:using-timefold-solver/benchmarking-and-tweaking.adoc#benchmarker[Benchmarker] to tweak them.
====
-The `CustomPhaseCommand` interface appears as follows:
+The `PhaseCommand` interface appears as follows:
[source,java,options="nowrap"]
----
-public interface CustomPhaseCommand<Solution_> {
- ...
+public interface PhaseCommand<Solution_> {
- void changeWorkingSolution(ScoreDirector<Solution_> scoreDirector);
+ void changeWorkingSolution(ScoreDirector<Solution_> scoreDirector, BooleanSupplier isPhaseTerminated);
}
----
-[WARNING]
-====
-Any change on the planning entities in a `CustomPhaseCommand` must be notified to the ``ScoreDirector``.
-====
+Any change on the planning entities in a `PhaseCommand` must be notified to the ``ScoreDirector``.
-[NOTE]
+Long-running commands may want to periodically check `isPhaseTerminated`
+and return when it returns true. | ```suggestion
and end it when it returns true.
``` |
timefold-solver | github_2023 | others | 1,422 | TimefoldAI | zepfred | @@ -93,6 +93,48 @@ var solverConfig = new SolverConfig()
----
====
+''' | Should we provide a recipe for that? |
timefold-solver | github_2023 | others | 1,422 | TimefoldAI | zepfred | @@ -914,23 +908,6 @@ add the `customProperties` element and use xref:using-timefold-solver/configurat
----
-[#noChangeSolverPhase] | I'm curious. Which rare cases would it be? |
timefold-solver | github_2023 | java | 1,411 | TimefoldAI | zepfred | @@ -316,10 +316,11 @@ public List<String> getWarningList() {
+ " Maybe reduce the parallelBenchmarkCount.");
}
EnvironmentMode environmentMode = plannerBenchmarkResult.getEnvironmentMode();
- if (environmentMode != null && environmentMode.isAsserted()) {
+ if (environmentMode != null && environmentMode.isStepAssertOrMore()) {
+ // Phase assert performance impact is negligible.
warningList.add("The environmentMode (" + environmentMode + ") is asserting."
+ " This decreases performance."
- + " Maybe set the environmentMode to " + EnvironmentMode.REPRODUCIBLE + ".");
+ + " Maybe set the environmentMode to " + EnvironmentMode.PHASE_ASSERT + "."); | Maybe `NO_ASSERT`? |
timefold-solver | github_2023 | java | 1,411 | TimefoldAI | zepfred | @@ -106,22 +130,46 @@ public enum EnvironmentMode {
this.asserted = asserted;
}
+ public boolean isStepAssertOrMore() {
+ return switch (this) {
+ case NON_REPRODUCIBLE, NO_ASSERT, PHASE_ASSERT, STEP_ASSERT, NON_INTRUSIVE_FULL_ASSERT, FULL_ASSERT,
+ TRACKED_FULL_ASSERT ->
+ isAsserted() && this != PHASE_ASSERT;
+ case REPRODUCIBLE -> PHASE_ASSERT.isAsserted(); | Should it be `NO_ASSERT.isAsserted()` instead? |
timefold-solver | github_2023 | java | 1,411 | TimefoldAI | zepfred | @@ -106,22 +130,46 @@ public enum EnvironmentMode {
this.asserted = asserted;
}
+ public boolean isStepAssertOrMore() {
+ return switch (this) {
+ case NON_REPRODUCIBLE, NO_ASSERT, PHASE_ASSERT, STEP_ASSERT, NON_INTRUSIVE_FULL_ASSERT, FULL_ASSERT,
+ TRACKED_FULL_ASSERT ->
+ isAsserted() && this != PHASE_ASSERT;
+ case REPRODUCIBLE -> PHASE_ASSERT.isAsserted();
+ case FAST_ASSERT -> STEP_ASSERT.isAsserted();
+ };
+ }
+
public boolean isAsserted() {
return asserted;
}
public boolean isNonIntrusiveFullAsserted() {
- if (!isAsserted()) {
- return false;
- }
- return this != FAST_ASSERT;
+ return switch (this) {
+ case NON_REPRODUCIBLE, NO_ASSERT, PHASE_ASSERT, STEP_ASSERT, NON_INTRUSIVE_FULL_ASSERT, FULL_ASSERT,
+ TRACKED_FULL_ASSERT -> {
+ if (!isStepAssertOrMore()) {
+ yield false;
+ }
+ yield this != STEP_ASSERT;
+ }
+ case REPRODUCIBLE -> PHASE_ASSERT.isNonIntrusiveFullAsserted(); | Same as before |
timefold-solver | github_2023 | java | 1,411 | TimefoldAI | zepfred | @@ -106,22 +130,46 @@ public enum EnvironmentMode {
this.asserted = asserted;
}
+ public boolean isStepAssertOrMore() {
+ return switch (this) {
+ case NON_REPRODUCIBLE, NO_ASSERT, PHASE_ASSERT, STEP_ASSERT, NON_INTRUSIVE_FULL_ASSERT, FULL_ASSERT,
+ TRACKED_FULL_ASSERT ->
+ isAsserted() && this != PHASE_ASSERT;
+ case REPRODUCIBLE -> PHASE_ASSERT.isAsserted();
+ case FAST_ASSERT -> STEP_ASSERT.isAsserted();
+ };
+ }
+
public boolean isAsserted() {
return asserted;
}
public boolean isNonIntrusiveFullAsserted() {
- if (!isAsserted()) {
- return false;
- }
- return this != FAST_ASSERT;
+ return switch (this) {
+ case NON_REPRODUCIBLE, NO_ASSERT, PHASE_ASSERT, STEP_ASSERT, NON_INTRUSIVE_FULL_ASSERT, FULL_ASSERT,
+ TRACKED_FULL_ASSERT -> {
+ if (!isStepAssertOrMore()) {
+ yield false;
+ }
+ yield this != STEP_ASSERT;
+ }
+ case REPRODUCIBLE -> PHASE_ASSERT.isNonIntrusiveFullAsserted();
+ case FAST_ASSERT -> STEP_ASSERT.isNonIntrusiveFullAsserted();
+ };
}
- public boolean isIntrusiveFastAsserted() {
- if (!isAsserted()) {
- return false;
- }
- return this != NON_INTRUSIVE_FULL_ASSERT;
+ public boolean isIntrusiveStepAsserted() {
+ return switch (this) {
+ case NON_REPRODUCIBLE, NO_ASSERT, PHASE_ASSERT, STEP_ASSERT, NON_INTRUSIVE_FULL_ASSERT, FULL_ASSERT,
+ TRACKED_FULL_ASSERT -> {
+ if (!isStepAssertOrMore()) {
+ yield false;
+ }
+ yield this != NON_INTRUSIVE_FULL_ASSERT;
+ }
+ case REPRODUCIBLE -> PHASE_ASSERT.isIntrusiveStepAsserted(); | Same as before |
timefold-solver | github_2023 | java | 1,411 | TimefoldAI | zepfred | @@ -106,22 +130,46 @@ public enum EnvironmentMode {
this.asserted = asserted;
}
+ public boolean isStepAssertOrMore() { | Do we have unit tests for this? |
timefold-solver | github_2023 | java | 1,411 | TimefoldAI | zepfred | @@ -106,22 +130,46 @@ public enum EnvironmentMode {
this.asserted = asserted;
}
+ public boolean isStepAssertOrMore() {
+ return switch (this) {
+ case NON_REPRODUCIBLE, NO_ASSERT, PHASE_ASSERT, STEP_ASSERT, NON_INTRUSIVE_FULL_ASSERT, FULL_ASSERT,
+ TRACKED_FULL_ASSERT ->
+ isAsserted() && this != PHASE_ASSERT;
+ case REPRODUCIBLE -> PHASE_ASSERT.isAsserted();
+ case FAST_ASSERT -> STEP_ASSERT.isAsserted();
+ };
+ }
+
public boolean isAsserted() {
return asserted;
}
public boolean isNonIntrusiveFullAsserted() { | Do we have unit tests for this? |
timefold-solver | github_2023 | java | 1,411 | TimefoldAI | zepfred | @@ -106,22 +130,46 @@ public enum EnvironmentMode {
this.asserted = asserted;
}
+ public boolean isStepAssertOrMore() {
+ return switch (this) {
+ case NON_REPRODUCIBLE, NO_ASSERT, PHASE_ASSERT, STEP_ASSERT, NON_INTRUSIVE_FULL_ASSERT, FULL_ASSERT,
+ TRACKED_FULL_ASSERT ->
+ isAsserted() && this != PHASE_ASSERT;
+ case REPRODUCIBLE -> PHASE_ASSERT.isAsserted();
+ case FAST_ASSERT -> STEP_ASSERT.isAsserted();
+ };
+ }
+
public boolean isAsserted() {
return asserted;
}
public boolean isNonIntrusiveFullAsserted() {
- if (!isAsserted()) {
- return false;
- }
- return this != FAST_ASSERT;
+ return switch (this) {
+ case NON_REPRODUCIBLE, NO_ASSERT, PHASE_ASSERT, STEP_ASSERT, NON_INTRUSIVE_FULL_ASSERT, FULL_ASSERT,
+ TRACKED_FULL_ASSERT -> {
+ if (!isStepAssertOrMore()) {
+ yield false;
+ }
+ yield this != STEP_ASSERT;
+ }
+ case REPRODUCIBLE -> PHASE_ASSERT.isNonIntrusiveFullAsserted();
+ case FAST_ASSERT -> STEP_ASSERT.isNonIntrusiveFullAsserted();
+ };
}
- public boolean isIntrusiveFastAsserted() {
- if (!isAsserted()) {
- return false;
- }
- return this != NON_INTRUSIVE_FULL_ASSERT;
+ public boolean isIntrusiveStepAsserted() { | Do we have unit tests for this? |
timefold-solver | github_2023 | java | 1,411 | TimefoldAI | zepfred | @@ -69,18 +69,10 @@ protected DefaultConstructionHeuristicPhaseBuilder<Solution_> createBuilder(
HeuristicConfigPolicy<Solution_> phaseConfigPolicy, Termination<Solution_> solverTermination, int phaseIndex,
boolean lastInitializingPhase, EntityPlacer<Solution_> entityPlacer) {
var phaseTermination = buildPhaseTermination(phaseConfigPolicy, solverTermination);
- var builder = new DefaultConstructionHeuristicPhaseBuilder<>(phaseIndex, lastInitializingPhase,
+ return new DefaultConstructionHeuristicPhaseBuilder<>(phaseIndex, lastInitializingPhase,
phaseConfigPolicy.getLogIndentation(), phaseTermination, entityPlacer,
- buildDecider(phaseConfigPolicy, phaseTermination));
- var environmentMode = phaseConfigPolicy.getEnvironmentMode();
- if (environmentMode.isNonIntrusiveFullAsserted()) {
- builder.setAssertStepScoreFromScratch(true);
- }
- if (environmentMode.isIntrusiveFastAsserted()) {
- builder.setAssertExpectedStepScore(true);
- builder.setAssertShadowVariablesAreNotStaleAfterStep(true);
- }
- return builder;
+ buildDecider(phaseConfigPolicy, phaseTermination))
+ .enableAssertions(phaseConfigPolicy.getEnvironmentMode()); | Nice! |
timefold-solver | github_2023 | java | 1,411 | TimefoldAI | zepfred | @@ -106,22 +130,46 @@ public enum EnvironmentMode {
this.asserted = asserted;
}
+ public boolean isStepAssertOrMore() {
+ return switch (this) {
+ case NON_REPRODUCIBLE, NO_ASSERT, PHASE_ASSERT, STEP_ASSERT, NON_INTRUSIVE_FULL_ASSERT, FULL_ASSERT,
+ TRACKED_FULL_ASSERT ->
+ isAsserted() && this != PHASE_ASSERT;
+ case REPRODUCIBLE -> PHASE_ASSERT.isAsserted();
+ case FAST_ASSERT -> STEP_ASSERT.isAsserted();
+ };
+ }
+
public boolean isAsserted() {
return asserted;
}
public boolean isNonIntrusiveFullAsserted() {
- if (!isAsserted()) {
- return false;
- }
- return this != FAST_ASSERT;
+ return switch (this) {
+ case NON_REPRODUCIBLE, NO_ASSERT, PHASE_ASSERT, STEP_ASSERT, NON_INTRUSIVE_FULL_ASSERT, FULL_ASSERT,
+ TRACKED_FULL_ASSERT -> {
+ if (!isStepAssertOrMore()) {
+ yield false;
+ }
+ yield this != STEP_ASSERT; | Do we want to check if it is equal to `NON_INTRUSIVE_FULL_ASSERT`? |
timefold-solver | github_2023 | java | 1,411 | TimefoldAI | zepfred | @@ -106,22 +130,46 @@ public enum EnvironmentMode {
this.asserted = asserted;
}
+ public boolean isStepAssertOrMore() {
+ return switch (this) {
+ case NON_REPRODUCIBLE, NO_ASSERT, PHASE_ASSERT, STEP_ASSERT, NON_INTRUSIVE_FULL_ASSERT, FULL_ASSERT,
+ TRACKED_FULL_ASSERT ->
+ isAsserted() && this != PHASE_ASSERT;
+ case REPRODUCIBLE -> PHASE_ASSERT.isAsserted();
+ case FAST_ASSERT -> STEP_ASSERT.isAsserted();
+ };
+ }
+
public boolean isAsserted() {
return asserted;
}
public boolean isNonIntrusiveFullAsserted() {
- if (!isAsserted()) {
- return false;
- }
- return this != FAST_ASSERT;
+ return switch (this) {
+ case NON_REPRODUCIBLE, NO_ASSERT, PHASE_ASSERT, STEP_ASSERT, NON_INTRUSIVE_FULL_ASSERT, FULL_ASSERT,
+ TRACKED_FULL_ASSERT -> {
+ if (!isStepAssertOrMore()) {
+ yield false;
+ }
+ yield this != STEP_ASSERT;
+ }
+ case REPRODUCIBLE -> PHASE_ASSERT.isNonIntrusiveFullAsserted();
+ case FAST_ASSERT -> STEP_ASSERT.isNonIntrusiveFullAsserted();
+ };
}
- public boolean isIntrusiveFastAsserted() {
- if (!isAsserted()) {
- return false;
- }
- return this != NON_INTRUSIVE_FULL_ASSERT;
+ public boolean isIntrusiveStepAsserted() {
+ return switch (this) {
+ case NON_REPRODUCIBLE, NO_ASSERT, PHASE_ASSERT, STEP_ASSERT, NON_INTRUSIVE_FULL_ASSERT, FULL_ASSERT,
+ TRACKED_FULL_ASSERT -> {
+ if (!isStepAssertOrMore()) {
+ yield false;
+ }
+ yield this != NON_INTRUSIVE_FULL_ASSERT; | ```suggestion
yield this != STEP_ASSERT && this != NON_INTRUSIVE_FULL_ASSERT;
``` |
timefold-solver | github_2023 | java | 1,411 | TimefoldAI | zepfred | @@ -557,38 +559,37 @@ public void afterProblemFactRemoved(Object problemFact) {
public void assertExpectedWorkingScore(Score_ expectedWorkingScore, Object completedAction) {
Score_ workingScore = calculateScore();
if (!expectedWorkingScore.equals(workingScore)) {
- throw new IllegalStateException(
- "Score corruption (" + expectedWorkingScore.subtract(workingScore).toShortString()
- + "): the expectedWorkingScore (" + expectedWorkingScore
- + ") is not the workingScore (" + workingScore
- + ") after completedAction (" + completedAction + ").");
+ throw new ScoreCorruptionException("""
+ Score corruption (%s): the expectedWorkingScore (%s) is not the workingScore (%s) \
+ after completedAction (%s)."""
+ .formatted(expectedWorkingScore.subtract(workingScore).toShortString(),
+ expectedWorkingScore, workingScore, completedAction));
}
}
@Override
public void assertShadowVariablesAreNotStale(Score_ expectedWorkingScore, Object completedAction) {
String violationMessage = variableListenerSupport.createShadowVariablesViolationMessage();
if (violationMessage != null) {
- throw new IllegalStateException(
- VariableListener.class.getSimpleName() + " corruption after completedAction ("
- + completedAction + "):\n"
- + violationMessage);
+ throw new VariableCorruptionException("""
+ %s corruption after completedAction (%s):
+ %s"""
+ .formatted(VariableListener.class.getSimpleName(), completedAction, violationMessage));
}
Score_ workingScore = calculateScore();
if (!expectedWorkingScore.equals(workingScore)) {
assertWorkingScoreFromScratch(workingScore,
"assertShadowVariablesAreNotStale(" + expectedWorkingScore + ", " + completedAction + ")");
- throw new IllegalStateException("Impossible " + VariableListener.class.getSimpleName() + " corruption ("
- + expectedWorkingScore.subtract(workingScore).toShortString() + "):"
- + " the expectedWorkingScore (" + expectedWorkingScore
- + ") is not the workingScore (" + workingScore
- + ") after all " + VariableListener.class.getSimpleName()
- + "s were triggered without changes to the genuine variables"
- + " after completedAction (" + completedAction + ").\n"
- + "But all the shadow variable values are still the same, so this is impossible.\n"
- + "Maybe run with " + EnvironmentMode.TRACKED_FULL_ASSERT
- + " if you aren't already, to fail earlier.");
+ throw new VariableCorruptionException("""
+ Impossible %s corruption (%s): the expectedWorkingScore (%s) is not the workingScore (%s) \
+ after all %ss were triggered without changes to the genuine variables after completedAction (%s). | ```suggestion
after all %s were triggered without changes to the genuine variables after completedAction (%s).
``` |
timefold-solver | github_2023 | java | 1,411 | TimefoldAI | zepfred | @@ -178,7 +179,7 @@ private SolutionDescriptor<Solution_> buildSolutionDescriptor() {
solverConfig.getGizmoSolutionClonerMap(),
solverConfig.getEntityClassList());
EnvironmentMode environmentMode = solverConfig.determineEnvironmentMode();
- if (environmentMode.isAsserted()) {
+ if (environmentMode.isStepAssertOrMore()) { | We are not asserting this by default anymore. Is that correct? |
timefold-solver | github_2023 | others | 1,407 | TimefoldAI | TomCools | @@ -269,6 +269,12 @@ public class Lesson {
this.studentGroup = studentGroup;
}
+ public Lesson(String id, String subject, String teacher, String studentGroup, Timeslot timeslot, Room room) { | I would add a comment this constructor is only for tests and make the constructor "package private" (no access modifier). |
timefold-solver | github_2023 | python | 1,037 | TimefoldAI | Christopher-Chianelli | @@ -276,6 +277,23 @@ def apply(self, module_name, globals_map, locals_map, from_list, level):
)
+class InvalidJVMVersionError(Exception):
+ pass
+
+
+def ensure_valid_jvm(runtime=None):
+ if runtime is None:
+ import java.lang.Runtime as runtime
+ try:
+ version = runtime.version().feature()
+ if version < 17:
+ raise InvalidJVMVersionError("""Timefold Solver for Python requires JVM (java) version 17 or later. Your JVM version {0} is not supported. | Use `f` strings:
`f"Timefold Solver for Python requires JVM (java) version 17 or later. Your JVM version {version} is not supported. Maybe use sdkman (https://sdkman.io) to install a more modern version of Java."` |
timefold-solver | github_2023 | python | 1,037 | TimefoldAI | Christopher-Chianelli | @@ -80,20 +80,30 @@ def init(*args, path: list[str] = None, include_timefold_jars: bool = True) -> N
if jpype.isJVMStarted(): # noqa
raise RuntimeError('JVM already started. Maybe call init before timefold.solver.types imports?')
+
if path is None:
include_timefold_jars = True
path = []
if include_timefold_jars:
path = path + extract_timefold_jars()
if len(args) == 0:
- args = [jpype.getDefaultJVMPath()]
+ args = [get_default_jvm_path()]
init(*args, path=path, include_translator_jars=False)
from ai.timefold.solver.python.logging import PythonDelegateAppender
PythonDelegateAppender.setLogEventConsumer(PythonConsumer(forward_logging_events))
update_log_level()
+def get_default_jvm_path(): | Can use `path_supplier=jpype.getDefaultJVMPath` as a parameter to make it unit testable, and do `path_supplier()` in the `try` block. |
timefold-solver | github_2023 | java | 1,039 | TimefoldAI | triceo | @@ -74,6 +78,10 @@ public void stepEnded(CustomStepScope<Solution_> stepScope) {
public void phaseEnded(CustomPhaseScope<Solution_> phaseScope) {
super.phaseEnded(phaseScope);
+ // Only update the best solution if the custom phase first initializes the solution and made any change.
+ if (triggersFirstInitializedSolutionEvent() && !phaseScope.getStartingScore().equals(phaseScope.getBestScore())) { | If the score is improved, shouldn't it _always_ give the better solution?
What would be a situation where the best solution should be ignored?
What happens if the custom phase is in between two local search phases? Is this behavior still correct? |
timefold-solver | github_2023 | others | 1,139 | TimefoldAI | triceo | @@ -118,4 +142,13 @@ jobs:
- name: Publish distribution to PyPI
uses: pypa/gh-action-pypi-publish@release/v1
- if: ${{ github.event.inputs.dryRun == 'false' }}
\ No newline at end of file
+ if: ${{ github.event.inputs.dryRun == 'false' }}
+
+ - name: Put back the 999-SNAPSHOT version on the release branch
+ run: |
+ git checkout -B $RELEASE_BRANCH_NAME
+ mvn -Dfull versions:set -DnewVersion=999-SNAPSHOT
+ sed -i "s/^timefold_solver_python_version.*=.*/timefold_solver_python_version = '999-dev0'/" setup.py
+ find . -name 'pom.xml' | xargs git add
+ git commit -am "build: move back to 999-SNAPSHOT"
+ git push origin $RELEASE_BRANCH_NAME | Does this work? You can't push directly to a .x branch, they're protected.
Also, this can only happen _after_ we published the tag (release), otherwise the tag will point to 999-SNAPSHOT. |
timefold-solver | github_2023 | others | 1,139 | TimefoldAI | triceo | @@ -48,7 +48,7 @@ jobs:
fetch-depth: 0
ref: ${{ github.event.inputs.sourceBranch }}
- - name: Init release branch
+ - name: Delete existing release branch | ```suggestion
- name: Delete release branch (if exists)
``` |
timefold-solver | github_2023 | others | 1,332 | TimefoldAI | triceo | @@ -39,7 +39,7 @@ jobs:
cache: 'maven'
- name: Build and test timefold-solver
- run: mvn -B verify
+ run: mvn -Dfull -B verify | The reason we don't do this is because it makes the jobs considerably longer.
Arguably, we want to do this once, not in every combination. |
timefold-solver | github_2023 | java | 1,395 | TimefoldAI | Christopher-Chianelli | @@ -1111,6 +1111,10 @@ public long getMaximumValueRangeSize(Solution_ solution) {
*/
public double getProblemScale(Solution_ solution) {
long logBase = getMaximumValueRangeSize(solution);
+ if (logBase == 1 && getListVariableDescriptor() != null && getListVariableDescriptor().allowsUnassignedValues()) {
+ // List variable allowing unassigned values must be increased; otherwise, the scale will be zero. | Comment incorrect; scale would be NaN, since `log(1) = 0`; as for what `logBase` actually does, it is the base of the logarithm used in calculations (which is converted back to base 10 after all the calculations are done).
It defaults to the maximum value range size, since for basic planning variables, usually each entity increases the size by `maxValueRangeSize`, and` log_{maxValueRangeSize}(maxValueRangeSize) = 1`, increasing accuracy. It appears there an inconsistency in value range size calculation, since basic variables does add 1 if allow unassigned is true: https://github.com/TimefoldAI/timefold-solver/blob/e8302c2484c531f135508d19e00994a05ae4f265/core/src/main/java/ai/timefold/solver/core/impl/domain/valuerange/descriptor/CompositeValueRangeDescriptor.java#L82 (inconsistency is introduced by this check that is only done for basic but not list: https://github.com/TimefoldAI/timefold-solver/blob/e8302c2484c531f135508d19e00994a05ae4f265/core/src/main/java/ai/timefold/solver/core/impl/domain/variable/descriptor/GenuineVariableDescriptor.java#L77-L80 ) |
timefold-solver | github_2023 | java | 1,395 | TimefoldAI | Christopher-Chianelli | @@ -1110,7 +1110,11 @@ public long getMaximumValueRangeSize(Solution_ solution) {
* @return {@code >= 0}
*/
public double getProblemScale(Solution_ solution) {
- long logBase = getMaximumValueRangeSize(solution);
+ long logBase = Math.max(2, getMaximumValueRangeSize(solution));
+ if (logBase == 1 && getListVariableDescriptor() != null && getListVariableDescriptor().allowsUnassignedValues()) {
+ // List variable allowing unassigned values must be increased; otherwise, the scale will be zero.
+ logBase++;
+ } | This `if` should be removed; it will never trigger (logBase is at least 2).
```suggestion
``` |
timefold-solver | github_2023 | java | 1,320 | TimefoldAI | triceo | @@ -28,4 +40,26 @@ public String getPhaseTypeString() {
return "Ruin & Recreate Construction Heuristics";
}
+ @Override
+ protected void doStep(ConstructionHeuristicStepScope<Solution_> stepScope) {
+ if (elementsToRuinSet != null) {
+ var listVariableDescriptor = stepScope.getPhaseScope().getSolverScope().getSolutionDescriptor()
+ .getListVariableDescriptor();
+ var entity = stepScope.getStep().extractPlanningEntities().iterator().next();
+ if (!elementsToRuinSet.contains(entity)) {
+ // Sometimes, the list of elements to be ruined does not include new destinations select by the CH.
+ // In these cases,
+ // we need to record the element list before making any move changes
+ // so that it can be referenced
+ // to restore the solution to its original state in the inner nodes. | ```suggestion
// Sometimes, the list of elements to be ruined does not include new destinations selected by the CH.
// In these cases, we need to record the element list before making any move changes
// so that it can be referenced to restore the solution to its original state in the inner nodes.
``` |
timefold-solver | github_2023 | java | 1,320 | TimefoldAI | triceo | @@ -24,29 +26,73 @@ public static <Solution_> RuinRecreateConstructionHeuristicPhaseBuilder<Solution
HeuristicConfigPolicy<Solution_> solverConfigPolicy, ConstructionHeuristicPhaseConfig constructionHeuristicConfig) {
var constructionHeuristicPhaseFactory =
new RuinRecreateConstructionHeuristicPhaseFactory<Solution_>(constructionHeuristicConfig);
- return (RuinRecreateConstructionHeuristicPhaseBuilder<Solution_>) constructionHeuristicPhaseFactory.getBuilder(0, false,
+ var builder = (RuinRecreateConstructionHeuristicPhaseBuilder<Solution_>) constructionHeuristicPhaseFactory.getBuilder(0,
+ false,
solverConfigPolicy, TerminationFactory.<Solution_> create(new TerminationConfig())
.buildTermination(solverConfigPolicy));
+ if (solverConfigPolicy.getMoveThreadCount() != null && solverConfigPolicy.getMoveThreadCount() >= 1) {
+ builder.multiThread = true; | `multithreaded` |
timefold-solver | github_2023 | java | 1,320 | TimefoldAI | triceo | @@ -24,29 +26,73 @@ public static <Solution_> RuinRecreateConstructionHeuristicPhaseBuilder<Solution
HeuristicConfigPolicy<Solution_> solverConfigPolicy, ConstructionHeuristicPhaseConfig constructionHeuristicConfig) {
var constructionHeuristicPhaseFactory =
new RuinRecreateConstructionHeuristicPhaseFactory<Solution_>(constructionHeuristicConfig);
- return (RuinRecreateConstructionHeuristicPhaseBuilder<Solution_>) constructionHeuristicPhaseFactory.getBuilder(0, false,
+ var builder = (RuinRecreateConstructionHeuristicPhaseBuilder<Solution_>) constructionHeuristicPhaseFactory.getBuilder(0,
+ false,
solverConfigPolicy, TerminationFactory.<Solution_> create(new TerminationConfig())
.buildTermination(solverConfigPolicy));
+ if (solverConfigPolicy.getMoveThreadCount() != null && solverConfigPolicy.getMoveThreadCount() >= 1) {
+ builder.multiThread = true;
+ }
+ return builder;
}
- private List<Object> elementsToRecreate;
+ private final HeuristicConfigPolicy<Solution_> configPolicy;
+ private final RuinRecreateConstructionHeuristicPhaseFactory<Solution_> constructionHeuristicPhaseFactory;
+ private final Termination<Solution_> phaseTermination;
+
+ Set<Object> elementsToRuin;
+ List<Object> elementsToRecreate;
+ private boolean multiThread = false;
- RuinRecreateConstructionHeuristicPhaseBuilder(Termination<Solution_> phaseTermination,
- EntityPlacer<Solution_> entityPlacer, ConstructionHeuristicDecider<Solution_> decider) {
+ RuinRecreateConstructionHeuristicPhaseBuilder(HeuristicConfigPolicy<Solution_> configPolicy,
+ RuinRecreateConstructionHeuristicPhaseFactory<Solution_> constructionHeuristicPhaseFactory,
+ Termination<Solution_> phaseTermination, EntityPlacer<Solution_> entityPlacer,
+ ConstructionHeuristicDecider<Solution_> decider) {
super(0, false, "", phaseTermination, entityPlacer, decider);
+ this.configPolicy = configPolicy;
+ this.constructionHeuristicPhaseFactory = constructionHeuristicPhaseFactory;
+ this.phaseTermination = phaseTermination;
+ }
+
+ /**
+ * In a multithreaded environment, the builder will be shared among all moves and threads.
+ * Consequently, the list {@code elementsToRecreate} used by {@code getEntityPlacer} or the {@code decider},
+ * will be shared between the main and move threads.
+ * This sharing can lead to race conditions.
+ * The method creates a new copy of the builder and the decider to avoid race conditions.
+ */
+ public RuinRecreateConstructionHeuristicPhaseBuilder<Solution_>
+ ensureThreadSafe(InnerScoreDirector<Solution_, ?> scoreDirector) {
+ if (multiThread && scoreDirector.isDerived()) {
+ return new RuinRecreateConstructionHeuristicPhaseBuilder<>(configPolicy, constructionHeuristicPhaseFactory,
+ phaseTermination, super.getEntityPlacer().copy(),
+ constructionHeuristicPhaseFactory.buildDecider(configPolicy, phaseTermination));
+ }
+ return this;
}
public RuinRecreateConstructionHeuristicPhaseBuilder<Solution_> withElementsToRecreate(List<Object> elements) {
this.elementsToRecreate = elements;
return this;
}
+ public RuinRecreateConstructionHeuristicPhaseBuilder<Solution_> withElementsToRuin(Set<Object> elements) {
+ this.elementsToRuin = elements;
+ return this;
+ }
+
+ public RuinRecreateConstructionHeuristicPhaseBuilder<Solution_> withCopyEntityPlacer(boolean multiThread) { | Shouldn't this be called `withMultithreaded`? |
timefold-solver | github_2023 | java | 1,320 | TimefoldAI | triceo | @@ -143,10 +173,23 @@ public SolutionDescriptor<Solution_> getSolutionDescriptor() {
return delegate.getSolutionDescriptor();
}
+ /**
+ * Returns the score director to which events are delegated.
+ */
public InnerScoreDirector<Solution_, ?> getDelegate() {
return delegate;
} | ```suggestion
public InnerScoreDirector<Solution_, ?> getBacking() {
return backingScoreDirector;
}
``` |
timefold-solver | github_2023 | java | 1,320 | TimefoldAI | triceo | @@ -143,10 +173,23 @@ public SolutionDescriptor<Solution_> getSolutionDescriptor() {
return delegate.getSolutionDescriptor();
}
+ /**
+ * Returns the score director to which events are delegated.
+ */
public InnerScoreDirector<Solution_, ?> getDelegate() {
return delegate;
}
+ /**
+ * The {@code VariableChangeRecordingScoreDirector} score director includes two main tasks:
+ * tracking any variable change and firing events to a delegated score director.
+ * This method returns a copy of the score director
+ * that only tracks variable changes without firing any delegated score director events.
+ */
+ public VariableChangeRecordingScoreDirector<Solution_> getNonDelegating() {
+ return new VariableChangeRecordingScoreDirector<>(delegate, variableChanges, cache, false); | For safety, shouldn't `delegate` be `null` here instead?
That way, you can possibly also avoid the boolean - if the delegate is null, do not delegate. |
timefold-solver | github_2023 | java | 1,320 | TimefoldAI | triceo | @@ -0,0 +1,48 @@
+package ai.timefold.solver.core.impl.heuristic.selector.move.generic;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import ai.timefold.solver.core.config.constructionheuristic.ConstructionHeuristicPhaseConfig;
+import ai.timefold.solver.core.config.score.trend.InitializingScoreTrendLevel;
+import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy;
+import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
+import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend;
+import ai.timefold.solver.core.impl.testdata.domain.TestdataSolution;
+
+import org.junit.jupiter.api.Test;
+
+class RuinRecreateConstructionHeuristicPhaseBuilderTest {
+
+ @Test
+ void buildSingleThread() {
+ var solverConfigPolicy = new HeuristicConfigPolicy.Builder<TestdataSolution>()
+ .withSolutionDescriptor(TestdataSolution.buildSolutionDescriptor())
+ .withInitializingScoreTrend(new InitializingScoreTrend(new InitializingScoreTrendLevel[] {
+ InitializingScoreTrendLevel.ANY, InitializingScoreTrendLevel.ANY, InitializingScoreTrendLevel.ANY }))
+ .build();
+ var constructionHeuristicConfig = mock(ConstructionHeuristicPhaseConfig.class);
+ var builder = RuinRecreateConstructionHeuristicPhaseBuilder.create(solverConfigPolicy, constructionHeuristicConfig);
+ var phase = builder.build();
+ assertThat(phase.getEntityPlacer()).isSameAs(builder.getEntityPlacer());
+ }
+
+ @Test
+ void buildMultiThread() { | ```suggestion
void buildMultiThreaded() {
``` |
timefold-solver | github_2023 | java | 1,320 | TimefoldAI | triceo | @@ -0,0 +1,48 @@
+package ai.timefold.solver.core.impl.heuristic.selector.move.generic;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import ai.timefold.solver.core.config.constructionheuristic.ConstructionHeuristicPhaseConfig;
+import ai.timefold.solver.core.config.score.trend.InitializingScoreTrendLevel;
+import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy;
+import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
+import ai.timefold.solver.core.impl.score.trend.InitializingScoreTrend;
+import ai.timefold.solver.core.impl.testdata.domain.TestdataSolution;
+
+import org.junit.jupiter.api.Test;
+
+class RuinRecreateConstructionHeuristicPhaseBuilderTest {
+
+ @Test
+ void buildSingleThread() { | ```suggestion
void buildSingleThreaded() {
``` |
timefold-solver | github_2023 | java | 1,309 | TimefoldAI | triceo | @@ -203,4 +203,20 @@ public void recordListAssignment(ListVariableDescriptor<Solution_> variableDescr
variableChanges.add(new ListVariableAfterAssignmentAction<>(element, variableDescriptor));
}
}
+
+ /**
+ * Record a before list assigment.
+ * Used when moves with nested phases create a new solution but do not record events before the list changes,
+ * such as ruin and recreate.
+ * The before event must be manually recorded,
+ * or the original list will not be restored during the rollback action.
+ *
+ * @param variableDescriptor never null
+ * @param entity never null
+ * @param list never null and may be empty
+ */
+ public void recordBeforeListVariableChanged(ListVariableDescriptor<Solution_> variableDescriptor, Object entity, | Two questions:
1. If this is `recordBeforeListVariableChanged`, does it mean that `recordListAssignment()` should instead be `recordAfterListVariableChanged`?
2. We typically call the usual before/after methods on the score director, except in this case, where we have a whole new bunch of methods. It is confusing. It looks as if these methods are glued to the recording score director "from the side". They look like they don't belong. I wonder... does the score director need refactoring in order for these methods to fit more naturally? |
timefold-solver | github_2023 | java | 1,309 | TimefoldAI | triceo | @@ -95,6 +95,19 @@ protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector)
}
for (var entry : entityToInsertedValuesMap.entrySet()) {
+ if (!entityToOriginalPositionMap.containsKey(entry.getKey())) {
+ // The entity has not been evaluated while creating the entityToOriginalPositionMap,
+ // meaning it is a new destination entity without a ListVariableBeforeChangeAction
+ // to restore the original elements.
+ // We need to ensure the before action is executed in order to restore the original elements.
+ var beforeActionElementList = new ArrayList<>(listVariableDescriptor.getValue(entry.getKey()));
+ for (var element : entry.getValue()) {
+ var location = listVariableStateSupply.getLocationInList(element).ensureAssigned();
+ beforeActionElementList.set(location.index(), null);
+ }
+ recordingScoreDirector.recordBeforeListVariableChanged(listVariableDescriptor, entry.getKey(),
+ beforeActionElementList.stream().filter(Objects::nonNull).toList()); | This is strange, and probably inefficient.
Why put the null entries into the list, only to remove them later?
Copying the list will be a big perf bottleneck. |
timefold-solver | github_2023 | java | 1,309 | TimefoldAI | triceo | @@ -95,7 +98,32 @@ protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector)
}
for (var entry : entityToInsertedValuesMap.entrySet()) {
- recordingScoreDirector.recordListAssignment(listVariableDescriptor, entry.getKey(), entry.getValue());
+ if (!entityToOriginalPositionMap.containsKey(entry.getKey())) {
+ // The entity has not been evaluated while creating the entityToOriginalPositionMap,
+ // meaning it is a new destination entity without a ListVariableBeforeChangeAction
+ // to restore the original elements.
+ // We need to ensure the before action is executed in order to restore the original elements.
+ var beforeActionElementList =
+ constructionHeuristicPhase.getMissingUpdatedElementsMap().get(entry.getKey());
+ recordingScoreDirector | I'm wondering if this recorder type isn't overkill. Effectively what you need to do is:
- Have before/after events that are delegated to the underlying score director.
- Have before/after events that are not delegated.
So why not create duplicates of the before/after methods, which clearly say they will not be delegated? That way, the complexity of the recorder and of the custom action can be removed. At least externally. You can still keep them internally, if you need them.
Alternatively, you can do something like
recordingScoreDirector.undelegated(scoreDirector -> ...);
And hide all of the undelegated operations inside this one lambda. That way, it is very clear what is and what is not delegated, and you still avoid the (external) complexity of the recorder and the custom action. (Both can remain internally, if that makes it easier to implement the functionality.) |
timefold-solver | github_2023 | java | 1,258 | TimefoldAI | triceo | @@ -341,4 +344,36 @@ void constructionHeuristicAllocateToValueFromQueue() {
assertThat(solution.getScore().isSolutionInitialized()).isTrue();
}
+ @Test
+ void constructionHeuristicWithDifficultyWeight() {
+ // Default configuration
+ var solverConfig = PlannerTestUtils.buildSolverConfig(TestdataDifficultyWeightSolution.class,
+ TestdataDifficultyWeightEntity.class);
+ solverConfig.setPhaseConfigList(null);
+ var solution = new TestdataDifficultyWeightSolution("s1");
+ solution.setValueList(
+ List.of(new TestdataDifficultyWeightValue("v1"),
+ new TestdataDifficultyWeightValue("v2")));
+ solution.setEntityList(List.of(new TestdataDifficultyWeightEntity("e1")));
+ solution = PlannerTestUtils.solve(solverConfig, solution);
+ assertThat(solution).isNotNull();
+ assertThat(solution.getEntityList().stream().allMatch(TestdataDifficultyWeightEntity::isComparisonCalled))
+ .isTrue();
+
+ // Custom phase configuration
+ solverConfig = PlannerTestUtils.buildSolverConfig(TestdataDifficultyWeightSolution.class,
+ TestdataDifficultyWeightEntity.class)
+ .withPhases(new ConstructionHeuristicPhaseConfig());
+
+ solution = new TestdataDifficultyWeightSolution("s1");
+ solution.setValueList(
+ List.of(new TestdataDifficultyWeightValue("v1"),
+ new TestdataDifficultyWeightValue("v2")));
+ solution.setEntityList(List.of(new TestdataDifficultyWeightEntity("e1")));
+ solution = PlannerTestUtils.solve(solverConfig, solution); | I'll be honest - I don't like this. We can't be testing everything by running the solver. It takes too much time, and the tests get bloated.
I'd verify that this was detected on the Entity Descriptor, and that's that. |
timefold-solver | github_2023 | java | 1,258 | TimefoldAI | triceo | @@ -0,0 +1,61 @@
+package ai.timefold.solver.core.impl.testdata.domain.difficultyweight;
+
+import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
+import ai.timefold.solver.core.api.domain.variable.PlanningVariable;
+import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
+import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
+import ai.timefold.solver.core.impl.testdata.domain.TestdataObject;
+
+@PlanningEntity(difficultyWeightFactoryClass = TestdataDifficultyWeightFactory.class)
+public class TestdataDifficultyWeightEntity extends TestdataObject {
+
+ public static final String VALUE_FIELD = "value";
+ private boolean comparisonCalled = false; | This is no longer necessary, some methods possibly too. Please simplify. |
timefold-solver | github_2023 | others | 1,236 | TimefoldAI | triceo | @@ -307,7 +307,7 @@ jobs:
sed -i "s/\${maven\.compiler\.release}/$(find build/build-parent/ -name pom.xml -exec grep '<maven.compiler.release>' {} \;|tail -n 1|cut -d\> -f1 --complement|cut -d\< -f1)/g" docs/src/antora.yml
sed -i "s/\${maven\.min\.version}/$(find build/build-parent/ -name pom.xml -exec grep '<maven.min.version>' {} \;|tail -n 1|cut -d\> -f1 --complement|cut -d\< -f1)/g" docs/src/antora.yml
sed -i "s/\${version\.io\.quarkus}/$(find build/build-parent/ -name pom.xml -exec grep '<maven.min.version>' {} \;|tail -n 1|cut -d\> -f1 --complement|cut -d\< -f1)/g" docs/src/antora.yml
- sed -i "s/\${version\.org\.springframework\.boot}/$(find build/build-parent/ -name pom.xml -exec grep '<version.ch.qos.logback>' {} \;|tail -n 1|cut -d\> -f1 --complement|cut -d\< -f1)N/g" docs/src/antora.yml
+ sed -i "s/\${version\.org\.springframework\.boot}/$(find build/build-parent/ -name pom.xml -exec grep '<version.ch.qos.logback>' {} \;|tail -n 1|cut -d\> -f1 --complement|cut -d\< -f1)/g" docs/src/antora.yml | Shouldn't this be:
```suggestion
sed -i "s/\${version\.org\.springframework\.boot}/$(find build/build-parent/ -name pom.xml -exec grep '<version.org.springframework.boot>' {} \;|tail -n 1|cut -d\> -f1 --complement|cut -d\< -f1)/g" docs/src/antora.yml
``` |
timefold-solver | github_2023 | others | 1,236 | TimefoldAI | triceo | @@ -307,7 +307,7 @@ jobs:
sed -i "s/\${maven\.compiler\.release}/$(find build/build-parent/ -name pom.xml -exec grep '<maven.compiler.release>' {} \;|tail -n 1|cut -d\> -f1 --complement|cut -d\< -f1)/g" docs/src/antora.yml
sed -i "s/\${maven\.min\.version}/$(find build/build-parent/ -name pom.xml -exec grep '<maven.min.version>' {} \;|tail -n 1|cut -d\> -f1 --complement|cut -d\< -f1)/g" docs/src/antora.yml
sed -i "s/\${version\.io\.quarkus}/$(find build/build-parent/ -name pom.xml -exec grep '<maven.min.version>' {} \;|tail -n 1|cut -d\> -f1 --complement|cut -d\< -f1)/g" docs/src/antora.yml | Also, I think this needs a fix as well. It reads the Maven version, not the Quarkus version. |
timefold-solver | github_2023 | others | 1,232 | TimefoldAI | triceo | @@ -287,13 +281,60 @@ jobs:
node-version-file: .nvmrc
cache: npm
+ - name: Checkout timefold-solver
+ uses: actions/checkout@v4
+ with:
+ repository: "${{ github.event.pull_request.head.repo.owner.login || 'TimefoldAI' }}/timefold-solver"
+ ref: ${{ github.event.pull_request.head.sha || 'main' }} # The GHA event will pull the main branch by default, and we must specify the PR reference version
+ path: "./timefold-solver"
+ fetch-depth: 0
+
+ - name: Install yq
+ run: |
+ sudo wget https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64 -O /usr/bin/yq
+ sudo chmod +x /usr/bin/yq
+
+ - name: Configuring Antora version
+ working-directory: "./timefold-solver"
+ run: |
+ LATEST_VERSION="SNAPSHOT"
+ echo "LATEST_VERSION=$LATEST_VERSION" >> "$GITHUB_ENV" | I'm thinking maybe we do the `sed` right here, instead of first sending the information to env and then reading it from there?
It's a lot of boilerplate already, and I don't think the extra script makes it easier to read or maintain. |
timefold-solver | github_2023 | others | 1,140 | TimefoldAI | triceo | @@ -259,6 +259,53 @@ jobs:
env:
PIP_FIND_LINKS: ${{ github.workspace }}/timefold-solver/dist
run: tox
+
+ build_documentation:
+ runs-on: ubuntu-latest
+ needs: approval_required
+ env:
+ BRANCH_NAME: ${{ github.head_ref || github.ref_name }}
+ steps:
+ - name: Checkout frontend
+ id: checkout-frontend
+ uses: actions/checkout@v4
+ with:
+ repository: TimefoldAI/frontend
+ token: ${{ secrets.JRELEASER_GITHUB_TOKEN }} # Safe; only used to clone the repo and not stored in the fork.
+ fetch-depth: 0 # Otherwise merge will fail on account of not having history.
+
+ - name: Checkout timefold-solver
+ uses: actions/checkout@v4
+ with:
+ path: ./timefold-solver
+
+ - name: Set up NodeJs
+ uses: actions/setup-node@v4
+ with:
+ node-version-file: .nvmrc
+ cache: npm
+
+ - name: Build Documentation
+ env:
+ GIT_CREDENTIALS: ${{ secrets.GIT_CREDENTIALS }}
+ run: |
+ cp ${{ github.workspace }}/timefold-solver/docs/src/antora-playbook-template.yml apps/docs/antora-playbook.yml
+ sed -i "s/REPLACEME/$BRANCH_NAME/" apps/docs/antora-playbook.yml
+ cat apps/docs/antora-playbook.yml
+ npm ci
+ npm run build -- --filter docs
+
+ - name: Deploy Documentation (Preview Mode)
+ if: ${{ github.ref != 'refs/heads/main' }}
+ id: deploy
+ uses: cloudflare/wrangler-action@v3
+ with:
+ apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
+ accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
+ workingDirectory: ./apps/docs
+ # command: pages deploy ./public-serve --project-name=timefold-docs --branch=${{ github.ref }} | No deploy? |
timefold-solver | github_2023 | others | 1,140 | TimefoldAI | pieterdeschepper | @@ -259,6 +259,61 @@ jobs:
env:
PIP_FIND_LINKS: ${{ github.workspace }}/timefold-solver/dist
run: tox
+
+ build_documentation:
+ runs-on: ubuntu-latest
+ needs: approval_required
+ name: Build Documentation
+ env:
+ BRANCH_NAME: ${{ github.head_ref || github.ref_name }}
+ steps:
+ - name: Checkout frontend
+ id: checkout-frontend
+ uses: actions/checkout@v4
+ with:
+ repository: TimefoldAI/frontend
+ token: ${{ secrets.JRELEASER_GITHUB_TOKEN }} # Safe; only used to clone the repo and not stored in the fork.
+ fetch-depth: 0 # Otherwise merge will fail on account of not having history.
+
+ - name: Checkout timefold-solver
+ uses: actions/checkout@v4
+ with:
+ path: ./timefold-solver
+
+ - name: Set up NodeJs
+ uses: actions/setup-node@v4
+ with:
+ node-version-file: .nvmrc
+ cache: npm
+
+ - name: Build Documentation
+ env:
+ GIT_CREDENTIALS: ${{ secrets.GIT_CREDENTIALS }}
+ run: |
+ cd ${{ github.workspace }}/timefold-solver/
+ GURL="$(git remote get-url origin)"
+ cd -
+ sed -i '/algolia/,+1d' apps/docs/antora-playbook.yml
+ sed -i '/timefold-orbit/,+3d' apps/docs/antora-playbook.yml
+ sed -i '/timefold-field/,+3d' apps/docs/antora-playbook.yml
+ sed -i '/timefold-models/,+3d' apps/docs/antora-playbook.yml
+ sed -i '/timefold-employee/,+3d' apps/docs/antora-playbook.yml
+ sed -i '/tags/,1d' apps/docs/antora-playbook.yml
+ sed -i "s#git@github.com:timefoldai/timefold-solver.git#$GURL#g" apps/docs/antora-playbook.yml
+ sed -i "s/branches:[ .-~]*/branches: $BRANCH_NAME/" apps/docs/antora-playbook.yml | Instead of all these `sed` replaces, I'd prefer something like the below for a couple of reasons:
- It's independent of any changes made to the original file (right now, making changes in the sources of the original file, might break your sed-replace
- It doesn't give any insights into our private repo / setup
The following code just clears out the whole `sources` section and only puts the relevant solver source in there:
```awk -vGURL="${GURL}" -vBRANCH_NAME="${BRANCH_NAME}" 'BEGIN{ print_flag=1 }
{
if( $0 ~ / sources:/ )
{
print " sources:"
print " - url: ", GURL
print " branches: [",BRANCH_NAME,"]"
print " start_path: docs/src"
print_flag=0;
next
}
if( $0 ~ /^$/ )
{
print_flag=1;
}
if ( print_flag == 1 )
print $0
} ' antora-playbook.yml |
timefold-solver | github_2023 | others | 1,394 | TimefoldAI | triceo | @@ -13,10 +13,11 @@ You are allowed to use Timefold Solver Enterprise Edition for evaluation and dev
Please contact https://timefold.ai/contact[contact Timefold]
to obtain the credentials necessary to start your evaluation.
+TIP: All our https://docs.timefold.ai/field-service-routing/latest/introduction[pre-built PlanningAI models] are backed by the Timefold Solver Enterprise Edition at no extra cost. | Does the "TIP" actually highlight in AsciiDoc?
I think you have to jump through some hoops. |
timefold-solver | github_2023 | others | 1,394 | TimefoldAI | triceo | @@ -14,6 +14,13 @@ that offers xref:enterprise-edition/enterprise-edition.adoc#enterpriseEditionFea
to scale out to very large datasets.
To find out more, see xref:enterprise-edition/enterprise-edition.adoc[Enterprise Edition section] of this documentation.
+== Does Timefold offer pre-built models to speed up development?
+
+Timefold offers a suite of pre-built PlanningAI models designed to expedite development by addressing complex scheduling and routing challenges across various industries.
+These models are built upon Timefold Enterprise Solver technology and are accessible through a REST API, facilitating seamless integration into your applications. | Throughout the docs, we say "Timefold Solver Enterprise Edition". It's a mouthful, I know - but I guess consistency wins? |
timefold-solver | github_2023 | others | 1,394 | TimefoldAI | triceo | @@ -14,6 +14,13 @@ that offers xref:enterprise-edition/enterprise-edition.adoc#enterpriseEditionFea
to scale out to very large datasets.
To find out more, see xref:enterprise-edition/enterprise-edition.adoc[Enterprise Edition section] of this documentation.
+== Does Timefold offer pre-built models to speed up development?
+
+Timefold offers a suite of pre-built PlanningAI models designed to expedite development by addressing complex scheduling and routing challenges across various industries.
+These models are built upon Timefold Enterprise Solver technology and are accessible through a REST API, facilitating seamless integration into your applications.
+
+You can find the available models at: https://docs.timefold.ai/ | I'd rephrase to something like "See all available models at ...", which will let you hide the link there. |
timefold-solver | github_2023 | others | 1,394 | TimefoldAI | triceo | @@ -10,7 +10,13 @@
Every organization faces planning problems: providing products or services with a limited set of _constrained_ resources (employees, assets, time, and money).
Timefold Solver’s xref:planning-ai-concepts.adoc[PlanningAI] optimizes these problems to do more business with fewer resources using Constraint Satisfaction Programming.
-> Want to dive right into it? Follow our xref:quickstart/overview.adoc[Quickstart Example] to tackle your first planning problem in minutes.
+[TIP]
+====
+This documentation provides guidance on using our open-source solver to build custom models from scratch.
+For common planning problems, we also offer ready-made models that can be seamlessly integrated via our REST API.
+
+Explore our documentation and available models here: https://docs.timefold.ai/ | Sometimes you just leave the URL, just like here.
Other times, it seems you actually describe it, as below.
Is this intentional? |
timefold-solver | github_2023 | others | 1,394 | TimefoldAI | triceo | @@ -23,6 +26,9 @@ Pick one that aligns with your requirements:
All three quick starts use Timefold Solver to optimize a school timetable for student and teachers:
+IMPORTANT: The https://github.com/TimefoldAI/timefold-quickstarts[timefold-quickstarts] repository
+contains the source code for all these guides and more. | Won't highlight. |
timefold-solver | github_2023 | others | 1,394 | TimefoldAI | triceo | @@ -15,6 +15,8 @@ include::../../_attributes.adoc[]
This guide walks you through the process of creating a Vehicle Routing application
with https://quarkus.io/[Quarkus] and https://timefold.ai[Timefold]'s constraint solving Artificial Intelligence (AI).
+TIP: https://docs.timefold.ai/field-service-routing/latest/introduction[Check out our off-the-shelf model for Field Service Routing] (REST API) | Dtto. |
timefold-solver | github_2023 | others | 1,394 | TimefoldAI | triceo | @@ -5,6 +5,14 @@
:sectnums:
:icons: font
+[TIP]
+====
+While we've simplified model creation with our constraint solver, it can still be complex and time-consuming.
+If rapid deployment is crucial, consider our pre-built models.
+Designed to tackle common optimization challenges, they integrate seamlessly through our REST API, enabling faster time-to-market.
+
+Explore our available models here: http://docs.timefold.ai. | Another instance. |
timefold-solver | github_2023 | others | 1,394 | TimefoldAI | lee-carlon | @@ -14,6 +14,13 @@ that offers xref:enterprise-edition/enterprise-edition.adoc#enterpriseEditionFea
to scale out to very large datasets.
To find out more, see xref:enterprise-edition/enterprise-edition.adoc[Enterprise Edition section] of this documentation.
+== Does Timefold offer pre-built models to speed up development? | PP: I'm not a fan of rhetorical questions in docs.
Perhaps: Timefold's pre-built models speed up development. |
timefold-solver | github_2023 | others | 1,394 | TimefoldAI | lee-carlon | @@ -6,8 +6,11 @@
overview-quickstarts.adoc
:imagesdir: ../..
-IMPORTANT: The https://github.com/TimefoldAI/timefold-quickstarts[timefold-quickstarts] repository
-contains the source code for all these guides and more.
+[TIP]
+====
+This documentation covers our Open Source solver and is meant in case you want to build a model from scratch. | ```suggestion
This documentation covers our Open Source solver to build a model from scratch.
``` |
timefold-solver | github_2023 | others | 1,372 | TimefoldAI | Christopher-Chianelli | @@ -1316,13 +1317,12 @@ Python::
[source,python,options="nowrap"]
----
def do_not_over_assign_equipment(factory: ConstraintFactory) -> Constraint:
- return (factory.for_each(Equipment)
- .join(Job, Joiners.equal(lambda equipment: equipment.id, lambda job: job.required_equipment_id))
- .group_by(lambda equipment, job: equipment,
- ConstraintCollectors.to_connected_ranges(lambda equipment, job: job,
- lambda job: job.start,
- lambda job: job.end,
- lambda a, b: b - a))
+ return (factory.for_each(Job)
+ .group_by(lambda job: job.equipment,
+ ConstraintCollectors.to_connected_temporal_ranges(
+ lambda job: job.startTime,
+ lambda job: job.endTime) | Use snake case for Python names
```suggestion
lambda job: job.start_time,
lambda job: job.end_time)
``` |
timefold-solver | github_2023 | others | 1,372 | TimefoldAI | Christopher-Chianelli | @@ -1260,8 +1259,8 @@ Python::
+
[source,python,options="nowrap"]
----
-.group_by(lambda match, team: team,
- ConstraintCollectors.toConsecutiveSequences(lambda match, team: match.round, lambda match_round: match_round.index))
+.group_by(lambda match,
+ ConstraintCollectors.to_consecutive_sequences(lambda match: match.homeTeam, lambda match: match.roundId)) | ```suggestion
ConstraintCollectors.to_consecutive_sequences(lambda match: match.home_team, lambda match: match.round_id))
``` |
timefold-solver | github_2023 | others | 1,372 | TimefoldAI | Christopher-Chianelli | @@ -1230,10 +1229,8 @@ Python::
----
def multiple_consecutive_home_matches(factory: ConstraintFactory) -> Constraint:
return (factory.for_each(Match)
- .join(Team,
- Joiners.equal(lambda match: match.home_team, lambda team: team))
- .group_by(lambda match, team: team,
- ConstraintCollectors.to_consecutive_sequences(lambda match, team: match.round, lambda match_round: match_round.index))
+ .group_by(lambda match,
+ ConstraintCollectors.to_consecutive_sequences(lambda match: match.homeTeam, lambda match: match.roundId)) | ```suggestion
ConstraintCollectors.to_consecutive_sequences(lambda match: match.home_team, lambda match: match.round_id))
``` |
timefold-solver | github_2023 | others | 1,372 | TimefoldAI | Christopher-Chianelli | @@ -1339,23 +1341,26 @@ Java::
+
[source,java,options="nowrap"]
----
- .groupBy((equipment, job) -> equipment, ConstraintCollectors.toConnectedRanges((equipment, job) -> job,
- Job::getStart,
- Job::getEnd,
- (a, b) -> b - a))
- .flattenLast((ConnectedRangeChain::getConnectedRanges)
- .filter((equipment, connectedRange) -> connectedRange.getMaximumOverlap() > equipment.getCapacity())
+.groupBy(Job::getEquipment,
+ ConstraintCollectors.toConnectedTemporalRanges(
+ Job::getStartTime,
+ Job::getEndTime
+ )
+)
+.flattenLast(ConnectedRangeChain::getConnectedRanges)
+.filter((equipment, connectedRange) -> connectedRange.getMaximumOverlap() > equipment.getCapacity())
----
Python::
+
[source,python,options="nowrap"]
----
-.group_by(lambda equipment, job: equipment,
- ConstraintCollectors.to_connected_ranges(lambda equipment, job: job,
- lambda job: job.start,
- lambda job: job.end,
- lambda a, b: b - a))
+.group_by(lambda job: job.equipment,
+ ConstraintCollectors.to_connected_temporal_ranges(
+ lambda job: job.startTime,
+ lambda job: job.endTime | ```suggestion
lambda job: job.start_time,
lambda job: job.end_time
``` |
timefold-solver | github_2023 | others | 1,372 | TimefoldAI | Christopher-Chianelli | @@ -1371,6 +1376,36 @@ Finally, we use <<constraintStreamsMappingTuples,mapping>> to calculate the viol
For example, if the equipment has a `capacity` of `3`, and the `maximumOverlap` of the `resource` is `5`, then `violationAmount` will be `2`.
If the amount is `0`, then the equipment is not being used over its capacity and we can filter the tuple out.
+In case no temporal data is available, it's still possible to create connected ranges using the `ConstraintCollectors.toConnectedRanges(...)` collector.
+In this case the start and end of a range needs to be provided as well as a function to calculate the difference between the two.
+
+[tabs]
+====
+Java::
++
+[source,java,options="nowrap"]
+----
+.groupBy(Job::getEquipment,
+ ConstraintCollectors.toConnectedRanges(
+ Job::getStart,
+ Job::getEnd,
+ (a, b) -> b - a // difference calculator
+ )
+)
+----
+Python::
++
+[source,python,options="nowrap"]
+----
+.group_by(lambda job: job.equipment,
+ ConstraintCollectors.to_connected_ranges(
+ lambda job: job.start,
+ lambda job: job.end,
+ lambda a, b: b - a) #difference calculator | Inline comments should be seperated by code by at least 2 spaces, and have a space before text.
https://peps.python.org/pep-0008/#inline-comments
```suggestion
lambda a, b: b - a) # Difference calculator
``` |
timefold-solver | github_2023 | java | 1,375 | TimefoldAI | zepfred | @@ -381,22 +383,32 @@ public interface SolverManager<Solution_, ProblemId_> extends AutoCloseable {
@NonNull
SolverStatus getSolverStatus(@NonNull ProblemId_ problemId);
- // TODO Future features
- // void reloadProblem(ProblemId_ problemId, Function<? super ProblemId_, Solution_> problemFinder);
+ /**
+ * As defined by {@link #addProblemChanges(Object, List)}, only with a single {@link ProblemChange}. | Two different interfaces utilize these methods. Perhaps we should create a separate contract for the problem change operations and allow SolverJob and SolverManager to extend it. |
timefold-solver | github_2023 | java | 1,375 | TimefoldAI | zepfred | @@ -158,14 +159,18 @@ private void solvingTerminated() {
}
@Override
- public @NonNull CompletableFuture<Void> addProblemChange(@NonNull ProblemChange<Solution_> problemChange) {
- Objects.requireNonNull(problemChange, () -> "A problem change (%s) must not be null.".formatted(problemId));
- if (solverStatus == SolverStatus.NOT_SOLVING) {
- throw new IllegalStateException("Cannot add the problem change (%s) because the solver job (%s) is not solving."
- .formatted(problemChange, solverStatus));
+ public @NonNull CompletableFuture<Void> addProblemChanges(@NonNull List<ProblemChange<Solution_>> problemChangeList) {
+ Objects.requireNonNull(problemChangeList, () -> "A problem change listfor problem (%s) must not be null." | “listfor” missing space |
timefold-solver | github_2023 | java | 1,370 | TimefoldAI | zepfred | @@ -3,54 +3,104 @@
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
+import java.util.Collections;
import java.util.List;
-import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicReference;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantLock;
import java.util.function.BooleanSupplier;
import ai.timefold.solver.core.api.solver.Solver;
import ai.timefold.solver.core.api.solver.change.ProblemChange;
import org.jspecify.annotations.NonNull;
-
+import org.jspecify.annotations.NullMarked;
+import org.jspecify.annotations.Nullable;
+
+/**
+ * The goal of this class is to register problem changes and best solutions in a thread-safe way.
+ * Problem changes are {@link #addProblemChange(Solver, ProblemChange) put in a queue}
+ * and later associated with the best solution which contains them.
+ * The best solution is associated with a version number
+ * that is incremented each time a {@link #set new best solution is set}.
+ * The best solution is {@link #take() taken} together with all problem changes
+ * that were registered before the best solution was set.
+ *
+ * <p>
+ * This class needs to be thread-safe.
+ * Due to complicated interactions between the solver, solver manager and problem changes,
+ * it is best if we avoid explicit locking here,
+ * reducing cognitive complexity of the whole system.
+ * The core idea being to never modify the same data structure from multiple threads;
+ * instead, we replace the data structure with a new one atomically.
+ * The code contains comments throughout the class that explain the reasoning behind the design.
+ *
+ * @param <Solution_>
+ */
+@NullMarked
final class BestSolutionHolder<Solution_> {
- private final Lock problemChangesLock = new ReentrantLock();
- private final AtomicReference<VersionedBestSolution<Solution_>> versionedBestSolutionRef = new AtomicReference<>();
- private final SortedMap<BigInteger, List<CompletableFuture<Void>>> problemChangesPerVersion =
- new TreeMap<>();
- private BigInteger currentVersion = BigInteger.ZERO;
+ private final AtomicReference<@Nullable VersionedBestSolution<Solution_>> versionedBestSolutionRef =
+ new AtomicReference<>();
+ private final AtomicReference<SortedMap<BigInteger, List<CompletableFuture<Void>>>> problemChangesPerVersionRef =
+ new AtomicReference<>(createNewProblemChangesMap());
+ // The version is BigInteger to avoid long overflow.
+ // The solver can run potentially forever, so long overflow is a (remote) possibility.
+ private final AtomicReference<BigInteger> currentVersion = new AtomicReference<>(BigInteger.ZERO);
+ private final AtomicReference<BigInteger> lastProcessedVersion = new AtomicReference<>(BigInteger.valueOf(-1));
+
+ private static SortedMap<BigInteger, List<CompletableFuture<Void>>> createNewProblemChangesMap() {
+ return createNewProblemChangesMap(Collections.emptySortedMap());
+ }
+
+ private static SortedMap<BigInteger, List<CompletableFuture<Void>>>
+ createNewProblemChangesMap(SortedMap<BigInteger, List<CompletableFuture<Void>>> map) {
+ return new TreeMap<>(map);
+ }
boolean isEmpty() {
return versionedBestSolutionRef.get() == null;
}
/**
- * NOT thread-safe.
- *
* @return the last best solution together with problem changes the solution contains.
+ * If there is no new best solution, returns null.
*/
+ @Nullable
BestSolutionContainingProblemChanges<Solution_> take() {
- VersionedBestSolution<Solution_> versionedBestSolution = versionedBestSolutionRef.getAndSet(null);
+ var versionedBestSolution = versionedBestSolutionRef.getAndSet(null);
if (versionedBestSolution == null) {
return null;
}
- SortedMap<BigInteger, List<CompletableFuture<Void>>> containedProblemChangesPerVersion =
- problemChangesPerVersion.headMap(versionedBestSolution.getVersion().add(BigInteger.ONE));
- List<CompletableFuture<Void>> containedProblemChanges = new ArrayList<>();
- for (Map.Entry<BigInteger, List<CompletableFuture<Void>>> entry : containedProblemChangesPerVersion.entrySet()) {
- containedProblemChanges.addAll(entry.getValue());
- problemChangesPerVersion.remove(entry.getKey());
+ var boundaryVersion = versionedBestSolution.version().add(BigInteger.ONE);
+ if (lastProcessedVersion.getAndSet(boundaryVersion).compareTo(boundaryVersion) >= 0) { | I understand the goal of this block, but I'm uncertain about setting `lastProcessedVersion` here. It seems we identify a more recent change, but we revert it to the earlier version. Should we keep the new version? |
timefold-solver | github_2023 | java | 1,370 | TimefoldAI | zepfred | @@ -3,54 +3,104 @@
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
+import java.util.Collections;
import java.util.List;
-import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicReference;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantLock;
import java.util.function.BooleanSupplier;
import ai.timefold.solver.core.api.solver.Solver;
import ai.timefold.solver.core.api.solver.change.ProblemChange;
import org.jspecify.annotations.NonNull;
-
+import org.jspecify.annotations.NullMarked;
+import org.jspecify.annotations.Nullable;
+
+/**
+ * The goal of this class is to register problem changes and best solutions in a thread-safe way.
+ * Problem changes are {@link #addProblemChange(Solver, ProblemChange) put in a queue}
+ * and later associated with the best solution which contains them.
+ * The best solution is associated with a version number
+ * that is incremented each time a {@link #set new best solution is set}.
+ * The best solution is {@link #take() taken} together with all problem changes
+ * that were registered before the best solution was set.
+ *
+ * <p>
+ * This class needs to be thread-safe.
+ * Due to complicated interactions between the solver, solver manager and problem changes,
+ * it is best if we avoid explicit locking here,
+ * reducing cognitive complexity of the whole system.
+ * The core idea being to never modify the same data structure from multiple threads;
+ * instead, we replace the data structure with a new one atomically.
+ * The code contains comments throughout the class that explain the reasoning behind the design.
+ *
+ * @param <Solution_>
+ */
+@NullMarked
final class BestSolutionHolder<Solution_> {
- private final Lock problemChangesLock = new ReentrantLock();
- private final AtomicReference<VersionedBestSolution<Solution_>> versionedBestSolutionRef = new AtomicReference<>();
- private final SortedMap<BigInteger, List<CompletableFuture<Void>>> problemChangesPerVersion =
- new TreeMap<>();
- private BigInteger currentVersion = BigInteger.ZERO;
+ private final AtomicReference<@Nullable VersionedBestSolution<Solution_>> versionedBestSolutionRef =
+ new AtomicReference<>();
+ private final AtomicReference<SortedMap<BigInteger, List<CompletableFuture<Void>>>> problemChangesPerVersionRef =
+ new AtomicReference<>(createNewProblemChangesMap());
+ // The version is BigInteger to avoid long overflow.
+ // The solver can run potentially forever, so long overflow is a (remote) possibility.
+ private final AtomicReference<BigInteger> currentVersion = new AtomicReference<>(BigInteger.ZERO);
+ private final AtomicReference<BigInteger> lastProcessedVersion = new AtomicReference<>(BigInteger.valueOf(-1));
+
+ private static SortedMap<BigInteger, List<CompletableFuture<Void>>> createNewProblemChangesMap() {
+ return createNewProblemChangesMap(Collections.emptySortedMap());
+ }
+
+ private static SortedMap<BigInteger, List<CompletableFuture<Void>>>
+ createNewProblemChangesMap(SortedMap<BigInteger, List<CompletableFuture<Void>>> map) {
+ return new TreeMap<>(map);
+ }
boolean isEmpty() {
return versionedBestSolutionRef.get() == null;
}
/**
- * NOT thread-safe.
- *
* @return the last best solution together with problem changes the solution contains.
+ * If there is no new best solution, returns null.
*/
+ @Nullable
BestSolutionContainingProblemChanges<Solution_> take() {
- VersionedBestSolution<Solution_> versionedBestSolution = versionedBestSolutionRef.getAndSet(null);
+ var versionedBestSolution = versionedBestSolutionRef.getAndSet(null);
if (versionedBestSolution == null) {
return null;
}
- SortedMap<BigInteger, List<CompletableFuture<Void>>> containedProblemChangesPerVersion =
- problemChangesPerVersion.headMap(versionedBestSolution.getVersion().add(BigInteger.ONE));
- List<CompletableFuture<Void>> containedProblemChanges = new ArrayList<>();
- for (Map.Entry<BigInteger, List<CompletableFuture<Void>>> entry : containedProblemChangesPerVersion.entrySet()) {
- containedProblemChanges.addAll(entry.getValue());
- problemChangesPerVersion.remove(entry.getKey());
+ var boundaryVersion = versionedBestSolution.version().add(BigInteger.ONE);
+ if (lastProcessedVersion.getAndSet(boundaryVersion).compareTo(boundaryVersion) >= 0) {
+ // Corner case: The best solution has already been taken,
+ // because a later take() was scheduled to run before an earlier take().
+ // This causes the later take() to return the latest best solution and all the problem changes,
+ // and the earlier best solution to be skipped entirely.
+ return null;
}
-
- return new BestSolutionContainingProblemChanges<>(versionedBestSolution.getBestSolution(),
- containedProblemChanges);
+ // The map is replaced by a map containing only the problem changes that are not contained in the best solution.
+ // This is done atomically, so no other thread can access the old map anymore.
+ // The old map can then be processed by the current thread without synchronization.
+ // The copying of maps is possibly expensive, but due to the nature of problem changes,
+ // we do not expect the map to ever get too big.
+ // It is not practical to submit a problem change every second, as that gives the solver no time to react.
+ // This limits the size of the map on input.
+ // The solver also finds new best solutions, which regularly trims the size of the map as well.
+ var oldProblemChangesPerVersion =
+ problemChangesPerVersionRef.getAndUpdate(map -> createNewProblemChangesMap(map.tailMap(boundaryVersion)));
+ // At this point, the old map is not accessible to any other thread.
+ // We also do not need to clear it, because this being the only reference,
+ // garbage collector will do it for us.
+ var containedProblemChanges = oldProblemChangesPerVersion.headMap(boundaryVersion)
+ .values()
+ .stream()
+ .flatMap(Collection::stream)
+ .toList();
+ return new BestSolutionContainingProblemChanges<>(versionedBestSolution.bestSolution(), containedProblemChanges); | Maybe we can update `lastProcessedVersion` before returning the changes. |
timefold-solver | github_2023 | java | 1,370 | TimefoldAI | zepfred | @@ -61,77 +113,56 @@ BestSolutionContainingProblemChanges<Solution_> take() {
* @param isEveryProblemChangeProcessed a supplier that tells if all problem changes have been processed
*/
void set(Solution_ bestSolution, BooleanSupplier isEveryProblemChangeProcessed) {
- problemChangesLock.lock();
- try {
- /*
- * The new best solution can be accepted only if there are no pending problem changes nor any additional
- * changes may come during this operation. Otherwise, a race condition might occur that leads to associating
- * problem changes with a solution that was created later, but does not contain them yet.
- * As a result, CompletableFutures representing these changes would be completed too early.
- */
- if (isEveryProblemChangeProcessed.getAsBoolean()) {
- versionedBestSolutionRef.set(new VersionedBestSolution(bestSolution, currentVersion));
- currentVersion = currentVersion.add(BigInteger.ONE);
- }
- } finally {
- problemChangesLock.unlock();
+ /*
+ * The new best solution can be accepted only if there are no pending problem changes
+ * nor any additional changes may come during this operation.
+ * Otherwise, a race condition might occur
+ * that leads to associating problem changes with a solution that was created later,
+ * but does not contain them yet.
+ * As a result, CompletableFutures representing these changes would be completed too early.
+ */
+ if (isEveryProblemChangeProcessed.getAsBoolean()) {
+ // This field is atomic, so we can safely set the new best solution without synchronization.
+ versionedBestSolutionRef.set(
+ new VersionedBestSolution<>(bestSolution, currentVersion.getAndUpdate(old -> old.add(BigInteger.ONE))));
}
}
/**
- * Adds a new problem change to a solver and registers the problem change to be later retrieved together with
- * a relevant best solution by the {@link #take()} method.
+ * Adds a new problem change to a solver and registers the problem change
+ * to be later retrieved together with a relevant best solution by the {@link #take()} method.
*
* @return CompletableFuture that will be completed after the best solution containing this change is passed to
* a user-defined Consumer.
*/
@NonNull
CompletableFuture<Void> addProblemChange(Solver<Solution_> solver, ProblemChange<Solution_> problemChange) {
- problemChangesLock.lock();
- try {
- CompletableFuture<Void> futureProblemChange = new CompletableFuture<>();
- problemChangesPerVersion.compute(currentVersion, (version, futureProblemChangeList) -> {
- if (futureProblemChangeList == null) {
- futureProblemChangeList = new ArrayList<>();
- }
- futureProblemChangeList.add(futureProblemChange);
- return futureProblemChangeList;
- });
+ var futureProblemChange = new CompletableFuture<Void>();
+ synchronized (this) {
+ // This actually needs to be synchronized,
+ // as we want the new problem change and its version to be linked.
+ var futureProblemChangeList =
+ problemChangesPerVersionRef.get().computeIfAbsent(currentVersion.get(), version -> new ArrayList<>());
+ futureProblemChangeList.add(futureProblemChange);
solver.addProblemChange(problemChange);
- return futureProblemChange;
- } finally {
- problemChangesLock.unlock();
}
+ return futureProblemChange;
}
void cancelPendingChanges() {
- problemChangesLock.lock();
- try {
- problemChangesPerVersion.values()
- .stream()
- .flatMap(Collection::stream)
- .forEach(pendingProblemChange -> pendingProblemChange.cancel(false));
- problemChangesPerVersion.clear();
- } finally {
- problemChangesLock.unlock();
- }
+ // The map is an atomic reference.
+ // We first replace the reference with a new map atomically, avoiding synchronization issues.
+ // Then we process the old map, which is safe because no one can access it anymore.
+ // We do not need to clear it, because this being the only reference,
+ // the garbage collector will do it for us.
+ problemChangesPerVersionRef.getAndSet(createNewProblemChangesMap()) | Nice! |
timefold-solver | github_2023 | java | 1,370 | TimefoldAI | rsynek | @@ -2,30 +2,42 @@
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
+import ai.timefold.solver.core.api.domain.variable.VariableListener;
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.api.solver.Solver;
+import ai.timefold.solver.core.api.solver.event.BestSolutionChangedEvent;
+import ai.timefold.solver.core.impl.heuristic.move.Move;
import org.jspecify.annotations.NonNull;
/**
* A ProblemChange represents a change in one or more {@link PlanningEntity planning entities} or problem facts
* of a {@link PlanningSolution}.
* <p>
- * The {@link Solver} checks the presence of waiting problem changes after every
- * {@link ai.timefold.solver.core.impl.heuristic.move.Move} evaluation. If there are waiting problem changes,
- * the {@link Solver}:
+ * The {@link Solver} checks the presence of waiting problem changes after every {@link Move} evaluation.
+ * If there are waiting problem changes, the {@link Solver}:
* <ol>
- * <li>clones the last {@link PlanningSolution best solution} and sets the clone
- * as the new {@link PlanningSolution working solution}</li>
+ * <li>clones the last {@link PlanningSolution best solution}
+ * and sets the clone as the new {@link PlanningSolution working solution}</li>
* <li>applies every problem change keeping the order in which problem changes have been submitted;
- * after every problem change, {@link ai.timefold.solver.core.api.domain.variable.VariableListener variable listeners}
- * are triggered
+ * after every problem change, {@link VariableListener variable listeners} are triggered
* <li>calculates the score and makes the {@link PlanningSolution updated working solution}
- * the new {@link PlanningSolution best solution}; note that this {@link PlanningSolution solution} is not published
- * via the {@link ai.timefold.solver.core.api.solver.event.BestSolutionChangedEvent}, as it hasn't been initialized yet</li>
+ * the new {@link PlanningSolution best solution};
+ * note that this {@link PlanningSolution solution} is not published via the {@link BestSolutionChangedEvent},
+ * as it hasn't been initialized yet</li>
* <li>restarts solving to fill potential uninitialized {@link PlanningEntity planning entities}</li>
* </ol>
* <p>
+ * From the above, it follows that the solver will require some time | Valuable info for users, thanks! |
timefold-solver | github_2023 | java | 1,362 | TimefoldAI | zepfred | @@ -122,4 +138,31 @@ public interface SolverJobBuilder<Solution_, ProblemId_> {
*/
@NonNull
SolverJob<Solution_, ProblemId_> run();
+
+ /**
+ * A consumer that accepts the first initialized solution.
+ *
+ * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
+ */
+ @NullMarked
+ interface FirstInitializedSolutionConsumer<Solution_> {
+
+ /**
+ * Accepts the first solution after initialization.
+ *
+ * @param solution the first solution after initialization phase(s) finished
+ * @param isTerminatedEarly false in most common cases.
+ * True if the solver was terminated early, before the solution could be fully initialized,
+ * typically as a result of construction heuristic running for too long
+ * and tripping a time-based termination condition.
+ * In that case, there will likely be no other phase after this one
+ * and the solver will terminate as well, without launching any optimizing phase.
+ * Therefore the solution captured with {@link SolverJobBuilder#withBestSolutionConsumer(Consumer)} | ```suggestion
* Therefore, the solution captured with {@link SolverJobBuilder#withBestSolutionConsumer(Consumer)}
``` |
timefold-solver | github_2023 | java | 1,362 | TimefoldAI | zepfred | @@ -83,17 +103,24 @@ public void solve(SolverScope<Solution_> solverScope) {
+ ") has selected move count (" + stepScope.getSelectedMoveCount()
+ ") but failed to pick a nextStep (" + stepScope.getStep() + ").");
}
- // Although stepStarted has been called, stepEnded is not called for this step
+ // Although stepStarted has been called, stepEnded is not called for this step.
+ earlyTerminationStatus = TerminationStatus.early(phaseScope.getNextStepIndex());
break;
}
doStep(stepScope);
stepEnded(stepScope);
phaseScope.setLastCompletedStepScope(stepScope);
- if (phaseTermination.isPhaseTerminated(phaseScope)
- || (hasListVariable && stepScope.getStepIndex() >= maxStepCount)) {
+ if (hasListVariable && stepScope.getStepIndex() >= maxStepCount) {
+ earlyTerminationStatus = TerminationStatus.regular(phaseScope.getNextStepIndex());
+ break;
+ } else if (phaseTermination.isPhaseTerminated(phaseScope)) {
+ earlyTerminationStatus = TerminationStatus.early(phaseScope.getNextStepIndex());
break;
}
}
+ // We only store the termination status, which is exposed to the outside, when the phase has ended.
+ terminationStatus =
+ PossiblyInitializingPhase.translateEarlyTermination(phaseScope, earlyTerminationStatus, iterator.hasNext()); | Why are we using a static method? |
timefold-solver | github_2023 | java | 1,362 | TimefoldAI | zepfred | @@ -1,27 +1,48 @@
package ai.timefold.solver.core.impl.phase.custom;
+import java.util.Iterator;
import java.util.List;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.impl.phase.AbstractPhase;
+import ai.timefold.solver.core.impl.phase.PossiblyInitializingPhase;
import ai.timefold.solver.core.impl.phase.custom.scope.CustomPhaseScope;
import ai.timefold.solver.core.impl.phase.custom.scope.CustomStepScope;
+import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import ai.timefold.solver.core.impl.solver.termination.Termination;
+import org.jspecify.annotations.NullMarked;
+
/**
* Default implementation of {@link CustomPhase}.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
*/
-final class DefaultCustomPhase<Solution_> extends AbstractPhase<Solution_> implements CustomPhase<Solution_> {
+@NullMarked
+public final class DefaultCustomPhase<Solution_> | This class shares a logic similar to that of the construction phase. We can consider adding a new abstract phase, `AbstractPossiblyInitializingPhase`, that extends `AbstractPhase` and implements `PossiblyInitializingPhase`. The new class can specify the relevant attributes and implement the related phase events. |
timefold-solver | github_2023 | java | 1,362 | TimefoldAI | zepfred | @@ -32,21 +32,23 @@ public abstract class AbstractPhase<Solution_> implements Phase<Solution_> {
protected final boolean assertStepScoreFromScratch;
protected final boolean assertExpectedStepScore;
protected final boolean assertShadowVariablesAreNotStaleAfterStep;
- protected final boolean triggerFirstInitializedSolutionEvent;
/** Used for {@link #addPhaseLifecycleListener(PhaseLifecycleListener)}. */
protected PhaseLifecycleSupport<Solution_> phaseLifecycleSupport = new PhaseLifecycleSupport<>();
protected AbstractSolver<Solution_> solver;
protected AbstractPhase(Builder<Solution_> builder) {
+ if (builder.isLastInitializingPhase() && !(this instanceof PossiblyInitializingPhase)) { | Adding a new abstract class won't require casting here. |
timefold-solver | github_2023 | others | 1,362 | TimefoldAI | zepfred | @@ -57,6 +57,35 @@ Every upgrade note indicates how likely your code will be affected by that chang
The upgrade recipe often lists the changes as they apply to Java code.
We kindly ask Kotlin and Python users to translate the changes accordingly.
+=== Upgrade from 1.18.0 to 1.19.0 | Why are we not adding a recipe for that? |
timefold-solver | github_2023 | others | 1,362 | TimefoldAI | zepfred | @@ -57,6 +57,35 @@ Every upgrade note indicates how likely your code will be affected by that chang
The upgrade recipe often lists the changes as they apply to Java code.
We kindly ask Kotlin and Python users to translate the changes accordingly.
+=== Upgrade from 1.18.0 to 1.19.0
+
+.icon:info-circle[role=yellow] New argument to `FirstInitializedSolutionConsumer`
+[%collapsible%open]
+====
+`SolverJob` 's `FirstInitializedSolutionConsumer` gets an additional argument | ```suggestion
`SolverJob`'s `FirstInitializedSolutionConsumer` gets an additional argument
``` |
timefold-solver | github_2023 | java | 1,362 | TimefoldAI | zepfred | @@ -0,0 +1,83 @@
+package ai.timefold.solver.core.impl.phase;
+
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
+import ai.timefold.solver.core.impl.constructionheuristic.ConstructionHeuristicPhase;
+import ai.timefold.solver.core.impl.localsearch.LocalSearchPhase;
+import ai.timefold.solver.core.impl.phase.custom.CustomPhase;
+import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
+import ai.timefold.solver.core.impl.solver.termination.Termination;
+
+import org.jspecify.annotations.Nullable;
+import org.slf4j.Logger;
+
+/** | Do we need to duplicate this comment? |
timefold-solver | github_2023 | java | 1,362 | TimefoldAI | zepfred | @@ -0,0 +1,83 @@
+package ai.timefold.solver.core.impl.phase;
+
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
+import ai.timefold.solver.core.impl.constructionheuristic.ConstructionHeuristicPhase;
+import ai.timefold.solver.core.impl.localsearch.LocalSearchPhase;
+import ai.timefold.solver.core.impl.phase.custom.CustomPhase;
+import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
+import ai.timefold.solver.core.impl.solver.termination.Termination;
+
+import org.jspecify.annotations.Nullable;
+import org.slf4j.Logger;
+
+/**
+ * Describes a phase that can be used to initialize a solution.
+ * {@link ConstructionHeuristicPhase} is automatically an initializing phase.
+ * {@link CustomPhase} can be an initializing phase, if it comes before the first {@link LocalSearchPhase}.
+ *
+ * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
+ */
+public abstract class AbstractPossiblyInitializingPhase<Solution_>
+ extends AbstractPhase<Solution_>
+ implements PossiblyInitializingPhase<Solution_> {
+
+ private final boolean lastInitializingPhase;
+
+ protected AbstractPossiblyInitializingPhase(AbstractPossiblyInitializingPhaseBuilder<Solution_> builder) { | There was a validation at `AbstractPhase`:
```
if (builder.isLastInitializingPhase() && !(this instanceof PossiblyInitializingPhase)) {
...
```
Is it no longer necessary? |
timefold-solver | github_2023 | java | 1,343 | TimefoldAI | triceo | @@ -15,7 +15,7 @@ public final class SolverConfigBuildItem extends SimpleBuildItem {
* Constructor for multiple solver configurations.
*/
public SolverConfigBuildItem(Map<String, SolverConfig> solverConfig, GeneratedGizmoClasses generatedGizmoClasses) {
- this.solverConfigurations = solverConfig;
+ this.solverConfigurations = Map.copyOf(solverConfig); | Please add a comment explaining why this is necessary. |
timefold-solver | github_2023 | java | 1,343 | TimefoldAI | triceo | @@ -573,6 +577,43 @@ private SolverConfig loadSolverConfig(IndexView indexView,
return solverConfig;
}
+ @BuildStep
+ void buildConstraintMetaModel(SolverConfigBuildItem solverConfigBuildItem, | This is new code? I don't understand. Didn't we already have support for this, and therefore the code should have been either reused, or moved from elsewhere? |
timefold-solver | github_2023 | java | 1,313 | TimefoldAI | triceo | @@ -0,0 +1,171 @@
+package ai.timefold.solver.core.impl.solver.termination;
+
+import java.util.NavigableMap;
+import java.util.TreeMap;
+
+import ai.timefold.solver.core.api.score.Score;
+import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
+import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope;
+import ai.timefold.solver.core.impl.solver.scope.SolverScope;
+import ai.timefold.solver.core.impl.solver.thread.ChildThreadType;
+
+import org.jspecify.annotations.NonNull;
+import org.jspecify.annotations.Nullable;
+
+public final class AdaptiveTermination<Solution_, Score_ extends Score<Score_>> implements Termination<Solution_> {
+ private final long gracePeriodMillis;
+ private final double minimumImprovementRatio;
+
+ boolean isGracePeriodActive;
+ private long gracePeriodStartTimeMillis;
+ private LevelScoreDiff gracePeriodScoreDiff;
+
+ private final NavigableMap<Long, Score_> scoresByTime;
+
+ public AdaptiveTermination(long gracePeriodMillis, double minimumImprovementRatio) {
+ this.gracePeriodMillis = gracePeriodMillis;
+ this.minimumImprovementRatio = minimumImprovementRatio;
+ this.scoresByTime = new TreeMap<>(); | I was skeptical of this approach, as fast-stepping algorithms will easily put tens of thousands of entries to this map per second, and I was expecting that to be both CPU-intensive and memory-intensive.
However, in the experiments I ran, this did not materialize. Impact of the termination is barely visible in the data. Interesting. |
timefold-solver | github_2023 | java | 1,313 | TimefoldAI | triceo | @@ -0,0 +1,171 @@
+package ai.timefold.solver.core.impl.solver.termination;
+
+import java.util.NavigableMap;
+import java.util.TreeMap;
+
+import ai.timefold.solver.core.api.score.Score;
+import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
+import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope;
+import ai.timefold.solver.core.impl.solver.scope.SolverScope;
+import ai.timefold.solver.core.impl.solver.thread.ChildThreadType;
+
+import org.jspecify.annotations.NonNull;
+import org.jspecify.annotations.Nullable;
+
+public final class AdaptiveTermination<Solution_, Score_ extends Score<Score_>> implements Termination<Solution_> {
+ private final long gracePeriodMillis;
+ private final double minimumImprovementRatio;
+
+ boolean isGracePeriodActive;
+ private long gracePeriodStartTimeMillis;
+ private LevelScoreDiff gracePeriodScoreDiff;
+
+ private final NavigableMap<Long, Score_> scoresByTime;
+
+ public AdaptiveTermination(long gracePeriodMillis, double minimumImprovementRatio) {
+ this.gracePeriodMillis = gracePeriodMillis;
+ this.minimumImprovementRatio = minimumImprovementRatio;
+ this.scoresByTime = new TreeMap<>();
+ }
+
+ private record LevelScoreDiff(boolean harderScoreChanged, double softestScoreDiff) { | Typically, I would be all for a carrier type like this. In this case, and on the hot path, I'd rather store the two variables individually and avoid allocating instances of the wrapper.
In fact, this is the only thing that actually made a measurable impact in my experiments - `LevelScoreDiff` was ~10th most allocated object on the heap. |
timefold-solver | github_2023 | java | 1,313 | TimefoldAI | triceo | @@ -0,0 +1,171 @@
+package ai.timefold.solver.core.impl.solver.termination;
+
+import java.util.NavigableMap;
+import java.util.TreeMap;
+
+import ai.timefold.solver.core.api.score.Score;
+import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
+import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope;
+import ai.timefold.solver.core.impl.solver.scope.SolverScope;
+import ai.timefold.solver.core.impl.solver.thread.ChildThreadType;
+
+import org.jspecify.annotations.NonNull;
+import org.jspecify.annotations.Nullable;
+
+public final class AdaptiveTermination<Solution_, Score_ extends Score<Score_>> implements Termination<Solution_> {
+ private final long gracePeriodMillis;
+ private final double minimumImprovementRatio;
+
+ boolean isGracePeriodActive;
+ private long gracePeriodStartTimeMillis;
+ private LevelScoreDiff gracePeriodScoreDiff;
+
+ private final NavigableMap<Long, Score_> scoresByTime;
+
+ public AdaptiveTermination(long gracePeriodMillis, double minimumImprovementRatio) {
+ this.gracePeriodMillis = gracePeriodMillis;
+ this.minimumImprovementRatio = minimumImprovementRatio;
+ this.scoresByTime = new TreeMap<>();
+ }
+
+ private record LevelScoreDiff(boolean harderScoreChanged, double softestScoreDiff) {
+ /**
+ * Calculates the softest score difference between two scores and records
+ * if any harder levels changed. Returns null if the score are the same.
+ *
+ * @param start The first score, typically smaller
+ * @param end The second score, typically larger
+ * @return A {@link LevelScoreDiff} where harderScoreChanged is true
+ * if and only if a level beside the softest score level changed,
+ * and the difference between the softest score as a double, or null
+ * if both scores are the same.
+ * @param <Score_> The score type.
+ */
+ public static <Score_ extends Score<Score_>> @Nullable LevelScoreDiff between(@NonNull Score_ start,
+ @NonNull Score_ end) {
+ var scoreDiffs = end.subtract(start).toLevelDoubles();
+ var softestLevel = scoreDiffs.length - 1;
+ for (int i = 0; i < scoreDiffs.length; i++) {
+ if (scoreDiffs[i] != 0.0) {
+ return new LevelScoreDiff(softestLevel != i, scoreDiffs[softestLevel]);
+ }
+ }
+ return null;
+ }
+ }
+
+ public void start(long startTime, Score_ startingScore) {
+ resetGracePeriod(startTime, startingScore);
+ }
+
+ public void step(long time, Score_ bestScore) {
+ scoresByTime.put(time, bestScore);
+ }
+
+ private void resetGracePeriod(long currentTime, Score_ startingScore) {
+ gracePeriodStartTimeMillis = currentTime;
+ isGracePeriodActive = true;
+
+ // Remove all entries in the map since grace is reset
+ scoresByTime.clear();
+
+ // Put the current best score as the first entry
+ scoresByTime.put(currentTime, startingScore);
+ }
+
+ public boolean isTerminated(long currentTime, Score_ endScore) {
+ if (isGracePeriodActive) {
+ // first score in scoresByTime = first score in grace period window
+ var endpointDiff = LevelScoreDiff.between(scoresByTime.firstEntry().getValue(), endScore);
+ var timeElapsedMillis = currentTime - gracePeriodStartTimeMillis;
+ if (endpointDiff != null && endpointDiff.harderScoreChanged) {
+ // A harder score changed, so reset the grace period
+ resetGracePeriod(currentTime, endScore);
+ return false;
+ }
+ if (timeElapsedMillis >= gracePeriodMillis) {
+ // grace period over, record the reference diff
+ isGracePeriodActive = false;
+ gracePeriodScoreDiff = endpointDiff;
+ return endpointDiff == null;
+ }
+ return false;
+ }
+
+ var startScoreEntry = scoresByTime.floorEntry(currentTime - gracePeriodMillis);
+ var startScore = startScoreEntry.getValue();
+ scoresByTime.subMap(0L, startScoreEntry.getKey()).clear();
+ var scoreDiff = LevelScoreDiff.between(startScore, endScore);
+
+ if (scoreDiff == null) {
+ // no change after grace period, terminate
+ return true;
+ }
+
+ if (scoreDiff.harderScoreChanged) {
+ // A harder score changed, so reset the grace period
+ resetGracePeriod(currentTime, endScore);
+ return false;
+ }
+
+ return scoreDiff.softestScoreDiff / gracePeriodScoreDiff.softestScoreDiff < minimumImprovementRatio;
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public boolean isSolverTerminated(SolverScope<Solution_> solverScope) {
+ return isTerminated(System.currentTimeMillis(), (Score_) solverScope.getBestScore()); | I wonder if we should use nanotime instead, and truncate it to millis.
The precision of `currentTimeMillis` is questionable, see Javadoc:
> Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds. |
timefold-solver | github_2023 | java | 1,313 | TimefoldAI | triceo | @@ -0,0 +1,171 @@
+package ai.timefold.solver.core.impl.solver.termination;
+
+import java.util.NavigableMap;
+import java.util.TreeMap;
+
+import ai.timefold.solver.core.api.score.Score;
+import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
+import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope;
+import ai.timefold.solver.core.impl.solver.scope.SolverScope;
+import ai.timefold.solver.core.impl.solver.thread.ChildThreadType;
+
+import org.jspecify.annotations.NonNull;
+import org.jspecify.annotations.Nullable;
+
+public final class AdaptiveTermination<Solution_, Score_ extends Score<Score_>> implements Termination<Solution_> {
+ private final long gracePeriodMillis;
+ private final double minimumImprovementRatio;
+
+ boolean isGracePeriodActive;
+ private long gracePeriodStartTimeMillis;
+ private LevelScoreDiff gracePeriodScoreDiff;
+
+ private final NavigableMap<Long, Score_> scoresByTime;
+
+ public AdaptiveTermination(long gracePeriodMillis, double minimumImprovementRatio) {
+ this.gracePeriodMillis = gracePeriodMillis;
+ this.minimumImprovementRatio = minimumImprovementRatio;
+ this.scoresByTime = new TreeMap<>();
+ }
+
+ private record LevelScoreDiff(boolean harderScoreChanged, double softestScoreDiff) {
+ /**
+ * Calculates the softest score difference between two scores and records
+ * if any harder levels changed. Returns null if the score are the same.
+ *
+ * @param start The first score, typically smaller
+ * @param end The second score, typically larger
+ * @return A {@link LevelScoreDiff} where harderScoreChanged is true
+ * if and only if a level beside the softest score level changed,
+ * and the difference between the softest score as a double, or null
+ * if both scores are the same.
+ * @param <Score_> The score type.
+ */
+ public static <Score_ extends Score<Score_>> @Nullable LevelScoreDiff between(@NonNull Score_ start,
+ @NonNull Score_ end) {
+ var scoreDiffs = end.subtract(start).toLevelDoubles();
+ var softestLevel = scoreDiffs.length - 1;
+ for (int i = 0; i < scoreDiffs.length; i++) {
+ if (scoreDiffs[i] != 0.0) {
+ return new LevelScoreDiff(softestLevel != i, scoreDiffs[softestLevel]);
+ }
+ }
+ return null;
+ }
+ }
+
+ public void start(long startTime, Score_ startingScore) {
+ resetGracePeriod(startTime, startingScore);
+ }
+
+ public void step(long time, Score_ bestScore) {
+ scoresByTime.put(time, bestScore);
+ }
+
+ private void resetGracePeriod(long currentTime, Score_ startingScore) {
+ gracePeriodStartTimeMillis = currentTime;
+ isGracePeriodActive = true;
+
+ // Remove all entries in the map since grace is reset
+ scoresByTime.clear();
+
+ // Put the current best score as the first entry
+ scoresByTime.put(currentTime, startingScore);
+ }
+
+ public boolean isTerminated(long currentTime, Score_ endScore) {
+ if (isGracePeriodActive) {
+ // first score in scoresByTime = first score in grace period window
+ var endpointDiff = LevelScoreDiff.between(scoresByTime.firstEntry().getValue(), endScore);
+ var timeElapsedMillis = currentTime - gracePeriodStartTimeMillis;
+ if (endpointDiff != null && endpointDiff.harderScoreChanged) {
+ // A harder score changed, so reset the grace period
+ resetGracePeriod(currentTime, endScore);
+ return false;
+ }
+ if (timeElapsedMillis >= gracePeriodMillis) {
+ // grace period over, record the reference diff
+ isGracePeriodActive = false;
+ gracePeriodScoreDiff = endpointDiff;
+ return endpointDiff == null;
+ }
+ return false;
+ }
+
+ var startScoreEntry = scoresByTime.floorEntry(currentTime - gracePeriodMillis);
+ var startScore = startScoreEntry.getValue();
+ scoresByTime.subMap(0L, startScoreEntry.getKey()).clear();
+ var scoreDiff = LevelScoreDiff.between(startScore, endScore);
+
+ if (scoreDiff == null) {
+ // no change after grace period, terminate
+ return true;
+ }
+
+ if (scoreDiff.harderScoreChanged) {
+ // A harder score changed, so reset the grace period
+ resetGracePeriod(currentTime, endScore);
+ return false;
+ }
+
+ return scoreDiff.softestScoreDiff / gracePeriodScoreDiff.softestScoreDiff < minimumImprovementRatio;
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public boolean isSolverTerminated(SolverScope<Solution_> solverScope) {
+ return isTerminated(System.currentTimeMillis(), (Score_) solverScope.getBestScore());
+ }
+
+ @Override
+ public boolean isPhaseTerminated(AbstractPhaseScope<Solution_> phaseScope) {
+ return isTerminated(System.currentTimeMillis(), phaseScope.getBestScore());
+ }
+
+ @Override
+ public double calculateSolverTimeGradient(SolverScope<Solution_> solverScope) {
+ return -1.0; | I wonder if there's a way to estimate this based on how close we are to the minimum necessary improvement. |
timefold-solver | github_2023 | java | 1,313 | TimefoldAI | triceo | @@ -0,0 +1,171 @@
+package ai.timefold.solver.core.impl.solver.termination;
+
+import java.util.NavigableMap;
+import java.util.TreeMap;
+
+import ai.timefold.solver.core.api.score.Score;
+import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
+import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope;
+import ai.timefold.solver.core.impl.solver.scope.SolverScope;
+import ai.timefold.solver.core.impl.solver.thread.ChildThreadType;
+
+import org.jspecify.annotations.NonNull;
+import org.jspecify.annotations.Nullable;
+
+public final class AdaptiveTermination<Solution_, Score_ extends Score<Score_>> implements Termination<Solution_> {
+ private final long gracePeriodMillis;
+ private final double minimumImprovementRatio;
+
+ boolean isGracePeriodActive;
+ private long gracePeriodStartTimeMillis;
+ private LevelScoreDiff gracePeriodScoreDiff;
+
+ private final NavigableMap<Long, Score_> scoresByTime;
+
+ public AdaptiveTermination(long gracePeriodMillis, double minimumImprovementRatio) {
+ this.gracePeriodMillis = gracePeriodMillis;
+ this.minimumImprovementRatio = minimumImprovementRatio;
+ this.scoresByTime = new TreeMap<>();
+ }
+
+ private record LevelScoreDiff(boolean harderScoreChanged, double softestScoreDiff) {
+ /**
+ * Calculates the softest score difference between two scores and records
+ * if any harder levels changed. Returns null if the score are the same.
+ *
+ * @param start The first score, typically smaller
+ * @param end The second score, typically larger
+ * @return A {@link LevelScoreDiff} where harderScoreChanged is true
+ * if and only if a level beside the softest score level changed,
+ * and the difference between the softest score as a double, or null
+ * if both scores are the same.
+ * @param <Score_> The score type.
+ */
+ public static <Score_ extends Score<Score_>> @Nullable LevelScoreDiff between(@NonNull Score_ start,
+ @NonNull Score_ end) {
+ var scoreDiffs = end.subtract(start).toLevelDoubles(); | Arguably, you can save yourself some of this work. `compareTo()` the two scores; if no better, no need to do anything anymore. The comparison works directly on the underlying data types, so no need to convert them to doubles and create a new array of them. |
timefold-solver | github_2023 | java | 1,313 | TimefoldAI | triceo | @@ -0,0 +1,171 @@
+package ai.timefold.solver.core.impl.solver.termination;
+
+import java.util.NavigableMap;
+import java.util.TreeMap;
+
+import ai.timefold.solver.core.api.score.Score;
+import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
+import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope;
+import ai.timefold.solver.core.impl.solver.scope.SolverScope;
+import ai.timefold.solver.core.impl.solver.thread.ChildThreadType;
+
+import org.jspecify.annotations.NonNull;
+import org.jspecify.annotations.Nullable; | You can use `@NullMarked` on the class, which means that everything is `@NonNull` unless marked as `@Nullable`. In my experience, this saves a lot of hassle. |
timefold-solver | github_2023 | java | 1,313 | TimefoldAI | triceo | @@ -1,57 +1,71 @@
package ai.timefold.solver.core.impl.solver.termination;
-import java.util.NavigableMap;
-import java.util.TreeMap;
-
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import ai.timefold.solver.core.impl.solver.thread.ChildThreadType;
import org.jspecify.annotations.NonNull;
-import org.jspecify.annotations.Nullable;
public final class AdaptiveTermination<Solution_, Score_ extends Score<Score_>> implements Termination<Solution_> {
- private final long gracePeriodMillis;
+ static final long NANOS_PER_MILLISECOND = 1_000_000;
+
+ private final long gracePeriodNanos;
private final double minimumImprovementRatio;
- boolean isGracePeriodActive;
- private long gracePeriodStartTimeMillis;
- private LevelScoreDiff gracePeriodScoreDiff;
+ private boolean isGracePeriodActive;
+ private long gracePeriodStartTimeNanos;
+ private double gracePeriodSoftestImprovementDouble;
- private final NavigableMap<Long, Score_> scoresByTime;
+ private final AdaptiveScoreRingBuffer<Score_> scoresByTime;
public AdaptiveTermination(long gracePeriodMillis, double minimumImprovementRatio) {
- this.gracePeriodMillis = gracePeriodMillis;
+ // convert to nanoseconds here so we don't need to do a
+ // division in the hot loop
+ this.gracePeriodNanos = gracePeriodMillis * NANOS_PER_MILLISECOND;
this.minimumImprovementRatio = minimumImprovementRatio;
- this.scoresByTime = new TreeMap<>();
- }
-
- private record LevelScoreDiff(boolean harderScoreChanged, double softestScoreDiff) {
- /**
- * Calculates the softest score difference between two scores and records
- * if any harder levels changed. Returns null if the score are the same.
- *
- * @param start The first score, typically smaller
- * @param end The second score, typically larger
- * @return A {@link LevelScoreDiff} where harderScoreChanged is true
- * if and only if a level beside the softest score level changed,
- * and the difference between the softest score as a double, or null
- * if both scores are the same.
- * @param <Score_> The score type.
- */
- public static <Score_ extends Score<Score_>> @Nullable LevelScoreDiff between(@NonNull Score_ start,
- @NonNull Score_ end) {
- var scoreDiffs = end.subtract(start).toLevelDoubles();
- var softestLevel = scoreDiffs.length - 1;
- for (int i = 0; i < scoreDiffs.length; i++) {
- if (scoreDiffs[i] != 0.0) {
- return new LevelScoreDiff(softestLevel != i, scoreDiffs[softestLevel]);
- }
+ this.scoresByTime = new AdaptiveScoreRingBuffer<>();
+ }
+
+ /**
+ * An exception that is thrown to signal a hard score improvement.
+ * This is done since:
+ * <p/>
+ * <ul>
+ * <li/>Hard score improvements are significantly rarer than soft score improvements.
+ * <li/>Allows us to directly return a double in a method instead of using a
+ * carrier type/needing to box it so we can use null as a special value.
+ * <li/>Avoid branching in code on the hot path.
+ * </ul>
+ * <p/>
+ * This exception does not fill the stack trace to improve performance;
+ * it is a signal that should always be caught
+ * and handled appropriately.
+ */
+ private static final class HardLevelImprovedSignal extends Exception {
+ @Override
+ public Throwable fillInStackTrace() {
+ return this;
+ }
+ }
+
+ private static <Score_ extends Score<Score_>> double softImprovement(@NonNull Score_ start,
+ @NonNull Score_ end) throws HardLevelImprovedSignal {
+ if (start.equals(end)) {
+ // optimization: since most of the time the score the same,
+ // we can use equals to avoid creating double arrays in the
+ // vast majority of comparisons
+ return 0.0;
+ }
+ var scoreDiffs = end.subtract(start).toLevelDoubles();
+ var softestLevel = scoreDiffs.length - 1;
+ for (int i = 0; i < softestLevel; i++) {
+ if (scoreDiffs[i] != 0.0) {
+ throw new HardLevelImprovedSignal(); | May I suggest we return an impossible value instead of using exceptions for control flow? Perhaps [NaN](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Double.html#NaN)? |
timefold-solver | github_2023 | java | 1,313 | TimefoldAI | triceo | @@ -1,57 +1,71 @@
package ai.timefold.solver.core.impl.solver.termination;
-import java.util.NavigableMap;
-import java.util.TreeMap;
-
import ai.timefold.solver.core.api.score.Score;
import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope;
import ai.timefold.solver.core.impl.solver.scope.SolverScope;
import ai.timefold.solver.core.impl.solver.thread.ChildThreadType;
import org.jspecify.annotations.NonNull;
-import org.jspecify.annotations.Nullable;
public final class AdaptiveTermination<Solution_, Score_ extends Score<Score_>> implements Termination<Solution_> {
- private final long gracePeriodMillis;
+ static final long NANOS_PER_MILLISECOND = 1_000_000;
+
+ private final long gracePeriodNanos;
private final double minimumImprovementRatio;
- boolean isGracePeriodActive;
- private long gracePeriodStartTimeMillis;
- private LevelScoreDiff gracePeriodScoreDiff;
+ private boolean isGracePeriodActive;
+ private long gracePeriodStartTimeNanos;
+ private double gracePeriodSoftestImprovementDouble;
- private final NavigableMap<Long, Score_> scoresByTime;
+ private final AdaptiveScoreRingBuffer<Score_> scoresByTime;
public AdaptiveTermination(long gracePeriodMillis, double minimumImprovementRatio) {
- this.gracePeriodMillis = gracePeriodMillis;
+ // convert to nanoseconds here so we don't need to do a
+ // division in the hot loop
+ this.gracePeriodNanos = gracePeriodMillis * NANOS_PER_MILLISECOND;
this.minimumImprovementRatio = minimumImprovementRatio;
- this.scoresByTime = new TreeMap<>();
- }
-
- private record LevelScoreDiff(boolean harderScoreChanged, double softestScoreDiff) {
- /**
- * Calculates the softest score difference between two scores and records
- * if any harder levels changed. Returns null if the score are the same.
- *
- * @param start The first score, typically smaller
- * @param end The second score, typically larger
- * @return A {@link LevelScoreDiff} where harderScoreChanged is true
- * if and only if a level beside the softest score level changed,
- * and the difference between the softest score as a double, or null
- * if both scores are the same.
- * @param <Score_> The score type.
- */
- public static <Score_ extends Score<Score_>> @Nullable LevelScoreDiff between(@NonNull Score_ start,
- @NonNull Score_ end) {
- var scoreDiffs = end.subtract(start).toLevelDoubles();
- var softestLevel = scoreDiffs.length - 1;
- for (int i = 0; i < scoreDiffs.length; i++) {
- if (scoreDiffs[i] != 0.0) {
- return new LevelScoreDiff(softestLevel != i, scoreDiffs[softestLevel]);
- }
+ this.scoresByTime = new AdaptiveScoreRingBuffer<>();
+ }
+
+ /**
+ * An exception that is thrown to signal a hard score improvement.
+ * This is done since:
+ * <p/>
+ * <ul>
+ * <li/>Hard score improvements are significantly rarer than soft score improvements.
+ * <li/>Allows us to directly return a double in a method instead of using a
+ * carrier type/needing to box it so we can use null as a special value.
+ * <li/>Avoid branching in code on the hot path.
+ * </ul>
+ * <p/>
+ * This exception does not fill the stack trace to improve performance;
+ * it is a signal that should always be caught
+ * and handled appropriately.
+ */
+ private static final class HardLevelImprovedSignal extends Exception {
+ @Override
+ public Throwable fillInStackTrace() {
+ return this;
+ }
+ }
+
+ private static <Score_ extends Score<Score_>> double softImprovement(@NonNull Score_ start,
+ @NonNull Score_ end) throws HardLevelImprovedSignal {
+ if (start.equals(end)) { | Can the score be _worse_ here? Arguably, it can - sometimes the solver picks a deteriorating move to try to get out of a local optima. |
timefold-solver | github_2023 | java | 1,313 | TimefoldAI | triceo | @@ -0,0 +1,203 @@
+package ai.timefold.solver.core.impl.solver.termination;
+
+import java.util.Arrays;
+import java.util.Objects;
+
+import ai.timefold.solver.core.api.score.Score;
+
+import org.jspecify.annotations.NonNull;
+import org.jspecify.annotations.Nullable;
+
+final class AdaptiveScoreRingBuffer<Score_ extends Score<Score_>> { | Is there a way to refactor the ring buffer to make it a general-purpose collection?
I can see it being useful to the Solver for more than this. |
timefold-solver | github_2023 | java | 1,313 | TimefoldAI | triceo | @@ -0,0 +1,210 @@
+package ai.timefold.solver.core.config.solver.termination;
+
+import static ai.timefold.solver.core.config.solver.termination.TerminationConfig.requireNonNegative;
+
+import java.time.Duration;
+import java.util.function.Consumer;
+
+import jakarta.xml.bind.annotation.XmlType;
+import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
+
+import ai.timefold.solver.core.config.AbstractConfig;
+import ai.timefold.solver.core.config.util.ConfigUtils;
+import ai.timefold.solver.core.impl.io.jaxb.adapter.JaxbDurationAdapter;
+
+import org.jspecify.annotations.NonNull;
+import org.jspecify.annotations.Nullable;
+
+@XmlType(propOrder = {
+ "slidingWindowDuration",
+ "slidingWindowMilliseconds",
+ "slidingWindowSeconds",
+ "slidingWindowMinutes",
+ "slidingWindowHours",
+ "slidingWindowDays",
+ "minimumImprovementRatio"
+})
+public class DiminishedReturnsTerminationConfig extends AbstractConfig<DiminishedReturnsTerminationConfig> {
+ @XmlJavaTypeAdapter(JaxbDurationAdapter.class)
+ private Duration slidingWindowDuration = null;
+ private Long slidingWindowMilliseconds = null;
+ private Long slidingWindowSeconds = null;
+ private Long slidingWindowMinutes = null;
+ private Long slidingWindowHours = null;
+ private Long slidingWindowDays = null;
+
+ private Double minimumImprovementRatio = null;
+
+ public @Nullable Duration getSlidingWindowDuration() {
+ return slidingWindowDuration;
+ }
+
+ public void setSlidingWindowDuration(@Nullable Duration slidingWindowDuration) {
+ this.slidingWindowDuration = slidingWindowDuration;
+ }
+
+ public @Nullable Long getSlidingWindowMilliseconds() {
+ return slidingWindowMilliseconds;
+ }
+
+ public void setSlidingWindowMilliseconds(@Nullable Long slidingWindowMilliseconds) {
+ this.slidingWindowMilliseconds = slidingWindowMilliseconds;
+ }
+
+ public @Nullable Long getSlidingWindowSeconds() {
+ return slidingWindowSeconds;
+ }
+
+ public void setSlidingWindowSeconds(@Nullable Long slidingWindowSeconds) {
+ this.slidingWindowSeconds = slidingWindowSeconds;
+ }
+
+ public @Nullable Long getSlidingWindowMinutes() {
+ return slidingWindowMinutes;
+ }
+
+ public void setSlidingWindowMinutes(@Nullable Long slidingWindowMinutes) {
+ this.slidingWindowMinutes = slidingWindowMinutes;
+ }
+
+ public @Nullable Long getSlidingWindowHours() {
+ return slidingWindowHours;
+ }
+
+ public void setSlidingWindowHours(@Nullable Long slidingWindowHours) {
+ this.slidingWindowHours = slidingWindowHours;
+ }
+
+ public @Nullable Long getSlidingWindowDays() {
+ return slidingWindowDays;
+ }
+
+ public void setSlidingWindowDays(@Nullable Long slidingWindowDays) {
+ this.slidingWindowDays = slidingWindowDays;
+ }
+
+ public @Nullable Double getMinimumImprovementRatio() {
+ return minimumImprovementRatio;
+ }
+
+ public void setMinimumImprovementRatio(@Nullable Double minimumImprovementRatio) {
+ this.minimumImprovementRatio = minimumImprovementRatio;
+ }
+
+ // ************************************************************************
+ // With methods
+ // ************************************************************************
+ @NonNull
+ public DiminishedReturnsTerminationConfig withSlidingWindowDuration(@NonNull Duration slidingWindowDuration) {
+ this.slidingWindowDuration = slidingWindowDuration;
+ return this;
+ }
+
+ @NonNull
+ public DiminishedReturnsTerminationConfig withSlidingWindowMilliseconds(@NonNull Long slidingWindowMilliseconds) {
+ this.slidingWindowMilliseconds = slidingWindowMilliseconds;
+ return this;
+ }
+
+ @NonNull
+ public DiminishedReturnsTerminationConfig withSlidingWindowSeconds(@NonNull Long slidingWindowSeconds) {
+ this.slidingWindowSeconds = slidingWindowSeconds;
+ return this;
+ }
+
+ @NonNull
+ public DiminishedReturnsTerminationConfig withSlidingWindowMinutes(@NonNull Long slidingWindowMinutes) {
+ this.slidingWindowMinutes = slidingWindowMinutes;
+ return this;
+ }
+
+ @NonNull
+ public DiminishedReturnsTerminationConfig withSlidingWindowHours(@NonNull Long slidingWindowHours) {
+ this.slidingWindowHours = slidingWindowHours;
+ return this;
+ }
+
+ @NonNull
+ public DiminishedReturnsTerminationConfig withSlidingWindowDays(@NonNull Long slidingWindowDays) {
+ this.slidingWindowDays = slidingWindowDays;
+ return this;
+ }
+
+ @NonNull
+ public DiminishedReturnsTerminationConfig withMinimumImprovementRatio(@NonNull Double minimumImprovementRatio) {
+ this.minimumImprovementRatio = minimumImprovementRatio;
+ return this;
+ }
+
+ // Complex methods
+ @Override
+ public @NonNull DiminishedReturnsTerminationConfig inherit(@NonNull DiminishedReturnsTerminationConfig inheritedConfig) {
+ if (!slidingWindowIsSet()) {
+ inheritSlidingWindow(inheritedConfig);
+ }
+ minimumImprovementRatio = ConfigUtils.inheritOverwritableProperty(minimumImprovementRatio,
+ inheritedConfig.getMinimumImprovementRatio());
+ return this;
+ }
+
+ private void inheritSlidingWindow(@NonNull DiminishedReturnsTerminationConfig parent) {
+ slidingWindowDuration =
+ ConfigUtils.inheritOverwritableProperty(slidingWindowDuration, parent.getSlidingWindowDuration());
+ slidingWindowMilliseconds = ConfigUtils.inheritOverwritableProperty(slidingWindowMilliseconds,
+ parent.getSlidingWindowMilliseconds());
+ slidingWindowSeconds = ConfigUtils.inheritOverwritableProperty(slidingWindowSeconds, parent.getSlidingWindowSeconds());
+ slidingWindowMinutes = ConfigUtils.inheritOverwritableProperty(slidingWindowMinutes, parent.getSlidingWindowMinutes());
+ slidingWindowHours = ConfigUtils.inheritOverwritableProperty(slidingWindowHours, parent.getSlidingWindowHours());
+ slidingWindowDays = ConfigUtils.inheritOverwritableProperty(slidingWindowDays, parent.getSlidingWindowDays());
+ }
+
+ @Override
+ public @NonNull DiminishedReturnsTerminationConfig copyConfig() {
+ return new DiminishedReturnsTerminationConfig().inherit(this);
+ }
+
+ @Override
+ public void visitReferencedClasses(@NonNull Consumer<Class<?>> classVisitor) {
+ // intentionally empty - no classes to visit
+ }
+
+ /** Check whether any slidingWindow... is non-null. */
+ public boolean slidingWindowIsSet() {
+ return slidingWindowDuration != null
+ || slidingWindowMilliseconds != null
+ || slidingWindowSeconds != null
+ || slidingWindowMinutes != null
+ || slidingWindowHours != null
+ || slidingWindowDays != null;
+ }
+
+ public @Nullable Long calculateSlidingWindowMilliseconds() {
+ if (slidingWindowMilliseconds == null && slidingWindowSeconds == null
+ && slidingWindowMinutes == null && slidingWindowHours == null
+ && slidingWindowDays == null) {
+ if (slidingWindowDuration != null) {
+ if (slidingWindowDuration.getNano() % 1000 != 0) {
+ throw new IllegalArgumentException("The termination slidingWindowDuration (" + slidingWindowDuration
+ + ") cannot use nanoseconds.");
+ }
+ return slidingWindowDuration.toMillis();
+ }
+ return null;
+ }
+ if (slidingWindowDuration != null) {
+ throw new IllegalArgumentException("The termination slidingWindowDuration (" + slidingWindowDuration
+ + ") cannot be combined with slidingWindowMilliseconds (" + slidingWindowMilliseconds
+ + "), slidingWindowSeconds (" + slidingWindowSeconds
+ + "), slidingWindowMinutes (" + slidingWindowMinutes
+ + "), slidingWindowHours (" + slidingWindowHours + "),"
+ + ") or slidingWindowDays (" + slidingWindowDays + ").");
+ }
+ long slidingWindowMillis = 0L
+ + requireNonNegative(slidingWindowMilliseconds, "slidingWindowMilliseconds")
+ + requireNonNegative(slidingWindowSeconds, "slidingWindowSeconds") * 1000L
+ + requireNonNegative(slidingWindowMinutes, "slidingWindowMinutes") * 60_000L
+ + requireNonNegative(slidingWindowHours, "slidingWindowHours") * 3_600_000L
+ + requireNonNegative(slidingWindowDays, "slidingWindowDays") * 86_400_000L;
+ return slidingWindowMillis;
+ } | Is this how the other terminations deal with durations? It would make more sense to me to merge all of those data points into `Duration` - as that is the one data type that brings semantics (as opposed to `long`).
But if this is how the other terminations do this, then so be it. |
timefold-solver | github_2023 | java | 1,313 | TimefoldAI | triceo | @@ -0,0 +1,224 @@
+package ai.timefold.solver.core.impl.solver.termination;
+
+import java.util.Arrays;
+import java.util.NavigableMap;
+import java.util.Objects;
+
+import ai.timefold.solver.core.api.score.Score;
+
+import org.jspecify.annotations.NonNull;
+import org.jspecify.annotations.Nullable;
+
+/**
+ * A heavily specialized pair of
+ * <a href="https://en.wikipedia.org/wiki/Circular_buffer">ring buffers</a> | Maybe use `@see` for the link? |
timefold-solver | github_2023 | java | 1,313 | TimefoldAI | triceo | @@ -0,0 +1,224 @@
+package ai.timefold.solver.core.impl.solver.termination;
+
+import java.util.Arrays;
+import java.util.NavigableMap;
+import java.util.Objects;
+
+import ai.timefold.solver.core.api.score.Score;
+
+import org.jspecify.annotations.NonNull;
+import org.jspecify.annotations.Nullable;
+
+/**
+ * A heavily specialized pair of
+ * <a href="https://en.wikipedia.org/wiki/Circular_buffer">ring buffers</a>
+ * that acts as a {@link NavigableMap} for getting the scores at a prior time.
+ * <br/>
+ * The ring buffers operate with the following assumptions:
+ * <ul>
+ * <li>Keys (i.e. {@link System#nanoTime()} are inserted in ascending order</li>
+ * <li>Times are queried in ascending order</li>
+ * <li>The queried time is probably near the start of the ring buffer</li>
+ * </ul>
+ * <br/>
+ * {@link DiminishedReturnsScoreRingBuffer} automatically clear entries prior
+ * to the queried time when polled (if the queried time is not in the
+ * {@link DiminishedReturnsScoreRingBuffer}, then the largest entry prior
+ * to the queried time is kept and returned).
+ * The ring buffers will automatically resize when filled past their capacity.
+ *
+ * @param <Score_> The score type
+ */
+final class DiminishedReturnsScoreRingBuffer<Score_ extends Score<Score_>> {
+ private static final int DEFAULT_CAPACITY = 4096; | Where did this number come from?
It's generally a good idea to explain in a comment what you used to determine the value. Even if it just says "Arbitrary.", it gives future us an insight into your mind. |
timefold-solver | github_2023 | java | 1,313 | TimefoldAI | triceo | @@ -0,0 +1,224 @@
+package ai.timefold.solver.core.impl.solver.termination;
+
+import java.util.Arrays;
+import java.util.NavigableMap;
+import java.util.Objects;
+
+import ai.timefold.solver.core.api.score.Score;
+
+import org.jspecify.annotations.NonNull;
+import org.jspecify.annotations.Nullable;
+
+/**
+ * A heavily specialized pair of
+ * <a href="https://en.wikipedia.org/wiki/Circular_buffer">ring buffers</a>
+ * that acts as a {@link NavigableMap} for getting the scores at a prior time.
+ * <br/>
+ * The ring buffers operate with the following assumptions:
+ * <ul>
+ * <li>Keys (i.e. {@link System#nanoTime()} are inserted in ascending order</li>
+ * <li>Times are queried in ascending order</li>
+ * <li>The queried time is probably near the start of the ring buffer</li>
+ * </ul>
+ * <br/>
+ * {@link DiminishedReturnsScoreRingBuffer} automatically clear entries prior
+ * to the queried time when polled (if the queried time is not in the
+ * {@link DiminishedReturnsScoreRingBuffer}, then the largest entry prior
+ * to the queried time is kept and returned).
+ * The ring buffers will automatically resize when filled past their capacity.
+ *
+ * @param <Score_> The score type
+ */
+final class DiminishedReturnsScoreRingBuffer<Score_ extends Score<Score_>> {
+ private static final int DEFAULT_CAPACITY = 4096;
+
+ int readIndex;
+ int writeIndex;
+ private long[] nanoTimeRingBuffer;
+ private Score_[] scoreRingBuffer;
+
+ DiminishedReturnsScoreRingBuffer() {
+ this(DEFAULT_CAPACITY);
+ }
+
+ @SuppressWarnings("unchecked")
+ DiminishedReturnsScoreRingBuffer(int capacity) {
+ this(0, 0, new long[capacity], (Score_[]) new Score[capacity]);
+ }
+
+ DiminishedReturnsScoreRingBuffer(int readIndex, int writeIndex,
+ long[] nanoTimeRingBuffer, @Nullable Score_[] scoreRingBuffer) {
+ this.nanoTimeRingBuffer = nanoTimeRingBuffer;
+ this.scoreRingBuffer = scoreRingBuffer;
+ this.readIndex = readIndex;
+ this.writeIndex = writeIndex;
+ }
+
+ record RingBufferState(int readIndex, int writeIndex,
+ long[] nanoTimeRingBuffer, @Nullable Score<?>[] scoreRingBuffer) {
+ @Override
+ public boolean equals(Object o) {
+ if (!(o instanceof RingBufferState that)) {
+ return false;
+ }
+ return readIndex == that.readIndex && writeIndex == that.writeIndex && Objects.deepEquals(nanoTimeRingBuffer,
+ that.nanoTimeRingBuffer) && Objects.deepEquals(scoreRingBuffer, that.scoreRingBuffer);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(readIndex, writeIndex, Arrays.hashCode(nanoTimeRingBuffer), Arrays.hashCode(scoreRingBuffer));
+ }
+
+ @Override
+ public String toString() {
+ return "RingBufferState{" +
+ "readIndex=" + readIndex +
+ ", writeIndex=" + writeIndex +
+ ", nanoTimeRingBuffer=" + Arrays.toString(nanoTimeRingBuffer) +
+ ", scoreRingBuffer=" + Arrays.toString(scoreRingBuffer) +
+ '}';
+ }
+ }
+
+ @NonNull
+ RingBufferState getState() {
+ return new RingBufferState(readIndex, writeIndex, nanoTimeRingBuffer, scoreRingBuffer);
+ }
+
+ void resize() {
+ var newCapacity = nanoTimeRingBuffer.length * 2;
+ var newNanoTimeRingBuffer = new long[newCapacity];
+ @SuppressWarnings("unchecked")
+ var newScoreRingBuffer = (Score_[]) new Score[newCapacity];
+
+ if (readIndex < writeIndex) {
+ // entries are [startIndex, writeIndex)
+ var newLength = writeIndex - readIndex;
+ System.arraycopy(nanoTimeRingBuffer, readIndex, newNanoTimeRingBuffer, 0, newLength);
+ System.arraycopy(scoreRingBuffer, readIndex, newScoreRingBuffer, 0, newLength);
+ readIndex = 0;
+ writeIndex = newLength;
+ } else {
+ // entries are [readIndex, CAPACITY) + [0, writeIndex)
+ var firstLength = nanoTimeRingBuffer.length - readIndex;
+ var secondLength = writeIndex;
+ var totalLength = firstLength + secondLength;
+
+ System.arraycopy(nanoTimeRingBuffer, readIndex, newNanoTimeRingBuffer, 0, firstLength);
+ System.arraycopy(scoreRingBuffer, readIndex, newScoreRingBuffer, 0, firstLength);
+ System.arraycopy(nanoTimeRingBuffer, 0, newNanoTimeRingBuffer, firstLength, secondLength);
+ System.arraycopy(scoreRingBuffer, 0, newScoreRingBuffer, firstLength, secondLength);
+ readIndex = 0;
+ writeIndex = totalLength;
+ }
+ nanoTimeRingBuffer = newNanoTimeRingBuffer;
+ scoreRingBuffer = newScoreRingBuffer;
+ }
+
+ public void clear() { | I wonder if:
- Throwing away the array and re-allocating it would be faster than clearing it. (Maybe not.)
- We should allocate the array using the original size, not using whatever size it is now. |
timefold-solver | github_2023 | java | 1,313 | TimefoldAI | triceo | @@ -0,0 +1,224 @@
+package ai.timefold.solver.core.impl.solver.termination;
+
+import java.util.Arrays;
+import java.util.NavigableMap;
+import java.util.Objects;
+
+import ai.timefold.solver.core.api.score.Score;
+
+import org.jspecify.annotations.NonNull;
+import org.jspecify.annotations.Nullable;
+
+/**
+ * A heavily specialized pair of
+ * <a href="https://en.wikipedia.org/wiki/Circular_buffer">ring buffers</a>
+ * that acts as a {@link NavigableMap} for getting the scores at a prior time.
+ * <br/>
+ * The ring buffers operate with the following assumptions:
+ * <ul>
+ * <li>Keys (i.e. {@link System#nanoTime()} are inserted in ascending order</li>
+ * <li>Times are queried in ascending order</li>
+ * <li>The queried time is probably near the start of the ring buffer</li>
+ * </ul>
+ * <br/>
+ * {@link DiminishedReturnsScoreRingBuffer} automatically clear entries prior
+ * to the queried time when polled (if the queried time is not in the
+ * {@link DiminishedReturnsScoreRingBuffer}, then the largest entry prior
+ * to the queried time is kept and returned).
+ * The ring buffers will automatically resize when filled past their capacity.
+ *
+ * @param <Score_> The score type
+ */
+final class DiminishedReturnsScoreRingBuffer<Score_ extends Score<Score_>> {
+ private static final int DEFAULT_CAPACITY = 4096;
+
+ int readIndex;
+ int writeIndex;
+ private long[] nanoTimeRingBuffer;
+ private Score_[] scoreRingBuffer;
+
+ DiminishedReturnsScoreRingBuffer() {
+ this(DEFAULT_CAPACITY);
+ }
+
+ @SuppressWarnings("unchecked")
+ DiminishedReturnsScoreRingBuffer(int capacity) {
+ this(0, 0, new long[capacity], (Score_[]) new Score[capacity]);
+ }
+
+ DiminishedReturnsScoreRingBuffer(int readIndex, int writeIndex,
+ long[] nanoTimeRingBuffer, @Nullable Score_[] scoreRingBuffer) {
+ this.nanoTimeRingBuffer = nanoTimeRingBuffer;
+ this.scoreRingBuffer = scoreRingBuffer;
+ this.readIndex = readIndex;
+ this.writeIndex = writeIndex;
+ }
+
+ record RingBufferState(int readIndex, int writeIndex,
+ long[] nanoTimeRingBuffer, @Nullable Score<?>[] scoreRingBuffer) {
+ @Override
+ public boolean equals(Object o) {
+ if (!(o instanceof RingBufferState that)) {
+ return false;
+ }
+ return readIndex == that.readIndex && writeIndex == that.writeIndex && Objects.deepEquals(nanoTimeRingBuffer,
+ that.nanoTimeRingBuffer) && Objects.deepEquals(scoreRingBuffer, that.scoreRingBuffer);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(readIndex, writeIndex, Arrays.hashCode(nanoTimeRingBuffer), Arrays.hashCode(scoreRingBuffer));
+ }
+
+ @Override
+ public String toString() {
+ return "RingBufferState{" +
+ "readIndex=" + readIndex +
+ ", writeIndex=" + writeIndex +
+ ", nanoTimeRingBuffer=" + Arrays.toString(nanoTimeRingBuffer) +
+ ", scoreRingBuffer=" + Arrays.toString(scoreRingBuffer) +
+ '}';
+ }
+ }
+
+ @NonNull
+ RingBufferState getState() {
+ return new RingBufferState(readIndex, writeIndex, nanoTimeRingBuffer, scoreRingBuffer);
+ }
+
+ void resize() {
+ var newCapacity = nanoTimeRingBuffer.length * 2;
+ var newNanoTimeRingBuffer = new long[newCapacity];
+ @SuppressWarnings("unchecked")
+ var newScoreRingBuffer = (Score_[]) new Score[newCapacity];
+
+ if (readIndex < writeIndex) {
+ // entries are [startIndex, writeIndex)
+ var newLength = writeIndex - readIndex;
+ System.arraycopy(nanoTimeRingBuffer, readIndex, newNanoTimeRingBuffer, 0, newLength);
+ System.arraycopy(scoreRingBuffer, readIndex, newScoreRingBuffer, 0, newLength);
+ readIndex = 0;
+ writeIndex = newLength;
+ } else {
+ // entries are [readIndex, CAPACITY) + [0, writeIndex)
+ var firstLength = nanoTimeRingBuffer.length - readIndex;
+ var secondLength = writeIndex;
+ var totalLength = firstLength + secondLength;
+
+ System.arraycopy(nanoTimeRingBuffer, readIndex, newNanoTimeRingBuffer, 0, firstLength);
+ System.arraycopy(scoreRingBuffer, readIndex, newScoreRingBuffer, 0, firstLength);
+ System.arraycopy(nanoTimeRingBuffer, 0, newNanoTimeRingBuffer, firstLength, secondLength);
+ System.arraycopy(scoreRingBuffer, 0, newScoreRingBuffer, firstLength, secondLength);
+ readIndex = 0;
+ writeIndex = totalLength;
+ }
+ nanoTimeRingBuffer = newNanoTimeRingBuffer;
+ scoreRingBuffer = newScoreRingBuffer;
+ }
+
+ public void clear() {
+ readIndex = 0;
+ writeIndex = 0;
+ Arrays.fill(nanoTimeRingBuffer, 0);
+ Arrays.fill(scoreRingBuffer, null);
+ }
+
+ /**
+ * Returns the first element of the score ring buffer.
+ * Does not remove the element.
+ *
+ * @return the first element of the score ring buffer
+ */
+ public @NonNull Score_ peekFirst() { | Since the array starts as empty, this should not be annotated as `@NonNull`, because `null` is entirely possible. |
timefold-solver | github_2023 | java | 1,313 | TimefoldAI | triceo | @@ -0,0 +1,224 @@
+package ai.timefold.solver.core.impl.solver.termination;
+
+import java.util.Arrays;
+import java.util.NavigableMap;
+import java.util.Objects;
+
+import ai.timefold.solver.core.api.score.Score;
+
+import org.jspecify.annotations.NonNull;
+import org.jspecify.annotations.Nullable;
+
+/**
+ * A heavily specialized pair of
+ * <a href="https://en.wikipedia.org/wiki/Circular_buffer">ring buffers</a>
+ * that acts as a {@link NavigableMap} for getting the scores at a prior time.
+ * <br/>
+ * The ring buffers operate with the following assumptions:
+ * <ul>
+ * <li>Keys (i.e. {@link System#nanoTime()} are inserted in ascending order</li>
+ * <li>Times are queried in ascending order</li>
+ * <li>The queried time is probably near the start of the ring buffer</li>
+ * </ul>
+ * <br/>
+ * {@link DiminishedReturnsScoreRingBuffer} automatically clear entries prior
+ * to the queried time when polled (if the queried time is not in the
+ * {@link DiminishedReturnsScoreRingBuffer}, then the largest entry prior
+ * to the queried time is kept and returned).
+ * The ring buffers will automatically resize when filled past their capacity.
+ *
+ * @param <Score_> The score type
+ */
+final class DiminishedReturnsScoreRingBuffer<Score_ extends Score<Score_>> {
+ private static final int DEFAULT_CAPACITY = 4096;
+
+ int readIndex;
+ int writeIndex;
+ private long[] nanoTimeRingBuffer;
+ private Score_[] scoreRingBuffer;
+
+ DiminishedReturnsScoreRingBuffer() {
+ this(DEFAULT_CAPACITY);
+ }
+
+ @SuppressWarnings("unchecked")
+ DiminishedReturnsScoreRingBuffer(int capacity) {
+ this(0, 0, new long[capacity], (Score_[]) new Score[capacity]);
+ }
+
+ DiminishedReturnsScoreRingBuffer(int readIndex, int writeIndex,
+ long[] nanoTimeRingBuffer, @Nullable Score_[] scoreRingBuffer) {
+ this.nanoTimeRingBuffer = nanoTimeRingBuffer;
+ this.scoreRingBuffer = scoreRingBuffer;
+ this.readIndex = readIndex;
+ this.writeIndex = writeIndex;
+ }
+
+ record RingBufferState(int readIndex, int writeIndex,
+ long[] nanoTimeRingBuffer, @Nullable Score<?>[] scoreRingBuffer) {
+ @Override
+ public boolean equals(Object o) {
+ if (!(o instanceof RingBufferState that)) {
+ return false;
+ }
+ return readIndex == that.readIndex && writeIndex == that.writeIndex && Objects.deepEquals(nanoTimeRingBuffer,
+ that.nanoTimeRingBuffer) && Objects.deepEquals(scoreRingBuffer, that.scoreRingBuffer);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(readIndex, writeIndex, Arrays.hashCode(nanoTimeRingBuffer), Arrays.hashCode(scoreRingBuffer));
+ }
+
+ @Override
+ public String toString() {
+ return "RingBufferState{" +
+ "readIndex=" + readIndex +
+ ", writeIndex=" + writeIndex +
+ ", nanoTimeRingBuffer=" + Arrays.toString(nanoTimeRingBuffer) +
+ ", scoreRingBuffer=" + Arrays.toString(scoreRingBuffer) +
+ '}';
+ }
+ }
+
+ @NonNull
+ RingBufferState getState() {
+ return new RingBufferState(readIndex, writeIndex, nanoTimeRingBuffer, scoreRingBuffer);
+ }
+
+ void resize() {
+ var newCapacity = nanoTimeRingBuffer.length * 2;
+ var newNanoTimeRingBuffer = new long[newCapacity];
+ @SuppressWarnings("unchecked")
+ var newScoreRingBuffer = (Score_[]) new Score[newCapacity];
+
+ if (readIndex < writeIndex) {
+ // entries are [startIndex, writeIndex)
+ var newLength = writeIndex - readIndex;
+ System.arraycopy(nanoTimeRingBuffer, readIndex, newNanoTimeRingBuffer, 0, newLength);
+ System.arraycopy(scoreRingBuffer, readIndex, newScoreRingBuffer, 0, newLength);
+ readIndex = 0;
+ writeIndex = newLength;
+ } else {
+ // entries are [readIndex, CAPACITY) + [0, writeIndex)
+ var firstLength = nanoTimeRingBuffer.length - readIndex;
+ var secondLength = writeIndex;
+ var totalLength = firstLength + secondLength;
+
+ System.arraycopy(nanoTimeRingBuffer, readIndex, newNanoTimeRingBuffer, 0, firstLength);
+ System.arraycopy(scoreRingBuffer, readIndex, newScoreRingBuffer, 0, firstLength);
+ System.arraycopy(nanoTimeRingBuffer, 0, newNanoTimeRingBuffer, firstLength, secondLength);
+ System.arraycopy(scoreRingBuffer, 0, newScoreRingBuffer, firstLength, secondLength);
+ readIndex = 0;
+ writeIndex = totalLength;
+ }
+ nanoTimeRingBuffer = newNanoTimeRingBuffer;
+ scoreRingBuffer = newScoreRingBuffer;
+ }
+
+ public void clear() {
+ readIndex = 0;
+ writeIndex = 0;
+ Arrays.fill(nanoTimeRingBuffer, 0);
+ Arrays.fill(scoreRingBuffer, null);
+ }
+
+ /**
+ * Returns the first element of the score ring buffer.
+ * Does not remove the element.
+ *
+ * @return the first element of the score ring buffer
+ */
+ public @NonNull Score_ peekFirst() {
+ return scoreRingBuffer[readIndex];
+ }
+
+ /**
+ * Adds a time-score pairing to the ring buffers, resizing the
+ * ring buffers if necessary.
+ *
+ * @param nanoTime the {@link System#nanoTime()} when the score was produced.
+ * @param score the score that was produced.
+ */
+ public void put(long nanoTime, @NonNull Score_ score) {
+ if (nanoTimeRingBuffer[writeIndex] != 0L) {
+ resize();
+ }
+ nanoTimeRingBuffer[writeIndex] = nanoTime;
+ scoreRingBuffer[writeIndex] = score;
+ writeIndex = (writeIndex + 1) % nanoTimeRingBuffer.length;
+ }
+
+ /**
+ * Removes count elements from both ring buffers,
+ * and returns the next element (which remains in the buffers).
+ *
+ * @param count the number of items to remove from both buffers.
+ * @return the first element in the score ring buffer after the count
+ * elements were removed.
+ */
+ private @NonNull Score_ clearCountAndPeekNext(int count) {
+ if (readIndex + count < nanoTimeRingBuffer.length) {
+ Arrays.fill(nanoTimeRingBuffer, readIndex, readIndex + count, 0L);
+ Arrays.fill(scoreRingBuffer, readIndex, readIndex + count, null);
+ readIndex += count;
+ } else {
+ int remaining = count - (nanoTimeRingBuffer.length - readIndex);
+ Arrays.fill(nanoTimeRingBuffer, readIndex, nanoTimeRingBuffer.length, 0L);
+ Arrays.fill(scoreRingBuffer, readIndex, nanoTimeRingBuffer.length, null);
+ Arrays.fill(nanoTimeRingBuffer, 0, remaining, 0L);
+ Arrays.fill(scoreRingBuffer, 0, remaining, null);
+ readIndex = remaining;
+ }
+ return scoreRingBuffer[readIndex];
+ }
+
+ /**
+ * Returns the latest score prior or at the given time, and removes
+ * all time-score pairings prior to it.
+ *
+ * @param nanoTime the queried time in nanoseconds.
+ * @return the latest score prior to the given time.
+ */
+ public @NonNull Score_ pollLatestScoreBeforeTimeAndClearPrior(long nanoTime) {
+ if (readIndex == writeIndex && nanoTimeRingBuffer[writeIndex] == 0L) {
+ throw new IllegalStateException("Ring buffer is empty"); | Do you want to treat this as an exception? I see two options here:
- Either this is an exceptional state which must not happen, because the algorithm would not be correct. Then the message should start with "Impossible state: ", and I'm going to argue it should be thrown by the code calling this method, not by this method directly.
- Or this is a totally possible state, which we just want to signal to the calling code. In that case, this exception should be replaced by a return on `null` - see our previous conversation on exceptions and control flow. |
timefold-solver | github_2023 | java | 1,313 | TimefoldAI | triceo | @@ -0,0 +1,179 @@
+package ai.timefold.solver.core.impl.solver.termination;
+
+import ai.timefold.solver.core.api.score.Score;
+import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
+import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope;
+import ai.timefold.solver.core.impl.solver.scope.SolverScope;
+import ai.timefold.solver.core.impl.solver.thread.ChildThreadType;
+
+import org.jspecify.annotations.NonNull;
+
+public final class DiminishedReturnsTermination<Solution_, Score_ extends Score<Score_>>
+ extends AbstractTermination<Solution_> {
+ static final long NANOS_PER_MILLISECOND = 1_000_000;
+
+ private final long slidingWindowNanos; | If the length of the window was a `Duration` (see my comment on the termination config), then you could avoid this and just call `slidingWindowDuration.toMillis()`. |
timefold-solver | github_2023 | java | 1,313 | TimefoldAI | triceo | @@ -0,0 +1,179 @@
+package ai.timefold.solver.core.impl.solver.termination;
+
+import ai.timefold.solver.core.api.score.Score;
+import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope;
+import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope;
+import ai.timefold.solver.core.impl.solver.scope.SolverScope;
+import ai.timefold.solver.core.impl.solver.thread.ChildThreadType;
+
+import org.jspecify.annotations.NonNull;
+
+public final class DiminishedReturnsTermination<Solution_, Score_ extends Score<Score_>>
+ extends AbstractTermination<Solution_> {
+ static final long NANOS_PER_MILLISECOND = 1_000_000;
+
+ private final long slidingWindowNanos;
+ private final double minimumImprovementRatio;
+
+ private boolean isGracePeriodActive;
+ private long gracePeriodStartTimeNanos;
+ private double gracePeriodSoftestImprovementDouble;
+
+ private final DiminishedReturnsScoreRingBuffer<Score_> scoresByTime;
+
+ public DiminishedReturnsTermination(long slidingWindowMillis, double minimumImprovementRatio) {
+ if (slidingWindowMillis < 0L) {
+ throw new IllegalArgumentException("The slidingWindowMillis (%d) cannot be negative."
+ .formatted(slidingWindowMillis));
+ }
+
+ if (minimumImprovementRatio <= 0.0) {
+ throw new IllegalArgumentException("The minimumImprovementRatio (%f) must be positive."
+ .formatted(minimumImprovementRatio));
+ }
+
+ // convert to nanoseconds here so we don't need to do a
+ // division in the hot loop
+ this.slidingWindowNanos = slidingWindowMillis * NANOS_PER_MILLISECOND;
+ this.minimumImprovementRatio = minimumImprovementRatio;
+ this.scoresByTime = new DiminishedReturnsScoreRingBuffer<>();
+ }
+
+ public long getSlidingWindowNanos() {
+ return slidingWindowNanos;
+ }
+
+ public double getMinimumImprovementRatio() {
+ return minimumImprovementRatio;
+ }
+
+ /**
+ * Returns the improvement in the softest level between the prior
+ * and current best scores as a double, or {@link Double#NaN} if
+ * there is a difference in any of their other levels.
+ *
+ * @param start the prior best score
+ * @param end the current best score
+ * @return the softest level difference between end and start, or
+ * {@link Double#NaN} if a harder level changed
+ * @param <Score_> The score type
+ */
+ private static <Score_ extends Score<Score_>> double softImprovementOrNaNForHarderChange(@NonNull Score_ start,
+ @NonNull Score_ end) {
+ if (start.equals(end)) {
+ // optimization: since most of the time the score the same,
+ // we can use equals to avoid creating double arrays in the
+ // vast majority of comparisons
+ return 0.0;
+ }
+ if (start.initScore() != end.initScore()) {
+ // init score improved
+ return Double.NaN;
+ }
+ var scoreDiffs = end.subtract(start).toLevelDoubles();
+ var softestLevel = scoreDiffs.length - 1;
+ for (int i = 0; i < softestLevel; i++) {
+ if (scoreDiffs[i] != 0.0) {
+ return Double.NaN;
+ }
+ }
+ return scoreDiffs[softestLevel];
+ }
+
+ public void start(long startTime, Score_ startingScore) {
+ resetGracePeriod(startTime, startingScore);
+ }
+
+ public void step(long time, Score_ bestScore) {
+ scoresByTime.put(time, bestScore);
+ }
+
+ private void resetGracePeriod(long currentTime, Score_ startingScore) {
+ gracePeriodStartTimeNanos = currentTime;
+ isGracePeriodActive = true;
+
+ // Remove all entries in the map since grace is reset
+ scoresByTime.clear();
+
+ // Put the current best score as the first entry
+ scoresByTime.put(currentTime, startingScore);
+ }
+
+ public boolean isTerminated(long currentTime, Score_ endScore) {
+ if (isGracePeriodActive) {
+ // first score in scoresByTime = first score in grace period window
+ var endpointDiff = softImprovementOrNaNForHarderChange(scoresByTime.peekFirst(), endScore);
+ if (Double.isNaN(endpointDiff)) {
+ resetGracePeriod(currentTime, endScore);
+ return false;
+ }
+ var timeElapsedNanos = currentTime - gracePeriodStartTimeNanos;
+ if (timeElapsedNanos >= slidingWindowNanos) {
+ // grace period over, record the reference diff
+ isGracePeriodActive = false;
+ gracePeriodSoftestImprovementDouble = endpointDiff;
+ if (endpointDiff < 0.0) {
+ // Should be impossible; the only cases where the best score improves
+ // and have a lower softest level are if either a harder level or init score
+ // improves, but if that happens, we reset the grace period.
+ throw new IllegalStateException("The score deteriorated from (%s) to (%s) during the grace period." | ```suggestion
throw new IllegalStateException("Impossible state: The score deteriorated from (%s) to (%s) during the grace period."
``` |
timefold-solver | github_2023 | java | 1,313 | TimefoldAI | triceo | @@ -122,6 +122,19 @@ The termination with bestScoreFeasible (%s) can only be used with a score type \
+ unimprovedTimeMillisSpentLimit + ") is used too.");
}
+ if (terminationConfig.getDiminishedReturnsConfig() != null) {
+ var adaptiveTerminationConfig = terminationConfig.getDiminishedReturnsConfig();
+ var gracePeriodMillis = adaptiveTerminationConfig.calculateSlidingWindowMilliseconds();
+ if (gracePeriodMillis == null) {
+ gracePeriodMillis = 30_000L;
+ }
+ var minimumImprovementRatio = adaptiveTerminationConfig.getMinimumImprovementRatio();
+ if (minimumImprovementRatio == null) {
+ minimumImprovementRatio = 0.01; | See Slack thread on the "correct" default value. |
timefold-solver | github_2023 | java | 1,313 | TimefoldAI | triceo | @@ -48,6 +48,9 @@ private static String getRequiredProperty(String name) {
.overrideConfigKey("quarkus.timefold.solver.termination.best-score-limit", "0")
.overrideConfigKey("quarkus.timefold.solver.move-thread-count", "4")
.overrideConfigKey("quarkus.timefold.solver-manager.parallel-solver-count", "1")
+ .overrideConfigKey("quarkus.timefold.solver.termination.diminished-returns.enabled", "false") | Arguably this is not necessary, if either of the other two properties is present? |
timefold-solver | github_2023 | java | 1,313 | TimefoldAI | triceo | @@ -0,0 +1,24 @@
+package ai.timefold.solver.quarkus;
+
+class TimefoldProcessorXMLDiminishedReturnsTest { | Delete or finish? |
timefold-solver | github_2023 | java | 1,313 | TimefoldAI | triceo | @@ -0,0 +1,44 @@
+package ai.timefold.solver.quarkus.config;
+
+import java.time.Duration;
+import java.util.Optional;
+
+import io.quarkus.runtime.annotations.ConfigGroup;
+
+@ConfigGroup
+public interface DiminishedReturnsRuntimeConfig {
+ /**
+ * If set to true, adds a termination to the local search
+ * phase that records the initial improvement after a duration,
+ * and terminates when the ratio new improvement/initial improvement
+ * is below a specified ratio.
+ */
+ Optional<Boolean> enabled();
+
+ /**
+ * Specifies the best score from how long ago should the current best
+ * score be compared to.
+ * For "30s", the current best score is compared against
+ * the best score from 30 seconds ago to calculate the improvement.
+ * "5m" is 5 minutes. "2h" is 2 hours. "1d" is 1 day.
+ * Also supports ISO-8601 format, see {@link Duration}.
+ * <br/>
+ * Default to 30s.
+ */
+ Optional<Duration> slidingWindowDuration();
+
+ /**
+ * Specifies the minimum ratio between the current improvement and the
+ * initial improvement. Must be positive.
+ * <br/>
+ * For example, if the {@link #slidingWindowDuration} is "30s",
+ * the {@link #minimumImprovementRatio} is 0.25, and the
+ * score improves by 100soft during the first 30 seconds of local search,
+ * then the local search phase will terminate when the difference between
+ * the current best score and the best score from 30 seconds ago is less than
+ * 25soft (= 0.25 * 100soft).
+ * <br/>
+ * Defaults to 0.1.
+ */
+ Optional<Double> minimumImprovementRatio(); | `OptionalDouble` exists.
(For some reason, `OptionalBoolean` does not.) |
timefold-solver | github_2023 | java | 1,313 | TimefoldAI | triceo | @@ -0,0 +1,44 @@
+package ai.timefold.solver.quarkus.config;
+
+import java.time.Duration;
+import java.util.Optional;
+
+import io.quarkus.runtime.annotations.ConfigGroup;
+
+@ConfigGroup
+public interface DiminishedReturnsRuntimeConfig {
+ /**
+ * If set to true, adds a termination to the local search
+ * phase that records the initial improvement after a duration,
+ * and terminates when the ratio new improvement/initial improvement
+ * is below a specified ratio.
+ */
+ Optional<Boolean> enabled();
+
+ /**
+ * Specifies the best score from how long ago should the current best
+ * score be compared to.
+ * For "30s", the current best score is compared against
+ * the best score from 30 seconds ago to calculate the improvement.
+ * "5m" is 5 minutes. "2h" is 2 hours. "1d" is 1 day.
+ * Also supports ISO-8601 format, see {@link Duration}.
+ * <br/>
+ * Default to 30s.
+ */
+ Optional<Duration> slidingWindowDuration();
+
+ /**
+ * Specifies the minimum ratio between the current improvement and the
+ * initial improvement. Must be positive.
+ * <br/>
+ * For example, if the {@link #slidingWindowDuration} is "30s",
+ * the {@link #minimumImprovementRatio} is 0.25, and the
+ * score improves by 100soft during the first 30 seconds of local search,
+ * then the local search phase will terminate when the difference between
+ * the current best score and the best score from 30 seconds ago is less than
+ * 25soft (= 0.25 * 100soft).
+ * <br/>
+ * Defaults to 0.1. | Please remember to update. |
timefold-solver | github_2023 | others | 1,313 | TimefoldAI | triceo | @@ -637,6 +637,126 @@ This is useful for benchmarking.
Switching xref:using-timefold-solver/running-the-solver.adoc#environmentMode[EnvironmentMode] can heavily impact when this termination ends.
+[#diminishedReturnsTermination]
+==== `DiminishedReturnsTermination`
+
+Terminates when the rate of improvement is below a percentage of the initial rate of improvement.
+The rate of improvement is the score difference between the final best score and the initial best score in a window, divided by the duration of the window. | I think we should talk about the softest score here. |
timefold-solver | github_2023 | others | 1,313 | TimefoldAI | triceo | @@ -637,6 +637,126 @@ This is useful for benchmarking.
Switching xref:using-timefold-solver/running-the-solver.adoc#environmentMode[EnvironmentMode] can heavily impact when this termination ends.
+[#diminishedReturnsTermination]
+==== `DiminishedReturnsTermination`
+
+Terminates when the rate of improvement is below a percentage of the initial rate of improvement.
+The rate of improvement is the score difference between the final best score and the initial best score in a window, divided by the duration of the window.
+The first window is called a grace period, which cannot trigger a termination.
+
+image::optimization-algorithms/overview/diminishedReturnsTermination.png[align="center"]
+
+[NOTE]
+====
+If the hard score improves, the grace period is reset and the initial rate of improvement is recalculated.
+==== | Since this is a core part of the algorithm, I don't think it should be a NOTE. Rather, a normal text like everything else.
Also, the above comment about the softest score will pay off here, where we talk about the hard score all of a sudden. |
timefold-solver | github_2023 | others | 1,313 | TimefoldAI | triceo | @@ -637,6 +637,126 @@ This is useful for benchmarking.
Switching xref:using-timefold-solver/running-the-solver.adoc#environmentMode[EnvironmentMode] can heavily impact when this termination ends.
+[#diminishedReturnsTermination]
+==== `DiminishedReturnsTermination`
+
+Terminates when the rate of improvement is below a percentage of the initial rate of improvement.
+The rate of improvement is the score difference between the final best score and the initial best score in a window, divided by the duration of the window.
+The first window is called a grace period, which cannot trigger a termination.
+
+image::optimization-algorithms/overview/diminishedReturnsTermination.png[align="center"]
+
+[NOTE]
+====
+If the hard score improves, the grace period is reset and the initial rate of improvement is recalculated.
+====
+
+[source,xml,options="nowrap"]
+----
+ <localSearch>
+ <termination>
+ <diminishedReturns />
+ </termination>
+ </localSearch>
+----
+
+There are two properties that can optionally be configured:
+
+* `slidingWindowDuration`, which is the initial grace period and is the length of the window that is used for the rate of improvement calculation.
++
+[source,xml,options="nowrap"]
+----
+ <localSearch>
+ <termination>
+ <diminishedReturns>
+ <slidingWindowDuration>PT2M30S</slidingWindowDuration>
+ </diminishedReturns>
+ </termination>
+ </localSearch>
+----
+
+Alternatively to a `java.util.Duration` in ISO 8601 format, you can also use:
++
+** Milliseconds
++
+[source,xml,options="nowrap"]
+----
+ <localSearch>
+ <termination>
+ <diminishedReturns>
+ <slidingWindowMilliseconds>500</slidingWindowMilliseconds>
+ </diminishedReturns>
+ </termination>
+ </localSearch>
+----
++
+** Seconds
++
+[source,xml,options="nowrap"]
+----
+ <localSearch>
+ <termination>
+ <diminishedReturns>
+ <slidingWindowSeconds>500</slidingWindowSeconds>
+ </diminishedReturns>
+ </termination>
+ </localSearch>
+---- | I consider this section too verbose. It's IMO enough to show the duration and the seconds, and then mention we also support the others. |
timefold-solver | github_2023 | others | 1,313 | TimefoldAI | triceo | @@ -637,6 +637,126 @@ This is useful for benchmarking.
Switching xref:using-timefold-solver/running-the-solver.adoc#environmentMode[EnvironmentMode] can heavily impact when this termination ends.
+[#diminishedReturnsTermination]
+==== `DiminishedReturnsTermination`
+
+Terminates when the rate of improvement is below a percentage of the initial rate of improvement.
+The rate of improvement is the score difference between the final best score and the initial best score in a window, divided by the duration of the window.
+The first window is called a grace period, which cannot trigger a termination.
+
+image::optimization-algorithms/overview/diminishedReturnsTermination.png[align="center"]
+
+[NOTE]
+====
+If the hard score improves, the grace period is reset and the initial rate of improvement is recalculated.
+====
+
+[source,xml,options="nowrap"]
+----
+ <localSearch>
+ <termination>
+ <diminishedReturns />
+ </termination>
+ </localSearch>
+----
+
+There are two properties that can optionally be configured:
+
+* `slidingWindowDuration`, which is the initial grace period and is the length of the window that is used for the rate of improvement calculation.
++
+[source,xml,options="nowrap"]
+----
+ <localSearch>
+ <termination>
+ <diminishedReturns>
+ <slidingWindowDuration>PT2M30S</slidingWindowDuration>
+ </diminishedReturns>
+ </termination>
+ </localSearch>
+----
+
+Alternatively to a `java.util.Duration` in ISO 8601 format, you can also use:
++
+** Milliseconds
++
+[source,xml,options="nowrap"]
+----
+ <localSearch>
+ <termination>
+ <diminishedReturns>
+ <slidingWindowMilliseconds>500</slidingWindowMilliseconds>
+ </diminishedReturns>
+ </termination>
+ </localSearch>
+----
++
+** Seconds
++
+[source,xml,options="nowrap"]
+----
+ <localSearch>
+ <termination>
+ <diminishedReturns>
+ <slidingWindowSeconds>500</slidingWindowSeconds>
+ </diminishedReturns>
+ </termination>
+ </localSearch>
+----
++
+** Minutes
++
+[source,xml,options="nowrap"]
+----
+ <localSearch>
+ <termination>
+ <diminishedReturns>
+ <slidingWindowMinutes>500</slidingWindowMinutes>
+ </diminishedReturns>
+ </termination>
+ </localSearch>
+----
++
+** Hours
++
+[source,xml,options="nowrap"]
+----
+ <localSearch>
+ <termination>
+ <diminishedReturns>
+ <slidingWindowHours>500</slidingWindowHours>
+ </diminishedReturns>
+ </termination>
+ </localSearch>
+----
++
+** Days
++
+[source,xml,options="nowrap"]
+----
+ <localSearch>
+ <termination>
+ <diminishedReturns>
+ <slidingWindowDays>500</slidingWindowDays>
+ </diminishedReturns>
+ </termination>
+ </localSearch>
+----
+
+* `minimumImprovementRatio`, which is the minimum value that the ratio between the current and the initial rate of change can be to prevent termination.
+For instance, if `minimumImprovementRatio` is `0.2`, then the current rate of change must be `20%` of the initial rate of change to prevent termination.
++
+[source,xml,options="nowrap"]
+----
+ <localSearch>
+ <termination>
+ <diminishedReturns>
+ <minimumImprovementRatio>0.2</minimumImprovementRatio>
+ </diminishedReturns>
+ </termination>
+ </localSearch>
+----
+
+This `Termination` can only be used for a `Phase` (such as ``<localSearch>``), not for the `Solver` itself. | I'd invert this statement - this termination cannot be used globally on the solver, only on a phase, and not on a CH phase. |
timefold-solver | github_2023 | others | 1,313 | TimefoldAI | triceo | @@ -637,6 +637,126 @@ This is useful for benchmarking.
Switching xref:using-timefold-solver/running-the-solver.adoc#environmentMode[EnvironmentMode] can heavily impact when this termination ends.
+[#diminishedReturnsTermination]
+==== `DiminishedReturnsTermination`
+
+Terminates when the rate of improvement is below a percentage of the initial rate of improvement.
+The rate of improvement is the score difference between the final best score and the initial best score in a window, divided by the duration of the window.
+The first window is called a grace period, which cannot trigger a termination.
+
+image::optimization-algorithms/overview/diminishedReturnsTermination.png[align="center"]
+
+[NOTE]
+====
+If the hard score improves, the grace period is reset and the initial rate of improvement is recalculated.
+====
+
+[source,xml,options="nowrap"]
+----
+ <localSearch>
+ <termination>
+ <diminishedReturns />
+ </termination>
+ </localSearch>
+----
+
+There are two properties that can optionally be configured:
+
+* `slidingWindowDuration`, which is the initial grace period and is the length of the window that is used for the rate of improvement calculation.
++
+[source,xml,options="nowrap"]
+----
+ <localSearch>
+ <termination>
+ <diminishedReturns>
+ <slidingWindowDuration>PT2M30S</slidingWindowDuration>
+ </diminishedReturns>
+ </termination>
+ </localSearch>
+----
+
+Alternatively to a `java.util.Duration` in ISO 8601 format, you can also use:
++
+** Milliseconds
++
+[source,xml,options="nowrap"]
+----
+ <localSearch>
+ <termination>
+ <diminishedReturns>
+ <slidingWindowMilliseconds>500</slidingWindowMilliseconds>
+ </diminishedReturns>
+ </termination>
+ </localSearch>
+----
++
+** Seconds
++
+[source,xml,options="nowrap"]
+----
+ <localSearch>
+ <termination>
+ <diminishedReturns>
+ <slidingWindowSeconds>500</slidingWindowSeconds>
+ </diminishedReturns>
+ </termination>
+ </localSearch>
+----
++
+** Minutes
++
+[source,xml,options="nowrap"]
+----
+ <localSearch>
+ <termination>
+ <diminishedReturns>
+ <slidingWindowMinutes>500</slidingWindowMinutes>
+ </diminishedReturns>
+ </termination>
+ </localSearch>
+----
++
+** Hours
++
+[source,xml,options="nowrap"]
+----
+ <localSearch>
+ <termination>
+ <diminishedReturns>
+ <slidingWindowHours>500</slidingWindowHours>
+ </diminishedReturns>
+ </termination>
+ </localSearch>
+----
++
+** Days
++
+[source,xml,options="nowrap"]
+----
+ <localSearch>
+ <termination>
+ <diminishedReturns>
+ <slidingWindowDays>500</slidingWindowDays>
+ </diminishedReturns>
+ </termination>
+ </localSearch>
+----
+
+* `minimumImprovementRatio`, which is the minimum value that the ratio between the current and the initial rate of change can be to prevent termination.
+For instance, if `minimumImprovementRatio` is `0.2`, then the current rate of change must be `20%` of the initial rate of change to prevent termination.
++
+[source,xml,options="nowrap"]
+----
+ <localSearch>
+ <termination>
+ <diminishedReturns>
+ <minimumImprovementRatio>0.2</minimumImprovementRatio>
+ </diminishedReturns>
+ </termination>
+ </localSearch>
+----
+
+This `Termination` can only be used for a `Phase` (such as ``<localSearch>``), not for the `Solver` itself.
[#combiningMultipleTerminations] | I'd mention that the termination can run for a very long time, and add a recommendation to combine the termination with a maximum time spent, to ensure it doesn't run for longer than acceptable.
Do we have a test for this? When I was toying with the termination, I saw some weird behavior where a composite termination wasn't working properly. |
timefold-solver | github_2023 | others | 1,313 | TimefoldAI | triceo | @@ -637,6 +637,126 @@ This is useful for benchmarking.
Switching xref:using-timefold-solver/running-the-solver.adoc#environmentMode[EnvironmentMode] can heavily impact when this termination ends.
+[#diminishedReturnsTermination]
+==== `DiminishedReturnsTermination` | I'd start with an introductory paragraph explaining why we've done this. Absolute terminations are hard to configure, because they either depend on hardware (time-based) or on the problem (score-based). The relative termination doesn't have this problem. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.