repo_name
stringlengths
1
62
dataset
stringclasses
1 value
lang
stringclasses
11 values
pr_id
int64
1
20.1k
owner
stringlengths
2
34
reviewer
stringlengths
2
39
diff_hunk
stringlengths
15
262k
code_review_comment
stringlengths
1
99.6k
timefold-solver
github_2023
others
1,099
TimefoldAI
zepfred
@@ -3,22 +3,20 @@ _Planning optimization made easy._ [timefold.ai](https://timefold.ai) -[![PyPI](https://img.shields.io/pypi/v/timefold?style=for-the-badge& "PyPI")](https://pypi.org/project/timefold/) -[![License](https://img.shields.io/github/license/TimefoldAI/timefold-solver?style=for-the-badge&logo=apache)](https://www.apache.org/licenses/LICENSE-2.0) -[![JVM support](https://img.shields.io/badge/Java-17+-brightgreen.svg?style=for-the-badge)](https://sdkman.io) -[![Python support](https://img.shields.io/badge/Python-3.10+-brightgreen.svg?style=for-the-badge)](https://www.python.org/downloads) -[![Commit Activity](https://img.shields.io/github/commit-activity/m/TimefoldAI/timefold-solver?label=commits&style=for-the-badge)](https://github.com/TimefoldAI/timefold-solver/pulse) - -[![Stackoverflow](https://img.shields.io/badge/stackoverflow-ask_question-orange.svg?logo=stackoverflow&style=for-the-badge)](https://stackoverflow.com/questions/tagged/timefold) +[![Stackoverflow](https://img.shields.io/badge/stackoverflow-ask_question-orange.svg?logo=stackoverflow&style=for-the-badge)](https://stackoverflow.com/questions/tagged/timefold) [![GitHub Discussions](https://img.shields.io/github/discussions/TimefoldAI/timefold-solver?style=for-the-badge&logo=github)](https://github.com/TimefoldAI/timefold-solver/discussions) -[![GitHub Issues](https://img.shields.io/github/issues/TimefoldAI/timefold-solver?style=for-the-badge&logo=github)](https://github.com/TimefoldAI/timefold-solver/issues) + +[![PyPI](https://img.shields.io/pypi/v/timefold?style=for-the-badge& "PyPI")](https://pypi.org/project/timefold/) +[![Python support](https://img.shields.io/badge/Python-3.10+-brightgreen.svg?style=for-the-badge)](https://www.python.org/downloads) +[![License](https://img.shields.io/github/license/TimefoldAI/timefold-solver?style=for-the-badge&logo=apache)](https://www.apache.org/licenses/LICENSE-2.0) [![Reliability Rating](https://sonarcloud.io/api/project_badges/measure?project=ai.timefold:timefold-solver&metric=reliability_rating)](https://sonarcloud.io/summary/new_code?id=ai.timefold:timefold-solver) [![Security Rating](https://sonarcloud.io/api/project_badges/measure?project=ai.timefold:timefold-solver&metric=security_rating)](https://sonarcloud.io/summary/new_code?id=ai.timefold:timefold-solver) [![Maintainability Rating](https://sonarcloud.io/api/project_badges/measure?project=ai.timefold:timefold-solver&metric=sqale_rating)](https://sonarcloud.io/summary/new_code?id=ai.timefold:timefold-solver) [![Coverage](https://sonarcloud.io/api/project_badges/measure?project=ai.timefold:timefold-solver&metric=coverage)](https://sonarcloud.io/summary/new_code?id=ai.timefold:timefold-solver) -Timefold Solver for Python is an AI constraint solver to optimize + +Timefold Solver for Python is an AI constraint solver you can use to optimize the Vehicle Routing Problem, Employee Rostering, Maintenance Scheduling, Task Assignment, School Timetabling, Cloud Optimization, Conference Scheduling, Job Shop Scheduling and many more planning problems.
Let's make the "get started" title consistent: `## Get started with Timefold Solver in Python`
timefold-solver
github_2023
java
1,095
TimefoldAI
zepfred
@@ -0,0 +1,95 @@ +package ai.timefold.solver.core.impl.heuristic.selector.move.generic; + +import static ai.timefold.solver.core.impl.testdata.util.PlannerTestUtils.mockRebasingScoreDirector; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.SoftAssertions.assertSoftly; +import static org.mockito.Mockito.mock; + +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Set; + +import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; +import ai.timefold.solver.core.impl.solver.scope.SolverScope; +import ai.timefold.solver.core.impl.testdata.domain.TestdataEntity; +import ai.timefold.solver.core.impl.testdata.domain.TestdataSolution; +import ai.timefold.solver.core.impl.testdata.domain.TestdataValue; + +import org.junit.jupiter.api.Test; + +class RuinRecreateMoveTest {
Should we add multithreading tests using the R&R moves?
timefold-solver
github_2023
java
1,084
TimefoldAI
triceo
@@ -62,6 +65,11 @@ void consumeFirstInitializedSolution(Solution_ firstInitializedSolution) { scheduleFirstInitializedSolutionConsumption(); } + // Called on the solver thread when it starts + void triggerStartSolverJob() {
Shouldn't this run on a different thread? The solver thread cannot be blocked by user code. Have you seen what platform does in the listeners? It's heavy.
timefold-solver
github_2023
java
1,084
TimefoldAI
triceo
@@ -81,6 +81,14 @@ default SolverJobBuilder<Solution_, ProblemId_> withProblem(Solution_ problem) { SolverJobBuilder<Solution_, ProblemId_> withFirstInitializedSolutionConsumer(Consumer<? super Solution_> firstInitializedSolutionConsumer); + /** + * Sets the runnable action for when the solver starts its solving process. + * + * @param startSolverJobHandler never null, called only once when the solver is starting the solving process + * @return this, never null + */ + SolverJobBuilder<Solution_, ProblemId_> withStartSolverJobHandler(Runnable startSolverJobHandler);
I'm wondering... how do I find out which job is starting? Maybe we want to replace `Runnable` with something that can give some context? Not sure.
timefold-solver
github_2023
java
1,084
TimefoldAI
triceo
@@ -306,4 +311,24 @@ public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) { } } } + + /** + * A listener that is triggered once when the solver starts the solving process. + */ + private final class StartSolverJobPhaseLifecycleListener extends PhaseLifecycleListenerAdapter<Solution_> {
`SolverLifecycleListenerAdapter` can listen to `solvingStarted` events. This is what you should listen to, instead of reading the phases.
timefold-solver
github_2023
java
1,084
TimefoldAI
triceo
@@ -170,10 +175,12 @@ public void terminateEarly(ProblemId_ problemId) { public void close() { solverThreadPool.shutdownNow(); problemIdToSolverJobMap.values().forEach(DefaultSolverJob::close); + resourcesToRelease.forEach(DefaultSolverJob::close); } void unregisterSolverJob(ProblemId_ problemId) { - problemIdToSolverJobMap.remove(getProblemIdOrThrow(problemId)); + var job = problemIdToSolverJobMap.remove(getProblemIdOrThrow(problemId)); + resourcesToRelease.add(job);
This creates a bit of a memory leak for as long as the solver manager is alive. If we're unregistering the job, why not close it immediately? We should only remember the jobs that are never unregistered.
timefold-solver
github_2023
java
1,091
TimefoldAI
zepfred
@@ -297,33 +292,29 @@ protected void setCalculatedScore(Score_ score) { calculationCount++; } + /** + * @deprecated Unused, but kept for backward compatibility. + */ + @Deprecated(forRemoval = true, since = "1.14.0") @Override public AbstractScoreDirector<Solution_, Score_, Factory_> clone() { - // Breaks incremental score calculation. - // Subclasses should overwrite this method to avoid breaking it if possible. - AbstractScoreDirector<Solution_, Score_, Factory_> clone = - (AbstractScoreDirector<Solution_, Score_, Factory_>) scoreDirectorFactory - .buildScoreDirector(lookUpEnabled, constraintMatchEnabledPreference); - clone.setWorkingSolution(cloneWorkingSolution()); - return clone; + throw new UnsupportedOperationException("Cloning score directors is not supported.");
Should we update the `upgrade-to-latest-version.adoc` file to include information about this breaking change?
timefold-solver
github_2023
java
1,091
TimefoldAI
zepfred
@@ -228,17 +230,6 @@ default Score_ doAndProcessMove(Move<Solution_> move, boolean assertMoveScoreFro */ SupplyManager getSupplyManager(); - /**
Should we deprecate it before removing it?
timefold-solver
github_2023
java
1,091
TimefoldAI
zepfred
@@ -81,18 +98,32 @@ public BavetConstraintSession<Score_> buildSession(Solution_ workingSolution, bo castConstraint.collectActiveConstraintStreams(constraintStreamSet); constraintWeightMap.put(constraint, constraintWeight); } else {
```suggestion } else if (constraintWeightLoggingEnabled) { ```
timefold-solver
github_2023
python
1,082
TimefoldAI
zepfred
@@ -277,6 +277,22 @@ def register_java_class(python_object: Solution_, return python_object +def wrap_errors(func):
Is there any test case covering the change?
timefold-solver
github_2023
java
1,067
TimefoldAI
zepfred
@@ -824,15 +823,33 @@ public int countReinitializableVariables(Object entity) { return count; } - public boolean isMovable(ScoreDirector<Solution_> scoreDirector, Object entity) { + public boolean isMovable(Solution_ workingSolution, Object entity) { return isGenuine() && - (effectiveMovableEntitySelectionFilter == null - || effectiveMovableEntitySelectionFilter.accept(scoreDirector, entity)); + (effectiveMovableEntityFilter == null + || effectiveMovableEntityFilter.test(workingSolution, entity)); } @Override public String toString() { return getClass().getSimpleName() + "(" + entityClass.getName() + ")"; } + @FunctionalInterface
This class appears to be hidden here, and I think it should be moved to a separate package (e.g., ai.timefold.solver.core.impl.heuristic.selector.common.decorator), and it also deserves better documentation.
timefold-solver
github_2023
java
1,067
TimefoldAI
zepfred
@@ -22,7 +21,7 @@ public PinEntityFilter(MemberAccessor memberAccessor) { } @Override - public boolean accept(ScoreDirector<Solution_> scoreDirector, Object entity) { + public boolean test(Solution_ solution, Object entity) {
I understand your point about using BiPredicate, but I'm wondering if MovableFilter should have a contract consistent with SelectionFilter. For example, it could have a method named accept instead of test.
timefold-solver
github_2023
java
1,067
TimefoldAI
zepfred
@@ -26,51 +28,51 @@ final class KOptListMoveSelector<Solution_> extends GenericMoveSelector<Solution private final int[] pickedKDistribution; private ListVariableStateSupply<Solution_> listVariableStateSupply; - private EntityIndependentValueSelector<Solution_> effectiveOriginSelector; - private EntityIndependentValueSelector<Solution_> effectiveValueSelector; + + @Override + public void solvingEnded(SolverScope<Solution_> solverScope) {
Let's move this method below to the constructor.
timefold-solver
github_2023
java
1,067
TimefoldAI
zepfred
@@ -41,41 +43,36 @@ public void solvingStarted(SolverScope<Solution_> solverScope) { var listVariableDescriptor = (ListVariableDescriptor<Solution_>) leftValueSelector.getVariableDescriptor(); var supplyManager = solverScope.getScoreDirector().getSupplyManager(); listVariableStateSupply = supplyManager.demand(listVariableDescriptor.getStateDemand()); - movableLeftValueSelector = filterPinnedListPlanningVariableValuesWithIndex(leftValueSelector, listVariableStateSupply); - movableRightValueSelector = - filterPinnedListPlanningVariableValuesWithIndex(rightValueSelector, listVariableStateSupply); } @Override public void solvingEnded(SolverScope<Solution_> solverScope) { super.solvingEnded(solverScope); listVariableStateSupply = null; - movableLeftValueSelector = null;
I liked the simplification made with the "effective" selectors, and I noted a pattern where we recreate the selectors when the solver starts. You might have already considered this before making the changes, but would it be possible for the selectors to be inconsistent if we don't recreate them when the solver starts?
timefold-solver
github_2023
java
1,060
TimefoldAI
triceo
@@ -372,12 +372,19 @@ public static List<Member> getAllMembers(Class<?> baseClass, Class<? extends Ann .filter(field -> field.isAnnotationPresent(annotationClass) && !field.isSynthetic()) .sorted(alphabeticMemberComparator); var methodStream = Stream.of(clazz.getDeclaredMethods()) - .filter(method -> method.isAnnotationPresent(annotationClass) && !method.isSynthetic()) - .sorted(alphabeticMemberComparator); + .filter(method -> method.isAnnotationPresent(annotationClass) && !method.isSynthetic());
You can filter the entire concated stream at the end, avoiding this duplication.
timefold-solver
github_2023
java
1,060
TimefoldAI
triceo
@@ -372,12 +372,19 @@ public static List<Member> getAllMembers(Class<?> baseClass, Class<? extends Ann .filter(field -> field.isAnnotationPresent(annotationClass) && !field.isSynthetic()) .sorted(alphabeticMemberComparator); var methodStream = Stream.of(clazz.getDeclaredMethods()) - .filter(method -> method.isAnnotationPresent(annotationClass) && !method.isSynthetic()) - .sorted(alphabeticMemberComparator); + .filter(method -> method.isAnnotationPresent(annotationClass) && !method.isSynthetic()); + + for (var implementedInterface : clazz.getInterfaces()) { + methodStream = Stream.concat( + methodStream, + Arrays.stream(implementedInterface.getMethods()) + .filter(method -> method.isAnnotationPresent(annotationClass) && !method.isSynthetic())); + }
Since we're already using stream concatenation, no need to mix normal iteration with it too. Use `flatMap` to achieve the same result.
timefold-solver
github_2023
java
1,060
TimefoldAI
triceo
@@ -372,12 +372,19 @@ public static List<Member> getAllMembers(Class<?> baseClass, Class<? extends Ann .filter(field -> field.isAnnotationPresent(annotationClass) && !field.isSynthetic()) .sorted(alphabeticMemberComparator); var methodStream = Stream.of(clazz.getDeclaredMethods()) - .filter(method -> method.isAnnotationPresent(annotationClass) && !method.isSynthetic()) - .sorted(alphabeticMemberComparator); + .filter(method -> method.isAnnotationPresent(annotationClass) && !method.isSynthetic()); + + for (var implementedInterface : clazz.getInterfaces()) { + methodStream = Stream.concat( + methodStream, + Arrays.stream(implementedInterface.getMethods()) + .filter(method -> method.isAnnotationPresent(annotationClass) && !method.isSynthetic())); + } + methodStream = methodStream.sorted(alphabeticMemberComparator); memberStream = Stream.concat(memberStream, Stream.concat(fieldStream, methodStream)); clazz = clazz.getSuperclass(); } - return memberStream.collect(Collectors.toList()); + return memberStream.distinct().collect(Collectors.toList());
Wouldn't it be better to first distinct and then sort? Either way, both can be done at this final stream, and not on the intermediate streams.
timefold-solver
github_2023
java
1,056
TimefoldAI
triceo
@@ -21,9 +21,9 @@ public ObjectCalculatorBiCollector(BiFunction<? super A, ? super B, ? extends In @Override public TriFunction<Calculator_, A, B, Runnable> accumulator() { return (calculator, a, b) -> { - final Input_ mapped = mapper.apply(a, b); - calculator.insert(mapped); - return () -> calculator.retract(mapped); + final var mapped = mapper.apply(a, b); + final var saved = calculator.insert(mapped);
`final` shouldn't be necessary here. The variable is _effectively final_ without it too.
timefold-solver
github_2023
java
1,056
TimefoldAI
triceo
@@ -23,9 +23,9 @@ public ObjectCalculatorQuadCollector(QuadFunction<? super A, ? super B, ? super @Override public PentaFunction<Calculator_, A, B, C, D, Runnable> accumulator() { return (calculator, a, b, c, d) -> { - final Input_ mapped = mapper.apply(a, b, c, d); - calculator.insert(mapped); - return () -> calculator.retract(mapped); + final var mapped = mapper.apply(a, b, c, d); + final var saved = calculator.insert(mapped);
Dtto.
timefold-solver
github_2023
java
1,056
TimefoldAI
triceo
@@ -21,9 +21,9 @@ public ObjectCalculatorTriCollector(TriFunction<? super A, ? super B, ? super C, @Override public QuadFunction<Calculator_, A, B, C, Runnable> accumulator() { return (calculator, a, b, c) -> { - final Input_ mapped = mapper.apply(a, b, c); - calculator.insert(mapped); - return () -> calculator.retract(mapped); + final var mapped = mapper.apply(a, b, c); + final var saved = calculator.insert(mapped);
Dtto.
timefold-solver
github_2023
java
1,056
TimefoldAI
triceo
@@ -21,9 +21,9 @@ public ObjectCalculatorUniCollector(Function<? super A, ? extends Input_> mapper @Override public BiFunction<Calculator_, A, Runnable> accumulator() { return (calculator, a) -> { - final Input_ mapped = mapper.apply(a); - calculator.insert(mapped); - return () -> calculator.retract(mapped); + final var mapped = mapper.apply(a); + final var saved = calculator.insert(mapped);
Dtto.
timefold-solver
github_2023
java
1,056
TimefoldAI
triceo
@@ -0,0 +1,137 @@ +package ai.timefold.solver.core.impl.score.stream.collector.connected_ranges; + +import java.util.ArrayList; +import java.util.List; + +import ai.timefold.solver.core.api.domain.entity.PlanningEntity; +import ai.timefold.solver.core.api.domain.lookup.PlanningId; +import ai.timefold.solver.core.api.domain.solution.PlanningEntityCollectionProperty; +import ai.timefold.solver.core.api.domain.solution.PlanningScore; +import ai.timefold.solver.core.api.domain.solution.PlanningSolution; +import ai.timefold.solver.core.api.domain.solution.ProblemFactCollectionProperty; +import ai.timefold.solver.core.api.domain.valuerange.CountableValueRange; +import ai.timefold.solver.core.api.domain.valuerange.ValueRangeFactory; +import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider; +import ai.timefold.solver.core.api.domain.variable.PlanningVariable; +import ai.timefold.solver.core.api.score.buildin.hardmediumsoft.HardMediumSoftScore; +import ai.timefold.solver.core.api.score.stream.Constraint; +import ai.timefold.solver.core.api.score.stream.ConstraintCollectors; +import ai.timefold.solver.core.api.score.stream.ConstraintFactory; +import ai.timefold.solver.core.api.score.stream.ConstraintProvider; +import ai.timefold.solver.core.api.score.stream.Joiners; +import ai.timefold.solver.core.api.score.stream.common.ConnectedRangeChain; +import ai.timefold.solver.core.api.solver.SolverFactory; +import ai.timefold.solver.core.config.solver.EnvironmentMode; +import ai.timefold.solver.core.config.solver.SolverConfig; +import ai.timefold.solver.core.config.solver.termination.TerminationConfig; + +import org.junit.jupiter.api.Test; + +public class ConnectedRangeSolvingTest { + public record Equipment(int id, int capacity) { + } + + @PlanningEntity + public static class Job { + private int id; + private int requiredEquipmentId; + private Integer start; + + public Job() { + } + + public Job(int id, int requiredEquipmentId) { + this.id = id; + this.requiredEquipmentId = requiredEquipmentId; + } + + @PlanningId + public int getId() { + return id; + } + + public int getRequiredEquipmentId() { + return requiredEquipmentId; + } + + @PlanningVariable + public Integer getStart() { + return start; + } + + public void setStart(Integer start) { + this.start = start; + } + + public Integer getEnd() { + return start == null ? null : start + 10; + } + } + + @PlanningSolution + public static class Planner { + @PlanningScore + private HardMediumSoftScore score; + + @ProblemFactCollectionProperty + private final List<Equipment> equipments = new ArrayList<>(); + + @PlanningEntityCollectionProperty + private final List<Job> jobs = new ArrayList<>(); + + @ValueRangeProvider + public CountableValueRange<Integer> getStartOffsetRange() { + return ValueRangeFactory.createIntValueRange(0, 100); + } + + public Planner() { + } + + public Planner(List<Equipment> equipments, List<Job> jobs) { + this.equipments.addAll(equipments); + this.jobs.addAll(jobs); + } + } + + public static class MyConstraintProvider implements ConstraintProvider { + public MyConstraintProvider() { + } + + @Override + public Constraint[] defineConstraints(ConstraintFactory constraintFactory) { + return new Constraint[] { doNotOverAssignEquipment(constraintFactory) }; + } + + public Constraint doNotOverAssignEquipment(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(Equipment.class) + .join(Job.class, Joiners.equal(Equipment::id, Job::getRequiredEquipmentId)) + .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.capacity()) + .penalize(HardMediumSoftScore.ONE_HARD) + .asConstraint("Concurrent equipment usage over capacity"); + } + } + + @Test + public void solveConnectedRanges() { + var e1 = new Equipment(1, 1); + var j1 = new Job(1, e1.id()); + var j2 = new Job(2, e1.id()); + var problem = new Planner(List.of(e1), List.of(j1, j2)); + + var config = new SolverConfig() + .withSolutionClass(Planner.class) + .withEntityClasses(Job.class) + .withConstraintProviderClass(MyConstraintProvider.class) + .withEnvironmentMode(EnvironmentMode.FULL_ASSERT) + .withTerminationConfig( + new TerminationConfig() + .withScoreCalculationCountLimit(1_000L)); + var solver = SolverFactory.create(config).buildSolver(); + solver.solve(problem);
Please write a test which tests the collector directly. I think we have been overdoing it with these integration tests lately. There are several reasons why tests that run the solver should be the exception, rather than the norm: - They take a relatively long time and if overused, our test suite will take impractically long to run. - They do not actually test anything. Yes, the test otherwise would've failed without this fix, but that's not a guarantee of anything into the future. If the solver changes how it iterates through things, because for example the RNG impl in the JDK changed, the test may no longer be testing the same conditions and therefore no longer catch the issue. These kinds of tests should only be used in cases where it is not possible or practical to reproduce a particular behavior on a lower level. There are cases like that, but this is not one of them - we know how to test collectors directly, and we should take the time to reproduce the actual problematic behavior.
timefold-solver
github_2023
java
1,010
TimefoldAI
zepfred
@@ -165,19 +175,24 @@ public void solvingError(SolverScope<Solution_> solverScope, Exception exception decider.solvingError(solverScope, exception); } - public static class Builder<Solution_> extends AbstractPhase.Builder<Solution_> { + public static class DefaultConstructionHeuristicPhaseBuilder<Solution_>
The name `Builder` is used by other builders, e.g., `DefaultLocalSearchPhase`. Is there a reason for changing this one?
timefold-solver
github_2023
java
1,010
TimefoldAI
zepfred
@@ -44,53 +47,65 @@ public DefaultConstructionHeuristicPhaseFactory(ConstructionHeuristicPhaseConfig super(phaseConfig); } - @Override - public ConstructionHeuristicPhase<Solution_> buildPhase(int phaseIndex, boolean triggerFirstInitializedSolutionEvent, - HeuristicConfigPolicy<Solution_> solverConfigPolicy, BestSolutionRecaller<Solution_> bestSolutionRecaller, - Termination<Solution_> solverTermination) { - ConstructionHeuristicType constructionHeuristicType_ = Objects.requireNonNullElse( - phaseConfig.getConstructionHeuristicType(), + protected DefaultConstructionHeuristicPhaseBuilder<Solution_> getBaseBuilder(int phaseIndex,
I understand using the `DefaultConstructionHeuristicPhaseFactory` class to construct both phases, but I wonder if we can use a different approach. Here are some ideas: Do we want to allow using `RuinRecreateConstructionHeuristicPhase` as an alternative construction phase to `DefaultConstructionHeuristicPhase`? If so, wouldn't having a separate config class instead of using `ConstructionHeuristicPhaseConfig` make sense? My point is the use of separate factory and phase classes, which would keep the changes located only in the respective classes, improving the concern separation. However, if we want to use R&R as an LS method only, I don't see a reason to change the logic in `DefaultConstructionHeuristicPhaseFactory::buildPhase`. Also, it seems unnecessary to add `isNested` to `DefaultConstructionHeuristicPhase` if the class `RuinRecreateConstructionHeuristicPhase` overrides the methods `doStep` and `phaseEnded`. In short, can we maintain the default construction factory and phase classes and extend their behavior by creating separate R&R classes?
timefold-solver
github_2023
java
1,010
TimefoldAI
zepfred
@@ -0,0 +1,71 @@ +package ai.timefold.solver.core.impl.heuristic.move; + +import java.util.Collection; +import java.util.Objects; + +import ai.timefold.solver.core.api.domain.solution.PlanningSolution; +import ai.timefold.solver.core.api.score.director.ScoreDirector; + +/** + * Abstract superclass for {@link Move}, suggested starting point to implement undo moves + * when not using {@link AbstractSimplifiedMove}. + * Unless raw performance is a concern, consider using {@link AbstractSimplifiedMove} instead. + * + * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation + * @see Move + */ +public abstract class AbstractUndoMove<Solution_> implements Move<Solution_> { + + protected final Move<Solution_> parentMove; + + protected AbstractUndoMove(Move<Solution_> parentMove) { + this.parentMove = Objects.requireNonNull(parentMove); + } + + @Override + public final boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) { + return true; // Undo moves are always doable; the parent move was already done. + } + + @Override + public final Move<Solution_> doMove(ScoreDirector<Solution_> scoreDirector) { + throw new UnsupportedOperationException("""
Do we need a text block here?
timefold-solver
github_2023
java
1,010
TimefoldAI
zepfred
@@ -0,0 +1,76 @@ +package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.ruin; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Random; + +import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply; +import ai.timefold.solver.core.impl.heuristic.move.Move; +import ai.timefold.solver.core.impl.heuristic.move.NoChangeMove; +import ai.timefold.solver.core.impl.heuristic.selector.common.iterator.UpcomingSelectionIterator; +import ai.timefold.solver.core.impl.heuristic.selector.move.generic.RuinRecreateConstructionHeuristicPhase.RuinRecreateConstructionHeuristicPhaseBuilder; +import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector; +import ai.timefold.solver.core.impl.solver.scope.SolverScope; +import ai.timefold.solver.core.impl.util.CollectionUtils; + +public final class ListRuinRecreateMoveIterator<Solution_> extends UpcomingSelectionIterator<Move<Solution_>> { + + private final EntityIndependentValueSelector<Solution_> valueSelector; + private final RuinRecreateConstructionHeuristicPhaseBuilder<Solution_> constructionHeuristicPhaseBuilder; + private final SolverScope<Solution_> solverScope; + private final ListVariableStateSupply<Solution_> listVariableStateSupply; + private final long minimumRuinedCount; + private final long maximumRuinedCount; + private final Random workingRandom; + + public ListRuinRecreateMoveIterator(EntityIndependentValueSelector<Solution_> valueSelector, + RuinRecreateConstructionHeuristicPhaseBuilder<Solution_> constructionHeuristicPhaseBuilder, + SolverScope<Solution_> solverScope, + ListVariableStateSupply<Solution_> listVariableStateSupply, long minimumRuinedCount, long maximumRuinedCount,
Should we use an int instead of a long type?
timefold-solver
github_2023
java
1,010
TimefoldAI
zepfred
@@ -0,0 +1,52 @@ +package ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.ruin; + +import java.util.function.ToLongFunction; + +import ai.timefold.solver.core.config.constructionheuristic.ConstructionHeuristicPhaseConfig; +import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; +import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder; +import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.ListRuinRecreateMoveSelectorConfig; +import ai.timefold.solver.core.config.heuristic.selector.value.ValueSelectorConfig; +import ai.timefold.solver.core.impl.constructionheuristic.DefaultConstructionHeuristicPhaseFactory; +import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy; +import ai.timefold.solver.core.impl.heuristic.selector.move.AbstractMoveSelectorFactory; +import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector; +import ai.timefold.solver.core.impl.heuristic.selector.value.EntityIndependentValueSelector; +import ai.timefold.solver.core.impl.heuristic.selector.value.ValueSelectorFactory; + +public final class ListRuinRecreateMoveSelectorFactory<Solution_> + extends AbstractMoveSelectorFactory<Solution_, ListRuinRecreateMoveSelectorConfig> { + + private final ListRuinRecreateMoveSelectorConfig ruinMoveSelectorConfig; + + public ListRuinRecreateMoveSelectorFactory(ListRuinRecreateMoveSelectorConfig ruinMoveSelectorConfig) { + super(ruinMoveSelectorConfig); + this.ruinMoveSelectorConfig = ruinMoveSelectorConfig; + } + + @Override + protected MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy, + SelectionCacheType minimumCacheType, boolean randomSelection) { + ToLongFunction<Long> minimumSelectedSupplier = ruinMoveSelectorConfig::determineMinimumRuinedCount; + ToLongFunction<Long> maximumSelectedSupplier = ruinMoveSelectorConfig::determineMaximumRuinedCount; + + this.getTheOnlyEntityDescriptor(configPolicy.getSolutionDescriptor()); + + var listVariableDescriptor = configPolicy.getSolutionDescriptor().getListVariableDescriptor(); + var entityDescriptor = listVariableDescriptor.getEntityDescriptor(); + var valueSelector = + (EntityIndependentValueSelector<Solution_>) ValueSelectorFactory.<Solution_> create(new ValueSelectorConfig()) + .buildValueSelector(configPolicy, entityDescriptor, minimumCacheType, SelectionOrder.RANDOM, + false, ValueSelectorFactory.ListValueFilteringType.ACCEPT_ASSIGNED); + var entityPlacerConfig = DefaultConstructionHeuristicPhaseFactory.buildListVariableQueuedValuePlacerConfig(configPolicy, + listVariableDescriptor); + + var constructionHeuristicConfig = new ConstructionHeuristicPhaseConfig(); + constructionHeuristicConfig.setEntityPlacerConfig(entityPlacerConfig); + var constructionHeuristicPhaseFactory =
It looks like we could use a distinct factory class here instead of `DefaultConstructionHeuristicPhaseFactory`.
timefold-solver
github_2023
java
1,010
TimefoldAI
zepfred
@@ -0,0 +1,60 @@ +package ai.timefold.solver.core.impl.heuristic.selector.move.generic; + +import java.util.List; + +import ai.timefold.solver.core.impl.constructionheuristic.ConstructionHeuristicPhase; +import ai.timefold.solver.core.impl.constructionheuristic.DefaultConstructionHeuristicPhase; +import ai.timefold.solver.core.impl.constructionheuristic.decider.ConstructionHeuristicDecider; +import ai.timefold.solver.core.impl.constructionheuristic.placer.EntityPlacer; +import ai.timefold.solver.core.impl.solver.termination.Termination; + +public final class RuinRecreateConstructionHeuristicPhase<Solution_> + extends DefaultConstructionHeuristicPhase<Solution_> + implements ConstructionHeuristicPhase<Solution_> { + + public RuinRecreateConstructionHeuristicPhase(RuinRecreateConstructionHeuristicPhaseBuilder<Solution_> builder) { + super(builder); + } + + @Override + protected boolean isNested() { + return true; + } + + public static final class RuinRecreateConstructionHeuristicPhaseBuilder<Solution_> + extends DefaultConstructionHeuristicPhaseBuilder<Solution_> { + + private List<Object> elementsToRecreate; + + public RuinRecreateConstructionHeuristicPhaseBuilder(Termination<Solution_> phaseTermination, + EntityPlacer<Solution_> entityPlacer, ConstructionHeuristicDecider<Solution_> decider) { + super(0, false, "", phaseTermination, entityPlacer, decider); + } + + public RuinRecreateConstructionHeuristicPhaseBuilder<Solution_> setElementsToRecreate(List<Object> elements) {
```suggestion public RuinRecreateConstructionHeuristicPhaseBuilder<Solution_> withElementsToRecreate(List<Object> elements) { ```
timefold-solver
github_2023
java
1,010
TimefoldAI
zepfred
@@ -0,0 +1,49 @@ +package ai.timefold.solver.core.impl.heuristic.selector.move.generic; + +import java.util.function.ToLongFunction; + +import ai.timefold.solver.core.config.constructionheuristic.ConstructionHeuristicPhaseConfig; +import ai.timefold.solver.core.config.heuristic.selector.common.SelectionCacheType; +import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder; +import ai.timefold.solver.core.config.heuristic.selector.entity.EntitySelectorConfig; +import ai.timefold.solver.core.config.heuristic.selector.move.generic.RuinRecreateMoveSelectorConfig; +import ai.timefold.solver.core.impl.constructionheuristic.DefaultConstructionHeuristicPhaseFactory; +import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy; +import ai.timefold.solver.core.impl.heuristic.selector.entity.EntitySelectorFactory; +import ai.timefold.solver.core.impl.heuristic.selector.move.AbstractMoveSelectorFactory; +import ai.timefold.solver.core.impl.heuristic.selector.move.MoveSelector; + +public final class RuinRecreateMoveSelectorFactory<Solution_> + extends AbstractMoveSelectorFactory<Solution_, RuinRecreateMoveSelectorConfig> { + + private final RuinRecreateMoveSelectorConfig ruinRecreateMoveSelectorConfig; + + public RuinRecreateMoveSelectorFactory(RuinRecreateMoveSelectorConfig ruinRecreateMoveSelectorConfig) { + super(ruinRecreateMoveSelectorConfig); + this.ruinRecreateMoveSelectorConfig = ruinRecreateMoveSelectorConfig; + } + + @Override + protected MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy, + SelectionCacheType minimumCacheType, boolean randomSelection) { + ToLongFunction<Long> minimumSelectedSupplier = ruinRecreateMoveSelectorConfig::determineMinimumRuinedCount; + ToLongFunction<Long> maximumSelectedSupplier = ruinRecreateMoveSelectorConfig::determineMaximumRuinedCount; + + var entitySelector = EntitySelectorFactory.<Solution_> create(new EntitySelectorConfig()) + .buildEntitySelector(configPolicy, minimumCacheType, + SelectionOrder.fromRandomSelectionBoolean(true)); + var genuineVariableDescriptorList = entitySelector.getEntityDescriptor().getGenuineVariableDescriptorList(); + if (genuineVariableDescriptorList.size() != 1) { + throw new UnsupportedOperationException( + "Ruin and Recreate move selector currently only supports 1 planning variable."); + } + var variableDescriptor = genuineVariableDescriptorList.get(0); + + var constructionHeuristicConfig = new ConstructionHeuristicPhaseConfig(); + var constructionHeuristicPhaseFactory = + new DefaultConstructionHeuristicPhaseFactory<Solution_>(constructionHeuristicConfig);
Same comment as the list variable version.
timefold-solver
github_2023
others
1,010
TimefoldAI
zepfred
@@ -0,0 +1,789 @@ +[#moveSelectorReference] += Move Selector reference +:doctype: book +:sectnums: +:icons: font + +This chapter describes the move selectors that can be used to select moves for the optimization algorithms. +For a general introduction to move selectors, +see xref:optimization-algorithms/overview.adoc#moveAndNeighborhoodSelection[Move and neighborhood selection]. + +The following `MoveSelector` implementations are available out of the box: + +[cols="1,2a",options="header"] +|=== +|Name |Description + +|<<changeMoveSelector,Change move>> +|Change 1 entity's variable + +|<<swapMoveSelector,Swap move>> +|Swap all variables of 2 entities + +|<<pillarChangeMoveSelector,Pillar change move>> +|Change a set of entities with the same value + +|<<pillarSwapMoveSelector,Pillar swap move>> +|Swap 2 sets of entities with the same values + +|<<ruinRecreateMoveSelector,Ruin and Recreate move>> +|Take a subset of entities, uninitialize them and run a construction heuristic to put them back + +|<<listChangeMoveSelector,List change move>> +|Move a list element to a different index or to another entity's list variable + +|<<listSwapMoveSelector,List swap move>> +|Swap 2 list elements + +|<<subListChangeMoveSelector,SubList change move>> +|Move a subList from one position to another + +|<<subListSwapMoveSelector,SubList swap move>> +|Swap 2 subLists + +|<<kOptListMoveSelector,k-opt move>> +|Select an entity, remove k edges from its list variable, add k new edges from the removed endpoints + +|<<listRuinRecreateMoveSelector,List Ruin and Recreate move>> +|Take a subset of values, remove them from their lists, and run a construction heuristic to recreate the lists + +|<<tailChainSwapMoveSelector,Tail chain swap move>> +|Swap 2 tails chains + +|<<subChainChangeMoveSelector,Sub chain change move>> +|Cut a subchain and paste it into another chain + +|<<subChainSwapMoveSelector,Sub chain swap move>> +|Swap 2 subchains + +|=== + +[#basicMoveSelectors] +== Move selectors for basic variables + +These moves are applicable to planning variables that aren’t part of a list or a chain, +also called xref:using-timefold-solver/modeling-planning-problems.adoc#planningVariable[basic variables]. + +[#changeMoveSelector] +=== `ChangeMoveSelector` + +For one planning variable, the `ChangeMove` selects one planning entity and one planning value and assigns the entity's variable to that value. + +image::optimization-algorithms/move-selector-reference/changeMove.png[align="center"] + +Simplest configuration: + +[source,xml,options="nowrap"] +---- + <changeMoveSelector/> +---- + +If there are multiple entity classes or multiple planning variables for one entity class, +a simple configuration will automatically unfold into +an xref:optimization-algorithms/overview.adoc#unionMoveSelector[union] +of `ChangeMove` selectors for every planning variable. + +Advanced configuration: + +[source,xml,options="nowrap"] +---- + <changeMoveSelector> + ... <!-- Normal selector properties --> + <entitySelector> + <entityClass>...Lecture</entityClass> + ... + </entitySelector> + <valueSelector variableName="room"> + ... + </valueSelector> + </changeMoveSelector> +---- + +A `ChangeMove` is the finest grained move. + +[IMPORTANT] +==== +Almost every `moveSelector` configuration injected into a metaheuristic algorithm should include a `changeMoveSelector`. +This guarantees that every possible solution can be reached in theory through applying a number of moves in sequence. +Of course, normally it is unioned with other, more coarse grained move selectors. +==== + +This move selector only supports xref:optimization-algorithms/overview.adoc#cacheType[phase or solver caching] +if it doesn't apply on a xref:using-timefold-solver/modeling-planning-problems.adoc#chainedPlanningVariable[chained] variable. + + +[#swapMoveSelector] +=== `SwapMoveSelector` + +The `SwapMove` selects two different planning entities and swaps the planning values of all their planning variables. + +image::optimization-algorithms/move-selector-reference/swapMove.png[align="center"] + +Although a `SwapMove` on a single variable is essentially just two ``ChangeMove``s, +it's often the winning step in cases that the first of the two ``ChangeMove``s would not win +because it leaves the solution in a state with broken hard constraints. +For example: swapping the room of two lectures doesn't bring the solution in an intermediate state where both lectures are in the same room which breaks a hard constraint. + +Simplest configuration: + +[source,xml,options="nowrap"] +---- + <swapMoveSelector/> +---- + +If there are multiple entity classes, a simple configuration will automatically unfold +into an xref:optimization-algorithms/overview.adoc#unionMoveSelector[union] +of `SwapMove` selectors for every entity class. + +Advanced configuration: + +[source,xml,options="nowrap"] +---- + <swapMoveSelector> + ... <!-- Normal selector properties --> + <entitySelector> + <entityClass>...Lecture</entityClass> + ... + </entitySelector> + <secondaryEntitySelector> + <entityClass>...Lecture</entityClass> + ... + </secondaryEntitySelector> + <variableNameIncludes> + <variableNameInclude>room</variableNameInclude> + <variableNameInclude>...</variableNameInclude> + </variableNameIncludes> + </swapMoveSelector> +---- + +The `secondaryEntitySelector` is rarely needed: if it is not specified, entities from the same `entitySelector` are swapped. + +If one or more `variableNameInclude` properties are specified, not all planning variables will be swapped, but only those specified. + +This move selector only supports xref:optimization-algorithms/overview.adoc#cacheType[phase or solver caching] +if it doesn't apply on any xref:using-timefold-solver/modeling-planning-problems.adoc#chainedPlanningVariable[chained] variables. + +[#pillarMoveSelectors] +=== Pillar-based move selectors + +A _pillar_ is a set of planning entities which have the same planning value(s) for their planning variable(s). + +[#pillarChangeMoveSelector] +==== `PillarChangeMoveSelector` + +The `PillarChangeMove` selects one entity pillar (or subset of those) and changes the value of one variable (which is the same for all entities) to another value. + +image::optimization-algorithms/move-selector-reference/pillarChangeMove.png[align="center"] + +In the example above, queen A and C have the same value (row 0) and are moved to row 2. +Also the yellow and blue process have the same value (computer Y) and are moved to computer X. + +Simplest configuration: + +[source,xml,options="nowrap"] +---- + <pillarChangeMoveSelector/> +---- + +Advanced configuration: + +[source,xml,options="nowrap"] +---- + <pillarChangeMoveSelector> + <subPillarType>SEQUENCE</subPillarType> + <subPillarSequenceComparatorClass>...ShiftComparator</subPillarSequenceComparatorClass> + ... <!-- Normal selector properties --> + <pillarSelector> + <entitySelector> + <entityClass>...Shift</entityClass> + ... + </entitySelector> + <minimumSubPillarSize>1</minimumSubPillarSize> + <maximumSubPillarSize>1000</maximumSubPillarSize> + </pillarSelector> + <valueSelector variableName="employee"> + ... + </valueSelector> + </pillarChangeMoveSelector> +---- + +For a description of `subPillarType` and related properties, please refer to <<subPillars,Sub-pillars>>. + +The other properties are explained in <<changeMoveSelector,changeMoveSelector>>. +This move selector doesn’t support xref:optimization-algorithms/overview.adoc#cacheType[phase or solver caching] +and step caching scales badly memory wise. + + +[#pillarSwapMoveSelector] +==== `PillarSwapMoveSelector` + +The `PillarSwapMove` selects two different entity pillars and swaps the values of all their variables for all their entities. + +image::optimization-algorithms/move-selector-reference/pillarSwapMove.png[align="center"] + +Simplest configuration: + +[source,xml,options="nowrap"] +---- + <pillarSwapMoveSelector/> +---- + +Advanced configuration: + +[source,xml,options="nowrap"] +---- + <pillarSwapMoveSelector> + <subPillarType>SEQUENCE</subPillarType> + <subPillarSequenceComparatorClass>...ShiftComparator</subPillarSequenceComparatorClass> + ... <!-- Normal selector properties --> + <pillarSelector> + <entitySelector> + <entityClass>...Shift</entityClass> + ... + </entitySelector> + <minimumSubPillarSize>1</minimumSubPillarSize> + <maximumSubPillarSize>1000</maximumSubPillarSize> + </pillarSelector> + <secondaryPillarSelector> + <entitySelector> + ... + </entitySelector> + ... + </secondaryPillarSelector> + <variableNameIncludes> + <variableNameInclude>employee</variableNameInclude> + <variableNameInclude>...</variableNameInclude> + </variableNameIncludes> + </pillarSwapMoveSelector> +---- + +For a description of `subPillarType` and related properties, please refer to <<subPillars,sub-pillars>>. + +The `secondaryPillarSelector` is rarely needed: if it is not specified, entities from the same `pillarSelector` are swapped. + +The other properties are explained in <<swapMoveSelector,swapMoveSelector>> and <<pillarChangeMoveSelector,pillarChangeMoveSelector>>. +This move selector doesn’t support xref:optimization-algorithms/overview.adoc#cacheType[phase or solver caching] +and step caching scales badly memory wise. + +[#subPillars] +==== Sub-pillars + +A sub-pillar is a subset of entities that share the same value(s) for their variable(s). +For example if queen A, B, C and D are all located on row 0, they’re a pillar and `[A, D]` is one of the many sub-pillars. + +There are several ways how sub-pillars can be selected by the `subPillarType` property: + +- `ALL` (default) selects all possible sub-pillars. +- `SEQUENCE` limits selection of sub-pillars to <<sequentialSubPillars,Sequential sub-pillars>>. +- `NONE` never selects any sub-pillars. + +If sub-pillars are enabled, the pillar itself is also included and the properties `minimumSubPillarSize` (defaults to ``1``) and `maximumSubPillarSize` (defaults to ``infinity``) limit the size of the selected (sub) pillar. + +[NOTE] +==== +The number of sub-pillars of a pillar is exponential to the size of the pillar. +For example a pillar of size 32 has `(2^32 - 1)` sub-pillars. +Therefore a `pillarSelector` only supports xref:optimization-algorithms/overview.adoc#justInTimeRandomSelection[JIT random selection] (which is the default). +==== + +[#sequentialSubPillars] +===== Sequential sub-pillars + +sub-pillars can be sorted with a `Comparator`. A sequential sub-pillar is a continuous subset of its sorted base pillar. + +For example, if an employee has shifts on Monday (`M`), Tuesday (`T`), and Wednesday (`W`), +they’re a pillar and only the following are its sequential sub-pillars: `[M], [T], [W], [M, T], [T, W], [M, T, W]`. +But `[M, W]` is not a sub-pillar in this case, as there is a gap on Tuesday. + +Sequential sub-pillars apply to both <<pillarChangeMoveSelector,Pillar change move>> and +<<pillarSwapMoveSelector,Pillar swap move>>. A minimal configuration looks like this: + +[source,xml,options="nowrap"] +---- + <pillar...MoveSelector> + <subPillarType>SEQUENCE</subPillarType> + </pillar...MoveSelector> +---- + +In this case, the entity being operated on must implement the `Comparable` interface. The size of sub-pillars will not be limited in any way. + +An advanced configuration looks like this: + +[source,xml,options="nowrap"] +---- + <pillar...MoveSelector> + ... + <subPillarType>SEQUENCE</subPillarType> + <subPillarSequenceComparatorClass>...ShiftComparator</subPillarSequenceComparatorClass> + <pillarSelector> + ... + <minimumSubPillarSize>1</minimumSubPillarSize> + <maximumSubPillarSize>1000</maximumSubPillarSize> + </pillarSelector> + ... + </pillar...MoveSelector> +---- + +In this case, the entity being operated on needn’t be `Comparable`. +The given `subPillarSequenceComparatorClass` is used to establish the sequence instead. +Also, the size of the sub-pillars is limited in length of up to 1000 entities. + +[#ruinRecreateMoveSelector] +=== `RuinRecreateMoveSelector` + +The `RuinRecreateMove` selects a subset of entities and sets their values to null, +effectively unassigning them. +Then it runs a construction heuristic to assign them again. +If xref:using-timefold-solver/modeling-planning-problems.adoc#planningVariableAllowingUnassigned[unassigned values] are allowed, +it may leave them unassigned. + +This coarse-grained move is useful to help get the solver out of a local optimum.
```suggestion This coarse-grained move is useful to help the solver to escape from a local optimum. ```
timefold-solver
github_2023
others
1,010
TimefoldAI
zepfred
@@ -0,0 +1,789 @@ +[#moveSelectorReference] += Move Selector reference +:doctype: book +:sectnums: +:icons: font + +This chapter describes the move selectors that can be used to select moves for the optimization algorithms. +For a general introduction to move selectors, +see xref:optimization-algorithms/overview.adoc#moveAndNeighborhoodSelection[Move and neighborhood selection]. + +The following `MoveSelector` implementations are available out of the box: + +[cols="1,2a",options="header"] +|=== +|Name |Description + +|<<changeMoveSelector,Change move>> +|Change 1 entity's variable + +|<<swapMoveSelector,Swap move>> +|Swap all variables of 2 entities + +|<<pillarChangeMoveSelector,Pillar change move>> +|Change a set of entities with the same value + +|<<pillarSwapMoveSelector,Pillar swap move>> +|Swap 2 sets of entities with the same values + +|<<ruinRecreateMoveSelector,Ruin and Recreate move>> +|Take a subset of entities, uninitialize them and run a construction heuristic to put them back + +|<<listChangeMoveSelector,List change move>> +|Move a list element to a different index or to another entity's list variable + +|<<listSwapMoveSelector,List swap move>> +|Swap 2 list elements + +|<<subListChangeMoveSelector,SubList change move>> +|Move a subList from one position to another + +|<<subListSwapMoveSelector,SubList swap move>> +|Swap 2 subLists + +|<<kOptListMoveSelector,k-opt move>> +|Select an entity, remove k edges from its list variable, add k new edges from the removed endpoints + +|<<listRuinRecreateMoveSelector,List Ruin and Recreate move>> +|Take a subset of values, remove them from their lists, and run a construction heuristic to recreate the lists + +|<<tailChainSwapMoveSelector,Tail chain swap move>> +|Swap 2 tails chains + +|<<subChainChangeMoveSelector,Sub chain change move>> +|Cut a subchain and paste it into another chain + +|<<subChainSwapMoveSelector,Sub chain swap move>> +|Swap 2 subchains + +|=== + +[#basicMoveSelectors] +== Move selectors for basic variables + +These moves are applicable to planning variables that aren’t part of a list or a chain, +also called xref:using-timefold-solver/modeling-planning-problems.adoc#planningVariable[basic variables]. + +[#changeMoveSelector] +=== `ChangeMoveSelector` + +For one planning variable, the `ChangeMove` selects one planning entity and one planning value and assigns the entity's variable to that value. + +image::optimization-algorithms/move-selector-reference/changeMove.png[align="center"] + +Simplest configuration: + +[source,xml,options="nowrap"] +---- + <changeMoveSelector/> +---- + +If there are multiple entity classes or multiple planning variables for one entity class, +a simple configuration will automatically unfold into +an xref:optimization-algorithms/overview.adoc#unionMoveSelector[union] +of `ChangeMove` selectors for every planning variable. + +Advanced configuration: + +[source,xml,options="nowrap"] +---- + <changeMoveSelector> + ... <!-- Normal selector properties --> + <entitySelector> + <entityClass>...Lecture</entityClass> + ... + </entitySelector> + <valueSelector variableName="room"> + ... + </valueSelector> + </changeMoveSelector> +---- + +A `ChangeMove` is the finest grained move. + +[IMPORTANT] +==== +Almost every `moveSelector` configuration injected into a metaheuristic algorithm should include a `changeMoveSelector`. +This guarantees that every possible solution can be reached in theory through applying a number of moves in sequence. +Of course, normally it is unioned with other, more coarse grained move selectors. +==== + +This move selector only supports xref:optimization-algorithms/overview.adoc#cacheType[phase or solver caching] +if it doesn't apply on a xref:using-timefold-solver/modeling-planning-problems.adoc#chainedPlanningVariable[chained] variable. + + +[#swapMoveSelector] +=== `SwapMoveSelector` + +The `SwapMove` selects two different planning entities and swaps the planning values of all their planning variables. + +image::optimization-algorithms/move-selector-reference/swapMove.png[align="center"] + +Although a `SwapMove` on a single variable is essentially just two ``ChangeMove``s, +it's often the winning step in cases that the first of the two ``ChangeMove``s would not win +because it leaves the solution in a state with broken hard constraints. +For example: swapping the room of two lectures doesn't bring the solution in an intermediate state where both lectures are in the same room which breaks a hard constraint. + +Simplest configuration: + +[source,xml,options="nowrap"] +---- + <swapMoveSelector/> +---- + +If there are multiple entity classes, a simple configuration will automatically unfold +into an xref:optimization-algorithms/overview.adoc#unionMoveSelector[union] +of `SwapMove` selectors for every entity class. + +Advanced configuration: + +[source,xml,options="nowrap"] +---- + <swapMoveSelector> + ... <!-- Normal selector properties --> + <entitySelector> + <entityClass>...Lecture</entityClass> + ... + </entitySelector> + <secondaryEntitySelector> + <entityClass>...Lecture</entityClass> + ... + </secondaryEntitySelector> + <variableNameIncludes> + <variableNameInclude>room</variableNameInclude> + <variableNameInclude>...</variableNameInclude> + </variableNameIncludes> + </swapMoveSelector> +---- + +The `secondaryEntitySelector` is rarely needed: if it is not specified, entities from the same `entitySelector` are swapped. + +If one or more `variableNameInclude` properties are specified, not all planning variables will be swapped, but only those specified. + +This move selector only supports xref:optimization-algorithms/overview.adoc#cacheType[phase or solver caching] +if it doesn't apply on any xref:using-timefold-solver/modeling-planning-problems.adoc#chainedPlanningVariable[chained] variables. + +[#pillarMoveSelectors] +=== Pillar-based move selectors + +A _pillar_ is a set of planning entities which have the same planning value(s) for their planning variable(s). + +[#pillarChangeMoveSelector] +==== `PillarChangeMoveSelector` + +The `PillarChangeMove` selects one entity pillar (or subset of those) and changes the value of one variable (which is the same for all entities) to another value. + +image::optimization-algorithms/move-selector-reference/pillarChangeMove.png[align="center"] + +In the example above, queen A and C have the same value (row 0) and are moved to row 2. +Also the yellow and blue process have the same value (computer Y) and are moved to computer X. + +Simplest configuration: + +[source,xml,options="nowrap"] +---- + <pillarChangeMoveSelector/> +---- + +Advanced configuration: + +[source,xml,options="nowrap"] +---- + <pillarChangeMoveSelector> + <subPillarType>SEQUENCE</subPillarType> + <subPillarSequenceComparatorClass>...ShiftComparator</subPillarSequenceComparatorClass> + ... <!-- Normal selector properties --> + <pillarSelector> + <entitySelector> + <entityClass>...Shift</entityClass> + ... + </entitySelector> + <minimumSubPillarSize>1</minimumSubPillarSize> + <maximumSubPillarSize>1000</maximumSubPillarSize> + </pillarSelector> + <valueSelector variableName="employee"> + ... + </valueSelector> + </pillarChangeMoveSelector> +---- + +For a description of `subPillarType` and related properties, please refer to <<subPillars,Sub-pillars>>. + +The other properties are explained in <<changeMoveSelector,changeMoveSelector>>. +This move selector doesn’t support xref:optimization-algorithms/overview.adoc#cacheType[phase or solver caching] +and step caching scales badly memory wise. + + +[#pillarSwapMoveSelector] +==== `PillarSwapMoveSelector` + +The `PillarSwapMove` selects two different entity pillars and swaps the values of all their variables for all their entities. + +image::optimization-algorithms/move-selector-reference/pillarSwapMove.png[align="center"] + +Simplest configuration: + +[source,xml,options="nowrap"] +---- + <pillarSwapMoveSelector/> +---- + +Advanced configuration: + +[source,xml,options="nowrap"] +---- + <pillarSwapMoveSelector> + <subPillarType>SEQUENCE</subPillarType> + <subPillarSequenceComparatorClass>...ShiftComparator</subPillarSequenceComparatorClass> + ... <!-- Normal selector properties --> + <pillarSelector> + <entitySelector> + <entityClass>...Shift</entityClass> + ... + </entitySelector> + <minimumSubPillarSize>1</minimumSubPillarSize> + <maximumSubPillarSize>1000</maximumSubPillarSize> + </pillarSelector> + <secondaryPillarSelector> + <entitySelector> + ... + </entitySelector> + ... + </secondaryPillarSelector> + <variableNameIncludes> + <variableNameInclude>employee</variableNameInclude> + <variableNameInclude>...</variableNameInclude> + </variableNameIncludes> + </pillarSwapMoveSelector> +---- + +For a description of `subPillarType` and related properties, please refer to <<subPillars,sub-pillars>>. + +The `secondaryPillarSelector` is rarely needed: if it is not specified, entities from the same `pillarSelector` are swapped. + +The other properties are explained in <<swapMoveSelector,swapMoveSelector>> and <<pillarChangeMoveSelector,pillarChangeMoveSelector>>. +This move selector doesn’t support xref:optimization-algorithms/overview.adoc#cacheType[phase or solver caching] +and step caching scales badly memory wise. + +[#subPillars] +==== Sub-pillars + +A sub-pillar is a subset of entities that share the same value(s) for their variable(s). +For example if queen A, B, C and D are all located on row 0, they’re a pillar and `[A, D]` is one of the many sub-pillars. + +There are several ways how sub-pillars can be selected by the `subPillarType` property: + +- `ALL` (default) selects all possible sub-pillars. +- `SEQUENCE` limits selection of sub-pillars to <<sequentialSubPillars,Sequential sub-pillars>>. +- `NONE` never selects any sub-pillars. + +If sub-pillars are enabled, the pillar itself is also included and the properties `minimumSubPillarSize` (defaults to ``1``) and `maximumSubPillarSize` (defaults to ``infinity``) limit the size of the selected (sub) pillar. + +[NOTE] +==== +The number of sub-pillars of a pillar is exponential to the size of the pillar. +For example a pillar of size 32 has `(2^32 - 1)` sub-pillars. +Therefore a `pillarSelector` only supports xref:optimization-algorithms/overview.adoc#justInTimeRandomSelection[JIT random selection] (which is the default). +==== + +[#sequentialSubPillars] +===== Sequential sub-pillars + +sub-pillars can be sorted with a `Comparator`. A sequential sub-pillar is a continuous subset of its sorted base pillar. + +For example, if an employee has shifts on Monday (`M`), Tuesday (`T`), and Wednesday (`W`), +they’re a pillar and only the following are its sequential sub-pillars: `[M], [T], [W], [M, T], [T, W], [M, T, W]`. +But `[M, W]` is not a sub-pillar in this case, as there is a gap on Tuesday. + +Sequential sub-pillars apply to both <<pillarChangeMoveSelector,Pillar change move>> and +<<pillarSwapMoveSelector,Pillar swap move>>. A minimal configuration looks like this: + +[source,xml,options="nowrap"] +---- + <pillar...MoveSelector> + <subPillarType>SEQUENCE</subPillarType> + </pillar...MoveSelector> +---- + +In this case, the entity being operated on must implement the `Comparable` interface. The size of sub-pillars will not be limited in any way. + +An advanced configuration looks like this: + +[source,xml,options="nowrap"] +---- + <pillar...MoveSelector> + ... + <subPillarType>SEQUENCE</subPillarType> + <subPillarSequenceComparatorClass>...ShiftComparator</subPillarSequenceComparatorClass> + <pillarSelector> + ... + <minimumSubPillarSize>1</minimumSubPillarSize> + <maximumSubPillarSize>1000</maximumSubPillarSize> + </pillarSelector> + ... + </pillar...MoveSelector> +---- + +In this case, the entity being operated on needn’t be `Comparable`. +The given `subPillarSequenceComparatorClass` is used to establish the sequence instead. +Also, the size of the sub-pillars is limited in length of up to 1000 entities. + +[#ruinRecreateMoveSelector] +=== `RuinRecreateMoveSelector` + +The `RuinRecreateMove` selects a subset of entities and sets their values to null, +effectively unassigning them. +Then it runs a construction heuristic to assign them again. +If xref:using-timefold-solver/modeling-planning-problems.adoc#planningVariableAllowingUnassigned[unassigned values] are allowed, +it may leave them unassigned. + +This coarse-grained move is useful to help get the solver out of a local optimum. +It allows the solver to effectively "undo" a number of earlier decisions in one step, +opening up a new part of the solution space. + +[NOTE] +==== +If xref:enterprise-edition/enterprise-edition.adoc#nearbySelection[nearby selection] is enabled, +the `RuinRecreateMove` is likely to underperform +as it won't be able to rebuild the solution using nearby selection. +This almost always results in worse solutions than those that were originally ruined, +without a big likelihood of leading to a better solution further down the line. +We recommend not using this move together with nearby selection. +==== + +This move is not enabled by default. +To enable it, add the following to the `localSearch` section of the solver configuration: + +[source,xml,options="nowrap"] +---- + <ruinRecreateMoveSelector/> +---- + +[IMPORTANT] +==== +The default values have been determined by extensive benchmarking. +That said, the optimal values may vary depending on the problem, available solving time, and dataset at hand. +We recommend that you xref:using-timefold-solver/benchmarking-and-tweaking.adoc#benchmarker[experiment with these values] +to find the best fit for your problem. +==== + +Advanced configuration: + +[source,xml,options="nowrap"] +---- + <ruinRecreateMoveSelector> + <minimumRuinedCount>5</minimumRuinedCount> + <maximumRuinedCount>40</maximumRuinedCount> + </ruinRecreateMoveSelector> +---- + +The `minimumRuinedCount` and `maximumRuinedCount` properties limit the number of entities that are unassigned. +The default values are `5` and `20` respectively, but for large datasets, +it may prove beneficial to increase these values. + +[NOTE] +==== +`RuinRecreateMove` doesn’t support customizing the construction heuristic that it runs. +Neither does it support customizing any entity or value selectors. +If your problem needs more control over the construction heuristic, +don’t enable this move. +==== + +Since the `RuinRecreateMove` is a coarse-grained move, +it is expensive and can slow the solver down significantly. +However, the default local search configuration will attempt to run it at the same frequency +as the other fine-grained moves. +For that reason, we recommend that you use xref:optimization-algorithms/overview.adoc#probabilisticSelection[probabilistic selection] +to control the frequency of this move: + +[source,xml,options="nowrap"] +---- + <unionMoveSelector> + <unionMoveSelector> + <fixedProbabilityWeight>100.0</fixedProbabilityWeight> + <changeMoveSelector/> + <swapMoveSelector/> + <pillarChangeMoveSelector/> + <pillarSwapMoveSelector/> + </unionMoveSelector> + <ruinMoveSelector> + <fixedProbabilityWeight>1.0</fixedProbabilityWeight> + </ruinMoveSelector> + </unionMoveSelector> +---- + +The above configuration will run the `RuinRecreateMove` once for every 100 fine-grained moves. +As always, benchmarking is recommended to find the optimal value for your use case. + + +[#listMoveSelectors] +== Move selectors for list variables + +These moves are applicable to xref:using-timefold-solver/modeling-planning-problems.adoc#planningListVariable[list planning variables]. + +[#listChangeMoveSelector] +=== `ListChangeMoveSelector` + +The `ListChangeMoveSelector` selects an element from a list variable's value range and moves it from its current position to a new one. + +Simplest configuration: + +[source,xml] +---- + <listChangeMoveSelector/> +---- + +Advanced configuration: + +[source,xml] +---- + <listChangeMoveSelector> + ... <!-- Normal selector properties --> + <valueSelector id="valueSelector1"> + ... + </valueSelector> + <destinationSelector> + <entitySelector> + ... + </entitySelector> + <valueSelector> + ... + </valueSelector> + </destinationSelector> + </listChangeMoveSelector> +---- + +[#listSwapMoveSelector] +=== `ListSwapMoveSelector` + +The `ListSwapMoveSelector` selects two elements from the same list variable value range and swaps their positions. + +Simplest configuration: + +[source,xml] +---- + <listSwapMoveSelector/> +---- + +[#subListChangeMoveSelector] +=== `SubListChangeMoveSelector` + +A _subList_ is a sequence of elements in a specific entity's list variable between `fromIndex` and `toIndex`. +The `SubListChangeMoveSelector` selects a source subList by selecting a source entity and the source subList's `fromIndex` and `toIndex`. +Then it selects a destination entity and a `destinationIndex` in the destination entity's list variable. +Selecting these parameters results in a `SubListChangeMove` that removes the source subList elements from the source entity and adds them to the destination entity's list variable at the `destinationIndex`. + +Simplest configuration: + +[source,xml] +---- + <subListChangeMoveSelector/> +---- + +Advanced configuration: + +[source,xml] +---- + <subListChangeMoveSelector> + ... <!-- Normal selector properties --> + <selectReversingMoveToo>true</selectReversingMoveToo> + <subListSelector id="subListSelector1"> + <valueSelector> + ... + </valueSelector> + <minimumSubListSize>2</minimumSubListSize> + <maximumSubListSize>6</maximumSubListSize> + </subListSelector> + </subListChangeMoveSelector> +---- + +[#subListSwapMoveSelector] +=== `SubListSwapMoveSelector` + +A _subList_ is a sequence of elements in a specific entity's list variable between `fromIndex` and `toIndex`. +The `SubListSwapMoveSelector` selects a left subList by selecting a left entity and the left subList's `fromIndex` and `toIndex`. +Then it selects a right subList by selecting a right entity and the right subList's `fromIndex` and `toIndex`. +Selecting these parameters results in a `SubListSwapMove` that swaps the right and left subLists between right and left entities. + +Simplest configuration: + +[source,xml] +---- + <subListSwapMoveSelector/> +---- + +Advanced configuration: + +[source,xml] +---- + <subListSwapMoveSelector> + ... <!-- Normal selector properties --> + <selectReversingMoveToo>true</selectReversingMoveToo> + <subListSelector id="subListSelector1"> + <valueSelector> + ... + </valueSelector> + <minimumSubListSize>2</minimumSubListSize> + <maximumSubListSize>6</maximumSubListSize> + </subListSelector> + </subListSwapMoveSelector> +---- + +[#kOptListMoveSelector] +=== `KOptListMoveSelector` + +The `KOptListMoveSelector` considers the list variable to be +a graph whose edges are the consecutive elements of the list +(with the last element being consecutive to the first element). +A `KOptListMove` selects an entity, remove `k` edges from its list variable, and add `k` new edges from the removed edges' endpoints. +This move may reverse segments of the graph. + +image::optimization-algorithms/move-selector-reference/koptMove.png[align="center"] + +Simplest configuration: + +[source,xml] +---- + <kOptListMoveSelector/> +---- + +Advanced configuration: + +[source,xml] +---- + <kOptListMoveSelector> + ... <!-- Normal selector properties --> + <minimumK>2</minimumK> + <maximumK>4</maximumK> + </kOptListMoveSelector> +---- + +[#listRuinRecreateMoveSelector] +=== `ListRuinRecreateMoveSelector` + +The `ListRuinRecreateMove` selects a subset of values, and removes them from their list variables. +Then it runs a construction heuristic to assign them again. +If xref:using-timefold-solver/modeling-planning-problems.adoc#planningListVariableAllowingUnassigned[unassigned values] are allowed, +it may leave them unassigned. + +This coarse-grained move is useful to help get the solver out of a local optimum.
```suggestion This coarse-grained move is useful to help the solver to escape from a local optimum. ```
timefold-solver
github_2023
others
1,010
TimefoldAI
zepfred
@@ -0,0 +1,2134 @@ +[#optimizationAlgorithmsOverview]
The new chapter organization looks better!
timefold-solver
github_2023
java
1,010
TimefoldAI
zepfred
@@ -0,0 +1,139 @@ +package ai.timefold.solver.core.config.heuristic.selector.move.generic.list; + +import java.util.function.Consumer; + +import jakarta.xml.bind.annotation.XmlType; + +import ai.timefold.solver.core.config.heuristic.selector.move.MoveSelectorConfig; +import ai.timefold.solver.core.config.util.ConfigUtils; + +@XmlType(propOrder = { + "minimumRuinedCount", + "maximumRuinedCount", + "minimumRuinedPercentage", + "maximumRuinedPercentage" +}) +public class ListRuinRecreateMoveSelectorConfig extends MoveSelectorConfig<ListRuinRecreateMoveSelectorConfig> { + + // Determined by benchmarking on multiple datasets. + private static final int DEFAULT_MINIMUM_RUINED_COUNT = 5; + private static final int DEFAULT_MAXIMUM_RUINED_COUNT = 40;
Just to confirm, the maximum value for `RuinRecreateMoveSelectorConfig` is `20`, and this one is `40`, correct?
timefold-solver
github_2023
java
1,010
TimefoldAI
zepfred
@@ -95,6 +98,10 @@ private void doStep(ConstructionHeuristicStepScope<Solution_> stepScope) { var step = stepScope.getStep(); step.doMoveOnly(stepScope.getScoreDirector()); predictWorkingStepScore(stepScope, step); + processWorkingSolutionDuringStep(stepScope); + } + + protected void processWorkingSolutionDuringStep(ConstructionHeuristicStepScope<Solution_> stepScope) {
It looks like the new method is not used anywhere else and could be inlined.
timefold-solver
github_2023
java
1,010
TimefoldAI
zepfred
@@ -162,59 +165,47 @@ public static EntityPlacerConfig buildListVariableQueuedValuePlacerConfig( .withMoveSelectorConfig(listChangeMoveSelectorConfig); } - private ConstructionHeuristicDecider<Solution_> buildDecider(HeuristicConfigPolicy<Solution_> configPolicy, + protected ConstructionHeuristicDecider<Solution_> buildDecider(HeuristicConfigPolicy<Solution_> configPolicy, Termination<Solution_> termination) { - ConstructionHeuristicForagerConfig foragerConfig_ = - Objects.requireNonNullElseGet(phaseConfig.getForagerConfig(), ConstructionHeuristicForagerConfig::new); - ConstructionHeuristicForager<Solution_> forager = - ConstructionHeuristicForagerFactory.<Solution_> create(foragerConfig_).buildForager(configPolicy); - EnvironmentMode environmentMode = configPolicy.getEnvironmentMode(); - ConstructionHeuristicDecider<Solution_> decider; - Integer moveThreadCount = configPolicy.getMoveThreadCount(); - if (moveThreadCount == null) { - decider = new ConstructionHeuristicDecider<>(configPolicy.getLogIndentation(), termination, forager); - } else { - decider = TimefoldSolverEnterpriseService.loadOrFail(TimefoldSolverEnterpriseService.Feature.MULTITHREADED_SOLVING) - .buildConstructionHeuristic(moveThreadCount, termination, forager, environmentMode, configPolicy); - } - if (environmentMode.isNonIntrusiveFullAsserted()) {
I couldn't find any other place that updates the decider properties. Please confirm if setting them is still necessary.
timefold-solver
github_2023
java
1,010
TimefoldAI
zepfred
@@ -0,0 +1,37 @@ +package ai.timefold.solver.core.impl.heuristic.selector.move.generic; + +import ai.timefold.solver.core.config.constructionheuristic.ConstructionHeuristicPhaseConfig; +import ai.timefold.solver.core.impl.constructionheuristic.DefaultConstructionHeuristicPhase.DefaultConstructionHeuristicPhaseBuilder; +import ai.timefold.solver.core.impl.constructionheuristic.DefaultConstructionHeuristicPhaseFactory; +import ai.timefold.solver.core.impl.constructionheuristic.decider.ConstructionHeuristicDecider; +import ai.timefold.solver.core.impl.constructionheuristic.placer.EntityPlacer; +import ai.timefold.solver.core.impl.heuristic.HeuristicConfigPolicy; +import ai.timefold.solver.core.impl.solver.termination.BasicPlumbingTermination; +import ai.timefold.solver.core.impl.solver.termination.PhaseToSolverTerminationBridge; +import ai.timefold.solver.core.impl.solver.termination.Termination; + +final class RuinRecreateConstructionHeuristicPhaseFactory<Solution_>
Nice!
timefold-solver
github_2023
others
1,047
TimefoldAI
triceo
@@ -115,6 +177,25 @@ solution.setConstraintWeightOverrides(constraintWeightOverrides); ... ---- +Python:: ++ +[source,python,options="nowrap"] +---- +... + +constraint_weight_overrides = ConstraintWeightOverrides( + { + "Vehicle capacity": HardSoftScore.of(2, 0),
We don't have `ofHard(...)` in Python?
timefold-solver
github_2023
others
1,047
TimefoldAI
triceo
@@ -394,23 +491,23 @@ Variants of this `Score` type: [#scoreCalculationTypes] === Score calculation types -There are several ways to calculate the `Score` of a solution in Java or another JVM language: +There are several ways to calculate the `Score` of a solution in Java, Python or another JVM language: * **xref:constraints-and-score/score-calculation.adoc[Constraint Streams API]**: Implement each constraint as a separate Constraint Stream. Fast and scalable. -* **xref:constraints-and-score/score-calculation.adoc#incrementalJavaScoreCalculation[Incremental Java score calculation]** (not recommended): +* **xref:constraints-and-score/score-calculation.adoc#incrementalJavaScoreCalculation[Incremental Java/Python score calculation]** (not recommended):
Arguably, "Incremental X score calculation" is no longer the correct name. Not only do we have Python, we also have Kotlin. It seems that the name of the language just shouldn't be there at all. The name of the class is `IncrementalScoreCalculator` - maybe we should just call this "Incremental score calculator"?
timefold-solver
github_2023
others
1,047
TimefoldAI
triceo
@@ -394,23 +491,23 @@ Variants of this `Score` type: [#scoreCalculationTypes] === Score calculation types -There are several ways to calculate the `Score` of a solution in Java or another JVM language: +There are several ways to calculate the `Score` of a solution in Java, Python or another JVM language: * **xref:constraints-and-score/score-calculation.adoc[Constraint Streams API]**: Implement each constraint as a separate Constraint Stream. Fast and scalable. -* **xref:constraints-and-score/score-calculation.adoc#incrementalJavaScoreCalculation[Incremental Java score calculation]** (not recommended): +* **xref:constraints-and-score/score-calculation.adoc#incrementalJavaScoreCalculation[Incremental Java/Python score calculation]** (not recommended): Implement multiple low-level methods. Fast and scalable. Very difficult to implement and maintain. Supports xref:constraints-and-score/understanding-the-score.adoc[score explanations] with extra effort. -* **xref:constraints-and-score/score-calculation.adoc#easyJavaScoreCalculation[Easy Java score calculation]** (not recommended): +* **xref:constraints-and-score/score-calculation.adoc#easyJavaScoreCalculation[Easy Java/Python score calculation]** (not recommended): Implement all constraints together in a single method. Does not scale. Does not support xref:constraints-and-score/understanding-the-score.adoc[score explanations]. Every score calculation type can work with any Score definition (such as ``HardSoftScore`` or ``HardMediumSoftScore``). -All score calculation types are Object Oriented and can reuse existing Java code. +All score calculation types are Object Oriented and can reuse existing Java or Python code.
```suggestion All score calculation types are object-oriented and can reuse existing Java or Python code. ```
timefold-solver
github_2023
others
1,047
TimefoldAI
triceo
@@ -113,9 +113,13 @@ In order for constraints to scale well, it is necessary to limit the amount of d In Constraint Streams, it starts with xref:constraints-and-score/score-calculation.adoc#constraintStreamsJoin[joins]. Consider a school timetabling problem, where a teacher must not have two overlapping lessons. -This is how the lesson could look in Java: +This is how the lesson could look in Java/Python:
```suggestion This is how the lesson could look: ``` No need to duplicate the language name, which can be seen in the tabs.
timefold-solver
github_2023
others
1,047
TimefoldAI
triceo
@@ -179,35 +222,76 @@ Let's instead remove them from the cross-product entirely. For the first lesson in the join, also called “left,” we put the cancellation check before the join like so: -[source, java] +[tabs] +==== +Java:: ++ +[source, java, options="nowrap"] ---- constraintFactory.forEach(Lesson.class) .filter(lesson -> !lesson.isCancelled()) .join(Lesson.class) .filter((leftLesson, rightLesson) -> !rightLesson.isCancelled() - && leftLesson.getTeacher() == rightLesson.getTeacher() + && leftLesson.getTeacher().equals(rightLesson.getTeacher())
Technically, I think the previous example was correct too; the model should ensure there are never two instances which equal. It's a problem fact, those don't need identity.
timefold-solver
github_2023
others
1,047
TimefoldAI
triceo
@@ -5,39 +5,53 @@ :sectnums: :icons: font -Using Java's Streams API, +Using Java's Streams API or Python's generator expressions,
This is another example where maybe talking about a particular language doesn't make sense anymore. This can be "Let's implement ... using a functional approach:". Then inside the tab for a particular language, we can add more details specific to that language, if we need to.
timefold-solver
github_2023
others
1,047
TimefoldAI
triceo
@@ -5,39 +5,53 @@ :sectnums: :icons: font -Using Java's Streams API, +Using Java's Streams API or Python's generator expressions, we could implement an xref:constraints-and-score/score-calculation.adoc#easyJavaScoreCalculation[easy score calculator] that uses a functional approach: +[tabs] +==== +Java:: ++ [source,java,options="nowrap"] ---- private int doNotAssignAnn() { - int softScore = 0; - schedule.getShifts().stream() + return schedule.getShifts().stream() .filter(Shift::isEmployeeAnn) - .forEach(shift -> { - softScore -= 1; - }); - return softScore; + .mapToInt(shift -> -1) + .sum(); } ---- +Python:: ++ +[source,python,options="nowrap"] +---- +def do_not_assign_ann() -> int: + return sum(-1 for shift in schedule.shifts if shift.employee == 'Ann'); +---- +==== + However, that scales poorly because it doesn't do an xref:constraints-and-score/performance.adoc#incrementalScoreCalculation[incremental calculation]: When the planning variable of a single `Shift` changes, to recalculate the score, the normal Streams API has to execute the entire stream from scratch. [#constraintStreams] == Introducing Constraint Streams -Constraint streams are a Functional Programming form of incremental score calculation in plain Java +Constraint streams are a Functional Programming form of incremental score calculation in plain Java, Python or Kotlin
```suggestion Constraint streams are a functional programming form of incremental score calculation ```
timefold-solver
github_2023
others
1,047
TimefoldAI
triceo
@@ -5,39 +5,53 @@ :sectnums: :icons: font -Using Java's Streams API, +Using Java's Streams API or Python's generator expressions, we could implement an xref:constraints-and-score/score-calculation.adoc#easyJavaScoreCalculation[easy score calculator] that uses a functional approach: +[tabs] +==== +Java:: ++ [source,java,options="nowrap"] ---- private int doNotAssignAnn() { - int softScore = 0; - schedule.getShifts().stream() + return schedule.getShifts().stream() .filter(Shift::isEmployeeAnn) - .forEach(shift -> { - softScore -= 1; - }); - return softScore; + .mapToInt(shift -> -1) + .sum(); } ---- +Python:: ++ +[source,python,options="nowrap"] +---- +def do_not_assign_ann() -> int: + return sum(-1 for shift in schedule.shifts if shift.employee == 'Ann'); +---- +==== + However, that scales poorly because it doesn't do an xref:constraints-and-score/performance.adoc#incrementalScoreCalculation[incremental calculation]: When the planning variable of a single `Shift` changes, to recalculate the score, the normal Streams API has to execute the entire stream from scratch. [#constraintStreams] == Introducing Constraint Streams -Constraint streams are a Functional Programming form of incremental score calculation in plain Java +Constraint streams are a Functional Programming form of incremental score calculation in plain Java, Python or Kotlin that is easy to read, write and debug. The API should feel familiar if you're familiar with Java Streams or SQL. -The Constraint Streams API enables you to write similar code in pure Java, +The Constraint Streams API enables you to write similar code in pure Java, Python or Kotlin,
```suggestion The Constraint Streams API enables you to write similar code in a language of your choice, ```
timefold-solver
github_2023
others
1,047
TimefoldAI
triceo
@@ -72,9 +99,13 @@ image::constraints-and-score/score-calculation/constraintStreamJustification.png [#constraintStreamsConfiguration] == Creating a constraint stream -To use the Constraint Streams API in your project, first write a pure Java `ConstraintProvider` implementation similar +To use the Constraint Streams API in your project, first write a pure Java, Python or Kotlin `ConstraintProvider` implementation similar
```suggestion To use the Constraint Streams API in your project, first write a `ConstraintProvider` implementation similar ```
timefold-solver
github_2023
others
1,047
TimefoldAI
triceo
@@ -666,17 +1052,35 @@ collector. The following code snippet first groups all visits by the vehicle that will be used, and averages all the service durations using the `ConstraintCollectors.average(...)` collector. +[tabs] +==== +Java:: ++ [source,java,options="nowrap"] ---- private Constraint averageServiceDuration(ConstraintFactory constraintFactory) { return constraintFactory.forEach(Visit.class) .groupBy(Visit::getVehicle, average(Visit::getServiceDuration)) .penalize(HardSoftScore.ONE_SOFT, - (vehicle, averageServiceDuration) -> averageServiceDuration) + (vehicle, averageServiceDuration) -> (int) averageServiceDuration)
Personally, I'd prefer `HardSoftLongScore` and removing the cast. Simpler code for the example.
timefold-solver
github_2023
others
1,047
TimefoldAI
triceo
@@ -1350,23 +2226,67 @@ The following example uses the Constraint Verifier API to create a simple unit t } ---- +Python:: ++ +[source,python,options="nowrap"] +---- +from timefold.solver.test import ConstraintVerifier +from datetime import datetime, date, time, timedelta +from .constraints import vehicle_routing_constraints, vehicle_capacity + +constraint_verifier = ConstraintVerifier.build(vehicle_routing_constraints, VehicleRoutePlan, Vehicle, Visit) + +TOMORROW = date.today() + timedelta(days=1) + +def test_vehicle_capacity(): + tomorrow_07_00 = datetime.combine(TOMORROW, time(7, 0)) + tomorrow_08_00 = datetime.combine(TOMORROW, time(8, 0)) + tomorrow_10_00 = datetime.combine(TOMORROW, time(10, 0)) + + vehicleA = Vehicle("1", 100, LOCATION_1, tomorrow_07_00) + visit1 = Visit("2", "John", LOCATION_2, 80, tomorrow_08_00, tomorrow_10_00, timedelta(minutes=30)) + vehicleA.visits.append(visit1) + visit2 = Visit("3", "Paul", LOCATION_3, 40, tomorrow_08_00, tomorrow_10_00, timedelta(minutes=30)) + vehicleA.visits.append(visit2) + + (constraint_verifier.verify_that(vehicle_capacity) + .given(vehicleA, visit1, visit2) + .penalizes_by(20)) +---- +==== + This test ensures that, if a vehicle capacity is exceeded, that the constraint penalizes accordingly. The following line creates a shared `ConstraintVerifier` instance and initializes the instance with the `VehicleRoutingConstraintProvider`: - +[tabs] +==== +Java:: ++ [source,java,options="nowrap"] ---- private ConstraintVerifier<VehicleRoutingConstraintProvider, VehicleRoutePlan> constraintVerifier - = ConstraintVerifier.build(new VehicleRoutingConstraintProvider(), Vehicle.class, Visit.class); + = ConstraintVerifier.build(new VehicleRoutingConstraintProvider(), VehicleRoutePlan.class, Vehicle.class, Visit.class); ---- +Python:: ++ +[source,python,options="nowrap"] +---- +constraint_verifier = ConstraintVerifier.build(vehicle_routing_constraints, VehicleRoutePlan, Vehicle, Visit) +---- +==== + The `@Test` annotation indicates that the method is a unit test in a testing framework of your choice. -Constraint Verifier works with many testing frameworks including JUnit and AssertJ. +Constraint Verifier works with many testing frameworks including JUnit, AssertJ and PyTest.
```suggestion Constraint Verifier works with testing frameworks popular in your ecosystem, including JUnit and PyTest. ```
timefold-solver
github_2023
others
1,047
TimefoldAI
triceo
@@ -1498,21 +2469,25 @@ public class MyConstraintProviderTest { Timefold Solver supports two other types of score calculation. [#easyJavaScoreCalculation] -=== Easy Java score calculation +=== Easy Java/Python score calculation -An easy way to implement your score calculation in Java. +An easy way to implement your score calculation in Java or Python.
```suggestion An easy way to implement your score calculation as imperative code: ```
timefold-solver
github_2023
others
1,047
TimefoldAI
triceo
@@ -1498,21 +2469,25 @@ public class MyConstraintProviderTest { Timefold Solver supports two other types of score calculation. [#easyJavaScoreCalculation] -=== Easy Java score calculation +=== Easy Java/Python score calculation
Same comment as above; specifically naming the technology seems unnecessary. The heading, as well as the references, should change.
timefold-solver
github_2023
others
1,047
TimefoldAI
triceo
@@ -1498,21 +2469,25 @@ public class MyConstraintProviderTest { Timefold Solver supports two other types of score calculation. [#easyJavaScoreCalculation] -=== Easy Java score calculation +=== Easy Java/Python score calculation -An easy way to implement your score calculation in Java. +An easy way to implement your score calculation in Java or Python. * Advantages: -** Plain old Java: no learning curve. +** Plain old Java/Python: no learning curve.
```suggestion ** No learning curve; use the language you're already familiar with. ```
timefold-solver
github_2023
others
1,047
TimefoldAI
triceo
@@ -1498,21 +2469,25 @@ public class MyConstraintProviderTest { Timefold Solver supports two other types of score calculation. [#easyJavaScoreCalculation] -=== Easy Java score calculation +=== Easy Java/Python score calculation -An easy way to implement your score calculation in Java. +An easy way to implement your score calculation in Java or Python. * Advantages: -** Plain old Java: no learning curve. +** Plain old Java/Python: no learning curve. ** Opportunity to delegate score calculation to an existing code base or legacy system. ** Useful for prototyping. * Disadvantages: ** Slower, typically not suitable for production. ** Does not scale because there is no xref:constraints-and-score/performance.adoc#incrementalScoreCalculation[incremental score calculation]. ** Can not xref:constraints-and-score/understanding-the-score.adoc[explain the score]. -To start using Easy Java score calculation, implement the one method of the interface ``EasyScoreCalculator``: +To start using Easy Java/Python score calculation, implement the one method of the interface ``EasyScoreCalculator``:
```suggestion To start using Easy score calculator, implement the one method of the interface ``EasyScoreCalculator``: ```
timefold-solver
github_2023
others
1,047
TimefoldAI
triceo
@@ -1547,9 +2534,9 @@ add the `easyScoreCalculatorCustomProperties` element and use xref:using-timefol [#incrementalJavaScoreCalculation] -=== Incremental Java score calculation +=== Incremental Java/Python score calculation
Dtto.
timefold-solver
github_2023
others
1,047
TimefoldAI
triceo
@@ -1547,9 +2534,9 @@ add the `easyScoreCalculatorCustomProperties` element and use xref:using-timefol [#incrementalJavaScoreCalculation] -=== Incremental Java score calculation +=== Incremental Java/Python score calculation -A way to implement your score calculation incrementally in Java. +A way to implement your score calculation incrementally in Java or Python.
```suggestion A way to implement your score calculation incrementally in a supported programming language. ```
timefold-solver
github_2023
others
1,047
TimefoldAI
triceo
@@ -1561,9 +2548,13 @@ Why not have <<constraintStreams,constraint streams>> do the hard work for you? ** Hard to read *** Regular score constraint changes can lead to high maintenance costs. -To start using Incremental Java score calculation, +To start using Incremental Java/Python score calculation,
```suggestion To start using Incremental score calculator, ```
timefold-solver
github_2023
others
1,047
TimefoldAI
triceo
@@ -86,6 +87,40 @@ repositories { } ---- -- + +Pyproject.toml::
I question if we want to do this. We don't want to push Python to Enterprise users, at least not yet. Having documentation for it suggests that Timefold will support it; this is not the case.
timefold-solver
github_2023
others
1,047
TimefoldAI
triceo
@@ -122,7 +122,7 @@ by changing the solver configuration in a few lines of code. == Status of Timefold Solver Timefold Solver is 100% pure Java^TM^ and runs on Java {java-version} or higher. -It xref:integration/integration.adoc#integration[integrates very easily] with other Java^TM^ technologies. +It xref:integration/integration.adoc#integration[integrates very easily] with other Java^TM^ and Python technologies.
```suggestion It xref:integration/integration.adoc#integration[integrates very easily] with other Java^TM^, Python and other technologies. ```
timefold-solver
github_2023
others
1,047
TimefoldAI
triceo
@@ -66,12 +85,16 @@ These various parts of a configuration are explained further in this manual. [#solverConfigurationByJavaAPI] -== Solver configuration by Java API +== Solver configuration by Java/Python API
```suggestion == Solver configuration as code ``` Please also update the ID and all links.
timefold-solver
github_2023
others
1,047
TimefoldAI
triceo
@@ -121,10 +189,10 @@ Timefold Solver needs to be told which classes in your domain model are planning which properties are planning variables, etc. There are several ways to deliver this information: -* Add class annotations and JavaBean property annotations on the domain model (recommended). +* Add class annotations and JavaBean property annotations on the domain model (recommended in Java). The property annotations must be on the getter method, not on the setter method. Such a getter does not need to be public. -* Add class annotations and field annotations on the domain model. +* Add class annotations and field annotations on the domain model (recommended in Python). Such a field does not need to be public.
Do we want tabs for this? It's different enough.
timefold-solver
github_2023
others
1,047
TimefoldAI
triceo
@@ -31,14 +31,18 @@ In xref:responding-to-change/responding-to-change.adoc#realTimePlanning[real-tim To create a good domain model, read the xref:design-patterns/design-patterns.adoc#domainModelingGuide[domain modeling guide]. -*In Timefold Solver, all problem facts and planning entities are plain old JavaBeans (POJOs).* Load them from a database, an XML file, a data repository, a REST service, a noSQL cloud, ... (see xref:integration/integration.adoc#integration[integration]): it doesn't matter. +*In Timefold Solver, all problem facts and planning entities are plain old JavaBeans (POJOs) or Python objects.* Load them from a database, an XML file, a data repository, a REST service, a noSQL cloud, ... (see xref:integration/integration.adoc#integration[integration]): it doesn't matter.
```suggestion *In Timefold Solver, all problem facts and planning entities are plain objects.* Load them from a database, an XML file, a data repository, a REST service, a noSQL cloud, ... (see xref:integration/integration.adoc#integration[integration]): it doesn't matter. ```
timefold-solver
github_2023
others
1,047
TimefoldAI
triceo
@@ -31,14 +31,18 @@ In xref:responding-to-change/responding-to-change.adoc#realTimePlanning[real-tim To create a good domain model, read the xref:design-patterns/design-patterns.adoc#domainModelingGuide[domain modeling guide]. -*In Timefold Solver, all problem facts and planning entities are plain old JavaBeans (POJOs).* Load them from a database, an XML file, a data repository, a REST service, a noSQL cloud, ... (see xref:integration/integration.adoc#integration[integration]): it doesn't matter. +*In Timefold Solver, all problem facts and planning entities are plain old JavaBeans (POJOs) or Python objects.* Load them from a database, an XML file, a data repository, a REST service, a noSQL cloud, ... (see xref:integration/integration.adoc#integration[integration]): it doesn't matter. [#problemFact] == Problem fact -A problem fact is any JavaBean (POJO) with getters that does not change during planning. +A problem fact is any JavaBean (POJO) or Python object with getters that does not change during planning.
```suggestion A problem fact is any object with getters that does not change during planning. ```
timefold-solver
github_2023
others
1,047
TimefoldAI
triceo
@@ -1121,7 +1583,7 @@ For example, none of the `timeslot` variables of any `Lesson` may be used to det Use the planning list variable to model problems where the goal is to distribute a number of workload elements among limited resources in a specific order. This includes, for example, vehicle routing, traveling salesman, task assigning, and similar problems, that have previously been modeled using the <<chainedPlanningVariable,chained planning variable>>. -The planning list variable is a successor to the chained planning variable and provides a more intuitive way to express the problem domain with Java classes. +The planning list variable is a successor to the chained planning variable and provides a more intuitive way to express the problem domain with Java/Python classes.
```suggestion The planning list variable is a successor to the chained planning variable and provides a more intuitive way to express the problem domain. ```
timefold-solver
github_2023
others
1,047
TimefoldAI
triceo
@@ -394,23 +491,23 @@ Variants of this `Score` type: [#scoreCalculationTypes] === Score calculation types -There are several ways to calculate the `Score` of a solution in Java or another JVM language: +There are several ways to calculate the `Score` of a solution in Java, Python or another JVM language:
```suggestion There are several ways to calculate the `Score` of a solution: ```
timefold-solver
github_2023
java
1,020
TimefoldAI
triceo
@@ -3,54 +3,24 @@ import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.RetentionPolicy.RUNTIME; -import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.Target; -import ai.timefold.solver.core.api.domain.entity.PlanningEntity; - /** - * Specifies that field may be updated by the target method when one or more source variables change. + * Specifies that field may be updated by the target method when a dependency changes. * <p> - * Automatically cascades change events to {@link NextElementShadowVariable} of a {@link PlanningListVariable}. + * Automatically cascades change events to the next elements of a {@link PlanningListVariable}.
```suggestion * Automatically cascades change events to the subsequent elements of a {@link PlanningListVariable}. ```
timefold-solver
github_2023
java
1,020
TimefoldAI
triceo
@@ -3,54 +3,24 @@ import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.RetentionPolicy.RUNTIME; -import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.Target; -import ai.timefold.solver.core.api.domain.entity.PlanningEntity; - /** - * Specifies that field may be updated by the target method when one or more source variables change. + * Specifies that field may be updated by the target method when a dependency changes.
```suggestion * Specifies that a field may be updated by the target method when any of its variables change, genuine or shadow. ``` Is this correct?
timefold-solver
github_2023
java
1,020
TimefoldAI
triceo
@@ -3,54 +3,24 @@ import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.RetentionPolicy.RUNTIME; -import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.Target; -import ai.timefold.solver.core.api.domain.entity.PlanningEntity; - /** - * Specifies that field may be updated by the target method when one or more source variables change. + * Specifies that field may be updated by the target method when a dependency changes. * <p> - * Automatically cascades change events to {@link NextElementShadowVariable} of a {@link PlanningListVariable}. + * Automatically cascades change events to the next elements of a {@link PlanningListVariable}. * <p> * Important: it must only change the shadow variable(s) for which it's configured. - * It is only possible to define either {@code sourceVariableName} or {@code sourceVariableNames}. * It can be applied to multiple fields to modify different shadow variables. * It should never change a genuine variable or a problem fact. * It can change its shadow variable(s) on multiple entity instances * (for example: an arrivalTime change affects all trailing entities too). */ @Target({ FIELD }) @Retention(RUNTIME) -@Repeatable(CascadingUpdateShadowVariable.List.class) public @interface CascadingUpdateShadowVariable {
The Javadoc should also discuss the differences between this and a shadow variable. Specifically, that nothing is allowed to depend on it, and that it will always be processed after all other shadow variables have been updated. Maybe it should discuss what happens if multiple cascading vars on the same entity instance depend on each other. (Because they share fields.)
timefold-solver
github_2023
java
1,020
TimefoldAI
triceo
@@ -49,56 +49,62 @@ public void linkVariableDescriptors(DescriptorPolicy descriptorPolicy) { private void linkSourceVariableDescriptorToListenerClass(ShadowVariable shadowVariable) { EntityDescriptor<Solution_> sourceEntityDescriptor; - Class<?> sourceEntityClass = shadowVariable.sourceEntityClass(); + var sourceEntityClass = shadowVariable.sourceEntityClass(); if (sourceEntityClass.equals(ShadowVariable.NullEntityClass.class)) { sourceEntityDescriptor = entityDescriptor; } else { sourceEntityDescriptor = entityDescriptor.getSolutionDescriptor().findEntityDescriptor(sourceEntityClass); if (sourceEntityDescriptor == null) { - throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass() - + ") has a @" + ShadowVariable.class.getSimpleName() - + " annotated property (" + variableMemberAccessor.getName() - + ") with a sourceEntityClass (" + sourceEntityClass - + ") which is not a valid planning entity." - + "\nMaybe check the annotations of the class (" + sourceEntityClass + ")." - + "\nMaybe add the class (" + sourceEntityClass - + ") among planning entities in the solver configuration."); + throw new IllegalArgumentException( + """ + The entityClass (%s) has a @%s annotated property (%s) with a sourceEntityClass (%s) which is not a valid planning entity. + Maybe check the annotations of the class (%s). + Maybe add the class (%s) among planning entities in the solver configuration.""" + .formatted(entityDescriptor.getEntityClass(), ShadowVariable.class.getSimpleName(), + variableMemberAccessor.getName(), sourceEntityClass, sourceEntityClass, + sourceEntityClass)); } } - String sourceVariableName = shadowVariable.sourceVariableName(); - VariableDescriptor<Solution_> sourceVariableDescriptor = - sourceEntityDescriptor.getVariableDescriptor(sourceVariableName); + var sourceVariableName = shadowVariable.sourceVariableName(); + var sourceVariableDescriptor = sourceEntityDescriptor.getVariableDescriptor(sourceVariableName); if (sourceVariableDescriptor == null) { - throw new IllegalArgumentException("The entityClass (" + entityDescriptor.getEntityClass() - + ") has a @" + ShadowVariable.class.getSimpleName() - + " annotated property (" + variableMemberAccessor.getName() - + ") with sourceVariableName (" + sourceVariableName - + ") which is not a valid planning variable on entityClass (" - + sourceEntityDescriptor.getEntityClass() + ").\n" - + sourceEntityDescriptor.buildInvalidVariableNameExceptionMessage(sourceVariableName)); + throw new IllegalArgumentException( + """ + The entityClass (%s) has a @%s annotated property (%s) with sourceVariableName (%s) which is not a valid planning variable on entityClass (%s). + %s""" + .formatted(entityDescriptor.getEntityClass(), ShadowVariable.class.getSimpleName(), + variableMemberAccessor.getName(), sourceVariableName, + sourceEntityDescriptor.getEntityClass(), + sourceEntityDescriptor.buildInvalidVariableNameExceptionMessage(sourceVariableName))); } - Class<? extends AbstractVariableListener> variableListenerClass = shadowVariable.variableListenerClass(); + if (!sourceVariableDescriptor.canBeUsedAsSource()) { + throw new IllegalArgumentException( + "The entityClass (%s) has a @%s annotated property (%s) with sourceVariableName (%s) which cannot be used as source."
Maybe these new exceptions should explain _why_ that's not the case. What did the user do wrong? From the message, it's not at all clear.
timefold-solver
github_2023
java
1,020
TimefoldAI
triceo
@@ -33,12 +36,26 @@ public static <Solution_> VariableListenerSupport<Solution_> create(InnerScoreDi private final NotifiableRegistry<Solution_> notifiableRegistry; private final Map<Demand<?>, SupplyWithDemandCount> supplyMap = new HashMap<>(); + private final List<ListVariableEvent> listVariableEventList; + private final ListVariableDescriptor<Solution_> listVariableDescriptor; + private final List<CascadingUpdateShadowVariableDescriptor<Solution_>> cascadingUpdateShadowVarDescriptorList; + private boolean notificationQueuesAreEmpty = true; private int nextGlobalOrder = 0; VariableListenerSupport(InnerScoreDirector<Solution_, ?> scoreDirector, NotifiableRegistry<Solution_> notifiableRegistry) { this.scoreDirector = scoreDirector; this.notifiableRegistry = notifiableRegistry; + this.cascadingUpdateShadowVarDescriptorList = scoreDirector.getSolutionDescriptor().getEntityDescriptors().stream() + .flatMap(e -> e.getDeclaredCascadingUpdateShadowVariableDescriptors().stream()) + .toList(); + this.listVariableDescriptor = scoreDirector.getSolutionDescriptor().getEntityDescriptors().stream()
Afaik `SolutionDescriptor` has a method which can already retrieve the one and only list variable descriptor.
timefold-solver
github_2023
java
1,020
TimefoldAI
triceo
@@ -33,12 +36,26 @@ public static <Solution_> VariableListenerSupport<Solution_> create(InnerScoreDi private final NotifiableRegistry<Solution_> notifiableRegistry; private final Map<Demand<?>, SupplyWithDemandCount> supplyMap = new HashMap<>(); + private final List<ListVariableEvent> listVariableEventList; + private final ListVariableDescriptor<Solution_> listVariableDescriptor; + private final List<CascadingUpdateShadowVariableDescriptor<Solution_>> cascadingUpdateShadowVarDescriptorList; + private boolean notificationQueuesAreEmpty = true; private int nextGlobalOrder = 0; VariableListenerSupport(InnerScoreDirector<Solution_, ?> scoreDirector, NotifiableRegistry<Solution_> notifiableRegistry) { this.scoreDirector = scoreDirector; this.notifiableRegistry = notifiableRegistry; + this.cascadingUpdateShadowVarDescriptorList = scoreDirector.getSolutionDescriptor().getEntityDescriptors().stream() + .flatMap(e -> e.getDeclaredCascadingUpdateShadowVariableDescriptors().stream()) + .toList(); + this.listVariableDescriptor = scoreDirector.getSolutionDescriptor().getEntityDescriptors().stream() + .flatMap(e -> e.getGenuineVariableDescriptorList().stream()) + .filter(VariableDescriptor::isListVariable) + .map(d -> (ListVariableDescriptor<Solution_>) d) + .findFirst() + .orElse(null); + this.listVariableEventList = new LinkedList<>();
Please don't use `LinkedList`. https://kjellkod.wordpress.com/2012/02/25/why-you-should-never-ever-ever-use-linked-list-in-your-code-again/ I know that it has theoretical benefits in computer science, but in computer reality, they are no longer valid.
timefold-solver
github_2023
java
1,020
TimefoldAI
triceo
@@ -195,34 +212,69 @@ public void beforeListVariableChanged(ListVariableDescriptor<Solution_> variable public void afterListVariableChanged(ListVariableDescriptor<Solution_> variableDescriptor, Object entity, int fromIndex, int toIndex) { - Collection<ListVariableListenerNotifiable<Solution_>> notifiables = notifiableRegistry.get(variableDescriptor); + var notifiables = notifiableRegistry.get(variableDescriptor); if (!notifiables.isEmpty()) { ListVariableNotification<Solution_> notification = Notification.listVariableChanged(entity, fromIndex, toIndex); - for (ListVariableListenerNotifiable<Solution_> notifiable : notifiables) { + for (var notifiable : notifiables) { notifiable.notifyAfter(notification); } notificationQueuesAreEmpty = false; } + listVariableEventList.add(new ListVariableEvent(entity, fromIndex, toIndex)); } public void triggerVariableListenersInNotificationQueues() { - for (Notifiable notifiable : notifiableRegistry.getAll()) { + for (var notifiable : notifiableRegistry.getAll()) { notifiable.triggerAllNotifications(); } + if (listVariableDescriptor != null && !cascadingUpdateShadowVarDescriptorList.isEmpty()) { + triggerCascadingUpdateShadowVariableUpdate(); + } notificationQueuesAreEmpty = true; + listVariableEventList.clear(); + } + + /** + * Triggers all cascading update shadow variable user-logic. + */ + private void triggerCascadingUpdateShadowVariableUpdate() { + if (listVariableEventList.isEmpty() || cascadingUpdateShadowVarDescriptorList.isEmpty()) { + return; + } + for (var cascadingUpdateShadowVariableDescriptor : cascadingUpdateShadowVarDescriptorList) { + for (var event : listVariableEventList) { + var values = listVariableDescriptor.getValue(event.entity()); + // Evaluate all elements inside the range + evaluateFromIndex(values, event.fromIndex(), event.toIndex(), true, cascadingUpdateShadowVariableDescriptor); + // Evaluate later elements, but stops when there is no change + evaluateFromIndex(values, event.toIndex(), values.size(), false, cascadingUpdateShadowVariableDescriptor);
I find it surprising that this is faster than the alternatives discussed. If there's two events to say `process the entire list`, this will do it twice, even though it's unnecessary.
timefold-solver
github_2023
others
1,020
TimefoldAI
triceo
@@ -1427,7 +1427,13 @@ A user-defined logic can only change shadow variables. It must never change a genuine planning variable or a problem fact. ==== -==== Multiple shadow variables +[WARNING]
```suggestion [NOTE] ```
timefold-solver
github_2023
others
1,020
TimefoldAI
triceo
@@ -1462,6 +1468,11 @@ It is not allowed to specify the property `shadowEntityClass` in `@PiggybackShad when the source shadow variable is `@CascadingUpdateShadowVariable`. ==== +[WARNING] +==== +The user's logic is responsible for defining the order in which each variable is updated.
I don't understand what this is trying to say. Maybe it needs a bit of context? Not sure if it's a warning. If it has more text explaining why this is bad, then I say it could be a warning.
timefold-solver
github_2023
java
1,020
TimefoldAI
triceo
@@ -195,34 +207,69 @@ public void beforeListVariableChanged(ListVariableDescriptor<Solution_> variable public void afterListVariableChanged(ListVariableDescriptor<Solution_> variableDescriptor, Object entity, int fromIndex, int toIndex) { - Collection<ListVariableListenerNotifiable<Solution_>> notifiables = notifiableRegistry.get(variableDescriptor); + var notifiables = notifiableRegistry.get(variableDescriptor); if (!notifiables.isEmpty()) { ListVariableNotification<Solution_> notification = Notification.listVariableChanged(entity, fromIndex, toIndex); - for (ListVariableListenerNotifiable<Solution_> notifiable : notifiables) { + for (var notifiable : notifiables) { notifiable.notifyAfter(notification); } notificationQueuesAreEmpty = false; } + listVariableEventList.add(new ListVariableEvent(entity, fromIndex, toIndex)); } public void triggerVariableListenersInNotificationQueues() { - for (Notifiable notifiable : notifiableRegistry.getAll()) { + for (var notifiable : notifiableRegistry.getAll()) { notifiable.triggerAllNotifications(); } + if (listVariableDescriptor != null && !cascadingUpdateShadowVarDescriptorList.isEmpty()) { + triggerCascadingUpdateShadowVariableUpdate(); + } notificationQueuesAreEmpty = true; + listVariableEventList.clear(); + } + + /** + * Triggers all cascading update shadow variable user-logic. + */ + private void triggerCascadingUpdateShadowVariableUpdate() { + if (listVariableEventList.isEmpty() || cascadingUpdateShadowVarDescriptorList.isEmpty()) { + return; + } + for (var cascadingUpdateShadowVariableDescriptor : cascadingUpdateShadowVarDescriptorList) { + for (var event : listVariableEventList) { + var values = listVariableDescriptor.getValue(event.entity()); + // Evaluate all elements inside the range + evaluateFromIndex(values, event.fromIndex(), event.toIndex(), true, cascadingUpdateShadowVariableDescriptor); + // Evaluate later elements, but stops when there is no change + evaluateFromIndex(values, event.toIndex(), values.size(), false, cascadingUpdateShadowVariableDescriptor); + } + } + } + + private void evaluateFromIndex(List<Object> values, int fromIndex, int toIndex, boolean forceUpdate, + CascadingUpdateShadowVariableDescriptor<Solution_> cascadingUpdateShadowVariableDescriptor) { + var lastUpdated = fromIndex; + while (lastUpdated < toIndex) { + if (!cascadingUpdateShadowVariableDescriptor.update(scoreDirector, values.get(lastUpdated)) + && !forceUpdate) { + break; + } + lastUpdated++; + } } /** * @return null if there are no violations */ public String createShadowVariablesViolationMessage() { - Solution_ workingSolution = scoreDirector.getWorkingSolution(); - ShadowVariablesAssert snapshot = + var workingSolution = scoreDirector.getWorkingSolution(); + var snapshot = ShadowVariablesAssert.takeSnapshot(scoreDirector.getSolutionDescriptor(), workingSolution); forceTriggerAllVariableListeners(workingSolution); - final int SHADOW_VARIABLE_VIOLATION_DISPLAY_LIMIT = 3; + final var SHADOW_VARIABLE_VIOLATION_DISPLAY_LIMIT = 3;
We don't use `final` for local variables. Also, arguably this should be standard `camelCase`, unless you want to make it a class-level constant. (Which it probably should be.)
timefold-solver
github_2023
others
1,020
TimefoldAI
triceo
@@ -1412,98 +1414,23 @@ public class Customer { The `targetMethodName` refers to the user-defined logic that updates the annotated shadow variable. The method must be implemented in the defining entity class, be non-static, and not include any parameters. -The `sourceVariableName` property is the planning variable's name on the getter's return type, -which will trigger the cascade update listener in case of changes. - In the previous example, -the cascade update listener calls `updateArrivalTime` whenever `previousCustomer` changes. -It then automatically calls `updateArrivalTime` for the subsequent `nextCustomer` elements +the cascade update listener calls `updateArrivalTime` after all shadow variables have been updated, +including `vehicle` and `previousCustomer`. +It then automatically calls `updateArrivalTime` for the subsequent customers and stops when the `arrivalTime` value does not change after running target method or when it reaches the end. -The shadow variable `nextCustomer` is not required, but defining it in the model is recommended: - -[source,java] ----- -@PlanningEntity -public class Customer { - - @PreviousElementShadowVariable(sourceVariableName = "customers") - private Customer previousCustomer; - @CascadingUpdateShadowVariable(targetMethodName = "updateArrivalTime", sourceVariableName = "previousCustomer") - private LocalDateTime arrivalTime; - - ... - - public void updateArrivalTime() {...} ----- - -It is also possible to define multiple sources per variable: - -[source,java] ----- -@PlanningEntity -public class Customer { - - @InverseRelationShadowVariable(sourceVariableName = "customers") - private Vehicle vehicle; - @PreviousElementShadowVariable(sourceVariableName = "customers") - private Customer previousCustomer; - @NextElementShadowVariable(sourceVariableName = "customers") - private Customer nextCustomer; - @CascadingUpdateShadowVariable(targetMethodName = "updateArrivalTime", sourceVariableNames = {"vehicle", "previousCustomer"}) - private LocalDateTime arrivalTime; - - ... - - public void updateArrivalTime() {...} ----- - -The listener behaves as described previously. -It calls `updateArrivalTime` whenever a `previousCustomer` or `vehicle` changes. -It then propagates the changes to the subsequent elements, -stopping when the method results in no change to the variable, or when it reaches the tail. - [WARNING] ==== A user-defined logic can only change shadow variables. It must never change a genuine planning variable or a problem fact. ==== -==== Multiple source variables - -If the user-defined logic requires updating multiple shadow variables, -apply the `@CascadingUpdateShadowVariable` annotation to only one shadow variable, -and specify the sources and target method. -Next, -use the `@PiggybackShadowVariable` for all other shadow variables -that will also be updated by the specified target method. - -[source,java] ----- -@PlanningEntity -public class Customer { - - @PreviousElementShadowVariable(sourceVariableName = "customers") - private Customer previousCustomer; - @NextElementShadowVariable(sourceVariableName = "customers") - private Customer nextCustomer; - @CascadingUpdateShadowVariable(targetMethodName = "updateWeightAndArrivalTime", sourceVariableName = "previousCustomer") - private LocalDateTime arrivalTime; - @PiggybackShadowVariable(shadowVariableName = "arrivalTime") - private Integer weightAtVisit; - ... - - public void updateWeightAndArrivalTime() {...} ----- - -Timefold Solver triggers a single listener to run the user-defined logic whenever `previousCustomer` changes. -It stops when both `arrivalTime` and `weightAtVisit` values do not change or when it reaches the end. - -[WARNING] +[NOTE] ==== -It is not allowed to specify the property `shadowEntityClass` in `@PiggybackShadowVariable` -when the source shadow variable is `@CascadingUpdateShadowVariable`. +When distinct target methods are used by separate `@CascadingUpdateShadowVariable` variables in the same model, +there will be no guarantees regarding which target method is executed first.
```suggestion the order of their execution is undefined. ```
timefold-solver
github_2023
others
1,020
TimefoldAI
triceo
@@ -1412,98 +1414,23 @@ public class Customer { The `targetMethodName` refers to the user-defined logic that updates the annotated shadow variable. The method must be implemented in the defining entity class, be non-static, and not include any parameters. -The `sourceVariableName` property is the planning variable's name on the getter's return type, -which will trigger the cascade update listener in case of changes. - In the previous example, -the cascade update listener calls `updateArrivalTime` whenever `previousCustomer` changes. -It then automatically calls `updateArrivalTime` for the subsequent `nextCustomer` elements +the cascade update listener calls `updateArrivalTime` after all shadow variables have been updated, +including `vehicle` and `previousCustomer`. +It then automatically calls `updateArrivalTime` for the subsequent customers and stops when the `arrivalTime` value does not change after running target method or when it reaches the end. -The shadow variable `nextCustomer` is not required, but defining it in the model is recommended: - -[source,java] ----- -@PlanningEntity -public class Customer { - - @PreviousElementShadowVariable(sourceVariableName = "customers") - private Customer previousCustomer; - @CascadingUpdateShadowVariable(targetMethodName = "updateArrivalTime", sourceVariableName = "previousCustomer") - private LocalDateTime arrivalTime; - - ... - - public void updateArrivalTime() {...} ----- - -It is also possible to define multiple sources per variable: - -[source,java] ----- -@PlanningEntity -public class Customer { - - @InverseRelationShadowVariable(sourceVariableName = "customers") - private Vehicle vehicle; - @PreviousElementShadowVariable(sourceVariableName = "customers") - private Customer previousCustomer; - @NextElementShadowVariable(sourceVariableName = "customers") - private Customer nextCustomer; - @CascadingUpdateShadowVariable(targetMethodName = "updateArrivalTime", sourceVariableNames = {"vehicle", "previousCustomer"}) - private LocalDateTime arrivalTime; - - ... - - public void updateArrivalTime() {...} ----- - -The listener behaves as described previously. -It calls `updateArrivalTime` whenever a `previousCustomer` or `vehicle` changes. -It then propagates the changes to the subsequent elements, -stopping when the method results in no change to the variable, or when it reaches the tail. - [WARNING] ==== A user-defined logic can only change shadow variables. It must never change a genuine planning variable or a problem fact.
```suggestion Changing a genuine planning variable or a problem fact will result in score corruption. ```
timefold-solver
github_2023
others
1,020
TimefoldAI
triceo
@@ -1371,8 +1371,10 @@ public class Customer { === Updating tail chains The annotation `@CascadingUpdateShadowVariable` provides a built-in listener that updates a set of connected elements. -Timefold Solver triggers a user-defined logic whenever the a defined source variable changes. -Moreover, it automatically propagates changes to the next elements when the value of the related shadow variable changes. +Timefold Solver triggers a user-defined logic after all events are processed. +Hence, the related listener is the final one executed during the event lifecycle. +Moreover, +it automatically propagates changes to the next elements when the value of the related shadow variable changes.
```suggestion it automatically propagates changes to the subsequent elements in the list when the value of the related shadow variable changes. ```
timefold-solver
github_2023
java
1,020
TimefoldAI
triceo
@@ -4,33 +4,36 @@ import ai.timefold.solver.core.api.domain.variable.CascadingUpdateShadowVariable; import ai.timefold.solver.core.api.domain.variable.InverseRelationShadowVariable; import ai.timefold.solver.core.api.domain.variable.NextElementShadowVariable; +import ai.timefold.solver.core.api.domain.variable.PiggybackShadowVariable; import ai.timefold.solver.core.api.domain.variable.PreviousElementShadowVariable; import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor; -import ai.timefold.solver.core.impl.testdata.domain.cascade.single_var.shadow_var.TestdataSingleCascadingEntity; -import ai.timefold.solver.core.impl.testdata.domain.cascade.single_var.shadow_var.TestdataSingleCascadingSolution; +import ai.timefold.solver.core.impl.testdata.domain.cascade.single_var.TestdataSingleCascadingEntity; +import ai.timefold.solver.core.impl.testdata.domain.cascade.single_var.TestdataSingleCascadingSolution; @PlanningEntity -public class TestdataCascadingNoSources { +public class TestdataCascadingPiggyback { public static EntityDescriptor<TestdataSingleCascadingSolution> buildEntityDescriptor() { return SolutionDescriptor .buildSolutionDescriptor(TestdataSingleCascadingSolution.class, TestdataSingleCascadingEntity.class, - TestdataCascadingNoSources.class) - .findEntityDescriptorOrFail(TestdataCascadingNoSources.class); + TestdataCascadingPiggyback.class) + .findEntityDescriptorOrFail(TestdataCascadingPiggyback.class); } @InverseRelationShadowVariable(sourceVariableName = "valueList") private TestdataSingleCascadingEntity entity; @PreviousElementShadowVariable(sourceVariableName = "valueList") - private TestdataCascadingNoSources previous; + private TestdataCascadingPiggyback previous; @NextElementShadowVariable(sourceVariableName = "valueList") - private TestdataCascadingNoSources next; + private TestdataCascadingPiggyback next; @CascadingUpdateShadowVariable(targetMethodName = "updateCascadeValue") private Integer cascadeValue; + @PiggybackShadowVariable(shadowVariableName = "cascadeValue") + private Integer cascadeValue2;
This should be no longer possible, right?
timefold-solver
github_2023
java
996
TimefoldAI
triceo
@@ -38,6 +40,18 @@ */ String[] sourceVariableNames() default {}; + /** + * The {@link PlanningEntity} class of the source variable. + * <p> + * Specified if the source variable is on a different {@link Class} than the class that uses this referencing annotation. + * + * @return {@link CascadingUpdateShadowVariable.NullEntityClass} when the attribute is omitted + * (workaround for annotation limitation). + * Defaults to the same {@link Class} as the one + * that uses this annotation.
```suggestion * Defaults to the same {@link Class} as the one that uses this annotation. ```
timefold-solver
github_2023
java
996
TimefoldAI
triceo
@@ -6,39 +6,51 @@ import ai.timefold.solver.core.api.domain.variable.VariableListener; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor; +import ai.timefold.solver.core.impl.domain.variable.cascade.command.CascadingUpdateCommand; +import ai.timefold.solver.core.impl.domain.variable.cascade.command.Pair; +import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; /** * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public abstract class AbstractCascadingUpdateShadowVariableListener<Solution_> implements VariableListener<Solution_, Object> { + private final CascadingUpdateCommand<Pair<Integer, Object>> indexElementCommand; + final ListVariableDescriptor<Solution_> sourceListVariableDescriptor; final List<VariableDescriptor<Solution_>> targetVariableDescriptorList; final MemberAccessor targetMethod;
Any chance we could make these protected? It's a minor issue; I just don't like to expose fields to the outside.
timefold-solver
github_2023
java
996
TimefoldAI
triceo
@@ -6,39 +6,51 @@ import ai.timefold.solver.core.api.domain.variable.VariableListener; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor; +import ai.timefold.solver.core.impl.domain.variable.cascade.command.CascadingUpdateCommand; +import ai.timefold.solver.core.impl.domain.variable.cascade.command.Pair; +import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; /** * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public abstract class AbstractCascadingUpdateShadowVariableListener<Solution_> implements VariableListener<Solution_, Object> { + private final CascadingUpdateCommand<Pair<Integer, Object>> indexElementCommand; + final ListVariableDescriptor<Solution_> sourceListVariableDescriptor; final List<VariableDescriptor<Solution_>> targetVariableDescriptorList; final MemberAccessor targetMethod; - AbstractCascadingUpdateShadowVariableListener(List<VariableDescriptor<Solution_>> targetVariableDescriptorList, - MemberAccessor targetMethod) { + AbstractCascadingUpdateShadowVariableListener(ListVariableDescriptor<Solution_> sourceListVariableDescriptor, + List<VariableDescriptor<Solution_>> targetVariableDescriptorList, MemberAccessor targetMethod, + CascadingUpdateCommand<Pair<Integer, Object>> indexElementCommand) { + this.sourceListVariableDescriptor = sourceListVariableDescriptor; this.targetVariableDescriptorList = targetVariableDescriptorList; this.targetMethod = targetMethod; + this.indexElementCommand = indexElementCommand; } abstract boolean execute(ScoreDirector<Solution_> scoreDirector, Object entity); - abstract Object getNextElement(Object entity); - @Override public void beforeVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity) { // Do nothing } @Override public void afterVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity) { - var currentEntity = entity; - while (currentEntity != null) { - if (!execute(scoreDirector, currentEntity)) { - break; + boolean isChanged = execute(scoreDirector, entity);
```suggestion var isChanged = execute(scoreDirector, entity); ``` Let's stick to this convention in new code, and do it consistently.
timefold-solver
github_2023
java
996
TimefoldAI
triceo
@@ -6,39 +6,51 @@ import ai.timefold.solver.core.api.domain.variable.VariableListener; import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor; +import ai.timefold.solver.core.impl.domain.variable.cascade.command.CascadingUpdateCommand; +import ai.timefold.solver.core.impl.domain.variable.cascade.command.Pair; +import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; /** * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public abstract class AbstractCascadingUpdateShadowVariableListener<Solution_> implements VariableListener<Solution_, Object> { + private final CascadingUpdateCommand<Pair<Integer, Object>> indexElementCommand; + final ListVariableDescriptor<Solution_> sourceListVariableDescriptor; final List<VariableDescriptor<Solution_>> targetVariableDescriptorList; final MemberAccessor targetMethod; - AbstractCascadingUpdateShadowVariableListener(List<VariableDescriptor<Solution_>> targetVariableDescriptorList, - MemberAccessor targetMethod) { + AbstractCascadingUpdateShadowVariableListener(ListVariableDescriptor<Solution_> sourceListVariableDescriptor, + List<VariableDescriptor<Solution_>> targetVariableDescriptorList, MemberAccessor targetMethod, + CascadingUpdateCommand<Pair<Integer, Object>> indexElementCommand) { + this.sourceListVariableDescriptor = sourceListVariableDescriptor; this.targetVariableDescriptorList = targetVariableDescriptorList; this.targetMethod = targetMethod; + this.indexElementCommand = indexElementCommand; } abstract boolean execute(ScoreDirector<Solution_> scoreDirector, Object entity); - abstract Object getNextElement(Object entity); - @Override public void beforeVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity) { // Do nothing } @Override public void afterVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity) { - var currentEntity = entity; - while (currentEntity != null) { - if (!execute(scoreDirector, currentEntity)) { - break; + boolean isChanged = execute(scoreDirector, entity); + if (isChanged) { + var indexElement = indexElementCommand.getValue(entity); + if (indexElement != null) { + int fromIndex = indexElement.firstValue(); + List<Object> values = sourceListVariableDescriptor.getValue(indexElement.secondValue()); + for (int i = fromIndex + 1; i < values.size(); i++) {
`var`; won't mention it anymore, but the PR is full of this.
timefold-solver
github_2023
java
996
TimefoldAI
triceo
@@ -110,13 +110,22 @@ public void linkVariableDescriptors(DescriptorPolicy descriptorPolicy) { v -> v.getEntityDescriptor().getEntityClass().getSimpleName() + "::" + v.getVariableName()) .collect(joining(", ")))); } - sourceListVariable = (ListVariableDescriptor<Solution_>) listVariableDescriptorList.get(0); + sourceListVariableDescriptor = (ListVariableDescriptor<Solution_>) listVariableDescriptorList.get(0); - nextElementShadowVariableDescriptor = entityDescriptor.getShadowVariableDescriptors().stream() - .filter(variableDescriptor -> NextElementShadowVariableDescriptor.class - .isAssignableFrom(variableDescriptor.getClass())) - .findFirst() - .orElse(null); + // Defining the source variable and the source entity class may result in references to different sources, + // such as regular shadow or planning list variables. + // In order to simplify implementation, + // the cascading listener can be configured for multiple shadow variables or a single planning list variable. + if (hasShadowVariable() && hasPlanningListVariable()) { + throw new IllegalArgumentException( + """ + The entity class (%s) has an @%s annotated properties, but the sources can be either a regular shadow variable or a planning list variable.
```suggestion The entity class (%s) has @%s-annotated properties, but the sources can be either a regular shadow variable or a planning list variable. ```
timefold-solver
github_2023
java
996
TimefoldAI
triceo
@@ -213,22 +270,21 @@ public boolean hasVariableListener() { @Override public Iterable<VariableListenerWithSources<Solution_>> buildVariableListeners(SupplyManager supplyManager) { AbstractCascadingUpdateShadowVariableListener<Solution_> listener; - if (nextElementShadowVariableDescriptor != null) { - if (targetVariableDescriptorList.size() == 1) { - listener = new SingleCascadingUpdateShadowVariableListener<>(targetVariableDescriptorList, - nextElementShadowVariableDescriptor, targetMethod); + ListVariableStateSupply<Solution_> listVariableStateSupply =
`var`
timefold-solver
github_2023
java
996
TimefoldAI
triceo
@@ -1,33 +1,51 @@ package ai.timefold.solver.core.impl.domain.variable.cascade; +import java.util.ArrayList; import java.util.List; +import java.util.Objects; import ai.timefold.solver.core.api.domain.solution.PlanningSolution; +import ai.timefold.solver.core.api.score.director.ScoreDirector; import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor; -import ai.timefold.solver.core.impl.domain.variable.descriptor.ShadowVariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.cascade.command.CascadingUpdateCommand; +import ai.timefold.solver.core.impl.domain.variable.cascade.command.Pair; +import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; /** - * The primary listener relies on the user-defined next-element shadow variable - * to fetch the next element of a given planning value. + * Alternative to {@link SingleCascadingUpdateShadowVariableListener}. * * The listener might update multiple shadow variables since the targetVariableDescriptorList contains various fields. - * + * * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation */ public class CollectionCascadingUpdateShadowVariableListener<Solution_> - extends AbstractCollectionAbstractCascadingUpdateShadowVariableListener<Solution_> { - - private final ShadowVariableDescriptor<Solution_> nextElementShadowVariableDescriptor; + extends AbstractCascadingUpdateShadowVariableListener<Solution_> { - public CollectionCascadingUpdateShadowVariableListener(List<VariableDescriptor<Solution_>> targetVariableDescriptorList, - ShadowVariableDescriptor<Solution_> nextElementShadowVariableDescriptor, MemberAccessor targetMethod) { - super(targetVariableDescriptorList, targetMethod); - this.nextElementShadowVariableDescriptor = nextElementShadowVariableDescriptor; + protected CollectionCascadingUpdateShadowVariableListener(ListVariableDescriptor<Solution_> sourceListVariableDescriptor, + List<VariableDescriptor<Solution_>> targetVariableDescriptorList, MemberAccessor targetMethod, + CascadingUpdateCommand<Pair<Integer, Object>> indexElementCommand) { + super(sourceListVariableDescriptor, targetVariableDescriptorList, targetMethod, indexElementCommand); } @Override - Object getNextElement(Object entity) { - return nextElementShadowVariableDescriptor.getValue(entity); + boolean execute(ScoreDirector<Solution_> scoreDirector, Object entity) { + var oldValueList = new ArrayList<>(targetVariableDescriptorList.size()); + for (VariableDescriptor<Solution_> targetVariableDescriptor : targetVariableDescriptorList) { + scoreDirector.beforeVariableChanged(entity, targetVariableDescriptor.getVariableName()); + oldValueList.add(targetVariableDescriptor.getValue(entity)); + } + targetMethod.executeGetter(entity); + var newValueList = new ArrayList<>(targetVariableDescriptorList.size()); + var hasChange = false; + for (int i = 0; i < targetVariableDescriptorList.size(); i++) { + var targetVariableDescriptor = targetVariableDescriptorList.get(i); + newValueList.add(targetVariableDescriptor.getValue(entity));
Why have the `newValueList`? Can't you just check the value directly, without storing it? The list is never read otherwise.
timefold-solver
github_2023
java
996
TimefoldAI
triceo
@@ -0,0 +1,24 @@ +package ai.timefold.solver.core.impl.domain.variable.cascade.command; + +import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply; +import ai.timefold.solver.core.impl.heuristic.selector.list.ElementLocation; +import ai.timefold.solver.core.impl.heuristic.selector.list.LocationInList; + +public class IndexElementSupplyCommand<Solution_> implements CascadingUpdateCommand<Pair<Integer, Object>> { + + private final ListVariableStateSupply<Solution_> listVariableStateSupply; + + public IndexElementSupplyCommand(ListVariableStateSupply<Solution_> listVariableStateSupply) { + this.listVariableStateSupply = listVariableStateSupply; + } + + @Override + public Pair<Integer, Object> getValue(Object value) { + ElementLocation elementLocation = listVariableStateSupply.getLocationInList(value); + if (elementLocation instanceof LocationInList location) { + return new Pair<>(location.index(), location.entity());
I'd just return `LocationInList`; let's spare GC some work.
timefold-solver
github_2023
java
996
TimefoldAI
triceo
@@ -0,0 +1,24 @@ +package ai.timefold.solver.core.impl.domain.variable.cascade.command; + +import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply; +import ai.timefold.solver.core.impl.heuristic.selector.list.ElementLocation; +import ai.timefold.solver.core.impl.heuristic.selector.list.LocationInList; + +public class IndexElementSupplyCommand<Solution_> implements CascadingUpdateCommand<Pair<Integer, Object>> { + + private final ListVariableStateSupply<Solution_> listVariableStateSupply; + + public IndexElementSupplyCommand(ListVariableStateSupply<Solution_> listVariableStateSupply) { + this.listVariableStateSupply = listVariableStateSupply; + } + + @Override + public Pair<Integer, Object> getValue(Object value) { + ElementLocation elementLocation = listVariableStateSupply.getLocationInList(value); + if (elementLocation instanceof LocationInList location) { + return new Pair<>(location.index(), location.entity()); + } + // Unassigned + return null;
`LocationInList.unassigned()`.
timefold-solver
github_2023
java
996
TimefoldAI
triceo
@@ -0,0 +1,5 @@ +package ai.timefold.solver.core.impl.domain.variable.cascade.command; + +public interface CascadingUpdateCommand<T> {
Not sure why we have this. Isn't this just a `Function<T, Object>`? Since it seems to only have one implementor, I'd remove it.
timefold-solver
github_2023
java
996
TimefoldAI
Christopher-Chianelli
@@ -0,0 +1,4 @@ +package ai.timefold.solver.core.impl.domain.variable.cascade.command; + +public record Pair<T, U>(T firstValue, U secondValue) {
We already define a Pair record in `ai.timefold.solver.core.impl.util`
timefold-solver
github_2023
java
996
TimefoldAI
Christopher-Chianelli
@@ -0,0 +1,24 @@ +package ai.timefold.solver.core.impl.domain.variable.cascade.command; + +import ai.timefold.solver.core.impl.domain.variable.ListVariableStateSupply; +import ai.timefold.solver.core.impl.heuristic.selector.list.ElementLocation; +import ai.timefold.solver.core.impl.heuristic.selector.list.LocationInList; + +public class IndexElementSupplyCommand<Solution_> implements CascadingUpdateCommand<Pair<Integer, Object>> { + + private final ListVariableStateSupply<Solution_> listVariableStateSupply; + + public IndexElementSupplyCommand(ListVariableStateSupply<Solution_> listVariableStateSupply) { + this.listVariableStateSupply = listVariableStateSupply; + } + + @Override + public Pair<Integer, Object> getValue(Object value) { + ElementLocation elementLocation = listVariableStateSupply.getLocationInList(value); + if (elementLocation instanceof LocationInList location) {
Why not use the `LocationInList` record directly? This `Pair` is duplicating an immutable object.
timefold-solver
github_2023
python
996
TimefoldAI
Christopher-Chianelli
@@ -231,7 +231,7 @@ def __init__(self, *, super().__init__(JavaPiggybackShadowVariable, { 'shadowVariableName': PythonClassTranslator.getJavaFieldName(shadow_variable_name), - 'shadowEntityClass': shadow_entity_class, + 'shadowEntityClass': get_asm_type(shadow_entity_class),
`get_asm_type` is not needed; remove.
timefold-solver
github_2023
python
996
TimefoldAI
Christopher-Chianelli
@@ -39,7 +40,11 @@ class Visit: target_method_name='update_arrival_time')] = field(default=None) piggyback_arrival_time: Annotated[ Optional[datetime], - PiggybackShadowVariable(shadow_variable_name='arrival_time')] = field(default=None) + PiggybackShadowVariable(shadow_variable_name='arrival_time', shadow_entity_class=Visit)] = field(default=None)
Visit is not defined yet (this is inside the Visit class); this code would not run/crash at runtime. Remove the `shadow_entity_class` here.
timefold-solver
github_2023
others
784
TimefoldAI
rsynek
@@ -37,15 +38,15 @@ jobs: path: ./timefold-quickstarts fetch-depth: 0 # Otherwise merge will fail on account of not having history. - name: Checkout timefold-quickstarts (development) # Checkout the development branch if the PR branch does not exist - if: steps.checkout-quickstarts.outcome != 'success' + if: ${{ steps.checkout-quickstarts-pr.outcome != 'success' }} uses: actions/checkout@v4 with: repository: TimefoldAI/timefold-quickstarts ref: development path: ./timefold-quickstarts fetch-depth: 0 # Otherwise merge will fail on account of not having history. - name: Prevent stale fork of quickstarts - if: steps.checkout-solver-quickstarts.outcome == 'success' # Only run if not on the main line. + if: ${{ steps.checkout-solver-quickstarts-pr.outcome == 'success' }}
I don't see any `checkout-solver-quickstarts-pr` ID in this file.
timefold-solver
github_2023
others
998
TimefoldAI
winklerm
@@ -8,8 +8,19 @@ on: - opened - reopened - synchronize + - labeled jobs: + safe_for_ci: + name: "Ensure that PR is safe for CI" + runs-on: ubuntu-latest + steps: + - name: Fail of not safe
Nitpick: Typo?
timefold-solver
github_2023
others
992
TimefoldAI
triceo
@@ -1465,6 +1464,28 @@ It calls `updateArrivalTime` whenever a `previousCustomer` or `vehicle` changes. It then propagates the changes to the subsequent elements, stopping when the method results in no change to the variable, or when it reaches the tail. +Another valid approach for defining multiple sources per variable is described as follows:
I wouldn't mention this; at this moment, there's no reason why anyone would want to do it. If we ever implement the variable on a different entity, then we can write a section to describe that aspect.
timefold-solver
github_2023
java
992
TimefoldAI
triceo
@@ -137,8 +137,39 @@ public void linkVariableDescriptors(DescriptorPolicy descriptorPolicy) { MemberAccessorFactory.MemberAccessorType.REGULAR_METHOD, null, descriptorPolicy.getDomainAccessType()); } - public void linkVariableDescriptorToSource(CascadingUpdateShadowVariable listener) { - var sourceDescriptor = entityDescriptor.getShadowVariableDescriptor(listener.sourceVariableName()); + public void linkVariableDescriptorToSource(CascadingUpdateShadowVariable shadowVariable) { + var noEmptySources = Arrays.stream(shadowVariable.sourceVariableNames()) + .filter(s -> !s.isBlank()) + .toList(); + if (shadowVariable.sourceVariableName().isBlank() && noEmptySources.isEmpty()) { + throw new IllegalArgumentException( + """ + The entity class (%s) has an @%s annotated property (%s), but neither the sourceVariableName nor the sourceVariableNames properties are set. + Maybe update the field "%s" and set one of the properties: sourceVariableName or sourceVariableNames.""" + .formatted(entityDescriptor.getEntityClass(), + CascadingUpdateShadowVariable.class.getSimpleName(), + variableMemberAccessor.getName(), + variableMemberAccessor.getName())); + } + if (!shadowVariable.sourceVariableName().isBlank() && !noEmptySources.isEmpty()) { + throw new IllegalArgumentException( + """ + The entity class (%s) has an @%s annotated property (%s), but it is only possible to define either sourceVariableName or sourceVariableNames. + Maybe update the field "%s" and setting only one of the properties: sourceVariableName or sourceVariableNames."""
```suggestion Maybe update the field "%s" to set only one of the properties ([sourceVariableName, sourceVariableNames]).""" ```
timefold-solver
github_2023
java
992
TimefoldAI
triceo
@@ -137,8 +137,39 @@ public void linkVariableDescriptors(DescriptorPolicy descriptorPolicy) { MemberAccessorFactory.MemberAccessorType.REGULAR_METHOD, null, descriptorPolicy.getDomainAccessType()); } - public void linkVariableDescriptorToSource(CascadingUpdateShadowVariable listener) { - var sourceDescriptor = entityDescriptor.getShadowVariableDescriptor(listener.sourceVariableName()); + public void linkVariableDescriptorToSource(CascadingUpdateShadowVariable shadowVariable) { + var noEmptySources = Arrays.stream(shadowVariable.sourceVariableNames()) + .filter(s -> !s.isBlank()) + .toList(); + if (shadowVariable.sourceVariableName().isBlank() && noEmptySources.isEmpty()) { + throw new IllegalArgumentException( + """ + The entity class (%s) has an @%s annotated property (%s), but neither the sourceVariableName nor the sourceVariableNames properties are set. + Maybe update the field "%s" and set one of the properties: sourceVariableName or sourceVariableNames."""
```suggestion Maybe update the field "%s" and set one of the properties ([sourceVariableName, sourceVariableNames]).""" ```
timefold-solver
github_2023
others
992
TimefoldAI
triceo
@@ -1451,8 +1451,7 @@ public class Customer { private Customer previousCustomer; @NextElementShadowVariable(sourceVariableName = "customers") private Customer nextCustomer; - @CascadingUpdateShadowVariable(targetMethodName = "updateArrivalTime", sourceVariableName = "vehicle") - @CascadingUpdateShadowVariable(targetMethodName = "updateArrivalTime", sourceVariableName = "previousCustomer") + @CascadingUpdateShadowVariable(targetMethodName = "updateArrivalTime", sourceVariableNames = {"vehicle", "previousCustomer"})
Now would be the time to add a section of the documentation that shows how piggybacks interact with cascading variables.
timefold-solver
github_2023
java
992
TimefoldAI
Christopher-Chianelli
@@ -137,8 +137,39 @@ public void linkVariableDescriptors(DescriptorPolicy descriptorPolicy) { MemberAccessorFactory.MemberAccessorType.REGULAR_METHOD, null, descriptorPolicy.getDomainAccessType()); } - public void linkVariableDescriptorToSource(CascadingUpdateShadowVariable listener) { - var sourceDescriptor = entityDescriptor.getShadowVariableDescriptor(listener.sourceVariableName()); + public void linkVariableDescriptorToSource(CascadingUpdateShadowVariable shadowVariable) { + var noEmptySources = Arrays.stream(shadowVariable.sourceVariableNames())
Nitpick: Should be called `nonEmptySources`; `noEmptySources` would be for a boolean, not a list.
timefold-solver
github_2023
python
992
TimefoldAI
Christopher-Chianelli
@@ -244,13 +244,14 @@ class CascadingUpdateShadowVariable(JavaAnnotation): Notes ----- Important: it must only change the shadow variable(s) for which it's configured. + It is only possible to define either `sourceVariableName` or `sourceVariableNames`.
```suggestion It is only possible to define either `source_variable_name` or `source_variable_names`. ```
timefold-solver
github_2023
python
992
TimefoldAI
Christopher-Chianelli
@@ -244,13 +244,14 @@ class CascadingUpdateShadowVariable(JavaAnnotation): Notes ----- Important: it must only change the shadow variable(s) for which it's configured. + It is only possible to define either `sourceVariableName` or `sourceVariableNames`. It can be applied to multiple attributes to modify different shadow variables. It should never change a genuine variable or a problem fact. It can change its shadow variable(s) on multiple entity instances (for example: an arrival_time change affects all trailing entities too). - Examples - -------- + Example - Single source + ------------------------
``` Examples -------- ``` is a standard section used in NumPy formatted docs. Do not change it or add new sections. See https://numpydoc.readthedocs.io/en/latest/format.html . For this, it would be ``` Examples -------- Single source (example here) Multiple sources (example here) ```
timefold-solver
github_2023
python
992
TimefoldAI
Christopher-Chianelli
@@ -244,13 +244,16 @@ class CascadingUpdateShadowVariable(JavaAnnotation): Notes ----- Important: it must only change the shadow variable(s) for which it's configured. + It is only possible to define either `source_variable_name` or `source_variable_names`. It can be applied to multiple attributes to modify different shadow variables. It should never change a genuine variable or a problem fact. It can change its shadow variable(s) on multiple entity instances (for example: an arrival_time change affects all trailing entities too). - Examples - -------- + Example
```suggestion Examples ``` ```suggestion Example ```