repo_name
stringlengths
1
62
dataset
stringclasses
1 value
lang
stringclasses
11 values
pr_id
int64
1
20.1k
owner
stringlengths
2
34
reviewer
stringlengths
2
39
diff_hunk
stringlengths
15
262k
code_review_comment
stringlengths
1
99.6k
timefold-solver
github_2023
java
1,341
TimefoldAI
zepfred
@@ -19,15 +19,16 @@ final class DynamicPropagationQueue<Tuple_ extends AbstractTuple, Carrier_ extends AbstractPropagationMetadataCarrier<Tuple_>> implements PropagationQueue<Carrier_> { + private static final int INITIAL_CAPACITY = 1000; // Selected arbitrarily.
Would it make sense to use the entity count to estimate capacity?
timefold-solver
github_2023
java
1,324
TimefoldAI
zepfred
@@ -14,19 +14,37 @@ final class ComparisonIndexer<T, Key_ extends Comparable<Key_>> implements Indexer<T> { - private final int propertyIndex; + private final KeyRetriever<Key_> keyRetriever; private final Supplier<Indexer<T>> downstreamIndexerSupplier; private final Comparator<Key_> keyComparator; private final boolean hasOrEquals; private final NavigableMap<Key_, Indexer<T>> comparisonMap; - public ComparisonIndexer(JoinerType comparisonJoinerType, Supplier<Indexer<T>> downstreamIndexerSupplier) { - this(comparisonJoinerType, 0, downstreamIndexerSupplier); + /** + * Construct an {@link ComparisonIndexer} which immediately ends in a {@link NoneIndexer}.
The name `NoneIndexer` seems off to me. Maybe should choose a more meaningful name, such as `RawDataIndexer` or something similar.
timefold-solver
github_2023
java
1,329
TimefoldAI
zepfred
@@ -19,43 +19,26 @@ */ public abstract sealed class AbstractTuple permits UniTuple, BiTuple, TriTuple, QuadTuple { - /* - * We create a lot of tuples, many of them having store size of 1. - * If an array of size 1 was created for each such tuple, memory would be wasted and indirection created. - * This trade-off of increased memory efficiency for marginally slower access time is proven beneficial. - */ - private final boolean storeIsArray; - - private Object store; + private static final Object[] EMPTY_STORE = new Object[0];
Does this change increase memory consumption?
timefold-solver
github_2023
java
1,312
TimefoldAI
Christopher-Chianelli
@@ -0,0 +1,157 @@ +package ai.timefold.solver.core.impl.domain.solution.descriptor; + +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +import ai.timefold.solver.core.preview.api.domain.metamodel.PlanningSolutionMetaModel; +import ai.timefold.solver.core.preview.api.domain.solution.diff.PlanningEntityDiff; +import ai.timefold.solver.core.preview.api.domain.solution.diff.PlanningSolutionDiff; + +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; + +@NullMarked +final class DefaultPlanningSolutionDiff<Solution_> implements PlanningSolutionDiff<Solution_> { + + private static final int TO_STRING_ITEM_LIMIT = 5;
Might be useful to add `toFullString` that ignores the limit (I find with `TRACKED_FULL_ASSERT`, the diff limit often hides changed variables).
timefold-solver
github_2023
java
1,312
TimefoldAI
Christopher-Chianelli
@@ -1265,6 +1268,68 @@ public <Score_ extends Score<Score_>> void setScore(Solution_ solution, Score_ s ((ScoreDescriptor) scoreDescriptor).setScore(solution, score); } + public PlanningSolutionDiff<Solution_> diff(Solution_ oldSolution, Solution_ newSolution) { + var oldEntities = getEntityDescriptors().stream() + .map(descriptor -> descriptor.extractEntities(oldSolution)) + .flatMap(Collection::stream) + .collect(Collectors.groupingBy(Object::getClass, Collectors.toSet())); + var newEntities = getEntityDescriptors().stream() + .map(descriptor -> descriptor.extractEntities(newSolution)) + .flatMap(Collection::stream) + .collect(Collectors.groupingBy(Object::getClass, Collectors.toSet())); + + var removedOldEntities = new LinkedHashSet<>(); + var oldToNewEntities = new LinkedHashMap<>(); + for (var entry : oldEntities.entrySet()) { + var entityClass = entry.getKey(); + for (var oldEntity : entry.getValue()) { + var newEntity = newEntities.getOrDefault(entityClass, Collections.emptySet()) + .stream() + .filter(e -> Objects.equals(e, oldEntity)) + .findFirst() + .orElse(null); + if (newEntity == null) { + removedOldEntities.add(oldEntity); + } else { + oldToNewEntities.put(oldEntity, newEntity); + } + } + } + + var addedNewEntities = new LinkedHashSet<>(); + for (var entry : newEntities.entrySet()) { + for (var newEntity : entry.getValue()) { + var noOldEqualsNew = !oldToNewEntities.containsValue(newEntity); + if (noOldEqualsNew) { + addedNewEntities.add(newEntity); + } + } + } + + var solutionDiff = new DefaultPlanningSolutionDiff<>(getMetaModel(), oldSolution, newSolution, removedOldEntities, + addedNewEntities); + for (var entry : oldToNewEntities.entrySet()) { + var oldEntity = entry.getKey(); + var newEntity = entry.getValue(); + var entityDescriptor = findEntityDescriptorOrFail(oldEntity.getClass()); + var entityDiff = new DefaultPlanningEntityDiff<>(solutionDiff, entry.getKey()); + for (var variableDescriptor : entityDescriptor.getGenuineVariableDescriptorList()) {
Might be useful to also add shadow variable differences (ex: users might be interested in the difference in arrival time of a visit, which is hard to know just from the list assigned to a vehicle).
timefold-solver
github_2023
java
1,308
TimefoldAI
triceo
@@ -78,6 +82,14 @@ class TimefoldProcessorMultipleSolversInvalidSolutionClassTest { .hasMessageContaining( "Unused classes ([ai.timefold.solver.quarkus.testdata.chained.domain.TestdataChainedQuarkusSolution]) found with a @PlanningSolution annotation.")); + @Inject + @Named("solver1") + SolverManager<?, ?> solverManager1; + + @Inject + @Named("solver2") + SolverManager<?, ?> solverManager2;
Why do we need to add these, if the test worked without them before? Smells of a backwards incompatible change.
timefold-solver
github_2023
python
1,271
TimefoldAI
Christopher-Chianelli
@@ -653,13 +653,13 @@ def __init__(self, *, class DeepPlanningClone(JavaAnnotation): """ - Marks a problem fact class as being required to be deep planning cloned.
Please keep this in the docstring; attributes that are instances of a planning_entity and planning_solution type are automatically deep cloned.
timefold-solver
github_2023
python
1,271
TimefoldAI
Christopher-Chianelli
@@ -954,3 +954,68 @@ class Solution: solution = solver.solve(problem) assert solution.score.score == 0 assert solution.entity.value == [1, 2, 3] + +def test_deep_clone_class(): + @deep_planning_clone + @dataclass + class Code: + value: str + parent_entity: 'Entity' = field(default=None) + + @dataclass + class Value: + code: Code + + @planning_entity + @dataclass + class Entity: + code: Code + value: Annotated[Value, PlanningVariable] = field(default=None) + + def assign_to_v1(constraint_factory: ConstraintFactory): + return (constraint_factory.for_each(Entity) + .filter(lambda e: e.value.code.value == 'v1') + .reward(SimpleScore.ONE) + .as_constraint('assign to v1') + ) + + @constraint_provider + def my_constraints(constraint_factory: ConstraintFactory): + return [ + assign_to_v1(constraint_factory) + ] + + @planning_solution + @dataclass + class Solution: + entities: Annotated[List[Entity], PlanningEntityCollectionProperty] + values: Annotated[List[Value], ProblemFactCollectionProperty, ValueRangeProvider] + codes: Annotated[List[Code], ProblemFactCollectionProperty] + score: Annotated[SimpleScore, PlanningScore] = field(default=None) + + solver_config = SolverConfig( + solution_class=Solution, + entity_class_list=[Entity], + score_director_factory_config=ScoreDirectorFactoryConfig( + constraint_provider_function=my_constraints + ), + termination_config=TerminationConfig( + best_score_limit='2' + ) + ) + + e1 = Entity(Code('e1')) + e1.code.parent_entity = e1 + e2 = Entity(Code('e2')) + e2.code.parent_entity = e2 + + v1 = Value(Code('v1')) + v2 = Value(Code('v2')) + + problem = Solution([e1, e2], [v1, v2], [e1.code, e2.code, v1.code, v2.code]) + solver = SolverFactory.create(solver_config).build_solver() + solution = solver.solve(problem) + + assert solution.score.score == 2 + assert solution.entities[0].value == v1 + assert solution.codes[0].parent_entity == solution.entities[0]
There should be an assert here to test if the cloning created a new instance ```suggestion assert solution.codes[0].parent_entity == solution.entities[0] assert solution.codes[0] is not problem.codes[0] ```
timefold-solver
github_2023
python
1,271
TimefoldAI
Christopher-Chianelli
@@ -653,13 +653,13 @@ def __init__(self, *, class DeepPlanningClone(JavaAnnotation): """ - Marks a problem fact class as being required to be deep planning cloned. - Not needed for a `planning_solution` or `planning_entity` because those are automatically deep cloned. - It can also mark an attribute as being required to be deep planning cloned. + Marks an attribute as being required to be deep planning cloned.
```suggestion Marks an attribute as being required to be deep planning cloned. Not needed for `planning_solution` or `planning_entity` attributes because those are automatically deep cloned. ```
timefold-solver
github_2023
java
1,306
TimefoldAI
zepfred
@@ -0,0 +1,179 @@ +package ai.timefold.solver.core.impl.score.stream.bavet.visual; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import ai.timefold.solver.core.impl.score.stream.bavet.BavetConstraint; +import ai.timefold.solver.core.impl.score.stream.bavet.common.AbstractNode; +import ai.timefold.solver.core.impl.score.stream.bavet.common.BavetAbstractConstraintStream; +import ai.timefold.solver.core.impl.score.stream.bavet.common.BavetStreamBinaryOperation; +import ai.timefold.solver.core.impl.score.stream.bavet.common.NodeBuildHelper; +import ai.timefold.solver.core.impl.score.stream.bavet.common.tuple.LeftTupleLifecycle; +import ai.timefold.solver.core.impl.score.stream.bavet.common.tuple.RightTupleLifecycle; +import ai.timefold.solver.core.impl.score.stream.bavet.uni.AbstractForEachUniNode; +import ai.timefold.solver.core.impl.score.stream.bavet.uni.BavetForEachUniConstraintStream; +import ai.timefold.solver.core.impl.score.stream.common.inliner.AbstractScoreInliner; + +public record NodeGraph<Solution_>(Solution_ solution, List<AbstractNode> sources, List<GraphEdge> edges, + List<GraphSink<Solution_>> sinks) { + + @SuppressWarnings("unchecked") + public static <Solution_> NodeGraph<Solution_> of(Solution_ solution, NodeBuildHelper<?> buildHelper, + List<AbstractNode> nodeList, AbstractScoreInliner<?> scoreInliner) { + var sourceList = new ArrayList<AbstractNode>(); + var edgeList = new ArrayList<GraphEdge>(); + for (var node : nodeList) { + var nodeCreator = buildHelper.getNodeCreatingStream(node); + if (nodeCreator instanceof BavetForEachUniConstraintStream<?, ?>) { + sourceList.add(node); + } else if (nodeCreator instanceof BavetStreamBinaryOperation<?> binaryOperation) { + var leftParent = buildHelper.findParentNode(binaryOperation.getLeftParent()); + edgeList.add(new GraphEdge(leftParent, node)); + var rightParent = buildHelper.findParentNode(binaryOperation.getRightParent()); + edgeList.add(new GraphEdge(rightParent, node)); + } else { + var parent = buildHelper.findParentNode(nodeCreator.getParent()); + edgeList.add(new GraphEdge(parent, node)); + } + } + var sinkList = new ArrayList<GraphSink<Solution_>>(); + for (var constraint : scoreInliner.getConstraints()) { + var castConstraint = (BavetConstraint<Solution_>) constraint; + var stream = (BavetAbstractConstraintStream<?>) castConstraint.getScoringConstraintStream(); + var node = buildHelper.findParentNode(stream); + sinkList.add(new GraphSink<>(node, castConstraint)); + } + return new NodeGraph<>(solution, sourceList.stream().distinct().toList(), + edgeList.stream().distinct().toList(), + sinkList.stream().distinct().toList()); + } + + public String write() {
I'm unsure about the method name. What about `parse`?
timefold-solver
github_2023
java
1,300
TimefoldAI
zepfred
@@ -0,0 +1,45 @@ +package ai.timefold.solver.core.api.function; + +import java.util.Objects; +import java.util.function.Consumer; +import java.util.function.Function; + +import org.jspecify.annotations.NonNull; + +/** + * Represents a function that accepts three arguments and returns no result.
```suggestion * Represents a function that accepts four arguments and returns no result. ```
timefold-solver
github_2023
java
1,300
TimefoldAI
zepfred
@@ -31,7 +30,7 @@ public IndexedIfExistsBiNode(boolean shouldExist, } public IndexedIfExistsBiNode(boolean shouldExist, - BiFunction<A, B, IndexProperties> mappingAB, Function<C, IndexProperties> mappingC, + BiMapping<A, B> mappingAB, IndexerFactory.UniMapping<C> mappingC,
```suggestion BiMapping<A, B> mappingAB, UniMapping<C> mappingC, ```
timefold-solver
github_2023
java
1,300
TimefoldAI
zepfred
@@ -43,8 +43,8 @@ public ComparisonIndexer(JoinerType comparisonJoinerType, int propertyIndex, } @Override - public ElementAwareListEntry<T> put(IndexProperties indexProperties, T tuple) { - Key_ indexKey = indexProperties.toKey(propertyIndex); + public ElementAwareListEntry<T> put(Object indexProperties, T tuple) {
Can we guarantee that the type of `indexProperties` is always `Key_`? It seems better to me that using a contract requiring the type `Key_` is preferable to allowing two possible types.
timefold-solver
github_2023
java
1,300
TimefoldAI
zepfred
@@ -526,87 +467,119 @@ public Function<Right_, ai.timefold.solver.core.impl.score.stream.bavet.common.i for (int i = 0; i < mappingCount; i++) { result[i] = mappings[i].apply(a); } - return new ai.timefold.solver.core.impl.score.stream.bavet.common.index.IndexerKey(result); + return new IndexerKey(result); }; } }; keyFunctionList.add(keyFunction); startIndexInclusive = endIndexExclusive; } int keyFunctionCount = keyFunctionList.size(); - switch (keyFunctionCount) { - case 1 -> { - var keyFunction = keyFunctionList.get(0); - yield a -> new ai.timefold.solver.core.impl.score.stream.bavet.common.index.SingleIndexProperties<>( - keyFunction.apply(a)); - } + yield switch (keyFunctionCount) { + case 1 -> wrap(keyFunctionList.get(0)); case 2 -> { var keyFunction1 = keyFunctionList.get(0); var keyFunction2 = keyFunctionList.get(1); - yield a -> new ai.timefold.solver.core.impl.score.stream.bavet.common.index.TwoIndexProperties<>( - keyFunction1.apply(a), keyFunction2.apply(a)); + yield a -> new TwoIndexProperties<>(keyFunction1.apply(a), keyFunction2.apply(a)); } case 3 -> { var keyFunction1 = keyFunctionList.get(0); var keyFunction2 = keyFunctionList.get(1); var keyFunction3 = keyFunctionList.get(2); - yield a -> new ai.timefold.solver.core.impl.score.stream.bavet.common.index.ThreeIndexProperties<>( - keyFunction1.apply(a), keyFunction2.apply(a), + yield a -> new ThreeIndexProperties<>(keyFunction1.apply(a), keyFunction2.apply(a), keyFunction3.apply(a)); } - default -> { - yield a -> { - Object[] arr = new Object[keyFunctionCount]; - for (int i = 0; i < keyFunctionCount; i++) { - arr[i] = keyFunctionList.get(i).apply(a); - } - return new ai.timefold.solver.core.impl.score.stream.bavet.common.index.ManyIndexProperties(arr); - }; - } - } + default -> a -> { + Object[] arr = new Object[keyFunctionCount]; + for (int i = 0; i < keyFunctionCount; i++) { + arr[i] = keyFunctionList.get(i).apply(a); + } + return new ManyIndexProperties(arr); + }; + }; } }; } - public <T> ai.timefold.solver.core.impl.score.stream.bavet.common.index.Indexer<T> buildIndexer(boolean isLeftBridge) { + public <T> Indexer<T> buildIndexer(boolean isLeftBridge) { /* * Note that if creating indexer for a right bridge node, the joiner type has to be flipped. * (<A, B> becomes <B, A>.) */ if (!hasJoiners()) { // NoneJoiner results in NoneIndexer. - return new ai.timefold.solver.core.impl.score.stream.bavet.common.index.NoneIndexer<>(); + return new NoneIndexer<>(); } else if (joiner.getJoinerCount() == 1) { // Single joiner maps directly to EqualsIndexer or ComparisonIndexer. var joinerType = joiner.getJoinerType(0); if (joinerType == JoinerType.EQUAL) { - return new ai.timefold.solver.core.impl.score.stream.bavet.common.index.EqualsIndexer<>(NoneIndexer::new); + return new EqualsIndexer<>(NoneIndexer::new); } else { - return new ai.timefold.solver.core.impl.score.stream.bavet.common.index.ComparisonIndexer<>( + return new ComparisonIndexer<>( isLeftBridge ? joinerType : joinerType.flip(), NoneIndexer::new); } } // The following code builds the children first, so it needs to iterate over the joiners in reverse order. var descendingJoinerTypeMap = joinerTypeMap.descendingMap(); - Supplier<ai.timefold.solver.core.impl.score.stream.bavet.common.index.Indexer<T>> downstreamIndexerSupplier = - NoneIndexer::new; + Supplier<Indexer<T>> downstreamIndexerSupplier = NoneIndexer::new; var indexPropertyId = descendingJoinerTypeMap.size() - 1; for (var entry : descendingJoinerTypeMap.entrySet()) { var joinerType = entry.getValue(); var actualDownstreamIndexerSupplier = downstreamIndexerSupplier; var effectivelyFinalIndexPropertyId = indexPropertyId; if (joinerType == JoinerType.EQUAL) { downstreamIndexerSupplier = - () -> new ai.timefold.solver.core.impl.score.stream.bavet.common.index.EqualsIndexer<>( - effectivelyFinalIndexPropertyId, actualDownstreamIndexerSupplier); + () -> new EqualsIndexer<>(effectivelyFinalIndexPropertyId, actualDownstreamIndexerSupplier); } else { var actualJoinerType = isLeftBridge ? joinerType : joinerType.flip(); - downstreamIndexerSupplier = - () -> new ai.timefold.solver.core.impl.score.stream.bavet.common.index.ComparisonIndexer<>( - actualJoinerType, effectivelyFinalIndexPropertyId, - actualDownstreamIndexerSupplier); + downstreamIndexerSupplier = () -> new ComparisonIndexer<>(actualJoinerType, effectivelyFinalIndexPropertyId, + actualDownstreamIndexerSupplier); } indexPropertyId--; } return downstreamIndexerSupplier.get(); } + private static <A> UniMapping<A> wrap(Function<A, Object> mapping) { + return a -> { + var result = mapping.apply(a); + return Objects.requireNonNullElse(result, NullIndexProperties.INSTANCE); + }; + } + + private static <A, B> BiMapping<A, B> wrap(BiFunction<A, B, Object> mapping) { + return (a, b) -> { + var result = mapping.apply(a, b); + return Objects.requireNonNullElse(result, NullIndexProperties.INSTANCE); + }; + } + + private static <A, B, C> TriMapping<A, B, C> wrap(TriFunction<A, B, C, Object> mapping) { + return (a, b, c) -> { + var result = mapping.apply(a, b, c); + return Objects.requireNonNullElse(result, NullIndexProperties.INSTANCE); + }; + } + + private static <A, B, C, D> QuadMapping<A, B, C, D> wrap(QuadFunction<A, B, C, D, Object> mapping) { + return (a, b, c, d) -> { + var result = mapping.apply(a, b, c, d); + return Objects.requireNonNullElse(result, NullIndexProperties.INSTANCE); + }; + } + + @FunctionalInterface + public interface UniMapping<A> extends Function<A, Object> {
The logic seems correct. I wonder if the result type could be something other than `Object`, which would clarify the contract for inner nodes.
timefold-solver
github_2023
java
1,300
TimefoldAI
zepfred
@@ -430,61 +384,48 @@ public <A> Function<A, ai.timefold.solver.core.impl.score.stream.bavet.common.in for (int i = 0; i < mappingCount; i++) { result[i] = mappings[i].apply(a, b, c, d); } - return new ai.timefold.solver.core.impl.score.stream.bavet.common.index.IndexerKey(result); + return new IndexerKey(result); }; } }; keyFunctionList.add(keyFunction); startIndexInclusive = endIndexExclusive; } int keyFunctionCount = keyFunctionList.size(); - switch (keyFunctionList.size()) { - case 1 -> { - var keyFunction = keyFunctionList.get(0); - yield (a, b, c, - d) -> new ai.timefold.solver.core.impl.score.stream.bavet.common.index.SingleIndexProperties<>( - keyFunction.apply(a, b, c, d)); - } + yield switch (keyFunctionList.size()) { + case 1 -> wrap(keyFunctionList.get(0)); case 2 -> { var keyFunction1 = keyFunctionList.get(0); var keyFunction2 = keyFunctionList.get(1); - yield (a, b, c, - d) -> new ai.timefold.solver.core.impl.score.stream.bavet.common.index.TwoIndexProperties<>( - keyFunction1.apply(a, b, c, d), - keyFunction2.apply(a, b, c, d)); + yield (a, b, c, d) -> new TwoIndexProperties<>(keyFunction1.apply(a, b, c, d), + keyFunction2.apply(a, b, c, d)); } case 3 -> { var keyFunction1 = keyFunctionList.get(0); var keyFunction2 = keyFunctionList.get(1); var keyFunction3 = keyFunctionList.get(2); - yield (a, b, c, - d) -> new ai.timefold.solver.core.impl.score.stream.bavet.common.index.ThreeIndexProperties<>( - keyFunction1.apply(a, b, c, d), - keyFunction2.apply(a, b, c, d), - keyFunction3.apply(a, b, c, d)); + yield (a, b, c, d) -> new ThreeIndexProperties<>(keyFunction1.apply(a, b, c, d), + keyFunction2.apply(a, b, c, d), keyFunction3.apply(a, b, c, d)); } - default -> { - yield (a, b, c, d) -> { - Object[] arr = new Object[keyFunctionCount]; - for (int i = 0; i < keyFunctionCount; i++) { - arr[i] = keyFunctionList.get(i).apply(a, b, c, d); - } - return new ai.timefold.solver.core.impl.score.stream.bavet.common.index.ManyIndexProperties(arr); - }; - } - } + default -> (a, b, c, d) -> { + Object[] arr = new Object[keyFunctionCount]; + for (int i = 0; i < keyFunctionCount; i++) { + arr[i] = keyFunctionList.get(i).apply(a, b, c, d); + } + return new ManyIndexProperties(arr); + }; + }; } }; } - public Function<Right_, ai.timefold.solver.core.impl.score.stream.bavet.common.index.IndexProperties> buildRightMapping() { + public UniMapping<Right_> buildRightMapping() { var joinerCount = joiner.getJoinerCount(); return switch (joinerCount) { case 0 -> a -> NoneIndexProperties.INSTANCE; case 1 -> { var mapping = joiner.getRightMapping(0); - yield a -> new ai.timefold.solver.core.impl.score.stream.bavet.common.index.SingleIndexProperties<>( - mapping.apply(a)); + yield mapping::apply;
Is there a reason for not wrapping here?
timefold-solver
github_2023
java
1,300
TimefoldAI
zepfred
@@ -23,21 +22,19 @@ public abstract class AbstractIndexedIfExistsNode<LeftTuple_ extends AbstractTup extends AbstractIfExistsNode<LeftTuple_, Right_> implements LeftTupleLifecycle<LeftTuple_>, RightTupleLifecycle<UniTuple<Right_>> { - private final Function<Right_, IndexProperties> mappingRight; + private final UniMapping<Right_> mappingRight; private final int inputStoreIndexLeftProperties; private final int inputStoreIndexLeftCounterEntry; private final int inputStoreIndexRightProperties; private final int inputStoreIndexRightEntry; private final Indexer<ExistsCounter<LeftTuple_>> indexerLeft; private final Indexer<UniTuple<Right_>> indexerRight; - protected AbstractIndexedIfExistsNode(boolean shouldExist, - Function<Right_, IndexProperties> mappingRight, + protected AbstractIndexedIfExistsNode(boolean shouldExist, IndexerFactory.UniMapping<Right_> mappingRight,
```suggestion protected AbstractIndexedIfExistsNode(boolean shouldExist, UniMapping<Right_> mappingRight, ```
timefold-solver
github_2023
java
1,300
TimefoldAI
zepfred
@@ -44,17 +44,15 @@ public final void insertLeft(LeftTuple_ leftTuple) { throw new IllegalStateException("Impossible state: the input for the tuple (" + leftTuple + ") was already added in the tupleStore."); } - ExistsCounter<LeftTuple_> counter = new ExistsCounter<>(leftTuple); - ElementAwareListEntry<ExistsCounter<LeftTuple_>> counterEntry = leftCounterList.add(counter); + var counter = new ExistsCounter<>(leftTuple); + var counterEntry = leftCounterList.add(counter); leftTuple.setStore(inputStoreIndexLeftCounterEntry, counterEntry); if (!isFiltering) { counter.countRight = rightTupleList.size(); } else { - ElementAwareList<FilteringTracker<LeftTuple_>> leftTrackerList = new ElementAwareList<>(); - for (UniTuple<Right_> tuple : rightTupleList) { - updateCounterFromLeft(leftTuple, tuple, counter, leftTrackerList); - } + var leftTrackerList = new ElementAwareList<FilteringTracker<LeftTuple_>>(); + rightTupleList.forEach(leftTuple, counter, leftTrackerList, this::updateCounterFromLeft);
The tuple instance will be the first parameter in the forEach loop, even though it originally appears in the second position in the code. Will this break any existing code?
timefold-solver
github_2023
java
1,300
TimefoldAI
zepfred
@@ -77,9 +75,7 @@ public final void updateLeft(LeftTuple_ leftTuple) { ElementAwareList<FilteringTracker<LeftTuple_>> leftTrackerList = leftTuple.getStore(inputStoreIndexLeftTrackerList); leftTrackerList.forEach(FilteringTracker::remove); counter.countRight = 0; - for (UniTuple<Right_> tuple : rightTupleList) { - updateCounterFromLeft(leftTuple, tuple, counter, leftTrackerList); - } + rightTupleList.forEach(leftTuple, counter, leftTrackerList, this::updateCounterFromLeft);
Same as above
timefold-solver
github_2023
java
1,300
TimefoldAI
zepfred
@@ -106,32 +102,27 @@ public final void insertRight(UniTuple<Right_> rightTuple) { throw new IllegalStateException("Impossible state: the input for the tuple (" + rightTuple + ") was already added in the tupleStore."); } - ElementAwareListEntry<UniTuple<Right_>> rightEntry = rightTupleList.add(rightTuple); + var rightEntry = rightTupleList.add(rightTuple); rightTuple.setStore(inputStoreIndexRightEntry, rightEntry); if (!isFiltering) { leftCounterList.forEach(this::incrementCounterRight); } else { - ElementAwareList<FilteringTracker<LeftTuple_>> rightTrackerList = new ElementAwareList<>(); - for (ExistsCounter<LeftTuple_> tuple : leftCounterList) { - updateCounterFromRight(rightTuple, tuple, rightTrackerList); - } + var rightTrackerList = new ElementAwareList<FilteringTracker<LeftTuple_>>();
Same as above
timefold-solver
github_2023
java
1,300
TimefoldAI
zepfred
@@ -106,32 +102,27 @@ public final void insertRight(UniTuple<Right_> rightTuple) { throw new IllegalStateException("Impossible state: the input for the tuple (" + rightTuple + ") was already added in the tupleStore."); } - ElementAwareListEntry<UniTuple<Right_>> rightEntry = rightTupleList.add(rightTuple); + var rightEntry = rightTupleList.add(rightTuple); rightTuple.setStore(inputStoreIndexRightEntry, rightEntry); if (!isFiltering) { leftCounterList.forEach(this::incrementCounterRight); } else { - ElementAwareList<FilteringTracker<LeftTuple_>> rightTrackerList = new ElementAwareList<>(); - for (ExistsCounter<LeftTuple_> tuple : leftCounterList) { - updateCounterFromRight(rightTuple, tuple, rightTrackerList); - } + var rightTrackerList = new ElementAwareList<FilteringTracker<LeftTuple_>>(); + leftCounterList.forEach(rightTuple, rightTrackerList, this::updateCounterFromRight); rightTuple.setStore(inputStoreIndexRightTrackerList, rightTrackerList); } } @Override public final void updateRight(UniTuple<Right_> rightTuple) { - ElementAwareListEntry<UniTuple<Right_>> rightEntry = rightTuple.getStore(inputStoreIndexRightEntry); - if (rightEntry == null) { + if (rightTuple.getStore(inputStoreIndexRightEntry) == null) { // No fail fast if null because we don't track which tuples made it through the filter predicate(s) insertRight(rightTuple); return; } if (isFiltering) { - ElementAwareList<FilteringTracker<LeftTuple_>> rightTrackerList = updateRightTrackerList(rightTuple); - for (ExistsCounter<LeftTuple_> tuple : leftCounterList) { - updateCounterFromRight(rightTuple, tuple, rightTrackerList); - } + var rightTrackerList = updateRightTrackerList(rightTuple);
Same as above
timefold-solver
github_2023
java
1,300
TimefoldAI
zepfred
@@ -40,19 +40,16 @@ public final void insertLeft(LeftTuple_ leftTuple) { throw new IllegalStateException("Impossible state: the input for the tuple (" + leftTuple + ") was already added in the tupleStore."); } - ElementAwareListEntry<LeftTuple_> leftEntry = leftTupleList.add(leftTuple); + var leftEntry = leftTupleList.add(leftTuple); leftTuple.setStore(inputStoreIndexLeftEntry, leftEntry); - ElementAwareList<OutTuple_> outTupleListLeft = new ElementAwareList<>(); + var outTupleListLeft = new ElementAwareList<OutTuple_>(); leftTuple.setStore(inputStoreIndexLeftOutTupleList, outTupleListLeft); - for (UniTuple<Right_> tuple : rightTupleList) { - insertOutTupleFiltered(leftTuple, tuple); - } + rightTupleList.forEach(leftTuple, (rightTuple, leftTuple_) -> insertOutTupleFiltered(leftTuple_, rightTuple));
That's what I meant in my comments in `AbstractUnindexedIfExistsNode`
timefold-solver
github_2023
java
1,300
TimefoldAI
zepfred
@@ -31,7 +30,7 @@ public IndexedIfExistsQuadNode(boolean shouldExist, } public IndexedIfExistsQuadNode(boolean shouldExist, - QuadFunction<A, B, C, D, IndexProperties> mappingABCD, Function<E, IndexProperties> mappingE, + QuadMapping<A, B, C, D> mappingABCD, IndexerFactory.UniMapping<E> mappingE,
```suggestion QuadMapping<A, B, C, D> mappingABCD, UniMapping<E> mappingE, ```
timefold-solver
github_2023
java
1,300
TimefoldAI
zepfred
@@ -31,7 +30,7 @@ public IndexedIfExistsTriNode(boolean shouldExist, } public IndexedIfExistsTriNode(boolean shouldExist, - TriFunction<A, B, C, IndexProperties> mappingABC, Function<D, IndexProperties> mappingD, + TriMapping<A, B, C> mappingABC, IndexerFactory.UniMapping<D> mappingD,
```suggestion TriMapping<A, B, C> mappingABC, UniMapping<D> mappingD, ```
timefold-solver
github_2023
java
1,300
TimefoldAI
zepfred
@@ -72,8 +93,13 @@ public void remove(ElementAwareListEntry<T> entry) { } else { entry.next.previous = entry.previous; } + entry.list = null; entry.previous = null; entry.next = null; + if (availableBlankEntry == null) { // Entry will be reused.
Nice!
timefold-solver
github_2023
others
1,269
TimefoldAI
lee-carlon
@@ -98,6 +98,25 @@ The solution instance given to the `solve(Solution)` method does not need to be It can be partially or fully initialized, which is often the case in xref:responding-to-change/responding-to-change.adoc[repeated planning]. ==== +[#multithreadedSolving] +=== Multi-threaded solving + +There are several ways of running the solver in parallel: + +* *xref:enterprise-edition/enterprise-edition.adoc#multithreadedIncrementalSolving[Multi-threaded incremental solving]*: +Solve 1 dataset with multiple threads without sacrificing xref:constraints-and-score/performance.adoc#incrementalScoreCalculationPerformance[incremental score calculation]. +This is an exclusive feature of the xref:enterprise-edition/enterprise-edition.adoc[Enterprise Edition]. + +* *xref:enterprise-edition/enterprise-edition.adoc#partitionedSearch[Partitioned search]*: +Split 1 dataset in multiple parts and solve them independently. +This is an exclusive feature of the xref:enterprise-edition/enterprise-edition.adoc[Enterprise Edition]. +* *Multi bet solving*: solve 1 dataset with multiple, isolated solvers and take the best result. +** Not recommended: This is a marginal gain for a high cost of hardware resources. +** Use the xref:using-timefold-solver/benchmarking-and-tweaking.adoc#benchmarker[Benchmarker] during development to determine the algorithm that is the most appropriate on average. +* *Multitenancy*: solve different datasets in parallel. +** The xref:using-timefold-solver/running-the-solver.adoc#solverManager[`SolverManager`] can help with that.
```suggestion ** The xref:using-timefold-solver/running-the-solver.adoc#solverManager[`SolverManager`] can help with this. ```
timefold-solver
github_2023
others
1,269
TimefoldAI
lee-carlon
@@ -262,7 +281,8 @@ Even `debug` logging can slow down performance considerably for fast stepping al (such as Late Acceptance and Simulated Annealing), but not for slow stepping algorithms (such as Tabu Search). -Both cause congestion in xref:enterprise-edition/enterprise-edition.adoc#multithreadedSolving[multi-threaded solving] with most appenders, see below. +Both cause congestion in xref:using-timefold-solver/running-the.solver.adoc#multithreadedSolving[multi-threaded solving] with most appenders,
```suggestion Both trace logging and debug logging cause congestion in xref:using-timefold-solver/running-the.solver.adoc#multithreadedSolving[multi-threaded solving] with most appenders, ```
timefold-solver
github_2023
java
1,253
TimefoldAI
triceo
@@ -210,6 +212,7 @@ public class SolverConfig extends AbstractConfig<SolverConfig> { // Warning: all fields are null (and not defaulted) because they can be inherited // and also because the input config file should match the output config file + protected List<PreviewFeature> enablePreviewFeatureList = null;
Shouldn't this be an `EnumSet`?
timefold-solver
github_2023
java
1,253
TimefoldAI
triceo
@@ -60,6 +61,7 @@ */ @XmlRootElement(name = SolverConfig.XML_ELEMENT_NAME) @XmlType(name = SolverConfig.XML_TYPE_NAME, propOrder = { + "enablePreviewFeatureList",
I'd drop the `list` - or do we have a precedent for that anywhere else in the config?
timefold-solver
github_2023
java
1,253
TimefoldAI
triceo
@@ -432,6 +443,14 @@ public void setMonitoringConfig(@Nullable MonitoringConfig monitoringConfig) { // With methods // ************************************************************************ + public @NonNull SolverConfig withPreviewFeature(@NonNull PreviewFeature previewFeature) {
I'd consider making this a vararg, and override the list every time. If nothing is provided, nothing is enabled. If something is provided, then that's what's enabled.
timefold-solver
github_2023
java
1,253
TimefoldAI
triceo
@@ -25,6 +27,7 @@ public class HeuristicConfigPolicy<Solution_> { + private final List<PreviewFeature> previewFeatureList;
`EnumSet` will work better for this.
timefold-solver
github_2023
java
1,253
TimefoldAI
triceo
@@ -0,0 +1,95 @@ +package ai.timefold.solver.core.impl.localsearch.decider.acceptor.lateacceptance; + +import ai.timefold.solver.core.api.score.Score; +import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchMoveScope; +import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchPhaseScope; +import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchStepScope; + +public class DiversifiedLateAcceptanceAcceptor<Solution_> extends LateAcceptanceAcceptor<Solution_> { + + // The worst score in the late elements list + protected Score<?> lateWorse; + // Number of occurrences of lateWorse in the late elements + protected int lateWorseOccurrences = -1; + + // ************************************************************************ + // Worker methods + // ************************************************************************ + + @Override + public void phaseStarted(LocalSearchPhaseScope<Solution_> phaseScope) { + super.phaseStarted(phaseScope); + lateWorseOccurrences = lateAcceptanceSize; + lateWorse = phaseScope.getBestScore(); + } + + @Override + @SuppressWarnings("unchecked") + public boolean isAccepted(LocalSearchMoveScope<Solution_> moveScope) { + // The acceptance and replacement strategies are based on the work: + // Diversified Late Acceptance Search by M. Namazi, C. Sanderson, M. A. H. Newton, M. M. A. Polash, and A. Sattar + var lateScore = previousScores[lateScoreIndex]; + var moveScore = moveScope.getScore(); + var current = moveScope.getStepScope().getPhaseScope().getLastCompletedStepScope().getScore(); + var previous = current; + var accept = compare(moveScore, current) == 0 || compare(moveScore, lateWorse) > 0; + if (accept) { + current = moveScore; + } + // Improves the diversification to allow the next iterations to find a better solution + var lateUnimprovedCmp = compare(current, lateScore) < 0; + // Improves the intensification but avoids replacing values when the search falls into a plateau or local minima + var lateImprovedCmp = compare(current, lateScore) > 0 && compare(current, previous) > 0; + if (lateUnimprovedCmp || lateImprovedCmp) { + updateLateScore(current); + } + lateScoreIndex = (lateScoreIndex + 1) % lateAcceptanceSize; + return accept; + } + + @Override + public void stepEnded(LocalSearchStepScope<Solution_> stepScope) { + // Do nothing + } + + private void updateLateScore(Score<?> score) { + var worseCmp = compare(score, lateWorse); + var lateCmp = compare(previousScores[lateScoreIndex], lateWorse); + if (worseCmp < 0) { + this.lateWorse = score; + this.lateWorseOccurrences = 1; + } else if (lateCmp == 0 && worseCmp != 0) { + this.lateWorseOccurrences--; + } else if (lateCmp != 0 && worseCmp == 0) { + this.lateWorseOccurrences++; + } + previousScores[lateScoreIndex] = score; + // Recompute the new lateWorse and the number of occurrences + if (lateWorseOccurrences == 0) { + lateWorse = previousScores[0]; + lateWorseOccurrences = 1; + for (var i = 1; i < lateAcceptanceSize; i++) { + var cmp = compare(previousScores[i], lateWorse); + if (cmp < 0) { + lateWorse = previousScores[i]; + lateWorseOccurrences = 1; + } else if (cmp == 0) { + lateWorseOccurrences++; + } + } + } + } + + @Override + public void phaseEnded(LocalSearchPhaseScope<Solution_> phaseScope) { + super.phaseEnded(phaseScope); + lateWorse = null; + lateWorseOccurrences = -1; + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private int compare(Score<?> first, Score<?> second) { + return ((Score) first).compareTo(second); + }
Do we need this? It's a shorthand for something already very short. Also, wouldn't you be able to get rid of the cast, if you do it like so? private <Score_ extends Score<Score_>> int compare(Score_ first, Score_ second) {
timefold-solver
github_2023
java
1,253
TimefoldAI
triceo
@@ -0,0 +1,95 @@ +package ai.timefold.solver.core.impl.localsearch.decider.acceptor.lateacceptance; + +import ai.timefold.solver.core.api.score.Score; +import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchMoveScope; +import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchPhaseScope; +import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchStepScope; + +public class DiversifiedLateAcceptanceAcceptor<Solution_> extends LateAcceptanceAcceptor<Solution_> { + + // The worst score in the late elements list + protected Score<?> lateWorse; + // Number of occurrences of lateWorse in the late elements + protected int lateWorseOccurrences = -1; + + // ************************************************************************ + // Worker methods + // ************************************************************************ + + @Override + public void phaseStarted(LocalSearchPhaseScope<Solution_> phaseScope) { + super.phaseStarted(phaseScope); + lateWorseOccurrences = lateAcceptanceSize; + lateWorse = phaseScope.getBestScore(); + } + + @Override + @SuppressWarnings("unchecked") + public boolean isAccepted(LocalSearchMoveScope<Solution_> moveScope) { + // The acceptance and replacement strategies are based on the work: + // Diversified Late Acceptance Search by M. Namazi, C. Sanderson, M. A. H. Newton, M. M. A. Polash, and A. Sattar + var lateScore = previousScores[lateScoreIndex]; + var moveScore = moveScope.getScore(); + var current = moveScope.getStepScope().getPhaseScope().getLastCompletedStepScope().getScore(); + var previous = current; + var accept = compare(moveScore, current) == 0 || compare(moveScore, lateWorse) > 0; + if (accept) { + current = moveScore; + } + // Improves the diversification to allow the next iterations to find a better solution + var lateUnimprovedCmp = compare(current, lateScore) < 0; + // Improves the intensification but avoids replacing values when the search falls into a plateau or local minima + var lateImprovedCmp = compare(current, lateScore) > 0 && compare(current, previous) > 0; + if (lateUnimprovedCmp || lateImprovedCmp) { + updateLateScore(current); + } + lateScoreIndex = (lateScoreIndex + 1) % lateAcceptanceSize; + return accept; + } + + @Override + public void stepEnded(LocalSearchStepScope<Solution_> stepScope) { + // Do nothing + } + + private void updateLateScore(Score<?> score) { + var worseCmp = compare(score, lateWorse); + var lateCmp = compare(previousScores[lateScoreIndex], lateWorse);
Personally, I'd refactor this to something with meaning - such as: var lateScoreWorse = compare(score, lateWorse) > 0;
timefold-solver
github_2023
java
1,253
TimefoldAI
triceo
@@ -0,0 +1,95 @@ +package ai.timefold.solver.core.impl.localsearch.decider.acceptor.lateacceptance; + +import ai.timefold.solver.core.api.score.Score; +import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchMoveScope; +import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchPhaseScope; +import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchStepScope; + +public class DiversifiedLateAcceptanceAcceptor<Solution_> extends LateAcceptanceAcceptor<Solution_> {
Do we need to extend this? IMO it's different enough to stand on its own. There's not so much code to share anyway.
timefold-solver
github_2023
java
1,253
TimefoldAI
triceo
@@ -15,9 +15,8 @@ public static HeuristicConfigPolicy<TestdataSolution> buildHeuristicConfigPolicy public static <Solution_> HeuristicConfigPolicy<Solution_> buildHeuristicConfigPolicy(SolutionDescriptor<Solution_> solutionDescriptor) { - return new HeuristicConfigPolicy.Builder<>(EnvironmentMode.REPRODUCIBLE, null, null, null, null, new Random(), null, - solutionDescriptor, ClassInstanceCache.create()) - .build(); + return new HeuristicConfigPolicy.Builder<>(null, EnvironmentMode.REPRODUCIBLE, null, null, null, null, new Random(), + null, solutionDescriptor, ClassInstanceCache.create()).build();
Isn't the point of a builder to not have these crazy constructors?
timefold-solver
github_2023
others
1,253
TimefoldAI
triceo
@@ -507,6 +507,50 @@ Use a lower tabu size than in a pure Tabu Search configuration. </localSearch> ---- +[#diversifiedLateAcceptance] +== Diversified Late acceptance + + +[#diversifiedLateAcceptanceAlgorithm] +=== Algorithm description + +Diversified Late Acceptance is similar to Late Acceptance, +but it offers different acceptance and replacement strategies. +A move is accepted if its score matches the current solution score +or is better than the late score (which is the winning score of a fixed number of steps ago). + +Scientific paper: https://arxiv.org/pdf/1806.09328[Diversified Late Acceptance Search by M. Namazi, C. Sanderson, M. A. H. Newton, M. M. A. Polash, and A. Sattar] + +[#diversifiedLateAcceptanceConfiguration] +=== Configuration + +Simplest configuration: + +[source,xml,options="nowrap"] +---- + <localSearch> + <localSearchType>DIVERSIFIED_LATE_ACCEPTANCE</localSearchType> + </localSearch> +---- + +The late elements list is updated +only if the current solution score is worse than the late score or better than the late score and different from the previous one.
This sentence is a bit complicated. I'd break it down into bullet points - updated if X, or if Y.
timefold-solver
github_2023
others
1,253
TimefoldAI
triceo
@@ -507,6 +507,50 @@ Use a lower tabu size than in a pure Tabu Search configuration. </localSearch> ---- +[#diversifiedLateAcceptance] +== Diversified Late acceptance + + +[#diversifiedLateAcceptanceAlgorithm] +=== Algorithm description + +Diversified Late Acceptance is similar to Late Acceptance, +but it offers different acceptance and replacement strategies. +A move is accepted if its score matches the current solution score +or is better than the late score (which is the winning score of a fixed number of steps ago). + +Scientific paper: https://arxiv.org/pdf/1806.09328[Diversified Late Acceptance Search by M. Namazi, C. Sanderson, M. A. H. Newton, M. M. A. Polash, and A. Sattar] + +[#diversifiedLateAcceptanceConfiguration] +=== Configuration + +Simplest configuration: + +[source,xml,options="nowrap"] +---- + <localSearch> + <localSearchType>DIVERSIFIED_LATE_ACCEPTANCE</localSearchType> + </localSearch> +---- + +The late elements list is updated +only if the current solution score is worse than the late score or better than the late score and different from the previous one. +The size of the late elements list is typically smaller. + +Advanced configuration: + +[source,xml,options="nowrap"] +---- + <localSearch>
You should also show the preview configuration.
timefold-solver
github_2023
others
1,253
TimefoldAI
triceo
@@ -507,6 +507,50 @@ Use a lower tabu size than in a pure Tabu Search configuration. </localSearch> ---- +[#diversifiedLateAcceptance] +== Diversified Late acceptance +
I'd add a note that it's a preview feature, with a link here: https://docs.timefold.ai/timefold-solver/latest/upgrading-timefold-solver/backwards-compatibility#previewFeatures
timefold-solver
github_2023
others
1,253
TimefoldAI
triceo
@@ -317,6 +317,9 @@ <xs:sequence> + <xs:element maxOccurs="unbounded" minOccurs="0" name="enablePreviewFeatureList" nillable="true" type="tns:previewFeature"/>
If I read this correctly, if there were more than one preview feature, this would look like this: <enablePreviewFeatureList>FEATURE_A</> <enablePreviewFeatureList>FEATURE_B</> Then _for sure_ this shouldn't have the `list` suffix.
timefold-solver
github_2023
java
1,253
TimefoldAI
triceo
@@ -198,20 +217,31 @@ public ThreadFactory buildThreadFactory(ChildThreadType childThreadType) { } } + public void ensurePreviewFeature(PreviewFeature previewFeature) { + if (previewFeatureList == null || !previewFeatureList.contains(previewFeature)) { + throw new IllegalStateException( + """ + The preview feature %s is not enabled. + Maybe add %s to <enablePreviewFeatureList> in your configuration file?"""
Tag needs fixing.
timefold-solver
github_2023
others
1,253
TimefoldAI
triceo
@@ -507,6 +507,63 @@ Use a lower tabu size than in a pure Tabu Search configuration. </localSearch> ---- +[#diversifiedLateAcceptance] +== Diversified Late acceptance + + +[#diversifiedLateAcceptanceAlgorithm] +=== Algorithm description + +Diversified Late Acceptance is similar to Late Acceptance, +but it offers different acceptance and replacement strategies. +A move is accepted if its score matches the current solution score +or is better than the late score (which is the winning score of a fixed number of steps ago). + +Scientific paper: https://arxiv.org/pdf/1806.09328[Diversified Late Acceptance Search by M. Namazi, C. Sanderson, M. A. H. Newton, M. M. A. Polash, and A. Sattar]
```suggestion Diversified Late Acceptance was first proposed in https://arxiv.org/pdf/1806.09328[Diversified Late Acceptance Search by M. Namazi, C. Sanderson, M. A. H. Newton, M. M. A. Polash, and A. Sattar] ```
timefold-solver
github_2023
java
1,253
TimefoldAI
triceo
@@ -0,0 +1,113 @@ +package ai.timefold.solver.core.impl.localsearch.decider.acceptor.lateacceptance; + +import java.util.Arrays; + +import ai.timefold.solver.core.api.score.Score; +import ai.timefold.solver.core.impl.localsearch.decider.acceptor.AbstractAcceptor; +import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchMoveScope; +import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchPhaseScope; + +public class DiversifiedLateAcceptanceAcceptor<Solution_> extends AbstractAcceptor<Solution_> { + + // The worst score in the late elements list + protected Score<?> lateWorse; + // Number of occurrences of lateWorse in the late elements + protected int lateWorseOccurrences = -1; + + protected int lateAcceptanceSize = -1; + + protected Score<?>[] previousScores; + protected int lateScoreIndex = -1; + + public void setLateAcceptanceSize(int lateAcceptanceSize) { + this.lateAcceptanceSize = lateAcceptanceSize; + } + + // ************************************************************************ + // Worker methods + // ************************************************************************ + + @Override + public void phaseStarted(LocalSearchPhaseScope<Solution_> phaseScope) { + super.phaseStarted(phaseScope); + validate(); + previousScores = new Score[lateAcceptanceSize]; + var initialScore = phaseScope.getBestScore(); + Arrays.fill(previousScores, initialScore); + lateScoreIndex = 0; + lateWorseOccurrences = lateAcceptanceSize; + lateWorse = initialScore; + } + + private void validate() { + if (lateAcceptanceSize <= 0) { + throw new IllegalArgumentException( + "The lateAcceptanceSize (%d) cannot be negative or zero.".formatted(lateAcceptanceSize)); + } + } + + @Override + @SuppressWarnings({ "rawtypes", "unchecked" }) + public boolean isAccepted(LocalSearchMoveScope<Solution_> moveScope) { + // The acceptance and replacement strategies are based on the work: + // Diversified Late Acceptance Search by M. Namazi, C. Sanderson, M. A. H. Newton, M. M. A. Polash, and A. Sattar + var lateScore = previousScores[lateScoreIndex];
Please declare variables closer to where you need them, you decrease the size of the context readers need to keep in their heads. This particular variable is only needed on line 63.
timefold-solver
github_2023
java
1,253
TimefoldAI
triceo
@@ -0,0 +1,113 @@ +package ai.timefold.solver.core.impl.localsearch.decider.acceptor.lateacceptance; + +import java.util.Arrays; + +import ai.timefold.solver.core.api.score.Score; +import ai.timefold.solver.core.impl.localsearch.decider.acceptor.AbstractAcceptor; +import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchMoveScope; +import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchPhaseScope; + +public class DiversifiedLateAcceptanceAcceptor<Solution_> extends AbstractAcceptor<Solution_> { + + // The worst score in the late elements list + protected Score<?> lateWorse; + // Number of occurrences of lateWorse in the late elements + protected int lateWorseOccurrences = -1; + + protected int lateAcceptanceSize = -1; + + protected Score<?>[] previousScores; + protected int lateScoreIndex = -1; + + public void setLateAcceptanceSize(int lateAcceptanceSize) { + this.lateAcceptanceSize = lateAcceptanceSize; + } + + // ************************************************************************ + // Worker methods + // ************************************************************************ + + @Override + public void phaseStarted(LocalSearchPhaseScope<Solution_> phaseScope) { + super.phaseStarted(phaseScope); + validate(); + previousScores = new Score[lateAcceptanceSize]; + var initialScore = phaseScope.getBestScore(); + Arrays.fill(previousScores, initialScore); + lateScoreIndex = 0; + lateWorseOccurrences = lateAcceptanceSize; + lateWorse = initialScore; + } + + private void validate() { + if (lateAcceptanceSize <= 0) { + throw new IllegalArgumentException( + "The lateAcceptanceSize (%d) cannot be negative or zero.".formatted(lateAcceptanceSize)); + } + } + + @Override + @SuppressWarnings({ "rawtypes", "unchecked" }) + public boolean isAccepted(LocalSearchMoveScope<Solution_> moveScope) { + // The acceptance and replacement strategies are based on the work: + // Diversified Late Acceptance Search by M. Namazi, C. Sanderson, M. A. H. Newton, M. M. A. Polash, and A. Sattar + var lateScore = previousScores[lateScoreIndex]; + var moveScore = moveScope.getScore(); + var current = (Score) moveScope.getStepScope().getPhaseScope().getLastCompletedStepScope().getScore(); + var previous = current; + var accept = moveScore.compareTo(current) == 0 || moveScore.compareTo(lateWorse) > 0; + if (accept) { + current = moveScore; + } + // Improves the diversification to allow the next iterations to find a better solution + var currentScoreWorse = current.compareTo(lateScore) < 0; + // Improves the intensification but avoids replacing values when the search falls into a plateau or local minima + var currentScoreBetter = current.compareTo(lateScore) > 0 && current.compareTo(previous) > 0;
The comparison is already made on line 63. Please reuse.
timefold-solver
github_2023
java
1,253
TimefoldAI
triceo
@@ -0,0 +1,113 @@ +package ai.timefold.solver.core.impl.localsearch.decider.acceptor.lateacceptance; + +import java.util.Arrays; + +import ai.timefold.solver.core.api.score.Score; +import ai.timefold.solver.core.impl.localsearch.decider.acceptor.AbstractAcceptor; +import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchMoveScope; +import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchPhaseScope; + +public class DiversifiedLateAcceptanceAcceptor<Solution_> extends AbstractAcceptor<Solution_> { + + // The worst score in the late elements list + protected Score<?> lateWorse; + // Number of occurrences of lateWorse in the late elements + protected int lateWorseOccurrences = -1; + + protected int lateAcceptanceSize = -1; + + protected Score<?>[] previousScores; + protected int lateScoreIndex = -1; + + public void setLateAcceptanceSize(int lateAcceptanceSize) { + this.lateAcceptanceSize = lateAcceptanceSize; + } + + // ************************************************************************ + // Worker methods + // ************************************************************************ + + @Override + public void phaseStarted(LocalSearchPhaseScope<Solution_> phaseScope) { + super.phaseStarted(phaseScope); + validate(); + previousScores = new Score[lateAcceptanceSize]; + var initialScore = phaseScope.getBestScore(); + Arrays.fill(previousScores, initialScore); + lateScoreIndex = 0; + lateWorseOccurrences = lateAcceptanceSize; + lateWorse = initialScore; + } + + private void validate() { + if (lateAcceptanceSize <= 0) { + throw new IllegalArgumentException( + "The lateAcceptanceSize (%d) cannot be negative or zero.".formatted(lateAcceptanceSize)); + } + } + + @Override + @SuppressWarnings({ "rawtypes", "unchecked" }) + public boolean isAccepted(LocalSearchMoveScope<Solution_> moveScope) { + // The acceptance and replacement strategies are based on the work: + // Diversified Late Acceptance Search by M. Namazi, C. Sanderson, M. A. H. Newton, M. M. A. Polash, and A. Sattar + var lateScore = previousScores[lateScoreIndex]; + var moveScore = moveScope.getScore(); + var current = (Score) moveScope.getStepScope().getPhaseScope().getLastCompletedStepScope().getScore(); + var previous = current; + var accept = moveScore.compareTo(current) == 0 || moveScore.compareTo(lateWorse) > 0; + if (accept) { + current = moveScore; + } + // Improves the diversification to allow the next iterations to find a better solution + var currentScoreWorse = current.compareTo(lateScore) < 0; + // Improves the intensification but avoids replacing values when the search falls into a plateau or local minima + var currentScoreBetter = current.compareTo(lateScore) > 0 && current.compareTo(previous) > 0; + if (currentScoreWorse || currentScoreBetter) { + updateLateScore(current); + } + lateScoreIndex = (lateScoreIndex + 1) % lateAcceptanceSize; + return accept; + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + private void updateLateScore(Score newScore) { + var newScoreWorse = newScore.compareTo(lateWorse) < 0; + var newScoreEqual = newScore.compareTo(lateWorse) == 0;
Please reuse the comparison. This is called relatively frequently, it needs to be efficient.
timefold-solver
github_2023
java
1,237
TimefoldAI
triceo
@@ -0,0 +1,34 @@ +package ai.timefold.solver.core.impl.domain.solution.cloner.gizmo; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; +import java.util.Map; + +import ai.timefold.solver.core.impl.testdata.domain.clone.deepcloning.AnnotatedTestdataVariousTypes; +import ai.timefold.solver.core.impl.testdata.domain.clone.deepcloning.ExtraDeepClonedObject; +import ai.timefold.solver.core.impl.testdata.domain.clone.deepcloning.TestdataDeepCloningEntity; +import ai.timefold.solver.core.impl.testdata.domain.clone.deepcloning.TestdataVariousTypes; +import ai.timefold.solver.core.impl.testdata.domain.clone.deepcloning.field.TestdataFieldAnnotatedDeepCloningEntity; +import ai.timefold.solver.core.impl.testdata.domain.clone.deepcloning.field.TestdataFieldAnnotatedDeepCloningSolution; + +import org.junit.jupiter.api.Test; + +class GizmoCloningUtilsTest {
If my memory serves, the cloning tests are usually written in a way that the same bug can be tested for both reflection-based and Gizmo-based cloners. It is important that we maintain functional equivalence between the two implementations. Please find the cloner test which implements this duality, and preferrably add the test there.
timefold-solver
github_2023
java
1,228
TimefoldAI
Christopher-Chianelli
@@ -0,0 +1,291 @@ +package ai.timefold.solver.core.impl.domain.variable; + +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.index.IndexShadowVariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.inverserelation.InverseRelationShadowVariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.nextprev.NextElementShadowVariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.nextprev.PreviousElementShadowVariableDescriptor; +import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; +import ai.timefold.solver.core.impl.util.CollectionUtils; +import ai.timefold.solver.core.preview.api.domain.metamodel.ElementLocation; +import ai.timefold.solver.core.preview.api.domain.metamodel.LocationInList; + +final class ListVariableState<Solution_> { + + private final ListVariableDescriptor<Solution_> sourceVariableDescriptor; + + private ExternalizedIndexVariableProcessor<Solution_> externalizedIndexProcessor = null; + private ExternalizedListInverseVariableProcessor<Solution_> externalizedInverseProcessor = null; + private AbstractExternalizedNextPrevElementVariableProcessor<Solution_> externalizedPreviousElementProcessor = null; + private AbstractExternalizedNextPrevElementVariableProcessor<Solution_> externalizedNextElementProcessor = null; + + private boolean canUseExternalizedLocation = false; + private boolean requiresLocationMap = true; + private InnerScoreDirector<Solution_, ?> scoreDirector; + private int unassignedCount = 0; + private Map<Object, LocationInList> elementLocationMap; + + public ListVariableState(ListVariableDescriptor<Solution_> sourceVariableDescriptor) { + this.sourceVariableDescriptor = sourceVariableDescriptor; + } + + public void linkDescriptor(IndexShadowVariableDescriptor<Solution_> shadowVariableDescriptor) { + this.externalizedIndexProcessor = new ExternalizedIndexVariableProcessor<>(shadowVariableDescriptor); + } + + public void linkDescriptor(InverseRelationShadowVariableDescriptor<Solution_> shadowVariableDescriptor) { + this.externalizedInverseProcessor = + new ExternalizedListInverseVariableProcessor<>(shadowVariableDescriptor, sourceVariableDescriptor); + } + + public void linkDescriptor(PreviousElementShadowVariableDescriptor<Solution_> shadowVariableDescriptor) { + this.externalizedPreviousElementProcessor = + new ExternalizedPreviousElementVariableProcessor<>(shadowVariableDescriptor); + } + + public void linkDescriptor(NextElementShadowVariableDescriptor<Solution_> shadowVariableDescriptor) { + this.externalizedNextElementProcessor = new ExternalizedNextElementVariableProcessor<>(shadowVariableDescriptor); + } + + public void initialize(InnerScoreDirector<Solution_, ?> scoreDirector, int initialUnassignedCount) { + this.scoreDirector = scoreDirector; + this.unassignedCount = initialUnassignedCount; + + this.canUseExternalizedLocation = externalizedIndexProcessor != null && externalizedInverseProcessor != null; + this.requiresLocationMap = !canUseExternalizedLocation + || externalizedPreviousElementProcessor == null || externalizedNextElementProcessor == null; + if (requiresLocationMap) { + if (elementLocationMap == null) { + elementLocationMap = CollectionUtils.newIdentityHashMap(unassignedCount); + } else { + elementLocationMap.clear(); + } + } else { + elementLocationMap = null; + } + } + + public void addElement(Object entity, List<Object> elements, Object element, int index) { + if (requiresLocationMap) { + var location = ElementLocation.of(entity, index); + var oldLocation = elementLocationMap.put(element, location); + if (oldLocation != null) { + throw new IllegalStateException( + "The supply for list variable (%s) is corrupted, because the element (%s) at index (%d) already exists (%s)." + .formatted(sourceVariableDescriptor, element, index, oldLocation)); + } + } + if (externalizedIndexProcessor != null) { + externalizedIndexProcessor.addElement(scoreDirector, element, index); + } + if (externalizedInverseProcessor != null) { + externalizedInverseProcessor.addElement(scoreDirector, entity, element); + } + if (externalizedPreviousElementProcessor != null) { + externalizedPreviousElementProcessor.setElement(scoreDirector, elements, element, index); + } + if (externalizedNextElementProcessor != null) { + externalizedNextElementProcessor.setElement(scoreDirector, elements, element, index); + } + unassignedCount--; + } + + public void removeElement(Object entity, Object element, int index) { + if (requiresLocationMap) { + var oldElementLocation = elementLocationMap.remove(element); + if (oldElementLocation == null) { + throw new IllegalStateException( + "The supply for list variable (%s) is corrupted, because the element (%s) at index (%d) was already unassigned (%s)." + .formatted(sourceVariableDescriptor, element, index, oldElementLocation)); + } + var oldIndex = oldElementLocation.index(); + if (oldIndex != index) { + throw new IllegalStateException( + "The supply for list variable (%s) is corrupted, because the element (%s) at index (%d) had an old index (%d) which is not the current index (%d)." + .formatted(sourceVariableDescriptor, element, index, oldIndex, index)); + } + } + if (externalizedIndexProcessor != null) { + externalizedIndexProcessor.removeElement(scoreDirector, element); + } + if (externalizedInverseProcessor != null) { + externalizedInverseProcessor.removeElement(scoreDirector, entity, element); + } + if (externalizedPreviousElementProcessor != null) { + externalizedPreviousElementProcessor.unsetElement(scoreDirector, element); + } + if (externalizedNextElementProcessor != null) { + externalizedNextElementProcessor.unsetElement(scoreDirector, element); + } + unassignedCount++; + } + + public void unassignElement(Object element) { + if (requiresLocationMap) { + var oldLocation = elementLocationMap.remove(element); + if (oldLocation == null) { + throw new IllegalStateException( + "The supply for list variable (%s) is corrupted, because the element (%s) did not exist before unassigning." + .formatted(sourceVariableDescriptor, element)); + } + } + if (externalizedIndexProcessor != null) { + externalizedIndexProcessor.unassignElement(scoreDirector, element); + } + if (externalizedInverseProcessor != null) { + externalizedInverseProcessor.unassignElement(scoreDirector, element); + } + if (externalizedPreviousElementProcessor != null) { + externalizedPreviousElementProcessor.unsetElement(scoreDirector, element); + } + if (externalizedNextElementProcessor != null) { + externalizedNextElementProcessor.unsetElement(scoreDirector, element); + } + unassignedCount++; + } + + public boolean changeElement(Object entity, List<Object> elements, int index) { + var element = elements.get(index); + var difference = processElementLocation(entity, element, index); + if (difference.indexChanged && externalizedIndexProcessor != null) { + externalizedIndexProcessor.changeElement(scoreDirector, element, index); + } + if (difference.entityChanged && externalizedInverseProcessor != null) { + externalizedInverseProcessor.changeElement(scoreDirector, entity, element); + } + // Next and previous still might have changed, even if the index and entity did not. + // Those are based on what happened elsewhere in the list. + if (externalizedPreviousElementProcessor != null) { + externalizedPreviousElementProcessor.setElement(scoreDirector, elements, element, index); + } + if (externalizedNextElementProcessor != null) { + externalizedNextElementProcessor.setElement(scoreDirector, elements, element, index); + } + return difference.anythingChanged; + } + + private ChangeType processElementLocation(Object entity, Object element, int index) { + if (requiresLocationMap) { // Update the location and figure out if it is different from previous. + var newLocation = ElementLocation.of(entity, index); + var oldLocation = elementLocationMap.put(element, newLocation); + if (oldLocation == null) { + unassignedCount--; + return ChangeType.BOTH; + } + return compareLocations(entity, oldLocation.entity(), index, oldLocation.index()); + } else { // Read the location and figure out if it is different from previous. + var oldEntity = getInverseSingleton(element); + if (oldEntity == null) { + unassignedCount--; + return ChangeType.BOTH; + } + var oldIndex = getIndex(element); + if (oldIndex == null) { // Technically impossible, but we handle it anyway. + return ChangeType.BOTH; + } + return compareLocations(entity, oldEntity, index, oldIndex); + } + } + + private static ChangeType compareLocations(Object entity, Object otherEntity, int index, int otherIndex) { + if (entity != otherEntity) { + return ChangeType.BOTH; // Entity changed, so index changed too. + } else if (index != otherIndex) { + return ChangeType.INDEX; + } else { + return ChangeType.NEITHER; + } + } + + private enum ChangeType { + + BOTH(true, true), + INDEX(false, true), + NEITHER(false, false); + + final boolean anythingChanged; + final boolean entityChanged; + final boolean indexChanged; + + ChangeType(boolean entityChanged, boolean indexChanged) { + this.anythingChanged = entityChanged || indexChanged; + this.entityChanged = entityChanged; + this.indexChanged = indexChanged; + } + + } + + public ElementLocation getLocationInList(Object planningValue) { + if (!canUseExternalizedLocation) { + return Objects.requireNonNullElse(elementLocationMap.get(planningValue), ElementLocation.unassigned()); + } else { + var inverse = getInverseSingleton(planningValue);
`getInverseSingleton` and `getIndex` might do a map lookup on the same value. Might be worth it to do a single map lookup here if requiresLocationMap is true.
timefold-solver
github_2023
others
1,196
TimefoldAI
triceo
@@ -587,6 +587,9 @@ <xs:element minOccurs="0" name="moveCountLimit" type="xs:long"/> + <xs:element minOccurs="0" name="unimprovedBestSolutionLimit" type="xs:double"/>
We need a better name for this one - one that actually indicated what is going to happen. - `exhaustionDetection` (we already use "exhaust" for exhaustive search, so maybe not) - `depletionDetection` - `flatLineDetection` (I like it because it is simple; I don't like it because it is too un-scientific) - ... ?
timefold-solver
github_2023
java
1,196
TimefoldAI
triceo
@@ -0,0 +1,178 @@ +package ai.timefold.solver.core.impl.solver.termination; + +import ai.timefold.solver.core.api.score.Score; +import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope; +import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope; +import ai.timefold.solver.core.impl.solver.scope.SolverScope; +import ai.timefold.solver.core.impl.solver.thread.ChildThreadType; + +public final class UnimprovedBestSolutionTermination<Solution_> extends AbstractTermination<Solution_> { + + // Minimal interval of time to avoid early conclusions + protected static final long MINIMAL_INTERVAL_TIME = 10L;
Needs a unit in the name.
timefold-solver
github_2023
java
1,196
TimefoldAI
triceo
@@ -0,0 +1,178 @@ +package ai.timefold.solver.core.impl.solver.termination; + +import ai.timefold.solver.core.api.score.Score; +import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope; +import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope; +import ai.timefold.solver.core.impl.solver.scope.SolverScope; +import ai.timefold.solver.core.impl.solver.thread.ChildThreadType; + +public final class UnimprovedBestSolutionTermination<Solution_> extends AbstractTermination<Solution_> { + + // Minimal interval of time to avoid early conclusions + protected static final long MINIMAL_INTERVAL_TIME = 10L; + // The ratio specifies the minimum criteria to determine a flat line between two move count values. + // A value of 0.2 represents 20% of the execution time of the current growth curve. + // For example, the first best solution is found at 0 seconds, + // while the last best solution is found at 60 seconds. + // Given the total time of 60 seconds, + // we will identify a flat line between the last best solution and the discovered new best solution + // if the time difference exceeds 12 seconds. + private final double maxUnimprovedBestSolutionLimit;
Needs a better name, describing the functionality. This also needs to show up in the docs and in the images, as it is one of the key parameters to understand the algorithm. The charts need to clearly mark this point.
timefold-solver
github_2023
java
1,196
TimefoldAI
triceo
@@ -0,0 +1,178 @@ +package ai.timefold.solver.core.impl.solver.termination; + +import ai.timefold.solver.core.api.score.Score; +import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope; +import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope; +import ai.timefold.solver.core.impl.solver.scope.SolverScope; +import ai.timefold.solver.core.impl.solver.thread.ChildThreadType; + +public final class UnimprovedBestSolutionTermination<Solution_> extends AbstractTermination<Solution_> { + + // Minimal interval of time to avoid early conclusions + protected static final long MINIMAL_INTERVAL_TIME = 10L; + // The ratio specifies the minimum criteria to determine a flat line between two move count values. + // A value of 0.2 represents 20% of the execution time of the current growth curve. + // For example, the first best solution is found at 0 seconds, + // while the last best solution is found at 60 seconds. + // Given the total time of 60 seconds, + // we will identify a flat line between the last best solution and the discovered new best solution + // if the time difference exceeds 12 seconds. + private final double maxUnimprovedBestSolutionLimit; + // Similar to unimprovedBestSolutionLimit, + // this criterion is specifically used to identify flat lines among multiple curves before the termination. + // The goal is to adjust the stop criterion based on the latest curve found when there are several. + private final double minUnimprovedBestSolutionLimit;
Based on the current description, I do not understand what this does. Also, same comment as above.
timefold-solver
github_2023
java
1,196
TimefoldAI
triceo
@@ -0,0 +1,178 @@ +package ai.timefold.solver.core.impl.solver.termination; + +import ai.timefold.solver.core.api.score.Score; +import ai.timefold.solver.core.impl.phase.scope.AbstractPhaseScope; +import ai.timefold.solver.core.impl.phase.scope.AbstractStepScope; +import ai.timefold.solver.core.impl.solver.scope.SolverScope; +import ai.timefold.solver.core.impl.solver.thread.ChildThreadType; + +public final class UnimprovedBestSolutionTermination<Solution_> extends AbstractTermination<Solution_> { + + // Minimal interval of time to avoid early conclusions + protected static final long MINIMAL_INTERVAL_TIME = 10L; + // The ratio specifies the minimum criteria to determine a flat line between two move count values. + // A value of 0.2 represents 20% of the execution time of the current growth curve. + // For example, the first best solution is found at 0 seconds, + // while the last best solution is found at 60 seconds. + // Given the total time of 60 seconds, + // we will identify a flat line between the last best solution and the discovered new best solution + // if the time difference exceeds 12 seconds. + private final double maxUnimprovedBestSolutionLimit; + // Similar to unimprovedBestSolutionLimit, + // this criterion is specifically used to identify flat lines among multiple curves before the termination. + // The goal is to adjust the stop criterion based on the latest curve found when there are several. + private final double minUnimprovedBestSolutionLimit; + // The field stores the first best solution move count found in the curve growth chart. + // If a solving process involves multiple curves, + // the value is tied to the growth of the last curve analyzed. + protected long initialImprovementMoveCount; + protected long lastImprovementMoveCount; + protected long lastMoveEvaluationSpeed; + private Score<?> previousBest; + protected Score<?> currentBest; + protected boolean waitForFirstBestScore; + protected Boolean terminate; + + public UnimprovedBestSolutionTermination(double unimprovedBestSolutionLimit) { + this.maxUnimprovedBestSolutionLimit = unimprovedBestSolutionLimit; + // 80% of the max unimproved limit + this.minUnimprovedBestSolutionLimit = unimprovedBestSolutionLimit * 0.8; + if (unimprovedBestSolutionLimit < 0) { + throw new IllegalArgumentException( + "The unimprovedBestSolutionLimit (%.2f) cannot be negative.".formatted(unimprovedBestSolutionLimit)); + } + } + + public double getUnimprovedBestSolutionLimit() { + return maxUnimprovedBestSolutionLimit; + } + + // ************************************************************************ + // Lifecycle methods + // ************************************************************************ + + @Override + @SuppressWarnings("unchecked") + public void phaseStarted(AbstractPhaseScope<Solution_> phaseScope) { + super.phaseStarted(phaseScope); + initialImprovementMoveCount = 0L; + lastImprovementMoveCount = 0L; + lastMoveEvaluationSpeed = 0L; + currentBest = phaseScope.getBestScore(); + previousBest = currentBest; + waitForFirstBestScore = true; + terminate = null; + } + + @Override + public void stepStarted(AbstractStepScope<Solution_> stepScope) { + super.stepStarted(stepScope); + terminate = null; + } + + @Override + @SuppressWarnings({ "unchecked", "rawtypes" }) + public void stepEnded(AbstractStepScope<Solution_> stepScope) { + super.stepEnded(stepScope); + if (waitForFirstBestScore) { + waitForFirstBestScore = ((Score) currentBest).compareTo(stepScope.getScore()) >= 0; + } + } + + // ************************************************************************ + // Terminated methods + // ************************************************************************ + + @Override + public boolean isSolverTerminated(SolverScope<Solution_> solverScope) { + throw new UnsupportedOperationException( + "%s can only be used for phase termination.".formatted(getClass().getSimpleName()));
I understand why this is, but as a future improvement, we should think about ways of making this termination the default without the user having to configure anything. I want this to eventually be the only termination the user will ever need. This will require the termination to _somehow_ survive the CH phase.
timefold-solver
github_2023
others
1,196
TimefoldAI
triceo
@@ -565,6 +565,58 @@ Terminates as soon as a feasible solution has been discovered. This `Termination` is usually combined with other terminations. +[#unimprovedBestSolutionTermination] +==== `UnimprovedBestSolutionTermination` + +`UnimprovedBestSolutionTermination` terminates when the solver cannot improve the best solution in an estimated time interval. +The estimation of the termination interval is based on the last time +the solver improved the solution and how much time has passed without any improvements.
Are we using time? I thought we were using move counts.
timefold-solver
github_2023
others
1,196
TimefoldAI
triceo
@@ -565,6 +565,58 @@ Terminates as soon as a feasible solution has been discovered. This `Termination` is usually combined with other terminations. +[#unimprovedBestSolutionTermination] +==== `UnimprovedBestSolutionTermination` + +`UnimprovedBestSolutionTermination` terminates when the solver cannot improve the best solution in an estimated time interval. +The estimation of the termination interval is based on the last time +the solver improved the solution and how much time has passed without any improvements. + +[source,xml,options="nowrap"] +---- + <termination> + <unimprovedBestSolutionLimit>0.5</unimprovedBestSolutionLimit> + </termination> +---- + +Let's consider a solution process based on the following image. + +image::optimization-algorithms/overview/terminationGrowthCurve.png[align="center"] + +In the previous image, the estimated unimproved time is represented by the flat red line. +With a configuration for `unimprovedBestSolutionLimit` set to `0.5`, +and considering that the last best score was achieved at `10 seconds`, +the solver will terminate the process if no improvement is found within a maximum of 10 seconds. +This `10-seconds` limit is calculated +by multiplying the estimated total time (`20 seconds`) by the `unimprovedBestSolutionLimit` (`0.5`).
Isn't this a bit confusing? Why not change the definition and instead of basing it on estimated total time, it would be based on the time it spent improving? The limit would be `1.0` in that case, and the docs would say eg. "the last best score was achieved at 10 seconds, and the solver will terminate in another 10 seconds." Nothing further needs to be explained, there are no more calculations. For this approach, with 1.0, 10 = +10. The the old approach, with 0.5, 10 = 20 * 0.5. Seems less confusing to me this way, no?
timefold-solver
github_2023
others
1,196
TimefoldAI
triceo
@@ -565,6 +565,58 @@ Terminates as soon as a feasible solution has been discovered. This `Termination` is usually combined with other terminations. +[#unimprovedBestSolutionTermination] +==== `UnimprovedBestSolutionTermination` + +`UnimprovedBestSolutionTermination` terminates when the solver cannot improve the best solution in an estimated time interval. +The estimation of the termination interval is based on the last time +the solver improved the solution and how much time has passed without any improvements. + +[source,xml,options="nowrap"] +---- + <termination> + <unimprovedBestSolutionLimit>0.5</unimprovedBestSolutionLimit> + </termination> +---- + +Let's consider a solution process based on the following image. + +image::optimization-algorithms/overview/terminationGrowthCurve.png[align="center"] + +In the previous image, the estimated unimproved time is represented by the flat red line. +With a configuration for `unimprovedBestSolutionLimit` set to `0.5`, +and considering that the last best score was achieved at `10 seconds`, +the solver will terminate the process if no improvement is found within a maximum of 10 seconds. +This `10-seconds` limit is calculated +by multiplying the estimated total time (`20 seconds`) by the `unimprovedBestSolutionLimit` (`0.5`). + + +[NOTE] +==== +This `Termination` configuration includes some built-in properties: + +* The `Termination` process requires the growth curve to last at least `10 seconds`, +meaning that the solver will not finish until approximately `10 seconds` after the growth curve evaluation begins.
We should discuss this interval, give it a name, and write the pictures in such a way that they show this interval.
timefold-solver
github_2023
others
1,196
TimefoldAI
triceo
@@ -565,6 +565,58 @@ Terminates as soon as a feasible solution has been discovered. This `Termination` is usually combined with other terminations. +[#unimprovedBestSolutionTermination] +==== `UnimprovedBestSolutionTermination` + +`UnimprovedBestSolutionTermination` terminates when the solver cannot improve the best solution in an estimated time interval. +The estimation of the termination interval is based on the last time +the solver improved the solution and how much time has passed without any improvements. + +[source,xml,options="nowrap"] +---- + <termination> + <unimprovedBestSolutionLimit>0.5</unimprovedBestSolutionLimit> + </termination> +---- + +Let's consider a solution process based on the following image. + +image::optimization-algorithms/overview/terminationGrowthCurve.png[align="center"] + +In the previous image, the estimated unimproved time is represented by the flat red line. +With a configuration for `unimprovedBestSolutionLimit` set to `0.5`, +and considering that the last best score was achieved at `10 seconds`, +the solver will terminate the process if no improvement is found within a maximum of 10 seconds. +This `10-seconds` limit is calculated +by multiplying the estimated total time (`20 seconds`) by the `unimprovedBestSolutionLimit` (`0.5`). + + +[NOTE] +==== +This `Termination` configuration includes some built-in properties: + +* The `Termination` process requires the growth curve to last at least `10 seconds`, +meaning that the solver will not finish until approximately `10 seconds` after the growth curve evaluation begins. +* The estimated time is determined by the speed of move evaluation. +As the evaluation speed changes during the solving process, +the conditions for ending the solver will also be adjusted. +This means that the flat line may appear longer when analyzing a growth curve chart. +==== + +Now, let's discuss the problem-solving process involving multiple growth curves: + +image::optimization-algorithms/overview/terminationMultipleGrowthCurve.png[align="center"] + +The termination process will track the solver's progress to identify various growth curves. +Each time a new curve is identified, the newly identified curve is used to trigger the termination process. +This means +that the previously explained interval calculation will only consider the last curve rather than the entire flow.
We keep talking about curves here, but maybe we should talk about the last point of improvement. (Which is also a concept which needs a good name, and needs to be shown in the graph.)
timefold-solver
github_2023
others
1,196
TimefoldAI
triceo
@@ -565,6 +565,58 @@ Terminates as soon as a feasible solution has been discovered. This `Termination` is usually combined with other terminations. +[#unimprovedBestSolutionTermination] +==== `UnimprovedBestSolutionTermination` + +`UnimprovedBestSolutionTermination` terminates when the solver cannot improve the best solution in an estimated time interval. +The estimation of the termination interval is based on the last time +the solver improved the solution and how much time has passed without any improvements. + +[source,xml,options="nowrap"] +---- + <termination> + <unimprovedBestSolutionLimit>0.5</unimprovedBestSolutionLimit> + </termination> +---- + +Let's consider a solution process based on the following image. + +image::optimization-algorithms/overview/terminationGrowthCurve.png[align="center"] + +In the previous image, the estimated unimproved time is represented by the flat red line. +With a configuration for `unimprovedBestSolutionLimit` set to `0.5`, +and considering that the last best score was achieved at `10 seconds`, +the solver will terminate the process if no improvement is found within a maximum of 10 seconds. +This `10-seconds` limit is calculated +by multiplying the estimated total time (`20 seconds`) by the `unimprovedBestSolutionLimit` (`0.5`). + + +[NOTE] +==== +This `Termination` configuration includes some built-in properties: + +* The `Termination` process requires the growth curve to last at least `10 seconds`, +meaning that the solver will not finish until approximately `10 seconds` after the growth curve evaluation begins. +* The estimated time is determined by the speed of move evaluation. +As the evaluation speed changes during the solving process, +the conditions for ending the solver will also be adjusted. +This means that the flat line may appear longer when analyzing a growth curve chart. +==== + +Now, let's discuss the problem-solving process involving multiple growth curves: + +image::optimization-algorithms/overview/terminationMultipleGrowthCurve.png[align="center"] + +The termination process will track the solver's progress to identify various growth curves. +Each time a new curve is identified, the newly identified curve is used to trigger the termination process. +This means +that the previously explained interval calculation will only consider the last curve rather than the entire flow. + +The previous chart displays a red line that is smaller than the size needed to trigger termination, +but it is still significant enough to indicate the beginning of a new curve. +The termination threshold is calculated as `80%` of the size of the flat line that would end the solving process. + +This `Termination` is usually combined with other terminations.
Please explain why, and with which.
timefold-solver
github_2023
others
1,229
TimefoldAI
lee-carlon
@@ -10,6 +10,8 @@ image::quickstart/vehicle-routing/vehicleRoutingClassDiagramPure.png[] == Location The `Location` class is used to represent the destination for deliveries or the home location for vehicles. +The `drivingTimeSeconds` map contains the time required to driving from `this` location to any other location.
```suggestion The `drivingTimeSeconds` map contains the time required to drive from `this` location to any other location. ```
timefold-solver
github_2023
others
1,229
TimefoldAI
lee-carlon
@@ -306,12 +274,15 @@ The `Visit` class represents a delivery that needs to be made by vehicles. A visit includes a destination location, a delivery time window represented by `[minStartTime, maxEndTime]`, a demand that needs to be fulfilled by the vehicle, and a service duration time. +The `Visit` class has an `@PlanningEntity` annotation +but no genuine variables and is called https://timefold.ai/docs/timefold-solver/latest/using-timefold-solver/modeling-planning-problems#shadowVariable[shadow entity].
```suggestion The `Visit` class has an `@PlanningEntity` annotation but no genuine variables and is called a https://timefold.ai/docs/timefold-solver/latest/using-timefold-solver/modeling-planning-problems#shadowVariable[shadow entity]. ```
timefold-solver
github_2023
others
1,229
TimefoldAI
lee-carlon
@@ -608,193 +505,27 @@ class Visit { -- ==== -Some methods are annotated with `@InverseRelationShadowVariable`, `@PreviousElementShadowVariable`, -`@NextElementShadowVariable`, and `@ShadowVariable`. +Some methods are annotated with `@InverseRelationShadowVariable`, `@PreviousElementShadowVariable` and `@CascadingUpdateShadowVariable`. They are called https://timefold.ai/docs/timefold-solver/latest/using-timefold-solver/modeling-planning-problems#shadowVariable[shadow variables], and because Timefold Solver changes them, `Visit` is a https://timefold.ai/docs/timefold-solver/latest/using-timefold-solver/modeling-planning-problems#planningEntity[_planning entity_]: image::quickstart/vehicle-routing/vehicleRoutingCompleteClassDiagramAnnotated.png[] -The method `getVehicle()` has an `@InverseRelationShadowVariable` annotation, +The field `vehicle` has an `@InverseRelationShadowVariable` annotation, creating a bi-directional relationship with the `Vehicle`. The function returns a reference to the `Vehicle` where the visit is scheduled. Let's say the visit `Ann` was scheduled to the vehicle `V1` during the solving process. The method returns a reference of `V1`. -The methods `getPreviousVisit()` and `getNextVisit()` are annotated with `@PreviousElementShadowVariable` and -`@NextElementShadowVariable`, respectively. -The method returns a reference of the previous and next visit of the current visit instance. +The field `previousVisit` is annotated with `@PreviousElementShadowVariable`. +The solver will update this field with a reference of the visit preceding the current visit instance. Assuming that vehicle `V1` is assigned the visits of `Ann`, `Beth`, and `Carl`, -the `getNextVisit()` method returns `Carl`, -and the `getPreviousVisit()` method returns `Ann` for the visit of `Beth`. - -The method `getArrivalTime()` has two `@ShadowVariable` annotations, -one per each variable: `vehicle` and `previousVisit`. -The solver triggers `ArrivalTimeUpdatingVariableListener` to update `arrivalTime` field every time the fields `vehicle` -or `previousVisit` get updated. - -The `Visit` class has an `@PlanningEntity` annotation -but no genuine variables and is called https://timefold.ai/docs/timefold-solver/latest/using-timefold-solver/modeling-planning-problems#shadowVariable[shadow entity]. - -[tabs] -==== -Java:: -+ --- -Create the `src/main/java/org/acme/vehiclerouting/solver/ArrivalTimeUpdatingVariableListener.java` class: - -[source,java] ----- -package org.acme.vehiclerouting.solver; - -import java.time.LocalDateTime; -import java.util.Objects; - -import ai.timefold.solver.core.api.domain.variable.VariableListener; -import ai.timefold.solver.core.api.score.director.ScoreDirector; - -import org.acme.vehiclerouting.domain.Visit; -import org.acme.vehiclerouting.domain.VehicleRoutePlan; - -public class ArrivalTimeUpdatingVariableListener implements VariableListener<VehicleRoutePlan, Visit> { - - private static final String ARRIVAL_TIME_FIELD = "arrivalTime"; - - @Override - public void beforeVariableChanged(ScoreDirector<VehicleRoutePlan> scoreDirector, Visit visit) { - - } - - @Override - public void afterVariableChanged(ScoreDirector<VehicleRoutePlan> scoreDirector, Visit visit) { - if (visit.getVehicle() == null) { - if (visit.getArrivalTime() != null) { - scoreDirector.beforeVariableChanged(visit, ARRIVAL_TIME_FIELD); - visit.setArrivalTime(null); - scoreDirector.afterVariableChanged(visit, ARRIVAL_TIME_FIELD); - } - return; - } +the `previousVisit` field will be filled with `Ann` for the visit of `Beth`. - Visit previousVisit = visit.getPreviousVisit(); - LocalDateTime departureTime = - previousVisit == null ? visit.getVehicle().getDepartureTime() : previousVisit.getDepartureTime(); - - Visit nextVisit = visit; - LocalDateTime arrivalTime = calculateArrivalTime(nextVisit, departureTime); - while (nextVisit != null && !Objects.equals(nextVisit.getArrivalTime(), arrivalTime)) { - scoreDirector.beforeVariableChanged(nextVisit, ARRIVAL_TIME_FIELD); - nextVisit.setArrivalTime(arrivalTime); - scoreDirector.afterVariableChanged(nextVisit, ARRIVAL_TIME_FIELD); - departureTime = nextVisit.getDepartureTime(); - nextVisit = nextVisit.getNextVisit(); - arrivalTime = calculateArrivalTime(nextVisit, departureTime); - } - } - - @Override - public void beforeEntityAdded(ScoreDirector<VehicleRoutePlan> scoreDirector, Visit visit) { - - } +NOTE: `@NextElementShadowVariable` also exists, which can be used to get a reference to the successor element. - @Override - public void afterEntityAdded(ScoreDirector<VehicleRoutePlan> scoreDirector, Visit visit) { - - } - - @Override - public void beforeEntityRemoved(ScoreDirector<VehicleRoutePlan> scoreDirector, Visit visit) { +The `arrivalTime` field has a `@CascadingUpdateShadowVariable` annotation. +This annotation indicates which method should be triggered to update this field whenever this entity is moved, in this case the `updateArrivalTime()` method. +This change is automatically propagated to the subsequent visits and stops when the `arrivalTime` value hasn't changed or when it's reached the end of the chain of Visit objects.
```suggestion This change is automatically propagated to the subsequent visits and stops when the `arrivalTime` value hasn't changed or when it's reached the end of the chain of visit objects. ```
timefold-solver
github_2023
others
1,203
TimefoldAI
triceo
@@ -64,9 +64,14 @@ To complete this guide, you need: == The build file and the dependencies -Use https://code.quarkus.io/[code.quarkus.io] to generate an application +Use https://code.quarkus.io/?a=timefold-solver-quickstart&j=17&e=resteasy&e=resteasy-jackson&e=ai.timefold.solver%3Atimefold-solver-quarkus-jackson&e=ai.timefold.solver%3Atimefold-solver-quarkus[code.quarkus.io] to generate an application
```suggestion Use https://code.quarkus.io/?a=timefold-solver-quickstart&j=21&e=resteasy&e=resteasy-jackson&e=ai.timefold.solver%3Atimefold-solver-quarkus-jackson&e=ai.timefold.solver%3Atimefold-solver-quarkus[code.quarkus.io] to generate an application ``` Maybe we want to nudge people towards the latest LTS?
timefold-solver
github_2023
others
1,201
TimefoldAI
triceo
@@ -1,19 +1,19 @@ # This file is temporary, since for the time being, we need to build docs from the main branch. # Remove when 1.16.0 is out, otherwise this file quickly becomes stale.
```suggestion # Remove when 1.17.0 is out, otherwise this file quickly becomes stale. ```
timefold-solver
github_2023
java
1,198
TimefoldAI
zepfred
@@ -198,71 +199,65 @@ private EntitySelector<Solution_> applyFiltering(EntitySelector<Solution_> entit } protected void validateSorting(SelectionOrder resolvedSelectionOrder) { - if ((config.getSorterManner() != null || config.getSorterComparatorClass() != null + var sorterManner = config.getSorterManner(); + if ((sorterManner != null || config.getSorterComparatorClass() != null || config.getSorterWeightFactoryClass() != null || config.getSorterOrder() != null || config.getSorterClass() != null) && resolvedSelectionOrder != SelectionOrder.SORTED) { - throw new IllegalArgumentException("The entitySelectorConfig (" + config - + ") with sorterManner (" + config.getSorterManner() - + ") and sorterComparatorClass (" + config.getSorterComparatorClass() - + ") and sorterWeightFactoryClass (" + config.getSorterWeightFactoryClass() - + ") and sorterOrder (" + config.getSorterOrder() - + ") and sorterClass (" + config.getSorterClass() - + ") has a resolvedSelectionOrder (" + resolvedSelectionOrder - + ") that is not " + SelectionOrder.SORTED + "."); - } - if (config.getSorterManner() != null && config.getSorterComparatorClass() != null) { - throw new IllegalArgumentException("The entitySelectorConfig (" + config - + ") has both a sorterManner (" + config.getSorterManner() - + ") and a sorterComparatorClass (" + config.getSorterComparatorClass() + ")."); - } - if (config.getSorterManner() != null && config.getSorterWeightFactoryClass() != null) { - throw new IllegalArgumentException("The entitySelectorConfig (" + config - + ") has both a sorterManner (" + config.getSorterManner() - + ") and a sorterWeightFactoryClass (" + config.getSorterWeightFactoryClass() + ")."); - } - if (config.getSorterManner() != null && config.getSorterClass() != null) { - throw new IllegalArgumentException("The entitySelectorConfig (" + config - + ") has both a sorterManner (" + config.getSorterManner() - + ") and a sorterClass (" + config.getSorterClass() + ")."); - } - if (config.getSorterManner() != null && config.getSorterOrder() != null) { - throw new IllegalArgumentException("The entitySelectorConfig (" + config - + ") with sorterManner (" + config.getSorterManner() - + ") has a non-null sorterOrder (" + config.getSorterOrder() + ")."); + throw new IllegalArgumentException(""" + The entitySelectorConfig (%s) with sorterManner (%s) \ + and sorterComparatorClass (%s) and sorterWeightFactoryClass (%s) and sorterOrder (%s) and sorterClass (%s) \ + has a resolvedSelectionOrder (%s) that is not %s.""" + .formatted(config, sorterManner, config.getSorterComparatorClass(), + config.getSorterWeightFactoryClass(), config.getSorterOrder(), config.getSorterClass(), + resolvedSelectionOrder, SelectionOrder.SORTED)); } + assertNotSorterMannerAnd(config, "sorterComparatorClass", EntitySelectorConfig::getSorterComparatorClass); + assertNotSorterMannerAnd(config, "sorterWeightFactoryClass", EntitySelectorConfig::getSorterWeightFactoryClass); + assertNotSorterMannerAnd(config, "sorterClass", EntitySelectorConfig::getSorterClass); + assertNotSorterMannerAnd(config, "sorterOrder", EntitySelectorConfig::getSorterOrder); + assertNotSorterClassAnd(config, "sorterComparatorClass", EntitySelectorConfig::getSorterComparatorClass); + assertNotSorterClassAnd(config, "sorterWeightFactoryClass", EntitySelectorConfig::getSorterWeightFactoryClass); + assertNotSorterClassAnd(config, "sorterOrder", EntitySelectorConfig::getSorterOrder); if (config.getSorterComparatorClass() != null && config.getSorterWeightFactoryClass() != null) { - throw new IllegalArgumentException("The entitySelectorConfig (" + config - + ") has both a sorterComparatorClass (" + config.getSorterComparatorClass() - + ") and a sorterWeightFactoryClass (" + config.getSorterWeightFactoryClass() + ")."); + throw new IllegalArgumentException( + "The entitySelectorConfig (%s) has both a sorterComparatorClass (%s) and a sorterWeightFactoryClass (%s)." + .formatted(config, config.getSorterComparatorClass(), config.getSorterWeightFactoryClass()));
Let's create a variable for `config.getSorterComparatorClass()` and `config.getSorterWeightFactoryClass()`.
timefold-solver
github_2023
java
1,198
TimefoldAI
zepfred
@@ -278,7 +273,7 @@ protected EntitySelector<Solution_> applySorting(SelectionCacheType resolvedCach } else { throw new IllegalArgumentException("The entitySelectorConfig (" + config
Let's use `formatted`
timefold-solver
github_2023
java
1,198
TimefoldAI
zepfred
@@ -256,71 +257,64 @@ protected ValueSelector<Solution_> applyInitializedChainedValueFilter(HeuristicC } protected void validateSorting(SelectionOrder resolvedSelectionOrder) { - if ((config.getSorterManner() != null || config.getSorterComparatorClass() != null + var sorterManner = config.getSorterManner();
Consider applying the same pattern used in multiple places: declare the variable and then check if it is null.
timefold-solver
github_2023
java
1,198
TimefoldAI
zepfred
@@ -198,71 +199,65 @@ private EntitySelector<Solution_> applyFiltering(EntitySelector<Solution_> entit } protected void validateSorting(SelectionOrder resolvedSelectionOrder) { - if ((config.getSorterManner() != null || config.getSorterComparatorClass() != null + var sorterManner = config.getSorterManner();
Consider applying the same pattern used in multiple places: declare the variable and then check if it is null.
timefold-solver
github_2023
java
1,198
TimefoldAI
zepfred
@@ -336,7 +330,7 @@ protected ValueSelector<Solution_> applySorting(SelectionCacheType resolvedCache } else { throw new IllegalArgumentException("The valueSelectorConfig (" + config
Let's use `formatted`
timefold-solver
github_2023
java
1,198
TimefoldAI
zepfred
@@ -610,18 +610,16 @@ public String toString() { @Override public boolean equals(Object o) { - if (this == o) { + if (this == o)
Do we want to remove the curly braces?
timefold-solver
github_2023
java
1,197
TimefoldAI
zepfred
@@ -111,15 +101,15 @@ protected MoveSelectorConfig<?> buildUnfoldedMoveSelectorConfig(HeuristicConfigP + " or use a changeMoveSelector instead."); } if (!onlyDestinationVariableDescriptor.isListVariable()) { - throw new IllegalArgumentException("The destinationSelector (" + config.getDestinationSelectorConfig() + throw new IllegalArgumentException("The destinationSelector (" + destinationSelectorConfig
Let's use `formatted`.
timefold-solver
github_2023
java
1,197
TimefoldAI
zepfred
@@ -111,15 +101,15 @@ protected MoveSelectorConfig<?> buildUnfoldedMoveSelectorConfig(HeuristicConfigP + " or use a changeMoveSelector instead."); } if (!onlyDestinationVariableDescriptor.isListVariable()) { - throw new IllegalArgumentException("The destinationSelector (" + config.getDestinationSelectorConfig() + throw new IllegalArgumentException("The destinationSelector (" + destinationSelectorConfig + ") is configured to use a planning variable (" + onlyDestinationVariableDescriptor + "), which is not a planning list variable."); } if (onlyVariableDescriptor != onlyDestinationVariableDescriptor) { throw new IllegalArgumentException("The listChangeMoveSelector's valueSelector (" - + config.getValueSelectorConfig() + + valueSelectorConfig
Let's use `formatted`.
timefold-solver
github_2023
java
1,197
TimefoldAI
zepfred
@@ -146,61 +145,57 @@ protected ValueSelector<Solution_> buildMimicReplaying(HeuristicConfigPolicy<Sol || config.getSorterClass() != null || config.getProbabilityWeightFactoryClass() != null || config.getSelectedCountLimit() != null) { - throw new IllegalArgumentException("The valueSelectorConfig (" + config - + ") with mimicSelectorRef (" + config.getMimicSelectorRef() - + ") has another property that is not null."); + throw new IllegalArgumentException( + "The valueSelectorConfig (%s) with mimicSelectorRef (%s) has another property that is not null." + .formatted(config, config.getMimicSelectorRef())); } - ValueMimicRecorder<Solution_> valueMimicRecorder = configPolicy.getValueMimicRecorder(config.getMimicSelectorRef()); + var valueMimicRecorder = configPolicy.getValueMimicRecorder(config.getMimicSelectorRef()); if (valueMimicRecorder == null) { - throw new IllegalArgumentException("The valueSelectorConfig (" + config - + ") has a mimicSelectorRef (" + config.getMimicSelectorRef() - + ") for which no valueSelector with that id exists (in its solver phase)."); + throw new IllegalArgumentException( + "The valueSelectorConfig (%s) has a mimicSelectorRef (%s) for which no valueSelector with that id exists (in its solver phase)." + .formatted(config, config.getMimicSelectorRef())); } return new MimicReplayingValueSelector<>(valueMimicRecorder); } protected EntityDescriptor<Solution_> downcastEntityDescriptor(HeuristicConfigPolicy<Solution_> configPolicy, EntityDescriptor<Solution_> entityDescriptor) { - if (config.getDowncastEntityClass() != null) { - Class<?> parentEntityClass = entityDescriptor.getEntityClass(); - if (!parentEntityClass.isAssignableFrom(config.getDowncastEntityClass())) { - throw new IllegalStateException("The downcastEntityClass (" + config.getDowncastEntityClass() - + ") is not a subclass of the parentEntityClass (" + parentEntityClass - + ") configured by the " + EntitySelector.class.getSimpleName() + "."); + var downcastEntityClass = config.getDowncastEntityClass(); + if (downcastEntityClass != null) { + var parentEntityClass = entityDescriptor.getEntityClass(); + if (!parentEntityClass.isAssignableFrom(downcastEntityClass)) { + throw new IllegalStateException( + "The downcastEntityClass (%s) is not a subclass of the parentEntityClass (%s) configured by the %s." + .formatted(downcastEntityClass, parentEntityClass, EntitySelector.class.getSimpleName())); } - SolutionDescriptor<Solution_> solutionDescriptor = configPolicy.getSolutionDescriptor(); - entityDescriptor = solutionDescriptor.getEntityDescriptorStrict(config.getDowncastEntityClass()); + var solutionDescriptor = configPolicy.getSolutionDescriptor(); + entityDescriptor = solutionDescriptor.getEntityDescriptorStrict(downcastEntityClass); if (entityDescriptor == null) { - throw new IllegalArgumentException("The selectorConfig (" + config - + ") has an downcastEntityClass (" + config.getDowncastEntityClass() - + ") that is not a known planning entity.\n" - + "Check your solver configuration. If that class (" + config.getDowncastEntityClass().getSimpleName() - + ") is not in the entityClassSet (" + solutionDescriptor.getEntityClassSet() - + "), check your @" + PlanningSolution.class.getSimpleName() - + " implementation's annotated methods too."); + throw new IllegalArgumentException(""" + The selectorConfig (%s) has an downcastEntityClass (%s) that is not a known planning entity. + Check your solver configuration. If that class (%s) is not in the entityClassSet (%s), \ + check your @%s implementation's annotated methods too.""" + .formatted(config, downcastEntityClass, downcastEntityClass.getSimpleName(), + solutionDescriptor.getEntityClassSet(), PlanningSolution.class.getSimpleName())); } } return entityDescriptor; } protected boolean determineBaseRandomSelection(GenuineVariableDescriptor<Solution_> variableDescriptor, SelectionCacheType resolvedCacheType, SelectionOrder resolvedSelectionOrder) { - switch (resolvedSelectionOrder) { - case ORIGINAL: - return false; - case SORTED: - case SHUFFLED: - case PROBABILISTIC: + return switch (resolvedSelectionOrder) { + case ORIGINAL -> false; + case SORTED, SHUFFLED, PROBABILISTIC ->
It can be merged with `ORIGINAL`.
timefold-solver
github_2023
java
1,197
TimefoldAI
zepfred
@@ -47,10 +47,7 @@ public EasyScoreCalculator<Solution_, Score_> getEasyScoreCalculator() { public Score_ calculateScore() { variableListenerSupport.assertNotificationQueuesAreEmpty(); Score_ score = easyScoreCalculator.calculateScore(workingSolution); - if (score == null) { - throw new IllegalStateException("The easyScoreCalculator (" + easyScoreCalculator.getClass() - + ") must return a non-null score (" + score + ") in the method calculateScore()."); - } else if (!score.isSolutionInitialized()) { + if (!score.isSolutionInitialized()) { throw new IllegalStateException("The score (" + this + ")'s initScore (" + score.initScore()
Let's use `formatted`.
timefold-solver
github_2023
java
1,197
TimefoldAI
zepfred
@@ -86,12 +86,11 @@ public <A> void assertValidFromType(Class<A> fromType) { } public List<Constraint_> buildConstraints(ConstraintProvider constraintProvider) { - Constraint[] constraints = constraintProvider.defineConstraints(this); - if (constraints == null) { - throw new IllegalStateException("The constraintProvider class (" + constraintProvider.getClass() - + ")'s defineConstraints() must not return null.\n" - + "Maybe return an empty array instead if there are no constraints."); - } + Constraint[] constraints = Objects.requireNonNull(constraintProvider.defineConstraints(this), + () -> """ + The constraintProvider class (%s)'s defineConstraints() must not return null." + Maybe return an empty array instead if there are no constraints.""" + .formatted(constraintProvider.getClass())); if (Arrays.stream(constraints).anyMatch(Objects::isNull)) { throw new IllegalStateException("The constraintProvider class (" + constraintProvider.getClass()
Let's use `formatted`.
timefold-solver
github_2023
java
1,197
TimefoldAI
zepfred
@@ -57,18 +57,20 @@ public <Score_ extends Score<Score_>> Termination<Solution_> buildTermination( Arrays.fill(timeGradientWeightNumbers, 0.50); // Number pulled out of thin air terminationList.add(new BestScoreTermination<>(scoreDefinition, bestScoreLimit_, timeGradientWeightNumbers)); } - if (terminationConfig.getBestScoreFeasible() != null) { + var bestScoreFeasible = terminationConfig.getBestScoreFeasible(); + if (bestScoreFeasible != null) { ScoreDefinition<Score_> scoreDefinition = configPolicy.getScoreDefinition(); - if (!terminationConfig.getBestScoreFeasible()) { - throw new IllegalArgumentException("The termination bestScoreFeasible (" - + terminationConfig.getBestScoreFeasible() + ") cannot be false."); + if (!bestScoreFeasible) { + throw new IllegalArgumentException("The termination bestScoreFeasible (%s) cannot be false." + .formatted(bestScoreFeasible)); } int feasibleLevelsSize = scoreDefinition.getFeasibleLevelsSize(); if (feasibleLevelsSize < 1) { - throw new IllegalStateException("The termination with bestScoreFeasible (" - + terminationConfig.getBestScoreFeasible() - + ") can only be used with a score type that has at least 1 feasible level but the scoreDefinition (" - + scoreDefinition + ") has feasibleLevelsSize (" + feasibleLevelsSize + "), which is less than 1."); + throw new IllegalStateException(""" + The termination with bestScoreFeasible (%s) can only be used with a score type \
Why are we including the backslash in this message?
timefold-solver
github_2023
java
1,197
TimefoldAI
zepfred
@@ -18,7 +19,7 @@ public void serialize(ConstraintWeightOverrides<Score_> constraintWeightOverride generator.writeStartObject(); for (var constraintName : constraintWeightOverrides.getKnownConstraintNames()) { var weight = constraintWeightOverrides.getConstraintWeight(constraintName);
```suggestion var weight = Objects.requireNonNull(constraintWeightOverrides.getConstraintWeight(constraintName)); ```
timefold-solver
github_2023
java
1,197
TimefoldAI
zepfred
@@ -18,7 +19,7 @@ public void serialize(ConstraintWeightOverrides<Score_> constraintWeightOverride generator.writeStartObject(); for (var constraintName : constraintWeightOverrides.getKnownConstraintNames()) { var weight = constraintWeightOverrides.getConstraintWeight(constraintName); - generator.writeStringField(constraintName, weight.toString()); + generator.writeStringField(constraintName, Objects.requireNonNull(weight).toString());
```suggestion generator.writeStringField(constraintName, weight.toString()); ```
timefold-solver
github_2023
java
1,197
TimefoldAI
zepfred
@@ -238,18 +238,19 @@ private void loadSolverConfig(IncludeAbstractClassesEntityScanner entityScanner, if (solverConfig.getSolutionClass() == null) { solverConfig.setSolutionClass(entityScanner.findFirstSolutionClass()); } - if (solverConfig.getEntityClassList() == null) { + var solverEntityClassList = solverConfig.getEntityClassList(); + if (solverEntityClassList == null) { solverConfig.setEntityClassList(entityScanner.findEntityClassList()); } else { - long entityClassCount = solverConfig.getEntityClassList().stream() + long entityClassCount = solverEntityClassList.stream()
```suggestion var entityClassCount = solverEntityClassList.stream() ```
timefold-solver
github_2023
java
1,160
TimefoldAI
triceo
@@ -219,226 +219,233 @@ public final class ConstraintCollectors { * The default result of the collector (e.g. when never called) is {@code 0}. * * @param <A> type of the matched fact - * @return never null */ - public static <A> UniConstraintCollector<A, ?, Integer> sum(ToIntFunction<? super A> groupValueMapping) { + public static <A> @NonNull UniConstraintCollector<A, ?, Integer> sum(@NonNull ToIntFunction<? super A> groupValueMapping) { return InnerUniConstraintCollectors.sum(groupValueMapping); } /** * As defined by {@link #sum(ToIntFunction)}. */ - public static <A> UniConstraintCollector<A, ?, Long> sumLong(ToLongFunction<? super A> groupValueMapping) { + public static <A> @NonNull UniConstraintCollector<A, ?, Long> + sumLong(@NonNull ToLongFunction<? super A> groupValueMapping) { return InnerUniConstraintCollectors.sum(groupValueMapping); } /** * As defined by {@link #sum(ToIntFunction)}. */ - public static <A, Result> UniConstraintCollector<A, ?, Result> sum(Function<? super A, Result> groupValueMapping, + // TODO: nullability of further params (suppose all are @NonNull)
Yes. There are overloads for that method which do not require these arguments - so when an argument is actually present, it is required unless Javadoc says otherwise.
timefold-solver
github_2023
java
1,160
TimefoldAI
triceo
@@ -543,168 +509,172 @@ public void setThreadFactoryClass(Class<? extends ThreadFactory> threadFactoryCl * * @return null, a number or {@value #PARALLEL_BENCHMARK_COUNT_AUTO}. */ - public String getParallelBenchmarkCount() { + public @Nullable String getParallelBenchmarkCount() { return parallelBenchmarkCount; } - public void setParallelBenchmarkCount(String parallelBenchmarkCount) { + public void setParallelBenchmarkCount(@Nullable String parallelBenchmarkCount) { this.parallelBenchmarkCount = parallelBenchmarkCount; } - public Long getWarmUpMillisecondsSpentLimit() { + public @NonNull Long getWarmUpMillisecondsSpentLimit() { return warmUpMillisecondsSpentLimit; } - public void setWarmUpMillisecondsSpentLimit(Long warmUpMillisecondsSpentLimit) { + public void setWarmUpMillisecondsSpentLimit(@NonNull Long warmUpMillisecondsSpentLimit) { this.warmUpMillisecondsSpentLimit = warmUpMillisecondsSpentLimit; } - public Long getWarmUpSecondsSpentLimit() { + public @NonNull Long getWarmUpSecondsSpentLimit() { return warmUpSecondsSpentLimit; } - public void setWarmUpSecondsSpentLimit(Long warmUpSecondsSpentLimit) { + public void setWarmUpSecondsSpentLimit(@NonNull Long warmUpSecondsSpentLimit) { this.warmUpSecondsSpentLimit = warmUpSecondsSpentLimit; } - public Long getWarmUpMinutesSpentLimit() { + public @NonNull Long getWarmUpMinutesSpentLimit() { return warmUpMinutesSpentLimit; } - public void setWarmUpMinutesSpentLimit(Long warmUpMinutesSpentLimit) { + public void setWarmUpMinutesSpentLimit(@NonNull Long warmUpMinutesSpentLimit) { this.warmUpMinutesSpentLimit = warmUpMinutesSpentLimit; } - public Long getWarmUpHoursSpentLimit() { + public @NonNull Long getWarmUpHoursSpentLimit() { return warmUpHoursSpentLimit; } - public void setWarmUpHoursSpentLimit(Long warmUpHoursSpentLimit) { + public void setWarmUpHoursSpentLimit(@NonNull Long warmUpHoursSpentLimit) { this.warmUpHoursSpentLimit = warmUpHoursSpentLimit; } - public Long getWarmUpDaysSpentLimit() { + public @NonNull Long getWarmUpDaysSpentLimit() {
I'm afraid this pattern is not correct. :-( - Getters in configs have to be `Nullable`, because the fields may hold `null`. `null` here means that the user chose not to specify. (Why else would we choose `Long` instead of `long`, avoiding reference types altogether?) - Setters likewise have to be able to accept `null`, because the solver code needs to be able to express that something should explicitly be set to its default value. - It is only the withers which should not accept null and never return it, because we understand withers to mean that the user is making an explicit choice, and therefore `null` no longer applies. This is an unfortunate miscommunication. We have discussed this topic in comments above - even after re-reading my answer, I still think I said the same thing as I am saying here. Sadly, I can not accept this and the annotations in configs need to be reviewed with the above in mind. :-( Interestingly, it seems like not all configs use this wrong pattern - some configs properly assign nullability as we agreed. Maybe this file was annotated before our agreement?
timefold-solver
github_2023
java
1,160
TimefoldAI
triceo
@@ -90,12 +92,15 @@ public enum SolverMetric { this.isConstraintMatchBased = isConstraintMatchBased; } - public String getMeterId() { + public @NonNull String getMeterId() { return meterId; } - public static void registerScoreMetrics(SolverMetric metric, Tags tags, ScoreDefinition<?> scoreDefinition, - Map<Tags, List<AtomicReference<Number>>> tagToScoreLevels, Score<?> score) { + public static void registerScoreMetrics(@NonNull SolverMetric metric, @NonNull Tags tags, + // TODO: @NonNull Map<@NonNull Tags, @NonNull List<@NonNull AtomicReference<@NonNull Number>>> tagToScoreLevels? + @NonNull ScoreDefinition<?> scoreDefinition, + @NonNull Map<@NonNull Tags, List<AtomicReference<Number>>> tagToScoreLevels, + @NonNull Score<?> score) {
Not our best API design here. :-( You know Kotlin better than I do. Would these annotations on this crazy type actually help? I feel like they would, but I will defer to your judgment here.
timefold-solver
github_2023
java
1,160
TimefoldAI
triceo
@@ -236,7 +246,8 @@ public NearbySelectionConfig withBetaDistributionBeta(Double betaDistributionBet // Builder methods // ************************************************************************ - public void validateNearby(SelectionCacheType resolvedCacheType, SelectionOrder resolvedSelectionOrder) { + // TODO clarify if @NonNull is ok for both params + public void validateNearby(@NonNull SelectionCacheType resolvedCacheType, @NonNull SelectionOrder resolvedSelectionOrder) {
Non-null OK for both.
timefold-solver
github_2023
java
1,160
TimefoldAI
triceo
@@ -325,7 +329,8 @@ public String toString() { return getClass().getSimpleName() + "(" + entityClass + ")"; } - public static <Solution_> boolean hasSorter(EntitySorterManner entitySorterManner, + // TODO: entityDescriptor @NonNull? + public static <Solution_> boolean hasSorter(@NonNull EntitySorterManner entitySorterManner, EntityDescriptor<Solution_> entityDescriptor) {
Non-null OK for both.
timefold-solver
github_2023
java
1,160
TimefoldAI
triceo
@@ -234,28 +237,26 @@ public Config_ withFixedProbabilityWeight(Double fixedProbabilityWeight) { * Gather a list of all descendant {@link MoveSelectorConfig}s * except for {@link UnionMoveSelectorConfig} and {@link CartesianProductMoveSelectorConfig}. * - * @param leafMoveSelectorConfigList not null */ - public void extractLeafMoveSelectorConfigsIntoList(List<MoveSelectorConfig> leafMoveSelectorConfigList) { + // TODO: list elements @NonNull? + public void extractLeafMoveSelectorConfigsIntoList(@NonNull List<@NonNull MoveSelectorConfig> leafMoveSelectorConfigList) {
Yes, it makes sense. I would not expect null inside of this collection.
timefold-solver
github_2023
java
1,160
TimefoldAI
triceo
@@ -69,213 +72,215 @@ public class ValueSelectorConfig extends SelectorConfig<ValueSelectorConfig> { public ValueSelectorConfig() { } - public ValueSelectorConfig(String variableName) { + // TODO: @NonNull ok here?
I went over the code and everywhere this is called, it is actually given a value. If there is something in the docs about this, then first of all I don't really understand why we decided to document this, but more importantly, it should just be fixed to say that this is not nullable.
timefold-solver
github_2023
java
1,160
TimefoldAI
triceo
@@ -275,112 +278,116 @@ public TerminationConfig withTerminationClass(Class<? extends Termination> termi return this; } - public TerminationConfig withTerminationCompositionStyle(TerminationCompositionStyle terminationCompositionStyle) { + public @NonNull TerminationConfig + withTerminationCompositionStyle(@NonNull TerminationCompositionStyle terminationCompositionStyle) { this.terminationCompositionStyle = terminationCompositionStyle; return this; } - public TerminationConfig withSpentLimit(Duration spentLimit) { + public @NonNull TerminationConfig withSpentLimit(@NonNull Duration spentLimit) { this.spentLimit = spentLimit; return this; } - public TerminationConfig withMillisecondsSpentLimit(Long millisecondsSpentLimit) { + public @NonNull TerminationConfig withMillisecondsSpentLimit(@NonNull Long millisecondsSpentLimit) { this.millisecondsSpentLimit = millisecondsSpentLimit; return this; } - public TerminationConfig withSecondsSpentLimit(Long secondsSpentLimit) { + public @NonNull TerminationConfig withSecondsSpentLimit(@NonNull Long secondsSpentLimit) { this.secondsSpentLimit = secondsSpentLimit; return this; } - public TerminationConfig withMinutesSpentLimit(Long minutesSpentLimit) { + public @NonNull TerminationConfig withMinutesSpentLimit(@NonNull Long minutesSpentLimit) { this.minutesSpentLimit = minutesSpentLimit; return this; } - public TerminationConfig withHoursSpentLimit(Long hoursSpentLimit) { + public @NonNull TerminationConfig withHoursSpentLimit(@NonNull Long hoursSpentLimit) { this.hoursSpentLimit = hoursSpentLimit; return this; } - public TerminationConfig withDaysSpentLimit(Long daysSpentLimit) { + public @NonNull TerminationConfig withDaysSpentLimit(@NonNull Long daysSpentLimit) { this.daysSpentLimit = daysSpentLimit; return this; } - public TerminationConfig withUnimprovedSpentLimit(Duration unimprovedSpentLimit) { + public @NonNull TerminationConfig withUnimprovedSpentLimit(@NonNull Duration unimprovedSpentLimit) { this.unimprovedSpentLimit = unimprovedSpentLimit; return this; } - public TerminationConfig withUnimprovedMillisecondsSpentLimit(Long unimprovedMillisecondsSpentLimit) { + public @NonNull TerminationConfig withUnimprovedMillisecondsSpentLimit(@NonNull Long unimprovedMillisecondsSpentLimit) { this.unimprovedMillisecondsSpentLimit = unimprovedMillisecondsSpentLimit; return this; } - public TerminationConfig withUnimprovedSecondsSpentLimit(Long unimprovedSecondsSpentLimit) { + public @NonNull TerminationConfig withUnimprovedSecondsSpentLimit(@NonNull Long unimprovedSecondsSpentLimit) { this.unimprovedSecondsSpentLimit = unimprovedSecondsSpentLimit; return this; } - public TerminationConfig withUnimprovedMinutesSpentLimit(Long unimprovedMinutesSpentLimit) { + public @NonNull TerminationConfig withUnimprovedMinutesSpentLimit(@NonNull Long unimprovedMinutesSpentLimit) { this.unimprovedMinutesSpentLimit = unimprovedMinutesSpentLimit; return this; } - public TerminationConfig withUnimprovedHoursSpentLimit(Long unimprovedHoursSpentLimit) { + public @NonNull TerminationConfig withUnimprovedHoursSpentLimit(@NonNull Long unimprovedHoursSpentLimit) { this.unimprovedHoursSpentLimit = unimprovedHoursSpentLimit; return this; } - public TerminationConfig withUnimprovedDaysSpentLimit(Long unimprovedDaysSpentLimit) { + public @NonNull TerminationConfig withUnimprovedDaysSpentLimit(@NonNull Long unimprovedDaysSpentLimit) { this.unimprovedDaysSpentLimit = unimprovedDaysSpentLimit; return this; } - public TerminationConfig withUnimprovedScoreDifferenceThreshold(String unimprovedScoreDifferenceThreshold) { + public @NonNull TerminationConfig + withUnimprovedScoreDifferenceThreshold(@NonNull String unimprovedScoreDifferenceThreshold) { this.unimprovedScoreDifferenceThreshold = unimprovedScoreDifferenceThreshold; return this; } - public TerminationConfig withBestScoreLimit(String bestScoreLimit) { + public @NonNull TerminationConfig withBestScoreLimit(@NonNull String bestScoreLimit) { this.bestScoreLimit = bestScoreLimit; return this; } - public TerminationConfig withBestScoreFeasible(Boolean bestScoreFeasible) { + public @NonNull TerminationConfig withBestScoreFeasible(@NonNull Boolean bestScoreFeasible) { this.bestScoreFeasible = bestScoreFeasible; return this; } - public TerminationConfig withStepCountLimit(Integer stepCountLimit) { + public @NonNull TerminationConfig withStepCountLimit(@NonNull Integer stepCountLimit) { this.stepCountLimit = stepCountLimit; return this; } - public TerminationConfig withUnimprovedStepCountLimit(Integer unimprovedStepCountLimit) { + public @NonNull TerminationConfig withUnimprovedStepCountLimit(@NonNull Integer unimprovedStepCountLimit) { this.unimprovedStepCountLimit = unimprovedStepCountLimit; return this; } - public TerminationConfig withScoreCalculationCountLimit(Long scoreCalculationCountLimit) { + public @NonNull TerminationConfig withScoreCalculationCountLimit(@NonNull Long scoreCalculationCountLimit) { this.scoreCalculationCountLimit = scoreCalculationCountLimit; return this; } - public TerminationConfig withMoveCountLimit(Long moveCountLimit) { + public @NonNull TerminationConfig withMoveCountLimit(@NonNull Long moveCountLimit) { this.moveCountLimit = moveCountLimit; return this; } - public TerminationConfig withTerminationConfigList(List<TerminationConfig> terminationConfigList) { + public @NonNull TerminationConfig + withTerminationConfigList(@NonNull List<@NonNull TerminationConfig> terminationConfigList) { this.terminationConfigList = terminationConfigList; return this; } - public void overwriteSpentLimit(Duration spentLimit) { + // TODO @NonNull ok here? + public void overwriteSpentLimit(@NonNull Duration spentLimit) {
This is very unclear. Erring on the side of caution, I'd say nullable.
timefold-solver
github_2023
java
1,160
TimefoldAI
triceo
@@ -430,7 +437,8 @@ public void shortenTimeMillisSpentLimit(long timeMillisSpentLimit) { } } - public void overwriteUnimprovedSpentLimit(Duration unimprovedSpentLimit) { + // TODO @NonNull ok here? + public void overwriteUnimprovedSpentLimit(@NonNull Duration unimprovedSpentLimit) {
Dtto.
timefold-solver
github_2023
java
1,160
TimefoldAI
triceo
@@ -268,10 +261,7 @@ public static SolverConfig createFromXmlReader(Reader reader, ClassLoader classL public SolverConfig() { } - /** - * @param classLoader sometimes null - */ - public SolverConfig(ClassLoader classLoader) { + public SolverConfig(@Nullable ClassLoader classLoader) {
People can create their own instances of this class, and build the solver config programmatically, as opposed to using XML. Therefore I'd say that nullable is correct here.
timefold-solver
github_2023
java
1,160
TimefoldAI
triceo
@@ -58,7 +61,8 @@ public class ConfigUtils { * @param <T> the new instance type * @return new instance of clazz */ - public static <T> T newInstance(Object configBean, String propertyName, Class<T> clazz) { + // TODO: propertyName, clazz + public static <T> @NonNull T newInstance(@Nullable Object configBean, String propertyName, Class<T> clazz) {
I'd say so.
timefold-solver
github_2023
java
1,160
TimefoldAI
triceo
@@ -87,8 +91,9 @@ public static <T> T newInstance(Supplier<String> ownerDescriptor, String propert } } - public static void applyCustomProperties(Object bean, String beanClassPropertyName, - Map<String, String> customProperties, String customPropertiesPropertyName) { + // TODO: param customPropertiesPropertyName + public static void applyCustomProperties(@NonNull Object bean, @NonNull String beanClassPropertyName, + @Nullable Map<@NonNull String, @NonNull String> customProperties, String customPropertiesPropertyName) {
Judgment call. I say no.
timefold-solver
github_2023
java
1,160
TimefoldAI
triceo
@@ -295,7 +304,8 @@ public static int ceilDivide(int dividend, int divisor) { return (dividend / divisor) + correction; } - public static int resolvePoolSize(String propertyName, String value, String... magicValues) { + // TODO what to make of magicValues? + public static int resolvePoolSize(String propertyName, @NonNull String value, String... magicValues) {
The user would have to specifically cast the `null` to either `String[]` or `String`, in order for this to work at all. For that reason, I say non-null. Also, shouldn't `propertyName` be non-null as well? I'd say so.
timefold-solver
github_2023
java
1,160
TimefoldAI
triceo
@@ -384,6 +392,7 @@ public static List<Member> getAllMembers(Class<?> baseClass, Class<? extends Ann return memberStream.distinct().sorted(alphabeticMemberComparator).collect(Collectors.toList()); } + // TODO @SafeVarargs public static Class<? extends Annotation> extractAnnotationClass(Member member, Class<? extends Annotation>... annotationClasses) {
Agree.
timefold-solver
github_2023
java
1,160
TimefoldAI
triceo
@@ -415,6 +425,7 @@ Maybe the member (%s) should return a parameterized %s.""" memberName, type, memberName, type.getSimpleName()))); } + // TODO public static Optional<Class<?>> extractGenericTypeParameter(String parentClassConcept, Class<?> parentClass, Class<?> type, Type genericType, Class<? extends Annotation> annotationClass, String memberName) {
Agree.
timefold-solver
github_2023
java
1,160
TimefoldAI
triceo
@@ -11,17 +14,19 @@ public interface MultiConstraintAssertion { * @param score total score calculated for the given set of facts * @throws AssertionError when the expected score does not match the calculated score */ - default void scores(Score<?> score) { + // TODO: @NonNull score sensible? + default void scores(@NonNull Score<?> score) {
Yes. This is an assertion - since it's not possible for score returned by the solver to ever be null, I'd say non-null here makes total sense.
timefold-solver
github_2023
java
1,160
TimefoldAI
triceo
@@ -11,17 +14,19 @@ public interface MultiConstraintAssertion { * @param score total score calculated for the given set of facts * @throws AssertionError when the expected score does not match the calculated score */ - default void scores(Score<?> score) { + // TODO: @NonNull score sensible? + default void scores(@NonNull Score<?> score) { scores(score, null); } /** * As defined by {@link #scores(Score)}. * * @param score total score calculated for the given set of facts - * @param message sometimes null, description of the scenario being asserted + * @param message description of the scenario being asserted * @throws AssertionError when the expected score does not match the calculated score */ - void scores(Score<?> score, String message); + // TODO: @NonNull score sensible? + void scores(@NonNull Score<?> score, @Nullable String message);
Dtto.
timefold-solver
github_2023
java
1,160
TimefoldAI
triceo
@@ -1,21 +1,22 @@ package ai.timefold.solver.test.api.score.stream; +import org.jspecify.annotations.NonNull; + public interface MultiConstraintVerification<Solution_> { /** * As defined by {@link SingleConstraintVerification#given(Object...)}. * - * @param facts never null, at least one - * @return never null + * @param facts at least one */ - MultiConstraintAssertion given(Object... facts); + // TODO @NonNull Object correct here? + @NonNull + MultiConstraintAssertion given(@NonNull Object @NonNull... facts);
Agree. For varargs, I think they generally should be non-null. (See my explanation above.)
timefold-solver
github_2023
java
1,160
TimefoldAI
triceo
@@ -90,10 +93,11 @@ public enum SolverMetric { this.isConstraintMatchBased = isConstraintMatchBased; } - public String getMeterId() { + public @NonNull String getMeterId() { return meterId; } + @NullMarked public static void registerScoreMetrics(SolverMetric metric, Tags tags, ScoreDefinition<?> scoreDefinition, Map<Tags, List<AtomicReference<Number>>> tagToScoreLevels, Score<?> score) {
I'd leave it for now. I'll have some downtime before the release, I'll go back to my notes and review some of the places where maybe I want to think about it a bit more. This will be one of them.
timefold-solver
github_2023
java
1,160
TimefoldAI
triceo
@@ -527,9 +518,9 @@ public SolverConfig withClassLoader(ClassLoader classLoader) { * As defined by {@link ScoreDirectorFactoryConfig#withEasyScoreCalculatorClass(Class)}, but returns this. * * @param easyScoreCalculatorClass sometimes null - * @return this, never null */ - public SolverConfig withEasyScoreCalculatorClass(Class<? extends EasyScoreCalculator> easyScoreCalculatorClass) { + // TODO docu says param of a with-method may be null + public @NonNull SolverConfig withEasyScoreCalculatorClass(Class<? extends EasyScoreCalculator> easyScoreCalculatorClass) {
Damn, I keep missing questions. :-( The Github UX for this needs to improve. I'd go with non-null - let's make a distinction between the getters and the withers. Brief search through the code indicates we do not actually pass null there anywhere.
timefold-solver
github_2023
java
1,185
TimefoldAI
zepfred
@@ -94,14 +95,14 @@ public void setTrackingWorkingSolution(boolean trackingWorkingSolution) { @Override public InnerScoreDirector<Solution_, Score_> buildScoreDirector() { - return buildScoreDirector(true, true); + return buildScoreDirector(false, ConstraintMatchPolicy.DISABLED);
Should we set `ENABLED_WITHOUT_JUSTIFICATIONS` or `ENABLED` instead?
timefold-solver
github_2023
java
1,185
TimefoldAI
zepfred
@@ -29,56 +30,53 @@ public interface InnerScoreDirectorFactory<Solution_, Score_ extends Score<Score InnerScoreDirector<Solution_, Score_> buildScoreDirector();
Is there documentation for the default value of `ConstraintMatchPolicy` used in `buildScoreDirector()`?
timefold-solver
github_2023
java
1,185
TimefoldAI
zepfred
@@ -28,9 +29,9 @@ public final class EasyScoreDirector<Solution_, Score_ extends Score<Score_>> private final EasyScoreCalculator<Solution_, Score_> easyScoreCalculator; public EasyScoreDirector(EasyScoreDirectorFactory<Solution_, Score_> scoreDirectorFactory, - boolean lookUpEnabled, boolean constraintMatchEnabledPreference, boolean expectShadowVariablesInCorrectState, + boolean lookUpEnabled, boolean expectShadowVariablesInCorrectState,
It seems that changing the `ConstraintMatchPolicy` is no longer possible. Should it be allowed?
timefold-solver
github_2023
java
1,009
TimefoldAI
triceo
@@ -13,9 +15,10 @@ public interface PinningFilter<Solution_, Entity_> { /** * @param solution working solution to which the entity belongs - * @param entity never null, a {@link PlanningEntity} + * @param entity a {@link PlanningEntity} * @return true if the entity it is pinned, false if the entity is movable. */ - boolean accept(Solution_ solution, Entity_ entity); + // TODO @param solution is probably never null?
Agree.
timefold-solver
github_2023
java
1,009
TimefoldAI
triceo
@@ -46,6 +46,7 @@ * * @return {@link NullPinningFilter} when it is null (workaround for annotation limitation) */ + // TODO feels like this could be annotated with @NonNull
As we've agreed annotations wouldn't be treated, let's remove these TODOs.