• Spring Boot集成Timefold Solver实现课程表编排


    1. 什么是Timefold Solver?

    每个组织都面临规划问题:使用一组有限的资源(员工、资产、时间和金钱)提供产品或服务。Timefold Solver 优化了此类规划,以更少的资源开展更多业务。这被称为约束满足编程(属于运筹学学科的一部分)。

    Timefold Solver是一个轻量级、可嵌入的约束满足引擎,可优化规划问题。它解决了以下用例:

    • 员工轮班排班:安排护士、修理工等的时间
    • 议程安排:安排会议、约会、维护工作、广告等
    • 教育时间表:安排课程、课程、考试、会议演示等
    • 车辆路线:使用已知的地图工具规划车辆路线(卡车、火车、轮船、飞机等),以便将货物和/或乘客运送到多个目的地……
    • 装箱:用物品填充集装箱、卡车、轮船和仓库,同时也跨计算机资源打包信息,例如云计算……
    • 车间调度:汽车装配线规划、机器队列规划、劳动力任务规划……
    • 切割库存:切割纸张、钢材、地毯等时尽量减少浪费……
    • 体育赛事安排:规划足球联赛、棒球联赛等的比赛和训练日程……
    • 财务优化:投资组合优化、风险分散……

    useCaseOverview

    1.1什么是规划问题?

    whatIsAPlanningProblem

    规划问题具有基于有限资源和特定约束的最优目标。最优目标可以是任意数量的事物,例如:

    • 利润最大化——最佳目标带来最高的利润。
    • 最小化生态足迹——最佳目标是对环境的影响最小。
    • 最大限度地提高员工或客户的满意度——最佳目标优先考虑员工或客户的需求。

    实现这些目标的能力取决于可用资源的数量,例如:

    • 人的数量。
    • 多少时间。
    • 预算。
    • 实物资产,例如机械、车辆、计算机、建筑物等。

    还必须考虑与这些资源相关的具体限制,例如一个人的工作时间、他们使用某些机器的能力或设备之间的兼容性。

    Timefold Solver 可帮助 Java TM、Kotlin 和 Python 程序员高效地解决约束满足问题。在底层,它将优化启发式和元启发式与非常高效的分数计算相结合。

    1.2规划问题是 NP 完全问题还是 NP 难题

    所有上述用例可能是 NP-complete/NP-hard,用外行人的话来说就是:

    • 在合理的时间内验证问题的给定解决方案很容易。
    • 没有什么灵丹妙药可以在合理的时间内找到问题的最佳解决方案(*)。

    (*) 至少,世界上最聪明的计算机科学家还没有找到这样的灵丹妙药。但如果他们能找到一个解决 NP 完全问题的灵丹妙药,那么它就能解决所有 NP 完全问题。

    事实上,如果有人能证明这种灵丹妙药是否真的存在,就可以获得 1,000,000 美元的奖励。

    这意味着非常可怕的事情:解决你的问题可能比你想象的要难,因为两种常用的技术是不够的:

    • 暴力算法(即使是更智能的变体)也会花费太长时间。
    • 一种快速算法,例如在装箱中,首先放入最大的物品,将返回远非最优的解决方案。

    通过使用先进的优化算法,Timefold Solver 确实能够在合理的时间内为此类规划问题找到接近最优的解决方案。

    1.3. 规划问题有(硬和软)约束

    通常,规划问题至少有两个层次的约束:

    • (负面)硬约束不能被打破。例如:1 位老师不能同时教授 2 门不同的课程
    • 如果可以避免,则不应打破(负面)软约束。例如: A 老师不喜欢在星期五下午上课

    有些问题也有积极的约束:

    • 如果可能的话,应该满足积极的软约束(或奖励)。例如:B老师喜欢在周一早上上课

    有些基本问题只有硬约束,有些问题有三级或更多级的约束——硬约束、中等约束和软约束。

    这些约束定义了规划问题的得分计算(又称适应度函数)。规划问题的每个解决方案都可以用分数来评分。 使用 Timefold Solver,问题可以在 Java TM、Kotlin 或 Python等语言中以面向对象范式建模。这样的代码简单、灵活且可扩展。

    1.4. 规划问题具有巨大的搜索空间

    规划问题有多种解决方案。解决方案有以下几类:

    • 任何解决方案都是可能的解决方案,无论它是否打破了多少限制。规划问题往往有大量的可能解决方案。其中许多解决方案毫无价值。
    • 可行是指不打破任何(负面)硬约束的解。可行解的数量往往与可能解的数量有关。有时没有可行解。每个可行解都是一个可能解。
    • 最优是得分最高的解。规划问题往往有 1 个或几个最优解。即使在没有可行解且最优解不可行的情况下,也总是至少有 1 个最优解。
    • 找到的最佳解决方案是实现在给定时间内找到的得分最高的解决方案。找到的最佳解决方案很可能是可行的,并且如果有足够的时间,它就是最优解决方案。

    与直觉相反的是,即使数据集很小,可能的解决方案数量也是巨大的(如果计算正确的话)。正如您在示例中看到的,大多数情况下的可能解决方案比已知宇宙中原子的最小数量(10^80)要多得多。由于没有灵丹妙药可以找到最佳解决方案,因此任何实现都必须评估所有这些可能解决方案的至少一个子集。

    Timefold Solver 支持多种优化算法,可高效地处理数量惊人的可能解决方案。根据用例,某些优化算法的性能优于其他算法,但无法提前知道。 使用 Timefold Solver,只需在几行代码中更改求解器配置,即可轻松切换优化算法。

    2.代码工程

    实验目的:

    实现课程表编排,Lesson实例分配给TimeslotRoom实例以遵守硬调度和软调度约束,例如以下示例:

    • 一个房间最多可以同时上一节课。
    • 一位老师最多可以同时讲授一节课。
    • 一名学生最多可同时参加一节课。
    • 一位老师喜欢在同一个教室里讲授所有课程。
    • 一位老师喜欢教授连续的课程并且不喜欢课程之间有间隙。
    • 学生不喜欢连续学习同一科目。

    从数学上讲,学校时间表是一个NP难题。这意味着它很难扩展。对于一个非平凡的数据集,简单地用蛮力迭代所有可能的组合需要数百万年的时间,即使在超级计算机上也是如此。幸运的是,Timefold Solver 等 AI 约束求解器拥有先进的算法,可以在合理的时间内提供接近最优的解决方案。

    pom.xml

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    4. <modelVersion>4.0.0</modelVersion>
    5. <!-- Use spring boot parent to use its native profile -->
    6. <parent>
    7. <groupId>org.springframework.boot</groupId>
    8. <artifactId>spring-boot-starter-parent</artifactId>
    9. <version>3.2.1</version>
    10. </parent>
    11. <groupId>org.acme</groupId>
    12. <artifactId>spring-boot-school-timetabling</artifactId>
    13. <version>1.0-SNAPSHOT</version>
    14. <properties>
    15. <maven.compiler.release>17</maven.compiler.release>
    16. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    17. <version.ai.timefold.solver>1.10.0</version.ai.timefold.solver>
    18. <version.org.springframework.boot>${project.parent.version}</version.org.springframework.boot>
    19. <version.compiler.plugin>3.13.0</version.compiler.plugin>
    20. <version.surefire.plugin>3.2.5</version.surefire.plugin>
    21. </properties>
    22. <dependencyManagement>
    23. <dependencies>
    24. <dependency>
    25. <groupId>org.springframework.boot</groupId>
    26. <artifactId>spring-boot-dependencies</artifactId>
    27. <version>${version.org.springframework.boot}</version>
    28. <type>pom</type>
    29. <scope>import</scope>
    30. </dependency>
    31. <dependency>
    32. <groupId>ai.timefold.solver</groupId>
    33. <artifactId>timefold-solver-bom</artifactId>
    34. <version>${version.ai.timefold.solver}</version>
    35. <type>pom</type>
    36. <scope>import</scope>
    37. </dependency>
    38. </dependencies>
    39. </dependencyManagement>
    40. <dependencies>
    41. <!-- Spring boot -->
    42. <dependency>
    43. <groupId>org.springframework.boot</groupId>
    44. <artifactId>spring-boot-starter-web</artifactId>
    45. </dependency>
    46. <dependency>
    47. <groupId>ai.timefold.solver</groupId>
    48. <artifactId>timefold-solver-spring-boot-starter</artifactId>
    49. </dependency>
    50. <!-- Swagger -->
    51. <dependency>
    52. <groupId>org.springdoc</groupId>
    53. <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    54. <version>2.5.0</version>
    55. </dependency>
    56. <!-- Testing -->
    57. <dependency>
    58. <groupId>org.springframework.boot</groupId>
    59. <artifactId>spring-boot-starter-test</artifactId>
    60. <scope>test</scope>
    61. </dependency>
    62. <dependency>
    63. <groupId>ai.timefold.solver</groupId>
    64. <artifactId>timefold-solver-test</artifactId>
    65. <scope>test</scope>
    66. </dependency>
    67. <dependency>
    68. <groupId>org.springframework</groupId>
    69. <artifactId>spring-webflux</artifactId>
    70. <scope>test</scope>
    71. </dependency>
    72. <dependency>
    73. <groupId>org.awaitility</groupId>
    74. <artifactId>awaitility</artifactId>
    75. <scope>test</scope>
    76. </dependency>
    77. <!-- UI -->
    78. <!-- No webjar locator; incompatible in native mode;
    79. see https://github.com/spring-projects/spring-framework/issues/27619
    80. and https://github.com/webjars/webjars-locator-core/issues/96
    81. -->
    82. <dependency>
    83. <groupId>ai.timefold.solver</groupId>
    84. <artifactId>timefold-solver-webui</artifactId>
    85. <scope>runtime</scope>
    86. </dependency>
    87. <dependency>
    88. <groupId>org.webjars</groupId>
    89. <artifactId>bootstrap</artifactId>
    90. <version>5.2.3</version>
    91. <scope>runtime</scope>
    92. </dependency>
    93. <dependency>
    94. <groupId>org.webjars</groupId>
    95. <artifactId>jquery</artifactId>
    96. <version>3.6.4</version>
    97. <scope>runtime</scope>
    98. </dependency>
    99. <dependency>
    100. <groupId>org.webjars</groupId>
    101. <artifactId>font-awesome</artifactId>
    102. <version>5.15.1</version>
    103. <scope>runtime</scope>
    104. </dependency>
    105. <dependency>
    106. <groupId>org.webjars.npm</groupId>
    107. <artifactId>js-joda</artifactId>
    108. <version>1.11.0</version>
    109. <scope>runtime</scope>
    110. </dependency>
    111. </dependencies>
    112. <build>
    113. <plugins>
    114. <plugin>
    115. <artifactId>maven-compiler-plugin</artifactId>
    116. <version>${version.compiler.plugin}</version>
    117. </plugin>
    118. <plugin>
    119. <artifactId>maven-surefire-plugin</artifactId>
    120. <version>${version.surefire.plugin}</version>
    121. </plugin>
    122. <plugin>
    123. <groupId>org.springframework.boot</groupId>
    124. <artifactId>spring-boot-maven-plugin</artifactId>
    125. <version>${version.org.springframework.boot}</version>
    126. <executions>
    127. <!-- Repackage the archive produced by maven-jar-plugin into an executable JAR file. -->
    128. <execution>
    129. <goals>
    130. <goal>repackage</goal>
    131. </goals>
    132. </execution>
    133. </executions>
    134. <configuration>
    135. <!-- optimizedLaunch disables the C2 compiler, which has a massive performance impact -->
    136. <optimizedLaunch>false</optimizedLaunch>
    137. </configuration>
    138. </plugin>
    139. <plugin>
    140. <groupId>org.graalvm.buildtools</groupId>
    141. <artifactId>native-maven-plugin</artifactId>
    142. </plugin>
    143. </plugins>
    144. </build>
    145. </project>

    时间段

    课程Timeslot代表授课的时间间隔,例如Monday 10:30 - 11:30Tuesday 13:30 - 14:30。为简单起见,所有时间段的持续时间相同,午餐或其他休息期间没有时间段。

    1. package org.acme.schooltimetabling.domain;
    2. import ai.timefold.solver.core.api.domain.lookup.PlanningId;
    3. import com.fasterxml.jackson.annotation.JsonIdentityInfo;
    4. import com.fasterxml.jackson.annotation.ObjectIdGenerators;
    5. import java.time.DayOfWeek;
    6. import java.time.LocalTime;
    7. @JsonIdentityInfo(scope = Timeslot.class, generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
    8. public class Timeslot {
    9. @PlanningId
    10. private String id;
    11. private DayOfWeek dayOfWeek;
    12. private LocalTime startTime;
    13. private LocalTime endTime;
    14. public Timeslot() {
    15. }
    16. public Timeslot(String id, DayOfWeek dayOfWeek, LocalTime startTime, LocalTime endTime) {
    17. this.id = id;
    18. this.dayOfWeek = dayOfWeek;
    19. this.startTime = startTime;
    20. this.endTime = endTime;
    21. }
    22. public Timeslot(String id, DayOfWeek dayOfWeek, LocalTime startTime) {
    23. this(id, dayOfWeek, startTime, startTime.plusMinutes(50));
    24. }
    25. @Override
    26. public String toString() {
    27. return dayOfWeek + " " + startTime;
    28. }
    29. // ************************************************************************
    30. // Getters and setters
    31. // ************************************************************************
    32. public String getId() {
    33. return id;
    34. }
    35. public DayOfWeek getDayOfWeek() {
    36. return dayOfWeek;
    37. }
    38. public LocalTime getStartTime() {
    39. return startTime;
    40. }
    41. public LocalTime getEndTime() {
    42. return endTime;
    43. }
    44. }

    房间

    教室Room代表授课地点,例如Room ARoom B。为简单起见,所有房间均无容量限制,可容纳所有课程。

    1. package org.acme.schooltimetabling.domain;
    2. import ai.timefold.solver.core.api.domain.lookup.PlanningId;
    3. import com.fasterxml.jackson.annotation.JsonIdentityInfo;
    4. import com.fasterxml.jackson.annotation.ObjectIdGenerators;
    5. @JsonIdentityInfo(scope = Room.class, generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
    6. public class Room {
    7. @PlanningId
    8. private String id;
    9. private String name;
    10. public Room() {
    11. }
    12. public Room(String id, String name) {
    13. this.id = id;
    14. this.name = name;
    15. }
    16. @Override
    17. public String toString() {
    18. return name;
    19. }
    20. // ************************************************************************
    21. // Getters and setters
    22. // ************************************************************************
    23. public String getId() {
    24. return id;
    25. }
    26. public String getName() {
    27. return name;
    28. }
    29. }

    课程

    在课堂上Lesson,一位老师向一组学生讲授一门课程,例如Math by A.Turing for 9th gradeChemistry by M.Curie for 10th grade。如果同一老师每周向同一组学生讲授同一门课程多次,则存在多个Lesson实例,只能通过 来区分id。例如,9 年级每周有 6 节数学课。

    在解决过程中,Timefold Solver 会更改课程的timeslotroom字段Lesson,以将每节课分配到时间段和房间。由于 Timefold Solver 会更改这些字段,因此Lesson是一个规划实体

    schoolTimetablingClassDiagramAnnotated

    1. package org.acme.schooltimetabling.domain;
    2. import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
    3. import ai.timefold.solver.core.api.domain.lookup.PlanningId;
    4. import ai.timefold.solver.core.api.domain.variable.PlanningVariable;
    5. import com.fasterxml.jackson.annotation.JsonIdentityReference;
    6. @PlanningEntity
    7. public class Lesson {
    8. @PlanningId
    9. private String id;
    10. private String subject;
    11. private String teacher;
    12. private String studentGroup;
    13. @JsonIdentityReference
    14. @PlanningVariable
    15. private Timeslot timeslot;
    16. @JsonIdentityReference
    17. @PlanningVariable
    18. private Room room;
    19. public Lesson() {
    20. }
    21. public Lesson(String id, String subject, String teacher, String studentGroup) {
    22. this.id = id;
    23. this.subject = subject;
    24. this.teacher = teacher;
    25. this.studentGroup = studentGroup;
    26. }
    27. public Lesson(String id, String subject, String teacher, String studentGroup, Timeslot timeslot, Room room) {
    28. this(id, subject, teacher, studentGroup);
    29. this.timeslot = timeslot;
    30. this.room = room;
    31. }
    32. @Override
    33. public String toString() {
    34. return subject + "(" + id + ")";
    35. }
    36. // ************************************************************************
    37. // Getters and setters
    38. // ************************************************************************
    39. public String getId() {
    40. return id;
    41. }
    42. public String getSubject() {
    43. return subject;
    44. }
    45. public String getTeacher() {
    46. return teacher;
    47. }
    48. public String getStudentGroup() {
    49. return studentGroup;
    50. }
    51. public Timeslot getTimeslot() {
    52. return timeslot;
    53. }
    54. public void setTimeslot(Timeslot timeslot) {
    55. this.timeslot = timeslot;
    56. }
    57. public Room getRoom() {
    58. return room;
    59. }
    60. public void setRoom(Room room) {
    61. this.room = room;
    62. }
    63. }

    定义约束并计算分数

    分数代表特定解决方案的质量。分数越高越好。Timefold Solver 寻找最佳解决方案,即在可用时间内找到的得分最高的解决方案。它可能是最佳解决方案。

    由于此用例有硬约束和软约束,因此使用HardSoftScore类来表示分数:

    • 不能打破硬性约束。例如:一个房间最多只能同时上一节课。
    • 软约束不能被打破。例如:老师喜欢在单人教室上课。

    硬约束相对于其他硬约束具有权重。软约束相对于其他软约束也具有权重。 无论各自的权重如何,硬约束总是比软约束更重要。

    1. package org.acme.schooltimetabling.solver;
    2. import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore;
    3. import ai.timefold.solver.core.api.score.stream.Constraint;
    4. import ai.timefold.solver.core.api.score.stream.ConstraintFactory;
    5. import ai.timefold.solver.core.api.score.stream.ConstraintProvider;
    6. import ai.timefold.solver.core.api.score.stream.Joiners;
    7. import org.acme.schooltimetabling.domain.Lesson;
    8. import org.acme.schooltimetabling.solver.justifications.*;
    9. import java.time.Duration;
    10. public class TimetableConstraintProvider implements ConstraintProvider {
    11. @Override
    12. public Constraint[] defineConstraints(ConstraintFactory constraintFactory) {
    13. return new Constraint[] {
    14. // Hard constraints
    15. roomConflict(constraintFactory),
    16. teacherConflict(constraintFactory),
    17. studentGroupConflict(constraintFactory),
    18. // Soft constraints
    19. teacherRoomStability(constraintFactory),
    20. teacherTimeEfficiency(constraintFactory),
    21. studentGroupSubjectVariety(constraintFactory)
    22. };
    23. }
    24. Constraint roomConflict(ConstraintFactory constraintFactory) {
    25. // A room can accommodate at most one lesson at the same time.
    26. return constraintFactory
    27. // Select each pair of 2 different lessons ...
    28. .forEachUniquePair(Lesson.class,
    29. // ... in the same timeslot ...
    30. Joiners.equal(Lesson::getTimeslot),
    31. // ... in the same room ...
    32. Joiners.equal(Lesson::getRoom))
    33. // ... and penalize each pair with a hard weight.
    34. .penalize(HardSoftScore.ONE_HARD)
    35. .justifyWith((lesson1, lesson2, score) -> new RoomConflictJustification(lesson1.getRoom(), lesson1, lesson2))
    36. .asConstraint("Room conflict");
    37. }
    38. Constraint teacherConflict(ConstraintFactory constraintFactory) {
    39. // A teacher can teach at most one lesson at the same time.
    40. return constraintFactory
    41. .forEachUniquePair(Lesson.class,
    42. Joiners.equal(Lesson::getTimeslot),
    43. Joiners.equal(Lesson::getTeacher))
    44. .penalize(HardSoftScore.ONE_HARD)
    45. .justifyWith(
    46. (lesson1, lesson2, score) -> new TeacherConflictJustification(lesson1.getTeacher(), lesson1, lesson2))
    47. .asConstraint("Teacher conflict");
    48. }
    49. Constraint studentGroupConflict(ConstraintFactory constraintFactory) {
    50. // A student can attend at most one lesson at the same time.
    51. return constraintFactory
    52. .forEachUniquePair(Lesson.class,
    53. Joiners.equal(Lesson::getTimeslot),
    54. Joiners.equal(Lesson::getStudentGroup))
    55. .penalize(HardSoftScore.ONE_HARD)
    56. .justifyWith((lesson1, lesson2, score) -> new StudentGroupConflictJustification(lesson1.getStudentGroup(), lesson1, lesson2))
    57. .asConstraint("Student group conflict");
    58. }
    59. Constraint teacherRoomStability(ConstraintFactory constraintFactory) {
    60. // A teacher prefers to teach in a single room.
    61. return constraintFactory
    62. .forEachUniquePair(Lesson.class,
    63. Joiners.equal(Lesson::getTeacher))
    64. .filter((lesson1, lesson2) -> lesson1.getRoom() != lesson2.getRoom())
    65. .penalize(HardSoftScore.ONE_SOFT)
    66. .justifyWith((lesson1, lesson2, score) -> new TeacherRoomStabilityJustification(lesson1.getTeacher(), lesson1, lesson2))
    67. .asConstraint("Teacher room stability");
    68. }
    69. Constraint teacherTimeEfficiency(ConstraintFactory constraintFactory) {
    70. // A teacher prefers to teach sequential lessons and dislikes gaps between lessons.
    71. return constraintFactory
    72. .forEach(Lesson.class)
    73. .join(Lesson.class, Joiners.equal(Lesson::getTeacher),
    74. Joiners.equal((lesson) -> lesson.getTimeslot().getDayOfWeek()))
    75. .filter((lesson1, lesson2) -> {
    76. Duration between = Duration.between(lesson1.getTimeslot().getEndTime(),
    77. lesson2.getTimeslot().getStartTime());
    78. return !between.isNegative() && between.compareTo(Duration.ofMinutes(30)) <= 0;
    79. })
    80. .reward(HardSoftScore.ONE_SOFT)
    81. .justifyWith((lesson1, lesson2, score) -> new TeacherTimeEfficiencyJustification(lesson1.getTeacher(), lesson1, lesson2))
    82. .asConstraint("Teacher time efficiency");
    83. }
    84. Constraint studentGroupSubjectVariety(ConstraintFactory constraintFactory) {
    85. // A student group dislikes sequential lessons on the same subject.
    86. return constraintFactory
    87. .forEach(Lesson.class)
    88. .join(Lesson.class,
    89. Joiners.equal(Lesson::getSubject),
    90. Joiners.equal(Lesson::getStudentGroup),
    91. Joiners.equal((lesson) -> lesson.getTimeslot().getDayOfWeek()))
    92. .filter((lesson1, lesson2) -> {
    93. Duration between = Duration.between(lesson1.getTimeslot().getEndTime(),
    94. lesson2.getTimeslot().getStartTime());
    95. return !between.isNegative() && between.compareTo(Duration.ofMinutes(30)) <= 0;
    96. })
    97. .penalize(HardSoftScore.ONE_SOFT)
    98. .justifyWith((lesson1, lesson2, score) -> new StudentGroupSubjectVarietyJustification(lesson1.getStudentGroup(), lesson1, lesson2))
    99. .asConstraint("Student group subject variety");
    100. }
    101. }

    在规划解决方案中收集领域对象

    ATimetable包装单个数据集的所有TimeslotRoom和实例。此外,由于它包含所有课程,每个课程都有特定的规划变量状态,因此它是一个规划解决方案,并且具有分数:Lesson

    • 如果课程仍未分配,那么它就是一个未初始化的解决方案,例如分数为 的解决方案-4init/0hard/0soft
    • 如果它打破了硬约束,那么它就是一个不可行的解决方案,例如得分为 的解决方案-2hard/-3soft
    • 如果它遵守所有硬性约束,那么它就是一个可行的解决方案,例如分数为 的解决方案0hard/-7soft
    1. package org.acme.schooltimetabling.domain;
    2. import ai.timefold.solver.core.api.domain.solution.PlanningEntityCollectionProperty;
    3. import ai.timefold.solver.core.api.domain.solution.PlanningScore;
    4. import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
    5. import ai.timefold.solver.core.api.domain.solution.ProblemFactCollectionProperty;
    6. import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider;
    7. import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore;
    8. import ai.timefold.solver.core.api.solver.SolverStatus;
    9. import java.util.List;
    10. @PlanningSolution
    11. public class Timetable {
    12. private String name;
    13. @ProblemFactCollectionProperty
    14. @ValueRangeProvider
    15. private List<Timeslot> timeslots;
    16. @ProblemFactCollectionProperty
    17. @ValueRangeProvider
    18. private List<Room> rooms;
    19. @PlanningEntityCollectionProperty
    20. private List<Lesson> lessons;
    21. @PlanningScore
    22. private HardSoftScore score;
    23. // Ignored by Timefold, used by the UI to display solve or stop solving button
    24. private SolverStatus solverStatus;
    25. // No-arg constructor required for Timefold
    26. public Timetable() {
    27. }
    28. public Timetable(String name, HardSoftScore score, SolverStatus solverStatus) {
    29. this.name = name;
    30. this.score = score;
    31. this.solverStatus = solverStatus;
    32. }
    33. public Timetable(String name, List<Timeslot> timeslots, List<Room> rooms, List<Lesson> lessons) {
    34. this.name = name;
    35. this.timeslots = timeslots;
    36. this.rooms = rooms;
    37. this.lessons = lessons;
    38. }
    39. // ************************************************************************
    40. // Getters and setters
    41. // ************************************************************************
    42. public String getName() {
    43. return name;
    44. }
    45. public List<Timeslot> getTimeslots() {
    46. return timeslots;
    47. }
    48. public List<Room> getRooms() {
    49. return rooms;
    50. }
    51. public List<Lesson> getLessons() {
    52. return lessons;
    53. }
    54. public HardSoftScore getScore() {
    55. return score;
    56. }
    57. public SolverStatus getSolverStatus() {
    58. return solverStatus;
    59. }
    60. public void setSolverStatus(SolverStatus solverStatus) {
    61. this.solverStatus = solverStatus;
    62. }
    63. }

    controller

    1. package org.acme.schooltimetabling.rest;
    2. import java.util.Collection;
    3. import java.util.UUID;
    4. import java.util.concurrent.ConcurrentHashMap;
    5. import java.util.concurrent.ConcurrentMap;
    6. import ai.timefold.solver.core.api.score.analysis.ScoreAnalysis;
    7. import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore;
    8. import ai.timefold.solver.core.api.solver.ScoreAnalysisFetchPolicy;
    9. import ai.timefold.solver.core.api.solver.SolutionManager;
    10. import ai.timefold.solver.core.api.solver.SolverManager;
    11. import ai.timefold.solver.core.api.solver.SolverStatus;
    12. import org.acme.schooltimetabling.domain.Timetable;
    13. import org.acme.schooltimetabling.rest.exception.ErrorInfo;
    14. import org.acme.schooltimetabling.rest.exception.TimetableSolverException;
    15. import org.acme.schooltimetabling.solver.justifications.RoomConflictJustification;
    16. import org.acme.schooltimetabling.solver.justifications.StudentGroupConflictJustification;
    17. import org.acme.schooltimetabling.solver.justifications.StudentGroupSubjectVarietyJustification;
    18. import org.acme.schooltimetabling.solver.justifications.TeacherConflictJustification;
    19. import org.acme.schooltimetabling.solver.justifications.TeacherRoomStabilityJustification;
    20. import org.acme.schooltimetabling.solver.justifications.TeacherTimeEfficiencyJustification;
    21. import org.slf4j.Logger;
    22. import org.slf4j.LoggerFactory;
    23. import org.springframework.aot.hint.annotation.RegisterReflectionForBinding;
    24. import org.springframework.http.HttpStatus;
    25. import org.springframework.http.MediaType;
    26. import org.springframework.web.bind.annotation.DeleteMapping;
    27. import org.springframework.web.bind.annotation.GetMapping;
    28. import org.springframework.web.bind.annotation.PathVariable;
    29. import org.springframework.web.bind.annotation.PostMapping;
    30. import org.springframework.web.bind.annotation.PutMapping;
    31. import org.springframework.web.bind.annotation.RequestBody;
    32. import org.springframework.web.bind.annotation.RequestMapping;
    33. import org.springframework.web.bind.annotation.RequestParam;
    34. import org.springframework.web.bind.annotation.RestController;
    35. import io.swagger.v3.oas.annotations.Operation;
    36. import io.swagger.v3.oas.annotations.Parameter;
    37. import io.swagger.v3.oas.annotations.media.Content;
    38. import io.swagger.v3.oas.annotations.media.Schema;
    39. import io.swagger.v3.oas.annotations.responses.ApiResponse;
    40. import io.swagger.v3.oas.annotations.responses.ApiResponses;
    41. import io.swagger.v3.oas.annotations.tags.Tag;
    42. @Tag(name = "School Timetables", description = "School timetable service assigning lessons to rooms and timeslots.")
    43. @RestController
    44. @RequestMapping("/timetables")
    45. public class TimetableController {
    46. private static final Logger LOGGER = LoggerFactory.getLogger(TimetableController.class);
    47. private final SolverManager<Timetable, String> solverManager;
    48. private final SolutionManager<Timetable, HardSoftScore> solutionManager;
    49. // TODO: Without any "time to live", the map may eventually grow out of memory.
    50. private final ConcurrentMap<String, Job> jobIdToJob = new ConcurrentHashMap<>();
    51. public TimetableController(SolverManager<Timetable, String> solverManager,
    52. SolutionManager<Timetable, HardSoftScore> solutionManager) {
    53. this.solverManager = solverManager;
    54. this.solutionManager = solutionManager;
    55. }
    56. @Operation(summary = "List the job IDs of all submitted timetables.")
    57. @ApiResponses(value = {
    58. @ApiResponse(responseCode = "200", description = "List of all job IDs.",
    59. content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE,
    60. schema = @Schema(type = "array", implementation = String.class))) })
    61. @GetMapping
    62. public Collection<String> list() {
    63. return jobIdToJob.keySet();
    64. }
    65. @Operation(summary = "Submit a timetable to start solving as soon as CPU resources are available.")
    66. @ApiResponses(value = {
    67. @ApiResponse(responseCode = "202",
    68. description = "The job ID. Use that ID to get the solution with the other methods.",
    69. content = @Content(mediaType = MediaType.TEXT_PLAIN_VALUE,
    70. schema = @Schema(implementation = String.class))) })
    71. @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.TEXT_PLAIN_VALUE)
    72. public String solve(@RequestBody Timetable problem) {
    73. String jobId = UUID.randomUUID().toString();
    74. jobIdToJob.put(jobId, Job.ofTimetable(problem));
    75. solverManager.solveBuilder()
    76. .withProblemId(jobId)
    77. .withProblemFinder(jobId_ -> jobIdToJob.get(jobId).timetable)
    78. .withBestSolutionConsumer(solution -> jobIdToJob.put(jobId, Job.ofTimetable(solution)))
    79. .withExceptionHandler((jobId_, exception) -> {
    80. jobIdToJob.put(jobId, Job.ofException(exception));
    81. LOGGER.error("Failed solving jobId ({}).", jobId, exception);
    82. })
    83. .run();
    84. return jobId;
    85. }
    86. @Operation(summary = "Submit a timetable to analyze its score.")
    87. @ApiResponses(value = {
    88. @ApiResponse(responseCode = "202",
    89. description = "Resulting score analysis, optionally without constraint matches.",
    90. content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE,
    91. schema = @Schema(implementation = ScoreAnalysis.class))) })
    92. @PutMapping(value = "/analyze", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    93. @RegisterReflectionForBinding({
    94. RoomConflictJustification.class,
    95. StudentGroupConflictJustification.class,
    96. StudentGroupSubjectVarietyJustification.class,
    97. TeacherConflictJustification.class,
    98. TeacherRoomStabilityJustification.class,
    99. TeacherTimeEfficiencyJustification.class
    100. })
    101. public ScoreAnalysis<HardSoftScore> analyze(@RequestBody Timetable problem,
    102. @RequestParam(name = "fetchPolicy", required = false) ScoreAnalysisFetchPolicy fetchPolicy) {
    103. return fetchPolicy == null ? solutionManager.analyze(problem) : solutionManager.analyze(problem, fetchPolicy);
    104. }
    105. @Operation(
    106. summary = "Get the solution and score for a given job ID. This is the best solution so far, as it might still be running or not even started.")
    107. @ApiResponses(value = {
    108. @ApiResponse(responseCode = "200", description = "The best solution of the timetable so far.",
    109. content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE,
    110. schema = @Schema(implementation = Timetable.class))),
    111. @ApiResponse(responseCode = "404", description = "No timetable found.",
    112. content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE,
    113. schema = @Schema(implementation = ErrorInfo.class))),
    114. @ApiResponse(responseCode = "500", description = "Exception during solving a timetable.",
    115. content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE,
    116. schema = @Schema(implementation = ErrorInfo.class)))
    117. })
    118. @GetMapping(value = "/{jobId}", produces = MediaType.APPLICATION_JSON_VALUE)
    119. public Timetable getTimeTable(
    120. @Parameter(description = "The job ID returned by the POST method.") @PathVariable("jobId") String jobId) {
    121. Timetable timetable = getTimetableAndCheckForExceptions(jobId);
    122. SolverStatus solverStatus = solverManager.getSolverStatus(jobId);
    123. timetable.setSolverStatus(solverStatus);
    124. return timetable;
    125. }
    126. @Operation(
    127. summary = "Get the timetable status and score for a given job ID.")
    128. @ApiResponses(value = {
    129. @ApiResponse(responseCode = "200", description = "The timetable status and the best score so far.",
    130. content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE,
    131. schema = @Schema(implementation = Timetable.class))),
    132. @ApiResponse(responseCode = "404", description = "No timetable found.",
    133. content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE,
    134. schema = @Schema(implementation = ErrorInfo.class))),
    135. @ApiResponse(responseCode = "500", description = "Exception during solving a timetable.",
    136. content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE,
    137. schema = @Schema(implementation = ErrorInfo.class)))
    138. })
    139. @GetMapping(value = "/{jobId}/status", produces = MediaType.APPLICATION_JSON_VALUE)
    140. public Timetable getStatus(
    141. @Parameter(description = "The job ID returned by the POST method.") @PathVariable("jobId") String jobId) {
    142. Timetable timetable = getTimetableAndCheckForExceptions(jobId);
    143. SolverStatus solverStatus = solverManager.getSolverStatus(jobId);
    144. return new Timetable(timetable.getName(), timetable.getScore(), solverStatus);
    145. }
    146. private Timetable getTimetableAndCheckForExceptions(String jobId) {
    147. Job job = jobIdToJob.get(jobId);
    148. if (job == null) {
    149. throw new TimetableSolverException(jobId, HttpStatus.NOT_FOUND, "No timetable found.");
    150. }
    151. if (job.exception != null) {
    152. throw new TimetableSolverException(jobId, job.exception);
    153. }
    154. return job.timetable;
    155. }
    156. @Operation(
    157. summary = "Terminate solving for a given job ID. Returns the best solution of the timetable so far, as it might still be running or not even started.")
    158. @ApiResponses(value = {
    159. @ApiResponse(responseCode = "200", description = "The best solution of the timetable so far.",
    160. content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE,
    161. schema = @Schema(implementation = Timetable.class))),
    162. @ApiResponse(responseCode = "404", description = "No timetable found.",
    163. content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE,
    164. schema = @Schema(implementation = ErrorInfo.class))),
    165. @ApiResponse(responseCode = "500", description = "Exception during solving a timetable.",
    166. content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE,
    167. schema = @Schema(implementation = ErrorInfo.class)))
    168. })
    169. @DeleteMapping(value = "/{jobId}", produces = MediaType.APPLICATION_JSON_VALUE)
    170. public Timetable terminateSolving(
    171. @Parameter(description = "The job ID returned by the POST method.") @PathVariable("jobId") String jobId) {
    172. // TODO: Replace with .terminateEarlyAndWait(... [, timeout]); see https://github.com/TimefoldAI/timefold-solver/issues/77
    173. solverManager.terminateEarly(jobId);
    174. return getTimeTable(jobId);
    175. }
    176. private record Job(Timetable timetable, Throwable exception) {
    177. static Job ofTimetable(Timetable timetable) {
    178. return new Job(timetable, null);
    179. }
    180. static Job ofException(Throwable error) {
    181. return new Job(null, error);
    182. }
    183. }
    184. }

    设置终止时间

    如果没有终止设置或terminationEarly()事件,求解器将永远运行。为避免这种情况,请将求解时间限制为五秒。这足够短,可以避免 HTTP 超时。

    创建src/main/resources/application.properties文件:

    1. # The solver runs only for 5 seconds to avoid a HTTP timeout in this simple implementation.
    2. # It's recommended to run for at least 5 minutes ("5m") otherwise.
    3. timefold.solver.termination.spent-limit=5s

    Timefold Solver 返回在可用终止时间内找到的最佳解决方案。由于NP-hard 问题的性质,最佳解决方案可能不是最优的,尤其是对于较大的数据集。增加终止时间可能会找到更好的解决方案。

    以上只是一些关键代码,所有代码请参见下面代码仓库

    代码仓库

    3.测试

    启动Spring Boot应用程序

    时间表生成

    访问http://127.0.0.1:8080/,点击solve

    111

    4.引用

  • 相关阅读:
    【华为OD题库-027】代码编辑器-java
    大热电视剧《好事成双》里的IT故事:用户数据泄露事件引出的美女黑客
    ZYNQ7000交叉编译MPlayer到开发板播放视频
    (SpringBoot)第八章:SpringMVC程序开发
    c#学习系列相关之多线程(三)----invoke和begininvoke
    图论08-图的建模-状态的表达与理解 - 倒水问题为例
    CSS画一条虚线,并且灵活设置虚线的宽度和虚线之间的间隔和虚线的颜色
    acwing算法提高之数据结构--树状数组
    Flutter 调用百度地图APP实现位置搜索、路线规划
    如何在C程序中使用libcurl库下载网页内容
  • 原文地址:https://blog.csdn.net/dot_life/article/details/139668653