repo_name stringlengths 1 62 | dataset stringclasses 1 value | lang stringclasses 11 values | pr_id int64 1 20.1k | owner stringlengths 2 34 | reviewer stringlengths 2 39 | diff_hunk stringlengths 15 262k | code_review_comment stringlengths 1 99.6k |
|---|---|---|---|---|---|---|---|
timefold-solver | github_2023 | java | 564 | TimefoldAI | triceo | @@ -0,0 +1,69 @@
+package ai.timefold.solver.quarkus.rest;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import ai.timefold.solver.quarkus.testdata.normal.constraints.TestdataQuarkusConstraintProvider;
+import ai.timefold.solver.quarkus.testdata.normal.domain.TestdataQuarkusEntity;
+import ai.timefold.solver.quarkus.testdata.normal.domain.TestdataQuarkusSolution;
+import ai.timefold.solver.quarkus.testdata.shadowvariable.constraints.TestdataQuarkusShadowVariableConstraintProvider;
+import ai.timefold.solver.quarkus.testdata.shadowvariable.domain.TestdataQuarkusShadowVariableEntity;
+import ai.timefold.solver.quarkus.testdata.shadowvariable.domain.TestdataQuarkusShadowVariableListener;
+import ai.timefold.solver.quarkus.testdata.shadowvariable.domain.TestdataQuarkusShadowVariableSolution;
+
+import org.jboss.shrinkwrap.api.ShrinkWrap;
+import org.jboss.shrinkwrap.api.spec.JavaArchive;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+
+import io.quarkus.test.QuarkusDevModeTest;
+import io.restassured.RestAssured;
+
+/**
+ * Do not remove the public modifier from this class. Otherwise, the test will fail with the following:
+ * <p>
+ * Caused by: java.lang.IllegalAccessException: class io.quarkus.test.QuarkusDevModeTest cannot access a member of class
+ * ai.timefold.solver.quarkus.rest.TimefoldProcessorHotReloadMultipleSolversTest with modifiers ""
+ * at java.base/java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:674)
+ * at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:489)
+ * at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
+ * at io.quarkus.test.QuarkusDevModeTest.createTestInstance(QuarkusDevModeTest.java:222)
+ */ | No need to be so verbose. Enough to say that removing public will cause an exception. If someone decides to try even though they've been warned, they'll find out what exception it is. :-) |
timefold-solver | github_2023 | java | 564 | TimefoldAI | triceo | @@ -1,21 +1,32 @@
package ai.timefold.solver.quarkus.rest;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
import ai.timefold.solver.quarkus.testdata.normal.constraints.TestdataQuarkusConstraintProvider;
import ai.timefold.solver.quarkus.testdata.normal.domain.TestdataQuarkusEntity;
import ai.timefold.solver.quarkus.testdata.normal.domain.TestdataQuarkusSolution;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
-import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import io.quarkus.test.QuarkusDevModeTest;
import io.restassured.RestAssured;
+/**
+ * Do not remove the public modifier from this class. Otherwise, the test will fail with the following: | Dtto. I'm even considering if we need to warn about this at all; we typically don't. |
timefold-solver | github_2023 | java | 564 | TimefoldAI | triceo | @@ -0,0 +1,111 @@
+package ai.timefold.solver.quarkus.it.devui;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.List;
+
+import jakarta.inject.Inject;
+import jakarta.inject.Named;
+import jakarta.ws.rs.Path;
+
+import ai.timefold.solver.core.api.solver.SolverManager;
+import ai.timefold.solver.quarkus.it.devui.domain.StringLengthVariableListener;
+import ai.timefold.solver.quarkus.it.devui.domain.TestdataStringLengthShadowEntity;
+import ai.timefold.solver.quarkus.it.devui.domain.TestdataStringLengthShadowSolution;
+import ai.timefold.solver.quarkus.it.devui.solver.TestdataStringLengthConstraintProvider;
+
+import org.apache.commons.lang3.tuple.Pair;
+import org.jboss.shrinkwrap.api.ShrinkWrap;
+import org.jboss.shrinkwrap.api.spec.JavaArchive;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.TextNode;
+
+import io.quarkus.devui.tests.DevUIJsonRPCTest;
+import io.quarkus.test.QuarkusDevModeTest;
+
+public class TimefoldDevUIMultipleSolversTest extends DevUIJsonRPCTest {
+
+ @RegisterExtension
+ static final QuarkusDevModeTest config = new QuarkusDevModeTest()
+ .setBuildSystemProperty("quarkus.timefold.solver.\"solver1\".environment-mode", "FULL_ASSERT")
+ .setBuildSystemProperty("quarkus.timefold.solver.\"solver2\".environment-mode", "REPRODUCIBLE")
+ .setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class)
+ .addClasses(StringLengthVariableListener.class,
+ TestdataStringLengthShadowEntity.class, TestdataStringLengthShadowSolution.class,
+ TestdataStringLengthConstraintProvider.class, TimefoldTestMultipleResource.class));
+
+ @Path("/timefold/test")
+ public static class TimefoldTestMultipleResource {
+
+ @Inject
+ @Named("solver1")
+ SolverManager<TestdataStringLengthShadowSolution, Long> solverManager;
+
+ @Inject
+ @Named("solver2")
+ SolverManager<TestdataStringLengthShadowSolution, Long> solverManager2;
+ }
+
+ public TimefoldDevUIMultipleSolversTest() {
+ super("Timefold Solver");
+ }
+
+ @Test
+ void testSolverConfigPage() throws Exception {
+ JsonNode configResponse = super.executeJsonRPCMethod("getConfig");
+ List.of(Pair.of("solver1", "FULL_ASSERT"), Pair.of("solver2", "REPRODUCIBLE")).forEach(key -> {
+ String solverConfig = configResponse.get("config").get(key.getLeft()).asText();
+ assertThat(solverConfig).isEqualToIgnoringWhitespace(
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ + "<!--Properties that can be set at runtime are not included-->\n"
+ + "<solver>\n"
+ + " <environmentMode>" + key.getRight() + "</environmentMode>\n"
+ + " <solutionClass>" + TestdataStringLengthShadowSolution.class.getCanonicalName()
+ + "</solutionClass>\n"
+ + " <entityClass>" + TestdataStringLengthShadowEntity.class.getCanonicalName() + "</entityClass>\n"
+ + " <domainAccessType>GIZMO</domainAccessType>\n"
+ + " <scoreDirectorFactory>\n"
+ + " <constraintProviderClass>" + TestdataStringLengthConstraintProvider.class.getCanonicalName()
+ + "</constraintProviderClass>\n"
+ + " </scoreDirectorFactory>\n"
+ + " <termination/>\n"
+ + "</solver>");
+ });
+ }
+
+ @Test
+ void testModelPage() throws Exception {
+ JsonNode modelResponse = super.executeJsonRPCMethod("getModelInfo");
+ List.of("solver1", "solver2").forEach(key -> { | For sake of simplicity, I'd refactor this to avoid the lambda.
Make the assertions be inside a method, have the string as an argument to the method, call the method twice.
The stack trace in case of a failure will be nicer, and more self-explanatory. |
timefold-solver | github_2023 | java | 564 | TimefoldAI | triceo | @@ -0,0 +1,111 @@
+package ai.timefold.solver.quarkus.it.devui;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.List;
+
+import jakarta.inject.Inject;
+import jakarta.inject.Named;
+import jakarta.ws.rs.Path;
+
+import ai.timefold.solver.core.api.solver.SolverManager;
+import ai.timefold.solver.quarkus.it.devui.domain.StringLengthVariableListener;
+import ai.timefold.solver.quarkus.it.devui.domain.TestdataStringLengthShadowEntity;
+import ai.timefold.solver.quarkus.it.devui.domain.TestdataStringLengthShadowSolution;
+import ai.timefold.solver.quarkus.it.devui.solver.TestdataStringLengthConstraintProvider;
+
+import org.apache.commons.lang3.tuple.Pair;
+import org.jboss.shrinkwrap.api.ShrinkWrap;
+import org.jboss.shrinkwrap.api.spec.JavaArchive;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.TextNode;
+
+import io.quarkus.devui.tests.DevUIJsonRPCTest;
+import io.quarkus.test.QuarkusDevModeTest;
+
+public class TimefoldDevUIMultipleSolversTest extends DevUIJsonRPCTest {
+
+ @RegisterExtension
+ static final QuarkusDevModeTest config = new QuarkusDevModeTest()
+ .setBuildSystemProperty("quarkus.timefold.solver.\"solver1\".environment-mode", "FULL_ASSERT")
+ .setBuildSystemProperty("quarkus.timefold.solver.\"solver2\".environment-mode", "REPRODUCIBLE")
+ .setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class)
+ .addClasses(StringLengthVariableListener.class,
+ TestdataStringLengthShadowEntity.class, TestdataStringLengthShadowSolution.class,
+ TestdataStringLengthConstraintProvider.class, TimefoldTestMultipleResource.class));
+
+ @Path("/timefold/test")
+ public static class TimefoldTestMultipleResource {
+
+ @Inject
+ @Named("solver1")
+ SolverManager<TestdataStringLengthShadowSolution, Long> solverManager;
+
+ @Inject
+ @Named("solver2")
+ SolverManager<TestdataStringLengthShadowSolution, Long> solverManager2;
+ }
+
+ public TimefoldDevUIMultipleSolversTest() {
+ super("Timefold Solver");
+ }
+
+ @Test
+ void testSolverConfigPage() throws Exception {
+ JsonNode configResponse = super.executeJsonRPCMethod("getConfig");
+ List.of(Pair.of("solver1", "FULL_ASSERT"), Pair.of("solver2", "REPRODUCIBLE")).forEach(key -> {
+ String solverConfig = configResponse.get("config").get(key.getLeft()).asText();
+ assertThat(solverConfig).isEqualToIgnoringWhitespace(
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ + "<!--Properties that can be set at runtime are not included-->\n"
+ + "<solver>\n"
+ + " <environmentMode>" + key.getRight() + "</environmentMode>\n"
+ + " <solutionClass>" + TestdataStringLengthShadowSolution.class.getCanonicalName()
+ + "</solutionClass>\n"
+ + " <entityClass>" + TestdataStringLengthShadowEntity.class.getCanonicalName() + "</entityClass>\n"
+ + " <domainAccessType>GIZMO</domainAccessType>\n"
+ + " <scoreDirectorFactory>\n"
+ + " <constraintProviderClass>" + TestdataStringLengthConstraintProvider.class.getCanonicalName()
+ + "</constraintProviderClass>\n"
+ + " </scoreDirectorFactory>\n"
+ + " <termination/>\n"
+ + "</solver>");
+ });
+ }
+
+ @Test
+ void testModelPage() throws Exception {
+ JsonNode modelResponse = super.executeJsonRPCMethod("getModelInfo");
+ List.of("solver1", "solver2").forEach(key -> {
+ assertThat(modelResponse.get(key).get("solutionClass").asText())
+ .contains(TestdataStringLengthShadowSolution.class.getCanonicalName());
+ assertThat(modelResponse.get(key).get("entityClassList"))
+ .containsExactly(
+ new TextNode(TestdataStringLengthShadowEntity.class.getCanonicalName()));
+ assertThat(modelResponse.get(key).get("entityClassToGenuineVariableListMap")).hasSize(1);
+ assertThat(modelResponse.get(key).get("entityClassToGenuineVariableListMap")
+ .get(TestdataStringLengthShadowEntity.class.getCanonicalName()))
+ .containsExactly(new TextNode("value"));
+ assertThat(modelResponse.get(key).get("entityClassToShadowVariableListMap")).hasSize(1);
+ assertThat(modelResponse.get(key).get("entityClassToShadowVariableListMap")
+ .get(TestdataStringLengthShadowEntity.class.getCanonicalName()))
+ .containsExactly(new TextNode("length"));
+ });
+ }
+
+ @Test
+ void testConstraintsPage() throws Exception {
+ JsonNode constraintsResponse = super.executeJsonRPCMethod("getConstraints");
+ List.of("solver1", "solver2").forEach(key -> { | Dtto. |
timefold-solver | github_2023 | java | 564 | TimefoldAI | triceo | @@ -27,11 +28,11 @@ public class TimefoldProcessorHotReloadTest {
@Test
void solverConfigHotReload() { | This test (and its `MultipleSolvers` counterpart) seems to throw a lot of exceptions into the sysout, even though it is passing. Let's fix that. |
timefold-solver | github_2023 | java | 564 | TimefoldAI | triceo | @@ -229,18 +230,27 @@ SolverConfigBuildItem recordAndRegisterBuildTimeBeans(CombinedIndexBuildItem com
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Map<String, SolverConfig> allSolverConfig = new HashMap<>(); | According to the convention, this would be a `solverConfigMap`. |
timefold-solver | github_2023 | java | 564 | TimefoldAI | triceo | @@ -268,9 +278,79 @@ SolverConfigBuildItem recordAndRegisterBuildTimeBeans(CombinedIndexBuildItem com
return new SolverConfigBuildItem(allSolverConfig, generatedGizmoClasses);
}
- private SolverConfig generateSolverConfig(ClassLoader classLoader, IndexView indexView,
- BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchyClass, String solverName,
- Set<Class<?>> reflectiveClassSet) {
+ private void assertSolverConfigSolutionClasses(IndexView indexView, Map<String, SolverConfig> allSolverConfig) {
+ // Validate the solution class
+ Collection<AnnotationInstance> annotationInstances = indexView.getAnnotations(DotNames.PLANNING_SOLUTION);
+ // No solution class
+ if (annotationInstances.isEmpty()) {
+ throw new IllegalStateException(
+ "No classes found with a @%s annotation.".formatted(PlanningSolution.class.getSimpleName()));
+ }
+ // Multiple classes and single solver
+ if (annotationInstances.size() > 1 && allSolverConfig.size() == 1) {
+ throw new IllegalStateException("Multiple classes (%s) found with a @%s annotation.".formatted(
+ convertAnnotationInstancesToString(annotationInstances), PlanningSolution.class.getSimpleName()));
+ }
+ // Multiple classes and at least one solver config does not specify the solution class
+ List<String> emptySolutionClasses = allSolverConfig.entrySet().stream() | `solverConfigWithoutSolutionClassList` |
timefold-solver | github_2023 | java | 564 | TimefoldAI | triceo | @@ -268,9 +278,79 @@ SolverConfigBuildItem recordAndRegisterBuildTimeBeans(CombinedIndexBuildItem com
return new SolverConfigBuildItem(allSolverConfig, generatedGizmoClasses);
}
- private SolverConfig generateSolverConfig(ClassLoader classLoader, IndexView indexView,
- BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchyClass, String solverName,
- Set<Class<?>> reflectiveClassSet) {
+ private void assertSolverConfigSolutionClasses(IndexView indexView, Map<String, SolverConfig> allSolverConfig) {
+ // Validate the solution class
+ Collection<AnnotationInstance> annotationInstances = indexView.getAnnotations(DotNames.PLANNING_SOLUTION);
+ // No solution class
+ if (annotationInstances.isEmpty()) {
+ throw new IllegalStateException(
+ "No classes found with a @%s annotation.".formatted(PlanningSolution.class.getSimpleName()));
+ }
+ // Multiple classes and single solver
+ if (annotationInstances.size() > 1 && allSolverConfig.size() == 1) {
+ throw new IllegalStateException("Multiple classes (%s) found with a @%s annotation.".formatted(
+ convertAnnotationInstancesToString(annotationInstances), PlanningSolution.class.getSimpleName()));
+ }
+ // Multiple classes and at least one solver config does not specify the solution class
+ List<String> emptySolutionClasses = allSolverConfig.entrySet().stream()
+ .filter(e -> e.getValue().getSolutionClass() == null)
+ .map(Map.Entry::getKey)
+ .toList();
+ if (annotationInstances.size() > 1 && !emptySolutionClasses.isEmpty()) {
+ throw new IllegalStateException(
+ """
+ Multiple classes (%s) found with a @%s annotation and some solver configs ([%s]) does not specify it.
+ Maybe set the XML config file to the related solver configs, or add the missing solution classes to the XML files,
+ or remove the unnecessary solution classes from the classpath.
+ """
+ .formatted(convertAnnotationInstancesToString(annotationInstances),
+ PlanningSolution.class.getSimpleName(),
+ String.join(", ", emptySolutionClasses)));
+ }
+ // Unused solution classes
+ List<String> unusedSolutionClasses = annotationInstances.stream() | `solverConfigWithUnusedSolutionClassList` |
timefold-solver | github_2023 | java | 564 | TimefoldAI | triceo | @@ -268,9 +278,79 @@ SolverConfigBuildItem recordAndRegisterBuildTimeBeans(CombinedIndexBuildItem com
return new SolverConfigBuildItem(allSolverConfig, generatedGizmoClasses);
}
- private SolverConfig generateSolverConfig(ClassLoader classLoader, IndexView indexView,
- BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchyClass, String solverName,
- Set<Class<?>> reflectiveClassSet) {
+ private void assertSolverConfigSolutionClasses(IndexView indexView, Map<String, SolverConfig> allSolverConfig) {
+ // Validate the solution class
+ Collection<AnnotationInstance> annotationInstances = indexView.getAnnotations(DotNames.PLANNING_SOLUTION);
+ // No solution class
+ if (annotationInstances.isEmpty()) {
+ throw new IllegalStateException(
+ "No classes found with a @%s annotation.".formatted(PlanningSolution.class.getSimpleName()));
+ }
+ // Multiple classes and single solver
+ if (annotationInstances.size() > 1 && allSolverConfig.size() == 1) {
+ throw new IllegalStateException("Multiple classes (%s) found with a @%s annotation.".formatted(
+ convertAnnotationInstancesToString(annotationInstances), PlanningSolution.class.getSimpleName()));
+ }
+ // Multiple classes and at least one solver config does not specify the solution class
+ List<String> emptySolutionClasses = allSolverConfig.entrySet().stream()
+ .filter(e -> e.getValue().getSolutionClass() == null)
+ .map(Map.Entry::getKey)
+ .toList();
+ if (annotationInstances.size() > 1 && !emptySolutionClasses.isEmpty()) {
+ throw new IllegalStateException(
+ """
+ Multiple classes (%s) found with a @%s annotation and some solver configs ([%s]) does not specify it.
+ Maybe set the XML config file to the related solver configs, or add the missing solution classes to the XML files,
+ or remove the unnecessary solution classes from the classpath.
+ """
+ .formatted(convertAnnotationInstancesToString(annotationInstances),
+ PlanningSolution.class.getSimpleName(),
+ String.join(", ", emptySolutionClasses)));
+ }
+ // Unused solution classes
+ List<String> unusedSolutionClasses = annotationInstances.stream()
+ .map(planningClass -> planningClass.target().asClass().name().toString())
+ .filter(planningClassName -> allSolverConfig.values().stream()
+ .noneMatch(c -> c.getSolutionClass().getName().equals(planningClassName)))
+ .toList();
+ if (!unusedSolutionClasses.isEmpty()) {
+ throw new IllegalStateException(
+ "Unused classes ([%s]) found with a @%s annotation.".formatted(String.join(", ", unusedSolutionClasses),
+ PlanningSolution.class.getSimpleName()));
+ }
+ // Validate the solution classes target types
+ List<String> invalidTargetClasses = annotationInstances.stream()
+ .filter(planningClass -> allSolverConfig.values().stream()
+ .anyMatch(
+ c -> c.getSolutionClass().getName().equals(planningClass.target().asClass().name().toString())))
+ .map(AnnotationInstance::target)
+ .filter(t -> t.kind() != AnnotationTarget.Kind.CLASS)
+ .map(t -> t.asClass().name().toString())
+ .toList();
+ if (!invalidTargetClasses.isEmpty()) {
+ throw new IllegalStateException("The targets classes ([%s]) with a @%s must be a class."
+ .formatted(String.join(", ", invalidTargetClasses), PlanningSolution.class.getSimpleName()));
+ } | What is a target? Nothing in the solver is called a target. The exception should not mention a "target" because the user does not know what that is. |
timefold-solver | github_2023 | java | 564 | TimefoldAI | triceo | @@ -268,9 +278,79 @@ SolverConfigBuildItem recordAndRegisterBuildTimeBeans(CombinedIndexBuildItem com
return new SolverConfigBuildItem(allSolverConfig, generatedGizmoClasses);
}
- private SolverConfig generateSolverConfig(ClassLoader classLoader, IndexView indexView,
- BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchyClass, String solverName,
- Set<Class<?>> reflectiveClassSet) {
+ private void assertSolverConfigSolutionClasses(IndexView indexView, Map<String, SolverConfig> allSolverConfig) {
+ // Validate the solution class
+ Collection<AnnotationInstance> annotationInstances = indexView.getAnnotations(DotNames.PLANNING_SOLUTION);
+ // No solution class
+ if (annotationInstances.isEmpty()) {
+ throw new IllegalStateException(
+ "No classes found with a @%s annotation.".formatted(PlanningSolution.class.getSimpleName()));
+ }
+ // Multiple classes and single solver
+ if (annotationInstances.size() > 1 && allSolverConfig.size() == 1) {
+ throw new IllegalStateException("Multiple classes (%s) found with a @%s annotation.".formatted(
+ convertAnnotationInstancesToString(annotationInstances), PlanningSolution.class.getSimpleName()));
+ }
+ // Multiple classes and at least one solver config does not specify the solution class
+ List<String> emptySolutionClasses = allSolverConfig.entrySet().stream()
+ .filter(e -> e.getValue().getSolutionClass() == null)
+ .map(Map.Entry::getKey)
+ .toList();
+ if (annotationInstances.size() > 1 && !emptySolutionClasses.isEmpty()) {
+ throw new IllegalStateException(
+ """
+ Multiple classes (%s) found with a @%s annotation and some solver configs ([%s]) does not specify it. | I'd rephrase the first sentence. "Some solver configs (...) don't specify a @PlanningSolution class, yet there are multiple available (...) on the classpath." |
timefold-solver | github_2023 | java | 564 | TimefoldAI | triceo | @@ -268,9 +278,79 @@ SolverConfigBuildItem recordAndRegisterBuildTimeBeans(CombinedIndexBuildItem com
return new SolverConfigBuildItem(allSolverConfig, generatedGizmoClasses);
}
- private SolverConfig generateSolverConfig(ClassLoader classLoader, IndexView indexView,
- BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchyClass, String solverName,
- Set<Class<?>> reflectiveClassSet) {
+ private void assertSolverConfigSolutionClasses(IndexView indexView, Map<String, SolverConfig> allSolverConfig) {
+ // Validate the solution class
+ Collection<AnnotationInstance> annotationInstances = indexView.getAnnotations(DotNames.PLANNING_SOLUTION);
+ // No solution class
+ if (annotationInstances.isEmpty()) {
+ throw new IllegalStateException(
+ "No classes found with a @%s annotation.".formatted(PlanningSolution.class.getSimpleName()));
+ }
+ // Multiple classes and single solver
+ if (annotationInstances.size() > 1 && allSolverConfig.size() == 1) {
+ throw new IllegalStateException("Multiple classes (%s) found with a @%s annotation.".formatted(
+ convertAnnotationInstancesToString(annotationInstances), PlanningSolution.class.getSimpleName()));
+ }
+ // Multiple classes and at least one solver config does not specify the solution class
+ List<String> emptySolutionClasses = allSolverConfig.entrySet().stream()
+ .filter(e -> e.getValue().getSolutionClass() == null)
+ .map(Map.Entry::getKey)
+ .toList();
+ if (annotationInstances.size() > 1 && !emptySolutionClasses.isEmpty()) {
+ throw new IllegalStateException(
+ """
+ Multiple classes (%s) found with a @%s annotation and some solver configs ([%s]) does not specify it.
+ Maybe set the XML config file to the related solver configs, or add the missing solution classes to the XML files,
+ or remove the unnecessary solution classes from the classpath.
+ """
+ .formatted(convertAnnotationInstancesToString(annotationInstances),
+ PlanningSolution.class.getSimpleName(),
+ String.join(", ", emptySolutionClasses)));
+ }
+ // Unused solution classes
+ List<String> unusedSolutionClasses = annotationInstances.stream()
+ .map(planningClass -> planningClass.target().asClass().name().toString())
+ .filter(planningClassName -> allSolverConfig.values().stream()
+ .noneMatch(c -> c.getSolutionClass().getName().equals(planningClassName)))
+ .toList();
+ if (!unusedSolutionClasses.isEmpty()) {
+ throw new IllegalStateException(
+ "Unused classes ([%s]) found with a @%s annotation.".formatted(String.join(", ", unusedSolutionClasses),
+ PlanningSolution.class.getSimpleName()));
+ }
+ // Validate the solution classes target types
+ List<String> invalidTargetClasses = annotationInstances.stream()
+ .filter(planningClass -> allSolverConfig.values().stream()
+ .anyMatch(
+ c -> c.getSolutionClass().getName().equals(planningClass.target().asClass().name().toString())))
+ .map(AnnotationInstance::target)
+ .filter(t -> t.kind() != AnnotationTarget.Kind.CLASS)
+ .map(t -> t.asClass().name().toString())
+ .toList();
+ if (!invalidTargetClasses.isEmpty()) {
+ throw new IllegalStateException("The targets classes ([%s]) with a @%s must be a class."
+ .formatted(String.join(", ", invalidTargetClasses), PlanningSolution.class.getSimpleName()));
+ }
+ }
+
+ private void assertSolverConfigEntityClasses(IndexView indexView) {
+ Collection<AnnotationInstance> annotationInstances = indexView.getAnnotations(DotNames.PLANNING_ENTITY);
+ if (annotationInstances.isEmpty()) {
+ throw new IllegalStateException(
+ "No classes found with a @%s annotation.".formatted(PlanningEntity.class.getSimpleName()));
+ }
+ List<AnnotationTarget> targetList = annotationInstances.stream()
+ .map(AnnotationInstance::target)
+ .toList();
+ if (targetList.stream().anyMatch(target -> target.kind() != AnnotationTarget.Kind.CLASS)) { | Targets again. |
timefold-solver | github_2023 | java | 564 | TimefoldAI | triceo | @@ -121,10 +127,17 @@ private static void registerSpi(Class<?> serviceClass, BuildProducer<ServiceProv
}
@BuildStep
- HotDeploymentWatchedFileBuildItem watchSolverConfigXml() {
- String solverConfigXML = timefoldBuildTimeConfig.solverConfigXml
+ void watchSolverConfigXml(BuildProducer<HotDeploymentWatchedFileBuildItem> hotDeploymentWatchedFiles) {
+ String solverConfigXML = timefoldBuildTimeConfig.solverConfigXml()
.orElse(TimefoldBuildTimeConfig.DEFAULT_SOLVER_CONFIG_URL);
- return new HotDeploymentWatchedFileBuildItem(solverConfigXML);
+ Set<String> solverConfigXMLFiles = new HashSet<>(); | Please be consistent; `solverCongigXmlFileSet`. |
timefold-solver | github_2023 | java | 564 | TimefoldAI | triceo | @@ -225,29 +218,330 @@ SolverConfigBuildItem recordAndRegisterBeans(TimefoldRecorder recorder, Recorder
+ "application.properties entries (quarkus.index-dependency.<name>.group-id"
+ " and quarkus.index-dependency.<name>.artifact-id).");
additionalBeans.produce(new AdditionalBeanBuildItem(UnavailableTimefoldBeanProvider.class));
- return new SolverConfigBuildItem(null);
+ Map<String, SolverConfig> solverConfig = new HashMap<>(); | `solverConfigMap` |
timefold-solver | github_2023 | java | 564 | TimefoldAI | triceo | @@ -225,29 +218,330 @@ SolverConfigBuildItem recordAndRegisterBeans(TimefoldRecorder recorder, Recorder
+ "application.properties entries (quarkus.index-dependency.<name>.group-id"
+ " and quarkus.index-dependency.<name>.artifact-id).");
additionalBeans.produce(new AdditionalBeanBuildItem(UnavailableTimefoldBeanProvider.class));
- return new SolverConfigBuildItem(null);
+ Map<String, SolverConfig> solverConfig = new HashMap<>();
+ this.timefoldBuildTimeConfig.solver().keySet().forEach(solverName -> solverConfig.put(solverName, null));
+ return new SolverConfigBuildItem(solverConfig, null);
}
// Quarkus extensions must always use getContextClassLoader()
// Internally, Timefold defaults the ClassLoader to getContextClassLoader() too
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
+
+ Map<String, SolverConfig> solverConfigMap = new HashMap<>();
+ // Step 1 - create all SolverConfig
+ // If the config map is empty, we build the config using the default solver name
+ if (timefoldBuildTimeConfig.solver().isEmpty()) {
+ solverConfigMap.put(TimefoldBuildTimeConfig.DEFAULT_SOLVER_NAME,
+ createSolverConfig(classLoader, TimefoldBuildTimeConfig.DEFAULT_SOLVER_NAME));
+ } else {
+ // One config per solver mapped name
+ this.timefoldBuildTimeConfig.solver().keySet().forEach(solverName -> solverConfigMap.put(solverName,
+ createSolverConfig(classLoader, solverName)));
+ }
+
+ // Step 2 - validate all SolverConfig definitions
+ assertNoMemberAnnotationWithoutClassAnnotation(indexView);
+ assertSolverConfigSolutionClasses(indexView, solverConfigMap);
+ assertSolverConfigEntityClasses(indexView);
+ assertSolverConfigConstraintClasses(indexView, solverConfigMap);
+
+ // Step 3 - load all additional information per SolverConfig
+ Set<Class<?>> reflectiveClassSet = new LinkedHashSet<>();
+ solverConfigMap.forEach((solverName, solverConfig) -> loadSolverConfig(indexView, reflectiveHierarchyClass,
+ solverConfig, solverName, reflectiveClassSet));
+
+ // Register all annotated domain model classes
+ registerClassesFromAnnotations(indexView, reflectiveClassSet);
+
+ // Register only distinct constraint providers
+ solverConfigMap.values()
+ .stream()
+ .filter(config -> config.getScoreDirectorFactoryConfig().getConstraintProviderClass() != null)
+ .map(config -> config.getScoreDirectorFactoryConfig().getConstraintProviderClass().getName())
+ .distinct()
+ .map(constraintName -> solverConfigMap.entrySet().stream().filter(entryConfig -> entryConfig.getValue()
+ .getScoreDirectorFactoryConfig().getConstraintProviderClass().getName().equals(constraintName))
+ .findFirst().get())
+ .forEach(
+ entryConfig -> generateConstraintVerifier(entryConfig.getValue(), syntheticBeanBuildItemBuildProducer));
+
+ GeneratedGizmoClasses generatedGizmoClasses = generateDomainAccessors(solverConfigMap, indexView, generatedBeans,
+ generatedClasses, transformers, reflectiveClassSet);
+
+ additionalBeans.produce(new AdditionalBeanBuildItem(TimefoldSolverBannerBean.class));
+ if (solverConfigMap.size() <= 1) {
+ // Only registered for the default solver
+ additionalBeans.produce(new AdditionalBeanBuildItem(DefaultTimefoldBeanProvider.class));
+ }
+ unremovableBeans.produce(UnremovableBeanBuildItem.beanTypes(TimefoldRuntimeConfig.class));
+ return new SolverConfigBuildItem(solverConfigMap, generatedGizmoClasses);
+ }
+
+ private void assertNoMemberAnnotationWithoutClassAnnotation(IndexView indexView) {
+ Collection<AnnotationInstance> timefoldFieldAnnotations = new HashSet<>();
+
+ for (DotName annotationName : DotNames.PLANNING_ENTITY_FIELD_ANNOTATIONS) {
+ timefoldFieldAnnotations.addAll(indexView.getAnnotationsWithRepeatable(annotationName, indexView));
+ }
+
+ for (AnnotationInstance annotationInstance : timefoldFieldAnnotations) {
+ AnnotationTarget annotationTarget = annotationInstance.target();
+ ClassInfo declaringClass;
+ String prefix;
+ switch (annotationTarget.kind()) {
+ case FIELD:
+ prefix = "The field (" + annotationTarget.asField().name() + ") ";
+ declaringClass = annotationTarget.asField().declaringClass();
+ break;
+ case METHOD:
+ prefix = "The method (" + annotationTarget.asMethod().name() + ") ";
+ declaringClass = annotationTarget.asMethod().declaringClass();
+ break;
+ default:
+ throw new IllegalStateException(
+ "Member annotation @" + annotationInstance.name().withoutPackagePrefix() + " is on ("
+ + annotationTarget +
+ "), which is an invalid target type (" + annotationTarget.kind() +
+ ") for @" + annotationInstance.name().withoutPackagePrefix() + "."); | Since we started using the raw strings with `%s` patterns, please apply it here as well - the new code needs to be consistent. Over time, the old pattern will be replaced entirely, as we touch more and more of the old code. |
timefold-solver | github_2023 | java | 564 | TimefoldAI | triceo | @@ -225,29 +218,330 @@ SolverConfigBuildItem recordAndRegisterBeans(TimefoldRecorder recorder, Recorder
+ "application.properties entries (quarkus.index-dependency.<name>.group-id"
+ " and quarkus.index-dependency.<name>.artifact-id).");
additionalBeans.produce(new AdditionalBeanBuildItem(UnavailableTimefoldBeanProvider.class));
- return new SolverConfigBuildItem(null);
+ Map<String, SolverConfig> solverConfig = new HashMap<>();
+ this.timefoldBuildTimeConfig.solver().keySet().forEach(solverName -> solverConfig.put(solverName, null));
+ return new SolverConfigBuildItem(solverConfig, null);
}
// Quarkus extensions must always use getContextClassLoader()
// Internally, Timefold defaults the ClassLoader to getContextClassLoader() too
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
+
+ Map<String, SolverConfig> solverConfigMap = new HashMap<>();
+ // Step 1 - create all SolverConfig
+ // If the config map is empty, we build the config using the default solver name
+ if (timefoldBuildTimeConfig.solver().isEmpty()) {
+ solverConfigMap.put(TimefoldBuildTimeConfig.DEFAULT_SOLVER_NAME,
+ createSolverConfig(classLoader, TimefoldBuildTimeConfig.DEFAULT_SOLVER_NAME));
+ } else {
+ // One config per solver mapped name
+ this.timefoldBuildTimeConfig.solver().keySet().forEach(solverName -> solverConfigMap.put(solverName,
+ createSolverConfig(classLoader, solverName)));
+ }
+
+ // Step 2 - validate all SolverConfig definitions
+ assertNoMemberAnnotationWithoutClassAnnotation(indexView);
+ assertSolverConfigSolutionClasses(indexView, solverConfigMap);
+ assertSolverConfigEntityClasses(indexView);
+ assertSolverConfigConstraintClasses(indexView, solverConfigMap);
+
+ // Step 3 - load all additional information per SolverConfig
+ Set<Class<?>> reflectiveClassSet = new LinkedHashSet<>();
+ solverConfigMap.forEach((solverName, solverConfig) -> loadSolverConfig(indexView, reflectiveHierarchyClass,
+ solverConfig, solverName, reflectiveClassSet));
+
+ // Register all annotated domain model classes
+ registerClassesFromAnnotations(indexView, reflectiveClassSet);
+
+ // Register only distinct constraint providers
+ solverConfigMap.values()
+ .stream()
+ .filter(config -> config.getScoreDirectorFactoryConfig().getConstraintProviderClass() != null)
+ .map(config -> config.getScoreDirectorFactoryConfig().getConstraintProviderClass().getName())
+ .distinct()
+ .map(constraintName -> solverConfigMap.entrySet().stream().filter(entryConfig -> entryConfig.getValue()
+ .getScoreDirectorFactoryConfig().getConstraintProviderClass().getName().equals(constraintName))
+ .findFirst().get())
+ .forEach(
+ entryConfig -> generateConstraintVerifier(entryConfig.getValue(), syntheticBeanBuildItemBuildProducer));
+
+ GeneratedGizmoClasses generatedGizmoClasses = generateDomainAccessors(solverConfigMap, indexView, generatedBeans,
+ generatedClasses, transformers, reflectiveClassSet);
+
+ additionalBeans.produce(new AdditionalBeanBuildItem(TimefoldSolverBannerBean.class));
+ if (solverConfigMap.size() <= 1) {
+ // Only registered for the default solver
+ additionalBeans.produce(new AdditionalBeanBuildItem(DefaultTimefoldBeanProvider.class));
+ }
+ unremovableBeans.produce(UnremovableBeanBuildItem.beanTypes(TimefoldRuntimeConfig.class));
+ return new SolverConfigBuildItem(solverConfigMap, generatedGizmoClasses);
+ }
+
+ private void assertNoMemberAnnotationWithoutClassAnnotation(IndexView indexView) {
+ Collection<AnnotationInstance> timefoldFieldAnnotations = new HashSet<>();
+
+ for (DotName annotationName : DotNames.PLANNING_ENTITY_FIELD_ANNOTATIONS) {
+ timefoldFieldAnnotations.addAll(indexView.getAnnotationsWithRepeatable(annotationName, indexView));
+ }
+
+ for (AnnotationInstance annotationInstance : timefoldFieldAnnotations) {
+ AnnotationTarget annotationTarget = annotationInstance.target();
+ ClassInfo declaringClass;
+ String prefix;
+ switch (annotationTarget.kind()) {
+ case FIELD:
+ prefix = "The field (" + annotationTarget.asField().name() + ") ";
+ declaringClass = annotationTarget.asField().declaringClass();
+ break;
+ case METHOD:
+ prefix = "The method (" + annotationTarget.asMethod().name() + ") ";
+ declaringClass = annotationTarget.asMethod().declaringClass();
+ break;
+ default:
+ throw new IllegalStateException(
+ "Member annotation @" + annotationInstance.name().withoutPackagePrefix() + " is on ("
+ + annotationTarget +
+ "), which is an invalid target type (" + annotationTarget.kind() +
+ ") for @" + annotationInstance.name().withoutPackagePrefix() + ".");
+ }
+
+ if (!declaringClass.annotationsMap().containsKey(DotNames.PLANNING_ENTITY)) {
+ throw new IllegalStateException(prefix + "with a @" +
+ annotationInstance.name().withoutPackagePrefix() +
+ " annotation is in a class (" + declaringClass.name()
+ + ") that does not have a @" + PlanningEntity.class.getSimpleName() +
+ " annotation.\n" +
+ "Maybe add a @" + PlanningEntity.class.getSimpleName() +
+ " annotation on the class (" + declaringClass.name() + ")."); | And here as well. |
timefold-solver | github_2023 | java | 564 | TimefoldAI | triceo | @@ -225,29 +218,330 @@ SolverConfigBuildItem recordAndRegisterBeans(TimefoldRecorder recorder, Recorder
+ "application.properties entries (quarkus.index-dependency.<name>.group-id"
+ " and quarkus.index-dependency.<name>.artifact-id).");
additionalBeans.produce(new AdditionalBeanBuildItem(UnavailableTimefoldBeanProvider.class));
- return new SolverConfigBuildItem(null);
+ Map<String, SolverConfig> solverConfig = new HashMap<>();
+ this.timefoldBuildTimeConfig.solver().keySet().forEach(solverName -> solverConfig.put(solverName, null));
+ return new SolverConfigBuildItem(solverConfig, null);
}
// Quarkus extensions must always use getContextClassLoader()
// Internally, Timefold defaults the ClassLoader to getContextClassLoader() too
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
+
+ Map<String, SolverConfig> solverConfigMap = new HashMap<>();
+ // Step 1 - create all SolverConfig
+ // If the config map is empty, we build the config using the default solver name
+ if (timefoldBuildTimeConfig.solver().isEmpty()) {
+ solverConfigMap.put(TimefoldBuildTimeConfig.DEFAULT_SOLVER_NAME,
+ createSolverConfig(classLoader, TimefoldBuildTimeConfig.DEFAULT_SOLVER_NAME));
+ } else {
+ // One config per solver mapped name
+ this.timefoldBuildTimeConfig.solver().keySet().forEach(solverName -> solverConfigMap.put(solverName,
+ createSolverConfig(classLoader, solverName)));
+ }
+
+ // Step 2 - validate all SolverConfig definitions
+ assertNoMemberAnnotationWithoutClassAnnotation(indexView);
+ assertSolverConfigSolutionClasses(indexView, solverConfigMap);
+ assertSolverConfigEntityClasses(indexView);
+ assertSolverConfigConstraintClasses(indexView, solverConfigMap);
+
+ // Step 3 - load all additional information per SolverConfig
+ Set<Class<?>> reflectiveClassSet = new LinkedHashSet<>();
+ solverConfigMap.forEach((solverName, solverConfig) -> loadSolverConfig(indexView, reflectiveHierarchyClass,
+ solverConfig, solverName, reflectiveClassSet));
+
+ // Register all annotated domain model classes
+ registerClassesFromAnnotations(indexView, reflectiveClassSet);
+
+ // Register only distinct constraint providers
+ solverConfigMap.values()
+ .stream()
+ .filter(config -> config.getScoreDirectorFactoryConfig().getConstraintProviderClass() != null)
+ .map(config -> config.getScoreDirectorFactoryConfig().getConstraintProviderClass().getName())
+ .distinct()
+ .map(constraintName -> solverConfigMap.entrySet().stream().filter(entryConfig -> entryConfig.getValue()
+ .getScoreDirectorFactoryConfig().getConstraintProviderClass().getName().equals(constraintName))
+ .findFirst().get())
+ .forEach(
+ entryConfig -> generateConstraintVerifier(entryConfig.getValue(), syntheticBeanBuildItemBuildProducer));
+
+ GeneratedGizmoClasses generatedGizmoClasses = generateDomainAccessors(solverConfigMap, indexView, generatedBeans,
+ generatedClasses, transformers, reflectiveClassSet);
+
+ additionalBeans.produce(new AdditionalBeanBuildItem(TimefoldSolverBannerBean.class));
+ if (solverConfigMap.size() <= 1) {
+ // Only registered for the default solver
+ additionalBeans.produce(new AdditionalBeanBuildItem(DefaultTimefoldBeanProvider.class));
+ }
+ unremovableBeans.produce(UnremovableBeanBuildItem.beanTypes(TimefoldRuntimeConfig.class));
+ return new SolverConfigBuildItem(solverConfigMap, generatedGizmoClasses);
+ }
+
+ private void assertNoMemberAnnotationWithoutClassAnnotation(IndexView indexView) {
+ Collection<AnnotationInstance> timefoldFieldAnnotations = new HashSet<>();
+
+ for (DotName annotationName : DotNames.PLANNING_ENTITY_FIELD_ANNOTATIONS) {
+ timefoldFieldAnnotations.addAll(indexView.getAnnotationsWithRepeatable(annotationName, indexView));
+ }
+
+ for (AnnotationInstance annotationInstance : timefoldFieldAnnotations) {
+ AnnotationTarget annotationTarget = annotationInstance.target();
+ ClassInfo declaringClass;
+ String prefix;
+ switch (annotationTarget.kind()) {
+ case FIELD:
+ prefix = "The field (" + annotationTarget.asField().name() + ") ";
+ declaringClass = annotationTarget.asField().declaringClass();
+ break;
+ case METHOD:
+ prefix = "The method (" + annotationTarget.asMethod().name() + ") ";
+ declaringClass = annotationTarget.asMethod().declaringClass();
+ break;
+ default:
+ throw new IllegalStateException(
+ "Member annotation @" + annotationInstance.name().withoutPackagePrefix() + " is on ("
+ + annotationTarget +
+ "), which is an invalid target type (" + annotationTarget.kind() +
+ ") for @" + annotationInstance.name().withoutPackagePrefix() + ".");
+ }
+
+ if (!declaringClass.annotationsMap().containsKey(DotNames.PLANNING_ENTITY)) {
+ throw new IllegalStateException(prefix + "with a @" +
+ annotationInstance.name().withoutPackagePrefix() +
+ " annotation is in a class (" + declaringClass.name()
+ + ") that does not have a @" + PlanningEntity.class.getSimpleName() +
+ " annotation.\n" +
+ "Maybe add a @" + PlanningEntity.class.getSimpleName() +
+ " annotation on the class (" + declaringClass.name() + ").");
+ }
+ }
+ }
+
+ private void assertSolverConfigSolutionClasses(IndexView indexView, Map<String, SolverConfig> solverConfigMap) {
+ // Validate the solution class
+ // No solution class
+ assertEmptyInstances(indexView, DotNames.PLANNING_SOLUTION);
+ // Multiple classes and single solver
+ Collection<AnnotationInstance> annotationInstances = indexView.getAnnotations(DotNames.PLANNING_SOLUTION);
+ if (annotationInstances.size() > 1 && solverConfigMap.size() == 1) {
+ throw new IllegalStateException("Multiple classes (%s) found in the classpath with a @%s annotation.".formatted(
+ convertAnnotationInstancesToString(annotationInstances), PlanningSolution.class.getSimpleName()));
+ }
+ // Multiple classes and at least one solver config does not specify the solution class
+ List<String> solverConfigWithoutSolutionClassList = solverConfigMap.entrySet().stream()
+ .filter(e -> e.getValue().getSolutionClass() == null)
+ .map(Map.Entry::getKey)
+ .toList();
+ if (annotationInstances.size() > 1 && !solverConfigWithoutSolutionClassList.isEmpty()) {
+ throw new IllegalStateException(
+ """
+ Some solver configs (%s) don't specify a %s class, yet there are multiple available (%s) on the classpath.
+ Maybe set the XML config file to the related solver configs, or add the missing solution classes to the XML files,
+ or remove the unnecessary solution classes from the classpath.
+ """ | ```suggestion
or remove the unnecessary solution classes from the classpath."""
```
Be mindful that, if the `"""` is on a new line, the exception message will include an empty line. You don't want that. |
timefold-solver | github_2023 | java | 564 | TimefoldAI | triceo | @@ -225,29 +218,330 @@ SolverConfigBuildItem recordAndRegisterBeans(TimefoldRecorder recorder, Recorder
+ "application.properties entries (quarkus.index-dependency.<name>.group-id"
+ " and quarkus.index-dependency.<name>.artifact-id).");
additionalBeans.produce(new AdditionalBeanBuildItem(UnavailableTimefoldBeanProvider.class));
- return new SolverConfigBuildItem(null);
+ Map<String, SolverConfig> solverConfig = new HashMap<>();
+ this.timefoldBuildTimeConfig.solver().keySet().forEach(solverName -> solverConfig.put(solverName, null));
+ return new SolverConfigBuildItem(solverConfig, null);
}
// Quarkus extensions must always use getContextClassLoader()
// Internally, Timefold defaults the ClassLoader to getContextClassLoader() too
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
+
+ Map<String, SolverConfig> solverConfigMap = new HashMap<>();
+ // Step 1 - create all SolverConfig
+ // If the config map is empty, we build the config using the default solver name
+ if (timefoldBuildTimeConfig.solver().isEmpty()) {
+ solverConfigMap.put(TimefoldBuildTimeConfig.DEFAULT_SOLVER_NAME,
+ createSolverConfig(classLoader, TimefoldBuildTimeConfig.DEFAULT_SOLVER_NAME));
+ } else {
+ // One config per solver mapped name
+ this.timefoldBuildTimeConfig.solver().keySet().forEach(solverName -> solverConfigMap.put(solverName,
+ createSolverConfig(classLoader, solverName)));
+ }
+
+ // Step 2 - validate all SolverConfig definitions
+ assertNoMemberAnnotationWithoutClassAnnotation(indexView);
+ assertSolverConfigSolutionClasses(indexView, solverConfigMap);
+ assertSolverConfigEntityClasses(indexView);
+ assertSolverConfigConstraintClasses(indexView, solverConfigMap);
+
+ // Step 3 - load all additional information per SolverConfig
+ Set<Class<?>> reflectiveClassSet = new LinkedHashSet<>();
+ solverConfigMap.forEach((solverName, solverConfig) -> loadSolverConfig(indexView, reflectiveHierarchyClass,
+ solverConfig, solverName, reflectiveClassSet));
+
+ // Register all annotated domain model classes
+ registerClassesFromAnnotations(indexView, reflectiveClassSet);
+
+ // Register only distinct constraint providers
+ solverConfigMap.values()
+ .stream()
+ .filter(config -> config.getScoreDirectorFactoryConfig().getConstraintProviderClass() != null)
+ .map(config -> config.getScoreDirectorFactoryConfig().getConstraintProviderClass().getName())
+ .distinct()
+ .map(constraintName -> solverConfigMap.entrySet().stream().filter(entryConfig -> entryConfig.getValue()
+ .getScoreDirectorFactoryConfig().getConstraintProviderClass().getName().equals(constraintName))
+ .findFirst().get())
+ .forEach(
+ entryConfig -> generateConstraintVerifier(entryConfig.getValue(), syntheticBeanBuildItemBuildProducer));
+
+ GeneratedGizmoClasses generatedGizmoClasses = generateDomainAccessors(solverConfigMap, indexView, generatedBeans,
+ generatedClasses, transformers, reflectiveClassSet);
+
+ additionalBeans.produce(new AdditionalBeanBuildItem(TimefoldSolverBannerBean.class));
+ if (solverConfigMap.size() <= 1) {
+ // Only registered for the default solver
+ additionalBeans.produce(new AdditionalBeanBuildItem(DefaultTimefoldBeanProvider.class));
+ }
+ unremovableBeans.produce(UnremovableBeanBuildItem.beanTypes(TimefoldRuntimeConfig.class));
+ return new SolverConfigBuildItem(solverConfigMap, generatedGizmoClasses);
+ }
+
+ private void assertNoMemberAnnotationWithoutClassAnnotation(IndexView indexView) {
+ Collection<AnnotationInstance> timefoldFieldAnnotations = new HashSet<>();
+
+ for (DotName annotationName : DotNames.PLANNING_ENTITY_FIELD_ANNOTATIONS) {
+ timefoldFieldAnnotations.addAll(indexView.getAnnotationsWithRepeatable(annotationName, indexView));
+ }
+
+ for (AnnotationInstance annotationInstance : timefoldFieldAnnotations) {
+ AnnotationTarget annotationTarget = annotationInstance.target();
+ ClassInfo declaringClass;
+ String prefix;
+ switch (annotationTarget.kind()) {
+ case FIELD:
+ prefix = "The field (" + annotationTarget.asField().name() + ") ";
+ declaringClass = annotationTarget.asField().declaringClass();
+ break;
+ case METHOD:
+ prefix = "The method (" + annotationTarget.asMethod().name() + ") ";
+ declaringClass = annotationTarget.asMethod().declaringClass();
+ break;
+ default:
+ throw new IllegalStateException(
+ "Member annotation @" + annotationInstance.name().withoutPackagePrefix() + " is on ("
+ + annotationTarget +
+ "), which is an invalid target type (" + annotationTarget.kind() +
+ ") for @" + annotationInstance.name().withoutPackagePrefix() + ".");
+ }
+
+ if (!declaringClass.annotationsMap().containsKey(DotNames.PLANNING_ENTITY)) {
+ throw new IllegalStateException(prefix + "with a @" +
+ annotationInstance.name().withoutPackagePrefix() +
+ " annotation is in a class (" + declaringClass.name()
+ + ") that does not have a @" + PlanningEntity.class.getSimpleName() +
+ " annotation.\n" +
+ "Maybe add a @" + PlanningEntity.class.getSimpleName() +
+ " annotation on the class (" + declaringClass.name() + ").");
+ }
+ }
+ }
+
+ private void assertSolverConfigSolutionClasses(IndexView indexView, Map<String, SolverConfig> solverConfigMap) {
+ // Validate the solution class
+ // No solution class
+ assertEmptyInstances(indexView, DotNames.PLANNING_SOLUTION);
+ // Multiple classes and single solver
+ Collection<AnnotationInstance> annotationInstances = indexView.getAnnotations(DotNames.PLANNING_SOLUTION);
+ if (annotationInstances.size() > 1 && solverConfigMap.size() == 1) {
+ throw new IllegalStateException("Multiple classes (%s) found in the classpath with a @%s annotation.".formatted(
+ convertAnnotationInstancesToString(annotationInstances), PlanningSolution.class.getSimpleName()));
+ }
+ // Multiple classes and at least one solver config does not specify the solution class
+ List<String> solverConfigWithoutSolutionClassList = solverConfigMap.entrySet().stream()
+ .filter(e -> e.getValue().getSolutionClass() == null)
+ .map(Map.Entry::getKey)
+ .toList();
+ if (annotationInstances.size() > 1 && !solverConfigWithoutSolutionClassList.isEmpty()) {
+ throw new IllegalStateException(
+ """
+ Some solver configs (%s) don't specify a %s class, yet there are multiple available (%s) on the classpath.
+ Maybe set the XML config file to the related solver configs, or add the missing solution classes to the XML files,
+ or remove the unnecessary solution classes from the classpath.
+ """
+ .formatted(String.join(", ", solverConfigWithoutSolutionClassList),
+ PlanningSolution.class.getSimpleName(),
+ convertAnnotationInstancesToString(annotationInstances)));
+ }
+ // Unused solution classes
+ List<String> unusedSolutionClasses = annotationInstances.stream() | `unusedSolutionClassNameSet`. |
timefold-solver | github_2023 | java | 564 | TimefoldAI | triceo | @@ -225,29 +218,330 @@ SolverConfigBuildItem recordAndRegisterBeans(TimefoldRecorder recorder, Recorder
+ "application.properties entries (quarkus.index-dependency.<name>.group-id"
+ " and quarkus.index-dependency.<name>.artifact-id).");
additionalBeans.produce(new AdditionalBeanBuildItem(UnavailableTimefoldBeanProvider.class));
- return new SolverConfigBuildItem(null);
+ Map<String, SolverConfig> solverConfig = new HashMap<>();
+ this.timefoldBuildTimeConfig.solver().keySet().forEach(solverName -> solverConfig.put(solverName, null));
+ return new SolverConfigBuildItem(solverConfig, null);
}
// Quarkus extensions must always use getContextClassLoader()
// Internally, Timefold defaults the ClassLoader to getContextClassLoader() too
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
+
+ Map<String, SolverConfig> solverConfigMap = new HashMap<>();
+ // Step 1 - create all SolverConfig
+ // If the config map is empty, we build the config using the default solver name
+ if (timefoldBuildTimeConfig.solver().isEmpty()) {
+ solverConfigMap.put(TimefoldBuildTimeConfig.DEFAULT_SOLVER_NAME,
+ createSolverConfig(classLoader, TimefoldBuildTimeConfig.DEFAULT_SOLVER_NAME));
+ } else {
+ // One config per solver mapped name
+ this.timefoldBuildTimeConfig.solver().keySet().forEach(solverName -> solverConfigMap.put(solverName,
+ createSolverConfig(classLoader, solverName)));
+ }
+
+ // Step 2 - validate all SolverConfig definitions
+ assertNoMemberAnnotationWithoutClassAnnotation(indexView);
+ assertSolverConfigSolutionClasses(indexView, solverConfigMap);
+ assertSolverConfigEntityClasses(indexView);
+ assertSolverConfigConstraintClasses(indexView, solverConfigMap);
+
+ // Step 3 - load all additional information per SolverConfig
+ Set<Class<?>> reflectiveClassSet = new LinkedHashSet<>();
+ solverConfigMap.forEach((solverName, solverConfig) -> loadSolverConfig(indexView, reflectiveHierarchyClass,
+ solverConfig, solverName, reflectiveClassSet));
+
+ // Register all annotated domain model classes
+ registerClassesFromAnnotations(indexView, reflectiveClassSet);
+
+ // Register only distinct constraint providers
+ solverConfigMap.values()
+ .stream()
+ .filter(config -> config.getScoreDirectorFactoryConfig().getConstraintProviderClass() != null)
+ .map(config -> config.getScoreDirectorFactoryConfig().getConstraintProviderClass().getName())
+ .distinct()
+ .map(constraintName -> solverConfigMap.entrySet().stream().filter(entryConfig -> entryConfig.getValue()
+ .getScoreDirectorFactoryConfig().getConstraintProviderClass().getName().equals(constraintName))
+ .findFirst().get())
+ .forEach(
+ entryConfig -> generateConstraintVerifier(entryConfig.getValue(), syntheticBeanBuildItemBuildProducer));
+
+ GeneratedGizmoClasses generatedGizmoClasses = generateDomainAccessors(solverConfigMap, indexView, generatedBeans,
+ generatedClasses, transformers, reflectiveClassSet);
+
+ additionalBeans.produce(new AdditionalBeanBuildItem(TimefoldSolverBannerBean.class));
+ if (solverConfigMap.size() <= 1) {
+ // Only registered for the default solver
+ additionalBeans.produce(new AdditionalBeanBuildItem(DefaultTimefoldBeanProvider.class));
+ }
+ unremovableBeans.produce(UnremovableBeanBuildItem.beanTypes(TimefoldRuntimeConfig.class));
+ return new SolverConfigBuildItem(solverConfigMap, generatedGizmoClasses);
+ }
+
+ private void assertNoMemberAnnotationWithoutClassAnnotation(IndexView indexView) {
+ Collection<AnnotationInstance> timefoldFieldAnnotations = new HashSet<>();
+
+ for (DotName annotationName : DotNames.PLANNING_ENTITY_FIELD_ANNOTATIONS) {
+ timefoldFieldAnnotations.addAll(indexView.getAnnotationsWithRepeatable(annotationName, indexView));
+ }
+
+ for (AnnotationInstance annotationInstance : timefoldFieldAnnotations) {
+ AnnotationTarget annotationTarget = annotationInstance.target();
+ ClassInfo declaringClass;
+ String prefix;
+ switch (annotationTarget.kind()) {
+ case FIELD:
+ prefix = "The field (" + annotationTarget.asField().name() + ") ";
+ declaringClass = annotationTarget.asField().declaringClass();
+ break;
+ case METHOD:
+ prefix = "The method (" + annotationTarget.asMethod().name() + ") ";
+ declaringClass = annotationTarget.asMethod().declaringClass();
+ break;
+ default:
+ throw new IllegalStateException(
+ "Member annotation @" + annotationInstance.name().withoutPackagePrefix() + " is on ("
+ + annotationTarget +
+ "), which is an invalid target type (" + annotationTarget.kind() +
+ ") for @" + annotationInstance.name().withoutPackagePrefix() + ".");
+ }
+
+ if (!declaringClass.annotationsMap().containsKey(DotNames.PLANNING_ENTITY)) {
+ throw new IllegalStateException(prefix + "with a @" +
+ annotationInstance.name().withoutPackagePrefix() +
+ " annotation is in a class (" + declaringClass.name()
+ + ") that does not have a @" + PlanningEntity.class.getSimpleName() +
+ " annotation.\n" +
+ "Maybe add a @" + PlanningEntity.class.getSimpleName() +
+ " annotation on the class (" + declaringClass.name() + ").");
+ }
+ }
+ }
+
+ private void assertSolverConfigSolutionClasses(IndexView indexView, Map<String, SolverConfig> solverConfigMap) {
+ // Validate the solution class
+ // No solution class
+ assertEmptyInstances(indexView, DotNames.PLANNING_SOLUTION);
+ // Multiple classes and single solver
+ Collection<AnnotationInstance> annotationInstances = indexView.getAnnotations(DotNames.PLANNING_SOLUTION);
+ if (annotationInstances.size() > 1 && solverConfigMap.size() == 1) {
+ throw new IllegalStateException("Multiple classes (%s) found in the classpath with a @%s annotation.".formatted(
+ convertAnnotationInstancesToString(annotationInstances), PlanningSolution.class.getSimpleName()));
+ }
+ // Multiple classes and at least one solver config does not specify the solution class
+ List<String> solverConfigWithoutSolutionClassList = solverConfigMap.entrySet().stream()
+ .filter(e -> e.getValue().getSolutionClass() == null)
+ .map(Map.Entry::getKey)
+ .toList();
+ if (annotationInstances.size() > 1 && !solverConfigWithoutSolutionClassList.isEmpty()) {
+ throw new IllegalStateException(
+ """
+ Some solver configs (%s) don't specify a %s class, yet there are multiple available (%s) on the classpath.
+ Maybe set the XML config file to the related solver configs, or add the missing solution classes to the XML files,
+ or remove the unnecessary solution classes from the classpath.
+ """
+ .formatted(String.join(", ", solverConfigWithoutSolutionClassList),
+ PlanningSolution.class.getSimpleName(),
+ convertAnnotationInstancesToString(annotationInstances)));
+ }
+ // Unused solution classes
+ List<String> unusedSolutionClasses = annotationInstances.stream()
+ .map(planningClass -> planningClass.target().asClass().name().toString())
+ .filter(planningClassName -> solverConfigMap.values().stream().filter(c -> c.getSolutionClass() != null)
+ .noneMatch(c -> c.getSolutionClass().getName().equals(planningClassName)))
+ .toList();
+ if (annotationInstances.size() > 1 && !unusedSolutionClasses.isEmpty()) {
+ throw new IllegalStateException(
+ "Unused classes ([%s]) found with a @%s annotation.".formatted(String.join(", ", unusedSolutionClasses),
+ PlanningSolution.class.getSimpleName()));
+ }
+ // Validate the solution classes target types
+ List<AnnotationTarget> targetList = annotationInstances.stream()
+ .map(AnnotationInstance::target)
+ .toList();
+ assertTargetClasses(targetList, DotNames.PLANNING_SOLUTION);
+ }
+
+ private void assertSolverConfigEntityClasses(IndexView indexView) {
+ // No entity classes
+ assertEmptyInstances(indexView, DotNames.PLANNING_ENTITY);
+ // Validate the entity classes target types
+ Collection<AnnotationInstance> annotationInstances = indexView.getAnnotations(DotNames.PLANNING_ENTITY);
+ List<AnnotationTarget> targetList = annotationInstances.stream()
+ .map(AnnotationInstance::target)
+ .toList();
+ assertTargetClasses(targetList, DotNames.PLANNING_ENTITY);
+ }
+
+ private void assertSolverConfigConstraintClasses(IndexView indexView, Map<String, SolverConfig> solverConfigMap) {
+ Collection<ClassInfo> simpleScoreClasses = indexView.getAllKnownImplementors(DotNames.EASY_SCORE_CALCULATOR);
+ Collection<ClassInfo> constraintScoreClasses = indexView.getAllKnownImplementors(DotNames.CONSTRAINT_PROVIDER);
+ Collection<ClassInfo> incrementalScoreClasses =
+ indexView.getAllKnownImplementors(DotNames.INCREMENTAL_SCORE_CALCULATOR);
+ // No score classes
+ if (simpleScoreClasses.isEmpty() && constraintScoreClasses.isEmpty() && incrementalScoreClasses.isEmpty()) {
+ throw new IllegalStateException(
+ "No classes found that implement %s, %s, or %s.".formatted(EasyScoreCalculator.class.getSimpleName(),
+ ConstraintProvider.class.getSimpleName(), IncrementalScoreCalculator.class.getSimpleName()));
+ }
+ // Multiple classes and single solver
+ String errorMessage = "Multiple score classes classes (%s) that implements %s were found in the classpath.";
+ if (simpleScoreClasses.size() > 1 && solverConfigMap.size() == 1) {
+ throw new IllegalStateException(errorMessage.formatted(
+ simpleScoreClasses.stream().map(c -> c.name().toString()).collect(Collectors.joining(", ")),
+ EasyScoreCalculator.class.getSimpleName()));
+ }
+ if (constraintScoreClasses.size() > 1 && solverConfigMap.size() == 1) {
+ throw new IllegalStateException(errorMessage.formatted(
+ constraintScoreClasses.stream().map(c -> c.name().toString()).collect(Collectors.joining(", ")),
+ ConstraintProvider.class.getSimpleName()));
+ }
+ if (incrementalScoreClasses.size() > 1 && solverConfigMap.size() == 1) {
+ throw new IllegalStateException(errorMessage.formatted(
+ incrementalScoreClasses.stream().map(c -> c.name().toString()).collect(Collectors.joining(", ")),
+ IncrementalScoreCalculator.class.getSimpleName()));
+ }
+ // Multiple classes and at least one solver config does not specify the score class
+ errorMessage = """
+ Some solver configs (%s) don't specify a %s score class, yet there are multiple available (%s) on the classpath.
+ Maybe set the XML config file to the related solver configs, or add the missing score classes to the XML files,
+ or remove the unnecessary score classes from the classpath.
+ """; | Another newline at the end. |
timefold-solver | github_2023 | java | 564 | TimefoldAI | triceo | @@ -563,40 +845,46 @@ private GeneratedGizmoClasses generateDomainAccessors(SolverConfig solverConfig,
membersToGeneratedAccessorsFor.removeIf(this::shouldIgnoreMember);
// Fail fast on auto-discovery.
- var planningSolutionAnnotationInstanceCollection =
+ Collection<AnnotationInstance> planningSolutionAnnotationInstanceCollection =
indexView.getAnnotations(DotNames.PLANNING_SOLUTION);
+ List<String> unusedSolutionClasses = planningSolutionAnnotationInstanceCollection.stream() | `unusedSolutionClassNameSet`. |
timefold-solver | github_2023 | java | 590 | TimefoldAI | triceo | @@ -0,0 +1,115 @@
+package ai.timefold.solver.spring.boot.autoconfigure;
+
+import static java.util.Collections.emptyList;
+
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
+
+import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
+import org.springframework.beans.factory.config.BeanDefinition;
+import org.springframework.boot.autoconfigure.AutoConfigurationPackages;
+import org.springframework.boot.autoconfigure.domain.EntityScanPackages;
+import org.springframework.boot.autoconfigure.domain.EntityScanner;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
+import org.springframework.core.type.AnnotationMetadata;
+import org.springframework.core.type.filter.AssignableTypeFilter;
+import org.springframework.util.ClassUtils;
+
+public class IncludeAbstractClassesEntityScanner extends EntityScanner { | Why was introducing this necessary?
What abstract classes do we need to find? |
timefold-solver | github_2023 | java | 590 | TimefoldAI | triceo | @@ -0,0 +1,115 @@
+package ai.timefold.solver.spring.boot.autoconfigure;
+
+import static java.util.Collections.emptyList;
+
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
+
+import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
+import org.springframework.beans.factory.config.BeanDefinition;
+import org.springframework.boot.autoconfigure.AutoConfigurationPackages;
+import org.springframework.boot.autoconfigure.domain.EntityScanPackages;
+import org.springframework.boot.autoconfigure.domain.EntityScanner;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
+import org.springframework.core.type.AnnotationMetadata;
+import org.springframework.core.type.filter.AssignableTypeFilter;
+import org.springframework.util.ClassUtils;
+
+public class IncludeAbstractClassesEntityScanner extends EntityScanner {
+
+ private final ApplicationContext context;
+
+ public IncludeAbstractClassesEntityScanner(ApplicationContext context) {
+ super(context);
+ this.context = context;
+ }
+
+ public <T> Class<? extends T> findFirstImplementingClass(Class<T> targetClass) {
+ return Optional.ofNullable(findImplementingClassList(targetClass)).filter(classes -> !classes.isEmpty())
+ .map(classes -> classes.get(0)).orElse(null); | Let's avoid `Optional` if the only purpose of it is to avoid a local `null` check.
I'd argue the following code reads much better:
var implementingClassList = findImplementingClassList(targetClass);
if (implementingClassList == null || implementingClassList.isEmpty()) {
return null;
} else {
return implementingClassList.get(0);
}
`Optional` is useful to communicate nullness information with outside code. But if we can keep the `null` local inside of a method, using `Optional` is just a more difficult way to write a `null` check.
Also, why are we bothering with `null` at all? `findImplementingClassList(...)` doesn't seem to ever return `null`.
|
timefold-solver | github_2023 | java | 590 | TimefoldAI | triceo | @@ -0,0 +1,115 @@
+package ai.timefold.solver.spring.boot.autoconfigure;
+
+import static java.util.Collections.emptyList;
+
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
+
+import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
+import org.springframework.beans.factory.config.BeanDefinition;
+import org.springframework.boot.autoconfigure.AutoConfigurationPackages;
+import org.springframework.boot.autoconfigure.domain.EntityScanPackages;
+import org.springframework.boot.autoconfigure.domain.EntityScanner;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
+import org.springframework.core.type.AnnotationMetadata;
+import org.springframework.core.type.filter.AssignableTypeFilter;
+import org.springframework.util.ClassUtils;
+
+public class IncludeAbstractClassesEntityScanner extends EntityScanner {
+
+ private final ApplicationContext context;
+
+ public IncludeAbstractClassesEntityScanner(ApplicationContext context) {
+ super(context);
+ this.context = context;
+ }
+
+ public <T> Class<? extends T> findFirstImplementingClass(Class<T> targetClass) {
+ return Optional.ofNullable(findImplementingClassList(targetClass)).filter(classes -> !classes.isEmpty())
+ .map(classes -> classes.get(0)).orElse(null);
+ }
+
+ public <T> List<Class<? extends T>> findImplementingClassList(Class<T> targetClass) {
+ if (!AutoConfigurationPackages.has(context)) {
+ return emptyList();
+ }
+ ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
+ scanner.setEnvironment(context.getEnvironment());
+ scanner.setResourceLoader(context);
+ scanner.addIncludeFilter(new AssignableTypeFilter(targetClass));
+
+ EntityScanPackages entityScanPackages = EntityScanPackages.get(context);
+
+ Set<String> packages = new HashSet<>(); | `packageSet`. |
timefold-solver | github_2023 | java | 590 | TimefoldAI | triceo | @@ -0,0 +1,115 @@
+package ai.timefold.solver.spring.boot.autoconfigure;
+
+import static java.util.Collections.emptyList;
+
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
+
+import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
+import org.springframework.beans.factory.config.BeanDefinition;
+import org.springframework.boot.autoconfigure.AutoConfigurationPackages;
+import org.springframework.boot.autoconfigure.domain.EntityScanPackages;
+import org.springframework.boot.autoconfigure.domain.EntityScanner;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
+import org.springframework.core.type.AnnotationMetadata;
+import org.springframework.core.type.filter.AssignableTypeFilter;
+import org.springframework.util.ClassUtils;
+
+public class IncludeAbstractClassesEntityScanner extends EntityScanner {
+
+ private final ApplicationContext context;
+
+ public IncludeAbstractClassesEntityScanner(ApplicationContext context) {
+ super(context);
+ this.context = context;
+ }
+
+ public <T> Class<? extends T> findFirstImplementingClass(Class<T> targetClass) {
+ return Optional.ofNullable(findImplementingClassList(targetClass)).filter(classes -> !classes.isEmpty())
+ .map(classes -> classes.get(0)).orElse(null);
+ }
+
+ public <T> List<Class<? extends T>> findImplementingClassList(Class<T> targetClass) {
+ if (!AutoConfigurationPackages.has(context)) {
+ return emptyList();
+ }
+ ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
+ scanner.setEnvironment(context.getEnvironment());
+ scanner.setResourceLoader(context);
+ scanner.addIncludeFilter(new AssignableTypeFilter(targetClass));
+
+ EntityScanPackages entityScanPackages = EntityScanPackages.get(context);
+
+ Set<String> packages = new HashSet<>();
+ packages.addAll(AutoConfigurationPackages.get(context));
+ packages.addAll(entityScanPackages.getPackageNames());
+ return packages.stream()
+ .flatMap(basePackage -> scanner.findCandidateComponents(basePackage).stream())
+ // findCandidateComponents can return the same package for different base packages
+ .distinct()
+ .sorted(Comparator.comparing(BeanDefinition::getBeanClassName))
+ .map(candidate -> {
+ try {
+ return (Class<? extends T>) ClassUtils.forName(candidate.getBeanClassName(), context.getClassLoader())
+ .asSubclass(targetClass);
+ } catch (ClassNotFoundException e) {
+ throw new IllegalStateException("The " + targetClass.getSimpleName() + " class (" | Please apply the new convention to formatting error messages. |
timefold-solver | github_2023 | java | 590 | TimefoldAI | triceo | @@ -0,0 +1,115 @@
+package ai.timefold.solver.spring.boot.autoconfigure;
+
+import static java.util.Collections.emptyList;
+
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
+
+import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
+import org.springframework.beans.factory.config.BeanDefinition;
+import org.springframework.boot.autoconfigure.AutoConfigurationPackages;
+import org.springframework.boot.autoconfigure.domain.EntityScanPackages;
+import org.springframework.boot.autoconfigure.domain.EntityScanner;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
+import org.springframework.core.type.AnnotationMetadata;
+import org.springframework.core.type.filter.AssignableTypeFilter;
+import org.springframework.util.ClassUtils;
+
+public class IncludeAbstractClassesEntityScanner extends EntityScanner {
+
+ private final ApplicationContext context;
+
+ public IncludeAbstractClassesEntityScanner(ApplicationContext context) {
+ super(context);
+ this.context = context;
+ }
+
+ public <T> Class<? extends T> findFirstImplementingClass(Class<T> targetClass) {
+ return Optional.ofNullable(findImplementingClassList(targetClass)).filter(classes -> !classes.isEmpty())
+ .map(classes -> classes.get(0)).orElse(null);
+ }
+
+ public <T> List<Class<? extends T>> findImplementingClassList(Class<T> targetClass) {
+ if (!AutoConfigurationPackages.has(context)) {
+ return emptyList();
+ }
+ ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
+ scanner.setEnvironment(context.getEnvironment());
+ scanner.setResourceLoader(context);
+ scanner.addIncludeFilter(new AssignableTypeFilter(targetClass));
+
+ EntityScanPackages entityScanPackages = EntityScanPackages.get(context);
+
+ Set<String> packages = new HashSet<>();
+ packages.addAll(AutoConfigurationPackages.get(context));
+ packages.addAll(entityScanPackages.getPackageNames());
+ return packages.stream()
+ .flatMap(basePackage -> scanner.findCandidateComponents(basePackage).stream())
+ // findCandidateComponents can return the same package for different base packages
+ .distinct()
+ .sorted(Comparator.comparing(BeanDefinition::getBeanClassName))
+ .map(candidate -> {
+ try {
+ return (Class<? extends T>) ClassUtils.forName(candidate.getBeanClassName(), context.getClassLoader())
+ .asSubclass(targetClass);
+ } catch (ClassNotFoundException e) {
+ throw new IllegalStateException("The " + targetClass.getSimpleName() + " class ("
+ + candidate.getBeanClassName() + ") cannot be found.", e);
+ }
+ })
+ .collect(Collectors.toList());
+ }
+
+ public boolean hasSolutionOrEntityClasses() {
+ try {
+ return !scan(PlanningSolution.class).isEmpty() || !scan(PlanningEntity.class).isEmpty();
+ } catch (ClassNotFoundException e) {
+ throw new IllegalStateException("Scanning for @" + PlanningSolution.class.getSimpleName() | Dtto. |
timefold-solver | github_2023 | java | 590 | TimefoldAI | triceo | @@ -0,0 +1,115 @@
+package ai.timefold.solver.spring.boot.autoconfigure;
+
+import static java.util.Collections.emptyList;
+
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
+
+import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
+import org.springframework.beans.factory.config.BeanDefinition;
+import org.springframework.boot.autoconfigure.AutoConfigurationPackages;
+import org.springframework.boot.autoconfigure.domain.EntityScanPackages;
+import org.springframework.boot.autoconfigure.domain.EntityScanner;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
+import org.springframework.core.type.AnnotationMetadata;
+import org.springframework.core.type.filter.AssignableTypeFilter;
+import org.springframework.util.ClassUtils;
+
+public class IncludeAbstractClassesEntityScanner extends EntityScanner {
+
+ private final ApplicationContext context;
+
+ public IncludeAbstractClassesEntityScanner(ApplicationContext context) {
+ super(context);
+ this.context = context;
+ }
+
+ public <T> Class<? extends T> findFirstImplementingClass(Class<T> targetClass) {
+ return Optional.ofNullable(findImplementingClassList(targetClass)).filter(classes -> !classes.isEmpty())
+ .map(classes -> classes.get(0)).orElse(null);
+ }
+
+ public <T> List<Class<? extends T>> findImplementingClassList(Class<T> targetClass) {
+ if (!AutoConfigurationPackages.has(context)) {
+ return emptyList();
+ }
+ ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
+ scanner.setEnvironment(context.getEnvironment());
+ scanner.setResourceLoader(context);
+ scanner.addIncludeFilter(new AssignableTypeFilter(targetClass));
+
+ EntityScanPackages entityScanPackages = EntityScanPackages.get(context);
+
+ Set<String> packages = new HashSet<>();
+ packages.addAll(AutoConfigurationPackages.get(context));
+ packages.addAll(entityScanPackages.getPackageNames());
+ return packages.stream()
+ .flatMap(basePackage -> scanner.findCandidateComponents(basePackage).stream())
+ // findCandidateComponents can return the same package for different base packages
+ .distinct()
+ .sorted(Comparator.comparing(BeanDefinition::getBeanClassName))
+ .map(candidate -> {
+ try {
+ return (Class<? extends T>) ClassUtils.forName(candidate.getBeanClassName(), context.getClassLoader())
+ .asSubclass(targetClass);
+ } catch (ClassNotFoundException e) {
+ throw new IllegalStateException("The " + targetClass.getSimpleName() + " class ("
+ + candidate.getBeanClassName() + ") cannot be found.", e);
+ }
+ })
+ .collect(Collectors.toList());
+ }
+
+ public boolean hasSolutionOrEntityClasses() {
+ try {
+ return !scan(PlanningSolution.class).isEmpty() || !scan(PlanningEntity.class).isEmpty();
+ } catch (ClassNotFoundException e) {
+ throw new IllegalStateException("Scanning for @" + PlanningSolution.class.getSimpleName()
+ + " and @" + PlanningEntity.class.getSimpleName() + " annotations failed.", e);
+ }
+ }
+
+ public Class<?> findFirstSolutionClass() {
+ Set<Class<?>> solutionClassSet;
+ try {
+ solutionClassSet = scan(PlanningSolution.class);
+ } catch (ClassNotFoundException e) {
+ throw new IllegalStateException("Scanning for @" + PlanningSolution.class.getSimpleName() | Dtto. |
timefold-solver | github_2023 | java | 590 | TimefoldAI | triceo | @@ -0,0 +1,115 @@
+package ai.timefold.solver.spring.boot.autoconfigure;
+
+import static java.util.Collections.emptyList;
+
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
+
+import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
+import org.springframework.beans.factory.config.BeanDefinition;
+import org.springframework.boot.autoconfigure.AutoConfigurationPackages;
+import org.springframework.boot.autoconfigure.domain.EntityScanPackages;
+import org.springframework.boot.autoconfigure.domain.EntityScanner;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
+import org.springframework.core.type.AnnotationMetadata;
+import org.springframework.core.type.filter.AssignableTypeFilter;
+import org.springframework.util.ClassUtils;
+
+public class IncludeAbstractClassesEntityScanner extends EntityScanner {
+
+ private final ApplicationContext context;
+
+ public IncludeAbstractClassesEntityScanner(ApplicationContext context) {
+ super(context);
+ this.context = context;
+ }
+
+ public <T> Class<? extends T> findFirstImplementingClass(Class<T> targetClass) {
+ return Optional.ofNullable(findImplementingClassList(targetClass)).filter(classes -> !classes.isEmpty())
+ .map(classes -> classes.get(0)).orElse(null);
+ }
+
+ public <T> List<Class<? extends T>> findImplementingClassList(Class<T> targetClass) {
+ if (!AutoConfigurationPackages.has(context)) {
+ return emptyList();
+ }
+ ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
+ scanner.setEnvironment(context.getEnvironment());
+ scanner.setResourceLoader(context);
+ scanner.addIncludeFilter(new AssignableTypeFilter(targetClass));
+
+ EntityScanPackages entityScanPackages = EntityScanPackages.get(context);
+
+ Set<String> packages = new HashSet<>();
+ packages.addAll(AutoConfigurationPackages.get(context));
+ packages.addAll(entityScanPackages.getPackageNames());
+ return packages.stream()
+ .flatMap(basePackage -> scanner.findCandidateComponents(basePackage).stream())
+ // findCandidateComponents can return the same package for different base packages
+ .distinct()
+ .sorted(Comparator.comparing(BeanDefinition::getBeanClassName))
+ .map(candidate -> {
+ try {
+ return (Class<? extends T>) ClassUtils.forName(candidate.getBeanClassName(), context.getClassLoader())
+ .asSubclass(targetClass);
+ } catch (ClassNotFoundException e) {
+ throw new IllegalStateException("The " + targetClass.getSimpleName() + " class ("
+ + candidate.getBeanClassName() + ") cannot be found.", e);
+ }
+ })
+ .collect(Collectors.toList());
+ }
+
+ public boolean hasSolutionOrEntityClasses() {
+ try {
+ return !scan(PlanningSolution.class).isEmpty() || !scan(PlanningEntity.class).isEmpty();
+ } catch (ClassNotFoundException e) {
+ throw new IllegalStateException("Scanning for @" + PlanningSolution.class.getSimpleName()
+ + " and @" + PlanningEntity.class.getSimpleName() + " annotations failed.", e);
+ }
+ }
+
+ public Class<?> findFirstSolutionClass() {
+ Set<Class<?>> solutionClassSet;
+ try {
+ solutionClassSet = scan(PlanningSolution.class);
+ } catch (ClassNotFoundException e) {
+ throw new IllegalStateException("Scanning for @" + PlanningSolution.class.getSimpleName()
+ + " annotations failed.", e);
+ }
+ return solutionClassSet.iterator().next();
+ }
+
+ public List<Class<?>> findEntityClassList() {
+ Set<Class<?>> entityClassSet;
+ try {
+ entityClassSet = scan(PlanningEntity.class);
+ } catch (ClassNotFoundException e) {
+ throw new IllegalStateException("Scanning for @" + PlanningEntity.class.getSimpleName() + " failed.", e); | Dtto. |
timefold-solver | github_2023 | java | 590 | TimefoldAI | triceo | @@ -64,62 +70,422 @@
@ConditionalOnMissingBean({ SolverConfig.class, SolverFactory.class, ScoreManager.class, SolutionManager.class,
SolverManager.class })
@EnableConfigurationProperties({ TimefoldProperties.class })
-public class TimefoldAutoConfiguration implements BeanClassLoaderAware {
+public class TimefoldAutoConfiguration
+ implements BeanClassLoaderAware, ApplicationContextAware, EnvironmentAware, BeanFactoryPostProcessor {
- private final ApplicationContext context;
- private final TimefoldProperties timefoldProperties;
+ private static final Log LOG = LogFactory.getLog(TimefoldAutoConfiguration.class);
+ private static String DEFAULT_SOLVER_CONFIG_NAME = "getSolverConfig";
+ private ApplicationContext context;
private ClassLoader beanClassLoader;
+ private TimefoldProperties timefoldProperties;
- protected TimefoldAutoConfiguration(ApplicationContext context,
- TimefoldProperties timefoldProperties) {
- this.context = context;
- this.timefoldProperties = timefoldProperties;
+ protected TimefoldAutoConfiguration() {
}
@Override
public void setBeanClassLoader(ClassLoader beanClassLoader) {
this.beanClassLoader = beanClassLoader;
}
- @Bean
- public TimefoldSolverBannerBean getBanner() {
- return new TimefoldSolverBannerBean();
+ @Override
+ public void setApplicationContext(ApplicationContext context) throws BeansException {
+ this.context = context;
}
- @Bean
- @ConditionalOnMissingBean
- public SolverConfig solverConfig() {
- String solverConfigXml = timefoldProperties.getSolverConfigXml();
+ @Override
+ public void setEnvironment(Environment environment) {
+ // postProcessBeanFactory runs before creating any bean, but we need TimefoldProperties. Therefore, we use the
+ // Environment to load the properties | ```suggestion
// postProcessBeanFactory runs before creating any bean, but we need TimefoldProperties.
// Therefore, we use the Environment to load the properties.
``` |
timefold-solver | github_2023 | java | 590 | TimefoldAI | triceo | @@ -64,62 +70,422 @@
@ConditionalOnMissingBean({ SolverConfig.class, SolverFactory.class, ScoreManager.class, SolutionManager.class,
SolverManager.class })
@EnableConfigurationProperties({ TimefoldProperties.class })
-public class TimefoldAutoConfiguration implements BeanClassLoaderAware {
+public class TimefoldAutoConfiguration
+ implements BeanClassLoaderAware, ApplicationContextAware, EnvironmentAware, BeanFactoryPostProcessor {
- private final ApplicationContext context;
- private final TimefoldProperties timefoldProperties;
+ private static final Log LOG = LogFactory.getLog(TimefoldAutoConfiguration.class);
+ private static String DEFAULT_SOLVER_CONFIG_NAME = "getSolverConfig";
+ private ApplicationContext context;
private ClassLoader beanClassLoader;
+ private TimefoldProperties timefoldProperties;
- protected TimefoldAutoConfiguration(ApplicationContext context,
- TimefoldProperties timefoldProperties) {
- this.context = context;
- this.timefoldProperties = timefoldProperties;
+ protected TimefoldAutoConfiguration() {
}
@Override
public void setBeanClassLoader(ClassLoader beanClassLoader) {
this.beanClassLoader = beanClassLoader;
}
- @Bean
- public TimefoldSolverBannerBean getBanner() {
- return new TimefoldSolverBannerBean();
+ @Override
+ public void setApplicationContext(ApplicationContext context) throws BeansException {
+ this.context = context;
}
- @Bean
- @ConditionalOnMissingBean
- public SolverConfig solverConfig() {
- String solverConfigXml = timefoldProperties.getSolverConfigXml();
+ @Override
+ public void setEnvironment(Environment environment) {
+ // postProcessBeanFactory runs before creating any bean, but we need TimefoldProperties. Therefore, we use the
+ // Environment to load the properties
+ BindResult<TimefoldProperties> result = Binder.get(environment).bind("timefold", TimefoldProperties.class);
+ this.timefoldProperties = result.orElseGet(TimefoldProperties::new);
+ }
+
+ @Override
+ public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
+ IncludeAbstractClassesEntityScanner entityScanner = new IncludeAbstractClassesEntityScanner(this.context);
+ if (!entityScanner.hasSolutionOrEntityClasses()) {
+ LOG.warn(
+ """
+ Skipping Timefold loading because there are no @%s or @%s annotated classes.
+ Maybe your annotated classes are not in a subpackage of your @%s annotated class's package.
+ Maybe move your planning solution and entity classes to your application class's (sub)package (or use @%s)."""
+ .formatted(PlanningSolution.class.getSimpleName(), PlanningEntity.class.getSimpleName(),
+ SpringBootApplication.class.getSimpleName(), EntityScan.class.getSimpleName()));
+ beanFactory.registerSingleton(DEFAULT_SOLVER_CONFIG_NAME, new SolverConfig(beanClassLoader));
+ return;
+ }
+ Map<String, SolverConfig> solverConfigMap = new HashMap<>();
+ // Step 1 - create all SolverConfig
+ // If the config map is empty, we build the config using the default solver name
+ if (timefoldProperties.getSolver() == null || timefoldProperties.getSolver().isEmpty()) {
+ solverConfigMap.put(TimefoldProperties.DEFAULT_SOLVER_NAME,
+ createSolverConfig(timefoldProperties, TimefoldProperties.DEFAULT_SOLVER_NAME));
+ } else {
+ timefoldProperties.getSolver().keySet()
+ .forEach(solverName -> solverConfigMap.put(solverName, createSolverConfig(timefoldProperties, solverName)));
+ }
+ // Step 2 - validate all SolverConfig definitions
+ // TODO - Should we assert planning members belongs to a PlanningEntity Quarkus#assertNoMemberAnnotationWithoutClassAnnotation? | I suggest we should have the same behavior in Spring Boot and Quarkus, where possible.
What would be the reasons _not_ to do this here? |
timefold-solver | github_2023 | java | 590 | TimefoldAI | triceo | @@ -64,62 +70,422 @@
@ConditionalOnMissingBean({ SolverConfig.class, SolverFactory.class, ScoreManager.class, SolutionManager.class,
SolverManager.class })
@EnableConfigurationProperties({ TimefoldProperties.class })
-public class TimefoldAutoConfiguration implements BeanClassLoaderAware {
+public class TimefoldAutoConfiguration
+ implements BeanClassLoaderAware, ApplicationContextAware, EnvironmentAware, BeanFactoryPostProcessor {
- private final ApplicationContext context;
- private final TimefoldProperties timefoldProperties;
+ private static final Log LOG = LogFactory.getLog(TimefoldAutoConfiguration.class);
+ private static String DEFAULT_SOLVER_CONFIG_NAME = "getSolverConfig";
+ private ApplicationContext context;
private ClassLoader beanClassLoader;
+ private TimefoldProperties timefoldProperties;
- protected TimefoldAutoConfiguration(ApplicationContext context,
- TimefoldProperties timefoldProperties) {
- this.context = context;
- this.timefoldProperties = timefoldProperties;
+ protected TimefoldAutoConfiguration() {
}
@Override
public void setBeanClassLoader(ClassLoader beanClassLoader) {
this.beanClassLoader = beanClassLoader;
}
- @Bean
- public TimefoldSolverBannerBean getBanner() {
- return new TimefoldSolverBannerBean();
+ @Override
+ public void setApplicationContext(ApplicationContext context) throws BeansException {
+ this.context = context;
}
- @Bean
- @ConditionalOnMissingBean
- public SolverConfig solverConfig() {
- String solverConfigXml = timefoldProperties.getSolverConfigXml();
+ @Override
+ public void setEnvironment(Environment environment) {
+ // postProcessBeanFactory runs before creating any bean, but we need TimefoldProperties. Therefore, we use the
+ // Environment to load the properties
+ BindResult<TimefoldProperties> result = Binder.get(environment).bind("timefold", TimefoldProperties.class);
+ this.timefoldProperties = result.orElseGet(TimefoldProperties::new);
+ }
+
+ @Override
+ public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
+ IncludeAbstractClassesEntityScanner entityScanner = new IncludeAbstractClassesEntityScanner(this.context);
+ if (!entityScanner.hasSolutionOrEntityClasses()) {
+ LOG.warn(
+ """
+ Skipping Timefold loading because there are no @%s or @%s annotated classes.
+ Maybe your annotated classes are not in a subpackage of your @%s annotated class's package.
+ Maybe move your planning solution and entity classes to your application class's (sub)package (or use @%s)."""
+ .formatted(PlanningSolution.class.getSimpleName(), PlanningEntity.class.getSimpleName(),
+ SpringBootApplication.class.getSimpleName(), EntityScan.class.getSimpleName()));
+ beanFactory.registerSingleton(DEFAULT_SOLVER_CONFIG_NAME, new SolverConfig(beanClassLoader));
+ return;
+ }
+ Map<String, SolverConfig> solverConfigMap = new HashMap<>();
+ // Step 1 - create all SolverConfig
+ // If the config map is empty, we build the config using the default solver name
+ if (timefoldProperties.getSolver() == null || timefoldProperties.getSolver().isEmpty()) {
+ solverConfigMap.put(TimefoldProperties.DEFAULT_SOLVER_NAME,
+ createSolverConfig(timefoldProperties, TimefoldProperties.DEFAULT_SOLVER_NAME));
+ } else {
+ timefoldProperties.getSolver().keySet()
+ .forEach(solverName -> solverConfigMap.put(solverName, createSolverConfig(timefoldProperties, solverName)));
+ }
+ // Step 2 - validate all SolverConfig definitions
+ // TODO - Should we assert planning members belongs to a PlanningEntity Quarkus#assertNoMemberAnnotationWithoutClassAnnotation?
+ assertSolverConfigSolutionClasses(entityScanner, solverConfigMap);
+ assertSolverConfigEntityClasses(entityScanner);
+ assertSolverConfigConstraintClasses(entityScanner, solverConfigMap);
+
+ // Step 3 - load all additional information per SolverConfig
+ solverConfigMap.forEach(
+ (solverName, solverConfig) -> loadSolverConfig(entityScanner, timefoldProperties, solverName, solverConfig));
+
+ if (timefoldProperties.getSolver() == null || timefoldProperties.getSolver().size() == 1) {
+ beanFactory.registerSingleton(DEFAULT_SOLVER_CONFIG_NAME, solverConfigMap.values().iterator().next());
+ } else {
+ // Only SolverManager can be injected for multiple solver configurations
+ solverConfigMap.forEach((solverName, solverConfig) -> {
+ SolverFactory<?> solverFactory = SolverFactory.create(solverConfig);
+
+ SolverManagerConfig solverManagerConfig = new SolverManagerConfig();
+ SolverManagerProperties solverManagerProperties = timefoldProperties.getSolverManager();
+ if (solverManagerProperties != null && solverManagerProperties.getParallelSolverCount() != null) {
+ solverManagerConfig.setParallelSolverCount(solverManagerProperties.getParallelSolverCount());
+ }
+ beanFactory.registerSingleton(solverName, SolverManager.create(solverFactory, solverManagerConfig));
+ });
+ }
+ }
+
+ private SolverConfig createSolverConfig(TimefoldProperties timefoldProperties, String solverName) {
+ // 1 - The solver configuration takes precedence over root and default settings
+ Optional<String> solverConfigXml = timefoldProperties.getSolverConfig(solverName)
+ .map(SolverProperties::getSolverConfigXml);
+
+ // 2 - Root settings
+ if (solverConfigXml.isEmpty()) {
+ solverConfigXml = Optional.ofNullable(timefoldProperties.getSolverConfigXml());
+ }
+
SolverConfig solverConfig;
- if (solverConfigXml != null) {
- if (beanClassLoader.getResource(solverConfigXml) == null) {
- throw new IllegalStateException("Invalid timefold.solverConfigXml property (" + solverConfigXml
- + "): that classpath resource does not exist.");
+ if (solverConfigXml.isPresent()) {
+ String solverUrl = solverConfigXml.get();
+ if (beanClassLoader.getResource(solverUrl) == null) {
+ String message =
+ "\"Invalid timefold.solverConfigXml property (%s): that classpath resource does not exist." | Why the quote inside the string? |
timefold-solver | github_2023 | java | 590 | TimefoldAI | triceo | @@ -64,62 +70,422 @@
@ConditionalOnMissingBean({ SolverConfig.class, SolverFactory.class, ScoreManager.class, SolutionManager.class,
SolverManager.class })
@EnableConfigurationProperties({ TimefoldProperties.class })
-public class TimefoldAutoConfiguration implements BeanClassLoaderAware {
+public class TimefoldAutoConfiguration
+ implements BeanClassLoaderAware, ApplicationContextAware, EnvironmentAware, BeanFactoryPostProcessor {
- private final ApplicationContext context;
- private final TimefoldProperties timefoldProperties;
+ private static final Log LOG = LogFactory.getLog(TimefoldAutoConfiguration.class);
+ private static String DEFAULT_SOLVER_CONFIG_NAME = "getSolverConfig";
+ private ApplicationContext context;
private ClassLoader beanClassLoader;
+ private TimefoldProperties timefoldProperties;
- protected TimefoldAutoConfiguration(ApplicationContext context,
- TimefoldProperties timefoldProperties) {
- this.context = context;
- this.timefoldProperties = timefoldProperties;
+ protected TimefoldAutoConfiguration() {
}
@Override
public void setBeanClassLoader(ClassLoader beanClassLoader) {
this.beanClassLoader = beanClassLoader;
}
- @Bean
- public TimefoldSolverBannerBean getBanner() {
- return new TimefoldSolverBannerBean();
+ @Override
+ public void setApplicationContext(ApplicationContext context) throws BeansException {
+ this.context = context;
}
- @Bean
- @ConditionalOnMissingBean
- public SolverConfig solverConfig() {
- String solverConfigXml = timefoldProperties.getSolverConfigXml();
+ @Override
+ public void setEnvironment(Environment environment) {
+ // postProcessBeanFactory runs before creating any bean, but we need TimefoldProperties. Therefore, we use the
+ // Environment to load the properties
+ BindResult<TimefoldProperties> result = Binder.get(environment).bind("timefold", TimefoldProperties.class);
+ this.timefoldProperties = result.orElseGet(TimefoldProperties::new);
+ }
+
+ @Override
+ public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
+ IncludeAbstractClassesEntityScanner entityScanner = new IncludeAbstractClassesEntityScanner(this.context);
+ if (!entityScanner.hasSolutionOrEntityClasses()) {
+ LOG.warn(
+ """
+ Skipping Timefold loading because there are no @%s or @%s annotated classes.
+ Maybe your annotated classes are not in a subpackage of your @%s annotated class's package.
+ Maybe move your planning solution and entity classes to your application class's (sub)package (or use @%s)."""
+ .formatted(PlanningSolution.class.getSimpleName(), PlanningEntity.class.getSimpleName(),
+ SpringBootApplication.class.getSimpleName(), EntityScan.class.getSimpleName()));
+ beanFactory.registerSingleton(DEFAULT_SOLVER_CONFIG_NAME, new SolverConfig(beanClassLoader));
+ return;
+ }
+ Map<String, SolverConfig> solverConfigMap = new HashMap<>();
+ // Step 1 - create all SolverConfig
+ // If the config map is empty, we build the config using the default solver name
+ if (timefoldProperties.getSolver() == null || timefoldProperties.getSolver().isEmpty()) {
+ solverConfigMap.put(TimefoldProperties.DEFAULT_SOLVER_NAME,
+ createSolverConfig(timefoldProperties, TimefoldProperties.DEFAULT_SOLVER_NAME));
+ } else {
+ timefoldProperties.getSolver().keySet()
+ .forEach(solverName -> solverConfigMap.put(solverName, createSolverConfig(timefoldProperties, solverName)));
+ }
+ // Step 2 - validate all SolverConfig definitions
+ // TODO - Should we assert planning members belongs to a PlanningEntity Quarkus#assertNoMemberAnnotationWithoutClassAnnotation?
+ assertSolverConfigSolutionClasses(entityScanner, solverConfigMap);
+ assertSolverConfigEntityClasses(entityScanner);
+ assertSolverConfigConstraintClasses(entityScanner, solverConfigMap);
+
+ // Step 3 - load all additional information per SolverConfig
+ solverConfigMap.forEach(
+ (solverName, solverConfig) -> loadSolverConfig(entityScanner, timefoldProperties, solverName, solverConfig));
+
+ if (timefoldProperties.getSolver() == null || timefoldProperties.getSolver().size() == 1) {
+ beanFactory.registerSingleton(DEFAULT_SOLVER_CONFIG_NAME, solverConfigMap.values().iterator().next());
+ } else {
+ // Only SolverManager can be injected for multiple solver configurations
+ solverConfigMap.forEach((solverName, solverConfig) -> {
+ SolverFactory<?> solverFactory = SolverFactory.create(solverConfig);
+
+ SolverManagerConfig solverManagerConfig = new SolverManagerConfig();
+ SolverManagerProperties solverManagerProperties = timefoldProperties.getSolverManager();
+ if (solverManagerProperties != null && solverManagerProperties.getParallelSolverCount() != null) {
+ solverManagerConfig.setParallelSolverCount(solverManagerProperties.getParallelSolverCount());
+ }
+ beanFactory.registerSingleton(solverName, SolverManager.create(solverFactory, solverManagerConfig));
+ });
+ }
+ }
+
+ private SolverConfig createSolverConfig(TimefoldProperties timefoldProperties, String solverName) {
+ // 1 - The solver configuration takes precedence over root and default settings
+ Optional<String> solverConfigXml = timefoldProperties.getSolverConfig(solverName)
+ .map(SolverProperties::getSolverConfigXml);
+
+ // 2 - Root settings
+ if (solverConfigXml.isEmpty()) {
+ solverConfigXml = Optional.ofNullable(timefoldProperties.getSolverConfigXml());
+ }
+
SolverConfig solverConfig;
- if (solverConfigXml != null) {
- if (beanClassLoader.getResource(solverConfigXml) == null) {
- throw new IllegalStateException("Invalid timefold.solverConfigXml property (" + solverConfigXml
- + "): that classpath resource does not exist.");
+ if (solverConfigXml.isPresent()) {
+ String solverUrl = solverConfigXml.get();
+ if (beanClassLoader.getResource(solverUrl) == null) {
+ String message =
+ "\"Invalid timefold.solverConfigXml property (%s): that classpath resource does not exist."
+ .formatted(solverUrl);
+ if (!solverName.equals(TimefoldProperties.DEFAULT_SOLVER_NAME)) {
+ message =
+ "Invalid timefold.solver.\"%s\".solverConfigXML property (%s): that classpath resource does not exist."
+ .formatted(solverName, solverUrl);
+ }
+ throw new IllegalStateException(message);
}
- solverConfig = SolverConfig.createFromXmlResource(solverConfigXml, beanClassLoader);
+ solverConfig = SolverConfig.createFromXmlResource(solverUrl);
} else if (beanClassLoader.getResource(TimefoldProperties.DEFAULT_SOLVER_CONFIG_URL) != null) {
+ // 3 - Default file URL
solverConfig = SolverConfig.createFromXmlResource(
- TimefoldProperties.DEFAULT_SOLVER_CONFIG_URL, beanClassLoader);
+ TimefoldProperties.DEFAULT_SOLVER_CONFIG_URL);
} else {
solverConfig = new SolverConfig(beanClassLoader);
}
- if (!applySolverProperties(solverConfig)) {
- return null;
- }
return solverConfig;
}
+ private void loadSolverConfig(IncludeAbstractClassesEntityScanner entityScanner, TimefoldProperties timefoldProperties,
+ String solverName, SolverConfig solverConfig) {
+ if (solverConfig.getSolutionClass() == null) {
+ solverConfig.setSolutionClass(entityScanner.findFirstSolutionClass());
+ }
+ if (solverConfig.getEntityClassList() == null) {
+ solverConfig.setEntityClassList(entityScanner.findEntityClassList());
+ } else {
+ long entityClassCount = solverConfig.getEntityClassList().stream()
+ .filter(Objects::nonNull)
+ .count();
+ if (entityClassCount == 0L) {
+ throw new IllegalStateException(
+ """
+ The solverConfig's entityClassList (%s) does not contain any non-null entries.
+ Maybe the classes listed there do not actually exist and therefore deserialization turned them to null?"""
+ .formatted(solverConfig.getEntityClassList().stream().map(Class::getSimpleName)
+ .collect(joining(", "))));
+ }
+ }
+ applyScoreDirectorFactoryProperties(entityScanner, solverConfig);
+ Optional<SolverProperties> solverProperties = timefoldProperties.getSolverConfig(solverName);
+ if (solverProperties.isPresent()) {
+ if (solverProperties.get().getEnvironmentMode() != null) {
+ solverConfig.setEnvironmentMode(solverProperties.get().getEnvironmentMode());
+ }
+ if (solverProperties.get().getDomainAccessType() != null) {
+ solverConfig.setDomainAccessType(solverProperties.get().getDomainAccessType());
+ }
+ if (solverProperties.get().getDaemon() != null) {
+ solverConfig.setDaemon(solverProperties.get().getDaemon());
+ }
+ if (solverProperties.get().getMoveThreadCount() != null) {
+ solverConfig.setMoveThreadCount(solverProperties.get().getMoveThreadCount());
+ }
+ applyTerminationProperties(solverConfig, solverProperties.get().getTermination());
+ }
+ }
+
+ protected void applyScoreDirectorFactoryProperties(IncludeAbstractClassesEntityScanner entityScanner,
+ SolverConfig solverConfig) {
+ if (solverConfig.getScoreDirectorFactoryConfig() == null) {
+ solverConfig.setScoreDirectorFactoryConfig(defaultScoreDirectoryFactoryConfig(entityScanner));
+ }
+ }
+
+ private ScoreDirectorFactoryConfig defaultScoreDirectoryFactoryConfig(IncludeAbstractClassesEntityScanner entityScanner) {
+ ScoreDirectorFactoryConfig scoreDirectorFactoryConfig = new ScoreDirectorFactoryConfig();
+ scoreDirectorFactoryConfig
+ .setEasyScoreCalculatorClass(entityScanner.findFirstImplementingClass(EasyScoreCalculator.class));
+ scoreDirectorFactoryConfig
+ .setConstraintProviderClass(entityScanner.findFirstImplementingClass(ConstraintProvider.class));
+ scoreDirectorFactoryConfig
+ .setIncrementalScoreCalculatorClass(entityScanner.findFirstImplementingClass(IncrementalScoreCalculator.class));
+
+ return scoreDirectorFactoryConfig;
+ }
+
+ static void applyTerminationProperties(SolverConfig solverConfig, TerminationProperties terminationProperties) {
+ TerminationConfig terminationConfig = solverConfig.getTerminationConfig();
+ if (terminationConfig == null) {
+ terminationConfig = new TerminationConfig();
+ solverConfig.setTerminationConfig(terminationConfig);
+ }
+ if (terminationProperties != null) {
+ if (terminationProperties.getSpentLimit() != null) {
+ terminationConfig.overwriteSpentLimit(terminationProperties.getSpentLimit());
+ }
+ if (terminationProperties.getUnimprovedSpentLimit() != null) {
+ terminationConfig.overwriteUnimprovedSpentLimit(terminationProperties.getUnimprovedSpentLimit());
+ }
+ if (terminationProperties.getBestScoreLimit() != null) {
+ terminationConfig.setBestScoreLimit(terminationProperties.getBestScoreLimit());
+ }
+ }
+ }
+
+ private void failInjectionWithMultipleSolvers(String resourceName) {
+ if (timefoldProperties.getSolver() != null && timefoldProperties.getSolver().size() > 1) {
+ throw new BeanCreationException(
+ "No qualifying bean of type '%s' available".formatted(resourceName));
+ }
+ }
+
+ private void assertSolverConfigSolutionClasses(IncludeAbstractClassesEntityScanner entityScanner,
+ Map<String, SolverConfig> solverConfigMap) {
+ // Validate the solution class
+ // No solution class
+ String emptyListErrorMessage = """
+ No classes were found with a @%s annotation.
+ Maybe your @%s annotated class is not in a subpackage of your @%s annotated class's package.
+ Maybe move your planning solution class to your application class's (sub)package (or use @%s).""".formatted(
+ PlanningSolution.class.getSimpleName(), PlanningSolution.class.getSimpleName(),
+ SpringBootApplication.class.getSimpleName(), EntityScan.class.getSimpleName());
+ assertEmptyInstances(entityScanner, PlanningSolution.class, emptyListErrorMessage);
+ // Multiple classes and single solver
+ try {
+ Set<Class<?>> annotationInstanceSet = entityScanner.scan(PlanningSolution.class);
+ if (annotationInstanceSet.size() > 1 && solverConfigMap.size() == 1) {
+ throw new IllegalStateException(
+ "Multiple classes ([%s]) found in the classpath with a @%s annotation.".formatted(
+ annotationInstanceSet.stream().map(Class::getSimpleName).collect(joining(", ")),
+ PlanningSolution.class.getSimpleName()));
+ }
+ // Multiple classes and at least one solver config does not specify the solution class
+ List<String> solverConfigWithoutSolutionClassList = solverConfigMap.entrySet().stream()
+ .filter(e -> e.getValue().getSolutionClass() == null)
+ .map(Map.Entry::getKey)
+ .toList();
+ if (annotationInstanceSet.size() > 1 && !solverConfigWithoutSolutionClassList.isEmpty()) {
+ throw new IllegalStateException(
+ """
+ Some solver configs (%s) don't specify a %s class, yet there are multiple available (%s) on the classpath.
+ Maybe set the XML config file to the related solver configs, or add the missing solution classes to the XML files,
+ or remove the unnecessary solution classes from the classpath."""
+ .formatted(String.join(", ", solverConfigWithoutSolutionClassList),
+ PlanningSolution.class.getSimpleName(),
+ annotationInstanceSet.stream().map(Class::getSimpleName).collect(joining(", "))));
+ }
+ // Unused solution classes
+ List<String> unusedSolutionClassList = annotationInstanceSet.stream()
+ .map(Class::getName)
+ .filter(planningClassName -> solverConfigMap.values().stream().filter(c -> c.getSolutionClass() != null)
+ .noneMatch(c -> c.getSolutionClass().getName().equals(planningClassName)))
+ .toList();
+ if (annotationInstanceSet.size() > 1 && !unusedSolutionClassList.isEmpty()) {
+ throw new IllegalStateException(
+ "Unused classes ([%s]) found with a @%s annotation.".formatted(
+ String.join(", ", unusedSolutionClassList),
+ PlanningSolution.class.getSimpleName()));
+ }
+ // TODO - Should we validate target types?
+ } catch (ClassNotFoundException e) {
+ throw new IllegalStateException(
+ "Scanning for @%s annotations failed.".formatted(PlanningSolution.class.getSimpleName()), e);
+ }
+ }
+
+ private void assertSolverConfigEntityClasses(IncludeAbstractClassesEntityScanner entityScanner) {
+ // No Entity class
+ String emptyListErrorMessage = """
+ No classes were found with a @%s annotation.
+ Maybe your @%s annotated class(es) are not in a subpackage of your @%s annotated class's package.
+ Maybe move your planning entity classes to your application class's (sub)package(or use @%s)."""
+ .formatted(
+ PlanningEntity.class.getSimpleName(), PlanningEntity.class.getSimpleName(),
+ SpringBootApplication.class.getSimpleName(), EntityScan.class.getSimpleName());
+ assertEmptyInstances(entityScanner, PlanningEntity.class, emptyListErrorMessage);
+ // TODO - Should we validate target types? | Let's not leave the TODO here, let's fix it instead.
What would be the pros and cons?
What does Quarkus do? |
timefold-solver | github_2023 | java | 590 | TimefoldAI | triceo | @@ -1,12 +1,24 @@
package ai.timefold.solver.spring.boot.autoconfigure.config;
+import java.util.Map;
+import java.util.Set;
+
import ai.timefold.solver.core.api.domain.common.DomainAccessType;
import ai.timefold.solver.core.api.score.stream.ConstraintStreamImplType;
import ai.timefold.solver.core.config.solver.EnvironmentMode;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
public class SolverProperties {
+ public static final Set<String> VALID_FIELD_NAMES_SET =
+ Set.of("solver-config-xml", "environment-mode", "daemon", "move-thread-count", "domain-access-type",
+ "constraint-stream-impl-type", "termination"); | It is a good idea to have a constant for this.
However, I'd go further and have constants even for the names themselves - that way, you don't need to repeat them later in this class. |
timefold-solver | github_2023 | others | 687 | TimefoldAI | triceo | @@ -50,6 +50,12 @@ Defaults to `REFLECTION`.
The other possible value is `GIZMO`.
endif::[]
+{property_prefix}timefold.solver.{solver_name_prefix}nearby-distance-meter-class::
+Enable the xref:enterprise-edition/enterprise-edition.adoc#nearbySelection[Nearby Selection] quick configuration.
+If the Nearby Selection distance meter class is specified,
+the solver evaluates the available move selectors
+and autoconfigures the Nearby Selection feature for the compatible move selectors. | ```suggestion
and automatically enables Nearby Selection for the compatible move selectors.
``` |
timefold-solver | github_2023 | java | 687 | TimefoldAI | triceo | @@ -719,6 +720,27 @@ private void applySolverProperties(IndexView indexView, String solverName, Solve
if (solverConfig.getDomainAccessType() == null) {
solverConfig.setDomainAccessType(DomainAccessType.GIZMO);
}
+
+ Optional<String> nearbyDistanceMeterClass =
+ timefoldBuildTimeConfig.getSolverConfig(solverName)
+ .flatMap(SolverBuildTimeConfig::nearbyDistanceMeterClass);
+ if (nearbyDistanceMeterClass.isPresent()) { | `Optional` has `ifPresent(...)` for just this use case. |
timefold-solver | github_2023 | java | 687 | TimefoldAI | triceo | @@ -60,6 +60,11 @@ public interface SolverBuildTimeConfig {
*/
TerminationRuntimeConfig termination();
+ /**
+ * Enable the Nearby Selection quick configuration.
+ */
+ Optional<String> nearbyDistanceMeterClass(); | Shouldn't this return `Class<? extends NearbyDistanceMeter>` directly? The other properties also don't return `String`. |
timefold-solver | github_2023 | java | 687 | TimefoldAI | triceo | @@ -52,7 +55,7 @@ void solverProperties() {
assertEquals(DomainAccessType.REFLECTION, solverConfig.getDomainAccessType());
assertEquals(null,
solverConfig.getScoreDirectorFactoryConfig().getConstraintStreamImplType());
-
+ assertNotNull(solverConfig.getNearbyDistanceMeterClass()); | I obviously didn't notice before, but we use AssertJ, not JUnit assertions. |
timefold-solver | github_2023 | java | 687 | TimefoldAI | triceo | @@ -39,30 +40,27 @@ class TimefoldBenchmarkProcessorInheritedSolverBenchmarkTest {
@Test
void inheritClassesFromSolverConfig() {
- Assertions.assertEquals(TestdataQuarkusSolution.class, solverConfig.getSolutionClass());
- Assertions.assertEquals(2, solverConfig.getEntityClassList().size());
- Assertions.assertTrue(solverConfig.getEntityClassList().contains(TestdataQuarkusEntity.class));
- Assertions.assertTrue(solverConfig.getEntityClassList().contains(TestdataQuarkusOtherEntity.class));
- Assertions.assertEquals(5, plannerBenchmarkConfig.getInheritedSolverBenchmarkConfig()
- .getSolverConfig().getTerminationConfig().getMillisecondsSpentLimit());
- Assertions.assertEquals(List.of(TestdataQuarkusEntity.class),
- plannerBenchmarkConfig.getInheritedSolverBenchmarkConfig().getSolverConfig().getEntityClassList());
+ assertThat(solverConfig.getSolutionClass()).isEqualTo(TestdataQuarkusSolution.class);
+ assertThat(solverConfig.getEntityClassList()).hasSize(2);
+ assertThat(solverConfig.getEntityClassList()).contains(TestdataQuarkusEntity.class);
+ assertThat(solverConfig.getEntityClassList()).contains(TestdataQuarkusOtherEntity.class); | `containsExactly` (and similar methods) is your friend. |
timefold-solver | github_2023 | java | 687 | TimefoldAI | triceo | @@ -39,30 +40,27 @@ class TimefoldBenchmarkProcessorInheritedSolverBenchmarkTest {
@Test
void inheritClassesFromSolverConfig() {
- Assertions.assertEquals(TestdataQuarkusSolution.class, solverConfig.getSolutionClass());
- Assertions.assertEquals(2, solverConfig.getEntityClassList().size());
- Assertions.assertTrue(solverConfig.getEntityClassList().contains(TestdataQuarkusEntity.class));
- Assertions.assertTrue(solverConfig.getEntityClassList().contains(TestdataQuarkusOtherEntity.class));
- Assertions.assertEquals(5, plannerBenchmarkConfig.getInheritedSolverBenchmarkConfig()
- .getSolverConfig().getTerminationConfig().getMillisecondsSpentLimit());
- Assertions.assertEquals(List.of(TestdataQuarkusEntity.class),
- plannerBenchmarkConfig.getInheritedSolverBenchmarkConfig().getSolverConfig().getEntityClassList());
+ assertThat(solverConfig.getSolutionClass()).isEqualTo(TestdataQuarkusSolution.class);
+ assertThat(solverConfig.getEntityClassList()).hasSize(2);
+ assertThat(solverConfig.getEntityClassList()).contains(TestdataQuarkusEntity.class);
+ assertThat(solverConfig.getEntityClassList()).contains(TestdataQuarkusOtherEntity.class);
+ assertThat(plannerBenchmarkConfig.getInheritedSolverBenchmarkConfig()
+ .getSolverConfig().getTerminationConfig().getMillisecondsSpentLimit()).isEqualTo(5);
+ assertThat(plannerBenchmarkConfig.getInheritedSolverBenchmarkConfig().getSolverConfig().getEntityClassList())
+ .isEqualTo(List.of(TestdataQuarkusEntity.class)); | Also easier done with `containsExactly`. |
timefold-solver | github_2023 | java | 684 | TimefoldAI | triceo | @@ -280,4 +282,33 @@ private void inheritCommon(MoveSelectorConfig<?> inheritedConfig) {
fixedProbabilityWeight, inheritedConfig.getFixedProbabilityWeight());
}
+ protected String addRandomSuffix(String name, Random random) { | Should be `static`, no? |
timefold-solver | github_2023 | java | 684 | TimefoldAI | triceo | @@ -280,4 +282,33 @@ private void inheritCommon(MoveSelectorConfig<?> inheritedConfig) {
fixedProbabilityWeight, inheritedConfig.getFixedProbabilityWeight());
}
+ protected String addRandomSuffix(String name, Random random) {
+ StringBuilder value = new StringBuilder(name);
+ value.append("-");
+ random.ints(97, 122) // ['a', 'z']
+ .limit(4) // 4 letters
+ .forEach(value::appendCodePoint);
+ return value.toString();
+ }
+
+ /**
+ * Check if the selector factory accepts Nearby selection autoconfiguration.
+ *
+ * @return false by default
+ */
+ public boolean acceptNearbySelectionAutoConfiguration() {
+ return false;
+ } | I'd consider working without this. You can call `enableNearbySelection(...)`, which by default returns the config unchanged.
(I'm driven by eliminating boilerplate code; the selectors already have plenty without adding more.) |
timefold-solver | github_2023 | java | 684 | TimefoldAI | triceo | @@ -280,4 +282,33 @@ private void inheritCommon(MoveSelectorConfig<?> inheritedConfig) {
fixedProbabilityWeight, inheritedConfig.getFixedProbabilityWeight());
}
+ protected String addRandomSuffix(String name, Random random) {
+ StringBuilder value = new StringBuilder(name);
+ value.append("-");
+ random.ints(97, 122) // ['a', 'z']
+ .limit(4) // 4 letters
+ .forEach(value::appendCodePoint);
+ return value.toString();
+ }
+
+ /**
+ * Check if the selector factory accepts Nearby selection autoconfiguration.
+ *
+ * @return false by default
+ */
+ public boolean acceptNearbySelectionAutoConfiguration() {
+ return false;
+ }
+
+ /**
+ * Enables the Nearby Selection autoconfiguration.
+ *
+ * @return new instance with the Nearby Selection settings properly configured
+ */
+ public Config_ enableNearbySelection(Class<? extends NearbyDistanceMeter<?, ?>> distanceMeter, Random random) {
+ throw new UnsupportedOperationException();
+ }
+
+ public abstract boolean hasNearbySelectionConfig(); | Maybe this could return `false` by default, so that you only need to override it when `true` needs to be returned? |
timefold-solver | github_2023 | java | 684 | TimefoldAI | triceo | @@ -154,6 +154,18 @@ public void visitReferencedClasses(Consumer<Class<?>> classVisitor) {
}
}
+ @Override
+ public boolean hasNearbySelectionConfig() {
+ return (subListSelectorConfig != null && ((subListSelectorConfig.getNearbySelectionConfig() != null) | This condition is kinda insane.
Maybe simplify it by introducing boolean variables for its components?
The code will be longer, but people will actually be able to understand what the condition does.
(There are similar conditions elsewhere in this PR.)
|
timefold-solver | github_2023 | java | 684 | TimefoldAI | triceo | @@ -22,8 +23,24 @@ public UnionMoveSelectorFactory(UnionMoveSelectorConfig moveSelectorConfig) {
@Override
protected MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy,
SelectionCacheType minimumCacheType, boolean randomSelection) {
- List<MoveSelector<Solution_>> moveSelectorList = buildInnerMoveSelectors(config.getMoveSelectorList(),
- configPolicy, minimumCacheType, randomSelection);
+ List<MoveSelectorConfig> moveSelectorConfigList = new LinkedList<>(config.getMoveSelectorList());
+ if (configPolicy.getNearbyDistanceMeterClass() != null) {
+ for (MoveSelectorConfig selectorConfig : config.getMoveSelectorList().stream()
+ .filter(MoveSelectorConfig::acceptNearbySelectionAutoConfiguration).toList()) {
+ if (selectorConfig.hasNearbySelectionConfig()) {
+ throw new IllegalArgumentException( | Maybe explain _why_ in a comment?
The problem with cartesian is that if there are two selectors, it will have A×B moves. So if there are four selectors (2 non-nearby + 2 nearby), it will be A×B×C×D moves.
Whereas union will always be A+B+C+D.
|
timefold-solver | github_2023 | java | 684 | TimefoldAI | triceo | @@ -22,8 +23,24 @@ public UnionMoveSelectorFactory(UnionMoveSelectorConfig moveSelectorConfig) {
@Override
protected MoveSelector<Solution_> buildBaseMoveSelector(HeuristicConfigPolicy<Solution_> configPolicy,
SelectionCacheType minimumCacheType, boolean randomSelection) {
- List<MoveSelector<Solution_>> moveSelectorList = buildInnerMoveSelectors(config.getMoveSelectorList(),
- configPolicy, minimumCacheType, randomSelection);
+ List<MoveSelectorConfig> moveSelectorConfigList = new LinkedList<>(config.getMoveSelectorList());
+ if (configPolicy.getNearbyDistanceMeterClass() != null) {
+ for (MoveSelectorConfig selectorConfig : config.getMoveSelectorList().stream()
+ .filter(MoveSelectorConfig::acceptNearbySelectionAutoConfiguration).toList()) {
+ if (selectorConfig.hasNearbySelectionConfig()) {
+ throw new IllegalArgumentException(
+ """
+ The selector configuration (%s) already includes the Nearby Selection setting, making it incompatible with the top-level property nearbyDistanceMeterClass (%s).
+ Remove the Nearby setting from the selector configuration or remove the top-level nearbyDistanceMeterClass."""
+ .formatted(selectorConfig, configPolicy.getNearbyDistanceMeterClass()));
+ }
+ // Add a new configuration with Nearby Selection enabled
+ moveSelectorConfigList.add(selectorConfig.enableNearbySelection(configPolicy.getNearbyDistanceMeterClass(),
+ configPolicy.getRandom()));
+ }
+ }
+ List<MoveSelector<Solution_>> moveSelectorList = | Cautious use of `var` wouldn't hurt here, I think.
The name already says `list`. |
timefold-solver | github_2023 | java | 684 | TimefoldAI | triceo | @@ -0,0 +1,355 @@
+package ai.timefold.solver.core.config.heuristic.selector.move;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.List;
+import java.util.Random;
+
+import ai.timefold.solver.core.config.heuristic.selector.common.SelectionOrder;
+import ai.timefold.solver.core.config.heuristic.selector.entity.EntitySelectorConfig;
+import ai.timefold.solver.core.config.heuristic.selector.move.composite.CartesianProductMoveSelectorConfig;
+import ai.timefold.solver.core.config.heuristic.selector.move.composite.UnionMoveSelectorConfig;
+import ai.timefold.solver.core.config.heuristic.selector.move.factory.MoveIteratorFactoryConfig;
+import ai.timefold.solver.core.config.heuristic.selector.move.factory.MoveListFactoryConfig;
+import ai.timefold.solver.core.config.heuristic.selector.move.generic.ChangeMoveSelectorConfig;
+import ai.timefold.solver.core.config.heuristic.selector.move.generic.PillarChangeMoveSelectorConfig;
+import ai.timefold.solver.core.config.heuristic.selector.move.generic.PillarSwapMoveSelectorConfig;
+import ai.timefold.solver.core.config.heuristic.selector.move.generic.SwapMoveSelectorConfig;
+import ai.timefold.solver.core.config.heuristic.selector.move.generic.chained.KOptMoveSelectorConfig;
+import ai.timefold.solver.core.config.heuristic.selector.move.generic.chained.SubChainChangeMoveSelectorConfig;
+import ai.timefold.solver.core.config.heuristic.selector.move.generic.chained.SubChainSwapMoveSelectorConfig;
+import ai.timefold.solver.core.config.heuristic.selector.move.generic.chained.TailChainSwapMoveSelectorConfig;
+import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.ListChangeMoveSelectorConfig;
+import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.ListSwapMoveSelectorConfig;
+import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.SubListChangeMoveSelectorConfig;
+import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.SubListSwapMoveSelectorConfig;
+import ai.timefold.solver.core.config.heuristic.selector.move.generic.list.kopt.KOptListMoveSelectorConfig;
+import ai.timefold.solver.core.config.heuristic.selector.value.ValueSelectorConfig;
+import ai.timefold.solver.core.impl.testdata.domain.list.TestDistanceMeter;
+
+import org.junit.jupiter.api.Test;
+
+class MoveSelectorConfigTest {
+
+ @Test
+ void assertEnableNearbyForChangeMoveSelectorConfig() {
+ // Default configuration
+ ChangeMoveSelectorConfig config = new ChangeMoveSelectorConfig();
+ assertFalse(config.hasNearbySelectionConfig()); | We use AssertJ, not JUnit assertions. |
timefold-solver | github_2023 | java | 684 | TimefoldAI | triceo | @@ -162,6 +166,31 @@ public void visitReferencedClasses(Consumer<Class<?>> classVisitor) {
classVisitor.accept(selectorProbabilityWeightFactoryClass);
}
+ @Override
+ public UnionMoveSelectorConfig enableNearbySelection(Class<? extends NearbyDistanceMeter<?, ?>> distanceMeter,
+ Random random) {
+ UnionMoveSelectorConfig nearbyConfig = copyConfig();
+ List<MoveSelectorConfig> updatedMoveSelectorList = new LinkedList<>();
+ for (NearbyAutoConfigurationMoveSelectorConfig<?> selectorConfig : moveSelectorConfigList.stream()
+ .filter(s -> NearbyAutoConfigurationMoveSelectorConfig.class.isAssignableFrom(s.getClass()))
+ .map(s -> (NearbyAutoConfigurationMoveSelectorConfig<?>) s).toList()) { | Id argue that the following would read better, also coincidentally doesn't need to create an extra list or iterate twice:
for (... all configs ...) {
if (not nearby) {
continue;
}
...
}
Also, the `selectorConfig` variable is another nice use of `var` - all the necessary context is already there. |
timefold-solver | github_2023 | others | 726 | TimefoldAI | triceo | @@ -10,7 +10,7 @@ Assign each conference talk to a timeslot and a room, after the talks have been
image::use-cases-and-examples/conference-scheduling/conferenceSchedulingMilestonesTimeline.png[align="center"] | I think this entire adoc file can disappear entirely. It is a description of an example which we no longer have. (In fact, I will be removing the entire "use cases and examples" chapter very soon.) |
timefold-solver | github_2023 | java | 659 | TimefoldAI | triceo | @@ -32,7 +32,8 @@ protected TriFunction<A, B, Score_, ConstraintJustification> getJustificationMap
public <ConstraintJustification_ extends ConstraintJustification> BiConstraintBuilder<A, B, Score_> justifyWith(
TriFunction<A, B, Score_, ConstraintJustification_> justificationMapping) {
if (this.justificationMapping != null) {
- throw new IllegalStateException("Justification mapping already set (" + justificationMapping + ").");
+ throw new IllegalStateException("Justification mapping already set (" + justificationMapping | Please convert to the new convention, using multi-line strings and placeholders. |
timefold-solver | github_2023 | java | 659 | TimefoldAI | triceo | @@ -47,7 +48,8 @@ protected BiFunction<A, B, Collection<Object>> getIndictedObjectsMapping() {
@Override
public BiConstraintBuilder<A, B, Score_> indictWith(BiFunction<A, B, Collection<Object>> indictedObjectsMapping) {
if (this.indictedObjectsMapping != null) {
- throw new IllegalStateException("Indicted objects' mapping already set (" + indictedObjectsMapping + ").");
+ throw new IllegalStateException("Indicted objects' mapping already set (" + indictedObjectsMapping | Dtto. |
timefold-solver | github_2023 | java | 659 | TimefoldAI | triceo | @@ -32,7 +32,8 @@ protected PentaFunction<A, B, C, D, Score_, ConstraintJustification> getJustific
public <ConstraintJustification_ extends ConstraintJustification> QuadConstraintBuilder<A, B, C, D, Score_> justifyWith(
PentaFunction<A, B, C, D, Score_, ConstraintJustification_> justificationMapping) {
if (this.justificationMapping != null) {
- throw new IllegalStateException("Justification mapping already set (" + justificationMapping + ").");
+ throw new IllegalStateException("Justification mapping already set (" + justificationMapping
+ + ").\nMaybe the constraint calls justifyWith() twice?"); | Please convert to the new convention, using multi-line strings and placeholders. |
timefold-solver | github_2023 | java | 659 | TimefoldAI | triceo | @@ -48,7 +49,8 @@ protected QuadFunction<A, B, C, D, Collection<Object>> getIndictedObjectsMapping
public QuadConstraintBuilder<A, B, C, D, Score_>
indictWith(QuadFunction<A, B, C, D, Collection<Object>> indictedObjectsMapping) {
if (this.indictedObjectsMapping != null) {
- throw new IllegalStateException("Indicted objects' mapping already set (" + indictedObjectsMapping + ").");
+ throw new IllegalStateException("Indicted objects' mapping already set (" + indictedObjectsMapping | Dtto. |
timefold-solver | github_2023 | java | 659 | TimefoldAI | triceo | @@ -32,7 +32,8 @@ protected QuadFunction<A, B, C, Score_, ConstraintJustification> getJustificatio
public <ConstraintJustification_ extends ConstraintJustification> TriConstraintBuilder<A, B, C, Score_> justifyWith(
QuadFunction<A, B, C, Score_, ConstraintJustification_> justificationMapping) {
if (this.justificationMapping != null) {
- throw new IllegalStateException("Justification mapping already set (" + justificationMapping + ").");
+ throw new IllegalStateException("Justification mapping already set (" + justificationMapping | Dtto. |
timefold-solver | github_2023 | java | 659 | TimefoldAI | triceo | @@ -47,7 +48,8 @@ protected TriFunction<A, B, C, Collection<Object>> getIndictedObjectsMapping() {
@Override
public TriConstraintBuilder<A, B, C, Score_> indictWith(TriFunction<A, B, C, Collection<Object>> indictedObjectsMapping) {
if (this.indictedObjectsMapping != null) {
- throw new IllegalStateException("Indicted objects' mapping already set (" + indictedObjectsMapping + ").");
+ throw new IllegalStateException("Indicted objects' mapping already set (" + indictedObjectsMapping
+ + ").\nMaybe the constraint calls indictWith() twice?"); | Dtto. |
timefold-solver | github_2023 | java | 659 | TimefoldAI | triceo | @@ -32,7 +32,8 @@ protected BiFunction<A, Score_, ConstraintJustification> getJustificationMapping
public <ConstraintJustification_ extends ConstraintJustification> UniConstraintBuilder<A, Score_> justifyWith(
BiFunction<A, Score_, ConstraintJustification_> justificationMapping) {
if (this.justificationMapping != null) {
- throw new IllegalStateException("Justification mapping already set (" + justificationMapping + ").");
+ throw new IllegalStateException("Justification mapping already set (" + justificationMapping | Dtto. |
timefold-solver | github_2023 | java | 659 | TimefoldAI | triceo | @@ -47,7 +48,8 @@ protected Function<A, Collection<Object>> getIndictedObjectsMapping() {
@Override
public UniConstraintBuilder<A, Score_> indictWith(Function<A, Collection<Object>> indictedObjectsMapping) {
if (this.indictedObjectsMapping != null) {
- throw new IllegalStateException("Indicted objects' mapping already set (" + indictedObjectsMapping + ").");
+ throw new IllegalStateException("Indicted objects' mapping already set (" + indictedObjectsMapping | Dtto. |
timefold-solver | github_2023 | java | 659 | TimefoldAI | triceo | @@ -104,6 +125,17 @@ private void validateMatchWeighTotal(Number matchWeightTotal) {
}
}
+ private void validateJustification(ConstraintJustification... justifications) {
+ Objects.requireNonNull(justifications, "The justification must be not null.");
+ }
+
+ private void validateIndictments(Object[] indictments) {
+ Objects.requireNonNull(indictments, "The indictments must be not null.");
+ if (indictments.length == 0) { | Arguably, this should not be here. What if the user decided to indict with no indictments? We should be able to test for that. |
timefold-solver | github_2023 | java | 659 | TimefoldAI | triceo | @@ -135,6 +167,65 @@ private void assertImpact(ScoreImpactType scoreImpactType, Number matchWeightTot
throw new AssertionError(assertionMessage);
}
+ private void assertJustification(ConstraintJustification justification, String message) {
+ if (constraintJustificationCollection.isEmpty()) {
+ throw new IllegalStateException(
+ "Invalid state: expecting one justification for the constraint, and there is none.");
+ }
+ // No match
+ if (constraintJustificationCollection.stream()
+ .noneMatch(c -> justification.getClass().isAssignableFrom(c.getClass()))) {
+ String assertionMessage = buildAssertionErrorMessage("No match", justification,
+ constraintJustificationCollection.stream().findFirst().get(), message);
+ throw new AssertionError(assertionMessage);
+ }
+ // Test invalid match
+ if (assertEquality(justification, constraintJustificationCollection)) {
+ return;
+ }
+ String assertionMessage = buildAssertionErrorMessage(constraint.getConstraintRef().constraintId(), justification,
+ constraintJustificationCollection.stream().findFirst().get(), message);
+ throw new AssertionError(assertionMessage);
+ }
+
+ private void assertIndictments(String message, Object... indictments) {
+ if (indictmentCollection.isEmpty()) {
+ throw new IllegalStateException(
+ "Invalid state: expecting at least one indictment for the constraint, and there is none.");
+ }
+ List<Object> noneMatchedList = new LinkedList<>();
+ List<Object> invalidMatchList = new LinkedList<>();
+ for (Object indictment : indictments) {
+ // No match
+ if (indictmentCollection.stream().map(Indictment::getIndictedObject)
+ .noneMatch(i -> indictment.getClass().isAssignableFrom(i.getClass()))) {
+ noneMatchedList.add(indictment);
+ continue;
+ }
+ // Test invalid match
+ if (!assertEquality(indictment, indictmentCollection.stream().map(Indictment::getIndictedObject).toList())) {
+ invalidMatchList.add(indictment);
+ }
+ }
+ if (noneMatchedList.isEmpty() && invalidMatchList.isEmpty()) {
+ return;
+ }
+ String assertionMessage = buildAssertionErrorMessage(constraint.getConstraintRef().constraintId(), noneMatchedList,
+ invalidMatchList, indictmentCollection, message);
+ throw new AssertionError(assertionMessage);
+ }
+
+ private boolean assertEquality(Object target, Collection<?> otherList) { | Hmm, I think I didn't think this through.
A constraint can trigger multiple matches, therefore there may be multiple justifications. Therefore the user must be able to provide _all_ justifications that they expect to be there. So the code constraint verifier `justifiesWith(...)` needs to be a vararg. |
timefold-solver | github_2023 | java | 659 | TimefoldAI | triceo | @@ -32,7 +32,9 @@ protected TriFunction<A, B, Score_, ConstraintJustification> getJustificationMap
public <ConstraintJustification_ extends ConstraintJustification> BiConstraintBuilder<A, B, Score_> justifyWith(
TriFunction<A, B, Score_, ConstraintJustification_> justificationMapping) {
if (this.justificationMapping != null) {
- throw new IllegalStateException("Justification mapping already set (" + justificationMapping + ").");
+ throw new IllegalStateException(
+ "Justification mapping already set (%s).\nMaybe the constraint calls justifyWith() twice?" | ```suggestion
"""
Justification mapping already set (%s).
Maybe the constraint calls justifyWith() twice?"""
```
Java's got cool features now. Use them, please. (Apply in other places in the PR as well.) |
timefold-solver | github_2023 | java | 659 | TimefoldAI | triceo | @@ -0,0 +1,25 @@
+package ai.timefold.solver.test.api.score.stream.testdata.justification;
+
+import ai.timefold.solver.core.api.score.stream.ConstraintJustification;
+
+public class TestSecondComparableJustification | Any particular reason for testing comparable justifications? What specifically is being tested here? |
timefold-solver | github_2023 | java | 659 | TimefoldAI | triceo | @@ -4,9 +4,55 @@
import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore;
import ai.timefold.solver.core.api.score.stream.Constraint;
+import ai.timefold.solver.core.api.score.stream.ConstraintJustification;
public interface SingleConstraintAssertion {
+ /**
+ * As defined by {@link #justifiesWith(ConstraintJustification...)}.
+ *
+ * @param justifications the expected justification.
+ * @param message sometimes null, description of the scenario being asserted
+ * @return never null
+ * @throws AssertionError when the expected penalty is not observed
+ */
+ SingleConstraintAssertion justifiesWith(String message, ConstraintJustification... justifications); | I'm wondering, for the sake of consistency... the `penalizes(...)` method (and its reward counterparts) has the `message` as second argument. Maybe we deprecate those and introduce new ones where `message` goes first?
It would look silly if some methods have message first, and other have message last. This is going to need a `migration` script, and the quickstarts adjusted. (But the quickstarts need to happen anyway, we want to test the justifications in the real world.) |
timefold-solver | github_2023 | java | 659 | TimefoldAI | triceo | @@ -26,6 +29,9 @@ public Constraint[] defineConstraints(ConstraintFactory factory) {
protected Constraint horizontalConflict(ConstraintFactory factory) {
return factory.forEachUniquePair(Queen.class, equal(Queen::getRowIndex))
.penalize(SimpleScore.ONE)
+ .justifyWith((queen, otherQueen, simpleScore) -> new CustomHorizontalConflictJustification(queen.getId(),
+ otherQueen.getId()))
+ .indictWith((queen, otherQueen) -> List.of(queen, otherQueen)) | Isn't this the default if you don't provide any indictments? |
timefold-solver | github_2023 | java | 659 | TimefoldAI | triceo | @@ -39,36 +98,64 @@ default void penalizesBy(int matchWeightTotal) {
* @throws AssertionError when the expected penalty is not observed
*/
default void penalizesBy(long matchWeightTotal) {
- penalizesBy(matchWeightTotal, null);
+ penalizesBy(null, matchWeightTotal);
}
/**
- * As defined by {@link #penalizesBy(int)}.
+ * As defined by {@link #penalizesBy(long)}.
*
* @param matchWeightTotal at least 0, expected sum of match weights of matches of the constraint.
* @param message sometimes null, description of the scenario being asserted
* @throws AssertionError when the expected penalty is not observed
+ *
+ * @deprecated Use {@link #penalizesBy(String, long)} instead
*/
- void penalizesBy(long matchWeightTotal, String message);
+ @Deprecated(forRemoval = true, since = "1.7.0")
+ default void penalizesBy(long matchWeightTotal, String message) {
+ penalizesBy(message, matchWeightTotal);
+ }
/**
- * As defined by {@link #penalizesBy(int)}.
+ * As defined by {@link #penalizesBy(long)}.
+ *
+ * @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 penalizesBy(String message, long matchWeightTotal);
+
+ /**
+ * As defined by {@link #penalizesBy(long)}.
*
* @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 penalizesBy(BigDecimal matchWeightTotal) {
- penalizesBy(matchWeightTotal, null);
+ penalizesBy(null, matchWeightTotal);
}
/**
- * As defined by {@link #penalizesBy(int)}.
+ * As defined by {@link #penalizesBy(BigDecimal)}.
*
* @param matchWeightTotal at least 0, expected sum of match weights of matches of the constraint.
* @param message sometimes null, description of the scenario being asserted
* @throws AssertionError when the expected penalty is not observed
+ *
+ * @deprecated Use {@link #penalizesBy(String, BigDecimal)} instead
*/
- void penalizesBy(BigDecimal matchWeightTotal, String message);
+ @Deprecated(forRemoval = true, since = "1.7.0") | The next version of Solver is `1.8.0`. Please apply consistently. |
timefold-solver | github_2023 | others | 659 | TimefoldAI | triceo | @@ -0,0 +1,17 @@
+type: specs.openrewrite.org/v1beta/recipe
+name: ai.timefold.solver.migration.ToLatestSingleConstraintAssertion
+displayName: 'Use non-deprecated SingleConstraintAssertion methods'
+description: 'Use `penalizesBy/rewardsWith(String, int)` instead of `penalizesBy/rewardsWith(int, String)` on `SingleConstraintAssertion` tests.' | I'd prefer we have a Java class for this. See how I created the `NullableRecipe`.
The main reason is that if we did every such thing as a top-level YML recipe, we would soon have too many of them. I'd like to keep that folder relatively clean. |
timefold-solver | github_2023 | java | 659 | TimefoldAI | triceo | @@ -39,36 +98,64 @@ default void penalizesBy(int matchWeightTotal) {
* @throws AssertionError when the expected penalty is not observed
*/
default void penalizesBy(long matchWeightTotal) {
- penalizesBy(matchWeightTotal, null);
+ penalizesBy(null, matchWeightTotal);
}
/**
- * As defined by {@link #penalizesBy(int)}.
+ * As defined by {@link #penalizesBy(long)}.
*
* @param matchWeightTotal at least 0, expected sum of match weights of matches of the constraint.
* @param message sometimes null, description of the scenario being asserted
* @throws AssertionError when the expected penalty is not observed
+ *
+ * @deprecated Use {@link #penalizesBy(String, long)} instead
*/
- void penalizesBy(long matchWeightTotal, String message);
+ @Deprecated(forRemoval = true, since = "1.7.0")
+ default void penalizesBy(long matchWeightTotal, String message) {
+ penalizesBy(message, matchWeightTotal);
+ }
/**
- * As defined by {@link #penalizesBy(int)}.
+ * As defined by {@link #penalizesBy(long)}.
+ *
+ * @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 penalizesBy(String message, long matchWeightTotal);
+
+ /**
+ * As defined by {@link #penalizesBy(long)}.
*
* @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 penalizesBy(BigDecimal matchWeightTotal) {
- penalizesBy(matchWeightTotal, null);
+ penalizesBy(null, matchWeightTotal);
}
/**
- * As defined by {@link #penalizesBy(int)}.
+ * As defined by {@link #penalizesBy(BigDecimal)}.
*
* @param matchWeightTotal at least 0, expected sum of match weights of matches of the constraint.
* @param message sometimes null, description of the scenario being asserted
* @throws AssertionError when the expected penalty is not observed
+ *
+ * @deprecated Use {@link #penalizesBy(String, BigDecimal)} instead | If it starts with a capital letter, it is a sentence and therefore it ends with a `.`. |
timefold-solver | github_2023 | java | 515 | TimefoldAI | zepfred | @@ -213,6 +217,59 @@ void solveGenerics() throws ExecutionException, InterruptedException {
solverJob.getFinalBestSolution();
}
+ @Test
+ void solveWithOverride() throws InterruptedException {
+ CountDownLatch countDownLatch = new CountDownLatch(2);
+ PhaseConfig<?> customPhaseConfig = new CustomPhaseConfig().withCustomPhaseCommands(
+ scoreDirector -> {
+ await().pollDelay(Duration.ofSeconds(5L)).until(() -> true);
+ countDownLatch.countDown(); | Yes, it makes sense. The goal is to ensure the termination time is overridden, but the internal state is not fetchable. I'll try to think of something else. |
timefold-solver | github_2023 | java | 515 | TimefoldAI | zepfred | @@ -0,0 +1,41 @@
+package ai.timefold.solver.core.api.solver;
+
+import java.util.UUID;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
+import ai.timefold.solver.core.config.solver.termination.TerminationConfig;
+
+/**
+ * Provides a fluid contract that allows customization and submission of planning problems to solve. It differs {@link SolverJobFactory}
+ * because it allows to listen to intermediate best solutions.
+ * <p>
+ * To create a {@link SolverJob}, use {@link #solveAndListen()}.
+ *
+ * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
+ * @param <ProblemId_> the ID type of a submitted problem, such as {@link Long} or {@link UUID}.
+ */
+public interface SolverAndListenerJobFactory<Solution_, ProblemId_> extends SolverJobFactory<Solution_, ProblemId_> { | Let's wait for the design meeting to define the next steps here. |
timefold-solver | github_2023 | java | 515 | TimefoldAI | zepfred | @@ -0,0 +1,41 @@
+package ai.timefold.solver.core.api.solver;
+
+import java.util.UUID;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
+import ai.timefold.solver.core.config.solver.termination.TerminationConfig;
+
+/**
+ * Provides a fluid contract that allows customization and submission of planning problems to solve. It differs {@link SolverJobFactory}
+ * because it allows to listen to intermediate best solutions.
+ * <p>
+ * To create a {@link SolverJob}, use {@link #solveAndListen()}.
+ *
+ * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
+ * @param <ProblemId_> the ID type of a submitted problem, such as {@link Long} or {@link UUID}.
+ */
+public interface SolverAndListenerJobFactory<Solution_, ProblemId_> extends SolverJobFactory<Solution_, ProblemId_> {
+
+ // ************************************************************************
+ // With methods
+ // ************************************************************************
+ @Override
+ SolverAndListenerJobFactory<Solution_, ProblemId_> withFinalBestSolutionConsumer(Consumer<? super Solution_> finalBestSolutionConsumer);
+
+ @Override
+ SolverAndListenerJobFactory<Solution_, ProblemId_> withExceptionHandler(BiConsumer<? super ProblemId_, ? super Throwable> exceptionHandler);
+
+ @Override
+ SolverAndListenerJobFactory<Solution_, ProblemId_> withTerminationConfig(TerminationConfig terminationConfig); | Let's wait for the design meeting to define the next steps here. |
timefold-solver | github_2023 | java | 515 | TimefoldAI | zepfred | @@ -0,0 +1,37 @@
+package ai.timefold.solver.core.api.solver;
+
+import java.util.UUID;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
+import ai.timefold.solver.core.config.solver.termination.TerminationConfig;
+
+/**
+ * Provides a fluid contract that allows customization and submission of planning problems to solve.
+ * <p>
+ * To create a {@link SolverJob}, use {@link #solve()}.
+ *
+ * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
+ * @param <ProblemId_> the ID type of a submitted problem, such as {@link Long} or {@link UUID}.
+ */
+public interface SolverJobFactory<Solution_, ProblemId_> { | Let's wait for the design meeting to define the next steps here. |
timefold-solver | github_2023 | java | 515 | TimefoldAI | zepfred | @@ -268,11 +364,46 @@ default SolverJob<Solution_, ProblemId_> solveAndListen(ProblemId_ problemId,
* If null it defaults to logging the exception as an error.
* @return never null
*/
+ default SolverJob<Solution_, ProblemId_> solveAndListen(ProblemId_ problemId,
+ Function<? super ProblemId_, ? extends Solution_> problemFinder,
+ Consumer<? super Solution_> bestSolutionConsumer,
+ Consumer<? super Solution_> finalBestSolutionConsumer,
+ BiConsumer<? super ProblemId_, ? super Throwable> exceptionHandler) {
+ return builder(problemId, problemFinder, bestSolutionConsumer)
+ .withFinalBestSolutionConsumer(finalBestSolutionConsumer)
+ .withExceptionHandler(exceptionHandler)
+ .solveAndListen();
+ }
+
+ /**
+ * As defined by {@link #solveAndListen(Object, Function, Consumer, Consumer, BiConsumer)}.
+ * <p>
+ * The final best solution is delivered twice:
+ * first to the {@code bestSolutionConsumer} when it is found
+ * and then again to the {@code finalBestSolutionConsumer} when the solver terminates.
+ * Do not store the solution twice.
+ * This allows for use cases that only process the {@link Score} first (during best solution changed events)
+ * and then store the solution upon termination.
+ *
+ * @param problemId never null, an ID for each planning problem. This must be unique.
+ * Use this problemId to {@link #terminateEarly(Object) terminate} the solver early,
+ * {@link #getSolverStatus(Object) to get the status} or if the problem changes while solving.
+ * @param problemFinder never null, function that returns a {@link PlanningSolution}, usually with uninitialized planning
+ * variables
+ * @param bestSolutionConsumer never null, called multiple times, on a consumer thread
+ * @param finalBestSolutionConsumer sometimes null, called only once, at the end, on a consumer thread.
+ * That final best solution is already consumed by the bestSolutionConsumer earlier.
+ * @param exceptionHandler sometimes null, called if an exception or error occurs.
+ * If null it defaults to logging the exception as an error.
+ * @param configOverride sometimes null, includes settings that override the default configuration
+ * @return never null
+ */
SolverJob<Solution_, ProblemId_> solveAndListen(ProblemId_ problemId,
Function<? super ProblemId_, ? extends Solution_> problemFinder,
Consumer<? super Solution_> bestSolutionConsumer,
Consumer<? super Solution_> finalBestSolutionConsumer,
- BiConsumer<? super ProblemId_, ? super Throwable> exceptionHandler);
+ BiConsumer<? super ProblemId_, ? super Throwable> exceptionHandler,
+ SolverConfigOverride configOverride); | Let's wait for the design meeting to define the next steps here. |
timefold-solver | github_2023 | java | 515 | TimefoldAI | zepfred | @@ -98,6 +99,65 @@ static <Solution_, ProblemId_> SolverManager<Solution_, ProblemId_> create(
return new DefaultSolverManager<>(solverFactory, solverManagerConfig);
}
+ // ************************************************************************
+ // Builder methods
+ // ************************************************************************
+
+ /**
+ * Creates a Builder that allows to customize and submit a planning problem to solve.
+ *
+ * @param problemId never null, a ID for each planning problem. This must be unique.
+ * Use this problemId to {@link #terminateEarly(Object) terminate} the solver early,
+ * @param problem never null, a {@link PlanningSolution} usually with uninitialized planning variables
+ * @return never null
+ */
+ default SolverJobFactory<Solution_, ProblemId_> builder(ProblemId_ problemId, Solution_ problem) {
+ return builder(problemId, (problemId_) -> problem);
+ }
+
+
+ /**
+ * As defined by {@link #builder(Object, Object)}
+ *
+ * @param problemId never null, a ID for each planning problem. This must be unique.
+ * Use this problemId to {@link #terminateEarly(Object) terminate} the solver early,
+ * {@link #getSolverStatus(Object) to get the status} or if the problem changes while solving.
+ * @param problemFinder never null, function that returns a {@link PlanningSolution}, usually with uninitialized planning
+ * variables
+ * @return never null
+ */
+ SolverJobFactory<Solution_, ProblemId_> builder(ProblemId_ problemId,
+ Function<? super ProblemId_, ? extends Solution_> problemFinder);
+
+ /**
+ * Creates a Builder that allows to customize and submit a planning problem to solve and listen to intermediate
+ * best solutions.
+ *
+ * @param problemId never null, a ID for each planning problem. This must be unique.
+ * Use this problemId to {@link #terminateEarly(Object) terminate} the solver early,
+ * @param problem never null, a {@link PlanningSolution} usually with uninitialized planning variables
+ * @param bestSolutionConsumer never null, called multiple times, on a consumer thread
+ * @return never null
+ */
+ default SolverAndListenerJobFactory<Solution_, ProblemId_> builder(ProblemId_ problemId, Solution_ problem,
+ Consumer<? super Solution_> bestSolutionConsumer) {
+ return builder(problemId, (problemId_) -> problem, bestSolutionConsumer);
+ } | Let's wait for the design meeting to define the next steps here. |
timefold-solver | github_2023 | java | 515 | TimefoldAI | zepfred | @@ -196,10 +264,35 @@ default SolverJob<Solution_, ProblemId_> solve(ProblemId_ problemId,
* If null it defaults to logging the exception as an error.
* @return never null
*/
+ default SolverJob<Solution_, ProblemId_> solve(ProblemId_ problemId,
+ Function<? super ProblemId_, ? extends Solution_> problemFinder,
+ Consumer<? super Solution_> finalBestSolutionConsumer,
+ BiConsumer<? super ProblemId_, ? super Throwable> exceptionHandler) {
+ return builder(problemId, problemFinder)
+ .withFinalBestSolutionConsumer(finalBestSolutionConsumer)
+ .withExceptionHandler(exceptionHandler)
+ .solve();
+ }
+
+ /**
+ * As defined by {@link #solve(Object, Function, Consumer, BiConsumer)}.
+ *
+ * @param problemId never null, a ID for each planning problem. This must be unique.
+ * Use this problemId to {@link #terminateEarly(Object) terminate} the solver early,
+ * {@link #getSolverStatus(Object) to get the status} or if the problem changes while solving.
+ * @param problemFinder never null, function that returns a {@link PlanningSolution}, usually with uninitialized planning
+ * variables
+ * @param finalBestSolutionConsumer sometimes null, called only once, at the end, on a consumer thread
+ * @param exceptionHandler sometimes null, called if an exception or error occurs.
+ * If null it defaults to logging the exception as an error.
+ * @param configOverride sometimes null, includes settings that override the default configuration
+ * @return never null
+ */
SolverJob<Solution_, ProblemId_> solve(ProblemId_ problemId,
- Function<? super ProblemId_, ? extends Solution_> problemFinder,
- Consumer<? super Solution_> finalBestSolutionConsumer,
- BiConsumer<? super ProblemId_, ? super Throwable> exceptionHandler);
+ Function<? super ProblemId_, ? extends Solution_> problemFinder,
+ Consumer<? super Solution_> finalBestSolutionConsumer,
+ BiConsumer<? super ProblemId_, ? super Throwable> exceptionHandler,
+ SolverConfigOverride configOverride); | Let's wait for the design meeting to define the next steps here. |
timefold-solver | github_2023 | java | 515 | TimefoldAI | zepfred | @@ -0,0 +1,38 @@
+package ai.timefold.solver.core.config.solver;
+
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
+import ai.timefold.solver.core.config.solver.termination.TerminationConfig;
+
+/**
+ * Includes settings to override default {@link ai.timefold.solver.core.api.solver.Solver} configuration.
+ *
+ * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
+ */
+public class SolverConfigOverride<Solution_> { | > It is questionable if this class belongs in `config` package. As you can see, it caused it to be needlessly inserted in the XSD. I'd move this to `api/solver`, which is where it is primarily used.
>
Yes, I was unsure about how to deal with this XSD auto-generation, and it makes sense to move it to `api/solver.`
> Also, let's make it `final`. I am a big friend of removing freedom from people (in code); if you allow people to do something, in this case extending the class, they will. And then you have to live with that forever.
>
> We can always allow it if we see the need in the future. We can never forbid it once we've allowed it.
Done!
|
timefold-solver | github_2023 | java | 515 | TimefoldAI | zepfred | @@ -0,0 +1,101 @@
+package ai.timefold.solver.core.config.solver;
+
+import java.util.UUID;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+import java.util.function.Function;
+
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
+import ai.timefold.solver.core.config.solver.termination.TerminationConfig;
+
+/**
+ * Settings used by {@link ai.timefold.solver.core.api.solver.SolverManager} to submit and solve problems. It also
+ * includes settings to override default {@link ai.timefold.solver.core.api.solver.Solver} configuration.
+ *
+ * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
+ * @param <ProblemId_> the ID type of a submitted problem, such as {@link Long} or {@link UUID}.
+ */
+public class SolverJobConfig<Solution_, ProblemId_> { | I removed this class as it had become unused after updating the public API contract. |
timefold-solver | github_2023 | java | 515 | TimefoldAI | zepfred | @@ -0,0 +1,82 @@
+package ai.timefold.solver.core.impl.solver;
+
+import java.util.Objects;
+import java.util.UUID;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+import java.util.function.Function;
+
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
+import ai.timefold.solver.core.api.solver.SolverJob;
+import ai.timefold.solver.core.api.solver.SolverJobBuilder;
+import ai.timefold.solver.core.api.solver.SolverManager;
+import ai.timefold.solver.core.config.solver.SolverJobConfig;
+import ai.timefold.solver.core.config.solver.termination.TerminationConfig;
+
+/**
+ * A {@link SolverManager} can solve multiple planning problems and can be used across different threads. The session of
+ * solver manager is responsible for constructing and solving a specific configuration problem. Hence, it is possible to
+ * have multiple distinct sessions that are scheduled to run by the SolverManager implementation.
+ * <p>
+ * To solve a planning problem, set the problem configuration: {@link #withProblemId(Object)},
+ * {@link #withProblemFinder(Function)} and {@link #withProblem(Object)}. Then solve it by calling {@link #run()}.
+ *
+ * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
+ * @param <ProblemId_> the ID type of submitted problem, such as {@link Long} or {@link UUID}.
+ *
+ * @see DefaultSolverManager
+ */
+public class DefaultSolverJobSession<Solution_, ProblemId_> implements SolverJobBuilder<Solution_, ProblemId_> { | > If you're implementing `SolverJobBuilder`, typically we call the implementation `DefaultSolverJobBuilder`.
Done!
> In this case, it is questionable whether we need the interface at all - why not make this the `SolverJobBuilder` directly? Make the constructors package-private and there are no issues.
The interface belongs to the public API, and `DefaultSolverJobBuilder` needs to access `DefaultSolverManager` in order to submit the problem. So, it seems not correct to access `DefaultSolverManager` from the public API. Does that make sense? |
timefold-solver | github_2023 | others | 515 | TimefoldAI | zepfred | @@ -1435,6 +1435,18 @@
</xs:complexType>
+ <xs:complexType name="solverConfigOverride"> | Yes, I confirmed that no changes have been made to this file. |
timefold-solver | github_2023 | java | 515 | TimefoldAI | zepfred | @@ -115,6 +116,15 @@ static <Solution_> SolverFactory<Solution_> create(SolverConfig solverConfig) {
*
* @return never null
*/
- Solver<Solution_> buildSolver();
+ default Solver<Solution_> buildSolver() {
+ return this.buildSolver(null);
+ }
+ /**
+ * As defined by {@link #buildSolver()}.
+ *
+ * @param configOverride sometimes null, includes settings that override the default configuration
+ * @return never null
+ */
+ Solver<Solution_> buildSolver(SolverConfigOverride<Solution_> configOverride); | I have made changes to the logic to ensure that the configOverride is now required. |
timefold-solver | github_2023 | java | 515 | TimefoldAI | zepfred | @@ -0,0 +1,95 @@
+package ai.timefold.solver.core.api.solver;
+
+import java.util.UUID;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+import java.util.function.Function;
+
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
+
+/**
+ * Provides a fluid contract that allows customization and submission of planning problems to solve.
+ * <p>
+ * A {@link SolverManager} can solve multiple planning problems and can be used across different threads. The builder is
+ * responsible for constructing and solving a specific configuration problem. Hence, it is possible to
+ * have multiple distinct build configurations that are scheduled to run by the {@link SolverManager} implementation.
+ * <p>
+ * To solve a planning problem, set the problem configuration: {@link #withProblemId(Object)},
+ * {@link #withProblemFinder(Function)} and {@link #withProblem(Object)}. Then solve it by calling {@link #run()}.
+ *
+ * @param <Solution_> the solution type, the class with the {@link PlanningSolution} annotation
+ * @param <ProblemId_> the ID type of submitted problem, such as {@link Long} or {@link UUID}.
+ */
+public interface SolverJobBuilder<Solution_, ProblemId_> {
+
+ /**
+ * Sets the problem id.
+ *
+ * @param problemId never null, a ID for each planning problem. This must be unique.
+ * @return this, never null
+ */
+ SolverJobBuilder<Solution_, ProblemId_> withProblemId(ProblemId_ problemId);
+
+ /**
+ * Sets the problem definition.
+ *
+ * @param problem never null, a {@link PlanningSolution} usually with uninitialized planning variables
+ * @return this, never null
+ */
+ default SolverJobBuilder<Solution_, ProblemId_> withProblem(Solution_ problem) {
+ return withProblemFinder(id -> problem);
+ }
+
+ /**
+ * Sets the mapping function to the problem definition.
+ *
+ * @param problemFinder never null, a function that returns a {@link PlanningSolution}, usually with uninitialized
+ * planning variables
+ * @return this, never null
+ */
+ SolverJobBuilder<Solution_, ProblemId_> withProblemFinder(Function<? super ProblemId_, ? extends Solution_> problemFinder);
+
+ /**
+ * Sets the best solution consumer, which may be called multiple times during the solving process.
+ *
+ * @param bestSolutionConsumer called multiple times for each new best solution on a consumer thread | The only case I can think of is if we want to reuse a builder and update the configuration, which seems an anti-pattern. |
timefold-solver | github_2023 | java | 515 | TimefoldAI | zepfred | @@ -72,7 +72,10 @@ void solve() throws ExecutionException, InterruptedException {
Collections.emptyList(),
HardSoftLongScore.ZERO);
- SolverJob<TestDataKitchenSinkSolution, Long> solverJob = solverManager.solve(1L, problem);
+ SolverJob<TestDataKitchenSinkSolution, Long> solverJob = solverManager.solveBuilder()
+ .withProblemId(1L)
+ .withProblem(problem)
+ .run(); | Agreed. Should we keep using the builder or revert changes for this method? |
timefold-solver | github_2023 | others | 623 | TimefoldAI | triceo | @@ -0,0 +1,286 @@
+= Define the constraints and calculate the score
+:imagesdir: ../..
+
+A _score_ represents the quality of a specific solution.
+The higher the better.
+Timefold Solver looks for the best solution, which is the solution with the highest score found in the available time.
+It might be the _optimal_ solution.
+
+Because this use case has hard and soft constraints,
+use the `HardSoftScore` class to represent the score:
+
+* Hard constraints must not be broken.
+For example: _The vehicle capacity must not be exceeded._
+* Soft constraints should not be broken.
+For example: _The total travel time should be a minimum._ | ```suggestion
For example: _The sum total of travel time._
``` |
timefold-solver | github_2023 | others | 623 | TimefoldAI | triceo | @@ -0,0 +1,286 @@
+= Define the constraints and calculate the score
+:imagesdir: ../..
+
+A _score_ represents the quality of a specific solution.
+The higher the better.
+Timefold Solver looks for the best solution, which is the solution with the highest score found in the available time.
+It might be the _optimal_ solution.
+
+Because this use case has hard and soft constraints,
+use the `HardSoftScore` class to represent the score:
+
+* Hard constraints must not be broken.
+For example: _The vehicle capacity must not be exceeded._
+* Soft constraints should not be broken.
+For example: _The total travel time should be a minimum._
+
+Hard constraints are weighted against other hard constraints.
+Soft constraints are weighted too, against other soft constraints.
+*Hard constraints always outweigh soft constraints*, regardless of their respective weights.
+
+To calculate the score, you could implement an `EasyScoreCalculator` class:
+
+[tabs]
+====
+Java::
++
+--
+[source,java]
+----
+package org.acme.vehiclerouting.solver;
+
+import java.util.List;
+
+import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore;
+import ai.timefold.solver.core.api.score.calculator.EasyScoreCalculator;
+import ai.timefold.solver.core.impl.util.MutableInt;
+
+import org.acme.vehiclerouting.domain.Vehicle;
+import org.acme.vehiclerouting.domain.VehicleRoutePlan;
+
+public class VehicleRoutingEasyScoreCalculator implements EasyScoreCalculator<VehicleRoutePlan, HardSoftLongScore> {
+ @Override
+ public HardSoftLongScore calculateScore(VehicleRoutePlan vehicleRoutePlan) {
+
+ List<Vehicle> vehicleList = vehicleRoutePlan.getVehicles();
+
+ MutableInt hardScore = new MutableInt(0);
+ int softScore = 0;
+ for (Vehicle vehicle : vehicleList) {
+
+ // The demand exceeds the capacity
+ if (vehicle.getVisits() != null && vehicle.getTotalDemand() > vehicle.getCapacity()) {
+ hardScore.setValue(hardScore.intValue() - (vehicle.getTotalDemand() - vehicle.getCapacity()));
+ }
+
+ // Max end-time not meted | ```suggestion
// Max end-time not met
``` |
timefold-solver | github_2023 | others | 623 | TimefoldAI | triceo | @@ -0,0 +1,286 @@
+= Define the constraints and calculate the score
+:imagesdir: ../..
+
+A _score_ represents the quality of a specific solution.
+The higher the better.
+Timefold Solver looks for the best solution, which is the solution with the highest score found in the available time.
+It might be the _optimal_ solution.
+
+Because this use case has hard and soft constraints,
+use the `HardSoftScore` class to represent the score:
+
+* Hard constraints must not be broken.
+For example: _The vehicle capacity must not be exceeded._
+* Soft constraints should not be broken.
+For example: _The total travel time should be a minimum._
+
+Hard constraints are weighted against other hard constraints.
+Soft constraints are weighted too, against other soft constraints.
+*Hard constraints always outweigh soft constraints*, regardless of their respective weights.
+
+To calculate the score, you could implement an `EasyScoreCalculator` class:
+
+[tabs]
+====
+Java::
++
+--
+[source,java]
+----
+package org.acme.vehiclerouting.solver;
+
+import java.util.List;
+
+import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore;
+import ai.timefold.solver.core.api.score.calculator.EasyScoreCalculator;
+import ai.timefold.solver.core.impl.util.MutableInt;
+
+import org.acme.vehiclerouting.domain.Vehicle;
+import org.acme.vehiclerouting.domain.VehicleRoutePlan;
+
+public class VehicleRoutingEasyScoreCalculator implements EasyScoreCalculator<VehicleRoutePlan, HardSoftLongScore> {
+ @Override
+ public HardSoftLongScore calculateScore(VehicleRoutePlan vehicleRoutePlan) {
+
+ List<Vehicle> vehicleList = vehicleRoutePlan.getVehicles();
+
+ MutableInt hardScore = new MutableInt(0);
+ int softScore = 0;
+ for (Vehicle vehicle : vehicleList) {
+
+ // The demand exceeds the capacity
+ if (vehicle.getVisits() != null && vehicle.getTotalDemand() > vehicle.getCapacity()) {
+ hardScore.setValue(hardScore.intValue() - (vehicle.getTotalDemand() - vehicle.getCapacity()));
+ }
+
+ // Max end-time not meted
+ if (vehicle.getVisits() != null) {
+ vehicle.getVisits().forEach(visit -> {
+ if (visit.isServiceFinishedAfterMaxEndTime()) {
+ hardScore.setValue((int) (hardScore.intValue() - visit.getServiceFinishedDelayInMinutes()));
+ }
+ });
+ }
+
+ softScore -= (int) vehicle.getTotalDrivingTimeSeconds();
+ }
+
+ return HardSoftLongScore.of(hardScore.intValue(), softScore);
+ }
+}
+
+----
+--
+
+Kotlin::
++
+--
+[source,kotlin]
+----
+package org.acme.vehiclerouting.solver
+
+import java.util.function.Consumer
+
+import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore
+import ai.timefold.solver.core.api.score.calculator.EasyScoreCalculator
+import ai.timefold.solver.core.impl.util.MutableInt
+
+import org.acme.vehiclerouting.domain.Vehicle
+import org.acme.vehiclerouting.domain.VehicleRoutePlan
+import org.acme.vehiclerouting.domain.Visit
+
+class VehicleRoutingEasyScoreCalculator :
+ EasyScoreCalculator<VehicleRoutePlan, HardSoftLongScore> {
+ override fun calculateScore(vehicleRoutePlan: VehicleRoutePlan): HardSoftLongScore {
+ val vehicleList: List<Vehicle>? = vehicleRoutePlan.vehicles
+
+ val hardScore = MutableInt(0)
+ var softScore = 0
+ for (vehicle in vehicleList!!) {
+ // The demand exceeds the capacity
+
+ if (vehicle.visits != null && vehicle.totalDemand > vehicle.capacity) {
+ hardScore.setValue((hardScore.toInt() - (vehicle.totalDemand - vehicle.capacity)).toInt())
+ }
+
+ // Max end-time not meted | ```suggestion
// Max end-time not met
``` |
timefold-solver | github_2023 | others | 623 | TimefoldAI | triceo | @@ -0,0 +1,286 @@
+= Define the constraints and calculate the score
+:imagesdir: ../..
+
+A _score_ represents the quality of a specific solution.
+The higher the better.
+Timefold Solver looks for the best solution, which is the solution with the highest score found in the available time.
+It might be the _optimal_ solution.
+
+Because this use case has hard and soft constraints,
+use the `HardSoftScore` class to represent the score:
+
+* Hard constraints must not be broken.
+For example: _The vehicle capacity must not be exceeded._
+* Soft constraints should not be broken.
+For example: _The total travel time should be a minimum._
+
+Hard constraints are weighted against other hard constraints.
+Soft constraints are weighted too, against other soft constraints.
+*Hard constraints always outweigh soft constraints*, regardless of their respective weights.
+
+To calculate the score, you could implement an `EasyScoreCalculator` class:
+
+[tabs]
+====
+Java::
++
+--
+[source,java]
+----
+package org.acme.vehiclerouting.solver;
+
+import java.util.List;
+
+import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore;
+import ai.timefold.solver.core.api.score.calculator.EasyScoreCalculator;
+import ai.timefold.solver.core.impl.util.MutableInt;
+
+import org.acme.vehiclerouting.domain.Vehicle;
+import org.acme.vehiclerouting.domain.VehicleRoutePlan;
+
+public class VehicleRoutingEasyScoreCalculator implements EasyScoreCalculator<VehicleRoutePlan, HardSoftLongScore> {
+ @Override
+ public HardSoftLongScore calculateScore(VehicleRoutePlan vehicleRoutePlan) {
+
+ List<Vehicle> vehicleList = vehicleRoutePlan.getVehicles();
+
+ MutableInt hardScore = new MutableInt(0); | Let's make this an `int`. |
timefold-solver | github_2023 | others | 623 | TimefoldAI | triceo | @@ -0,0 +1,286 @@
+= Define the constraints and calculate the score
+:imagesdir: ../..
+
+A _score_ represents the quality of a specific solution.
+The higher the better.
+Timefold Solver looks for the best solution, which is the solution with the highest score found in the available time.
+It might be the _optimal_ solution.
+
+Because this use case has hard and soft constraints,
+use the `HardSoftScore` class to represent the score:
+
+* Hard constraints must not be broken.
+For example: _The vehicle capacity must not be exceeded._
+* Soft constraints should not be broken.
+For example: _The total travel time should be a minimum._
+
+Hard constraints are weighted against other hard constraints.
+Soft constraints are weighted too, against other soft constraints.
+*Hard constraints always outweigh soft constraints*, regardless of their respective weights.
+
+To calculate the score, you could implement an `EasyScoreCalculator` class:
+
+[tabs]
+====
+Java::
++
+--
+[source,java]
+----
+package org.acme.vehiclerouting.solver;
+
+import java.util.List;
+
+import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore;
+import ai.timefold.solver.core.api.score.calculator.EasyScoreCalculator;
+import ai.timefold.solver.core.impl.util.MutableInt;
+
+import org.acme.vehiclerouting.domain.Vehicle;
+import org.acme.vehiclerouting.domain.VehicleRoutePlan;
+
+public class VehicleRoutingEasyScoreCalculator implements EasyScoreCalculator<VehicleRoutePlan, HardSoftLongScore> {
+ @Override
+ public HardSoftLongScore calculateScore(VehicleRoutePlan vehicleRoutePlan) {
+
+ List<Vehicle> vehicleList = vehicleRoutePlan.getVehicles();
+
+ MutableInt hardScore = new MutableInt(0);
+ int softScore = 0;
+ for (Vehicle vehicle : vehicleList) {
+
+ // The demand exceeds the capacity
+ if (vehicle.getVisits() != null && vehicle.getTotalDemand() > vehicle.getCapacity()) {
+ hardScore.setValue(hardScore.intValue() - (vehicle.getTotalDemand() - vehicle.getCapacity())); | To avoid this. |
timefold-solver | github_2023 | others | 623 | TimefoldAI | triceo | @@ -0,0 +1,286 @@
+= Define the constraints and calculate the score
+:imagesdir: ../..
+
+A _score_ represents the quality of a specific solution.
+The higher the better.
+Timefold Solver looks for the best solution, which is the solution with the highest score found in the available time.
+It might be the _optimal_ solution.
+
+Because this use case has hard and soft constraints,
+use the `HardSoftScore` class to represent the score:
+
+* Hard constraints must not be broken.
+For example: _The vehicle capacity must not be exceeded._
+* Soft constraints should not be broken.
+For example: _The total travel time should be a minimum._
+
+Hard constraints are weighted against other hard constraints.
+Soft constraints are weighted too, against other soft constraints.
+*Hard constraints always outweigh soft constraints*, regardless of their respective weights.
+
+To calculate the score, you could implement an `EasyScoreCalculator` class:
+
+[tabs]
+====
+Java::
++
+--
+[source,java]
+----
+package org.acme.vehiclerouting.solver;
+
+import java.util.List;
+
+import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore;
+import ai.timefold.solver.core.api.score.calculator.EasyScoreCalculator;
+import ai.timefold.solver.core.impl.util.MutableInt;
+
+import org.acme.vehiclerouting.domain.Vehicle;
+import org.acme.vehiclerouting.domain.VehicleRoutePlan;
+
+public class VehicleRoutingEasyScoreCalculator implements EasyScoreCalculator<VehicleRoutePlan, HardSoftLongScore> {
+ @Override
+ public HardSoftLongScore calculateScore(VehicleRoutePlan vehicleRoutePlan) {
+
+ List<Vehicle> vehicleList = vehicleRoutePlan.getVehicles();
+
+ MutableInt hardScore = new MutableInt(0);
+ int softScore = 0;
+ for (Vehicle vehicle : vehicleList) {
+
+ // The demand exceeds the capacity
+ if (vehicle.getVisits() != null && vehicle.getTotalDemand() > vehicle.getCapacity()) {
+ hardScore.setValue(hardScore.intValue() - (vehicle.getTotalDemand() - vehicle.getCapacity()));
+ }
+
+ // Max end-time not meted
+ if (vehicle.getVisits() != null) {
+ vehicle.getVisits().forEach(visit -> {
+ if (visit.isServiceFinishedAfterMaxEndTime()) {
+ hardScore.setValue((int) (hardScore.intValue() - visit.getServiceFinishedDelayInMinutes()));
+ }
+ });
+ }
+
+ softScore -= (int) vehicle.getTotalDrivingTimeSeconds();
+ }
+
+ return HardSoftLongScore.of(hardScore.intValue(), softScore);
+ }
+}
+
+----
+--
+
+Kotlin::
++
+--
+[source,kotlin]
+----
+package org.acme.vehiclerouting.solver
+
+import java.util.function.Consumer
+
+import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore
+import ai.timefold.solver.core.api.score.calculator.EasyScoreCalculator
+import ai.timefold.solver.core.impl.util.MutableInt
+
+import org.acme.vehiclerouting.domain.Vehicle
+import org.acme.vehiclerouting.domain.VehicleRoutePlan
+import org.acme.vehiclerouting.domain.Visit
+
+class VehicleRoutingEasyScoreCalculator :
+ EasyScoreCalculator<VehicleRoutePlan, HardSoftLongScore> {
+ override fun calculateScore(vehicleRoutePlan: VehicleRoutePlan): HardSoftLongScore {
+ val vehicleList: List<Vehicle>? = vehicleRoutePlan.vehicles
+
+ val hardScore = MutableInt(0) | `int` please. |
timefold-solver | github_2023 | others | 623 | TimefoldAI | triceo | @@ -0,0 +1,286 @@
+= Define the constraints and calculate the score
+:imagesdir: ../..
+
+A _score_ represents the quality of a specific solution.
+The higher the better.
+Timefold Solver looks for the best solution, which is the solution with the highest score found in the available time.
+It might be the _optimal_ solution.
+
+Because this use case has hard and soft constraints,
+use the `HardSoftScore` class to represent the score:
+
+* Hard constraints must not be broken.
+For example: _The vehicle capacity must not be exceeded._
+* Soft constraints should not be broken.
+For example: _The total travel time should be a minimum._
+
+Hard constraints are weighted against other hard constraints.
+Soft constraints are weighted too, against other soft constraints.
+*Hard constraints always outweigh soft constraints*, regardless of their respective weights.
+
+To calculate the score, you could implement an `EasyScoreCalculator` class:
+
+[tabs]
+====
+Java::
++
+--
+[source,java]
+----
+package org.acme.vehiclerouting.solver;
+
+import java.util.List;
+
+import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore;
+import ai.timefold.solver.core.api.score.calculator.EasyScoreCalculator;
+import ai.timefold.solver.core.impl.util.MutableInt;
+
+import org.acme.vehiclerouting.domain.Vehicle;
+import org.acme.vehiclerouting.domain.VehicleRoutePlan;
+
+public class VehicleRoutingEasyScoreCalculator implements EasyScoreCalculator<VehicleRoutePlan, HardSoftLongScore> {
+ @Override
+ public HardSoftLongScore calculateScore(VehicleRoutePlan vehicleRoutePlan) {
+
+ List<Vehicle> vehicleList = vehicleRoutePlan.getVehicles();
+
+ MutableInt hardScore = new MutableInt(0);
+ int softScore = 0;
+ for (Vehicle vehicle : vehicleList) {
+
+ // The demand exceeds the capacity
+ if (vehicle.getVisits() != null && vehicle.getTotalDemand() > vehicle.getCapacity()) {
+ hardScore.setValue(hardScore.intValue() - (vehicle.getTotalDemand() - vehicle.getCapacity()));
+ }
+
+ // Max end-time not meted
+ if (vehicle.getVisits() != null) {
+ vehicle.getVisits().forEach(visit -> {
+ if (visit.isServiceFinishedAfterMaxEndTime()) {
+ hardScore.setValue((int) (hardScore.intValue() - visit.getServiceFinishedDelayInMinutes()));
+ }
+ });
+ }
+
+ softScore -= (int) vehicle.getTotalDrivingTimeSeconds();
+ }
+
+ return HardSoftLongScore.of(hardScore.intValue(), softScore);
+ }
+}
+
+----
+--
+
+Kotlin::
++
+--
+[source,kotlin]
+----
+package org.acme.vehiclerouting.solver
+
+import java.util.function.Consumer
+
+import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore
+import ai.timefold.solver.core.api.score.calculator.EasyScoreCalculator
+import ai.timefold.solver.core.impl.util.MutableInt
+
+import org.acme.vehiclerouting.domain.Vehicle
+import org.acme.vehiclerouting.domain.VehicleRoutePlan
+import org.acme.vehiclerouting.domain.Visit
+
+class VehicleRoutingEasyScoreCalculator :
+ EasyScoreCalculator<VehicleRoutePlan, HardSoftLongScore> {
+ override fun calculateScore(vehicleRoutePlan: VehicleRoutePlan): HardSoftLongScore {
+ val vehicleList: List<Vehicle>? = vehicleRoutePlan.vehicles
+
+ val hardScore = MutableInt(0)
+ var softScore = 0
+ for (vehicle in vehicleList!!) {
+ // The demand exceeds the capacity
+
+ if (vehicle.visits != null && vehicle.totalDemand > vehicle.capacity) {
+ hardScore.setValue((hardScore.toInt() - (vehicle.totalDemand - vehicle.capacity)).toInt())
+ }
+
+ // Max end-time not meted
+ if (vehicle.visits != null) {
+ vehicle.visits!!.forEach(Consumer { visit: Visit ->
+ if (visit.isServiceFinishedAfterMaxEndTime) {
+ hardScore.setValue((hardScore.toInt() - visit.serviceFinishedDelayInMinutes).toInt())
+ }
+ })
+ }
+
+ softScore -= vehicle.totalDrivingTimeSeconds.toInt()
+ }
+
+ return HardSoftLongScore.of(hardScore.toInt().toLong(), softScore.toLong())
+ }
+}
+----
+--
+====
+
+
+Unfortunately **that does not scale well**, because it is non-incremental:
+every time a visit is scheduled to a different vehicle,
+all visits are re-evaluated to calculate the new score.
+
+Instead, create a `VehicleRoutingConstraintProvider` class
+to perform incremental score calculation.
+It uses Timefold Solver's xref:constraints-and-score/score-calculation.adoc[Constraint Streams API]
+which is inspired by Java Streams and SQL:
+
+[tabs]
+====
+Java::
++
+--
+Create a `src/main/java/org/acme/vehiclerouting/solver/VehicleRoutingConstraintProvider.java` class:
+
+[source,java]
+----
+package org.acme.vehiclerouting.solver;
+
+import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore;
+import ai.timefold.solver.core.api.score.stream.Constraint;
+import ai.timefold.solver.core.api.score.stream.ConstraintFactory;
+import ai.timefold.solver.core.api.score.stream.ConstraintProvider;
+
+import org.acme.vehiclerouting.domain.Visit;
+import org.acme.vehiclerouting.domain.Vehicle;
+import org.acme.vehiclerouting.solver.justifications.MinimizeTravelTimeJustification;
+import org.acme.vehiclerouting.solver.justifications.ServiceFinishedAfterMaxEndTimeJustification;
+import org.acme.vehiclerouting.solver.justifications.VehicleCapacityJustification;
+
+public class VehicleRoutingConstraintProvider implements ConstraintProvider {
+
+ public static final String VEHICLE_CAPACITY = "vehicleCapacity";
+ public static final String SERVICE_FINISHED_AFTER_MAX_END_TIME = "serviceFinishedAfterMaxEndTime";
+ public static final String MINIMIZE_TRAVEL_TIME = "minimizeTravelTime";
+
+ @Override
+ public Constraint[] defineConstraints(ConstraintFactory factory) {
+ return new Constraint[] {
+ vehicleCapacity(factory),
+ serviceFinishedAfterMaxEndTime(factory),
+ minimizeTravelTime(factory)
+ };
+ }
+
+ protected Constraint vehicleCapacity(ConstraintFactory factory) {
+ return factory.forEach(Vehicle.class)
+ .filter(vehicle -> vehicle.getTotalDemand() > vehicle.getCapacity())
+ .penalizeLong(HardSoftLongScore.ONE_HARD,
+ vehicle -> vehicle.getTotalDemand() - vehicle.getCapacity())
+ .justifyWith((vehicle, score) -> new VehicleCapacityJustification(vehicle.getId(), vehicle.getTotalDemand(),
+ vehicle.getCapacity()))
+ .asConstraint(VEHICLE_CAPACITY);
+ }
+
+ protected Constraint serviceFinishedAfterMaxEndTime(ConstraintFactory factory) {
+ return factory.forEach(Visit.class)
+ .filter(Visit::isServiceFinishedAfterMaxEndTime)
+ .penalizeLong(HardSoftLongScore.ONE_HARD,
+ Visit::getServiceFinishedDelayInMinutes)
+ .justifyWith((visit, score) -> new ServiceFinishedAfterMaxEndTimeJustification(visit.getId(),
+ visit.getServiceFinishedDelayInMinutes()))
+ .asConstraint(SERVICE_FINISHED_AFTER_MAX_END_TIME);
+ }
+
+ protected Constraint minimizeTravelTime(ConstraintFactory factory) {
+ return factory.forEach(Vehicle.class)
+ .penalizeLong(HardSoftLongScore.ONE_SOFT,
+ Vehicle::getTotalDrivingTimeSeconds)
+ .justifyWith((vehicle, score) -> new MinimizeTravelTimeJustification(vehicle.getId(),
+ vehicle.getTotalDrivingTimeSeconds()))
+ .asConstraint(MINIMIZE_TRAVEL_TIME);
+ }
+}
+
+----
+--
+
+Kotlin::
++
+--
+Create a `src/main/kotlin/org/acme/vehiclerouting/solver/VehicleRoutingConstraintProvider.kt` class:
+
+[source,kotlin]
+----
+package org.acme.vehiclerouting.solver
+
+import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore
+import ai.timefold.solver.core.api.score.stream.Constraint
+import ai.timefold.solver.core.api.score.stream.ConstraintFactory
+import ai.timefold.solver.core.api.score.stream.ConstraintProvider
+
+import org.acme.vehiclerouting.domain.Visit
+import org.acme.vehiclerouting.domain.Vehicle
+import org.acme.vehiclerouting.solver.justifications.MinimizeTravelTimeJustification
+import org.acme.vehiclerouting.solver.justifications.ServiceFinishedAfterMaxEndTimeJustification
+import org.acme.vehiclerouting.solver.justifications.VehicleCapacityJustification
+
+class VehicleRoutingConstraintProvider : ConstraintProvider {
+ override fun defineConstraints(factory: ConstraintFactory): Array<Constraint> {
+ return arrayOf(
+ vehicleCapacity(factory),
+ serviceFinishedAfterMaxEndTime(factory),
+ minimizeTravelTime(factory)
+ )
+ }
+
+ protected fun vehicleCapacity(factory: ConstraintFactory): Constraint {
+ return factory.forEach(Vehicle::class.java)
+ .filter({ vehicle: Vehicle -> vehicle.totalDemand > vehicle.capacity })
+ .penalizeLong(
+ HardSoftLongScore.ONE_HARD
+ ) { vehicle: Vehicle -> vehicle.totalDemand - vehicle.capacity }
+ .justifyWith({ vehicle: Vehicle, score: HardSoftLongScore? ->
+ VehicleCapacityJustification(
+ vehicle.id, vehicle.totalDemand.toInt(),
+ vehicle.capacity
+ )
+ })
+ .asConstraint(VEHICLE_CAPACITY)
+ }
+
+ protected fun serviceFinishedAfterMaxEndTime(factory: ConstraintFactory): Constraint {
+ return factory.forEach(Visit::class.java)
+ .filter({ obj: Visit -> obj.isServiceFinishedAfterMaxEndTime })
+ .penalizeLong(HardSoftLongScore.ONE_HARD,
+ { obj: Visit -> obj.serviceFinishedDelayInMinutes })
+ .justifyWith({ visit: Visit, score: HardSoftLongScore? ->
+ ServiceFinishedAfterMaxEndTimeJustification(
+ visit.id,
+ visit.serviceFinishedDelayInMinutes
+ )
+ })
+ .asConstraint(SERVICE_FINISHED_AFTER_MAX_END_TIME)
+ }
+
+ protected fun minimizeTravelTime(factory: ConstraintFactory): Constraint {
+ return factory.forEach(Vehicle::class.java)
+ .penalizeLong(HardSoftLongScore.ONE_SOFT,
+ { obj: Vehicle -> obj.totalDrivingTimeSeconds })
+ .justifyWith({ vehicle: Vehicle, score: HardSoftLongScore? ->
+ MinimizeTravelTimeJustification(
+ vehicle.id,
+ vehicle.totalDrivingTimeSeconds
+ )
+ })
+ .asConstraint(MINIMIZE_TRAVEL_TIME)
+ }
+
+ companion object {
+ const val VEHICLE_CAPACITY: String = "vehicleCapacity"
+ const val SERVICE_FINISHED_AFTER_MAX_END_TIME: String = "serviceFinishedAfterMaxEndTime"
+ const val MINIMIZE_TRAVEL_TIME: String = "minimizeTravelTime"
+ }
+}
+----
+--
+====
+
+The `ConstraintProvider` scales an order of magnitude better than the `EasyScoreCalculator`: __O__(n) instead of __O__(n²). | ```suggestion
The `ConstraintProvider` scales much better than the `EasyScoreCalculator`: typically __O__(n) instead of __O__(n²).
``` |
timefold-solver | github_2023 | others | 623 | TimefoldAI | triceo | @@ -0,0 +1,790 @@
+= Model the domain objects
+:imagesdir: ../..
+
+Your goal is to assign each visit to a vehicle.
+You will create these classes:
+
+image::quickstart/vehicle-routing/vehicleRoutingClassDiagramPure.png[]
+
+== Location
+
+The `Location` class is used to represent the destination for deliveries or the home location for vehicles.
+
+[tabs]
+====
+Java::
++
+--
+Create the `src/main/java/org/acme/vehiclerouting/domain/Location.java` class:
+
+[source,java]
+----
+package org.acme.vehiclerouting.domain;
+
+import java.util.Map;
+
+public class Location {
+
+ private double latitude;
+ private double longitude;
+
+ private Map<Location, Long> drivingTimeSeconds;
+
+ public Location(double latitude, double longitude) {
+ this.latitude = latitude;
+ this.longitude = longitude;
+ }
+
+ public double getLatitude() {
+ return latitude;
+ }
+
+ public double getLongitude() {
+ return longitude;
+ }
+
+ public Map<Location, Long> getDrivingTimeSeconds() {
+ return drivingTimeSeconds;
+ }
+
+ public void setDrivingTimeSeconds(Map<Location, Long> drivingTimeSeconds) {
+ this.drivingTimeSeconds = drivingTimeSeconds;
+ }
+
+ public long getDrivingTimeTo(Location location) {
+ return drivingTimeSeconds.get(location);
+ }
+}
+----
+--
+
+Kotlin::
++
+--
+Create the `src/main/kotlin/org/acme/vehiclerouting/domain/Location.kt` class:
+
+[source,kotlin]
+----
+package org.acme.vehiclerouting.domain
+
+class Location @JsonCreator constructor(val latitude: Double, val longitude: Double) {
+ var drivingTimeSeconds: Map<Location, Long>? = null
+
+ fun getDrivingTimeTo(location: Location): Long {
+ if (drivingTimeSeconds == null) {
+ return 0
+ }
+ return drivingTimeSeconds!![location]!!
+ }
+
+ override fun toString(): String {
+ return "$latitude,$longitude"
+ }
+}
+----
+--
+====
+
+== Vehicle
+
+`Vehicle` has a defined route plan with scheduled visits to make. Each vehicle has a specific departure time and
+starting location. It returns to its home location after completing the route and has a maximum capacity that must
+not be exceeded.
+
+During solving, Timefold Solver updates the `visits` field of the `Vehicle` class to assign a list of visits.
+Because Timefold Solver changes this field, `Vehicle` is a _planning entity_: | Maybe reference planning entity doc? |
timefold-solver | github_2023 | others | 623 | TimefoldAI | triceo | @@ -0,0 +1,790 @@
+= Model the domain objects
+:imagesdir: ../..
+
+Your goal is to assign each visit to a vehicle.
+You will create these classes:
+
+image::quickstart/vehicle-routing/vehicleRoutingClassDiagramPure.png[]
+
+== Location
+
+The `Location` class is used to represent the destination for deliveries or the home location for vehicles.
+
+[tabs]
+====
+Java::
++
+--
+Create the `src/main/java/org/acme/vehiclerouting/domain/Location.java` class:
+
+[source,java]
+----
+package org.acme.vehiclerouting.domain;
+
+import java.util.Map;
+
+public class Location {
+
+ private double latitude;
+ private double longitude;
+
+ private Map<Location, Long> drivingTimeSeconds;
+
+ public Location(double latitude, double longitude) {
+ this.latitude = latitude;
+ this.longitude = longitude;
+ }
+
+ public double getLatitude() {
+ return latitude;
+ }
+
+ public double getLongitude() {
+ return longitude;
+ }
+
+ public Map<Location, Long> getDrivingTimeSeconds() {
+ return drivingTimeSeconds;
+ }
+
+ public void setDrivingTimeSeconds(Map<Location, Long> drivingTimeSeconds) {
+ this.drivingTimeSeconds = drivingTimeSeconds;
+ }
+
+ public long getDrivingTimeTo(Location location) {
+ return drivingTimeSeconds.get(location);
+ }
+}
+----
+--
+
+Kotlin::
++
+--
+Create the `src/main/kotlin/org/acme/vehiclerouting/domain/Location.kt` class:
+
+[source,kotlin]
+----
+package org.acme.vehiclerouting.domain
+
+class Location @JsonCreator constructor(val latitude: Double, val longitude: Double) {
+ var drivingTimeSeconds: Map<Location, Long>? = null
+
+ fun getDrivingTimeTo(location: Location): Long {
+ if (drivingTimeSeconds == null) {
+ return 0
+ }
+ return drivingTimeSeconds!![location]!!
+ }
+
+ override fun toString(): String {
+ return "$latitude,$longitude"
+ }
+}
+----
+--
+====
+
+== Vehicle
+
+`Vehicle` has a defined route plan with scheduled visits to make. Each vehicle has a specific departure time and
+starting location. It returns to its home location after completing the route and has a maximum capacity that must
+not be exceeded.
+
+During solving, Timefold Solver updates the `visits` field of the `Vehicle` class to assign a list of visits.
+Because Timefold Solver changes this field, `Vehicle` is a _planning entity_:
+
+image::quickstart/vehicle-routing/vehicleRoutingClassDiagramAnnotated.png[]
+
+Based on the diagram, the `visits` field is a genuine variable that changes during the solving process. To ensure that
+Timefold Solver recognizes it as a list of planning variables, the field must have an `@PlanningListVariable` annotation. | ```suggestion
Timefold Solver recognizes it as a sequence of connected variables, the field must have an `@PlanningListVariable` annotation.
``` |
timefold-solver | github_2023 | others | 623 | TimefoldAI | triceo | @@ -0,0 +1,790 @@
+= Model the domain objects
+:imagesdir: ../..
+
+Your goal is to assign each visit to a vehicle.
+You will create these classes:
+
+image::quickstart/vehicle-routing/vehicleRoutingClassDiagramPure.png[]
+
+== Location
+
+The `Location` class is used to represent the destination for deliveries or the home location for vehicles.
+
+[tabs]
+====
+Java::
++
+--
+Create the `src/main/java/org/acme/vehiclerouting/domain/Location.java` class:
+
+[source,java]
+----
+package org.acme.vehiclerouting.domain;
+
+import java.util.Map;
+
+public class Location {
+
+ private double latitude;
+ private double longitude;
+
+ private Map<Location, Long> drivingTimeSeconds;
+
+ public Location(double latitude, double longitude) {
+ this.latitude = latitude;
+ this.longitude = longitude;
+ }
+
+ public double getLatitude() {
+ return latitude;
+ }
+
+ public double getLongitude() {
+ return longitude;
+ }
+
+ public Map<Location, Long> getDrivingTimeSeconds() {
+ return drivingTimeSeconds;
+ }
+
+ public void setDrivingTimeSeconds(Map<Location, Long> drivingTimeSeconds) {
+ this.drivingTimeSeconds = drivingTimeSeconds;
+ }
+
+ public long getDrivingTimeTo(Location location) {
+ return drivingTimeSeconds.get(location);
+ }
+}
+----
+--
+
+Kotlin::
++
+--
+Create the `src/main/kotlin/org/acme/vehiclerouting/domain/Location.kt` class:
+
+[source,kotlin]
+----
+package org.acme.vehiclerouting.domain
+
+class Location @JsonCreator constructor(val latitude: Double, val longitude: Double) {
+ var drivingTimeSeconds: Map<Location, Long>? = null
+
+ fun getDrivingTimeTo(location: Location): Long {
+ if (drivingTimeSeconds == null) {
+ return 0
+ }
+ return drivingTimeSeconds!![location]!!
+ }
+
+ override fun toString(): String {
+ return "$latitude,$longitude"
+ }
+}
+----
+--
+====
+
+== Vehicle
+
+`Vehicle` has a defined route plan with scheduled visits to make. Each vehicle has a specific departure time and
+starting location. It returns to its home location after completing the route and has a maximum capacity that must
+not be exceeded.
+
+During solving, Timefold Solver updates the `visits` field of the `Vehicle` class to assign a list of visits.
+Because Timefold Solver changes this field, `Vehicle` is a _planning entity_:
+
+image::quickstart/vehicle-routing/vehicleRoutingClassDiagramAnnotated.png[]
+
+Based on the diagram, the `visits` field is a genuine variable that changes during the solving process. To ensure that
+Timefold Solver recognizes it as a list of planning variables, the field must have an `@PlanningListVariable` annotation.
+
+[tabs]
+====
+Java::
++
+--
+Create the `src/main/java/org/acme/vehiclerouting/domain/Vehicle.java` class:
+
+[source,java]
+----
+package org.acme.vehiclerouting.domain;
+
+import java.time.LocalDateTime;
+import java.util.ArrayList;
+import java.util.List;
+
+import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
+import ai.timefold.solver.core.api.domain.lookup.PlanningId;
+import ai.timefold.solver.core.api.domain.variable.PlanningListVariable;
+
+@PlanningEntity
+public class Vehicle {
+
+ @PlanningId
+ private String id;
+ private int capacity;
+ private Location homeLocation;
+
+ private LocalDateTime departureTime;
+
+ @PlanningListVariable
+ private List<Visit> visits;
+
+ public Vehicle() {
+ }
+
+ public Vehicle(String id, int capacity, Location homeLocation, LocalDateTime departureTime) {
+ this.id = id;
+ this.capacity = capacity;
+ this.homeLocation = homeLocation;
+ this.departureTime = departureTime;
+ this.visits = new ArrayList<>();
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public int getCapacity() {
+ return capacity;
+ }
+
+ public void setCapacity(int capacity) {
+ this.capacity = capacity;
+ }
+
+ public Location getHomeLocation() {
+ return homeLocation;
+ }
+
+ public void setHomeLocation(Location homeLocation) {
+ this.homeLocation = homeLocation;
+ }
+
+ public LocalDateTime getDepartureTime() {
+ return departureTime;
+ }
+
+ public List<Visit> getVisits() {
+ return visits;
+ }
+
+ public void setVisits(List<Visit> visits) {
+ this.visits = visits;
+ }
+
+ public int getTotalDemand() {
+ int totalDemand = 0;
+ for (Visit visit : visits) {
+ totalDemand += visit.getDemand();
+ }
+ return totalDemand;
+ }
+
+ public long getTotalDrivingTimeSeconds() {
+ if (visits.isEmpty()) {
+ return 0;
+ }
+
+ long totalDrivingTime = 0;
+ Location previousLocation = homeLocation;
+
+ for (Visit visit : visits) {
+ totalDrivingTime += previousLocation.getDrivingTimeTo(visit.getLocation());
+ previousLocation = visit.getLocation();
+ }
+ totalDrivingTime += previousLocation.getDrivingTimeTo(homeLocation);
+
+ return totalDrivingTime;
+ }
+
+ @Override
+ public String toString() {
+ return id;
+ }
+}
+----
+--
+
+Kotlin::
++
+--
+Create the `src/main/kotlin/org/acme/vehiclerouting/domain/Vehicle.kt` class:
+
+[source,kotlin]
+----
+package org.acme.vehiclerouting.domain
+
+import java.time.LocalDateTime
+import java.util.ArrayList
+
+import ai.timefold.solver.core.api.domain.entity.PlanningEntity
+import ai.timefold.solver.core.api.domain.lookup.PlanningId
+import ai.timefold.solver.core.api.domain.variable.PlanningListVariable
+
+@PlanningEntity
+class Vehicle {
+ @PlanningId
+ lateinit var id: String
+ var capacity: Int = 0
+ lateinit var homeLocation: Location
+ lateinit var departureTime: LocalDateTime
+
+ @PlanningListVariable
+ var visits: List<Visit>? = null
+
+ constructor()
+
+ constructor(id: String, capacity: Int, homeLocation: Location, departureTime: LocalDateTime) {
+ this.id = id
+ this.capacity = capacity
+ this.homeLocation = homeLocation
+ this.departureTime = departureTime
+ this.visits = ArrayList()
+ }
+
+ val totalDemand: Long
+ get() {
+ var totalDemand = 0L
+ for (visit in visits!!) {
+ totalDemand += visit.demand
+ }
+ return totalDemand
+ }
+
+ val totalDrivingTimeSeconds: Long
+ get() {
+ if (visits!!.isEmpty()) {
+ return 0
+ }
+
+ var totalDrivingTime: Long = 0
+ var previousLocation = homeLocation
+
+ for (visit in visits!!) {
+ totalDrivingTime += previousLocation.getDrivingTimeTo(visit.location!!)
+ previousLocation = visit.location!!
+ }
+ totalDrivingTime += previousLocation.getDrivingTimeTo(homeLocation)
+
+ return totalDrivingTime
+ }
+
+ override fun toString(): String {
+ return id
+ }
+}
+----
+--
+====
+
+The `Vehicle` class has an `@PlanningEntity` annotation, so Timefold Solver knows that this class changes during solving
+because it contains one or more planning variables. | Aren't we repeating ourselves here? |
timefold-solver | github_2023 | others | 623 | TimefoldAI | triceo | @@ -0,0 +1,790 @@
+= Model the domain objects
+:imagesdir: ../..
+
+Your goal is to assign each visit to a vehicle.
+You will create these classes:
+
+image::quickstart/vehicle-routing/vehicleRoutingClassDiagramPure.png[]
+
+== Location
+
+The `Location` class is used to represent the destination for deliveries or the home location for vehicles.
+
+[tabs]
+====
+Java::
++
+--
+Create the `src/main/java/org/acme/vehiclerouting/domain/Location.java` class:
+
+[source,java]
+----
+package org.acme.vehiclerouting.domain;
+
+import java.util.Map;
+
+public class Location {
+
+ private double latitude;
+ private double longitude;
+
+ private Map<Location, Long> drivingTimeSeconds;
+
+ public Location(double latitude, double longitude) {
+ this.latitude = latitude;
+ this.longitude = longitude;
+ }
+
+ public double getLatitude() {
+ return latitude;
+ }
+
+ public double getLongitude() {
+ return longitude;
+ }
+
+ public Map<Location, Long> getDrivingTimeSeconds() {
+ return drivingTimeSeconds;
+ }
+
+ public void setDrivingTimeSeconds(Map<Location, Long> drivingTimeSeconds) {
+ this.drivingTimeSeconds = drivingTimeSeconds;
+ }
+
+ public long getDrivingTimeTo(Location location) {
+ return drivingTimeSeconds.get(location);
+ }
+}
+----
+--
+
+Kotlin::
++
+--
+Create the `src/main/kotlin/org/acme/vehiclerouting/domain/Location.kt` class:
+
+[source,kotlin]
+----
+package org.acme.vehiclerouting.domain
+
+class Location @JsonCreator constructor(val latitude: Double, val longitude: Double) {
+ var drivingTimeSeconds: Map<Location, Long>? = null
+
+ fun getDrivingTimeTo(location: Location): Long {
+ if (drivingTimeSeconds == null) {
+ return 0
+ }
+ return drivingTimeSeconds!![location]!!
+ }
+
+ override fun toString(): String {
+ return "$latitude,$longitude"
+ }
+}
+----
+--
+====
+
+== Vehicle
+
+`Vehicle` has a defined route plan with scheduled visits to make. Each vehicle has a specific departure time and
+starting location. It returns to its home location after completing the route and has a maximum capacity that must
+not be exceeded.
+
+During solving, Timefold Solver updates the `visits` field of the `Vehicle` class to assign a list of visits.
+Because Timefold Solver changes this field, `Vehicle` is a _planning entity_:
+
+image::quickstart/vehicle-routing/vehicleRoutingClassDiagramAnnotated.png[]
+
+Based on the diagram, the `visits` field is a genuine variable that changes during the solving process. To ensure that
+Timefold Solver recognizes it as a list of planning variables, the field must have an `@PlanningListVariable` annotation.
+
+[tabs]
+====
+Java::
++
+--
+Create the `src/main/java/org/acme/vehiclerouting/domain/Vehicle.java` class:
+
+[source,java]
+----
+package org.acme.vehiclerouting.domain;
+
+import java.time.LocalDateTime;
+import java.util.ArrayList;
+import java.util.List;
+
+import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
+import ai.timefold.solver.core.api.domain.lookup.PlanningId;
+import ai.timefold.solver.core.api.domain.variable.PlanningListVariable;
+
+@PlanningEntity
+public class Vehicle {
+
+ @PlanningId
+ private String id;
+ private int capacity;
+ private Location homeLocation;
+
+ private LocalDateTime departureTime;
+
+ @PlanningListVariable
+ private List<Visit> visits;
+
+ public Vehicle() {
+ }
+
+ public Vehicle(String id, int capacity, Location homeLocation, LocalDateTime departureTime) {
+ this.id = id;
+ this.capacity = capacity;
+ this.homeLocation = homeLocation;
+ this.departureTime = departureTime;
+ this.visits = new ArrayList<>();
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public int getCapacity() {
+ return capacity;
+ }
+
+ public void setCapacity(int capacity) {
+ this.capacity = capacity;
+ }
+
+ public Location getHomeLocation() {
+ return homeLocation;
+ }
+
+ public void setHomeLocation(Location homeLocation) {
+ this.homeLocation = homeLocation;
+ }
+
+ public LocalDateTime getDepartureTime() {
+ return departureTime;
+ }
+
+ public List<Visit> getVisits() {
+ return visits;
+ }
+
+ public void setVisits(List<Visit> visits) {
+ this.visits = visits;
+ }
+
+ public int getTotalDemand() {
+ int totalDemand = 0;
+ for (Visit visit : visits) {
+ totalDemand += visit.getDemand();
+ }
+ return totalDemand;
+ }
+
+ public long getTotalDrivingTimeSeconds() {
+ if (visits.isEmpty()) {
+ return 0;
+ }
+
+ long totalDrivingTime = 0;
+ Location previousLocation = homeLocation;
+
+ for (Visit visit : visits) {
+ totalDrivingTime += previousLocation.getDrivingTimeTo(visit.getLocation());
+ previousLocation = visit.getLocation();
+ }
+ totalDrivingTime += previousLocation.getDrivingTimeTo(homeLocation);
+
+ return totalDrivingTime;
+ }
+
+ @Override
+ public String toString() {
+ return id;
+ }
+}
+----
+--
+
+Kotlin::
++
+--
+Create the `src/main/kotlin/org/acme/vehiclerouting/domain/Vehicle.kt` class:
+
+[source,kotlin]
+----
+package org.acme.vehiclerouting.domain
+
+import java.time.LocalDateTime
+import java.util.ArrayList
+
+import ai.timefold.solver.core.api.domain.entity.PlanningEntity
+import ai.timefold.solver.core.api.domain.lookup.PlanningId
+import ai.timefold.solver.core.api.domain.variable.PlanningListVariable
+
+@PlanningEntity
+class Vehicle {
+ @PlanningId
+ lateinit var id: String
+ var capacity: Int = 0
+ lateinit var homeLocation: Location
+ lateinit var departureTime: LocalDateTime
+
+ @PlanningListVariable
+ var visits: List<Visit>? = null
+
+ constructor()
+
+ constructor(id: String, capacity: Int, homeLocation: Location, departureTime: LocalDateTime) {
+ this.id = id
+ this.capacity = capacity
+ this.homeLocation = homeLocation
+ this.departureTime = departureTime
+ this.visits = ArrayList()
+ }
+
+ val totalDemand: Long
+ get() {
+ var totalDemand = 0L
+ for (visit in visits!!) {
+ totalDemand += visit.demand
+ }
+ return totalDemand
+ }
+
+ val totalDrivingTimeSeconds: Long
+ get() {
+ if (visits!!.isEmpty()) {
+ return 0
+ }
+
+ var totalDrivingTime: Long = 0
+ var previousLocation = homeLocation
+
+ for (visit in visits!!) {
+ totalDrivingTime += previousLocation.getDrivingTimeTo(visit.location!!)
+ previousLocation = visit.location!!
+ }
+ totalDrivingTime += previousLocation.getDrivingTimeTo(homeLocation)
+
+ return totalDrivingTime
+ }
+
+ override fun toString(): String {
+ return id
+ }
+}
+----
+--
+====
+
+The `Vehicle` class has an `@PlanningEntity` annotation, so Timefold Solver knows that this class changes during solving
+because it contains one or more planning variables.
+
+The `visits` field is a planning list variable used to schedule a list of visits. It is annotated with `@PlanningListVariable`,
+indicating that the solver can distribute a subset of the available visits to it. The objective is to create an ordered
+scheduled visit plan for each vehicle. | This paragraph contains more information than the first one regarding the list variable, but I still wonder why does it duplicate some of the information. |
timefold-solver | github_2023 | others | 623 | TimefoldAI | triceo | @@ -0,0 +1,790 @@
+= Model the domain objects
+:imagesdir: ../..
+
+Your goal is to assign each visit to a vehicle.
+You will create these classes:
+
+image::quickstart/vehicle-routing/vehicleRoutingClassDiagramPure.png[]
+
+== Location
+
+The `Location` class is used to represent the destination for deliveries or the home location for vehicles.
+
+[tabs]
+====
+Java::
++
+--
+Create the `src/main/java/org/acme/vehiclerouting/domain/Location.java` class:
+
+[source,java]
+----
+package org.acme.vehiclerouting.domain;
+
+import java.util.Map;
+
+public class Location {
+
+ private double latitude;
+ private double longitude;
+
+ private Map<Location, Long> drivingTimeSeconds;
+
+ public Location(double latitude, double longitude) {
+ this.latitude = latitude;
+ this.longitude = longitude;
+ }
+
+ public double getLatitude() {
+ return latitude;
+ }
+
+ public double getLongitude() {
+ return longitude;
+ }
+
+ public Map<Location, Long> getDrivingTimeSeconds() {
+ return drivingTimeSeconds;
+ }
+
+ public void setDrivingTimeSeconds(Map<Location, Long> drivingTimeSeconds) {
+ this.drivingTimeSeconds = drivingTimeSeconds;
+ }
+
+ public long getDrivingTimeTo(Location location) {
+ return drivingTimeSeconds.get(location);
+ }
+}
+----
+--
+
+Kotlin::
++
+--
+Create the `src/main/kotlin/org/acme/vehiclerouting/domain/Location.kt` class:
+
+[source,kotlin]
+----
+package org.acme.vehiclerouting.domain
+
+class Location @JsonCreator constructor(val latitude: Double, val longitude: Double) {
+ var drivingTimeSeconds: Map<Location, Long>? = null
+
+ fun getDrivingTimeTo(location: Location): Long {
+ if (drivingTimeSeconds == null) {
+ return 0
+ }
+ return drivingTimeSeconds!![location]!!
+ }
+
+ override fun toString(): String {
+ return "$latitude,$longitude"
+ }
+}
+----
+--
+====
+
+== Vehicle
+
+`Vehicle` has a defined route plan with scheduled visits to make. Each vehicle has a specific departure time and
+starting location. It returns to its home location after completing the route and has a maximum capacity that must
+not be exceeded.
+
+During solving, Timefold Solver updates the `visits` field of the `Vehicle` class to assign a list of visits.
+Because Timefold Solver changes this field, `Vehicle` is a _planning entity_:
+
+image::quickstart/vehicle-routing/vehicleRoutingClassDiagramAnnotated.png[]
+
+Based on the diagram, the `visits` field is a genuine variable that changes during the solving process. To ensure that
+Timefold Solver recognizes it as a list of planning variables, the field must have an `@PlanningListVariable` annotation.
+
+[tabs]
+====
+Java::
++
+--
+Create the `src/main/java/org/acme/vehiclerouting/domain/Vehicle.java` class:
+
+[source,java]
+----
+package org.acme.vehiclerouting.domain;
+
+import java.time.LocalDateTime;
+import java.util.ArrayList;
+import java.util.List;
+
+import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
+import ai.timefold.solver.core.api.domain.lookup.PlanningId;
+import ai.timefold.solver.core.api.domain.variable.PlanningListVariable;
+
+@PlanningEntity
+public class Vehicle {
+
+ @PlanningId
+ private String id;
+ private int capacity;
+ private Location homeLocation;
+
+ private LocalDateTime departureTime;
+
+ @PlanningListVariable
+ private List<Visit> visits;
+
+ public Vehicle() {
+ }
+
+ public Vehicle(String id, int capacity, Location homeLocation, LocalDateTime departureTime) {
+ this.id = id;
+ this.capacity = capacity;
+ this.homeLocation = homeLocation;
+ this.departureTime = departureTime;
+ this.visits = new ArrayList<>();
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public int getCapacity() {
+ return capacity;
+ }
+
+ public void setCapacity(int capacity) {
+ this.capacity = capacity;
+ }
+
+ public Location getHomeLocation() {
+ return homeLocation;
+ }
+
+ public void setHomeLocation(Location homeLocation) {
+ this.homeLocation = homeLocation;
+ }
+
+ public LocalDateTime getDepartureTime() {
+ return departureTime;
+ }
+
+ public List<Visit> getVisits() {
+ return visits;
+ }
+
+ public void setVisits(List<Visit> visits) {
+ this.visits = visits;
+ }
+
+ public int getTotalDemand() {
+ int totalDemand = 0;
+ for (Visit visit : visits) {
+ totalDemand += visit.getDemand();
+ }
+ return totalDemand;
+ }
+
+ public long getTotalDrivingTimeSeconds() {
+ if (visits.isEmpty()) {
+ return 0;
+ }
+
+ long totalDrivingTime = 0;
+ Location previousLocation = homeLocation;
+
+ for (Visit visit : visits) {
+ totalDrivingTime += previousLocation.getDrivingTimeTo(visit.getLocation());
+ previousLocation = visit.getLocation();
+ }
+ totalDrivingTime += previousLocation.getDrivingTimeTo(homeLocation);
+
+ return totalDrivingTime;
+ }
+
+ @Override
+ public String toString() {
+ return id;
+ }
+}
+----
+--
+
+Kotlin::
++
+--
+Create the `src/main/kotlin/org/acme/vehiclerouting/domain/Vehicle.kt` class:
+
+[source,kotlin]
+----
+package org.acme.vehiclerouting.domain
+
+import java.time.LocalDateTime
+import java.util.ArrayList
+
+import ai.timefold.solver.core.api.domain.entity.PlanningEntity
+import ai.timefold.solver.core.api.domain.lookup.PlanningId
+import ai.timefold.solver.core.api.domain.variable.PlanningListVariable
+
+@PlanningEntity
+class Vehicle {
+ @PlanningId
+ lateinit var id: String
+ var capacity: Int = 0
+ lateinit var homeLocation: Location
+ lateinit var departureTime: LocalDateTime
+
+ @PlanningListVariable
+ var visits: List<Visit>? = null
+
+ constructor()
+
+ constructor(id: String, capacity: Int, homeLocation: Location, departureTime: LocalDateTime) {
+ this.id = id
+ this.capacity = capacity
+ this.homeLocation = homeLocation
+ this.departureTime = departureTime
+ this.visits = ArrayList()
+ }
+
+ val totalDemand: Long
+ get() {
+ var totalDemand = 0L
+ for (visit in visits!!) {
+ totalDemand += visit.demand
+ }
+ return totalDemand
+ }
+
+ val totalDrivingTimeSeconds: Long
+ get() {
+ if (visits!!.isEmpty()) {
+ return 0
+ }
+
+ var totalDrivingTime: Long = 0
+ var previousLocation = homeLocation
+
+ for (visit in visits!!) {
+ totalDrivingTime += previousLocation.getDrivingTimeTo(visit.location!!)
+ previousLocation = visit.location!!
+ }
+ totalDrivingTime += previousLocation.getDrivingTimeTo(homeLocation)
+
+ return totalDrivingTime
+ }
+
+ override fun toString(): String {
+ return id
+ }
+}
+----
+--
+====
+
+The `Vehicle` class has an `@PlanningEntity` annotation, so Timefold Solver knows that this class changes during solving
+because it contains one or more planning variables.
+
+The `visits` field is a planning list variable used to schedule a list of visits. It is annotated with `@PlanningListVariable`,
+indicating that the solver can distribute a subset of the available visits to it. The objective is to create an ordered
+scheduled visit plan for each vehicle.
+
+Notice the `toString()` method keeps the output short, so it is easier to read Timefold Solver's `DEBUG` or `TRACE` log,
+as shown later.
+
+[NOTE]
+====
+Determining the `@PlanningListVariable` fields for an arbitrary constraint solving use case
+is often challenging the first time.
+Read xref:design-patterns/design-patterns.adoc#domainModelingGuide[the domain modeling guidelines] to avoid common pitfalls.
+====
+
+== Visit
+
+The `Visit` class represents a delivery that needs to be made by vehicles. A visit includes a destination location, a
+delivery time window represented by `[minStartTime, maxEndTime]`, a demand that needs to be fulfilled by the vehicle,
+and a service duration time.
+
+[tabs]
+====
+Java::
++
+--
+Create the `src/main/java/org/acme/vehiclerouting/domain/Visit.java` class:
+
+[source,java]
+----
+package org.acme.vehiclerouting.domain;
+
+import java.time.Duration;
+import java.time.LocalDateTime;
+
+import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
+import ai.timefold.solver.core.api.domain.lookup.PlanningId;
+import ai.timefold.solver.core.api.domain.variable.InverseRelationShadowVariable;
+import ai.timefold.solver.core.api.domain.variable.NextElementShadowVariable;
+import ai.timefold.solver.core.api.domain.variable.PreviousElementShadowVariable;
+import ai.timefold.solver.core.api.domain.variable.ShadowVariable;
+
+import org.acme.vehiclerouting.solver.ArrivalTimeUpdatingVariableListener;
+
+@PlanningEntity
+public class Visit {
+
+ @PlanningId
+ private String id;
+ private String name;
+ private Location location;
+ private int demand;
+ private LocalDateTime minStartTime;
+ private LocalDateTime maxEndTime;
+ private Duration serviceDuration;
+
+ private Vehicle vehicle;
+
+ private Visit previousVisit;
+
+ private Visit nextVisit;
+
+ private LocalDateTime arrivalTime;
+
+ public Visit() {
+ }
+
+ public Visit(String id, String name, Location location, int demand,
+ LocalDateTime minStartTime, LocalDateTime maxEndTime, Duration serviceDuration) {
+ this.id = id;
+ this.name = name;
+ this.location = location;
+ this.demand = demand;
+ this.minStartTime = minStartTime;
+ this.maxEndTime = maxEndTime;
+ this.serviceDuration = serviceDuration;
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public Location getLocation() {
+ return location;
+ }
+
+ public void setLocation(Location location) {
+ this.location = location;
+ }
+
+ public int getDemand() {
+ return demand;
+ }
+
+ public void setDemand(int demand) {
+ this.demand = demand;
+ }
+
+ public LocalDateTime getMinStartTime() {
+ return minStartTime;
+ }
+
+ public LocalDateTime getMaxEndTime() {
+ return maxEndTime;
+ }
+
+ public Duration getServiceDuration() {
+ return serviceDuration;
+ }
+
+ @InverseRelationShadowVariable(sourceVariableName = "visits")
+ public Vehicle getVehicle() {
+ return vehicle;
+ }
+
+ public void setVehicle(Vehicle vehicle) {
+ this.vehicle = vehicle;
+ }
+
+ @PreviousElementShadowVariable(sourceVariableName = "visits")
+ public Visit getPreviousVisit() {
+ return previousVisit;
+ }
+
+ public void setPreviousVisit(Visit previousVisit) {
+ this.previousVisit = previousVisit;
+ }
+
+ @NextElementShadowVariable(sourceVariableName = "visits")
+ public Visit getNextVisit() {
+ return nextVisit;
+ }
+
+ public void setNextVisit(Visit nextVisit) {
+ this.nextVisit = nextVisit;
+ }
+
+ @ShadowVariable(variableListenerClass = ArrivalTimeUpdatingVariableListener.class, sourceVariableName = "vehicle")
+ @ShadowVariable(variableListenerClass = ArrivalTimeUpdatingVariableListener.class, sourceVariableName = "previousVisit")
+ public LocalDateTime getArrivalTime() {
+ return arrivalTime;
+ }
+
+ public void setArrivalTime(LocalDateTime arrivalTime) {
+ this.arrivalTime = arrivalTime;
+ }
+
+ public LocalDateTime getDepartureTime() {
+ if (arrivalTime == null) {
+ return null;
+ }
+ return getStartServiceTime().plus(serviceDuration);
+ }
+
+ public LocalDateTime getStartServiceTime() {
+ if (arrivalTime == null) {
+ return null;
+ }
+ return arrivalTime.isBefore(minStartTime) ? minStartTime : arrivalTime;
+ }
+
+ public boolean isServiceFinishedAfterMaxEndTime() {
+ return arrivalTime != null
+ && arrivalTime.plus(serviceDuration).isAfter(maxEndTime);
+ }
+
+ public long getServiceFinishedDelayInMinutes() {
+ if (arrivalTime == null) {
+ return 0;
+ }
+ return Duration.between(maxEndTime, arrivalTime.plus(serviceDuration)).toMinutes();
+ }
+
+ public long getDrivingTimeSecondsFromPreviousStandstill() {
+ if (vehicle == null) {
+ throw new IllegalStateException(
+ "This method must not be called when the shadow variables are not initialized yet.");
+ }
+ if (previousVisit == null) {
+ return vehicle.getHomeLocation().getDrivingTimeTo(location);
+ }
+ return previousVisit.getLocation().getDrivingTimeTo(location);
+ }
+
+ @Override
+ public String toString() {
+ return id;
+ }
+}
+----
+--
+
+Kotlin::
++
+--
+Create the `src/main/kotlin/org/acme/vehiclerouting/domain/Visit.kt` class:
+
+[source,kotlin]
+----
+package org.acme.vehiclerouting.domain
+
+import java.time.Duration
+import java.time.LocalDateTime
+
+import ai.timefold.solver.core.api.domain.entity.PlanningEntity
+import ai.timefold.solver.core.api.domain.lookup.PlanningId
+import ai.timefold.solver.core.api.domain.variable.InverseRelationShadowVariable
+import ai.timefold.solver.core.api.domain.variable.NextElementShadowVariable
+import ai.timefold.solver.core.api.domain.variable.PreviousElementShadowVariable
+import ai.timefold.solver.core.api.domain.variable.ShadowVariable
+
+import org.acme.vehiclerouting.solver.ArrivalTimeUpdatingVariableListener
+
+@PlanningEntity
+class Visit {
+ @PlanningId
+ lateinit var id: String
+ lateinit var name: String
+ lateinit var location: Location
+ var demand: Int = 0
+ lateinit var minStartTime: LocalDateTime
+ lateinit var maxEndTime: LocalDateTime
+ lateinit var serviceDuration: Duration
+
+ private var vehicle: Vehicle? = null
+
+ @get:PreviousElementShadowVariable(sourceVariableName = "visits")
+ var previousVisit: Visit? = null
+
+ @get:NextElementShadowVariable(sourceVariableName = "visits")
+ var nextVisit: Visit? = null
+
+ @get:ShadowVariable(
+ variableListenerClass = ArrivalTimeUpdatingVariableListener::class,
+ sourceVariableName = "previousVisit"
+ )
+ @get:ShadowVariable(
+ variableListenerClass = ArrivalTimeUpdatingVariableListener::class,
+ sourceVariableName = "vehicle"
+ )
+ var arrivalTime: LocalDateTime? = null
+
+ constructor()
+
+ constructor(
+ id: String, name: String, location: Location, demand: Int,
+ minStartTime: LocalDateTime, maxEndTime: LocalDateTime, serviceDuration: Duration
+ ) {
+ this.id = id
+ this.name = name
+ this.location = location
+ this.demand = demand
+ this.minStartTime = minStartTime
+ this.maxEndTime = maxEndTime
+ this.serviceDuration = serviceDuration
+ }
+
+ @InverseRelationShadowVariable(sourceVariableName = "visits")
+ fun getVehicle(): Vehicle? {
+ return vehicle
+ }
+
+ fun setVehicle(vehicle: Vehicle?) {
+ this.vehicle = vehicle
+ }
+
+ val departureTime: LocalDateTime?
+ get() {
+ if (arrivalTime == null) {
+ return null
+ }
+ return startServiceTime!!.plus(serviceDuration)
+ }
+
+ val startServiceTime: LocalDateTime?
+ get() {
+ if (arrivalTime == null) {
+ return null
+ }
+ return if (arrivalTime!!.isBefore(minStartTime)) minStartTime else arrivalTime
+ }
+
+ val isServiceFinishedAfterMaxEndTime: Boolean
+ get() = (arrivalTime != null
+ && arrivalTime!!.plus(serviceDuration).isAfter(maxEndTime))
+
+ val serviceFinishedDelayInMinutes: Long
+ get() {
+ if (arrivalTime == null) {
+ return 0
+ }
+ return Duration.between(maxEndTime, arrivalTime!!.plus(serviceDuration)).toMinutes()
+ }
+
+ val drivingTimeSecondsFromPreviousStandstill: Long
+ get() {
+ if (vehicle == null) {
+ throw IllegalStateException(
+ "This method must not be called when the shadow variables are not initialized yet."
+ )
+ }
+ if (previousVisit == null) {
+ return vehicle!!.homeLocation.getDrivingTimeTo(location)
+ }
+ return previousVisit!!.location.getDrivingTimeTo((location))
+ }
+
+ override fun toString(): String {
+ return id
+ }
+}
+----
+--
+====
+
+Some methods are annotated with `@InverseRelationShadowVariable`, `@PreviousElementShadowVariable`,
+`@NextElementShadowVariable`, and `@ShadowVariable`. They are called shadow variables, and because Timefold Solver
+changes them, `Visit` is a _planning entity_: | Link to section on shadow variables? |
timefold-solver | github_2023 | others | 623 | TimefoldAI | triceo | @@ -0,0 +1,790 @@
+= Model the domain objects
+:imagesdir: ../..
+
+Your goal is to assign each visit to a vehicle.
+You will create these classes:
+
+image::quickstart/vehicle-routing/vehicleRoutingClassDiagramPure.png[]
+
+== Location
+
+The `Location` class is used to represent the destination for deliveries or the home location for vehicles.
+
+[tabs]
+====
+Java::
++
+--
+Create the `src/main/java/org/acme/vehiclerouting/domain/Location.java` class:
+
+[source,java]
+----
+package org.acme.vehiclerouting.domain;
+
+import java.util.Map;
+
+public class Location {
+
+ private double latitude;
+ private double longitude;
+
+ private Map<Location, Long> drivingTimeSeconds;
+
+ public Location(double latitude, double longitude) {
+ this.latitude = latitude;
+ this.longitude = longitude;
+ }
+
+ public double getLatitude() {
+ return latitude;
+ }
+
+ public double getLongitude() {
+ return longitude;
+ }
+
+ public Map<Location, Long> getDrivingTimeSeconds() {
+ return drivingTimeSeconds;
+ }
+
+ public void setDrivingTimeSeconds(Map<Location, Long> drivingTimeSeconds) {
+ this.drivingTimeSeconds = drivingTimeSeconds;
+ }
+
+ public long getDrivingTimeTo(Location location) {
+ return drivingTimeSeconds.get(location);
+ }
+}
+----
+--
+
+Kotlin::
++
+--
+Create the `src/main/kotlin/org/acme/vehiclerouting/domain/Location.kt` class:
+
+[source,kotlin]
+----
+package org.acme.vehiclerouting.domain
+
+class Location @JsonCreator constructor(val latitude: Double, val longitude: Double) {
+ var drivingTimeSeconds: Map<Location, Long>? = null
+
+ fun getDrivingTimeTo(location: Location): Long {
+ if (drivingTimeSeconds == null) {
+ return 0
+ }
+ return drivingTimeSeconds!![location]!!
+ }
+
+ override fun toString(): String {
+ return "$latitude,$longitude"
+ }
+}
+----
+--
+====
+
+== Vehicle
+
+`Vehicle` has a defined route plan with scheduled visits to make. Each vehicle has a specific departure time and
+starting location. It returns to its home location after completing the route and has a maximum capacity that must
+not be exceeded.
+
+During solving, Timefold Solver updates the `visits` field of the `Vehicle` class to assign a list of visits.
+Because Timefold Solver changes this field, `Vehicle` is a _planning entity_:
+
+image::quickstart/vehicle-routing/vehicleRoutingClassDiagramAnnotated.png[]
+
+Based on the diagram, the `visits` field is a genuine variable that changes during the solving process. To ensure that
+Timefold Solver recognizes it as a list of planning variables, the field must have an `@PlanningListVariable` annotation.
+
+[tabs]
+====
+Java::
++
+--
+Create the `src/main/java/org/acme/vehiclerouting/domain/Vehicle.java` class:
+
+[source,java]
+----
+package org.acme.vehiclerouting.domain;
+
+import java.time.LocalDateTime;
+import java.util.ArrayList;
+import java.util.List;
+
+import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
+import ai.timefold.solver.core.api.domain.lookup.PlanningId;
+import ai.timefold.solver.core.api.domain.variable.PlanningListVariable;
+
+@PlanningEntity
+public class Vehicle {
+
+ @PlanningId
+ private String id;
+ private int capacity;
+ private Location homeLocation;
+
+ private LocalDateTime departureTime;
+
+ @PlanningListVariable
+ private List<Visit> visits;
+
+ public Vehicle() {
+ }
+
+ public Vehicle(String id, int capacity, Location homeLocation, LocalDateTime departureTime) {
+ this.id = id;
+ this.capacity = capacity;
+ this.homeLocation = homeLocation;
+ this.departureTime = departureTime;
+ this.visits = new ArrayList<>();
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public int getCapacity() {
+ return capacity;
+ }
+
+ public void setCapacity(int capacity) {
+ this.capacity = capacity;
+ }
+
+ public Location getHomeLocation() {
+ return homeLocation;
+ }
+
+ public void setHomeLocation(Location homeLocation) {
+ this.homeLocation = homeLocation;
+ }
+
+ public LocalDateTime getDepartureTime() {
+ return departureTime;
+ }
+
+ public List<Visit> getVisits() {
+ return visits;
+ }
+
+ public void setVisits(List<Visit> visits) {
+ this.visits = visits;
+ }
+
+ public int getTotalDemand() {
+ int totalDemand = 0;
+ for (Visit visit : visits) {
+ totalDemand += visit.getDemand();
+ }
+ return totalDemand;
+ }
+
+ public long getTotalDrivingTimeSeconds() {
+ if (visits.isEmpty()) {
+ return 0;
+ }
+
+ long totalDrivingTime = 0;
+ Location previousLocation = homeLocation;
+
+ for (Visit visit : visits) {
+ totalDrivingTime += previousLocation.getDrivingTimeTo(visit.getLocation());
+ previousLocation = visit.getLocation();
+ }
+ totalDrivingTime += previousLocation.getDrivingTimeTo(homeLocation);
+
+ return totalDrivingTime;
+ }
+
+ @Override
+ public String toString() {
+ return id;
+ }
+}
+----
+--
+
+Kotlin::
++
+--
+Create the `src/main/kotlin/org/acme/vehiclerouting/domain/Vehicle.kt` class:
+
+[source,kotlin]
+----
+package org.acme.vehiclerouting.domain
+
+import java.time.LocalDateTime
+import java.util.ArrayList
+
+import ai.timefold.solver.core.api.domain.entity.PlanningEntity
+import ai.timefold.solver.core.api.domain.lookup.PlanningId
+import ai.timefold.solver.core.api.domain.variable.PlanningListVariable
+
+@PlanningEntity
+class Vehicle {
+ @PlanningId
+ lateinit var id: String
+ var capacity: Int = 0
+ lateinit var homeLocation: Location
+ lateinit var departureTime: LocalDateTime
+
+ @PlanningListVariable
+ var visits: List<Visit>? = null
+
+ constructor()
+
+ constructor(id: String, capacity: Int, homeLocation: Location, departureTime: LocalDateTime) {
+ this.id = id
+ this.capacity = capacity
+ this.homeLocation = homeLocation
+ this.departureTime = departureTime
+ this.visits = ArrayList()
+ }
+
+ val totalDemand: Long
+ get() {
+ var totalDemand = 0L
+ for (visit in visits!!) {
+ totalDemand += visit.demand
+ }
+ return totalDemand
+ }
+
+ val totalDrivingTimeSeconds: Long
+ get() {
+ if (visits!!.isEmpty()) {
+ return 0
+ }
+
+ var totalDrivingTime: Long = 0
+ var previousLocation = homeLocation
+
+ for (visit in visits!!) {
+ totalDrivingTime += previousLocation.getDrivingTimeTo(visit.location!!)
+ previousLocation = visit.location!!
+ }
+ totalDrivingTime += previousLocation.getDrivingTimeTo(homeLocation)
+
+ return totalDrivingTime
+ }
+
+ override fun toString(): String {
+ return id
+ }
+}
+----
+--
+====
+
+The `Vehicle` class has an `@PlanningEntity` annotation, so Timefold Solver knows that this class changes during solving
+because it contains one or more planning variables.
+
+The `visits` field is a planning list variable used to schedule a list of visits. It is annotated with `@PlanningListVariable`,
+indicating that the solver can distribute a subset of the available visits to it. The objective is to create an ordered
+scheduled visit plan for each vehicle.
+
+Notice the `toString()` method keeps the output short, so it is easier to read Timefold Solver's `DEBUG` or `TRACE` log,
+as shown later.
+
+[NOTE]
+====
+Determining the `@PlanningListVariable` fields for an arbitrary constraint solving use case
+is often challenging the first time.
+Read xref:design-patterns/design-patterns.adoc#domainModelingGuide[the domain modeling guidelines] to avoid common pitfalls.
+====
+
+== Visit
+
+The `Visit` class represents a delivery that needs to be made by vehicles. A visit includes a destination location, a
+delivery time window represented by `[minStartTime, maxEndTime]`, a demand that needs to be fulfilled by the vehicle,
+and a service duration time.
+
+[tabs]
+====
+Java::
++
+--
+Create the `src/main/java/org/acme/vehiclerouting/domain/Visit.java` class:
+
+[source,java]
+----
+package org.acme.vehiclerouting.domain;
+
+import java.time.Duration;
+import java.time.LocalDateTime;
+
+import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
+import ai.timefold.solver.core.api.domain.lookup.PlanningId;
+import ai.timefold.solver.core.api.domain.variable.InverseRelationShadowVariable;
+import ai.timefold.solver.core.api.domain.variable.NextElementShadowVariable;
+import ai.timefold.solver.core.api.domain.variable.PreviousElementShadowVariable;
+import ai.timefold.solver.core.api.domain.variable.ShadowVariable;
+
+import org.acme.vehiclerouting.solver.ArrivalTimeUpdatingVariableListener;
+
+@PlanningEntity
+public class Visit {
+
+ @PlanningId
+ private String id;
+ private String name;
+ private Location location;
+ private int demand;
+ private LocalDateTime minStartTime;
+ private LocalDateTime maxEndTime;
+ private Duration serviceDuration;
+
+ private Vehicle vehicle;
+
+ private Visit previousVisit;
+
+ private Visit nextVisit;
+
+ private LocalDateTime arrivalTime;
+
+ public Visit() {
+ }
+
+ public Visit(String id, String name, Location location, int demand,
+ LocalDateTime minStartTime, LocalDateTime maxEndTime, Duration serviceDuration) {
+ this.id = id;
+ this.name = name;
+ this.location = location;
+ this.demand = demand;
+ this.minStartTime = minStartTime;
+ this.maxEndTime = maxEndTime;
+ this.serviceDuration = serviceDuration;
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public Location getLocation() {
+ return location;
+ }
+
+ public void setLocation(Location location) {
+ this.location = location;
+ }
+
+ public int getDemand() {
+ return demand;
+ }
+
+ public void setDemand(int demand) {
+ this.demand = demand;
+ }
+
+ public LocalDateTime getMinStartTime() {
+ return minStartTime;
+ }
+
+ public LocalDateTime getMaxEndTime() {
+ return maxEndTime;
+ }
+
+ public Duration getServiceDuration() {
+ return serviceDuration;
+ }
+
+ @InverseRelationShadowVariable(sourceVariableName = "visits")
+ public Vehicle getVehicle() {
+ return vehicle;
+ }
+
+ public void setVehicle(Vehicle vehicle) {
+ this.vehicle = vehicle;
+ }
+
+ @PreviousElementShadowVariable(sourceVariableName = "visits")
+ public Visit getPreviousVisit() {
+ return previousVisit;
+ }
+
+ public void setPreviousVisit(Visit previousVisit) {
+ this.previousVisit = previousVisit;
+ }
+
+ @NextElementShadowVariable(sourceVariableName = "visits")
+ public Visit getNextVisit() {
+ return nextVisit;
+ }
+
+ public void setNextVisit(Visit nextVisit) {
+ this.nextVisit = nextVisit;
+ }
+
+ @ShadowVariable(variableListenerClass = ArrivalTimeUpdatingVariableListener.class, sourceVariableName = "vehicle")
+ @ShadowVariable(variableListenerClass = ArrivalTimeUpdatingVariableListener.class, sourceVariableName = "previousVisit")
+ public LocalDateTime getArrivalTime() {
+ return arrivalTime;
+ }
+
+ public void setArrivalTime(LocalDateTime arrivalTime) {
+ this.arrivalTime = arrivalTime;
+ }
+
+ public LocalDateTime getDepartureTime() {
+ if (arrivalTime == null) {
+ return null;
+ }
+ return getStartServiceTime().plus(serviceDuration);
+ }
+
+ public LocalDateTime getStartServiceTime() {
+ if (arrivalTime == null) {
+ return null;
+ }
+ return arrivalTime.isBefore(minStartTime) ? minStartTime : arrivalTime;
+ }
+
+ public boolean isServiceFinishedAfterMaxEndTime() {
+ return arrivalTime != null
+ && arrivalTime.plus(serviceDuration).isAfter(maxEndTime);
+ }
+
+ public long getServiceFinishedDelayInMinutes() {
+ if (arrivalTime == null) {
+ return 0;
+ }
+ return Duration.between(maxEndTime, arrivalTime.plus(serviceDuration)).toMinutes();
+ }
+
+ public long getDrivingTimeSecondsFromPreviousStandstill() {
+ if (vehicle == null) {
+ throw new IllegalStateException(
+ "This method must not be called when the shadow variables are not initialized yet.");
+ }
+ if (previousVisit == null) {
+ return vehicle.getHomeLocation().getDrivingTimeTo(location);
+ }
+ return previousVisit.getLocation().getDrivingTimeTo(location);
+ }
+
+ @Override
+ public String toString() {
+ return id;
+ }
+}
+----
+--
+
+Kotlin::
++
+--
+Create the `src/main/kotlin/org/acme/vehiclerouting/domain/Visit.kt` class:
+
+[source,kotlin]
+----
+package org.acme.vehiclerouting.domain
+
+import java.time.Duration
+import java.time.LocalDateTime
+
+import ai.timefold.solver.core.api.domain.entity.PlanningEntity
+import ai.timefold.solver.core.api.domain.lookup.PlanningId
+import ai.timefold.solver.core.api.domain.variable.InverseRelationShadowVariable
+import ai.timefold.solver.core.api.domain.variable.NextElementShadowVariable
+import ai.timefold.solver.core.api.domain.variable.PreviousElementShadowVariable
+import ai.timefold.solver.core.api.domain.variable.ShadowVariable
+
+import org.acme.vehiclerouting.solver.ArrivalTimeUpdatingVariableListener
+
+@PlanningEntity
+class Visit {
+ @PlanningId
+ lateinit var id: String
+ lateinit var name: String
+ lateinit var location: Location
+ var demand: Int = 0
+ lateinit var minStartTime: LocalDateTime
+ lateinit var maxEndTime: LocalDateTime
+ lateinit var serviceDuration: Duration
+
+ private var vehicle: Vehicle? = null
+
+ @get:PreviousElementShadowVariable(sourceVariableName = "visits")
+ var previousVisit: Visit? = null
+
+ @get:NextElementShadowVariable(sourceVariableName = "visits")
+ var nextVisit: Visit? = null
+
+ @get:ShadowVariable(
+ variableListenerClass = ArrivalTimeUpdatingVariableListener::class,
+ sourceVariableName = "previousVisit"
+ )
+ @get:ShadowVariable(
+ variableListenerClass = ArrivalTimeUpdatingVariableListener::class,
+ sourceVariableName = "vehicle"
+ )
+ var arrivalTime: LocalDateTime? = null
+
+ constructor()
+
+ constructor(
+ id: String, name: String, location: Location, demand: Int,
+ minStartTime: LocalDateTime, maxEndTime: LocalDateTime, serviceDuration: Duration
+ ) {
+ this.id = id
+ this.name = name
+ this.location = location
+ this.demand = demand
+ this.minStartTime = minStartTime
+ this.maxEndTime = maxEndTime
+ this.serviceDuration = serviceDuration
+ }
+
+ @InverseRelationShadowVariable(sourceVariableName = "visits")
+ fun getVehicle(): Vehicle? {
+ return vehicle
+ }
+
+ fun setVehicle(vehicle: Vehicle?) {
+ this.vehicle = vehicle
+ }
+
+ val departureTime: LocalDateTime?
+ get() {
+ if (arrivalTime == null) {
+ return null
+ }
+ return startServiceTime!!.plus(serviceDuration)
+ }
+
+ val startServiceTime: LocalDateTime?
+ get() {
+ if (arrivalTime == null) {
+ return null
+ }
+ return if (arrivalTime!!.isBefore(minStartTime)) minStartTime else arrivalTime
+ }
+
+ val isServiceFinishedAfterMaxEndTime: Boolean
+ get() = (arrivalTime != null
+ && arrivalTime!!.plus(serviceDuration).isAfter(maxEndTime))
+
+ val serviceFinishedDelayInMinutes: Long
+ get() {
+ if (arrivalTime == null) {
+ return 0
+ }
+ return Duration.between(maxEndTime, arrivalTime!!.plus(serviceDuration)).toMinutes()
+ }
+
+ val drivingTimeSecondsFromPreviousStandstill: Long
+ get() {
+ if (vehicle == null) {
+ throw IllegalStateException(
+ "This method must not be called when the shadow variables are not initialized yet."
+ )
+ }
+ if (previousVisit == null) {
+ return vehicle!!.homeLocation.getDrivingTimeTo(location)
+ }
+ return previousVisit!!.location.getDrivingTimeTo((location))
+ }
+
+ override fun toString(): String {
+ return id
+ }
+}
+----
+--
+====
+
+Some methods are annotated with `@InverseRelationShadowVariable`, `@PreviousElementShadowVariable`,
+`@NextElementShadowVariable`, and `@ShadowVariable`. They are called shadow variables, and because Timefold Solver
+changes them, `Visit` is a _planning entity_:
+
+image::quickstart/vehicle-routing/vehicleRoutingCompleteClassDiagramAnnotated.png[]
+
+The method `getVehicle()` has an `@InverseRelationShadowVariable` annotation, creating a bi-directional relationship
+with the `Vehicle`. The function returns a reference to the `Vehicle` where the visit is scheduled. Let's say the visit
+`Ann` was scheduled to the vehicle `V1` during the solving process. The method returns a reference of `V1`.
+
+The methods `getPreviousVisit()` and `getNextVisit()` are annotated with `@PreviousElementShadowVariable` and
+`@NextElementShadowVariable`, respectively. The Solver returns a reference of the previous and next visit of | ```suggestion
`@NextElementShadowVariable`, respectively. The method returns a reference of the previous and next visit of
``` |
timefold-solver | github_2023 | others | 623 | TimefoldAI | triceo | @@ -0,0 +1,518 @@
+= Gather the domain objects in a planning solution
+:imagesdir: ../..
+
+A `VehicleRoutePlan` wraps all `Vehicle` and `Visit` instances of a single dataset.
+Furthermore, because it contains all vehicles and visits, each with a specific planning variable state,
+it is a _planning solution_ and it has a score: | Link to planning solution doc. |
timefold-solver | github_2023 | others | 623 | TimefoldAI | triceo | @@ -0,0 +1,518 @@
+= Gather the domain objects in a planning solution
+:imagesdir: ../..
+
+A `VehicleRoutePlan` wraps all `Vehicle` and `Visit` instances of a single dataset.
+Furthermore, because it contains all vehicles and visits, each with a specific planning variable state,
+it is a _planning solution_ and it has a score:
+
+* If visits are still unassigned, then it is an _uninitialized_ solution,
+for example, a solution with the score `-4init/0hard/0soft`.
+* If it breaks hard constraints, then it is an _infeasible_ solution,
+for example, a solution with the score `-2hard/-3soft`.
+* If it adheres to all hard constraints, then it is a _feasible_ solution,
+for example, a solution with the score `0hard/-7soft`.
+
+[tabs]
+====
+Java::
++
+--
+Create the `src/main/java/org/acme/vehiclerouting/domain/VehicleRoutePlan.java` class:
+
+[source,java]
+----
+package org.acme.vehiclerouting.domain;
+
+import java.time.LocalDateTime;
+import java.util.List;
+import java.util.stream.Stream;
+
+import ai.timefold.solver.core.api.domain.solution.PlanningEntityCollectionProperty;
+import ai.timefold.solver.core.api.domain.solution.PlanningScore;
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
+import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider;
+import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore;
+import ai.timefold.solver.core.api.solver.SolverStatus;
+
+import org.acme.vehiclerouting.domain.geo.DrivingTimeCalculator;
+import org.acme.vehiclerouting.domain.geo.HaversineDrivingTimeCalculator;
+
+@PlanningSolution
+public class VehicleRoutePlan {
+
+ private String name;
+
+ private Location southWestCorner;
+ private Location northEastCorner;
+
+ private LocalDateTime startDateTime;
+
+ private LocalDateTime endDateTime;
+
+ @PlanningEntityCollectionProperty
+ private List<Vehicle> vehicles;
+
+ @PlanningEntityCollectionProperty
+ @ValueRangeProvider
+ private List<Visit> visits;
+
+ @PlanningScore
+ private HardSoftLongScore score;
+
+ private SolverStatus solverStatus;
+
+ private String scoreExplanation;
+
+ public VehicleRoutePlan() {
+ }
+
+ public VehicleRoutePlan(String name, HardSoftLongScore score, SolverStatus solverStatus) {
+ this.name = name;
+ this.score = score;
+ this.solverStatus = solverStatus;
+ }
+
+ public VehicleRoutePlan(String name,
+ Location southWestCorner,
+ Location northEastCorner,
+ LocalDateTime startDateTime,
+ LocalDateTime endDateTime,
+ List<Vehicle> vehicles,
+ List<Visit> visits) {
+ this.name = name;
+ this.southWestCorner = southWestCorner;
+ this.northEastCorner = northEastCorner;
+ this.startDateTime = startDateTime;
+ this.endDateTime = endDateTime;
+ this.vehicles = vehicles;
+ this.visits = visits;
+ List<Location> locations = Stream.concat(
+ vehicles.stream().map(Vehicle::getHomeLocation),
+ visits.stream().map(Visit::getLocation)).toList();
+
+ DrivingTimeCalculator drivingTimeCalculator = HaversineDrivingTimeCalculator.getInstance();
+ drivingTimeCalculator.initDrivingTimeMaps(locations);
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public Location getSouthWestCorner() {
+ return southWestCorner;
+ }
+
+ public Location getNorthEastCorner() {
+ return northEastCorner;
+ }
+
+ public LocalDateTime getStartDateTime() {
+ return startDateTime;
+ }
+
+ public LocalDateTime getEndDateTime() {
+ return endDateTime;
+ }
+
+ public List<Vehicle> getVehicles() {
+ return vehicles;
+ }
+
+ public List<Visit> getVisits() {
+ return visits;
+ }
+
+ public HardSoftLongScore getScore() {
+ return score;
+ }
+
+ public void setScore(HardSoftLongScore score) {
+ this.score = score;
+ }
+
+ public long getTotalDrivingTimeSeconds() {
+ return vehicles == null ? 0 : vehicles.stream().mapToLong(Vehicle::getTotalDrivingTimeSeconds).sum();
+ }
+
+ public SolverStatus getSolverStatus() {
+ return solverStatus;
+ }
+
+ public void setSolverStatus(SolverStatus solverStatus) {
+ this.solverStatus = solverStatus;
+ }
+
+ public String getScoreExplanation() {
+ return scoreExplanation;
+ }
+
+ public void setScoreExplanation(String scoreExplanation) {
+ this.scoreExplanation = scoreExplanation;
+ }
+}
+----
+--
+
+Kotlin::
++
+--
+Create the `src/main/kotlin/org/acme/vehiclerouting/domain/VehicleRoutePlan.kt` class:
+
+[source,kotlin]
+----
+package org.acme.vehiclerouting.domain;
+
+import java.time.LocalDateTime
+import java.util.stream.Stream
+
+import ai.timefold.solver.core.api.domain.solution.PlanningEntityCollectionProperty
+import ai.timefold.solver.core.api.domain.solution.PlanningScore
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution
+import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider
+import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore
+import ai.timefold.solver.core.api.solver.SolverStatus
+
+import org.acme.vehiclerouting.domain.geo.DrivingTimeCalculator
+import org.acme.vehiclerouting.domain.geo.HaversineDrivingTimeCalculator
+
+@PlanningSolution
+class VehicleRoutePlan {
+ lateinit var name: String
+ var southWestCorner: Location? = null
+ private set
+ var northEastCorner: Location? = null
+ private set
+ var startDateTime: LocalDateTime? = null
+ private set
+ var endDateTime: LocalDateTime? = null
+ private set
+
+ @PlanningEntityCollectionProperty
+ var vehicles: List<Vehicle>? = null
+ private set
+
+ @PlanningEntityCollectionProperty
+ @ValueRangeProvider
+ var visits: List<Visit>? = null
+ private set
+
+ @PlanningScore
+ var score: HardSoftLongScore? = null
+
+ var solverStatus: SolverStatus? = null
+
+ var scoreExplanation: String? = null
+
+ constructor()
+
+ constructor(name: String, score: HardSoftLongScore?, solverStatus: SolverStatus?) {
+ this.name = name
+ this.score = score
+ this.solverStatus = solverStatus
+ }
+
+ constructor(
+ name: String,
+ southWestCorner: Location?,
+ northEastCorner: Location?,
+ startDateTime: LocalDateTime?,
+ endDateTime: LocalDateTime?,
+ vehicles: List<Vehicle>,
+ visits: List<Visit>
+ ) {
+ this.name = name
+ this.southWestCorner = southWestCorner
+ this.northEastCorner = northEastCorner
+ this.startDateTime = startDateTime
+ this.endDateTime = endDateTime
+ this.vehicles = vehicles
+ this.visits = visits
+ val locations = Stream.concat(
+ vehicles.stream().map({ obj: Vehicle -> obj.homeLocation }),
+ visits.stream().map({ obj: Visit -> obj.location })
+ ).toList()
+
+ val drivingTimeCalculator: DrivingTimeCalculator = HaversineDrivingTimeCalculator.INSTANCE
+ drivingTimeCalculator.initDrivingTimeMaps(locations)
+ }
+
+ val totalDrivingTimeSeconds: Long
+ get() = if (vehicles == null) 0 else vehicles!!.stream()
+ .mapToLong({ obj: Vehicle -> obj.totalDrivingTimeSeconds }).sum()
+}
+----
+--
+====
+
+
+The `VehicleRoutePlan` class has an `@PlanningSolution` annotation,
+so Timefold Solver knows that this class contains all of the input and output data.
+
+Specifically, these classes are the input of the problem:
+
+* The `vehicles` field with all vehicles
+** This is a list of planning entities, because they change during solving.
+** Of each `Vehicle`:
+*** The value of the `visits` is typically still `null`, so unassigned. | It is not `null`. The solver fails when list variable is null.
It is an empty list. |
timefold-solver | github_2023 | others | 623 | TimefoldAI | triceo | @@ -0,0 +1,518 @@
+= Gather the domain objects in a planning solution
+:imagesdir: ../..
+
+A `VehicleRoutePlan` wraps all `Vehicle` and `Visit` instances of a single dataset.
+Furthermore, because it contains all vehicles and visits, each with a specific planning variable state,
+it is a _planning solution_ and it has a score:
+
+* If visits are still unassigned, then it is an _uninitialized_ solution,
+for example, a solution with the score `-4init/0hard/0soft`.
+* If it breaks hard constraints, then it is an _infeasible_ solution,
+for example, a solution with the score `-2hard/-3soft`.
+* If it adheres to all hard constraints, then it is a _feasible_ solution,
+for example, a solution with the score `0hard/-7soft`.
+
+[tabs]
+====
+Java::
++
+--
+Create the `src/main/java/org/acme/vehiclerouting/domain/VehicleRoutePlan.java` class:
+
+[source,java]
+----
+package org.acme.vehiclerouting.domain;
+
+import java.time.LocalDateTime;
+import java.util.List;
+import java.util.stream.Stream;
+
+import ai.timefold.solver.core.api.domain.solution.PlanningEntityCollectionProperty;
+import ai.timefold.solver.core.api.domain.solution.PlanningScore;
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
+import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider;
+import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore;
+import ai.timefold.solver.core.api.solver.SolverStatus;
+
+import org.acme.vehiclerouting.domain.geo.DrivingTimeCalculator;
+import org.acme.vehiclerouting.domain.geo.HaversineDrivingTimeCalculator;
+
+@PlanningSolution
+public class VehicleRoutePlan {
+
+ private String name;
+
+ private Location southWestCorner;
+ private Location northEastCorner;
+
+ private LocalDateTime startDateTime;
+
+ private LocalDateTime endDateTime;
+
+ @PlanningEntityCollectionProperty
+ private List<Vehicle> vehicles;
+
+ @PlanningEntityCollectionProperty
+ @ValueRangeProvider
+ private List<Visit> visits;
+
+ @PlanningScore
+ private HardSoftLongScore score;
+
+ private SolverStatus solverStatus;
+
+ private String scoreExplanation;
+
+ public VehicleRoutePlan() {
+ }
+
+ public VehicleRoutePlan(String name, HardSoftLongScore score, SolverStatus solverStatus) {
+ this.name = name;
+ this.score = score;
+ this.solverStatus = solverStatus;
+ }
+
+ public VehicleRoutePlan(String name,
+ Location southWestCorner,
+ Location northEastCorner,
+ LocalDateTime startDateTime,
+ LocalDateTime endDateTime,
+ List<Vehicle> vehicles,
+ List<Visit> visits) {
+ this.name = name;
+ this.southWestCorner = southWestCorner;
+ this.northEastCorner = northEastCorner;
+ this.startDateTime = startDateTime;
+ this.endDateTime = endDateTime;
+ this.vehicles = vehicles;
+ this.visits = visits;
+ List<Location> locations = Stream.concat(
+ vehicles.stream().map(Vehicle::getHomeLocation),
+ visits.stream().map(Visit::getLocation)).toList();
+
+ DrivingTimeCalculator drivingTimeCalculator = HaversineDrivingTimeCalculator.getInstance();
+ drivingTimeCalculator.initDrivingTimeMaps(locations);
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public Location getSouthWestCorner() {
+ return southWestCorner;
+ }
+
+ public Location getNorthEastCorner() {
+ return northEastCorner;
+ }
+
+ public LocalDateTime getStartDateTime() {
+ return startDateTime;
+ }
+
+ public LocalDateTime getEndDateTime() {
+ return endDateTime;
+ }
+
+ public List<Vehicle> getVehicles() {
+ return vehicles;
+ }
+
+ public List<Visit> getVisits() {
+ return visits;
+ }
+
+ public HardSoftLongScore getScore() {
+ return score;
+ }
+
+ public void setScore(HardSoftLongScore score) {
+ this.score = score;
+ }
+
+ public long getTotalDrivingTimeSeconds() {
+ return vehicles == null ? 0 : vehicles.stream().mapToLong(Vehicle::getTotalDrivingTimeSeconds).sum();
+ }
+
+ public SolverStatus getSolverStatus() {
+ return solverStatus;
+ }
+
+ public void setSolverStatus(SolverStatus solverStatus) {
+ this.solverStatus = solverStatus;
+ }
+
+ public String getScoreExplanation() {
+ return scoreExplanation;
+ }
+
+ public void setScoreExplanation(String scoreExplanation) {
+ this.scoreExplanation = scoreExplanation;
+ }
+}
+----
+--
+
+Kotlin::
++
+--
+Create the `src/main/kotlin/org/acme/vehiclerouting/domain/VehicleRoutePlan.kt` class:
+
+[source,kotlin]
+----
+package org.acme.vehiclerouting.domain;
+
+import java.time.LocalDateTime
+import java.util.stream.Stream
+
+import ai.timefold.solver.core.api.domain.solution.PlanningEntityCollectionProperty
+import ai.timefold.solver.core.api.domain.solution.PlanningScore
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution
+import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider
+import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore
+import ai.timefold.solver.core.api.solver.SolverStatus
+
+import org.acme.vehiclerouting.domain.geo.DrivingTimeCalculator
+import org.acme.vehiclerouting.domain.geo.HaversineDrivingTimeCalculator
+
+@PlanningSolution
+class VehicleRoutePlan {
+ lateinit var name: String
+ var southWestCorner: Location? = null
+ private set
+ var northEastCorner: Location? = null
+ private set
+ var startDateTime: LocalDateTime? = null
+ private set
+ var endDateTime: LocalDateTime? = null
+ private set
+
+ @PlanningEntityCollectionProperty
+ var vehicles: List<Vehicle>? = null
+ private set
+
+ @PlanningEntityCollectionProperty
+ @ValueRangeProvider
+ var visits: List<Visit>? = null
+ private set
+
+ @PlanningScore
+ var score: HardSoftLongScore? = null
+
+ var solverStatus: SolverStatus? = null
+
+ var scoreExplanation: String? = null
+
+ constructor()
+
+ constructor(name: String, score: HardSoftLongScore?, solverStatus: SolverStatus?) {
+ this.name = name
+ this.score = score
+ this.solverStatus = solverStatus
+ }
+
+ constructor(
+ name: String,
+ southWestCorner: Location?,
+ northEastCorner: Location?,
+ startDateTime: LocalDateTime?,
+ endDateTime: LocalDateTime?,
+ vehicles: List<Vehicle>,
+ visits: List<Visit>
+ ) {
+ this.name = name
+ this.southWestCorner = southWestCorner
+ this.northEastCorner = northEastCorner
+ this.startDateTime = startDateTime
+ this.endDateTime = endDateTime
+ this.vehicles = vehicles
+ this.visits = visits
+ val locations = Stream.concat(
+ vehicles.stream().map({ obj: Vehicle -> obj.homeLocation }),
+ visits.stream().map({ obj: Visit -> obj.location })
+ ).toList()
+
+ val drivingTimeCalculator: DrivingTimeCalculator = HaversineDrivingTimeCalculator.INSTANCE
+ drivingTimeCalculator.initDrivingTimeMaps(locations)
+ }
+
+ val totalDrivingTimeSeconds: Long
+ get() = if (vehicles == null) 0 else vehicles!!.stream()
+ .mapToLong({ obj: Vehicle -> obj.totalDrivingTimeSeconds }).sum()
+}
+----
+--
+====
+
+
+The `VehicleRoutePlan` class has an `@PlanningSolution` annotation,
+so Timefold Solver knows that this class contains all of the input and output data.
+
+Specifically, these classes are the input of the problem:
+
+* The `vehicles` field with all vehicles
+** This is a list of planning entities, because they change during solving.
+** Of each `Vehicle`: | ```suggestion
** For each `Vehicle`:
``` |
timefold-solver | github_2023 | others | 623 | TimefoldAI | triceo | @@ -0,0 +1,518 @@
+= Gather the domain objects in a planning solution
+:imagesdir: ../..
+
+A `VehicleRoutePlan` wraps all `Vehicle` and `Visit` instances of a single dataset.
+Furthermore, because it contains all vehicles and visits, each with a specific planning variable state,
+it is a _planning solution_ and it has a score:
+
+* If visits are still unassigned, then it is an _uninitialized_ solution,
+for example, a solution with the score `-4init/0hard/0soft`.
+* If it breaks hard constraints, then it is an _infeasible_ solution,
+for example, a solution with the score `-2hard/-3soft`.
+* If it adheres to all hard constraints, then it is a _feasible_ solution,
+for example, a solution with the score `0hard/-7soft`.
+
+[tabs]
+====
+Java::
++
+--
+Create the `src/main/java/org/acme/vehiclerouting/domain/VehicleRoutePlan.java` class:
+
+[source,java]
+----
+package org.acme.vehiclerouting.domain;
+
+import java.time.LocalDateTime;
+import java.util.List;
+import java.util.stream.Stream;
+
+import ai.timefold.solver.core.api.domain.solution.PlanningEntityCollectionProperty;
+import ai.timefold.solver.core.api.domain.solution.PlanningScore;
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
+import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider;
+import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore;
+import ai.timefold.solver.core.api.solver.SolverStatus;
+
+import org.acme.vehiclerouting.domain.geo.DrivingTimeCalculator;
+import org.acme.vehiclerouting.domain.geo.HaversineDrivingTimeCalculator;
+
+@PlanningSolution
+public class VehicleRoutePlan {
+
+ private String name;
+
+ private Location southWestCorner;
+ private Location northEastCorner;
+
+ private LocalDateTime startDateTime;
+
+ private LocalDateTime endDateTime;
+
+ @PlanningEntityCollectionProperty
+ private List<Vehicle> vehicles;
+
+ @PlanningEntityCollectionProperty
+ @ValueRangeProvider
+ private List<Visit> visits;
+
+ @PlanningScore
+ private HardSoftLongScore score;
+
+ private SolverStatus solverStatus;
+
+ private String scoreExplanation;
+
+ public VehicleRoutePlan() {
+ }
+
+ public VehicleRoutePlan(String name, HardSoftLongScore score, SolverStatus solverStatus) {
+ this.name = name;
+ this.score = score;
+ this.solverStatus = solverStatus;
+ }
+
+ public VehicleRoutePlan(String name,
+ Location southWestCorner,
+ Location northEastCorner,
+ LocalDateTime startDateTime,
+ LocalDateTime endDateTime,
+ List<Vehicle> vehicles,
+ List<Visit> visits) {
+ this.name = name;
+ this.southWestCorner = southWestCorner;
+ this.northEastCorner = northEastCorner;
+ this.startDateTime = startDateTime;
+ this.endDateTime = endDateTime;
+ this.vehicles = vehicles;
+ this.visits = visits;
+ List<Location> locations = Stream.concat(
+ vehicles.stream().map(Vehicle::getHomeLocation),
+ visits.stream().map(Visit::getLocation)).toList();
+
+ DrivingTimeCalculator drivingTimeCalculator = HaversineDrivingTimeCalculator.getInstance();
+ drivingTimeCalculator.initDrivingTimeMaps(locations);
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public Location getSouthWestCorner() {
+ return southWestCorner;
+ }
+
+ public Location getNorthEastCorner() {
+ return northEastCorner;
+ }
+
+ public LocalDateTime getStartDateTime() {
+ return startDateTime;
+ }
+
+ public LocalDateTime getEndDateTime() {
+ return endDateTime;
+ }
+
+ public List<Vehicle> getVehicles() {
+ return vehicles;
+ }
+
+ public List<Visit> getVisits() {
+ return visits;
+ }
+
+ public HardSoftLongScore getScore() {
+ return score;
+ }
+
+ public void setScore(HardSoftLongScore score) {
+ this.score = score;
+ }
+
+ public long getTotalDrivingTimeSeconds() {
+ return vehicles == null ? 0 : vehicles.stream().mapToLong(Vehicle::getTotalDrivingTimeSeconds).sum();
+ }
+
+ public SolverStatus getSolverStatus() {
+ return solverStatus;
+ }
+
+ public void setSolverStatus(SolverStatus solverStatus) {
+ this.solverStatus = solverStatus;
+ }
+
+ public String getScoreExplanation() {
+ return scoreExplanation;
+ }
+
+ public void setScoreExplanation(String scoreExplanation) {
+ this.scoreExplanation = scoreExplanation;
+ }
+}
+----
+--
+
+Kotlin::
++
+--
+Create the `src/main/kotlin/org/acme/vehiclerouting/domain/VehicleRoutePlan.kt` class:
+
+[source,kotlin]
+----
+package org.acme.vehiclerouting.domain;
+
+import java.time.LocalDateTime
+import java.util.stream.Stream
+
+import ai.timefold.solver.core.api.domain.solution.PlanningEntityCollectionProperty
+import ai.timefold.solver.core.api.domain.solution.PlanningScore
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution
+import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider
+import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore
+import ai.timefold.solver.core.api.solver.SolverStatus
+
+import org.acme.vehiclerouting.domain.geo.DrivingTimeCalculator
+import org.acme.vehiclerouting.domain.geo.HaversineDrivingTimeCalculator
+
+@PlanningSolution
+class VehicleRoutePlan {
+ lateinit var name: String
+ var southWestCorner: Location? = null
+ private set
+ var northEastCorner: Location? = null
+ private set
+ var startDateTime: LocalDateTime? = null
+ private set
+ var endDateTime: LocalDateTime? = null
+ private set
+
+ @PlanningEntityCollectionProperty
+ var vehicles: List<Vehicle>? = null
+ private set
+
+ @PlanningEntityCollectionProperty
+ @ValueRangeProvider
+ var visits: List<Visit>? = null
+ private set
+
+ @PlanningScore
+ var score: HardSoftLongScore? = null
+
+ var solverStatus: SolverStatus? = null
+
+ var scoreExplanation: String? = null
+
+ constructor()
+
+ constructor(name: String, score: HardSoftLongScore?, solverStatus: SolverStatus?) {
+ this.name = name
+ this.score = score
+ this.solverStatus = solverStatus
+ }
+
+ constructor(
+ name: String,
+ southWestCorner: Location?,
+ northEastCorner: Location?,
+ startDateTime: LocalDateTime?,
+ endDateTime: LocalDateTime?,
+ vehicles: List<Vehicle>,
+ visits: List<Visit>
+ ) {
+ this.name = name
+ this.southWestCorner = southWestCorner
+ this.northEastCorner = northEastCorner
+ this.startDateTime = startDateTime
+ this.endDateTime = endDateTime
+ this.vehicles = vehicles
+ this.visits = visits
+ val locations = Stream.concat(
+ vehicles.stream().map({ obj: Vehicle -> obj.homeLocation }),
+ visits.stream().map({ obj: Visit -> obj.location })
+ ).toList()
+
+ val drivingTimeCalculator: DrivingTimeCalculator = HaversineDrivingTimeCalculator.INSTANCE
+ drivingTimeCalculator.initDrivingTimeMaps(locations)
+ }
+
+ val totalDrivingTimeSeconds: Long
+ get() = if (vehicles == null) 0 else vehicles!!.stream()
+ .mapToLong({ obj: Vehicle -> obj.totalDrivingTimeSeconds }).sum()
+}
+----
+--
+====
+
+
+The `VehicleRoutePlan` class has an `@PlanningSolution` annotation,
+so Timefold Solver knows that this class contains all of the input and output data.
+
+Specifically, these classes are the input of the problem:
+
+* The `vehicles` field with all vehicles
+** This is a list of planning entities, because they change during solving.
+** Of each `Vehicle`:
+*** The value of the `visits` is typically still `null`, so unassigned.
+It is a planning variable.
+*** The other fields, such as `capacity`, `homeLocation` and `departureTime`, are filled in.
+These fields are problem properties.
+* The `visits` field with all visits
+** This is a list of planning entities, because they change during solving.
+** Of each `Visit`:
+*** The values of `vehicle`, `previousVisit`, `nextVisit`, `arrivalTime` are typically still `null`.
+They are planning shadow variables, which may be optional if the data is not used. | Shadow vars are not optional - if you specify them, they will be filled.
(They are optional in a sense that you don't need to specify them.)
However, with a fresh solution, they are null because the listeners did not run yet. |
timefold-solver | github_2023 | others | 623 | TimefoldAI | triceo | @@ -0,0 +1,518 @@
+= Gather the domain objects in a planning solution
+:imagesdir: ../..
+
+A `VehicleRoutePlan` wraps all `Vehicle` and `Visit` instances of a single dataset.
+Furthermore, because it contains all vehicles and visits, each with a specific planning variable state,
+it is a _planning solution_ and it has a score:
+
+* If visits are still unassigned, then it is an _uninitialized_ solution,
+for example, a solution with the score `-4init/0hard/0soft`.
+* If it breaks hard constraints, then it is an _infeasible_ solution,
+for example, a solution with the score `-2hard/-3soft`.
+* If it adheres to all hard constraints, then it is a _feasible_ solution,
+for example, a solution with the score `0hard/-7soft`.
+
+[tabs]
+====
+Java::
++
+--
+Create the `src/main/java/org/acme/vehiclerouting/domain/VehicleRoutePlan.java` class:
+
+[source,java]
+----
+package org.acme.vehiclerouting.domain;
+
+import java.time.LocalDateTime;
+import java.util.List;
+import java.util.stream.Stream;
+
+import ai.timefold.solver.core.api.domain.solution.PlanningEntityCollectionProperty;
+import ai.timefold.solver.core.api.domain.solution.PlanningScore;
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
+import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider;
+import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore;
+import ai.timefold.solver.core.api.solver.SolverStatus;
+
+import org.acme.vehiclerouting.domain.geo.DrivingTimeCalculator;
+import org.acme.vehiclerouting.domain.geo.HaversineDrivingTimeCalculator;
+
+@PlanningSolution
+public class VehicleRoutePlan {
+
+ private String name;
+
+ private Location southWestCorner;
+ private Location northEastCorner;
+
+ private LocalDateTime startDateTime;
+
+ private LocalDateTime endDateTime;
+
+ @PlanningEntityCollectionProperty
+ private List<Vehicle> vehicles;
+
+ @PlanningEntityCollectionProperty
+ @ValueRangeProvider
+ private List<Visit> visits;
+
+ @PlanningScore
+ private HardSoftLongScore score;
+
+ private SolverStatus solverStatus;
+
+ private String scoreExplanation;
+
+ public VehicleRoutePlan() {
+ }
+
+ public VehicleRoutePlan(String name, HardSoftLongScore score, SolverStatus solverStatus) {
+ this.name = name;
+ this.score = score;
+ this.solverStatus = solverStatus;
+ }
+
+ public VehicleRoutePlan(String name,
+ Location southWestCorner,
+ Location northEastCorner,
+ LocalDateTime startDateTime,
+ LocalDateTime endDateTime,
+ List<Vehicle> vehicles,
+ List<Visit> visits) {
+ this.name = name;
+ this.southWestCorner = southWestCorner;
+ this.northEastCorner = northEastCorner;
+ this.startDateTime = startDateTime;
+ this.endDateTime = endDateTime;
+ this.vehicles = vehicles;
+ this.visits = visits;
+ List<Location> locations = Stream.concat(
+ vehicles.stream().map(Vehicle::getHomeLocation),
+ visits.stream().map(Visit::getLocation)).toList();
+
+ DrivingTimeCalculator drivingTimeCalculator = HaversineDrivingTimeCalculator.getInstance();
+ drivingTimeCalculator.initDrivingTimeMaps(locations);
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public Location getSouthWestCorner() {
+ return southWestCorner;
+ }
+
+ public Location getNorthEastCorner() {
+ return northEastCorner;
+ }
+
+ public LocalDateTime getStartDateTime() {
+ return startDateTime;
+ }
+
+ public LocalDateTime getEndDateTime() {
+ return endDateTime;
+ }
+
+ public List<Vehicle> getVehicles() {
+ return vehicles;
+ }
+
+ public List<Visit> getVisits() {
+ return visits;
+ }
+
+ public HardSoftLongScore getScore() {
+ return score;
+ }
+
+ public void setScore(HardSoftLongScore score) {
+ this.score = score;
+ }
+
+ public long getTotalDrivingTimeSeconds() {
+ return vehicles == null ? 0 : vehicles.stream().mapToLong(Vehicle::getTotalDrivingTimeSeconds).sum();
+ }
+
+ public SolverStatus getSolverStatus() {
+ return solverStatus;
+ }
+
+ public void setSolverStatus(SolverStatus solverStatus) {
+ this.solverStatus = solverStatus;
+ }
+
+ public String getScoreExplanation() {
+ return scoreExplanation;
+ }
+
+ public void setScoreExplanation(String scoreExplanation) {
+ this.scoreExplanation = scoreExplanation;
+ }
+}
+----
+--
+
+Kotlin::
++
+--
+Create the `src/main/kotlin/org/acme/vehiclerouting/domain/VehicleRoutePlan.kt` class:
+
+[source,kotlin]
+----
+package org.acme.vehiclerouting.domain;
+
+import java.time.LocalDateTime
+import java.util.stream.Stream
+
+import ai.timefold.solver.core.api.domain.solution.PlanningEntityCollectionProperty
+import ai.timefold.solver.core.api.domain.solution.PlanningScore
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution
+import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider
+import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore
+import ai.timefold.solver.core.api.solver.SolverStatus
+
+import org.acme.vehiclerouting.domain.geo.DrivingTimeCalculator
+import org.acme.vehiclerouting.domain.geo.HaversineDrivingTimeCalculator
+
+@PlanningSolution
+class VehicleRoutePlan {
+ lateinit var name: String
+ var southWestCorner: Location? = null
+ private set
+ var northEastCorner: Location? = null
+ private set
+ var startDateTime: LocalDateTime? = null
+ private set
+ var endDateTime: LocalDateTime? = null
+ private set
+
+ @PlanningEntityCollectionProperty
+ var vehicles: List<Vehicle>? = null
+ private set
+
+ @PlanningEntityCollectionProperty
+ @ValueRangeProvider
+ var visits: List<Visit>? = null
+ private set
+
+ @PlanningScore
+ var score: HardSoftLongScore? = null
+
+ var solverStatus: SolverStatus? = null
+
+ var scoreExplanation: String? = null
+
+ constructor()
+
+ constructor(name: String, score: HardSoftLongScore?, solverStatus: SolverStatus?) {
+ this.name = name
+ this.score = score
+ this.solverStatus = solverStatus
+ }
+
+ constructor(
+ name: String,
+ southWestCorner: Location?,
+ northEastCorner: Location?,
+ startDateTime: LocalDateTime?,
+ endDateTime: LocalDateTime?,
+ vehicles: List<Vehicle>,
+ visits: List<Visit>
+ ) {
+ this.name = name
+ this.southWestCorner = southWestCorner
+ this.northEastCorner = northEastCorner
+ this.startDateTime = startDateTime
+ this.endDateTime = endDateTime
+ this.vehicles = vehicles
+ this.visits = visits
+ val locations = Stream.concat(
+ vehicles.stream().map({ obj: Vehicle -> obj.homeLocation }),
+ visits.stream().map({ obj: Visit -> obj.location })
+ ).toList()
+
+ val drivingTimeCalculator: DrivingTimeCalculator = HaversineDrivingTimeCalculator.INSTANCE
+ drivingTimeCalculator.initDrivingTimeMaps(locations)
+ }
+
+ val totalDrivingTimeSeconds: Long
+ get() = if (vehicles == null) 0 else vehicles!!.stream()
+ .mapToLong({ obj: Vehicle -> obj.totalDrivingTimeSeconds }).sum()
+}
+----
+--
+====
+
+
+The `VehicleRoutePlan` class has an `@PlanningSolution` annotation,
+so Timefold Solver knows that this class contains all of the input and output data.
+
+Specifically, these classes are the input of the problem:
+
+* The `vehicles` field with all vehicles
+** This is a list of planning entities, because they change during solving.
+** Of each `Vehicle`:
+*** The value of the `visits` is typically still `null`, so unassigned.
+It is a planning variable.
+*** The other fields, such as `capacity`, `homeLocation` and `departureTime`, are filled in.
+These fields are problem properties.
+* The `visits` field with all visits
+** This is a list of planning entities, because they change during solving.
+** Of each `Visit`:
+*** The values of `vehicle`, `previousVisit`, `nextVisit`, `arrivalTime` are typically still `null`.
+They are planning shadow variables, which may be optional if the data is not used.
+*** The other fields, such as `name`, `location` and `demand`, are filled in.
+These fields are problem properties.
+
+However, this class is also the output of the solution:
+
+* The `vehicles` field for which each `Vehicle` instance has non-null `visits` field after solving.
+* The `score` field that represents the quality of the output solution, for example, `0hard/-5soft`.
+
+== The value range providers
+
+The `visits` field is a value range provider.
+It holds the `Visit` instances which Timefold Solver can pick from to assign to the `visits` field of `Vehicle` instances.
+The `visits` field has an `@ValueRangeProvider` annotation to connect the `@PlanningListVariable` with the `@ValueRangeProvider`,
+by matching the type of the planning list variable with the type returned by the xref:using-timefold-solver/modeling-planning-problems.adoc#planningValueRangeProvider[value range provider].
+
+== Distance calculation
+
+The distance calculation method applies the Haversine approach, which measures distances in meters. First create a
+contract for driving time calculation.
+
+[tabs]
+====
+Java::
++
+--
+Create the `src/main/java/org/acme/vehiclerouting/domain/geo/DrivingTimeCalculator.java` interface:
+
+[source,java]
+----
+package org.acme.vehiclerouting.domain.geo;
+
+import java.util.Collection;
+import java.util.Map;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import org.acme.vehiclerouting.domain.Location;
+
+public interface DrivingTimeCalculator {
+
+ long calculateDrivingTime(Location from, Location to);
+
+ default Map<Location, Map<Location, Long>> calculateBulkDrivingTime(
+ Collection<Location> fromLocations,
+ Collection<Location> toLocations) {
+ return fromLocations.stream().collect(Collectors.toMap(
+ Function.identity(),
+ from -> toLocations.stream().collect(Collectors.toMap(
+ Function.identity(),
+ to -> calculateDrivingTime(from, to)))));
+ }
+
+ default void initDrivingTimeMaps(Collection<Location> locations) {
+ Map<Location, Map<Location, Long>> drivingTimeMatrix = calculateBulkDrivingTime(locations, locations);
+ locations.forEach(location -> location.setDrivingTimeSeconds(drivingTimeMatrix.get(location)));
+ }
+}
+----
+--
+
+Kotlin::
++
+--
+Create the `src/main/kotlin/org/acme/vehiclerouting/domain/geo/DrivingTimeCalculator.kt` interface:
+
+[source,kotlin]
+----
+package org.acme.vehiclerouting.domain.geo
+
+import org.acme.vehiclerouting.domain.Location
+import java.util.function.Function
+import java.util.stream.Collectors
+
+interface DrivingTimeCalculator {
+
+ fun calculateDrivingTime(from: Location, to: Location): Long
+
+ fun calculateBulkDrivingTime(
+ fromLocations: Collection<Location>,
+ toLocations: Collection<Location>
+ ): Map<Location, Map<Location, Long>> {
+ return fromLocations.stream().collect(
+ Collectors.toMap(
+ Function.identity()
+ ) { from: Location ->
+ toLocations.stream()
+ .collect(
+ Collectors.toMap(
+ Function.identity(),
+ { to: Location ->
+ calculateDrivingTime(
+ from,
+ to
+ )
+ })
+ )
+ }
+ )
+ }
+
+ fun initDrivingTimeMaps(locations: Collection<Location>) {
+ val drivingTimeMatrix = calculateBulkDrivingTime(locations, locations)
+ locations.forEach { location: Location ->
+ location.drivingTimeSeconds = drivingTimeMatrix[location]
+ }
+ }
+}
+----
+--
+====
+
+Then create an implementation using Haversine method. | ```suggestion
Then create an implementation using Haversine method:
``` |
timefold-solver | github_2023 | others | 623 | TimefoldAI | triceo | @@ -0,0 +1,518 @@
+= Gather the domain objects in a planning solution
+:imagesdir: ../..
+
+A `VehicleRoutePlan` wraps all `Vehicle` and `Visit` instances of a single dataset.
+Furthermore, because it contains all vehicles and visits, each with a specific planning variable state,
+it is a _planning solution_ and it has a score:
+
+* If visits are still unassigned, then it is an _uninitialized_ solution,
+for example, a solution with the score `-4init/0hard/0soft`.
+* If it breaks hard constraints, then it is an _infeasible_ solution,
+for example, a solution with the score `-2hard/-3soft`.
+* If it adheres to all hard constraints, then it is a _feasible_ solution,
+for example, a solution with the score `0hard/-7soft`.
+
+[tabs]
+====
+Java::
++
+--
+Create the `src/main/java/org/acme/vehiclerouting/domain/VehicleRoutePlan.java` class:
+
+[source,java]
+----
+package org.acme.vehiclerouting.domain;
+
+import java.time.LocalDateTime;
+import java.util.List;
+import java.util.stream.Stream;
+
+import ai.timefold.solver.core.api.domain.solution.PlanningEntityCollectionProperty;
+import ai.timefold.solver.core.api.domain.solution.PlanningScore;
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
+import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider;
+import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore;
+import ai.timefold.solver.core.api.solver.SolverStatus;
+
+import org.acme.vehiclerouting.domain.geo.DrivingTimeCalculator;
+import org.acme.vehiclerouting.domain.geo.HaversineDrivingTimeCalculator;
+
+@PlanningSolution
+public class VehicleRoutePlan {
+
+ private String name;
+
+ private Location southWestCorner;
+ private Location northEastCorner;
+
+ private LocalDateTime startDateTime;
+
+ private LocalDateTime endDateTime;
+
+ @PlanningEntityCollectionProperty
+ private List<Vehicle> vehicles;
+
+ @PlanningEntityCollectionProperty
+ @ValueRangeProvider
+ private List<Visit> visits;
+
+ @PlanningScore
+ private HardSoftLongScore score;
+
+ private SolverStatus solverStatus;
+
+ private String scoreExplanation;
+
+ public VehicleRoutePlan() {
+ }
+
+ public VehicleRoutePlan(String name, HardSoftLongScore score, SolverStatus solverStatus) {
+ this.name = name;
+ this.score = score;
+ this.solverStatus = solverStatus;
+ }
+
+ public VehicleRoutePlan(String name,
+ Location southWestCorner,
+ Location northEastCorner,
+ LocalDateTime startDateTime,
+ LocalDateTime endDateTime,
+ List<Vehicle> vehicles,
+ List<Visit> visits) {
+ this.name = name;
+ this.southWestCorner = southWestCorner;
+ this.northEastCorner = northEastCorner;
+ this.startDateTime = startDateTime;
+ this.endDateTime = endDateTime;
+ this.vehicles = vehicles;
+ this.visits = visits;
+ List<Location> locations = Stream.concat(
+ vehicles.stream().map(Vehicle::getHomeLocation),
+ visits.stream().map(Visit::getLocation)).toList();
+
+ DrivingTimeCalculator drivingTimeCalculator = HaversineDrivingTimeCalculator.getInstance();
+ drivingTimeCalculator.initDrivingTimeMaps(locations);
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public Location getSouthWestCorner() {
+ return southWestCorner;
+ }
+
+ public Location getNorthEastCorner() {
+ return northEastCorner;
+ }
+
+ public LocalDateTime getStartDateTime() {
+ return startDateTime;
+ }
+
+ public LocalDateTime getEndDateTime() {
+ return endDateTime;
+ }
+
+ public List<Vehicle> getVehicles() {
+ return vehicles;
+ }
+
+ public List<Visit> getVisits() {
+ return visits;
+ }
+
+ public HardSoftLongScore getScore() {
+ return score;
+ }
+
+ public void setScore(HardSoftLongScore score) {
+ this.score = score;
+ }
+
+ public long getTotalDrivingTimeSeconds() {
+ return vehicles == null ? 0 : vehicles.stream().mapToLong(Vehicle::getTotalDrivingTimeSeconds).sum();
+ }
+
+ public SolverStatus getSolverStatus() {
+ return solverStatus;
+ }
+
+ public void setSolverStatus(SolverStatus solverStatus) {
+ this.solverStatus = solverStatus;
+ }
+
+ public String getScoreExplanation() {
+ return scoreExplanation;
+ }
+
+ public void setScoreExplanation(String scoreExplanation) {
+ this.scoreExplanation = scoreExplanation;
+ }
+}
+----
+--
+
+Kotlin::
++
+--
+Create the `src/main/kotlin/org/acme/vehiclerouting/domain/VehicleRoutePlan.kt` class:
+
+[source,kotlin]
+----
+package org.acme.vehiclerouting.domain;
+
+import java.time.LocalDateTime
+import java.util.stream.Stream
+
+import ai.timefold.solver.core.api.domain.solution.PlanningEntityCollectionProperty
+import ai.timefold.solver.core.api.domain.solution.PlanningScore
+import ai.timefold.solver.core.api.domain.solution.PlanningSolution
+import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider
+import ai.timefold.solver.core.api.score.buildin.hardsoftlong.HardSoftLongScore
+import ai.timefold.solver.core.api.solver.SolverStatus
+
+import org.acme.vehiclerouting.domain.geo.DrivingTimeCalculator
+import org.acme.vehiclerouting.domain.geo.HaversineDrivingTimeCalculator
+
+@PlanningSolution
+class VehicleRoutePlan {
+ lateinit var name: String
+ var southWestCorner: Location? = null
+ private set
+ var northEastCorner: Location? = null
+ private set
+ var startDateTime: LocalDateTime? = null
+ private set
+ var endDateTime: LocalDateTime? = null
+ private set
+
+ @PlanningEntityCollectionProperty
+ var vehicles: List<Vehicle>? = null
+ private set
+
+ @PlanningEntityCollectionProperty
+ @ValueRangeProvider
+ var visits: List<Visit>? = null
+ private set
+
+ @PlanningScore
+ var score: HardSoftLongScore? = null
+
+ var solverStatus: SolverStatus? = null
+
+ var scoreExplanation: String? = null
+
+ constructor()
+
+ constructor(name: String, score: HardSoftLongScore?, solverStatus: SolverStatus?) {
+ this.name = name
+ this.score = score
+ this.solverStatus = solverStatus
+ }
+
+ constructor(
+ name: String,
+ southWestCorner: Location?,
+ northEastCorner: Location?,
+ startDateTime: LocalDateTime?,
+ endDateTime: LocalDateTime?,
+ vehicles: List<Vehicle>,
+ visits: List<Visit>
+ ) {
+ this.name = name
+ this.southWestCorner = southWestCorner
+ this.northEastCorner = northEastCorner
+ this.startDateTime = startDateTime
+ this.endDateTime = endDateTime
+ this.vehicles = vehicles
+ this.visits = visits
+ val locations = Stream.concat(
+ vehicles.stream().map({ obj: Vehicle -> obj.homeLocation }),
+ visits.stream().map({ obj: Visit -> obj.location })
+ ).toList()
+
+ val drivingTimeCalculator: DrivingTimeCalculator = HaversineDrivingTimeCalculator.INSTANCE
+ drivingTimeCalculator.initDrivingTimeMaps(locations)
+ }
+
+ val totalDrivingTimeSeconds: Long
+ get() = if (vehicles == null) 0 else vehicles!!.stream()
+ .mapToLong({ obj: Vehicle -> obj.totalDrivingTimeSeconds }).sum()
+}
+----
+--
+====
+
+
+The `VehicleRoutePlan` class has an `@PlanningSolution` annotation,
+so Timefold Solver knows that this class contains all of the input and output data.
+
+Specifically, these classes are the input of the problem:
+
+* The `vehicles` field with all vehicles
+** This is a list of planning entities, because they change during solving.
+** Of each `Vehicle`:
+*** The value of the `visits` is typically still `null`, so unassigned.
+It is a planning variable.
+*** The other fields, such as `capacity`, `homeLocation` and `departureTime`, are filled in.
+These fields are problem properties.
+* The `visits` field with all visits
+** This is a list of planning entities, because they change during solving.
+** Of each `Visit`:
+*** The values of `vehicle`, `previousVisit`, `nextVisit`, `arrivalTime` are typically still `null`.
+They are planning shadow variables, which may be optional if the data is not used.
+*** The other fields, such as `name`, `location` and `demand`, are filled in.
+These fields are problem properties.
+
+However, this class is also the output of the solution:
+
+* The `vehicles` field for which each `Vehicle` instance has non-null `visits` field after solving.
+* The `score` field that represents the quality of the output solution, for example, `0hard/-5soft`.
+
+== The value range providers
+
+The `visits` field is a value range provider.
+It holds the `Visit` instances which Timefold Solver can pick from to assign to the `visits` field of `Vehicle` instances.
+The `visits` field has an `@ValueRangeProvider` annotation to connect the `@PlanningListVariable` with the `@ValueRangeProvider`,
+by matching the type of the planning list variable with the type returned by the xref:using-timefold-solver/modeling-planning-problems.adoc#planningValueRangeProvider[value range provider].
+
+== Distance calculation
+
+The distance calculation method applies the Haversine approach, which measures distances in meters. First create a
+contract for driving time calculation. | ```suggestion
contract for driving time calculation:
``` |
timefold-solver | github_2023 | others | 623 | TimefoldAI | triceo | @@ -0,0 +1,918 @@
+[#quarkusQuickStart]
+= Vehicle Routing Quick Start Guide
+:doctype: book
+:imagesdir: ../..
+:sectnums:
+:icons: font
+include::../../_attributes.adoc[]
+
+// Keep this in sync with the quarkus repo's copy
+// https://github.com/quarkusio/quarkus/blob/main/docs/src/main/asciidoc/timefold.adoc
+// Keep this also in sync with spring-boot-quickstart.adoc where applicable
+
+This guide walks you through the process of creating a Vehicle Routing application
+with https://quarkus.io/[Quarkus] and https://timefold.ai[Timefold]'s constraint solving Artificial Intelligence (AI).
+
+== What you will build
+
+You will build a REST application that optimizes a Vehicle Route Problem (VRP):
+
+image::quickstart/vrp-quarkus/vehicleRouteScreenshot.png[]
+
+Your service will assign `Vist` instances to `Vehicle` instances automatically
+by using AI to adhere to hard and soft scheduling _constraints_, such as the following examples:
+
+* The demand for a vehicle cannot exceed its capacity.
+* The deliveries have specific deadlines that must be met.
+* The less total travel time, the better.
+
+Mathematically speaking, VRP is an _NP-hard_ problem.
+This means it is difficult to scale.
+Simply brute force iterating through all possible combinations takes millions of years
+for a non-trivial dataset, even on a supercomputer.
+Luckily, AI constraint solvers such as Timefold Solver have advanced algorithms
+that deliver a near-optimal solution in a reasonable amount of time.
+
+== Solution source code
+
+Follow the instructions in the next sections to create the application step by step (recommended).
+
+Alternatively, you can also skip right to the completed example:
+
+. Clone the Git repository:
++
+[source,shell,subs=attributes+]
+----
+$ git clone {quickstarts-clone-url}
+----
++
+or download an {quickstarts-archive-url}[archive].
+
+. Find the solution in {vrp-quickstart-url}[the `use-cases` directory]
+and run it (see its README file).
+
+== Prerequisites
+
+To complete this guide, you need:
+
+* https://adoptopenjdk.net/[JDK] {java-version}+ with `JAVA_HOME` configured appropriately | Maybe suggest `SDKMAN`? |
timefold-solver | github_2023 | others | 623 | TimefoldAI | triceo | @@ -0,0 +1,918 @@
+[#quarkusQuickStart]
+= Vehicle Routing Quick Start Guide
+:doctype: book
+:imagesdir: ../..
+:sectnums:
+:icons: font
+include::../../_attributes.adoc[]
+
+// Keep this in sync with the quarkus repo's copy
+// https://github.com/quarkusio/quarkus/blob/main/docs/src/main/asciidoc/timefold.adoc
+// Keep this also in sync with spring-boot-quickstart.adoc where applicable
+
+This guide walks you through the process of creating a Vehicle Routing application
+with https://quarkus.io/[Quarkus] and https://timefold.ai[Timefold]'s constraint solving Artificial Intelligence (AI).
+
+== What you will build
+
+You will build a REST application that optimizes a Vehicle Route Problem (VRP):
+
+image::quickstart/vrp-quarkus/vehicleRouteScreenshot.png[]
+
+Your service will assign `Vist` instances to `Vehicle` instances automatically
+by using AI to adhere to hard and soft scheduling _constraints_, such as the following examples:
+
+* The demand for a vehicle cannot exceed its capacity.
+* The deliveries have specific deadlines that must be met.
+* The less total travel time, the better.
+
+Mathematically speaking, VRP is an _NP-hard_ problem.
+This means it is difficult to scale.
+Simply brute force iterating through all possible combinations takes millions of years
+for a non-trivial dataset, even on a supercomputer.
+Luckily, AI constraint solvers such as Timefold Solver have advanced algorithms
+that deliver a near-optimal solution in a reasonable amount of time.
+
+== Solution source code
+
+Follow the instructions in the next sections to create the application step by step (recommended).
+
+Alternatively, you can also skip right to the completed example:
+
+. Clone the Git repository:
++
+[source,shell,subs=attributes+]
+----
+$ git clone {quickstarts-clone-url}
+----
++
+or download an {quickstarts-archive-url}[archive].
+
+. Find the solution in {vrp-quickstart-url}[the `use-cases` directory]
+and run it (see its README file).
+
+== Prerequisites
+
+To complete this guide, you need:
+
+* https://adoptopenjdk.net/[JDK] {java-version}+ with `JAVA_HOME` configured appropriately
+* https://maven.apache.org/download.html[Apache Maven] {maven-version}+
+* An IDE, such as https://www.jetbrains.com/idea[IntelliJ IDEA], VSCode or Eclipse
+
+== The build file and the dependencies
+
+Use https://code.quarkus.io/[code.quarkus.io] to generate an application
+with the following extensions, for Maven or Gradle:
+
+* RESTEasy JAX-RS (`quarkus-resteasy`)
+* RESTEasy Jackson (`quarkus-resteasy-jackson`)
+* Timefold Solver (`timefold-solver-quarkus`)
+* Timefold Solver Jackson (`timefold-solver-quarkus-jackson`)
+
+Your `pom.xml` file has the following content:
+
+[tabs]
+====
+Java::
++
+--
+[source,xml,subs=attributes+]
+----
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <groupId>org.acme</groupId>
+ <artifactId>timefold-solver-quarkus-vehicle-routing-quickstart</artifactId>
+ <version>1.0-SNAPSHOT</version>
+
+ <properties>
+ <maven.compiler.release>11</maven.compiler.release>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+
+ <version.io.quarkus>{quarkus-version}</version.io.quarkus>
+ <version.ai.timefold.solver>{timefold-solver-version}</version.ai.timefold.solver>
+ </properties>
+
+ <dependencyManagement>
+ <dependencies>
+ <dependency>
+ <groupId>io.quarkus</groupId>
+ <!-- Alternatively, use <artifactId>quarkus-universe-bom</artifactId>
+ which includes both quarkus-bom and timefold-solver-bom. -->
+ <artifactId>quarkus-bom</artifactId>
+ <version>${version.io.quarkus}</version>
+ <type>pom</type>
+ <scope>import</scope>
+ </dependency>
+ <dependency>
+ <groupId>ai.timefold.solver</groupId>
+ <artifactId>timefold-solver-bom</artifactId>
+ <version>${version.ai.timefold.solver}</version>
+ <type>pom</type>
+ <scope>import</scope>
+ </dependency>
+ </dependencies>
+ </dependencyManagement>
+ <dependencies>
+ <dependency>
+ <groupId>io.quarkus</groupId>
+ <artifactId>quarkus-resteasy</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>io.quarkus</groupId>
+ <artifactId>quarkus-resteasy-jackson</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>ai.timefold.solver</groupId>
+ <artifactId>timefold-solver-quarkus</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>ai.timefold.solver</groupId>
+ <artifactId>timefold-solver-quarkus-jackson</artifactId>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <version>${version.compiler.plugin}</version>
+ </plugin>
+ <plugin>
+ <groupId>io.quarkus</groupId>
+ <artifactId>quarkus-maven-plugin</artifactId>
+ <version>${version.io.quarkus}</version>
+ <executions>
+ <execution>
+ <goals>
+ <goal>build</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <configuration>
+ <systemPropertyVariables>
+ <java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
+ </systemPropertyVariables>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+</project>
+----
+--
+Kotlin::
++
+--
+[source,xml,subs=attributes+]
+----
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <groupId>org.acme</groupId>
+ <artifactId>timefold-solver-quarkus-vehicle-routing-quickstart</artifactId>
+ <version>1.0-SNAPSHOT</version>
+
+ <properties>
+ <maven.compiler.release>11</maven.compiler.release>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+
+ <version.io.quarkus>{quarkus-version}</version.io.quarkus>
+ <version.ai.timefold.solver>{timefold-solver-version}</version.ai.timefold.solver>
+ </properties>
+
+ <dependencyManagement>
+ <dependencies>
+ <dependency>
+ <groupId>io.quarkus</groupId>
+ <!-- Alternatively, use <artifactId>quarkus-universe-bom</artifactId>
+ which includes both quarkus-bom and timefold-solver-bom. -->
+ <artifactId>quarkus-bom</artifactId>
+ <version>${version.io.quarkus}</version>
+ <type>pom</type>
+ <scope>import</scope>
+ </dependency>
+ <dependency>
+ <groupId>ai.timefold.solver</groupId>
+ <artifactId>timefold-solver-bom</artifactId>
+ <version>${version.ai.timefold.solver}</version>
+ <type>pom</type>
+ <scope>import</scope>
+ </dependency>
+ </dependencies>
+ </dependencyManagement>
+ <dependencies>
+ <dependency>
+ <groupId>io.quarkus</groupId>
+ <artifactId>quarkus-resteasy</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>io.quarkus</groupId>
+ <artifactId>quarkus-resteasy-jackson</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>ai.timefold.solver</groupId>
+ <artifactId>timefold-solver-quarkus</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>ai.timefold.solver</groupId>
+ <artifactId>timefold-solver-quarkus-jackson</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.jetbrains.kotlin</groupId>
+ <artifactId>kotlin-stdlib</artifactId>
+ <version>1.9.22</version>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <sourceDirectory>src/main/kotlin</sourceDirectory>
+ <testSourceDirectory>src/test/kotlin</testSourceDirectory>
+ <plugins>
+ <plugin>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <version>${version.compiler.plugin}</version>
+ </plugin>
+ <plugin>
+ <groupId>io.quarkus</groupId>
+ <artifactId>quarkus-maven-plugin</artifactId>
+ <version>${version.io.quarkus}</version>
+ <executions>
+ <execution>
+ <goals>
+ <goal>build</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <configuration>
+ <systemPropertyVariables>
+ <java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
+ </systemPropertyVariables>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.jetbrains.kotlin</groupId>
+ <artifactId>kotlin-maven-plugin</artifactId>
+ <version>${version.kotlin}</version>
+ <executions>
+ <execution>
+ <id>compile</id>
+ <goals>
+ <goal>compile</goal>
+ </goals>
+ </execution>
+ <execution>
+ <id>test-compile</id>
+ <goals>
+ <goal>test-compile</goal>
+ </goals>
+ </execution>
+ </executions>
+ <dependencies>
+ <dependency>
+ <groupId>org.jetbrains.kotlin</groupId>
+ <artifactId>kotlin-maven-allopen</artifactId>
+ <version>${version.kotlin}</version>
+ </dependency>
+ </dependencies>
+ <configuration>
+ <javaParameters>true</javaParameters>
+ <jvmTarget>17</jvmTarget>
+ <compilerPlugins>
+ <plugin>all-open</plugin>
+ </compilerPlugins>
+ <pluginOptions>
+ <option>all-open:annotation=jakarta.ws.rs.Path</option>
+ <option>all-open:annotation=jakarta.enterprise.context.ApplicationScoped</option>
+ <option>all-open:annotation=io.quarkus.test.junit.QuarkusTest</option>
+ </pluginOptions>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+</project>
+----
+--
+====
+
+include::vehicle-routing-model.adoc[leveloffset=+1]
+include::vehicle-routing-constraints.adoc[leveloffset=+1]
+include::vehicle-routing-solution.adoc[leveloffset=+1]
+
+== Create the solver service
+
+Now you are ready to put everything together and create a REST service.
+But solving planning problems on REST threads causes HTTP timeout issues.
+Therefore, the Quarkus extension injects a `SolverManager` instance,
+which runs solvers in a separate thread pool
+and can solve multiple datasets in parallel.
+
+[tabs]
+====
+Java::
++
+--
+Create the `src/main/java/org/acme/vehiclerouting/rest/VehicleRoutePlanResource.java` class:
+
+[source,java]
+----
+package org.acme.vehiclerouting.rest;
+
+import java.util.UUID;
+import java.util.concurrent.ExecutionException;
+
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Consumes;
+import jakarta.ws.rs.POST;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.core.MediaType;
+
+import ai.timefold.solver.core.api.solver.SolverJob;
+import ai.timefold.solver.core.api.solver.SolverManager;
+
+import org.acme.vehiclerouting.domain.VehicleRoutePlan;
+
+@Path("route-plans")
+public class VehicleRoutePlanResource {
+
+ private final SolverManager<VehicleRoutePlan, String> solverManager;
+
+ public VehicleRoutePlanResource() {
+ this.solverManager = null;
+ }
+
+ @Inject
+ public VehicleRoutePlanResource(SolverManager<VehicleRoutePlan, String> solverManager) {
+ this.solverManager = solverManager;
+ }
+
+ @POST
+ @Path("solve")
+ @Consumes({ MediaType.APPLICATION_JSON })
+ @Produces(MediaType.APPLICATION_JSON)
+ public VehicleRoutePlan solve(VehicleRoutePlan problem) {
+ String jobId = UUID.randomUUID().toString();
+ SolverJob<VehicleRoutePlan, String> solverJob = solverManager.solveBuilder()
+ .withProblemId(jobId)
+ .withProblem(problem)
+ .run();
+ VehicleRoutePlan solution;
+ try {
+ // Wait until the solving ends
+ solution = solverJob.getFinalBestSolution();
+ } catch (InterruptedException | ExecutionException e) {
+ throw new IllegalStateException("Solving failed.", e);
+ }
+ return solution;
+ }
+}
+----
+--
+Kotlin::
++
+--
+Create the `src/main/kotlin/org/acme/vehiclerouting/rest/VehicleRoutePlanResource.kt` class:
+
+[source,kotlin]
+----
+package org.acme.vehiclerouting.rest
+
+import java.util.UUID
+import java.util.concurrent.ExecutionException
+
+import jakarta.inject.Inject
+import jakarta.ws.rs.Consumes
+import jakarta.ws.rs.POST
+import jakarta.ws.rs.Path
+import jakarta.ws.rs.Produces
+import jakarta.ws.rs.core.MediaType
+
+import ai.timefold.solver.core.api.solver.SolverManager
+
+import org.acme.vehiclerouting.domain.VehicleRoutePlan
+
+@Path("route-plans")
+class VehicleRoutePlanResource {
+ private val solverManager: SolverManager<VehicleRoutePlan, String>?
+
+ constructor() {
+ this.solverManager = null
+ }
+
+ @Inject
+ constructor(solverManager: SolverManager<VehicleRoutePlan, String>?) {
+ this.solverManager = solverManager
+ }
+
+ @POST
+ @Path("solve")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ fun solve(problem: VehicleRoutePlan): VehicleRoutePlan {
+ val jobId = UUID.randomUUID().toString()
+ val solverJob = solverManager!!.solveBuilder()
+ .withProblemId(jobId)
+ .withProblem(problem)
+ .run()
+ val solution: VehicleRoutePlan
+ try {
+ // Wait until the solving ends
+ solution = solverJob.finalBestSolution
+ } catch (e: InterruptedException) {
+ throw IllegalStateException("Solving failed.", e)
+ } catch (e: ExecutionException) {
+ throw IllegalStateException("Solving failed.", e)
+ }
+ return solution
+ }
+}
+----
+--
+====
+
+For simplicity's sake, this initial implementation waits for the solver to finish,
+which can still cause an HTTP timeout.
+The _complete_ implementation avoids HTTP timeouts much more elegantly.
+
+== Set the termination time
+
+Without a termination setting or a `terminationEarly()` event, the solver runs forever.
+To avoid that, limit the solving time to five seconds.
+That is short enough to avoid the HTTP timeout.
+
+Create the `src/main/resources/application.properties` file:
+
+[source,properties]
+----
+# The solver runs only for 5 seconds to avoid a HTTP timeout in this simple implementation.
+# It's recommended to run for at least 5 minutes ("5m") otherwise.
+quarkus.timefold.solver.termination.spent-limit=5s
+----
+
+Timefold Solver returns _the best solution_ found in the available termination time.
+Due to xref:optimization-algorithms/optimization-algorithms.adoc#doesTimefoldFindTheOptimalSolution[the nature of NP-hard problems],
+the best solution might not be optimal, especially for larger datasets.
+Increase the termination time to potentially find a better solution.
+
+== Run the application
+
+First start the application:
+
+[source,shell]
+----
+$ mvn compile quarkus:dev
+----
+
+=== Try the application
+
+Now that the application is running, you can test the REST service.
+You can use any REST client you wish.
+The following example uses the Linux command `curl` to send a POST request:
+
+[source,shell]
+----
+$ curl -i -X POST http://localhost:8080/route-plans/solve -H "Content-Type:application/json" -d '{"name":"demo","southWestCorner":[39.7656099067391,-76.83782328143754],"northEastCorner":[40.77636644354855,-74.9300739430771],"startDateTime":"2024-02-10T07:30:00","endDateTime":"2024-02-11T00:00:00","vehicles":[{"id":"1","capacity":15,"homeLocation":[40.605994321126936,-75.68106859680056],"departureTime":"2024-02-10T07:30:00","visits":[],"totalDrivingTimeSeconds":0,"totalDemand":0,"arrivalTime":"2024-02-10T07:30:00"},{"id":"2","capacity":25,"homeLocation":[40.32196770776356,-75.69785667307953],"departureTime":"2024-02-10T07:30:00","visits":[],"totalDrivingTimeSeconds":0,"totalDemand":0,"arrivalTime":"2024-02-10T07:30:00"}],"visits":[{"id":"1","name":"Dan Green","location":[40.76104493121754,-75.16056341466826],"demand":1,"minStartTime":"2024-02-10T13:00:00","maxEndTime":"2024-02-10T18:00:00","serviceDuration":1200.000000000,"vehicle":null,"previousVisit":null,"nextVisit":null,"arrivalTime":null,"startServiceTime":null,"departureTime":null,"drivingTimeSecondsFromPreviousStandstill":null},{"id":"2","name":"Ivy King","location":[40.13754381024318,-75.492526629236],"demand":1,"minStartTime":"2024-02-10T13:00:00","maxEndTime":"2024-02-10T18:00:00","serviceDuration":1200.000000000,"vehicle":null,"previousVisit":null,"nextVisit":null,"arrivalTime":null,"startServiceTime":null,"departureTime":null,"drivingTimeSecondsFromPreviousStandstill":null},{"id":"3","name":"Flo Li","location":[39.87122455090297,-75.64520072015769],"demand":2,"minStartTime":"2024-02-10T08:00:00","maxEndTime":"2024-02-10T12:00:00","serviceDuration":600.000000000,"vehicle":null,"previousVisit":null,"nextVisit":null,"arrivalTime":null,"startServiceTime":null,"departureTime":null,"drivingTimeSecondsFromPreviousStandstill":null},{"id":"4","name":"Flo Cole","location":[40.46124744193433,-75.18250987609025],"demand":1,"minStartTime":"2024-02-10T13:00:00","maxEndTime":"2024-02-10T18:00:00","serviceDuration":2400.000000000,"vehicle":null,"previousVisit":null,"nextVisit":null,"arrivalTime":null,"startServiceTime":null,"departureTime":null,"drivingTimeSecondsFromPreviousStandstill":null},{"id":"5","name":"Chad Green","location":[40.61352381171549,-75.83301278355529],"demand":1,"minStartTime":"2024-02-10T08:00:00","maxEndTime":"2024-02-10T12:00:00","serviceDuration":1800.000000000,"vehicle":null,"previousVisit":null,"nextVisit":null,"arrivalTime":null,"startServiceTime":null,"departureTime":null,"drivingTimeSecondsFromPreviousStandstill":null}],"totalDrivingTimeSeconds":0}'
+----
+
+After about five seconds, according to the termination spent time defined in your `application.properties`,
+the service returns an output similar to the following example:
+
+[source]
+----
+HTTP/1.1 200
+Content-Type: application/json
+...
+
+{"name":"demo","southWestCorner":[39.7656099067391,-76.83782328143754],"northEastCorner":[40.77636644354855,-74.9300739430771],"startDateTime":"2024-02-10T07:30:00","endDateTime":"2024-02-11T00:00:00","vehicles":[{"id":"1","capacity":15,"homeLocation":[40.605994321126936,-75.68106859680056],"departureTime":"2024-02-10T07:30:00","visits":["5","1","4"],"arrivalTime":"2024-02-10T15:34:11","totalDemand":3,"totalDrivingTimeSeconds":10826},{"id":"2","capacity":25,"homeLocation":[40.32196770776356,-75.69785667307953],"departureTime":"2024-02-10T07:30:00","visits":["3","2"],"arrivalTime":"2024-02-10T13:52:18","totalDemand":3,"totalDrivingTimeSeconds":7890}],"visits":[{"id":"1","name":"Dan Green","location":[40.76104493121754,-75.16056341466826],"demand":1,"minStartTime":"2024-02-10T13:00:00","maxEndTime":"2024-02-10T18:00:00","serviceDuration":1200.000000000,"vehicle":"1","previousVisit":"5","nextVisit":"4","arrivalTime":"2024-02-10T09:40:50","startServiceTime":"2024-02-10T13:00:00","departureTime":"2024-02-10T13:20:00","drivingTimeSecondsFromPreviousStandstill":4250},{"id":"2","name":"Ivy King","location":[40.13754381024318,-75.492526629236],"demand":1,"minStartTime":"2024-02-10T13:00:00","maxEndTime":"2024-02-10T18:00:00","serviceDuration":1200.000000000,"vehicle":"2","previousVisit":"3","nextVisit":null,"arrivalTime":"2024-02-10T09:19:12","startServiceTime":"2024-02-10T13:00:00","departureTime":"2024-02-10T13:20:00","drivingTimeSecondsFromPreviousStandstill":2329},{"id":"3","name":"Flo Li","location":[39.87122455090297,-75.64520072015769],"demand":2,"minStartTime":"2024-02-10T08:00:00","maxEndTime":"2024-02-10T12:00:00","serviceDuration":600.000000000,"vehicle":"2","previousVisit":null,"nextVisit":"2","arrivalTime":"2024-02-10T08:30:23","startServiceTime":"2024-02-10T08:30:23","departureTime":"2024-02-10T08:40:23","drivingTimeSecondsFromPreviousStandstill":3623},{"id":"4","name":"Flo Cole","location":[40.46124744193433,-75.18250987609025],"demand":1,"minStartTime":"2024-02-10T13:00:00","maxEndTime":"2024-02-10T18:00:00","serviceDuration":2400.000000000,"vehicle":"1","previousVisit":"1","nextVisit":null,"arrivalTime":"2024-02-10T14:00:04","startServiceTime":"2024-02-10T14:00:04","departureTime":"2024-02-10T14:40:04","drivingTimeSecondsFromPreviousStandstill":2404},{"id":"5","name":"Chad Green","location":[40.61352381171549,-75.83301278355529],"demand":1,"minStartTime":"2024-02-10T08:00:00","maxEndTime":"2024-02-10T12:00:00","serviceDuration":1800.000000000,"vehicle":"1","previousVisit":null,"nextVisit":"1","arrivalTime":"2024-02-10T07:45:25","startServiceTime":"2024-02-10T08:00:00","departureTime":"2024-02-10T08:30:00","drivingTimeSecondsFromPreviousStandstill":925}],"score":"0hard/-18716soft","totalDrivingTimeSeconds":18716}
+----
+
+Notice that your application assigned all five visits to one of the two vehicles.
+Also notice that it conforms to all hard constraints.
+For example, visits `1`, `4`, and `5` were scheduled to the vehicle `1`.
+
+On the server side, the `info` log shows what Timefold Solver did in those five seconds:
+
+[source,options="nowrap"]
+----
+... Solving started: time spent (17), best score (-5init/0hard/0soft), environment mode (REPRODUCIBLE), move thread count (NONE), random (JDK with seed 0).
+... Construction Heuristic phase (0) ended: time spent (33), best score (0hard/-18755soft), score calculation speed (2222/sec), step total (5).
+... Local Search phase (1) ended: time spent (5000), best score (0hard/-18716soft), score calculation speed (89685/sec), step total (40343).
+... Solving ended: time spent (5000), best score (0hard/-18716soft), score calculation speed (89079/sec), phase total (2), environment mode (REPRODUCIBLE), move thread count (NONE).
+----
+
+=== Test the application
+
+A good application includes test coverage.
+
+==== Test the constraints
+
+To test each constraint in isolation, use a `ConstraintVerifier` in unit tests.
+It tests each constraint's corner cases in isolation from the other tests,
+which lowers maintenance when adding a new constraint with proper test coverage.
+
+First update your build tool configuration:
+
+Add a `timefold-solver-test` dependency in your `pom.xml`:
+[source,xml]
+----
+ <dependency>
+ <groupId>io.quarkus</groupId>
+ <artifactId>quarkus-junit5</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>ai.timefold.solver</groupId>
+ <artifactId>timefold-solver-test</artifactId>
+ <scope>test</scope>
+ </dependency>
+----
+
+Then create the test itself:
+
+[tabs]
+====
+Java::
++
+--
+Create the `src/test/java/org/acme/vehiclerouting/solver/VehicleRoutingConstraintProviderTest.java` class:
+
+[source,java]
+----
+package org.acme.vehiclerouting.solver;
+
+import java.time.Duration;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.LocalTime;
+import java.util.Arrays;
+
+import jakarta.inject.Inject;
+
+import ai.timefold.solver.test.api.score.stream.ConstraintVerifier;
+
+import org.acme.vehiclerouting.domain.Location;
+import org.acme.vehiclerouting.domain.Vehicle;
+import org.acme.vehiclerouting.domain.VehicleRoutePlan;
+import org.acme.vehiclerouting.domain.Visit;
+import org.acme.vehiclerouting.domain.geo.HaversineDrivingTimeCalculator;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import io.quarkus.test.junit.QuarkusTest;
+
+@QuarkusTest
+class VehicleRoutingConstraintProviderTest {
+
+ /*
+ * LOCATION_1 to LOCATION_2 is approx. 11713 m ~843 seconds of driving time
+ * LOCATION_2 to LOCATION_3 is approx. 8880 m ~639 seconds of driving time
+ * LOCATION_1 to LOCATION_3 is approx. 13075 m ~941 seconds of driving time
+ */
+ private static final Location LOCATION_1 = new Location(49.288087, 16.562172);
+ private static final Location LOCATION_2 = new Location(49.190922, 16.624466);
+ private static final Location LOCATION_3 = new Location(49.1767533245638, 16.50422914190477);
+
+ private static final LocalDate TOMORROW = LocalDate.now().plusDays(1);
+ @Inject
+ ConstraintVerifier<VehicleRoutingConstraintProvider, VehicleRoutePlan> constraintVerifier;
+
+ @BeforeAll
+ static void initDrivingTimeMaps() {
+ HaversineDrivingTimeCalculator.getInstance().initDrivingTimeMaps(Arrays.asList(LOCATION_1, LOCATION_2, LOCATION_3));
+ }
+
+ @Test
+ void vehicleCapacityPenalized() {
+ LocalDateTime tomorrow_07_00 = LocalDateTime.of(TOMORROW, LocalTime.of(7, 0));
+ LocalDateTime tomorrow_08_00 = LocalDateTime.of(TOMORROW, LocalTime.of(8, 0));
+ LocalDateTime tomorrow_10_00 = LocalDateTime.of(TOMORROW, LocalTime.of(10, 0));
+ Vehicle vehicleA = new Vehicle("1", 100, LOCATION_1, tomorrow_07_00);
+ Visit visit1 = new Visit("2", "John", LOCATION_2, 80, tomorrow_08_00, tomorrow_10_00, Duration.ofMinutes(30L));
+ vehicleA.getVisits().add(visit1);
+ Visit visit2 = new Visit("3", "Paul", LOCATION_3, 40, tomorrow_08_00, tomorrow_10_00, Duration.ofMinutes(30L));
+ vehicleA.getVisits().add(visit2);
+
+ constraintVerifier.verifyThat(VehicleRoutingConstraintProvider::vehicleCapacity)
+ .given(vehicleA, visit1, visit2)
+ .penalizesBy(20);
+ }
+}
+
+----
+--
+Kotlin::
++
+--
+Create the `src/test/kotlin/org/acme/schooltimetabling/solver/TimetableConstraintProviderTest.kt` class:
+
+[source,kotlin]
+----
+package org.acme.vehiclerouting.solver;
+
+import java.time.Duration
+import java.time.LocalDate
+import java.time.LocalDateTime
+import java.time.LocalTime
+import java.util.Arrays
+
+import jakarta.inject.Inject
+
+import ai.timefold.solver.test.api.score.stream.ConstraintVerifier
+import ai.timefold.solver.core.api.score.stream.ConstraintFactory
+
+import org.acme.vehiclerouting.domain.Location
+import org.acme.vehiclerouting.domain.Vehicle
+import org.acme.vehiclerouting.domain.VehicleRoutePlan
+import org.acme.vehiclerouting.domain.Visit
+import org.acme.vehiclerouting.domain.geo.HaversineDrivingTimeCalculator
+import org.junit.jupiter.api.BeforeAll
+import org.junit.jupiter.api.Test
+
+import io.quarkus.test.junit.QuarkusTest
+
+@QuarkusTest
+internal class VehicleRoutingConstraintProviderTest {
+
+ @Inject
+ lateinit var constraintVerifier: ConstraintVerifier<VehicleRoutingConstraintProvider, VehicleRoutePlan>
+
+ @Test
+ fun vehicleCapacityPenalized() {
+ val tomorrow_07_00 = LocalDateTime.of(TOMORROW, LocalTime.of(7, 0))
+ val tomorrow_08_00 = LocalDateTime.of(TOMORROW, LocalTime.of(8, 0))
+ val tomorrow_10_00 = LocalDateTime.of(TOMORROW, LocalTime.of(10, 0))
+ val vehicleA = Vehicle("1", 100, LOCATION_1, tomorrow_07_00)
+ val visit1 = Visit("2", "John", LOCATION_2, 80, tomorrow_08_00, tomorrow_10_00, Duration.ofMinutes(30L))
+ vehicleA.visits!!.add(visit1)
+ val visit2 = Visit("3", "Paul", LOCATION_3, 40, tomorrow_08_00, tomorrow_10_00, Duration.ofMinutes(30L))
+ vehicleA.visits!!.add(visit2)
+
+ constraintVerifier!!.verifyThat { obj: VehicleRoutingConstraintProvider, factory: ConstraintFactory? ->
+ obj.vehicleCapacity(
+ factory!!
+ )
+ }
+ .given(vehicleA, visit1, visit2)
+ .penalizesBy(20)
+ }
+
+ companion object {
+ /*
+ * LOCATION_1 to LOCATION_2 is approx. 11713 m ~843 seconds of driving time
+ * LOCATION_2 to LOCATION_3 is approx. 8880 m ~639 seconds of driving time
+ * LOCATION_1 to LOCATION_3 is approx. 13075 m ~941 seconds of driving time
+ */
+ private val LOCATION_1 = Location(49.288087, 16.562172)
+ private val LOCATION_2 = Location(49.190922, 16.624466)
+ private val LOCATION_3 = Location(49.1767533245638, 16.50422914190477)
+
+ private val TOMORROW: LocalDate = LocalDate.now().plusDays(1)
+ @JvmStatic
+ @BeforeAll
+ fun initDrivingTimeMaps() {
+ HaversineDrivingTimeCalculator.INSTANCE.initDrivingTimeMaps(
+ Arrays.asList(
+ LOCATION_1, LOCATION_2, LOCATION_3
+ )
+ )
+ }
+ }
+}
+----
+--
+====
+
+This test verifies that the constraint `VehicleRoutingConstraintProvider::vehicleCapacity`,
+when given two visits assigned to the same vehicle, it penalizes with a match weight of `20` (exceeded capacity). | ```suggestion
when given two visits assigned to the same vehicle, penalizes with a match weight of `20` (exceeded capacity).
``` |
timefold-solver | github_2023 | others | 734 | TimefoldAI | zepfred | @@ -346,17 +346,19 @@ It is not available in the Community Edition.
There are several ways of doing multi-threaded solving:
-* *Multitenancy*: solve different datasets in parallel
-** The `SolverManager` will make it even easier to set this up, in a future version.
+* *<<multithreadedIncrementalSolving,Multi-threaded incremental solving>>*:
+Solve 1 dataset with multiple threads without sacrificing xref:constraints-and-score/performance.adoc#incrementalScoreCalculation[incremental score calculation].
+** Donate a portion of your CPU cores to Timefold Solver to scale up the score calculation speed and get the same results in fraction of the time.
+* *<<partitionedSearch,Partitioned Search>>*:
+Split 1 dataset in multiple parts and solve them independently.
* *Multi bet solving*: solve 1 dataset with multiple, isolated solvers and take the best result.
** Not recommended: This is a marginal gain for a high cost of hardware resources.
** Use the xref:using-timefold-solver/benchmarking-and-tweaking.adoc#benchmarker[Benchmarker] during development to determine the most appropriate algorithm, although that's only on average.
** Use multi-threaded incremental solving instead. | This sentence is repeated |
timefold-solver | github_2023 | others | 734 | TimefoldAI | zepfred | @@ -366,89 +368,109 @@ A xref:using-timefold-solver/running-the-solver.adoc#logging[logging level] of `
and slow down the xref:constraints-and-score/performance.adoc#scoreCalculationSpeed[score calculation speed].
====
-[#planningId]
-==== `@PlanningId`
-
-For some functionality (such as multi-threaded solving and real-time planning),
-Timefold Solver needs to map problem facts and planning entities to an ID.
-Timefold Solver uses that ID to _rebase_ a move from one thread's solution state to another's.
-To enable such functionality, specify the `@PlanningId` annotation on the identification field or getter method,
-for example on the database ID:
-
-[source,java,options="nowrap"]
-----
-public class Visit {
+[#multithreadedIncrementalSolving]
+==== Multi-threaded incremental solving
- @PlanningId
- private String username;
+With this feature, the solver can run significantly faster, getting you the right solution earlier. | ```suggestion
With this feature, the solver can run significantly faster,
getting you the right solution earlier.
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.