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 | 573 | TimefoldAI | Christopher-Chianelli | @@ -849,6 +887,44 @@ void solveRepeatedlyListVariable(SoftAssertions softly) {
softly.assertThat(solution.getScore().isSolutionInitialized()).isTrue();
}
+ @Test
+ void solveWithAllowsUnassignedValuesListVariable() {
+ var solverConfig = PlannerTestUtils.buildSolverConfig(TestdataAllowsUnassignedValuesListSolution.class,
+ TestdataAllowsUnassignedValuesListEntity.class, TestdataAllowsUnassignedValuesListValue.class)
+ .withEasyScoreCalculatorClass(TestdataAllowsUnassignedValuesListEasyScoreCalculator.class)
+ .withTerminationConfig(new TerminationConfig().withBestScoreLimit("0"))
+ .withPhases();
+ var solverFactory = SolverFactory.<TestdataAllowsUnassignedValuesListSolution> create(solverConfig);
+ var solver = solverFactory.buildSolver();
+
+ var value1 = new TestdataAllowsUnassignedValuesListValue("v1");
+ var value2 = new TestdataAllowsUnassignedValuesListValue("v2");
+ var value3 = new TestdataAllowsUnassignedValuesListValue("v3");
+ var value4 = new TestdataAllowsUnassignedValuesListValue("v4");
+ var entity = new TestdataAllowsUnassignedValuesListEntity("e1");
+ entity.setValueList(Arrays.asList(value1, value2));
+ value1.setIndex(0);
+ value1.setEntity(entity);
+ value1.setPrevious(null);
+ value1.setNext(value2);
+ value2.setIndex(1);
+ value2.setEntity(entity);
+ value2.setPrevious(value1);
+ value2.setNext(null);
+
+ var solution = new TestdataAllowsUnassignedValuesListSolution();
+ solution.setEntityList(List.of(entity));
+ solution.setValueList(Arrays.asList(value1, value2, value3, value4));
+
+ var bestSolution = solver.solve(solution);
+ assertSoftly(softly -> { | Why is `firstEntity.getValueList()` empty for `solveWithUnassignedValuesListVariable` and equal to `[value1, value2]` for `constructionHeuristicWithAllowsUnassignedValuesListVariable`, since it appears the dataset are the same (or are index, previous and next problem facts instead of shadow variables)? |
timefold-solver | github_2023 | java | 573 | TimefoldAI | Christopher-Chianelli | @@ -0,0 +1,22 @@
+package ai.timefold.solver.core.impl.testdata.domain.list.allows_unassigned_values;
+
+import ai.timefold.solver.core.api.score.buildin.simple.SimpleScore;
+import ai.timefold.solver.core.api.score.stream.Constraint;
+import ai.timefold.solver.core.api.score.stream.ConstraintFactory;
+import ai.timefold.solver.core.api.score.stream.ConstraintProvider;
+
+public final class TestdataAllowsUnassignedValuesListConstraintProvider implements ConstraintProvider { | Does `core-impl` have `constraint-streams` as a test dependency? |
timefold-solver | github_2023 | java | 573 | TimefoldAI | Christopher-Chianelli | @@ -24,6 +24,7 @@ public static IndexShadowVariableDescriptor<TestdataPinnedListSolution> buildVar
.getShadowVariableDescriptor("index");
}
+ // Intentionally missing the inverse relation variable; some tests rely on it not being here. | TBH, not sure how I feel about TestdataPinnedListValue not having inverse relation variable, since it not obvious from the class name that this class is serving the second purpose of not having an inverse relation variable. |
timefold-solver | github_2023 | java | 573 | TimefoldAI | Christopher-Chianelli | @@ -106,14 +107,14 @@ public static TestdataSolution generateTestdataSolution(String code, int entityA
// ScoreDirector methods
// ************************************************************************
- public static <Solution_> InnerScoreDirector<Solution_, SimpleScore> mockScoreDirector(
+ public static <Solution_> AbstractScoreDirector<Solution_, SimpleScore, ?> mockScoreDirector(
SolutionDescriptor<Solution_> solutionDescriptor) {
EasyScoreDirectorFactory<Solution_, SimpleScore> scoreDirectorFactory =
new EasyScoreDirectorFactory<>(solutionDescriptor, (solution_) -> SimpleScore.of(0));
scoreDirectorFactory.setInitializingScoreTrend(
InitializingScoreTrend.buildUniformTrend(InitializingScoreTrendLevel.ONLY_DOWN, 1));
- return mock(InnerScoreDirector.class,
- AdditionalAnswers.delegatesTo(scoreDirectorFactory.buildScoreDirector(false, false)));
+ return mock(AbstractScoreDirector.class,
+ AdditionalAnswers.delegatesTo(scoreDirectorFactory.buildScoreDirector(true, false))); | Any particular reason to enable lookup in the mock? |
timefold-solver | github_2023 | java | 573 | TimefoldAI | Christopher-Chianelli | @@ -138,7 +138,7 @@ Constraint roomConflict(ConstraintFactory factory) {
}
Constraint speakerUnavailableTimeslot(ConstraintFactory factory) {
- return factory.forEachIncludingNullVars(Talk.class)
+ return factory.forEachIncludingUnassigned(Talk.class) | I think the Talk still uses `nullable=true`, since I don't see it in the changed files |
timefold-solver | github_2023 | java | 573 | TimefoldAI | Christopher-Chianelli | @@ -51,7 +51,7 @@ protected Constraint roomConflict(ConstraintFactory constraintFactory) {
}
protected Constraint avoidOvertime(ConstraintFactory constraintFactory) {
- return constraintFactory.forEachIncludingNullVars(MeetingAssignment.class)
+ return constraintFactory.forEachIncludingUnassigned(MeetingAssignment.class) | I think `MeetingAssignment` still uses `nullable=true`, since I don't see it in the changed files. |
timefold-solver | github_2023 | java | 573 | TimefoldAI | Christopher-Chianelli | @@ -218,4 +232,151 @@ void uniquePairShouldWorkOnStringPlanningId() {
.rewards(1, "There should be rewards")).hasMessageContaining("There should be rewards")
.hasMessageContaining("Expected reward");
}
+
+ @Test
+ void listVarUnassignedWhileAllowsUnassigned() {
+ var constraintVerifier =
+ ConstraintVerifier.build(new TestdataAllowsUnassignedListConstraintProvider(),
+ TestdataAllowsUnassignedValuesListSolution.class,
+ TestdataAllowsUnassignedValuesListEntity.class,
+ TestdataAllowsUnassignedValuesListValue.class);
+
+ var value1 = new TestdataAllowsUnassignedValuesListValue("v1");
+ var value2 = new TestdataAllowsUnassignedValuesListValue("v2");
+ var entity = new TestdataAllowsUnassignedValuesListEntity("eA");
+ entity.setValueList(Collections.singletonList(value1));
+ value1.setIndex(0);
+ value1.setEntity(entity);
+
+ assertThatCode(() -> constraintVerifier | I don't think you tested the case where the assertion fails for SingleConstraintAssertionTest (but that probably covered in other tests). |
timefold-solver | github_2023 | java | 573 | TimefoldAI | Christopher-Chianelli | @@ -0,0 +1,62 @@
+package ai.timefold.solver.core.impl.domain.variable;
+
+import ai.timefold.solver.core.api.domain.variable.ListVariableListener;
+import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
+import ai.timefold.solver.core.impl.domain.variable.index.IndexVariableSupply;
+import ai.timefold.solver.core.impl.domain.variable.inverserelation.SingletonInverseVariableSupply;
+import ai.timefold.solver.core.impl.domain.variable.listener.SourcedVariableListener;
+import ai.timefold.solver.core.impl.heuristic.selector.list.ElementLocation;
+
+public interface ListVariableDataSupply<Solution_> extends
+ SourcedVariableListener<Solution_>,
+ ListVariableListener<Solution_, Object, Object>,
+ SingletonInverseVariableSupply,
+ IndexVariableSupply,
+ ListVariableElementStateSupply<Solution_> {
+
+ /**
+ * Returns the state that the element of the list variable is in.
+ * To avoid hash lookups, calling {@link #countNotAssigned()} is possible; | Nitpick: identity hash lookups? |
timefold-solver | github_2023 | java | 573 | TimefoldAI | Christopher-Chianelli | @@ -0,0 +1,193 @@
+package ai.timefold.solver.core.impl.score.director;
+
+import ai.timefold.solver.core.api.score.director.ScoreDirector;
+import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
+import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
+import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
+
+public interface VariableDescriptorAwareScoreDirector<Solution_>
+ extends ScoreDirector<Solution_> {
+
+ SolutionDescriptor<Solution_> getSolutionDescriptor();
+
+ // ************************************************************************
+ // Basic variable
+ // ************************************************************************
+
+ void beforeVariableChanged(VariableDescriptor<Solution_> variableDescriptor, Object entity);
+
+ void afterVariableChanged(VariableDescriptor<Solution_> variableDescriptor, Object entity);
+
+ void changeVariableFacade(VariableDescriptor<Solution_> variableDescriptor, Object entity, Object newValue);
+
+ // ************************************************************************
+ // List variable
+ // ************************************************************************
+
+ /**
+ * Call this for each element that will be assigned (added to a list variable of one entity without being removed
+ * from a list variable of another entity).
+ *
+ * @param variableDescriptor the list variable descriptor
+ * @param element the assigned element
+ */
+ void beforeListVariableElementAssigned(ListVariableDescriptor<Solution_> variableDescriptor, Object element);
+
+ /**
+ * Call this for each element that was assigned (added to a list variable of one entity without being removed
+ * from a list variable of another entity).
+ *
+ * @param variableDescriptor the list variable descriptor
+ * @param element the assigned element
+ */
+ void afterListVariableElementAssigned(ListVariableDescriptor<Solution_> variableDescriptor, Object element);
+
+ /**
+ * Call this for each element that will be unassigned (removed from a list variable of one entity without being added
+ * to a list variable of another entity).
+ *
+ * @param variableDescriptor the list variable descriptor
+ * @param element the unassigned element
+ */
+ void beforeListVariableElementUnassigned(ListVariableDescriptor<Solution_> variableDescriptor, Object element);
+
+ /**
+ * Call this for each element that was unassigned (removed from a list variable of one entity without being added
+ * to a list variable of another entity).
+ *
+ * @param variableDescriptor the list variable descriptor
+ * @param element the unassigned element
+ */
+ void afterListVariableElementUnassigned(ListVariableDescriptor<Solution_> variableDescriptor, Object element);
+
+ /**
+ * Notify the score director before a list variable changes.
+ * <p>
+ * The list variable change includes:
+ * <ul>
+ * <li>Changing position (index) of one or more elements.</li>
+ * <li>Removing one or more elements from the list variable.</li>
+ * <li>Adding one or more elements to the list variable.</li>
+ * <li>Any mix of the above.</li>
+ * </ul>
+ * For the sake of variable listeners' efficiency, the change notification requires an index range that contains elements
+ * affected by the change. The range starts at {@code fromIndex} (inclusive) and ends at {@code toIndex} (exclusive).
+ * <p>
+ * The range has to comply with the following contract:
+ * <ol>
+ * <li>{@code fromIndex} must be greater than or equal to 0; {@code toIndex} must be less than or equal to the list variable
+ * size.</li>
+ * <li>{@code toIndex} must be greater than or equal to {@code fromIndex}.</li>
+ * <li>The range must contain all elements that are going to be changed.</li>
+ * <li>The range is allowed to contain elements that are not going to be changed.</li>
+ * <li>The range may be empty ({@code fromIndex} equals {@code toIndex}) if none of the existing list variable elements
+ * are going to be changed.</li>
+ * </ol>
+ * <p>
+ * {@link #beforeListVariableElementUnassigned(ListVariableDescriptor, Object)} must be called for each element
+ * that will be unassigned (removed from a list variable of one entity without being added
+ * to a list variable of another entity).
+ *
+ * @param variableDescriptor descriptor of the list variable being changed
+ * @param entity the entity owning the list variable being changed
+ * @param fromIndex low endpoint (inclusive) of the changed range
+ * @param toIndex high endpoint (exclusive) of the changed range
+ */
+ void beforeListVariableChanged(ListVariableDescriptor<Solution_> variableDescriptor, Object entity, int fromIndex,
+ int toIndex);
+
+ /**
+ * Notify the score director after a list variable changes.
+ * <p>
+ * The list variable change includes:
+ * <ul>
+ * <li>Changing position (index) of one or more elements.</li>
+ * <li>Removing one or more elements from the list variable.</li>
+ * <li>Adding one or more elements to the list variable.</li>
+ * <li>Any mix of the above.</li>
+ * </ul>
+ * For the sake of variable listeners' efficiency, the change notification requires an index range that contains elements
+ * affected by the change. The range starts at {@code fromIndex} (inclusive) and ends at {@code toIndex} (exclusive).
+ * <p>
+ * The range has to comply with the following contract:
+ * <ol>
+ * <li>{@code fromIndex} must be greater than or equal to 0; {@code toIndex} must be less than or equal to the list variable
+ * size.</li>
+ * <li>{@code toIndex} must be greater than or equal to {@code fromIndex}.</li>
+ * <li>The range must contain all elements that have changed.</li>
+ * <li>The range is allowed to contain elements that have not changed.</li>
+ * <li>The range may be empty ({@code fromIndex} equals {@code toIndex}) if none of the existing list variable elements
+ * have changed.</li>
+ * </ol> | For `AbstractEasyMove`, there are additional restrictions on `beforeListVariableChange` and `afterListVariableChanged`. In particular:
- The `fromIndex` of `afterListVariableChanged` must match the `fromIndex` of its `beforeListVariableChanged` call. Otherwise this will happen in the undo move
```
// beforeListVariableChanged(0, 3);
[1, 2, 3, 4]
change
[1, 2, 3]
// afterListVariableChanged(2, 3)
// Start Undo
// Undo afterListVariableChanged(2, 3)
[1, 2, 3] -> [1, 2]
// Undo beforeListVariableChanged(0, 3);
[1, 2, 3, 4, 1, 2]
```
`VariableChangeRecordingScoreDirector` should be able to detect this. In particular, instead of creating the `ListVariableAfterChangeAction` using the `fromIndex` from the `afterListVariableChanged` call, it will use the `fromIndex` from the `beforeListVariableChanged` call (by tracking it in an identity hash map using the entity as key). |
timefold-solver | github_2023 | java | 573 | TimefoldAI | Christopher-Chianelli | @@ -451,29 +477,26 @@ private void createEffectivePlanningPinIndexReader() {
effectivePlanningPinToIndexReader = null;
return;
}
-
- var listVariableDescriptor = getGenuineListVariableDescriptor();
- var planningListVariableReader = new Function<Object, List<?>>() {
-
- @Override
- public List<?> apply(Object o) {
- return (List<?>) listVariableDescriptor.getValue(o);
- }
- };
-
var planningPinIndexMemberAccessorList = new ArrayList<MemberAccessor>();
for (EntityDescriptor<Solution_> inheritedEntityDescriptor : inheritedEntityDescriptorList) {
if (inheritedEntityDescriptor.effectivePlanningPinToIndexReader != null) {
planningPinIndexMemberAccessorList.addAll(inheritedEntityDescriptor.declaredPlanningPinIndexMemberAccessorList);
}
}
planningPinIndexMemberAccessorList.addAll(declaredPlanningPinIndexMemberAccessorList);
-
- if (planningPinIndexMemberAccessorList.isEmpty()) {
- effectivePlanningPinToIndexReader = null;
- } else {
- effectivePlanningPinToIndexReader = new PlanningPinToIndexReader<>(effectiveMovableEntitySelectionFilter,
- planningListVariableReader, planningPinIndexMemberAccessorList.toArray(MemberAccessor[]::new));
+ switch (planningPinIndexMemberAccessorList.size()) {
+ case 0: | Style: we can use `->` switch statement/expressions:
```
switch (planningPinIndexMemberAccessorList.size()) {
case 0 -> {
// ...
}
}
``` |
timefold-solver | github_2023 | java | 573 | TimefoldAI | Christopher-Chianelli | @@ -52,50 +51,50 @@ public <Node_> EntityOrderInfo withNewNode(Node_ node, ListVariableDescriptor<?>
}
@SuppressWarnings("unchecked")
- public <Node_> Node_ successor(Node_ object, ListVariableDescriptor<?> listVariableDescriptor,
- IndexVariableSupply indexVariableSupply, SingletonInverseVariableSupply inverseVariableSupply) {
- var entity = inverseVariableSupply.getInverseSingleton(object);
- var indexInEntityList = indexVariableSupply.getIndex(object);
- var listVariable = listVariableDescriptor.getListVariable(entity);
+ public <Node_> Node_ successor(Node_ object, ListVariableStateSupply<?> listVariableStateSupply) {
+ var listVariableDescriptor = listVariableStateSupply.getSourceVariableDescriptor();
+ var elementLocation = (LocationInList) listVariableStateSupply.getLocationInList(object);
+ var entity = elementLocation.entity();
+ var indexInEntityList = elementLocation.index();
+ var listVariable = listVariableDescriptor.getValue(entity);
if (indexInEntityList == listVariable.size() - 1) {
var nextEntityIndex = (entityToEntityIndex.get(entity) + 1) % entities.length;
var nextEntity = entities[nextEntityIndex];
- var firstUnpinnedIndexInList = listVariableDescriptor.getEntityDescriptor()
- .extractFirstUnpinnedIndex(nextEntity);
- return (Node_) listVariableDescriptor.getListVariable(nextEntity)
- .get(firstUnpinnedIndexInList);
+ var firstUnpinnedIndexInList = listVariableDescriptor.getFirstUnpinnedIndex(nextEntity);
+ return (Node_) listVariableDescriptor.getElement(nextEntity, firstUnpinnedIndexInList);
} else {
return (Node_) listVariable.get(indexInEntityList + 1);
}
}
@SuppressWarnings("unchecked")
- public <Node_> Node_ predecessor(Node_ object, ListVariableDescriptor<?> listVariableDescriptor,
- IndexVariableSupply indexVariableSupply, SingletonInverseVariableSupply inverseVariableSupply) {
- var entity = inverseVariableSupply.getInverseSingleton(object);
- var indexInEntityList = indexVariableSupply.getIndex(object);
- var firstUnpinnedIndexInList = listVariableDescriptor.getEntityDescriptor()
- .extractFirstUnpinnedIndex(entity);
- var listVariable = listVariableDescriptor.getListVariable(entity);
+ public <Node_> Node_ predecessor(Node_ object, ListVariableStateSupply<?> listVariableStateSupply) {
+ var listVariableDescriptor = listVariableStateSupply.getSourceVariableDescriptor();
+ var elementLocation = (LocationInList) listVariableStateSupply.getLocationInList(object);
+ var entity = elementLocation.entity();
+ var indexInEntityList = elementLocation.index();
+ var firstUnpinnedIndexInList = listVariableDescriptor.getFirstUnpinnedIndex(entity);
if (indexInEntityList == firstUnpinnedIndexInList) {
// add entities.length to ensure modulo result is positive
int previousEntityIndex = (entityToEntityIndex.get(entity) - 1 + entities.length) % entities.length;
- listVariable = listVariableDescriptor.getListVariable(entities[previousEntityIndex]);
+ var listVariable = listVariableDescriptor.getValue(entities[previousEntityIndex]); | An selected entity has at least one unpinned index, right? |
timefold-solver | github_2023 | others | 573 | TimefoldAI | Christopher-Chianelli | @@ -12,12 +12,57 @@ recipeList:
oldPropertyKey: quarkus.timefold.solver.solve-length
newPropertyKey: quarkus.timefold.solver.solve.duration
fileMatcher: '**/application.properties'
+ - org.openrewrite.java.ChangeMethodName: | I don't see a corresponding open-rewrite test |
timefold-solver | github_2023 | java | 609 | TimefoldAI | triceo | @@ -0,0 +1,419 @@
+package ai.timefold.solver.spring.boot.autoconfigure.util;
+
+import java.lang.reflect.Array;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.lang.reflect.RecordComponent;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.IdentityHashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import ai.timefold.solver.core.impl.domain.common.ReflectionHelper;
+
+import org.apache.commons.text.StringEscapeUtils;
+import org.springframework.javapoet.CodeBlock;
+import org.springframework.javapoet.TypeSpec;
+
+public final class PojoInliner { | I think that this is a bad idea. This is a piece of code which we shouldn't be implementing; serialization is a well understood problem, it has security implications if done wrong, and there are libraries who will do it better than we can.
Solver config is fully serializable to XML. If we have to do crazy things, let's do crazy things to make XML work - because config serialization to and from XML is tried and tested, we do it all the time, and the mechanics of it are someone else's problem. |
timefold-solver | github_2023 | java | 609 | TimefoldAI | triceo | @@ -0,0 +1,200 @@
+package ai.timefold.solver.spring.boot.autoconfigure;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.lang.model.element.Modifier;
+
+import ai.timefold.solver.core.api.solver.SolverFactory;
+import ai.timefold.solver.core.api.solver.SolverManager;
+import ai.timefold.solver.core.config.solver.SolverConfig;
+import ai.timefold.solver.core.config.solver.SolverManagerConfig;
+import ai.timefold.solver.spring.boot.autoconfigure.config.SolverManagerProperties;
+import ai.timefold.solver.spring.boot.autoconfigure.config.TimefoldProperties;
+import ai.timefold.solver.spring.boot.autoconfigure.util.PojoInliner;
+
+import org.springframework.aot.generate.DefaultMethodReference;
+import org.springframework.aot.generate.GeneratedClass;
+import org.springframework.aot.generate.GenerationContext;
+import org.springframework.aot.hint.MemberCategory;
+import org.springframework.aot.hint.ReflectionHints;
+import org.springframework.beans.factory.aot.BeanFactoryInitializationAotContribution;
+import org.springframework.beans.factory.aot.BeanFactoryInitializationCode;
+import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
+import org.springframework.boot.context.properties.bind.BindResult;
+import org.springframework.boot.context.properties.bind.Binder;
+import org.springframework.core.env.Environment;
+import org.springframework.javapoet.CodeBlock;
+import org.springframework.javapoet.MethodSpec;
+
+public class TimefoldAotContribution implements BeanFactoryInitializationAotContribution { | Let's find a better name for this class. I'm not sure why it's called "contribution", and it should be `TimefoldSolver`, not `Timefold`. |
timefold-solver | github_2023 | java | 609 | TimefoldAI | triceo | @@ -0,0 +1,204 @@
+package ai.timefold.solver.spring.boot.autoconfigure;
+
+import java.util.function.BiFunction;
+
+import ai.timefold.solver.core.api.score.Score;
+import ai.timefold.solver.core.api.score.ScoreManager;
+import ai.timefold.solver.core.api.score.stream.Constraint;
+import ai.timefold.solver.core.api.score.stream.ConstraintFactory;
+import ai.timefold.solver.core.api.score.stream.ConstraintProvider;
+import ai.timefold.solver.core.api.score.stream.ConstraintStreamImplType;
+import ai.timefold.solver.core.api.solver.SolutionManager;
+import ai.timefold.solver.core.api.solver.SolverFactory;
+import ai.timefold.solver.core.api.solver.SolverManager;
+import ai.timefold.solver.core.config.score.director.ScoreDirectorFactoryConfig;
+import ai.timefold.solver.core.config.solver.SolverConfig;
+import ai.timefold.solver.core.config.solver.SolverManagerConfig;
+import ai.timefold.solver.jackson.api.TimefoldJacksonModule;
+import ai.timefold.solver.spring.boot.autoconfigure.config.SolverManagerProperties;
+import ai.timefold.solver.spring.boot.autoconfigure.config.TimefoldProperties;
+import ai.timefold.solver.test.api.score.stream.ConstraintVerifier;
+import ai.timefold.solver.test.api.score.stream.MultiConstraintVerification;
+import ai.timefold.solver.test.api.score.stream.SingleConstraintVerification;
+
+import org.springframework.beans.BeansException;
+import org.springframework.beans.factory.BeanCreationException;
+import org.springframework.beans.factory.aot.BeanFactoryInitializationAotProcessor;
+import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
+import org.springframework.boot.autoconfigure.AutoConfigureAfter;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.context.properties.bind.BindResult;
+import org.springframework.boot.context.properties.bind.Binder;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.ApplicationContextAware;
+import org.springframework.context.EnvironmentAware;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Lazy;
+import org.springframework.core.env.Environment;
+import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
+
+import com.fasterxml.jackson.databind.Module;
+
+/**
+ * Must be seperated from {@link TimefoldAutoConfiguration} since
+ * {@link TimefoldAutoConfiguration} will not be available at runtime
+ * for a native image (since it is a {@link BeanFactoryInitializationAotProcessor}/
+ * {@link BeanFactoryPostProcessor}).
+ */
+@Configuration
+public class TimefoldBeanFactory implements ApplicationContextAware, EnvironmentAware {
+ private ApplicationContext context;
+ private TimefoldProperties timefoldProperties;
+
+ @Override
+ public void setApplicationContext(ApplicationContext context) throws BeansException {
+ this.context = context;
+ }
+
+ @Override
+ public void setEnvironment(Environment environment) {
+ // We need the environment to set run time properties of SolverFactory and SolverManager
+ BindResult<TimefoldProperties> result = Binder.get(environment).bind("timefold", TimefoldProperties.class);
+ this.timefoldProperties = result.orElseGet(TimefoldProperties::new);
+ }
+
+ private void failInjectionWithMultipleSolvers(String resourceName) {
+ if (timefoldProperties.getSolver() != null && timefoldProperties.getSolver().size() > 1) {
+ throw new BeanCreationException(
+ "No qualifying bean of type '%s' available".formatted(resourceName));
+ }
+ }
+
+ @Bean
+ @Lazy
+ public TimefoldSolverBannerBean getBanner() {
+ return new TimefoldSolverBannerBean();
+ }
+
+ @Bean
+ @Lazy
+ @ConditionalOnMissingBean
+ public <Solution_> SolverFactory<Solution_> getSolverFactory() {
+ failInjectionWithMultipleSolvers(SolverFactory.class.getName());
+ SolverConfig solverConfig = context.getBean(SolverConfig.class);
+ if (solverConfig == null || solverConfig.getSolutionClass() == null) {
+ return null;
+ }
+ return SolverFactory.create(solverConfig);
+ }
+
+ @Bean
+ @Lazy
+ @ConditionalOnMissingBean
+ public <Solution_, ProblemId_> SolverManager<Solution_, ProblemId_> solverManager(SolverFactory solverFactory) {
+ // TODO supply ThreadFactory
+ if (solverFactory == null) {
+ return null;
+ }
+ SolverManagerConfig solverManagerConfig = new SolverManagerConfig();
+ SolverManagerProperties solverManagerProperties = timefoldProperties.getSolverManager();
+ if (solverManagerProperties != null && solverManagerProperties.getParallelSolverCount() != null) {
+ solverManagerConfig.setParallelSolverCount(solverManagerProperties.getParallelSolverCount());
+ }
+ return SolverManager.create(solverFactory, solverManagerConfig);
+ }
+
+ @Bean
+ @Lazy
+ @ConditionalOnMissingBean
+ @Deprecated(forRemoval = true)
+ public <Solution_, Score_ extends Score<Score_>> ScoreManager<Solution_, Score_> scoreManager() {
+ failInjectionWithMultipleSolvers(ScoreManager.class.getName());
+ SolverFactory solverFactory = context.getBean(SolverFactory.class);
+ if (solverFactory == null) {
+ return null;
+ }
+ return ScoreManager.create(solverFactory);
+ }
+
+ @Bean
+ @Lazy
+ @ConditionalOnMissingBean
+ public <Solution_, Score_ extends Score<Score_>> SolutionManager<Solution_, Score_> solutionManager() {
+ failInjectionWithMultipleSolvers(SolutionManager.class.getName());
+ SolverFactory solverFactory = context.getBean(SolverFactory.class);
+ if (solverFactory == null) {
+ return null;
+ }
+ return SolutionManager.create(solverFactory);
+ }
+
+ // @Bean wrapped by static class to avoid classloading issues if dependencies are absent
+ @ConditionalOnClass({ ConstraintVerifier.class })
+ @ConditionalOnMissingBean({ ConstraintVerifier.class })
+ @AutoConfigureAfter(TimefoldAutoConfiguration.class)
+ class TimefoldConstraintVerifierConfiguration {
+
+ private final ApplicationContext context;
+
+ protected TimefoldConstraintVerifierConfiguration(ApplicationContext context) {
+ this.context = context;
+ }
+
+ @Bean
+ @Lazy
+ @SuppressWarnings("unchecked")
+ <ConstraintProvider_ extends ConstraintProvider, SolutionClass_>
+ ConstraintVerifier<ConstraintProvider_, SolutionClass_> constraintVerifier() {
+ // Using SolverConfig as an injected parameter here leads to an injection failure on an empty app,
+ // so we need to get the SolverConfig from context
+ failInjectionWithMultipleSolvers(ConstraintProvider.class.getName());
+ SolverConfig solverConfig;
+ try {
+ solverConfig = context.getBean(SolverConfig.class);
+ } catch (BeansException exception) {
+ solverConfig = null;
+ }
+
+ ScoreDirectorFactoryConfig scoreDirectorFactoryConfig =
+ (solverConfig != null) ? solverConfig.getScoreDirectorFactoryConfig() : null;
+ if (scoreDirectorFactoryConfig == null || scoreDirectorFactoryConfig.getConstraintProviderClass() == null) {
+ // Return a mock ConstraintVerifier so not having ConstraintProvider doesn't crash tests
+ // (Cannot create custom condition that checks SolverConfig, since that
+ // requires TimefoldAutoConfiguration to have a no-args constructor)
+ final String noConstraintProviderErrorMsg = (scoreDirectorFactoryConfig != null)
+ ? "Cannot provision a ConstraintVerifier because there is no ConstraintProvider class."
+ : "Cannot provision a ConstraintVerifier because there is no PlanningSolution or PlanningEntity classes.";
+ return new ConstraintVerifier<>() { | Let's make this a proper class, inner if you prefer; reads better in stack traces and profiler results. |
timefold-solver | github_2023 | java | 609 | TimefoldAI | triceo | @@ -0,0 +1,419 @@
+package ai.timefold.solver.spring.boot.autoconfigure.util;
+
+import java.lang.reflect.Array;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.lang.reflect.RecordComponent;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.IdentityHashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import ai.timefold.solver.core.impl.domain.common.ReflectionHelper;
+
+import org.apache.commons.text.StringEscapeUtils;
+import org.springframework.javapoet.CodeBlock;
+import org.springframework.javapoet.TypeSpec;
+
+public final class PojoInliner {
+ static final String COMPLEX_POJO_MAP_FIELD_NAME = "$pojoMap";
+ private final Map<Object, String> complexPojoToIdentifier = new IdentityHashMap<>();
+ private final Set<Object> possibleCircularRecordReferenceSet = Collections.newSetFromMap(new IdentityHashMap<>());
+ private final CodeBlock.Builder initializerBuilder;
+
+ // The code below uses CodeBlock.Builder to generate the Java file
+ // that stores the SolverConfig.
+ // CodeBlock.Builder.add supports different kinds of formatting args.
+ // The ones we use are:
+ // - $L: Format as is (i.e. literal replacement).
+ // - $S: Format as a Java String, doing the necessary escapes
+ // and surrounding it by double quotes.
+ // - $T: Format as a fully qualified type, which allows you to use
+ // classes without importing them.
+ PojoInliner() {
+ this.initializerBuilder = CodeBlock.builder();
+ initializerBuilder.add("$T $L = new $T();", Map.class, COMPLEX_POJO_MAP_FIELD_NAME, HashMap.class);
+ }
+
+ public record PojoField(Class<?> type, String name, Object value) {
+ }
+
+ public static PojoField field(Class<?> type, String name, Object value) {
+ return new PojoField(type, name, value);
+ }
+
+ public static void inlineFields(TypeSpec.Builder typeBuilder, PojoField... fields) {
+ PojoInliner inliner = new PojoInliner();
+ for (PojoField field : fields) {
+ typeBuilder.addField(field.type(), field.name,
+ javax.lang.model.element.Modifier.PRIVATE,
+ javax.lang.model.element.Modifier.STATIC,
+ javax.lang.model.element.Modifier.FINAL);
+ }
+ for (PojoField field : fields) {
+ inliner.inlineField(field.name(), field.value());
+ }
+ inliner.initializerBuilder.add("\n");
+ typeBuilder.addStaticBlock(inliner.initializerBuilder.build());
+ }
+
+ void inlineField(String fieldName, Object fieldValue) {
+ initializerBuilder.add("\n$L = $L;", fieldName, getInlinedPojo(fieldValue));
+ }
+
+ /**
+ * Serializes a Pojo to code that uses its no-args constructor
+ * and setters to create the object.
+ *
+ * @param pojo The object to be serialized.
+ * @return A string that can be used in a {@link CodeBlock.Builder} to access the object
+ */
+ String getInlinedPojo(Object pojo) {
+ // First, check for primitives
+ if (pojo == null) {
+ return "null";
+ }
+ if (pojo instanceof Boolean value) {
+ return value.toString();
+ }
+ if (pojo instanceof Byte value) {
+ // Cast to byte
+ return "((byte) " + value + ")";
+ }
+ if (pojo instanceof Character value) {
+ return "'\\u" + Integer.toHexString(value | 0x10000).substring(1) + "'";
+ }
+ if (pojo instanceof Short value) {
+ // Cast to short
+ return "((short) " + value + ")";
+ }
+ if (pojo instanceof Integer value) {
+ return value.toString();
+ }
+ if (pojo instanceof Long value) {
+ // Add long suffix to number string
+ return value + "L";
+ }
+ if (pojo instanceof Float value) {
+ // Add float suffix to number string
+ return value + "f";
+ }
+ if (pojo instanceof Double value) {
+ // Add double suffix to number string
+ return value + "d";
+ }
+
+ // Check for builtin classes
+ if (pojo instanceof String value) {
+ return "\"" + StringEscapeUtils.escapeJava(value) + "\"";
+ }
+ if (pojo instanceof Class<?> value) {
+ if (!Modifier.isPublic(value.getModifiers())) {
+ throw new IllegalArgumentException("Cannot serialize (" + value + ") because it is not a public class."); | ```suggestion
throw new IllegalArgumentException("Cannot serialize (%s) because it is not a public class."
.formatted(value));
```
Let's consistently apply this convention in new code.
It makes for messages that are easier to read, especially as the number of arguments grows. |
timefold-solver | github_2023 | java | 609 | TimefoldAI | triceo | @@ -0,0 +1,25 @@
+package ai.timefold.solver.spring.boot.it;
+
+import ai.timefold.solver.core.api.solver.SolverFactory;
+import ai.timefold.solver.spring.boot.it.domain.IntegrationTestSolution;
+
+import org.springframework.http.MediaType;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+@RequestMapping("/integration-test")
+public class TimefoldController { | Timefold is a company; we have Solver, we have Orbit. Let's start using `TimefoldSolver` consistently, because we're dealing with the solver here, not with the company. |
timefold-solver | github_2023 | java | 618 | TimefoldAI | Christopher-Chianelli | @@ -10,50 +10,28 @@
import ai.timefold.solver.core.api.score.buildin.simple.SimpleScore;
import ai.timefold.solver.core.api.score.calculator.ConstraintMatchAwareIncrementalScoreCalculator;
-import ai.timefold.solver.core.api.score.constraint.ConstraintMatch;
import ai.timefold.solver.core.api.score.constraint.ConstraintMatchTotal;
import ai.timefold.solver.core.api.score.constraint.ConstraintRef;
import ai.timefold.solver.core.api.score.constraint.Indictment;
import ai.timefold.solver.core.impl.score.constraint.DefaultConstraintMatchTotal;
import ai.timefold.solver.core.impl.score.constraint.DefaultIndictment;
import ai.timefold.solver.core.impl.testdata.domain.TestdataValue;
-public final class TestdataNullableIncrementalScoreCalculator
+public class TestdataNullableIncrementalScoreCalculator
implements ConstraintMatchAwareIncrementalScoreCalculator<TestdataNullableSolution, SimpleScore> {
- private int score = 0;
- private DefaultConstraintMatchTotal<SimpleScore> constraintMatchTotal;
+ private TestdataNullableSolution workingSolution;
private Map<Object, Indictment<SimpleScore>> indictmentMap;
@Override
public void resetWorkingSolution(TestdataNullableSolution workingSolution) {
- score = 0; | Why was this change necessary? |
timefold-solver | github_2023 | java | 103 | TimefoldAI | ge0ffrey | @@ -992,9 +1020,11 @@ public long getMaximumValueCount(Solution_ solution) {
}
/**
+ * @deprecated This was never implemented; any code that depends on this will throw {@link UnsupportedOperationException}.
* @param solution never null
* @return {@code >= 0}
*/
+ @Deprecated(forRemoval = true, since = "1.0.0")
public int getValueCount(Solution_ solution) { | SolutionDescription isn't public API nor documention nor really know.
I'd just remove the method instead of deprecating it. |
timefold-solver | github_2023 | java | 103 | TimefoldAI | ge0ffrey | @@ -838,6 +839,12 @@ public void validateConstraintWeight(String constraintPackage, String constraint
// Extraction methods
// ************************************************************************
+ public Collection<Object> getAllEntities(Solution_ solution) { | Is this method used somewhere in the new code? |
timefold-solver | github_2023 | java | 173 | TimefoldAI | ge0ffrey | @@ -24,6 +24,22 @@ protected void validateCacheTypeVersusSelectionOrder(SelectionCacheType resolved
break;
case SORTED:
case SHUFFLED: | step caching with shuffled is a theoretically possible use case, no?
You generate all your moves at the beginning of a step (because you can't do it at phase cache because the generated moves change depending on the variables state), and then you want to go through them shuffled (unlike random get every element at most once).
Sorted has the same logic, no? |
timefold-solver | github_2023 | java | 614 | TimefoldAI | Christopher-Chianelli | @@ -42,13 +42,30 @@ protected Move<Solution_> createUpcomingSelection() {
}
Object upcomingValue = valueIterator.next();
- ElementRef destination = destinationIterator.next();
-
+ ElementRef destination = findUnpinnedDestination(destinationIterator, listVariableDescriptor);
+ if (destination == null) {
+ return noUpcomingSelection();
+ }
return new ListChangeMove<>(
listVariableDescriptor,
inverseVariableSupply.getInverseSingleton(upcomingValue),
indexVariableSupply.getIndex(upcomingValue),
destination.entity(),
destination.index());
}
+
+ public static ElementRef findUnpinnedDestination(Iterator<ElementRef> destinationIterator, | Should this be a static method in `UpcomingSelectionIterator`? |
timefold-solver | github_2023 | others | 611 | TimefoldAI | triceo | @@ -161,18 +161,19 @@ However, in exam timetabling, that is allowed, if there is enough seating capaci
Assigning humans to start a meeting at four seconds after 9 o'clock is pointless because most human activities have a time granularity of five minutes or 15 minutes.
Therefore it is not necessary to allow a planning entity to be assigned subsecond, second or even one minute accuracy.
-The five minute or 15 minutes accuracy suffices.
+A granularity of 15 minutes, 1 hour or 1 day accuracy suffices for most use cases.
The TimeGrain pattern models such *time accuracy* by partitioning time as time grains.
For example in xref:use-cases-and-examples/meeting-scheduling/meeting-scheduling.adoc#meetingScheduling[meeting scheduling], all meetings start/end in hour, half hour, or 15-minute intervals before or after each hour, therefore the optimal settings for time grains is 15 minutes.
Each planning entity is assigned to a start time grain.
The end time grain is calculated by adding the duration in grains to the starting time grain.
Overlap of two entities is determined by comparing their start and end time grains.
-This pattern also works well with a coarser time granularity (such as days, half days, hours, ...).
-With a finer time granularity (such as seconds, milliseconds, ...) and a long time window, the value range (and therefore xref:optimization-algorithms/optimization-algorithms.adoc#searchSpaceSize[the search space]) can become too high, which reduces efficiency and scalability.
-However, such a solution is not impossible.
-
+*The TimeGrain pattern doesn't scale well*.
+Especially with a finer time granularity (such as 1 minute) and a long planning window,
+the value range (and therefore xref:optimization-algorithms/optimization-algorithms.adoc#searchSpaceSize[the search space]) is too big to scale well.
+It's recommend to use a coarse time granularity (such as 1 week, 1 day, 1 half day, ...) or shorten the planning window size to scale. | ```suggestion
It's recommended to use a coarse time granularity (such as 1 week, 1 day, 1 half day, ...) or shorten the planning window size to scale.
``` |
timefold-solver | github_2023 | others | 606 | TimefoldAI | triceo | @@ -2673,6 +2673,108 @@ the whole purpose of `MoveIteratorFactory` over `MoveListFactory` is to create a
in a custom ``Iterator.next()``.
====
+For example:
+
+[source,java,options="nowrap"]
+----
+public class PossibleAssignmentsOnlyMoveIteratorFactory implements MoveIteratorFactory<MyPlanningSolution, MyChangeMove> {
+ @Override
+ public long getSize(ScoreDirector<MyPlanningSolution> scoreDirector) {
+ // In this case, we return the exact size, but an estimate can be used
+ // if it too expensive to calculate or unknown
+ long totalSize = 0L;
+ var solution = scoreDirector.getWorkingSolution();
+ for (MyEntity entity : solution.getEntities()) {
+ for (MyPlanningValue value : solution.getValues()) {
+ if (entity.canBeAssigned(value)) {
+ totalSize++;
+ }
+ }
+ }
+ return totalSize;
+ }
+
+ @Override
+ public Iterator<MyChangeMove> createOriginalMoveIterator(ScoreDirector<MyPlanningSolution> scoreDirector) {
+ // Only needed if selectionOrder is ORIGINAL or if it is cached
+ var solution = scoreDirector.getWorkingSolution();
+ var entities = solution.getEntities();
+ var values = solution.getValues();
+ // Assumes each entity has at least one assignable value
+ var firstEntityIndex = 0;
+ var firstValueIndex = 0;
+ while (!entities.get(firstEntityIndex).canBeAssigned(values.get(firstValueIndex))) {
+ firstValueIndex++;
+ }
+
+
+ return new Iterator<>() {
+ int nextEntityIndex = firstEntityIndex;
+ int nextValueIndex = firstValueIndex;
+
+ @Override
+ public boolean hasNext() {
+ return nextEntityIndex < entities.size();
+ }
+
+ @Override
+ public MyChangeMove next() {
+ var selectedEntity = entities.get(nextEntityIndex);
+ var selectedValue = values.get(nextValueIndex);
+ nextValueIndex++;
+ while (nextValueIndex < values.size() && !selectedEntity.canBeAssigned(values.get(nextValueIndex))) {
+ nextValueIndex++;
+ }
+ if (nextValueIndex >= values.size()) {
+ // value list exhausted, go to next entity
+ nextEntityIndex++;
+ if (nextEntityIndex < entities.size()) {
+ nextValueIndex = 0;
+ while (nextValueIndex < values.size() && !entities.get(nextEntityIndex).canBeAssigned(values.get(nextValueIndex))) {
+ // Assumes each entity has at least one assignable value
+ nextValueIndex++;
+ }
+ }
+ }
+ return new MyChangeMove(selectedEntity, selectedValue);
+ }
+ };
+ }
+
+ @Override
+ public Iterator<MyChangeMove> createRandomMoveIterator(ScoreDirector<MyPlanningSolution> scoreDirector,
+ Random workingRandom) {
+ // Not needed if selectionOrder is ORIGINAL or if it is cached
+ var solution = scoreDirector.getWorkingSolution();
+ var entities = solution.getEntities();
+ var values = solution.getValues();
+
+ return new Iterator<>() {
+ @Override
+ public boolean hasNext() {
+ return !entities.isEmpty();
+ }
+
+ @Override
+ public MyChangeMove next() {
+ var selectedEntity = entities.get(workingRandom.nextInt(entities.size()));
+ var selectedValue = values.get(workingRandom.nextInt(values.size()));
+ while (!selectedEntity.canBeAssigned(selectedValue)) {
+ // This assumes there at least one value that can be assigned to the selected entity
+ selectedValue = values.get(workingRandom.nextInt(values.size()));
+ }
+ return new MyChangeMove(selectedEntity, selectedValue);
+ }
+ };
+ }
+}
+----
+
+[NOTE]
+====
+The example above can also be done using <<filteredSelection,filtered selection>>. | ```suggestion
The same effect can also be accomplished using <<filteredSelection,filtered selection>>.
``` |
timefold-solver | github_2023 | java | 540 | TimefoldAI | triceo | @@ -10,4 +22,18 @@ public <Type_> Type_ toKey(int id) {
return (Type_) property;
}
+ @Override
+ public boolean equals(Object o) {
+ if (this == o)
+ return true;
+ if (o == null || getClass() != o.getClass())
+ return false;
+ SingleIndexProperties<?> that = (SingleIndexProperties<?>) o;
+ return Objects.equals(property, that.property);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(property); | This is an anti-pattern.
`Object.hash(...)` is a varargs method, and as such, every invocation creates a needless array that is immediately thrown away. This causes a major performance regression and should never be used on the hot path. |
timefold-solver | github_2023 | java | 540 | TimefoldAI | triceo | @@ -8,6 +10,35 @@
* @param <Key_>
* @param <Value_>
*/
-public record Pair<Key_, Value_>(Key_ key, Value_ value) {
+public class Pair<Key_, Value_> { | This causes Javadoc plugin to fail. The params need to be on the constructor, not on the class. (As it's no longer a record with a canonical constructor.) |
timefold-solver | github_2023 | java | 546 | TimefoldAI | zepfred | @@ -130,8 +128,17 @@ public ScoreAnalysis<Score_> diff(ScoreAnalysis<Score_> other) {
return ConstraintAnalysis.diff(constraintRef, constraintAnalysis, otherConstraintAnalysis);
},
(constraintRef, otherConstraintRef) -> constraintRef,
- TreeMap::new));
+ HashMap::new)); | I wonder if this change could break existing user tests. |
timefold-solver | github_2023 | others | 541 | TimefoldAI | thimmwork | @@ -52,16 +57,61 @@ public class TimetableEasyScoreCalculator implements EasyScoreCalculator<Timetab
}
----
+--
+
+Kotlin::
++
+--
+[source,kotlin]
+----
+class TimetableEasyScoreCalculator : EasyScoreCalculator<Timetable?, HardSoftScore?> { | both Timetable and HardSoftScore should be not-null (no "?"), because the interface's only method will never be called with a null parameter and the returned score should never be null, right? btw sorry to bust in here, and probably being out of line. |
timefold-solver | github_2023 | others | 541 | TimefoldAI | thimmwork | @@ -122,5 +172,150 @@ public class TimetableConstraintProvider implements ConstraintProvider {
}
----
+--
+
+Kotlin::
++
+--
+Create a `src/main/kotlin/org/acme/schooltimetabling/solver/TimetableConstraintProvider.kt` class:
+
+[source,kotlin]
+----
+package org.acme.schooltimetabling.solver
+
+import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore
+import ai.timefold.solver.core.api.score.stream.Constraint
+import ai.timefold.solver.core.api.score.stream.ConstraintFactory
+import ai.timefold.solver.core.api.score.stream.ConstraintProvider
+import ai.timefold.solver.core.api.score.stream.Joiners
+import org.acme.schooltimetabling.domain.Lesson
+import org.acme.schooltimetabling.solver.justifications.RoomConflictJustification
+import org.acme.schooltimetabling.solver.justifications.StudentGroupConflictJustification
+import org.acme.schooltimetabling.solver.justifications.StudentGroupSubjectVarietyJustification
+import org.acme.schooltimetabling.solver.justifications.TeacherConflictJustification
+import org.acme.schooltimetabling.solver.justifications.TeacherRoomStabilityJustification
+import org.acme.schooltimetabling.solver.justifications.TeacherTimeEfficiencyJustification
+import java.time.Duration
+
+class TimeTableConstraintProvider : ConstraintProvider {
+
+ override fun defineConstraints(constraintFactory: ConstraintFactory): Array<Constraint>? { | return type should be not-null (no "?") |
timefold-solver | github_2023 | others | 541 | TimefoldAI | thimmwork | @@ -122,5 +172,150 @@ public class TimetableConstraintProvider implements ConstraintProvider {
}
----
+--
+
+Kotlin::
++
+--
+Create a `src/main/kotlin/org/acme/schooltimetabling/solver/TimetableConstraintProvider.kt` class:
+
+[source,kotlin]
+----
+package org.acme.schooltimetabling.solver
+
+import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore
+import ai.timefold.solver.core.api.score.stream.Constraint
+import ai.timefold.solver.core.api.score.stream.ConstraintFactory
+import ai.timefold.solver.core.api.score.stream.ConstraintProvider
+import ai.timefold.solver.core.api.score.stream.Joiners
+import org.acme.schooltimetabling.domain.Lesson
+import org.acme.schooltimetabling.solver.justifications.RoomConflictJustification
+import org.acme.schooltimetabling.solver.justifications.StudentGroupConflictJustification
+import org.acme.schooltimetabling.solver.justifications.StudentGroupSubjectVarietyJustification
+import org.acme.schooltimetabling.solver.justifications.TeacherConflictJustification
+import org.acme.schooltimetabling.solver.justifications.TeacherRoomStabilityJustification
+import org.acme.schooltimetabling.solver.justifications.TeacherTimeEfficiencyJustification
+import java.time.Duration
+
+class TimeTableConstraintProvider : ConstraintProvider {
+
+ override fun defineConstraints(constraintFactory: ConstraintFactory): Array<Constraint>? {
+ return arrayOf(
+ // Hard constraints
+ roomConflict(constraintFactory),
+ teacherConflict(constraintFactory),
+ studentGroupConflict(constraintFactory),
+ // Soft constraints
+ teacherRoomStability(constraintFactory),
+ teacherTimeEfficiency(constraintFactory),
+ studentGroupSubjectVariety(constraintFactory)
+ )
+ }
+
+ fun roomConflict(constraintFactory: ConstraintFactory): Constraint {
+ // A room can accommodate at most one lesson at the same time.
+ return constraintFactory
+ // Select each pair of 2 different lessons ...
+ .forEachUniquePair(
+ Lesson::class.java,
+ // ... in the same timeslot ...
+ Joiners.equal(Lesson::timeslot),
+ // ... in the same room ...
+ Joiners.equal(Lesson::room)
+ )
+ // ... and penalize each pair with a hard weight.
+ .penalize(HardSoftScore.ONE_HARD)
+ .justifyWith({ lesson1: Lesson, lesson2: Lesson?, score: HardSoftScore? -> | parentheses can be removed as the lambda is the only parameter.
all parameters are not-null in this case, aren't they? removing lesson2's "?" will eliminate the need for not-null casting ("!!") in the next line. Same applies to the justifyWith() calls that follow |
timefold-solver | github_2023 | others | 541 | TimefoldAI | zepfred | @@ -391,19 +395,326 @@ public class TimetableApp {
}
----
+--
+
+Kotlin::
++
+--
+Create the `src/main/kotlin/org/acme/schooltimetabling/TimetableApp.kt` class:
+
+[source,kotlin]
+----
+package org.acme.schooltimetabling
+
+import ai.timefold.solver.core.api.solver.SolverFactory
+import ai.timefold.solver.core.config.solver.SolverConfig
+import org.acme.schooltimetabling.domain.Lesson
+import org.acme.schooltimetabling.domain.Room
+import org.acme.schooltimetabling.domain.Timeslot
+import org.acme.schooltimetabling.domain.Timetable
+import org.acme.schooltimetabling.solver.TimetableConstraintProvider
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+import java.time.DayOfWeek
+import java.time.Duration
+import java.time.LocalTime
+import java.util.Objects
+import java.util.function.Function
+import java.util.stream.Collectors
+
+object TimetableApp {
+ private val LOGGER: Logger = LoggerFactory.getLogger(TimetableApp::class.java)
+
+ @JvmStatic
+ fun main(args: Array<String>) {
+ val solverFactory = SolverFactory.create<Timetable>(
+ SolverConfig()
+ .withSolutionClass(Timetable::class.java)
+ .withEntityClasses(Lesson::class.java)
+ .withConstraintProviderClass(TimetableConstraintProvider::class.java)
+ // The solver runs only for 5 seconds on this small dataset.
+ // It's recommended to run for at least 5 minutes ("5m") otherwise.
+ .withTerminationSpentLimit(Duration.ofSeconds(5))
+ )
+
+ // Load the problem
+ val problem = generateDemoData(DemoData.SMALL)
+
+ // Solve the problem
+ val solver = solverFactory.buildSolver()
+ val solution = solver.solve(problem)
+
+ // Visualize the solution
+ printTimetable(solution)
+ }
+
+ fun generateDemoData(demoData: DemoData): Timetable {
+ val timeslots: MutableList<Timeslot> = ArrayList(10)
+ var nextTimeslotId = 0L
+ timeslots.add(Timeslot(nextTimeslotId++, DayOfWeek.MONDAY, LocalTime.of(8, 30), LocalTime.of(9, 30))) | There is no `id` property for `Timeslot`. We should either update the model class or remove `nextTimeslotId++`. |
timefold-solver | github_2023 | others | 541 | TimefoldAI | zepfred | @@ -391,19 +395,326 @@ public class TimetableApp {
}
----
+--
+
+Kotlin::
++
+--
+Create the `src/main/kotlin/org/acme/schooltimetabling/TimetableApp.kt` class:
+
+[source,kotlin]
+----
+package org.acme.schooltimetabling
+
+import ai.timefold.solver.core.api.solver.SolverFactory
+import ai.timefold.solver.core.config.solver.SolverConfig
+import org.acme.schooltimetabling.domain.Lesson
+import org.acme.schooltimetabling.domain.Room
+import org.acme.schooltimetabling.domain.Timeslot
+import org.acme.schooltimetabling.domain.Timetable
+import org.acme.schooltimetabling.solver.TimetableConstraintProvider
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+import java.time.DayOfWeek
+import java.time.Duration
+import java.time.LocalTime
+import java.util.Objects
+import java.util.function.Function
+import java.util.stream.Collectors
+
+object TimetableApp {
+ private val LOGGER: Logger = LoggerFactory.getLogger(TimetableApp::class.java)
+
+ @JvmStatic
+ fun main(args: Array<String>) {
+ val solverFactory = SolverFactory.create<Timetable>(
+ SolverConfig()
+ .withSolutionClass(Timetable::class.java)
+ .withEntityClasses(Lesson::class.java)
+ .withConstraintProviderClass(TimetableConstraintProvider::class.java)
+ // The solver runs only for 5 seconds on this small dataset.
+ // It's recommended to run for at least 5 minutes ("5m") otherwise.
+ .withTerminationSpentLimit(Duration.ofSeconds(5))
+ )
+
+ // Load the problem
+ val problem = generateDemoData(DemoData.SMALL)
+
+ // Solve the problem
+ val solver = solverFactory.buildSolver()
+ val solution = solver.solve(problem)
+
+ // Visualize the solution
+ printTimetable(solution)
+ }
+
+ fun generateDemoData(demoData: DemoData): Timetable {
+ val timeslots: MutableList<Timeslot> = ArrayList(10)
+ var nextTimeslotId = 0L
+ timeslots.add(Timeslot(nextTimeslotId++, DayOfWeek.MONDAY, LocalTime.of(8, 30), LocalTime.of(9, 30)))
+ timeslots.add(Timeslot(nextTimeslotId++, DayOfWeek.MONDAY, LocalTime.of(9, 30), LocalTime.of(10, 30)))
+ timeslots.add(Timeslot(nextTimeslotId++, DayOfWeek.MONDAY, LocalTime.of(10, 30), LocalTime.of(11, 30)))
+ timeslots.add(Timeslot(nextTimeslotId++, DayOfWeek.MONDAY, LocalTime.of(13, 30), LocalTime.of(14, 30)))
+ timeslots.add(Timeslot(nextTimeslotId++, DayOfWeek.MONDAY, LocalTime.of(14, 30), LocalTime.of(15, 30)))
+
+ timeslots.add(Timeslot(nextTimeslotId++, DayOfWeek.TUESDAY, LocalTime.of(8, 30), LocalTime.of(9, 30)))
+ timeslots.add(Timeslot(nextTimeslotId++, DayOfWeek.TUESDAY, LocalTime.of(9, 30), LocalTime.of(10, 30)))
+ timeslots.add(Timeslot(nextTimeslotId++, DayOfWeek.TUESDAY, LocalTime.of(10, 30), LocalTime.of(11, 30)))
+ timeslots.add(Timeslot(nextTimeslotId++, DayOfWeek.TUESDAY, LocalTime.of(13, 30), LocalTime.of(14, 30)))
+ timeslots.add(Timeslot(nextTimeslotId++, DayOfWeek.TUESDAY, LocalTime.of(14, 30), LocalTime.of(15, 30)))
+ if (demoData == DemoData.LARGE) {
+ timeslots.add(Timeslot(nextTimeslotId++, DayOfWeek.WEDNESDAY, LocalTime.of(8, 30), LocalTime.of(9, 30)))
+ timeslots.add(Timeslot(nextTimeslotId++, DayOfWeek.WEDNESDAY, LocalTime.of(9, 30), LocalTime.of(10, 30)))
+ timeslots.add(Timeslot(nextTimeslotId++, DayOfWeek.WEDNESDAY, LocalTime.of(10, 30), LocalTime.of(11, 30)))
+ timeslots.add(Timeslot(nextTimeslotId++, DayOfWeek.WEDNESDAY, LocalTime.of(13, 30), LocalTime.of(14, 30)))
+ timeslots.add(Timeslot(nextTimeslotId++, DayOfWeek.WEDNESDAY, LocalTime.of(14, 30), LocalTime.of(15, 30)))
+ timeslots.add(Timeslot(nextTimeslotId++, DayOfWeek.THURSDAY, LocalTime.of(8, 30), LocalTime.of(9, 30)))
+ timeslots.add(Timeslot(nextTimeslotId++, DayOfWeek.THURSDAY, LocalTime.of(9, 30), LocalTime.of(10, 30)))
+ timeslots.add(Timeslot(nextTimeslotId++, DayOfWeek.THURSDAY, LocalTime.of(10, 30), LocalTime.of(11, 30)))
+ timeslots.add(Timeslot(nextTimeslotId++, DayOfWeek.THURSDAY, LocalTime.of(13, 30), LocalTime.of(14, 30)))
+ timeslots.add(Timeslot(nextTimeslotId++, DayOfWeek.THURSDAY, LocalTime.of(14, 30), LocalTime.of(15, 30)))
+ timeslots.add(Timeslot(nextTimeslotId++, DayOfWeek.FRIDAY, LocalTime.of(8, 30), LocalTime.of(9, 30)))
+ timeslots.add(Timeslot(nextTimeslotId++, DayOfWeek.FRIDAY, LocalTime.of(9, 30), LocalTime.of(10, 30)))
+ timeslots.add(Timeslot(nextTimeslotId++, DayOfWeek.FRIDAY, LocalTime.of(10, 30), LocalTime.of(11, 30)))
+ timeslots.add(Timeslot(nextTimeslotId++, DayOfWeek.FRIDAY, LocalTime.of(13, 30), LocalTime.of(14, 30)))
+ timeslots.add(Timeslot(nextTimeslotId, DayOfWeek.FRIDAY, LocalTime.of(14, 30), LocalTime.of(15, 30)))
+ }
+
+ val rooms: MutableList<Room> = ArrayList(3)
+ var nextRoomId = 0L
+ rooms.add(Room(nextRoomId++, "Room A")) | There is no `id` property for `Room`. We should either update the model class or remove `nextRoomId++`. |
timefold-solver | github_2023 | others | 541 | TimefoldAI | zepfred | @@ -545,6 +888,56 @@ class TimetableConstraintProviderTest {
}
----
+--
+
+Kotlin::
++
+--
+
+Create the `src/test/kotlin/org/acme/schooltimetabling/solver/TimetableConstraintProviderTest.kt` class:
+
+[source,kotlin]
+----
+package org.acme.schooltimetabling.solver
+
+import ai.timefold.solver.core.api.score.stream.ConstraintFactory
+import ai.timefold.solver.test.api.score.stream.ConstraintVerifier
+import org.acme.schooltimetabling.domain.Lesson
+import org.acme.schooltimetabling.domain.Room
+import org.acme.schooltimetabling.domain.Timeslot
+import org.acme.schooltimetabling.domain.Timetable
+import org.junit.jupiter.api.Test
+import java.time.DayOfWeek
+import java.time.LocalTime
+
+internal class TimetableConstraintProviderTest {
+ var constraintVerifier: ConstraintVerifier<TimetableConstraintProvider, Timetable> = ConstraintVerifier.build(
+ TimetableConstraintProvider(), Timetable::class.java, Lesson::class.java
+ )
+
+ @Test
+ fun roomConflict() {
+ val firstLesson = Lesson(1, "Subject1", "Teacher1", "Group1", TIMESLOT1, ROOM1)
+ val conflictingLesson = Lesson(2, "Subject2", "Teacher2", "Group2", TIMESLOT1, ROOM1)
+ val nonConflictingLesson = Lesson(3, "Subject3", "Teacher3", "Group3", TIMESLOT2, ROOM1)
+ constraintVerifier.verifyThat { obj: TimetableConstraintProvider, constraintFactory: ConstraintFactory? ->
+ obj.roomConflict(
+ constraintFactory
+ )
+ }
+ .given(firstLesson, conflictingLesson, nonConflictingLesson)
+ .penalizesBy(1)
+ }
+
+ companion object {
+ private val ROOM1 = Room(1, "Room1") | Same `id` issue for `Room` and `Timeslot`. |
timefold-solver | github_2023 | others | 541 | TimefoldAI | zepfred | @@ -692,6 +1091,9 @@ application {
----
After building the project, you can find an archive with a runnable application inside the `build/distributions/` directory.
+-- | Let's make it consistent with Maven:
```
After building the project, you can find an archive with a runnable application inside the `build/libs/` directory.
[source,options="nowrap"]
----
$ gradle build
...
$ java -jar build/libs/hello-world-1.0-SNAPSHOT.jar
----
``` |
timefold-solver | github_2023 | java | 536 | TimefoldAI | zepfred | @@ -111,6 +120,96 @@ void solve() {
assertThat(solution.getScore().isSolutionInitialized()).isTrue();
}
+ @Test | Nice! |
timefold-solver | github_2023 | java | 536 | TimefoldAI | zepfred | @@ -865,4 +964,74 @@ void solveWithMultipleChainedPlanningEntities() {
assertThat(solution.getScore().isSolutionInitialized()).isTrue();
}
+ public static class CorruptedEasyScoreCalculator implements EasyScoreCalculator<TestdataSolution, SimpleScore> { | Mocking this class would make the test simpler. |
timefold-solver | github_2023 | java | 536 | TimefoldAI | zepfred | @@ -865,4 +964,74 @@ void solveWithMultipleChainedPlanningEntities() {
assertThat(solution.getScore().isSolutionInitialized()).isTrue();
}
+ public static class CorruptedEasyScoreCalculator implements EasyScoreCalculator<TestdataSolution, SimpleScore> {
+
+ @Override
+ public SimpleScore calculateScore(TestdataSolution testdataSolution) {
+ int random = (int) (Math.random() * 1000);
+ return SimpleScore.of(random);
+ }
+ }
+
+ public static class CorruptedIncrementalScoreCalculator | Same mocking idea as above. |
timefold-solver | github_2023 | others | 538 | TimefoldAI | rsynek | @@ -0,0 +1,38 @@
+#!/bin/bash
+
+# Expects the following environment variables to be set:
+# $SPRING_INITIALIZR_YAML_FILE_PATH (Example: "application.yml")
+# $TIMEFOLD_SOLVER_VERSION (Example: "1.6.0")
+
+# Temporary file
+temp_file="temp.yml"
+
+# Flag to indicate if the 'timefold-solver' keyword is found
+found_keyword=false
+
+# Read the YAML file line by line
+while IFS= read -r line | After looking at the `application.yaml` I finally understand why this loop cannot be just a simple `sed` command (all hail the yaml files). |
timefold-solver | github_2023 | others | 494 | TimefoldAI | triceo | @@ -604,7 +601,7 @@ In Maven, add the following to your `pom.xml`:
...
<build>
<plugins>
- <plugin>
+ <plugin> | The formatting doesn't seem right here. The indent should be two spaces, no? |
timefold-solver | github_2023 | others | 494 | TimefoldAI | triceo | @@ -61,7 +61,6 @@ public class Timeslot {
----
Because no `Timeslot` instances change during solving, a `Timeslot` is called a _problem fact_.
-Such classes do not require any Timefold Solver specific annotations. | Any reason why you're removing this line? |
timefold-solver | github_2023 | others | 494 | TimefoldAI | triceo | @@ -627,33 +639,33 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
@SpringBootTest(properties = {
"timefold.solver.termination.spent-limit=1h", // Effectively disable this termination in favor of the best-score-limit
"timefold.solver.termination.best-score-limit=0hard/*soft"})
-public class TimeTableControllerTest {
+public class TimetableControllerTest {
@Autowired
- private TimeTableController timeTableController;
+ private TimetableController timetableController;
@Test
@Timeout(600_000)
public void solveDemoDataUntilFeasible() throws InterruptedException {
- timeTableController.solve();
- TimeTable timeTable = timeTableController.getTimeTable();
- while (timeTable.getSolverStatus() != SolverStatus.NOT_SOLVING) {
+ timetableController.solve();
+ Timetable timetable = timetableController.getTimetable();
+ while (timetable.getSolverStatus() != SolverStatus.NOT_SOLVING) {
// Quick polling (not a Test Thread Sleep anti-pattern)
// Test is still fast on fast machines and doesn't randomly fail on slow machines.
Thread.sleep(20L);
- timeTable = timeTableController.getTimeTable();
+ timetable = timetableController.getTimetable();
}
- assertFalse(timeTable.getLessonList().isEmpty());
- for (Lesson lesson : timeTable.getLessonList()) {
+ assertFalse(timetable.getLessonList().isEmpty());
+ for (Lesson lesson : timetable.getLessonList()) {
assertNotNull(lesson.getTimeslot());
assertNotNull(lesson.getRoom());
}
- assertTrue(timeTable.getScore().isFeasible());
+ assertTrue(timetable.getScore().isFeasible());
}
}
----
. Build an attractive web UI on top of these REST methods to visualize the timetable.
-Take a look at {spring-boot-quickstart-url}[the quickstart source code] to see how this all turns out.
+For an implementation with UI-integrated and in-memory storage, check out {spring-boot-quickstart-url}[the Spring-boot quickstart source code]. | ```suggestion
For a full implementation with a web UI and in-memory storage, check out {spring-boot-quickstart-url}[the Spring-boot quickstart source code].
``` |
timefold-solver | github_2023 | java | 484 | TimefoldAI | triceo | @@ -695,14 +695,18 @@ public void assertExpectedUndoMoveScore(Move<Solution_> move, Score_ beforeMoveS
assertShadowVariablesAreNotStale(undoScore, undoMoveText);
String corruptionDiagnosis = "";
if (trackingWorkingSolution) {
- // Recalculate all shadow variables from scratch
- variableListenerSupport.recalculateAllShadowVariablesFromScratch(workingSolution);
+ // Recalculate all shadow variables from scratch.
+ // We cannot set all shadow variables to null, since some variable listeners
+ // may expect them to be non-null.
+ // | ```suggestion
``` |
timefold-solver | github_2023 | java | 484 | TimefoldAI | triceo | @@ -142,28 +143,54 @@ void corruptedUndoShadowVariableListener(EnvironmentMode environmentMode) {
SolverConfig solverConfig = new SolverConfig()
.withEnvironmentMode(environmentMode)
.withSolutionClass(CorruptedUndoShadowSolution.class)
- .withEntityClasses(CorruptedUndoShadowEntity.class)
+ .withEntityClasses(CorruptedUndoShadowEntity.class, CorruptedUndoShadowValue.class)
.withScoreDirectorFactory(new ScoreDirectorFactoryConfig()
.withEasyScoreCalculatorClass(CorruptedUndoShadowEasyScoreCalculator.class))
.withTerminationConfig(new TerminationConfig()
.withScoreCalculationCountLimit(10L));
switch (environmentMode) {
case TRACKED_FULL_ASSERT -> {
+ var e1 = new CorruptedUndoShadowEntity("e1");
+ var e2 = new CorruptedUndoShadowEntity("e2");
+ var v1 = new CorruptedUndoShadowValue("v1");
+ var v2 = new CorruptedUndoShadowValue("v2");
+
+ e1.setValue(v1);
+ e1.setValueClone(v1);
+ v1.setEntities(new ArrayList<>(List.of(e1)));
+
+ e2.setValue(v2);
+ e2.setValueClone(v2);
+ v2.setEntities(new ArrayList<>(List.of(e2)));
assertThatExceptionOfType(IllegalStateException.class)
.isThrownBy(() -> PlannerTestUtils.solve(solverConfig,
- new CorruptedUndoShadowSolution(List.of(new CorruptedUndoShadowEntity()), List.of("v1"))))
+ new CorruptedUndoShadowSolution(List.of(e1, e2),
+ List.of(v1, v2))))
.withMessageContainingAll("corrupted undoMove",
"Variables that are different between before and undo",
- "Actual value (v1) of variable valueClone on CorruptedUndoShadowEntity entity (CorruptedUndoShadowEntity) differs from expected (null)");
+ "Actual value (v2) of variable valueClone on CorruptedUndoShadowEntity entity (CorruptedUndoShadowEntity) differs from expected (v1)");
}
case FULL_ASSERT,
FAST_ASSERT -> {
// FAST_ASSERT does not create snapshots since it does not intrusive, and hence it can only | ```suggestion
// FAST_ASSERT does not create snapshots since it is not intrusive, and hence it can only
``` |
timefold-solver | github_2023 | java | 474 | TimefoldAI | rsynek | @@ -50,19 +50,21 @@ public List<RecommendedFit<Out_, Score_>> apply(InnerScoreDirector<Solution_, Sc
entityPlacer.stepStarted(stepScope);
try (scoreDirector) {
- for (var placement : entityPlacer) {
- var recommendedFitList = new ArrayList<RecommendedFit<Out_, Score_>>();
- var moveIndex = 0L;
- for (var move : placement) {
- recommendedFitList.add(execute(scoreDirector, move, moveIndex, clonedElement, valueResultFunction));
- moveIndex++;
- }
- recommendedFitList.sort(null);
- return recommendedFitList;
+ var placementIterator = entityPlacer.iterator();
+ if (!placementIterator.hasNext()) {
+ throw new IllegalStateException("""
+ Impossible state: entity placer (%s) has no placements.
+ """.formatted(entityPlacer));
}
- throw new IllegalStateException("""
- Impossible state: entity placer (%s) has no placements.
- """.formatted(entityPlacer));
+ var placement = placementIterator.next();
+ var recommendedFitList = new ArrayList<RecommendedFit<Out_, Score_>>();
+ var moveIndex = 0L;
+ for (var move : placement) {
+ recommendedFitList.add(execute(scoreDirector, move, moveIndex, clonedElement, valueResultFunction));
+ moveIndex++;
+ }
+ recommendedFitList.sort(null); | Interesting there is no `sort()` method without a parameter instead of forcing users to pass `null`. |
timefold-solver | github_2023 | java | 433 | TimefoldAI | triceo | @@ -63,7 +67,18 @@ public abstract class AbstractScoreDirector<Solution_, Score_ extends Score<Scor
private long calculationCount = 0L;
protected Solution_ workingSolution;
protected Integer workingInitScore = null;
- private ShadowVariablesAssert beforeMoveSnapshot;
+ private AllVariablesAssert<Solution_> beforeMoveSnapshot;
+ private Solution_ beforeMoveSolution;
+ private AllVariablesAssert<Solution_> afterMoveSnapshot;
+ private Solution_ afterMoveSolution;
+ private final List<Pair<VariableDescriptor<Solution_>, Object>> beforeVariableChangedForwardEvents = new ArrayList<>();
+ private final List<Pair<VariableDescriptor<Solution_>, Object>> afterVariableChangedForwardEvents = new ArrayList<>();
+ private final List<Pair<VariableDescriptor<Solution_>, Object>> beforeVariableChangedUndoEvents = new ArrayList<>();
+ private final List<Pair<VariableDescriptor<Solution_>, Object>> afterVariableChangedUndoEvents = new ArrayList<>();
+
+ // These points to either ...ForwardEvents or ...UndoEvents, or null if not in an assert mode
+ private List<Pair<VariableDescriptor<Solution_>, Object>> beforeVariableChangedEvents = null;
+ private List<Pair<VariableDescriptor<Solution_>, Object>> afterVariableChangedEvents = null; | This complicates the score director far too much.
Let's think of a way of encapsulating it in a single type. All of this work should happen within that type, with the interactions between `ScoreDirector` and the other type being kept at a minimum; thinking out loud here, perhaps some event-based system could do.
Once we have this in a separate class independent of the score director, it will also be easier to test for corner cases without having to involve the entire machinery of `ScoreDirector`. |
timefold-solver | github_2023 | java | 433 | TimefoldAI | triceo | @@ -147,15 +155,23 @@ void corruptedUndoShadowVariableListener(EnvironmentMode environmentMode) {
switch (environmentMode) {
case FULL_ASSERT:
- case FAST_ASSERT: | We need a name for the new environment mode, something more descriptive than `SUPER_FULL_ASSERT`. Or maybe not?
Your original numbers suggest that this is not *that much* slower than `FULL_ASSERT`. If you can first fix the score calculation numbers to give us *correct* data, we can assess those speeds again and if we're talking about a drop of a couple percent, we really don't need a whole new env mode for this. |
timefold-solver | github_2023 | java | 433 | TimefoldAI | triceo | @@ -644,53 +693,166 @@ public void assertExpectedUndoMoveScore(Move<Solution_> move, Score_ beforeMoveS
if (!undoScore.equals(beforeMoveScore)) {
logger.trace(" Corruption detected. Diagnosing...");
- ShadowVariablesAssert afterUndoSnapshot =
- ShadowVariablesAssert.takeSnapshot(getSolutionDescriptor(), workingSolution);
+ AllVariablesAssert<Solution_> afterUndoSnapshot =
+ AllVariablesAssert.takeSnapshot(getSolutionDescriptor(), workingSolution);
+ Solution_ afterUndoSolution = cloneSolution(workingSolution);
// Precondition: assert that there are probably no corrupted constraints
assertWorkingScoreFromScratch(undoScore, undoMoveText);
// Precondition: assert that shadow variables aren't stale after doing the undoMove
assertShadowVariablesAreNotStale(undoScore, undoMoveText);
- String differentShadowVariables = buildShadowVariableDiff(afterUndoSnapshot);
+ String differentVariables = buildVariableDiff(afterUndoSnapshot);
String scoreDifference = undoScore.subtract(beforeMoveScore).toShortString();
- throw new IllegalStateException("UndoMove corruption (" + scoreDifference
+ throw new UndoScoreCorruptionException("UndoMove corruption (" + scoreDifference
+ "): the beforeMoveScore (" + beforeMoveScore + ") is not the undoScore (" + undoScore
+ ") which is the uncorruptedScore (" + undoScore + ") of the workingSolution.\n"
- + differentShadowVariables
+ + differentVariables
+ " 1) Enable EnvironmentMode " + EnvironmentMode.FULL_ASSERT
+ " (if you haven't already) to fail-faster in case there's a score corruption or variable listener corruption.\n"
+ " 2) Check the Move.createUndoMove(...) method of the moveClass (" + move.getClass() + ")."
+ " The move (" + move + ") might have a corrupted undoMove (" + undoMoveText + ").\n"
+ " 3) Check your custom " + VariableListener.class.getSimpleName() + "s (if you have any)"
+ " for shadow variables that are used by score constraints that could cause"
- + " the scoreDifference (" + scoreDifference + ").");
+ + " the scoreDifference (" + scoreDifference + ").",
+ beforeMoveSolution,
+ afterMoveSolution,
+ afterUndoSolution,
+ move,
+ scoreDirectorFactory);
}
}
- private String buildShadowVariableDiff(ShadowVariablesAssert afterMoveSnapshot) {
+ private String buildVariableDiff(AllVariablesAssert<Solution_> afterUndoMoveSnapshot) {
+ if (beforeMoveSnapshot == null) {
+ return "";
+ }
+ final int VIOLATION_LIMIT = 5;
ShadowVariablesAssert.resetShadowVariables(getSolutionDescriptor(), workingSolution);
variableListenerSupport.forceTriggerAllVariableListeners(workingSolution);
+ AllVariablesAssert<Solution_> recalculatedFromScratch =
+ AllVariablesAssert.takeSnapshot(getSolutionDescriptor(), workingSolution);
+
+ StringBuilder out = new StringBuilder();
+ var changedBetweenBeforeAndUndo = afterUndoMoveSnapshot.changedVariablesFrom(beforeMoveSnapshot);
+ if (!changedBetweenBeforeAndUndo.isEmpty()) {
+ appendVariableChangedViolations(out,
+ "Undo variables do not match before variables",
+ changedBetweenBeforeAndUndo,
+ beforeMoveSnapshot,
+ afterUndoMoveSnapshot,
+ VIOLATION_LIMIT);
+ }
+
+ var changedBetweenBeforeUndoAndScratch = beforeMoveSnapshot.changedVariablesFrom(recalculatedFromScratch);
+ var changedBetweenAfterUndoAndScratch = afterUndoMoveSnapshot.changedVariablesFrom(recalculatedFromScratch);
+
+ if (!changedBetweenBeforeUndoAndScratch.isEmpty()) {
+ appendVariableChangedViolations(out,
+ "Before shadow variables do not match recalculated from scratch shadow variables",
+ changedBetweenBeforeUndoAndScratch,
+ recalculatedFromScratch,
+ beforeMoveSnapshot,
+ VIOLATION_LIMIT);
+ }
+
+ if (!changedBetweenAfterUndoAndScratch.isEmpty()) {
+ appendVariableChangedViolations(out,
+ "After Undo shadow variables do not match recalculated from scratch shadow variables",
+ changedBetweenAfterUndoAndScratch,
+ recalculatedFromScratch,
+ afterUndoMoveSnapshot,
+ VIOLATION_LIMIT);
+ }
+
+ var expectedBeforeAfterCalls = beforeMoveSnapshot.changedVariablesFrom(afterMoveSnapshot);
+ if (!beforeVariableChangedForwardEvents.containsAll(expectedBeforeAfterCalls)) {
+ appendVariableChangedEventViolations(out, "Missing beforeVariableChanged events for actual move",
+ "before", expectedBeforeAfterCalls, beforeVariableChangedForwardEvents,
+ VIOLATION_LIMIT);
+ }
+ if (!afterVariableChangedForwardEvents.containsAll(expectedBeforeAfterCalls)) {
+ appendVariableChangedEventViolations(out, "Missing afterVariableChanged events for actual move",
+ "after", expectedBeforeAfterCalls, afterVariableChangedForwardEvents,
+ VIOLATION_LIMIT);
+ }
+
+ if (!beforeVariableChangedUndoEvents.containsAll(expectedBeforeAfterCalls)) {
+ appendVariableChangedEventViolations(out, "Missing beforeVariableChanged events for undo move",
+ "before", expectedBeforeAfterCalls, beforeVariableChangedUndoEvents,
+ VIOLATION_LIMIT);
+ }
+ if (!afterVariableChangedUndoEvents.containsAll(expectedBeforeAfterCalls)) {
+ appendVariableChangedEventViolations(out, "Missing afterVariableChanged events for undo move",
+ "after", expectedBeforeAfterCalls, afterVariableChangedUndoEvents,
+ VIOLATION_LIMIT);
+ }
+
+ if (out.isEmpty()) {
+ return "Genuine and shadow variables agree with from scratch calculation after the undo move and match the state prior to the move.";
+ }
+
+ return out.toString();
+ }
+
+ private void appendVariableChangedViolations(StringBuilder out, String prefix,
+ List<Pair<VariableDescriptor<Solution_>, Object>> changedVariables,
+ AllVariablesAssert<Solution_> expectedSnapshot,
+ AllVariablesAssert<Solution_> actualSnapshot, int limit) {
+ out.append(prefix);
+ out.append(":\n");
+ int violationCount = 0;
+ for (var changedVariable : changedVariables) {
+ var expectedSnapshotVariable = expectedSnapshot.getVariableSnapshot(changedVariable);
+ var actualSnapshotVariable = actualSnapshot.getVariableSnapshot(changedVariable);
+ out.append(" ");
+ out.append(expectedSnapshotVariable.getVariableDescriptor().getSimpleEntityAndVariableName());
+ out.append(" (");
+ out.append(expectedSnapshotVariable.getEntity());
+ out.append(") expected (");
+ out.append(expectedSnapshotVariable.getValue());
+ out.append(") actual (");
+ out.append(actualSnapshotVariable.getValue());
+ out.append(")\n");
+ violationCount++;
+ if (violationCount >= limit) {
+ return;
+ }
+ }
+ }
- String undoShadowVariableViolations = afterMoveSnapshot.createShadowVariablesViolationMessage(3L);
- String beforeShadowVariableViolations = null;
-
- if (beforeMoveSnapshot != null) {
- beforeShadowVariableViolations = beforeMoveSnapshot.createShadowVariablesViolationMessage(3L);
- }
- if (undoShadowVariableViolations != null && beforeShadowVariableViolations != null) {
- return "Shadow variables have different values when recalculated from scratch before and after undo:\n" +
- "Before undo: " + beforeShadowVariableViolations + "\n" +
- "After undo: " + undoShadowVariableViolations + "\n";
- } else if (undoShadowVariableViolations != null) {
- return "Shadow variables have different values when recalculated from scratch after undo:\n" +
- undoShadowVariableViolations + "\n";
- } else if (beforeShadowVariableViolations != null) {
- return "Shadow variables have different values when recalculated from scratch before undo:\n"
- + beforeShadowVariableViolations
- + "\n";
- } else {
- return "Shadow variables agrees with from scratch calculations before and after undo.\n";
+ private void appendVariableChangedEventViolations(StringBuilder out, String prefix,
+ String kind,
+ List<Pair<VariableDescriptor<Solution_>, Object>> expectedEvents,
+ List<Pair<VariableDescriptor<Solution_>, Object>> actualEvents,
+ int limit) {
+ out.append(prefix);
+ out.append(":\n");
+ int violationCount = 0;
+ for (var variable : expectedEvents) {
+ if (!actualEvents.contains(variable)) {
+ boolean isListVariable = variable.key().isGenuineListVariable();
+ out.append(" ");
+ out.append("Missing ");
+ out.append(kind);
+ if (isListVariable) {
+ out.append("ListVariableChanged(");
+ } else {
+ out.append("VariableChanged(");
+ }
+ out.append(variable.value());
+ out.append(", \"");
+ out.append(variable.key().getVariableName());
+ out.append("\"");
+ if (isListVariable) {
+ out.append(", ...");
+ }
+ out.append(")\n");
+ violationCount++;
+ if (violationCount >= limit) {
+ return;
+ }
+ } | It is very difficult to decipher what this will produce.
Let's start moving away from string builders; this is not performance-sensitive code, this leads to an exception.
So we can use the `"something %s something else".formatted(var)` pattern to make this much more readable.
We can also use raw strings to get rid of all the `\n`. |
timefold-solver | github_2023 | java | 433 | TimefoldAI | triceo | @@ -644,53 +693,166 @@ public void assertExpectedUndoMoveScore(Move<Solution_> move, Score_ beforeMoveS
if (!undoScore.equals(beforeMoveScore)) {
logger.trace(" Corruption detected. Diagnosing...");
- ShadowVariablesAssert afterUndoSnapshot =
- ShadowVariablesAssert.takeSnapshot(getSolutionDescriptor(), workingSolution);
+ AllVariablesAssert<Solution_> afterUndoSnapshot =
+ AllVariablesAssert.takeSnapshot(getSolutionDescriptor(), workingSolution);
+ Solution_ afterUndoSolution = cloneSolution(workingSolution);
// Precondition: assert that there are probably no corrupted constraints
assertWorkingScoreFromScratch(undoScore, undoMoveText);
// Precondition: assert that shadow variables aren't stale after doing the undoMove
assertShadowVariablesAreNotStale(undoScore, undoMoveText);
- String differentShadowVariables = buildShadowVariableDiff(afterUndoSnapshot);
+ String differentVariables = buildVariableDiff(afterUndoSnapshot);
String scoreDifference = undoScore.subtract(beforeMoveScore).toShortString();
- throw new IllegalStateException("UndoMove corruption (" + scoreDifference
+ throw new UndoScoreCorruptionException("UndoMove corruption (" + scoreDifference
+ "): the beforeMoveScore (" + beforeMoveScore + ") is not the undoScore (" + undoScore
+ ") which is the uncorruptedScore (" + undoScore + ") of the workingSolution.\n"
- + differentShadowVariables
+ + differentVariables
+ " 1) Enable EnvironmentMode " + EnvironmentMode.FULL_ASSERT
+ " (if you haven't already) to fail-faster in case there's a score corruption or variable listener corruption.\n"
+ " 2) Check the Move.createUndoMove(...) method of the moveClass (" + move.getClass() + ")."
+ " The move (" + move + ") might have a corrupted undoMove (" + undoMoveText + ").\n"
+ " 3) Check your custom " + VariableListener.class.getSimpleName() + "s (if you have any)"
+ " for shadow variables that are used by score constraints that could cause"
- + " the scoreDifference (" + scoreDifference + ").");
+ + " the scoreDifference (" + scoreDifference + ").",
+ beforeMoveSolution,
+ afterMoveSolution,
+ afterUndoSolution,
+ move,
+ scoreDirectorFactory);
}
}
- private String buildShadowVariableDiff(ShadowVariablesAssert afterMoveSnapshot) {
+ private String buildVariableDiff(AllVariablesAssert<Solution_> afterUndoMoveSnapshot) {
+ if (beforeMoveSnapshot == null) {
+ return "";
+ }
+ final int VIOLATION_LIMIT = 5;
ShadowVariablesAssert.resetShadowVariables(getSolutionDescriptor(), workingSolution);
variableListenerSupport.forceTriggerAllVariableListeners(workingSolution);
+ AllVariablesAssert<Solution_> recalculatedFromScratch =
+ AllVariablesAssert.takeSnapshot(getSolutionDescriptor(), workingSolution);
+
+ StringBuilder out = new StringBuilder();
+ var changedBetweenBeforeAndUndo = afterUndoMoveSnapshot.changedVariablesFrom(beforeMoveSnapshot);
+ if (!changedBetweenBeforeAndUndo.isEmpty()) {
+ appendVariableChangedViolations(out,
+ "Undo variables do not match before variables",
+ changedBetweenBeforeAndUndo,
+ beforeMoveSnapshot,
+ afterUndoMoveSnapshot,
+ VIOLATION_LIMIT);
+ }
+
+ var changedBetweenBeforeUndoAndScratch = beforeMoveSnapshot.changedVariablesFrom(recalculatedFromScratch);
+ var changedBetweenAfterUndoAndScratch = afterUndoMoveSnapshot.changedVariablesFrom(recalculatedFromScratch);
+
+ if (!changedBetweenBeforeUndoAndScratch.isEmpty()) {
+ appendVariableChangedViolations(out,
+ "Before shadow variables do not match recalculated from scratch shadow variables",
+ changedBetweenBeforeUndoAndScratch,
+ recalculatedFromScratch,
+ beforeMoveSnapshot,
+ VIOLATION_LIMIT);
+ }
+
+ if (!changedBetweenAfterUndoAndScratch.isEmpty()) {
+ appendVariableChangedViolations(out,
+ "After Undo shadow variables do not match recalculated from scratch shadow variables",
+ changedBetweenAfterUndoAndScratch,
+ recalculatedFromScratch,
+ afterUndoMoveSnapshot,
+ VIOLATION_LIMIT);
+ }
+
+ var expectedBeforeAfterCalls = beforeMoveSnapshot.changedVariablesFrom(afterMoveSnapshot);
+ if (!beforeVariableChangedForwardEvents.containsAll(expectedBeforeAfterCalls)) {
+ appendVariableChangedEventViolations(out, "Missing beforeVariableChanged events for actual move",
+ "before", expectedBeforeAfterCalls, beforeVariableChangedForwardEvents,
+ VIOLATION_LIMIT);
+ }
+ if (!afterVariableChangedForwardEvents.containsAll(expectedBeforeAfterCalls)) {
+ appendVariableChangedEventViolations(out, "Missing afterVariableChanged events for actual move",
+ "after", expectedBeforeAfterCalls, afterVariableChangedForwardEvents,
+ VIOLATION_LIMIT);
+ }
+
+ if (!beforeVariableChangedUndoEvents.containsAll(expectedBeforeAfterCalls)) {
+ appendVariableChangedEventViolations(out, "Missing beforeVariableChanged events for undo move",
+ "before", expectedBeforeAfterCalls, beforeVariableChangedUndoEvents,
+ VIOLATION_LIMIT);
+ }
+ if (!afterVariableChangedUndoEvents.containsAll(expectedBeforeAfterCalls)) {
+ appendVariableChangedEventViolations(out, "Missing afterVariableChanged events for undo move",
+ "after", expectedBeforeAfterCalls, afterVariableChangedUndoEvents,
+ VIOLATION_LIMIT);
+ }
+
+ if (out.isEmpty()) {
+ return "Genuine and shadow variables agree with from scratch calculation after the undo move and match the state prior to the move.";
+ }
+
+ return out.toString();
+ }
+
+ private void appendVariableChangedViolations(StringBuilder out, String prefix,
+ List<Pair<VariableDescriptor<Solution_>, Object>> changedVariables,
+ AllVariablesAssert<Solution_> expectedSnapshot,
+ AllVariablesAssert<Solution_> actualSnapshot, int limit) {
+ out.append(prefix);
+ out.append(":\n");
+ int violationCount = 0;
+ for (var changedVariable : changedVariables) {
+ var expectedSnapshotVariable = expectedSnapshot.getVariableSnapshot(changedVariable);
+ var actualSnapshotVariable = actualSnapshot.getVariableSnapshot(changedVariable);
+ out.append(" ");
+ out.append(expectedSnapshotVariable.getVariableDescriptor().getSimpleEntityAndVariableName());
+ out.append(" (");
+ out.append(expectedSnapshotVariable.getEntity());
+ out.append(") expected (");
+ out.append(expectedSnapshotVariable.getValue());
+ out.append(") actual (");
+ out.append(actualSnapshotVariable.getValue());
+ out.append(")\n");
+ violationCount++;
+ if (violationCount >= limit) {
+ return;
+ } | Same comment on readable strings. |
timefold-solver | github_2023 | java | 433 | TimefoldAI | triceo | @@ -644,53 +693,166 @@ public void assertExpectedUndoMoveScore(Move<Solution_> move, Score_ beforeMoveS
if (!undoScore.equals(beforeMoveScore)) {
logger.trace(" Corruption detected. Diagnosing...");
- ShadowVariablesAssert afterUndoSnapshot =
- ShadowVariablesAssert.takeSnapshot(getSolutionDescriptor(), workingSolution);
+ AllVariablesAssert<Solution_> afterUndoSnapshot =
+ AllVariablesAssert.takeSnapshot(getSolutionDescriptor(), workingSolution);
+ Solution_ afterUndoSolution = cloneSolution(workingSolution);
// Precondition: assert that there are probably no corrupted constraints
assertWorkingScoreFromScratch(undoScore, undoMoveText);
// Precondition: assert that shadow variables aren't stale after doing the undoMove
assertShadowVariablesAreNotStale(undoScore, undoMoveText);
- String differentShadowVariables = buildShadowVariableDiff(afterUndoSnapshot);
+ String differentVariables = buildVariableDiff(afterUndoSnapshot);
String scoreDifference = undoScore.subtract(beforeMoveScore).toShortString();
- throw new IllegalStateException("UndoMove corruption (" + scoreDifference
+ throw new UndoScoreCorruptionException("UndoMove corruption (" + scoreDifference
+ "): the beforeMoveScore (" + beforeMoveScore + ") is not the undoScore (" + undoScore
+ ") which is the uncorruptedScore (" + undoScore + ") of the workingSolution.\n"
- + differentShadowVariables
+ + differentVariables
+ " 1) Enable EnvironmentMode " + EnvironmentMode.FULL_ASSERT
+ " (if you haven't already) to fail-faster in case there's a score corruption or variable listener corruption.\n"
+ " 2) Check the Move.createUndoMove(...) method of the moveClass (" + move.getClass() + ")."
+ " The move (" + move + ") might have a corrupted undoMove (" + undoMoveText + ").\n"
+ " 3) Check your custom " + VariableListener.class.getSimpleName() + "s (if you have any)"
+ " for shadow variables that are used by score constraints that could cause"
- + " the scoreDifference (" + scoreDifference + ").");
+ + " the scoreDifference (" + scoreDifference + ").", | IMO we can also do a lot here to make the string much more readable, raw strings were made for this. |
timefold-solver | github_2023 | java | 433 | TimefoldAI | triceo | @@ -644,53 +693,166 @@ public void assertExpectedUndoMoveScore(Move<Solution_> move, Score_ beforeMoveS
if (!undoScore.equals(beforeMoveScore)) {
logger.trace(" Corruption detected. Diagnosing...");
- ShadowVariablesAssert afterUndoSnapshot =
- ShadowVariablesAssert.takeSnapshot(getSolutionDescriptor(), workingSolution);
+ AllVariablesAssert<Solution_> afterUndoSnapshot =
+ AllVariablesAssert.takeSnapshot(getSolutionDescriptor(), workingSolution);
+ Solution_ afterUndoSolution = cloneSolution(workingSolution);
// Precondition: assert that there are probably no corrupted constraints
assertWorkingScoreFromScratch(undoScore, undoMoveText);
// Precondition: assert that shadow variables aren't stale after doing the undoMove
assertShadowVariablesAreNotStale(undoScore, undoMoveText);
- String differentShadowVariables = buildShadowVariableDiff(afterUndoSnapshot);
+ String differentVariables = buildVariableDiff(afterUndoSnapshot);
String scoreDifference = undoScore.subtract(beforeMoveScore).toShortString();
- throw new IllegalStateException("UndoMove corruption (" + scoreDifference
+ throw new UndoScoreCorruptionException("UndoMove corruption (" + scoreDifference
+ "): the beforeMoveScore (" + beforeMoveScore + ") is not the undoScore (" + undoScore
+ ") which is the uncorruptedScore (" + undoScore + ") of the workingSolution.\n"
- + differentShadowVariables
+ + differentVariables
+ " 1) Enable EnvironmentMode " + EnvironmentMode.FULL_ASSERT
+ " (if you haven't already) to fail-faster in case there's a score corruption or variable listener corruption.\n"
+ " 2) Check the Move.createUndoMove(...) method of the moveClass (" + move.getClass() + ")."
+ " The move (" + move + ") might have a corrupted undoMove (" + undoMoveText + ").\n"
+ " 3) Check your custom " + VariableListener.class.getSimpleName() + "s (if you have any)"
+ " for shadow variables that are used by score constraints that could cause"
- + " the scoreDifference (" + scoreDifference + ").");
+ + " the scoreDifference (" + scoreDifference + ").",
+ beforeMoveSolution,
+ afterMoveSolution,
+ afterUndoSolution,
+ move,
+ scoreDirectorFactory);
}
}
- private String buildShadowVariableDiff(ShadowVariablesAssert afterMoveSnapshot) {
+ private String buildVariableDiff(AllVariablesAssert<Solution_> afterUndoMoveSnapshot) {
+ if (beforeMoveSnapshot == null) {
+ return "";
+ }
+ final int VIOLATION_LIMIT = 5;
ShadowVariablesAssert.resetShadowVariables(getSolutionDescriptor(), workingSolution);
variableListenerSupport.forceTriggerAllVariableListeners(workingSolution);
+ AllVariablesAssert<Solution_> recalculatedFromScratch =
+ AllVariablesAssert.takeSnapshot(getSolutionDescriptor(), workingSolution);
+
+ StringBuilder out = new StringBuilder();
+ var changedBetweenBeforeAndUndo = afterUndoMoveSnapshot.changedVariablesFrom(beforeMoveSnapshot);
+ if (!changedBetweenBeforeAndUndo.isEmpty()) {
+ appendVariableChangedViolations(out,
+ "Undo variables do not match before variables",
+ changedBetweenBeforeAndUndo,
+ beforeMoveSnapshot,
+ afterUndoMoveSnapshot,
+ VIOLATION_LIMIT);
+ }
+
+ var changedBetweenBeforeUndoAndScratch = beforeMoveSnapshot.changedVariablesFrom(recalculatedFromScratch);
+ var changedBetweenAfterUndoAndScratch = afterUndoMoveSnapshot.changedVariablesFrom(recalculatedFromScratch);
+
+ if (!changedBetweenBeforeUndoAndScratch.isEmpty()) {
+ appendVariableChangedViolations(out,
+ "Before shadow variables do not match recalculated from scratch shadow variables",
+ changedBetweenBeforeUndoAndScratch,
+ recalculatedFromScratch,
+ beforeMoveSnapshot,
+ VIOLATION_LIMIT);
+ }
+
+ if (!changedBetweenAfterUndoAndScratch.isEmpty()) {
+ appendVariableChangedViolations(out,
+ "After Undo shadow variables do not match recalculated from scratch shadow variables",
+ changedBetweenAfterUndoAndScratch,
+ recalculatedFromScratch,
+ afterUndoMoveSnapshot,
+ VIOLATION_LIMIT);
+ }
+
+ var expectedBeforeAfterCalls = beforeMoveSnapshot.changedVariablesFrom(afterMoveSnapshot);
+ if (!beforeVariableChangedForwardEvents.containsAll(expectedBeforeAfterCalls)) {
+ appendVariableChangedEventViolations(out, "Missing beforeVariableChanged events for actual move",
+ "before", expectedBeforeAfterCalls, beforeVariableChangedForwardEvents,
+ VIOLATION_LIMIT);
+ }
+ if (!afterVariableChangedForwardEvents.containsAll(expectedBeforeAfterCalls)) {
+ appendVariableChangedEventViolations(out, "Missing afterVariableChanged events for actual move",
+ "after", expectedBeforeAfterCalls, afterVariableChangedForwardEvents,
+ VIOLATION_LIMIT);
+ }
+
+ if (!beforeVariableChangedUndoEvents.containsAll(expectedBeforeAfterCalls)) {
+ appendVariableChangedEventViolations(out, "Missing beforeVariableChanged events for undo move",
+ "before", expectedBeforeAfterCalls, beforeVariableChangedUndoEvents,
+ VIOLATION_LIMIT);
+ }
+ if (!afterVariableChangedUndoEvents.containsAll(expectedBeforeAfterCalls)) {
+ appendVariableChangedEventViolations(out, "Missing afterVariableChanged events for undo move",
+ "after", expectedBeforeAfterCalls, afterVariableChangedUndoEvents,
+ VIOLATION_LIMIT);
+ }
+
+ if (out.isEmpty()) {
+ return "Genuine and shadow variables agree with from scratch calculation after the undo move and match the state prior to the move.";
+ }
+
+ return out.toString();
+ }
+
+ private void appendVariableChangedViolations(StringBuilder out, String prefix,
+ List<Pair<VariableDescriptor<Solution_>, Object>> changedVariables,
+ AllVariablesAssert<Solution_> expectedSnapshot,
+ AllVariablesAssert<Solution_> actualSnapshot, int limit) {
+ out.append(prefix);
+ out.append(":\n");
+ int violationCount = 0;
+ for (var changedVariable : changedVariables) {
+ var expectedSnapshotVariable = expectedSnapshot.getVariableSnapshot(changedVariable);
+ var actualSnapshotVariable = actualSnapshot.getVariableSnapshot(changedVariable);
+ out.append(" ");
+ out.append(expectedSnapshotVariable.getVariableDescriptor().getSimpleEntityAndVariableName());
+ out.append(" (");
+ out.append(expectedSnapshotVariable.getEntity());
+ out.append(") expected (");
+ out.append(expectedSnapshotVariable.getValue());
+ out.append(") actual (");
+ out.append(actualSnapshotVariable.getValue());
+ out.append(")\n");
+ violationCount++;
+ if (violationCount >= limit) {
+ return;
+ }
+ }
+ }
- String undoShadowVariableViolations = afterMoveSnapshot.createShadowVariablesViolationMessage(3L);
- String beforeShadowVariableViolations = null;
-
- if (beforeMoveSnapshot != null) {
- beforeShadowVariableViolations = beforeMoveSnapshot.createShadowVariablesViolationMessage(3L);
- }
- if (undoShadowVariableViolations != null && beforeShadowVariableViolations != null) {
- return "Shadow variables have different values when recalculated from scratch before and after undo:\n" +
- "Before undo: " + beforeShadowVariableViolations + "\n" +
- "After undo: " + undoShadowVariableViolations + "\n";
- } else if (undoShadowVariableViolations != null) {
- return "Shadow variables have different values when recalculated from scratch after undo:\n" +
- undoShadowVariableViolations + "\n";
- } else if (beforeShadowVariableViolations != null) {
- return "Shadow variables have different values when recalculated from scratch before undo:\n"
- + beforeShadowVariableViolations
- + "\n";
- } else {
- return "Shadow variables agrees with from scratch calculations before and after undo.\n";
+ private void appendVariableChangedEventViolations(StringBuilder out, String prefix, | Let's make this (and other `append...` functions) a function without side effects; return `String`, don't accept `out`. |
timefold-solver | github_2023 | java | 433 | TimefoldAI | triceo | @@ -0,0 +1,100 @@
+package ai.timefold.solver.core.api.solver.exception;
+
+import ai.timefold.solver.core.api.score.Score;
+import ai.timefold.solver.core.impl.heuristic.move.Move;
+import ai.timefold.solver.core.impl.score.director.AbstractScoreDirectorFactory;
+import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
+
+/**
+ * An exception that is thrown in {@link ai.timefold.solver.core.config.solver.EnvironmentMode#FULL_ASSERT_WITH_TRACKING} when
+ * undo score corruption is detected. It contains the working solution before the move, after the move, and after the undo move,
+ * as well as the move that caused the corruption. You can catch this exception to create a reproducer of the corruption.
+ */
+public class UndoScoreCorruptionException extends IllegalStateException {
+ private final Object beforeMoveSolution;
+ private final Object afterMoveSolution;
+ private final Object afterUndoSolution;
+
+ @SuppressWarnings("rawtypes")
+ private final Move move;
+
+ @SuppressWarnings("rawtypes")
+ private final AbstractScoreDirectorFactory scoreDirectorFactory;
+
+ public UndoScoreCorruptionException(String message, Object beforeMoveSolution, Object afterMoveSolution,
+ Object afterUndoSolution,
+ @SuppressWarnings("rawtypes") Move move,
+ @SuppressWarnings("rawtypes") AbstractScoreDirectorFactory scoreDirectorFactory) {
+ super(message); | As much as I like the idea of giving the user something to use in their code to catch and reproduce a corruption, I don't think I'm ready to expose `Move` to people and tell them to use it.
When in doubt leave it out?
We can give them `toString()` of the move, if that'd help.
We can discuss on Slack.
|
timefold-solver | github_2023 | java | 433 | TimefoldAI | triceo | @@ -0,0 +1,100 @@
+package ai.timefold.solver.core.api.solver.exception;
+
+import ai.timefold.solver.core.api.score.Score;
+import ai.timefold.solver.core.impl.heuristic.move.Move;
+import ai.timefold.solver.core.impl.score.director.AbstractScoreDirectorFactory;
+import ai.timefold.solver.core.impl.score.director.InnerScoreDirector;
+
+/**
+ * An exception that is thrown in {@link ai.timefold.solver.core.config.solver.EnvironmentMode#FULL_ASSERT_WITH_TRACKING} when
+ * undo score corruption is detected. It contains the working solution before the move, after the move, and after the undo move,
+ * as well as the move that caused the corruption. You can catch this exception to create a reproducer of the corruption.
+ */
+public class UndoScoreCorruptionException extends IllegalStateException {
+ private final Object beforeMoveSolution;
+ private final Object afterMoveSolution;
+ private final Object afterUndoSolution;
+
+ @SuppressWarnings("rawtypes")
+ private final Move move;
+
+ @SuppressWarnings("rawtypes")
+ private final AbstractScoreDirectorFactory scoreDirectorFactory;
+
+ public UndoScoreCorruptionException(String message, Object beforeMoveSolution, Object afterMoveSolution,
+ Object afterUndoSolution,
+ @SuppressWarnings("rawtypes") Move move,
+ @SuppressWarnings("rawtypes") AbstractScoreDirectorFactory scoreDirectorFactory) {
+ super(message);
+ this.beforeMoveSolution = beforeMoveSolution;
+ this.afterMoveSolution = afterMoveSolution;
+ this.afterUndoSolution = afterUndoSolution;
+ this.move = move;
+ this.scoreDirectorFactory = scoreDirectorFactory;
+ }
+
+ /**
+ * Return the state of the working solution before a move was executed.
+ *
+ * @return the state of the working solution before a move was executed.
+ */
+ @SuppressWarnings("unchecked")
+ public <Solution_> Solution_ getBeforeMoveSolution() {
+ return (Solution_) beforeMoveSolution;
+ }
+
+ /**
+ * Return the state of the working solution after a move was executed, but prior to the undo move.
+ *
+ * @return the state of the working solution after a move was executed, but prior to the undo move.
+ */
+ @SuppressWarnings("unchecked")
+ public <Solution_> Solution_ getAfterMoveSolution() {
+ return (Solution_) afterMoveSolution;
+ }
+
+ /**
+ * Return the state of the working solution after the undo move was executed.
+ *
+ * @return the state of the working solution after the undo move was executed.
+ */
+ @SuppressWarnings("unchecked")
+ public <Solution_> Solution_ getAfterUndoSolution() {
+ return (Solution_) afterUndoSolution;
+ }
+
+ /**
+ * Returns the move that caused the corruption, rebased on {@link #getBeforeMoveSolution()}.
+ *
+ * @return the move that caused the corruption, rebased on {@link #getBeforeMoveSolution}.
+ * @throws UnsupportedOperationException If the {@link Move} does not support rebasing.
+ */
+ @SuppressWarnings("unchecked")
+ public <Solution_> Move<Solution_> getMove() {
+ try (InnerScoreDirector<Solution_, ?> scoreDirector =
+ (InnerScoreDirector<Solution_, ?>) scoreDirectorFactory.buildScoreDirector()) {
+ scoreDirector.setWorkingSolution((Solution_) beforeMoveSolution);
+ return move.rebase(scoreDirector);
+ }
+ }
+
+ /**
+ * Calculate the score of a given solution, using the
+ * {@link ai.timefold.solver.core.impl.score.director.ScoreDirectorFactory}
+ * of the {@link ai.timefold.solver.core.api.solver.Solver} that encountered the corruption.
+ *
+ * @param solution The solution to be evaluated
+ * @return
+ * @param <Solution_>
+ * @param <Score_>
+ */
+ @SuppressWarnings("unchecked")
+ public <Solution_, Score_ extends Score<Score_>> Score_ evaluateSolution(Solution_ solution) {
+ try (InnerScoreDirector<Solution_, Score_> scoreDirector =
+ (InnerScoreDirector<Solution_, Score_>) scoreDirectorFactory.buildScoreDirector()) {
+ Solution_ solutionClone = scoreDirector.cloneSolution(solution);
+ scoreDirector.setWorkingSolution(solutionClone);
+ return scoreDirector.calculateScore();
+ }
+ } | IMO exceptions should not have complex methods such as this one. If the users want to execute something over those solutions, they can do so on their own. |
timefold-solver | github_2023 | java | 433 | TimefoldAI | triceo | @@ -0,0 +1,100 @@
+package ai.timefold.solver.core.api.solver.exception; | I am definitely not ready to expose this in the public API.
I'm not saying it will never be exposed, but let's give it some bake time in the internals; if users pick it up, we can talk about exposing it. |
timefold-solver | github_2023 | java | 433 | TimefoldAI | triceo | @@ -0,0 +1,54 @@
+package ai.timefold.solver.core.impl.domain.variable.listener.support.violation;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
+import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
+import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
+
+/**
+ * Serves for detecting undo move corruption. When a snapshot is created, it records the state of all variables (genuine and
+ * shadow) for all entities.
+ */ | IntelliJ has a plugin (I think it's called Grazie) that suggests appropriate line breaks in comments (among other things).
It makes for longer comments, but ones that read much better, because the lines are short and nothing goes over the fold.
I suggest you start using it and review the comments in your PR with that plugin enabled. |
timefold-solver | github_2023 | java | 433 | TimefoldAI | triceo | @@ -0,0 +1,6 @@
+package ai.timefold.solver.core.impl.domain.variable.listener.support.violation;
+
+import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
+
+public record VariableId<Solution_>(VariableDescriptor<Solution_> variableDescriptor, Object entity) { | Thinking out loud... two records are considered equal if their components are equal. This works for variable descriptor, but how about entities? Does this need to survive cloning? After cloning, entities may not be equal - what often determines equality is their Planning ID. |
timefold-solver | github_2023 | java | 433 | TimefoldAI | triceo | @@ -0,0 +1,48 @@
+package ai.timefold.solver.core.impl.domain.variable.listener.support.violation;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+
+import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
+import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
+
+public class VariableSnapshot<Solution_> { | Could be a record too, no? You can have custom constructors for records. |
timefold-solver | github_2023 | java | 433 | TimefoldAI | triceo | @@ -0,0 +1,54 @@
+package ai.timefold.solver.core.impl.domain.variable.listener.support.violation;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
+import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
+import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
+
+/**
+ * Serves for detecting undo move corruption. When a snapshot is created, it records the state of all variables (genuine and
+ * shadow) for all entities.
+ */
+public class AllVariablesAssert<Solution_> {
+ private final Map<VariableId<Solution_>, VariableSnapshot<Solution_>> variableIdToSnapshot =
+ new HashMap<>();
+
+ public static <Solution_> AllVariablesAssert<Solution_> takeSnapshot(
+ SolutionDescriptor<Solution_> solutionDescriptor,
+ Solution_ workingSolution) {
+ AllVariablesAssert<Solution_> out = new AllVariablesAssert<>(); | If you only want this constructed from this method, you should introduce a private constructor. |
timefold-solver | github_2023 | java | 433 | TimefoldAI | triceo | @@ -0,0 +1,54 @@
+package ai.timefold.solver.core.impl.domain.variable.listener.support.violation;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
+import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
+import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
+
+/**
+ * Serves for detecting undo move corruption. When a snapshot is created, it records the state of all variables (genuine and
+ * shadow) for all entities.
+ */
+public class AllVariablesAssert<Solution_> { | Let's agree going forward that if a type can be `final`, it will be final, OK?
I'd also argue that we should agree on hiding types in packages by default, but that's not applicable here. |
timefold-solver | github_2023 | java | 433 | TimefoldAI | triceo | @@ -0,0 +1,99 @@
+package ai.timefold.solver.core.impl.domain.variable.listener.support.violation;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import ai.timefold.solver.core.api.domain.variable.VariableListener;
+import ai.timefold.solver.core.api.score.director.ScoreDirector;
+import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
+import ai.timefold.solver.core.impl.domain.variable.listener.SourcedVariableListener;
+import ai.timefold.solver.core.impl.domain.variable.supply.Demand;
+import ai.timefold.solver.core.impl.domain.variable.supply.Supply;
+import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager;
+
+public class NormalVariableTracker<Solution_> | We call that a `Genuine` variable. (Technically, the list variable is `GenuineListVariable`, but plenty of places shortcut that to just `ListVariable` already.) |
timefold-solver | github_2023 | java | 433 | TimefoldAI | triceo | @@ -0,0 +1,54 @@
+package ai.timefold.solver.core.impl.domain.variable.listener.support.violation;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
+import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
+import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
+
+/**
+ * Serves for detecting undo move corruption. When a snapshot is created, it records the state of all variables (genuine and
+ * shadow) for all entities.
+ */
+public class AllVariablesAssert<Solution_> {
+ private final Map<VariableId<Solution_>, VariableSnapshot<Solution_>> variableIdToSnapshot =
+ new HashMap<>();
+
+ public static <Solution_> AllVariablesAssert<Solution_> takeSnapshot(
+ SolutionDescriptor<Solution_> solutionDescriptor,
+ Solution_ workingSolution) {
+ AllVariablesAssert<Solution_> out = new AllVariablesAssert<>();
+ solutionDescriptor.visitAllEntities(workingSolution, entity -> {
+ EntityDescriptor<Solution_> entityDescriptor = solutionDescriptor.findEntityDescriptorOrFail(entity.getClass());
+ for (VariableDescriptor<Solution_> variableDescriptor : entityDescriptor.getDeclaredVariableDescriptors()) {
+ out.recordVariable(solutionDescriptor, variableDescriptor, entity);
+ }
+ }); | These long declarations call for `var`. The type of the variable here is obvious enough from the right hand side. |
timefold-solver | github_2023 | java | 433 | TimefoldAI | triceo | @@ -0,0 +1,107 @@
+package ai.timefold.solver.core.impl.domain.variable.listener.support.violation;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import ai.timefold.solver.core.api.domain.variable.ListVariableListener;
+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.domain.variable.descriptor.VariableDescriptor;
+import ai.timefold.solver.core.impl.domain.variable.listener.SourcedVariableListener;
+import ai.timefold.solver.core.impl.domain.variable.supply.Demand;
+import ai.timefold.solver.core.impl.domain.variable.supply.Supply;
+import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager;
+
+public class ListVariableTracker<Solution_>
+ implements SourcedVariableListener<Solution_>, ListVariableListener<Solution_, Object, Object>, Supply {
+ private final ListVariableDescriptor<Solution_> variableDescriptor;
+ private final List<Object> beforeVariableChangedEntityList;
+ private final List<Object> afterVariableChangedEntityList;
+
+ public ListVariableTracker(ListVariableDescriptor<Solution_> variableDescriptor) {
+ this.variableDescriptor = variableDescriptor;
+ beforeVariableChangedEntityList = new ArrayList<>();
+ afterVariableChangedEntityList = new ArrayList<>();
+ }
+
+ @Override
+ public VariableDescriptor<Solution_> getSourceVariableDescriptor() {
+ return variableDescriptor;
+ }
+
+ @Override
+ public void resetWorkingSolution(ScoreDirector<Solution_> scoreDirector) {
+ beforeVariableChangedEntityList.clear();
+ afterVariableChangedEntityList.clear();
+ }
+
+ @Override
+ public void beforeEntityAdded(ScoreDirector<Solution_> scoreDirector, Object entity) {
+
+ }
+
+ @Override
+ public void afterEntityAdded(ScoreDirector<Solution_> scoreDirector, Object entity) {
+
+ }
+
+ @Override
+ public void beforeEntityRemoved(ScoreDirector<Solution_> scoreDirector, Object entity) {
+
+ }
+
+ @Override
+ public void afterEntityRemoved(ScoreDirector<Solution_> scoreDirector, Object entity) {
+
+ }
+
+ @Override
+ public void afterListVariableElementUnassigned(ScoreDirector<Solution_> scoreDirector, Object element) {
+
+ }
+
+ @Override
+ public void beforeListVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity, int fromIndex, int toIndex) {
+ beforeVariableChangedEntityList.add(entity);
+ }
+
+ @Override
+ public void afterListVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity, int fromIndex, int toIndex) {
+ afterVariableChangedEntityList.add(entity);
+ }
+
+ public List<String> getEntitiesMissingBeforeAfterEvents(
+ List<VariableId<Solution_>> changedVariables) {
+ List<String> out = new ArrayList<>();
+ for (var changedVariable : changedVariables) {
+ if (!variableDescriptor.equals(changedVariable.variableDescriptor())) {
+ continue;
+ }
+ Object entity = changedVariable.entity();
+ if (!beforeVariableChangedEntityList.contains(entity)) {
+ out.add("Entity (" + entity
+ + ") is missing a beforeListVariableChanged call for list variable ("
+ + variableDescriptor.getVariableName() + ").");
+ }
+ if (!afterVariableChangedEntityList.contains(entity)) {
+ out.add("Entity (" + entity
+ + ") is missing a afterListVariableChanged call for list variable ("
+ + variableDescriptor.getVariableName() + ").");
+ }
+ }
+ beforeVariableChangedEntityList.clear();
+ afterVariableChangedEntityList.clear();
+ return out;
+ }
+
+ public TrackerDemand demand() {
+ return new TrackerDemand(); | IIRC for the demand-supply mechanism to work properly, the demands actually need to equal to some others, otherwise you're not really achieving the perf benefits for which the system exists.
Did you really mean that no two demands should ever be equal? |
timefold-solver | github_2023 | java | 433 | TimefoldAI | triceo | @@ -0,0 +1,99 @@
+package ai.timefold.solver.core.impl.domain.variable.listener.support.violation;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import ai.timefold.solver.core.api.domain.variable.VariableListener;
+import ai.timefold.solver.core.api.score.director.ScoreDirector;
+import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
+import ai.timefold.solver.core.impl.domain.variable.listener.SourcedVariableListener;
+import ai.timefold.solver.core.impl.domain.variable.supply.Demand;
+import ai.timefold.solver.core.impl.domain.variable.supply.Supply;
+import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager;
+
+public class NormalVariableTracker<Solution_>
+ implements SourcedVariableListener<Solution_>, VariableListener<Solution_, Object>, Supply {
+ private final VariableDescriptor<Solution_> variableDescriptor;
+ private final List<Object> beforeVariableChangedEntityList;
+ private final List<Object> afterVariableChangedEntityList;
+
+ public NormalVariableTracker(VariableDescriptor<Solution_> variableDescriptor) {
+ this.variableDescriptor = variableDescriptor;
+ beforeVariableChangedEntityList = new ArrayList<>();
+ afterVariableChangedEntityList = new ArrayList<>();
+ }
+
+ @Override
+ public VariableDescriptor<Solution_> getSourceVariableDescriptor() {
+ return variableDescriptor;
+ }
+
+ @Override
+ public void beforeEntityAdded(ScoreDirector<Solution_> scoreDirector, Object object) {
+
+ }
+
+ @Override
+ public void afterEntityAdded(ScoreDirector<Solution_> scoreDirector, Object object) {
+
+ }
+
+ @Override
+ public void beforeEntityRemoved(ScoreDirector<Solution_> scoreDirector, Object object) {
+
+ }
+
+ @Override
+ public void afterEntityRemoved(ScoreDirector<Solution_> scoreDirector, Object object) {
+
+ }
+
+ @Override
+ public void resetWorkingSolution(ScoreDirector<Solution_> scoreDirector) {
+ beforeVariableChangedEntityList.clear();
+ afterVariableChangedEntityList.clear();
+ }
+
+ @Override
+ public void beforeVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity) {
+ beforeVariableChangedEntityList.add(entity);
+ }
+
+ @Override
+ public void afterVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity) {
+ afterVariableChangedEntityList.add(entity);
+ }
+
+ public List<String> getEntitiesMissingBeforeAfterEvents(
+ List<VariableId<Solution_>> changedVariables) {
+ List<String> out = new ArrayList<>();
+ for (var changedVariable : changedVariables) { | I see you use `var` in some places, and in others you don't. Let's try to be a bit more consistent; let's always use `var` where the right hand side makes it sufficiently obvious what ends up on the left hand side.
For collection declarations, I don't have a firm opinion. The generics either need to be on the LHS or RHS. If the rest of the method uses `var`, I'd argue they should be on the RHS. Also, if we follow the convention of appending `List` to variable names of type `List` (which `out` doesn't), `var` becomes even less problematic. |
timefold-solver | github_2023 | java | 433 | TimefoldAI | triceo | @@ -0,0 +1,99 @@
+package ai.timefold.solver.core.impl.domain.variable.listener.support.violation;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import ai.timefold.solver.core.api.domain.variable.VariableListener;
+import ai.timefold.solver.core.api.score.director.ScoreDirector;
+import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
+import ai.timefold.solver.core.impl.domain.variable.listener.SourcedVariableListener;
+import ai.timefold.solver.core.impl.domain.variable.supply.Demand;
+import ai.timefold.solver.core.impl.domain.variable.supply.Supply;
+import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager;
+
+public class NormalVariableTracker<Solution_>
+ implements SourcedVariableListener<Solution_>, VariableListener<Solution_, Object>, Supply {
+ private final VariableDescriptor<Solution_> variableDescriptor;
+ private final List<Object> beforeVariableChangedEntityList;
+ private final List<Object> afterVariableChangedEntityList;
+
+ public NormalVariableTracker(VariableDescriptor<Solution_> variableDescriptor) {
+ this.variableDescriptor = variableDescriptor;
+ beforeVariableChangedEntityList = new ArrayList<>();
+ afterVariableChangedEntityList = new ArrayList<>();
+ }
+
+ @Override
+ public VariableDescriptor<Solution_> getSourceVariableDescriptor() {
+ return variableDescriptor;
+ }
+
+ @Override
+ public void beforeEntityAdded(ScoreDirector<Solution_> scoreDirector, Object object) {
+
+ }
+
+ @Override
+ public void afterEntityAdded(ScoreDirector<Solution_> scoreDirector, Object object) {
+
+ }
+
+ @Override
+ public void beforeEntityRemoved(ScoreDirector<Solution_> scoreDirector, Object object) {
+
+ }
+
+ @Override
+ public void afterEntityRemoved(ScoreDirector<Solution_> scoreDirector, Object object) {
+
+ }
+
+ @Override
+ public void resetWorkingSolution(ScoreDirector<Solution_> scoreDirector) {
+ beforeVariableChangedEntityList.clear();
+ afterVariableChangedEntityList.clear();
+ }
+
+ @Override
+ public void beforeVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity) {
+ beforeVariableChangedEntityList.add(entity);
+ }
+
+ @Override
+ public void afterVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity) {
+ afterVariableChangedEntityList.add(entity);
+ }
+
+ public List<String> getEntitiesMissingBeforeAfterEvents(
+ List<VariableId<Solution_>> changedVariables) {
+ List<String> out = new ArrayList<>();
+ for (var changedVariable : changedVariables) {
+ if (!variableDescriptor.equals(changedVariable.variableDescriptor())) {
+ continue;
+ }
+ Object entity = changedVariable.entity();
+ if (!beforeVariableChangedEntityList.contains(entity)) {
+ out.add("Entity (" + entity + ") is missing a beforeVariableChanged call for variable ("
+ + variableDescriptor.getVariableName() + ").");
+ }
+ if (!afterVariableChangedEntityList.contains(entity)) {
+ out.add("Entity (" + entity + ") is missing a afterVariableChanged call for variable ("
+ + variableDescriptor.getVariableName() + ").");
+ }
+ }
+ beforeVariableChangedEntityList.clear();
+ afterVariableChangedEntityList.clear();
+ return out;
+ }
+
+ public TrackerDemand demand() { | Same comment as above regarding demand/supply. |
timefold-solver | github_2023 | java | 433 | TimefoldAI | triceo | @@ -0,0 +1,192 @@
+package ai.timefold.solver.core.impl.domain.variable.listener.support.violation;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
+import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
+import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
+import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
+import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager;
+
+public final class SolutionTracker<Solution_> {
+ private final SolutionDescriptor<Solution_> solutionDescriptor;
+ private final List<NormalVariableTracker<Solution_>> normalVariableTrackers;
+ private final List<ListVariableTracker<Solution_>> listVariableTrackers;
+ private List<String> missingEventsForward;
+ private List<String> missingEventsBackward;
+ Solution_ beforeMoveSolution;
+ AllVariablesAssert<Solution_> beforeVariables;
+ Solution_ afterMoveSolution;
+ AllVariablesAssert<Solution_> afterVariables;
+ Solution_ afterUndoSolution;
+ AllVariablesAssert<Solution_> undoVariables;
+ Solution_ fromScratchSolution;
+ AllVariablesAssert<Solution_> scratchVariables;
+
+ public SolutionTracker(SolutionDescriptor<Solution_> solutionDescriptor,
+ SupplyManager supplyManager) {
+ this.solutionDescriptor = solutionDescriptor;
+ normalVariableTrackers = new ArrayList<>();
+ listVariableTrackers = new ArrayList<>();
+ for (EntityDescriptor<Solution_> entityDescriptor : solutionDescriptor.getEntityDescriptors()) {
+ for (VariableDescriptor<Solution_> variableDescriptor : entityDescriptor.getDeclaredVariableDescriptors()) {
+ if (variableDescriptor instanceof ListVariableDescriptor<Solution_> listVariableDescriptor) {
+ listVariableTrackers.add(new ListVariableTracker<>(listVariableDescriptor));
+ } else {
+ normalVariableTrackers.add(new NormalVariableTracker<>(variableDescriptor));
+ }
+ }
+ }
+ for (NormalVariableTracker<Solution_> normalVariableTracker : normalVariableTrackers) {
+ supplyManager.demand(normalVariableTracker.demand());
+ }
+ for (ListVariableTracker<Solution_> listVariableTracker : listVariableTrackers) {
+ supplyManager.demand(listVariableTracker.demand());
+ }
+ }
+
+ public Solution_ getBeforeMoveSolution() {
+ return beforeMoveSolution;
+ }
+
+ public Solution_ getAfterMoveSolution() {
+ return afterMoveSolution;
+ }
+
+ public Solution_ getAfterUndoSolution() {
+ return afterUndoSolution;
+ }
+
+ public void setBeforeMoveSolution(Solution_ workingSolution) {
+ beforeVariables = AllVariablesAssert.takeSnapshot(solutionDescriptor, workingSolution);
+ beforeMoveSolution = cloneSolution(workingSolution);
+ }
+
+ public void setAfterMoveSolution(Solution_ workingSolution) {
+ afterVariables = AllVariablesAssert.takeSnapshot(solutionDescriptor, workingSolution);
+ afterMoveSolution = cloneSolution(workingSolution);
+
+ if (beforeVariables != null) {
+ missingEventsForward = getEntitiesMissingBeforeAfterEvents(beforeVariables, afterVariables);
+ } else {
+ missingEventsBackward = Collections.emptyList();
+ }
+ }
+
+ public void setAfterUndoSolution(Solution_ workingSolution) {
+ undoVariables = AllVariablesAssert.takeSnapshot(solutionDescriptor, workingSolution);
+ afterUndoSolution = cloneSolution(workingSolution);
+ if (beforeVariables != null) {
+ missingEventsBackward = getEntitiesMissingBeforeAfterEvents(undoVariables, afterVariables);
+ } else {
+ missingEventsBackward = Collections.emptyList();
+ }
+ }
+
+ public void setFromScratchSolution(Solution_ workingSolution) {
+ scratchVariables = AllVariablesAssert.takeSnapshot(solutionDescriptor, workingSolution);
+ fromScratchSolution = cloneSolution(workingSolution);
+ }
+
+ private Solution_ cloneSolution(Solution_ workingSolution) {
+ return solutionDescriptor.getSolutionCloner().cloneSolution(workingSolution);
+ }
+
+ private List<String> getEntitiesMissingBeforeAfterEvents(AllVariablesAssert<Solution_> beforeSolution,
+ AllVariablesAssert<Solution_> afterSolution) {
+ List<String> out = new ArrayList<>();
+ var changes = afterSolution.changedVariablesFrom(beforeSolution);
+ for (NormalVariableTracker<Solution_> normalVariableTracker : normalVariableTrackers) {
+ out.addAll(normalVariableTracker.getEntitiesMissingBeforeAfterEvents(changes));
+ }
+ for (ListVariableTracker<Solution_> listVariableTracker : listVariableTrackers) {
+ out.addAll(listVariableTracker.getEntitiesMissingBeforeAfterEvents(changes));
+ }
+ return out; | Since at this point in time, performance no longer matters, this is the place where lambdas can help a lot with reducing code verbosity. I'd use `forEach` here. |
timefold-solver | github_2023 | java | 433 | TimefoldAI | triceo | @@ -0,0 +1,192 @@
+package ai.timefold.solver.core.impl.domain.variable.listener.support.violation;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
+import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
+import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
+import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
+import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager;
+
+public final class SolutionTracker<Solution_> {
+ private final SolutionDescriptor<Solution_> solutionDescriptor;
+ private final List<NormalVariableTracker<Solution_>> normalVariableTrackers;
+ private final List<ListVariableTracker<Solution_>> listVariableTrackers;
+ private List<String> missingEventsForward;
+ private List<String> missingEventsBackward;
+ Solution_ beforeMoveSolution;
+ AllVariablesAssert<Solution_> beforeVariables;
+ Solution_ afterMoveSolution;
+ AllVariablesAssert<Solution_> afterVariables;
+ Solution_ afterUndoSolution;
+ AllVariablesAssert<Solution_> undoVariables;
+ Solution_ fromScratchSolution;
+ AllVariablesAssert<Solution_> scratchVariables;
+
+ public SolutionTracker(SolutionDescriptor<Solution_> solutionDescriptor,
+ SupplyManager supplyManager) {
+ this.solutionDescriptor = solutionDescriptor;
+ normalVariableTrackers = new ArrayList<>();
+ listVariableTrackers = new ArrayList<>();
+ for (EntityDescriptor<Solution_> entityDescriptor : solutionDescriptor.getEntityDescriptors()) {
+ for (VariableDescriptor<Solution_> variableDescriptor : entityDescriptor.getDeclaredVariableDescriptors()) {
+ if (variableDescriptor instanceof ListVariableDescriptor<Solution_> listVariableDescriptor) {
+ listVariableTrackers.add(new ListVariableTracker<>(listVariableDescriptor));
+ } else {
+ normalVariableTrackers.add(new NormalVariableTracker<>(variableDescriptor));
+ }
+ }
+ }
+ for (NormalVariableTracker<Solution_> normalVariableTracker : normalVariableTrackers) {
+ supplyManager.demand(normalVariableTracker.demand());
+ }
+ for (ListVariableTracker<Solution_> listVariableTracker : listVariableTrackers) {
+ supplyManager.demand(listVariableTracker.demand());
+ }
+ }
+
+ public Solution_ getBeforeMoveSolution() {
+ return beforeMoveSolution;
+ }
+
+ public Solution_ getAfterMoveSolution() {
+ return afterMoveSolution;
+ }
+
+ public Solution_ getAfterUndoSolution() {
+ return afterUndoSolution;
+ }
+
+ public void setBeforeMoveSolution(Solution_ workingSolution) {
+ beforeVariables = AllVariablesAssert.takeSnapshot(solutionDescriptor, workingSolution);
+ beforeMoveSolution = cloneSolution(workingSolution);
+ }
+
+ public void setAfterMoveSolution(Solution_ workingSolution) {
+ afterVariables = AllVariablesAssert.takeSnapshot(solutionDescriptor, workingSolution);
+ afterMoveSolution = cloneSolution(workingSolution);
+
+ if (beforeVariables != null) {
+ missingEventsForward = getEntitiesMissingBeforeAfterEvents(beforeVariables, afterVariables);
+ } else {
+ missingEventsBackward = Collections.emptyList();
+ }
+ }
+
+ public void setAfterUndoSolution(Solution_ workingSolution) {
+ undoVariables = AllVariablesAssert.takeSnapshot(solutionDescriptor, workingSolution);
+ afterUndoSolution = cloneSolution(workingSolution);
+ if (beforeVariables != null) {
+ missingEventsBackward = getEntitiesMissingBeforeAfterEvents(undoVariables, afterVariables);
+ } else {
+ missingEventsBackward = Collections.emptyList();
+ }
+ }
+
+ public void setFromScratchSolution(Solution_ workingSolution) {
+ scratchVariables = AllVariablesAssert.takeSnapshot(solutionDescriptor, workingSolution);
+ fromScratchSolution = cloneSolution(workingSolution);
+ }
+
+ private Solution_ cloneSolution(Solution_ workingSolution) {
+ return solutionDescriptor.getSolutionCloner().cloneSolution(workingSolution);
+ }
+
+ private List<String> getEntitiesMissingBeforeAfterEvents(AllVariablesAssert<Solution_> beforeSolution,
+ AllVariablesAssert<Solution_> afterSolution) {
+ List<String> out = new ArrayList<>();
+ var changes = afterSolution.changedVariablesFrom(beforeSolution);
+ for (NormalVariableTracker<Solution_> normalVariableTracker : normalVariableTrackers) {
+ out.addAll(normalVariableTracker.getEntitiesMissingBeforeAfterEvents(changes));
+ }
+ for (ListVariableTracker<Solution_> listVariableTracker : listVariableTrackers) {
+ out.addAll(listVariableTracker.getEntitiesMissingBeforeAfterEvents(changes));
+ }
+ return out;
+ }
+
+ public String buildScoreCorruptionMessage() {
+ if (beforeMoveSolution == null) {
+ return "";
+ }
+
+ StringBuilder out = new StringBuilder();
+ var changedBetweenBeforeAndUndo = getVariableChangedViolations(beforeVariables,
+ undoVariables);
+
+ var changedBetweenBeforeAndScratch = getVariableChangedViolations(scratchVariables,
+ beforeVariables);
+
+ var changedBetweenUndoAndScratch = getVariableChangedViolations(scratchVariables,
+ undoVariables);
+
+ if (!changedBetweenBeforeAndUndo.isEmpty()) {
+ out.append("Variables that are different between before and undo:\n")
+ .append(formatList(changedBetweenBeforeAndUndo));
+ } | I'd argue that the following reads better:
out.append("""
Variables that are different between before and undo:
%s"""
.formatted(formatList(changedBetweenBeforeAndUndo)));
The newlines are an anti-pattern which Java finally gave us a way to avoid.
|
timefold-solver | github_2023 | java | 433 | TimefoldAI | triceo | @@ -0,0 +1,192 @@
+package ai.timefold.solver.core.impl.domain.variable.listener.support.violation;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor;
+import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
+import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor;
+import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
+import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager;
+
+public final class SolutionTracker<Solution_> {
+ private final SolutionDescriptor<Solution_> solutionDescriptor;
+ private final List<NormalVariableTracker<Solution_>> normalVariableTrackers;
+ private final List<ListVariableTracker<Solution_>> listVariableTrackers;
+ private List<String> missingEventsForward;
+ private List<String> missingEventsBackward;
+ Solution_ beforeMoveSolution;
+ AllVariablesAssert<Solution_> beforeVariables;
+ Solution_ afterMoveSolution;
+ AllVariablesAssert<Solution_> afterVariables;
+ Solution_ afterUndoSolution;
+ AllVariablesAssert<Solution_> undoVariables;
+ Solution_ fromScratchSolution;
+ AllVariablesAssert<Solution_> scratchVariables;
+
+ public SolutionTracker(SolutionDescriptor<Solution_> solutionDescriptor,
+ SupplyManager supplyManager) {
+ this.solutionDescriptor = solutionDescriptor;
+ normalVariableTrackers = new ArrayList<>();
+ listVariableTrackers = new ArrayList<>();
+ for (EntityDescriptor<Solution_> entityDescriptor : solutionDescriptor.getEntityDescriptors()) {
+ for (VariableDescriptor<Solution_> variableDescriptor : entityDescriptor.getDeclaredVariableDescriptors()) {
+ if (variableDescriptor instanceof ListVariableDescriptor<Solution_> listVariableDescriptor) {
+ listVariableTrackers.add(new ListVariableTracker<>(listVariableDescriptor));
+ } else {
+ normalVariableTrackers.add(new NormalVariableTracker<>(variableDescriptor));
+ }
+ }
+ }
+ for (NormalVariableTracker<Solution_> normalVariableTracker : normalVariableTrackers) {
+ supplyManager.demand(normalVariableTracker.demand());
+ }
+ for (ListVariableTracker<Solution_> listVariableTracker : listVariableTrackers) {
+ supplyManager.demand(listVariableTracker.demand());
+ }
+ }
+
+ public Solution_ getBeforeMoveSolution() {
+ return beforeMoveSolution;
+ }
+
+ public Solution_ getAfterMoveSolution() {
+ return afterMoveSolution;
+ }
+
+ public Solution_ getAfterUndoSolution() {
+ return afterUndoSolution;
+ }
+
+ public void setBeforeMoveSolution(Solution_ workingSolution) {
+ beforeVariables = AllVariablesAssert.takeSnapshot(solutionDescriptor, workingSolution);
+ beforeMoveSolution = cloneSolution(workingSolution);
+ }
+
+ public void setAfterMoveSolution(Solution_ workingSolution) {
+ afterVariables = AllVariablesAssert.takeSnapshot(solutionDescriptor, workingSolution);
+ afterMoveSolution = cloneSolution(workingSolution);
+
+ if (beforeVariables != null) {
+ missingEventsForward = getEntitiesMissingBeforeAfterEvents(beforeVariables, afterVariables);
+ } else {
+ missingEventsBackward = Collections.emptyList();
+ }
+ }
+
+ public void setAfterUndoSolution(Solution_ workingSolution) {
+ undoVariables = AllVariablesAssert.takeSnapshot(solutionDescriptor, workingSolution);
+ afterUndoSolution = cloneSolution(workingSolution);
+ if (beforeVariables != null) {
+ missingEventsBackward = getEntitiesMissingBeforeAfterEvents(undoVariables, afterVariables);
+ } else {
+ missingEventsBackward = Collections.emptyList();
+ }
+ }
+
+ public void setFromScratchSolution(Solution_ workingSolution) {
+ scratchVariables = AllVariablesAssert.takeSnapshot(solutionDescriptor, workingSolution);
+ fromScratchSolution = cloneSolution(workingSolution);
+ }
+
+ private Solution_ cloneSolution(Solution_ workingSolution) {
+ return solutionDescriptor.getSolutionCloner().cloneSolution(workingSolution);
+ }
+
+ private List<String> getEntitiesMissingBeforeAfterEvents(AllVariablesAssert<Solution_> beforeSolution,
+ AllVariablesAssert<Solution_> afterSolution) {
+ List<String> out = new ArrayList<>();
+ var changes = afterSolution.changedVariablesFrom(beforeSolution);
+ for (NormalVariableTracker<Solution_> normalVariableTracker : normalVariableTrackers) {
+ out.addAll(normalVariableTracker.getEntitiesMissingBeforeAfterEvents(changes));
+ }
+ for (ListVariableTracker<Solution_> listVariableTracker : listVariableTrackers) {
+ out.addAll(listVariableTracker.getEntitiesMissingBeforeAfterEvents(changes));
+ }
+ return out;
+ }
+
+ public String buildScoreCorruptionMessage() {
+ if (beforeMoveSolution == null) {
+ return "";
+ }
+
+ StringBuilder out = new StringBuilder();
+ var changedBetweenBeforeAndUndo = getVariableChangedViolations(beforeVariables,
+ undoVariables);
+
+ var changedBetweenBeforeAndScratch = getVariableChangedViolations(scratchVariables,
+ beforeVariables);
+
+ var changedBetweenUndoAndScratch = getVariableChangedViolations(scratchVariables,
+ undoVariables);
+
+ if (!changedBetweenBeforeAndUndo.isEmpty()) {
+ out.append("Variables that are different between before and undo:\n")
+ .append(formatList(changedBetweenBeforeAndUndo));
+ }
+
+ if (!changedBetweenBeforeAndScratch.isEmpty()) {
+ out.append("Variables that are different between from scratch and before:\n")
+ .append(formatList(changedBetweenBeforeAndScratch));
+ }
+
+ if (!changedBetweenUndoAndScratch.isEmpty()) {
+ out.append("Variables that are different between from scratch and undo:\n")
+ .append(formatList(changedBetweenUndoAndScratch));
+ }
+
+ if (!missingEventsForward.isEmpty()) {
+ out.append("Missing variable listener events for actual move:\n")
+ .append(formatList(missingEventsForward));
+ }
+
+ if (!missingEventsBackward.isEmpty()) {
+ out.append("Missing variable listener events for undo move:\n")
+ .append(formatList(missingEventsBackward));
+ }
+
+ if (out.isEmpty()) {
+ return "Genuine and shadow variables agree with from scratch calculation after the undo move and match the state prior to the move.";
+ }
+
+ return out.toString();
+ }
+
+ static <Solution_> List<String> getVariableChangedViolations(
+ AllVariablesAssert<Solution_> expectedSnapshot,
+ AllVariablesAssert<Solution_> actualSnapshot) {
+ List<String> out = new ArrayList<>();
+ var changedVariables = expectedSnapshot.changedVariablesFrom(actualSnapshot);
+ for (var changedVariable : changedVariables) {
+ var expectedSnapshotVariable = expectedSnapshot.getVariableSnapshot(changedVariable);
+ var actualSnapshotVariable = actualSnapshot.getVariableSnapshot(changedVariable);
+ out.add("Actual value (%s) of variable %s on %s entity (%s) differs from expected (%s)"
+ .formatted(actualSnapshotVariable.getValue(),
+ expectedSnapshotVariable.getVariableDescriptor().getVariableName(),
+ expectedSnapshotVariable.getVariableDescriptor().getEntityDescriptor().getEntityClass()
+ .getSimpleName(),
+ expectedSnapshotVariable.getEntity(),
+ expectedSnapshotVariable.getValue()));
+ }
+ return out;
+ }
+
+ static String formatList(List<String> messages) {
+ final int LIMIT = 5;
+ if (messages.isEmpty()) {
+ return "";
+ }
+ if (messages.size() <= LIMIT) {
+ return messages.stream()
+ .collect(Collectors.joining("\n - ",
+ " - ", "\n"));
+ }
+ return messages.stream()
+ .limit(LIMIT)
+ .collect(Collectors.joining("\n - ",
+ " - ", "\n ...(" + (messages.size() - LIMIT) + " more)\n"));
+ } | I'm wondering if this perhaps creates too much verbosity. Why not `[A, B, C, D, ...]`?
Or do you expect the list elements to contain far too much text to require this extra formatting? |
timefold-solver | github_2023 | java | 433 | TimefoldAI | triceo | @@ -0,0 +1,48 @@
+package ai.timefold.solver.core.impl.domain.variable.listener.support.violation;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+
+import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor;
+import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor;
+
+public class VariableSnapshot<Solution_> {
+ private final VariableDescriptor<Solution_> variableDescriptor;
+ private final Object entity;
+ private final Object value;
+ private final VariableId<Solution_> variableId;
+
+ public VariableSnapshot(SolutionDescriptor<Solution_> solutionDescriptor, VariableDescriptor<Solution_> variableDescriptor,
+ Object entity) {
+ this.variableDescriptor = variableDescriptor;
+ this.entity = entity;
+ this.variableId = new VariableId<>(variableDescriptor, entity);
+
+ // If it is a genuine list variable, we need to create a copy
+ // of the value in order to create a snapshot (since the contents
+ // of the list change instead of the list itself).
+ this.value = variableDescriptor.isGenuineListVariable() ? new ArrayList<>((List<?>) variableDescriptor.getValue(entity))
+ : variableDescriptor.getValue(entity);
+ }
+
+ public VariableDescriptor<Solution_> getVariableDescriptor() {
+ return variableDescriptor;
+ }
+
+ public Object getEntity() {
+ return entity;
+ }
+
+ public Object getValue() {
+ return value;
+ }
+
+ public VariableId<Solution_> getVariableId() {
+ return variableId;
+ }
+
+ public boolean isDifferentFrom(VariableSnapshot<Solution_> other) {
+ return !Objects.equals(value, other.value);
+ }
+} | Why not use `equals(...)` for this? Isn't that what it's for? |
timefold-solver | github_2023 | java | 433 | TimefoldAI | triceo | @@ -203,13 +211,16 @@ private void assertNonNullPlanningId(Object fact) {
@Override
public Score_ doAndProcessMove(Move<Solution_> move, boolean assertMoveScoreFromScratch) {
- if (assertMoveScoreFromScratch) {
- beforeMoveSnapshot = ShadowVariablesAssert.takeSnapshot(getSolutionDescriptor(), workingSolution);
+ if (solutionTracker != null) { | I like the previous approach, where this condition was hidden behind a variable. The variable makes the purpose of the check obvious, while hiding what the check actually is. |
timefold-solver | github_2023 | java | 433 | TimefoldAI | triceo | @@ -607,7 +621,8 @@ public void assertShadowVariablesAreNotStale(Score_ expectedWorkingScore, Object
+ "s were triggered without changes to the genuine variables"
+ " after completedAction (" + completedAction + ").\n"
+ "But all the shadow variable values are still the same, so this is impossible.\n"
- + "Maybe run with " + EnvironmentMode.FULL_ASSERT + " if you aren't already, to fail earlier.");
+ + "Maybe run with " + EnvironmentMode.FULL_ASSERT_WITH_TRACKING
+ + " if you aren't already, to fail earlier."); | Since we're touching this code, let's convert this nastiness to the new formatting pattern.
Remember: if you can, and it is not too disruptive, always leave the code in better shape than the one you found it in. |
timefold-solver | github_2023 | java | 433 | TimefoldAI | triceo | @@ -667,53 +682,41 @@ public void assertExpectedUndoMoveScore(Move<Solution_> move, Score_ beforeMoveS
if (!undoScore.equals(beforeMoveScore)) {
logger.trace(" Corruption detected. Diagnosing...");
- ShadowVariablesAssert afterUndoSnapshot =
- ShadowVariablesAssert.takeSnapshot(getSolutionDescriptor(), workingSolution);
+ if (solutionTracker != null) {
+ solutionTracker.setAfterUndoSolution(workingSolution);
+ }
// Precondition: assert that there are probably no corrupted constraints
assertWorkingScoreFromScratch(undoScore, undoMoveText);
// Precondition: assert that shadow variables aren't stale after doing the undoMove
assertShadowVariablesAreNotStale(undoScore, undoMoveText);
-
- String differentShadowVariables = buildShadowVariableDiff(afterUndoSnapshot);
+ String corruptionDiagnosis = "";
+ if (solutionTracker != null) {
+ solutionTracker.setFromScratchSolution(workingSolution);
+ corruptionDiagnosis = solutionTracker.buildScoreCorruptionMessage();
+ }
String scoreDifference = undoScore.subtract(beforeMoveScore).toShortString();
-
- throw new IllegalStateException("UndoMove corruption (" + scoreDifference
+ String corruptionMessage = ("UndoMove corruption (" + scoreDifference | Dtto., formatting pattern. |
timefold-solver | github_2023 | java | 433 | TimefoldAI | triceo | @@ -68,6 +69,14 @@ public void setAssertClonedSolution(boolean assertClonedSolution) {
this.assertClonedSolution = assertClonedSolution;
}
+ public boolean isTrackingWorkingSolution() { | This deserves a Javadoc, pointing to someplace that describes what it will do. Perhaps a reference to the relevant `EnvironmentMode`? |
timefold-solver | github_2023 | java | 433 | TimefoldAI | triceo | @@ -88,17 +87,16 @@ void determinism(EnvironmentMode environmentMode) {
Solver<TestdataSolution> solver2 = SolverFactory.<TestdataSolution> create(solverConfig).buildSolver();
switch (environmentMode) {
- case NON_REPRODUCIBLE:
+ case NON_REPRODUCIBLE -> { | I like we're doing this!
Just please double check the entire codebase for switching over environment modes and apply this consistently. (If you haven't already.) |
timefold-solver | github_2023 | java | 433 | TimefoldAI | triceo | @@ -141,6 +141,8 @@ void constraintPresentEvenIfNoMatches() {
scoreDirector.beforeVariableChanged(entity, "value");
entity.setValue(null);
scoreDirector.afterVariableChanged(entity, "value");
+ // FULL_ASSERT add variable listeners for tracking
+ scoreDirector.triggerVariableListeners();
var score2 = scoreDirector.calculateScore(); | This concerns me.
Are you saying we need to do something *new* in order to use this functionality?
Why would this code need it, if it doesn't run any of the assert modes? |
timefold-solver | github_2023 | java | 433 | TimefoldAI | triceo | @@ -19,6 +19,26 @@
*/
@XmlEnum
public enum EnvironmentMode {
+ /**
+ * This mode turns on variable tracking and all assertions to fail-fast on a bug in a {@link Move} implementation, a
+ * constraint, the engine itself or something else at an appalling performance cost.
+ * <p>
+ * Because it tracks genuine and shadow variables, it is able to report precisely what variables caused the corruption and
+ * report any missed {@link ai.timefold.solver.core.api.domain.variable.VariableListener} events.
+ * <p>
+ * When undo score corruption is detected, it throws an
+ * {@link ai.timefold.solver.core.api.solver.exception.UndoScoreCorruptionException}, which can be used to inspect the
+ * working solution state before, after and after the undo of a {@link Move}.
+ * <p>
+ * This mode is reproducible (see {@link #REPRODUCIBLE} mode).
+ * <p>
+ * This mode is intrusive because it calls the {@link InnerScoreDirector#calculateScore()} more frequently than a non assert
+ * mode.
+ * <p>
+ * This mode is appallingly slow.
+ */ | Besides the general comment on line breaks and formatting, I think maybe we're a bit more evolved now to use words such as "horrible" and "appaling" in user-facing documentation. :-)
In this case, I suggest "This mode is by far the slowest of all the modes."
Also, somewhere in the body of the text, I would reference that it does everything that `FULL_ASSERT` does, plus X and Y. If you can reference an information that is already somewhere else, I prefer you do so - that way, you still have only a single point of truth for that information, helping with future maintenance. |
timefold-solver | github_2023 | java | 433 | TimefoldAI | triceo | @@ -19,6 +19,26 @@
*/
@XmlEnum
public enum EnvironmentMode {
+ /**
+ * This mode turns on variable tracking and all assertions to fail-fast on a bug in a {@link Move} implementation, a
+ * constraint, the engine itself or something else at an appalling performance cost.
+ * <p>
+ * Because it tracks genuine and shadow variables, it is able to report precisely what variables caused the corruption and
+ * report any missed {@link ai.timefold.solver.core.api.domain.variable.VariableListener} events.
+ * <p>
+ * When undo score corruption is detected, it throws an
+ * {@link ai.timefold.solver.core.api.solver.exception.UndoScoreCorruptionException}, which can be used to inspect the
+ * working solution state before, after and after the undo of a {@link Move}.
+ * <p>
+ * This mode is reproducible (see {@link #REPRODUCIBLE} mode).
+ * <p>
+ * This mode is intrusive because it calls the {@link InnerScoreDirector#calculateScore()} more frequently than a non assert
+ * mode.
+ * <p>
+ * This mode is appallingly slow.
+ */
+ FULL_ASSERT_WITH_TRACKING(true),
+
/**
* This mode turns on all assertions | This no longer turns on _all_ assertions. |
timefold-solver | github_2023 | others | 433 | TimefoldAI | triceo | @@ -102,6 +102,59 @@ This mode is reproducible (see the reproducible mode). It is also intrusive beca
The FULL_ASSERT mode is horribly slow (because it does not rely on incremental score calculation).
+[#environmentModeTracedFullAssert]
+=== `TRACED_FULL_ASSERT`
+
+The TRACED_FULL_ASSERT mode turns on all the <<environmentModeFullAssert, FULL_ASSERT>> assertions and additionally track changes to the working solution. | ```suggestion
The TRACED_FULL_ASSERT mode turns on all the <<environmentModeFullAssert, FULL_ASSERT>> assertions and additionally tracks changes to the working solution.
``` |
timefold-solver | github_2023 | others | 433 | TimefoldAI | triceo | @@ -102,6 +102,59 @@ This mode is reproducible (see the reproducible mode). It is also intrusive beca
The FULL_ASSERT mode is horribly slow (because it does not rely on incremental score calculation).
+[#environmentModeTracedFullAssert]
+=== `TRACED_FULL_ASSERT`
+
+The TRACED_FULL_ASSERT mode turns on all the <<environmentModeFullAssert, FULL_ASSERT>> assertions and additionally track changes to the working solution.
+This allows the solver to report exactly what variables were corrupted and what variable listener events are missing.
+
+For instance, when this incorrect move is evaluated | ```suggestion
Consider the following incorrectly implemented move:
``` |
timefold-solver | github_2023 | others | 433 | TimefoldAI | triceo | @@ -102,6 +102,59 @@ This mode is reproducible (see the reproducible mode). It is also intrusive beca
The FULL_ASSERT mode is horribly slow (because it does not rely on incremental score calculation).
+[#environmentModeTracedFullAssert]
+=== `TRACED_FULL_ASSERT`
+
+The TRACED_FULL_ASSERT mode turns on all the <<environmentModeFullAssert, FULL_ASSERT>> assertions and additionally track changes to the working solution.
+This allows the solver to report exactly what variables were corrupted and what variable listener events are missing.
+
+For instance, when this incorrect move is evaluated
+
+```java
+ @Override
+ public Move<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) {
+ return this;
+ }
+
+ @Override
+ protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
+ scoreDirector.beforeVariableChanged(entity, "value");
+ entity.setValue(newValue);
+ scoreDirector.afterVariableChanged(entity, "value");
+ }
+```
+
+the exception thrown by the solver will have the following in its message: | ```suggestion
When it is evaluated by the solver, an exception will be thrown with the following in its message:
``` |
timefold-solver | github_2023 | others | 433 | TimefoldAI | triceo | @@ -102,6 +102,59 @@ This mode is reproducible (see the reproducible mode). It is also intrusive beca
The FULL_ASSERT mode is horribly slow (because it does not rely on incremental score calculation).
+[#environmentModeTracedFullAssert]
+=== `TRACED_FULL_ASSERT`
+
+The TRACED_FULL_ASSERT mode turns on all the <<environmentModeFullAssert, FULL_ASSERT>> assertions and additionally track changes to the working solution.
+This allows the solver to report exactly what variables were corrupted and what variable listener events are missing.
+
+For instance, when this incorrect move is evaluated
+
+```java
+ @Override
+ public Move<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) {
+ return this;
+ }
+
+ @Override
+ protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
+ scoreDirector.beforeVariableChanged(entity, "value");
+ entity.setValue(newValue);
+ scoreDirector.afterVariableChanged(entity, "value");
+ }
+```
+
+the exception thrown by the solver will have the following in its message:
+
+```
+Variables that are different between before and undo:
+ - Actual value (newValue) of variable value on EntityClass entity (entity) differs from expected (oldValue)
+```
+
+In particular, the solver will recalculate all shadow variables from scratch on the solution after the undo and then report:
+
+- Genuine and shadow variables that are different between before and undo. | ```suggestion
- Genuine and shadow variables that are different between "before" and "undo".
``` |
timefold-solver | github_2023 | others | 433 | TimefoldAI | triceo | @@ -102,6 +102,59 @@ This mode is reproducible (see the reproducible mode). It is also intrusive beca
The FULL_ASSERT mode is horribly slow (because it does not rely on incremental score calculation).
+[#environmentModeTracedFullAssert]
+=== `TRACED_FULL_ASSERT`
+
+The TRACED_FULL_ASSERT mode turns on all the <<environmentModeFullAssert, FULL_ASSERT>> assertions and additionally track changes to the working solution.
+This allows the solver to report exactly what variables were corrupted and what variable listener events are missing.
+
+For instance, when this incorrect move is evaluated
+
+```java
+ @Override
+ public Move<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) {
+ return this;
+ }
+
+ @Override
+ protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
+ scoreDirector.beforeVariableChanged(entity, "value");
+ entity.setValue(newValue);
+ scoreDirector.afterVariableChanged(entity, "value");
+ }
+```
+
+the exception thrown by the solver will have the following in its message:
+
+```
+Variables that are different between before and undo:
+ - Actual value (newValue) of variable value on EntityClass entity (entity) differs from expected (oldValue)
+```
+
+In particular, the solver will recalculate all shadow variables from scratch on the solution after the undo and then report:
+
+- Genuine and shadow variables that are different between before and undo.
+After an undo move is evaluated, it is expected to exactly match the original working solution.
+
+- Variables that are different between from scratch and before. | ```suggestion
- Variables that are different between "from scratch" and "before".
``` |
timefold-solver | github_2023 | others | 433 | TimefoldAI | triceo | @@ -102,6 +102,59 @@ This mode is reproducible (see the reproducible mode). It is also intrusive beca
The FULL_ASSERT mode is horribly slow (because it does not rely on incremental score calculation).
+[#environmentModeTracedFullAssert]
+=== `TRACED_FULL_ASSERT`
+
+The TRACED_FULL_ASSERT mode turns on all the <<environmentModeFullAssert, FULL_ASSERT>> assertions and additionally track changes to the working solution.
+This allows the solver to report exactly what variables were corrupted and what variable listener events are missing.
+
+For instance, when this incorrect move is evaluated
+
+```java
+ @Override
+ public Move<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) {
+ return this;
+ }
+
+ @Override
+ protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
+ scoreDirector.beforeVariableChanged(entity, "value");
+ entity.setValue(newValue);
+ scoreDirector.afterVariableChanged(entity, "value");
+ }
+```
+
+the exception thrown by the solver will have the following in its message:
+
+```
+Variables that are different between before and undo:
+ - Actual value (newValue) of variable value on EntityClass entity (entity) differs from expected (oldValue)
+```
+
+In particular, the solver will recalculate all shadow variables from scratch on the solution after the undo and then report:
+
+- Genuine and shadow variables that are different between before and undo.
+After an undo move is evaluated, it is expected to exactly match the original working solution.
+
+- Variables that are different between from scratch and before.
+This is to detect if the solution was corrupted before the move was evaluated due to shadow variable corruption.
+
+- Variables that are different between from scratch and undo. | ```suggestion
- Variables that are different between "from scratch" and "undo".
``` |
timefold-solver | github_2023 | others | 433 | TimefoldAI | triceo | @@ -102,6 +102,59 @@ This mode is reproducible (see the reproducible mode). It is also intrusive beca
The FULL_ASSERT mode is horribly slow (because it does not rely on incremental score calculation).
+[#environmentModeTracedFullAssert]
+=== `TRACED_FULL_ASSERT`
+
+The TRACED_FULL_ASSERT mode turns on all the <<environmentModeFullAssert, FULL_ASSERT>> assertions and additionally track changes to the working solution.
+This allows the solver to report exactly what variables were corrupted and what variable listener events are missing.
+
+For instance, when this incorrect move is evaluated
+
+```java
+ @Override
+ public Move<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) {
+ return this;
+ }
+
+ @Override
+ protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
+ scoreDirector.beforeVariableChanged(entity, "value");
+ entity.setValue(newValue);
+ scoreDirector.afterVariableChanged(entity, "value");
+ }
+```
+
+the exception thrown by the solver will have the following in its message:
+
+```
+Variables that are different between before and undo:
+ - Actual value (newValue) of variable value on EntityClass entity (entity) differs from expected (oldValue)
+```
+
+In particular, the solver will recalculate all shadow variables from scratch on the solution after the undo and then report:
+
+- Genuine and shadow variables that are different between before and undo.
+After an undo move is evaluated, it is expected to exactly match the original working solution.
+
+- Variables that are different between from scratch and before.
+This is to detect if the solution was corrupted before the move was evaluated due to shadow variable corruption.
+
+- Variables that are different between from scratch and undo.
+This is to detect if recalculating the shadow variables from scratch is different from the incremental shadow variable calculation.
+
+- Missing variable listener events for actual move. | ```suggestion
- Missing variable listener events for the actual move.
``` |
timefold-solver | github_2023 | others | 433 | TimefoldAI | triceo | @@ -102,6 +102,59 @@ This mode is reproducible (see the reproducible mode). It is also intrusive beca
The FULL_ASSERT mode is horribly slow (because it does not rely on incremental score calculation).
+[#environmentModeTracedFullAssert]
+=== `TRACED_FULL_ASSERT`
+
+The TRACED_FULL_ASSERT mode turns on all the <<environmentModeFullAssert, FULL_ASSERT>> assertions and additionally track changes to the working solution.
+This allows the solver to report exactly what variables were corrupted and what variable listener events are missing.
+
+For instance, when this incorrect move is evaluated
+
+```java
+ @Override
+ public Move<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) {
+ return this;
+ }
+
+ @Override
+ protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
+ scoreDirector.beforeVariableChanged(entity, "value");
+ entity.setValue(newValue);
+ scoreDirector.afterVariableChanged(entity, "value");
+ }
+```
+
+the exception thrown by the solver will have the following in its message:
+
+```
+Variables that are different between before and undo:
+ - Actual value (newValue) of variable value on EntityClass entity (entity) differs from expected (oldValue)
+```
+
+In particular, the solver will recalculate all shadow variables from scratch on the solution after the undo and then report:
+
+- Genuine and shadow variables that are different between before and undo.
+After an undo move is evaluated, it is expected to exactly match the original working solution.
+
+- Variables that are different between from scratch and before.
+This is to detect if the solution was corrupted before the move was evaluated due to shadow variable corruption.
+
+- Variables that are different between from scratch and undo.
+This is to detect if recalculating the shadow variables from scratch is different from the incremental shadow variable calculation.
+
+- Missing variable listener events for actual move.
+Any variable that changed between the before move solution and after move solution without either a | ```suggestion
Any variable that changed between the "before move" solution and the "after move" solution without either a
``` |
timefold-solver | github_2023 | others | 433 | TimefoldAI | triceo | @@ -102,6 +102,59 @@ This mode is reproducible (see the reproducible mode). It is also intrusive beca
The FULL_ASSERT mode is horribly slow (because it does not rely on incremental score calculation).
+[#environmentModeTracedFullAssert]
+=== `TRACED_FULL_ASSERT`
+
+The TRACED_FULL_ASSERT mode turns on all the <<environmentModeFullAssert, FULL_ASSERT>> assertions and additionally track changes to the working solution.
+This allows the solver to report exactly what variables were corrupted and what variable listener events are missing.
+
+For instance, when this incorrect move is evaluated
+
+```java
+ @Override
+ public Move<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) {
+ return this;
+ }
+
+ @Override
+ protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
+ scoreDirector.beforeVariableChanged(entity, "value");
+ entity.setValue(newValue);
+ scoreDirector.afterVariableChanged(entity, "value");
+ }
+```
+
+the exception thrown by the solver will have the following in its message:
+
+```
+Variables that are different between before and undo:
+ - Actual value (newValue) of variable value on EntityClass entity (entity) differs from expected (oldValue)
+```
+
+In particular, the solver will recalculate all shadow variables from scratch on the solution after the undo and then report:
+
+- Genuine and shadow variables that are different between before and undo.
+After an undo move is evaluated, it is expected to exactly match the original working solution.
+
+- Variables that are different between from scratch and before.
+This is to detect if the solution was corrupted before the move was evaluated due to shadow variable corruption.
+
+- Variables that are different between from scratch and undo.
+This is to detect if recalculating the shadow variables from scratch is different from the incremental shadow variable calculation.
+
+- Missing variable listener events for actual move.
+Any variable that changed between the before move solution and after move solution without either a
+`beforeVariableChanged` or `afterVariableChanged` would be reported here.
+
+- Missing variable listener events for undo move.
+Any variable that changed between the after move solution and after undo move solution without either a | ```suggestion
Any variable that changed between the "after move" solution and "after undo move" solution without either a
``` |
timefold-solver | github_2023 | others | 433 | TimefoldAI | triceo | @@ -102,6 +102,59 @@ This mode is reproducible (see the reproducible mode). It is also intrusive beca
The FULL_ASSERT mode is horribly slow (because it does not rely on incremental score calculation).
+[#environmentModeTracedFullAssert]
+=== `TRACED_FULL_ASSERT`
+
+The TRACED_FULL_ASSERT mode turns on all the <<environmentModeFullAssert, FULL_ASSERT>> assertions and additionally track changes to the working solution.
+This allows the solver to report exactly what variables were corrupted and what variable listener events are missing.
+
+For instance, when this incorrect move is evaluated
+
+```java
+ @Override
+ public Move<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) {
+ return this;
+ }
+
+ @Override
+ protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
+ scoreDirector.beforeVariableChanged(entity, "value");
+ entity.setValue(newValue);
+ scoreDirector.afterVariableChanged(entity, "value");
+ }
+```
+
+the exception thrown by the solver will have the following in its message:
+
+```
+Variables that are different between before and undo:
+ - Actual value (newValue) of variable value on EntityClass entity (entity) differs from expected (oldValue)
+```
+
+In particular, the solver will recalculate all shadow variables from scratch on the solution after the undo and then report:
+
+- Genuine and shadow variables that are different between before and undo.
+After an undo move is evaluated, it is expected to exactly match the original working solution.
+
+- Variables that are different between from scratch and before.
+This is to detect if the solution was corrupted before the move was evaluated due to shadow variable corruption.
+
+- Variables that are different between from scratch and undo.
+This is to detect if recalculating the shadow variables from scratch is different from the incremental shadow variable calculation.
+
+- Missing variable listener events for actual move.
+Any variable that changed between the before move solution and after move solution without either a
+`beforeVariableChanged` or `afterVariableChanged` would be reported here.
+
+- Missing variable listener events for undo move.
+Any variable that changed between the after move solution and after undo move solution without either a
+`beforeVariableChanged` or `afterVariableChanged` would be reported here.
+
+This mode is reproducible (see the reproducible mode). | The reproducible mode deserves a direct reference. (Unless it doesn't have an ID.) |
timefold-solver | github_2023 | others | 433 | TimefoldAI | triceo | @@ -102,6 +102,59 @@ This mode is reproducible (see the reproducible mode). It is also intrusive beca
The FULL_ASSERT mode is horribly slow (because it does not rely on incremental score calculation).
+[#environmentModeTracedFullAssert]
+=== `TRACED_FULL_ASSERT`
+
+The TRACED_FULL_ASSERT mode turns on all the <<environmentModeFullAssert, FULL_ASSERT>> assertions and additionally track changes to the working solution.
+This allows the solver to report exactly what variables were corrupted and what variable listener events are missing.
+
+For instance, when this incorrect move is evaluated
+
+```java
+ @Override
+ public Move<Solution_> createUndoMove(ScoreDirector<Solution_> scoreDirector) {
+ return this;
+ }
+
+ @Override
+ protected void doMoveOnGenuineVariables(ScoreDirector<Solution_> scoreDirector) {
+ scoreDirector.beforeVariableChanged(entity, "value");
+ entity.setValue(newValue);
+ scoreDirector.afterVariableChanged(entity, "value");
+ }
+```
+
+the exception thrown by the solver will have the following in its message:
+
+```
+Variables that are different between before and undo:
+ - Actual value (newValue) of variable value on EntityClass entity (entity) differs from expected (oldValue)
+```
+
+In particular, the solver will recalculate all shadow variables from scratch on the solution after the undo and then report:
+
+- Genuine and shadow variables that are different between before and undo.
+After an undo move is evaluated, it is expected to exactly match the original working solution.
+
+- Variables that are different between from scratch and before.
+This is to detect if the solution was corrupted before the move was evaluated due to shadow variable corruption.
+
+- Variables that are different between from scratch and undo.
+This is to detect if recalculating the shadow variables from scratch is different from the incremental shadow variable calculation.
+
+- Missing variable listener events for actual move.
+Any variable that changed between the before move solution and after move solution without either a
+`beforeVariableChanged` or `afterVariableChanged` would be reported here.
+
+- Missing variable listener events for undo move.
+Any variable that changed between the after move solution and after undo move solution without either a
+`beforeVariableChanged` or `afterVariableChanged` would be reported here.
+
+This mode is reproducible (see the reproducible mode).
+It is also intrusive because it calls the method `calculateScore()` more frequently than a non-assert mode.
+
+The TRACED_FULL_ASSERT mode is by far the slowest mode (because it clones solutions before and after each move). | ```suggestion
The `TRACED_FULL_ASSERT` mode is by far the slowest mode,
because it clones solutions before and after each move.
``` |
timefold-solver | github_2023 | others | 432 | TimefoldAI | rsynek | @@ -522,6 +522,109 @@ A `BestSolutionChangedEvent` does not guarantee that every `ProblemChange` has b
. Use `Score.isSolutionInitialized()` instead of `Score.isFeasible()` to only ignore uninitialized solutions, but do accept infeasible solutions too.
+
+[#recommendedFitAPI]
+== Responding to adhoc changes
+
+With <<realTimePlanning,real-time planning>>, we can respond to a continuous stream of external changes.
+However, it is often necessary to respond to adhoc changes too,
+for example when a call center operator needs to arrange an appointment with a customer.
+In such cases, it is not necessary to use the full power of real-time planning.
+Instead, immediate response to the customer and a selection of available time windows are more important.
+This is where _Recommended Fit API_ comes in.
+
+The Recommended Fit API is a simple API that allows you to quickly respond to adhoc changes, | Every user might have a different idea what a simple API is.
```suggestion
The Recommended Fit API allows you to quickly respond to adhoc changes,
``` |
timefold-solver | github_2023 | others | 432 | TimefoldAI | rsynek | @@ -522,6 +522,109 @@ A `BestSolutionChangedEvent` does not guarantee that every `ProblemChange` has b
. Use `Score.isSolutionInitialized()` instead of `Score.isFeasible()` to only ignore uninitialized solutions, but do accept infeasible solutions too.
+
+[#recommendedFitAPI]
+== Responding to adhoc changes
+
+With <<realTimePlanning,real-time planning>>, we can respond to a continuous stream of external changes.
+However, it is often necessary to respond to adhoc changes too,
+for example when a call center operator needs to arrange an appointment with a customer.
+In such cases, it is not necessary to use the full power of real-time planning.
+Instead, immediate response to the customer and a selection of available time windows are more important.
+This is where _Recommended Fit API_ comes in.
+
+The Recommended Fit API is a simple API that allows you to quickly respond to adhoc changes,
+while providing a selection of the best available options for fitting the change in the existing schedule.
+It doesn't use the full xref:optimization-algorithms/optimization-algorithms.adoc#localSearch[local search algorithm].
+Instead,
+it uses a simple xref:optimization-algorithms/optimization-algorithms.adoc#constructionHeuristics[greedy algorithm]
+together with xref:constraints-and-score/performance.adoc#incrementalScoreCalculation[incremental calculation].
+This combination allows the API to find the best possible fit within the existing solution in a matter of milliseconds,
+even for large planning problems.
+
+Once the customer has accepted of the available options | ```suggestion
Once the customer has accepted one of the available options
``` |
timefold-solver | github_2023 | others | 432 | TimefoldAI | rsynek | @@ -522,6 +522,109 @@ A `BestSolutionChangedEvent` does not guarantee that every `ProblemChange` has b
. Use `Score.isSolutionInitialized()` instead of `Score.isFeasible()` to only ignore uninitialized solutions, but do accept infeasible solutions too.
+
+[#recommendedFitAPI]
+== Responding to adhoc changes
+
+With <<realTimePlanning,real-time planning>>, we can respond to a continuous stream of external changes.
+However, it is often necessary to respond to adhoc changes too,
+for example when a call center operator needs to arrange an appointment with a customer.
+In such cases, it is not necessary to use the full power of real-time planning.
+Instead, immediate response to the customer and a selection of available time windows are more important.
+This is where _Recommended Fit API_ comes in.
+
+The Recommended Fit API is a simple API that allows you to quickly respond to adhoc changes,
+while providing a selection of the best available options for fitting the change in the existing schedule.
+It doesn't use the full xref:optimization-algorithms/optimization-algorithms.adoc#localSearch[local search algorithm].
+Instead,
+it uses a simple xref:optimization-algorithms/optimization-algorithms.adoc#constructionHeuristics[greedy algorithm]
+together with xref:constraints-and-score/performance.adoc#incrementalScoreCalculation[incremental calculation].
+This combination allows the API to find the best possible fit within the existing solution in a matter of milliseconds,
+even for large planning problems.
+
+Once the customer has accepted of the available options
+and the change has been reflected in the solution,
+the full xref:optimization-algorithms/optimization-algorithms.adoc#localSearch[local search algorithm]
+can be used to optimize the entire solution around this change.
+This would be an example of <<continuousPlanning,continuous planning>>.
+
+[#usingRecommendedFitAPI]
+=== Using the Recommended Fit API
+
+The Recommended Fit API requires one uninitialized entity to be present in the solution:
+
+[source,java,options="nowrap"]
+----
+NurseRoster nurseRoster = ...; // Our planning solution.
+ShiftAssignment unassignedShift = new ShiftAssignment(...); // A new shift needs to be assigned.
+nurseRoster.getShiftAssignmentList().add(unassignedShift);
+----
+
+The `SolutionManager` is then used to retrieve the recommended fit for the uninitialized entity:
+
+[source,java,options="nowrap"]
+----
+SolutionManager<NurseRoster, HardSoftScore> solutionManager = ...;
+List<RecommendedFit<Employee, HardSoftScore>> recommendations = | What happens if the planning entity has two planning variables of different types? Do we call the API twice (for every variable with different proposition functions)? |
timefold-solver | github_2023 | others | 432 | TimefoldAI | rsynek | @@ -522,6 +522,109 @@ A `BestSolutionChangedEvent` does not guarantee that every `ProblemChange` has b
. Use `Score.isSolutionInitialized()` instead of `Score.isFeasible()` to only ignore uninitialized solutions, but do accept infeasible solutions too.
+
+[#recommendedFitAPI]
+== Responding to adhoc changes
+
+With <<realTimePlanning,real-time planning>>, we can respond to a continuous stream of external changes.
+However, it is often necessary to respond to adhoc changes too,
+for example when a call center operator needs to arrange an appointment with a customer.
+In such cases, it is not necessary to use the full power of real-time planning.
+Instead, immediate response to the customer and a selection of available time windows are more important.
+This is where _Recommended Fit API_ comes in.
+
+The Recommended Fit API is a simple API that allows you to quickly respond to adhoc changes,
+while providing a selection of the best available options for fitting the change in the existing schedule.
+It doesn't use the full xref:optimization-algorithms/optimization-algorithms.adoc#localSearch[local search algorithm].
+Instead,
+it uses a simple xref:optimization-algorithms/optimization-algorithms.adoc#constructionHeuristics[greedy algorithm]
+together with xref:constraints-and-score/performance.adoc#incrementalScoreCalculation[incremental calculation].
+This combination allows the API to find the best possible fit within the existing solution in a matter of milliseconds,
+even for large planning problems.
+
+Once the customer has accepted of the available options
+and the change has been reflected in the solution,
+the full xref:optimization-algorithms/optimization-algorithms.adoc#localSearch[local search algorithm]
+can be used to optimize the entire solution around this change.
+This would be an example of <<continuousPlanning,continuous planning>>.
+
+[#usingRecommendedFitAPI]
+=== Using the Recommended Fit API
+
+The Recommended Fit API requires one uninitialized entity to be present in the solution:
+
+[source,java,options="nowrap"]
+----
+NurseRoster nurseRoster = ...; // Our planning solution.
+ShiftAssignment unassignedShift = new ShiftAssignment(...); // A new shift needs to be assigned.
+nurseRoster.getShiftAssignmentList().add(unassignedShift);
+----
+
+The `SolutionManager` is then used to retrieve the recommended fit for the uninitialized entity:
+
+[source,java,options="nowrap"]
+----
+SolutionManager<NurseRoster, HardSoftScore> solutionManager = ...;
+List<RecommendedFit<Employee, HardSoftScore>> recommendations =
+ solutionManager.recommendFit(nurseRoster, unassignedShift, ShiftAssignment::getEmployee);
+----
+
+Breaking this down, we have:
+
+- `nurseRoster`, the planning solution.
+- `unassignedShift`, the uninitialized entity, which is part of the planning solution.
+- `ShiftAssignment::getEmployee`, a function extracting the planning variable from the entity,
+also called a "proposition function".
+- `List<RecommendedFit<Employee, HardSoftScore>>`, the list of recommended employees to assign to the shift,
+in the order of decreasing preference.
+Each recommendation contains the employee and the difference in score caused by assigning the employee to the shift.
+This difference has the full explanatory power of xref:constraints-and-score/understanding-the-score.adoc#scoreAnalysis[score analysis].
+
+This list of recommendations can be used to present the operator with a selection of available options,
+as it is fully serializable to JSON and can be sent to a web browser or mobile app.
+The operator can then select the best available recommendation and assign the employee to the shift,
+represented here by the necessary backend code:
+
+[source,java,options="nowrap"]
+----
+RecommendedFit<Employee, HardSoftScore> bestRecommendation = recommendations.get(0);
+Employee bestEmployee = bestRecommendation.proposition();
+unassignedShift.setEmployee(bestEmployee);
+----
+
+If required, <<continuousPlanning,continuous planning>> can be used to optimize the entire solution afterwards.
+
+[#usingMutableTypesInPropositionFunction]
+=== Using mutable types in the proposition function
+
+In the previous example,
+we used a simple proposition function that extracts the planning variable from the entity.
+However,
+it is also possible to use a more complex proposition function that extracts the entire planning entity,
+or any values that will mutate as the solver tries to find the best fit.
+In that case, there are some caveats to consider.
+
+The solver will try to find the best fit for the uninitialized entity,
+and it will start from the solution it received on input.
+Before trying the next value to assign, it will first return to that original solution.
+The consequence of this is that if our proposition function returns any values that change during this process,
+those changes will also affect the previously processed propositions.
+
+In other words, if we decide to return the entire entity from the proposition function, | Can you maybe think of an example to show this situation? |
timefold-solver | github_2023 | java | 432 | TimefoldAI | mcimbora | @@ -0,0 +1,50 @@
+package ai.timefold.solver.core.impl.solver;
+
+import java.util.List;
+import java.util.Objects;
+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_>>> {
+
+ private final DefaultSolverFactory<Solution_> solverFactory;
+ private final Solution_ originalSolution;
+ private final In_ originalElement;
+ private final Function<In_, Out_> propositionFunction;
+ private final ScoreAnalysisFetchPolicy fetchPolicy;
+
+ public Fitter(DefaultSolverFactory<Solution_> solverFactory, Solution_ originalSolution, In_ originalElement,
+ Function<In_, Out_> propositionFunction, ScoreAnalysisFetchPolicy fetchPolicy) {
+ this.solverFactory = Objects.requireNonNull(solverFactory);
+ this.originalSolution = Objects.requireNonNull(originalSolution);
+ this.originalElement = Objects.requireNonNull(originalElement);
+ this.propositionFunction = Objects.requireNonNull(propositionFunction);
+ this.fetchPolicy = Objects.requireNonNull(fetchPolicy);
+ }
+
+ @Override
+ public List<RecommendedFit<Out_, Score_>> 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(""" | Trying to understand this check. Let's say I've got the following solution with nullable variables (which is very common use case, since you might not be able to assign all the shifts everytime the solver runs).
Shift A - null
Shift B - employee1
Shift C - employee2
Now I call recommend(solution_with_shift_D, Shift D). This will contain 2 unitialized shifts (Shift A, Shift D). Does the new API handle this case, or throws an exception? |
timefold-solver | github_2023 | java | 446 | TimefoldAI | mcimbora | @@ -11,12 +13,12 @@ public interface SequenceChain<Value_, Difference_ extends Comparable<Difference
/**
* @return never null; the sequences contained in the collection in ascending order.
*/
- Iterable<Sequence<Value_, Difference_>> getConsecutiveSequences();
+ Collection<Sequence<Value_, Difference_>> getConsecutiveSequences(); | +1 Collection is easier to work with.
Unrelated to this changeset, with List, we could even get rid of getFirst/last etc? No strong opinion if these will be used. |
timefold-solver | github_2023 | java | 446 | TimefoldAI | mcimbora | @@ -0,0 +1,252 @@
+package ai.timefold.solver.jackson.api.score.stream.common;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.SoftAssertions.assertSoftly;
+
+import java.util.List;
+
+import ai.timefold.solver.core.api.score.stream.ConstraintCollectors;
+import ai.timefold.solver.core.api.score.stream.common.Break;
+import ai.timefold.solver.core.api.score.stream.common.Sequence;
+import ai.timefold.solver.core.api.score.stream.common.SequenceChain;
+import ai.timefold.solver.core.api.score.stream.uni.UniConstraintCollector;
+import ai.timefold.solver.core.impl.score.stream.SequenceCalculator;
+import ai.timefold.solver.jackson.api.TimefoldJacksonModule;
+
+import org.junit.jupiter.api.Test;
+
+import com.fasterxml.jackson.annotation.JsonIdentityInfo;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.ObjectIdGenerators;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.MapperFeature;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.json.JsonMapper;
+
+class SequenceRoundTripTest {
+
+ @JsonIdentityInfo(scope = Item.class, generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
+ private record Item(String id, int index) {
+
+ }
+
+ @Test
+ void roundTrip() throws JsonProcessingException {
+ // Prepare the data to be serialized.
+ Item sequence1Item1 = new Item("sequence1Item1", 0);
+ Item sequence1Item2 = new Item("sequence1Item2", 1);
+ Item sequence2Item1 = new Item("sequence2Item1", 3);
+ Item sequence2Item2 = new Item("sequence2Item2", 4);
+ Item sequence2Item3 = new Item("sequence2Item3", 5);
+ Item sequence3Item1 = new Item("sequence3Item1", 7);
+ UniConstraintCollector<Item, SequenceCalculator<Integer>, SequenceChain<Item, Integer>> collector =
+ (UniConstraintCollector) ConstraintCollectors.toConsecutiveSequences(Item::index);
+ var context = collector.supplier().get();
+ var accumulator = collector.accumulator();
+ for (var item : List.of(sequence1Item1, sequence1Item2, sequence2Item1, sequence2Item2, sequence2Item3,
+ sequence3Item1)) {
+ accumulator.apply(context, item);
+ }
+
+ // Retrieve the instances to be serialized.
+ var sequenceChain = collector.finisher().apply(context);
+ var sequences = sequenceChain.getConsecutiveSequences().toArray(new Sequence[0]);
+ var breaks = sequenceChain.getBreaks().toArray(new Break[0]);
+
+ ObjectMapper objectMapper = JsonMapper.builder()
+ .enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY)
+ .serializationInclusion(JsonInclude.Include.NON_NULL)
+ .addModule(TimefoldJacksonModule.createModule())
+ .build();
+
+ assertSequenceChainRoundTrip(objectMapper, sequenceChain, """
+ {
+ "sequences" : [ {
+ "first" : true, | Wondering if we need first/last attributes? This can be derived from the position of the sequence in the array, wdyt? |
timefold-solver | github_2023 | java | 446 | TimefoldAI | mcimbora | @@ -0,0 +1,252 @@
+package ai.timefold.solver.jackson.api.score.stream.common;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.SoftAssertions.assertSoftly;
+
+import java.util.List;
+
+import ai.timefold.solver.core.api.score.stream.ConstraintCollectors;
+import ai.timefold.solver.core.api.score.stream.common.Break;
+import ai.timefold.solver.core.api.score.stream.common.Sequence;
+import ai.timefold.solver.core.api.score.stream.common.SequenceChain;
+import ai.timefold.solver.core.api.score.stream.uni.UniConstraintCollector;
+import ai.timefold.solver.core.impl.score.stream.SequenceCalculator;
+import ai.timefold.solver.jackson.api.TimefoldJacksonModule;
+
+import org.junit.jupiter.api.Test;
+
+import com.fasterxml.jackson.annotation.JsonIdentityInfo;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.ObjectIdGenerators;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.MapperFeature;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.json.JsonMapper;
+
+class SequenceRoundTripTest {
+
+ @JsonIdentityInfo(scope = Item.class, generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
+ private record Item(String id, int index) {
+
+ }
+
+ @Test
+ void roundTrip() throws JsonProcessingException {
+ // Prepare the data to be serialized.
+ Item sequence1Item1 = new Item("sequence1Item1", 0);
+ Item sequence1Item2 = new Item("sequence1Item2", 1);
+ Item sequence2Item1 = new Item("sequence2Item1", 3);
+ Item sequence2Item2 = new Item("sequence2Item2", 4);
+ Item sequence2Item3 = new Item("sequence2Item3", 5);
+ Item sequence3Item1 = new Item("sequence3Item1", 7);
+ UniConstraintCollector<Item, SequenceCalculator<Integer>, SequenceChain<Item, Integer>> collector =
+ (UniConstraintCollector) ConstraintCollectors.toConsecutiveSequences(Item::index);
+ var context = collector.supplier().get();
+ var accumulator = collector.accumulator();
+ for (var item : List.of(sequence1Item1, sequence1Item2, sequence2Item1, sequence2Item2, sequence2Item3,
+ sequence3Item1)) {
+ accumulator.apply(context, item);
+ }
+
+ // Retrieve the instances to be serialized.
+ var sequenceChain = collector.finisher().apply(context);
+ var sequences = sequenceChain.getConsecutiveSequences().toArray(new Sequence[0]);
+ var breaks = sequenceChain.getBreaks().toArray(new Break[0]);
+
+ ObjectMapper objectMapper = JsonMapper.builder()
+ .enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY)
+ .serializationInclusion(JsonInclude.Include.NON_NULL)
+ .addModule(TimefoldJacksonModule.createModule())
+ .build();
+
+ assertSequenceChainRoundTrip(objectMapper, sequenceChain, """
+ {
+ "sequences" : [ {
+ "first" : true,
+ "items" : [ {
+ "id" : "sequence1Item1",
+ "index" : 0
+ }, {
+ "id" : "sequence1Item2",
+ "index" : 1
+ } ],
+ "last" : false
+ }, {
+ "first" : false,
+ "items" : [ {
+ "id" : "sequence2Item1",
+ "index" : 3
+ }, {
+ "id" : "sequence2Item2",
+ "index" : 4
+ }, {
+ "id" : "sequence2Item3",
+ "index" : 5
+ } ],
+ "last" : false
+ }, {
+ "first" : false,
+ "items" : [ {
+ "id" : "sequence3Item1",
+ "index" : 7
+ } ],
+ "last" : true
+ } ]
+ }""");
+
+ assertSequenceRoundTrip(objectMapper, sequences[0], """
+ {
+ "first" : true,
+ "items" : [ {
+ "id" : "sequence1Item1",
+ "index" : 0
+ }, {
+ "id" : "sequence1Item2",
+ "index" : 1
+ } ],
+ "last": false,
+ "next_break" : {
+ "first" : true,
+ "last" : false,
+ "next_sequence_start" : {
+ "id" : "sequence2Item1",
+ "index" : 3
+ },
+ "previous_sequence_end" : "sequence1Item2"
+ }
+ }""");
+ assertSequenceRoundTrip(objectMapper, sequences[1], """
+ {
+ "first" : false,
+ "items" : [ {
+ "id" : "sequence2Item1",
+ "index" : 3
+ }, {
+ "id" : "sequence2Item2",
+ "index" : 4
+ }, {
+ "id" : "sequence2Item3",
+ "index" : 5
+ } ],
+ "last": false,
+ "next_break" : {
+ "first" : false,
+ "last" : true,
+ "next_sequence_start" : {
+ "id" : "sequence3Item1",
+ "index" : 7
+ },
+ "previous_sequence_end" : "sequence2Item3" | Got that, when a sequence with an id is already included in the payload, we use the id reference, otherwise we attach the sequence object (id + index). |
timefold-solver | github_2023 | others | 437 | TimefoldAI | rsynek | @@ -6,16 +6,20 @@
** xref:quickstart/spring-boot/spring-boot-quickstart.adoc[leveloffset=+1]
* xref:use-cases-and-examples/use-cases-and-examples.adoc[leveloffset=+1]
* xref:configuration/configuration.adoc[leveloffset=+1] | What is the difference between this configuration chapter and the `using-timefold-solver/configuration.adoc` ? I would rather avoid duplicate menu entries. |
timefold-solver | github_2023 | java | 428 | TimefoldAI | rsynek | @@ -1,115 +1,568 @@
package ai.timefold.solver.constraint.streams.bavet.common.index;
-import java.util.Map;
+import java.util.ArrayList;
import java.util.NavigableMap;
import java.util.TreeMap;
+import java.util.function.BiFunction;
+import java.util.function.Function;
import java.util.function.Supplier;
+import ai.timefold.solver.constraint.streams.bavet.common.tuple.AbstractTuple;
+import ai.timefold.solver.constraint.streams.bavet.common.tuple.TriTuple;
import ai.timefold.solver.constraint.streams.common.AbstractJoiner;
+import ai.timefold.solver.constraint.streams.common.bi.DefaultBiJoiner;
+import ai.timefold.solver.constraint.streams.common.penta.DefaultPentaJoiner;
+import ai.timefold.solver.constraint.streams.common.quad.DefaultQuadJoiner;
+import ai.timefold.solver.constraint.streams.common.tri.DefaultTriJoiner;
+import ai.timefold.solver.core.api.function.QuadFunction;
+import ai.timefold.solver.core.api.function.TriFunction;
import ai.timefold.solver.core.impl.score.stream.JoinerType;
+import ai.timefold.solver.core.impl.util.Pair;
+import ai.timefold.solver.core.impl.util.Quadruple;
+import ai.timefold.solver.core.impl.util.Triple;
-public class IndexerFactory {
+/**
+ * {@link Indexer Indexers} form a parent-child hierarchy,
+ * each child has exactly one parent.
+ * {@link NoneIndexer} is always at the bottom of the hierarchy,
+ * never a parent unless it is the only indexer.
+ * Parent indexers delegate to their children,
+ * until they reach the ultimate {@link NoneIndexer}.
+ * <p>
+ * Example 1: EQUAL+LESS_THAN joiner will become EqualsIndexer -> ComparisonIndexer -> NoneIndexer.
+ * <p>
+ * Indexers have an id, which is the position of the indexer in the chain.
+ * Top-most indexer has id 0, and the id increases as we go down the hierarchy.
+ * Each {@link AbstractTuple tuple} is assigned an {@link IndexProperties} instance,
+ * which determines its location in the index.
+ * {@link IndexProperties} instances are built from {@link AbstractJoiner joiners}
+ * using methods such as {@link #buildUniLeftMapping()} and {@link #buildRightMapping()}.
+ * Each {@link IndexProperties#toKey(int) index keyFunction} has an id,
+ * and this id matches the id of the indexer;
+ * each keyFunction in {@link IndexProperties} is associated with a single indexer.
+ * <p>
+ * Comparison joiners result in a single indexer each,
+ * whereas equal joiners will be merged into a single indexer if they are consecutive.
+ * In the latter case,
+ * a composite keyFunction is created of type {@link Pair}, {@link TriTuple},
+ * {@link Quadruple} or {@link IndexerKey},
+ * based on the length of the composite keyFunction (number of equals joiners in sequence).
+ *
+ * <ul>
+ * <li>Example 2: For an EQUAL+LESS_THAN joiner,
+ * there are two indexers in the chain with keyFunction length of 1 each.</li>
+ * <li>Example 3: For an LESS_THAN+EQUAL+EQUAL joiner,
+ * there are still two indexers,
+ * but the second indexer's keyFunction length is 2.</li>
+ * <li>Example 4: For an LESS_THAN+EQUAL+EQUAL+LESS_THAN joiner,
+ * there are three indexers in the chain,
+ * and the middle one's keyFunction length is 2.</li>
+ * </ul>
+ *
+ * @param <Right_>
+ */
+public class IndexerFactory<Right_> {
- private final JoinerType[] joinerTypes;
+ private final AbstractJoiner<Right_> joiner;
+ private final NavigableMap<Integer, JoinerType> joinerTypeMap;
- public IndexerFactory(AbstractJoiner joiner) {
- int joinerCount = joiner.getJoinerCount();
- joinerTypes = new JoinerType[joinerCount];
- for (int i = 0; i < joinerCount; i++) {
- JoinerType joinerType = joiner.getJoinerType(i);
- switch (joinerType) {
- case EQUAL:
- case LESS_THAN:
- case LESS_THAN_OR_EQUAL:
- case GREATER_THAN:
- case GREATER_THAN_OR_EQUAL:
- break;
- default:
- throw new UnsupportedOperationException("Unsupported joiner type (" + joinerType + ").");
+ public IndexerFactory(AbstractJoiner<Right_> joiner) {
+ this.joiner = joiner;
+ var joinerCount = joiner.getJoinerCount();
+ if (joinerCount < 2) {
+ joinerTypeMap = null;
+ } else {
+ joinerTypeMap = new TreeMap<>();
+ for (var i = 1; i <= joinerCount; i++) {
+ var joinerType = i < joinerCount ? joiner.getJoinerType(i) : null;
+ var previousJoinerType = joiner.getJoinerType(i - 1);
+ if (joinerType != JoinerType.EQUAL || previousJoinerType != joinerType) {
+ // Equal joiner may build composite keyFunction with preceding equal joiner(s). | The condition and the comment made me think there is a bug at the first glance; after carefully looking in the code I understand we intentionally skip the map for Equal joiners so that the index increases through the iteration.
Maybe a bit more explanatory comment would help. |
timefold-solver | github_2023 | java | 426 | TimefoldAI | Christopher-Chianelli | @@ -1829,6 +1879,248 @@ public static <A, ResultContainer_, Result_> UniConstraintCollector<A, ResultCon
composeFunction);
}
+ // ************************************************************************
+ // consecutive collectors
+ // ************************************************************************
+
+ /**
+ * Creates a constraint collector that returns {@link SequenceChain} about the first fact.
+ *
+ * For instance, {@code [Shift slot=1] [Shift slot=2] [Shift slot=4] [Shift slot=6]}
+ * returns the following information:
+ *
+ * <pre>
+ * {@code
+ * Consecutive Lengths: 2, 1, 1
+ * Break Lengths: 1, 2
+ * Consecutive Items: [[Shift slot=1] [Shift slot=2]], [[Shift slot=4]], [[Shift slot=6]]
+ * }
+ * </pre>
+ *
+ * @param indexMap Maps the fact to its position in the sequence
+ * @param <A> type of the first mapped fact
+ * @return never null
+ */
+ public static <A> UniConstraintCollector<A, ?, SequenceChain<A, Integer>>
+ toConsecutiveSequences(ToIntFunction<A> indexMap) {
+ return InnerUniConstraintCollectors.toConsecutiveSequences(indexMap);
+ }
+
+ /**
+ * Contains info regarding the consecutive sequences and breaks in a collection of points.
+ *
+ * @param <Value_> The type of value in the sequence.
+ * @param <Difference_> The type of difference between values in the sequence.
+ */
+ public interface SequenceChain<Value_, Difference_ extends Comparable<Difference_>> { | I wonder if these interfaces should be top-level |
timefold-solver | github_2023 | java | 426 | TimefoldAI | Christopher-Chianelli | @@ -0,0 +1,40 @@
+package ai.timefold.solver.core.impl.score.stream.bi;
+
+import java.util.Objects;
+import java.util.function.BiFunction;
+import java.util.function.Supplier;
+import java.util.function.ToIntFunction;
+
+import ai.timefold.solver.core.api.score.stream.ConstraintCollectors.SequenceChain;
+import ai.timefold.solver.core.impl.score.stream.SequenceCalculator;
+
+final class ConsecutiveSequencesBiConstraintCollector<A, B, Result_>
+ extends
+ ObjectCalculatorBiCollector<A, B, Result_, SequenceChain<Result_, Integer>, SequenceCalculator<Result_>> {
+
+ private final ToIntFunction<Result_> indexMap;
+
+ public ConsecutiveSequencesBiConstraintCollector(BiFunction<A, B, Result_> resultMap, ToIntFunction<Result_> indexMap) {
+ super(resultMap);
+ this.indexMap = Objects.requireNonNull(indexMap);
+ }
+
+ @Override
+ public Supplier<SequenceCalculator<Result_>> supplier() {
+ return () -> new SequenceCalculator<>(indexMap);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o instanceof ConsecutiveSequencesBiConstraintCollector<?, ?, ?> other) { | You can call `super.equals()` to check if mappers are the same |
timefold-solver | github_2023 | java | 426 | TimefoldAI | Christopher-Chianelli | @@ -10,9 +10,9 @@
abstract sealed class ObjectCalculatorBiCollector<A, B, Input_, Output_, Calculator_ extends ObjectCalculator<Input_, Output_>>
implements BiConstraintCollector<A, B, Calculator_, Output_>
- permits AverageReferenceBiCollector, CountDistinctIntBiCollector, CountDistinctLongBiCollector,
- SumReferenceBiCollector {
- private final BiFunction<? super A, ? super B, ? extends Input_> mapper;
+ permits AverageReferenceBiCollector, ConsecutiveSequencesBiConstraintCollector, CountDistinctIntBiCollector,
+ CountDistinctLongBiCollector, SumReferenceBiCollector {
+ protected final BiFunction<? super A, ? super B, ? extends Input_> mapper; | Can remain private; call `super.equals` in subclasses' `equals` method. |
timefold-solver | github_2023 | java | 426 | TimefoldAI | Christopher-Chianelli | @@ -79,9 +101,9 @@ void testConsecutiveNumbers() {
tree.add(atomic(8), 8);
IterableList<Sequence<AtomicInteger, Integer>> sequenceList = new IterableList<>(tree.getConsecutiveSequences());
- assertThat(sequenceList).hasSize(2);
+ Assertions.assertThat(sequenceList).hasSize(2); | Why use `Assertions.assertThat` when `import static org.assertj.core.api.Assertions.assertThat;` is in the file? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.