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,009 | TimefoldAI | triceo | @@ -18,31 +18,33 @@
import ai.timefold.solver.core.impl.score.constraint.DefaultConstraintMatchTotal;
import ai.timefold.solver.core.impl.util.CollectionUtils;
+import org.jspecify.annotations.NonNull;
+import org.jspecify.annotations.Nullable;
+
/**
* Note: Users should never create instances of this type directly.
* It is available transitively via {@link SolutionManager#analyze(Object)}.
*
* @param <Score_>
- * @param constraintRef never null
- * @param weight never null
- * @param score never null
* @param matches null if analysis not available;
* empty if constraint has no matches, but still non-zero constraint weight;
* non-empty if constraint has matches.
* This is a {@link List} to simplify access to individual elements,
* but it contains no duplicates just like {@link HashSet} wouldn't.
*/
-public record ConstraintAnalysis<Score_ extends Score<Score_>>(ConstraintRef constraintRef, Score_ weight,
- Score_ score, List<MatchAnalysis<Score_>> matches) {
+public record ConstraintAnalysis<Score_ extends Score<Score_>>(@NonNull ConstraintRef constraintRef, @NonNull Score_ weight,
+ @NonNull Score_ score, @Nullable List<MatchAnalysis<Score_>> matches) {
- static <Score_ extends Score<Score_>> ConstraintAnalysis<Score_> of(ConstraintRef constraintRef, Score_ constraintWeight,
- Score_ score) {
+ static <Score_ extends Score<Score_>> @NonNull ConstraintAnalysis<Score_> of(
+ @NonNull ConstraintRef constraintRef,
+ @NonNull Score_ constraintWeight,
+ @NonNull Score_ score) {
return new ConstraintAnalysis<>(constraintRef, constraintWeight, score, null);
}
public ConstraintAnalysis {
Objects.requireNonNull(constraintRef);
- if (weight == null) {
+ if (weight == null) { // TODO: clarify - why illegal arg exception vs NPE from requireNonNull? | No particular reason. I guess I just don't like to throw an NPE, but I agree that this might as well be one. |
timefold-solver | github_2023 | java | 1,009 | TimefoldAI | triceo | @@ -46,22 +44,22 @@ public static BendableBigDecimalScore parseScore(String scoreString) {
* Creates a new {@link BendableBigDecimalScore}.
*
* @param initScore see {@link Score#initScore()}
- * @param hardScores never null, never change that array afterwards: it must be immutable
- * @param softScores never null, never change that array afterwards: it must be immutable
- * @return never null
+ * @param hardScores never change that array afterwards: it must be immutable
+ * @param softScores never change that array afterwards: it must be immutable
*/
- public static BendableBigDecimalScore ofUninitialized(int initScore, BigDecimal[] hardScores, BigDecimal[] softScores) {
+ // TODO: @NonNull BigDecimal? | Not sure what you mean. If the question is whether the array contents can be null, than the answer is no - but I'm not sure you can state that using these annotations. |
timefold-solver | github_2023 | java | 1,009 | TimefoldAI | triceo | @@ -138,9 +131,9 @@ public int initScore() {
}
/**
- * @return not null, array copy because this class is immutable
+ * @return array copy because this class is immutable
*/
- public long[] hardScores() {
+ public long @NonNull [] hardScores() { | For my edification, as I haven't seen this before... is this how you have to annotate array types? My brain would find `@NonNull long[]` much more natural. |
timefold-solver | github_2023 | java | 1,009 | TimefoldAI | triceo | @@ -53,15 +55,18 @@ public static HardMediumSoftBigDecimalScore parseScore(String scoreString) {
return ofUninitialized(initScore, hardScore, mediumScore, softScore);
}
- public static HardMediumSoftBigDecimalScore ofUninitialized(int initScore, BigDecimal hardScore, BigDecimal mediumScore,
+ public static @NonNull HardMediumSoftBigDecimalScore ofUninitialized(int initScore, BigDecimal hardScore,
+ BigDecimal mediumScore,
BigDecimal softScore) {
if (initScore == 0) {
return of(hardScore, mediumScore, softScore);
}
return new HardMediumSoftBigDecimalScore(initScore, hardScore, mediumScore, softScore);
}
- public static HardMediumSoftBigDecimalScore of(BigDecimal hardScore, BigDecimal mediumScore, BigDecimal softScore) {
+ // TODO: params nonnull? | IMO yes. Let's make sure we propagate this to the other `BigDecimal` score types as well. |
timefold-solver | github_2023 | java | 1,009 | TimefoldAI | triceo | @@ -132,6 +137,7 @@ public static HardMediumSoftBigDecimalScore ofSoft(BigDecimal softScore) {
* timefold-solver-jpa, timefold-solver-jackson, timefold-solver-jaxb, ...
*/
@SuppressWarnings("unused")
+ // TODO: params default or null? | Well spotted. In the interest of getting rid of null, default values (`BigDecimal.ZERO`) would be preferred. |
timefold-solver | github_2023 | java | 1,009 | TimefoldAI | triceo | @@ -155,6 +161,7 @@ public int initScore() {
*
* @return higher is better, usually negative, 0 if no hard constraints are broken/fulfilled
*/
+ // TODO: nonnull? | Based on the above, yes. |
timefold-solver | github_2023 | java | 1,009 | TimefoldAI | triceo | @@ -694,6 +696,7 @@ or uncorrupted constraintMatchEnabled (%s) is disabled.
uncorruptedAnalysis.constraintMap().forEach((constraintRef, uncorruptedConstraintAnalysis) -> {
var corruptedConstraintAnalysis = corruptedAnalysis.constraintMap()
.get(constraintRef);
+ // TODO: matches() is Nullable | Keep the warning there, please. I'll take a look at all new warnings after this is merged, and decide if the code needs changing or if the annotation needs adjusting. |
timefold-solver | github_2023 | java | 1,009 | TimefoldAI | triceo | @@ -117,16 +111,15 @@ public static BendableScore ofSoft(int hardLevelsSize, int softLevelsSize, int s
* timefold-solver-jpa, timefold-solver-jackson, timefold-solver-jaxb, ...
*/
@SuppressWarnings("unused")
+ // TODO: suppress warnings here or use empty array? Also in related classes (bendable) | Yes. |
timefold-solver | github_2023 | java | 1,009 | TimefoldAI | triceo | @@ -66,6 +67,7 @@
*
* @return {@link NullSolutionCloner} when it is null (workaround for annotation limitation)
*/
+ // TODO: return @NonNull? | This is really just an annotations hack. I would avoid marking annotations. |
timefold-solver | github_2023 | java | 1,009 | TimefoldAI | triceo | @@ -19,33 +21,32 @@ public interface IncrementalScoreCalculator<Solution_, Score_ extends Score<Scor
/**
* There are no {@link #beforeEntityAdded(Object)} and {@link #afterEntityAdded(Object)} calls
* for entities that are already present in the workingSolution.
- *
- * @param workingSolution never null
*/
- void resetWorkingSolution(Solution_ workingSolution);
+ void resetWorkingSolution(@NonNull Solution_ workingSolution);
/**
- * @param entity never null, an instance of a {@link PlanningEntity} class
+ * @param entity an instance of a {@link PlanningEntity} class
*/
- void beforeEntityAdded(Object entity);
+ void beforeEntityAdded(@NonNull Object entity);
/**
- * @param entity never null, an instance of a {@link PlanningEntity} class
+ * @param entity an instance of a {@link PlanningEntity} class
*/
- void afterEntityAdded(Object entity);
+ void afterEntityAdded(@NonNull Object entity);
/**
- * @param entity never null, an instance of a {@link PlanningEntity} class
- * @param variableName never null, either a genuine or shadow {@link PlanningVariable}
+ * @param entity an instance of a {@link PlanningEntity} class
+ * @param variableName either a genuine or shadow {@link PlanningVariable}
*/
- void beforeVariableChanged(Object entity, String variableName);
+ void beforeVariableChanged(@NonNull Object entity, @NonNull String variableName);
/**
- * @param entity never null, an instance of a {@link PlanningEntity} class
- * @param variableName never null, either a genuine or shadow {@link PlanningVariable}
+ * @param entity an instance of a {@link PlanningEntity} class
+ * @param variableName either a genuine or shadow {@link PlanningVariable}
*/
- void afterVariableChanged(Object entity, String variableName);
+ void afterVariableChanged(@NonNull Object entity, @NonNull String variableName);
+ // TODO: should these params be @NonNull? | Correct. |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -0,0 +1,110 @@
+package ai.timefold.solver.core.api.domain.metamodel;
+
+import java.util.List;
+
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
+import ai.timefold.solver.core.api.domain.variable.PlanningListVariable;
+import ai.timefold.solver.core.api.domain.variable.PlanningVariable;
+
+/**
+ * Represents the meta-model of an entity.
+ * Gives access to the entity's variable meta-models.
+ * <p>
+ * <strong>This package and all of its contents are part of the Move Streams API,
+ * which is under development and is only offered as a preview feature.</strong>
+ * There are no guarantees for backward compatibility;
+ * any class, method or field may change or be removed without prior notice,
+ * although we will strive to avoid this as much as possible.
+ * <p>
+ * We encourage you to try the API and give us feedback on your experience with it,
+ * before we finalize the API.
+ * Please direct your feedback to
+ * <a href="https://github.com/TimefoldAI/timefold-solver/discussions">Timefold Solver Github</a>.
+ *
+ * @param <Solution_> The solution type.
+ * @param <Entity_> The entity type.
+ */
+public interface PlanningEntityMetaModel<Solution_, Entity_> {
+
+ /**
+ * Describes the {@link PlanningSolution} that owns this entity.
+ *
+ * @return never null, the solution meta-model.
+ */
+ PlanningSolutionMetaModel<Solution_> solution();
+
+ /**
+ * Returns the most specific class of the entity.
+ *
+ * @return never null, the entity type.
+ */
+ Class<Entity_> type();
+
+ /**
+ * Returns the variables owned by the entity, both genuine and shadow.
+ *
+ * @return never null
+ */
+ List<VariableMetaModel<Solution_, Entity_, ?>> variables();
+
+ /**
+ * Returns the genuine variables owned by the entity.
+ *
+ * @return never null
+ */
+ default List<VariableMetaModel<Solution_, Entity_, ?>> genuineVariables() {
+ return variables().stream()
+ .filter(VariableMetaModel::isGenuine)
+ .toList();
+ }
+
+ /**
+ * Returns a {@link VariableMetaModel} for a variable with the given name.
+ *
+ * @return never null
+ * @throws IllegalArgumentException if the variable does not exist on the entity
+ */
+ @SuppressWarnings("unchecked")
+ default <Value_> VariableMetaModel<Solution_, Entity_, Value_> variable(String variableName) {
+ for (var variableMetaModel : variables()) {
+ if (variableMetaModel.name().equals(variableName)) {
+ return (VariableMetaModel<Solution_, Entity_, Value_>) variableMetaModel;
+ }
+ }
+ throw new IllegalArgumentException( | Should we use the "formatted" instead? |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -0,0 +1,70 @@
+package ai.timefold.solver.core.api.domain.metamodel;
+
+import java.util.List;
+
+import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
+
+/**
+ * Represents the meta-model of a {@link PlanningSolution}.
+ * Allows access to information about all the entities and variables.
+ * <p>
+ * <strong>This package and all of its contents are part of the Move Streams API,
+ * which is under development and is only offered as a preview feature.</strong>
+ * There are no guarantees for backward compatibility;
+ * any class, method or field may change or be removed without prior notice,
+ * although we will strive to avoid this as much as possible.
+ * <p>
+ * We encourage you to try the API and give us feedback on your experience with it,
+ * before we finalize the API.
+ * Please direct your feedback to
+ * <a href="https://github.com/TimefoldAI/timefold-solver/discussions">Timefold Solver Github</a>.
+ *
+ * @param <Solution_> the type of the solution
+ */
+public interface PlanningSolutionMetaModel<Solution_> {
+
+ /**
+ * Returns the class of the solution.
+ *
+ * @return never null, the type of the solution
+ */
+ Class<Solution_> type();
+
+ /**
+ * Returns the meta-models of @{@link PlanningEntity planning entities} known to the solution, genuine or shadow.
+ *
+ * @return never null
+ */
+ List<PlanningEntityMetaModel<Solution_, ?>> entities();
+
+ /**
+ * Returns the meta-models of genuine @{@link PlanningEntity planning entities} known to the solution.
+ *
+ * @return never null
+ */
+ default List<PlanningEntityMetaModel<Solution_, ?>> genuineEntities() {
+ return entities().stream()
+ .filter(PlanningEntityMetaModel::isGenuine)
+ .toList();
+ }
+
+ /**
+ * Returns the meta-model of the @{@link PlanningEntity planning entity} with the given class.
+ *
+ * @param entityClass never null
+ * @return never null
+ * @throws IllegalArgumentException if the entity class is not known to the solution
+ */
+ @SuppressWarnings("unchecked")
+ default <Entity_> PlanningEntityMetaModel<Solution_, Entity_> entity(Class<Entity_> entityClass) {
+ for (var entityMetaModel : entities()) {
+ if (entityMetaModel.type().equals(entityClass)) {
+ return (PlanningEntityMetaModel<Solution_, Entity_>) entityMetaModel;
+ }
+ }
+ throw new IllegalArgumentException( | Let's use String::formatted |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -0,0 +1,51 @@
+package ai.timefold.solver.core.api.domain.metamodel;
+
+import ai.timefold.solver.core.api.domain.variable.PlanningVariable;
+
+/**
+ * A {@link VariableMetaModel} that represents a @{@link PlanningVariable basic planning variable}.
+ *
+ * <p>
+ * <strong>This package and all of its contents are part of the Move Streams API,
+ * which is under development and is only offered as a preview feature.</strong>
+ * There are no guarantees for backward compatibility;
+ * any class, method or field may change or be removed without prior notice,
+ * although we will strive to avoid this as much as possible.
+ * <p>
+ * We encourage you to try the API and give us feedback on your experience with it,
+ * before we finalize the API.
+ * Please direct your feedback to
+ * <a href="https://github.com/TimefoldAI/timefold-solver/discussions">Timefold Solver Github</a>.
+ *
+ * @param <Solution_> the solution type
+ * @param <Entity_> the entity type
+ * @param <Value_> the value type
+ */
+public non-sealed interface PlanningVariableMetaModel<Solution_, Entity_, Value_>
+ extends VariableMetaModel<Solution_, Entity_, Value_> {
+
+ @Override
+ default boolean isList() {
+ return false;
+ }
+
+ @Override
+ default boolean isGenuine() {
+ return true;
+ }
+
+ /**
+ * Returns whether the planning variable allows null values.
+ *
+ * @return {@code true} if the planning variable allows null values, {@code false} otherwise.
+ */
+ boolean allowsUnassigned(); | I wonder if `allowsUnassigned` should be part of `VariableMetaModel`. If we need to cast variable models to check this, perhaps we could avoid that by adding it to the parent class. |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -0,0 +1,51 @@
+package ai.timefold.solver.core.api.domain.metamodel;
+
+import ai.timefold.solver.core.api.domain.variable.PlanningVariable;
+
+/**
+ * A {@link VariableMetaModel} that represents a @{@link PlanningVariable basic planning variable}.
+ *
+ * <p>
+ * <strong>This package and all of its contents are part of the Move Streams API,
+ * which is under development and is only offered as a preview feature.</strong>
+ * There are no guarantees for backward compatibility;
+ * any class, method or field may change or be removed without prior notice,
+ * although we will strive to avoid this as much as possible.
+ * <p>
+ * We encourage you to try the API and give us feedback on your experience with it,
+ * before we finalize the API.
+ * Please direct your feedback to
+ * <a href="https://github.com/TimefoldAI/timefold-solver/discussions">Timefold Solver Github</a>.
+ *
+ * @param <Solution_> the solution type
+ * @param <Entity_> the entity type
+ * @param <Value_> the value type
+ */
+public non-sealed interface PlanningVariableMetaModel<Solution_, Entity_, Value_>
+ extends VariableMetaModel<Solution_, Entity_, Value_> {
+
+ @Override
+ default boolean isList() {
+ return false;
+ }
+
+ @Override
+ default boolean isGenuine() {
+ return true;
+ }
+
+ /**
+ * Returns whether the planning variable allows null values.
+ *
+ * @return {@code true} if the planning variable allows null values, {@code false} otherwise.
+ */
+ boolean allowsUnassigned();
+
+ /**
+ * Returns whether the planning variable is chained.
+ *
+ * @return {@code true} if the planning variable is chained, {@code false} otherwise.
+ */
+ boolean isChained(); | Same as above |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -0,0 +1,37 @@
+package ai.timefold.solver.core.api.domain.metamodel;
+
+/**
+ * A {@link VariableMetaModel} that represents a shadow planning variable. | Custom shadow variables can be modified by user code |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -0,0 +1,11 @@
+package ai.timefold.solver.core.api.domain.metamodel;
+
+record DefaultUnassignedLocation() implements UnassignedLocation { | I understand your strategy, but I suggest a different approach. What if `DefaultUnassignedLocation` extends `DefaultLocationInList` and throws exceptions for `DefaultUnassignedLocation::entity()` or `DefaultUnassignedLocation::index()`?
We still fail fast, and there will be no need to cast values in the internal classes, which I didn't like when using `LocationInList` previously. Additionally, we could add a method `ElementLocation::isAssigned()` and override it in `DefaultUnassignedLocation`. |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -0,0 +1,138 @@
+package ai.timefold.solver.core.api.move;
+
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.LinkedHashSet;
+import java.util.List;
+
+import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
+import ai.timefold.solver.core.api.domain.lookup.PlanningId;
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
+import ai.timefold.solver.core.api.domain.solution.ProblemFactProperty;
+import ai.timefold.solver.core.api.domain.variable.PlanningVariable;
+import ai.timefold.solver.core.api.score.director.ScoreDirector;
+
+/**
+ * A Move represents a change of 1 or more {@link PlanningVariable}s of 1 or more {@link PlanningEntity}s
+ * in the working {@link PlanningSolution}.
+ * <p>
+ * Usually the move holds a direct reference to each {@link PlanningEntity} of the {@link PlanningSolution}
+ * which it will change when {@link #execute(MutableSolutionState)} is called.
+ * On that change it will also notify the {@link ScoreDirector} accordingly.
+ * <p>
+ * For tabu search, a Move should implement {@link Object#equals(Object)} and {@link Object#hashCode()},
+ * {@link #extractPlanningEntities()} and {@link #extractPlanningValues()}.
+ * <p>
+ * <strong>This package and all of its contents are part of the Move Streams API,
+ * which is under development and is only offered as a preview feature.</strong>
+ * There are no guarantees for backward compatibility;
+ * any class, method or field may change or be removed without prior notice,
+ * although we will strive to avoid this as much as possible.
+ * <p>
+ * We encourage you to try the API and give us feedback on your experience with it,
+ * before we finalize the API.
+ * Please direct your feedback to
+ * <a href="https://github.com/TimefoldAI/timefold-solver/discussions">Timefold Solver Github</a>.
+ *
+ * @param <Solution_>
+ */
+public interface Move<Solution_> {
+
+ /**
+ * Runs the move and optionally records the changes done,
+ * so that they can be undone later.
+ *
+ * @param mutableSolutionState never null; exposes all possible mutative operations on the variables.
+ * Remembers those mutative operations and can replay them in reverse order
+ * when the solver needs to undo the move.
+ * Do not store this parameter in a field.
+ */
+ void execute(MutableSolutionState<Solution_> mutableSolutionState);
+
+ /**
+ * Rebases a move from an origin {@link ScoreDirector} to another destination {@link ScoreDirector}
+ * which is usually on another {@link Thread}.
+ * It is necessary for multithreaded solving to function.
+ * <p>
+ * The new move returned by this method translates the entities and problem facts
+ * to the destination {@link PlanningSolution} of the destination {@link ScoreDirector},
+ * That destination {@link PlanningSolution} is a deep planning clone (or an even deeper clone)
+ * of the origin {@link PlanningSolution} that this move has been generated from.
+ * <p>
+ * That new move does the exact same change as this move,
+ * resulting in the same {@link PlanningSolution} state,
+ * presuming that destination {@link PlanningSolution} was in the same state
+ * as the original {@link PlanningSolution} to begin with.
+ * <p>
+ * An implementation of this method typically iterates through every entity and fact instance in this move,
+ * translates each one to the destination {@link ScoreDirector} with {@link Rebaser#rebase(Object)}
+ * and creates a new move instance of the same move type, using those translated instances.
+ * <p>
+ * The destination {@link PlanningSolution} can be in a different state than the original {@link PlanningSolution}.
+ * So, rebasing can only depend on the identity of {@link PlanningEntity planning entities}
+ * and {@link ProblemFactProperty problem facts},
+ * which are usually declared by a {@link PlanningId} on those classes.
+ * It must not depend on the state of the {@link PlanningVariable planning variables}.
+ * One thread might rebase a move before, amid or after another thread does that same move instance.
+ * <p>
+ * This method is thread-safe.
+ *
+ * @param rebaser never null; do not store this parameter in a field
+ * @return never null, a new move that does the same change as this move on another solution instance
+ */
+ Move<Solution_> rebase(Rebaser rebaser);
+
+ /**
+ * Returns all planning entities that this move is changing.
+ * Required for entity tabu.
+ * <p>
+ * This method is only called after {@link #execute(MutableSolutionState)}, which might affect the return values.
+ * <p>
+ * Duplicate entries in the returned {@link Collection} are best avoided.
+ * The returned {@link Collection} is recommended to be in a stable order.
+ * For example, use {@link List} or {@link LinkedHashSet}, but not {@link HashSet}.
+ *
+ * @return never null
+ */
+ default Collection<?> extractPlanningEntities() { | Are there any move implementations that do not provide these methods? Does it make sense to have them for any move? Depending on the answers, why not transfer these tabu-related operations to a specific tabu-move interface, such as `TabuMove extends Move`?
Next to that, the TB logic should use `TabuMove` instead of `Move`. Does it make sense? |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -0,0 +1,80 @@
+package ai.timefold.solver.core.api.move;
+
+import ai.timefold.solver.core.api.domain.metamodel.PlanningListVariableMetaModel;
+import ai.timefold.solver.core.api.domain.metamodel.PlanningVariableMetaModel;
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
+import ai.timefold.solver.core.api.domain.variable.PlanningListVariable;
+import ai.timefold.solver.core.api.domain.variable.PlanningVariable;
+import ai.timefold.solver.core.api.score.director.ScoreDirector;
+
+/**
+ * Contains all reading and mutating methods available to a {@link Move}
+ * in order to change the state of a {@link PlanningSolution planning solution}.
+ * <p>
+ * <strong>This package and all of its contents are part of the Move Streams API,
+ * which is under development and is only offered as a preview feature.</strong>
+ * There are no guarantees for backward compatibility;
+ * any class, method or field may change or be removed without prior notice,
+ * although we will strive to avoid this as much as possible.
+ * <p>
+ * We encourage you to try the API and give us feedback on your experience with it,
+ * before we finalize the API.
+ * Please direct your feedback to
+ * <a href="https://github.com/TimefoldAI/timefold-solver/discussions">Timefold Solver Github</a>.
+ *
+ * @param <Solution_>
+ */
+public interface MutableSolutionState<Solution_> extends SolutionState<Solution_> { | What about the unassign operation? |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -0,0 +1,64 @@
+package ai.timefold.solver.core.impl.domain.solution.descriptor;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+
+import ai.timefold.solver.core.api.domain.metamodel.PlanningEntityMetaModel;
+import ai.timefold.solver.core.api.domain.metamodel.PlanningSolutionMetaModel;
+import ai.timefold.solver.core.api.domain.metamodel.VariableMetaModel;
+import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
+
+public final class DefaultPlanningEntityMetaModel<Solution_, Entity_>
+ implements PlanningEntityMetaModel<Solution_, Entity_> {
+
+ private final EntityDescriptor<Solution_> entityDescriptor;
+ private final PlanningSolutionMetaModel<Solution_> solution;
+ private final Class<Entity_> type;
+ private final List<VariableMetaModel<Solution_, Entity_, ?>> variables = new ArrayList<>();
+
+ @SuppressWarnings("unchecked")
+ DefaultPlanningEntityMetaModel(PlanningSolutionMetaModel<Solution_> solution,
+ EntityDescriptor<Solution_> entityDescriptor) {
+ this.solution = Objects.requireNonNull(solution);
+ this.entityDescriptor = Objects.requireNonNull(entityDescriptor);
+ this.type = (Class<Entity_>) entityDescriptor.getEntityClass();
+ }
+
+ public EntityDescriptor<Solution_> entityDescriptor() {
+ return entityDescriptor;
+ }
+
+ @Override
+ public PlanningSolutionMetaModel<Solution_> solution() {
+ return solution;
+ }
+
+ @Override
+ public Class<Entity_> type() {
+ return type;
+ }
+
+ @Override
+ public List<VariableMetaModel<Solution_, Entity_, ?>> variables() {
+ return Collections.unmodifiableList(variables);
+ }
+
+ void addVariable(VariableMetaModel<Solution_, Entity_, ?> variable) {
+ if (variable.entity() != this) {
+ throw new IllegalArgumentException("The variable (" + variable + ") is not part of this entity (" + this + ")."); | Let's use "formatted" |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -0,0 +1,67 @@
+package ai.timefold.solver.core.impl.domain.solution.descriptor;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+
+import ai.timefold.solver.core.api.domain.metamodel.PlanningEntityMetaModel;
+import ai.timefold.solver.core.api.domain.metamodel.PlanningSolutionMetaModel;
+
+public final class DefaultPlanningSolutionMetaModel<Solution_> implements PlanningSolutionMetaModel<Solution_> {
+
+ private final SolutionDescriptor<Solution_> solutionDescriptor;
+ private final Class<Solution_> type;
+ private final List<PlanningEntityMetaModel<Solution_, ?>> entities = new ArrayList<>();
+
+ DefaultPlanningSolutionMetaModel(SolutionDescriptor<Solution_> solutionDescriptor) {
+ this.solutionDescriptor = Objects.requireNonNull(solutionDescriptor);
+ this.type = solutionDescriptor.getSolutionClass();
+ }
+
+ public SolutionDescriptor<Solution_> solutionDescriptor() {
+ return solutionDescriptor;
+ }
+
+ @Override
+ public Class<Solution_> type() {
+ return type;
+ }
+
+ @Override
+ public List<PlanningEntityMetaModel<Solution_, ?>> entities() {
+ return Collections.unmodifiableList(entities);
+ }
+
+ void addEntity(PlanningEntityMetaModel<Solution_, ?> planningEntityMetaModel) {
+ if (planningEntityMetaModel.solution() != this) {
+ throw new IllegalArgumentException("The entityMetaModel (" + planningEntityMetaModel | Let's use "formatted" |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -0,0 +1,36 @@
+package ai.timefold.solver.core.impl.domain.solution.descriptor;
+
+import ai.timefold.solver.core.api.domain.metamodel.PlanningEntityMetaModel;
+import ai.timefold.solver.core.api.domain.metamodel.ShadowVariableMetaModel;
+import ai.timefold.solver.core.impl.domain.variable.descriptor.ShadowVariableDescriptor;
+
+public record DefaultShadowVariableMetaModel<Solution_, Entity_, Value_>(
+ PlanningEntityMetaModel<Solution_, Entity_> entity,
+ ShadowVariableDescriptor<Solution_> variableDescriptor)
+ implements
+ ShadowVariableMetaModel<Solution_, Entity_, Value_>,
+ InnerVariableMetaModel<Solution_> {
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public Class<Value_> type() {
+ return (Class<Value_>) variableDescriptor.getVariablePropertyType();
+ }
+
+ @Override
+ public String name() {
+ return variableDescriptor.getVariableName();
+ }
+
+ @Override
+ public ShadowVariableDescriptor<Solution_> variableDescriptor() { | Do we need this method? |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -0,0 +1,10 @@
+package ai.timefold.solver.core.impl.domain.solution.descriptor;
+
+import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
+
+public sealed interface InnerVariableMetaModel<Solution_> | Why not move this interface to the public API and return a generic type? Alternatively, we could add the method to `VariableMetaModel`, as it appears to be a common method for all its child classes. |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -4,16 +4,16 @@
import java.util.Map;
import java.util.Objects;
+import ai.timefold.solver.core.api.domain.metamodel.ElementLocation;
+import ai.timefold.solver.core.api.domain.metamodel.LocationInList;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
-import ai.timefold.solver.core.impl.heuristic.selector.list.ElementLocation;
-import ai.timefold.solver.core.impl.heuristic.selector.list.LocationInList;
final class ExternalizedListVariableStateSupply<Solution_> | Here is one of the places we could enhance the experience by modifying the default contract so that `ExternalizedListVariableStateSupply::getLocationInList` returns `LocationInList`. I'm uncertain whether calling `ensureAssigned()` would disrupt existing code, but if not, it would be logical to apply this validation when retrieving an element
`getLocationInList`.
My point is to return something that can be used without casting or converting with `ensureAssigned`. On the other hand, I understand that changing the contract could impact many other areas. |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -7,26 +7,24 @@
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
+import ai.timefold.solver.core.impl.move.director.VariableChangeRecordingScoreDirector;
/**
* Abstract superclass for {@link Move}, requiring implementation of undo moves.
- * Unless raw performance is a concern, consider using {@link AbstractSimplifiedMove} instead.
*
* @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
* @see Move
*/
public abstract class AbstractMove<Solution_> implements Move<Solution_> {
- @Override
- public final Move<Solution_> doMove(ScoreDirector<Solution_> scoreDirector) {
- var undoMove = createUndoMove(scoreDirector);
- doMoveOnly(scoreDirector);
- return undoMove;
- }
-
@Override
public final void doMoveOnly(ScoreDirector<Solution_> scoreDirector) {
- doMoveOnGenuineVariables(scoreDirector);
+ // LegacyMoveAdapter does not wrap the score director in a VariableChangeRecordingScoreDirector | I'm unsure if the comment makes sense. It looks like we will always use `VariableChangeRecordingScoreDirector`. |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -10,20 +11,20 @@
* therefore removing the need to implement the undo move.
*
* @param <Solution_>
+ * @deprecated In favor of {@link AbstractMove}, which no longer requires undo moves to be implemented either.
*/
+@Deprecated(forRemoval = true, since = "1.16.0")
public abstract class AbstractSimplifiedMove<Solution_> implements Move<Solution_> {
- @Override
- public final Move<Solution_> doMove(ScoreDirector<Solution_> scoreDirector) {
- var recordingScoreDirector = new VariableChangeRecordingScoreDirector<>(scoreDirector);
- doMoveOnly(recordingScoreDirector);
- return new RecordedUndoMove<>(this, recordingScoreDirector.getVariableChanges());
- }
-
@Override
public final void doMoveOnly(ScoreDirector<Solution_> scoreDirector) {
- doMoveOnGenuineVariables(scoreDirector);
- scoreDirector.triggerVariableListeners();
+ // LegacyMoveAdapter does not wrap the score director in a VariableChangeRecordingScoreDirector | ditto |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -0,0 +1,24 @@
+package ai.timefold.solver.core.impl.heuristic.selector.move.factory;
+
+import java.util.Iterator;
+
+import ai.timefold.solver.core.api.move.Move;
+
+final class LegacyIteratorAdapter<Solution_> implements Iterator<Move<Solution_>> {
+
+ private final Iterator<ai.timefold.solver.core.impl.heuristic.move.Move<Solution_>> moveIterator;
+
+ public LegacyIteratorAdapter(Iterator<ai.timefold.solver.core.impl.heuristic.move.Move<Solution_>> moveIterator) {
+ this.moveIterator = moveIterator;
+ }
+
+ @Override
+ public boolean hasNext() {
+ return moveIterator.hasNext();
+ }
+
+ @Override
+ public Move<Solution_> next() {
+ return new ai.timefold.solver.core.impl.heuristic.move.LegacyMoveAdapter<>(moveIterator.next()); | Is there a reason for not importing the class? |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -68,19 +68,13 @@ public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) {
return !Objects.equals(oldFirstValue, toPlanningValue);
}
- @Override
- public SubChainChangeMove<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) {
- Object oldFirstValue = variableDescriptor.getValue(subChain.getFirstEntity());
- return new SubChainChangeMove<>(subChain, variableDescriptor, oldFirstValue, newTrailingEntity, oldTrailingLastEntity);
- }
-
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
- Object firstEntity = subChain.getFirstEntity();
- Object lastEntity = subChain.getLastEntity();
- Object oldFirstValue = variableDescriptor.getValue(firstEntity);
+ var firstEntity = subChain.getFirstEntity();
+ var lastEntity = subChain.getLastEntity();
+ var oldFirstValue = variableDescriptor.getValue(firstEntity);
// Close the old chain
- InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector;
+ var innerScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector; | Let's make it consistent and rename the var to `castScoreDirector` |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -67,34 +69,27 @@ public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) {
return !SubChainSwapMove.containsAnyOf(rightSubChain, leftSubChain);
}
- @Override
- public SubChainReversingSwapMove<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) {
- return new SubChainReversingSwapMove<>(variableDescriptor,
- rightSubChain.reverse(), leftTrailingLastEntity,
- leftSubChain.reverse(), rightTrailingLastEntity);
- }
-
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
- Object leftFirstEntity = leftSubChain.getFirstEntity();
- Object leftFirstValue = variableDescriptor.getValue(leftFirstEntity);
- Object leftLastEntity = leftSubChain.getLastEntity();
- Object rightFirstEntity = rightSubChain.getFirstEntity();
- Object rightFirstValue = variableDescriptor.getValue(rightFirstEntity);
- Object rightLastEntity = rightSubChain.getLastEntity();
- Object leftLastEntityValue = variableDescriptor.getValue(leftLastEntity);
- Object rightLastEntityValue = variableDescriptor.getValue(rightLastEntity);
+ var leftFirstEntity = leftSubChain.getFirstEntity();
+ var leftFirstValue = variableDescriptor.getValue(leftFirstEntity);
+ var leftLastEntity = leftSubChain.getLastEntity();
+ var rightFirstEntity = rightSubChain.getFirstEntity();
+ var rightFirstValue = variableDescriptor.getValue(rightFirstEntity);
+ var rightLastEntity = rightSubChain.getLastEntity();
+ var leftLastEntityValue = variableDescriptor.getValue(leftLastEntity);
+ var rightLastEntityValue = variableDescriptor.getValue(rightLastEntity);
// Change the entities
- InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector;
+ var innerScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector; | Let's rename it to `castScoreDirector` |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -188,68 +188,43 @@ public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) {
return true;
}
- @Override
- public TailChainSwapMove<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) {
- if (!sameAnchor) {
- return new TailChainSwapMove<>(variableDescriptor,
- leftEntity, rightValue, rightAnchor,
- rightEntity, leftValue, leftAnchor);
- } else {
- if (rightEntity == null) {
- // TODO Currently unsupported because we fail to create a valid undoMove... even though doMove supports it
- // https://issues.redhat.com/browse/PLANNER-1250
- throw new IllegalStateException("Impossible state, because isMoveDoable() should not return true.");
- }
- if (!reverseAnchorSide) {
- return new TailChainSwapMove<>(variableDescriptor,
- rightEntity, rightNextEntity, leftAnchor,
- leftEntity, rightValue, rightAnchor,
- leftNextEntity, leftValue);
- } else {
- return new TailChainSwapMove<>(variableDescriptor,
- rightEntity, rightNextEntity, leftAnchor,
- leftEntity, rightValue, rightAnchor,
- leftNextEntity, leftValue, entityAfterAnchor, lastEntityInChain);
- }
- }
- }
-
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
- InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector;
+ var castScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector;
if (!sameAnchor) {
// Change the left entity
- innerScoreDirector.changeVariableFacade(variableDescriptor, leftEntity, rightValue);
+ castScoreDirector.changeVariableFacade(variableDescriptor, leftEntity, rightValue);
// Change the right entity
if (rightEntity != null) {
- innerScoreDirector.changeVariableFacade(variableDescriptor, rightEntity, leftValue);
+ castScoreDirector.changeVariableFacade(variableDescriptor, rightEntity, leftValue);
}
} else {
if (!reverseAnchorSide) {
// Reverses loop on the side that doesn't include the anchor, because rightValue is earlier than leftEntity
- innerScoreDirector.changeVariableFacade(variableDescriptor, leftEntity, rightValue);
- reverseChain(innerScoreDirector, leftValue, leftEntity, rightEntity);
+ castScoreDirector.changeVariableFacade(variableDescriptor, leftEntity, rightValue);
+ reverseChain(castScoreDirector, leftValue, leftEntity, rightEntity);
if (leftNextEntity != null) {
- innerScoreDirector.changeVariableFacade(variableDescriptor, leftNextEntity, rightEntity);
+ castScoreDirector.changeVariableFacade(variableDescriptor, leftNextEntity, rightEntity);
}
} else {
// Reverses loop on the side that does include the anchor, because rightValue is later than leftEntity
// Change the head of the chain
- reverseChain(innerScoreDirector, leftValue, leftEntity, entityAfterAnchor);
+ reverseChain(castScoreDirector, leftValue, leftEntity, entityAfterAnchor);
// Change leftEntity
- innerScoreDirector.changeVariableFacade(variableDescriptor, leftEntity, rightValue);
+ castScoreDirector.changeVariableFacade(variableDescriptor, leftEntity, rightValue);
// Change the tail of the chain
- reverseChain(innerScoreDirector, lastEntityInChain, leftAnchor, rightEntity);
- innerScoreDirector.changeVariableFacade(variableDescriptor, leftNextEntity, rightEntity);
+ reverseChain(castScoreDirector, lastEntityInChain, leftAnchor, rightEntity);
+ castScoreDirector.changeVariableFacade(variableDescriptor, leftNextEntity, rightEntity);
}
}
}
- protected void reverseChain(InnerScoreDirector scoreDirector, Object fromValue, Object fromEntity, Object toEntity) {
- Object entity = fromValue;
- Object newValue = fromEntity;
+ protected void reverseChain(VariableDescriptorAwareScoreDirector<Solution_> scoreDirector, Object fromValue, | This method seems similar to `SubChainReversingChangeMove::reverseChain` |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -71,7 +71,8 @@ public <Node_> Node_ successor(Node_ object, ListVariableStateSupply<?> listVari
@SuppressWarnings("unchecked")
public <Node_> Node_ predecessor(Node_ object, ListVariableStateSupply<?> listVariableStateSupply) {
var listVariableDescriptor = listVariableStateSupply.getSourceVariableDescriptor(); | Let's apply `var` to all possible places. |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -86,9 +87,12 @@ public <Node_> Node_ predecessor(Node_ object, ListVariableStateSupply<?> listVa
}
public <Node_> boolean between(Node_ start, Node_ middle, Node_ end, ListVariableStateSupply<?> listVariableStateSupply) {
- var startElementLocation = (LocationInList) listVariableStateSupply.getLocationInList(start);
- var middleElementLocation = (LocationInList) listVariableStateSupply.getLocationInList(middle);
- var endElementLocation = (LocationInList) listVariableStateSupply.getLocationInList(end);
+ var startElementLocation = listVariableStateSupply.getLocationInList(start) | ditto |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -376,8 +377,10 @@ int getShortestCycleIdentifier(EntityOrderInfo entityOrderInfo, Object[] removeE
private int getSegmentSize(EntityOrderInfo entityOrderInfo, Object from, Object to) {
var entityToEntityIndex = entityOrderInfo.entityToEntityIndex();
- var startElementLocation = (LocationInList) listVariableStateSupply.getLocationInList(from);
- var endElementLocation = (LocationInList) listVariableStateSupply.getLocationInList(to);
+ var startElementLocation = listVariableStateSupply.getLocationInList(from) | Let's apply `var` to all possible places. |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -70,7 +70,7 @@ public void applyChangesFromCopy(MultipleDelegateList<?> copy) {
public int getIndexOfValue(ListVariableStateSupply<?> listVariableStateSupply, Object value) {
var elementLocation = listVariableStateSupply.getLocationInList(value);
- if (elementLocation instanceof LocationInList elementLocationInList) {
+ if (elementLocation instanceof LocationInList<?> elementLocationInList) { | This is kind of casting operation we can avoid by changing the `ListVariableStateSupply` contract.
See my suggestions related to `LocationInList`. |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -120,11 +109,11 @@ protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector)
}
private void doTailSwap(ScoreDirector<Solution_> scoreDirector) {
- InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector;
- List<Object> firstListVariable = variableDescriptor.getValue(firstEntity);
- List<Object> secondListVariable = variableDescriptor.getValue(secondEntity);
- int firstOriginalSize = firstListVariable.size();
- int secondOriginalSize = secondListVariable.size();
+ var innerScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector; | Let's rename it to `castScoreDirector` |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -153,8 +142,8 @@ private void doTailSwap(ScoreDirector<Solution_> scoreDirector) {
}
private void doSublistReversal(ScoreDirector<Solution_> scoreDirector) {
- InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector;
- List<Object> listVariable = variableDescriptor.getValue(firstEntity);
+ var innerScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector; | ditto |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -133,12 +122,12 @@ private void doTailSwap(ScoreDirector<Solution_> scoreDirector) {
secondEdgeEndpoint,
secondOriginalSize);
- List<Object> firstListVariableTail = firstListVariable.subList(firstEdgeEndpoint, firstOriginalSize);
- List<Object> secondListVariableTail = secondListVariable.subList(secondEdgeEndpoint, secondOriginalSize);
+ var firstListVariableTail = firstListVariable.subList(firstEdgeEndpoint, firstOriginalSize);
+ var secondListVariableTail = secondListVariable.subList(secondEdgeEndpoint, secondOriginalSize);
int tailSizeDifference = secondListVariableTail.size() - firstListVariableTail.size(); | Let's apply `var` to all possible places. |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -84,11 +81,23 @@ protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector)
constructionHeuristicPhase.solvingEnded(solverScope);
scoreDirector.triggerVariableListeners();
+ var entityToInsertedValuesMap = CollectionUtils.<Object, List<Object>> newIdentityHashMap(0);
+ for (var entity : entityToOriginalPositionMap.keySet()) {
+ entityToInsertedValuesMap.put(entity, new ArrayList<>());
+ }
+
for (var ruinedValue : ruinedValueList) {
- var location = (LocationInList) listVariableStateSupply.getLocationInList(ruinedValue);
+ var location = listVariableStateSupply.getLocationInList(ruinedValue)
+ .ensureAssigned();
entityToNewPositionMap.computeIfAbsent(location.entity(), ignored -> new TreeSet<>())
.add(new RuinedLocation(ruinedValue, location.index()));
+ entityToInsertedValuesMap.computeIfAbsent(location.entity(), ignored -> new ArrayList<>()).add(ruinedValue);
+ }
+
+ for (var entry : entityToInsertedValuesMap.entrySet()) {
+ recordingScoreDirector.recordListAssignment(listVariableDescriptor, entry.getKey(), entry.getValue()); | Is the call to `recordingScoreDirector.afterListVariableChanged` no longer necessary? |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -119,20 +119,15 @@ public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) {
return !(rightEntity == leftEntity && leftIndex == rightIndex);
}
- @Override
- public ListSwapMove<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) {
- return new ListSwapMove<>(variableDescriptor, rightEntity, rightIndex, leftEntity, leftIndex);
- }
-
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
- InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector;
- Object leftElement = variableDescriptor.getElement(leftEntity, leftIndex);
- Object rightElement = variableDescriptor.getElement(rightEntity, rightIndex);
+ var innerScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector; | Let's rename it to `castScoreDirector` |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -88,23 +87,17 @@ public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) {
}
}
- @Override
- protected AbstractMove<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) {
- return new SubListChangeMove<>(variableDescriptor, destinationEntity, destinationIndex, length, sourceEntity,
- sourceIndex, reversing);
- }
-
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
- InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector;
+ var innerScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector; | Let's rename it to `castScoreDirector` |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -48,15 +48,9 @@ public boolean isMoveDoable(ScoreDirector<Solution_> scoreDirector) {
return !Objects.equals(oldValue, toPlanningValue);
}
- @Override
- public ChangeMove<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) {
- Object oldValue = variableDescriptor.getValue(entity);
- return new ChangeMove<>(variableDescriptor, entity, oldValue);
- }
-
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
- InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector;
+ var innerScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector; | Let's rename it to `castScoreDirector` |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -81,10 +76,10 @@ public SwapMove<Solution_> rebase(ScoreDirector<Solution_> destinationScoreDirec
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
- InnerScoreDirector<Solution_, ?> innerScoreDirector = (InnerScoreDirector<Solution_, ?>) scoreDirector;
- for (GenuineVariableDescriptor<Solution_> variableDescriptor : variableDescriptorList) {
- Object oldLeftValue = variableDescriptor.getValue(leftEntity);
- Object oldRightValue = variableDescriptor.getValue(rightEntity);
+ var innerScoreDirector = (VariableDescriptorAwareScoreDirector<Solution_>) scoreDirector; | Let's rename it to `castScoreDirector` |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -0,0 +1,48 @@
+package ai.timefold.solver.core.impl.move.director;
+
+import ai.timefold.solver.core.api.domain.metamodel.ElementLocation;
+import ai.timefold.solver.core.api.domain.metamodel.PlanningListVariableMetaModel;
+import ai.timefold.solver.core.api.move.Move;
+import ai.timefold.solver.core.impl.score.director.VariableDescriptorAwareScoreDirector;
+
+/**
+ * The only move director that supports undoing moves.
+ * Moves are undone when the director is {@link #close() closed}.
+ *
+ * @param <Solution_>
+ */
+public final class EphemeralMoveDirector<Solution_> extends MoveDirector<Solution_> | Cool! |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -0,0 +1,20 @@
+package ai.timefold.solver.core.impl.move.director;
+
+import ai.timefold.solver.core.api.move.Rebaser;
+import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
+import ai.timefold.solver.core.impl.score.director.VariableDescriptorAwareScoreDirector;
+
+record ListVariableAfterUnassignmentAction<Solution_>(Object element,
+ ListVariableDescriptor<Solution_> variableDescriptor) implements ChangeAction<Solution_> {
+
+ @Override
+ public void undo(VariableDescriptorAwareScoreDirector<Solution_> scoreDirector) {
+ scoreDirector.beforeListVariableElementAssigned(variableDescriptor, element); | No actions here? |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -0,0 +1,20 @@
+package ai.timefold.solver.core.impl.move.director;
+
+import ai.timefold.solver.core.api.move.Rebaser;
+import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
+import ai.timefold.solver.core.impl.score.director.VariableDescriptorAwareScoreDirector;
+
+record ListVariableBeforeAssignmentAction<Solution_>(Object element,
+ ListVariableDescriptor<Solution_> variableDescriptor) implements ChangeAction<Solution_> {
+
+ @Override
+ public void undo(VariableDescriptorAwareScoreDirector<Solution_> scoreDirector) {
+ scoreDirector.afterListVariableElementUnassigned(variableDescriptor, element); | ditto |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -0,0 +1,133 @@
+package ai.timefold.solver.core.impl.move.director;
+
+import java.util.Objects;
+
+import ai.timefold.solver.core.api.domain.metamodel.ElementLocation;
+import ai.timefold.solver.core.api.domain.metamodel.PlanningListVariableMetaModel;
+import ai.timefold.solver.core.api.domain.metamodel.PlanningVariableMetaModel;
+import ai.timefold.solver.core.api.move.Rebaser;
+import ai.timefold.solver.core.impl.domain.solution.descriptor.DefaultPlanningListVariableMetaModel;
+import ai.timefold.solver.core.impl.domain.solution.descriptor.DefaultPlanningVariableMetaModel;
+import ai.timefold.solver.core.impl.domain.variable.descriptor.BasicVariableDescriptor;
+import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
+import ai.timefold.solver.core.impl.move.InnerMutableSolutionState;
+import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
+import ai.timefold.solver.core.impl.score.director.VariableDescriptorAwareScoreDirector;
+
+public sealed class MoveDirector<Solution_> | Cool! |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -11,176 +11,145 @@
import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor;
import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableSupply;
import ai.timefold.solver.core.impl.heuristic.selector.SelectorTestUtils;
+import ai.timefold.solver.core.impl.move.director.MoveDirector;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
import ai.timefold.solver.core.impl.testdata.domain.chained.TestdataChainedAnchor;
import ai.timefold.solver.core.impl.testdata.domain.chained.TestdataChainedEntity;
import ai.timefold.solver.core.impl.testdata.domain.chained.TestdataChainedSolution;
import ai.timefold.solver.core.impl.testdata.util.PlannerTestUtils;
import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
class ChainedChangeMoveTest {
+ private final GenuineVariableDescriptor<TestdataChainedSolution> variableDescriptor = TestdataChainedEntity
+ .buildVariableDescriptorForChainedObject();
+ private final InnerScoreDirector<TestdataChainedSolution, SimpleScore> innerScoreDirector =
+ PlannerTestUtils.mockScoreDirector(variableDescriptor.getEntityDescriptor().getSolutionDescriptor());
+
@Test
void noTrailing() {
- GenuineVariableDescriptor<TestdataChainedSolution> variableDescriptor = TestdataChainedEntity
- .buildVariableDescriptorForChainedObject();
- InnerScoreDirector<TestdataChainedSolution, SimpleScore> scoreDirector =
- PlannerTestUtils.mockScoreDirector(variableDescriptor.getEntityDescriptor().getSolutionDescriptor());
-
- TestdataChainedAnchor a0 = new TestdataChainedAnchor("a0");
- TestdataChainedEntity a1 = new TestdataChainedEntity("a1", a0);
- TestdataChainedEntity a2 = new TestdataChainedEntity("a2", a1);
- TestdataChainedEntity a3 = new TestdataChainedEntity("a3", a2);
+ var a0 = new TestdataChainedAnchor("a0");
+ var a1 = new TestdataChainedEntity("a1", a0);
+ var a2 = new TestdataChainedEntity("a2", a1);
+ var a3 = new TestdataChainedEntity("a3", a2);
- TestdataChainedAnchor b0 = new TestdataChainedAnchor("b0");
- TestdataChainedEntity b1 = new TestdataChainedEntity("b1", b0);
+ var b0 = new TestdataChainedAnchor("b0");
+ var b1 = new TestdataChainedEntity("b1", b0);
- SingletonInverseVariableSupply inverseVariableSupply = SelectorTestUtils.mockSingletonInverseVariableSupply(
+ var inverseVariableSupply = SelectorTestUtils.mockSingletonInverseVariableSupply(
new TestdataChainedEntity[] { a1, a2, a3, b1 });
- ChainedChangeMove<TestdataChainedSolution> move =
- new ChainedChangeMove<>(variableDescriptor, a3, b1, inverseVariableSupply);
- assertThat(move.isMoveDoable(scoreDirector)).isTrue();
- ChainedChangeMove<TestdataChainedSolution> undoMove = move.createUndoMove(scoreDirector);
- move.doMove(scoreDirector); | This comment applies to all places where we are removing the undo validation. I understand the move logic has changed, but I am still concerned about removing the undo validation entirely.
I wonder how much effort it would take to use the ephemeral director while maintaining the undo validations. |
timefold-solver | github_2023 | others | 1,107 | TimefoldAI | zepfred | @@ -1842,20 +1842,7 @@ A move that is currently not doable can become doable when the working solution
otherwise we probably shouldn't have created it in the first place.
Each move has an __undo move__: a move (normally of the same type) which does the exact opposite. | Is the phrase "normally of the same type" still applicable? |
timefold-solver | github_2023 | others | 1,107 | TimefoldAI | zepfred | @@ -30,7 +30,23 @@ Those documented `impl` classes are reliable and safe to use (unless explicitly
but we're just not entirely comfortable yet to write their signatures in stone.
====
-[NOTE]
-====
-The Python Solver is currently in beta and its API is subject to change.
-====
\ No newline at end of file
+[#previewFeatures]
+= Preview features
+
+Timefold Solver includes several components which are only available as preview features. | ```suggestion
Timefold Solver may include components that are only available as preview features. Currently available are:
``` |
timefold-solver | github_2023 | java | 1,107 | TimefoldAI | zepfred | @@ -3,22 +3,16 @@
import java.util.Collection;
import java.util.Collections;
-import ai.timefold.solver.core.impl.heuristic.move.Move;
+import ai.timefold.solver.core.api.move.Move;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchMoveScope;
import ai.timefold.solver.core.impl.localsearch.scope.LocalSearchStepScope;
public class MoveTabuAcceptor<Solution_> extends AbstractTabuAcceptor<Solution_> {
- protected boolean useUndoMoveAsTabuMove = true; | Will removing the TS undo moves affect any existing code? |
timefold-solver | github_2023 | others | 1,151 | TimefoldAI | lee-carlon | @@ -0,0 +1,29 @@
+[#introduction]
+:page-aliases: ../index.adoc
+:doctype: book
+:sectnums:
+:icons: font
+
+[#whatIsTimefold]
+= What is Timefold Solver?
+
+Every organization faces planning problems: providing products or services with a limited set of _constrained_ resources (employees, assets, time and money).
+Timefold Solver’s xref:planning-ai-concepts.adoc[PlanningAI] optimizes these problems to do more business with less resources using Constraint Satisfaction Programming. | ```suggestion
Timefold Solver’s xref:planning-ai-concepts.adoc[PlanningAI] optimizes these problems to do more business with fewer resources using Constraint Satisfaction Programming.
```
Minor change: resources are a countable noun so we should use fewer. |
timefold-solver | github_2023 | others | 1,151 | TimefoldAI | lee-carlon | @@ -0,0 +1,29 @@
+[#introduction]
+:page-aliases: ../index.adoc
+:doctype: book
+:sectnums:
+:icons: font
+
+[#whatIsTimefold]
+= What is Timefold Solver?
+
+Every organization faces planning problems: providing products or services with a limited set of _constrained_ resources (employees, assets, time and money). | ```suggestion
Every organization faces planning problems: providing products or services with a limited set of _constrained_ resources (employees, assets, time, and money).
```
US English generally prefers the serial comma :) |
timefold-solver | github_2023 | others | 1,151 | TimefoldAI | lee-carlon | @@ -0,0 +1,29 @@
+[#introduction]
+:page-aliases: ../index.adoc
+:doctype: book
+:sectnums:
+:icons: font
+
+[#whatIsTimefold]
+= What is Timefold Solver?
+
+Every organization faces planning problems: providing products or services with a limited set of _constrained_ resources (employees, assets, time and money).
+Timefold Solver’s xref:planning-ai-concepts.adoc[PlanningAI] optimizes these problems to do more business with less resources using Constraint Satisfaction Programming.
+
+> Want to dive right into it? Follow our xref:quickstart/overview.adoc[Quickstart Example] to tackle your first planning problem in minutes.
+
+https://timefold.ai[Timefold Solver] is a lightweight, embeddable constraint satisfaction engine which optimizes planning problems.
+Example usecases include:
+
+image::introduction/useCaseOverview.png[align="center"]
+
+Timefold Solver is 100% pure Java^TM^ and runs on Java {java-version} or higher.
+It xref:integration/integration.adoc#integration[integrates very easily] with other Java^TM^, Python and other technologies. | ```suggestion
It xref:integration/integration.adoc#integration[integrates very easily] with other Java^TM^, Python, and other technologies.
``` |
timefold-solver | github_2023 | others | 1,151 | TimefoldAI | triceo | @@ -1,287 +0,0 @@
-[#introduction]
-= Introduction
-:page-aliases: ../index.adoc
-:doctype: book
-:sectnums:
-:icons: font
-
-[#whatIsTimefold]
-== What is Timefold Solver?
-
-Every organization faces planning problems: providing products or services with a limited set of _constrained_ resources (employees, assets, time and money).
-Timefold Solver's <<planningAI,Planning AI>> optimizes these problems to do more business with less resources using _Constraint Satisfaction Programming_, which is part of the _<<operationsResearch,Operations Research>>_ discipline.
-
-https://timefold.ai[Timefold Solver] is a lightweight, embeddable constraint satisfaction engine which optimizes planning problems.
-It solves use cases such as:
-
-* **Employee shift rostering**: timetabling nurses, repairmen, ...
-* **Agenda scheduling**: scheduling meetings, appointments, maintenance jobs, advertisements, ...
-* **Educational timetabling**: scheduling lessons, courses, exams, conference presentations, ...
-* **Vehicle routing**: planning vehicle routes (trucks, trains, boats, airplanes, ...) for moving freight and/or passengers through multiple destinations using known mapping tools ...
-* **Bin packing**: filling containers, trucks, ships, and storage warehouses with items, but also packing information across computer resources, as in cloud computing ...
-* **Job shop scheduling**: planning car assembly lines, machine queue planning, workforce task planning, ...
-* **Cutting stock**: minimizing waste while cutting paper, steel, carpet, ...
-* **Sport scheduling**: planning games and training schedules for football leagues, baseball leagues, ...
-* **Financial optimization**: investment portfolio optimization, risk spreading, ...
-
-image::introduction/useCaseOverview.png[align="center"]
-
-[#whatIsAPlanningProblem]
-== Planning
-
-The need to create plans generally arises from a desire to achieve a *goal*:
-
-* Build a house.
-* Correctly staff a hospital shift.
-* Complete work at all customer locations.
-
-Achieving those goals involves organizing the available *resources*.
-To correctly staff a hospital you need enough qualified personnel in a variety of fields and specializations to cover the opening hours of the hospital.
-
-Any plan to deploy resources, whether to staff a hospital shift or to assemble the building materials for a new house, is done under *constraints*.
-
-Constraints could be laws of the universe; people can't work two shifts in two separate locations at the same time,
-and you can't mount a roof on a house that doesn't exist.
-Constraints can also be relevant legislation; employees need a certain number of hours between shifts or are only allowed to work a maximum number of hours per week.
-Employee preferences can also be considered constraints, such as, certain employees prefer to work specific shift patterns.
-
-[#feasiblePlans]
-=== Feasible plans
-
-Any plan needs to consider all three elements, goals, resources, and constraints, in balance to be a feasible plan.
-A plan that fails to account for all the elements of the problem is an infeasible plan.
-For instance, if a hospital staff roster covers all shifts, but assigns employees back-to-back shifts with no breaks for sleep or life outside work,
-it is not a valid plan.
-
-=== Planning problems are hard to solve
-
-Planning problems become harder to solve as the number of resources and constraints increase.
-Creating an employee shift schedule for a small team of four employees is fairly straightforward.
-However, if each employee performs a specific function within the business and those functions need to be performed in a specific order,
-changes that affect one employee quickly cascade and affect everybody on the team.
-If parts are delivered late and prevent one employee from completing their tasks, subsequent work will also be delayed.
-
-As more employees and different work specializations are added, things become much more complicated.
-
-For a trivial field service routing problem with 4 vehicles and 8 visits, the number of possibilities that a brute algorithm considers is 19,958,418.
-
-What would take a team of planners many hours to schedule can be automatically scheduled by Timefold Solver in a fraction of the time.
-
-[#operationsResearch]
-==== Operations Research
-
-Operations Research (OR) is a field of research that is focused on finding optimal (or near optimal) solutions to problems with techniques that improve decision-making.
-
-Constraint satisfaction programming is part of Operations Research that aims to satisfy all the constraints of a problem.
-
-[#planningAI]
-=== Planning AI
-
-Planning AI is a type of artificial intelligence designed specifically to handle complex planning and scheduling tasks, and to satisfy the constraints of planning problems.
-Instead of just automating simple, repetitive tasks, it helps you make better decisions by sorting through countless possibilities to find the best solutions—saving you time, reducing costs, and improving efficiency.
-
-==== Why Planning AI is different
-Traditional methods of planning often involve manually sifting through options or relying on basic tools that can’t keep up with the complexity of real-world problems.
-Planning AI, on the other hand, uses advanced strategies to quickly focus on the most promising solutions, even when the situation is extremely complicated.
-Planning AI also makes it possible to understand the final solution with a breakdown of which constraints have been violated and scores for individual constraints and an overall score.
-This makes Planning AI incredibly valuable in industries where getting the right plan is crucial—whether that’s scheduling workers, routing deliveries, or managing resources in a factory.
-
-Planning AI is designed to be accessible, so you can start improving your planning process right away.
-
-[#aPlanningProblemHasConstraints]
-=== Constraints
-
-Constraints can be considered hard, medium, or soft.
-
-Hard constraints represent rules and limitations of the real world that any planning solution has to respect.
-For instance, there are only 24 hours in a day and people can only be in one place at a time.
-Hard constraints also include rules that must be adhered to, for instance, employee contracts and the order in which dependent tasks are completed.
-
-Breaking hard constraints would result in infeasible plans.
-
-Medium constraints help manage plans when resources are limited, (for instance, when there aren't enough technicians to complete all the customer visits or there aren't enough employees to work all the available shifts).
-Medium constraints incentivize Timefold Platform to assign as many entities (visits or shifts) as possible.
-
-Soft constraints help optimize plans based on the business goals, for instance, minimize travel time between customer visits or assign employees to their preferred shifts.
-
-To help determine the quality of the solution, plans are assigned a score with values for hard, medium, and soft constraints.
-
-`"0hard/-257medium/-6119520soft"`
-
-From this example score we can see zero hard constraints were broken, while both the medium and soft scores have negative values (the scores do not show how many constraints were broken, but values associated with those constraints).
-
-Because breaking hard constraints would result in an infeasible solution,
-a solution that breaks zero hard constraints and has a soft constraint score of -1,000,000 is better
-than a solution that breaks one hard constraint and has a soft constraint score of 0.
-
-The weight of constraints can be tweaked to adjust their impact on the solution.
-
-[#timefoldSolverStatus]
-== Status of Timefold Solver
-
-Timefold Solver is 100% pure Java^TM^ and runs on Java {java-version} or higher.
-It xref:integration/integration.adoc#integration[integrates very easily] with other Java^TM^, Python and other technologies.
-Timefold Solver works on any Java Virtual Machine and is compatible with the major JVM languages and all major platforms.
-It also supports Kotlin and Python.
-
-image::introduction/compatibility.png[align="center"]
-
-Timefold Solver is stable, reliable and scalable.
-It has been heavily tested with unit, integration, and stress tests, and is used in production throughout the world.
-One example handles over 50 000 variables with 5000 values each, multiple constraint types and billions of possible constraint matches.
-
-We offer two editions of Timefold Solver.
-
-[#communityEdition]
-=== Timefold Solver Community Edition
-
-Timefold Solver Community Edition is _open source_ software,
-released under http://www.apache.org/licenses/LICENSE-2.0.html[the Apache License 2.0].
-This license is very liberal and allows reuse for commercial purposes.
-Read http://www.apache.org/foundation/licence-FAQ.html#WhatDoesItMEAN[the layman's explanation].
-
-Timefold Solver Community Edition is available in <<useWithMavenGradleEtc,the Maven Central Repository>>.
-It is and will always be free.
-The overwhelming majority of solver features will always be available in the Community Edition.
-Most users will be able to solve their planning problems with the Community Edition.
-
-[#enterpriseEdition]
-=== Timefold Solver Enterprise Edition
-
-Timefold Solver Enterprise Edition is a commercial product
-that offers xref:enterprise-edition/enterprise-edition.adoc#enterpriseEditionFeatures[additional features]
-to scale out to very large datasets.
-To find out more, see xref:enterprise-edition/enterprise-edition.adoc[Enterprise Edition section] of this documentation.
-
-[#backwardsCompatibility]
-== Backwards compatibility | It this gone now? |
timefold-solver | github_2023 | others | 1,151 | TimefoldAI | triceo | @@ -1,287 +0,0 @@
-[#introduction]
-= Introduction
-:page-aliases: ../index.adoc
-:doctype: book
-:sectnums:
-:icons: font
-
-[#whatIsTimefold]
-== What is Timefold Solver?
-
-Every organization faces planning problems: providing products or services with a limited set of _constrained_ resources (employees, assets, time and money).
-Timefold Solver's <<planningAI,Planning AI>> optimizes these problems to do more business with less resources using _Constraint Satisfaction Programming_, which is part of the _<<operationsResearch,Operations Research>>_ discipline.
-
-https://timefold.ai[Timefold Solver] is a lightweight, embeddable constraint satisfaction engine which optimizes planning problems.
-It solves use cases such as: | The PR description mentions that this will be re-introduced as an image.
In my opinion, information should not be presented exclusively as images - text is important. For discoverability and accessibility, among other reasons. |
timefold-solver | github_2023 | java | 1,136 | TimefoldAI | zepfred | @@ -137,10 +137,122 @@ default ScoreAnalysis<Score_> analyze(Solution_ solution, ScoreAnalysisFetchPoli
ScoreAnalysis<Score_> analyze(Solution_ solution, ScoreAnalysisFetchPolicy fetchPolicy,
SolutionUpdatePolicy solutionUpdatePolicy);
+ /**
+ * As defined by {@link #recommendAssignment(Object, Object, Function, ScoreAnalysisFetchPolicy)},
+ * with {@link ScoreAnalysisFetchPolicy#FETCH_ALL}.
+ */
+ default <EntityOrElement_, Proposition_> List<RecommendedAssignment<Proposition_, Score_>> recommendAssignment(
+ Solution_ solution, EntityOrElement_ evaluatedEntityOrElement,
+ Function<EntityOrElement_, Proposition_> propositionFunction) {
+ return recommendAssignment(solution, evaluatedEntityOrElement, propositionFunction, FETCH_ALL);
+ }
+
+ /** | Very informative! |
timefold-solver | github_2023 | java | 1,136 | TimefoldAI | zepfred | @@ -137,10 +137,122 @@ default ScoreAnalysis<Score_> analyze(Solution_ solution, ScoreAnalysisFetchPoli
ScoreAnalysis<Score_> analyze(Solution_ solution, ScoreAnalysisFetchPolicy fetchPolicy,
SolutionUpdatePolicy solutionUpdatePolicy);
+ /**
+ * As defined by {@link #recommendAssignment(Object, Object, Function, ScoreAnalysisFetchPolicy)},
+ * with {@link ScoreAnalysisFetchPolicy#FETCH_ALL}.
+ */
+ default <EntityOrElement_, Proposition_> List<RecommendedAssignment<Proposition_, Score_>> recommendAssignment(
+ Solution_ solution, EntityOrElement_ evaluatedEntityOrElement,
+ Function<EntityOrElement_, Proposition_> propositionFunction) {
+ return recommendAssignment(solution, evaluatedEntityOrElement, propositionFunction, FETCH_ALL);
+ }
+
+ /**
+ * Quickly runs through all possible options of assigning a given entity or element in a given solution,
+ * and returns a list of recommendations sorted by score,
+ * with most favorable score first.
+ * The input solution must either be fully initialized,
+ * or have a single entity or element unassigned.
+ *
+ * <p>
+ * For problems with only basic planning variables or with chained planning variables,
+ * the fitted element is a planning entity of the problem.
+ * Each available planning value will be tested by setting it to the planning variable in question.
+ * For problems with a list variable,
+ * the evaluated element may be a shadow entity,
+ * and it will be tested in each position of the planning list variable.
+ *
+ * <p>
+ * The score returned by {@link RecommendedAssignment#scoreAnalysisDiff()}
+ * is the difference between the score of the solution before and after fitting.
+ * Every recommendation will be in a state as if the solution was never changed;
+ * if it references entities,
+ * none of their genuine planning variables or shadow planning variables will be initialized.
+ * The input solution will be unchanged.
+ *
+ * <p>
+ * This method does not call local search,
+ * it runs a fast greedy algorithm instead.
+ * The construction heuristic configuration from the solver configuration is used.
+ * If not present, the default construction heuristic configuration is used.
+ * This means that the API will fail if the solver config requires custom initialization phase.
+ * In this case, it will fail either directly by throwing an exception,
+ * or indirectly by not providing correct data.
+ *
+ * <p>
+ * When an element is tested,
+ * a score is calculated over the entire solution with the element in place,
+ * also called a placement.
+ * The proposition function is also called at that time,
+ * allowing the user to extract any information from the current placement;
+ * the extracted information is called the proposition.
+ * After the proposition is extracted,
+ * the solution is returned to its original state,
+ * resetting all changes made by the fitting.
+ * This has a major consequence for the proposition, if it is a planning entity:
+ * planning entities contain live data in their planning variables,
+ * and that data will be erased when the next placement is tested for fit.
+ * In this case,
+ * the proposition function needs to make defensive copies of everything it wants to return,
+ * such as values of shadow variables etc.
+ *
+ * <p>
+ * Example: Consider a planning entity Shift, with a variable "employee".
+ * Let's assume we have two employees to test for fit, Ann and Bob,
+ * and a single Shift instance to fit them into, {@code mondayShift}.
+ * The proposition function will be called twice,
+ * once as {@code mondayShift@Ann} and once as {@code mondayShift@Bob}.
+ * Let's assume the proposition function returns the Shift instance in its entirety.
+ * This is what will happen:
+ *
+ * <ol>
+ * <li>Calling propositionFunction on {@code mondayShift@Ann} results in proposition P1: {@code mondayShift@Ann}</li>
+ * <li>Placement is cleared, {@code mondayShift@Bob} is now tested for fit.</li>
+ * <li>Calling propositionFunction on {@code mondayShift@Bob} results in proposition P2: {@code mondayShift@Bob}</li>
+ * <li>Proposition P1 and P2 are now both the same {@code mondayShift},
+ * which means Bob is now assigned to both of them.
+ * This is because both propositions operate on the same entity,
+ * and therefore share the same state.
+ * </li>
+ * <li>The placement is then cleared again,
+ * both elements have been tested,
+ * and solution is returned to its original order.
+ * The propositions are then returned to the user,
+ * who notices that both P1 and P2 are {@code mondayShift@null}.
+ * This is because they shared state,
+ * and the original state of the solution was for Shift to be unassigned.
+ * </li>
+ * </ol>
+ *
+ * If instead the proposition function returned Ann and Bob directly, the immutable planning variables,
+ * this problem would have been avoided.
+ * Alternatively, the proposition function could have returned a defensive copy of the Shift.
+ *
+ * @param solution never null; must be fully initialized except for one entity or element | This param explanation is unclear to me. Can we explicitly state the difference between an initialized and uninitialized solution? |
timefold-solver | github_2023 | java | 1,136 | TimefoldAI | zepfred | @@ -5,45 +5,47 @@
import java.util.function.Function;
import ai.timefold.solver.core.api.score.Score;
-import ai.timefold.solver.core.api.solver.RecommendedFit;
import ai.timefold.solver.core.api.solver.ScoreAnalysisFetchPolicy;
import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
-final class Fitter<Solution_, In_, Out_, Score_ extends Score<Score_>>
- implements Function<InnerScoreDirector<Solution_, Score_>, List<RecommendedFit<Out_, Score_>>> {
+final class Assigner<Solution_, Score_ extends Score<Score_>, Recommendation_, In_, Out_>
+ implements Function<InnerScoreDirector<Solution_, Score_>, List<Recommendation_>> {
private final DefaultSolverFactory<Solution_> solverFactory;
- private final Solution_ originalSolution;
- private final In_ originalElement;
private final Function<In_, Out_> propositionFunction;
+ private final RecommendationConstructor<Score_, Recommendation_, Out_> recommendationConstructor;
private final ScoreAnalysisFetchPolicy fetchPolicy;
+ private final Solution_ originalSolution;
+ private final In_ originalElement;
- public Fitter(DefaultSolverFactory<Solution_> solverFactory, Solution_ originalSolution, In_ originalElement,
- Function<In_, Out_> propositionFunction, ScoreAnalysisFetchPolicy fetchPolicy) {
+ public Assigner(DefaultSolverFactory<Solution_> solverFactory, Function<In_, Out_> propositionFunction,
+ RecommendationConstructor<Score_, Recommendation_, Out_> recommendationConstructor,
+ ScoreAnalysisFetchPolicy fetchPolicy, Solution_ originalSolution, In_ originalElement) {
this.solverFactory = Objects.requireNonNull(solverFactory);
- this.originalSolution = Objects.requireNonNull(originalSolution);
- this.originalElement = Objects.requireNonNull(originalElement);
this.propositionFunction = Objects.requireNonNull(propositionFunction);
+ this.recommendationConstructor = Objects.requireNonNull(recommendationConstructor);
this.fetchPolicy = Objects.requireNonNull(fetchPolicy);
+ this.originalSolution = Objects.requireNonNull(originalSolution);
+ this.originalElement = Objects.requireNonNull(originalElement);
}
@Override
- public List<RecommendedFit<Out_, Score_>> apply(InnerScoreDirector<Solution_, Score_> scoreDirector) {
+ public List<Recommendation_> apply(InnerScoreDirector<Solution_, Score_> scoreDirector) {
var solutionDescriptor = scoreDirector.getSolutionDescriptor();
var initializationStatistics = solutionDescriptor.computeInitializationStatistics(originalSolution);
var uninitializedCount =
initializationStatistics.uninitializedEntityCount() + initializationStatistics.unassignedValueCount();
if (uninitializedCount > 1) {
throw new IllegalStateException("""
Solution (%s) has (%d) uninitialized elements.
- Fit Recommendation API requires at most one uninitialized element in the solution."""
+ Assignment Recommendation API requires at most one uninitialized element in the solution.""" | Should we also mention the fully initialized solution? |
timefold-solver | github_2023 | java | 1,136 | TimefoldAI | zepfred | @@ -0,0 +1,158 @@
+package ai.timefold.solver.core.impl.solver;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+import java.util.Random;
+import java.util.function.Function;
+
+import ai.timefold.solver.core.api.score.Score;
+import ai.timefold.solver.core.api.score.analysis.ScoreAnalysis;
+import ai.timefold.solver.core.api.solver.ScoreAnalysisFetchPolicy;
+import ai.timefold.solver.core.impl.constructionheuristic.DefaultConstructionHeuristicPhase;
+import ai.timefold.solver.core.impl.constructionheuristic.placer.EntityPlacer;
+import ai.timefold.solver.core.impl.constructionheuristic.scope.ConstructionHeuristicPhaseScope;
+import ai.timefold.solver.core.impl.constructionheuristic.scope.ConstructionHeuristicStepScope;
+import ai.timefold.solver.core.impl.domain.variable.descriptor.BasicVariableDescriptor;
+import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableDemand;
+import ai.timefold.solver.core.impl.heuristic.move.Move;
+import ai.timefold.solver.core.impl.heuristic.selector.list.LocationInList;
+import ai.timefold.solver.core.impl.heuristic.selector.move.generic.ChangeMove;
+import ai.timefold.solver.core.impl.heuristic.selector.move.generic.chained.ChainedChangeMove;
+import ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.ListUnassignMove;
+import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
+import ai.timefold.solver.core.impl.solver.scope.SolverScope;
+
+final class AssignmentProcessor<Solution_, Score_ extends Score<Score_>, Recommendation_, In_, Out_>
+ implements Function<InnerScoreDirector<Solution_, Score_>, List<Recommendation_>> {
+
+ private final DefaultSolverFactory<Solution_> solverFactory;
+ private final Function<In_, Out_> valueResultFunction;
+ private final RecommendationConstructor<Score_, Recommendation_, Out_> recommendationConstructor;
+ private final ScoreAnalysisFetchPolicy fetchPolicy;
+ private final ScoreAnalysis<Score_> originalScoreAnalysis;
+ private final In_ clonedElement;
+
+ public AssignmentProcessor(DefaultSolverFactory<Solution_> solverFactory, Function<In_, Out_> valueResultFunction,
+ RecommendationConstructor<Score_, Recommendation_, Out_> recommendationConstructor,
+ ScoreAnalysisFetchPolicy fetchPolicy, In_ clonedElement, ScoreAnalysis<Score_> originalScoreAnalysis) {
+ this.solverFactory = Objects.requireNonNull(solverFactory);
+ this.valueResultFunction = valueResultFunction;
+ this.recommendationConstructor = Objects.requireNonNull(recommendationConstructor);
+ this.fetchPolicy = Objects.requireNonNull(fetchPolicy);
+ this.originalScoreAnalysis = Objects.requireNonNull(originalScoreAnalysis);
+ this.clonedElement = clonedElement;
+ }
+
+ @Override
+ public List<Recommendation_> apply(InnerScoreDirector<Solution_, Score_> scoreDirector) {
+ // The cloned element may already be assigned.
+ // If it is, we need to unassign it before we can run the construction heuristic.
+ var supplyManager = scoreDirector.getSupplyManager();
+ var solutionDescriptor = solverFactory.getSolutionDescriptor();
+ var listVariableDescriptor = solutionDescriptor.getListVariableDescriptor();
+ if (listVariableDescriptor != null) { | I'm worried that this action will not be undone. We can unassign the element, but I can't find the corresponding undo action. Could this lead to an inconsistent state? |
timefold-solver | github_2023 | java | 1,136 | TimefoldAI | zepfred | @@ -0,0 +1,158 @@
+package ai.timefold.solver.core.impl.solver;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+import java.util.Random;
+import java.util.function.Function;
+
+import ai.timefold.solver.core.api.score.Score;
+import ai.timefold.solver.core.api.score.analysis.ScoreAnalysis;
+import ai.timefold.solver.core.api.solver.ScoreAnalysisFetchPolicy;
+import ai.timefold.solver.core.impl.constructionheuristic.DefaultConstructionHeuristicPhase;
+import ai.timefold.solver.core.impl.constructionheuristic.placer.EntityPlacer;
+import ai.timefold.solver.core.impl.constructionheuristic.scope.ConstructionHeuristicPhaseScope;
+import ai.timefold.solver.core.impl.constructionheuristic.scope.ConstructionHeuristicStepScope;
+import ai.timefold.solver.core.impl.domain.variable.descriptor.BasicVariableDescriptor;
+import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableDemand;
+import ai.timefold.solver.core.impl.heuristic.move.Move;
+import ai.timefold.solver.core.impl.heuristic.selector.list.LocationInList;
+import ai.timefold.solver.core.impl.heuristic.selector.move.generic.ChangeMove;
+import ai.timefold.solver.core.impl.heuristic.selector.move.generic.chained.ChainedChangeMove;
+import ai.timefold.solver.core.impl.heuristic.selector.move.generic.list.ListUnassignMove;
+import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
+import ai.timefold.solver.core.impl.solver.scope.SolverScope;
+
+final class AssignmentProcessor<Solution_, Score_ extends Score<Score_>, Recommendation_, In_, Out_>
+ implements Function<InnerScoreDirector<Solution_, Score_>, List<Recommendation_>> {
+
+ private final DefaultSolverFactory<Solution_> solverFactory;
+ private final Function<In_, Out_> valueResultFunction;
+ private final RecommendationConstructor<Score_, Recommendation_, Out_> recommendationConstructor;
+ private final ScoreAnalysisFetchPolicy fetchPolicy;
+ private final ScoreAnalysis<Score_> originalScoreAnalysis;
+ private final In_ clonedElement;
+
+ public AssignmentProcessor(DefaultSolverFactory<Solution_> solverFactory, Function<In_, Out_> valueResultFunction,
+ RecommendationConstructor<Score_, Recommendation_, Out_> recommendationConstructor,
+ ScoreAnalysisFetchPolicy fetchPolicy, In_ clonedElement, ScoreAnalysis<Score_> originalScoreAnalysis) {
+ this.solverFactory = Objects.requireNonNull(solverFactory);
+ this.valueResultFunction = valueResultFunction;
+ this.recommendationConstructor = Objects.requireNonNull(recommendationConstructor);
+ this.fetchPolicy = Objects.requireNonNull(fetchPolicy);
+ this.originalScoreAnalysis = Objects.requireNonNull(originalScoreAnalysis);
+ this.clonedElement = clonedElement;
+ }
+
+ @Override
+ public List<Recommendation_> apply(InnerScoreDirector<Solution_, Score_> scoreDirector) {
+ // The cloned element may already be assigned.
+ // If it is, we need to unassign it before we can run the construction heuristic.
+ var supplyManager = scoreDirector.getSupplyManager();
+ var solutionDescriptor = solverFactory.getSolutionDescriptor();
+ var listVariableDescriptor = solutionDescriptor.getListVariableDescriptor();
+ if (listVariableDescriptor != null) {
+ var demand = listVariableDescriptor.getStateDemand();
+ var listVariableStateSupply = supplyManager.demand(demand);
+ var elementLocation = listVariableStateSupply.getLocationInList(clonedElement);
+ if (elementLocation instanceof LocationInList locationInList) { // Unassign the cloned element.
+ var entity = locationInList.entity();
+ var index = locationInList.index();
+ var listUnassignMove = new ListUnassignMove<>(listVariableDescriptor, entity, index);
+ listUnassignMove.doMove(scoreDirector);
+ }
+ supplyManager.cancel(demand);
+ } else {
+ var entityDescriptor = solutionDescriptor.findEntityDescriptorOrFail(clonedElement.getClass());
+ for (var variableDescriptor : entityDescriptor.getGenuineVariableDescriptorList()) {
+ var basicVariableDescriptor = (BasicVariableDescriptor<Solution_>) variableDescriptor;
+ if (basicVariableDescriptor.getValue(clonedElement) == null) {
+ // The variable is already unassigned.
+ continue;
+ }
+ // Uninitialize the basic variable.
+ if (basicVariableDescriptor.isChained()) {
+ var demand = new SingletonInverseVariableDemand<>(basicVariableDescriptor);
+ var supply = supplyManager.demand(demand);
+ var move = new ChainedChangeMove<>(basicVariableDescriptor, clonedElement, null, supply);
+ move.doMove(scoreDirector);
+ supplyManager.cancel(demand);
+ } else {
+ var move = new ChangeMove<>(basicVariableDescriptor, clonedElement, null);
+ move.doMove(scoreDirector);
+ }
+ }
+ }
+ scoreDirector.triggerVariableListeners();
+
+ // The placers needs to be filtered.
+ // If anything else than the cloned element is unassigned, we want to keep it unassigned.
+ // Otherwise the solution would have to explicitly pin everything other than the cloned element.
+ var entityPlacer = buildEntityPlacer()
+ .rebuildWithFilter((solution, selection) -> selection == clonedElement);
+
+ var solverScope = new SolverScope<Solution_>();
+ solverScope.setWorkingRandom(new Random(0)); // We will evaluate every option; random does not matter.
+ solverScope.setScoreDirector(scoreDirector);
+ var phaseScope = new ConstructionHeuristicPhaseScope<>(solverScope, -1);
+ var stepScope = new ConstructionHeuristicStepScope<>(phaseScope);
+ entityPlacer.solvingStarted(solverScope);
+ entityPlacer.phaseStarted(phaseScope);
+ entityPlacer.stepStarted(stepScope);
+
+ try (scoreDirector) {
+ var placementIterator = entityPlacer.iterator();
+ if (!placementIterator.hasNext()) {
+ throw new IllegalStateException("""
+ Impossible state: entity placer (%s) has no placements.
+ """.formatted(entityPlacer));
+ }
+ var placement = placementIterator.next();
+ var recommendedAssignmentList = new ArrayList<Recommendation_>();
+ var moveIndex = 0L;
+ for (var move : placement) {
+ recommendedAssignmentList.add(execute(scoreDirector, move, moveIndex, clonedElement, valueResultFunction));
+ moveIndex++;
+ }
+ recommendedAssignmentList.sort(null);
+ return recommendedAssignmentList;
+ } finally {
+ entityPlacer.stepEnded(stepScope);
+ entityPlacer.phaseEnded(phaseScope);
+ entityPlacer.solvingEnded(solverScope);
+ }
+ }
+
+ private EntityPlacer<Solution_> buildEntityPlacer() {
+ var solver = (DefaultSolver<Solution_>) solverFactory.buildSolver();
+ var phaseList = solver.getPhaseList();
+ var constructionHeuristicCount = phaseList.stream()
+ .filter(DefaultConstructionHeuristicPhase.class::isInstance)
+ .count();
+ if (constructionHeuristicCount != 1) {
+ throw new IllegalStateException(
+ "Assignment Recommendation API requires the solver config to have exactly one construction heuristic phase, but it has (%s) instead."
+ .formatted(constructionHeuristicCount));
+ }
+ var phase = phaseList.get(0);
+ if (phase instanceof DefaultConstructionHeuristicPhase<Solution_> constructionHeuristicPhase) {
+ return constructionHeuristicPhase.getEntityPlacer();
+ } else {
+ throw new IllegalStateException(
+ "Assignment Recommendation API requires the first solver phase (%s) in the solver config to be a construction heuristic."
+ .formatted(phase));
+ }
+ }
+
+ private Recommendation_ execute(InnerScoreDirector<Solution_, Score_> scoreDirector, Move<Solution_> move, long moveIndex,
+ In_ clonedElement, Function<In_, Out_> propositionFunction) {
+ var undo = move.doMove(scoreDirector);
+ var newScoreAnalysis = scoreDirector.buildScoreAnalysis(fetchPolicy == ScoreAnalysisFetchPolicy.FETCH_ALL);
+ var newScoreDifference = newScoreAnalysis.diff(originalScoreAnalysis);
+ var result = propositionFunction.apply(clonedElement);
+ var recommendation = recommendationConstructor.apply(moveIndex, result, newScoreDifference); | I understand what the logic is doing here and have some questions:
1. Wouldn't this create a capturing lambda?
2. We will return `DefaultRecommendedAssignment` or `DefaultRecommendedFit`. What is the advantage of using the lambda instead of just instantiating the default implementations? |
timefold-solver | github_2023 | java | 1,136 | TimefoldAI | zepfred | @@ -338,7 +338,7 @@ void analyzeWithUninitializedSolution(SolutionManagerSource SolutionManagerSourc
@ParameterizedTest
@EnumSource(SolutionManagerSource.class)
- void recommendFit(SolutionManagerSource SolutionManagerSource) {
+ void recommendAssignment(SolutionManagerSource SolutionManagerSource) { | Maybe we should create a separate test for that. Even though `recommendFit` is deprecated now, we still should test it to ensure no regressions are introduced. |
timefold-solver | github_2023 | java | 1,136 | TimefoldAI | zepfred | @@ -386,22 +387,71 @@ void recommendFit(SolutionManagerSource SolutionManagerSource) {
@ParameterizedTest
@EnumSource(SolutionManagerSource.class)
- void recommendFitUninitializedSolution(SolutionManagerSource SolutionManagerSource) {
+ void recommendAssignmentAlreadyAssigned(SolutionManagerSource SolutionManagerSource) {
+ int valueSize = 3;
+ var solution = TestdataShadowedSolution.generateSolution(valueSize, 3);
+ var evaluatedEntity = solution.getEntityList().get(2);
+ var value = evaluatedEntity.getValue();
+ evaluatedEntity.setValue(value);
+
+ var solutionManager = SolutionManagerSource.createSolutionManager(SOLVER_FACTORY_SHADOWED);
+ assertThat(solutionManager).isNotNull();
+ var recommendationList =
+ solutionManager.recommendAssignment(solution, evaluatedEntity, TestdataShadowedEntity::getValue);
+
+ // Three values means there need to be three recommendations.
+ assertThat(recommendationList).hasSize(valueSize);
+ /*
+ * The calculator counts how many entities have the same value as another entity.
+ * Therefore the recommendation to assign value #2 needs to come first,
+ * as it means the solution is practically unchanged.
+ */
+ var firstRecommendation = recommendationList.get(0);
+ assertSoftly(softly -> {
+ softly.assertThat(firstRecommendation.proposition()).isEqualTo(value);
+ softly.assertThat(firstRecommendation.scoreAnalysisDiff()
+ .score()).isEqualTo(SimpleScore.of(0));
+ });
+ // The other two recommendations need to come in order of the placer; so value #0, then value #1.
+ var secondRecommendation = recommendationList.get(1);
+ assertSoftly(softly -> {
+ softly.assertThat(secondRecommendation.proposition()).isEqualTo(solution.getValueList().get(0));
+ softly.assertThat(secondRecommendation.scoreAnalysisDiff()
+ .score()).isEqualTo(SimpleScore.of(-2));
+ });
+ var thirdRecommendation = recommendationList.get(2);
+ assertSoftly(softly -> {
+ softly.assertThat(thirdRecommendation.proposition()).isEqualTo(solution.getValueList().get(1));
+ softly.assertThat(thirdRecommendation.scoreAnalysisDiff()
+ .score()).isEqualTo(SimpleScore.of(-2));
+ });
+ // Ensure the original solution is in its original state.
+ assertSoftly(softly -> {
+ softly.assertThat(evaluatedEntity.getValue()).isEqualTo(value);
+ softly.assertThat(solution.getEntityList().get(0).getValue()).isEqualTo(solution.getValueList().get(0));
+ softly.assertThat(solution.getEntityList().get(1).getValue()).isEqualTo(solution.getValueList().get(1));
+ softly.assertThat(solution.getScore()).isNull();
+ });
+ }
+
+ @ParameterizedTest
+ @EnumSource(SolutionManagerSource.class)
+ void recommendAssignmentUninitializedSolution(SolutionManagerSource SolutionManagerSource) {
int valueSize = 3;
var uninitializedSolution = TestdataShadowedSolution.generateSolution(valueSize, 3);
uninitializedSolution.getEntityList().forEach(e -> e.setValue(null));
var uninitializedEntity = uninitializedSolution.getEntityList().get(2);
var solutionManager = SolutionManagerSource.createSolutionManager(SOLVER_FACTORY_SHADOWED);
assertThat(solutionManager).isNotNull();
- assertThatThrownBy(() -> solutionManager.recommendFit(uninitializedSolution, uninitializedEntity,
+ assertThatThrownBy(() -> solutionManager.recommendAssignment(uninitializedSolution, uninitializedEntity,
TestdataShadowedEntity::getValue))
.hasMessageContaining("Solution (Generated Solution 0) has (3) uninitialized elements.");
}
@ParameterizedTest
@EnumSource(SolutionManagerSource.class)
- void recommendFitWithUnassigned(SolutionManagerSource SolutionManagerSource) {
+ void recommendAssignmentWithUnassigned(SolutionManagerSource SolutionManagerSource) { | ditto |
timefold-solver | github_2023 | java | 1,136 | TimefoldAI | zepfred | @@ -475,7 +581,7 @@ void recommendFitUninitializedSolutionWithUnassigned(SolutionManagerSource Solut
@ParameterizedTest
@EnumSource(SolutionManagerSource.class)
- void recommendFitMultivar(SolutionManagerSource SolutionManagerSource) {
+ void recommendAssignmentMultivar(SolutionManagerSource SolutionManagerSource) { | ditto |
timefold-solver | github_2023 | java | 1,136 | TimefoldAI | zepfred | @@ -578,7 +778,7 @@ void recommendFitUninitializedSolutionWithMultivar(SolutionManagerSource Solutio
solution.setMultiVarEntityList(List.of(uninitializedEntity, secondUninitializedEntity));
var solutionManager = SolutionManagerSource.createSolutionManager(SOLVER_FACTORY_MULTIVAR);
- assertThatThrownBy(() -> solutionManager.recommendFit(solution, uninitializedEntity,
+ assertThatThrownBy(() -> solutionManager.recommendAssignment(solution, uninitializedEntity, | ditto |
timefold-solver | github_2023 | java | 1,136 | TimefoldAI | zepfred | @@ -604,7 +804,8 @@ void recommendFitChained(SolutionManagerSource SolutionManagerSource) {
var solutionManager = SolutionManagerSource.createSolutionManager(SOLVER_FACTORY_CHAINED);
var recommendationList =
- solutionManager.recommendFit(solution, uninitializedEntity, TestdataShadowingChainedEntity::getChainedObject);
+ solutionManager.recommendAssignment(solution, uninitializedEntity, | ditto |
timefold-solver | github_2023 | java | 1,136 | TimefoldAI | zepfred | @@ -672,14 +940,14 @@ void recommendFitTwoUninitializedEntityWithChained(SolutionManagerSource Solutio
uninitializedSolution.setChainedEntityList(Arrays.asList(b1, c1, c2, uninitializedEntity, uninitializedEntity2));
var solutionManager = SolutionManagerSource.createSolutionManager(SOLVER_FACTORY_CHAINED);
- assertThatThrownBy(() -> solutionManager.recommendFit(uninitializedSolution, uninitializedEntity,
+ assertThatThrownBy(() -> solutionManager.recommendAssignment(uninitializedSolution, uninitializedEntity, | The suggestion to continue testing the `recommendFit` test applies to all instances where we are changing it to `recommendAssignment`. |
timefold-solver | github_2023 | java | 1,136 | TimefoldAI | zepfred | @@ -386,22 +387,71 @@ void recommendFit(SolutionManagerSource SolutionManagerSource) {
@ParameterizedTest
@EnumSource(SolutionManagerSource.class)
- void recommendFitUninitializedSolution(SolutionManagerSource SolutionManagerSource) {
+ void recommendAssignmentAlreadyAssigned(SolutionManagerSource SolutionManagerSource) {
+ int valueSize = 3;
+ var solution = TestdataShadowedSolution.generateSolution(valueSize, 3);
+ var evaluatedEntity = solution.getEntityList().get(2);
+ var value = evaluatedEntity.getValue();
+ evaluatedEntity.setValue(value);
+
+ var solutionManager = SolutionManagerSource.createSolutionManager(SOLVER_FACTORY_SHADOWED);
+ assertThat(solutionManager).isNotNull();
+ var recommendationList =
+ solutionManager.recommendAssignment(solution, evaluatedEntity, TestdataShadowedEntity::getValue);
+
+ // Three values means there need to be three recommendations.
+ assertThat(recommendationList).hasSize(valueSize);
+ /*
+ * The calculator counts how many entities have the same value as another entity.
+ * Therefore the recommendation to assign value #2 needs to come first,
+ * as it means the solution is practically unchanged.
+ */
+ var firstRecommendation = recommendationList.get(0);
+ assertSoftly(softly -> {
+ softly.assertThat(firstRecommendation.proposition()).isEqualTo(value);
+ softly.assertThat(firstRecommendation.scoreAnalysisDiff()
+ .score()).isEqualTo(SimpleScore.of(0));
+ });
+ // The other two recommendations need to come in order of the placer; so value #0, then value #1.
+ var secondRecommendation = recommendationList.get(1);
+ assertSoftly(softly -> {
+ softly.assertThat(secondRecommendation.proposition()).isEqualTo(solution.getValueList().get(0));
+ softly.assertThat(secondRecommendation.scoreAnalysisDiff()
+ .score()).isEqualTo(SimpleScore.of(-2));
+ });
+ var thirdRecommendation = recommendationList.get(2);
+ assertSoftly(softly -> {
+ softly.assertThat(thirdRecommendation.proposition()).isEqualTo(solution.getValueList().get(1));
+ softly.assertThat(thirdRecommendation.scoreAnalysisDiff()
+ .score()).isEqualTo(SimpleScore.of(-2));
+ });
+ // Ensure the original solution is in its original state.
+ assertSoftly(softly -> { | My comment in the `AssignmentProcessor` class relates to this validation. Please verify if I'm overlooking anything. |
timefold-solver | github_2023 | java | 1,136 | TimefoldAI | zepfred | @@ -386,22 +387,71 @@ void recommendFit(SolutionManagerSource SolutionManagerSource) {
@ParameterizedTest
@EnumSource(SolutionManagerSource.class)
- void recommendFitUninitializedSolution(SolutionManagerSource SolutionManagerSource) {
+ void recommendAssignmentAlreadyAssigned(SolutionManagerSource SolutionManagerSource) {
+ int valueSize = 3;
+ var solution = TestdataShadowedSolution.generateSolution(valueSize, 3);
+ var evaluatedEntity = solution.getEntityList().get(2);
+ var value = evaluatedEntity.getValue();
+ evaluatedEntity.setValue(value); | Is there a reason to set the value? |
timefold-solver | github_2023 | java | 1,136 | TimefoldAI | zepfred | @@ -459,14 +509,70 @@ void recommendFitWithUnassigned(SolutionManagerSource SolutionManagerSource) {
@ParameterizedTest
@EnumSource(SolutionManagerSource.class)
- void recommendFitUninitializedSolutionWithUnassigned(SolutionManagerSource SolutionManagerSource) {
+ void recommendAssignmentWithAllAssigned(SolutionManagerSource SolutionManagerSource) {
+ int valueSize = 3;
+ var solution = TestdataAllowsUnassignedSolution.generateSolution(valueSize, 3);
+ var evaluatedEntity = solution.getEntityList().get(2);
+
+ // At this point, entity 0 is unassigned.
+ // Entity 1 is assigned to value #1.
+ // But only entity2 should be processed for recommendations.
+ var solutionManager = SolutionManagerSource.createSolutionManager(SOLVER_FACTORY_UNASSIGNED);
+ assertThat(solutionManager).isNotNull();
+ var recommendationList =
+ solutionManager.recommendAssignment(solution, evaluatedEntity, TestdataAllowsUnassignedEntity::getValue);
+
+ // Three values means there need to be four recommendations, one extra for unassigned.
+ assertThat(recommendationList).hasSize(valueSize + 1); | How will this unassigned recommendation work if we already unassign it at the beginning of the `AssignmentProcessor` logic? |
timefold-solver | github_2023 | java | 1,136 | TimefoldAI | zepfred | @@ -764,13 +1101,33 @@ void recommendFitTwoUninitializedEntityWithList(SolutionManagerSource SolutionMa
var solutionManager = SolutionManagerSource.createSolutionManager(SOLVER_FACTORY_LIST);
var recommendationList =
- solutionManager.recommendFit(solution, uninitializedValue, v -> new Pair<>(v.getEntity(), v.getIndex()));
+ solutionManager.recommendAssignment(solution, uninitializedValue, v -> new Pair<>(v.getEntity(), v.getIndex()));
assertThat(recommendationList).hasSize(7);
}
@ParameterizedTest
@EnumSource(SolutionManagerSource.class)
- void recommendFitListPinned(SolutionManagerSource SolutionManagerSource) {
+ void recommendAssignmentTwoUninitializedEntityWithListAlreadyInitialized(SolutionManagerSource SolutionManagerSource) {
+ var a = new TestdataListEntityWithShadowHistory("a");
+ var b0 = new TestdataListValueWithShadowHistory("b0");
+ var b = new TestdataListEntityWithShadowHistory("b", b0);
+ var c0 = new TestdataListValueWithShadowHistory("c0");
+ var evaluatedValue = new TestdataListValueWithShadowHistory("c1");
+ var c = new TestdataListEntityWithShadowHistory("c", c0, evaluatedValue);
+ var d = new TestdataListEntityWithShadowHistory("d");
+ var solution = new TestdataListSolutionWithShadowHistory();
+ solution.setEntityList(Arrays.asList(a, b, c, d));
+ solution.setValueList(Arrays.asList(b0, c0, evaluatedValue));
+
+ var solutionManager = SolutionManagerSource.createSolutionManager(SOLVER_FACTORY_LIST);
+ var recommendationList =
+ solutionManager.recommendAssignment(solution, evaluatedValue, v -> new Pair<>(v.getEntity(), v.getIndex())); | Should this test fail as per the validation in `Assigner#apply`? |
timefold-solver | github_2023 | java | 1,136 | TimefoldAI | zepfred | @@ -113,12 +116,20 @@ public ScoreAnalysis<Score_> analyze(Solution_ solution, ScoreAnalysisFetchPolic
return analysis;
}
+ @Override
+ public <In_, Out_> List<RecommendedAssignment<Out_, Score_>> recommendAssignment(Solution_ solution, | I believe we need to add a new overloaded method without `fetchPolicy` param as we are using such a method in the documentation. |
timefold-solver | github_2023 | java | 1,136 | TimefoldAI | zepfred | @@ -174,15 +174,15 @@ private static String getSerializedScoreAnalysis() {
}
@Test
- void recommendationFit() throws JsonProcessingException {
+ void recommendedAssignment() throws JsonProcessingException { | The same comment about continuing to test the deprecated stuff applies here. |
timefold-solver | github_2023 | java | 1,123 | TimefoldAI | zepfred | @@ -15,24 +13,14 @@ final class RuinRecreateConstructionHeuristicPhase<Solution_>
super(builder);
}
- @Override
- protected void collectMetrics(AbstractStepScope<Solution_> stepScope) {
- // Nested phase doesn't collect metrics.
- }
-
@Override
protected ConstructionHeuristicPhaseScope<Solution_> buildPhaseScope(SolverScope<Solution_> solverScope, int phaseIndex) {
return new RuinRecreateConstructionHeuristicPhaseScope<>(solverScope, phaseIndex);
}
@Override
- protected void processWorkingSolutionDuringStep(ConstructionHeuristicStepScope<Solution_> stepScope) {
- // Ruin and Recreate CH doesn't process the working solution, it is a nested phase.
- }
-
- @Override
- protected void updateBestSolutionAndFire(ConstructionHeuristicPhaseScope<Solution_> phaseScope) { | What was the problem with this logic? |
timefold-solver | github_2023 | java | 1,072 | TimefoldAI | triceo | @@ -91,6 +91,8 @@ protected List<SolverMetric> getSolverMetrics(ProblemBenchmarksConfig config) {
.orElseGet(ProblemStatisticType::defaultList)) {
if (problemStatisticType == ProblemStatisticType.SCORE_CALCULATION_SPEED) {
out.add(SolverMetric.SCORE_CALCULATION_COUNT);
+ } else if (problemStatisticType == ProblemStatisticType.MOVE_CALCULATION_SPEED) { | Question: does "move calculation" make sense? Move's aren't calculated.
Arguably "move execution" would be more correct here.
Any other ideas? |
timefold-solver | github_2023 | java | 1,072 | TimefoldAI | triceo | @@ -0,0 +1,56 @@
+package ai.timefold.solver.benchmark.impl.statistic.movecalculationspeed;
+
+import static java.util.Collections.singletonList;
+
+import java.util.List;
+
+import ai.timefold.solver.benchmark.config.statistic.ProblemStatisticType;
+import ai.timefold.solver.benchmark.impl.report.BenchmarkReport;
+import ai.timefold.solver.benchmark.impl.report.LineChart;
+import ai.timefold.solver.benchmark.impl.result.ProblemBenchmarkResult;
+import ai.timefold.solver.benchmark.impl.result.SingleBenchmarkResult;
+import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult;
+import ai.timefold.solver.benchmark.impl.statistic.ProblemStatistic;
+import ai.timefold.solver.benchmark.impl.statistic.SubSingleStatistic;
+
+public class MoveCalculationSpeedProblemStatistic extends ProblemStatistic<LineChart<Long, Long>> {
+
+ private MoveCalculationSpeedProblemStatistic() {
+ // For JAXB.
+ }
+
+ public MoveCalculationSpeedProblemStatistic(ProblemBenchmarkResult<?> problemBenchmarkResult) {
+ super(problemBenchmarkResult, ProblemStatisticType.MOVE_CALCULATION_SPEED);
+ }
+
+ @Override
+ public SubSingleStatistic<?, ?> createSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult) {
+ return new MoveCalculationSpeedSubSingleStatistic<>(subSingleBenchmarkResult);
+ }
+
+ /**
+ * @return never null
+ */
+ @Override
+ protected List<LineChart<Long, Long>> generateCharts(BenchmarkReport benchmarkReport) {
+ LineChart.Builder<Long, Long> builder = new LineChart.Builder<>(); | For new code, I'd generally go with `var`. |
timefold-solver | github_2023 | java | 1,072 | TimefoldAI | triceo | @@ -0,0 +1,91 @@
+package ai.timefold.solver.benchmark.impl.statistic.movecalculationspeed;
+
+import java.util.List;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.Consumer;
+
+import ai.timefold.solver.benchmark.config.statistic.ProblemStatisticType;
+import ai.timefold.solver.benchmark.impl.result.SubSingleBenchmarkResult;
+import ai.timefold.solver.benchmark.impl.statistic.ProblemBasedSubSingleStatistic;
+import ai.timefold.solver.benchmark.impl.statistic.StatisticPoint;
+import ai.timefold.solver.benchmark.impl.statistic.StatisticRegistry;
+import ai.timefold.solver.core.config.solver.monitoring.SolverMetric;
+import ai.timefold.solver.core.impl.score.definition.ScoreDefinition;
+
+import io.micrometer.core.instrument.Tags;
+
+public class MoveCalculationSpeedSubSingleStatistic<Solution_>
+ extends ProblemBasedSubSingleStatistic<Solution_, MoveCalculationSpeedStatisticPoint> {
+
+ private long timeMillisThresholdInterval;
+
+ private MoveCalculationSpeedSubSingleStatistic() {
+ // For JAXB.
+ }
+
+ public MoveCalculationSpeedSubSingleStatistic(SubSingleBenchmarkResult subSingleBenchmarkResult) {
+ this(subSingleBenchmarkResult, 1000L);
+ }
+
+ public MoveCalculationSpeedSubSingleStatistic(SubSingleBenchmarkResult benchmarkResult, long timeMillisThresholdInterval) {
+ super(benchmarkResult, ProblemStatisticType.MOVE_CALCULATION_SPEED);
+ if (timeMillisThresholdInterval <= 0L) {
+ throw new IllegalArgumentException("The timeMillisThresholdInterval (" + timeMillisThresholdInterval
+ + ") must be bigger than 0.");
+ }
+ this.timeMillisThresholdInterval = timeMillisThresholdInterval;
+ }
+
+ // ************************************************************************
+ // Lifecycle methods
+ // ************************************************************************
+
+ @Override
+ public void open(StatisticRegistry<Solution_> registry, Tags runTag) {
+ registry.addListener(SolverMetric.MOVE_CALCULATION_COUNT, new Consumer<>() {
+ long nextTimeMillisThreshold = timeMillisThresholdInterval;
+ long lastTimeMillisSpent = 0;
+ final AtomicLong lastMoveCalculationCount = new AtomicLong(0);
+
+ @Override
+ public void accept(Long timeMillisSpent) {
+ if (timeMillisSpent >= nextTimeMillisThreshold) {
+ registry.getGaugeValue(SolverMetric.MOVE_CALCULATION_COUNT, runTag, moveCalculationCountNumber -> {
+ long moveCalculationCount = moveCalculationCountNumber.longValue();
+ long calculationCountInterval = moveCalculationCount - lastMoveCalculationCount.get();
+ long timeMillisSpentInterval = timeMillisSpent - lastTimeMillisSpent;
+ if (timeMillisSpentInterval == 0L) {
+ // Avoid divide by zero exception on a fast CPU
+ timeMillisSpentInterval = 1L;
+ }
+ long moveCalculationSpeed = calculationCountInterval * 1000L / timeMillisSpentInterval; | We already have this code elsewhere. It's a bit of a fishy logic, we should extract it to a method and reuse. |
timefold-solver | github_2023 | java | 1,072 | TimefoldAI | triceo | @@ -0,0 +1,22 @@
+package ai.timefold.solver.core.impl.heuristic.move;
+
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
+
+/**
+ * Abstract superclass for {@link Move} which includes the ability to enable or disable the move metric collection.
+ *
+ * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
+ */
+public abstract class AbstractMetricMove<Solution_> implements Move<Solution_> { | Please think of a different way of doing this. `Move` is something that people extend; we don't want them to think about metrics as they do so. Moves should not have to understand if they're being measured or not.
Also, this makes the move even more mutable than it already was before. I don't like this at all. |
timefold-solver | github_2023 | java | 1,072 | TimefoldAI | Christopher-Chianelli | @@ -515,13 +515,15 @@ void testScoreCalculationCountForFinishedJob() throws ExecutionException, Interr
solverJob.getFinalBestSolution();
assertThat(solverJob.getScoreCalculationCount()).isEqualTo(5L);
+ assertThat(solverJob.getMoveEvaluationCount()).isEqualTo(4L); | Why is it 4 and not 5? It only use Swap/Change moves? |
timefold-solver | github_2023 | others | 1,072 | TimefoldAI | triceo | @@ -596,6 +596,27 @@ Useful for comparing different score calculators and/or constraint implementatio
Also useful to measure the scalability cost of an extra constraint.
+[#benchmarkReportMoveEvaluationSpeedSummary]
+=== Move evaluation speed summary (graph And table) | ```suggestion
=== Move evaluation speed summary (graph and table)
``` |
timefold-solver | github_2023 | others | 1,072 | TimefoldAI | triceo | @@ -33,6 +33,18 @@ and still compare it with the original's calculation speed.
Comparing the best score with the original's best score is pointless: it's comparing apples and oranges.
====
+The solver usually calculates the score for each move it evaluates.
+This means a direct relationship exists between the score calculation and the evaluated move, typically a `1:1` ratio.
+However, some moves,
+such as xref:optimization-algorithms/move-selector-reference.adoc#ruinRecreateMoveSelector[Ruin and Recreate],
+involve processing the score multiple times within the same move.
+
+The use of moves like Ruin and Recreate may increase the number of score calculations,
+which makes the relationship `1:1` invalid. | ```suggestion
making this ratio `N:1`.
``` |
timefold-solver | github_2023 | others | 1,072 | TimefoldAI | triceo | @@ -33,6 +33,18 @@ and still compare it with the original's calculation speed.
Comparing the best score with the original's best score is pointless: it's comparing apples and oranges.
====
+The solver usually calculates the score for each move it evaluates.
+This means a direct relationship exists between the score calculation and the evaluated move, typically a `1:1` ratio.
+However, some moves,
+such as xref:optimization-algorithms/move-selector-reference.adoc#ruinRecreateMoveSelector[Ruin and Recreate],
+involve processing the score multiple times within the same move.
+
+The use of moves like Ruin and Recreate may increase the number of score calculations,
+which makes the relationship `1:1` invalid.
+In such cases,
+the metric xref:using-timefold-solver/benchmarking-and-tweaking.adoc#benchmarkReportMoveEvaluationSpeedSummary[__move evaluation speed per second__] makes more sense,
+as it will count the number of moves individually. | ```suggestion
as the move count will stay stable no matter how many score calculations the moves perform.
``` |
timefold-solver | github_2023 | others | 1,072 | TimefoldAI | triceo | @@ -596,6 +596,27 @@ Useful for comparing different score calculators and/or constraint implementatio
Also useful to measure the scalability cost of an extra constraint.
+[#benchmarkReportMoveEvaluationSpeedSummary]
+=== Move evaluation speed summary (graph And table)
+
+Shows the move evaluation speed: a count per move, per second and per problem scale for each solver configuration.
+
+Useful for comparing different solver algorithms,
+score calculators and/or constraint implementations
+(presuming that the solver configurations do not differ otherwise, including the move selector configuration).
+Also useful to measure the scalability cost of an extra constraint.
+
+[IMPORTANT]
+====
+When improving your move evaluation,
+it's important to note that comparing a configuration
+that uses xref:optimization-algorithms/move-selector-reference.adoc#ruinRecreateMoveSelector[Ruin and Recreate] moves with one that doesn't wouldn't be fair.
+This is because the configuration using Ruin and Recreate will likely execute fewer moves than one that doesn't.
+On the other hand, the Ruin and Recreate moves will likely calculate the score more times, improving the __score calculation speed__.
+The recreate step runs a construction heuristic,
+which uses greedy logic to find a better location to assign each one of the entities removed with the ruin step.
+==== | This note arguably applies to score calculation count, but is irrelevant in move count, no? Move counts are the same regardless of what moves are used.
(It is true that RnR is slow and therefore will decrease move count, but you can say that about any slow move. This is not specific to RnR.) |
timefold-solver | github_2023 | others | 1,072 | TimefoldAI | triceo | @@ -753,6 +774,34 @@ After those few seconds of initialization, the calculation speed is relatively s
====
+[#benchmarkReportMoveEvaluationSpeedOverTimeStatistic]
+=== Move evaluation speed over time statistic (graph and CSV)
+
+To see how fast the moves are evaluated, add:
+
+[source,xml,options="nowrap"]
+----
+ <problemBenchmarks>
+ ...
+ <problemStatisticType>MOVE_EVALUATION_SPEED</problemStatisticType>
+ </problemBenchmarks>
+----
+
+.Move Evaluation Speed Statistic
+image::using-timefold-solver/benchmarking-and-tweaking/moveEvaluationSpeedStatistic.png[align="center"]
+
+
+[NOTE]
+====
+The initial high calculation speed is typical during solution initialization:
+it's far easier to calculate the score of a solution if only a handful planning entities have been initialized,
+than when all the planning entities are initialized.
+
+After those few seconds of initialization, the evaluation speed is relatively stable, | ```suggestion
After the construction heuristic phase, the evaluation speed is relatively stable,
```
Let's not promise seconds. :-) We've seen it can be minutes, hours. |
timefold-solver | github_2023 | java | 1,072 | TimefoldAI | triceo | @@ -217,6 +226,16 @@ public Long getScoreCalculationSpeed() {
return scoreCalculationCount * 1000L / timeMillisSpent;
}
+ @SuppressWarnings("unused") // Used by FreeMarker.
+ public Long getMoveEvaluationSpeed() {
+ long timeSpent = this.timeMillisSpent;
+ if (timeSpent == 0L) {
+ // Avoid divide by zero exception on a fast CPU
+ timeSpent = 1L;
+ }
+ return moveEvaluationCount * 1000L / timeSpent;
+ } | Consider sharing this method statically; it's used in more than one place, and likely also for score calculation speed. |
timefold-solver | github_2023 | java | 1,072 | TimefoldAI | triceo | @@ -58,6 +58,7 @@ public EntityPlacer<Solution_> getEntityPlacer() {
@Override
public DefaultConstructionHeuristicPhase<Solution_> build() {
+ this.setEnableCollectMetrics(false); | Arguably, if this is only used in one place and the default is true, this should rather be called `disableMetricCollection()`, inverting the logic. |
timefold-solver | github_2023 | java | 1,072 | TimefoldAI | triceo | @@ -130,7 +130,9 @@ public void stepStarted(LocalSearchStepScope<Solution_> stepScope) {
public void stepEnded(LocalSearchStepScope<Solution_> stepScope) {
super.stepEnded(stepScope);
decider.stepEnded(stepScope);
- collectMetrics(stepScope);
+ if (stepScope.isPhaseEnableCollectMetrics()) {
+ collectMetrics(stepScope);
+ } | Why would metrics collection ever be disabled in Local Search? What changed that the metric collection is now conditional?
Also, let's change the method. Arguably, this belongs on the phase scope, and then it can be called `isMetricCollectionEnabled()`. If we need it, that is. |
timefold-solver | github_2023 | java | 1,072 | TimefoldAI | triceo | @@ -44,10 +46,23 @@ public void setBestScoreImproved(Boolean bestScoreImproved) {
this.bestScoreImproved = bestScoreImproved;
}
+ public void incrementMoveEvaluationCount(Move<?> move) {
+ if (isPhaseEnableCollectMetrics()) {
+ getPhaseScope().getSolverScope().addMoveEvaluationCount(1L);
+ if (getPhaseScope().getSolverScope().isMetricEnabled(SolverMetric.MOVE_COUNT_PER_TYPE)) {
+ getPhaseScope().getSolverScope().incrementMoveEvaluationCountPerType(move);
+ }
+ }
+ }
+
// ************************************************************************
// Calculated methods
// ************************************************************************
+ public boolean isPhaseEnableCollectMetrics() {
+ return getPhaseScope().isEnableCollectMetrics();
+ } | Ah, I see, it _is_ on the phase, you just make it available on the step like this.
I wouldn't - it increases amount of code in one place (here) to decrease amount of code later (at call time). But arguably, it adds more code than it removes. |
timefold-solver | github_2023 | java | 1,072 | TimefoldAI | triceo | @@ -355,4 +381,17 @@ public void destroyYielding() {
}
}
+ public void incrementMoveEvaluationCountPerType(Move<?> move) {
+ addMoveEvaluationCountPerType(move.getSimpleMoveTypeDescription(), 1L);
+ }
+
+ public void addMoveEvaluationCountPerType(String moveType, long count) { | Why is this method public, if we already have the one above? |
timefold-solver | github_2023 | java | 1,072 | TimefoldAI | triceo | @@ -62,6 +67,11 @@ public class SolverScope<Solution_> {
*/
private final Map<Tags, List<AtomicReference<Number>>> stepScoreMap = new ConcurrentHashMap<>();
+ /**
+ * Used for tracking move count per move type
+ */
+ private final Map<String, AtomicLong> moveEvaluationCountPerTypeMap = new ConcurrentHashMap<>(); | If the map is already concurrent, do you need the `AtomicLong`?
Wouldn't locking the entire write operation be a much better guarantee of atomicity? |
timefold-solver | github_2023 | others | 1,072 | TimefoldAI | triceo | @@ -4,35 +4,44 @@
[#scoreCalculationPerformanceTricksOverview]
== Overview
-The `Solver` will normally spend most of its execution time running score calculation,
+The `Solver` will normally spend most of its execution time evaluating moves and running score calculation,
which is called in its deepest loops.
-Faster score calculation will return the same solution in less time with the same algorithm,
+Faster move evaluation will return the same solution in less time with the same algorithm, | In this case, we are arguably talking about faster score calculation.
That is the deciding factor for speed, if everything else is equal. Move evaluation speed is _determined_ by score calculation speed. |
timefold-solver | github_2023 | others | 1,072 | TimefoldAI | triceo | @@ -4,35 +4,44 @@
[#scoreCalculationPerformanceTricksOverview]
== Overview
-The `Solver` will normally spend most of its execution time running score calculation,
+The `Solver` will normally spend most of its execution time evaluating moves and running score calculation,
which is called in its deepest loops.
-Faster score calculation will return the same solution in less time with the same algorithm,
+Faster move evaluation will return the same solution in less time with the same algorithm,
which normally means a better solution in equal time.
-[#scoreCalculationSpeed]
-== Score calculation speed
+[#moveEvaluationSpeed]
+== Move evaluation speed
-After solving a problem, the `Solver` will log the __score calculation speed per second__.
-This is a good measurement of Score calculation performance,
+After solving a problem, the `Solver` will log the __move evaluation speed per second__.
+This is a good measurement of Move evaluation performance,
despite that it is affected by non-score calculation execution time.
It depends on the problem scale of the problem dataset.
Normally, even for large scale problems, it is higher than ``1000``,
except if you are using xref:constraints-and-score/score-calculation.adoc#easyScoreCalculation[``EasyScoreCalculator``].
[IMPORTANT]
====
-When improving your score calculation, focus on maximizing the score calculation speed,
+When improving your move evaluation, focus on maximizing the move evaluation speed, | See, I don't agree with this statement.
To improve your performance, you have to increase your score calculation speed - if you focus on move evaluation speed, it means you start removing slow moves, and that is counter-productive. You need to increase the score calculation speed while _keeping_ the existing moves. |
timefold-solver | github_2023 | others | 1,072 | TimefoldAI | triceo | @@ -4,35 +4,44 @@
[#scoreCalculationPerformanceTricksOverview]
== Overview
-The `Solver` will normally spend most of its execution time running score calculation,
+The `Solver` will normally spend most of its execution time evaluating moves and running score calculation,
which is called in its deepest loops.
-Faster score calculation will return the same solution in less time with the same algorithm,
+Faster move evaluation will return the same solution in less time with the same algorithm,
which normally means a better solution in equal time.
-[#scoreCalculationSpeed]
-== Score calculation speed
+[#moveEvaluationSpeed] | Have you checked all the references to this?
Antora has a habit of failing when refs don't exist.
Also, I'd call this section "Move evaluation and score calculation speed". |
timefold-solver | github_2023 | others | 1,072 | TimefoldAI | triceo | @@ -458,5 +467,7 @@ For example, move multiple items from the same container to another container.
== `stepLimit` benchmark
Not all score constraints have the same performance cost.
-Sometimes one score constraint can kill the score calculation performance outright.
-Use the xref:using-timefold-solver/benchmarking-and-tweaking.adoc#benchmarker[Benchmarker] to do a one minute run and check what happens to the score calculation speed if you comment out all but one of the score constraints.
\ No newline at end of file
+Sometimes one score constraint can kill the move evaluation performance outright. | ```suggestion
Sometimes one score constraint can performance outright.
``` |
timefold-solver | github_2023 | others | 1,072 | TimefoldAI | triceo | @@ -595,6 +595,27 @@ Useful for comparing different score calculators and/or constraint implementatio
(presuming that the solver configurations do not differ otherwise).
Also useful to measure the scalability cost of an extra constraint.
+[IMPORTANT]
+====
+When improving your score speed,
+it's important to note that comparing a configuration
+that uses xref:optimization-algorithms/move-selector-reference.adoc#ruinRecreateMoveSelector[Ruin and Recreate] moves | ```suggestion
When improving your score calculation speed,
comparing a configuration that uses
xref:optimization-algorithms/move-selector-reference.adoc#ruinRecreateMoveSelector[Ruin and Recreate] moves
``` |
timefold-solver | github_2023 | others | 1,072 | TimefoldAI | triceo | @@ -753,6 +774,50 @@ After those few seconds of initialization, the calculation speed is relatively s
====
+[#benchmarkReportMoveEvaluationSpeedOverTimeStatistic]
+=== Move evaluation speed over time statistic (graph and CSV)
+
+To see how fast the moves are evaluated, add:
+
+[source,xml,options="nowrap"]
+----
+ <problemBenchmarks>
+ ...
+ <problemStatisticType>MOVE_EVALUATION_SPEED</problemStatisticType>
+ </problemBenchmarks>
+----
+
+.Move Evaluation Speed Statistic
+image::using-timefold-solver/benchmarking-and-tweaking/moveEvaluationSpeedStatistic.png[align="center"]
+
+
+[NOTE]
+====
+The initial high calculation speed is typical during solution initialization: | ```suggestion
The initial high evaluation speed is typical during solution initialization:
``` |
timefold-solver | github_2023 | others | 1,072 | TimefoldAI | triceo | @@ -287,7 +287,7 @@ 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.
-In Eclipse, `debug` logging to the console tends to cause congestion with a score calculation speeds above 10 000 per second.
+In Eclipse, `debug` logging to the console tends to cause congestion with a move evaluation speeds above 10 000 per second. | ```suggestion
In Eclipse, `debug` logging to the console tends to cause congestion with move evaluation speeds above 10 000 per second.
``` |
timefold-solver | github_2023 | java | 1,072 | TimefoldAI | triceo | @@ -44,10 +46,18 @@ public void setBestScoreImproved(Boolean bestScoreImproved) {
this.bestScoreImproved = bestScoreImproved;
}
+ public void incrementMoveEvaluationCount(Move<?> move) {
+ if (getPhaseScope().isEnableCollectMetrics()) { | Let's change the name; 'isMetricCollectionEnabled()', better English.
Also, it would be nice if the method were documented - why do we ever need to disable metrics? |
timefold-solver | github_2023 | java | 1,072 | TimefoldAI | triceo | @@ -93,7 +93,12 @@ public void setBestSolutionStepIndex(int bestSolutionStepIndex) {
public abstract AbstractStepScope<Solution_> getLastCompletedStepScope();
- public boolean isEnableCollectMetrics() {
+ /**
+ * @return true, if the metrics collection, such as
+ * {@link ai.timefold.solver.core.config.solver.monitoring.SolverMetric#MOVE_COUNT_PER_TYPE MOVE_COUNT_PER_TYPE},
+ * is enabled; false, if the collection is disabled for the phase. | ```suggestion
* @return true, if the metrics collection, such as
* {@link ai.timefold.solver.core.config.solver.monitoring.SolverMetric#MOVE_COUNT_PER_TYPE MOVE_COUNT_PER_TYPE},
* is enabled.
* This is disabled for nested phases, such as Construction heuristics in Ruin and Recreate.
``` |
timefold-solver | github_2023 | java | 1,108 | TimefoldAI | zepfred | @@ -20,12 +21,26 @@ default Constraint asConstraint(String constraintName) {
/**
* Builds a {@link Constraint} from the constraint stream.
* The {@link ConstraintRef#packageName() constraint package} defaults to the package of the {@link PlanningSolution} class.
+ * The constraint will be placed in the {@link Constraint#DEFAULT_CONSTRAINT_GROUP default constraint group}.
*
* @param constraintName never null, shows up in {@link ConstraintMatchTotal} during score justification
* @param constraintDescription never null
* @return never null
*/
- Constraint asConstraintDescribed(String constraintName, String constraintDescription);
+ default Constraint asConstraintDescribed(String constraintName, String constraintDescription) {
+ return asConstraintDescribed(constraintName, constraintDescription, Constraint.DEFAULT_CONSTRAINT_GROUP);
+ }
+
+ /**
+ * Builds a {@link Constraint} from the constraint stream.
+ * The {@link ConstraintRef#packageName() constraint package} defaults to the package of the {@link PlanningSolution} class.
+ *
+ * @param constraintName never null, shows up in {@link ConstraintMatchTotal} during score justification
+ * @param constraintDescription never null
+ * @param constraintGroup never null, only allows alphanumeric characters, "-" and "_" | The regex is using `\p{So}`, which means we will accept other symbols. |
timefold-solver | github_2023 | java | 1,108 | TimefoldAI | zepfred | @@ -35,54 +32,6 @@ protected TestConstraint<Solution_, Score_> buildConstraint(Score_ constraintWei
abstract protected AbstractScoreInliner<Score_> buildScoreInliner(Map<Constraint, Score_> constraintWeightMap,
boolean constraintMatchEnabled);
- public static final class TestConstraintFactory<Solution_, Score_ extends Score<Score_>>
- extends InnerConstraintFactory<Solution_, TestConstraint<Solution_, Score_>> {
-
- private final SolutionDescriptor<Solution_> solutionDescriptor;
-
- public TestConstraintFactory(SolutionDescriptor<Solution_> solutionDescriptor) {
- this.solutionDescriptor = Objects.requireNonNull(solutionDescriptor);
- }
-
- @Override
- public SolutionDescriptor<Solution_> getSolutionDescriptor() {
- return solutionDescriptor;
- }
-
- @Override
- public String getDefaultConstraintPackage() {
- return "constraintPackage";
- }
-
- @Override
- public <A> UniConstraintStream<A> forEach(Class<A> sourceClass) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public <A> UniConstraintStream<A> forEachIncludingUnassigned(Class<A> sourceClass) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public <A> UniConstraintStream<A> from(Class<A> fromClass) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public <A> UniConstraintStream<A> fromUnfiltered(Class<A> fromClass) {
- throw new UnsupportedOperationException();
- }
- };
-
- public static final class TestConstraint<Solution_, Score_ extends Score<Score_>>
- extends AbstractConstraint<Solution_, TestConstraint<Solution_, Score_>, TestConstraintFactory<Solution_, Score_>> {
-
- protected TestConstraint(TestConstraintFactory<Solution_, Score_> constraintFactory, String constraintName,
- Score_ constraintWeight) {
- super(constraintFactory, ConstraintRef.of(constraintFactory.getDefaultConstraintPackage(), constraintName), "",
- constraintWeight, ScoreImpactType.REWARD, null, null);
- }
- }
+ ; | ```suggestion
``` |
timefold-solver | github_2023 | java | 1,108 | TimefoldAI | zepfred | @@ -0,0 +1,35 @@
+package ai.timefold.solver.quarkus;
+
+import jakarta.inject.Inject;
+
+import ai.timefold.solver.core.api.score.stream.ConstraintMetaModel;
+import ai.timefold.solver.quarkus.testdata.normal.constraints.TestdataQuarkusConstraintProvider;
+import ai.timefold.solver.quarkus.testdata.normal.domain.TestdataQuarkusEntity;
+import ai.timefold.solver.quarkus.testdata.normal.domain.TestdataQuarkusSolution;
+
+import org.assertj.core.api.Assertions;
+import org.jboss.shrinkwrap.api.ShrinkWrap;
+import org.jboss.shrinkwrap.api.spec.JavaArchive;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+
+import io.quarkus.test.QuarkusUnitTest;
+
+class TimefoldProcessorConstraintMetaModelTest { | Please also update `TimefoldProcessorSolverResourcesTest` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.