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
python
992
TimefoldAI
Christopher-Chianelli
@@ -244,13 +244,16 @@ class CascadingUpdateShadowVariable(JavaAnnotation): Notes ----- Important: it must only change the shadow variable(s) for which it's configured. + It is only possible to define either `source_variable_name` or `source_variable_names`. It can be applied to multiple attributes to modify different shadow variables. It should never change a genuine variable or a problem fact. It can change its shadow variable(s) on multiple entity instances (for example: an arrival_time change affects all trailing entities too). - Examples - -------- + Example + -------
```suggestion -------- ```
timefold-solver
github_2023
python
992
TimefoldAI
Christopher-Chianelli
@@ -244,13 +244,16 @@ class CascadingUpdateShadowVariable(JavaAnnotation): Notes ----- Important: it must only change the shadow variable(s) for which it's configured. + It is only possible to define either `source_variable_name` or `source_variable_names`. It can be applied to multiple attributes to modify different shadow variables. It should never change a genuine variable or a problem fact. It can change its shadow variable(s) on multiple entity instances (for example: an arrival_time change affects all trailing entities too). Examples -------- + + Single source >>> from timefold.solver.domain import CascadingUpdateShadowVariable, PreviousElementShadowVariable, planning_entity
```suggestion >>> from timefold.solver.domain import CascadingUpdateShadowVariable, PreviousElementShadowVariable, planning_entity ```
timefold-solver
github_2023
python
992
TimefoldAI
Christopher-Chianelli
@@ -268,10 +271,31 @@ class CascadingUpdateShadowVariable(JavaAnnotation): ... ... def update_arrival_time(self): ... self.arrival_time = previous.arrival_time + timedelta(hours=1) + Multiple sources
```suggestion Multiple sources ```
timefold-solver
github_2023
java
990
TimefoldAI
Christopher-Chianelli
@@ -118,20 +118,24 @@ public void linkVariableDescriptors(DescriptorPolicy descriptorPolicy) { .orElse(null); var targetMethodName = getTargetMethodName(); - var sourceMethodMember = ConfigUtils.getDeclaredMembers(entityDescriptor.getEntityClass()) + var sourceMethodMembers = ConfigUtils.getDeclaredMembers(entityDescriptor.getEntityClass()) .stream() .filter(member -> member.getName().equals(targetMethodName))
Might want to filter out fields here; using a field as a "cascade update method" makes no sense. i.e. we want this to fail: ```java @PlanningEntity class A { Runnable update; @CascadingUpdateShadowVariable(targetMethodName = "update", sourceVariableName = "entity")) Integer variable; } ``` If `update` was the only member (i.e. no `update` method), then when its getter is invoked, it will only do `return this.update;`, which is almost certainly not what anybody want.
timefold-solver
github_2023
java
990
TimefoldAI
Christopher-Chianelli
@@ -118,20 +119,24 @@ public void linkVariableDescriptors(DescriptorPolicy descriptorPolicy) { .orElse(null); var targetMethodName = getTargetMethodName(); - var sourceMethodMember = ConfigUtils.getDeclaredMembers(entityDescriptor.getEntityClass()) + var sourceMethodMembers = ConfigUtils.getDeclaredMembers(entityDescriptor.getEntityClass()) .stream() .filter(member -> member.getName().equals(targetMethodName)) - .findFirst() - .orElse(null); - if (sourceMethodMember == null) { + .toList(); + if (sourceMethodMembers.size() > 1) { + throw new IllegalArgumentException(""" + The entity class (%s) has multiple members named as "%s". + Maybe rename the method "%s" with a unique name.""".formatted(entityDescriptor.getEntityClass(), + targetMethodName, targetMethodName)); + } else if (sourceMethodMembers.stream().noneMatch(m -> Method.class.isAssignableFrom(m.getClass()))) {
I would honestly do it like this: ```java var sourceMethodMembers = ConfigUtils.getDeclaredMembers(entityDescriptor.getEntityClass()) .stream() .filter(member -> member instanceof Method method && method.getName().equals(targetMethod) && method.getParameterCount() == 0) .toList(); ``` This: - Select only 0-arg methods with the given name, which are the only valid choice Since only 0-arg methods would be selected, it would be impossible to choose a field accidentally, and we can allow having a field with the same name as a method. This also makes the `sourceMethodMembers.stream().noneMatch(m -> Method.class.isAssignableFrom(m.getClass()))` never trigger. In normal classes, `sourceMethodMembers.size() > 1` would also never trigger, but generated classes allow multiple 0-arg methods with the same name (provided they have a different return type).
timefold-solver
github_2023
java
990
TimefoldAI
Christopher-Chianelli
@@ -119,24 +119,28 @@ public void linkVariableDescriptors(DescriptorPolicy descriptorPolicy) { .orElse(null); var targetMethodName = getTargetMethodName(); - var sourceMethodMembers = ConfigUtils.getDeclaredMembers(entityDescriptor.getEntityClass()) + var allSourceMethodMembers = ConfigUtils.getDeclaredMembers(entityDescriptor.getEntityClass()) .stream() .filter(member -> member.getName().equals(targetMethodName))
This line should be ``` member -> member instanceof Method method && member.getName().equals(targetMethodName) && method.getParameterCount() == 0 ```
timefold-solver
github_2023
java
990
TimefoldAI
Christopher-Chianelli
@@ -119,24 +119,28 @@ public void linkVariableDescriptors(DescriptorPolicy descriptorPolicy) { .orElse(null); var targetMethodName = getTargetMethodName(); - var sourceMethodMembers = ConfigUtils.getDeclaredMembers(entityDescriptor.getEntityClass()) + var allSourceMethodMembers = ConfigUtils.getDeclaredMembers(entityDescriptor.getEntityClass()) .stream() .filter(member -> member.getName().equals(targetMethodName)) .toList(); - if (sourceMethodMembers.size() > 1) { + if (allSourceMethodMembers.size() > 1) { throw new IllegalArgumentException(""" The entity class (%s) has multiple members named as "%s". Maybe rename the method "%s" with a unique name.""".formatted(entityDescriptor.getEntityClass(), targetMethodName, targetMethodName)); - } else if (sourceMethodMembers.stream().noneMatch(m -> Method.class.isAssignableFrom(m.getClass()))) { + } + var validSourceMethodMembers = allSourceMethodMembers.stream()
Should be done on `allSourceMethodMembers`
timefold-solver
github_2023
java
954
TimefoldAI
triceo
@@ -0,0 +1,32 @@ +package ai.timefold.solver.core.api.domain.variable; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +/** + * A listener automatically sourced on a {@link PreviousElementShadowVariable} and {@link InverseRelationShadowVariable}. + * <p> + * Change shadow variables when the previous or inverse relation elements changes. + * <p> + * Automatically cascades change events to {@link NextElementShadowVariable} of a {@link PlanningListVariable}. + * <p> + * Important: it must only change the shadow variable(s) for which it's configured! + * It can be applied to multiple fields to modify different shadow variables. + * It should never change a genuine variable or a problem fact. + * It can change its shadow variable(s) on multiple entity instances + * (for example: an arrivalTime change affects all trailing entities too). + */ +@Target({ FIELD }) +@Retention(RUNTIME) +public @interface CascadeUpdateElementShadowVariable {
TODO: Naming.
timefold-solver
github_2023
java
954
TimefoldAI
triceo
@@ -0,0 +1,32 @@ +package ai.timefold.solver.core.api.domain.variable; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +/** + * A listener automatically sourced on a {@link PreviousElementShadowVariable} and {@link InverseRelationShadowVariable}. + * <p> + * Change shadow variables when the previous or inverse relation elements changes. + * <p> + * Automatically cascades change events to {@link NextElementShadowVariable} of a {@link PlanningListVariable}. + * <p> + * Important: it must only change the shadow variable(s) for which it's configured!
```suggestion * Important: it must only change the shadow variable(s) for which it's configured. ``` We generally don't shout at people. :-)
timefold-solver
github_2023
java
954
TimefoldAI
triceo
@@ -19,6 +19,10 @@ public final class ReflectionMethodMemberAccessor extends AbstractMemberAccessor private final MethodHandle methodHandle; public ReflectionMethodMemberAccessor(Method readMethod) { + this(readMethod, true); + } + + public ReflectionMethodMemberAccessor(Method readMethod, boolean requiredReturnType) {
I think `returnTypeRequired` makes it more obvious that it's a `boolean`. Please apply consistently throughout the codebase.
timefold-solver
github_2023
java
954
TimefoldAI
triceo
@@ -161,12 +162,17 @@ private static void createConstructor(ClassCreator classCreator, GizmoMemberInfo Method.class, String.class, Class[].class), declaringClass, name, methodCreator.newArray(Class.class, 0)); - ResultHandle type = - methodCreator.invokeVirtualMethod( - MethodDescriptor.ofMethod(Method.class, "getGenericReturnType", Type.class), - method); - methodCreator.writeInstanceField(FieldDescriptor.of(classCreator.getClassName(), GENERIC_TYPE_FIELD, Type.class), - thisObj, type); + if (memberInfo.isRequiredReturnType()) { + // We create a field to store the result, only if the called method has a return type; otherwise, we + // will only execute it
```suggestion // We create a field to store the result, only if the called method has a return type. // Otherwise, we will only execute it. ``` It reads better if the lines are split by sentence, if possible. (The IntelliJ Grazie Pro plugin helps with writing a lot.)
timefold-solver
github_2023
java
954
TimefoldAI
triceo
@@ -246,9 +254,8 @@ private static void createGetName(ClassCreator classCreator, GizmoMemberInfo mem // If it is a method, assert that it has the required // properties - memberInfo.getDescriptor().whenIsMethod(method -> { - assertIsGoodMethod(method, memberInfo.getAnnotationClass()); - }); + memberInfo.getDescriptor().whenIsMethod( + method -> assertIsGoodMethod(method, memberInfo.isRequiredReturnType(), memberInfo.getAnnotationClass()));
It's a race to the finish line now. :-) We're going to have conflicts, you and I. Nevermind, we'll figure it out when the time comes.
timefold-solver
github_2023
java
954
TimefoldAI
triceo
@@ -0,0 +1,135 @@ +package ai.timefold.solver.core.impl.domain.variable.cascade; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +import ai.timefold.solver.core.api.domain.variable.AbstractVariableListener; +import ai.timefold.solver.core.api.domain.variable.CascadeUpdateElementShadowVariable; +import ai.timefold.solver.core.config.util.ConfigUtils; +import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor; +import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessorFactory; +import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; +import ai.timefold.solver.core.impl.domain.policy.DescriptorPolicy; +import ai.timefold.solver.core.impl.domain.variable.descriptor.ShadowVariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.inverserelation.InverseRelationShadowVariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.listener.VariableListenerWithSources; +import ai.timefold.solver.core.impl.domain.variable.nextprev.NextElementShadowVariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.nextprev.PreviousElementShadowVariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.supply.Demand; +import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager; + +public final class CascadeUpdateElementShadowVariableDescriptor<Solution_> extends ShadowVariableDescriptor<Solution_> { + + private final List<VariableDescriptor<Solution_>> sourceVariableDescriptorList = new ArrayList<>(); + private ShadowVariableDescriptor<Solution_> sourceShadowVariableDescriptor; + private ShadowVariableDescriptor<Solution_> nextElementShadowVariableDescriptor; + private MemberAccessor listenerUpdateMethod; + + public CascadeUpdateElementShadowVariableDescriptor(int ordinal, EntityDescriptor<Solution_> entityDescriptor, + MemberAccessor variableMemberAccessor) { + super(ordinal, entityDescriptor, variableMemberAccessor); + } + + @Override + public void processAnnotations(DescriptorPolicy descriptorPolicy) { + // Do nothing + } + + @Override + public void linkVariableDescriptors(DescriptorPolicy descriptorPolicy) { + this.sourceShadowVariableDescriptor = entityDescriptor.getShadowVariableDescriptor(variableMemberAccessor.getName()); + + var inverseRelationShadowDescriptor = entityDescriptor.getShadowVariableDescriptors().stream() + .filter(variableDescriptor -> InverseRelationShadowVariableDescriptor.class + .isAssignableFrom(variableDescriptor.getClass())) + .findFirst() + .orElse(null); + if (inverseRelationShadowDescriptor == null) { + throw new IllegalArgumentException( + """ + The entityClass (%s) has an @%s annotated property (%s), but has no @InverseRelationShadowVariable shadow variable defined. + Maybe add a new shadow variable @InverseRelationShadowVariable to the entity %s.""" + .formatted(entityDescriptor.getEntityClass(), + CascadeUpdateElementShadowVariable.class.getSimpleName(), variableMemberAccessor.getName(), + entityDescriptor.getEntityClass()));
I wonder if this is necessary. If the inverse is not defined, can we not use a supply? List variable works even without defining these, so the code to support that is already in there.
timefold-solver
github_2023
java
954
TimefoldAI
triceo
@@ -0,0 +1,135 @@ +package ai.timefold.solver.core.impl.domain.variable.cascade; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +import ai.timefold.solver.core.api.domain.variable.AbstractVariableListener; +import ai.timefold.solver.core.api.domain.variable.CascadeUpdateElementShadowVariable; +import ai.timefold.solver.core.config.util.ConfigUtils; +import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor; +import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessorFactory; +import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; +import ai.timefold.solver.core.impl.domain.policy.DescriptorPolicy; +import ai.timefold.solver.core.impl.domain.variable.descriptor.ShadowVariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.inverserelation.InverseRelationShadowVariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.listener.VariableListenerWithSources; +import ai.timefold.solver.core.impl.domain.variable.nextprev.NextElementShadowVariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.nextprev.PreviousElementShadowVariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.supply.Demand; +import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager; + +public final class CascadeUpdateElementShadowVariableDescriptor<Solution_> extends ShadowVariableDescriptor<Solution_> { + + private final List<VariableDescriptor<Solution_>> sourceVariableDescriptorList = new ArrayList<>(); + private ShadowVariableDescriptor<Solution_> sourceShadowVariableDescriptor; + private ShadowVariableDescriptor<Solution_> nextElementShadowVariableDescriptor; + private MemberAccessor listenerUpdateMethod; + + public CascadeUpdateElementShadowVariableDescriptor(int ordinal, EntityDescriptor<Solution_> entityDescriptor, + MemberAccessor variableMemberAccessor) { + super(ordinal, entityDescriptor, variableMemberAccessor); + } + + @Override + public void processAnnotations(DescriptorPolicy descriptorPolicy) { + // Do nothing + } + + @Override + public void linkVariableDescriptors(DescriptorPolicy descriptorPolicy) { + this.sourceShadowVariableDescriptor = entityDescriptor.getShadowVariableDescriptor(variableMemberAccessor.getName()); + + var inverseRelationShadowDescriptor = entityDescriptor.getShadowVariableDescriptors().stream() + .filter(variableDescriptor -> InverseRelationShadowVariableDescriptor.class + .isAssignableFrom(variableDescriptor.getClass())) + .findFirst() + .orElse(null); + if (inverseRelationShadowDescriptor == null) { + throw new IllegalArgumentException( + """ + The entityClass (%s) has an @%s annotated property (%s), but has no @InverseRelationShadowVariable shadow variable defined. + Maybe add a new shadow variable @InverseRelationShadowVariable to the entity %s.""" + .formatted(entityDescriptor.getEntityClass(), + CascadeUpdateElementShadowVariable.class.getSimpleName(), variableMemberAccessor.getName(), + entityDescriptor.getEntityClass())); + } + sourceVariableDescriptorList.add(inverseRelationShadowDescriptor); + + var previousElementShadowDescriptor = entityDescriptor.getShadowVariableDescriptors().stream() + .filter(variableDescriptor -> PreviousElementShadowVariableDescriptor.class + .isAssignableFrom(variableDescriptor.getClass())) + .findFirst() + .orElse(null); + if (previousElementShadowDescriptor == null) { + throw new IllegalArgumentException( + """ + The entityClass (%s) has an @%s annotated property (%s), but has no @PreviousElementShadowVariable shadow variable defined. + Maybe add a new shadow variable @PreviousElementShadowVariable to the entity %s."""
Dtto.
timefold-solver
github_2023
java
954
TimefoldAI
triceo
@@ -0,0 +1,135 @@ +package ai.timefold.solver.core.impl.domain.variable.cascade; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +import ai.timefold.solver.core.api.domain.variable.AbstractVariableListener; +import ai.timefold.solver.core.api.domain.variable.CascadeUpdateElementShadowVariable; +import ai.timefold.solver.core.config.util.ConfigUtils; +import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor; +import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessorFactory; +import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; +import ai.timefold.solver.core.impl.domain.policy.DescriptorPolicy; +import ai.timefold.solver.core.impl.domain.variable.descriptor.ShadowVariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.inverserelation.InverseRelationShadowVariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.listener.VariableListenerWithSources; +import ai.timefold.solver.core.impl.domain.variable.nextprev.NextElementShadowVariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.nextprev.PreviousElementShadowVariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.supply.Demand; +import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager; + +public final class CascadeUpdateElementShadowVariableDescriptor<Solution_> extends ShadowVariableDescriptor<Solution_> { + + private final List<VariableDescriptor<Solution_>> sourceVariableDescriptorList = new ArrayList<>(); + private ShadowVariableDescriptor<Solution_> sourceShadowVariableDescriptor; + private ShadowVariableDescriptor<Solution_> nextElementShadowVariableDescriptor; + private MemberAccessor listenerUpdateMethod; + + public CascadeUpdateElementShadowVariableDescriptor(int ordinal, EntityDescriptor<Solution_> entityDescriptor, + MemberAccessor variableMemberAccessor) { + super(ordinal, entityDescriptor, variableMemberAccessor); + } + + @Override + public void processAnnotations(DescriptorPolicy descriptorPolicy) { + // Do nothing + } + + @Override + public void linkVariableDescriptors(DescriptorPolicy descriptorPolicy) { + this.sourceShadowVariableDescriptor = entityDescriptor.getShadowVariableDescriptor(variableMemberAccessor.getName()); + + var inverseRelationShadowDescriptor = entityDescriptor.getShadowVariableDescriptors().stream() + .filter(variableDescriptor -> InverseRelationShadowVariableDescriptor.class + .isAssignableFrom(variableDescriptor.getClass())) + .findFirst() + .orElse(null); + if (inverseRelationShadowDescriptor == null) { + throw new IllegalArgumentException( + """ + The entityClass (%s) has an @%s annotated property (%s), but has no @InverseRelationShadowVariable shadow variable defined. + Maybe add a new shadow variable @InverseRelationShadowVariable to the entity %s.""" + .formatted(entityDescriptor.getEntityClass(), + CascadeUpdateElementShadowVariable.class.getSimpleName(), variableMemberAccessor.getName(), + entityDescriptor.getEntityClass())); + } + sourceVariableDescriptorList.add(inverseRelationShadowDescriptor); + + var previousElementShadowDescriptor = entityDescriptor.getShadowVariableDescriptors().stream() + .filter(variableDescriptor -> PreviousElementShadowVariableDescriptor.class + .isAssignableFrom(variableDescriptor.getClass())) + .findFirst() + .orElse(null); + if (previousElementShadowDescriptor == null) { + throw new IllegalArgumentException( + """ + The entityClass (%s) has an @%s annotated property (%s), but has no @PreviousElementShadowVariable shadow variable defined. + Maybe add a new shadow variable @PreviousElementShadowVariable to the entity %s.""" + .formatted(entityDescriptor.getEntityClass(), + CascadeUpdateElementShadowVariable.class.getSimpleName(), variableMemberAccessor.getName(), + entityDescriptor.getEntityClass())); + } + sourceVariableDescriptorList.add(previousElementShadowDescriptor); + + nextElementShadowVariableDescriptor = entityDescriptor.getShadowVariableDescriptors().stream() + .filter(variableDescriptor -> NextElementShadowVariableDescriptor.class + .isAssignableFrom(variableDescriptor.getClass())) + .findFirst() + .orElse(null); + if (nextElementShadowVariableDescriptor == null) { + throw new IllegalArgumentException( + """ + The entityClass (%s) has an @%s annotated property (%s), but has no @NextElementShadowVariable shadow variable defined. + Maybe add a new shadow variable @NextElementShadowVariable to the entity %s."""
Dtto.
timefold-solver
github_2023
java
954
TimefoldAI
triceo
@@ -0,0 +1,168 @@ +package ai.timefold.solver.core.impl.domain.variable.cascade; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; + +import java.util.Arrays; +import java.util.List; + +import ai.timefold.solver.core.api.score.buildin.simple.SimpleScore; +import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; +import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; +import ai.timefold.solver.core.impl.testdata.domain.cascade.TestdataCascadeEntity; +import ai.timefold.solver.core.impl.testdata.domain.cascade.TestdataCascadeSolution; +import ai.timefold.solver.core.impl.testdata.domain.cascade.TestdataCascadeValue; +import ai.timefold.solver.core.impl.testdata.domain.shadow.wrong_cascade.TestdataCascadeMissingInverseValue; +import ai.timefold.solver.core.impl.testdata.domain.shadow.wrong_cascade.TestdataCascadeMissingNextValue; +import ai.timefold.solver.core.impl.testdata.domain.shadow.wrong_cascade.TestdataCascadeMissingPreviousValue; +import ai.timefold.solver.core.impl.testdata.domain.shadow.wrong_cascade.TestdataCascadeWrongMethod; +import ai.timefold.solver.core.impl.testdata.util.PlannerTestUtils; + +import org.junit.jupiter.api.Test; + +class CascadeUpdateVariableListenerTest { + + @Test + void requiredShadowVariableDependencies() { + assertThatIllegalArgumentException().isThrownBy(TestdataCascadeMissingInverseValue::buildEntityDescriptor) + .withMessageContaining( + "The entityClass (class ai.timefold.solver.core.impl.testdata.domain.shadow.wrong_cascade.TestdataCascadeMissingInverseValue)") + .withMessageContaining("has an @CascadeUpdateElementShadowVariable annotated property (cascadeValue)") + .withMessageContaining("but has no @InverseRelationShadowVariable shadow variable defined."); + + assertThatIllegalArgumentException().isThrownBy(TestdataCascadeMissingPreviousValue::buildEntityDescriptor) + .withMessageContaining( + "The entityClass (class ai.timefold.solver.core.impl.testdata.domain.shadow.wrong_cascade.TestdataCascadeMissingPreviousValue)") + .withMessageContaining("has an @CascadeUpdateElementShadowVariable annotated property (cascadeValue)") + .withMessageContaining("but has no @PreviousElementShadowVariable shadow variable defined"); + + assertThatIllegalArgumentException().isThrownBy(TestdataCascadeMissingNextValue::buildEntityDescriptor) + .withMessageContaining( + "The entityClass (class ai.timefold.solver.core.impl.testdata.domain.shadow.wrong_cascade.TestdataCascadeMissingNextValue)") + .withMessageContaining("has an @CascadeUpdateElementShadowVariable annotated property (cascadeValue)") + .withMessageContaining("but has no @NextElementShadowVariable shadow variable defined"); + + assertThatIllegalArgumentException().isThrownBy(TestdataCascadeWrongMethod::buildEntityDescriptor) + .withMessageContaining( + "The entityClass (class ai.timefold.solver.core.impl.testdata.domain.shadow.wrong_cascade.TestdataCascadeWrongMethod)") + .withMessageContaining( + "has an @CascadeUpdateElementShadowVariable annotated property (badUpdateCascadeValueWithReturnType)") + .withMessageContaining( + "with sourceMethodName (class ai.timefold.solver.core.impl.testdata.domain.shadow.wrong_cascade.TestdataCascadeWrongMethod), ") + .withMessageContaining("but the method has not been found in the entityClass"); + } + + @Test + void updateAllNextValues() {
Maybe we should also test the case where two listeners point to the same method?
timefold-solver
github_2023
others
954
TimefoldAI
triceo
@@ -1367,6 +1367,91 @@ public class Customer { public void setNextCustomer(Customer nextCustomer) {...} ---- +[#cascadeUpdateVariable] +==== Cascade element update shadow variable + +The annotation `@CascadeUpdateElementShadowVariable` provides a built-in listener that updates a set of connected elements. +Timefold Solver triggers a user-defined logic whenever the inverse relation or previous element changes. +Moreover, it automatically propagates changes to the next elements when the value of the related shadow variable changes. + +The planning entity side has a genuine list variable: + +[source,java] +---- +@PlanningEntity +public class Vehicle { + + @PlanningListVariable + public List<Customer> getCustomers() { + return customers; + } + + public void setCustomers(List<Customer> customers) {...} +} +---- + +On the element side: + +[source,java] +---- +@PlanningEntity +public class Customer { + + @InverseRelationShadowVariable(sourceVariableName = "customers") + private Vehicle vehicle; + @PreviousElementShadowVariable(sourceVariableName = "customers") + private Customer previousCustomer; + @NextElementShadowVariable(sourceVariableName = "customers") + private Customer nextCustomer; + @CascadeUpdateElementShadowVariable(sourceMethodName = "updateArrivalTime") + private LocalDateTime arrivalTime; + + ... + + public void updateArrivalTime() {...} +---- + +The `sourceMethodName` refers to the user-defined logic that updates the annotated shadow variable. +The method must be implemented in the defining entity class and should not include any parameters. +Also, the planning entity must add `InverseRelationShadowVariable`, `PreviousElementShadowVariable`, +and `NextElementShadowVariable` elements in order to use the cascade element shadow variable. + +In the previous example, +the cascade update listener calls `updateArrivalTime` whenever the `vehicle` or `previousCustomer` changes. +It then automatically calls `updateArrivalTime` for the subsequent `nextCustomer` elements +and stops when the `arrivalTime` value does not change after running the user-defined custom logic +or when it reaches the end. + +[WARNING] +==== +A user-defined logic can only change shadow variables. +It must never change a genuine planning variable or a problem fact. +==== + +===== Multiple source variables + +If the user-defined logic requires updating multiple shadow variables, +annotate each shadow variable with a separate `@CascadeUpdateElementShadowVariable` annotation. + +[source,java] +---- +@PlanningEntity +public class Customer { + + @InverseRelationShadowVariable(sourceVariableName = "customers") + private Vehicle vehicle; + @PreviousElementShadowVariable(sourceVariableName = "customers") + private Customer previousCustomer; + @NextElementShadowVariable(sourceVariableName = "customers") + private Customer nextCustomer; + @CascadeUpdateElementShadowVariable(sourceMethodName = "updateWeightAndArrivalTime")
Isn't it rather the `targetMethodName`? The relationship is inversed here.
timefold-solver
github_2023
others
954
TimefoldAI
triceo
@@ -1367,6 +1367,91 @@ public class Customer { public void setNextCustomer(Customer nextCustomer) {...} ---- +[#cascadeUpdateVariable] +==== Cascade element update shadow variable
This documentation is correct, but I've been wondering... Should we rather (or maybe in addition) write a short section on "updating tail chains"? And maybe we don't hide it deep in a subsection on variable listeners. Because as a user, that's what I will look for - not "cascade element update shadow variable".
timefold-solver
github_2023
java
954
TimefoldAI
triceo
@@ -127,9 +152,21 @@ public Demand<?> getProvidedDemand() { @Override public Iterable<VariableListenerWithSources<Solution_>> buildVariableListeners(SupplyManager supplyManager) { - return List.of(new VariableListenerWithSources<>( - new CascadeUpdateVariableListener<>(sourceShadowVariableDescriptor, nextElementShadowVariableDescriptor, - listenerUpdateMethod), - sourceVariableDescriptorList)); + // There are use cases where the shadow variable is applied to different fields and relies on the same method + // to update their values. Therefore, only one listener will be generated when multiple descriptors use the same + // method, and the notifiable flag won't be enabled in such cases.
```suggestion // There are use cases where the shadow variable is applied to different fields // and relies on the same method to update their values. // Therefore, only one listener will be generated when multiple descriptors use the same method, // and the notifiable flag won't be enabled in such cases. ```
timefold-solver
github_2023
java
954
TimefoldAI
triceo
@@ -33,12 +35,25 @@ public void beforeVariableChanged(ScoreDirector<Solution_> scoreDirector, Object public void afterVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity) { var currentEntity = entity; while (currentEntity != null) { - scoreDirector.beforeVariableChanged(currentEntity, sourceShadowVariableDescriptor.getVariableName()); - Object oldValue = sourceShadowVariableDescriptor.getValue(currentEntity); + List<Object> oldValueList = new ArrayList<>(sourceShadowVariableDescriptorList.size()); + for (ShadowVariableDescriptor<Solution_> sourceShadowVariableDescriptor : sourceShadowVariableDescriptorList) { + scoreDirector.beforeVariableChanged(currentEntity, sourceShadowVariableDescriptor.getVariableName()); + oldValueList.add(sourceShadowVariableDescriptor.getValue(currentEntity)); + } listenerUpdateMethod.executeGetter(currentEntity); - Object newValue = sourceShadowVariableDescriptor.getValue(currentEntity); - scoreDirector.afterVariableChanged(currentEntity, sourceShadowVariableDescriptor.getVariableName()); - if (Objects.equals(oldValue, newValue)) { + List<Object> newValueList = new ArrayList<>(sourceShadowVariableDescriptorList.size()); + for (ShadowVariableDescriptor<Solution_> sourceShadowVariableDescriptor : sourceShadowVariableDescriptorList) { + scoreDirector.afterVariableChanged(currentEntity, sourceShadowVariableDescriptor.getVariableName()); + newValueList.add(sourceShadowVariableDescriptor.getValue(currentEntity)); + } + boolean hasChange = false; + for (int i = 0; i < oldValueList.size(); i++) { + if (!Objects.equals(oldValueList.get(i), newValueList.get(i))) { + hasChange = true; + break; + } + }
Arguably you can make this check when you're reading the new value, completely avoiding this loop and improving performance.
timefold-solver
github_2023
java
954
TimefoldAI
triceo
@@ -33,12 +35,25 @@ public void beforeVariableChanged(ScoreDirector<Solution_> scoreDirector, Object public void afterVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity) { var currentEntity = entity; while (currentEntity != null) { - scoreDirector.beforeVariableChanged(currentEntity, sourceShadowVariableDescriptor.getVariableName()); - Object oldValue = sourceShadowVariableDescriptor.getValue(currentEntity); + List<Object> oldValueList = new ArrayList<>(sourceShadowVariableDescriptorList.size());
Personally, I'd introduce two methods for this - one which only has 1 var, and another which handles 2+ vars. The 1-var path will be significantly faster, avoiding the list and the iterations. It is also the most frequent use case, so it makes sense to have a path handling it.
timefold-solver
github_2023
java
954
TimefoldAI
triceo
@@ -0,0 +1,49 @@ +package ai.timefold.solver.core.api.domain.variable; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Repeatable; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +/** + * Specifies that field may be updated by the target method when one or more source variables change. + * <p> + * Automatically cascades change events to {@link NextElementShadowVariable} of a {@link PlanningListVariable}. + * <p> + * Important: it must only change the shadow variable(s) for which it's configured. + * It can be applied to multiple fields to modify different shadow variables. + * It should never change a genuine variable or a problem fact. + * It can change its shadow variable(s) on multiple entity instances + * (for example: an arrivalTime change affects all trailing entities too). + */ +@Target({ FIELD }) +@Retention(RUNTIME) +@Repeatable(CascadingUpdateListener.List.class) +public @interface CascadingUpdateListener { + + /** + * The target method element. + * + * @return method name of the source host element which will update the shadow variable + */ + String targetMethodName(); + + /** + * The source variable name. + * + * @return never null, a genuine or shadow variable name + */ + String sourceVariableName();
I'd put this first, as it is for other listeners.
timefold-solver
github_2023
java
954
TimefoldAI
triceo
@@ -320,7 +327,13 @@ private static void createGetGenericType(ClassCreator classCreator) { private static void createExecuteGetter(ClassCreator classCreator, GizmoMemberInfo memberInfo) { MethodCreator methodCreator = getMethodCreator(classCreator, Object.class, "executeGetter", Object.class); ResultHandle bean = methodCreator.getMethodParam(0); - methodCreator.returnValue(memberInfo.getDescriptor().readMemberValue(methodCreator, bean)); + if (memberInfo.isReturnTypeRequired()) {
Arguably the Javadoc should change, as the method now does something different than what it says.
timefold-solver
github_2023
java
954
TimefoldAI
triceo
@@ -5,16 +5,23 @@ public final class GizmoMemberInfo {
If I remember correctly, in my previous changes, I turned this into a record. Are you sure you resolved all conflicts with the main branch?
timefold-solver
github_2023
java
954
TimefoldAI
triceo
@@ -85,7 +88,9 @@ public class EntityDescriptor<Solution_> { ShadowVariable.class, ShadowVariable.List.class, PiggybackShadowVariable.class, - CustomShadowVariable.class }; + CustomShadowVariable.class, + CascadingUpdateListener.class, + CascadingUpdateListener.List.class };
Now that I see it written like this... maybe it should be `CascadingUpdateShadowVariable`?
timefold-solver
github_2023
java
954
TimefoldAI
triceo
@@ -350,6 +359,21 @@ The entityClass (%s) has a @%s annotated member (%s) that has an unsupported typ || variableAnnotationClass.equals(ShadowVariable.List.class)) { var variableDescriptor = new CustomShadowVariableDescriptor<>(nextVariableDescriptorOrdinal, this, memberAccessor); declaredShadowVariableDescriptorMap.put(memberName, variableDescriptor); + } else if (variableAnnotationClass.equals(CascadingUpdateListener.class) + || variableAnnotationClass.equals(CascadingUpdateListener.List.class)) { + var variableDescriptor = + new CascadingUpdateVariableListenerDescriptor<>(nextVariableDescriptorOrdinal, this, memberAccessor); + declaredShadowVariableDescriptorMap.put(memberName, variableDescriptor); + if (declaredCascadingUpdateVariableListenerDecriptorMap.containsKey(variableDescriptor.getTargetMethodName())) { + // This shadow variable won't be notifiable
Maybe also explain _why_? What's the point?
timefold-solver
github_2023
java
954
TimefoldAI
triceo
@@ -0,0 +1,49 @@ +package ai.timefold.solver.core.api.domain.variable; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Repeatable; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +/** + * Specifies that field may be updated by the target method when one or more source variables change. + * <p> + * Automatically cascades change events to {@link NextElementShadowVariable} of a {@link PlanningListVariable}. + * <p> + * Important: it must only change the shadow variable(s) for which it's configured. + * It can be applied to multiple fields to modify different shadow variables. + * It should never change a genuine variable or a problem fact. + * It can change its shadow variable(s) on multiple entity instances + * (for example: an arrivalTime change affects all trailing entities too). + */ +@Target({ FIELD }) +@Retention(RUNTIME) +@Repeatable(CascadingUpdateListener.List.class) +public @interface CascadingUpdateListener { + + /** + * The target method element.
We should describe the method. What are the arguments? What is the return value and what does it mean? Is it allowed to be static? What is the expected visibility?
timefold-solver
github_2023
java
954
TimefoldAI
triceo
@@ -0,0 +1,116 @@ +package ai.timefold.solver.core.impl.domain.variable.cascade; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import ai.timefold.solver.core.api.domain.solution.PlanningSolution; +import ai.timefold.solver.core.api.domain.variable.VariableListener; +import ai.timefold.solver.core.api.score.director.ScoreDirector; +import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor; +import ai.timefold.solver.core.impl.domain.variable.descriptor.ShadowVariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.nextprev.NextElementVariableSupply; + +/** + * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation + */ +public class CascadingUpdateVariableListener<Solution_> implements VariableListener<Solution_, Object> { + + private final List<VariableDescriptor<Solution_>> targetVariableDescriptorList; + private final ShadowVariableDescriptor<Solution_> nextElementShadowVariableDescriptor; + private final NextElementVariableSupply nextElementVariableSupply; + private final MemberAccessor targetMethod; + + public CascadingUpdateVariableListener(List<VariableDescriptor<Solution_>> targetVariableDescriptorList,
Personally, I'd have two listeners for this. One that only accepts the descriptor, and another that only accepts the supply. That way, it's clear what the code path intends to do.
timefold-solver
github_2023
java
954
TimefoldAI
triceo
@@ -0,0 +1,116 @@ +package ai.timefold.solver.core.impl.domain.variable.cascade; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import ai.timefold.solver.core.api.domain.solution.PlanningSolution; +import ai.timefold.solver.core.api.domain.variable.VariableListener; +import ai.timefold.solver.core.api.score.director.ScoreDirector; +import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor; +import ai.timefold.solver.core.impl.domain.variable.descriptor.ShadowVariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.nextprev.NextElementVariableSupply; + +/** + * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation + */ +public class CascadingUpdateVariableListener<Solution_> implements VariableListener<Solution_, Object> { + + private final List<VariableDescriptor<Solution_>> targetVariableDescriptorList; + private final ShadowVariableDescriptor<Solution_> nextElementShadowVariableDescriptor; + private final NextElementVariableSupply nextElementVariableSupply; + private final MemberAccessor targetMethod; + + public CascadingUpdateVariableListener(List<VariableDescriptor<Solution_>> targetVariableDescriptorList, + ShadowVariableDescriptor<Solution_> nextElementShadowVariableDescriptor, + NextElementVariableSupply nextElementVariableSupply, MemberAccessor targetMethod) { + this.targetVariableDescriptorList = targetVariableDescriptorList; + this.nextElementShadowVariableDescriptor = nextElementShadowVariableDescriptor; + this.nextElementVariableSupply = nextElementVariableSupply; + this.targetMethod = targetMethod; + } + + @Override + public void beforeVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity) { + // Do nothing + } + + @Override + public void afterVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity) { + var currentEntity = entity; + while (currentEntity != null) { + if (!execute(scoreDirector, currentEntity, targetVariableDescriptorList, targetMethod)) { + break; + } + currentEntity = getNextElement(currentEntity); + } + } + + private Object getNextElement(Object entity) { + // The primary choice is to select the user-defined next element shadow variable. + return nextElementShadowVariableDescriptor != null ? nextElementShadowVariableDescriptor.getValue(entity) + : nextElementVariableSupply.getNext(entity); + } + + private boolean execute(ScoreDirector<Solution_> scoreDirector, Object entity,
I'd consider having two separate impl classes with the same abstract parent. Otherwise you'll be paying the penalty for this condition on every call of this method, which is a lot. (Conditions = branch predictions = CPU cache misses.)
timefold-solver
github_2023
java
954
TimefoldAI
triceo
@@ -0,0 +1,116 @@ +package ai.timefold.solver.core.impl.domain.variable.cascade; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import ai.timefold.solver.core.api.domain.solution.PlanningSolution; +import ai.timefold.solver.core.api.domain.variable.VariableListener; +import ai.timefold.solver.core.api.score.director.ScoreDirector; +import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor; +import ai.timefold.solver.core.impl.domain.variable.descriptor.ShadowVariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.nextprev.NextElementVariableSupply; + +/** + * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation + */ +public class CascadingUpdateVariableListener<Solution_> implements VariableListener<Solution_, Object> { + + private final List<VariableDescriptor<Solution_>> targetVariableDescriptorList; + private final ShadowVariableDescriptor<Solution_> nextElementShadowVariableDescriptor; + private final NextElementVariableSupply nextElementVariableSupply; + private final MemberAccessor targetMethod; + + public CascadingUpdateVariableListener(List<VariableDescriptor<Solution_>> targetVariableDescriptorList, + ShadowVariableDescriptor<Solution_> nextElementShadowVariableDescriptor, + NextElementVariableSupply nextElementVariableSupply, MemberAccessor targetMethod) { + this.targetVariableDescriptorList = targetVariableDescriptorList; + this.nextElementShadowVariableDescriptor = nextElementShadowVariableDescriptor; + this.nextElementVariableSupply = nextElementVariableSupply; + this.targetMethod = targetMethod; + } + + @Override + public void beforeVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity) { + // Do nothing + } + + @Override + public void afterVariableChanged(ScoreDirector<Solution_> scoreDirector, Object entity) { + var currentEntity = entity; + while (currentEntity != null) { + if (!execute(scoreDirector, currentEntity, targetVariableDescriptorList, targetMethod)) { + break; + } + currentEntity = getNextElement(currentEntity); + } + } + + private Object getNextElement(Object entity) { + // The primary choice is to select the user-defined next element shadow variable. + return nextElementShadowVariableDescriptor != null ? nextElementShadowVariableDescriptor.getValue(entity)
Arguably, you can turn this into a lambda in the constructor, avoiding a condition at all. If you know the descriptor is null, simply provide a lambda to access the supply, and vice versa.
timefold-solver
github_2023
java
954
TimefoldAI
triceo
@@ -0,0 +1,194 @@ +package ai.timefold.solver.core.impl.domain.variable.cascade; + +import static java.util.stream.Collectors.joining; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import ai.timefold.solver.core.api.domain.variable.AbstractVariableListener; +import ai.timefold.solver.core.api.domain.variable.CascadingUpdateListener; +import ai.timefold.solver.core.config.util.ConfigUtils; +import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor; +import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessorFactory; +import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; +import ai.timefold.solver.core.impl.domain.policy.DescriptorPolicy; +import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.descriptor.ShadowVariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.listener.VariableListenerWithSources; +import ai.timefold.solver.core.impl.domain.variable.nextprev.NextElementShadowVariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.nextprev.NextElementVariableDemand; +import ai.timefold.solver.core.impl.domain.variable.supply.Demand; +import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager; + +public final class CascadingUpdateVariableListenerDescriptor<Solution_> extends ShadowVariableDescriptor<Solution_> { + + private final List<TargetVariable<Solution_>> targetVariables; + private ListVariableDescriptor<Solution_> sourceListVariable; + private final List<VariableDescriptor<Solution_>> targetVariableDescriptorList = new ArrayList<>(); + private final Set<ShadowVariableDescriptor<Solution_>> sourceShadowVariableDescriptorSet = new HashSet<>(); + private ShadowVariableDescriptor<Solution_> nextElementShadowVariableDescriptor; + private MemberAccessor targetMethod; + // This flag defines if the planning variable generates a listener, which will be notified later by the event system + private boolean notifiable = true; + + public CascadingUpdateVariableListenerDescriptor(int ordinal, EntityDescriptor<Solution_> entityDescriptor, + MemberAccessor variableMemberAccessor) { + super(ordinal, entityDescriptor, variableMemberAccessor); + targetVariables = new ArrayList<>(); + addTargetVariable(entityDescriptor, variableMemberAccessor); + } + + public void addTargetVariable(EntityDescriptor<Solution_> entityDescriptor, + MemberAccessor variableMemberAccessor) { + targetVariables.add(new TargetVariable<>(entityDescriptor, variableMemberAccessor)); + } + + public void setNotifiable(boolean notifiable) { + this.notifiable = notifiable; + } + + private List<CascadingUpdateListener> getDeclaredListeners(MemberAccessor variableMemberAccessor) { + List<CascadingUpdateListener> declaredListenerList = Arrays.asList(variableMemberAccessor + .getDeclaredAnnotationsByType(CascadingUpdateListener.class)); + var targetMethodList = declaredListenerList.stream() + .map(CascadingUpdateListener::targetMethodName) + .distinct() + .toList(); + if (targetMethodList.size() > 1) { + throw new IllegalArgumentException( + """ + The entityClass (%s) has multiple @%s in the annotated property (%s), and there are distinct targetMethodName values [%s]. + Maybe update targetMethodName to use same method in the field %s.""" + .formatted(entityDescriptor.getEntityClass(), + CascadingUpdateListener.class.getSimpleName(), + variableMemberAccessor.getName(), + String.join(", ", targetMethodList), + variableMemberAccessor.getName())); + } + return declaredListenerList; + } + + public String getTargetMethodName() { + return getDeclaredListeners(variableMemberAccessor).get(0).targetMethodName(); + } + + @Override + public void processAnnotations(DescriptorPolicy descriptorPolicy) { + // Do nothing + } + + @Override + public void linkVariableDescriptors(DescriptorPolicy descriptorPolicy) { + for (TargetVariable<Solution_> targetVariable : targetVariables) {
Let's use `var` consistently in new code. IDE can help you replace all.
timefold-solver
github_2023
java
954
TimefoldAI
triceo
@@ -0,0 +1,134 @@ +package ai.timefold.solver.core.impl.domain.variable.nextprev; + +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; + +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.ListVariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; +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.util.IdentityElementAwareList; + +/** + * Alternative to {@link NextElementVariableListener}. + */ +public class ExternalizedNextElementVariableSupply<Solution_> implements
I've been wondering... not sure here... should this be part of the externalized list variable state supply? That's one place where I've been putting logic related to list variable.
timefold-solver
github_2023
java
954
TimefoldAI
triceo
@@ -0,0 +1,93 @@ +package ai.timefold.solver.core.impl.util; + +import java.util.IdentityHashMap; +import java.util.Iterator; +import java.util.function.Consumer; +import java.util.function.UnaryOperator; + +/** + * This data structure differs from {@link ElementAwareList} because it provides a find operation in O(H). + * + * The implementation relies on two different data structures: {@link java.util.IdentityHashMap} and {@link ElementAwareList}. + * + * The element comparison works in the same way as {@link java.util.IdentityHashMap}, + * and two keys k1 and k2 are considered equal if and only if (k1==k2). + * + * @param <T> The element type. + */ +public class IdentityElementAwareList<T> implements Iterable<T> {
The point of `ElementAwareList` is to avoid hash lookups, and it replaced various uses of maps and sets. That's it's main benefit. Since you've introduced `IdentityHashMap` in there, you are effectively turning this into a `Map` again. You might as well use `new IdentityHashMap<>()` directly and avoid this entire new list.
timefold-solver
github_2023
java
954
TimefoldAI
triceo
@@ -67,6 +68,8 @@ public final class DotNames { static final DotName PIGGYBACK_SHADOW_VARIABLE = DotName.createSimple(PiggybackShadowVariable.class.getName()); static final DotName PREVIOUS_ELEMENT_SHADOW_VARIABLE = DotName.createSimple(PreviousElementShadowVariable.class.getName()); static final DotName SHADOW_VARIABLE = DotName.createSimple(ShadowVariable.class.getName()); + static final DotName CASCADE_UPDATE_ELEMENT_SHADOW_VARIABLE =
No list?
timefold-solver
github_2023
others
954
TimefoldAI
triceo
@@ -1367,6 +1367,121 @@ public class Customer { public void setNextCustomer(Customer nextCustomer) {...} ---- +[#tailChainVariable] +=== Updating tail chains + +The annotation `@CascadingUpdateListener` provides a built-in listener that updates a set of connected elements. +Timefold Solver triggers a user-defined logic whenever the inverse relation or previous element changes. +Moreover, it automatically propagates changes to the next elements when the value of the related shadow variable changes. + +The planning entity side has a genuine list variable: + +[source,java] +---- +@PlanningEntity +public class Vehicle { + + @PlanningListVariable + public List<Customer> getCustomers() { + return customers; + } + + public void setCustomers(List<Customer> customers) {...} +} +---- + +On the element side: + +[source,java] +---- +@PlanningEntity +public class Customer { + + @InverseRelationShadowVariable(sourceVariableName = "customers") + private Vehicle vehicle; + @PreviousElementShadowVariable(sourceVariableName = "customers") + private Customer previousCustomer; + @NextElementShadowVariable(sourceVariableName = "customers") + private Customer nextCustomer; + @CascadingUpdateListener(targetMethodName = "updateArrivalTime", sourceVariableName = "vehicle") + @CascadingUpdateListener(targetMethodName = "updateArrivalTime", sourceVariableName = "previousCustomer") + private LocalDateTime arrivalTime; +
The very first example shouldn't be this complicated. Reduce it to the bare minimum code. You can explain the extra features later.
timefold-solver
github_2023
java
954
TimefoldAI
triceo
@@ -0,0 +1,206 @@ +package ai.timefold.solver.core.impl.domain.variable.cascade; + +import static java.util.stream.Collectors.joining; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import ai.timefold.solver.core.api.domain.variable.AbstractVariableListener; +import ai.timefold.solver.core.api.domain.variable.CascadingUpdateShadowVariable; +import ai.timefold.solver.core.config.util.ConfigUtils; +import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor; +import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessorFactory; +import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; +import ai.timefold.solver.core.impl.domain.policy.DescriptorPolicy; +import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.descriptor.ShadowVariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.listener.VariableListenerWithSources; +import ai.timefold.solver.core.impl.domain.variable.nextprev.NextElementShadowVariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.nextprev.NextElementVariableDemand; +import ai.timefold.solver.core.impl.domain.variable.supply.Demand; +import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager; + +public final class CascadingUpdateShadowVariableDescriptor<Solution_> extends ShadowVariableDescriptor<Solution_> { + + private final List<TargetVariable<Solution_>> targetVariables; + private ListVariableDescriptor<Solution_> sourceListVariable; + private final List<VariableDescriptor<Solution_>> targetVariableDescriptorList = new ArrayList<>(); + private final Set<ShadowVariableDescriptor<Solution_>> sourceShadowVariableDescriptorSet = new HashSet<>(); + private ShadowVariableDescriptor<Solution_> nextElementShadowVariableDescriptor; + private MemberAccessor targetMethod; + // This flag defines if the planning variable generates a listener, which will be notified later by the event system + private boolean notifiable = true; + + public CascadingUpdateShadowVariableDescriptor(int ordinal, EntityDescriptor<Solution_> entityDescriptor, + MemberAccessor variableMemberAccessor) { + super(ordinal, entityDescriptor, variableMemberAccessor); + targetVariables = new ArrayList<>(); + addTargetVariable(entityDescriptor, variableMemberAccessor); + } + + public void addTargetVariable(EntityDescriptor<Solution_> entityDescriptor, + MemberAccessor variableMemberAccessor) { + targetVariables.add(new TargetVariable<>(entityDescriptor, variableMemberAccessor)); + } + + public void setNotifiable(boolean notifiable) { + this.notifiable = notifiable; + } + + private List<CascadingUpdateShadowVariable> getDeclaredListeners(MemberAccessor variableMemberAccessor) { + var declaredListenerList = Arrays.asList(variableMemberAccessor + .getDeclaredAnnotationsByType(CascadingUpdateShadowVariable.class)); + var targetMethodList = declaredListenerList.stream() + .map(CascadingUpdateShadowVariable::targetMethodName) + .distinct() + .toList(); + if (targetMethodList.size() > 1) { + throw new IllegalArgumentException( + """ + The entityClass (%s) has multiple @%s in the annotated property (%s), and there are distinct targetMethodName values [%s]. + Maybe update targetMethodName to use same method in the field %s.""" + .formatted(entityDescriptor.getEntityClass(), + CascadingUpdateShadowVariable.class.getSimpleName(), + variableMemberAccessor.getName(), + String.join(", ", targetMethodList), + variableMemberAccessor.getName())); + } + return declaredListenerList; + } + + public String getTargetMethodName() { + return getDeclaredListeners(variableMemberAccessor).get(0).targetMethodName(); + } + + @Override + public void processAnnotations(DescriptorPolicy descriptorPolicy) { + // Do nothing + } + + @Override + public void linkVariableDescriptors(DescriptorPolicy descriptorPolicy) { + for (TargetVariable<Solution_> targetVariable : targetVariables) { + var declaredListenerList = + getDeclaredListeners(targetVariable.variableMemberAccessor()); + for (var listener : declaredListenerList) { + linkVariableDescriptorToSource(listener); + } + targetVariableDescriptorList.add(targetVariable.entityDescriptor() + .getShadowVariableDescriptor(targetVariable.variableMemberAccessor().getName())); + } + + // Currently, only one list variable is supported per design. + // So, we assume that only one list variable can be found in the available entities, or we fail fast otherwise. + var listVariableDescriptorList = entityDescriptor.getSolutionDescriptor().getEntityDescriptors().stream() + .flatMap(e -> e.getGenuineVariableDescriptorList().stream()) + .filter(VariableDescriptor::isListVariable) + .toList(); + if (listVariableDescriptorList.size() > 1) { + throw new IllegalArgumentException( + "The listener @%s does not support models with multiple planning list variables [%s].".formatted( + CascadingUpdateShadowVariable.class.getSimpleName(), + listVariableDescriptorList.stream().map( + v -> v.getEntityDescriptor().getEntityClass().getSimpleName() + "::" + v.getVariableName()) + .collect(joining(", ")))); + } + sourceListVariable = (ListVariableDescriptor<Solution_>) listVariableDescriptorList.get(0); + + nextElementShadowVariableDescriptor = entityDescriptor.getShadowVariableDescriptors().stream() + .filter(variableDescriptor -> NextElementShadowVariableDescriptor.class + .isAssignableFrom(variableDescriptor.getClass())) + .findFirst() + .orElse(null); + + var targetMethodName = getTargetMethodName(); + var sourceMethodMember = ConfigUtils.getDeclaredMembers(entityDescriptor.getEntityClass()) + .stream() + .filter(member -> member.getName().equals(targetMethodName)) + .findFirst() + .orElse(null); + if (sourceMethodMember == null) { + throw new IllegalArgumentException( + "The entityClass (%s) has an @%s annotated property (%s), but the method \"%s\" is not found."
```suggestion "The entityClass (%s) has an @%s annotated property (%s), but the method \"%s\" cannot be found." ```
timefold-solver
github_2023
java
954
TimefoldAI
triceo
@@ -0,0 +1,206 @@ +package ai.timefold.solver.core.impl.domain.variable.cascade; + +import static java.util.stream.Collectors.joining; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import ai.timefold.solver.core.api.domain.variable.AbstractVariableListener; +import ai.timefold.solver.core.api.domain.variable.CascadingUpdateShadowVariable; +import ai.timefold.solver.core.config.util.ConfigUtils; +import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessor; +import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessorFactory; +import ai.timefold.solver.core.impl.domain.entity.descriptor.EntityDescriptor; +import ai.timefold.solver.core.impl.domain.policy.DescriptorPolicy; +import ai.timefold.solver.core.impl.domain.variable.descriptor.ListVariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.descriptor.ShadowVariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.descriptor.VariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.listener.VariableListenerWithSources; +import ai.timefold.solver.core.impl.domain.variable.nextprev.NextElementShadowVariableDescriptor; +import ai.timefold.solver.core.impl.domain.variable.nextprev.NextElementVariableDemand; +import ai.timefold.solver.core.impl.domain.variable.supply.Demand; +import ai.timefold.solver.core.impl.domain.variable.supply.SupplyManager; + +public final class CascadingUpdateShadowVariableDescriptor<Solution_> extends ShadowVariableDescriptor<Solution_> { + + private final List<TargetVariable<Solution_>> targetVariables; + private ListVariableDescriptor<Solution_> sourceListVariable; + private final List<VariableDescriptor<Solution_>> targetVariableDescriptorList = new ArrayList<>(); + private final Set<ShadowVariableDescriptor<Solution_>> sourceShadowVariableDescriptorSet = new HashSet<>(); + private ShadowVariableDescriptor<Solution_> nextElementShadowVariableDescriptor; + private MemberAccessor targetMethod; + // This flag defines if the planning variable generates a listener, which will be notified later by the event system + private boolean notifiable = true; + + public CascadingUpdateShadowVariableDescriptor(int ordinal, EntityDescriptor<Solution_> entityDescriptor, + MemberAccessor variableMemberAccessor) { + super(ordinal, entityDescriptor, variableMemberAccessor); + targetVariables = new ArrayList<>(); + addTargetVariable(entityDescriptor, variableMemberAccessor); + } + + public void addTargetVariable(EntityDescriptor<Solution_> entityDescriptor, + MemberAccessor variableMemberAccessor) { + targetVariables.add(new TargetVariable<>(entityDescriptor, variableMemberAccessor)); + } + + public void setNotifiable(boolean notifiable) { + this.notifiable = notifiable; + } + + private List<CascadingUpdateShadowVariable> getDeclaredListeners(MemberAccessor variableMemberAccessor) { + var declaredListenerList = Arrays.asList(variableMemberAccessor + .getDeclaredAnnotationsByType(CascadingUpdateShadowVariable.class)); + var targetMethodList = declaredListenerList.stream() + .map(CascadingUpdateShadowVariable::targetMethodName) + .distinct() + .toList(); + if (targetMethodList.size() > 1) { + throw new IllegalArgumentException( + """ + The entityClass (%s) has multiple @%s in the annotated property (%s), and there are distinct targetMethodName values [%s]. + Maybe update targetMethodName to use same method in the field %s.""" + .formatted(entityDescriptor.getEntityClass(), + CascadingUpdateShadowVariable.class.getSimpleName(), + variableMemberAccessor.getName(), + String.join(", ", targetMethodList), + variableMemberAccessor.getName())); + } + return declaredListenerList; + } + + public String getTargetMethodName() { + return getDeclaredListeners(variableMemberAccessor).get(0).targetMethodName(); + } + + @Override + public void processAnnotations(DescriptorPolicy descriptorPolicy) { + // Do nothing + } + + @Override + public void linkVariableDescriptors(DescriptorPolicy descriptorPolicy) { + for (TargetVariable<Solution_> targetVariable : targetVariables) { + var declaredListenerList = + getDeclaredListeners(targetVariable.variableMemberAccessor()); + for (var listener : declaredListenerList) { + linkVariableDescriptorToSource(listener); + } + targetVariableDescriptorList.add(targetVariable.entityDescriptor() + .getShadowVariableDescriptor(targetVariable.variableMemberAccessor().getName())); + } + + // Currently, only one list variable is supported per design. + // So, we assume that only one list variable can be found in the available entities, or we fail fast otherwise. + var listVariableDescriptorList = entityDescriptor.getSolutionDescriptor().getEntityDescriptors().stream() + .flatMap(e -> e.getGenuineVariableDescriptorList().stream()) + .filter(VariableDescriptor::isListVariable) + .toList(); + if (listVariableDescriptorList.size() > 1) { + throw new IllegalArgumentException( + "The listener @%s does not support models with multiple planning list variables [%s].".formatted( + CascadingUpdateShadowVariable.class.getSimpleName(), + listVariableDescriptorList.stream().map( + v -> v.getEntityDescriptor().getEntityClass().getSimpleName() + "::" + v.getVariableName()) + .collect(joining(", ")))); + } + sourceListVariable = (ListVariableDescriptor<Solution_>) listVariableDescriptorList.get(0); + + nextElementShadowVariableDescriptor = entityDescriptor.getShadowVariableDescriptors().stream() + .filter(variableDescriptor -> NextElementShadowVariableDescriptor.class + .isAssignableFrom(variableDescriptor.getClass())) + .findFirst() + .orElse(null); + + var targetMethodName = getTargetMethodName(); + var sourceMethodMember = ConfigUtils.getDeclaredMembers(entityDescriptor.getEntityClass()) + .stream() + .filter(member -> member.getName().equals(targetMethodName)) + .findFirst() + .orElse(null); + if (sourceMethodMember == null) { + throw new IllegalArgumentException( + "The entityClass (%s) has an @%s annotated property (%s), but the method \"%s\" is not found." + .formatted(entityDescriptor.getEntityClass(), + CascadingUpdateShadowVariable.class.getSimpleName(), + variableMemberAccessor.getName(), + targetMethodName)); + } + targetMethod = descriptorPolicy.getMemberAccessorFactory().buildAndCacheMemberAccessor(sourceMethodMember, + MemberAccessorFactory.MemberAccessorType.REGULAR_METHOD, null, descriptorPolicy.getDomainAccessType()); + } + + public void linkVariableDescriptorToSource(CascadingUpdateShadowVariable listener) { + var sourceDescriptor = entityDescriptor.getShadowVariableDescriptor(listener.sourceVariableName()); + if (sourceDescriptor == null) { + throw new IllegalArgumentException( + """ + The entityClass (%s) has an @%s annotated property (%s), but the shadow variable "%s" is not found.
```suggestion The entityClass (%s) has an @%s annotated property (%s), but the shadow variable "%s" cannot be found. ```
timefold-solver
github_2023
java
954
TimefoldAI
triceo
@@ -0,0 +1,171 @@ +package ai.timefold.solver.core.impl.domain.variable.cascade; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; + +import ai.timefold.solver.core.api.score.buildin.simple.SimpleScore; +import ai.timefold.solver.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; +import ai.timefold.solver.core.impl.score.director.InnerScoreDirector; +import ai.timefold.solver.core.impl.testdata.domain.cascade.multiple_var.supply.TestdataMultipleCascadingWithSupplyEntity; +import ai.timefold.solver.core.impl.testdata.domain.cascade.multiple_var.supply.TestdataMultipleCascadingWithSupplySolution; +import ai.timefold.solver.core.impl.testdata.domain.cascade.multiple_var.supply.TestdataMultipleCascadingWithSupplyValue; +import ai.timefold.solver.core.impl.testdata.util.PlannerTestUtils; + +import org.junit.jupiter.api.Test; + +class CollectionCascadingUpdateShadowVariableListenerTest {
Arguably, if the test can be parameterized, we should be able to do this with 1 test class, not 4, right? The test classes are nearly identical.
timefold-solver
github_2023
others
954
TimefoldAI
triceo
@@ -1367,6 +1367,135 @@ public class Customer { public void setNextCustomer(Customer nextCustomer) {...} ---- +[#tailChainVariable] +=== Updating tail chains + +The annotation `@CascadingUpdateShadowVariable` provides a built-in listener that updates a set of connected elements. +Timefold Solver triggers a user-defined logic whenever the a defined source variable changes. +Moreover, it automatically propagates changes to the next elements when the value of the related shadow variable changes. + +The planning entity side has a genuine list variable: + +[source,java] +---- +@PlanningEntity +public class Vehicle { + + @PlanningListVariable + public List<Customer> getCustomers() { + return customers; + } + + public void setCustomers(List<Customer> customers) {...} +} +---- + +On the element side: + +[source,java] +---- +@PlanningEntity +public class Customer { + + @PreviousElementShadowVariable(sourceVariableName = "customers") + private Customer previousCustomer; + @NextElementShadowVariable(sourceVariableName = "customers") + private Customer nextCustomer; + @CascadingUpdateShadowVariable(targetMethodName = "updateArrivalTime", sourceVariableName = "previousCustomer") + private LocalDateTime arrivalTime; + + ... + + public void updateArrivalTime() {...} +---- + +The `targetMethodName` refers to the user-defined logic that updates the annotated shadow variable. +The method must be implemented in the defining entity class, be non-static, and not include any parameters. + +The `sourceVariableName` property is the planning variable's name on the getter's return type, +which will trigger the cascade update listener in case of changes. + +In the previous example, +the cascade update listener calls `updateArrivalTime` whenever `previousCustomer` changes. +It then automatically calls `updateArrivalTime` for the subsequent `nextCustomer` elements +and stops when the `arrivalTime` value does not change after running target method +or when it reaches the end. + +The shadow variable `nextCustomer` is not required, but defining it in the model is recommended: + +[source,java] +---- +@PlanningEntity +public class Customer { + + @PreviousElementShadowVariable(sourceVariableName = "customers") + private Customer previousCustomer; + @CascadingUpdateShadowVariable(targetMethodName = "updateArrivalTime", sourceVariableName = "previousCustomer") + private LocalDateTime arrivalTime; + + ... + + public void updateArrivalTime() {...} +---- + +It is also possible to define multiple sources per variable: + +[source,java] +---- +@PlanningEntity +public class Customer { + + @InverseRelationShadowVariable(sourceVariableName = "customers") + private Vehicle vehicle; + @PreviousElementShadowVariable(sourceVariableName = "customers") + private Customer previousCustomer; + @NextElementShadowVariable(sourceVariableName = "customers") + private Customer nextCustomer; + @CascadingUpdateShadowVariable(targetMethodName = "updateArrivalTime", sourceVariableName = "vehicle") + @CascadingUpdateShadowVariable(targetMethodName = "updateArrivalTime", sourceVariableName = "previousCustomer") + private LocalDateTime arrivalTime; + + ... + + public void updateArrivalTime() {...} +---- + +The listener behaves as described previously. +It is called `updateArrivalTime` whenever a `previousCustomer` or `vehicle` changes.
```suggestion It calls `updateArrivalTime` whenever a `previousCustomer` or `vehicle` changes. ```
timefold-solver
github_2023
others
954
TimefoldAI
triceo
@@ -1367,6 +1367,135 @@ public class Customer { public void setNextCustomer(Customer nextCustomer) {...} ---- +[#tailChainVariable] +=== Updating tail chains + +The annotation `@CascadingUpdateShadowVariable` provides a built-in listener that updates a set of connected elements. +Timefold Solver triggers a user-defined logic whenever the a defined source variable changes. +Moreover, it automatically propagates changes to the next elements when the value of the related shadow variable changes. + +The planning entity side has a genuine list variable: + +[source,java] +---- +@PlanningEntity +public class Vehicle { + + @PlanningListVariable + public List<Customer> getCustomers() { + return customers; + } + + public void setCustomers(List<Customer> customers) {...} +} +---- + +On the element side: + +[source,java] +---- +@PlanningEntity +public class Customer { + + @PreviousElementShadowVariable(sourceVariableName = "customers") + private Customer previousCustomer; + @NextElementShadowVariable(sourceVariableName = "customers") + private Customer nextCustomer; + @CascadingUpdateShadowVariable(targetMethodName = "updateArrivalTime", sourceVariableName = "previousCustomer") + private LocalDateTime arrivalTime; + + ... + + public void updateArrivalTime() {...} +---- + +The `targetMethodName` refers to the user-defined logic that updates the annotated shadow variable. +The method must be implemented in the defining entity class, be non-static, and not include any parameters. + +The `sourceVariableName` property is the planning variable's name on the getter's return type, +which will trigger the cascade update listener in case of changes. + +In the previous example, +the cascade update listener calls `updateArrivalTime` whenever `previousCustomer` changes. +It then automatically calls `updateArrivalTime` for the subsequent `nextCustomer` elements +and stops when the `arrivalTime` value does not change after running target method +or when it reaches the end. + +The shadow variable `nextCustomer` is not required, but defining it in the model is recommended: + +[source,java] +---- +@PlanningEntity +public class Customer { + + @PreviousElementShadowVariable(sourceVariableName = "customers") + private Customer previousCustomer; + @CascadingUpdateShadowVariable(targetMethodName = "updateArrivalTime", sourceVariableName = "previousCustomer") + private LocalDateTime arrivalTime; + + ... + + public void updateArrivalTime() {...} +---- + +It is also possible to define multiple sources per variable: + +[source,java] +---- +@PlanningEntity +public class Customer { + + @InverseRelationShadowVariable(sourceVariableName = "customers") + private Vehicle vehicle; + @PreviousElementShadowVariable(sourceVariableName = "customers") + private Customer previousCustomer; + @NextElementShadowVariable(sourceVariableName = "customers") + private Customer nextCustomer; + @CascadingUpdateShadowVariable(targetMethodName = "updateArrivalTime", sourceVariableName = "vehicle") + @CascadingUpdateShadowVariable(targetMethodName = "updateArrivalTime", sourceVariableName = "previousCustomer") + private LocalDateTime arrivalTime; + + ... + + public void updateArrivalTime() {...} +---- + +The listener behaves as described previously. +It is called `updateArrivalTime` whenever a `previousCustomer` or `vehicle` changes. +It then propagates the changes to the subsequent elements, +stopping when no change is identified, or it reaches the tail.
```suggestion stopping when the method results in no change to the variable, or when it reaches the tail. ```
timefold-solver
github_2023
java
987
TimefoldAI
Christopher-Chianelli
@@ -920,6 +907,32 @@ private GeneratedGizmoClasses generateDomainAccessors(Map<String, SolverConfig> } } } + // The ConstraintWeightOverrides field is not annotated, but it needs a member accessor + AnnotationInstance solutionClassInstance = planningSolutionAnnotationInstanceCollection.iterator().next(); + ClassInfo solutionClassInfo = solutionClassInstance.target().asClass(); + FieldInfo constraintFieldInfo = solutionClassInfo.fields().stream() + .filter(f -> f.type().name().equals(DotNames.CONSTRAINT_WEIGHT_OVERRIDES)) + .findFirst() + .orElse(null); + if (constraintFieldInfo != null) { + // Prefer method to field + // (In Python, the field doesn't implement the interface).
Python cannot use Quarkus, so this comment is worthless here ```suggestion ```
timefold-solver
github_2023
java
981
TimefoldAI
zepfred
@@ -102,6 +106,9 @@ The constraint (%s) is not in the default package (%s). Constraint packages are deprecated, check your constraint implementation.""" .formatted(constraintRef, getDefaultConstraintPackage())); } + if (workingSolution == null) { // ConstraintVerifier is known to cause null here.
I recommend adding a test case as the existing tests did not catch that.
timefold-solver
github_2023
others
982
TimefoldAI
triceo
@@ -91,15 +91,6 @@ jobs: run: pip install tox build - - name: Quickly build timefold-solver - working-directory: ./timefold-solver - run: mvn -B -Dquickly clean install - - - name: Quickly Build timefold-solver-enterprise - working-directory: ./timefold-solver-enterprise - shell: bash - run: mvn -B -Dquickly clean install - - name: Build timefold solver python
```suggestion - name: Build Timefold Solver for Python ```
timefold-solver
github_2023
others
982
TimefoldAI
triceo
@@ -20,8 +20,13 @@ jobs: runs-on: ${{matrix.os}} strategy: matrix: - os: [ubuntu-latest, windows-latest] - java-version: [ 17, 21, 22 ] #Latest two LTS + latest non-LTS. + os: [ ubuntu-latest, macos-latest, windows-latest ] + java-version: [ 21 ] # Latest LTS if not Ubuntu + include: + - os: ubuntu-latest + java-version: 17 + - os: ubuntu-latest + java-version: 22
Nice, didn't know this was possible.
timefold-solver
github_2023
others
982
TimefoldAI
triceo
@@ -19,7 +19,7 @@ jobs: strategy: matrix: module: ["spring-integration", "quarkus-integration"] - java-version: [ 17, 21, 22 ] #Latest two LTS + latest non-LTS. + java-version: [ 21 ] # Latest LTS
I wonder if it makes sense to do Windows and Mac here too. I could argue that, for _native_, it makes more sense than for the JVM.
timefold-solver
github_2023
others
946
TimefoldAI
lee-carlon
@@ -1,21 +1,139 @@ [#constraintConfiguration] -= Constraint configuration: adjust constraint weights dynamically += Adjusting constraint weights at runtime :doctype: book :sectnums: :icons: font Deciding the correct xref:constraints-and-score/overview.adoc#scoreConstraintWeight[weight] and xref:constraints-and-score/overview.adoc#scoreLevel[level] for each constraint is not easy. It often involves negotiating with different stakeholders and their priorities. -Furthermore, quantifying the impact of soft constraints is often a new experience for business managers, so they'll need a number of iterations to get it right. +Furthermore, quantifying the impact of soft constraints is often a new experience for business managers, +so they'll need a number of iterations to get it right. Don't get stuck between a rock and a hard place. -Provide a UI to adjust the constraint weights and visualize the resulting solution, so the business managers can tweak the constraint weights themselves: +Provide a UI to adjust the constraint weights and visualize the resulting solution, +so the business managers can tweak the constraint weights themselves: image::constraints-and-score/constraint-configuration/parameterizeTheScoreWeights.png[align="center"] [#createAConstraintConfiguration] -== Create a constraint configuration +[#definingAndOverridingConstraintWeights] +== Defining and overriding constraint weights + +Let's define three constraints: + +- Constraint with a name of `Vehicle capacity` and a weight of `1hard'. +- Constraint with a name of `Service finished after max end time`, also with a weight of `1hard`. +- Constraint with a name of `Minimize travel time` and a weight of `1soft`. + +Using xref:constraints-and-score/score-calculation.adoc#constraintStreams[the Constraint Streams API], +this is done as follows: + +[source,java,options="nowrap"] +---- +public class VehicleRoutingConstraintProvider implements ConstraintProvider { + + ... + + @Override + public Constraint[] defineConstraints(ConstraintFactory factory) { + return new Constraint[] { + vehicleCapacity(factory), + serviceFinishedAfterMaxEndTime(factory), + minimizeTravelTime(factory) + }; + } + + Constraint vehicleCapacity(ConstraintFactory factory) { + return factory.forEach(Vehicle.class) + ... + .penalize(HardSoftScore.ONE_HARD, ...) + .asConstraint("Vehicle capacity"); + } + + Constraint serviceFinishedAfterMaxEndTime(ConstraintFactory factory) { + return factory.forEach(Visit.class) + ... + .penalize(HardSoftScore.ONE_HARD, ...) + .asConstraint("Service finished after max end time"); + } + + Constraint minimizeTravelTime(ConstraintFactory factory) { + return factory.forEach(Vehicle.class) + ... + .penalize(HardSoftScore.ONE_SOFT, ...) + .asConstraint("Minimize travel time"); + } +} +---- + +Without anything else, the constraint weights are fixed to the values we've given them in our `ConstraintProvider`. +To be able to override these weights at runtime, we need to introduce the `ConstraintWeightOverrides` class +to our planning solution class: + +[source,java,options="nowrap"] +---- +@PlanningSolution +public class VehicleRoutePlan { + + ... + + ConstraintWeightOverrides<HardSoftScore> constraintWeightOverrides; + + void setConstraintWeightOverrides(ConstraintWeightOverrides<HardSoftScore> constraintWeightOverrides) { + this.constraintWeightOverrides = constraintWeightOverrides; + } + + ConstraintWeightOverrides<HardSoftScore> getConstraintWeightOverrides() { + return constraintWeightOverrides; + } + + ... +} +---- + +We've just introduced a new field of type `ConstraintWeightOverrides`, +and we provided a getter and a setter for it. +The field will be automatically exposed as a xref:using-timefold-solver/modeling-planning-problems.adoc#problemFacts[problem fact], +there is no need to add a `@ProblemFactProperty` annotation. +But we need to fill it with the desired constraint weights: + +[source,java,options="nowrap"] +---- +... + +var constraintWeightOverrides = ConstraintWeightOverrides.of( + Map.of( + "Vehicle capacity", HardSoftScore.ofHard(2), + "Service finished after max end time", HardSoftScore.ZERO + ) +); + +var solution = new VehicleRoutePlan(); +solution.setConstraintWeightOverrides(constraintWeightOverrides); + +... +---- + +The `Vehicle capacity` constraint in this planning solution will get a weight of `2hard`,
```suggestion The `Vehicle capacity` constraint in this planning solution has a weight of `2hard`, ```
timefold-solver
github_2023
others
946
TimefoldAI
lee-carlon
@@ -1,21 +1,139 @@ [#constraintConfiguration] -= Constraint configuration: adjust constraint weights dynamically += Adjusting constraint weights at runtime :doctype: book :sectnums: :icons: font Deciding the correct xref:constraints-and-score/overview.adoc#scoreConstraintWeight[weight] and xref:constraints-and-score/overview.adoc#scoreLevel[level] for each constraint is not easy. It often involves negotiating with different stakeholders and their priorities. -Furthermore, quantifying the impact of soft constraints is often a new experience for business managers, so they'll need a number of iterations to get it right. +Furthermore, quantifying the impact of soft constraints is often a new experience for business managers, +so they'll need a number of iterations to get it right. Don't get stuck between a rock and a hard place. -Provide a UI to adjust the constraint weights and visualize the resulting solution, so the business managers can tweak the constraint weights themselves: +Provide a UI to adjust the constraint weights and visualize the resulting solution, +so the business managers can tweak the constraint weights themselves: image::constraints-and-score/constraint-configuration/parameterizeTheScoreWeights.png[align="center"] [#createAConstraintConfiguration] -== Create a constraint configuration +[#definingAndOverridingConstraintWeights] +== Defining and overriding constraint weights + +Let's define three constraints: + +- Constraint with a name of `Vehicle capacity` and a weight of `1hard'. +- Constraint with a name of `Service finished after max end time`, also with a weight of `1hard`. +- Constraint with a name of `Minimize travel time` and a weight of `1soft`. + +Using xref:constraints-and-score/score-calculation.adoc#constraintStreams[the Constraint Streams API], +this is done as follows: + +[source,java,options="nowrap"] +---- +public class VehicleRoutingConstraintProvider implements ConstraintProvider { + + ... + + @Override + public Constraint[] defineConstraints(ConstraintFactory factory) { + return new Constraint[] { + vehicleCapacity(factory), + serviceFinishedAfterMaxEndTime(factory), + minimizeTravelTime(factory) + }; + } + + Constraint vehicleCapacity(ConstraintFactory factory) { + return factory.forEach(Vehicle.class) + ... + .penalize(HardSoftScore.ONE_HARD, ...) + .asConstraint("Vehicle capacity"); + } + + Constraint serviceFinishedAfterMaxEndTime(ConstraintFactory factory) { + return factory.forEach(Visit.class) + ... + .penalize(HardSoftScore.ONE_HARD, ...) + .asConstraint("Service finished after max end time"); + } + + Constraint minimizeTravelTime(ConstraintFactory factory) { + return factory.forEach(Vehicle.class) + ... + .penalize(HardSoftScore.ONE_SOFT, ...) + .asConstraint("Minimize travel time"); + } +} +---- + +Without anything else, the constraint weights are fixed to the values we've given them in our `ConstraintProvider`. +To be able to override these weights at runtime, we need to introduce the `ConstraintWeightOverrides` class +to our planning solution class: + +[source,java,options="nowrap"] +---- +@PlanningSolution +public class VehicleRoutePlan { + + ... + + ConstraintWeightOverrides<HardSoftScore> constraintWeightOverrides; + + void setConstraintWeightOverrides(ConstraintWeightOverrides<HardSoftScore> constraintWeightOverrides) { + this.constraintWeightOverrides = constraintWeightOverrides; + } + + ConstraintWeightOverrides<HardSoftScore> getConstraintWeightOverrides() { + return constraintWeightOverrides; + } + + ... +} +---- + +We've just introduced a new field of type `ConstraintWeightOverrides`, +and we provided a getter and a setter for it. +The field will be automatically exposed as a xref:using-timefold-solver/modeling-planning-problems.adoc#problemFacts[problem fact], +there is no need to add a `@ProblemFactProperty` annotation. +But we need to fill it with the desired constraint weights: + +[source,java,options="nowrap"] +---- +... + +var constraintWeightOverrides = ConstraintWeightOverrides.of( + Map.of( + "Vehicle capacity", HardSoftScore.ofHard(2), + "Service finished after max end time", HardSoftScore.ZERO + ) +); + +var solution = new VehicleRoutePlan(); +solution.setConstraintWeightOverrides(constraintWeightOverrides); + +... +---- + +The `Vehicle capacity` constraint in this planning solution will get a weight of `2hard`, +as opposed to its original `1hard`. +The `Service finished after max end time` constraint will have a weight of `0hard`,
```suggestion The `Service finished after max end time` constraint has a weight of `0hard`, ```
timefold-solver
github_2023
others
946
TimefoldAI
lee-carlon
@@ -1,21 +1,139 @@ [#constraintConfiguration] -= Constraint configuration: adjust constraint weights dynamically += Adjusting constraint weights at runtime :doctype: book :sectnums: :icons: font Deciding the correct xref:constraints-and-score/overview.adoc#scoreConstraintWeight[weight] and xref:constraints-and-score/overview.adoc#scoreLevel[level] for each constraint is not easy. It often involves negotiating with different stakeholders and their priorities. -Furthermore, quantifying the impact of soft constraints is often a new experience for business managers, so they'll need a number of iterations to get it right. +Furthermore, quantifying the impact of soft constraints is often a new experience for business managers, +so they'll need a number of iterations to get it right. Don't get stuck between a rock and a hard place. -Provide a UI to adjust the constraint weights and visualize the resulting solution, so the business managers can tweak the constraint weights themselves: +Provide a UI to adjust the constraint weights and visualize the resulting solution, +so the business managers can tweak the constraint weights themselves: image::constraints-and-score/constraint-configuration/parameterizeTheScoreWeights.png[align="center"] [#createAConstraintConfiguration] -== Create a constraint configuration +[#definingAndOverridingConstraintWeights] +== Defining and overriding constraint weights + +Let's define three constraints: + +- Constraint with a name of `Vehicle capacity` and a weight of `1hard'. +- Constraint with a name of `Service finished after max end time`, also with a weight of `1hard`. +- Constraint with a name of `Minimize travel time` and a weight of `1soft`. + +Using xref:constraints-and-score/score-calculation.adoc#constraintStreams[the Constraint Streams API], +this is done as follows: + +[source,java,options="nowrap"] +---- +public class VehicleRoutingConstraintProvider implements ConstraintProvider { + + ... + + @Override + public Constraint[] defineConstraints(ConstraintFactory factory) { + return new Constraint[] { + vehicleCapacity(factory), + serviceFinishedAfterMaxEndTime(factory), + minimizeTravelTime(factory) + }; + } + + Constraint vehicleCapacity(ConstraintFactory factory) { + return factory.forEach(Vehicle.class) + ... + .penalize(HardSoftScore.ONE_HARD, ...) + .asConstraint("Vehicle capacity"); + } + + Constraint serviceFinishedAfterMaxEndTime(ConstraintFactory factory) { + return factory.forEach(Visit.class) + ... + .penalize(HardSoftScore.ONE_HARD, ...) + .asConstraint("Service finished after max end time"); + } + + Constraint minimizeTravelTime(ConstraintFactory factory) { + return factory.forEach(Vehicle.class) + ... + .penalize(HardSoftScore.ONE_SOFT, ...) + .asConstraint("Minimize travel time"); + } +} +---- + +Without anything else, the constraint weights are fixed to the values we've given them in our `ConstraintProvider`. +To be able to override these weights at runtime, we need to introduce the `ConstraintWeightOverrides` class +to our planning solution class: + +[source,java,options="nowrap"] +---- +@PlanningSolution +public class VehicleRoutePlan { + + ... + + ConstraintWeightOverrides<HardSoftScore> constraintWeightOverrides; + + void setConstraintWeightOverrides(ConstraintWeightOverrides<HardSoftScore> constraintWeightOverrides) { + this.constraintWeightOverrides = constraintWeightOverrides; + } + + ConstraintWeightOverrides<HardSoftScore> getConstraintWeightOverrides() { + return constraintWeightOverrides; + } + + ... +} +---- + +We've just introduced a new field of type `ConstraintWeightOverrides`, +and we provided a getter and a setter for it. +The field will be automatically exposed as a xref:using-timefold-solver/modeling-planning-problems.adoc#problemFacts[problem fact], +there is no need to add a `@ProblemFactProperty` annotation. +But we need to fill it with the desired constraint weights: + +[source,java,options="nowrap"] +---- +... + +var constraintWeightOverrides = ConstraintWeightOverrides.of( + Map.of( + "Vehicle capacity", HardSoftScore.ofHard(2), + "Service finished after max end time", HardSoftScore.ZERO + ) +); + +var solution = new VehicleRoutePlan(); +solution.setConstraintWeightOverrides(constraintWeightOverrides); + +... +---- + +The `Vehicle capacity` constraint in this planning solution will get a weight of `2hard`, +as opposed to its original `1hard`. +The `Service finished after max end time` constraint will have a weight of `0hard`, +and therefore will be disabled entirely. + +This way, you can solve the same problem +while applying different constraint weights to each instance.
```suggestion In this way, you can solve the same problem by applying different constraint weights to each instance. ```
timefold-solver
github_2023
java
946
TimefoldAI
zepfred
@@ -1892,10 +1915,10 @@ default Constraint penalizeBigDecimal(String constraintPackage, String constrain * For non-int {@link Score} types use {@link #penalizeConfigurableLong(String, ToLongTriFunction)} or * {@link #penalizeConfigurableBigDecimal(String, TriFunction)} instead. * - * @deprecated Prefer {@link #penalizeConfigurable(ToIntTriFunction)}. * @param constraintName never null, shows up in {@link ConstraintMatchTotal} during score justification * @param matchWeigher never null, the result of this function (matchWeight) is multiplied by the constraintWeight * @return never null + * @deprecated Prefer {@link #penalize(Score, ToIntTriFunction)} and {@link ConstraintWeightOverrides}. */ @Deprecated(forRemoval = true)
Should we include version `1.13.0` and update other stream classes?
timefold-solver
github_2023
java
946
TimefoldAI
zepfred
@@ -0,0 +1,53 @@ +package ai.timefold.solver.core.impl.domain.solution; + +import java.util.Set; + +import ai.timefold.solver.core.api.domain.common.DomainAccessType; +import ai.timefold.solver.core.api.domain.constraintweight.ConstraintConfiguration; +import ai.timefold.solver.core.api.domain.solution.ConstraintWeightOverrides; +import ai.timefold.solver.core.api.score.Score; +import ai.timefold.solver.core.api.score.constraint.ConstraintRef; +import ai.timefold.solver.core.api.score.stream.ConstraintProvider; +import ai.timefold.solver.core.impl.domain.common.accessor.MemberAccessorFactory; +import ai.timefold.solver.core.impl.domain.solution.descriptor.SolutionDescriptor; + +public sealed interface ConstraintWeightSupplier<Solution_, Score_ extends Score<Score_>>
Nice refactoring!
timefold-solver
github_2023
java
946
TimefoldAI
zepfred
@@ -237,9 +238,8 @@ public Expression visitExpression(Expression expression, ExecutionContext execut } else if (select.getType().isAssignableFrom(quadConstraintStreamPattern)) { templateCode = "#{any(ai.timefold.solver.core.api.score.stream.quad.QuadConstraintStream)}\n"; } else { - LOGGER.warn("Cannot refactor to asConstraint() method" + - " for deprecated method called in expression (" + e + ")."); - return e; + LOGGER.warn("Cannot refactor to asConstraint() method for deprecated method (" + method + ").");
```suggestion LOGGER.warn("Cannot refactor to asConstraint() method for deprecated method ({}).", method); ```
timefold-solver
github_2023
others
955
TimefoldAI
triceo
@@ -96,6 +96,22 @@ </build> <profiles> + <profile> + <id>non-essential</id>
Can you please explain what purpose this serves exactly? Since the Python stuff apparently doesn't re-build anything, I don't understand why this profile needs to exist. Plus I really don't like having entire modules marked as "non essential".
timefold-solver
github_2023
others
955
TimefoldAI
triceo
@@ -0,0 +1,186 @@ +![Timefold Logo](https://raw.githubusercontent.com/TimefoldAI/timefold-solver/main/docs/src/modules/ROOT/images/shared/timefold-logo.png) + +# Timefold Solver for Python
If the TOML stuff etc. needs to be in the root of the repo, why does the README need to be in a subfolder? And wouldn't it make sense to have one unified README for the entire repo? I doubt that people will click to the "python" subdir to see a Python-specific README; they'll stay at the top level, and only see Java-specific stuff.
timefold-solver
github_2023
python
955
TimefoldAI
triceo
@@ -15,9 +15,9 @@ class FetchDependencies(build_py): """ def create_stubs(self, project_root, command): subprocess.run([str((project_root / command).absolute()), 'dependency:copy-dependencies'], - cwd=project_root, check=True) + '-Dpython', '-Dquickly', '-Dexec.skip', cwd=project_root, check=True)
This could go into the special Maven profile, no? That way, the config would be shared without having to repeat it.
timefold-solver
github_2023
java
945
TimefoldAI
zepfred
@@ -23,12 +23,8 @@ public long getTimeMillisSpent() { return timeMillisSpent; } - public String getConstraintPackage() {
Should we first deprecate it before removing it?
timefold-solver
github_2023
java
945
TimefoldAI
zepfred
@@ -23,12 +23,8 @@ public long getTimeMillisSpent() { return timeMillisSpent; } - public String getConstraintPackage() { - return constraintRef.packageName(); - } - - public String getConstraintName() {
Same as above
timefold-solver
github_2023
java
945
TimefoldAI
zepfred
@@ -39,13 +35,9 @@ public Score getScoreTotal() { return scoreTotal; } - public String getConstraintId() {
Same as above
timefold-solver
github_2023
java
945
TimefoldAI
zepfred
@@ -942,16 +942,16 @@ public void groupBy_1Mapping1Collector() { // From scratch scoreDirector.setWorkingSolution(solution); assertScore(scoreDirector, - assertMatchWithScore(-1, TEST_CONSTRAINT_NAME, solution.getFirstEntity().toString(), 6), - assertMatchWithScore(-1, TEST_CONSTRAINT_NAME, solution.getEntityList().get(1).toString(), 5)); + assertMatchWithScore(-1, null, TEST_CONSTRAINT_NAME, solution.getFirstEntity().toString(), 6),
Are we still using the constraint package elsewhere? If not, why not remove it instead of using a `null` value?
timefold-solver
github_2023
others
918
TimefoldAI
lee-carlon
@@ -273,16 +273,12 @@ System.out.println( ((0.01 + 0.02) + 0.03) == (0.01 + (0.02 + 0.03)) ); // retur This leads to __score corruption__. -Decimal numbers (``BigDecimal``) have none of these problems. - -[NOTE] -==== -BigDecimal arithmetic is considerably slower than ``int``, `long` or `double` arithmetic. -In experiments we have seen the score calculation take five times longer. - -Therefore, in many cases, it can be worthwhile to multiply _all_ numbers for a single score weight by a plural of ten, so the score weight fits in a scaled `int` or ``long``. -For example, if we multiply all weights by ``1000``, a fuelCost of `0.07` becomes a fuelCostMillis of `70` and no longer uses a decimal score weight. -==== +Decimal numbers (``BigDecimal``) have none of these problems, +but their arithmetic operations are slower than with `int` or `long`. +In some cases, it can be worthwhile to multiply _all_ constraint weights by the same power of ten,
```suggestion In some cases, it can be worthwhile multiplying _all_ constraint weights by the same power of ten, ```
timefold-solver
github_2023
others
918
TimefoldAI
lee-carlon
@@ -849,6 +848,14 @@ Finally, we use <<constraintStreamsMappingTuples,mapping>> to calculate the viol For example, if the equipment has a `capacity` of `3`, and the `maximumOverlap` of the `resource` is `5`, then `violationAmount` will be `2`. If the amount is `0`, then the equipment is not being used over its capacity and we can filter the tuple out. +[#collectorsLoadBalance] +==== Load balancing collectors + +Certain constraints require resource usage to be balanced across the solution. +For example, employees should have mutually similar number of shifts.
```suggestion For example, employees should have a similar number of shifts. ``` We can delete mutually here as similar makes the point :)
timefold-solver
github_2023
others
918
TimefoldAI
lee-carlon
@@ -1217,6 +1224,79 @@ Consider the following naive implementation without `concat`: An employee with no assigned shifts _wouldn't have been penalized_ because no tuples were passed to the `groupBy` building block. +[#constraintStreamsConcatPadding] +==== Padding values + +Consider two constraint streams of different cardinalities like so:
```suggestion Consider two constraint streams of different cardinalities, for instance: ```
timefold-solver
github_2023
others
918
TimefoldAI
lee-carlon
@@ -1217,6 +1224,79 @@ Consider the following naive implementation without `concat`: An employee with no assigned shifts _wouldn't have been penalized_ because no tuples were passed to the `groupBy` building block. +[#constraintStreamsConcatPadding] +==== Padding values + +Consider two constraint streams of different cardinalities like so: + +[source,java,options="nowrap"] +---- +// All employees. +UniConstraintStream<Employee> uniStream = constraintFactory.forEach(Employee.class); +// Employees with a count of their shifts; some employees may have no shifts, therefore are not included. +BiConstraintStream<Employee, Integer> biStream = constraintFactory.forEach(Employee.class) + .join(Shift.class, equal(Function.identity(), Shift::getEmployee)) + .groupBy((employee, shift) -> employee, countBi()); +---- + +By default, when concatenating these streams, +the stream of lower cardinality will be padded with `null` values: + +[source,java,options="nowrap"] +---- +// Employees from uniStream will have null as their shift count. +BiConstraintStream<Employee, Integer> concatStream = uniStream.concat(biStream); +---- + +Instead of the `null` default,
```suggestion Instead of using `null` default, ```
timefold-solver
github_2023
others
918
TimefoldAI
lee-carlon
@@ -1217,6 +1224,79 @@ Consider the following naive implementation without `concat`: An employee with no assigned shifts _wouldn't have been penalized_ because no tuples were passed to the `groupBy` building block. +[#constraintStreamsConcatPadding] +==== Padding values + +Consider two constraint streams of different cardinalities like so: + +[source,java,options="nowrap"] +---- +// All employees. +UniConstraintStream<Employee> uniStream = constraintFactory.forEach(Employee.class); +// Employees with a count of their shifts; some employees may have no shifts, therefore are not included. +BiConstraintStream<Employee, Integer> biStream = constraintFactory.forEach(Employee.class) + .join(Shift.class, equal(Function.identity(), Shift::getEmployee)) + .groupBy((employee, shift) -> employee, countBi()); +---- + +By default, when concatenating these streams, +the stream of lower cardinality will be padded with `null` values: + +[source,java,options="nowrap"] +---- +// Employees from uniStream will have null as their shift count. +BiConstraintStream<Employee, Integer> concatStream = uniStream.concat(biStream); +---- + +Instead of the `null` default, +you can specify a padding value to use when padding the lower cardinality stream: + +[source,java,options="nowrap"] +---- +// Employees from uniStream will have a zero as their shift count. +BiConstraintStream<Employee, Integer> concatStream = uniStream.concat(biStream, employee -> 0); +---- + +[#constraintStreamsComplement] +=== Complementing a stream + +The <<constraintStreamsJoin,join building block>> provided by Constraint Streams is technically an inner join. +What this means is that only the matches that are present in both streams are considered.
```suggestion This means only the matches that are present in both streams are considered. ```
timefold-solver
github_2023
others
918
TimefoldAI
lee-carlon
@@ -1217,6 +1224,79 @@ Consider the following naive implementation without `concat`: An employee with no assigned shifts _wouldn't have been penalized_ because no tuples were passed to the `groupBy` building block. +[#constraintStreamsConcatPadding] +==== Padding values + +Consider two constraint streams of different cardinalities like so: + +[source,java,options="nowrap"] +---- +// All employees. +UniConstraintStream<Employee> uniStream = constraintFactory.forEach(Employee.class); +// Employees with a count of their shifts; some employees may have no shifts, therefore are not included. +BiConstraintStream<Employee, Integer> biStream = constraintFactory.forEach(Employee.class) + .join(Shift.class, equal(Function.identity(), Shift::getEmployee)) + .groupBy((employee, shift) -> employee, countBi()); +---- + +By default, when concatenating these streams, +the stream of lower cardinality will be padded with `null` values: + +[source,java,options="nowrap"] +---- +// Employees from uniStream will have null as their shift count. +BiConstraintStream<Employee, Integer> concatStream = uniStream.concat(biStream); +---- + +Instead of the `null` default, +you can specify a padding value to use when padding the lower cardinality stream: + +[source,java,options="nowrap"] +---- +// Employees from uniStream will have a zero as their shift count. +BiConstraintStream<Employee, Integer> concatStream = uniStream.concat(biStream, employee -> 0); +---- + +[#constraintStreamsComplement] +=== Complementing a stream + +The <<constraintStreamsJoin,join building block>> provided by Constraint Streams is technically an inner join. +What this means is that only the matches that are present in both streams are considered. +For example, if you have a stream of `Employee` instances and a stream of `Shift` instances, +joining `Shift` instances with `Employee` instances will only return shifts that are assigned to an employee. +Employees without shifts will not be considered. + +In cases such as xref:constraints-and-score/load-bancing-and-fairness.adoc#loadBalancingAndFairness[load balancing], +a similar situation happens where the `Shift` instances only refence the `Employee` instances assigned to them. +For a properly balanced solution, you also need to include `Employee` instances that are not assigned to any shifts. + +This is where you can use the `complement` block as shown in the following example: + +[source,java,options="nowrap"] +---- + factory.forEach(Shift.class) + .groupBy(Shift::getEmployee, count()) + .complement(Employee.class, employee -> 0) + .groupBy(loadBalance(...)) +---- + +After the <<constraintStreamsGroupingAndCollectors,`groupBy` building block>>, +the stream contains only employees with at least one shift assigned, +and each carries a count of shifts assigned. +The type of the stream is `BiConstraintStream<Employee, Integer>`. + +To add all the `Employee` instances that do not have any shift assigned, +the `complement` building block is used. +It looks at all the `Employee` instances already in the stream, +and adds to the stream all known `Employee` instances that are not in the stream yet.
```suggestion To add all the `Employee` instances that do not have any shifts assigned, the `complement` building block is used. It looks at all the `Employee` instances already in the stream, and adds all known `Employee` instances that are not present to the stream. ```
timefold-solver
github_2023
others
918
TimefoldAI
lee-carlon
@@ -0,0 +1,205 @@ +[#loadBalancingAndFairness] += Load balancing and fairness +:doctype: book +:sectnums: +:icons: font + +Load balancing is a common constraint for many Timefold Solver use cases. +Especially when scheduling employees, the workload needs to be spread out fairly; +there may even be legal requirements to that effect. + +[#fairnessWhatIsFair] +== What is fair? + +Fairness is a complex concept, and it is not always clear what is fair. +For example, let’s assign 15 undesirable tasks to five employees. +Each task takes a day, but they have different skill requirements.
```suggestion Each task takes a day, but the tasks have different skill requirements. ```
timefold-solver
github_2023
others
918
TimefoldAI
lee-carlon
@@ -0,0 +1,205 @@ +[#loadBalancingAndFairness] += Load balancing and fairness +:doctype: book +:sectnums: +:icons: font + +Load balancing is a common constraint for many Timefold Solver use cases. +Especially when scheduling employees, the workload needs to be spread out fairly; +there may even be legal requirements to that effect. + +[#fairnessWhatIsFair] +== What is fair? + +Fairness is a complex concept, and it is not always clear what is fair. +For example, let’s assign 15 undesirable tasks to five employees. +Each task takes a day, but they have different skill requirements. +In a perfectly fair schedule, each employee will get three tasks, +because the average is `15 / 5 = 3`. + +Unfortunately, this doesn't solve the entire problem, because there are other constraints. +For example, there are seven tasks that require a skill which only two of the employees possess. +One of them will have to do at least four tasks. + +From the above, we can see that our schedule cannot be perfectly fair, +but we can make it as fair as possible. + +[#fairnessWhichIsFairer] +=== Which is fairer? + +We can define fairness in two opposing ways: + +- A schedule is fair if most users think it is fair to them. +- A schedule is fair if the employee with most tasks has as few tasks as possible. + +Since we want to treat all employees equally, the second definition is correct. +Besides, if we make almost everyone happy by letting one employee do all the work, +that employee would probably quit on us and that doesn't help.
```suggestion that employee would probably quit and that doesn't help. ``` Or perhaps: that employee would probably quit and that's definitely not fair.
timefold-solver
github_2023
others
918
TimefoldAI
lee-carlon
@@ -0,0 +1,205 @@ +[#loadBalancingAndFairness] += Load balancing and fairness +:doctype: book +:sectnums: +:icons: font + +Load balancing is a common constraint for many Timefold Solver use cases. +Especially when scheduling employees, the workload needs to be spread out fairly; +there may even be legal requirements to that effect. + +[#fairnessWhatIsFair] +== What is fair? + +Fairness is a complex concept, and it is not always clear what is fair. +For example, let’s assign 15 undesirable tasks to five employees. +Each task takes a day, but they have different skill requirements. +In a perfectly fair schedule, each employee will get three tasks, +because the average is `15 / 5 = 3`. + +Unfortunately, this doesn't solve the entire problem, because there are other constraints. +For example, there are seven tasks that require a skill which only two of the employees possess. +One of them will have to do at least four tasks. + +From the above, we can see that our schedule cannot be perfectly fair, +but we can make it as fair as possible. + +[#fairnessWhichIsFairer] +=== Which is fairer? + +We can define fairness in two opposing ways: + +- A schedule is fair if most users think it is fair to them. +- A schedule is fair if the employee with most tasks has as few tasks as possible. + +Since we want to treat all employees equally, the second definition is correct. +Besides, if we make almost everyone happy by letting one employee do all the work, +that employee would probably quit on us and that doesn't help. + +Let’s look at a few different solutions of the same dataset, sorted from most to least fair. +Each one has 15 tasks: + +[%header,cols="7"] +|=== +| |Ann |Beth |Carl |Dan |Ed |Solution Quality + +|Schedule A +|3 +|3 +|3 +|3 +|3 +|Most fair + +|Schedule B +|4 +|4 +|3 +|2 +|2 +| + +|Schedule C +|5 +|3 +|3 +|2 +|2 +| + +|Schedule D +|5 +|5 +|2 +|2 +|1 +| + +|Schedule E +|6 +|3 +|3 +|2 +|1 +| + +|Schedule F +|5 +|6 +|2 +|1 +|1 +| + +|Schedule G +|11 +|1 +|1 +|1 +|1 +|Most unfair +|=== + +Ann has the most tasks each time. +How do we compare schedules in which Ann has the same number of tasks? + +[%header,cols="7"] +|=== +| |Ann |Beth |Carl |Dan |Ed |Solution Quality + +|Schedule C +|5 +|3 +|3 +|2 +|2 +|More fair + +|Schedule D +|5 +|5 +|2 +|2 +|1 +|Less fair +|=== + +We take a look at the second most loaded employee, Beth. +In schedule D, she has five tasks, while in schedule C, she has less. +This makes schedule C fairer.
```suggestion This makes schedule C fairer overall. ``` I added overall here to make it clearer that we're not just comparing Ann and Beth, but considering the entire schedule.
timefold-solver
github_2023
others
918
TimefoldAI
lee-carlon
@@ -0,0 +1,205 @@ +[#loadBalancingAndFairness] += Load balancing and fairness +:doctype: book +:sectnums: +:icons: font + +Load balancing is a common constraint for many Timefold Solver use cases. +Especially when scheduling employees, the workload needs to be spread out fairly; +there may even be legal requirements to that effect. + +[#fairnessWhatIsFair] +== What is fair? + +Fairness is a complex concept, and it is not always clear what is fair. +For example, let’s assign 15 undesirable tasks to five employees. +Each task takes a day, but they have different skill requirements. +In a perfectly fair schedule, each employee will get three tasks, +because the average is `15 / 5 = 3`. + +Unfortunately, this doesn't solve the entire problem, because there are other constraints. +For example, there are seven tasks that require a skill which only two of the employees possess. +One of them will have to do at least four tasks. + +From the above, we can see that our schedule cannot be perfectly fair, +but we can make it as fair as possible. + +[#fairnessWhichIsFairer] +=== Which is fairer? + +We can define fairness in two opposing ways: + +- A schedule is fair if most users think it is fair to them. +- A schedule is fair if the employee with most tasks has as few tasks as possible. + +Since we want to treat all employees equally, the second definition is correct. +Besides, if we make almost everyone happy by letting one employee do all the work, +that employee would probably quit on us and that doesn't help. + +Let’s look at a few different solutions of the same dataset, sorted from most to least fair. +Each one has 15 tasks: + +[%header,cols="7"] +|=== +| |Ann |Beth |Carl |Dan |Ed |Solution Quality + +|Schedule A +|3 +|3 +|3 +|3 +|3 +|Most fair + +|Schedule B +|4 +|4 +|3 +|2 +|2 +| + +|Schedule C +|5 +|3 +|3 +|2 +|2 +| + +|Schedule D +|5 +|5 +|2 +|2 +|1 +| + +|Schedule E +|6 +|3 +|3 +|2 +|1 +| + +|Schedule F +|5 +|6 +|2 +|1 +|1 +| + +|Schedule G +|11 +|1 +|1 +|1 +|1 +|Most unfair +|=== + +Ann has the most tasks each time. +How do we compare schedules in which Ann has the same number of tasks? + +[%header,cols="7"] +|=== +| |Ann |Beth |Carl |Dan |Ed |Solution Quality + +|Schedule C +|5 +|3 +|3 +|2 +|2 +|More fair + +|Schedule D +|5 +|5 +|2 +|2 +|1 +|Less fair +|=== + +We take a look at the second most loaded employee, Beth. +In schedule D, she has five tasks, while in schedule C, she has less. +This makes schedule C fairer. + +This is the definition of fairness that we will use in the remainder of this section.
```suggestion This is the definition of fairness we use in the remainder of this section. ```
timefold-solver
github_2023
others
918
TimefoldAI
lee-carlon
@@ -0,0 +1,205 @@ +[#loadBalancingAndFairness] += Load balancing and fairness +:doctype: book +:sectnums: +:icons: font + +Load balancing is a common constraint for many Timefold Solver use cases. +Especially when scheduling employees, the workload needs to be spread out fairly; +there may even be legal requirements to that effect. + +[#fairnessWhatIsFair] +== What is fair? + +Fairness is a complex concept, and it is not always clear what is fair. +For example, let’s assign 15 undesirable tasks to five employees. +Each task takes a day, but they have different skill requirements. +In a perfectly fair schedule, each employee will get three tasks, +because the average is `15 / 5 = 3`. + +Unfortunately, this doesn't solve the entire problem, because there are other constraints. +For example, there are seven tasks that require a skill which only two of the employees possess. +One of them will have to do at least four tasks. + +From the above, we can see that our schedule cannot be perfectly fair, +but we can make it as fair as possible. + +[#fairnessWhichIsFairer] +=== Which is fairer? + +We can define fairness in two opposing ways: + +- A schedule is fair if most users think it is fair to them. +- A schedule is fair if the employee with most tasks has as few tasks as possible. + +Since we want to treat all employees equally, the second definition is correct. +Besides, if we make almost everyone happy by letting one employee do all the work, +that employee would probably quit on us and that doesn't help. + +Let’s look at a few different solutions of the same dataset, sorted from most to least fair. +Each one has 15 tasks: + +[%header,cols="7"] +|=== +| |Ann |Beth |Carl |Dan |Ed |Solution Quality + +|Schedule A +|3 +|3 +|3 +|3 +|3 +|Most fair + +|Schedule B +|4 +|4 +|3 +|2 +|2 +| + +|Schedule C +|5 +|3 +|3 +|2 +|2 +| + +|Schedule D +|5 +|5 +|2 +|2 +|1 +| + +|Schedule E +|6 +|3 +|3 +|2 +|1 +| + +|Schedule F +|5 +|6 +|2 +|1 +|1 +| + +|Schedule G +|11 +|1 +|1 +|1 +|1 +|Most unfair +|=== + +Ann has the most tasks each time. +How do we compare schedules in which Ann has the same number of tasks? + +[%header,cols="7"] +|=== +| |Ann |Beth |Carl |Dan |Ed |Solution Quality + +|Schedule C +|5 +|3 +|3 +|2 +|2 +|More fair + +|Schedule D +|5 +|5 +|2 +|2 +|1 +|Less fair +|=== + +We take a look at the second most loaded employee, Beth. +In schedule D, she has five tasks, while in schedule C, she has less. +This makes schedule C fairer. + +This is the definition of fairness that we will use in the remainder of this section. + +[#fairnessConstraints] +== Fairness constraints + +Timefold Solver supports fairness constraints out of the box +through the use of xref:constraints-and-score/score-calculation.adoc#constraintStreamsGroupingAndCollectors[grouping] +and the xref:constraints-and-score/score-calculation.adoc#collectorsLoadBalance[load balancing constraint collector]. +In your `ConstraintProvider` implementation, a load-balancing constraint may look like this: + +[source,java] +---- +Constraint fairAssignments(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(ShiftAssignment.class) + .groupBy(ConstraintCollectors.loadBalance(ShiftAssignment::getEmployee)) + .penalizeBigDecimal(HardSoftBigDecimalScore.ONE_SOFT, LoadBalance::unfairness) + .asConstraint("fairAssignments"); +} +---- + +[IMPORTANT] +==== +When using fairness constraints, +we recommend that you use one of the xref:constraints-and-score/overview.adoc#scoreType[score types] based on `BigDecimal`, +such as `HardSoftBigDecimalScore`. +See below for a <<fairnessWhyBigDecimal,detailed rationale>>. +==== + +This constraint will penalize the solution based on its unfairness, +defined in this case by how many `ShiftAssignment` are allocated to any particular `Employee`. + +Unfairness is a dimensionless number, measuring how fair the solution is, +with a lower value indicating a fairer solution.
```suggestion Unfairness is a dimensionless number that measures how fair the solution is. A lower value indicates a fairer solution. ```
timefold-solver
github_2023
others
918
TimefoldAI
lee-carlon
@@ -0,0 +1,205 @@ +[#loadBalancingAndFairness] += Load balancing and fairness +:doctype: book +:sectnums: +:icons: font + +Load balancing is a common constraint for many Timefold Solver use cases. +Especially when scheduling employees, the workload needs to be spread out fairly; +there may even be legal requirements to that effect. + +[#fairnessWhatIsFair] +== What is fair? + +Fairness is a complex concept, and it is not always clear what is fair. +For example, let’s assign 15 undesirable tasks to five employees. +Each task takes a day, but they have different skill requirements. +In a perfectly fair schedule, each employee will get three tasks, +because the average is `15 / 5 = 3`. + +Unfortunately, this doesn't solve the entire problem, because there are other constraints. +For example, there are seven tasks that require a skill which only two of the employees possess. +One of them will have to do at least four tasks. + +From the above, we can see that our schedule cannot be perfectly fair, +but we can make it as fair as possible. + +[#fairnessWhichIsFairer] +=== Which is fairer? + +We can define fairness in two opposing ways: + +- A schedule is fair if most users think it is fair to them. +- A schedule is fair if the employee with most tasks has as few tasks as possible. + +Since we want to treat all employees equally, the second definition is correct. +Besides, if we make almost everyone happy by letting one employee do all the work, +that employee would probably quit on us and that doesn't help. + +Let’s look at a few different solutions of the same dataset, sorted from most to least fair. +Each one has 15 tasks: + +[%header,cols="7"] +|=== +| |Ann |Beth |Carl |Dan |Ed |Solution Quality + +|Schedule A +|3 +|3 +|3 +|3 +|3 +|Most fair + +|Schedule B +|4 +|4 +|3 +|2 +|2 +| + +|Schedule C +|5 +|3 +|3 +|2 +|2 +| + +|Schedule D +|5 +|5 +|2 +|2 +|1 +| + +|Schedule E +|6 +|3 +|3 +|2 +|1 +| + +|Schedule F +|5 +|6 +|2 +|1 +|1 +| + +|Schedule G +|11 +|1 +|1 +|1 +|1 +|Most unfair +|=== + +Ann has the most tasks each time. +How do we compare schedules in which Ann has the same number of tasks? + +[%header,cols="7"] +|=== +| |Ann |Beth |Carl |Dan |Ed |Solution Quality + +|Schedule C +|5 +|3 +|3 +|2 +|2 +|More fair + +|Schedule D +|5 +|5 +|2 +|2 +|1 +|Less fair +|=== + +We take a look at the second most loaded employee, Beth. +In schedule D, she has five tasks, while in schedule C, she has less. +This makes schedule C fairer. + +This is the definition of fairness that we will use in the remainder of this section. + +[#fairnessConstraints] +== Fairness constraints + +Timefold Solver supports fairness constraints out of the box +through the use of xref:constraints-and-score/score-calculation.adoc#constraintStreamsGroupingAndCollectors[grouping] +and the xref:constraints-and-score/score-calculation.adoc#collectorsLoadBalance[load balancing constraint collector]. +In your `ConstraintProvider` implementation, a load-balancing constraint may look like this: + +[source,java] +---- +Constraint fairAssignments(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(ShiftAssignment.class) + .groupBy(ConstraintCollectors.loadBalance(ShiftAssignment::getEmployee)) + .penalizeBigDecimal(HardSoftBigDecimalScore.ONE_SOFT, LoadBalance::unfairness) + .asConstraint("fairAssignments"); +} +---- + +[IMPORTANT] +==== +When using fairness constraints, +we recommend that you use one of the xref:constraints-and-score/overview.adoc#scoreType[score types] based on `BigDecimal`, +such as `HardSoftBigDecimalScore`. +See below for a <<fairnessWhyBigDecimal,detailed rationale>>. +==== + +This constraint will penalize the solution based on its unfairness, +defined in this case by how many `ShiftAssignment` are allocated to any particular `Employee`. + +Unfairness is a dimensionless number, measuring how fair the solution is, +with a lower value indicating a fairer solution. +The smallest possible value is 1, indicating that the solution is perfectly fair. +There is no upper limit to the value, +and it is expected to scale linearly with the size of your dataset. + +Different unfairness values may only be compared for solutions coming from the same dataset. +Unfairness values computed from different datasets are incomparable. + +[#fairnessWhyBigDecimal] +=== Why `BigDecimal`? + +When using fairness constraints, +we recommend that you use one of the xref:constraints-and-score/overview.adoc#scoreType[score types] based on `BigDecimal`. +We base our recommendation on the following reasons: + +- The unfairness value is a rational number. +The corresponding floating-point type (`double`) +is xref:constraints-and-score/overview.adoc#avoidFloatingPointNumbersInScoreCalculation[not suitable for score calculations]. +- Rounding the unfairness value to the nearest integer would lose precision, +causing a xref:constraints-and-score/performance.adoc#scoreTrap[score trap]. +Even a small difference in unfairness (such as between `1.000001` and `1.000002`) +gives the solver crucial information to distinguish different solutions from each other. + +If the somewhat worsened performance of `BigDecimal`-based score calculation is a concern, +you may decide instead to multiply the unfairness value by some power of ten to preserve precision, +and only then rounding it to the nearest integer. +This in turn allows you to use the simple integer-based score types. +
```suggestion If the somewhat worsened performance of a `BigDecimal`-based score calculation is a concern, instead, you may decide to multiply the unfairness value by some power of ten to preserve precision, and only then round it to the nearest integer. This allows you to use the simple integer-based score types. ```
timefold-solver
github_2023
others
918
TimefoldAI
lee-carlon
@@ -0,0 +1,205 @@ +[#loadBalancingAndFairness] += Load balancing and fairness +:doctype: book +:sectnums: +:icons: font + +Load balancing is a common constraint for many Timefold Solver use cases. +Especially when scheduling employees, the workload needs to be spread out fairly; +there may even be legal requirements to that effect. + +[#fairnessWhatIsFair] +== What is fair? + +Fairness is a complex concept, and it is not always clear what is fair. +For example, let’s assign 15 undesirable tasks to five employees. +Each task takes a day, but they have different skill requirements. +In a perfectly fair schedule, each employee will get three tasks, +because the average is `15 / 5 = 3`. + +Unfortunately, this doesn't solve the entire problem, because there are other constraints. +For example, there are seven tasks that require a skill which only two of the employees possess. +One of them will have to do at least four tasks. + +From the above, we can see that our schedule cannot be perfectly fair, +but we can make it as fair as possible. + +[#fairnessWhichIsFairer] +=== Which is fairer? + +We can define fairness in two opposing ways: + +- A schedule is fair if most users think it is fair to them. +- A schedule is fair if the employee with most tasks has as few tasks as possible. + +Since we want to treat all employees equally, the second definition is correct. +Besides, if we make almost everyone happy by letting one employee do all the work, +that employee would probably quit on us and that doesn't help. + +Let’s look at a few different solutions of the same dataset, sorted from most to least fair. +Each one has 15 tasks: + +[%header,cols="7"] +|=== +| |Ann |Beth |Carl |Dan |Ed |Solution Quality + +|Schedule A +|3 +|3 +|3 +|3 +|3 +|Most fair + +|Schedule B +|4 +|4 +|3 +|2 +|2 +| + +|Schedule C +|5 +|3 +|3 +|2 +|2 +| + +|Schedule D +|5 +|5 +|2 +|2 +|1 +| + +|Schedule E +|6 +|3 +|3 +|2 +|1 +| + +|Schedule F +|5 +|6 +|2 +|1 +|1 +| + +|Schedule G +|11 +|1 +|1 +|1 +|1 +|Most unfair +|=== + +Ann has the most tasks each time. +How do we compare schedules in which Ann has the same number of tasks? + +[%header,cols="7"] +|=== +| |Ann |Beth |Carl |Dan |Ed |Solution Quality + +|Schedule C +|5 +|3 +|3 +|2 +|2 +|More fair + +|Schedule D +|5 +|5 +|2 +|2 +|1 +|Less fair +|=== + +We take a look at the second most loaded employee, Beth. +In schedule D, she has five tasks, while in schedule C, she has less. +This makes schedule C fairer. + +This is the definition of fairness that we will use in the remainder of this section. + +[#fairnessConstraints] +== Fairness constraints + +Timefold Solver supports fairness constraints out of the box +through the use of xref:constraints-and-score/score-calculation.adoc#constraintStreamsGroupingAndCollectors[grouping] +and the xref:constraints-and-score/score-calculation.adoc#collectorsLoadBalance[load balancing constraint collector]. +In your `ConstraintProvider` implementation, a load-balancing constraint may look like this: + +[source,java] +---- +Constraint fairAssignments(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(ShiftAssignment.class) + .groupBy(ConstraintCollectors.loadBalance(ShiftAssignment::getEmployee)) + .penalizeBigDecimal(HardSoftBigDecimalScore.ONE_SOFT, LoadBalance::unfairness) + .asConstraint("fairAssignments"); +} +---- + +[IMPORTANT] +==== +When using fairness constraints, +we recommend that you use one of the xref:constraints-and-score/overview.adoc#scoreType[score types] based on `BigDecimal`, +such as `HardSoftBigDecimalScore`. +See below for a <<fairnessWhyBigDecimal,detailed rationale>>. +==== + +This constraint will penalize the solution based on its unfairness, +defined in this case by how many `ShiftAssignment` are allocated to any particular `Employee`. + +Unfairness is a dimensionless number, measuring how fair the solution is, +with a lower value indicating a fairer solution. +The smallest possible value is 1, indicating that the solution is perfectly fair. +There is no upper limit to the value, +and it is expected to scale linearly with the size of your dataset. + +Different unfairness values may only be compared for solutions coming from the same dataset. +Unfairness values computed from different datasets are incomparable. + +[#fairnessWhyBigDecimal] +=== Why `BigDecimal`? + +When using fairness constraints, +we recommend that you use one of the xref:constraints-and-score/overview.adoc#scoreType[score types] based on `BigDecimal`. +We base our recommendation on the following reasons: + +- The unfairness value is a rational number. +The corresponding floating-point type (`double`) +is xref:constraints-and-score/overview.adoc#avoidFloatingPointNumbersInScoreCalculation[not suitable for score calculations]. +- Rounding the unfairness value to the nearest integer would lose precision, +causing a xref:constraints-and-score/performance.adoc#scoreTrap[score trap]. +Even a small difference in unfairness (such as between `1.000001` and `1.000002`) +gives the solver crucial information to distinguish different solutions from each other. + +If the somewhat worsened performance of `BigDecimal`-based score calculation is a concern, +you may decide instead to multiply the unfairness value by some power of ten to preserve precision, +and only then rounding it to the nearest integer. +This in turn allows you to use the simple integer-based score types. + +Unfortunately, this also requires you to re-balance your constraint weights, +multiplying them by the same power of ten as used for unfairness. +Otherwise, the unfairness constraint would dominate the score,
```suggestion Otherwise, the unfairness constraint will dominate the score, ```
timefold-solver
github_2023
others
918
TimefoldAI
lee-carlon
@@ -0,0 +1,205 @@ +[#loadBalancingAndFairness] += Load balancing and fairness +:doctype: book +:sectnums: +:icons: font + +Load balancing is a common constraint for many Timefold Solver use cases. +Especially when scheduling employees, the workload needs to be spread out fairly; +there may even be legal requirements to that effect. + +[#fairnessWhatIsFair] +== What is fair? + +Fairness is a complex concept, and it is not always clear what is fair. +For example, let’s assign 15 undesirable tasks to five employees. +Each task takes a day, but they have different skill requirements. +In a perfectly fair schedule, each employee will get three tasks, +because the average is `15 / 5 = 3`. + +Unfortunately, this doesn't solve the entire problem, because there are other constraints. +For example, there are seven tasks that require a skill which only two of the employees possess. +One of them will have to do at least four tasks. + +From the above, we can see that our schedule cannot be perfectly fair, +but we can make it as fair as possible. + +[#fairnessWhichIsFairer] +=== Which is fairer? + +We can define fairness in two opposing ways: + +- A schedule is fair if most users think it is fair to them. +- A schedule is fair if the employee with most tasks has as few tasks as possible. + +Since we want to treat all employees equally, the second definition is correct. +Besides, if we make almost everyone happy by letting one employee do all the work, +that employee would probably quit on us and that doesn't help. + +Let’s look at a few different solutions of the same dataset, sorted from most to least fair. +Each one has 15 tasks: + +[%header,cols="7"] +|=== +| |Ann |Beth |Carl |Dan |Ed |Solution Quality + +|Schedule A +|3 +|3 +|3 +|3 +|3 +|Most fair + +|Schedule B +|4 +|4 +|3 +|2 +|2 +| + +|Schedule C +|5 +|3 +|3 +|2 +|2 +| + +|Schedule D +|5 +|5 +|2 +|2 +|1 +| + +|Schedule E +|6 +|3 +|3 +|2 +|1 +| + +|Schedule F +|5 +|6 +|2 +|1 +|1 +| + +|Schedule G +|11 +|1 +|1 +|1 +|1 +|Most unfair +|=== + +Ann has the most tasks each time. +How do we compare schedules in which Ann has the same number of tasks? + +[%header,cols="7"] +|=== +| |Ann |Beth |Carl |Dan |Ed |Solution Quality + +|Schedule C +|5 +|3 +|3 +|2 +|2 +|More fair + +|Schedule D +|5 +|5 +|2 +|2 +|1 +|Less fair +|=== + +We take a look at the second most loaded employee, Beth. +In schedule D, she has five tasks, while in schedule C, she has less. +This makes schedule C fairer. + +This is the definition of fairness that we will use in the remainder of this section. + +[#fairnessConstraints] +== Fairness constraints + +Timefold Solver supports fairness constraints out of the box +through the use of xref:constraints-and-score/score-calculation.adoc#constraintStreamsGroupingAndCollectors[grouping] +and the xref:constraints-and-score/score-calculation.adoc#collectorsLoadBalance[load balancing constraint collector]. +In your `ConstraintProvider` implementation, a load-balancing constraint may look like this: + +[source,java] +---- +Constraint fairAssignments(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(ShiftAssignment.class) + .groupBy(ConstraintCollectors.loadBalance(ShiftAssignment::getEmployee)) + .penalizeBigDecimal(HardSoftBigDecimalScore.ONE_SOFT, LoadBalance::unfairness) + .asConstraint("fairAssignments"); +} +---- + +[IMPORTANT] +==== +When using fairness constraints, +we recommend that you use one of the xref:constraints-and-score/overview.adoc#scoreType[score types] based on `BigDecimal`, +such as `HardSoftBigDecimalScore`. +See below for a <<fairnessWhyBigDecimal,detailed rationale>>. +==== + +This constraint will penalize the solution based on its unfairness, +defined in this case by how many `ShiftAssignment` are allocated to any particular `Employee`. + +Unfairness is a dimensionless number, measuring how fair the solution is, +with a lower value indicating a fairer solution. +The smallest possible value is 1, indicating that the solution is perfectly fair. +There is no upper limit to the value, +and it is expected to scale linearly with the size of your dataset. + +Different unfairness values may only be compared for solutions coming from the same dataset. +Unfairness values computed from different datasets are incomparable. + +[#fairnessWhyBigDecimal] +=== Why `BigDecimal`? + +When using fairness constraints, +we recommend that you use one of the xref:constraints-and-score/overview.adoc#scoreType[score types] based on `BigDecimal`. +We base our recommendation on the following reasons: + +- The unfairness value is a rational number. +The corresponding floating-point type (`double`) +is xref:constraints-and-score/overview.adoc#avoidFloatingPointNumbersInScoreCalculation[not suitable for score calculations]. +- Rounding the unfairness value to the nearest integer would lose precision, +causing a xref:constraints-and-score/performance.adoc#scoreTrap[score trap]. +Even a small difference in unfairness (such as between `1.000001` and `1.000002`) +gives the solver crucial information to distinguish different solutions from each other. + +If the somewhat worsened performance of `BigDecimal`-based score calculation is a concern, +you may decide instead to multiply the unfairness value by some power of ten to preserve precision, +and only then rounding it to the nearest integer. +This in turn allows you to use the simple integer-based score types. + +Unfortunately, this also requires you to re-balance your constraint weights, +multiplying them by the same power of ten as used for unfairness. +Otherwise, the unfairness constraint would dominate the score, +effectively becoming the most important constraint. + +If you decide to go down this route, +we recommend that you preserve at least six decimal places of the unfairness value
```suggestion If you take this approach, we recommend that you preserve at least six decimal places of the unfairness value ```
timefold-solver
github_2023
java
918
TimefoldAI
Christopher-Chianelli
@@ -28,7 +28,7 @@ public BavetConcatUniConstraintStream(BavetConstraintFactory<Solution_> constrai @Override public boolean guaranteesDistinct() { - return false; // The two parents could have the same source; guarantee impossible.
Unsure about `concat` class names for the same carnality; maybe do `BavetUniConcatUniConstraintStream` so it has the same format as all the others?
timefold-solver
github_2023
java
918
TimefoldAI
Christopher-Chianelli
@@ -1095,6 +1096,34 @@ public void consecutiveUsage() { assertResult(collector, container, buildConsecutiveUsage()); } + @Override + @Test + public void loadBalance() { + var collector = ConstraintCollectors.<String, Integer, String> loadBalance((a, b) -> a, (a, b) -> b); + var container = collector.supplier().get(); + + // Default state. + assertUnfairness(collector, container, BigDecimal.ZERO); + // Add first value, we have one now. + var firstRetractor = accumulate(collector, container, "A", 2); + assertUnfairness(collector, container, BigDecimal.ZERO); + // Add second value, we have two now. + var secondRetractor = accumulate(collector, container, "B", 1); + assertUnfairness(collector, container, BigDecimal.valueOf(0.707107));
Maybe explain in a comment this is `sqrt((3-2.5)^2 + (2 - 2.5)^2) = sqrt(0.5^2 + 0.5^2) = sqrt(0.25 + 0.25) = sqrt(0.5)`
timefold-solver
github_2023
java
918
TimefoldAI
Christopher-Chianelli
@@ -418,4 +418,366 @@ default void rewards() { */ void rewards(String message); + /** + * Asserts that the {@link Constraint} being tested, given a set of facts, + * results in a specific penalty larger than given. + * <p> + * Ignores the constraint weight: it only asserts the match weights. + * For example: + * a match with a match weight of {@code 10} on a constraint with a constraint weight of {@code -2hard} + * reduces the score by {@code -20hard}. + * In that case, this assertion checks for {@code 10}. + * <p> + * An {@code int matchWeightTotal} automatically casts to {@code long} for {@link HardSoftLongScore long scores}. + * + * @param matchWeightTotal at least 0, expected sum of match weights of matches of the constraint. + * @throws AssertionError when the expected penalty is not observed + */ + default void penalizesByMoreThan(int matchWeightTotal) { + penalizesByMoreThan(null, matchWeightTotal); + } + + /** + * As defined by {@link #penalizesByMoreThan(int)}. + * + * @param message sometimes null, description of the scenario being asserted + * @param matchWeightTotal at least 0, expected sum of match weights of matches of the constraint. + * @throws AssertionError when the expected penalty is not observed + */ + void penalizesByMoreThan(String message, int matchWeightTotal);
I wonder if we should have a `compareToGiven(Facts...).penalizesMore(String?)` Example usage: ```java constraintVerifier.verifyThat(MyConstraintProvider::fairnessConstraint) .given(Shift(Amy), Shift(Amy), Shift(Beth), Shift(Beth)) .compareToGiven(Shift(Amy), Shift(Beth), Shift(Beth), Shift(Beth)) .penalizesLess(); ```
timefold-solver
github_2023
java
923
TimefoldAI
triceo
@@ -56,6 +60,16 @@ static <Score_ extends Score<Score_>> ConstraintAnalysis<Score_> of(ConstraintRe Objects.requireNonNull(score); } + public int matchCount() {
Deserves a Javadoc to explain the exception maybe being thrown.
timefold-solver
github_2023
java
923
TimefoldAI
triceo
@@ -156,6 +170,51 @@ public String constraintName() { return constraintRef.constraintName(); } + /** + * Returns a diagnostic text that explains part of the score quality through the {@link ConstraintAnalysis} API.
```suggestion * Returns a diagnostic text that explains part of the score quality through the {@link ConstraintAnalysis} API. * The string is built fresh every time the method is called. ```
timefold-solver
github_2023
java
923
TimefoldAI
triceo
@@ -156,6 +170,51 @@ public String constraintName() { return constraintRef.constraintName(); } + /** + * Returns a diagnostic text that explains part of the score quality through the {@link ConstraintAnalysis} API. + * + * @return never null + */ + public String summarize() { + StringBuilder summary = new StringBuilder();
In new code, we use `var` where possible.
timefold-solver
github_2023
java
923
TimefoldAI
triceo
@@ -156,6 +170,51 @@ public String constraintName() { return constraintRef.constraintName(); } + /** + * Returns a diagnostic text that explains part of the score quality through the {@link ConstraintAnalysis} API. + * + * @return never null + */ + public String summarize() { + StringBuilder summary = new StringBuilder(); + summary.append(""" + Explanation of score (%s): + Constraint matches: + """.formatted(score)); + Comparator<MatchAnalysis<Score_>> matchScoreComparator = comparing(MatchAnalysis::score); + + var constraintMatches = matches(); + if (constraintMatches == null) { + throw new IllegalArgumentException(""" + The constraint matches must be non-null. + Maybe use ScoreAnalysisFetchPolicy.FETCH_ALL to request the score analysis + """); + } + if (constraintMatches.isEmpty()) { + summary.append(""" + %s: constraint (%s) has no matches. + """.formatted(score().toShortString(), constraintRef().constraintName()));
Arguably, for short single-line strings, ```"""``` is unnecessary and more verbose. But careful to maintain the newline at the end.
timefold-solver
github_2023
java
923
TimefoldAI
triceo
@@ -156,6 +170,51 @@ public String constraintName() { return constraintRef.constraintName(); } + /** + * Returns a diagnostic text that explains part of the score quality through the {@link ConstraintAnalysis} API. + * + * @return never null + */ + public String summarize() { + StringBuilder summary = new StringBuilder(); + summary.append(""" + Explanation of score (%s): + Constraint matches: + """.formatted(score)); + Comparator<MatchAnalysis<Score_>> matchScoreComparator = comparing(MatchAnalysis::score); + + var constraintMatches = matches(); + if (constraintMatches == null) { + throw new IllegalArgumentException(""" + The constraint matches must be non-null. + Maybe use ScoreAnalysisFetchPolicy.FETCH_ALL to request the score analysis + """); + } + if (constraintMatches.isEmpty()) { + summary.append(""" + %s: constraint (%s) has no matches. + """.formatted(score().toShortString(), constraintRef().constraintName())); + } else { + summary.append("""
Dtto.
timefold-solver
github_2023
java
923
TimefoldAI
triceo
@@ -156,6 +170,51 @@ public String constraintName() { return constraintRef.constraintName(); } + /** + * Returns a diagnostic text that explains part of the score quality through the {@link ConstraintAnalysis} API. + * + * @return never null + */ + public String summarize() { + StringBuilder summary = new StringBuilder(); + summary.append(""" + Explanation of score (%s): + Constraint matches: + """.formatted(score)); + Comparator<MatchAnalysis<Score_>> matchScoreComparator = comparing(MatchAnalysis::score); + + var constraintMatches = matches(); + if (constraintMatches == null) { + throw new IllegalArgumentException(""" + The constraint matches must be non-null. + Maybe use ScoreAnalysisFetchPolicy.FETCH_ALL to request the score analysis + """); + } + if (constraintMatches.isEmpty()) { + summary.append(""" + %s: constraint (%s) has no matches. + """.formatted(score().toShortString(), constraintRef().constraintName())); + } else { + summary.append(""" + %s: constraint (%s) has %s matches: + """.formatted(score().toShortString(), constraintRef().constraintName(), constraintMatches.size())); + } + constraintMatches.stream() + .sorted(matchScoreComparator) + .limit(DEFAULT_SUMMARY_CONSTRAINT_MATCH_LIMIT) + .forEach(match -> summary.append("""
Dtto.
timefold-solver
github_2023
java
923
TimefoldAI
triceo
@@ -156,6 +170,51 @@ public String constraintName() { return constraintRef.constraintName(); } + /** + * Returns a diagnostic text that explains part of the score quality through the {@link ConstraintAnalysis} API. + * + * @return never null + */ + public String summarize() { + StringBuilder summary = new StringBuilder(); + summary.append(""" + Explanation of score (%s): + Constraint matches: + """.formatted(score)); + Comparator<MatchAnalysis<Score_>> matchScoreComparator = comparing(MatchAnalysis::score); + + var constraintMatches = matches(); + if (constraintMatches == null) { + throw new IllegalArgumentException(""" + The constraint matches must be non-null. + Maybe use ScoreAnalysisFetchPolicy.FETCH_ALL to request the score analysis + """); + } + if (constraintMatches.isEmpty()) { + summary.append(""" + %s: constraint (%s) has no matches. + """.formatted(score().toShortString(), constraintRef().constraintName())); + } else { + summary.append(""" + %s: constraint (%s) has %s matches: + """.formatted(score().toShortString(), constraintRef().constraintName(), constraintMatches.size())); + } + constraintMatches.stream() + .sorted(matchScoreComparator) + .limit(DEFAULT_SUMMARY_CONSTRAINT_MATCH_LIMIT) + .forEach(match -> summary.append(""" + %s: justified with (%s) + """.formatted(match.score().toShortString(), + match.justification()))); + if (constraintMatches.size() > DEFAULT_SUMMARY_CONSTRAINT_MATCH_LIMIT) { + summary.append("""
Dtto.
timefold-solver
github_2023
java
923
TimefoldAI
triceo
@@ -141,4 +145,63 @@ public Collection<ConstraintAnalysis<Score_>> constraintAnalyses() { return constraintMap.values(); } + /** + * Returns a diagnostic text that explains the solution through the {@link ConstraintAnalysis} API to identify which + * constraints cause that score quality.
```suggestion * constraints cause that score quality. * The string is built fresh every time the method is called. ```
timefold-solver
github_2023
java
923
TimefoldAI
triceo
@@ -141,4 +145,63 @@ public Collection<ConstraintAnalysis<Score_>> constraintAnalyses() { return constraintMap.values(); } + /** + * Returns a diagnostic text that explains the solution through the {@link ConstraintAnalysis} API to identify which + * constraints cause that score quality. + * <p> + * In case of an {@link Score#isFeasible() infeasible} solution, this can help diagnose the cause of that. + * + * <p> + * Do not parse the return value, its format may change without warning. + * Instead, provide this information in a UI or a service, + * use {@link ScoreAnalysis#constraintAnalyses()} + * and convert those into a domain-specific API. + * + * @return never null + */ + public String summarize() { + StringBuilder summary = new StringBuilder(); + summary.append(""" + Explanation of score (%s): + Constraint matches: + """.formatted(score)); + Comparator<ConstraintAnalysis<Score_>> constraintsScoreComparator = comparing(ConstraintAnalysis::score); + Comparator<MatchAnalysis<Score_>> matchScoreComparator = comparing(MatchAnalysis::score); + + constraintAnalyses().stream() + .sorted(constraintsScoreComparator) + .forEach(constraint -> { + var matches = constraint.matches(); + if (matches == null) { + throw new IllegalArgumentException(""" + The constraint matches must be non-null. + Maybe use ScoreAnalysisFetchPolicy.FETCH_ALL to request the score analysis + """); + } + if (matches.isEmpty()) { + summary.append("""
One-line string, no need for string literals.
timefold-solver
github_2023
java
923
TimefoldAI
triceo
@@ -141,4 +145,63 @@ public Collection<ConstraintAnalysis<Score_>> constraintAnalyses() { return constraintMap.values(); } + /** + * Returns a diagnostic text that explains the solution through the {@link ConstraintAnalysis} API to identify which + * constraints cause that score quality. + * <p> + * In case of an {@link Score#isFeasible() infeasible} solution, this can help diagnose the cause of that. + * + * <p> + * Do not parse the return value, its format may change without warning. + * Instead, provide this information in a UI or a service, + * use {@link ScoreAnalysis#constraintAnalyses()} + * and convert those into a domain-specific API. + * + * @return never null + */ + public String summarize() { + StringBuilder summary = new StringBuilder(); + summary.append(""" + Explanation of score (%s): + Constraint matches: + """.formatted(score)); + Comparator<ConstraintAnalysis<Score_>> constraintsScoreComparator = comparing(ConstraintAnalysis::score); + Comparator<MatchAnalysis<Score_>> matchScoreComparator = comparing(MatchAnalysis::score); + + constraintAnalyses().stream() + .sorted(constraintsScoreComparator) + .forEach(constraint -> { + var matches = constraint.matches(); + if (matches == null) { + throw new IllegalArgumentException(""" + The constraint matches must be non-null. + Maybe use ScoreAnalysisFetchPolicy.FETCH_ALL to request the score analysis + """); + } + if (matches.isEmpty()) { + summary.append(""" + %s: constraint (%s) has no matches. + """.formatted(constraint.score().toShortString(), constraint.constraintRef().constraintName())); + } else { + summary.append(""" + %s: constraint (%s) has %s matches:
Dtto.
timefold-solver
github_2023
java
923
TimefoldAI
triceo
@@ -141,4 +145,63 @@ public Collection<ConstraintAnalysis<Score_>> constraintAnalyses() { return constraintMap.values(); } + /** + * Returns a diagnostic text that explains the solution through the {@link ConstraintAnalysis} API to identify which + * constraints cause that score quality. + * <p> + * In case of an {@link Score#isFeasible() infeasible} solution, this can help diagnose the cause of that. + * + * <p> + * Do not parse the return value, its format may change without warning. + * Instead, provide this information in a UI or a service, + * use {@link ScoreAnalysis#constraintAnalyses()} + * and convert those into a domain-specific API. + * + * @return never null + */ + public String summarize() { + StringBuilder summary = new StringBuilder(); + summary.append(""" + Explanation of score (%s): + Constraint matches: + """.formatted(score)); + Comparator<ConstraintAnalysis<Score_>> constraintsScoreComparator = comparing(ConstraintAnalysis::score); + Comparator<MatchAnalysis<Score_>> matchScoreComparator = comparing(MatchAnalysis::score); + + constraintAnalyses().stream() + .sorted(constraintsScoreComparator) + .forEach(constraint -> { + var matches = constraint.matches(); + if (matches == null) { + throw new IllegalArgumentException(""" + The constraint matches must be non-null. + Maybe use ScoreAnalysisFetchPolicy.FETCH_ALL to request the score analysis + """); + } + if (matches.isEmpty()) { + summary.append(""" + %s: constraint (%s) has no matches. + """.formatted(constraint.score().toShortString(), constraint.constraintRef().constraintName())); + } else { + summary.append(""" + %s: constraint (%s) has %s matches: + """.formatted(constraint.score().toShortString(), constraint.constraintRef().constraintName(), + matches.size())); + } + matches.stream() + .sorted(matchScoreComparator) + .limit(DEFAULT_SUMMARY_CONSTRAINT_MATCH_LIMIT) + .forEach(match -> summary.append("""
Dtto.
timefold-solver
github_2023
java
923
TimefoldAI
triceo
@@ -141,4 +145,63 @@ public Collection<ConstraintAnalysis<Score_>> constraintAnalyses() { return constraintMap.values(); } + /** + * Returns a diagnostic text that explains the solution through the {@link ConstraintAnalysis} API to identify which + * constraints cause that score quality. + * <p> + * In case of an {@link Score#isFeasible() infeasible} solution, this can help diagnose the cause of that. + * + * <p> + * Do not parse the return value, its format may change without warning. + * Instead, provide this information in a UI or a service, + * use {@link ScoreAnalysis#constraintAnalyses()} + * and convert those into a domain-specific API. + * + * @return never null + */ + public String summarize() { + StringBuilder summary = new StringBuilder(); + summary.append(""" + Explanation of score (%s): + Constraint matches: + """.formatted(score)); + Comparator<ConstraintAnalysis<Score_>> constraintsScoreComparator = comparing(ConstraintAnalysis::score); + Comparator<MatchAnalysis<Score_>> matchScoreComparator = comparing(MatchAnalysis::score); + + constraintAnalyses().stream() + .sorted(constraintsScoreComparator) + .forEach(constraint -> { + var matches = constraint.matches(); + if (matches == null) { + throw new IllegalArgumentException(""" + The constraint matches must be non-null. + Maybe use ScoreAnalysisFetchPolicy.FETCH_ALL to request the score analysis + """); + } + if (matches.isEmpty()) { + summary.append(""" + %s: constraint (%s) has no matches. + """.formatted(constraint.score().toShortString(), constraint.constraintRef().constraintName())); + } else { + summary.append(""" + %s: constraint (%s) has %s matches: + """.formatted(constraint.score().toShortString(), constraint.constraintRef().constraintName(), + matches.size())); + } + matches.stream() + .sorted(matchScoreComparator) + .limit(DEFAULT_SUMMARY_CONSTRAINT_MATCH_LIMIT) + .forEach(match -> summary.append(""" + %s: justified with (%s) + """.formatted(match.score().toShortString(), + match.justification()))); + if (matches.size() > DEFAULT_SUMMARY_CONSTRAINT_MATCH_LIMIT) { + summary.append("""
Dtto.
timefold-solver
github_2023
java
923
TimefoldAI
triceo
@@ -53,6 +55,8 @@ public record ScoreAnalysis<Score_ extends Score<Score_>>(Score_ score,
Arguably, `ScoreAnalysis` needs an informative `toString()` too. Something like `Score analysis of score X with Y constraints`.
timefold-solver
github_2023
java
915
TimefoldAI
triceo
@@ -70,6 +70,17 @@ default SolverJobBuilder<Solution_, ProblemId_> withProblem(Solution_ problem) { SolverJobBuilder<Solution_, ProblemId_> withFinalBestSolutionConsumer(Consumer<? super Solution_> finalBestSolutionConsumer); + /** + * Sets the initialized solution consumer, which is called before starting the first + * {@link ai.timefold.solver.core.impl.localsearch.LocalSearchPhase} or + * {@link ai.timefold.solver.core.impl.phase.custom.CustomPhase} phases.
This is not what was agreed, is it? First local search, yes. First custom phase, no. Custom phase may still be initializing. Also, arguably, the definition deserves a better explanation: "Sets the consumer of the first initialized solution. First initialized solution is the solution at the end of the last phase that immediately precedes the first local search phase. This solution marks the beginning of actual optimization." Also, I'd consider changing the name of the concept from "initialized solution" to "first initialized solution", to clearly explain what is the significance of it.
timefold-solver
github_2023
java
915
TimefoldAI
triceo
@@ -275,4 +281,23 @@ public void solvingStarted(SolverScope<Solution_> solverScope) { } } } + + /** + * A listener that consumes the solution from a phase only if the phase initializes the solution. + */ + private final class InitializedSolutionPhaseListener extends PhaseLifecycleListenerAdapter<Solution_> { + + private final ConsumerSupport<Solution_, ProblemId_> consumerSupport; + + public InitializedSolutionPhaseListener(ConsumerSupport<Solution_, ProblemId_> consumerSupport) { + this.consumerSupport = consumerSupport; + } + + @Override + public void phaseEnded(AbstractPhaseScope<Solution_> phaseScope) { + if (phaseScope.isInitializationPhase()) {
This seems to proliferate both to the phase, and to the phase scope. Is there any chance how we can only keep it on one of the two? It feels to me like this change touches more places than it needs to; if the information is available on the phase, or if it is available on the scope, why would it also need to be available on the other?
timefold-solver
github_2023
java
915
TimefoldAI
triceo
@@ -42,6 +44,27 @@ void consumeIntermediateBestSolution(Solution_ bestSolution, BooleanSupplier isE } } + // Called on the Solver thread. + void consumeInitializedSolution(Solution_ initializedSolution) { + if (initializedSolutionConsumer != null) { + // TODO - Do we need to sync it?
Why would we need to?
timefold-solver
github_2023
java
915
TimefoldAI
triceo
@@ -42,6 +44,27 @@ void consumeIntermediateBestSolution(Solution_ bestSolution, BooleanSupplier isE } } + // Called on the Solver thread. + void consumeInitializedSolution(Solution_ initializedSolution) { + if (initializedSolutionConsumer != null) { + // TODO - Do we need to sync it? + try { + // Wait for the previous consumption to complete. + activeConsumption.acquire(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted when waiting for the final best solution consumption."); + } + try { + initializedSolutionConsumer.accept(initializedSolution); + } catch (Throwable throwable) { + exceptionHandler.accept(problemId, throwable); + } finally { + activeConsumption.release(); + } + }
Isn't this a bit over-complicated? Why all the locking? We're calling a simple listener. (Unlike the best solution listener, this will only be called _once_, and therefore doesn't need to worry about triggering while another such event is already being consumed.) I'm not versed in this particular aspect of the code; perhaps @rsynek could explain?
timefold-solver
github_2023
java
915
TimefoldAI
triceo
@@ -77,6 +79,11 @@ public boolean isAssertShadowVariablesAreNotStaleAfterStep() { public abstract String getPhaseTypeString(); + @Override + public boolean isInitializationPhase() {
Arguably this needs a better name. What does it mean to be an "initialization phase"? I'd be more literal here. I'd call this "triggersFirstInitializedSolutionEvent()". Javadoc can then reference the definition of what that event is.
timefold-solver
github_2023
java
915
TimefoldAI
rsynek
@@ -42,12 +47,29 @@ void consumeIntermediateBestSolution(Solution_ bestSolution, BooleanSupplier isE } } + // Called on the Solver thread. + void consumeFirstInitializedSolution(Solution_ firstInitializedSolution) { + try { + // Called on the solver thread + // During the solving process, this lock is called once, and it won't block the Solver thread + firstSolutionConsumption.acquire(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted when waiting for the first initialized solution consumption."); + } + // called on the Consumer thread + this.firstInitializedSolution = firstInitializedSolution; + scheduleFirstInitializedSolutionConsumption(); + } + // Called on the Solver thread after Solver#solve() returns. void consumeFinalBestSolution(Solution_ finalBestSolution) { try { // Wait for the previous consumption to complete. // As the solver has already finished, holding the solver thread is not an issue. activeConsumption.acquire(); + // Wait for the first solution consumption to complete + firstSolutionConsumption.acquire();
Can the following (in theory) happen? 1. here, we acquire the `firstSolutionConsumption` lock 2. now if the init event comes, it waits on https://github.com/TimefoldAI/timefold-solver/pull/915/files#diff-07ca1817df09fb6ca99e48c7070b6e09d9992a9d31e7b02bd821bf62ecf52dedR55 3. the consumer finishes the final best solution and disposes the consumer thread 4. ` scheduleFirstInitializedSolutionConsumption` then fails due to the executor not accepting further tasks. The important question is whether the final BSE can come before the init event and intuitively, I would say no.
timefold-solver
github_2023
java
915
TimefoldAI
triceo
@@ -263,6 +264,173 @@ void solveGenerics() throws ExecutionException, InterruptedException { solverJob.getFinalBestSolution(); } + @Test + @Timeout(60) + void solveWithFirstInitializedSolutionConsumer() throws ExecutionException, InterruptedException {
This test is actually several independent tests in one; only CH, CH-LS, etc. Let's split them.
timefold-solver
github_2023
java
898
TimefoldAI
zepfred
@@ -184,28 +180,29 @@ public void removePhaseLifecycleListener(PhaseLifecycleListener<Solution_> phase protected void assertWorkingSolutionInitialized(AbstractPhaseScope<Solution_> phaseScope) { if (!phaseScope.getStartingScore().isSolutionInitialized()) { - InnerScoreDirector<Solution_, ?> scoreDirector = phaseScope.getScoreDirector(); - SolutionDescriptor<Solution_> solutionDescriptor = scoreDirector.getSolutionDescriptor(); - Solution_ workingSolution = scoreDirector.getWorkingSolution(); - solutionDescriptor.visitAllEntities(workingSolution, entity -> { - EntityDescriptor<Solution_> entityDescriptor = solutionDescriptor.findEntityDescriptorOrFail( - entity.getClass()); - if (!entityDescriptor.isEntityInitializedOrPinned(scoreDirector, entity)) { - String variableRef = null; - for (GenuineVariableDescriptor<Solution_> variableDescriptor : entityDescriptor - .getGenuineVariableDescriptorList()) { - if (!variableDescriptor.isInitialized(entity)) { - variableRef = variableDescriptor.getSimpleEntityAndVariableName(); - break; - } - } - throw new IllegalStateException(getPhaseTypeString() + " phase (" + phaseIndex - + ") needs to start from an initialized solution, but the planning variable (" + variableRef - + ") is uninitialized for the entity (" + entity + ").\n" - + "Maybe there is no Construction Heuristic configured before this phase to initialize the solution.\n" - + "Or maybe the getter/setters of your planning variables in your domain classes aren't implemented correctly."); - } - }); + var scoreDirector = phaseScope.getScoreDirector();
The logic looks good, but we should include a test case that covers this behavior.
timefold-solver
github_2023
others
894
TimefoldAI
Christopher-Chianelli
@@ -709,8 +726,8 @@ def print_timetable(time_table: Timetable) -> None: for lesson in lessons if lesson.room is not None and lesson.timeslot is not None } - row_format ="|{:<15}" * (len(rooms) + 1) + "|" - sep_format = "+" + ((("-" * 15) + "+") * (len(rooms) + 1)) + row_format = ("|{:<" + str(column_width) + "}") * (len(rooms) + 1) + "|" + sep_format = "+" + ((("-" * column_width) + "+") * (len(rooms) + 1))
Missing the Enum below print_table
timefold-solver
github_2023
others
890
TimefoldAI
rsynek
@@ -558,16 +546,11 @@ There are additional parameters you can supply to your `solverConfig.xml`: <solver xmlns="https://timefold.ai/xsd/solver" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://timefold.ai/xsd/solver https://timefold.ai/xsd/solver/solver.xsd"> <moveThreadCount>4</moveThreadCount> - <moveThreadBufferSize>10</moveThreadBufferSize>
Yep, this parameter has been always "a bit too much". Can we remove/deprecate it?
timefold-solver
github_2023
java
875
TimefoldAI
zepfred
@@ -1010,4 +1011,36 @@ void terminateScheduledSolverJobEarly_returnsInputProblem() throws ExecutionExce assertThat(result).isSameAs(inputProblem); assertThat(solverJob.isTerminatedEarly()).isTrue(); } + + public static class CustomThreadFactory implements ThreadFactory { + private static final String CUSTOM_THREAD_NAME = "CustomThread"; + + @Override + public Thread newThread(Runnable runnable) { + return new Thread(runnable, CUSTOM_THREAD_NAME); + } + } + + @Test + @Timeout(60) + void threadFactoryIsUsed() throws ExecutionException, InterruptedException {
Nice!
timefold-solver
github_2023
others
867
TimefoldAI
zepfred
@@ -218,6 +218,17 @@ test { } ---- -- +
The `Prerequisites` section does not include Python.