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-quickstarts | github_2023 | java | 353 | TimefoldAI | triceo | @@ -38,13 +38,12 @@ public class DemoDataGenerator {
// Audience tags
private static final List<String> AUDIENCE_TAGS = List.of("Programmers", "Analysts", "Managers");
// Content tags
- private static final List<String> CONTENT_TAGS =
- List.of("Timefold", "Constraints", "Metaheuristics", "Kubernetes");
- private final Random random = new Random(0);
+ private static final List<String> CONTENT_TAGS = List.of("Timefold", "Constraints", "Metaheuristics", "Kubernetes");
+ private static final Random random = new Random(0);
- private static final Set<TalkType> TALK_TYPES = Set.of(
+ private static final Set<TalkType> TALK_TYPES = new LinkedHashSet<>(Set.of( | Not very nice, is it? I recommend adding a new static method `toSet(T... items)`, which would do something like this under the hood:
var set = new LinkedHashSet<T>(items.length);
set.addAll(items);
return Collections.unmodifiableSet(set);
That way, you get reproducibility without sacrificing the readability of your code. |
timefold-quickstarts | github_2023 | java | 344 | TimefoldAI | triceo | @@ -0,0 +1,611 @@
+package org.acme.conferencescheduling.domain;
+
+import static java.util.Collections.emptyList;
+import static java.util.Collections.emptySet;
+
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+
+import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
+import ai.timefold.solver.core.api.domain.entity.PlanningPin;
+import ai.timefold.solver.core.api.domain.lookup.PlanningId;
+import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider;
+import ai.timefold.solver.core.api.domain.variable.PlanningVariable;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+
+@PlanningEntity
+public class Talk {
+
+ @PlanningId
+ private String code;
+ private String title;
+ private TalkType talkType;
+ private List<Speaker> speakers;
+ private Set<String> themeTrackTags;
+ private Set<String> sectorTags;
+ private Set<String> audienceTypes;
+ private int audienceLevel;
+ private Set<String> contentTags;
+ private String language;
+ private Set<String> requiredTimeslotTags;
+ private Set<String> preferredTimeslotTags;
+ private Set<String> prohibitedTimeslotTags;
+ private Set<String> undesiredTimeslotTags;
+ private Set<String> requiredRoomTags;
+ private Set<String> preferredRoomTags;
+ private Set<String> prohibitedRoomTags;
+ private Set<String> undesiredRoomTags;
+ private Set<String> mutuallyExclusiveTalksTags;
+ private Set<Talk> prerequisiteTalks;
+ private int favoriteCount;
+ private int crowdControlRisk;
+ private Timeslot publishedTimeslot;
+ private Room publishedRoom;
+
+ @PlanningPin
+ private boolean pinnedByUser = false;
+
+ @PlanningVariable
+ private Timeslot timeslot;
+
+ @PlanningVariable
+ private Room room;
+
+ public Talk() {
+ }
+
+ public Talk(String code, Timeslot timeslot, Room room) {
+ this(code, timeslot, room, emptyList());
+ }
+
+ public Talk(String code, Timeslot timeslot, Room room, List<Speaker> speakers) {
+ this(code, null, null, speakers, emptySet(), emptySet(), emptySet(), 0, emptySet(), null, 0, 0);
+ this.timeslot = timeslot;
+ this.room = room;
+ }
+
+ public Talk(String code, String title, TalkType talkType, List<Speaker> speakers, Set<String> themeTrackTags,
+ Set<String> sectorTags, Set<String> audienceTypes, int audienceLevel, Set<String> contentTags,
+ String language, int favoriteCount, int crowdControlRisk) {
+ this(code, title, talkType, speakers, themeTrackTags, sectorTags, audienceTypes, audienceLevel, contentTags,
+ language, emptySet(), emptySet(), emptySet(), emptySet(), emptySet(), emptySet(), emptySet(),
+ emptySet(), emptySet(), emptySet(), favoriteCount, crowdControlRisk, null,
+ null);
+ }
+
+ public Talk(String code, String title, TalkType talkType, List<Speaker> speakers, Set<String> themeTrackTags,
+ Set<String> sectorTags, Set<String> audienceTypes, int audienceLevel, Set<String> contentTags,
+ String language, Set<String> requiredTimeslotTags, Set<String> preferredTimeslotTags,
+ Set<String> prohibitedTimeslotTags, Set<String> undesiredTimeslotTags, Set<String> requiredRoomTags,
+ Set<String> preferredRoomTags, Set<String> prohibitedRoomTags, Set<String> undesiredRoomTags,
+ Set<String> mutuallyExclusiveTalksTags, Set<Talk> prerequisiteTalks, int favoriteCount, int crowdControlRisk,
+ Timeslot publishedTimeslot, Room publishedRoom) {
+ this.code = code;
+ this.title = title;
+ this.talkType = talkType;
+ this.speakers = speakers;
+ this.themeTrackTags = themeTrackTags;
+ this.sectorTags = sectorTags;
+ this.audienceTypes = audienceTypes;
+ this.audienceLevel = audienceLevel;
+ this.contentTags = contentTags;
+ this.language = language;
+ this.requiredTimeslotTags = requiredTimeslotTags;
+ this.preferredTimeslotTags = preferredTimeslotTags;
+ this.prohibitedTimeslotTags = prohibitedTimeslotTags;
+ this.undesiredTimeslotTags = undesiredTimeslotTags;
+ this.requiredRoomTags = requiredRoomTags;
+ this.preferredRoomTags = preferredRoomTags;
+ this.prohibitedRoomTags = prohibitedRoomTags;
+ this.undesiredRoomTags = undesiredRoomTags;
+ this.mutuallyExclusiveTalksTags = mutuallyExclusiveTalksTags;
+ this.prerequisiteTalks = prerequisiteTalks;
+ this.favoriteCount = favoriteCount;
+ this.crowdControlRisk = crowdControlRisk;
+ this.publishedTimeslot = publishedTimeslot;
+ this.publishedRoom = publishedRoom;
+ }
+
+ @ValueRangeProvider
+ public Set<Timeslot> getTimeslotRange() {
+ return talkType.getCompatibleTimeslots();
+ }
+
+ @ValueRangeProvider
+ public Set<Room> getRoomRange() {
+ return talkType.getCompatibleRooms();
+ }
+
+ public boolean hasSpeaker(Speaker speaker) {
+ return speakers.contains(speaker);
+ }
+
+ public int overlappingThemeTrackCount(Talk other) {
+ return overlappingCount(themeTrackTags, other.themeTrackTags);
+ }
+
+ private static <T> int overlappingCount(Set<T> left, Set<T> right) {
+ int leftSize = left.size();
+ if (leftSize == 0) {
+ return 0;
+ }
+ int rightSize = right.size();
+ if (rightSize == 0) {
+ return 0;
+ }
+ Set<T> smaller = leftSize < rightSize ? left : right;
+ Set<T> other = smaller == left ? right : left; | This is an optimization which, although useful, probably doesn't need to be here.
This is a quickstart - let's not overcomplicate it.
(The original example was suffering from it a bit.) |
timefold-quickstarts | github_2023 | java | 344 | TimefoldAI | triceo | @@ -0,0 +1,208 @@
+package org.acme.conferencescheduling.rest;
+
+import java.util.Collection;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Consumes;
+import jakarta.ws.rs.DELETE;
+import jakarta.ws.rs.GET;
+import jakarta.ws.rs.POST;
+import jakarta.ws.rs.PUT;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.PathParam;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.QueryParam;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+
+import ai.timefold.solver.core.api.score.analysis.ScoreAnalysis;
+import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore;
+import ai.timefold.solver.core.api.solver.ScoreAnalysisFetchPolicy;
+import ai.timefold.solver.core.api.solver.SolutionManager;
+import ai.timefold.solver.core.api.solver.SolverManager;
+import ai.timefold.solver.core.api.solver.SolverStatus;
+
+import org.acme.conferencescheduling.domain.ConferenceSchedule;
+import org.acme.conferencescheduling.rest.exception.ConferenceScheduleSolverException;
+import org.acme.conferencescheduling.rest.exception.ErrorInfo;
+import org.eclipse.microprofile.openapi.annotations.Operation;
+import org.eclipse.microprofile.openapi.annotations.enums.SchemaType;
+import org.eclipse.microprofile.openapi.annotations.media.Content;
+import org.eclipse.microprofile.openapi.annotations.media.Schema;
+import org.eclipse.microprofile.openapi.annotations.parameters.Parameter;
+import org.eclipse.microprofile.openapi.annotations.responses.APIResponse;
+import org.eclipse.microprofile.openapi.annotations.responses.APIResponses;
+import org.eclipse.microprofile.openapi.annotations.tags.Tag;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Tag(name = "Conference Scheduling",
+ description = "Conference Scheduling service assigning rooms and timeslots for conference talks.")
+@Path("schedules")
+public class ConferenceSchedulingResource {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(ConferenceSchedulingResource.class);
+
+ private final SolverManager<ConferenceSchedule, String> solverManager;
+ private final SolutionManager<ConferenceSchedule, HardSoftScore> solutionManager;
+
+ // TODO: Without any "time to live", the map may eventually grow out of memory. | Do we intend to do anything about this TODO? |
timefold-quickstarts | github_2023 | java | 344 | TimefoldAI | triceo | @@ -0,0 +1,192 @@
+package org.acme.conferencescheduling.rest;
+
+import static java.util.Collections.emptySet;
+import static java.util.stream.Collectors.toSet;
+
+import java.time.LocalDateTime;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Optional;
+import java.util.Random;
+import java.util.Set;
+
+import jakarta.enterprise.context.ApplicationScoped;
+
+import org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration;
+import org.acme.conferencescheduling.domain.ConferenceSchedule;
+import org.acme.conferencescheduling.domain.Room;
+import org.acme.conferencescheduling.domain.Speaker;
+import org.acme.conferencescheduling.domain.Talk;
+import org.acme.conferencescheduling.domain.TalkType;
+import org.acme.conferencescheduling.domain.Timeslot;
+
+@ApplicationScoped
+public class DemoDataGenerator {
+
+ // Talk types
+ private static final String BREAKOUT_TALK_TAG = "Breakout";
+ private static final String LAB_TALK_TAG = "Lab";
+ // Tags
+ private static final String AFTER_LUNCH_TAG = "After lunch";
+ private static final String RECORDED_TAG = "Recorded";
+ private static final String LARGE_TAG = "Large";
+ // Theme tags
+ private static final List<String> THEME_TAGS = List.of("Theme1", "Theme2", "Theme3");
+ // Sector tags
+ private static final List<String> SECTOR_TAGS = List.of("Sector1", "Sector2", "Sector3");
+ // Audience tags
+ private static final List<String> AUDIENCE_TAGS = List.of("Audience1", "Audience2", "Audience3");
+ // Content tags
+ private static final List<String> CONTENT_TAGS = List.of("Content1", "Content2", "Content3", "Content4", "Content5"); | Can we get some nice names for these tags? Themes could be "Optimization", "AI", ... Sectors could be colors. ("Green sector", "Blue sector", ...) Etc. |
timefold-quickstarts | github_2023 | java | 344 | TimefoldAI | triceo | @@ -0,0 +1,192 @@
+package org.acme.conferencescheduling.rest;
+
+import static java.util.Collections.emptySet;
+import static java.util.stream.Collectors.toSet;
+
+import java.time.LocalDateTime;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Optional;
+import java.util.Random;
+import java.util.Set;
+
+import jakarta.enterprise.context.ApplicationScoped;
+
+import org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration;
+import org.acme.conferencescheduling.domain.ConferenceSchedule;
+import org.acme.conferencescheduling.domain.Room;
+import org.acme.conferencescheduling.domain.Speaker;
+import org.acme.conferencescheduling.domain.Talk;
+import org.acme.conferencescheduling.domain.TalkType;
+import org.acme.conferencescheduling.domain.Timeslot;
+
+@ApplicationScoped
+public class DemoDataGenerator {
+
+ // Talk types
+ private static final String BREAKOUT_TALK_TAG = "Breakout";
+ private static final String LAB_TALK_TAG = "Lab";
+ // Tags
+ private static final String AFTER_LUNCH_TAG = "After lunch";
+ private static final String RECORDED_TAG = "Recorded";
+ private static final String LARGE_TAG = "Large";
+ // Theme tags
+ private static final List<String> THEME_TAGS = List.of("Theme1", "Theme2", "Theme3");
+ // Sector tags
+ private static final List<String> SECTOR_TAGS = List.of("Sector1", "Sector2", "Sector3");
+ // Audience tags
+ private static final List<String> AUDIENCE_TAGS = List.of("Audience1", "Audience2", "Audience3");
+ // Content tags
+ private static final List<String> CONTENT_TAGS = List.of("Content1", "Content2", "Content3", "Content4", "Content5");
+ private final Random random = new Random(); | Let's make this predictable. Give it a fixed seed. |
timefold-quickstarts | github_2023 | java | 344 | TimefoldAI | triceo | @@ -0,0 +1,537 @@
+package org.acme.conferencescheduling.solver;
+
+import static ai.timefold.solver.core.api.score.stream.ConstraintCollectors.compose;
+import static ai.timefold.solver.core.api.score.stream.ConstraintCollectors.countBi;
+import static ai.timefold.solver.core.api.score.stream.ConstraintCollectors.max;
+import static ai.timefold.solver.core.api.score.stream.ConstraintCollectors.min;
+import static ai.timefold.solver.core.api.score.stream.Joiners.equal;
+import static ai.timefold.solver.core.api.score.stream.Joiners.filtering;
+import static ai.timefold.solver.core.api.score.stream.Joiners.greaterThan;
+import static ai.timefold.solver.core.api.score.stream.Joiners.lessThan;
+import static ai.timefold.solver.core.api.score.stream.Joiners.overlapping;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.AUDIENCE_LEVEL_DIVERSITY;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.AUDIENCE_TYPE_DIVERSITY;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.AUDIENCE_TYPE_THEME_TRACK_CONFLICT;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.CONSECUTIVE_TALKS_PAUSE;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.CONTENT_AUDIENCE_LEVEL_FLOW_VIOLATION;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.CONTENT_CONFLICT;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.CROWD_CONTROL;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.LANGUAGE_DIVERSITY;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.POPULAR_TALKS;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.PUBLISHED_ROOM;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.PUBLISHED_TIMESLOT;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.ROOM_CONFLICT;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.ROOM_UNAVAILABLE_TIMESLOT;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.SAME_DAY_TALKS;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.SECTOR_CONFLICT;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.SPEAKER_CONFLICT;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.SPEAKER_MAKESPAN;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.SPEAKER_PREFERRED_ROOM_TAGS;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.SPEAKER_PREFERRED_TIMESLOT_TAGS;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.SPEAKER_PROHIBITED_ROOM_TAGS;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.SPEAKER_PROHIBITED_TIMESLOT_TAGS;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.SPEAKER_REQUIRED_ROOM_TAGS;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.SPEAKER_REQUIRED_TIMESLOT_TAGS;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.SPEAKER_UNAVAILABLE_TIMESLOT;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.SPEAKER_UNDESIRED_ROOM_TAGS;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.SPEAKER_UNDESIRED_TIMESLOT_TAGS;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.TALK_MUTUALLY_EXCLUSIVE_TALKS_TAGS;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.TALK_PREFERRED_ROOM_TAGS;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.TALK_PREFERRED_TIMESLOT_TAGS;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.TALK_PREREQUISITE_TALKS;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.TALK_PROHIBITED_ROOM_TAGS;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.TALK_PROHIBITED_TIMESLOT_TAGS;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.TALK_REQUIRED_ROOM_TAGS;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.TALK_REQUIRED_TIMESLOT_TAGS;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.TALK_UNDESIRED_ROOM_TAGS;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.TALK_UNDESIRED_TIMESLOT_TAGS;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.THEME_TRACK_CONFLICT;
+import static org.acme.conferencescheduling.domain.ConferenceConstraintConfiguration.THEME_TRACK_ROOM_STABILITY;
+
+import java.time.LocalDate;
+import java.time.temporal.ChronoUnit;
+import java.util.Collections;
+import java.util.Objects;
+
+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.conferencescheduling.domain.ConferenceConstraintConfiguration;
+import org.acme.conferencescheduling.domain.Speaker;
+import org.acme.conferencescheduling.domain.Talk;
+import org.acme.conferencescheduling.solver.justifications.SpeakerJustification;
+import org.acme.conferencescheduling.solver.justifications.TalkJustification;
+import org.acme.conferencescheduling.solver.justifications.TalkSpeakerJustification;
+import org.acme.conferencescheduling.solver.justifications.TwoTalkJustification;
+import org.acme.conferencescheduling.solver.justifications.TwoTalkSpeakerJustification;
+
+/**
+ * Provides the constraints for the conference scheduling problem.
+ * <p>
+ * Makes heavy use of CS expand() functionality to cache computation results,
+ * except in cases where doing so less is efficient than recomputing the result.
+ * That is the case in filtering joiners.
+ * In this case, it is better to reduce the size of the joins even at the expense of duplicating some calculations.
+ * In other words, time saved by caching those calculations is far outweighed by the time spent in unrestricted joins.
+ */
+public class ConferenceSchedulingConstraintProvider implements ConstraintProvider { | Although I understand that doing a different justification for each of these constraints would have been crazy, maybe the current granularity is lower than it ought to be?
At least `TalkTagJustification` would IMO be a good addition. |
timefold-quickstarts | github_2023 | java | 307 | TimefoldAI | triceo | @@ -55,7 +55,7 @@ public Integer getPatientPreferredMaximumRoomCapacity() {
}
@JsonIgnore
- public Specialism getSpecialism() {
+ public String getSpecialism() { | I'm not sure how I feel about this. Two aspects:
- `Specialism` is a word I've never seen used anywhere else other than this quickstart. What is it supposed to mean, and can we find a better one?
- To me, `String` is not a data type. It carries no meaning, you cannot effectively use it in constraints. I consider this to be an anti-pattern, and I'd rather not teach our users to do this. I prefer the original approach, where this had a specific type for itself.
This has been a point where Geoffrey and I've disagreed over the years. If the `specialism` is never ever used inside the constraints, or rather used through `BedSpecialism` et al., then I can live with this. But I still don't like the name. |
timefold-quickstarts | github_2023 | java | 307 | TimefoldAI | triceo | @@ -13,19 +15,20 @@ public class Department {
@PlanningId
private String id;
-
+ private Map<String, Integer> specialismsToPriority;
private String name;
private Integer minimumAge = null;
private Integer maximumAge = null;
-
private List<Room> rooms;
public Department() {
+ this.specialismsToPriority = new HashMap<>();
}
public Department(String id, String name) {
this.id = id;
this.name = name;
+ this.specialismsToPriority = new HashMap<>(); | Careful about `HashMap`s - if you ever iterate over them, they will introduce non-determinism in your solver. However, if you ever only `get(...)` on them, it's fine. |
timefold-quickstarts | github_2023 | java | 307 | TimefoldAI | triceo | @@ -8,14 +8,14 @@ public class DepartmentSpecialism {
private String id;
private Department department;
- private Specialism specialism;
+ private String specialism;
private int priority; // AKA choice
public DepartmentSpecialism() {
}
- public DepartmentSpecialism(String id, Department department, Specialism specialism, int priority) {
+ public DepartmentSpecialism(String id, Department department, String specialism, int priority) { | I don't understand. So we do have `DepartmentSpecialism`, but for some reason, `specialism` is still a `String` and we use it as `String` everywhere? |
timefold-quickstarts | github_2023 | java | 307 | TimefoldAI | triceo | @@ -19,8 +19,8 @@ public class Patient {
private int age;
private Integer preferredMaximumRoomCapacity;
- private List<Equipment> requiredEquipments;
- private List<Equipment> preferredEquipments;
+ private List<String> requiredEquipments; | Same concerns on `Equipment` as on `Specialism`. |
timefold-quickstarts | github_2023 | others | 307 | TimefoldAI | triceo | @@ -0,0 +1,898 @@
+ARTICLE BENCHMARK DATA SET | Why is this file here, and should it be here?
No other quickstart carries its own data files. |
timefold-quickstarts | github_2023 | java | 307 | TimefoldAI | triceo | @@ -0,0 +1,133 @@
+package org.acme.bedallocation.domain;
+
+import java.util.List;
+
+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.solution.ProblemFactCollectionProperty;
+import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider;
+import ai.timefold.solver.core.api.score.buildin.hardmediumsoft.HardMediumSoftScore;
+import ai.timefold.solver.core.api.solver.SolverStatus;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+
+@PlanningSolution
+public class Schedule {
+
+ private List<Department> departments;
+
+ @PlanningEntityCollectionProperty
+ private List<BedDesignation> bedDesignations;
+
+ @PlanningScore
+ private HardMediumSoftScore score;
+
+ private SolverStatus solverStatus;
+
+ // No-arg constructor required for Timefold
+ public Schedule() {
+ }
+
+ public Schedule(HardMediumSoftScore score, SolverStatus solverStatus) {
+ this.score = score;
+ this.solverStatus = solverStatus;
+ }
+
+ // ************************************************************************
+ // Getters and setters
+ // ************************************************************************
+
+ @JsonIgnore
+ @ProblemFactCollectionProperty
+ public List<String> getSpecialisms() {
+ return this.departments.stream().flatMap(d -> d.getSpecialismsToPriority().keySet().stream()).distinct().toList();
+ } | Is this ever used anywhere? I don't see it used in the constraints and if it's not in the constraints, it doesn't need to exist. |
timefold-quickstarts | github_2023 | java | 307 | TimefoldAI | triceo | @@ -0,0 +1,44 @@
+package org.acme.bedallocation.domain;
+
+import com.fasterxml.jackson.annotation.JsonIdentityInfo;
+import com.fasterxml.jackson.annotation.ObjectIdGenerators;
+
+import ai.timefold.solver.core.api.domain.lookup.PlanningId;
+
+@JsonIdentityInfo(scope = Specialism.class, generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
+public class Specialism { | If `Specialism` is now a `String`, why does this exist? |
timefold-quickstarts | github_2023 | java | 307 | TimefoldAI | triceo | @@ -0,0 +1,133 @@
+package org.acme.bedallocation.domain;
+
+import java.util.List;
+
+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.solution.ProblemFactCollectionProperty;
+import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider;
+import ai.timefold.solver.core.api.score.buildin.hardmediumsoft.HardMediumSoftScore;
+import ai.timefold.solver.core.api.solver.SolverStatus;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+
+@PlanningSolution
+public class Schedule { | I'd prefer if we called this `BedPlan` or something like that.
`Schedule` says nothing, and it makes looking up this class among other quickstarts needlessly difficult. |
timefold-quickstarts | github_2023 | java | 307 | TimefoldAI | triceo | @@ -52,7 +52,7 @@ public class DemoDataGenerator {
private final Random random = new Random(0);
/**
- * The dataset was generated based on the probability distributions found in the test dataset file overconstrained01.txt.
+ * The dataset was generated based on the probability distributions found in the test dataset file.
* However, the number of patients was reduced to 40 to simplify the quickstart process.
*/ | Maybe this entire comment doesn't apply anymore?
It references a file nobody will be able to find. |
timefold-quickstarts | github_2023 | java | 307 | TimefoldAI | triceo | @@ -0,0 +1,126 @@
+package org.acme.bedallocation.domain;
+
+import java.util.List;
+
+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.solution.ProblemFactCollectionProperty;
+import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider;
+import ai.timefold.solver.core.api.score.buildin.hardmediumsoft.HardMediumSoftScore;
+import ai.timefold.solver.core.api.solver.SolverStatus;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+
+@PlanningSolution
+public class Schedule {
+
+ private List<Department> departments;
+
+ @PlanningEntityCollectionProperty
+ private List<BedDesignation> bedDesignations;
+
+ @PlanningScore
+ private HardMediumSoftScore score;
+
+ private SolverStatus solverStatus;
+
+ // No-arg constructor required for Timefold
+ public Schedule() {
+ }
+
+ public Schedule(HardMediumSoftScore score, SolverStatus solverStatus) {
+ this.score = score;
+ this.solverStatus = solverStatus;
+ }
+
+ // ************************************************************************
+ // Getters and setters
+ // ************************************************************************
+ @ProblemFactCollectionProperty
+ public List<Department> getDepartments() {
+ return departments;
+ }
+
+ public void setDepartments(List<Department> departments) {
+ this.departments = departments;
+ }
+
+ @JsonIgnore
+ @ProblemFactCollectionProperty
+ public List<DepartmentSpecialism> getDepartmentSpecialisms() {
+ return departments.stream()
+ .flatMap(d -> d.getSpecialismsToPriority().entrySet().stream()
+ .map(e -> new DepartmentSpecialism("%s-%s".formatted(d.getId(), e.getKey()), d, e.getKey(),
+ e.getValue()))
+ .toList()
+ .stream())
+ .toList(); | I'd be very careful about this pattern.
First of all - this will do some very heavy lifting every time it is called.
But more importantly, this means that every time it is called, the facts will be different instances of objects, and that will eventually lead to inefficiencies, worst case bugs.
Personally, I'd fill these fields when the departments are being set, and not touch them after. |
timefold-quickstarts | github_2023 | javascript | 165 | TimefoldAI | triceo | @@ -101,7 +101,7 @@ function depotPopupContent(depot, color) {
function customerPopupContent(customer) {
const arrival = customer.arrivalTime ? `<h6>Arrival at ${showTimeOnly(customer.arrivalTime)}.</h6>` : '';
return `<h5>${customer.name}</h5>
- <h6>Available from ${showTimeOnly(customer.readyTime)} to ${showTimeOnly(customer.dueTime)}.</h6>
+ <h6>Available from ${showTimeOnly(customer.minStartTime)} to ${showTimeOnly(customer.minStartTime)}.</h6> | ```suggestion
<h6>Available from ${showTimeOnly(customer.minStartTime)} to ${showTimeOnly(customer.maxEndTime)}.</h6>
``` |
timefold-quickstarts | github_2023 | java | 185 | TimefoldAI | triceo | @@ -9,11 +9,7 @@
import ai.timefold.solver.core.api.score.stream.Joiners;
import org.acme.schooltimetabling.domain.Lesson;
-import org.acme.schooltimetabling.solver.justifications.RoomConflictJustification;
-import org.acme.schooltimetabling.solver.justifications.StudentGroupConflictJustification;
-import org.acme.schooltimetabling.solver.justifications.StudentGroupSubjectVarietyJustification;
-import org.acme.schooltimetabling.solver.justifications.TeacherConflictJustification;
-import org.acme.schooltimetabling.solver.justifications.TeacherRoomStabilityJustification;
+import org.acme.schooltimetabling.solver.justifications.*; | Please configure your IDE to not use * imports; that is a Solver convention. Enumerating imports is helpful for the JVM, as it doesn't need to load entire packages, and it is also helpful for the reviewer, to see what exactly is being used. |
timefold-quickstarts | github_2023 | java | 185 | TimefoldAI | triceo | @@ -2,9 +2,13 @@
import ai.timefold.solver.core.api.score.stream.ConstraintJustification;
+import org.acme.schooltimetabling.domain.Lesson;
import org.acme.schooltimetabling.domain.Room;
-public record RoomConflictJustification(Room room, long lessonId1, long lessonId2)
+public record RoomConflictJustification(Room room, Lesson lesson1, Lesson lesson2, String description)
implements ConstraintJustification {
+ public RoomConflictJustification(Room room, Lesson lesson1, Lesson lesson2) {
+ this(room, lesson1, lesson2, String.format("Room '%s' is used for lesson '%s' for student group '%s' and lesson '%s' for student group '%s' at '%s %s'", room, lesson1.getSubject(), lesson1.getStudentGroup(), lesson2.getSubject(), lesson2.getStudentGroup(), lesson1.getTimeslot().getDayOfWeek(), lesson1.getTimeslot().getStartTime())); | As a point of consistency, we use this pattern instead:
```suggestion
this(room, lesson1, lesson2, "Room '%s' is used for lesson '%s' for student group '%s' and lesson '%s' for student group '%s' at '%s %s'".formatted(room, lesson1.getSubject(), lesson1.getStudentGroup(), lesson2.getSubject(), lesson2.getStudentGroup(), lesson1.getTimeslot().getDayOfWeek(), lesson1.getTimeslot().getStartTime()));
``` |
timefold-quickstarts | github_2023 | java | 264 | TimefoldAI | zepfred | @@ -45,22 +42,21 @@ public class VehicleRouteDemoResource {
private static final LocalTime AFTERNOON_WINDOW_END = LocalTime.of(18, 0);
public enum DemoData {
- PHILADELPHIA(0, 60, 6, 2, LocalTime.of(7, 30),
+ PHILADELPHIA(0, 55, 6, LocalTime.of(7, 30), | Was the change to 55 made intentionally? |
timefold-quickstarts | github_2023 | java | 264 | TimefoldAI | zepfred | @@ -108,34 +108,34 @@ public String solve(VehicleRoutePlan problem) {
return jobId;
}
- @Operation(summary = "Request recommendations to the RecommendedFit API for a new customer.")
+ @Operation(summary = "Request recommendations to the RecommendedFit API for a new visit.")
@APIResponses(value = {
@APIResponse(responseCode = "200",
- description = "The list of fits for the given customer.",
+ description = "The list of fits for the given visit.",
content = @Content(mediaType = MediaType.APPLICATION_JSON,
schema = @Schema(implementation = List.class)))})
@POST
@Consumes({MediaType.APPLICATION_JSON})
@Produces(MediaType.APPLICATION_JSON)
@Path("recommendation")
public List<RecommendedFit<VehicleRecommendation, HardSoftLongScore>> recommendedFit(RecommendationRequest request) {
- Customer customer = request.solution().getCustomers().stream()
- .filter(c -> c.getId().equals(request.customerId()))
+ Visit visit = request.solution().getVisits().stream()
+ .filter(c -> c.getId().equals(request.visitId()))
.findFirst()
- .orElseThrow(() -> new IllegalStateException("Customer %s not found".formatted(request.customerId())));
+ .orElseThrow(() -> new IllegalStateException("Visit %s not found".formatted(request.visitId())));
List<RecommendedFit<VehicleRecommendation, HardSoftLongScore>> recommendedFitList = solutionManager
- .recommendFit(request.solution(), customer, c -> new VehicleRecommendation(c.getVehicle().getId(),
- c.getVehicle().getCustomers().indexOf(c)));
+ .recommendFit(request.solution(), visit, c -> new VehicleRecommendation(c.getVehicle().getId(), | ```suggestion
.recommendFit(request.solution(), visit, v -> new VehicleRecommendation(v.getVehicle().getId(),
``` |
timefold-quickstarts | github_2023 | java | 264 | TimefoldAI | zepfred | @@ -108,34 +108,34 @@ public String solve(VehicleRoutePlan problem) {
return jobId;
}
- @Operation(summary = "Request recommendations to the RecommendedFit API for a new customer.")
+ @Operation(summary = "Request recommendations to the RecommendedFit API for a new visit.")
@APIResponses(value = {
@APIResponse(responseCode = "200",
- description = "The list of fits for the given customer.",
+ description = "The list of fits for the given visit.",
content = @Content(mediaType = MediaType.APPLICATION_JSON,
schema = @Schema(implementation = List.class)))})
@POST
@Consumes({MediaType.APPLICATION_JSON})
@Produces(MediaType.APPLICATION_JSON)
@Path("recommendation")
public List<RecommendedFit<VehicleRecommendation, HardSoftLongScore>> recommendedFit(RecommendationRequest request) {
- Customer customer = request.solution().getCustomers().stream()
- .filter(c -> c.getId().equals(request.customerId()))
+ Visit visit = request.solution().getVisits().stream()
+ .filter(c -> c.getId().equals(request.visitId()))
.findFirst()
- .orElseThrow(() -> new IllegalStateException("Customer %s not found".formatted(request.customerId())));
+ .orElseThrow(() -> new IllegalStateException("Visit %s not found".formatted(request.visitId())));
List<RecommendedFit<VehicleRecommendation, HardSoftLongScore>> recommendedFitList = solutionManager
- .recommendFit(request.solution(), customer, c -> new VehicleRecommendation(c.getVehicle().getId(),
- c.getVehicle().getCustomers().indexOf(c)));
+ .recommendFit(request.solution(), visit, c -> new VehicleRecommendation(c.getVehicle().getId(),
+ c.getVehicle().getVisits().indexOf(c))); | ```suggestion
v.getVehicle().getVisits().indexOf(v)));
``` |
timefold-quickstarts | github_2023 | java | 264 | TimefoldAI | zepfred | @@ -149,11 +149,11 @@ public VehicleRoutePlan applyRecommendedFit(ApplyRecommendationRequest request)
.filter(v -> v.getId().equals(vehicleId))
.findFirst()
.orElseThrow(() -> new IllegalStateException("Vehicle %s not found".formatted(vehicleId)));
- Customer customer = request.solution().getCustomers().stream()
- .filter(c -> c.getId().equals(request.customerId()))
+ Visit visit = request.solution().getVisits().stream()
+ .filter(c -> c.getId().equals(request.visitId())) | ```suggestion
.filter(v -> v.getId().equals(request.visitId()))
``` |
timefold-quickstarts | github_2023 | java | 285 | TimefoldAI | Christopher-Chianelli | @@ -46,14 +50,19 @@ class FoodPackagingConstraintProviderTest {
@Test
void dueDateTime() {
+ Line line = new Line("1", "line1", "operator A", DAY_START_TIME); | `dueDateTime` does not use `Line`:
```java
protected Constraint dueDateTime(ConstraintFactory factory) {
return factory.forEach(Job.class)
.filter(job -> job.getEndDateTime() != null && job.getDueDateTime().isBefore(job.getEndDateTime()))
.penalizeLong(HardMediumSoftLongScore.ONE_HARD,
job -> Duration.between(job.getDueDateTime(), job.getEndDateTime()).toMinutes())
.asConstraint("Due date time");
}
```
Why is this change necessary? |
timefold-quickstarts | github_2023 | java | 285 | TimefoldAI | Christopher-Chianelli | @@ -63,14 +72,19 @@ void dueDateTime() {
@Test
void idealEndDateTime() {
+ Line line = new Line("1", "line1", "operator A", DAY_START_TIME); | Ditto:
```java
protected Constraint idealEndDateTime(ConstraintFactory factory) {
return factory.forEach(Job.class)
.filter(job -> job.getEndDateTime() != null && job.getIdealEndDateTime().isBefore(job.getEndDateTime()))
.penalizeLong(HardMediumSoftLongScore.ONE_MEDIUM,
job -> Duration.between(job.getIdealEndDateTime(), job.getEndDateTime()).toMinutes())
.asConstraint("Ideal end date time");
}
``` |
timefold-quickstarts | github_2023 | java | 227 | TimefoldAI | rsynek | @@ -22,6 +22,40 @@ public class VehicleRoutePlanResourceTest {
@Test
public void solveDemoDataUntilFeasible() {
+ VehicleRoutePlan solution = solveDemoData();
+ assertTrue(solution.getScore().isFeasible());
+ }
+
+ @Test
+ void analyze() { | Maybe split into two test methods, one of them does "shallow fetch". |
timefold-quickstarts | github_2023 | java | 227 | TimefoldAI | rsynek | @@ -22,6 +22,40 @@ public class VehicleRoutePlanResourceTest {
@Test
public void solveDemoDataUntilFeasible() {
+ VehicleRoutePlan solution = solveDemoData();
+ assertTrue(solution.getScore().isFeasible());
+ }
+
+ @Test
+ void analyze() {
+ VehicleRoutePlan solution = solveDemoData();
+ assertTrue(solution.getScore().isFeasible());
+
+ String analysis = given()
+ .contentType(ContentType.JSON)
+ .body(solution)
+ .expect().contentType(ContentType.JSON)
+ .when()
+ .put("/route-plans/analyze")
+ .then()
+ .extract()
+ .asString();
+ assertNotNull(analysis); // Too long to validate in its entirety. | Can we at least check the difference between shallow and full result? |
timefold-quickstarts | github_2023 | javascript | 227 | TimefoldAI | rsynek | @@ -336,6 +337,116 @@ function renderTimelines(routePlan) {
}
}
+function analyze() {
+ new bootstrap.Modal("#scoreAnalysisModal").show()
+ const scoreAnalysisModalContent = $("#scoreAnalysisModalContent");
+ scoreAnalysisModalContent.children().remove();
+ if (loadedRoutePlan.score == null || loadedRoutePlan.score.indexOf('init') != -1) {
+ scoreAnalysisModalContent.text("Score not ready for analysis, try to run the solver first or wait until it advances.");
+ } else {
+ $.put("/route-plans/analyze", JSON.stringify(loadedRoutePlan), function (scoreAnalysis) { | Consistency: we should picked either the `function (...) { }` or `(...) => { }` syntax, but not mix both of them. |
timefold-quickstarts | github_2023 | javascript | 227 | TimefoldAI | rsynek | @@ -336,6 +337,116 @@ function renderTimelines(routePlan) {
}
}
+function analyze() {
+ new bootstrap.Modal("#scoreAnalysisModal").show()
+ const scoreAnalysisModalContent = $("#scoreAnalysisModalContent");
+ scoreAnalysisModalContent.children().remove();
+ if (loadedRoutePlan.score == null || loadedRoutePlan.score.indexOf('init') != -1) {
+ scoreAnalysisModalContent.text("Score not ready for analysis, try to run the solver first or wait until it advances.");
+ } else {
+ $.put("/route-plans/analyze", JSON.stringify(loadedRoutePlan), function (scoreAnalysis) {
+ let constraints = scoreAnalysis.constraints;
+ constraints.sort((a, b) => {
+ let aComponents = getScoreComponents(a.score), bComponents = getScoreComponents(b.score);
+ if (aComponents.hard < 0 && bComponents.hard > 0) return -1;
+ if (aComponents.hard > 0 && bComponents.soft < 0) return 1;
+ if (Math.abs(aComponents.hard) > Math.abs(bComponents.hard)) {
+ return -1;
+ } else {
+ if (aComponents.medium < 0 && bComponents.medium > 0) return -1;
+ if (aComponents.medium > 0 && bComponents.medium < 0) return 1;
+ if (Math.abs(aComponents.medium) > Math.abs(bComponents.medium)) {
+ return -1;
+ } else {
+ if (aComponents.soft < 0 && bComponents.soft > 0) return -1;
+ if (aComponents.soft > 0 && bComponents.soft < 0) return 1;
+
+ return Math.abs(bComponents.soft) - Math.abs(aComponents.soft);
+ }
+ }
+ });
+ constraints.map((e) => {
+ let components = getScoreComponents(e.weight);
+ e.type = components.hard != 0 ? 'hard' : (components.medium != 0 ? 'medium' : 'soft');
+ e.weight = components[e.type];
+ let scores = getScoreComponents(e.score);
+ e.implicitScore = scores.hard != 0 ? scores.hard : (scores.medium != 0 ? scores.medium : scores.soft);
+ });
+ scoreAnalysis.constraints = constraints;
+
+ scoreAnalysisModalContent.children().remove();
+ scoreAnalysisModalContent.text("");
+
+ const analysisTable = $(`<table class="table"/>`).css({textAlign: 'center'});
+ const analysisTHead = $(`<thead/>`).append($(`<tr/>`)
+ .append($(`<th></th>`))
+ .append($(`<th>Constraint</th>`).css({textAlign: 'left'}))
+ .append($(`<th>Type</th>`))
+ .append($(`<th># Matches</th>`))
+ .append($(`<th>Weight</th>`))
+ .append($(`<th>Score</th>`))
+ .append($(`<th></th>`)));
+ analysisTable.append(analysisTHead);
+ const analysisTBody = $(`<tbody/>`)
+ $.each(scoreAnalysis.constraints, (index, constraintAnalysis) => {
+ let icon = constraintAnalysis.type == "hard" && constraintAnalysis.implicitScore < 0 ? '<span class="fas fa-exclamation-triangle" style="color: red"></span>' : '';
+ if (!icon) icon = constraintAnalysis.weight < 0 && constraintAnalysis.matches.length == 0 ? '<span class="fas fa-check-circle" style="color: green"></span>' : '';
+
+ let row = $(`<tr/>`);
+ row.append($(`<td/>`).html(icon))
+ .append($(`<td/>`).text(constraintAnalysis.name).css({textAlign: 'left'}))
+ .append($(`<td/>`).text(constraintAnalysis.type))
+ .append($(`<td/>`).html(`<b>${constraintAnalysis.matches.length}</b>`))
+ .append($(`<td/>`).text(constraintAnalysis.weight))
+ .append($(`<td/>`).text(constraintAnalysis.implicitScore));
+
+ analysisTBody.append(row);
+
+ if (constraintAnalysis.matches.length > 0) {
+ let matchesRow = $(`<tr/>`).addClass("collapse").attr("id", "row" + index + "Collapse");
+ let matchesListGroup = $(`<ul/>`).addClass('list-group').addClass('list-group-flush').css({textAlign: 'left'});
+
+ $.each(constraintAnalysis.matches, (index2, match) => {
+ matchesListGroup.append($(`<li/>`).addClass('list-group-item').addClass('list-group-item-light').text(match.justification.description));
+ });
+
+ matchesRow.append($(`<td/>`));
+ matchesRow.append($(`<td/>`).attr('colspan', '6').append(matchesListGroup));
+ analysisTBody.append(matchesRow);
+
+ row.append($(`<td/>`).append($(`<a/>`).attr("data-toggle", "collapse").attr('href', "#row" + index + "Collapse").append($(`<span/>`).addClass('fas').addClass('fa-arrow-down')).click(e => {
+ matchesRow.collapse('toggle');
+ let target = $(e.target);
+ if (target.hasClass('fa-arrow-down')) {
+ target.removeClass('fa-arrow-down').addClass('fa-arrow-up');
+ } else {
+ target.removeClass('fa-arrow-up').addClass('fa-arrow-down');
+ }
+ }))); | This might possibly go into a separate function. |
timefold-quickstarts | github_2023 | javascript | 227 | TimefoldAI | rsynek | @@ -336,6 +337,116 @@ function renderTimelines(routePlan) {
}
}
+function analyze() { | Please consider breaking this long function into shorter ones to increase the readability. |
timefold-quickstarts | github_2023 | java | 227 | TimefoldAI | rsynek | @@ -179,6 +183,21 @@ public VehicleRoutePlan terminateSolving(
return getRoutePlan(jobId);
}
+ @Operation(summary = "Submit a route plan to analyze its score.")
+ @APIResponses(value = {
+ @APIResponse(responseCode = "202", | This is a synchronous call that returns immediately; wouldn't be returning 200 more appropriate?
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/202 |
timefold-quickstarts | github_2023 | java | 227 | TimefoldAI | rsynek | @@ -0,0 +1,15 @@
+package org.acme.vehiclerouting.solver.justifications;
+
+import ai.timefold.solver.core.api.score.stream.ConstraintJustification;
+
+import org.acme.vehiclerouting.domain.Vehicle;
+
+import java.time.Duration;
+
+public record MinimizeTravelTimeJustification(Vehicle vehicle, String description) implements ConstraintJustification {
+
+ public MinimizeTravelTimeJustification(Vehicle vehicle) {
+ this(vehicle, "Vehicle '%s' total travel time is '%s'." | This is how the result looks like:
"Vehicle '1' total travel time is 'PT5H44M7S'."
While the ISO duration format is nice in API, it's not so user-friendly in the UI.
Option A) format to show hours and minutes
Option B) make the record return only the vehicle (or even vehicleId) and the travel time duration; format on the client
I incline towards B) as it gives the client freedom on how to display or interpret the data. |
timefold-quickstarts | github_2023 | java | 227 | TimefoldAI | rsynek | @@ -0,0 +1,15 @@
+package org.acme.vehiclerouting.solver.justifications;
+
+import ai.timefold.solver.core.api.score.stream.ConstraintJustification;
+
+import java.time.Duration;
+
+public record MinimizeTravelTimeJustification(String vehicleName, long totalDrivingTimeSeconds,
+ String description) implements ConstraintJustification {
+
+ public MinimizeTravelTimeJustification(String vehicleName, long totalDrivingTimeSeconds) {
+ this(vehicleName, totalDrivingTimeSeconds, "Vehicle '%s' total travel time is %d hours %d minutes."
+ .formatted(vehicleName, Duration.ofSeconds(totalDrivingTimeSeconds).toHours(),
+ Duration.ofSeconds(totalDrivingTimeSeconds).toMinutesPart())); | Nitpick: if `toSecondsPart() > 0` add one minute. |
timefold-quickstarts | github_2023 | java | 227 | TimefoldAI | triceo | @@ -0,0 +1,11 @@
+package org.acme.vehiclerouting.domain.jackson;
+
+import ai.timefold.solver.core.api.score.analysis.ScoreAnalysis;
+import com.fasterxml.jackson.databind.module.SimpleModule;
+
+public class VRPScoreAnalysisJacksonModule extends SimpleModule { | AFAIK modules can be registered as a resource, so jackson will read them from there.
I suggest we do it like this, to show people the proper way.
See `META-INF/resources` in `timefold-solver/persistence`. |
timefold-quickstarts | github_2023 | others | 226 | TimefoldAI | zepfred | @@ -101,12 +105,13 @@ class TimeTableConstraintProvider : ConstraintProvider {
lesson1.timeslot?.endTime,
lesson2.timeslot?.startTime
)
- !between.isNegative && between.compareTo(Duration.ofMinutes(30)) <= 0
+ !between.isNegative && between <= Duration.ofMinutes(30) | Nice! |
timefold-quickstarts | github_2023 | others | 223 | TimefoldAI | rsynek | @@ -143,6 +143,26 @@ <h5>
</div>
</div>
</div>
+ <div class="col mb-4">
+ <div class="card">
+ <div class="card-header">
+ <h5>
+ <i class="fas fa-truck"></i>
+ Vehicle routing with capacity and time windows
+ </h5>
+ </div>
+ <img src="screenshot/quarkus-vehicle-routing-screenshot.png" class="card-img-top mt-3" alt="Screenshot"/>
+ <div class="card-body">
+ <p class="card-text">
+ Find the most efficient routes for field service technicians to visits with time windows. | As we no longer target a specific sub-case, I would keep the description general:
"field service technicians" -> "vehicles"
and perhaps also:
"visits" -> "customers"
as it matches the domain class name. |
timefold-quickstarts | github_2023 | others | 223 | TimefoldAI | rsynek | @@ -0,0 +1,115 @@
+= Vehicle Routing with time windows and capacity planning (Java, Quarkus, Maven)
+
+Find the most efficient routes for a fleet of vehicles.
+
+image::../../build/quickstarts-showcase/src/main/resources/META-INF/resources/screenshot/quarkus-vehicle-routing-screenshot.png[] | The image does not seem to exists (there are two separate screenshots for each VRP sub-case). Let's take a new one and then replace the existing two. |
timefold-quickstarts | github_2023 | java | 223 | TimefoldAI | rsynek | @@ -0,0 +1,151 @@
+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.solution.ProblemFactCollectionProperty;
+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.DistanceCalculator;
+import org.acme.vehiclerouting.domain.geo.HaversineDistanceCalculator;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+@JsonInclude(JsonInclude.Include.NON_NULL)
+@PlanningSolution
+public class VehicleRoutePlan {
+
+ private String name;
+
+ private Location southWestCorner;
+ private Location northEastCorner;
+
+ private LocalDateTime startDateTime;
+
+ private LocalDateTime endDateTime;
+
+ @ProblemFactCollectionProperty
+ private List<Depot> depots;
+
+ @PlanningEntityCollectionProperty
+ private List<Vehicle> vehicles;
+
+ @PlanningEntityCollectionProperty
+ @ValueRangeProvider
+ private List<Customer> customers;
+
+ @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;
+ }
+
+ @JsonCreator
+ public VehicleRoutePlan(@JsonProperty("name") String name,
+ @JsonProperty("southWestCorner") Location southWestCorner,
+ @JsonProperty("northEastCorner") Location northEastCorner,
+ @JsonProperty("startDateTime") LocalDateTime startDateTime,
+ @JsonProperty("endDateTime") LocalDateTime endDateTime,
+ @JsonProperty("depots") List<Depot> depots,
+ @JsonProperty("vehicles") List<Vehicle> vehicles,
+ @JsonProperty("customers") List<Customer> customers) {
+ this.name = name;
+ this.southWestCorner = southWestCorner;
+ this.northEastCorner = northEastCorner;
+ this.startDateTime = startDateTime;
+ this.endDateTime = endDateTime;
+ this.depots = depots;
+ this.vehicles = vehicles;
+ this.customers = customers;
+ List<Location> locations = Stream.concat(
+ depots.stream().map(Depot::getLocation),
+ customers.stream().map(Customer::getLocation)).toList();
+
+ DistanceCalculator distanceCalculator = new HaversineDistanceCalculator();
+ distanceCalculator.initDistanceMaps(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<Depot> getDepots() {
+ return depots;
+ }
+
+ public List<Vehicle> getVehicles() {
+ return vehicles;
+ }
+
+ public List<Customer> getCustomers() {
+ return customers;
+ }
+
+ public HardSoftLongScore getScore() {
+ return score;
+ }
+
+ public void setScore(HardSoftLongScore score) {
+ this.score = score;
+ }
+
+ // ************************************************************************
+ // Complex methods
+ // ************************************************************************
+
+ @JsonProperty(access = JsonProperty.Access.READ_ONLY)
+ public long getTotalDrivingTimeSeconds() {
+ return score == null ? 0 : -score.softScore(); | I know this was implemented like that already before, but we could take this opportunity to fix it.
Conceptually, it's wrong: soft score should not serve as the source of driving time statistics. It works because there is only a single soft constraint. QS in a way teach users good habits and this is not an example of a good habit.
Proposal: sum up the driving time over all vehicles. |
timefold-quickstarts | github_2023 | java | 223 | TimefoldAI | rsynek | @@ -0,0 +1,51 @@
+package org.acme.vehiclerouting.domain.geo;
+
+import org.acme.vehiclerouting.domain.Location;
+
+public class HaversineDistanceCalculator implements DistanceCalculator {
+
+ private static final int EARTH_RADIUS_IN_KM = 6371;
+ private static final int TWICE_EARTH_RADIUS_IN_KM = 2 * EARTH_RADIUS_IN_KM;
+ public static final int AVERAGE_SPEED_KMPH = 60; | I set this value very optimistically; if we spend the majority of the driving time in cities, 50 is more realistic. |
timefold-quickstarts | github_2023 | java | 223 | TimefoldAI | rsynek | @@ -0,0 +1,51 @@
+package org.acme.vehiclerouting.domain.geo;
+
+import org.acme.vehiclerouting.domain.Location;
+
+public class HaversineDistanceCalculator implements DistanceCalculator {
+
+ private static final int EARTH_RADIUS_IN_KM = 6371;
+ private static final int TWICE_EARTH_RADIUS_IN_KM = 2 * EARTH_RADIUS_IN_KM;
+ public static final int AVERAGE_SPEED_KMPH = 60;
+
+ public static long kilometersToDrivingSeconds(double kilometers) { | As we discussed the distance vs. driving time, consider moving this method outside the distance calculator to make it easier for users to switch to optimizing the distance. |
timefold-quickstarts | github_2023 | others | 223 | TimefoldAI | rsynek | @@ -0,0 +1,203 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta http-equiv="content-type" content="text/html; charset=UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
+ <title>Vehicle Routing - Timefold Quarkus</title>
+ <link rel="stylesheet" href="/webjars/bootstrap/css/bootstrap.min.css">
+ <link rel="stylesheet" href="/webjars/leaflet/leaflet.css">
+ <link rel="stylesheet" href="/webjars/font-awesome/css/all.min.css">
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vis-timeline@7.7.2/styles/vis-timeline-graph2d.min.css"
+ integrity="sha256-svzNasPg1yR5gvEaRei2jg+n4Pc3sVyMUWeS6xRAh6U=" crossorigin="anonymous">
+ <link rel="stylesheet" href="/webjars/timefold/css/timefold-webui.css"/>
+ <link rel="icon" href="/webjars/timefold/img/timefold-favicon.svg" type="image/svg+xml">
+</head>
+<body>
+
+<header id="timefold-auto-header">
+ <!-- Filled in by app.js -->
+</header>
+<div class="tab-content">
+ <div id="demo" class="tab-pane fade show active container-fluid">
+ <div class="sticky-top d-flex justify-content-center align-items-center">
+ <div id="notificationPanel" style="position: absolute; top: .5rem;"></div>
+ </div>
+ <h1>Vehicle routing with capacity and time windows</h1>
+ <p>Generate optimal route plan of a vehicle fleet with vehicle capacity.</p> | Here we talk about a capacity...(see more below) |
timefold-quickstarts | github_2023 | others | 223 | TimefoldAI | rsynek | @@ -0,0 +1,203 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta http-equiv="content-type" content="text/html; charset=UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
+ <title>Vehicle Routing - Timefold Quarkus</title>
+ <link rel="stylesheet" href="/webjars/bootstrap/css/bootstrap.min.css">
+ <link rel="stylesheet" href="/webjars/leaflet/leaflet.css">
+ <link rel="stylesheet" href="/webjars/font-awesome/css/all.min.css">
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vis-timeline@7.7.2/styles/vis-timeline-graph2d.min.css"
+ integrity="sha256-svzNasPg1yR5gvEaRei2jg+n4Pc3sVyMUWeS6xRAh6U=" crossorigin="anonymous">
+ <link rel="stylesheet" href="/webjars/timefold/css/timefold-webui.css"/>
+ <link rel="icon" href="/webjars/timefold/img/timefold-favicon.svg" type="image/svg+xml">
+</head>
+<body>
+
+<header id="timefold-auto-header">
+ <!-- Filled in by app.js -->
+</header>
+<div class="tab-content">
+ <div id="demo" class="tab-pane fade show active container-fluid">
+ <div class="sticky-top d-flex justify-content-center align-items-center">
+ <div id="notificationPanel" style="position: absolute; top: .5rem;"></div>
+ </div>
+ <h1>Vehicle routing with capacity and time windows</h1>
+ <p>Generate optimal route plan of a vehicle fleet with vehicle capacity.</p>
+
+ <div class="container-fluid mb-2">
+ <div class="row justify-content-start">
+ <div class="col-9">
+ <ul class="nav nav-pills col" role="tablist">
+ <li class="nav-item" role="presentation">
+ <button class="nav-link active" id="mapTab" data-bs-toggle="tab" data-bs-target="#mapPanel"
+ type="button"
+ role="tab" aria-controls="mapPanel" aria-selected="false">Map
+ </button>
+ </li>
+ <li class="nav-item" role="presentation">
+ <button class="nav-link" id="byVehicleTab" data-bs-toggle="tab" data-bs-target="#byVehiclePanel"
+ type="button" role="tab" aria-controls="byVehiclePanel" aria-selected="true">By vehicle
+ </button>
+ </li>
+ <li class="nav-item" role="presentation">
+ <button class="nav-link" id="byCustomerTab" data-bs-toggle="tab" data-bs-target="#byCustomerPanel"
+ type="button" role="tab" aria-controls="byCustomerPanel" aria-selected="false">By customer
+ </button>
+ </li>
+ </ul>
+ </div>
+ <div class="col-3">
+ <button id="solveButton" type="button" class="btn btn-success">
+ <i class="fas fa-play"></i> Solve
+ </button>
+ <button id="stopSolvingButton" type="button" class="btn btn-danger">
+ <i class="fas fa-stop"></i> Stop solving
+ </button>
+ </div>
+ </div>
+ </div>
+
+ <div class="tab-content">
+
+ <div class="tab-pane fade show active" id="mapPanel" role="tabpanel" aria-labelledby="mapTab">
+ <div class="row">
+ <div class="col-7 col-lg-8 col-xl-9">
+ <div id="map" style="width: 100%; height: 100vh;"></div>
+ </div>
+ <div class="col-5 col-lg-4 col-xl-3" style="height: 100vh; overflow-y: scroll;">
+ <div class="row pt-2 row-cols-1">
+ <div class="col">
+ <h5>
+ Solution summary
+ <a href="#" class="float-justify" data-bs-toggle="modal" data-bs-target="#scoreDialog">
+ <i class="fas fa-info-circle"></i>
+ </a>
+ </h5>
+ <table class="table">
+ <tr>
+ <td>Score:</td>
+ <td><span id="score">unknown</span></td>
+ </tr>
+ <tr>
+ <td>Total driving time:</td>
+ <td><span id="drivingTime">unknown</span></td>
+ </tr>
+ </table>
+ </div>
+ <div class="col">
+ <h5>Depots</h5>
+ <table class="table-sm w-100">
+ <thead>
+ <tr>
+ <th class="col-1"></th>
+ <th class="col-11">Name</th>
+ </tr>
+ </thead>
+ <tbody id="depots"></tbody>
+ </table>
+ </div>
+ <div class="col">
+ <h5>Vehicles</h5>
+ <table class="table-sm w-100">
+ <thead>
+ <tr>
+ <th class="col-1"></th>
+ <th class="col-3">Name</th>
+ <th class="col-3">Driving time</th>
+ </tr>
+ </thead>
+ <tbody id="vehicles"></tbody>
+ </table>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+
+ <div class="tab-pane fade" id="byVehiclePanel" role="tabpanel" aria-labelledby="byVehicleTab">
+ </div>
+ <div class="tab-pane fade" id="byCustomerPanel" role="tabpanel" aria-labelledby="byCustomerTab">
+ </div>
+ </div>
+ </div>
+
+ <div id="rest" class="tab-pane fade container-fluid">
+ <h1>REST API Guide</h1>
+
+ <h2>Vehicle routing with time windows - integration via cURL</h2> | ...and here about time windows.
Let's try to unify the description. |
timefold-quickstarts | github_2023 | java | 223 | TimefoldAI | rsynek | @@ -0,0 +1,39 @@
+package org.acme.vehiclerouting.domain.geo;
+
+import org.acme.vehiclerouting.domain.Location;
+import org.assertj.core.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+class HaversineDistanceCalculatorTest {
+
+ private final DistanceCalculator distanceCalculator = new HaversineDistanceCalculator();
+
+ 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);
+
+ // Results have been verified with the help of https://latlongdata.com/.
+ @Test
+ void calculateDistance() {
+ Location Gent = new Location(51.0441461, 3.7336349);
+ Location Brno = new Location(49.1913945, 16.6122723);
+ Assertions.assertThat(distanceCalculator.calculateDistance(Gent, Brno))
+ .isEqualTo(939748L);
+
+ // Close to the North Pole.
+ Location Svolvaer = new Location(68.2359953, 14.5644379);
+ Location Lulea = new Location(65.5887708, 22.1518707);
+ Assertions.assertThat(distanceCalculator.calculateDistance(Svolvaer, Lulea))
+ .isEqualTo(442297L);
+ }
+
+ @Test
+ void calculateConstraintDistance() { | What is the motivation for this additional test? |
timefold-quickstarts | github_2023 | java | 223 | TimefoldAI | rsynek | @@ -0,0 +1,48 @@
+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 DistanceCalculator {
+
+ /**
+ * Calculate the distance between {@code from} and {@code to} in meters or driving time seconds when using {@link DrivingTimeDecorator} class.
+ *
+ * @param from starting location
+ * @param to target location
+ * @return meters or driving time in seconds, depending on the implementation
+ */
+ long calculateDistance(Location from, Location to);
+
+ /**
+ * Bulk calculation of distance.
+ * Typically, much more scalable than {@link #calculateDistance(Location, Location)} iteratively.
+ *
+ * @param fromLocations never null
+ * @param toLocations never null
+ * @return never null
+ */
+ default Map<Location, Map<Location, Long>> calculateBulkDistance(
+ Collection<Location> fromLocations,
+ Collection<Location> toLocations) {
+ return fromLocations.stream().collect(Collectors.toMap(
+ Function.identity(),
+ from -> toLocations.stream().collect(Collectors.toMap(
+ Function.identity(),
+ to -> calculateDistance(from, to)))));
+ }
+
+ /**
+ * Calculate distance matrix for the given list of locations and assign distance maps accordingly.
+ *
+ * @param locations locations list
+ */
+ default void initDistanceMaps(Collection<Location> locations) {
+ Map<Location, Map<Location, Long>> distanceMatrix = calculateBulkDistance(locations, locations);
+ locations.forEach(location -> location.setDrivingTimeSeconds(distanceMatrix.get(location))); | The `Location` uses seconds, so here, in this method, we already decide it's seconds and not meters.
What if we did this initialization in the `VehicleRoutePlan` and left the `DistanceCalculator` to only calculate distance? |
timefold-quickstarts | github_2023 | others | 223 | TimefoldAI | triceo | @@ -136,6 +137,14 @@ image::build/quickstarts-showcase/src/main/resources/META-INF/resources/screensh
* link:use-cases/vehicle-routing-time-windows/README.adoc[Run quarkus-vehicle-routing-time-windows] (Java, Maven, Quarkus)
+=== Vehicle Routing with capacity and time windows | I'd call this just "Vehicle routing". |
timefold-quickstarts | github_2023 | others | 223 | TimefoldAI | triceo | @@ -136,6 +137,14 @@ image::build/quickstarts-showcase/src/main/resources/META-INF/resources/screensh
* link:use-cases/vehicle-routing-time-windows/README.adoc[Run quarkus-vehicle-routing-time-windows] (Java, Maven, Quarkus)
+=== Vehicle Routing with capacity and time windows
+
+Find the most efficient routes for vehicles, taking into account their capacity, to customers with time windows. | ```suggestion
Find the most efficient routes for vehicles to reach customers, taking into account vehicle capacity and time windows when customers are available. Sometimes also called "CVRPTW".
``` |
timefold-quickstarts | github_2023 | others | 223 | TimefoldAI | triceo | @@ -143,6 +143,26 @@ <h5>
</div>
</div>
</div>
+ <div class="col mb-4">
+ <div class="card">
+ <div class="card-header">
+ <h5>
+ <i class="fas fa-truck"></i>
+ Vehicle routing with capacity and time windows
+ </h5>
+ </div>
+ <img src="screenshot/quarkus-vehicle-routing-screenshot.png" class="card-img-top mt-3" alt="Screenshot"/>
+ <div class="card-body">
+ <p class="card-text">
+ Find the most efficient routes for vehicles (taking into account their cargo capacity) to customers within specific time windows. | See suggested phrasing above. |
timefold-quickstarts | github_2023 | java | 223 | TimefoldAI | triceo | @@ -0,0 +1,31 @@
+package org.acme.vehiclerouting.domain;
+
+import com.fasterxml.jackson.annotation.JsonIdentityInfo;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.ObjectIdGenerators;
+
+@JsonIdentityInfo(scope = Depot.class, generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
+public class Depot { | I'm wondering... why not `record`? |
timefold-quickstarts | github_2023 | java | 223 | TimefoldAI | triceo | @@ -0,0 +1,56 @@
+package org.acme.vehiclerouting.domain.geo;
+
+import org.acme.vehiclerouting.domain.Location;
+
+/**
+ * Calculates the driving time (in seconds) between two locations by calculating their Haversine distance in meters
+ * assuming average speed {@link #AVERAGE_SPEED_KMPH}.
+ */
+public class HaversineDrivingTimeCalculator implements DrivingTimeCalculator { | Since this class has no instance fields, maybe we make it a singleton? |
timefold-quickstarts | github_2023 | java | 223 | TimefoldAI | triceo | @@ -0,0 +1,225 @@
+package org.acme.vehiclerouting.rest;
+
+import java.time.Duration;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.LocalTime;
+import java.util.List;
+import java.util.PrimitiveIterator;
+import java.util.Random;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.Function;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import jakarta.ws.rs.GET;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.PathParam;
+import jakarta.ws.rs.core.MediaType;
+
+import org.acme.vehiclerouting.domain.Customer;
+import org.acme.vehiclerouting.domain.Depot;
+import org.acme.vehiclerouting.domain.Location;
+import org.acme.vehiclerouting.domain.Vehicle;
+import org.acme.vehiclerouting.domain.VehicleRoutePlan;
+import org.eclipse.microprofile.openapi.annotations.Operation;
+import org.eclipse.microprofile.openapi.annotations.enums.SchemaType;
+import org.eclipse.microprofile.openapi.annotations.media.Content;
+import org.eclipse.microprofile.openapi.annotations.media.Schema;
+import org.eclipse.microprofile.openapi.annotations.parameters.Parameter;
+import org.eclipse.microprofile.openapi.annotations.responses.APIResponse;
+import org.eclipse.microprofile.openapi.annotations.responses.APIResponses;
+import org.eclipse.microprofile.openapi.annotations.tags.Tag;
+
+@Tag(name = "Demo data", description = "Timefold-provided demo vehicle routing data.")
+@Path("demo-data")
+public class VehicleRouteDemoResource {
+
+ private static final String[] FIRST_NAMES = { "Amy", "Beth", "Chad", "Dan", "Elsa", "Flo", "Gus", "Hugo", "Ivy", "Jay" };
+ private static final String[] LAST_NAMES = { "Cole", "Fox", "Green", "Jones", "King", "Li", "Poe", "Rye", "Smith", "Watt" };
+ private static final int[] SERVICE_DURATION_MINUTES = { 10, 20, 30, 40 };
+ private static final LocalTime MORNING_WINDOW_START = LocalTime.of(8, 0);
+ private static final LocalTime MORNING_WINDOW_END = LocalTime.of(12, 0);
+ private static final LocalTime AFTERNOON_WINDOW_START = LocalTime.of(13, 0);
+ private static final LocalTime AFTERNOON_WINDOW_END = LocalTime.of(18, 0);
+
+ public enum DemoData {
+ PHILADELPHIA(0, 60, 6, 2, LocalTime.of(7, 30),
+ 1,2,15, 30,
+ new Location(39.7656099067391, -76.83782328143754),
+ new Location(40.77636644354855, -74.9300739430771)),
+ HARTFORT(1,50, 6, 2, LocalTime.of(7, 30),
+ 1,3,20, 30,
+ new Location(41.48366520850297, -73.15901689943055),
+ new Location(41.99512052869307, -72.25114548877427)),
+ FIRENZE(2,77, 6, 2, LocalTime.of(7, 30),
+ 1, 2, 20, 40,
+ new Location(43.751466, 11.177210), new Location(43.809291, 11.290195));
+
+ private long seed;
+ private int customerCount;
+ private int vehicleCount;
+ private int depotCount;
+ private LocalTime vehicleStartTime;
+ private int minDemand;
+ private int maxDemand;
+ private int minVehicleCapacity;
+ private int maxVehicleCapacity;
+ private Location southWestCorner;
+ private Location northEastCorner;
+
+ DemoData(long seed, int customerCount, int vehicleCount, int depotCount, LocalTime vehicleStartTime,
+ int minDemand, int maxDemand, int minVehicleCapacity, int maxVehicleCapacity,
+ Location southWestCorner, Location northEastCorner) {
+ if (minDemand < 1) {
+ throw new IllegalStateException("minDemand (" + minDemand + ") must be greater than zero.");
+ }
+ if (maxDemand < 1) {
+ throw new IllegalStateException("maxDemand (" + maxDemand + ") must be greater than zero.");
+ }
+ if (minDemand >= maxDemand) {
+ throw new IllegalStateException("maxDemand (" + maxDemand + ") must be greater than minDemand ("
+ + minDemand + ").");
+ }
+ if (minVehicleCapacity < 1) {
+ throw new IllegalStateException(
+ "Number of minVehicleCapacity (" + minVehicleCapacity + ") must be greater than zero.");
+ }
+ if (maxVehicleCapacity < 1) {
+ throw new IllegalStateException(
+ "Number of maxVehicleCapacity (" + maxVehicleCapacity + ") must be greater than zero.");
+ }
+ if (minVehicleCapacity >= maxVehicleCapacity) {
+ throw new IllegalStateException("maxVehicleCapacity (" + maxVehicleCapacity
+ + ") must be greater than minVehicleCapacity (" + minVehicleCapacity + ").");
+ }
+ if (customerCount < 1) {
+ throw new IllegalStateException(
+ "Number of customerCount (" + customerCount + ") must be greater than zero.");
+ }
+ if (vehicleCount < 1) {
+ throw new IllegalStateException(
+ "Number of vehicleCount (" + vehicleCount + ") must be greater than zero.");
+ }
+ if (depotCount < 1) {
+ throw new IllegalStateException(
+ "Number of depotCount (" + depotCount + ") must be greater than zero.");
+ }
+ if (northEastCorner.getLatitude() <= southWestCorner.getLatitude()) {
+ throw new IllegalStateException("northEastCorner.getLatitude (" + northEastCorner.getLatitude()
+ + ") must be greater than southWestCorner.getLatitude(" + southWestCorner.getLatitude() + ").");
+ }
+ if (northEastCorner.getLongitude() <= southWestCorner.getLongitude()) {
+ throw new IllegalStateException("northEastCorner.getLongitude (" + northEastCorner.getLongitude()
+ + ") must be greater than southWestCorner.getLongitude(" + southWestCorner.getLongitude() + ").");
+ }
+
+ this.seed = seed;
+ this.customerCount = customerCount;
+ this.vehicleCount = vehicleCount;
+ this.depotCount = depotCount;
+ this.vehicleStartTime = vehicleStartTime;
+ this.minDemand = minDemand;
+ this.maxDemand = maxDemand;
+ this.minVehicleCapacity = minVehicleCapacity;
+ this.maxVehicleCapacity = maxVehicleCapacity;
+ this.southWestCorner = southWestCorner;
+ this.northEastCorner = northEastCorner;
+ }
+ }
+
+ @APIResponses(value = {
+ @APIResponse(responseCode = "200", description = "List of demo data represented as IDs.",
+ content = @Content(mediaType = MediaType.APPLICATION_JSON,
+ schema = @Schema(implementation = DemoData.class, type = SchemaType.ARRAY))) })
+ @Operation(summary = "List demo data.")
+ @GET
+ public DemoData[] list() {
+ return DemoData.values();
+ }
+
+ @APIResponses(value = {
+ @APIResponse(responseCode = "200", description = "Unsolved demo route plan.",
+ content = @Content(mediaType = MediaType.APPLICATION_JSON,
+ schema = @Schema(implementation = VehicleRoutePlan.class))) })
+ @Operation(summary = "Find an unsolved demo route plan by ID.")
+ @GET
+ @Path("/{demoDataId}")
+ public VehicleRoutePlan generate(@Parameter(description = "Unique identifier of the demo data.",
+ required = true) @PathParam("demoDataId") DemoData demoData) {
+ return build(demoData);
+ }
+
+ public VehicleRoutePlan build(DemoData demoData) {
+ String name = "demo";
+
+ Random random = new Random(demoData.seed);
+ PrimitiveIterator.OfDouble latitudes = random
+ .doubles(demoData.southWestCorner.getLatitude(), demoData.northEastCorner.getLatitude()).iterator();
+ PrimitiveIterator.OfDouble longitudes = random
+ .doubles(demoData.southWestCorner.getLongitude(), demoData.northEastCorner.getLongitude()).iterator();
+
+ PrimitiveIterator.OfInt demand = random.ints(demoData.minDemand, demoData.maxDemand + 1)
+ .iterator();
+ PrimitiveIterator.OfInt vehicleCapacity = random.ints(demoData.minVehicleCapacity, demoData.maxVehicleCapacity + 1)
+ .iterator();
+
+ PrimitiveIterator.OfInt depotRandom = random.ints(0, demoData.depotCount).iterator();
+
+ AtomicLong depotSequence = new AtomicLong();
+ Supplier<Depot> depotSupplier = () -> new Depot(
+ String.valueOf(depotSequence.incrementAndGet()),
+ new Location(latitudes.nextDouble(), longitudes.nextDouble()));
+
+ List<Depot> depots = Stream.generate(depotSupplier)
+ .limit(demoData.depotCount)
+ .collect(Collectors.toList());
+
+ AtomicLong vehicleSequence = new AtomicLong();
+ Supplier<Vehicle> vehicleSupplier = () -> new Vehicle(
+ String.valueOf(vehicleSequence.incrementAndGet()),
+ vehicleCapacity.nextInt(),
+ depots.get(depotRandom.nextInt()),
+ tomorrowAt(demoData.vehicleStartTime));
+
+ List<Vehicle> vehicles = Stream.generate(vehicleSupplier)
+ .limit(demoData.vehicleCount)
+ .collect(Collectors.toList());
+
+ Supplier<String> nameSupplier = () -> {
+ Function<String[], String> randomStringSelector = strings -> strings[random.nextInt(strings.length)];
+ String firstName = randomStringSelector.apply(FIRST_NAMES);
+ String lastName = randomStringSelector.apply(LAST_NAMES);
+ return firstName + " " + lastName;
+ };
+
+ AtomicLong customerSequence = new AtomicLong();
+ Supplier<Customer> customerSupplier = () -> {
+ boolean morningTimeWindow = random.nextBoolean();
+
+ LocalDateTime minStartTime = morningTimeWindow ? tomorrowAt(MORNING_WINDOW_START) : tomorrowAt(AFTERNOON_WINDOW_START);
+ LocalDateTime maxEndTime = morningTimeWindow ? tomorrowAt(MORNING_WINDOW_END) : tomorrowAt(AFTERNOON_WINDOW_END);
+ int serviceDurationMinutes = SERVICE_DURATION_MINUTES[random.nextInt(SERVICE_DURATION_MINUTES.length)];
+ return new Customer(
+ String.valueOf(customerSequence.incrementAndGet()),
+ nameSupplier.get(),
+ new Location(latitudes.nextDouble(), longitudes.nextDouble()),
+ demand.nextInt(),
+ minStartTime,
+ maxEndTime,
+ Duration.ofMinutes(serviceDurationMinutes));
+ };
+
+ List<Customer> customers = Stream.generate(customerSupplier)
+ .limit(demoData.customerCount)
+ .collect(Collectors.toList());
+
+ return new VehicleRoutePlan(name, demoData.southWestCorner, demoData.northEastCorner, tomorrowAt(demoData.vehicleStartTime), tomorrowAt(LocalTime.MIDNIGHT).plusDays(1L), depots, vehicles, customers
+ ); | The length of this line suggests to me that your IDE is not configured properly.
(Quickstarts don't have automated formatting via Maven plugin.) |
timefold-quickstarts | github_2023 | java | 223 | TimefoldAI | triceo | @@ -0,0 +1,225 @@
+package org.acme.vehiclerouting.rest;
+
+import java.time.Duration;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.LocalTime;
+import java.util.List;
+import java.util.PrimitiveIterator;
+import java.util.Random;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.Function;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import jakarta.ws.rs.GET;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.PathParam;
+import jakarta.ws.rs.core.MediaType;
+
+import org.acme.vehiclerouting.domain.Customer;
+import org.acme.vehiclerouting.domain.Depot;
+import org.acme.vehiclerouting.domain.Location;
+import org.acme.vehiclerouting.domain.Vehicle;
+import org.acme.vehiclerouting.domain.VehicleRoutePlan;
+import org.eclipse.microprofile.openapi.annotations.Operation;
+import org.eclipse.microprofile.openapi.annotations.enums.SchemaType;
+import org.eclipse.microprofile.openapi.annotations.media.Content;
+import org.eclipse.microprofile.openapi.annotations.media.Schema;
+import org.eclipse.microprofile.openapi.annotations.parameters.Parameter;
+import org.eclipse.microprofile.openapi.annotations.responses.APIResponse;
+import org.eclipse.microprofile.openapi.annotations.responses.APIResponses;
+import org.eclipse.microprofile.openapi.annotations.tags.Tag;
+
+@Tag(name = "Demo data", description = "Timefold-provided demo vehicle routing data.")
+@Path("demo-data")
+public class VehicleRouteDemoResource {
+
+ private static final String[] FIRST_NAMES = { "Amy", "Beth", "Chad", "Dan", "Elsa", "Flo", "Gus", "Hugo", "Ivy", "Jay" };
+ private static final String[] LAST_NAMES = { "Cole", "Fox", "Green", "Jones", "King", "Li", "Poe", "Rye", "Smith", "Watt" };
+ private static final int[] SERVICE_DURATION_MINUTES = { 10, 20, 30, 40 };
+ private static final LocalTime MORNING_WINDOW_START = LocalTime.of(8, 0);
+ private static final LocalTime MORNING_WINDOW_END = LocalTime.of(12, 0);
+ private static final LocalTime AFTERNOON_WINDOW_START = LocalTime.of(13, 0);
+ private static final LocalTime AFTERNOON_WINDOW_END = LocalTime.of(18, 0);
+
+ public enum DemoData {
+ PHILADELPHIA(0, 60, 6, 2, LocalTime.of(7, 30),
+ 1,2,15, 30,
+ new Location(39.7656099067391, -76.83782328143754),
+ new Location(40.77636644354855, -74.9300739430771)),
+ HARTFORT(1,50, 6, 2, LocalTime.of(7, 30),
+ 1,3,20, 30,
+ new Location(41.48366520850297, -73.15901689943055),
+ new Location(41.99512052869307, -72.25114548877427)),
+ FIRENZE(2,77, 6, 2, LocalTime.of(7, 30),
+ 1, 2, 20, 40,
+ new Location(43.751466, 11.177210), new Location(43.809291, 11.290195));
+
+ private long seed;
+ private int customerCount;
+ private int vehicleCount;
+ private int depotCount;
+ private LocalTime vehicleStartTime;
+ private int minDemand;
+ private int maxDemand;
+ private int minVehicleCapacity;
+ private int maxVehicleCapacity;
+ private Location southWestCorner;
+ private Location northEastCorner;
+
+ DemoData(long seed, int customerCount, int vehicleCount, int depotCount, LocalTime vehicleStartTime,
+ int minDemand, int maxDemand, int minVehicleCapacity, int maxVehicleCapacity,
+ Location southWestCorner, Location northEastCorner) {
+ if (minDemand < 1) {
+ throw new IllegalStateException("minDemand (" + minDemand + ") must be greater than zero.");
+ }
+ if (maxDemand < 1) {
+ throw new IllegalStateException("maxDemand (" + maxDemand + ") must be greater than zero.");
+ }
+ if (minDemand >= maxDemand) {
+ throw new IllegalStateException("maxDemand (" + maxDemand + ") must be greater than minDemand ("
+ + minDemand + ").");
+ }
+ if (minVehicleCapacity < 1) {
+ throw new IllegalStateException(
+ "Number of minVehicleCapacity (" + minVehicleCapacity + ") must be greater than zero.");
+ }
+ if (maxVehicleCapacity < 1) {
+ throw new IllegalStateException(
+ "Number of maxVehicleCapacity (" + maxVehicleCapacity + ") must be greater than zero.");
+ }
+ if (minVehicleCapacity >= maxVehicleCapacity) {
+ throw new IllegalStateException("maxVehicleCapacity (" + maxVehicleCapacity
+ + ") must be greater than minVehicleCapacity (" + minVehicleCapacity + ").");
+ }
+ if (customerCount < 1) {
+ throw new IllegalStateException(
+ "Number of customerCount (" + customerCount + ") must be greater than zero.");
+ }
+ if (vehicleCount < 1) {
+ throw new IllegalStateException(
+ "Number of vehicleCount (" + vehicleCount + ") must be greater than zero.");
+ }
+ if (depotCount < 1) {
+ throw new IllegalStateException(
+ "Number of depotCount (" + depotCount + ") must be greater than zero.");
+ }
+ if (northEastCorner.getLatitude() <= southWestCorner.getLatitude()) {
+ throw new IllegalStateException("northEastCorner.getLatitude (" + northEastCorner.getLatitude()
+ + ") must be greater than southWestCorner.getLatitude(" + southWestCorner.getLatitude() + ").");
+ }
+ if (northEastCorner.getLongitude() <= southWestCorner.getLongitude()) {
+ throw new IllegalStateException("northEastCorner.getLongitude (" + northEastCorner.getLongitude()
+ + ") must be greater than southWestCorner.getLongitude(" + southWestCorner.getLongitude() + ").");
+ }
+
+ this.seed = seed;
+ this.customerCount = customerCount;
+ this.vehicleCount = vehicleCount;
+ this.depotCount = depotCount;
+ this.vehicleStartTime = vehicleStartTime;
+ this.minDemand = minDemand;
+ this.maxDemand = maxDemand;
+ this.minVehicleCapacity = minVehicleCapacity;
+ this.maxVehicleCapacity = maxVehicleCapacity;
+ this.southWestCorner = southWestCorner;
+ this.northEastCorner = northEastCorner;
+ }
+ }
+
+ @APIResponses(value = {
+ @APIResponse(responseCode = "200", description = "List of demo data represented as IDs.",
+ content = @Content(mediaType = MediaType.APPLICATION_JSON,
+ schema = @Schema(implementation = DemoData.class, type = SchemaType.ARRAY))) })
+ @Operation(summary = "List demo data.")
+ @GET
+ public DemoData[] list() {
+ return DemoData.values();
+ }
+
+ @APIResponses(value = {
+ @APIResponse(responseCode = "200", description = "Unsolved demo route plan.",
+ content = @Content(mediaType = MediaType.APPLICATION_JSON,
+ schema = @Schema(implementation = VehicleRoutePlan.class))) })
+ @Operation(summary = "Find an unsolved demo route plan by ID.")
+ @GET
+ @Path("/{demoDataId}")
+ public VehicleRoutePlan generate(@Parameter(description = "Unique identifier of the demo data.",
+ required = true) @PathParam("demoDataId") DemoData demoData) {
+ return build(demoData);
+ }
+
+ public VehicleRoutePlan build(DemoData demoData) {
+ String name = "demo"; | I'm thinking... `var`? The methoud could arguably use it, but maybe for consistency with the rest of the code, we don't? |
timefold-quickstarts | github_2023 | java | 223 | TimefoldAI | triceo | @@ -0,0 +1,225 @@
+package org.acme.vehiclerouting.rest;
+
+import java.time.Duration;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.LocalTime;
+import java.util.List;
+import java.util.PrimitiveIterator;
+import java.util.Random;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.Function;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import jakarta.ws.rs.GET;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.PathParam;
+import jakarta.ws.rs.core.MediaType;
+
+import org.acme.vehiclerouting.domain.Customer;
+import org.acme.vehiclerouting.domain.Depot;
+import org.acme.vehiclerouting.domain.Location;
+import org.acme.vehiclerouting.domain.Vehicle;
+import org.acme.vehiclerouting.domain.VehicleRoutePlan;
+import org.eclipse.microprofile.openapi.annotations.Operation;
+import org.eclipse.microprofile.openapi.annotations.enums.SchemaType;
+import org.eclipse.microprofile.openapi.annotations.media.Content;
+import org.eclipse.microprofile.openapi.annotations.media.Schema;
+import org.eclipse.microprofile.openapi.annotations.parameters.Parameter;
+import org.eclipse.microprofile.openapi.annotations.responses.APIResponse;
+import org.eclipse.microprofile.openapi.annotations.responses.APIResponses;
+import org.eclipse.microprofile.openapi.annotations.tags.Tag;
+
+@Tag(name = "Demo data", description = "Timefold-provided demo vehicle routing data.")
+@Path("demo-data")
+public class VehicleRouteDemoResource {
+
+ private static final String[] FIRST_NAMES = { "Amy", "Beth", "Chad", "Dan", "Elsa", "Flo", "Gus", "Hugo", "Ivy", "Jay" };
+ private static final String[] LAST_NAMES = { "Cole", "Fox", "Green", "Jones", "King", "Li", "Poe", "Rye", "Smith", "Watt" };
+ private static final int[] SERVICE_DURATION_MINUTES = { 10, 20, 30, 40 };
+ private static final LocalTime MORNING_WINDOW_START = LocalTime.of(8, 0);
+ private static final LocalTime MORNING_WINDOW_END = LocalTime.of(12, 0);
+ private static final LocalTime AFTERNOON_WINDOW_START = LocalTime.of(13, 0);
+ private static final LocalTime AFTERNOON_WINDOW_END = LocalTime.of(18, 0);
+
+ public enum DemoData {
+ PHILADELPHIA(0, 60, 6, 2, LocalTime.of(7, 30),
+ 1,2,15, 30,
+ new Location(39.7656099067391, -76.83782328143754),
+ new Location(40.77636644354855, -74.9300739430771)),
+ HARTFORT(1,50, 6, 2, LocalTime.of(7, 30),
+ 1,3,20, 30,
+ new Location(41.48366520850297, -73.15901689943055),
+ new Location(41.99512052869307, -72.25114548877427)),
+ FIRENZE(2,77, 6, 2, LocalTime.of(7, 30),
+ 1, 2, 20, 40,
+ new Location(43.751466, 11.177210), new Location(43.809291, 11.290195));
+
+ private long seed;
+ private int customerCount;
+ private int vehicleCount;
+ private int depotCount;
+ private LocalTime vehicleStartTime;
+ private int minDemand;
+ private int maxDemand;
+ private int minVehicleCapacity;
+ private int maxVehicleCapacity;
+ private Location southWestCorner;
+ private Location northEastCorner;
+
+ DemoData(long seed, int customerCount, int vehicleCount, int depotCount, LocalTime vehicleStartTime,
+ int minDemand, int maxDemand, int minVehicleCapacity, int maxVehicleCapacity,
+ Location southWestCorner, Location northEastCorner) {
+ if (minDemand < 1) {
+ throw new IllegalStateException("minDemand (" + minDemand + ") must be greater than zero.");
+ }
+ if (maxDemand < 1) {
+ throw new IllegalStateException("maxDemand (" + maxDemand + ") must be greater than zero.");
+ }
+ if (minDemand >= maxDemand) {
+ throw new IllegalStateException("maxDemand (" + maxDemand + ") must be greater than minDemand ("
+ + minDemand + ")."); | For readability, we've lately been moving towards the `"maxDemand (%s) ...".formatted(maxDemand)` pattern. |
timefold-quickstarts | github_2023 | java | 223 | TimefoldAI | triceo | @@ -0,0 +1,25 @@
+package org.acme.vehiclerouting.domain.geo;
+
+import org.acme.vehiclerouting.domain.Location;
+import org.assertj.core.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+class HaversineDrivingTimeCalculatorTest {
+
+ private final DrivingTimeCalculator drivingTimeCalculator = new HaversineDrivingTimeCalculator();
+
+ // Results have been verified with the help of https://latlongdata.com/.
+ @Test
+ void calculateDrivingTime() {
+ Location Gent = new Location(51.0441461, 3.7336349);
+ Location Brno = new Location(49.1913945, 16.6122723); | Lovely! |
timefold-quickstarts | github_2023 | java | 223 | TimefoldAI | rsynek | @@ -0,0 +1,161 @@
+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.solution.ProblemFactCollectionProperty;
+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;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+/**
+ * The plan for routing vehicles to customers, including:
+ * <ul>
+ * <li>capacity - each vehicle has a capacity for customers demand,</li>
+ * <li>time windows - each customer accepts the vehicle only in specified time window.</li>
+ * </ul>
+ *
+ * The planning solution is optimized according to the driving time (as opposed to the travel distance, for example)
+ * because it is easy to determine if the vehicle arrival time fits into the customer time window. | I would even add one more sentence to explain that optimizing travel time optimizes the distance too, as a side effect, but in case there is a faster route, the travel time takes precedence (highway vs. some local road). |
timefold-quickstarts | github_2023 | java | 223 | TimefoldAI | triceo | @@ -174,8 +215,9 @@ public VehicleRoutePlan build(DemoData demoData) {
.limit(demoData.customerCount)
.collect(Collectors.toList());
- return new VehicleRoutePlan(name, demoData.southWestCorner, demoData.northEastCorner, tomorrowAt(demoData.vehicleStartTime), tomorrowAt(LocalTime.MIDNIGHT).plusDays(1L), depots, vehicles, customers
- );
+ return new VehicleRoutePlan(name, demoData.southWestCorner, demoData.northEastCorner,
+ tomorrowAt(demoData.vehicleStartTime), tomorrowAt(LocalTime.MIDNIGHT).plusDays(1L),
+ depots, vehicles, customers); | I think your formatting is still wrong; in this case, lines 219 and 220 should be indented, not aligned to the first argument on line 218. |
timefold-quickstarts | github_2023 | others | 139 | TimefoldAI | triceo | @@ -0,0 +1,641 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "source": [
+ "# School timetabling kotlin notebook\n",
+ "\n",
+ "This Kotlin Notebook solves the school timetabling problem with [Timefold](https://timefold.ai], the open source planning solver AI.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Dependencies\n",
+ "\n",
+ "Add the Timefold solver dependency:"
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 74,
+ "outputs": [],
+ "source": [
+ "@file:DependsOn(\"ai.timefold.solver:timefold-solver-core:1.3.0\")" | At this point on `development` branch, this version should be `999-SNAPSHOT`.
Please go into `.github/workflows/release.yml` and add support there for bumping this version during the release. |
timefold-quickstarts | github_2023 | others | 139 | TimefoldAI | triceo | @@ -0,0 +1,641 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "source": [
+ "# School timetabling kotlin notebook\n",
+ "\n",
+ "This Kotlin Notebook solves the school timetabling problem with [Timefold](https://timefold.ai], the open source planning solver AI.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Dependencies\n",
+ "\n",
+ "Add the Timefold solver dependency:"
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 74,
+ "outputs": [],
+ "source": [
+ "@file:DependsOn(\"ai.timefold.solver:timefold-solver-core:1.3.0\")"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.229748528Z",
+ "start_time": "2023-10-30T21:00:59.103295531Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "\n",
+ "## Domain\n",
+ "\n",
+ "Create the domain classes:\n",
+ "\n",
+ "### Room\n",
+ "\n",
+ "A school has rooms."
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 75,
+ "outputs": [],
+ "source": [
+ "class Room {\n",
+ "\n",
+ " var name: String\n",
+ "\n",
+ " constructor(name: String) {\n",
+ " this.name = name\n",
+ " }\n",
+ "\n",
+ " override fun toString(): String = name\n",
+ "\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.274546567Z",
+ "start_time": "2023-10-30T21:01:02.228839493Z"
+ }
+ } | Looks like user data leaked into the notebook. Does this need to be here? |
timefold-quickstarts | github_2023 | others | 139 | TimefoldAI | triceo | @@ -0,0 +1,641 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "source": [
+ "# School timetabling kotlin notebook\n",
+ "\n",
+ "This Kotlin Notebook solves the school timetabling problem with [Timefold](https://timefold.ai], the open source planning solver AI.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Dependencies\n",
+ "\n",
+ "Add the Timefold solver dependency:"
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 74,
+ "outputs": [],
+ "source": [
+ "@file:DependsOn(\"ai.timefold.solver:timefold-solver-core:1.3.0\")"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.229748528Z",
+ "start_time": "2023-10-30T21:00:59.103295531Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "\n",
+ "## Domain\n",
+ "\n",
+ "Create the domain classes:\n",
+ "\n",
+ "### Room\n",
+ "\n",
+ "A school has rooms."
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 75,
+ "outputs": [],
+ "source": [
+ "class Room {\n",
+ "\n",
+ " var name: String\n",
+ "\n",
+ " constructor(name: String) {\n",
+ " this.name = name\n",
+ " }\n",
+ "\n",
+ " override fun toString(): String = name\n",
+ "\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.274546567Z",
+ "start_time": "2023-10-30T21:01:02.228839493Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "### Timeslot\n",
+ "\n",
+ "A school timetable has timeslots."
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 76,
+ "outputs": [],
+ "source": [
+ "import java.time.DayOfWeek\n",
+ "import java.time.LocalTime\n",
+ "\n",
+ "class Timeslot {\n",
+ "\n",
+ " var dayOfWeek: DayOfWeek\n",
+ " var startTime: LocalTime\n",
+ " var endTime: LocalTime\n",
+ "\n",
+ " constructor(dayOfWeek: DayOfWeek, startTime: LocalTime, endTime: LocalTime) {\n",
+ " this.dayOfWeek = dayOfWeek\n",
+ " this.startTime = startTime\n",
+ " this.endTime = endTime\n",
+ " }\n",
+ "\n",
+ " override fun toString(): String = \"$dayOfWeek $startTime\"\n",
+ "\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.321779372Z",
+ "start_time": "2023-10-30T21:01:02.274072196Z"
+ } | Dtto. |
timefold-quickstarts | github_2023 | others | 139 | TimefoldAI | triceo | @@ -0,0 +1,641 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "source": [
+ "# School timetabling kotlin notebook\n",
+ "\n",
+ "This Kotlin Notebook solves the school timetabling problem with [Timefold](https://timefold.ai], the open source planning solver AI.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Dependencies\n",
+ "\n",
+ "Add the Timefold solver dependency:"
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 74,
+ "outputs": [],
+ "source": [
+ "@file:DependsOn(\"ai.timefold.solver:timefold-solver-core:1.3.0\")"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.229748528Z",
+ "start_time": "2023-10-30T21:00:59.103295531Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "\n",
+ "## Domain\n",
+ "\n",
+ "Create the domain classes:\n",
+ "\n",
+ "### Room\n",
+ "\n",
+ "A school has rooms."
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 75,
+ "outputs": [],
+ "source": [
+ "class Room {\n",
+ "\n",
+ " var name: String\n",
+ "\n",
+ " constructor(name: String) {\n",
+ " this.name = name\n",
+ " }\n",
+ "\n",
+ " override fun toString(): String = name\n",
+ "\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.274546567Z",
+ "start_time": "2023-10-30T21:01:02.228839493Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "### Timeslot\n",
+ "\n",
+ "A school timetable has timeslots."
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 76,
+ "outputs": [],
+ "source": [
+ "import java.time.DayOfWeek\n",
+ "import java.time.LocalTime\n",
+ "\n",
+ "class Timeslot {\n",
+ "\n",
+ " var dayOfWeek: DayOfWeek\n",
+ " var startTime: LocalTime\n",
+ " var endTime: LocalTime\n",
+ "\n",
+ " constructor(dayOfWeek: DayOfWeek, startTime: LocalTime, endTime: LocalTime) {\n",
+ " this.dayOfWeek = dayOfWeek\n",
+ " this.startTime = startTime\n",
+ " this.endTime = endTime\n",
+ " }\n",
+ "\n",
+ " override fun toString(): String = \"$dayOfWeek $startTime\"\n",
+ "\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.321779372Z",
+ "start_time": "2023-10-30T21:01:02.274072196Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "### Lesson\n",
+ "\n",
+ "Each lesson must be assigned to a timeslot and to a room by the solver."
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 77,
+ "outputs": [],
+ "source": [
+ "import ai.timefold.solver.core.api.domain.entity.PlanningEntity\n",
+ "import ai.timefold.solver.core.api.domain.lookup.PlanningId\n",
+ "import ai.timefold.solver.core.api.domain.variable.PlanningVariable\n",
+ "\n",
+ "@PlanningEntity\n",
+ "class Lesson {\n",
+ "\n",
+ " @PlanningId\n",
+ " var id: Long? = null\n",
+ " lateinit var subject: String\n",
+ " lateinit var teacher: String\n",
+ " lateinit var studentGroup: String\n",
+ "\n",
+ " @PlanningVariable\n",
+ " var timeslot: Timeslot? = null\n",
+ " @PlanningVariable\n",
+ " var room: Room? = null\n",
+ "\n",
+ " // No-arg constructor required for Timefold\n",
+ " constructor()\n",
+ "\n",
+ " constructor(id: Long, subject: String, teacher: String, studentGroup: String) {\n",
+ " this.id = id\n",
+ " this.subject = subject\n",
+ " this.teacher = teacher\n",
+ " this.studentGroup = studentGroup\n",
+ " }\n",
+ "\n",
+ "\n",
+ " override fun toString(): String = \"$subject\"\n",
+ "\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.387536998Z",
+ "start_time": "2023-10-30T21:01:02.321150649Z"
+ }
+ } | Dtto. |
timefold-quickstarts | github_2023 | others | 139 | TimefoldAI | triceo | @@ -0,0 +1,641 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "source": [
+ "# School timetabling kotlin notebook\n",
+ "\n",
+ "This Kotlin Notebook solves the school timetabling problem with [Timefold](https://timefold.ai], the open source planning solver AI.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Dependencies\n",
+ "\n",
+ "Add the Timefold solver dependency:"
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 74,
+ "outputs": [],
+ "source": [
+ "@file:DependsOn(\"ai.timefold.solver:timefold-solver-core:1.3.0\")"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.229748528Z",
+ "start_time": "2023-10-30T21:00:59.103295531Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "\n",
+ "## Domain\n",
+ "\n",
+ "Create the domain classes:\n",
+ "\n",
+ "### Room\n",
+ "\n",
+ "A school has rooms."
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 75,
+ "outputs": [],
+ "source": [
+ "class Room {\n",
+ "\n",
+ " var name: String\n",
+ "\n",
+ " constructor(name: String) {\n",
+ " this.name = name\n",
+ " }\n",
+ "\n",
+ " override fun toString(): String = name\n",
+ "\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.274546567Z",
+ "start_time": "2023-10-30T21:01:02.228839493Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "### Timeslot\n",
+ "\n",
+ "A school timetable has timeslots."
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 76,
+ "outputs": [],
+ "source": [
+ "import java.time.DayOfWeek\n",
+ "import java.time.LocalTime\n",
+ "\n",
+ "class Timeslot {\n",
+ "\n",
+ " var dayOfWeek: DayOfWeek\n",
+ " var startTime: LocalTime\n",
+ " var endTime: LocalTime\n",
+ "\n",
+ " constructor(dayOfWeek: DayOfWeek, startTime: LocalTime, endTime: LocalTime) {\n",
+ " this.dayOfWeek = dayOfWeek\n",
+ " this.startTime = startTime\n",
+ " this.endTime = endTime\n",
+ " }\n",
+ "\n",
+ " override fun toString(): String = \"$dayOfWeek $startTime\"\n",
+ "\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.321779372Z",
+ "start_time": "2023-10-30T21:01:02.274072196Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "### Lesson\n",
+ "\n",
+ "Each lesson must be assigned to a timeslot and to a room by the solver."
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 77,
+ "outputs": [],
+ "source": [
+ "import ai.timefold.solver.core.api.domain.entity.PlanningEntity\n",
+ "import ai.timefold.solver.core.api.domain.lookup.PlanningId\n",
+ "import ai.timefold.solver.core.api.domain.variable.PlanningVariable\n",
+ "\n",
+ "@PlanningEntity\n",
+ "class Lesson {\n",
+ "\n",
+ " @PlanningId\n",
+ " var id: Long? = null\n",
+ " lateinit var subject: String\n",
+ " lateinit var teacher: String\n",
+ " lateinit var studentGroup: String\n",
+ "\n",
+ " @PlanningVariable\n",
+ " var timeslot: Timeslot? = null\n",
+ " @PlanningVariable\n",
+ " var room: Room? = null\n",
+ "\n",
+ " // No-arg constructor required for Timefold\n",
+ " constructor()\n",
+ "\n",
+ " constructor(id: Long, subject: String, teacher: String, studentGroup: String) {\n",
+ " this.id = id\n",
+ " this.subject = subject\n",
+ " this.teacher = teacher\n",
+ " this.studentGroup = studentGroup\n",
+ " }\n",
+ "\n",
+ "\n",
+ " override fun toString(): String = \"$subject\"\n",
+ "\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.387536998Z",
+ "start_time": "2023-10-30T21:01:02.321150649Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "## Constraints\n",
+ "\n",
+ "The solver must take into account hard and soft constraints:"
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 78,
+ "outputs": [],
+ "source": [
+ "import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore\n",
+ "import ai.timefold.solver.core.api.score.stream.Constraint\n",
+ "import ai.timefold.solver.core.api.score.stream.ConstraintFactory\n",
+ "import ai.timefold.solver.core.api.score.stream.ConstraintProvider\n",
+ "import ai.timefold.solver.core.api.score.stream.Joiners\n",
+ "import java.time.Duration\n",
+ "\n",
+ "class TimeTableConstraintProvider : ConstraintProvider {\n",
+ "\n",
+ " override fun defineConstraints(constraintFactory: ConstraintFactory): Array<Constraint>? {\n",
+ " return arrayOf(\n",
+ " // Hard constraints\n",
+ " roomConflict(constraintFactory),\n",
+ " teacherConflict(constraintFactory),\n",
+ " studentGroupConflict(constraintFactory),\n",
+ " // Soft constraints\n",
+ " teacherRoomStability(constraintFactory),\n",
+ " teacherTimeEfficiency(constraintFactory),\n",
+ " studentGroupSubjectVariety(constraintFactory)\n",
+ " )\n",
+ " }\n",
+ "\n",
+ " fun roomConflict(constraintFactory: ConstraintFactory): Constraint {\n",
+ " // A room can accommodate at most one lesson at the same time.\n",
+ " return constraintFactory\n",
+ " // Select each pair of 2 different lessons ...\n",
+ " .forEachUniquePair(\n",
+ " Lesson::class.java,\n",
+ " // ... in the same timeslot ...\n",
+ " Joiners.equal(Lesson::timeslot),\n",
+ " // ... in the same room ...\n",
+ " Joiners.equal(Lesson::room)\n",
+ " )\n",
+ " // ... and penalize each pair with a hard weight.\n",
+ " .penalize(HardSoftScore.ONE_HARD)\n",
+ " .asConstraint(\"Room conflict\");\n",
+ " }\n",
+ "\n",
+ " fun teacherConflict(constraintFactory: ConstraintFactory): Constraint {\n",
+ " // A teacher can teach at most one lesson at the same time.\n",
+ " return constraintFactory\n",
+ " .forEachUniquePair(\n",
+ " Lesson::class.java,\n",
+ " Joiners.equal(Lesson::timeslot),\n",
+ " Joiners.equal(Lesson::teacher)\n",
+ " )\n",
+ " .penalize(HardSoftScore.ONE_HARD)\n",
+ " .asConstraint(\"Teacher conflict\");\n",
+ " }\n",
+ "\n",
+ " fun studentGroupConflict(constraintFactory: ConstraintFactory): Constraint {\n",
+ " // A student can attend at most one lesson at the same time.\n",
+ " return constraintFactory\n",
+ " .forEachUniquePair(\n",
+ " Lesson::class.java,\n",
+ " Joiners.equal(Lesson::timeslot),\n",
+ " Joiners.equal(Lesson::studentGroup)\n",
+ " )\n",
+ " .penalize(HardSoftScore.ONE_HARD)\n",
+ " .asConstraint(\"Student group conflict\");\n",
+ " }\n",
+ "\n",
+ " fun teacherRoomStability(constraintFactory: ConstraintFactory): Constraint {\n",
+ " // A teacher prefers to teach in a single room.\n",
+ " return constraintFactory\n",
+ " .forEachUniquePair(\n",
+ " Lesson::class.java,\n",
+ " Joiners.equal(Lesson::teacher)\n",
+ " )\n",
+ " .filter { lesson1: Lesson, lesson2: Lesson -> lesson1.room !== lesson2.room }\n",
+ " .penalize(HardSoftScore.ONE_SOFT)\n",
+ " .asConstraint(\"Teacher room stability\");\n",
+ " }\n",
+ "\n",
+ " fun teacherTimeEfficiency(constraintFactory: ConstraintFactory): Constraint {\n",
+ " // A teacher prefers to teach sequential lessons and dislikes gaps between lessons.\n",
+ " return constraintFactory\n",
+ " .forEach(Lesson::class.java)\n",
+ " .join(Lesson::class.java,\n",
+ " Joiners.equal(Lesson::teacher),\n",
+ " Joiners.equal { lesson: Lesson -> lesson.timeslot?.dayOfWeek })\n",
+ " .filter { lesson1: Lesson, lesson2: Lesson ->\n",
+ " val between = Duration.between(\n",
+ " lesson1.timeslot?.endTime,\n",
+ " lesson2.timeslot?.startTime\n",
+ " )\n",
+ " !between.isNegative && between.compareTo(Duration.ofMinutes(30)) <= 0\n",
+ " }\n",
+ " .reward(HardSoftScore.ONE_SOFT)\n",
+ " .asConstraint(\"Teacher time efficiency\");\n",
+ " }\n",
+ "\n",
+ " fun studentGroupSubjectVariety(constraintFactory: ConstraintFactory): Constraint {\n",
+ " // A student group dislikes sequential lessons on the same subject.\n",
+ " return constraintFactory\n",
+ " .forEach(Lesson::class.java)\n",
+ " .join(Lesson::class.java,\n",
+ " Joiners.equal(Lesson::subject),\n",
+ " Joiners.equal(Lesson::studentGroup),\n",
+ " Joiners.equal { lesson: Lesson -> lesson.timeslot?.dayOfWeek })\n",
+ " .filter { lesson1: Lesson, lesson2: Lesson ->\n",
+ " val between = Duration.between(\n",
+ " lesson1.timeslot?.endTime,\n",
+ " lesson2.timeslot?.startTime\n",
+ " )\n",
+ " !between.isNegative && between.compareTo(Duration.ofMinutes(30)) <= 0\n",
+ " }\n",
+ " .penalize(HardSoftScore.ONE_SOFT)\n",
+ " .asConstraint(\"Student group subject variety\");\n",
+ " }\n",
+ "\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.730088133Z",
+ "start_time": "2023-10-30T21:01:02.386917608Z"
+ }
+ } | Dtto. |
timefold-quickstarts | github_2023 | others | 139 | TimefoldAI | triceo | @@ -0,0 +1,641 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "source": [
+ "# School timetabling kotlin notebook\n",
+ "\n",
+ "This Kotlin Notebook solves the school timetabling problem with [Timefold](https://timefold.ai], the open source planning solver AI.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Dependencies\n",
+ "\n",
+ "Add the Timefold solver dependency:"
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 74,
+ "outputs": [],
+ "source": [
+ "@file:DependsOn(\"ai.timefold.solver:timefold-solver-core:1.3.0\")"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.229748528Z",
+ "start_time": "2023-10-30T21:00:59.103295531Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "\n",
+ "## Domain\n",
+ "\n",
+ "Create the domain classes:\n",
+ "\n",
+ "### Room\n",
+ "\n",
+ "A school has rooms."
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 75,
+ "outputs": [],
+ "source": [
+ "class Room {\n",
+ "\n",
+ " var name: String\n",
+ "\n",
+ " constructor(name: String) {\n",
+ " this.name = name\n",
+ " }\n",
+ "\n",
+ " override fun toString(): String = name\n",
+ "\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.274546567Z",
+ "start_time": "2023-10-30T21:01:02.228839493Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "### Timeslot\n",
+ "\n",
+ "A school timetable has timeslots."
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 76,
+ "outputs": [],
+ "source": [
+ "import java.time.DayOfWeek\n",
+ "import java.time.LocalTime\n",
+ "\n",
+ "class Timeslot {\n",
+ "\n",
+ " var dayOfWeek: DayOfWeek\n",
+ " var startTime: LocalTime\n",
+ " var endTime: LocalTime\n",
+ "\n",
+ " constructor(dayOfWeek: DayOfWeek, startTime: LocalTime, endTime: LocalTime) {\n",
+ " this.dayOfWeek = dayOfWeek\n",
+ " this.startTime = startTime\n",
+ " this.endTime = endTime\n",
+ " }\n",
+ "\n",
+ " override fun toString(): String = \"$dayOfWeek $startTime\"\n",
+ "\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.321779372Z",
+ "start_time": "2023-10-30T21:01:02.274072196Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "### Lesson\n",
+ "\n",
+ "Each lesson must be assigned to a timeslot and to a room by the solver."
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 77,
+ "outputs": [],
+ "source": [
+ "import ai.timefold.solver.core.api.domain.entity.PlanningEntity\n",
+ "import ai.timefold.solver.core.api.domain.lookup.PlanningId\n",
+ "import ai.timefold.solver.core.api.domain.variable.PlanningVariable\n",
+ "\n",
+ "@PlanningEntity\n",
+ "class Lesson {\n",
+ "\n",
+ " @PlanningId\n",
+ " var id: Long? = null\n",
+ " lateinit var subject: String\n",
+ " lateinit var teacher: String\n",
+ " lateinit var studentGroup: String\n",
+ "\n",
+ " @PlanningVariable\n",
+ " var timeslot: Timeslot? = null\n",
+ " @PlanningVariable\n",
+ " var room: Room? = null\n",
+ "\n",
+ " // No-arg constructor required for Timefold\n",
+ " constructor()\n",
+ "\n",
+ " constructor(id: Long, subject: String, teacher: String, studentGroup: String) {\n",
+ " this.id = id\n",
+ " this.subject = subject\n",
+ " this.teacher = teacher\n",
+ " this.studentGroup = studentGroup\n",
+ " }\n",
+ "\n",
+ "\n",
+ " override fun toString(): String = \"$subject\"\n",
+ "\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.387536998Z",
+ "start_time": "2023-10-30T21:01:02.321150649Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "## Constraints\n",
+ "\n",
+ "The solver must take into account hard and soft constraints:"
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 78,
+ "outputs": [],
+ "source": [
+ "import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore\n",
+ "import ai.timefold.solver.core.api.score.stream.Constraint\n",
+ "import ai.timefold.solver.core.api.score.stream.ConstraintFactory\n",
+ "import ai.timefold.solver.core.api.score.stream.ConstraintProvider\n",
+ "import ai.timefold.solver.core.api.score.stream.Joiners\n",
+ "import java.time.Duration\n",
+ "\n",
+ "class TimeTableConstraintProvider : ConstraintProvider {\n",
+ "\n",
+ " override fun defineConstraints(constraintFactory: ConstraintFactory): Array<Constraint>? {\n",
+ " return arrayOf(\n",
+ " // Hard constraints\n",
+ " roomConflict(constraintFactory),\n",
+ " teacherConflict(constraintFactory),\n",
+ " studentGroupConflict(constraintFactory),\n",
+ " // Soft constraints\n",
+ " teacherRoomStability(constraintFactory),\n",
+ " teacherTimeEfficiency(constraintFactory),\n",
+ " studentGroupSubjectVariety(constraintFactory)\n",
+ " )\n",
+ " }\n",
+ "\n",
+ " fun roomConflict(constraintFactory: ConstraintFactory): Constraint {\n",
+ " // A room can accommodate at most one lesson at the same time.\n",
+ " return constraintFactory\n",
+ " // Select each pair of 2 different lessons ...\n",
+ " .forEachUniquePair(\n",
+ " Lesson::class.java,\n",
+ " // ... in the same timeslot ...\n",
+ " Joiners.equal(Lesson::timeslot),\n",
+ " // ... in the same room ...\n",
+ " Joiners.equal(Lesson::room)\n",
+ " )\n",
+ " // ... and penalize each pair with a hard weight.\n",
+ " .penalize(HardSoftScore.ONE_HARD)\n",
+ " .asConstraint(\"Room conflict\");\n",
+ " }\n",
+ "\n",
+ " fun teacherConflict(constraintFactory: ConstraintFactory): Constraint {\n",
+ " // A teacher can teach at most one lesson at the same time.\n",
+ " return constraintFactory\n",
+ " .forEachUniquePair(\n",
+ " Lesson::class.java,\n",
+ " Joiners.equal(Lesson::timeslot),\n",
+ " Joiners.equal(Lesson::teacher)\n",
+ " )\n",
+ " .penalize(HardSoftScore.ONE_HARD)\n",
+ " .asConstraint(\"Teacher conflict\");\n",
+ " }\n",
+ "\n",
+ " fun studentGroupConflict(constraintFactory: ConstraintFactory): Constraint {\n",
+ " // A student can attend at most one lesson at the same time.\n",
+ " return constraintFactory\n",
+ " .forEachUniquePair(\n",
+ " Lesson::class.java,\n",
+ " Joiners.equal(Lesson::timeslot),\n",
+ " Joiners.equal(Lesson::studentGroup)\n",
+ " )\n",
+ " .penalize(HardSoftScore.ONE_HARD)\n",
+ " .asConstraint(\"Student group conflict\");\n",
+ " }\n",
+ "\n",
+ " fun teacherRoomStability(constraintFactory: ConstraintFactory): Constraint {\n",
+ " // A teacher prefers to teach in a single room.\n",
+ " return constraintFactory\n",
+ " .forEachUniquePair(\n",
+ " Lesson::class.java,\n",
+ " Joiners.equal(Lesson::teacher)\n",
+ " )\n",
+ " .filter { lesson1: Lesson, lesson2: Lesson -> lesson1.room !== lesson2.room }\n",
+ " .penalize(HardSoftScore.ONE_SOFT)\n",
+ " .asConstraint(\"Teacher room stability\");\n",
+ " }\n",
+ "\n",
+ " fun teacherTimeEfficiency(constraintFactory: ConstraintFactory): Constraint {\n",
+ " // A teacher prefers to teach sequential lessons and dislikes gaps between lessons.\n",
+ " return constraintFactory\n",
+ " .forEach(Lesson::class.java)\n",
+ " .join(Lesson::class.java,\n",
+ " Joiners.equal(Lesson::teacher),\n",
+ " Joiners.equal { lesson: Lesson -> lesson.timeslot?.dayOfWeek })\n",
+ " .filter { lesson1: Lesson, lesson2: Lesson ->\n",
+ " val between = Duration.between(\n",
+ " lesson1.timeslot?.endTime,\n",
+ " lesson2.timeslot?.startTime\n",
+ " )\n",
+ " !between.isNegative && between.compareTo(Duration.ofMinutes(30)) <= 0\n",
+ " }\n",
+ " .reward(HardSoftScore.ONE_SOFT)\n",
+ " .asConstraint(\"Teacher time efficiency\");\n",
+ " }\n",
+ "\n",
+ " fun studentGroupSubjectVariety(constraintFactory: ConstraintFactory): Constraint {\n",
+ " // A student group dislikes sequential lessons on the same subject.\n",
+ " return constraintFactory\n",
+ " .forEach(Lesson::class.java)\n",
+ " .join(Lesson::class.java,\n",
+ " Joiners.equal(Lesson::subject),\n",
+ " Joiners.equal(Lesson::studentGroup),\n",
+ " Joiners.equal { lesson: Lesson -> lesson.timeslot?.dayOfWeek })\n",
+ " .filter { lesson1: Lesson, lesson2: Lesson ->\n",
+ " val between = Duration.between(\n",
+ " lesson1.timeslot?.endTime,\n",
+ " lesson2.timeslot?.startTime\n",
+ " )\n",
+ " !between.isNegative && between.compareTo(Duration.ofMinutes(30)) <= 0\n",
+ " }\n",
+ " .penalize(HardSoftScore.ONE_SOFT)\n",
+ " .asConstraint(\"Student group subject variety\");\n",
+ " }\n",
+ "\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.730088133Z",
+ "start_time": "2023-10-30T21:01:02.386917608Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "### TimeTable\n",
+ "\n",
+ "The timetable class represents a single dataset, typically a single school:"
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 79,
+ "outputs": [],
+ "source": [
+ "import ai.timefold.solver.core.api.domain.solution.PlanningEntityCollectionProperty\n",
+ "import ai.timefold.solver.core.api.domain.solution.PlanningScore\n",
+ "import ai.timefold.solver.core.api.domain.solution.PlanningSolution\n",
+ "import ai.timefold.solver.core.api.domain.solution.ProblemFactCollectionProperty\n",
+ "import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider\n",
+ "import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore\n",
+ "\n",
+ "@PlanningSolution\n",
+ "class TimeTable {\n",
+ "\n",
+ " @ProblemFactCollectionProperty\n",
+ " @ValueRangeProvider\n",
+ " lateinit var timeslots: List<Timeslot>\n",
+ " @ProblemFactCollectionProperty\n",
+ " @ValueRangeProvider\n",
+ " lateinit var rooms: List<Room>\n",
+ " @PlanningEntityCollectionProperty\n",
+ " lateinit var lessons: List<Lesson>\n",
+ "\n",
+ " @PlanningScore\n",
+ " var score: HardSoftScore? = null\n",
+ "\n",
+ " // No-arg constructor required for Timefold\n",
+ " constructor() {}\n",
+ "\n",
+ " constructor(timeslots: List<Timeslot>, rooms: List<Room>, lessons: List<Lesson>) {\n",
+ " this.timeslots = timeslots\n",
+ " this.rooms = rooms\n",
+ " this.lessons = lessons\n",
+ " }\n",
+ "\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.786897117Z",
+ "start_time": "2023-10-30T21:01:02.729363789Z"
+ }
+ } | Dtto. |
timefold-quickstarts | github_2023 | others | 139 | TimefoldAI | triceo | @@ -0,0 +1,641 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "source": [
+ "# School timetabling kotlin notebook\n",
+ "\n",
+ "This Kotlin Notebook solves the school timetabling problem with [Timefold](https://timefold.ai], the open source planning solver AI.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Dependencies\n",
+ "\n",
+ "Add the Timefold solver dependency:"
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 74,
+ "outputs": [],
+ "source": [
+ "@file:DependsOn(\"ai.timefold.solver:timefold-solver-core:1.3.0\")"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.229748528Z",
+ "start_time": "2023-10-30T21:00:59.103295531Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "\n",
+ "## Domain\n",
+ "\n",
+ "Create the domain classes:\n",
+ "\n",
+ "### Room\n",
+ "\n",
+ "A school has rooms."
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 75,
+ "outputs": [],
+ "source": [
+ "class Room {\n",
+ "\n",
+ " var name: String\n",
+ "\n",
+ " constructor(name: String) {\n",
+ " this.name = name\n",
+ " }\n",
+ "\n",
+ " override fun toString(): String = name\n",
+ "\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.274546567Z",
+ "start_time": "2023-10-30T21:01:02.228839493Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "### Timeslot\n",
+ "\n",
+ "A school timetable has timeslots."
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 76,
+ "outputs": [],
+ "source": [
+ "import java.time.DayOfWeek\n",
+ "import java.time.LocalTime\n",
+ "\n",
+ "class Timeslot {\n",
+ "\n",
+ " var dayOfWeek: DayOfWeek\n",
+ " var startTime: LocalTime\n",
+ " var endTime: LocalTime\n",
+ "\n",
+ " constructor(dayOfWeek: DayOfWeek, startTime: LocalTime, endTime: LocalTime) {\n",
+ " this.dayOfWeek = dayOfWeek\n",
+ " this.startTime = startTime\n",
+ " this.endTime = endTime\n",
+ " }\n",
+ "\n",
+ " override fun toString(): String = \"$dayOfWeek $startTime\"\n",
+ "\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.321779372Z",
+ "start_time": "2023-10-30T21:01:02.274072196Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "### Lesson\n",
+ "\n",
+ "Each lesson must be assigned to a timeslot and to a room by the solver."
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 77,
+ "outputs": [],
+ "source": [
+ "import ai.timefold.solver.core.api.domain.entity.PlanningEntity\n",
+ "import ai.timefold.solver.core.api.domain.lookup.PlanningId\n",
+ "import ai.timefold.solver.core.api.domain.variable.PlanningVariable\n",
+ "\n",
+ "@PlanningEntity\n",
+ "class Lesson {\n",
+ "\n",
+ " @PlanningId\n",
+ " var id: Long? = null\n",
+ " lateinit var subject: String\n",
+ " lateinit var teacher: String\n",
+ " lateinit var studentGroup: String\n",
+ "\n",
+ " @PlanningVariable\n",
+ " var timeslot: Timeslot? = null\n",
+ " @PlanningVariable\n",
+ " var room: Room? = null\n",
+ "\n",
+ " // No-arg constructor required for Timefold\n",
+ " constructor()\n",
+ "\n",
+ " constructor(id: Long, subject: String, teacher: String, studentGroup: String) {\n",
+ " this.id = id\n",
+ " this.subject = subject\n",
+ " this.teacher = teacher\n",
+ " this.studentGroup = studentGroup\n",
+ " }\n",
+ "\n",
+ "\n",
+ " override fun toString(): String = \"$subject\"\n",
+ "\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.387536998Z",
+ "start_time": "2023-10-30T21:01:02.321150649Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "## Constraints\n",
+ "\n",
+ "The solver must take into account hard and soft constraints:"
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 78,
+ "outputs": [],
+ "source": [
+ "import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore\n",
+ "import ai.timefold.solver.core.api.score.stream.Constraint\n",
+ "import ai.timefold.solver.core.api.score.stream.ConstraintFactory\n",
+ "import ai.timefold.solver.core.api.score.stream.ConstraintProvider\n",
+ "import ai.timefold.solver.core.api.score.stream.Joiners\n",
+ "import java.time.Duration\n",
+ "\n",
+ "class TimeTableConstraintProvider : ConstraintProvider {\n",
+ "\n",
+ " override fun defineConstraints(constraintFactory: ConstraintFactory): Array<Constraint>? {\n",
+ " return arrayOf(\n",
+ " // Hard constraints\n",
+ " roomConflict(constraintFactory),\n",
+ " teacherConflict(constraintFactory),\n",
+ " studentGroupConflict(constraintFactory),\n",
+ " // Soft constraints\n",
+ " teacherRoomStability(constraintFactory),\n",
+ " teacherTimeEfficiency(constraintFactory),\n",
+ " studentGroupSubjectVariety(constraintFactory)\n",
+ " )\n",
+ " }\n",
+ "\n",
+ " fun roomConflict(constraintFactory: ConstraintFactory): Constraint {\n",
+ " // A room can accommodate at most one lesson at the same time.\n",
+ " return constraintFactory\n",
+ " // Select each pair of 2 different lessons ...\n",
+ " .forEachUniquePair(\n",
+ " Lesson::class.java,\n",
+ " // ... in the same timeslot ...\n",
+ " Joiners.equal(Lesson::timeslot),\n",
+ " // ... in the same room ...\n",
+ " Joiners.equal(Lesson::room)\n",
+ " )\n",
+ " // ... and penalize each pair with a hard weight.\n",
+ " .penalize(HardSoftScore.ONE_HARD)\n",
+ " .asConstraint(\"Room conflict\");\n",
+ " }\n",
+ "\n",
+ " fun teacherConflict(constraintFactory: ConstraintFactory): Constraint {\n",
+ " // A teacher can teach at most one lesson at the same time.\n",
+ " return constraintFactory\n",
+ " .forEachUniquePair(\n",
+ " Lesson::class.java,\n",
+ " Joiners.equal(Lesson::timeslot),\n",
+ " Joiners.equal(Lesson::teacher)\n",
+ " )\n",
+ " .penalize(HardSoftScore.ONE_HARD)\n",
+ " .asConstraint(\"Teacher conflict\");\n",
+ " }\n",
+ "\n",
+ " fun studentGroupConflict(constraintFactory: ConstraintFactory): Constraint {\n",
+ " // A student can attend at most one lesson at the same time.\n",
+ " return constraintFactory\n",
+ " .forEachUniquePair(\n",
+ " Lesson::class.java,\n",
+ " Joiners.equal(Lesson::timeslot),\n",
+ " Joiners.equal(Lesson::studentGroup)\n",
+ " )\n",
+ " .penalize(HardSoftScore.ONE_HARD)\n",
+ " .asConstraint(\"Student group conflict\");\n",
+ " }\n",
+ "\n",
+ " fun teacherRoomStability(constraintFactory: ConstraintFactory): Constraint {\n",
+ " // A teacher prefers to teach in a single room.\n",
+ " return constraintFactory\n",
+ " .forEachUniquePair(\n",
+ " Lesson::class.java,\n",
+ " Joiners.equal(Lesson::teacher)\n",
+ " )\n",
+ " .filter { lesson1: Lesson, lesson2: Lesson -> lesson1.room !== lesson2.room }\n",
+ " .penalize(HardSoftScore.ONE_SOFT)\n",
+ " .asConstraint(\"Teacher room stability\");\n",
+ " }\n",
+ "\n",
+ " fun teacherTimeEfficiency(constraintFactory: ConstraintFactory): Constraint {\n",
+ " // A teacher prefers to teach sequential lessons and dislikes gaps between lessons.\n",
+ " return constraintFactory\n",
+ " .forEach(Lesson::class.java)\n",
+ " .join(Lesson::class.java,\n",
+ " Joiners.equal(Lesson::teacher),\n",
+ " Joiners.equal { lesson: Lesson -> lesson.timeslot?.dayOfWeek })\n",
+ " .filter { lesson1: Lesson, lesson2: Lesson ->\n",
+ " val between = Duration.between(\n",
+ " lesson1.timeslot?.endTime,\n",
+ " lesson2.timeslot?.startTime\n",
+ " )\n",
+ " !between.isNegative && between.compareTo(Duration.ofMinutes(30)) <= 0\n",
+ " }\n",
+ " .reward(HardSoftScore.ONE_SOFT)\n",
+ " .asConstraint(\"Teacher time efficiency\");\n",
+ " }\n",
+ "\n",
+ " fun studentGroupSubjectVariety(constraintFactory: ConstraintFactory): Constraint {\n",
+ " // A student group dislikes sequential lessons on the same subject.\n",
+ " return constraintFactory\n",
+ " .forEach(Lesson::class.java)\n",
+ " .join(Lesson::class.java,\n",
+ " Joiners.equal(Lesson::subject),\n",
+ " Joiners.equal(Lesson::studentGroup),\n",
+ " Joiners.equal { lesson: Lesson -> lesson.timeslot?.dayOfWeek })\n",
+ " .filter { lesson1: Lesson, lesson2: Lesson ->\n",
+ " val between = Duration.between(\n",
+ " lesson1.timeslot?.endTime,\n",
+ " lesson2.timeslot?.startTime\n",
+ " )\n",
+ " !between.isNegative && between.compareTo(Duration.ofMinutes(30)) <= 0\n",
+ " }\n",
+ " .penalize(HardSoftScore.ONE_SOFT)\n",
+ " .asConstraint(\"Student group subject variety\");\n",
+ " }\n",
+ "\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.730088133Z",
+ "start_time": "2023-10-30T21:01:02.386917608Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "### TimeTable\n",
+ "\n",
+ "The timetable class represents a single dataset, typically a single school:"
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 79,
+ "outputs": [],
+ "source": [
+ "import ai.timefold.solver.core.api.domain.solution.PlanningEntityCollectionProperty\n",
+ "import ai.timefold.solver.core.api.domain.solution.PlanningScore\n",
+ "import ai.timefold.solver.core.api.domain.solution.PlanningSolution\n",
+ "import ai.timefold.solver.core.api.domain.solution.ProblemFactCollectionProperty\n",
+ "import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider\n",
+ "import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore\n",
+ "\n",
+ "@PlanningSolution\n",
+ "class TimeTable {\n",
+ "\n",
+ " @ProblemFactCollectionProperty\n",
+ " @ValueRangeProvider\n",
+ " lateinit var timeslots: List<Timeslot>\n",
+ " @ProblemFactCollectionProperty\n",
+ " @ValueRangeProvider\n",
+ " lateinit var rooms: List<Room>\n",
+ " @PlanningEntityCollectionProperty\n",
+ " lateinit var lessons: List<Lesson>\n",
+ "\n",
+ " @PlanningScore\n",
+ " var score: HardSoftScore? = null\n",
+ "\n",
+ " // No-arg constructor required for Timefold\n",
+ " constructor() {}\n",
+ "\n",
+ " constructor(timeslots: List<Timeslot>, rooms: List<Room>, lessons: List<Lesson>) {\n",
+ " this.timeslots = timeslots\n",
+ " this.rooms = rooms\n",
+ " this.lessons = lessons\n",
+ " }\n",
+ "\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.786897117Z",
+ "start_time": "2023-10-30T21:01:02.729363789Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "## Data generator\n",
+ "\n",
+ "Generate some data for a small school timetable:"
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 80,
+ "outputs": [],
+ "source": [
+ "fun generateDemoData(): TimeTable {\n",
+ " val timeslots: MutableList<Timeslot> = mutableListOf(\n",
+ " Timeslot(DayOfWeek.MONDAY, LocalTime.of(8, 30), LocalTime.of(9, 30)),\n",
+ " Timeslot(DayOfWeek.MONDAY, LocalTime.of(9, 30), LocalTime.of(10, 30)),\n",
+ " Timeslot(DayOfWeek.MONDAY, LocalTime.of(10, 30), LocalTime.of(11, 30)),\n",
+ " Timeslot(DayOfWeek.MONDAY, LocalTime.of(13, 30), LocalTime.of(14, 30)),\n",
+ " Timeslot(DayOfWeek.MONDAY, LocalTime.of(14, 30), LocalTime.of(15, 30)),\n",
+ " \n",
+ " Timeslot(DayOfWeek.TUESDAY, LocalTime.of(8, 30), LocalTime.of(9, 30)),\n",
+ " Timeslot(DayOfWeek.TUESDAY, LocalTime.of(9, 30), LocalTime.of(10, 30)),\n",
+ " Timeslot(DayOfWeek.TUESDAY, LocalTime.of(10, 30), LocalTime.of(11, 30)),\n",
+ " Timeslot(DayOfWeek.TUESDAY, LocalTime.of(13, 30), LocalTime.of(14, 30)),\n",
+ " Timeslot(DayOfWeek.TUESDAY, LocalTime.of(14, 30), LocalTime.of(15, 30)))\n",
+ " \n",
+ " \n",
+ " val rooms: MutableList<Room> = mutableListOf(\n",
+ " Room(\"Room A\"),\n",
+ " Room(\"Room B\"),\n",
+ " Room(\"Room C\"))\n",
+ " \n",
+ " var nextId: Long = 0\n",
+ " val lessons: MutableList<Lesson> = mutableListOf(\n",
+ " Lesson(nextId++, \"Math\", \"A. Turing\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"Math\", \"A. Turing\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"Physics\", \"M. Curie\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"Chemistry\", \"M. Curie\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"Biology\", \"C. Darwin\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"History\", \"I. Jones\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"English\", \"I. Jones\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"English\", \"I. Jones\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"Spanish\", \"P. Cruz\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"Spanish\", \"P. Cruz\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"Math\", \"A. Turing\", \"10th grade\"),\n",
+ " Lesson(nextId++, \"Math\", \"A. Turing\", \"10th grade\"),\n",
+ " Lesson(nextId++, \"Math\", \"A. Turing\", \"10th grade\"),\n",
+ " Lesson(nextId++, \"Physics\", \"M. Curie\", \"10th grade\"),\n",
+ " Lesson(nextId++, \"Chemistry\", \"M. Curie\", \"10th grade\"),\n",
+ " Lesson(nextId++, \"French\", \"M. Curie\", \"10th grade\"),\n",
+ " Lesson(nextId++, \"Geography\", \"C. Darwin\", \"10th grade\"),\n",
+ " Lesson(nextId++, \"History\", \"I. Jones\", \"10th grade\"),\n",
+ " Lesson(nextId++, \"English\", \"P. Cruz\", \"10th grade\"),\n",
+ " Lesson(nextId++, \"Spanish\", \"P. Cruz\", \"10th grade\"))\n",
+ " return TimeTable(timeslots, rooms, lessons)\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.992053111Z",
+ "start_time": "2023-10-30T21:01:02.786173253Z"
+ }
+ } | Dtto. |
timefold-quickstarts | github_2023 | others | 139 | TimefoldAI | triceo | @@ -0,0 +1,641 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "source": [
+ "# School timetabling kotlin notebook\n",
+ "\n",
+ "This Kotlin Notebook solves the school timetabling problem with [Timefold](https://timefold.ai], the open source planning solver AI.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Dependencies\n",
+ "\n",
+ "Add the Timefold solver dependency:"
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 74,
+ "outputs": [],
+ "source": [
+ "@file:DependsOn(\"ai.timefold.solver:timefold-solver-core:1.3.0\")"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.229748528Z",
+ "start_time": "2023-10-30T21:00:59.103295531Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "\n",
+ "## Domain\n",
+ "\n",
+ "Create the domain classes:\n",
+ "\n",
+ "### Room\n",
+ "\n",
+ "A school has rooms."
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 75,
+ "outputs": [],
+ "source": [
+ "class Room {\n",
+ "\n",
+ " var name: String\n",
+ "\n",
+ " constructor(name: String) {\n",
+ " this.name = name\n",
+ " }\n",
+ "\n",
+ " override fun toString(): String = name\n",
+ "\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.274546567Z",
+ "start_time": "2023-10-30T21:01:02.228839493Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "### Timeslot\n",
+ "\n",
+ "A school timetable has timeslots."
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 76,
+ "outputs": [],
+ "source": [
+ "import java.time.DayOfWeek\n",
+ "import java.time.LocalTime\n",
+ "\n",
+ "class Timeslot {\n",
+ "\n",
+ " var dayOfWeek: DayOfWeek\n",
+ " var startTime: LocalTime\n",
+ " var endTime: LocalTime\n",
+ "\n",
+ " constructor(dayOfWeek: DayOfWeek, startTime: LocalTime, endTime: LocalTime) {\n",
+ " this.dayOfWeek = dayOfWeek\n",
+ " this.startTime = startTime\n",
+ " this.endTime = endTime\n",
+ " }\n",
+ "\n",
+ " override fun toString(): String = \"$dayOfWeek $startTime\"\n",
+ "\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.321779372Z",
+ "start_time": "2023-10-30T21:01:02.274072196Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "### Lesson\n",
+ "\n",
+ "Each lesson must be assigned to a timeslot and to a room by the solver."
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 77,
+ "outputs": [],
+ "source": [
+ "import ai.timefold.solver.core.api.domain.entity.PlanningEntity\n",
+ "import ai.timefold.solver.core.api.domain.lookup.PlanningId\n",
+ "import ai.timefold.solver.core.api.domain.variable.PlanningVariable\n",
+ "\n",
+ "@PlanningEntity\n",
+ "class Lesson {\n",
+ "\n",
+ " @PlanningId\n",
+ " var id: Long? = null\n",
+ " lateinit var subject: String\n",
+ " lateinit var teacher: String\n",
+ " lateinit var studentGroup: String\n",
+ "\n",
+ " @PlanningVariable\n",
+ " var timeslot: Timeslot? = null\n",
+ " @PlanningVariable\n",
+ " var room: Room? = null\n",
+ "\n",
+ " // No-arg constructor required for Timefold\n",
+ " constructor()\n",
+ "\n",
+ " constructor(id: Long, subject: String, teacher: String, studentGroup: String) {\n",
+ " this.id = id\n",
+ " this.subject = subject\n",
+ " this.teacher = teacher\n",
+ " this.studentGroup = studentGroup\n",
+ " }\n",
+ "\n",
+ "\n",
+ " override fun toString(): String = \"$subject\"\n",
+ "\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.387536998Z",
+ "start_time": "2023-10-30T21:01:02.321150649Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "## Constraints\n",
+ "\n",
+ "The solver must take into account hard and soft constraints:"
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 78,
+ "outputs": [],
+ "source": [
+ "import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore\n",
+ "import ai.timefold.solver.core.api.score.stream.Constraint\n",
+ "import ai.timefold.solver.core.api.score.stream.ConstraintFactory\n",
+ "import ai.timefold.solver.core.api.score.stream.ConstraintProvider\n",
+ "import ai.timefold.solver.core.api.score.stream.Joiners\n",
+ "import java.time.Duration\n",
+ "\n",
+ "class TimeTableConstraintProvider : ConstraintProvider {\n",
+ "\n",
+ " override fun defineConstraints(constraintFactory: ConstraintFactory): Array<Constraint>? {\n",
+ " return arrayOf(\n",
+ " // Hard constraints\n",
+ " roomConflict(constraintFactory),\n",
+ " teacherConflict(constraintFactory),\n",
+ " studentGroupConflict(constraintFactory),\n",
+ " // Soft constraints\n",
+ " teacherRoomStability(constraintFactory),\n",
+ " teacherTimeEfficiency(constraintFactory),\n",
+ " studentGroupSubjectVariety(constraintFactory)\n",
+ " )\n",
+ " }\n",
+ "\n",
+ " fun roomConflict(constraintFactory: ConstraintFactory): Constraint {\n",
+ " // A room can accommodate at most one lesson at the same time.\n",
+ " return constraintFactory\n",
+ " // Select each pair of 2 different lessons ...\n",
+ " .forEachUniquePair(\n",
+ " Lesson::class.java,\n",
+ " // ... in the same timeslot ...\n",
+ " Joiners.equal(Lesson::timeslot),\n",
+ " // ... in the same room ...\n",
+ " Joiners.equal(Lesson::room)\n",
+ " )\n",
+ " // ... and penalize each pair with a hard weight.\n",
+ " .penalize(HardSoftScore.ONE_HARD)\n",
+ " .asConstraint(\"Room conflict\");\n",
+ " }\n",
+ "\n",
+ " fun teacherConflict(constraintFactory: ConstraintFactory): Constraint {\n",
+ " // A teacher can teach at most one lesson at the same time.\n",
+ " return constraintFactory\n",
+ " .forEachUniquePair(\n",
+ " Lesson::class.java,\n",
+ " Joiners.equal(Lesson::timeslot),\n",
+ " Joiners.equal(Lesson::teacher)\n",
+ " )\n",
+ " .penalize(HardSoftScore.ONE_HARD)\n",
+ " .asConstraint(\"Teacher conflict\");\n",
+ " }\n",
+ "\n",
+ " fun studentGroupConflict(constraintFactory: ConstraintFactory): Constraint {\n",
+ " // A student can attend at most one lesson at the same time.\n",
+ " return constraintFactory\n",
+ " .forEachUniquePair(\n",
+ " Lesson::class.java,\n",
+ " Joiners.equal(Lesson::timeslot),\n",
+ " Joiners.equal(Lesson::studentGroup)\n",
+ " )\n",
+ " .penalize(HardSoftScore.ONE_HARD)\n",
+ " .asConstraint(\"Student group conflict\");\n",
+ " }\n",
+ "\n",
+ " fun teacherRoomStability(constraintFactory: ConstraintFactory): Constraint {\n",
+ " // A teacher prefers to teach in a single room.\n",
+ " return constraintFactory\n",
+ " .forEachUniquePair(\n",
+ " Lesson::class.java,\n",
+ " Joiners.equal(Lesson::teacher)\n",
+ " )\n",
+ " .filter { lesson1: Lesson, lesson2: Lesson -> lesson1.room !== lesson2.room }\n",
+ " .penalize(HardSoftScore.ONE_SOFT)\n",
+ " .asConstraint(\"Teacher room stability\");\n",
+ " }\n",
+ "\n",
+ " fun teacherTimeEfficiency(constraintFactory: ConstraintFactory): Constraint {\n",
+ " // A teacher prefers to teach sequential lessons and dislikes gaps between lessons.\n",
+ " return constraintFactory\n",
+ " .forEach(Lesson::class.java)\n",
+ " .join(Lesson::class.java,\n",
+ " Joiners.equal(Lesson::teacher),\n",
+ " Joiners.equal { lesson: Lesson -> lesson.timeslot?.dayOfWeek })\n",
+ " .filter { lesson1: Lesson, lesson2: Lesson ->\n",
+ " val between = Duration.between(\n",
+ " lesson1.timeslot?.endTime,\n",
+ " lesson2.timeslot?.startTime\n",
+ " )\n",
+ " !between.isNegative && between.compareTo(Duration.ofMinutes(30)) <= 0\n",
+ " }\n",
+ " .reward(HardSoftScore.ONE_SOFT)\n",
+ " .asConstraint(\"Teacher time efficiency\");\n",
+ " }\n",
+ "\n",
+ " fun studentGroupSubjectVariety(constraintFactory: ConstraintFactory): Constraint {\n",
+ " // A student group dislikes sequential lessons on the same subject.\n",
+ " return constraintFactory\n",
+ " .forEach(Lesson::class.java)\n",
+ " .join(Lesson::class.java,\n",
+ " Joiners.equal(Lesson::subject),\n",
+ " Joiners.equal(Lesson::studentGroup),\n",
+ " Joiners.equal { lesson: Lesson -> lesson.timeslot?.dayOfWeek })\n",
+ " .filter { lesson1: Lesson, lesson2: Lesson ->\n",
+ " val between = Duration.between(\n",
+ " lesson1.timeslot?.endTime,\n",
+ " lesson2.timeslot?.startTime\n",
+ " )\n",
+ " !between.isNegative && between.compareTo(Duration.ofMinutes(30)) <= 0\n",
+ " }\n",
+ " .penalize(HardSoftScore.ONE_SOFT)\n",
+ " .asConstraint(\"Student group subject variety\");\n",
+ " }\n",
+ "\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.730088133Z",
+ "start_time": "2023-10-30T21:01:02.386917608Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "### TimeTable\n",
+ "\n",
+ "The timetable class represents a single dataset, typically a single school:"
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 79,
+ "outputs": [],
+ "source": [
+ "import ai.timefold.solver.core.api.domain.solution.PlanningEntityCollectionProperty\n",
+ "import ai.timefold.solver.core.api.domain.solution.PlanningScore\n",
+ "import ai.timefold.solver.core.api.domain.solution.PlanningSolution\n",
+ "import ai.timefold.solver.core.api.domain.solution.ProblemFactCollectionProperty\n",
+ "import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider\n",
+ "import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore\n",
+ "\n",
+ "@PlanningSolution\n",
+ "class TimeTable {\n",
+ "\n",
+ " @ProblemFactCollectionProperty\n",
+ " @ValueRangeProvider\n",
+ " lateinit var timeslots: List<Timeslot>\n",
+ " @ProblemFactCollectionProperty\n",
+ " @ValueRangeProvider\n",
+ " lateinit var rooms: List<Room>\n",
+ " @PlanningEntityCollectionProperty\n",
+ " lateinit var lessons: List<Lesson>\n",
+ "\n",
+ " @PlanningScore\n",
+ " var score: HardSoftScore? = null\n",
+ "\n",
+ " // No-arg constructor required for Timefold\n",
+ " constructor() {}\n",
+ "\n",
+ " constructor(timeslots: List<Timeslot>, rooms: List<Room>, lessons: List<Lesson>) {\n",
+ " this.timeslots = timeslots\n",
+ " this.rooms = rooms\n",
+ " this.lessons = lessons\n",
+ " }\n",
+ "\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.786897117Z",
+ "start_time": "2023-10-30T21:01:02.729363789Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "## Data generator\n",
+ "\n",
+ "Generate some data for a small school timetable:"
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 80,
+ "outputs": [],
+ "source": [
+ "fun generateDemoData(): TimeTable {\n",
+ " val timeslots: MutableList<Timeslot> = mutableListOf(\n",
+ " Timeslot(DayOfWeek.MONDAY, LocalTime.of(8, 30), LocalTime.of(9, 30)),\n",
+ " Timeslot(DayOfWeek.MONDAY, LocalTime.of(9, 30), LocalTime.of(10, 30)),\n",
+ " Timeslot(DayOfWeek.MONDAY, LocalTime.of(10, 30), LocalTime.of(11, 30)),\n",
+ " Timeslot(DayOfWeek.MONDAY, LocalTime.of(13, 30), LocalTime.of(14, 30)),\n",
+ " Timeslot(DayOfWeek.MONDAY, LocalTime.of(14, 30), LocalTime.of(15, 30)),\n",
+ " \n",
+ " Timeslot(DayOfWeek.TUESDAY, LocalTime.of(8, 30), LocalTime.of(9, 30)),\n",
+ " Timeslot(DayOfWeek.TUESDAY, LocalTime.of(9, 30), LocalTime.of(10, 30)),\n",
+ " Timeslot(DayOfWeek.TUESDAY, LocalTime.of(10, 30), LocalTime.of(11, 30)),\n",
+ " Timeslot(DayOfWeek.TUESDAY, LocalTime.of(13, 30), LocalTime.of(14, 30)),\n",
+ " Timeslot(DayOfWeek.TUESDAY, LocalTime.of(14, 30), LocalTime.of(15, 30)))\n",
+ " \n",
+ " \n",
+ " val rooms: MutableList<Room> = mutableListOf(\n",
+ " Room(\"Room A\"),\n",
+ " Room(\"Room B\"),\n",
+ " Room(\"Room C\"))\n",
+ " \n",
+ " var nextId: Long = 0\n",
+ " val lessons: MutableList<Lesson> = mutableListOf(\n",
+ " Lesson(nextId++, \"Math\", \"A. Turing\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"Math\", \"A. Turing\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"Physics\", \"M. Curie\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"Chemistry\", \"M. Curie\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"Biology\", \"C. Darwin\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"History\", \"I. Jones\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"English\", \"I. Jones\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"English\", \"I. Jones\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"Spanish\", \"P. Cruz\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"Spanish\", \"P. Cruz\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"Math\", \"A. Turing\", \"10th grade\"),\n",
+ " Lesson(nextId++, \"Math\", \"A. Turing\", \"10th grade\"),\n",
+ " Lesson(nextId++, \"Math\", \"A. Turing\", \"10th grade\"),\n",
+ " Lesson(nextId++, \"Physics\", \"M. Curie\", \"10th grade\"),\n",
+ " Lesson(nextId++, \"Chemistry\", \"M. Curie\", \"10th grade\"),\n",
+ " Lesson(nextId++, \"French\", \"M. Curie\", \"10th grade\"),\n",
+ " Lesson(nextId++, \"Geography\", \"C. Darwin\", \"10th grade\"),\n",
+ " Lesson(nextId++, \"History\", \"I. Jones\", \"10th grade\"),\n",
+ " Lesson(nextId++, \"English\", \"P. Cruz\", \"10th grade\"),\n",
+ " Lesson(nextId++, \"Spanish\", \"P. Cruz\", \"10th grade\"))\n",
+ " return TimeTable(timeslots, rooms, lessons)\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.992053111Z",
+ "start_time": "2023-10-30T21:01:02.786173253Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "## Visualize the result\n",
+ "\n",
+ "Print the timetable to the console:"
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 81,
+ "outputs": [],
+ "source": [
+ "fun printTimeTable(timeTable: TimeTable) {\n",
+ " println(\"\")\n",
+ "\n",
+ " val lessonMap = timeTable.lessons.groupBy { lesson -> Pair(lesson.timeslot, lesson.room) }\n",
+ "\n",
+ " print(\"| \")\n",
+ " for (room in timeTable.rooms) {\n",
+ " print(\"| \" + String.format(\"%-10s\", room.name) + \" \") \n",
+ " }\n",
+ " println(\"|\") \n",
+ " println(\"|\" + \"------------|\".repeat(timeTable.rooms.size + 1)) \n",
+ " \n",
+ " for (timeslot in timeTable.timeslots) {\n",
+ " print(\"| \" + String.format(\"%-10s\", \"\" + timeslot.dayOfWeek.toString().subSequence(0, 3) + \" \" + timeslot.startTime) + \" \")\n",
+ " for (room in timeTable.rooms) {\n",
+ " print(\"| \") \n",
+ " val cellLessons = lessonMap.get(Pair(timeslot, room)) ?: emptyList()\n",
+ " print(String.format(\"%-10s\", cellLessons.map { lesson -> lesson.subject }.joinToString(\", \")))\n",
+ " print(\" \")\n",
+ " }\n",
+ " println(\"|\")\n",
+ " print(\"| \" + String.format(\"%-10s\", \"\") + \" \")\n",
+ " for (room in timeTable.rooms) {\n",
+ " print(\"| \") \n",
+ " val cellLessons = lessonMap.get(Pair(timeslot, room)) ?: emptyList()\n",
+ " print(String.format(\"%-10s\", cellLessons.map { lesson -> lesson.teacher }.joinToString(\", \")))\n",
+ " print(\" \")\n",
+ " }\n",
+ " println(\"|\")\n",
+ " print(\"| \" + String.format(\"%-10s\", \"\") + \" \")\n",
+ " for (room in timeTable.rooms) {\n",
+ " print(\"| \") \n",
+ " val cellLessons = lessonMap.get(Pair(timeslot, room)) ?: emptyList()\n",
+ " print(String.format(\"%-10s\", cellLessons.map { lesson -> lesson.studentGroup }.joinToString(\", \")))\n",
+ " print(\" \")\n",
+ " }\n",
+ " println(\"|\") \n",
+ " println(\"|\" + \"------------|\".repeat(timeTable.rooms.size + 1)) \n",
+ " }\n",
+ " val unassignedLessons = lessonMap.get(Pair(null, null))\n",
+ " if (unassignedLessons != null && unassignedLessons.isNotEmpty()) {\n",
+ " println(\"\")\n",
+ " println(\"Unassigned lessons\")\n",
+ " for (lesson: Lesson in unassignedLessons) {\n",
+ " println(\" \" + lesson.subject + \" - \" + lesson.teacher + \" - \" + lesson.studentGroup)\n",
+ " }\n",
+ " }\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:03.344553989Z",
+ "start_time": "2023-10-30T21:01:02.991344533Z"
+ }
+ } | Dtto. |
timefold-quickstarts | github_2023 | others | 139 | TimefoldAI | triceo | @@ -0,0 +1,641 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "source": [
+ "# School timetabling kotlin notebook\n",
+ "\n",
+ "This Kotlin Notebook solves the school timetabling problem with [Timefold](https://timefold.ai], the open source planning solver AI.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Dependencies\n",
+ "\n",
+ "Add the Timefold solver dependency:"
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 74,
+ "outputs": [],
+ "source": [
+ "@file:DependsOn(\"ai.timefold.solver:timefold-solver-core:1.3.0\")"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.229748528Z",
+ "start_time": "2023-10-30T21:00:59.103295531Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "\n",
+ "## Domain\n",
+ "\n",
+ "Create the domain classes:\n",
+ "\n",
+ "### Room\n",
+ "\n",
+ "A school has rooms."
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 75,
+ "outputs": [],
+ "source": [
+ "class Room {\n",
+ "\n",
+ " var name: String\n",
+ "\n",
+ " constructor(name: String) {\n",
+ " this.name = name\n",
+ " }\n",
+ "\n",
+ " override fun toString(): String = name\n",
+ "\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.274546567Z",
+ "start_time": "2023-10-30T21:01:02.228839493Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "### Timeslot\n",
+ "\n",
+ "A school timetable has timeslots."
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 76,
+ "outputs": [],
+ "source": [
+ "import java.time.DayOfWeek\n",
+ "import java.time.LocalTime\n",
+ "\n",
+ "class Timeslot {\n",
+ "\n",
+ " var dayOfWeek: DayOfWeek\n",
+ " var startTime: LocalTime\n",
+ " var endTime: LocalTime\n",
+ "\n",
+ " constructor(dayOfWeek: DayOfWeek, startTime: LocalTime, endTime: LocalTime) {\n",
+ " this.dayOfWeek = dayOfWeek\n",
+ " this.startTime = startTime\n",
+ " this.endTime = endTime\n",
+ " }\n",
+ "\n",
+ " override fun toString(): String = \"$dayOfWeek $startTime\"\n",
+ "\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.321779372Z",
+ "start_time": "2023-10-30T21:01:02.274072196Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "### Lesson\n",
+ "\n",
+ "Each lesson must be assigned to a timeslot and to a room by the solver."
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 77,
+ "outputs": [],
+ "source": [
+ "import ai.timefold.solver.core.api.domain.entity.PlanningEntity\n",
+ "import ai.timefold.solver.core.api.domain.lookup.PlanningId\n",
+ "import ai.timefold.solver.core.api.domain.variable.PlanningVariable\n",
+ "\n",
+ "@PlanningEntity\n",
+ "class Lesson {\n",
+ "\n",
+ " @PlanningId\n",
+ " var id: Long? = null\n",
+ " lateinit var subject: String\n",
+ " lateinit var teacher: String\n",
+ " lateinit var studentGroup: String\n",
+ "\n",
+ " @PlanningVariable\n",
+ " var timeslot: Timeslot? = null\n",
+ " @PlanningVariable\n",
+ " var room: Room? = null\n",
+ "\n",
+ " // No-arg constructor required for Timefold\n",
+ " constructor()\n",
+ "\n",
+ " constructor(id: Long, subject: String, teacher: String, studentGroup: String) {\n",
+ " this.id = id\n",
+ " this.subject = subject\n",
+ " this.teacher = teacher\n",
+ " this.studentGroup = studentGroup\n",
+ " }\n",
+ "\n",
+ "\n",
+ " override fun toString(): String = \"$subject\"\n",
+ "\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.387536998Z",
+ "start_time": "2023-10-30T21:01:02.321150649Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "## Constraints\n",
+ "\n",
+ "The solver must take into account hard and soft constraints:"
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 78,
+ "outputs": [],
+ "source": [
+ "import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore\n",
+ "import ai.timefold.solver.core.api.score.stream.Constraint\n",
+ "import ai.timefold.solver.core.api.score.stream.ConstraintFactory\n",
+ "import ai.timefold.solver.core.api.score.stream.ConstraintProvider\n",
+ "import ai.timefold.solver.core.api.score.stream.Joiners\n",
+ "import java.time.Duration\n",
+ "\n",
+ "class TimeTableConstraintProvider : ConstraintProvider {\n",
+ "\n",
+ " override fun defineConstraints(constraintFactory: ConstraintFactory): Array<Constraint>? {\n",
+ " return arrayOf(\n",
+ " // Hard constraints\n",
+ " roomConflict(constraintFactory),\n",
+ " teacherConflict(constraintFactory),\n",
+ " studentGroupConflict(constraintFactory),\n",
+ " // Soft constraints\n",
+ " teacherRoomStability(constraintFactory),\n",
+ " teacherTimeEfficiency(constraintFactory),\n",
+ " studentGroupSubjectVariety(constraintFactory)\n",
+ " )\n",
+ " }\n",
+ "\n",
+ " fun roomConflict(constraintFactory: ConstraintFactory): Constraint {\n",
+ " // A room can accommodate at most one lesson at the same time.\n",
+ " return constraintFactory\n",
+ " // Select each pair of 2 different lessons ...\n",
+ " .forEachUniquePair(\n",
+ " Lesson::class.java,\n",
+ " // ... in the same timeslot ...\n",
+ " Joiners.equal(Lesson::timeslot),\n",
+ " // ... in the same room ...\n",
+ " Joiners.equal(Lesson::room)\n",
+ " )\n",
+ " // ... and penalize each pair with a hard weight.\n",
+ " .penalize(HardSoftScore.ONE_HARD)\n",
+ " .asConstraint(\"Room conflict\");\n",
+ " }\n",
+ "\n",
+ " fun teacherConflict(constraintFactory: ConstraintFactory): Constraint {\n",
+ " // A teacher can teach at most one lesson at the same time.\n",
+ " return constraintFactory\n",
+ " .forEachUniquePair(\n",
+ " Lesson::class.java,\n",
+ " Joiners.equal(Lesson::timeslot),\n",
+ " Joiners.equal(Lesson::teacher)\n",
+ " )\n",
+ " .penalize(HardSoftScore.ONE_HARD)\n",
+ " .asConstraint(\"Teacher conflict\");\n",
+ " }\n",
+ "\n",
+ " fun studentGroupConflict(constraintFactory: ConstraintFactory): Constraint {\n",
+ " // A student can attend at most one lesson at the same time.\n",
+ " return constraintFactory\n",
+ " .forEachUniquePair(\n",
+ " Lesson::class.java,\n",
+ " Joiners.equal(Lesson::timeslot),\n",
+ " Joiners.equal(Lesson::studentGroup)\n",
+ " )\n",
+ " .penalize(HardSoftScore.ONE_HARD)\n",
+ " .asConstraint(\"Student group conflict\");\n",
+ " }\n",
+ "\n",
+ " fun teacherRoomStability(constraintFactory: ConstraintFactory): Constraint {\n",
+ " // A teacher prefers to teach in a single room.\n",
+ " return constraintFactory\n",
+ " .forEachUniquePair(\n",
+ " Lesson::class.java,\n",
+ " Joiners.equal(Lesson::teacher)\n",
+ " )\n",
+ " .filter { lesson1: Lesson, lesson2: Lesson -> lesson1.room !== lesson2.room }\n",
+ " .penalize(HardSoftScore.ONE_SOFT)\n",
+ " .asConstraint(\"Teacher room stability\");\n",
+ " }\n",
+ "\n",
+ " fun teacherTimeEfficiency(constraintFactory: ConstraintFactory): Constraint {\n",
+ " // A teacher prefers to teach sequential lessons and dislikes gaps between lessons.\n",
+ " return constraintFactory\n",
+ " .forEach(Lesson::class.java)\n",
+ " .join(Lesson::class.java,\n",
+ " Joiners.equal(Lesson::teacher),\n",
+ " Joiners.equal { lesson: Lesson -> lesson.timeslot?.dayOfWeek })\n",
+ " .filter { lesson1: Lesson, lesson2: Lesson ->\n",
+ " val between = Duration.between(\n",
+ " lesson1.timeslot?.endTime,\n",
+ " lesson2.timeslot?.startTime\n",
+ " )\n",
+ " !between.isNegative && between.compareTo(Duration.ofMinutes(30)) <= 0\n",
+ " }\n",
+ " .reward(HardSoftScore.ONE_SOFT)\n",
+ " .asConstraint(\"Teacher time efficiency\");\n",
+ " }\n",
+ "\n",
+ " fun studentGroupSubjectVariety(constraintFactory: ConstraintFactory): Constraint {\n",
+ " // A student group dislikes sequential lessons on the same subject.\n",
+ " return constraintFactory\n",
+ " .forEach(Lesson::class.java)\n",
+ " .join(Lesson::class.java,\n",
+ " Joiners.equal(Lesson::subject),\n",
+ " Joiners.equal(Lesson::studentGroup),\n",
+ " Joiners.equal { lesson: Lesson -> lesson.timeslot?.dayOfWeek })\n",
+ " .filter { lesson1: Lesson, lesson2: Lesson ->\n",
+ " val between = Duration.between(\n",
+ " lesson1.timeslot?.endTime,\n",
+ " lesson2.timeslot?.startTime\n",
+ " )\n",
+ " !between.isNegative && between.compareTo(Duration.ofMinutes(30)) <= 0\n",
+ " }\n",
+ " .penalize(HardSoftScore.ONE_SOFT)\n",
+ " .asConstraint(\"Student group subject variety\");\n",
+ " }\n",
+ "\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.730088133Z",
+ "start_time": "2023-10-30T21:01:02.386917608Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "### TimeTable\n",
+ "\n",
+ "The timetable class represents a single dataset, typically a single school:"
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 79,
+ "outputs": [],
+ "source": [
+ "import ai.timefold.solver.core.api.domain.solution.PlanningEntityCollectionProperty\n",
+ "import ai.timefold.solver.core.api.domain.solution.PlanningScore\n",
+ "import ai.timefold.solver.core.api.domain.solution.PlanningSolution\n",
+ "import ai.timefold.solver.core.api.domain.solution.ProblemFactCollectionProperty\n",
+ "import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider\n",
+ "import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore\n",
+ "\n",
+ "@PlanningSolution\n",
+ "class TimeTable {\n",
+ "\n",
+ " @ProblemFactCollectionProperty\n",
+ " @ValueRangeProvider\n",
+ " lateinit var timeslots: List<Timeslot>\n",
+ " @ProblemFactCollectionProperty\n",
+ " @ValueRangeProvider\n",
+ " lateinit var rooms: List<Room>\n",
+ " @PlanningEntityCollectionProperty\n",
+ " lateinit var lessons: List<Lesson>\n",
+ "\n",
+ " @PlanningScore\n",
+ " var score: HardSoftScore? = null\n",
+ "\n",
+ " // No-arg constructor required for Timefold\n",
+ " constructor() {}\n",
+ "\n",
+ " constructor(timeslots: List<Timeslot>, rooms: List<Room>, lessons: List<Lesson>) {\n",
+ " this.timeslots = timeslots\n",
+ " this.rooms = rooms\n",
+ " this.lessons = lessons\n",
+ " }\n",
+ "\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.786897117Z",
+ "start_time": "2023-10-30T21:01:02.729363789Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "## Data generator\n",
+ "\n",
+ "Generate some data for a small school timetable:"
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 80,
+ "outputs": [],
+ "source": [
+ "fun generateDemoData(): TimeTable {\n",
+ " val timeslots: MutableList<Timeslot> = mutableListOf(\n",
+ " Timeslot(DayOfWeek.MONDAY, LocalTime.of(8, 30), LocalTime.of(9, 30)),\n",
+ " Timeslot(DayOfWeek.MONDAY, LocalTime.of(9, 30), LocalTime.of(10, 30)),\n",
+ " Timeslot(DayOfWeek.MONDAY, LocalTime.of(10, 30), LocalTime.of(11, 30)),\n",
+ " Timeslot(DayOfWeek.MONDAY, LocalTime.of(13, 30), LocalTime.of(14, 30)),\n",
+ " Timeslot(DayOfWeek.MONDAY, LocalTime.of(14, 30), LocalTime.of(15, 30)),\n",
+ " \n",
+ " Timeslot(DayOfWeek.TUESDAY, LocalTime.of(8, 30), LocalTime.of(9, 30)),\n",
+ " Timeslot(DayOfWeek.TUESDAY, LocalTime.of(9, 30), LocalTime.of(10, 30)),\n",
+ " Timeslot(DayOfWeek.TUESDAY, LocalTime.of(10, 30), LocalTime.of(11, 30)),\n",
+ " Timeslot(DayOfWeek.TUESDAY, LocalTime.of(13, 30), LocalTime.of(14, 30)),\n",
+ " Timeslot(DayOfWeek.TUESDAY, LocalTime.of(14, 30), LocalTime.of(15, 30)))\n",
+ " \n",
+ " \n",
+ " val rooms: MutableList<Room> = mutableListOf(\n",
+ " Room(\"Room A\"),\n",
+ " Room(\"Room B\"),\n",
+ " Room(\"Room C\"))\n",
+ " \n",
+ " var nextId: Long = 0\n",
+ " val lessons: MutableList<Lesson> = mutableListOf(\n",
+ " Lesson(nextId++, \"Math\", \"A. Turing\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"Math\", \"A. Turing\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"Physics\", \"M. Curie\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"Chemistry\", \"M. Curie\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"Biology\", \"C. Darwin\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"History\", \"I. Jones\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"English\", \"I. Jones\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"English\", \"I. Jones\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"Spanish\", \"P. Cruz\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"Spanish\", \"P. Cruz\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"Math\", \"A. Turing\", \"10th grade\"),\n",
+ " Lesson(nextId++, \"Math\", \"A. Turing\", \"10th grade\"),\n",
+ " Lesson(nextId++, \"Math\", \"A. Turing\", \"10th grade\"),\n",
+ " Lesson(nextId++, \"Physics\", \"M. Curie\", \"10th grade\"),\n",
+ " Lesson(nextId++, \"Chemistry\", \"M. Curie\", \"10th grade\"),\n",
+ " Lesson(nextId++, \"French\", \"M. Curie\", \"10th grade\"),\n",
+ " Lesson(nextId++, \"Geography\", \"C. Darwin\", \"10th grade\"),\n",
+ " Lesson(nextId++, \"History\", \"I. Jones\", \"10th grade\"),\n",
+ " Lesson(nextId++, \"English\", \"P. Cruz\", \"10th grade\"),\n",
+ " Lesson(nextId++, \"Spanish\", \"P. Cruz\", \"10th grade\"))\n",
+ " return TimeTable(timeslots, rooms, lessons)\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.992053111Z",
+ "start_time": "2023-10-30T21:01:02.786173253Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "## Visualize the result\n",
+ "\n",
+ "Print the timetable to the console:"
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 81,
+ "outputs": [],
+ "source": [
+ "fun printTimeTable(timeTable: TimeTable) {\n",
+ " println(\"\")\n",
+ "\n",
+ " val lessonMap = timeTable.lessons.groupBy { lesson -> Pair(lesson.timeslot, lesson.room) }\n",
+ "\n",
+ " print(\"| \")\n",
+ " for (room in timeTable.rooms) {\n",
+ " print(\"| \" + String.format(\"%-10s\", room.name) + \" \") \n",
+ " }\n",
+ " println(\"|\") \n",
+ " println(\"|\" + \"------------|\".repeat(timeTable.rooms.size + 1)) \n",
+ " \n",
+ " for (timeslot in timeTable.timeslots) {\n",
+ " print(\"| \" + String.format(\"%-10s\", \"\" + timeslot.dayOfWeek.toString().subSequence(0, 3) + \" \" + timeslot.startTime) + \" \")\n",
+ " for (room in timeTable.rooms) {\n",
+ " print(\"| \") \n",
+ " val cellLessons = lessonMap.get(Pair(timeslot, room)) ?: emptyList()\n",
+ " print(String.format(\"%-10s\", cellLessons.map { lesson -> lesson.subject }.joinToString(\", \")))\n",
+ " print(\" \")\n",
+ " }\n",
+ " println(\"|\")\n",
+ " print(\"| \" + String.format(\"%-10s\", \"\") + \" \")\n",
+ " for (room in timeTable.rooms) {\n",
+ " print(\"| \") \n",
+ " val cellLessons = lessonMap.get(Pair(timeslot, room)) ?: emptyList()\n",
+ " print(String.format(\"%-10s\", cellLessons.map { lesson -> lesson.teacher }.joinToString(\", \")))\n",
+ " print(\" \")\n",
+ " }\n",
+ " println(\"|\")\n",
+ " print(\"| \" + String.format(\"%-10s\", \"\") + \" \")\n",
+ " for (room in timeTable.rooms) {\n",
+ " print(\"| \") \n",
+ " val cellLessons = lessonMap.get(Pair(timeslot, room)) ?: emptyList()\n",
+ " print(String.format(\"%-10s\", cellLessons.map { lesson -> lesson.studentGroup }.joinToString(\", \")))\n",
+ " print(\" \")\n",
+ " }\n",
+ " println(\"|\") \n",
+ " println(\"|\" + \"------------|\".repeat(timeTable.rooms.size + 1)) \n",
+ " }\n",
+ " val unassignedLessons = lessonMap.get(Pair(null, null))\n",
+ " if (unassignedLessons != null && unassignedLessons.isNotEmpty()) {\n",
+ " println(\"\")\n",
+ " println(\"Unassigned lessons\")\n",
+ " for (lesson: Lesson in unassignedLessons) {\n",
+ " println(\" \" + lesson.subject + \" - \" + lesson.teacher + \" - \" + lesson.studentGroup)\n",
+ " }\n",
+ " }\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:03.344553989Z",
+ "start_time": "2023-10-30T21:01:02.991344533Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "## Solve it\n",
+ "\n",
+ "Configure and run the solver:"
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 82,
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Loading the problem ...\n",
+ "Solving the problem ...\n",
+ "Visualizing the solution ...\n",
+ "\n",
+ "| | Room A | Room B | Room C |\n",
+ "|------------|------------|------------|------------|\n",
+ "| MON 08:30 | Math | Spanish | |\n",
+ "| | A. Turing | P. Cruz | |\n",
+ "| | 10th grade | 9th grade | |\n",
+ "|------------|------------|------------|------------|\n",
+ "| MON 09:30 | Math | English | |\n",
+ "| | A. Turing | P. Cruz | |\n",
+ "| | 9th grade | 10th grade | |\n",
+ "|------------|------------|------------|------------|\n",
+ "| MON 10:30 | Math | Spanish | |\n",
+ "| | A. Turing | P. Cruz | |\n",
+ "| | 10th grade | 9th grade | |\n",
+ "|------------|------------|------------|------------|\n",
+ "| MON 13:30 | | English | Geography |\n",
+ "| | | I. Jones | C. Darwin |\n",
+ "| | | 9th grade | 10th grade |\n",
+ "|------------|------------|------------|------------|\n",
+ "| MON 14:30 | | History | Biology |\n",
+ "| | | I. Jones | C. Darwin |\n",
+ "| | | 10th grade | 9th grade |\n",
+ "|------------|------------|------------|------------|\n",
+ "| TUE 08:30 | | Spanish | Chemistry |\n",
+ "| | | P. Cruz | M. Curie |\n",
+ "| | | 10th grade | 9th grade |\n",
+ "|------------|------------|------------|------------|\n",
+ "| TUE 09:30 | Math | | Physics |\n",
+ "| | A. Turing | | M. Curie |\n",
+ "| | 10th grade | | 9th grade |\n",
+ "|------------|------------|------------|------------|\n",
+ "| TUE 10:30 | Math | | Chemistry |\n",
+ "| | A. Turing | | M. Curie |\n",
+ "| | 9th grade | | 10th grade |\n",
+ "|------------|------------|------------|------------|\n",
+ "| TUE 13:30 | | English | Physics |\n",
+ "| | | I. Jones | M. Curie |\n",
+ "| | | 9th grade | 10th grade |\n",
+ "|------------|------------|------------|------------|\n",
+ "| TUE 14:30 | | History | French |\n",
+ "| | | I. Jones | M. Curie |\n",
+ "| | | 9th grade | 10th grade |\n",
+ "|------------|------------|------------|------------|\n"
+ ]
+ }
+ ],
+ "source": [
+ "import ai.timefold.solver.core.config.solver.SolverConfig\n",
+ "import ai.timefold.solver.core.api.solver.SolverFactory\n",
+ "import ai.timefold.solver.core.api.solver.Solver\n",
+ "import ai.timefold.solver.core.api.solver.SolutionManager\n",
+ "import ai.timefold.solver.core.api.solver.SolverManager\n",
+ "\n",
+ "val solverFactory: SolverFactory<TimeTable> = SolverFactory.create(SolverConfig()\n",
+ " .withSolutionClass(TimeTable::class.java)\n",
+ " .withEntityClasses(Lesson::class.java)\n",
+ " .withConstraintProviderClass(TimeTableConstraintProvider::class.java)\n",
+ " // The solver runs only for 5 seconds on this small dataset.\n",
+ " // It's recommended to run for at least 5 minutes (\"5m\") otherwise.\n",
+ " .withTerminationSpentLimit(Duration.ofSeconds(5)))\n",
+ "\n",
+ "println(\"Loading the problem ...\")\n",
+ "val problem: TimeTable = generateDemoData()\n",
+ "\n",
+ "println(\"Solving the problem ...\")\n",
+ "val solver: Solver<TimeTable> = solverFactory.buildSolver()\n",
+ "val solution: TimeTable = solver.solve(problem)\n",
+ "\n",
+ "println(\"Visualizing the solution ...\")\n",
+ "printTimeTable(solution)\n"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:08.485939578Z",
+ "start_time": "2023-10-30T21:01:03.343882883Z"
+ }
+ } | Dtto. |
timefold-quickstarts | github_2023 | others | 139 | TimefoldAI | triceo | @@ -0,0 +1,641 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "source": [
+ "# School timetabling kotlin notebook\n",
+ "\n",
+ "This Kotlin Notebook solves the school timetabling problem with [Timefold](https://timefold.ai], the open source planning solver AI.\n",
+ "\n",
+ "\n",
+ "\n",
+ "## Dependencies\n",
+ "\n",
+ "Add the Timefold solver dependency:"
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 74,
+ "outputs": [],
+ "source": [
+ "@file:DependsOn(\"ai.timefold.solver:timefold-solver-core:1.3.0\")"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.229748528Z",
+ "start_time": "2023-10-30T21:00:59.103295531Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "\n",
+ "## Domain\n",
+ "\n",
+ "Create the domain classes:\n",
+ "\n",
+ "### Room\n",
+ "\n",
+ "A school has rooms."
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 75,
+ "outputs": [],
+ "source": [
+ "class Room {\n",
+ "\n",
+ " var name: String\n",
+ "\n",
+ " constructor(name: String) {\n",
+ " this.name = name\n",
+ " }\n",
+ "\n",
+ " override fun toString(): String = name\n",
+ "\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.274546567Z",
+ "start_time": "2023-10-30T21:01:02.228839493Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "### Timeslot\n",
+ "\n",
+ "A school timetable has timeslots."
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 76,
+ "outputs": [],
+ "source": [
+ "import java.time.DayOfWeek\n",
+ "import java.time.LocalTime\n",
+ "\n",
+ "class Timeslot {\n",
+ "\n",
+ " var dayOfWeek: DayOfWeek\n",
+ " var startTime: LocalTime\n",
+ " var endTime: LocalTime\n",
+ "\n",
+ " constructor(dayOfWeek: DayOfWeek, startTime: LocalTime, endTime: LocalTime) {\n",
+ " this.dayOfWeek = dayOfWeek\n",
+ " this.startTime = startTime\n",
+ " this.endTime = endTime\n",
+ " }\n",
+ "\n",
+ " override fun toString(): String = \"$dayOfWeek $startTime\"\n",
+ "\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.321779372Z",
+ "start_time": "2023-10-30T21:01:02.274072196Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "### Lesson\n",
+ "\n",
+ "Each lesson must be assigned to a timeslot and to a room by the solver."
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 77,
+ "outputs": [],
+ "source": [
+ "import ai.timefold.solver.core.api.domain.entity.PlanningEntity\n",
+ "import ai.timefold.solver.core.api.domain.lookup.PlanningId\n",
+ "import ai.timefold.solver.core.api.domain.variable.PlanningVariable\n",
+ "\n",
+ "@PlanningEntity\n",
+ "class Lesson {\n",
+ "\n",
+ " @PlanningId\n",
+ " var id: Long? = null\n",
+ " lateinit var subject: String\n",
+ " lateinit var teacher: String\n",
+ " lateinit var studentGroup: String\n",
+ "\n",
+ " @PlanningVariable\n",
+ " var timeslot: Timeslot? = null\n",
+ " @PlanningVariable\n",
+ " var room: Room? = null\n",
+ "\n",
+ " // No-arg constructor required for Timefold\n",
+ " constructor()\n",
+ "\n",
+ " constructor(id: Long, subject: String, teacher: String, studentGroup: String) {\n",
+ " this.id = id\n",
+ " this.subject = subject\n",
+ " this.teacher = teacher\n",
+ " this.studentGroup = studentGroup\n",
+ " }\n",
+ "\n",
+ "\n",
+ " override fun toString(): String = \"$subject\"\n",
+ "\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.387536998Z",
+ "start_time": "2023-10-30T21:01:02.321150649Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "## Constraints\n",
+ "\n",
+ "The solver must take into account hard and soft constraints:"
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 78,
+ "outputs": [],
+ "source": [
+ "import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore\n",
+ "import ai.timefold.solver.core.api.score.stream.Constraint\n",
+ "import ai.timefold.solver.core.api.score.stream.ConstraintFactory\n",
+ "import ai.timefold.solver.core.api.score.stream.ConstraintProvider\n",
+ "import ai.timefold.solver.core.api.score.stream.Joiners\n",
+ "import java.time.Duration\n",
+ "\n",
+ "class TimeTableConstraintProvider : ConstraintProvider {\n",
+ "\n",
+ " override fun defineConstraints(constraintFactory: ConstraintFactory): Array<Constraint>? {\n",
+ " return arrayOf(\n",
+ " // Hard constraints\n",
+ " roomConflict(constraintFactory),\n",
+ " teacherConflict(constraintFactory),\n",
+ " studentGroupConflict(constraintFactory),\n",
+ " // Soft constraints\n",
+ " teacherRoomStability(constraintFactory),\n",
+ " teacherTimeEfficiency(constraintFactory),\n",
+ " studentGroupSubjectVariety(constraintFactory)\n",
+ " )\n",
+ " }\n",
+ "\n",
+ " fun roomConflict(constraintFactory: ConstraintFactory): Constraint {\n",
+ " // A room can accommodate at most one lesson at the same time.\n",
+ " return constraintFactory\n",
+ " // Select each pair of 2 different lessons ...\n",
+ " .forEachUniquePair(\n",
+ " Lesson::class.java,\n",
+ " // ... in the same timeslot ...\n",
+ " Joiners.equal(Lesson::timeslot),\n",
+ " // ... in the same room ...\n",
+ " Joiners.equal(Lesson::room)\n",
+ " )\n",
+ " // ... and penalize each pair with a hard weight.\n",
+ " .penalize(HardSoftScore.ONE_HARD)\n",
+ " .asConstraint(\"Room conflict\");\n",
+ " }\n",
+ "\n",
+ " fun teacherConflict(constraintFactory: ConstraintFactory): Constraint {\n",
+ " // A teacher can teach at most one lesson at the same time.\n",
+ " return constraintFactory\n",
+ " .forEachUniquePair(\n",
+ " Lesson::class.java,\n",
+ " Joiners.equal(Lesson::timeslot),\n",
+ " Joiners.equal(Lesson::teacher)\n",
+ " )\n",
+ " .penalize(HardSoftScore.ONE_HARD)\n",
+ " .asConstraint(\"Teacher conflict\");\n",
+ " }\n",
+ "\n",
+ " fun studentGroupConflict(constraintFactory: ConstraintFactory): Constraint {\n",
+ " // A student can attend at most one lesson at the same time.\n",
+ " return constraintFactory\n",
+ " .forEachUniquePair(\n",
+ " Lesson::class.java,\n",
+ " Joiners.equal(Lesson::timeslot),\n",
+ " Joiners.equal(Lesson::studentGroup)\n",
+ " )\n",
+ " .penalize(HardSoftScore.ONE_HARD)\n",
+ " .asConstraint(\"Student group conflict\");\n",
+ " }\n",
+ "\n",
+ " fun teacherRoomStability(constraintFactory: ConstraintFactory): Constraint {\n",
+ " // A teacher prefers to teach in a single room.\n",
+ " return constraintFactory\n",
+ " .forEachUniquePair(\n",
+ " Lesson::class.java,\n",
+ " Joiners.equal(Lesson::teacher)\n",
+ " )\n",
+ " .filter { lesson1: Lesson, lesson2: Lesson -> lesson1.room !== lesson2.room }\n",
+ " .penalize(HardSoftScore.ONE_SOFT)\n",
+ " .asConstraint(\"Teacher room stability\");\n",
+ " }\n",
+ "\n",
+ " fun teacherTimeEfficiency(constraintFactory: ConstraintFactory): Constraint {\n",
+ " // A teacher prefers to teach sequential lessons and dislikes gaps between lessons.\n",
+ " return constraintFactory\n",
+ " .forEach(Lesson::class.java)\n",
+ " .join(Lesson::class.java,\n",
+ " Joiners.equal(Lesson::teacher),\n",
+ " Joiners.equal { lesson: Lesson -> lesson.timeslot?.dayOfWeek })\n",
+ " .filter { lesson1: Lesson, lesson2: Lesson ->\n",
+ " val between = Duration.between(\n",
+ " lesson1.timeslot?.endTime,\n",
+ " lesson2.timeslot?.startTime\n",
+ " )\n",
+ " !between.isNegative && between.compareTo(Duration.ofMinutes(30)) <= 0\n",
+ " }\n",
+ " .reward(HardSoftScore.ONE_SOFT)\n",
+ " .asConstraint(\"Teacher time efficiency\");\n",
+ " }\n",
+ "\n",
+ " fun studentGroupSubjectVariety(constraintFactory: ConstraintFactory): Constraint {\n",
+ " // A student group dislikes sequential lessons on the same subject.\n",
+ " return constraintFactory\n",
+ " .forEach(Lesson::class.java)\n",
+ " .join(Lesson::class.java,\n",
+ " Joiners.equal(Lesson::subject),\n",
+ " Joiners.equal(Lesson::studentGroup),\n",
+ " Joiners.equal { lesson: Lesson -> lesson.timeslot?.dayOfWeek })\n",
+ " .filter { lesson1: Lesson, lesson2: Lesson ->\n",
+ " val between = Duration.between(\n",
+ " lesson1.timeslot?.endTime,\n",
+ " lesson2.timeslot?.startTime\n",
+ " )\n",
+ " !between.isNegative && between.compareTo(Duration.ofMinutes(30)) <= 0\n",
+ " }\n",
+ " .penalize(HardSoftScore.ONE_SOFT)\n",
+ " .asConstraint(\"Student group subject variety\");\n",
+ " }\n",
+ "\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.730088133Z",
+ "start_time": "2023-10-30T21:01:02.386917608Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "### TimeTable\n",
+ "\n",
+ "The timetable class represents a single dataset, typically a single school:"
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 79,
+ "outputs": [],
+ "source": [
+ "import ai.timefold.solver.core.api.domain.solution.PlanningEntityCollectionProperty\n",
+ "import ai.timefold.solver.core.api.domain.solution.PlanningScore\n",
+ "import ai.timefold.solver.core.api.domain.solution.PlanningSolution\n",
+ "import ai.timefold.solver.core.api.domain.solution.ProblemFactCollectionProperty\n",
+ "import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider\n",
+ "import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore\n",
+ "\n",
+ "@PlanningSolution\n",
+ "class TimeTable {\n",
+ "\n",
+ " @ProblemFactCollectionProperty\n",
+ " @ValueRangeProvider\n",
+ " lateinit var timeslots: List<Timeslot>\n",
+ " @ProblemFactCollectionProperty\n",
+ " @ValueRangeProvider\n",
+ " lateinit var rooms: List<Room>\n",
+ " @PlanningEntityCollectionProperty\n",
+ " lateinit var lessons: List<Lesson>\n",
+ "\n",
+ " @PlanningScore\n",
+ " var score: HardSoftScore? = null\n",
+ "\n",
+ " // No-arg constructor required for Timefold\n",
+ " constructor() {}\n",
+ "\n",
+ " constructor(timeslots: List<Timeslot>, rooms: List<Room>, lessons: List<Lesson>) {\n",
+ " this.timeslots = timeslots\n",
+ " this.rooms = rooms\n",
+ " this.lessons = lessons\n",
+ " }\n",
+ "\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.786897117Z",
+ "start_time": "2023-10-30T21:01:02.729363789Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "## Data generator\n",
+ "\n",
+ "Generate some data for a small school timetable:"
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 80,
+ "outputs": [],
+ "source": [
+ "fun generateDemoData(): TimeTable {\n",
+ " val timeslots: MutableList<Timeslot> = mutableListOf(\n",
+ " Timeslot(DayOfWeek.MONDAY, LocalTime.of(8, 30), LocalTime.of(9, 30)),\n",
+ " Timeslot(DayOfWeek.MONDAY, LocalTime.of(9, 30), LocalTime.of(10, 30)),\n",
+ " Timeslot(DayOfWeek.MONDAY, LocalTime.of(10, 30), LocalTime.of(11, 30)),\n",
+ " Timeslot(DayOfWeek.MONDAY, LocalTime.of(13, 30), LocalTime.of(14, 30)),\n",
+ " Timeslot(DayOfWeek.MONDAY, LocalTime.of(14, 30), LocalTime.of(15, 30)),\n",
+ " \n",
+ " Timeslot(DayOfWeek.TUESDAY, LocalTime.of(8, 30), LocalTime.of(9, 30)),\n",
+ " Timeslot(DayOfWeek.TUESDAY, LocalTime.of(9, 30), LocalTime.of(10, 30)),\n",
+ " Timeslot(DayOfWeek.TUESDAY, LocalTime.of(10, 30), LocalTime.of(11, 30)),\n",
+ " Timeslot(DayOfWeek.TUESDAY, LocalTime.of(13, 30), LocalTime.of(14, 30)),\n",
+ " Timeslot(DayOfWeek.TUESDAY, LocalTime.of(14, 30), LocalTime.of(15, 30)))\n",
+ " \n",
+ " \n",
+ " val rooms: MutableList<Room> = mutableListOf(\n",
+ " Room(\"Room A\"),\n",
+ " Room(\"Room B\"),\n",
+ " Room(\"Room C\"))\n",
+ " \n",
+ " var nextId: Long = 0\n",
+ " val lessons: MutableList<Lesson> = mutableListOf(\n",
+ " Lesson(nextId++, \"Math\", \"A. Turing\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"Math\", \"A. Turing\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"Physics\", \"M. Curie\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"Chemistry\", \"M. Curie\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"Biology\", \"C. Darwin\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"History\", \"I. Jones\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"English\", \"I. Jones\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"English\", \"I. Jones\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"Spanish\", \"P. Cruz\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"Spanish\", \"P. Cruz\", \"9th grade\"),\n",
+ " Lesson(nextId++, \"Math\", \"A. Turing\", \"10th grade\"),\n",
+ " Lesson(nextId++, \"Math\", \"A. Turing\", \"10th grade\"),\n",
+ " Lesson(nextId++, \"Math\", \"A. Turing\", \"10th grade\"),\n",
+ " Lesson(nextId++, \"Physics\", \"M. Curie\", \"10th grade\"),\n",
+ " Lesson(nextId++, \"Chemistry\", \"M. Curie\", \"10th grade\"),\n",
+ " Lesson(nextId++, \"French\", \"M. Curie\", \"10th grade\"),\n",
+ " Lesson(nextId++, \"Geography\", \"C. Darwin\", \"10th grade\"),\n",
+ " Lesson(nextId++, \"History\", \"I. Jones\", \"10th grade\"),\n",
+ " Lesson(nextId++, \"English\", \"P. Cruz\", \"10th grade\"),\n",
+ " Lesson(nextId++, \"Spanish\", \"P. Cruz\", \"10th grade\"))\n",
+ " return TimeTable(timeslots, rooms, lessons)\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:02.992053111Z",
+ "start_time": "2023-10-30T21:01:02.786173253Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "## Visualize the result\n",
+ "\n",
+ "Print the timetable to the console:"
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 81,
+ "outputs": [],
+ "source": [
+ "fun printTimeTable(timeTable: TimeTable) {\n",
+ " println(\"\")\n",
+ "\n",
+ " val lessonMap = timeTable.lessons.groupBy { lesson -> Pair(lesson.timeslot, lesson.room) }\n",
+ "\n",
+ " print(\"| \")\n",
+ " for (room in timeTable.rooms) {\n",
+ " print(\"| \" + String.format(\"%-10s\", room.name) + \" \") \n",
+ " }\n",
+ " println(\"|\") \n",
+ " println(\"|\" + \"------------|\".repeat(timeTable.rooms.size + 1)) \n",
+ " \n",
+ " for (timeslot in timeTable.timeslots) {\n",
+ " print(\"| \" + String.format(\"%-10s\", \"\" + timeslot.dayOfWeek.toString().subSequence(0, 3) + \" \" + timeslot.startTime) + \" \")\n",
+ " for (room in timeTable.rooms) {\n",
+ " print(\"| \") \n",
+ " val cellLessons = lessonMap.get(Pair(timeslot, room)) ?: emptyList()\n",
+ " print(String.format(\"%-10s\", cellLessons.map { lesson -> lesson.subject }.joinToString(\", \")))\n",
+ " print(\" \")\n",
+ " }\n",
+ " println(\"|\")\n",
+ " print(\"| \" + String.format(\"%-10s\", \"\") + \" \")\n",
+ " for (room in timeTable.rooms) {\n",
+ " print(\"| \") \n",
+ " val cellLessons = lessonMap.get(Pair(timeslot, room)) ?: emptyList()\n",
+ " print(String.format(\"%-10s\", cellLessons.map { lesson -> lesson.teacher }.joinToString(\", \")))\n",
+ " print(\" \")\n",
+ " }\n",
+ " println(\"|\")\n",
+ " print(\"| \" + String.format(\"%-10s\", \"\") + \" \")\n",
+ " for (room in timeTable.rooms) {\n",
+ " print(\"| \") \n",
+ " val cellLessons = lessonMap.get(Pair(timeslot, room)) ?: emptyList()\n",
+ " print(String.format(\"%-10s\", cellLessons.map { lesson -> lesson.studentGroup }.joinToString(\", \")))\n",
+ " print(\" \")\n",
+ " }\n",
+ " println(\"|\") \n",
+ " println(\"|\" + \"------------|\".repeat(timeTable.rooms.size + 1)) \n",
+ " }\n",
+ " val unassignedLessons = lessonMap.get(Pair(null, null))\n",
+ " if (unassignedLessons != null && unassignedLessons.isNotEmpty()) {\n",
+ " println(\"\")\n",
+ " println(\"Unassigned lessons\")\n",
+ " for (lesson: Lesson in unassignedLessons) {\n",
+ " println(\" \" + lesson.subject + \" - \" + lesson.teacher + \" - \" + lesson.studentGroup)\n",
+ " }\n",
+ " }\n",
+ "}"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:03.344553989Z",
+ "start_time": "2023-10-30T21:01:02.991344533Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "## Solve it\n",
+ "\n",
+ "Configure and run the solver:"
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 82,
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Loading the problem ...\n",
+ "Solving the problem ...\n",
+ "Visualizing the solution ...\n",
+ "\n",
+ "| | Room A | Room B | Room C |\n",
+ "|------------|------------|------------|------------|\n",
+ "| MON 08:30 | Math | Spanish | |\n",
+ "| | A. Turing | P. Cruz | |\n",
+ "| | 10th grade | 9th grade | |\n",
+ "|------------|------------|------------|------------|\n",
+ "| MON 09:30 | Math | English | |\n",
+ "| | A. Turing | P. Cruz | |\n",
+ "| | 9th grade | 10th grade | |\n",
+ "|------------|------------|------------|------------|\n",
+ "| MON 10:30 | Math | Spanish | |\n",
+ "| | A. Turing | P. Cruz | |\n",
+ "| | 10th grade | 9th grade | |\n",
+ "|------------|------------|------------|------------|\n",
+ "| MON 13:30 | | English | Geography |\n",
+ "| | | I. Jones | C. Darwin |\n",
+ "| | | 9th grade | 10th grade |\n",
+ "|------------|------------|------------|------------|\n",
+ "| MON 14:30 | | History | Biology |\n",
+ "| | | I. Jones | C. Darwin |\n",
+ "| | | 10th grade | 9th grade |\n",
+ "|------------|------------|------------|------------|\n",
+ "| TUE 08:30 | | Spanish | Chemistry |\n",
+ "| | | P. Cruz | M. Curie |\n",
+ "| | | 10th grade | 9th grade |\n",
+ "|------------|------------|------------|------------|\n",
+ "| TUE 09:30 | Math | | Physics |\n",
+ "| | A. Turing | | M. Curie |\n",
+ "| | 10th grade | | 9th grade |\n",
+ "|------------|------------|------------|------------|\n",
+ "| TUE 10:30 | Math | | Chemistry |\n",
+ "| | A. Turing | | M. Curie |\n",
+ "| | 9th grade | | 10th grade |\n",
+ "|------------|------------|------------|------------|\n",
+ "| TUE 13:30 | | English | Physics |\n",
+ "| | | I. Jones | M. Curie |\n",
+ "| | | 9th grade | 10th grade |\n",
+ "|------------|------------|------------|------------|\n",
+ "| TUE 14:30 | | History | French |\n",
+ "| | | I. Jones | M. Curie |\n",
+ "| | | 9th grade | 10th grade |\n",
+ "|------------|------------|------------|------------|\n"
+ ]
+ }
+ ],
+ "source": [
+ "import ai.timefold.solver.core.config.solver.SolverConfig\n",
+ "import ai.timefold.solver.core.api.solver.SolverFactory\n",
+ "import ai.timefold.solver.core.api.solver.Solver\n",
+ "import ai.timefold.solver.core.api.solver.SolutionManager\n",
+ "import ai.timefold.solver.core.api.solver.SolverManager\n",
+ "\n",
+ "val solverFactory: SolverFactory<TimeTable> = SolverFactory.create(SolverConfig()\n",
+ " .withSolutionClass(TimeTable::class.java)\n",
+ " .withEntityClasses(Lesson::class.java)\n",
+ " .withConstraintProviderClass(TimeTableConstraintProvider::class.java)\n",
+ " // The solver runs only for 5 seconds on this small dataset.\n",
+ " // It's recommended to run for at least 5 minutes (\"5m\") otherwise.\n",
+ " .withTerminationSpentLimit(Duration.ofSeconds(5)))\n",
+ "\n",
+ "println(\"Loading the problem ...\")\n",
+ "val problem: TimeTable = generateDemoData()\n",
+ "\n",
+ "println(\"Solving the problem ...\")\n",
+ "val solver: Solver<TimeTable> = solverFactory.buildSolver()\n",
+ "val solution: TimeTable = solver.solve(problem)\n",
+ "\n",
+ "println(\"Visualizing the solution ...\")\n",
+ "printTimeTable(solution)\n"
+ ],
+ "metadata": {
+ "collapsed": false,
+ "ExecuteTime": {
+ "end_time": "2023-10-30T21:01:08.485939578Z",
+ "start_time": "2023-10-30T21:01:03.343882883Z"
+ }
+ }
+ },
+ {
+ "cell_type": "markdown",
+ "source": [
+ "To learn more, visit [timefold.ai](https://timefold.ai)."
+ ],
+ "metadata": {
+ "collapsed": false
+ }
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Kotlin",
+ "language": "kotlin",
+ "name": "kotlin"
+ },
+ "language_info": {
+ "name": "kotlin",
+ "version": "1.9.0",
+ "mimetype": "text/x-kotlin", | How do we update this? Typically our kotlin version is bumped by Dependabot, but I doubt it will see this. |
timefold-quickstarts | github_2023 | java | 202 | TimefoldAI | triceo | @@ -74,43 +74,43 @@ public void generateDemoData(@Observes StartupEvent startupEvent) {
ingredientMap.put(new Product(productId++, ingredient + " and " + ingredientB + " " + PRODUCT_VARIATION_LIST.get(2)), Set.of(ingredient, ingredientB));
ingredientMap.put(new Product(productId++, ingredient + ", " + ingredientA + " and " + ingredientC + " " + PRODUCT_VARIATION_LIST.get(1)), Set.of(ingredient, ingredientA, ingredientC));
}
- ArrayList<Product> productList = new ArrayList<>(ingredientMap.keySet());
- for (Product product : productList) {
- Map<Product, Duration> cleaningDurationMap = new HashMap<>(productList.size());
- Set<String> ingredientSet = ingredientMap.get(product);
- for (Product previousProduct : productList) {
- boolean noCleaning = ingredientSet.containsAll(ingredientMap.get(previousProduct));
+ ArrayList<Product> products = new ArrayList<>(ingredientMap.keySet()); | ```suggestion
List<Product> products = new ArrayList<>(ingredientMap.keySet());
``` |
timefold-quickstarts | github_2023 | others | 184 | TimefoldAI | triceo | @@ -18,25 +17,25 @@ repositories {
}
dependencies {
+ implementation platform("ai.timefold.solver:timefold-solver-bom:${timefoldVersion}")
+
implementation "org.springframework.boot:spring-boot-starter-web"
- implementation "org.springframework.boot:spring-boot-starter-data-rest"
- implementation "org.springframework.boot:spring-boot-starter-data-jpa"
+ implementation "ai.timefold.solver:timefold-solver-spring-boot-starter"
+
+ implementation "org.springdoc:springdoc-openapi-starter-webmvc-ui:2.1.0"
+
testImplementation("org.springframework.boot:spring-boot-starter-test")
+ testImplementation("ai.timefold.solver:timefold-solver-benchmark")
+ testImplementation("ai.timefold.solver:timefold-solver-test")
testImplementation "io.rest-assured:rest-assured"
testImplementation "org.awaitility:awaitility"
- implementation platform("ai.timefold.solver:timefold-solver-bom:${timefoldVersion}")
- implementation "ai.timefold.solver:timefold-solver-spring-boot-starter"
- testImplementation("ai.timefold.solver:timefold-solver-test")
- testImplementation("ai.timefold.solver:timefold-solver-benchmark")
- testImplementation "org.assertj:assertj-core:${assertjVersion}"
- runtimeOnly "com.h2database:h2"
- runtimeOnly "org.webjars:webjars-locator:0.37"
+ runtimeOnly "org.webjars:webjars-locator:0.50"
runtimeOnly "ai.timefold.solver:timefold-solver-webui"
runtimeOnly "org.webjars:bootstrap:5.2.3"
runtimeOnly "org.webjars:jquery:3.6.4"
- runtimeOnly "org.webjars:font-awesome:5.11.2"
+ runtimeOnly "org.webjars:font-awesome:5.15.1"
runtimeOnly "org.webjars.npm:js-joda:1.11.0" | If you're upgrading versions of these components, please do it consistently with the other School Timetabling quickstart. We want them to be truly identical, except for the places where they can not be for obvious reasons.
(Please remember to test the quickstart's UI after modifying these dependency versions.)
In general, let's try and keep the versions of *all* dependencies (not just this) in sync across quickstarts. Much of this is done automatically through Dependabot, but for some reason, Gradle doesn't work too well with it. |
timefold-quickstarts | github_2023 | others | 193 | TimefoldAI | triceo | @@ -143,7 +142,24 @@ Many examples in desktop technology.
image::build/quickstarts-showcase/src/main/resources/META-INF/resources/screenshot/timefold-solver-examples-screenshot.png[]
-* https://timefold.ai[Download]
+[[run]]
+== Run the application | The section is H3, so shouldn't this be H4?
```suggestion
==== Run the application
```
|
timefold-quickstarts | github_2023 | others | 194 | TimefoldAI | triceo | @@ -4,9 +4,10 @@ plugins {
}
def timefoldVersion = "999-SNAPSHOT"
-def logbackVersion = "1.4.11"
-def junitJupiterVersion = "5.10.0"
+def logbackVersion = "1.4.14"
+def junitJupiterVersion = "5.10.1"
def assertjVersion = "3.24.2"
+def jacksonAnnotationVersion = "2.15.3" | ```suggestion
``` |
timefold-quickstarts | github_2023 | others | 186 | TimefoldAI | triceo | @@ -9,16 +9,18 @@ import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore
import ai.timefold.solver.core.api.solver.SolverStatus
@PlanningSolution
-class TimeTable {
+class Timetable { | Nice detail, well spotted. |
timefold-quickstarts | github_2023 | others | 186 | TimefoldAI | triceo | @@ -0,0 +1,447 @@
+package org.acme.kotlin.schooltimetabling.rest
+
+import jakarta.ws.rs.GET
+import jakarta.ws.rs.Path
+import jakarta.ws.rs.PathParam
+import jakarta.ws.rs.core.MediaType
+import jakarta.ws.rs.core.Response
+import org.acme.kotlin.schooltimetabling.domain.Lesson
+import org.acme.kotlin.schooltimetabling.domain.Room
+import org.acme.kotlin.schooltimetabling.domain.Timeslot
+import org.acme.kotlin.schooltimetabling.domain.Timetable
+import org.eclipse.microprofile.openapi.annotations.Operation
+import org.eclipse.microprofile.openapi.annotations.enums.SchemaType
+import org.eclipse.microprofile.openapi.annotations.media.Content
+import org.eclipse.microprofile.openapi.annotations.media.Schema
+import org.eclipse.microprofile.openapi.annotations.parameters.Parameter
+import org.eclipse.microprofile.openapi.annotations.responses.APIResponse
+import org.eclipse.microprofile.openapi.annotations.responses.APIResponses
+import org.eclipse.microprofile.openapi.annotations.tags.Tag
+import java.time.DayOfWeek
+import java.time.LocalTime
+
+@Tag(name = "Demo data", description = "Timefold-provided demo school timetable data.")
+@Path("demo-data")
+class TimetableDemoResource {
+
+ enum class DemoData {
+ SMALL, LARGE
+ }
+
+ @APIResponses(
+ value = [APIResponse(
+ responseCode = "200", description = "List of demo data represented as IDs.", content = [Content(
+ mediaType = MediaType.APPLICATION_JSON,
+ schema = Schema(implementation = DemoData::class, type = SchemaType.ARRAY)
+ )]
+ )]
+ )
+ @Operation(summary = "List demo data.")
+ @GET
+ fun list(): Array<DemoData> {
+ return DemoData.entries.toTypedArray()
+ }
+
+ @APIResponses(
+ value = [APIResponse(
+ responseCode = "200", description = "Unsolved demo timetable.", content = [Content(
+ mediaType = MediaType.APPLICATION_JSON, schema = Schema(implementation = Timetable::class)
+ )]
+ )]
+ )
+ @Operation(summary = "Find an unsolved demo timetable by ID.")
+ @GET
+ @Path("/{demoDataId}")
+ fun generate(
+ @Parameter(
+ description = "Unique identifier of the demo data.", required = true
+ ) @PathParam("demoDataId") demoData: DemoData
+ ): Response {
+ val timeslotList: MutableList<Timeslot> = ArrayList(10)
+ var nextTimeslotId = 0L
+ timeslotList.add(
+ Timeslot(nextTimeslotId++, DayOfWeek.MONDAY, LocalTime.of(8, 30), LocalTime.of(9, 30))
+ ) | This is very verbose. Some later calls take even 5 lines.
Maybe by static importing `DayOfWeek` values, we can get this to fit on one line? |
timefold-quickstarts | github_2023 | others | 186 | TimefoldAI | triceo | @@ -0,0 +1,255 @@
+package org.acme.kotlin.schooltimetabling.rest
+
+import ai.timefold.solver.core.api.score.analysis.ScoreAnalysis
+import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore
+import ai.timefold.solver.core.api.solver.ScoreAnalysisFetchPolicy
+import ai.timefold.solver.core.api.solver.SolutionManager
+import ai.timefold.solver.core.api.solver.SolverManager
+import jakarta.inject.Inject
+import jakarta.ws.rs.* | Please configure your IDE to never use `*` imports.
(One of our little rules; makes reviews easier, and creates less classloading work for the JVM.) |
timefold-quickstarts | github_2023 | others | 186 | TimefoldAI | triceo | @@ -48,6 +56,13 @@ class TimeTableConstraintProvider : ConstraintProvider {
Joiners.equal(Lesson::teacher)
)
.penalize(HardSoftScore.ONE_HARD)
+ .justifyWith({ lesson1: Lesson, lesson2: Lesson?, score: HardSoftScore? ->
+ TeacherConflictJustification(
+ lesson1.teacher,
+ lesson1,
+ lesson2!!
+ ) | In the interest of brevity, I'd put this on one line. |
timefold-quickstarts | github_2023 | java | 170 | TimefoldAI | triceo | @@ -12,9 +12,12 @@
public class TimeTableConstraintProvider implements ConstraintProvider {
+ private static final int MAX_GAP_MINUTES = 30;
+
+ //TODO --> tool detected this as long statement, it is technically not : FP | Please remove the comment. |
timefold-quickstarts | github_2023 | java | 170 | TimefoldAI | triceo | @@ -70,21 +73,23 @@ Constraint teacherRoomStability(ConstraintFactory constraintFactory) {
.asConstraint("Teacher room stability");
}
- Constraint teacherTimeEfficiency(ConstraintFactory constraintFactory) {
- // A teacher prefers to teach sequential lessons and dislikes gaps between lessons.
+
+ //TODO ---> removed magic number and introduced global variable : TP | Please remove the comment. |
timefold-quickstarts | github_2023 | java | 170 | TimefoldAI | triceo | @@ -70,21 +73,23 @@ Constraint teacherRoomStability(ConstraintFactory constraintFactory) {
.asConstraint("Teacher room stability");
}
- Constraint teacherTimeEfficiency(ConstraintFactory constraintFactory) {
- // A teacher prefers to teach sequential lessons and dislikes gaps between lessons.
+
+ //TODO ---> removed magic number and introduced global variable : TP
+ public Constraint teacherTimeEfficiency(ConstraintFactory constraintFactory) {
return constraintFactory
.forEach(Lesson.class)
.join(Lesson.class, Joiners.equal(Lesson::getTeacher),
Joiners.equal((lesson) -> lesson.getTimeslot().getDayOfWeek()))
.filter((lesson1, lesson2) -> {
Duration between = Duration.between(lesson1.getTimeslot().getEndTime(),
lesson2.getTimeslot().getStartTime());
- return !between.isNegative() && between.compareTo(Duration.ofMinutes(30)) <= 0;
+ return !between.isNegative() && between.compareTo(Duration.ofMinutes(MAX_GAP_MINUTES)) <= 0;
})
.reward(HardSoftScore.ONE_SOFT)
.asConstraint("Teacher time efficiency");
}
+ //TODO ---> removed magic number and introduced global variable : TP | Please remove the comment. |
timefold-quickstarts | github_2023 | java | 170 | TimefoldAI | triceo | @@ -31,6 +31,7 @@ public class MaintenanceSchedule {
// Ignored by Timefold, used by the UI to display solve or stop solving button
private SolverStatus solverStatus;
+ //TODO --> Never used Constructor. | Please remove the comment. The constructor is required for Timefold to function, even though it seems unused. |
timefold-quickstarts | github_2023 | java | 170 | TimefoldAI | triceo | @@ -42,16 +43,17 @@ public MaintenanceSchedule(WorkCalendar workCalendar,
this.jobList = jobList;
}
- @ValueRangeProvider
- public List<LocalDate> createStartDateList() {
- return workCalendar.getFromDate().datesUntil(workCalendar.getToDate())
- // Skip weekends. Does not work for holidays.
- // Keep in sync with EndDateUpdatingVariableListener.updateEndDate().
- // To skip holidays too, cache all working days in WorkCalendar.
- .filter(date -> date.getDayOfWeek() != DayOfWeek.SATURDAY
- && date.getDayOfWeek() != DayOfWeek.SUNDAY)
- .collect(Collectors.toList());
- }
+ // Moved to WorkCalendar
+// @ValueRangeProvider
+// public List<LocalDate> createStartDateList() {
+// return workCalendar.getFromDate().datesUntil(workCalendar.getToDate())
+// // Skip weekends. Does not work for holidays.
+// // Keep in sync with EndDateUpdatingVariableListener.updateEndDate().
+// // To skip holidays too, cache all working days in WorkCalendar.
+// .filter(date -> date.getDayOfWeek() != DayOfWeek.SATURDAY
+// && date.getDayOfWeek() != DayOfWeek.SUNDAY)
+// .collect(Collectors.toList());
+// } | Why was this removed? I do not see it being replaced by anything. |
timefold-quickstarts | github_2023 | java | 170 | TimefoldAI | triceo | @@ -35,14 +35,14 @@ public enum DemoData {
FIRENZE(77, 6, 2, 1, 2, 25,
new Location(43.751466, 11.177210), new Location(43.809291, 11.290195));
- private int customerCount;
- private int vehicleCount;
- private int depotCount;
- private int minDemand;
- private int maxDemand;
- private int vehicleCapacity;
- private Location southWestCorner;
- private Location northEastCorner;
+ final private int customerCount;
+ final private int vehicleCount;
+ final private int depotCount;
+ final private int minDemand;
+ final private int maxDemand;
+ final private int vehicleCapacity;
+ final private Location southWestCorner;
+ final private Location northEastCorner; | Please use `private final`, not `final private`. |
timefold-quickstarts | github_2023 | java | 170 | TimefoldAI | triceo | @@ -48,41 +48,24 @@ public enum DemoData {
PHILADELPHIA(60, 6, 2, LocalTime.of(7, 30),
new Location(39.7656099067391, -76.83782328143754),
new Location(40.77636644354855, -74.9300739430771)),
- HARTFORT(50, 6, 2, LocalTime.of(7, 30),
+ HARTFORD(50, 6, 2, LocalTime.of(7, 30),
new Location(41.48366520850297, -73.15901689943055),
new Location(41.99512052869307, -72.25114548877427)),
FIRENZE(77, 6, 2, LocalTime.of(7, 30),
new Location(43.751466, 11.177210), new Location(43.809291, 11.290195));
- private int customerCount;
- private int vehicleCount;
- private int depotCount;
- private LocalTime vehicleStartTime;
- private Location southWestCorner;
- private Location northEastCorner;
+ // TODO --> these variables will be final : FN | Please remove the comment. |
timefold-quickstarts | github_2023 | java | 170 | TimefoldAI | triceo | @@ -16,6 +16,7 @@
import org.springframework.context.annotation.Bean;
import org.springframework.data.domain.Sort;
+// TODO --> unutilised abstraction --> main file : FP | Please remove the comment. |
timefold-quickstarts | github_2023 | java | 170 | TimefoldAI | triceo | @@ -11,6 +11,7 @@
@Transactional
public class TimeTableRepository {
+ // TODO --> SINGLETON_TIME_TABLE_ID is public : deficient encapsulation --> TP | Please remove the comment. |
timefold-quickstarts | github_2023 | others | 177 | TimefoldAI | triceo | @@ -2,7 +2,7 @@
Find the most efficient routes for a fleet of vehicles.
-image::../../build/quickstarts-showcase/src/main/resources/META-INF/resources/screenshot/quarkus-vehicle-routing-screenshot.png[]
+image::../../build/quickstarts-showcase/src/main/resources/META-INF/resources/screenshot/quarkus-vehicle-routing-capacity-screenshot.png[] | ```suggestion
image::../../build/quickstarts-showcase/src/main/resources/META-INF/resources/screenshot/quarkus-vehicle-routing-time-windows-screenshot.png[]
``` |
timefold-quickstarts | github_2023 | java | 142 | TimefoldAI | rsynek | @@ -55,4 +66,79 @@ public void solveDemoDataUntilFeasible() {
assertNotNull(solution.getLessons().get(0).getTimeslot());
assertTrue(solution.getScore().isFeasible());
}
+
+ @Test
+ public void analyze() {
+ Timetable testTimetable = given()
+ .when().get("/demo-data/SMALL")
+ .then()
+ .statusCode(200)
+ .extract()
+ .as(Timetable.class);
+ var roomList = testTimetable.getRooms();
+ var timeslotList = testTimetable.getTimeslots();
+ int i = 0;
+ for (var lesson : testTimetable.getLessons()) { // Initialize the solution.
+ lesson.setRoom(roomList.get(i % roomList.size()));
+ lesson.setTimeslot(timeslotList.get(i % timeslotList.size()));
+ i += 1;
+ }
+
+ String analysis = given()
+ .contentType(ContentType.JSON)
+ .body(testTimetable)
+ .expect().contentType(ContentType.JSON)
+ .when()
+ .put("/timetables/analyze")
+ .then()
+ .extract()
+ .asString();
+ assertNotNull(analysis); // Too long to validate in its entirety.
+
+ String analysis2 = given()
+ .contentType(ContentType.JSON)
+ .queryParam("fetchPolicy", "FETCH_SHALLOW")
+ .body(testTimetable)
+ .expect().contentType(ContentType.JSON)
+ .when()
+ .put("/timetables/analyze")
+ .then()
+ .extract()
+ .asString();
+ assertNotNull(analysis2); // Too long to validate in its entirety.
+ }
+
+ @Singleton
+ public static final class RegisterCustomModuleCustomizer implements ObjectMapperCustomizer {
+
+ @Override
+ public void customize(ObjectMapper objectMapper) {
+ objectMapper.registerModule(new CustomScoreAnalysisJacksonModule());
+ }
+
+ }
+
+ public static final class CustomScoreAnalysisJacksonModule extends SimpleModule {
+
+ public CustomScoreAnalysisJacksonModule() {
+ this.addDeserializer(ScoreAnalysis.class, new CustomScoreAnalysisJacksonDeserializer());
+ }
+
+ }
+
+ public static final class CustomScoreAnalysisJacksonDeserializer extends AbstractScoreAnalysisJacksonDeserializer<HardSoftScore> {
+
+ @Override
+ protected HardSoftScore parseScore(String scoreString) {
+ return HardSoftScore.parseScore(scoreString);
+ }
+
+ @Override
+ protected <ConstraintJustification_ extends ConstraintJustification> ConstraintJustification_
+ parseConstraintJustification(ConstraintRef constraintRef, String constraintJustificationString,
+ HardSoftScore score) {
+ return null;
+ }
+ } | Since the test operates on the client side, we don't need these classes.
```suggestion
``` |
timefold-quickstarts | github_2023 | javascript | 142 | TimefoldAI | rsynek | @@ -218,6 +222,36 @@ function solve() {
"text");
}
+function analyze() {
+ new bootstrap.Modal("#scoreAnalysisModal").show() | Consider more friendly message in case the data set has not been solved yet. As of now, the message starts with "{"details":"Error id c9e674b0-daca-4829-8db8-326753a24402-2, org.jboss.resteasy.spi.UnhandledException ..." and only later, if one reads carefully, they learn what the root cause is.
For unexpected exceptions, it's ok. In this case, I would argues it's not, as halve the users will be tempted to click the score analysis button first. |
timefold-quickstarts | github_2023 | others | 113 | TimefoldAI | rsynek | @@ -87,30 +64,17 @@ jobs:
git merge -s ours --no-edit ${{ github.event.inputs.stableBranch }}
git checkout ${{ github.event.inputs.releaseBranch }}-bump
git merge --squash ${{ github.event.inputs.releaseBranch }}
- git commit -m "chore: release version ${{ github.event.inputs.version }}"
+ git commit -m "build: release version ${{ github.event.inputs.version }}"
git push origin ${{ github.event.inputs.releaseBranch }}-bump
- gh pr create --reviewer triceo,ge0ffrey --base ${{ github.event.inputs.stableBranch }} --head ${{ github.event.inputs.releaseBranch }}-bump --title "chore: release version ${{ github.event.inputs.version }}" --body-file .github/workflows/release-pr-body-stable.md
+ gh pr create --reviewer triceo --base ${{ github.event.inputs.stableBranch }} --head ${{ github.event.inputs.releaseBranch }}-bump --title "build: release version ${{ github.event.inputs.version }}" --body-file .github/workflows/release-pr-body.md
env:
GITHUB_TOKEN: ${{ secrets.JRELEASER_GITHUB_TOKEN }}
- name: Set micro snapshot version on the release branch | ```suggestion
- name: Put back the 999-SNAPSHOT version on the release branch
``` |
timefold-quickstarts | github_2023 | others | 94 | TimefoldAI | rsynek | @@ -1,5 +1,4 @@
-/target
-/local | Any idea where does the /local come from? |
timefold-quickstarts | github_2023 | java | 53 | TimefoldAI | triceo | @@ -52,71 +62,129 @@ public VehicleRoutePlanResource(SolverManager<VehicleRoutePlan, String> solverMa
this.solutionManager = solutionManager;
}
+ @Operation(summary = "List the job IDs of all submitted route plans.")
+ @APIResponses(value = {
+ @APIResponse(responseCode = "200", description = "List of all job IDs.",
+ content = @Content(mediaType = MediaType.APPLICATION_JSON,
+ schema = @Schema(type = SchemaType.ARRAY, implementation = String.class))) })
+ @GET
+ @Produces(MediaType.APPLICATION_JSON)
+ public List<String> list() {
+ return jobIdToJob.keySet().stream().toList();
+ }
+
+ @Operation(summary = "Submit a route plan to start solving as soon as CPU resources are available.")
+ @APIResponses(value = {
+ @APIResponse(responseCode = "202",
+ description = "The job ID. Use that ID to get the solution with the other methods.",
+ content = @Content(mediaType = MediaType.TEXT_PLAIN, schema = @Schema(implementation = String.class))) })
@POST
@Consumes({ MediaType.APPLICATION_JSON })
@Produces(MediaType.TEXT_PLAIN)
public String solve(VehicleRoutePlan problem) {
String jobId = UUID.randomUUID().toString();
- jobIdToJob.put(jobId, Job.newRoutePlan(problem));
+ jobIdToJob.put(jobId, Job.ofRoutePlan(problem));
solverManager.solveAndListen(jobId,
jobId_ -> jobIdToJob.get(jobId).routePlan,
- solution -> jobIdToJob.put(jobId, Job.newRoutePlan(solution)),
+ solution -> jobIdToJob.put(jobId, Job.ofRoutePlan(solution)),
(jobId_, exception) -> {
- jobIdToJob.put(jobId, Job.error(jobId_, exception));
+ jobIdToJob.put(jobId, Job.ofException(exception));
LOGGER.error("Failed solving jobId ({}).", jobId, exception);
});
return jobId;
}
+ @Operation(
+ summary = "Get the route plan and score for a given job ID. This is the best solution so far, as it might still be running or not even started.")
+ @APIResponses(value = {
+ @APIResponse(responseCode = "200", description = "The best solution of the route plan so far.",
+ content = @Content(mediaType = MediaType.APPLICATION_JSON,
+ schema = @Schema(implementation = VehicleRoutePlan.class))),
+ @APIResponse(responseCode = "404", description = "No route plan found.",
+ content = @Content(mediaType = MediaType.APPLICATION_JSON,
+ schema = @Schema(implementation = ErrorInfo.class))),
+ @APIResponse(responseCode = "500", description = "Exception during solving a route plan.",
+ content = @Content(mediaType = MediaType.APPLICATION_JSON,
+ schema = @Schema(implementation = ErrorInfo.class)))
+ })
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{jobId}")
public VehicleRoutePlan getRoutePlan(
- @Parameter(description = "The job ID returned by the POST method.") @PathParam("jobId") String jobId,
- @QueryParam("retrieve") Retrieve retrieve) {
- retrieve = retrieve == null ? Retrieve.FULL : retrieve;
- Job job = jobIdToJob.get(jobId);
- if (job == null) {
- throw new VehicleRoutingSolverException(jobId, Response.Status.NOT_FOUND, "No route plan found.");
- }
- if (job.error != null) {
- throw new VehicleRoutingSolverException(jobId, job.error);
- }
- VehicleRoutePlan routePlan = job.routePlan;
+ @Parameter(description = "The job ID returned by the POST method.") @PathParam("jobId") String jobId) {
+ VehicleRoutePlan routePlan = getRoutePlanAndCheckForExceptions(jobId);
SolverStatus solverStatus = solverManager.getSolverStatus(jobId);
- if (retrieve == Retrieve.STATUS) {
- return new VehicleRoutePlan(routePlan.getName(), routePlan.getScore(), solverStatus);
- }
String scoreExplanation = solutionManager.explain(routePlan).getSummary();
routePlan.setSolverStatus(solverStatus);
routePlan.setScoreExplanation(scoreExplanation);
return routePlan;
}
+ @Operation(
+ summary = "Get the route plan status and score for a given job ID.")
+ @APIResponses(value = {
+ @APIResponse(responseCode = "200", description = "The route plan status and the best score so far.",
+ content = @Content(mediaType = MediaType.APPLICATION_JSON,
+ schema = @Schema(implementation = VehicleRoutePlan.class))),
+ @APIResponse(responseCode = "404", description = "No route plan found.",
+ content = @Content(mediaType = MediaType.APPLICATION_JSON,
+ schema = @Schema(implementation = ErrorInfo.class))),
+ @APIResponse(responseCode = "500", description = "Exception during solving a route plan.",
+ content = @Content(mediaType = MediaType.APPLICATION_JSON,
+ schema = @Schema(implementation = ErrorInfo.class)))
+ })
+ @GET
+ @Produces(MediaType.APPLICATION_JSON)
+ @Path("{jobId}/status")
+ public VehicleRoutePlan getStatus(
+ @Parameter(description = "The job ID returned by the POST method.") @PathParam("jobId") String jobId) {
+ VehicleRoutePlan routePlan = getRoutePlanAndCheckForExceptions(jobId);
+ SolverStatus solverStatus = solverManager.getSolverStatus(jobId);
+ return new VehicleRoutePlan(routePlan.getName(), routePlan.getScore(), solverStatus);
+ }
+
+ private VehicleRoutePlan getRoutePlanAndCheckForExceptions(String jobId) {
+ Job job = jobIdToJob.get(jobId);
+ if (job == null) {
+ throw new VehicleRoutingSolverException(jobId, Response.Status.NOT_FOUND, "No route plan found.");
+ }
+ if (job.exception != null) {
+ throw new VehicleRoutingSolverException(jobId, job.exception);
+ }
+ return job.routePlan;
+ }
+
+ @Operation(
+ summary = "Terminate solving for a given job ID. Returns the best solution of the route plan so far, as it might still be running or not even started.")
+ @APIResponses(value = {
+ @APIResponse(responseCode = "200", description = "The best solution of the route plan so far.",
+ content = @Content(mediaType = MediaType.APPLICATION_JSON,
+ schema = @Schema(implementation = VehicleRoutePlan.class))),
+ @APIResponse(responseCode = "404", description = "No route plan found.",
+ content = @Content(mediaType = MediaType.APPLICATION_JSON,
+ schema = @Schema(implementation = ErrorInfo.class))),
+ @APIResponse(responseCode = "500", description = "Exception during solving a route plan.",
+ content = @Content(mediaType = MediaType.APPLICATION_JSON,
+ schema = @Schema(implementation = ErrorInfo.class)))
+ })
@DELETE
@Produces(MediaType.APPLICATION_JSON)
@Path("{jobId}")
public VehicleRoutePlan terminateSolving(
- @Parameter(description = "The job ID returned by the POST method.") @PathParam("jobId") String jobId,
- @QueryParam("retrieve") Retrieve retrieve) {
+ @Parameter(description = "The job ID returned by the POST method.") @PathParam("jobId") String jobId) {
// TODO: Replace with .terminateEarlyAndWait(... [, timeout]); see https://github.com/TimefoldAI/timefold-solver/issues/77
solverManager.terminateEarly(jobId);
- return getRoutePlan(jobId, retrieve);
- }
-
- public enum Retrieve {
- STATUS,
- FULL
+ return getRoutePlan(jobId);
}
- private record Job(String jobId, VehicleRoutePlan routePlan, Throwable error) {
+ private record Job(VehicleRoutePlan routePlan, Throwable exception) {
- static Job newRoutePlan(VehicleRoutePlan routePlan) {
- return new Job(null, routePlan, null);
+ static Job ofRoutePlan(VehicleRoutePlan routePlan) {
+ return new Job(routePlan, null);
}
- static Job error(String jobId, Throwable error) {
- return new Job(jobId, null, error);
+ static Job ofException(Throwable exception) {
+ return new Job(null, exception); | You could declare constructors that do the same thing. |
timefold-quickstarts | github_2023 | java | 53 | TimefoldAI | triceo | @@ -52,71 +62,129 @@ public VehicleRoutePlanResource(SolverManager<VehicleRoutePlan, String> solverMa
this.solutionManager = solutionManager;
}
+ @Operation(summary = "List the job IDs of all submitted route plans.")
+ @APIResponses(value = {
+ @APIResponse(responseCode = "200", description = "List of all job IDs.",
+ content = @Content(mediaType = MediaType.APPLICATION_JSON,
+ schema = @Schema(type = SchemaType.ARRAY, implementation = String.class))) })
+ @GET
+ @Produces(MediaType.APPLICATION_JSON)
+ public List<String> list() {
+ return jobIdToJob.keySet().stream().toList(); | This has inefficiency built into it. The input is a set, the output is a list. Also, it is self-inflicted - nobody is forcing us to return a list. If this has to run in a web app which is exposed to some actual load, this will kill that web app.
And on top of that, it's done via a stream, which will do this inefficient thing inefficiently. |
timefold-quickstarts | github_2023 | java | 53 | TimefoldAI | triceo | @@ -102,23 +103,45 @@ public String solve(Timetable problem) {
@Produces(MediaType.APPLICATION_JSON)
@Path("{jobId}")
public Timetable getTimeTable(
- @Parameter(description = "The job ID returned by the POST method.") @PathParam("jobId") String jobId,
- @QueryParam("retrieve") Retrieve retrieve) {
- retrieve = retrieve == null ? Retrieve.FULL : retrieve;
+ @Parameter(description = "The job ID returned by the POST method.") @PathParam("jobId") String jobId) {
+ Timetable timetable = getTimetableAndCheckForExceptions(jobId);
+ SolverStatus solverStatus = solverManager.getSolverStatus(jobId);
+ timetable.setSolverStatus(solverStatus);
+ return timetable;
+ }
+
+ @Operation(
+ summary = "Get the timetable status and score for a given job ID.")
+ @APIResponses(value = {
+ @APIResponse(responseCode = "200", description = "The timetable status and the best score so far.",
+ content = @Content(mediaType = MediaType.APPLICATION_JSON,
+ schema = @Schema(implementation = Timetable.class))),
+ @APIResponse(responseCode = "404", description = "No timetable found.",
+ content = @Content(mediaType = MediaType.APPLICATION_JSON,
+ schema = @Schema(implementation = ErrorInfo.class))),
+ @APIResponse(responseCode = "500", description = "Exception during solving a timetable.",
+ content = @Content(mediaType = MediaType.APPLICATION_JSON,
+ schema = @Schema(implementation = ErrorInfo.class)))
+ }) | This is a massive obfuscation of *quickstart* code. I wouldn't add these. |
timefold-quickstarts | github_2023 | java | 35 | TimefoldAI | ge0ffrey | @@ -0,0 +1,28 @@
+package org.acme.vehiclerouting.domain;
+
+import com.fasterxml.jackson.annotation.JsonIdentityInfo;
+import com.fasterxml.jackson.annotation.JsonIdentityReference;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.ObjectIdGenerators;
+
+@JsonIdentityInfo(scope = Depot.class, generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
+public class Depot {
+
+ private final long id;
+
+ @JsonIdentityReference
+ private final Location location; | Does @JsonIdentityReference do anything? The Location is serialized as a json array |
timefold-quickstarts | github_2023 | java | 35 | TimefoldAI | ge0ffrey | @@ -0,0 +1,72 @@
+package org.acme.vehiclerouting.domain;
+
+import java.util.Map;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonFormat;
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+@JsonFormat(shape = JsonFormat.Shape.ARRAY)
+public class Location {
+
+ private double latitude;
+ private double longitude;
+
+ @JsonIgnore
+ private Map<Location, Long> distanceMap;
+
+ @JsonCreator
+ public Location(@JsonProperty("latitude") double latitude, @JsonProperty("longitude") double longitude) {
+ this.latitude = latitude;
+ this.longitude = longitude;
+ }
+
+ public double getLatitude() {
+ return latitude;
+ }
+
+ public double getLongitude() {
+ return longitude;
+ }
+
+ public Map<Location, Long> getDistanceMap() {
+ return distanceMap;
+ }
+
+ /**
+ * Set the distance map. Distances are in meters.
+ *
+ * @param distanceMap a map containing distances from here to other locations
+ */
+ public void setDistanceMap(Map<Location, Long> distanceMap) {
+ this.distanceMap = distanceMap;
+ }
+
+ /**
+ * Distance to the given location in meters.
+ *
+ * @param location other location
+ * @return distance in meters
+ */
+ public long getDistanceTo(Location location) {
+ return distanceMap.get(location);
+ }
+
+ // ************************************************************************
+ // Complex methods
+ // ************************************************************************
+
+ /**
+ * The angle relative to the direction EAST.
+ *
+ * @param location never null
+ * @return in Cartesian coordinates
+ */
+ public double getAngle(Location location) {
+ // Euclidean distance (Pythagorean theorem) - not correct when the surface is a sphere
+ double latitudeDifference = location.latitude - latitude;
+ double longitudeDifference = location.longitude - longitude;
+ return Math.atan2(latitudeDifference, longitudeDifference); | Is the comment still valid? atan2 smells like haversine, but comment says euclidean distance |
timefold-quickstarts | github_2023 | java | 35 | TimefoldAI | ge0ffrey | @@ -0,0 +1,170 @@
+package org.acme.vehiclerouting.domain;
+
+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.solution.ProblemFactCollectionProperty;
+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.DistanceCalculator;
+import org.acme.vehiclerouting.domain.geo.HaversineDistanceCalculator;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+@JsonInclude(JsonInclude.Include.NON_NULL)
+@PlanningSolution
+public class VehicleRoutePlan {
+
+ private String name;
+
+ @JsonIgnore
+ private List<Location> locations; | this can be a local field in the constructor, no need for a global field |
timefold-quickstarts | github_2023 | java | 35 | TimefoldAI | ge0ffrey | @@ -0,0 +1,45 @@
+package org.acme.vehiclerouting.domain.geo;
+
+import org.acme.vehiclerouting.domain.Location;
+
+public class HaversineDistanceCalculator implements DistanceCalculator {
+
+ private static final int EARTH_RADIUS_IN_KM = 6371;
+ private static final int TWICE_EARTH_RADIUS_IN_KM = 2 * EARTH_RADIUS_IN_KM;
+
+ @Override
+ public long calculateDistance(Location from, Location to) {
+ if (from.equals(to)) {
+ return 0L;
+ }
+
+ CartesianCoordinate fromCartesian = locationToCartesian(from);
+ CartesianCoordinate toCartesian = locationToCartesian(to); | If it overwrite the bulk method, it can do the locationToCartesian once for every location, instead of doing it n times for n locations. With 10k locations, I believe this could make a noticable difference. We should measure don't guess. |
timefold-quickstarts | github_2023 | java | 35 | TimefoldAI | ge0ffrey | @@ -0,0 +1,42 @@
+package org.acme.vehiclerouting.solver;
+
+import org.acme.vehiclerouting.domain.Customer;
+import org.acme.vehiclerouting.domain.Vehicle;
+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;
+
+public class VehicleRoutingConstraintProvider implements ConstraintProvider {
+
+ @Override
+ public Constraint[] defineConstraints(ConstraintFactory factory) {
+ return new Constraint[] {
+ totalDistance(factory),
+ serviceFinishedAfterDueTime(factory) | nitpick: order method calls same order a method declarations (hard before soft) |
timefold-quickstarts | github_2023 | java | 35 | TimefoldAI | ge0ffrey | @@ -0,0 +1,42 @@
+package org.acme.vehiclerouting.solver;
+
+import org.acme.vehiclerouting.domain.Customer;
+import org.acme.vehiclerouting.domain.Vehicle;
+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;
+
+public class VehicleRoutingConstraintProvider implements ConstraintProvider {
+
+ @Override
+ public Constraint[] defineConstraints(ConstraintFactory factory) {
+ return new Constraint[] {
+ totalDistance(factory),
+ serviceFinishedAfterDueTime(factory)
+ };
+ }
+
+ // ************************************************************************
+ // Hard constraints
+ // ************************************************************************
+
+ protected Constraint serviceFinishedAfterDueTime(ConstraintFactory factory) {
+ return factory.forEach(Customer.class)
+ .filter(Customer::isServiceFinishedAfterDueTime)
+ .penalizeLong(HardSoftLongScore.ONE_HARD,
+ Customer::getServiceFinishedDelayInMinutes)
+ .asConstraint("serviceFinishedAfterDueTime");
+ }
+
+ // ************************************************************************
+ // Soft constraints
+ // ************************************************************************
+
+ protected Constraint totalDistance(ConstraintFactory factory) {
+ return factory.forEach(Vehicle.class)
+ .penalizeLong(HardSoftLongScore.ONE_SOFT,
+ Vehicle::getTotalDistanceMeters)
+ .asConstraint("distanceFromPreviousStandstill"); | constraint name vs method name:
- distanceFromPreviousStandstill
- totalDistance
I'd argue neither, maybe: minimizeTravelTime? |
timefold-quickstarts | github_2023 | java | 35 | TimefoldAI | ge0ffrey | @@ -0,0 +1,185 @@
+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.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;
+
+import com.fasterxml.jackson.annotation.JsonIdentityInfo;
+import com.fasterxml.jackson.annotation.JsonIdentityReference;
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.ObjectIdGenerators;
+
+@JsonIdentityInfo(scope = Customer.class, generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
+@PlanningEntity
+public class Customer {
+
+ private long id; | We want to standarize on String id's for all classes that have one in the quickstarts.
Motivation: much more user friendly if you curl in your own json dataset |
timefold-quickstarts | github_2023 | java | 35 | TimefoldAI | ge0ffrey | @@ -0,0 +1,55 @@
+package org.acme.vehiclerouting.domain;
+
+import java.util.Map;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonFormat;
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+@JsonFormat(shape = JsonFormat.Shape.ARRAY)
+public class Location {
+
+ private double latitude;
+ private double longitude;
+
+ @JsonIgnore
+ private Map<Location, Long> drivingTimeMap; | It's not clear that the Long of drivingTime is in seconds.
Proposal A) Add a javadoc on this field that it's in seconds
Proposal B) change field name to drivingTimeInSecondsMap
Proposal C) change Long to Duration.
Which of these are clear in the Swagger open API? |
timefold-quickstarts | github_2023 | others | 35 | TimefoldAI | ge0ffrey | @@ -0,0 +1,36 @@
+########################
+# General properties
+########################
+# Enable CORS for runQuickstartsFromSource.sh
+quarkus.http.cors=true
+quarkus.http.cors.origins=/http://localhost:.*/
+# Allow all origins in dev-mode
+%dev.quarkus.http.cors.origins=/.*/
+# Enable Swagger UI also in the native mode
+quarkus.swagger-ui.always-include=true
+########################
+# Timefold properties
+########################
+# TODO: remove after https://github.com/TimefoldAI/timefold-solver/issues/117 is fixed
+quarkus.timefold.solver.domain-access-type=REFLECTION
+# The solver runs for 30 seconds. To run for 5 minutes use "5m" and for 2 hours use "2h".
+quarkus.timefold.solver.termination.spent-limit=30s | (code style) Not consistent with the other quickstarts: those use white lines to make it a bit more readable |
timefold-quickstarts | github_2023 | others | 43 | TimefoldAI | rsynek | @@ -48,6 +48,11 @@ jobs:
distribution: 'temurin'
cache: 'maven'
+ - name: Set up Maven
+ uses: stCarolas/setup-maven@v4.5
+ with:
+ maven-version: 3.9.3 | Is the maintenance cost (upgrading the maven version over all the release yaml files) worth the MAVEN_ARGS support?
Alternative: use just any env var ( that does not clash with any other ) and use its value in the maven command. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.